@flopay/react 1.4.14 → 1.4.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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 xn=za({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),dn=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 Tt(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),[S,M]=Do(null),y=Lo(null),R=Lo(null),C=Lo(null);Ar(()=>{if(!r)return;let I=Tt(r);return y.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[r]),Ar(()=>{let I=!1;return e instanceof Promise?e.then(x=>{I||a(x)}):a(e),()=>{I=!0}},[e]),Ar(()=>{let I=!1;if(!t){s(null);return}return t instanceof Promise?t.then(x=>{I||s(x)}):s(t),()=>{I=!0}},[t]),Ar(()=>{if(!r){M(null);return}let I=r.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return M(I),()=>{I.destroy()}},[r,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),Ar(()=>{if(!r||!S||R.current===S)return;R.current=S;let I=Tt(r);I?.log({name:"checkout.rendered",stage:"checkout_render"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(y.current??0),durationMode:"machine"})},[S,r]);let _=rs(()=>{if(!r||!S||C.current===S)return;C.current=S;let I=Tt(r);I?.log({name:"checkout.interactive",stage:"checkout_interactive"}),I?.performance({stage:"checkout_interactive",durationMs:I.elapsed(y.current??0),durationMode:"machine"})},[S,r]),l=as(n?.billingApiUrl),h=os(()=>({flopay:r,paypalFlopay:c,elements:S,billingApiUrl:l,reportInteractive:_}),[r,c,S,l,_]);return is(xn.Provider,{value:h,children:i})}import na,{useCallback as nr,useEffect as Bn,useMemo as un,useRef as qt,useState as wt}from"react";import{PaymentAPI as go,SESSION_CREATE_TELEMETRY as al}from"@flopay/js";import{SDK_VERSION as _i,FloPayError as Mt,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 en,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:[en("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),en("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",en("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:en("path",{d:"M9 18l6-6-6-6"})})]})}function ls(){return en(cr,{children:"Go back"})}function cs(){return en(cr,{children:"Secure card checkout"})}function ir(e){return e!==void 0&&(e===""||e===null||e===!1)}function sr({content:e}){return en(cr,{children:e===void 0?en(ss,{}):e})}function lr({content:e}){return en(cr,{children:e===void 0?en(ls,{}):e})}function Fr({content:e}){return en(cr,{children:e===void 0?en(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 Be,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 Nn,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:S}){let M=Dr(null),y=Dr(c),R=Dr(s),C=Dr(S);y.current=c,R.current=s,C.current=S;let _=Dr(r);return _.current=r,$a(()=>{let l=M.current;if(!l)return;let h=!0,I=!1,x=()=>{!h||I||(I=!0,y.current?.())},f=e.on("ready",()=>{x()}),ae=e.on("error",X=>{R.current?.(X.message??"There was a problem loading the secure card form.")}),U=e.on("validation",X=>{C.current?.(X.message??null)}),ie={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},..._.current?{theme:_.current}:{}};return e.mount(l,ie).then(()=>{x()}).catch(X=>{h&&R.current?.(X instanceof Error?X.message:"Failed to load the secure card form.")}),()=>{h=!1,f(),ae(),U(),e.unmount()}},[e,t,n,i]),$a(()=>{r&&e.applyTheme?.(r)},[e,r]),ds("div",{ref:M,"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 Ce,useContext as zs,useEffect as mt,useMemo as ot,useRef as ze,useState as be}from"react";import{useContext as Lr}from"react";import{resolveBillingApiUrl as ps}from"@flopay/shared";function fn(){return Lr(xn).flopay}function Oo(){return Lr(xn).paypalFlopay??null}function zo(){return Lr(xn).elements}function ms(){return Lr(dn)}function to(){return Lr(xn).billingApiUrl||ps()}import"react";import{jsx as tn,jsxs as ur}from"react/jsx-runtime";var Tn=1200,gn=1500;function hn({status:e,errorMessage:t}){return tn("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children: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:[tn("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),tn("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&tn("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:ur("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[tn("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),tn("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&tn("div",{style:{animation:"flopay-shake 0.4s ease"},children:ur("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[tn("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),tn("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),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"&&tn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:"You will be automatically redirected, do not close or navigate away from this window."}),e==="error"&&t&&tn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),tn("style",{children:`
1
+ import{useCallback as us,useEffect as Fr,useState as No,useMemo as ps,useRef as Oo}from"react";import{resolveBillingApiUrl as ms}from"@flopay/shared";import{createContext as Ha}from"react";var xn=Ha({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),yn=Ha({session:null,loading:!1,error:null});var ss=Symbol.for("@flopay/js.telemetry.bridge.v1"),ls=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function cs(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},flush:async()=>{},destroy:()=>{}}}function ds(e){let t=cs(),n=(o,a)=>o?o.bind(e):a,i=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:i,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,i()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function no(e){let t=globalThis[ls];return ds(t?.(e)??{})}function At(e){if(e)return e[ss]}import{jsx as ys}from"react/jsx-runtime";function ro({flopay:e,paypalFlopay:t,options:n,children:i}){let[o,a]=No(e instanceof Promise?null:e),[u,l]=No(t instanceof Promise||!t?null:t),[w,B]=No(null),h=Oo(null),R=Oo(null),S=Oo(null);Fr(()=>{if(!o)return;let I=At(o);return h.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),Fr(()=>{let I=!1;return e instanceof Promise?e.then(x=>{I||a(x)}):a(e),()=>{I=!0}},[e]),Fr(()=>{let I=!1;if(!t){l(null);return}return t instanceof Promise?t.then(x=>{I||l(x)}):l(t),()=>{I=!0}},[t]),Fr(()=>{if(!o){B(null);return}let I=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return B(I),()=>{I.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),Fr(()=>{if(!o||!w||R.current===w)return;R.current=w;let I=At(o);I?.log({name:"checkout.rendered",stage:"checkout_render"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(h.current??0),durationMode:"machine"})},[w,o]);let _=us(()=>{if(!o||!w||S.current===w)return;S.current=w;let I=At(o);I?.log({name:"checkout.interactive",stage:"checkout_interactive"}),I?.performance({stage:"checkout_interactive",durationMs:I.elapsed(h.current??0),durationMode:"machine"})},[w,o]),d=ms(n?.billingApiUrl),b=ps(()=>({flopay:o,paypalFlopay:u,elements:w,billingApiUrl:d,reportInteractive:_}),[o,u,w,d,_]);return ys(xn.Provider,{value:b,children:i})}import oa,{useCallback as rr,useEffect as Bn,useMemo as fn,useRef as jt,useState as bt}from"react";import{PaymentAPI as bo,SESSION_CREATE_TELEMETRY as yl}from"@flopay/js";import{SDK_VERSION as Ni,FloPayError as Pt,classifyTelemetryFailure as fl,isDetachedSessionEligible as gl,resolveBillingApiUrl as hl,buildCheckoutDisplayData as Mi,resolveButtonsLayoutTheme as Pl,resolveIdempotencyKey as Bi,resolveTheme as Oi}from"@flopay/shared";import"react";import{Fragment as dr,jsx as an,jsxs as Wa}from"react/jsx-runtime";function fs(){return Wa(dr,{children:[Wa("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:[an("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),an("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",an("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:an("path",{d:"M9 18l6-6-6-6"})})]})}function gs(){return an(dr,{children:"Go back"})}function hs(){return an(dr,{children:"Secure card checkout"})}function sr(e){return e!==void 0&&(e===""||e===null||e===!1)}function lr({content:e}){return an(dr,{children:e===void 0?an(fs,{}):e})}function cr({content:e}){return an(dr,{children:e===void 0?an(gs,{}):e})}function Dr({content:e}){return an(dr,{children:e===void 0?an(hs,{}):e})}import{ExpressCheckoutElement as vi,PaymentElement as As,Elements as tr,useElements as Qo,useStripe as Zo}from"@stripe/react-stripe-js";import{resolveButtonsLayoutTheme as Fs,getPostalCodeLabel as Jo,getStateLabel as si,getStateOptions as Ds,COUNTRY_OPTIONS as Ls,resolveAVSConfig as Ns,isAVSFieldVisible as De,getStateFromPostalCode as li,isPostalCodeSupported as Os,isValidPostalCode as zs,getPostalCodeExample as Us,filterStripeMethodsByCountry as $s,getStripeMethodDisplayName as hr,hasVendoredStripeMethodLogo as qs,needsStripeMethodExplicitConfirm as ci,resolveStripeMethodBrandVariant as js,partitionStripeMethods as Vs,stripeExpressMethodToOptionKey as di}from"@flopay/shared";import{PaymentAPI as $n,toStripeAppearance as Ks}from"@flopay/js";import{useEffect as Ya,useRef as Lr}from"react";import{jsx as Ps}from"react/jsx-runtime";function zo({capture:e,html:t,messageToken:n,expectedOrigin:i,theme:o,containerStyle:a,onReady:u,onError:l,onValidation:w}){let B=Lr(null),h=Lr(u),R=Lr(l),S=Lr(w);h.current=u,R.current=l,S.current=w;let _=Lr(o);return _.current=o,Ya(()=>{let d=B.current;if(!d)return;let b=!0,I=!1,x=()=>{!b||I||(I=!0,h.current?.())},P=e.on("ready",()=>{x()}),ae=e.on("error",ee=>{R.current?.(ee.message??"There was a problem loading the secure card form.")}),U=e.on("validation",ee=>{S.current?.(ee.message??null)}),le={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},..._.current?{theme:_.current}:{}};return e.mount(d,le).then(()=>{x()}).catch(ee=>{b&&R.current?.(ee instanceof Error?ee.message:"Failed to load the secure card form.")}),()=>{b=!1,P(),ae(),U(),e.unmount()}},[e,t,n,i]),Ya(()=>{o&&e.applyTheme?.(o)},[e,o]),Ps("div",{ref:B,"data-testid":"flopay-vault-card-fields",style:a})}import"react";import{jsx as Ga,jsxs as bs}from"react/jsx-runtime";function ur({children:e,margin:t,icon:n=!0,styleOverride:i}){return bs("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&&Ga("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Ga("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 Hs,{useCallback as we,useContext as Ws,useEffect as Qe,useMemo as nt,useRef as Be,useState as ve}from"react";import{useContext as Nr}from"react";import{resolveBillingApiUrl as vs}from"@flopay/shared";function vn(){return Nr(xn).flopay}function Uo(){return Nr(xn).paypalFlopay??null}function $o(){return Nr(xn).elements}function Cs(){return Nr(yn)}function oo(){return Nr(xn).billingApiUrl||vs()}import"react";import{jsx as sn,jsxs as pr}from"react/jsx-runtime";var Tn=1200,Cn=1500;function Sn({status:e,errorMessage:t}){return sn("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:[sn("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),sn("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&sn("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:[sn("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),sn("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"&&sn("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:[sn("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),sn("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"&&sn("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&&sn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),sn("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 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 ys=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Dn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:i}of 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 pt,useMemo as Or,useRef as He,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 ut(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function 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 Mn(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 Ln(e){let t=fs(e)?.toLowerCase()??"",i=`${Mn(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:S,onComplete:M,onErrorChange:y,onDecline:R,onTechnicalFailure:C,isProcessing:_=!1,onLoadStateChange:l,onInitializationStateChange:h,allowAutomaticRetry:I=!0,onButtonClick:x,runBeforeButtonClick:f,session:ae,existingOrderId:U,telemetry:ie,telemetryContext:X,debug:B=!1}){let G=fn(),H=Or(()=>{if(G)return null;let w=Qr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:hs,enabled:ie!==!1});return w.setCheckoutContext(X??{}),w.beginCheckout(X??{}),w},[n,G,ie,X?.checkoutMode,X?.layout]),se=Or(()=>Tt(G),[G]);pt(()=>()=>{H&&H.flush().catch(()=>{}).finally(()=>H.destroy())},[H]);let $=Or(()=>({error:w=>{se?se.error(w):H?.error(w)},log:w=>{se?se.log(w):H?.log(w)},performance:w=>{se?se.performance(w):H?.performance(w)},terminal:w=>{se?se.terminal(w):H?.terminal(w)},startTiming:()=>se?.now()??H?.now()??0,elapsed:w=>se?.elapsed(w)??Math.max(0,(H?.now()??w)-w)}),[se,H]),V=He(null),de=He(0),Ee=He(null),Pe=He(!1),[ye,Z]=Qn(!1),[fe,_e]=Qn(!1),[Q,ke]=Qn(0),Me=He(0),[we,Y]=Qn(!1),E=He(!1),le=He(!1),[Ne,Oe]=Qn(!1),[ue,k]=Qn(!1),ee=Or(()=>n.replace(/\/+$/,""),[n]),J=Or(()=>JSON.stringify([ee,r,c,a??"",s,e,U??""]),[ee,r,c,a,U,s,e]),Fe=He(J),yt=Fe.current!==J,[je,it]=Qn([]),F=w=>{B&&it(Je=>[...Je,`${new Date().toISOString().slice(11,23)} ${w}`])},L=He(S),Ue=He(M),qe=He(y),st=He(R),ft=He(C),Bt=He(x),Wt=He(l),m=He(h),ve=He(f),We=He(ae),tt=He(i),ht=He(t),Ye=He(null),Ze=He(0),xe=He(null),Ge=He(null),At=He(new Map),Ke=He(new Map),$n=He(!1);pt(()=>($n.current=!0,()=>{$n.current=!1}),[]),pt(()=>{L.current=S},[S]),pt(()=>{Ue.current=M},[M]),pt(()=>{qe.current=y},[y]),pt(()=>{st.current=R},[R]),pt(()=>{ft.current=C},[C]),pt(()=>{Bt.current=x},[x]),pt(()=>{Wt.current=l},[l]),pt(()=>{m.current=h},[h]),pt(()=>{ve.current=f},[f]),pt(()=>{We.current=ae},[ae]),pt(()=>{tt.current=i},[i]),pt(()=>{ht.current=t},[t]),pt(()=>{Me.current=Q},[Q]),pt(()=>{we&&Ee.current?.focus()},[we,Q]);let Pt=ao(()=>{window.setTimeout(()=>{Ee.current?.focus()},0)},[]),Sn=ao(()=>{Z(!1),ke(w=>w+1)},[]),wn=ao(()=>{Y(!1),(V.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??V.current)?.focus?.()},[]);pt(()=>{!ye||!Pe.current||(Pe.current=!1,wn())},[wn,ye,Q]);let qn=ao((w,Je)=>{let Se=ft.current;if(Se){Se("paypal",w,Je);return}qe.current?.(ks(Je?.popupBlocked??Ln(w)))},[]),Rt=()=>{xe.current?.timer&&(clearTimeout(xe.current.timer),xe.current.timer=null)},Ft=()=>{Rt();let w=Ze.current+1;return Ze.current=w,Ge.current=null,xe.current={generation:w,timer:null,yieldedControl:!1},Y(!1),w},Yt=w=>w!==void 0&&xe.current?.generation!==w?!1:(Rt(),xe.current=null,Ge.current=null,!0),Lt=w=>{let Je=w?.generation??xe.current?.generation??Ze.current;(!w?.generation||xe.current?.generation===Je)&&(Rt(),xe.current=null),Ge.current=Je,w?.showRetry&&Y(!0),w?.remount&&Sn(),w?.focus!==!1&&Pt()},Gt=w=>xe.current?.generation===w&&Ge.current!==w,pn=w=>{typeof document<"u"&&document.visibilityState!=="visible"||(Rt(),w.timer=setTimeout(()=>{xe.current?.generation===w.generation&&(xe.current=null,Ge.current=w.generation,qn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),Y(!0),Sn(),Pt())},600))},te=()=>{let w=xe.current;w?.yieldedControl&&pn(w)},jt=()=>{let w=xe.current;w&&(w.yieldedControl=!0,Rt())},kn=w=>{let Je=Ye.current;return Je&&Ke.current.set(w,Je),w};pt(()=>{let w=()=>{document.visibilityState==="visible"?te():jt()};return document.addEventListener("visibilitychange",w),window.addEventListener("focus",te),window.addEventListener("blur",jt),()=>{document.removeEventListener("visibilitychange",w),window.removeEventListener("focus",te),window.removeEventListener("blur",jt),Rt()}},[]),pt(()=>{Fe.current!==J&&(Fe.current=J,E.current=!1,le.current=!1,Z(!1),_e(!1),Oe(!1),m.current?.("loading"))},[J]),pt(()=>{ut(()=>Wt.current?.(ye&&!Ne))},[ye,Ne]);let Rn=bs(a);pt(()=>{let w=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",Je=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(F(`mount clientId=${w} env=${a??"(unset)"}\u2192${Rn??"live"} ccy=${c} sub=${s}`),F(`ua=${Je.slice(0,80)}${Je.length>80?"\u2026":""}`),!r){F("FAIL: clientId empty \u2014 gateway misconfigured"),Oe(!0),$.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!V.current){F("FAIL: containerRef not attached");return}de.current=$.startTiming(),$.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Se=!1,Fn=!1,$e=()=>Se||Fn,jn,rr=!1,Kt=()=>{jn=Ps(),jn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),rr=!0},lt=null,Dt=!1,Vt=null,vt=!1,nn=()=>{!Vt||vt||(vt=!0,Vt.close().catch(()=>{}))},rn=null,mn=()=>{rn!==null&&($.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"overlay_return",durationMs:$.elapsed(rn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),rn=null)},on=!1,It=V.current,Nt=null,Re=null,nt=[],rt=b=>{if(!b||typeof b.getBoundingClientRect!="function")return"(no rect)";let p=b.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},In=b=>{if(!b)return"(empty)";try{let p=new URL(b,typeof window<"u"?window.location.href:"https://localhost"),T=p.pathname.toLowerCase();return T.includes("checkcaptcha")||T.includes("captcha")?`CAPTCHA(${p.host}${T})`:T.includes("risk")||T.includes("challenge")?`RISK(${p.host}${T})`:T.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${T}`.slice(0,100)}catch{return b.slice(0,80)}},Kn=b=>{let p=b.getAttribute("src"),T=b.getAttribute("srcdoc"),Ie=b.getAttribute("name"),O=b.getAttribute("sandbox"),q=[];return p&&q.push(`src=${In(p)}`),T&&q.push(`srcdoc[${T.length}ch]`),!p&&!T&&q.push("src=(empty) srcdoc=(empty)"),Ie&&q.push(`name=${Ie.slice(0,40)}`),O!==null&&q.push(`sandbox="${O.slice(0,40)}"`),q.join(" ")},Ht=b=>{if(!(b instanceof HTMLIFrameElement))return"";try{let p=b.contentDocument;if(!p)return"cd=null";let T=p.body?.children.length??0,Ie=p.body?.innerHTML.length??0,O=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${T}children,${Ie}ch] head[${O}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},Ot=[],zt=b=>{if($e())return;let p=b.message??String(b.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(F(`window:error ${p.slice(0,140)}`),Ot.push(p))},En=b=>{if($e())return;let p=b.reason instanceof Error?b.reason.message:String(b.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(F(`window:rejection ${p.slice(0,140)}`),Ot.push(p))};B&&typeof window<"u"&&(window.addEventListener("error",zt),window.addEventListener("unhandledrejection",En));let Vn={value:0};if(B&&typeof PerformanceObserver<"u")try{Re=new PerformanceObserver(b=>{if(!$e())for(let p of b.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;Vn.value+=1;let T=Math.round(p.duration);F(`net ${T}ms ${p.name.slice(0,90)}`)}}),Re.observe({type:"resource",buffered:!0})}catch{}let Ut=()=>{for(Nt?.disconnect(),Nt=null,Re?.disconnect(),Re=null;nt.length;)clearTimeout(nt.pop());B&&typeof window<"u"&&(window.removeEventListener("error",zt),window.removeEventListener("unhandledrejection",En))},_n=b=>{if(!b)return!1;let p=b.toLowerCase();return p.includes("zoid destroyed")||p.includes("destroyed all components")||p.includes("window closed")||p.includes("detected container element removed")},bt=b=>{if($e()||_n(b))return;let p=Dn(b)??b;ut(()=>qe.current?.(p))},g=b=>{Se||(Oe(!0),b.includes("paypal_ineligible")||$.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:",b))},N=(b,p=!1)=>{if(Se)return;let T=E.current||!I;if(Dt)return;Dt=!0,Fn=!0,Ut(),nn();let Ie=p||Xa(b);if(Ie&&I&&!E.current){E.current=!0,Z(!1),k(!1),_e(!0),m.current?.("retrying"),lt=setTimeout(()=>{Se||ke(O=>O+1)},vs);return}if(Ie||T){if(Z(!1),k(!1),_e(!1),Oe(!0),m.current?.("exhausted"),!le.current){le.current=!0;let O=Xa(b)?"paypal_init_timeout":p?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",O)}return}g(b)};Oe(!1);let W=async(b,p=Ye.current)=>{if($e())return;let T=p?.sessionId??e;if(L.current){await L.current(b,{sessionId:T,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let Ie=$.startTiming();$.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let O=()=>{$.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"processing",durationMs:$.elapsed(Ie),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let q=We.current,he=p?.accountPatch?.email??tt.current,Qe=p?.accountPatch?.userId??q?.customer?.id??q?.accountData?.userId??"",ce=await new jo(ee,{telemetry:!1}).processPayment(Qe,{sessionId:T,nonce:p?.nonce??ht.current,tokenizedData:b,accountData:{userId:Qe,email:he??q?.customer?.email??"",firstName:p?.accountPatch?.firstName??q?.customer?.firstName??q?.accountData?.firstName??"",lastName:p?.accountPatch?.lastName??q?.customer?.lastName??q?.accountData?.lastName??"",country:p?.accountPatch?.country??q?.customer?.country??q?.accountData?.country??void 0,zip:p?.accountPatch?.zip??q?.customer?.zip??q?.accountData?.zip??void 0}});if(ce.ok){if(Fn||Se&&$n.current)return;O(),$.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ut(()=>Ue.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if($e())return;let pe=await ce.json().catch(()=>null),Ve=pe?.message??"PayPal payment failed.",an=Dn(Ve)??Ve;O(),ce.status===400&&(typeof pe?.declineCode=="string"||!Array.isArray(pe?.fields))?$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ce.status===400||ce.status===422?$.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):$.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ce.status>=500?"5xx":ce.status>=400?"4xx":ce.status>=300?"3xx":"unknown",failureCategory:ce.status>=500?"server_error":void 0}),bt(an),ut(()=>st.current?.(St("paypal",an,{code:pe?.code,declineCode:pe?.declineCode})));return}catch(q){if($e())return;O(),$.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let he=q instanceof Error?q.message:"PayPal payment failed.",Qe=Dn(he)??he;bt(Qe),ut(()=>st.current?.(St("paypal",Qe)));return}},Te=()=>new Ga("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ge=b=>$e()?Promise.reject(Te()):Promise.resolve(b),D=async b=>{if($e())throw Te();rr||Kt();let p=Ye.current,T=p?.sessionId??e,Ie=p?.nonce??ht.current;$.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let O=await new jo(ee,{telemetry:!1}).createSessionIntent(T,Ie??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:jn});if($e())throw Te();if(O.provider!=="paypal")throw new Error(b);return $.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),O.providerObjectId},P=(b,p)=>{let T=p?.nonce??ht.current;if(!T)return;let Ie=p?.sessionId??e,O=mr(b)??Mn(b)??"provider_declined";new jo(ee,{telemetry:!1}).reportSessionIntentDecline(Ie,T,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:O}).catch(()=>{})},A=Q;F("loadScript:scheduled (deferred 1 tick)");let u=null,me=setTimeout(()=>{if(Se){F("loadScript:skipped (cancelled before defer ran)");return}F("loadScript:start");let b=Rn==="live"?"production":Rn;u=gs({clientId:r,currency:c,intent:s?"subscription":"capture",vault:s?!0:void 0,...b?{environment:b}:{},...b==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),u.then(p=>{if(F(`loadScript:resolved inactive=${$e()} ns=${!!p} buttons=${!!p?.Buttons}`),$e())return;if(!p?.Buttons){F("FAIL: namespace missing Buttons factory"),N("PayPal SDK did not expose the Buttons factory.");return}$.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"provider_ready",durationMs:$.elapsed(de.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),$.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let T=async De=>{if($e()||Me.current!==A)return;let ce=De.subscriptionID??De.orderID??"",pe=ce?Ke.current.get(ce):At.current.get(A);if(!(!pe||!Gt(pe.generation))&&Yt(pe.generation)){Ke.current.delete(ce),At.current.delete(pe.surfaceKey),mn();try{if(k(!0),ut(()=>qe.current?.(null)),!ce)throw new Ga("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await W({id:ce,isPaypal:!0},pe)}catch(Ve){bt(Ve instanceof Error?Ve.message:"PayPal capture failed.")}finally{$e()||k(!1)}}},Ie=p.Buttons({style:{layout:"horizontal",height:io,tagline:!1},onClick:async(De,ce)=>{if($e()){await ce.reject();return}Kt();let pe=ve.current,Ve={};if(pe)try{let j=await pe("paypal");if($e()){await ce.reject();return}if(!j.proceed){Ye.current=null,At.current.delete(A),await ce.reject();return}Ve={sessionId:j.sessionId,accountPatch:j.accountPatch,nonce:j.nonce}}catch(j){F(`onClick:runBeforeButtonClick rejected msg=${(j instanceof Error?j.message:String(j)).slice(0,120)}`),Ye.current=null,At.current.delete(A),await ce.reject();return}ut(()=>Bt.current?.("paypal"));let sn={generation:Ft(),surfaceKey:A,...Ve};Ye.current=sn,At.current.set(A,sn),await ce.resolve(),$.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),$.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),$.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),rn=$.startTiming()},createOrder:s?void 0:U?()=>ge(U).then(kn):()=>D("Failed to create PayPal order.").then(kn),createSubscription:s?U?()=>ge(U).then(kn):()=>D("Failed to create PayPal subscription.").then(kn):void 0,onApprove:T,onCancel:()=>{if($e())return;let De=At.current.get(A)??Ye.current;De&&At.current.delete(De.surfaceKey),Ye.current=null,mn(),$.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Pe.current=!0,Lt({generation:De?.generation,remount:!0,focus:!1})},onError:De=>{if($e()||Me.current!==A)return;let ce=De instanceof Error?De.message:"PayPal failed to render.";if(F(`onError rendered=${on} msg=${ce.slice(0,120)}`),on){let pe=At.current.get(A)??Ye.current;if(pe&&!Gt(pe.generation)||!pe&&Ge.current===Ze.current)return;if(_n(ce)){Yt(pe?.generation);return}if(mn(),Nr(De)){$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),P(De,pe),ut(()=>st.current?.(St("paypal",ce))),pe&&At.current.delete(pe.surfaceKey),Ye.current=null,Yt(pe?.generation);return}let Ve=ce.toLowerCase();$.error({errorCode:Ve.includes("popup")&&Ve.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}),qn(De,{code:"paypal_runtime_failed"});return}N(ce)}}),O=Ie.isEligible();if(F(`isEligible=${O}`),$.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!O){Z(!1),N("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Vt=Ie,B&&F(`container:dims ${rt(It)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),B&&typeof MutationObserver<"u"&&(Nt=new MutationObserver(De=>{if(!$e()){for(let ce of De)if(ce.type==="childList")ce.addedNodes.forEach(pe=>{if(!(pe instanceof Element))return;let Ve=pe.tagName.toLowerCase(),an=(pe.getAttribute("title")??"").slice(0,40),sn=Ve==="iframe"?` ${Kn(pe)}`:"";F(`child+ ${Ve}${an?` title="${an}"`:""}${sn} dims=${rt(pe)}`)});else if(ce.type==="attributes"&&ce.target instanceof Element){let pe=ce.target;if(pe.tagName.toLowerCase()!=="iframe")continue;let Ve=ce.attributeName;(Ve==="src"||Ve==="srcdoc")&&F(`attr~ iframe ${Ve}=${Ve==="srcdoc"?`[${(pe.getAttribute("srcdoc")??"").length}ch]`:In(pe.getAttribute("src"))} dims=${rt(pe)}`)}}}),Nt.observe(It,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let he=De=>{if($e()||on)return;let ce=It.querySelectorAll("iframe"),pe=typeof document<"u"&&"hasStorageAccess"in document;F(`watchdog:${De} container=${rt(It)} children=${It.childElementCount} iframes=${ce.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${pe} paypalNetRequests=${Vn.value}`),ce.forEach((Ve,an)=>{let sn=(Ve.getAttribute("title")??"").slice(0,40);F(` iframe[${an}] ${rt(Ve)}${sn?` title="${sn}"`:""} ${Kn(Ve)}`);let j=Ht(Ve);j&&F(` ${j}`)}),Ot.length===0&&F(" (no PayPal/zoid window errors captured)")};B&&(nt.push(setTimeout(()=>he("3s"),3e3)),nt.push(setTimeout(()=>he("8s"),8e3)),nt.push(setTimeout(()=>he("15s"),15e3))),F("render:start");let Qe=$.startTiming();nt.push(setTimeout(()=>{$e()||on||(F("watchdog:11s retryable render timeout"),N("PayPal Buttons render did not settle within 11000ms.",!0))},Cs)),Ie.render(It).then(()=>{if(F(`render:resolved inactive=${$e()}`),Ut(),$e()){nn();return}on=!0,Z(!0),_e(!1),m.current?.("ready"),$.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"checkout_render",durationMs:$.elapsed(Qe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(De=>{let ce=De instanceof Error?De.message:"PayPal failed to render.";F(`render:rejected msg=${ce.slice(0,120)}`),Ut(),N(ce)})}).catch(p=>{let T=p instanceof Error?p.message:"PayPal SDK failed to load.";F(`loadScript:rejected msg=${T.slice(0,120)}`),N(T)})},0);return()=>{Se=!0,clearTimeout(me),lt&&clearTimeout(lt),Ut(),nn()}},[I,ee,r,c,a,s,e,U,Q,$]);let Jt=B?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=${ye} failed=${Ne})`,je.length===0?`
6
+ `})]})})}import{FloPayError as Uc,isSetupIntentClientSecret as $c}from"@flopay/shared";function Xa(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 qo(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 Qa(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,u)=>a+(u.overrideAmount??u.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(i*100),currency:o,status:"open",customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,u)=>({uuid:`synthetic-${a.type??"item"}-${u}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function jo(e,t){return t?{...e,...t}:e}function kt(e,t,n){let i=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:i,...o?{code:o}:{},...a?{declineCode:a}:{}}}var Ss=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function zn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:i}of Ss)if(n.test(t))return i;return e}function ao(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Za(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function ei(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function io(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var so="flopay_recent_completion_";function mr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(so+e,JSON.stringify(t))}catch{}}function Vo(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(so+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(so+e),!1):!0}catch{return!1}}function ti(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 lo,useEffect as dt,useMemo as zr,useRef as Ke,useState as er}from"react";import{loadScript as ks}from"@paypal/paypal-js";import{PaymentAPI as Ko}from"@flopay/js";import{FloPayError as ni,SDK_VERSION as Rs,generateIdempotencyKey as Is,normalizeGatewayEnvironment as Es}from"@flopay/shared";function ct(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 ws(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 Mn(e){if(typeof e!="object"||e===null)return;let t=e;return Zn(t.code)??Zn(t.type)??Zn(t.name)}function yr(e){if(!(typeof e!="object"||e===null))return Zn(e.decline_code)}function Or(e){return typeof e!="object"||e===null?!1:Zn(e.type)?.toLowerCase()==="card_error"||yr(e)!==void 0}function Un(e){let t=ws(e)?.toLowerCase()??"",i=`${Mn(e)?.toLowerCase()??""} ${t}`;return i.includes("popup")&&i.includes("block")}import{jsx as fr,jsxs as Ho}from"react/jsx-runtime";var co=45,_s=1e3,xs=11e3,Ts=["https://www.paypal.com","https://www.sandbox.paypal.com"],ri="We couldn't open PayPal. Try again or choose another payment method.",Ms={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 oi(e){return e.includes("No ack for postMessage init()")&&Ts.some(t=>e.includes(t))&&e.includes("10000ms")}function Bs(e){return e?`${ri} Allow pop-ups for this site, then try again.`:ri}function ai({sessionId:e,nonce:t,billingApiUrl:n,email:i,clientId:o,environment:a,currency:u,isSubscription:l,onTokenizedBody:w,onComplete:B,onErrorChange:h,onDecline:R,onTechnicalFailure:S,isProcessing:_=!1,onLoadStateChange:d,onInitializationStateChange:b,allowAutomaticRetry:I=!0,onButtonClick:x,runBeforeButtonClick:P,session:ae,existingOrderId:U,telemetry:le,telemetryContext:ee,debug:F=!1}){let J=vn(),W=zr(()=>{if(J)return null;let T=no({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Rs,enabled:le!==!1});return T.setCheckoutContext(ee??{}),T.beginCheckout(ee??{}),T},[n,J,le,ee?.checkoutMode,ee?.layout]),ce=zr(()=>At(J),[J]);dt(()=>()=>{W&&W.flush().catch(()=>{}).finally(()=>W.destroy())},[W]);let $=zr(()=>({error:T=>{ce?ce.error(T):W?.error(T)},log:T=>{ce?ce.log(T):W?.log(T)},performance:T=>{ce?ce.performance(T):W?.performance(T)},terminal:T=>{ce?ce.terminal(T):W?.terminal(T)},startTiming:()=>ce?.now()??W?.now()??0,elapsed:T=>ce?.elapsed(T)??Math.max(0,(W?.now()??T)-T)}),[ce,W]),K=Ke(null),de=Ke(0),_e=Ke(null),Pe=Ke(!1),[ye,te]=er(!1),[ge,xe]=er(!1),[ne,ke]=er(0),Re=Ke(0),[Ce,Y]=er(!1),E=Ke(!1),ie=Ke(!1),[Ne,Oe]=er(!1),[ue,k]=er(!1),Q=zr(()=>n.replace(/\/+$/,""),[n]),Z=zr(()=>JSON.stringify([Q,o,u,a??"",l,e,U??""]),[Q,o,u,a,U,l,e]),ze=Ke(Z),ut=ze.current!==Z,[qe,ot]=er([]),N=T=>{F&&ot(gt=>[...gt,`${new Date().toISOString().slice(11,23)} ${T}`])},V=Ke(w),Ze=Ke(B),Te=Ke(h),at=Ke(R),He=Ke(S),je=Ke(x),ln=Ke(d),f=Ke(b),be=Ke(P),pt=Ke(ae),et=Ke(i),Je=Ke(t),Ve=Ke(null),Xe=Ke(0),Ie=Ke(null),$e=Ke(null),It=Ke(new Map),Ye=Ke(new Map),Fn=Ke(!1);dt(()=>(Fn.current=!0,()=>{Fn.current=!1}),[]),dt(()=>{V.current=w},[w]),dt(()=>{Ze.current=B},[B]),dt(()=>{Te.current=h},[h]),dt(()=>{at.current=R},[R]),dt(()=>{He.current=S},[S]),dt(()=>{je.current=x},[x]),dt(()=>{ln.current=d},[d]),dt(()=>{f.current=b},[b]),dt(()=>{be.current=P},[P]),dt(()=>{pt.current=ae},[ae]),dt(()=>{et.current=i},[i]),dt(()=>{Je.current=t},[t]),dt(()=>{Re.current=ne},[ne]),dt(()=>{Ce&&_e.current?.focus()},[Ce,ne]);let vt=lo(()=>{window.setTimeout(()=>{_e.current?.focus()},0)},[]),Dn=lo(()=>{te(!1),ke(T=>T+1)},[]),cn=lo(()=>{Y(!1),(K.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??K.current)?.focus?.()},[]);dt(()=>{!ye||!Pe.current||(Pe.current=!1,cn())},[cn,ye,ne]);let gn=lo((T,gt)=>{let mt=He.current;if(mt){mt("paypal",T,gt);return}Te.current?.(Bs(gt?.popupBlocked??Un(T)))},[]),tn=()=>{Ie.current?.timer&&(clearTimeout(Ie.current.timer),Ie.current.timer=null)},Ln=()=>{tn();let T=Xe.current+1;return Xe.current=T,$e.current=null,Ie.current={generation:T,timer:null,yieldedControl:!1},Y(!1),T},Ut=T=>T!==void 0&&Ie.current?.generation!==T?!1:(tn(),Ie.current=null,$e.current=null,!0),Et=T=>{let gt=T?.generation??Ie.current?.generation??Xe.current;(!T?.generation||Ie.current?.generation===gt)&&(tn(),Ie.current=null),$e.current=gt,T?.showRetry&&Y(!0),T?.remount&&Dn(),T?.focus!==!1&&vt()},Vt=T=>Ie.current?.generation===T&&$e.current!==T,Xt=T=>{typeof document<"u"&&document.visibilityState!=="visible"||(tn(),T.timer=setTimeout(()=>{Ie.current?.generation===T.generation&&(Ie.current=null,$e.current=T.generation,gn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),Y(!0),Dn(),vt())},600))},Ft=()=>{let T=Ie.current;T?.yieldedControl&&Xt(T)},Kt=()=>{let T=Ie.current;T&&(T.yieldedControl=!0,tn())},Dt=T=>{let gt=Ve.current;return gt&&Ye.current.set(T,gt),T};dt(()=>{let T=()=>{document.visibilityState==="visible"?Ft():Kt()};return document.addEventListener("visibilitychange",T),window.addEventListener("focus",Ft),window.addEventListener("blur",Kt),()=>{document.removeEventListener("visibilitychange",T),window.removeEventListener("focus",Ft),window.removeEventListener("blur",Kt),tn()}},[]),dt(()=>{ze.current!==Z&&(ze.current=Z,E.current=!1,ie.current=!1,te(!1),xe(!1),Oe(!1),f.current?.("loading"))},[Z]),dt(()=>{ct(()=>ln.current?.(ye&&!Ne))},[ye,Ne]);let re=Es(a);dt(()=>{let T=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",gt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(N(`mount clientId=${T} env=${a??"(unset)"}\u2192${re??"live"} ccy=${u} sub=${l}`),N(`ua=${gt.slice(0,80)}${gt.length>80?"\u2026":""}`),!o){N("FAIL: clientId empty \u2014 gateway misconfigured"),Oe(!0),$.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(!K.current){N("FAIL: containerRef not attached");return}de.current=$.startTiming(),$.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let mt=!1,Ct=!1,Ee=()=>mt||Ct,Ue,Kn=!1,Nn=()=>{Ue=Is(),Ue||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Kn=!0},Hn=null,or=!1,Ht=null,it=!1,Lt=()=>{!Ht||it||(it=!0,Ht.close().catch(()=>{}))},Wt=null,ht=()=>{Wt!==null&&($.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"overlay_return",durationMs:$.elapsed(Wt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Wt=null)},Qt=!1,Yt=K.current,dn=null,hn=null,_t=[],$t=c=>{if(!c||typeof c.getBoundingClientRect!="function")return"(no rect)";let s=c.getBoundingClientRect();return`${Math.round(s.width)}\xD7${Math.round(s.height)}`},Ae=c=>{if(!c)return"(empty)";try{let s=new URL(c,typeof window<"u"?window.location.href:"https://localhost"),M=s.pathname.toLowerCase();return M.includes("checkcaptcha")||M.includes("captcha")?`CAPTCHA(${s.host}${M})`:M.includes("risk")||M.includes("challenge")?`RISK(${s.host}${M})`:M.includes("smart/buttons")?`smart-buttons(${s.host})`:`${s.host}${M}`.slice(0,100)}catch{return c.slice(0,80)}},St=c=>{let s=c.getAttribute("src"),M=c.getAttribute("srcdoc"),m=c.getAttribute("name"),G=c.getAttribute("sandbox"),Se=[];return s&&Se.push(`src=${Ae(s)}`),M&&Se.push(`srcdoc[${M.length}ch]`),!s&&!M&&Se.push("src=(empty) srcdoc=(empty)"),m&&Se.push(`name=${m.slice(0,40)}`),G!==null&&Se.push(`sandbox="${G.slice(0,40)}"`),Se.join(" ")},wt=c=>{if(!(c instanceof HTMLIFrameElement))return"";try{let s=c.contentDocument;if(!s)return"cd=null";let M=s.body?.children.length??0,m=s.body?.innerHTML.length??0,G=s.head?.innerHTML.length??0;return`cd=same-origin readyState=${s.readyState} body[${M}children,${m}ch] head[${G}ch]`}catch(s){return`cd=cross-origin(${s.message.slice(0,30)})`}},Pn=[],Wn=c=>{if(Ee())return;let s=c.message??String(c.error??"(no message)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(N(`window:error ${s.slice(0,140)}`),Pn.push(s))},Gt=c=>{if(Ee())return;let s=c.reason instanceof Error?c.reason.message:String(c.reason??"(no reason)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(N(`window:rejection ${s.slice(0,140)}`),Pn.push(s))};F&&typeof window<"u"&&(window.addEventListener("error",Wn),window.addEventListener("unhandledrejection",Gt));let Zt={value:0};if(F&&typeof PerformanceObserver<"u")try{hn=new PerformanceObserver(c=>{if(!Ee())for(let s of c.getEntries()){if(!s.name.toLowerCase().includes("paypal"))continue;Zt.value+=1;let M=Math.round(s.duration);N(`net ${M}ms ${s.name.slice(0,90)}`)}}),hn.observe({type:"resource",buffered:!0})}catch{}let Nt=()=>{for(dn?.disconnect(),dn=null,hn?.disconnect(),hn=null;_t.length;)clearTimeout(_t.pop());F&&typeof window<"u"&&(window.removeEventListener("error",Wn),window.removeEventListener("unhandledrejection",Gt))},En=c=>{if(!c)return!1;let s=c.toLowerCase();return s.includes("zoid destroyed")||s.includes("destroyed all components")||s.includes("window closed")||s.includes("detected container element removed")},On=c=>{if(Ee()||En(c))return;let s=zn(c)??c;ct(()=>Te.current?.(s))},un=c=>{mt||(Oe(!0),c.includes("paypal_ineligible")||$.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",c))},en=(c,s=!1)=>{if(mt)return;let M=E.current||!I;if(or)return;or=!0,Ct=!0,Nt(),Lt();let m=s||oi(c);if(m&&I&&!E.current){E.current=!0,te(!1),k(!1),xe(!0),f.current?.("retrying"),Hn=setTimeout(()=>{mt||ke(G=>G+1)},_s);return}if(m||M){if(te(!1),k(!1),xe(!1),Oe(!0),f.current?.("exhausted"),!ie.current){ie.current=!0;let G=oi(c)?"paypal_init_timeout":s?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",G)}return}un(c)};Oe(!1);let xt=async(c,s=Ve.current)=>{if(Ee())return;let M=s?.sessionId??e;if(V.current){await V.current(c,{sessionId:M,accountPatch:s?.accountPatch,nonce:s?.nonce});return}let m=$.startTiming();$.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let G=()=>{$.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"processing",durationMs:$.elapsed(m),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Se=pt.current,tt=s?.accountPatch?.email??et.current,he=s?.accountPatch?.userId??Se?.customer?.id??Se?.accountData?.userId??"",y=await new Ko(Q,{telemetry:!1}).processPayment(he,{sessionId:M,nonce:s?.nonce??Je.current,tokenizedData:c,accountData:{userId:he,email:tt??Se?.customer?.email??"",firstName:s?.accountPatch?.firstName??Se?.customer?.firstName??Se?.accountData?.firstName??"",lastName:s?.accountPatch?.lastName??Se?.customer?.lastName??Se?.accountData?.lastName??"",country:s?.accountPatch?.country??Se?.customer?.country??Se?.accountData?.country??void 0,zip:s?.accountPatch?.zip??Se?.customer?.zip??Se?.accountData?.zip??void 0}});if(y.ok){if(Ct||mt&&Fn.current)return;G(),$.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ct(()=>Ze.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ee())return;let D=await y.json().catch(()=>null),j=D?.message??"PayPal payment failed.",We=zn(j)??j;G(),y.status===400&&(typeof D?.declineCode=="string"||!Array.isArray(D?.fields))?$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):y.status===400||y.status===422?$.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):$.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:y.status>=500?"5xx":y.status>=400?"4xx":y.status>=300?"3xx":"unknown",failureCategory:y.status>=500?"server_error":void 0}),On(We),ct(()=>at.current?.(kt("paypal",We,{code:D?.code,declineCode:D?.declineCode})));return}catch(Se){if(Ee())return;G(),$.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let tt=Se instanceof Error?Se.message:"PayPal payment failed.",he=zn(tt)??tt;On(he),ct(()=>at.current?.(kt("paypal",he)));return}},g=()=>new ni("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),q=c=>Ee()?Promise.reject(g()):Promise.resolve(c),O=async c=>{if(Ee())throw g();Kn||Nn();let s=Ve.current,M=s?.sessionId??e,m=s?.nonce??Je.current;$.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let G=await new Ko(Q,{telemetry:!1}).createSessionIntent(M,m??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Ue});if(Ee())throw g();if(G.provider!=="paypal")throw new Error(c);return $.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),G.providerObjectId},pe=(c,s)=>{let M=s?.nonce??Je.current;if(!M)return;let m=s?.sessionId??e,G=yr(c)??Mn(c)??"provider_declined";new Ko(Q,{telemetry:!1}).reportSessionIntentDecline(m,M,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:G}).catch(()=>{})},H=ne;N("loadScript:scheduled (deferred 1 tick)");let se=null,C=setTimeout(()=>{if(mt){N("loadScript:skipped (cancelled before defer ran)");return}N("loadScript:start");let c=re==="live"?"production":re;se=ks({clientId:o,currency:u,intent:l?"subscription":"capture",vault:l?!0:void 0,...c?{environment:c}:{},...c==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),se.then(s=>{if(N(`loadScript:resolved inactive=${Ee()} ns=${!!s} buttons=${!!s?.Buttons}`),Ee())return;if(!s?.Buttons){N("FAIL: namespace missing Buttons factory"),en("PayPal SDK did not expose the Buttons factory.");return}$.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"provider_ready",durationMs:$.elapsed(de.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),$.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let M=async A=>{if(Ee()||Re.current!==H)return;let y=A.subscriptionID??A.orderID??"",D=y?Ye.current.get(y):It.current.get(H);if(!(!D||!Vt(D.generation))&&Ut(D.generation)){Ye.current.delete(y),It.current.delete(D.surfaceKey),ht();try{if(k(!0),ct(()=>Te.current?.(null)),!y)throw new ni("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await xt({id:y,isPaypal:!0},D)}catch(j){On(j instanceof Error?j.message:"PayPal capture failed.")}finally{Ee()||k(!1)}}},m=s.Buttons({style:{layout:"horizontal",height:co,tagline:!1},onClick:async(A,y)=>{if(Ee()){await y.reject();return}Nn();let D=be.current,j={};if(D)try{let Ot=await D("paypal");if(Ee()){await y.reject();return}if(!Ot.proceed){Ve.current=null,It.current.delete(H),await y.reject();return}j={sessionId:Ot.sessionId,accountPatch:Ot.accountPatch,nonce:Ot.nonce}}catch(Ot){N(`onClick:runBeforeButtonClick rejected msg=${(Ot instanceof Error?Ot.message:String(Ot)).slice(0,120)}`),Ve.current=null,It.current.delete(H),await y.reject();return}ct(()=>je.current?.("paypal"));let Tt={generation:Ln(),surfaceKey:H,...j};Ve.current=Tt,It.current.set(H,Tt),await y.resolve(),$.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),$.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),$.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Wt=$.startTiming()},createOrder:l?void 0:U?()=>q(U).then(Dt):()=>O("Failed to create PayPal order.").then(Dt),createSubscription:l?U?()=>q(U).then(Dt):()=>O("Failed to create PayPal subscription.").then(Dt):void 0,onApprove:M,onCancel:()=>{if(Ee())return;let A=It.current.get(H)??Ve.current;A&&It.current.delete(A.surfaceKey),Ve.current=null,ht(),$.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Pe.current=!0,Et({generation:A?.generation,remount:!0,focus:!1})},onError:A=>{if(Ee()||Re.current!==H)return;let y=A instanceof Error?A.message:"PayPal failed to render.";if(N(`onError rendered=${Qt} msg=${y.slice(0,120)}`),Qt){let D=It.current.get(H)??Ve.current;if(D&&!Vt(D.generation)||!D&&$e.current===Xe.current)return;if(En(y)){Ut(D?.generation);return}if(ht(),Or(A)){$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),pe(A,D),ct(()=>at.current?.(kt("paypal",y))),D&&It.current.delete(D.surfaceKey),Ve.current=null,Ut(D?.generation);return}let j=y.toLowerCase();$.error({errorCode:j.includes("popup")&&j.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),D&&It.current.delete(D.surfaceKey),Ve.current=null,Et({generation:D?.generation,remount:!0,showRetry:!0,focus:!0}),gn(A,{code:"paypal_runtime_failed"});return}en(y)}}),G=m.isEligible();if(N(`isEligible=${G}`),$.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!G){te(!1),en("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ht=m,F&&N(`container:dims ${$t(Yt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),F&&typeof MutationObserver<"u"&&(dn=new MutationObserver(A=>{if(!Ee()){for(let y of A)if(y.type==="childList")y.addedNodes.forEach(D=>{if(!(D instanceof Element))return;let j=D.tagName.toLowerCase(),We=(D.getAttribute("title")??"").slice(0,40),Tt=j==="iframe"?` ${St(D)}`:"";N(`child+ ${j}${We?` title="${We}"`:""}${Tt} dims=${$t(D)}`)});else if(y.type==="attributes"&&y.target instanceof Element){let D=y.target;if(D.tagName.toLowerCase()!=="iframe")continue;let j=y.attributeName;(j==="src"||j==="srcdoc")&&N(`attr~ iframe ${j}=${j==="srcdoc"?`[${(D.getAttribute("srcdoc")??"").length}ch]`:Ae(D.getAttribute("src"))} dims=${$t(D)}`)}}}),dn.observe(Yt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let tt=A=>{if(Ee()||Qt)return;let y=Yt.querySelectorAll("iframe"),D=typeof document<"u"&&"hasStorageAccess"in document;N(`watchdog:${A} container=${$t(Yt)} children=${Yt.childElementCount} iframes=${y.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${D} paypalNetRequests=${Zt.value}`),y.forEach((j,We)=>{let Tt=(j.getAttribute("title")??"").slice(0,40);N(` iframe[${We}] ${$t(j)}${Tt?` title="${Tt}"`:""} ${St(j)}`);let Ot=wt(j);Ot&&N(` ${Ot}`)}),Pn.length===0&&N(" (no PayPal/zoid window errors captured)")};F&&(_t.push(setTimeout(()=>tt("3s"),3e3)),_t.push(setTimeout(()=>tt("8s"),8e3)),_t.push(setTimeout(()=>tt("15s"),15e3))),N("render:start");let he=$.startTiming();_t.push(setTimeout(()=>{Ee()||Qt||(N("watchdog:11s retryable render timeout"),en("PayPal Buttons render did not settle within 11000ms.",!0))},xs)),m.render(Yt).then(()=>{if(N(`render:resolved inactive=${Ee()}`),Nt(),Ee()){Lt();return}Qt=!0,te(!0),xe(!1),f.current?.("ready"),$.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"checkout_render",durationMs:$.elapsed(he),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(A=>{let y=A instanceof Error?A.message:"PayPal failed to render.";N(`render:rejected msg=${y.slice(0,120)}`),Nt(),en(y)})}).catch(s=>{let M=s instanceof Error?s.message:"PayPal SDK failed to load.";N(`loadScript:rejected msg=${M.slice(0,120)}`),en(M)})},0);return()=>{mt=!0,clearTimeout(C),Hn&&clearTimeout(Hn),Nt(),Lt()}},[I,Q,o,u,a,l,e,U,ne,$]);let nn=F?Ho("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ne?"#fef2f2":"#f3f4f6",border:`1px solid ${Ne?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${ye} failed=${Ne})`,qe.length===0?`
7
7
  (waiting for first lifecycle event\u2026)`:`
8
- ${je.join(`
9
- `)}`]}):null;return Ne&&!yt?B?yr("div",{children:Jt}):null:Ko("div",{children:[Jt,Ko("div",{"aria-hidden":fe?!0:void 0,style:fe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:io},children:[!ye&&!fe&&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:V,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:io,display:"flex",opacity:ye?1:0},"aria-busy":ue||_},Q)]},Q),we&&yr("button",{ref:Ee,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:wn,style:ws,children:"Try PayPal again"})]})}function so(e){return yr(Za,{...e})}function Qa(e){return yr(Za,{...e})}import{FloPayError as Pn,isSetupIntentClientSecret as Us,resolveTheme as $s}from"@flopay/shared";import{Fragment as fr,jsx as d,jsxs as Ae}from"react/jsx-runtime";var bn="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 Nn(e,{telemetry:!1}).reportSessionIntentDecline(t,n,i)}catch{}}function qs(e){return e instanceof Pn&&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
+ ${qe.join(`
9
+ `)}`]}):null;return Ne&&!ut?F?fr("div",{children:nn}):null:Ho("div",{children:[nn,Ho("div",{"aria-hidden":ge?!0:void 0,style:ge?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:co},children:[!ye&&!ge&&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:K,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:co,display:"flex",opacity:ye?1:0},"aria-busy":ue||_},ne)]},ne),Ce&&fr("button",{ref:_e,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:cn,style:Ms,children:"Try PayPal again"})]})}function uo(e){return fr(ai,{...e})}function ii(e){return fr(ai,{...e})}import{FloPayError as wn,isSetupIntentClientSecret as Ys,resolveTheme as Gs}from"@flopay/shared";import{Fragment as gr,jsx as p,jsxs as Le}from"react/jsx-runtime";var kn="flopay_stripe_resume",ui="flopay_wallet_resume",Ur="flopay_paypal_resume",Js=250,pi="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ea(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function yo({billingApiUrl:e,sessionId:t,nonce:n,request:i}){if(!(!t||!n))try{await new $n(e,{telemetry:!1}).reportSessionIntentDecline(t,n,i)}catch{}}function Xs(e){return e instanceof wn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Yo(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function po(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let i=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),a=Math.round((i>>16&255)*o),u=Math.round((i>>8&255)*o),l=Math.round((i&255)*o);return`#${(1<<24|a<<16|u<<8|l).toString(16).slice(1)}`}var Qs=`
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 @@ ${je.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=ze(0),n=ze(null),i=ze(null),r=Ce((l=i.current)=>{let h=l;h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),a=Ce((l,h)=>{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"}))},h))},[r,e]),c=Ce(l=>{l.yieldedControl&&a(l,600)},[a]),s=Ce(l=>{r();let h=t.current+1;t.current=h,n.current=null;let I={generation:h,method:l,timer:null,yieldedControl:!1};return i.current=I,h},[r]),S=Ce(l=>{let h=i.current;return typeof l=="number"&&h?.generation!==l?!1:(r(h),i.current=null,(typeof l!="number"||n.current===l)&&(n.current=null),!0)},[r]),M=Ce(l=>{let h=i.current,I=l??h?.generation??t.current;(!l||h?.generation===l)&&(r(h),i.current=null),n.current=I},[r]),y=Ce(l=>n.current===(l??t.current),[]),R=Ce(l=>i.current?.generation===l&&n.current!==l,[]),C=Ce(()=>{let l=i.current;l&&c(l)},[c]),_=Ce(()=>{let l=i.current;l&&(l.yieldedControl=!0,r(l))},[r]);return mt(()=>{let l=()=>{document.visibilityState==="visible"?C():_()},h=()=>{_()};return document.addEventListener("visibilitychange",l),window.addEventListener("blur",h),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",l),window.removeEventListener("blur",h),window.removeEventListener("focus",C),r()}},[r,_,C]),{startAttempt:s,finishAttempt:S,invalidateAttempt:M,isAttemptInvalidated:y,isAttemptCurrent:R}}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 Pn?t:new Pn(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:Ae("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:S,onTechnicalFailure:M,runBeforeButtonClick:y,onLoadStateChange:R,placeholderBorderRadius:C}){let _=fn(),l=Xo(),h=Jo(),[I,x]=be("loading");mt(()=>{R?.(I)},[I,R]);let[f,ae]=be(!1),U=ze(!1),ie=ze(null),X=ze(null),[B,G]=be(0),[H,se]=be(!1),$=ze(!1),V=ze(new Map),{startAttempt:de,finishAttempt:Ee,invalidateAttempt:Pe,isAttemptInvalidated:ye,isAttemptCurrent:Z}=fi((Y,E,le)=>{M?.(Y,E,{...le,popupBlocked:le?.popupBlocked??Ln(E)}),se(!0),G(Ne=>Ne+1)});mt(()=>{H&&X.current?.focus()},[H,B]);let fe=Ce(()=>{G(Y=>Y+1)},[]),_e=Ce((Y,E,le)=>{Pe(le),M?.("paypal",Y,{code:E,popupBlocked:Ln(Y)}),se(!0),fe()},[Pe,M,fe]),Q=Ce(()=>{window.setTimeout(()=>{(ie.current?.querySelector("iframe")??ie.current)?.focus()},0)},[]);mt(()=>{$.current&&($.current=!1,Q())},[Q,B]);let ke=Ce(()=>{se(!1),a?.(null),Q()},[Q,a]);mt(()=>{if(!l||U.current)return;let Y=new URLSearchParams(window.location.search),E=Y.get("payment_intent"),le=Y.get("payment_intent_client_secret"),Ne=Y.get("redirect_status");if(!E||!le)return;U.current=!0;let Oe;try{let k=localStorage.getItem(zr);if(k){let ee=JSON.parse(k);ee.clientSecret===le&&(Oe={...ee.accountPatch?{accountPatch:ee.accountPatch}:{},...ee.sessionId?{sessionId:ee.sessionId}:{},...ee.nonce?{nonce:ee.nonce}:{}})}}catch{}try{localStorage.removeItem(zr)}catch{}let ue=new URL(window.location.href);ue.searchParams.delete("payment_intent"),ue.searchParams.delete("payment_intent_client_secret"),ue.searchParams.delete("redirect_status"),window.history.replaceState({},"",ue.toString()),(async()=>{try{if(ae(!0),Ne==="failed"){let J="PayPal payment was declined. Please try again.";a?.(J),S?.(St("paypal",J));return}let{paymentIntent:k,error:ee}=await l.retrievePaymentIntent(le);if(ee){a?.(ee.message??"Failed to retrieve PayPal payment status.");return}if(k&&(k.status==="requires_capture"||k.status==="succeeded")){let J=typeof k.payment_method=="string"?k.payment_method:k.payment_method?.id;r({id:J??k.id,type:"card",threeDSecureActionResultTokenId:k.id,isPaypal:!0},Oe)}else{let J="PayPal payment was not completed. Please try again.";a?.(J),S?.(St("paypal",J))}}catch(k){a?.(k instanceof Error?k.message:"Failed to complete PayPal payment.")}finally{ae(!1)}})()},[l,r,a,S]);let Me=Ce(async Y=>{if(c||f){Y.reject();return}let E=y?await y("paypal"):{proceed:!0};if(!E.proceed){V.current.delete(B),Y.reject();return}let le=de("paypal");V.current.set(B,{generation:le,accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}),se(!1),s?.("paypal"),Y.resolve()},[V,c,s,y,de,f,B]),we=Ce(async Y=>{if(!l||!h)return;let E=V.current.get(B);if(E&&!Z(E.generation)){V.current.delete(B);return}if(!E&&ye()||E&&!Ee(E.generation))return;E||Ee();let le=E??null;if(V.current.delete(B),!le&&y){let k=await y("paypal");if(!k.proceed){Y.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}le={accountPatch:k.accountPatch,sessionId:k.sessionId,nonce:k.nonce}}let Ne=le?.sessionId??e,Oe=le?.nonce??t,ue=le?.accountPatch?.email??n;try{if(ae(!0),a?.(null),!Ne||!ue)throw new Error("Missing sessionId or email for PayPal payment");let k=l.createPaymentMethod,{error:ee,paymentMethod:J}=await k({type:"paypal"});if(ee){_e(ee,"stripe_paypal_create_payment_method_failed",E?.generation),Y.paymentFailed({reason:"fail"});return}let Fe=await new Nn(i).createSessionIntent(Ne,Oe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:J?.id??null,intentKind:"payment"});if(Fe.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let yt=Fe.clientSecret,je={return_url:window.location.href};if(J?.id&&(je.payment_method=J.id),typeof window<"u")try{localStorage.setItem(zr,JSON.stringify({clientSecret:yt,sessionId:Ne,nonce:Oe,accountPatch:le?.accountPatch}))}catch{}let{error:it,paymentIntent:F}=await l.confirmPayment({clientSecret:yt,confirmParams:je,redirect:"if_required"});if(it){if(typeof window<"u")try{localStorage.removeItem(zr)}catch{}if(Nr(it)){let Ue=it.message??"Your payment was declined.";a?.(Ue),S?.(St("paypal",Ue,{code:Mn(it),declineCode:mr(it)})),await uo({billingApiUrl:i,sessionId:Ne,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(it)??"provider_declined"}})}else _e(it,"stripe_paypal_confirm_failed",E?.generation);return}if(typeof window<"u")try{localStorage.removeItem(zr)}catch{}let L=typeof F?.payment_method=="string"?F.payment_method:F?.payment_method?.id;r({id:L??F?.id,type:"card",threeDSecureActionResultTokenId:F?.id,isPaypal:!0},{accountPatch:le?.accountPatch,sessionId:Ne,nonce:Oe});return}catch(k){_e(k,"stripe_paypal_failed",E?.generation)}finally{ae(!1)}},[l,h,e,t,n,i,r,a,S,y,_e,Ee,Z,ye,B]);return Ae(fr,{children:[d(hi,{state:I,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:Ae("div",{ref:ie,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[H&&d("button",{ref:X,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ke,style:mi,children:"Try PayPal again"}),d(pi,{onReady:Y=>x(gi(Y,["paypal"])),onLoadError:()=>{x("load_error"),Zo(Tt(_),"paypal","paypal")},onClick:Me,onConfirm:we,onCancel:()=>{let Y=V.current.get(B);V.current.delete(B),Tt(_)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Pe(Y?.generation),se(!1),$.current=!0,fe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},B)]})}),f&&d(hn,{status:"processing"})]})}function di({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:r,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:S,onDecline:M,onTechnicalFailure:y,runBeforeButtonClick:R,onLoadStateChange:C,placeholderBorderRadius:_}){let l=fn(),h=Xo(),I=Jo(),[x,f]=be("loading");mt(()=>{C?.(x)},[x,C]);let[ae,U]=be(!1),ie=ze(null),X=ze(null),[B,G]=be(0),[H,se]=be(!1),[$,V]=be("google_pay"),de=ze(!1),Ee=ze("google_pay"),Pe=ze("google_pay"),ye=ze(new Map),{startAttempt:Z,finishAttempt:fe,invalidateAttempt:_e,isAttemptInvalidated:Q,isAttemptCurrent:ke}=fi((ue,k,ee)=>{y?.(ue,k,{...ee,popupBlocked:ee?.popupBlocked??Ln(k)}),V(ue),se(!0),G(J=>J+1)});mt(()=>{H&&X.current?.focus()},[H,B]);let Me=Ce(()=>{G(ue=>ue+1)},[]),we=Ce((ue,k,ee,J)=>{_e(J),y?.(ue,k,{code:ee,popupBlocked:Ln(k)}),V(ue),se(!0),Me()},[_e,y,Me]),Y=Ce(()=>{window.setTimeout(()=>{(ie.current?.querySelector("iframe")??ie.current)?.focus()},0)},[]);mt(()=>{de.current&&(de.current=!1,Y())},[Y,B]);let E=Ce(()=>{se(!1),s?.(null),Y()},[Y,s]),le=Ce(async ue=>{if(!h||!I)return;let k=ye.current.get(B);if(k&&!ke(k.generation)){ye.current.delete(B);return}if(!k&&Q()||k&&!fe(k.generation))return;k||fe();let ee=ue.expressPaymentType??k?.method??Ee.current,J=k??null;ye.current.delete(B);let Fe=ai(ee);if(!J&&R){let L=await R(Fe);if(!L.proceed){ue.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}J={accountPatch:L.accountPatch,sessionId:L.sessionId,nonce:L.nonce}}let yt=Fe,je=J?.sessionId??e,it=J?.nonce??t,F=J?.accountPatch?.email??n;try{U(!0),s?.(null);let{error:L}=await I.submit();if(L){we(ee,L,"stripe_wallet_submit_failed",k?.generation);return}let{error:Ue,paymentMethod:qe}=await h.createPaymentMethod({elements:I});if(Ue||!qe){we(ee,Ue??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",k?.generation);return}if(!je||!F)throw new Error("Missing sessionId or email for wallet payment");let st=await new Nn(i).createSessionIntent(je,it??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ee??Fe,paymentMethodId:qe.id,intentKind:r});if(st.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let ft=st.clientSecret,{error:Bt,intentId:Wt}=Us(ft)?await h.confirmCardSetup(ft,{payment_method:qe.id}).then(m=>({error:m.error,intentId:m.setupIntent?.id})):await h.confirmCardPayment(ft,{payment_method:qe.id}).then(m=>({error:m.error,intentId:m.paymentIntent?.id}));if(Bt){if(Nr(Bt)){let m=Bt.message??"Your payment was declined.";s?.(m),M?.(St(yt,m,{code:Mn(Bt),declineCode:mr(Bt)})),await uo({billingApiUrl:i,sessionId:je,nonce:it,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ee??Fe,providerDeclineReason:Mn(Bt)??"provider_declined"}})}else we(ee,Bt,"stripe_wallet_confirm_failed",k?.generation);return}c({id:qe.id,type:"card",threeDSecureActionResultTokenId:Wt},{accountPatch:J?.accountPatch,sessionId:je,nonce:it})}catch(L){we(ee,L,"stripe_wallet_failed",k?.generation)}finally{U(!1)}},[h,I,e,t,n,i,r,c,s,M,R,we,fe,ke,Q,B]),Ne=ot(()=>{let ue=["applePay","googlePay","paypal","link","amazonPay","klarna"],k=new Set(["applePay","googlePay"]),ee=new Set(a.map(ri)),J={};for(let Fe of ue)ee.has(Fe)?J[Fe]=k.has(Fe)?"always":"auto":J[Fe]="never";return J},[a]),Oe=ot(()=>a.map(ri),[a]);return Ae(fr,{children:[d(hi,{state:x,placeholderTestId:"flopay-wallet-placeholder",borderRadius:_,children:Ae("div",{ref:ie,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[H&&Ae("button",{ref:X,type:"button","data-testid":"flopay-wallet-retry-button",onClick:E,style:mi,children:["Try ",yi($)," again"]}),d(pi,{onReady:ue=>{f(gi(ue,Oe))},onLoadError:ue=>{f("load_error"),Zo(Tt(l),"stripe","wallet")},onClick:async ue=>{Ee.current=ue.expressPaymentType,Pe.current=ai(ue.expressPaymentType);let k=R?await R(Pe.current):{proceed:!0};if(!k.proceed){ye.current.delete(B),ue.reject();return}let ee=Z(ue.expressPaymentType);ye.current.set(B,{generation:ee,method:ue.expressPaymentType,accountPatch:k.accountPatch,sessionId:k.sessionId,nonce:k.nonce}),se(!1),S?.(Pe.current),ue.resolve()},onConfirm:le,onCancel:()=>{let ue=ye.current.get(B);ye.current.delete(B),Tt(l)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),_e(ue?.generation),se(!1),de.current=!0,Me()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ne,layout:{maxColumns:1,overflow:"never"}}},B)]})}),ae&&d(hn,{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:S,textColor:M,borderRadius:y,fontFamily:R}){let C=Ds(e,t),_=ja[e],l=C?.backgroundColor??s??"#ffffff",h=C?.borderColor??S??"#d1d5db",I=C?.textColor??M??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!i&&c()},disabled:n||i,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:co,padding:"0 1rem",backgroundColor:l,color:I,border:`1px solid ${h}`,borderRadius:y??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,cursor:n||i?"not-allowed":"pointer",opacity:i&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:r?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?d("span",{style:{margin:"0 auto"},children:`Connecting to ${gr(e)}\u2026`}):Ae(fr,{children:[Ae("span",{style:{display:"inline-flex",alignItems:"center",gap:Fs(e)?8:0},children:[_?d("img",{src:_,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):C?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:C.logoSvg}}):null,d("span",{children:gr(e)})]}),a&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:I,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:S,onCancel:M,runBeforeButtonClick:y,onButtonClick:R,isProcessing:C,submitButtonColor:_,submitButtonBorderRadius:l,submitButtonStyle:h,errorText:I}){let x=fn(),f=Xo(),ae=Jo(),[U,ie]=be(!1),X=ze(!1),[B,G]=be(!1),[H,se]=be("loading"),$=Ce(async()=>{if(!f||!ae||C||X.current||!B)return;X.current=!0,ie(!0);let V=y?await y("card"):{proceed:!0};if(!V.proceed){X.current=!1,ie(!1);return}R?.("card");let de=V.sessionId??t,Ee=V.nonce??n,Pe=V.accountPatch?.email??i;try{s?.(null);let ye=await ae.submit();if(ye.error){s?.(ye.error.message??"Payment failed.");return}let Z=await f.createPaymentMethod({elements:ae});if(Z.error||!Z.paymentMethod){s?.(Z.error?.message??"Failed to create payment method.");return}let fe=Z.paymentMethod;if(!de||!Pe)throw new Error("Missing sessionId or email for payment.");let _e=fe.type||e,Q=await new Nn(a).createSessionIntent(de,Ee??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_e,paymentMethodId:null,intentKind:"payment"});if(Q.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ke=Q.clientSecret;if(typeof window<"u")try{localStorage.setItem(bn,JSON.stringify({clientSecret:ke,sessionId:de,nonce:Ee,accountPatch:V.accountPatch,paymentMethodId:fe.id,paymentMethodType:fe.type??e,gateway:"stripe"}))}catch{}let{error:Me,paymentIntent:we}=await f.confirmPayment({clientSecret:ke,confirmParams:{return_url:window.location.href,payment_method:fe.id},redirect:"if_required"});if(Me){if(typeof window<"u")try{localStorage.removeItem(bn)}catch{}let le=Me.message??"Payment failed.";s?.(le),S?.(St("card",le,{code:Me.code})),await uo({billingApiUrl:a,sessionId:de,nonce:Ee,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Me.code??"provider_declined"}});return}let Y=we?.status;if(!no(Y)){if(typeof window<"u")try{localStorage.removeItem(bn)}catch{}let le=Y==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";s?.(le),S?.(St("card",le,{code:Y??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(bn)}catch{}let E=typeof we?.payment_method=="string"?we.payment_method:we?.payment_method?.id;c({id:E??fe.id,type:"card",threeDSecureActionResultTokenId:we?.id,gateway:"stripe",paymentMethodType:fe.type??e},{accountPatch:V.accountPatch,sessionId:de,nonce:Ee})}catch(ye){s?.(ye instanceof Error?ye.message:"Payment failed. Please try again.")}finally{X.current=!1,ie(!1)}},[f,ae,C,B,y,R,t,n,i,a,e,c,s,S]);return Ae("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(Rs,{onReady:()=>se("ready"),onLoadError:()=>{se("load_error"),Zo(Tt(x),"stripe","apm")},onChange:V=>{G(!!V.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...i?{email:i}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{$()},disabled:!B||U||C||H!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:_,color:"white",border:"none",borderRadius:l,fontSize:"1rem",fontWeight:600,cursor:!B||U||C||H!=="ready"?"not-allowed":"pointer",opacity:!B||U||C||H!=="ready"?.5:1,transition:"opacity 120ms ease-out",...h??{}},children:U?"Processing\u2026":`Pay with ${gr(e)}`}),I&&d(dr,{margin:"0.75rem 0 0",children:I})]})}function ui({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:r,paymentElementMethods:a,stripeInstance:c,paymentElementBaseOptions:s,onTokenizedBody:S,onErrorChange:M,onButtonClick:y,onDecline:R,runBeforeButtonClick:C,onLoadStateChange:_,isProcessing:l=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:I=8,submitButtonStyle:x,buttonAppearance:f,themeId:ae,onExpandApm:U,expandedApmMethod:ie}){let[X,B]=be(null),[G,H]=be(null),se=ze(!1);mt(()=>{a.length>0&&c?_?.("ready"):c||_?.("loading")},[a.length,c,_]);let $=Ce(async Z=>{if(!c||se.current||l)return;se.current=!0,H(Z);let fe=C?await C("card"):{proceed:!0};if(!fe.proceed){se.current=!1,H(null);return}y?.("card");let _e=fe.sessionId??e,Q=fe.nonce??t,ke=fe.accountPatch?.email??n;try{if(M?.(null),!_e||!ke)throw new Error("Missing sessionId or email for payment.");let Me=await new Nn(r).createSessionIntent(_e,Q??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,paymentMethodId:null,intentKind:"payment"});if(Me.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let we=Me.clientSecret;if(typeof window<"u")try{localStorage.setItem(bn,JSON.stringify({clientSecret:we,sessionId:_e,nonce:Q,accountPatch:fe.accountPatch,paymentMethodType:Z,gateway:"stripe"}))}catch{}let{error:Y,paymentIntent:E}=await c.confirmPayment({clientSecret:we,confirmParams:{return_url:window.location.href,payment_method_data:{type:Z,billing_details:{name:i&&i.trim().length>=3?i.trim():"FloPay Customer",...ke?{email:ke}:{}}}},redirect:"if_required"});if(Y){if(typeof window<"u")try{localStorage.removeItem(bn)}catch{}let Oe=Y.message??"Payment failed.";M?.(Oe),R?.(St("card",Oe,{code:Y.code})),await uo({billingApiUrl:r,sessionId:_e,nonce:Q,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,providerDeclineReason:Y.code??"provider_declined"}});return}let le=E?.status;if(!no(le)){if(typeof window<"u")try{localStorage.removeItem(bn)}catch{}let Oe=le==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";M?.(Oe),R?.(St("card",Oe,{code:le??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(bn)}catch{}let Ne=typeof E?.payment_method=="string"?E.payment_method:E?.payment_method?.id;S({id:Ne??E?.id,type:"card",threeDSecureActionResultTokenId:E?.id,gateway:"stripe",paymentMethodType:Z},{accountPatch:fe.accountPatch,sessionId:_e,nonce:Q})}catch(Me){M?.(Me instanceof Error?Me.message:"Payment failed. Please try again.")}finally{se.current=!1,H(null)}},[c,l,C,y,e,t,n,r,i,S,M,R]),[V,de]=be(null),Ee=U?ie??null:V,Pe=Ce(Z=>{se.current||l||Ee&&Ee!==Z||(ni(Z)?U?U(Z):de(Z):$(Z))},[Ee,l,$,U]),ye=ot(()=>V?{...s,paymentMethodTypes:[V]}:null,[V,s]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(Z=>{let fe=ie===Z,_e=G===Z,Q=G!==null&&G!==Z||ie!=null&&ie!==Z;return Ae(Os.Fragment,{children:[d(Js,{method:Z,themeId:ae,submitting:_e,disabled:Q,highlighted:fe,hasNextStep:ni(Z),onClick:()=>Pe(Z),backgroundColor:f?.backgroundColor,borderColor:f?.borderColor,textColor:f?.textColor,borderRadius:f?.borderRadius,fontFamily:f?.fontFamily}),!U&&V===Z&&ye&&c&&d(er,{stripe:c,options:ye,children:d(Go,{method:Z,sessionId:e,email:n,billingName:i,billingApiUrl:r,onTokenizedBody:S,onErrorChange:M,onDecline:R,onCancel:()=>de(null),runBeforeButtonClick:C,onButtonClick:y,isProcessing:l,submitButtonColor:h,submitButtonBorderRadius:I,submitButtonStyle:x})},Z)]},Z)})})}function Xs({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,onComplete:a,onError:c,onDecline:s,onTokenizedBody:S,firstName:M,lastName:y,chv:R,className:C,isProcessing:_,error:l,onErrorChange:h,showPayPal:I=!0,showStripe:x=!0,enabledPaymentMethods:f,enabledPaymentMethodCountries:ae,showApplePay:U=!0,showGooglePay:ie=!0,layout:X="default",theme:B,buttonsTheme:G,buttonsStyles:H,appearance:se,cardButtonContent:$,cardBackButtonContent:V,cardTitleContent:de,showSecurityFooter:Ee,onButtonClick:Pe,onBeforeButtonClick:ye,enableAVS:Z,cardFieldOrder:fe,cardPreFormSlot:_e,avsLayout:Q="row",country:ke,zip:Me,addressLine1:we,addressLine2:Y,city:E,state:le,onCountryChange:Ne,onZipChange:Oe,avsCheck:ue,checkoutType:k,checkoutLayout:ee,totalAmount:J=0,currency:Fe="usd",initialCardOpen:yt=!1,directPaypal:je,isSubscription:it=!1,session:F,debug:L=!1}){let Ue=fn(),qe=Oo(),st=zs(dn),ft=to(),[Bt,Wt]=be(!1),[m,ve]=be(null),[We,tt]=be(ke??"US"),[ht,Ye]=be(Me??""),[Ze,xe]=be(we??""),[Ge,At]=be(Y??""),[Ke,$n]=be(E??""),[Pt,Sn]=be(le??""),[wn,qn]=be({}),Rt=ze(Me??""),Ft=ze(ke??"US"),Yt=ze(we??""),Lt=ze(Y??""),Gt=ze(E??""),pn=ze(le??""),te=ot(()=>xs(Z),[Z]),jt=te!==null,kn=!!F?.vault?.html,Rn=!!F?.gateways?.pcivault,w=!!(F?.gateways?.stripe?.enabledPaymentMethods??f)?.includes("card"),Je=kn||w||Rn,Se=!!(x&&Je&&Ue&&e),[Fn,$e]=be(()=>X!=="buttons"||yt?e??null:null),[jn,rr]=be(0),Kt=X!=="buttons"||yt||!!e&&Fn===e,lt=ot(()=>!Ue||!Se||!e||!Kt?null:Ue.cardCapture({sessionId:e}),[Ue,Se,e,Kt]),Dt=ot(()=>{let o=We,v=te?Be(te.postal_code,o):!1;return Ys(o,ht,v)},[te,We,ht]),{avsInvalid:Vt,invalidAvsFields:vt}=ot(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!Se||!te)return{avsInvalid:!1,invalidAvsFields:o};let v=We,K=(ne,Xe)=>Be(ne,v)&&!Xe.trim(),oe={line1:K(te.address_line_1,Ze),city:K(te.city,Ke),state:K(te.state,Pt),zip:Dt.empty||Dt.malformed};return{avsInvalid:oe.line1||oe.city||oe.state||oe.zip,invalidAvsFields:oe}},[Se,te,We,Ze,Ke,Pt,Dt]),[nn,rn]=be(!1),[mn,on]=be(!1),[It,Nt]=be(()=>Ho(F?.vault)),[Re,nt]=be(yt&&Je?"card":"buttons"),[rt,In]=be(null),Kn=Re==="expanding"||Re==="card",Ht=280,Ot=ze(null),zt=Ce(o=>{Ot.current&&clearTimeout(Ot.current),Ot.current=setTimeout(()=>{Ot.current=null,o()},Ht)},[Ht]);mt(()=>()=>{Ot.current&&clearTimeout(Ot.current)},[]);let En=Ce(()=>{$e(e??null),rr(o=>o+1),nt("expanding"),zt(()=>nt("card"))},[zt,e]),Vn=Ce(()=>{nt("collapsing"),zt(()=>nt("buttons"))},[zt]),Ut=Ce(o=>{In(o),nt("apm-expanding"),zt(()=>nt("apm-form"))},[zt]),_n=Ce(()=>{nt("apm-collapsing"),zt(()=>{nt("buttons"),In(null)})},[zt]);mt(()=>{X==="buttons"&&yt&&Je&&($e(e??null),nt("card"))},[X,yt,Je,e]);let[bt,g]=be(null),N=ze(!1),[W,Te]=be(null),ge=ze(W);mt(()=>{ge.current=W},[W]);let D=n||ft,P=l??m,A=ot(()=>$s(B),[B]),u=ot(()=>{let o=A?.buttonsLayout??Is(G);return H?{...o,...H,cardButton:{...o.cardButton,...H.cardButton},cardFormContainer:{...o.cardFormContainer,...H.cardFormContainer},backButton:{...o.backButton,...H.backButton},backButtonIcon:{...o.backButtonIcon,...H.backButtonIcon},submitButton:{...o.submitButton,...H.submitButton},title:{...o.title,...H.title}}:o},[A,G,H]),me=se??A?.appearance,b=ot(()=>{let o=me?.variables,v=Xe=>typeof Xe=="string"&&Xe?Xe:void 0,K=u.submitButton,oe=v(o?.colorPrimary)??v(K?.backgroundColor)??"#4A49FF",z=X==="buttons",ne=u.nameInput;return{primaryColor:oe,primaryHoverColor:v(o?.colorPrimaryHover)??lo(oe,.12),inputBackgroundColor:v(u.cardInputBackground)??v(o?.colorBackground)??"#ffffff",textColor:v(u.cardInputColor)??v(ne?.color)??v(o?.colorText)??"#262833",borderColor:v(u.cardInputBorder)??(z?"#e5e7eb":"#A4A4FF"),placeholderColor:v(u.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(o?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(ne?.fontFamily)??v(o?.fontFamily)??"Poppins, sans-serif",fontSize:v(u.cardInputFontSize)??v(o?.fontSizeBase)??"16px",fontWeight:String(si(ne?.fontWeight)??400),borderRadius:v(o?.borderRadius)??"8px"}},[me,u,X]),p=st.inlineSessionPatchProcessing??!1,T=(_??Bt)||p,Ie=D.replace(/\/+$/,""),O=ot(()=>$o({userId:r,email:i,firstName:M,lastName:y,country:ke,zip:Me},wn),[r,i,M,y,ke,Me,wn]),q=[O.firstName,O.lastName].filter(o=>!!o?.trim()).join(" "),he=ot(()=>Ue?Ue.getRawProvider():null,[Ue]),Qe=ot(()=>qe?qe.getRawProvider():null,[qe]),De=J||100,ce=ot(()=>me?Ns(me):null,[me]),pe=ce?{appearance:ce}:null,Ve=ot(()=>{let o=ce??{},v=o.rules??{};return{...o,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[ce]),an=ot(()=>{let o=Wa(J);return{...o,currency:Fe.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...pe}},[J,Fe,pe]),sn=ot(()=>({mode:"payment",amount:De,currency:Fe.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...pe}),[De,Fe,pe]),j=Ce(o=>{ve(o),h?.(o)},[h]);mt(()=>{!Se||!lt||lt.setCardFieldOrder?.(fe??null,te==null)},[Se,lt,fe,te]),mt(()=>{(Re==="expanding"||Re==="collapsing"||Re==="apm-expanding"||Re==="apm-collapsing")&&j(null)},[Re,j]);let ln=Ce((o,v,K)=>{s?.(St(o,v,K))},[s]),or=Ce((o,v,K)=>{let oe=K?.popupBlocked??Ln(v),z=Hs(o,oe),ne=Zn(K?.code)??Mn(v)??"external_payment_method_failed",Xe=new Pn(z,"api_error",{code:"external_payment_method_failed",param:o});g(null),X==="buttons"&&(nt("buttons"),In(null)),j(z),c?.(Xe),console.error("[FloPay] External payment method failed:",{method:o,code:ne,popupBlocked:oe})},[X,c,j]);mt(()=>{if(!Se||!e){Nt(null);return}let o=Ho(F?.vault);if(o){Nt(o);return}if(!Kt){Nt(null);return}Nt(null);let v=!0;return new Nn(Ie).getVaultCapture(e,t).then(K=>{if(!v)return;let oe=Ho(K);oe?Nt(oe):j("Failed to load the secure card form.")}).catch(K=>{v&&j(K instanceof Error?K.message:"Failed to load the secure card form.")}),()=>{v=!1}},[Se,Kt,jn,e,F?.vault?.html,F?.vault?.messageToken,F?.vault?.expectedOrigin,Ie,t,j]);let Hn=ze({onComplete:a,onError:c,updateError:j,emitDecline:ln,resolvedAccount:O,avsConfig:te,avsCheckProp:ue,sessionId:e,nonce:t,baseUrl:Ie});Hn.current={onComplete:a,onError:c,updateError:j,emitDecline:ln,resolvedAccount:O,avsConfig:te,avsCheckProp:ue,sessionId:e,nonce:t,baseUrl:Ie};let So=ze(!1),Di=Ce(()=>{let{resolvedAccount:o,avsConfig:v,avsCheckProp:K}=Hn.current,oe=Ft.current||o.country||"US",z=v?Be(v.state,oe):!1,ne=v?Be(v.address_line_1,oe):!1,Xe=v?Be(v.postal_code,oe):!1,Ct=v?Be(v.city,oe):!1,Et=v?Be(v.address_line_2,oe):!1,et=ne&&!z&&Xe?ti(oe,(Rt.current??"").trim()):null,_t=z?pn.current:et;return{accountData:{userId:o.userId??"",email:o.email??"",firstName:o.firstName??"",lastName:o.lastName??"",...Xe&&Rt.current?{zip:Rt.current}:{},...Ct&&Gt.current?{city:Gt.current}:{},..._t?{state:_t}:{},...ne&&Yt.current?{addressLine1:Yt.current}:{},...Et&&Lt.current?{addressLine2:Lt.current}:{},country:oe},...K!==void 0?{avsCheck:K}:{},...v?{avsConfig:{country:Be(v.country,oe),postal_code:Xe,address_line_1:ne,address_line_2:Et,city:Ct,state:z}}:{}}},[]);mt(()=>{!Se||!lt||lt.setSubmitGate?.(Vt)},[Se,lt,Vt]),mt(()=>{if(!Se||!lt)return;So.current=!1;let o=!1,v=lt.on("submitting",()=>{rn(!0),g("processing");let{baseUrl:ne,sessionId:Xe,nonce:Ct,updateError:Et,onError:et}=Hn.current;!Xe||!Ct||new Nn(ne).patchAccountSnapshot(Xe,Ct,Di(),{telemetryMode:"best_effort"}).catch(_t=>{if(!qs(_t))return;let Le=_t instanceof Error?_t.message:"Please check your billing address and try again.";Et(Le),g(null),et?.(_t instanceof Pn?_t:new Pn(Le,"api_error"))})}),K=lt.on("complete",async ne=>{pr(ne.sessionId??Hn.current.sessionId),g("success"),await new Promise(Xe=>setTimeout(Xe,Tn)),!So.current&&(So.current=!0,Hn.current.onComplete?.({status:"succeeded",paymentIntentId:ne.intentId,checkoutMethod:"card"}))}),oe=lt.on("decline",async ne=>{let{updateError:Xe,emitDecline:Ct}=Hn.current,Et=ne.message??"Your payment was declined. Please try another card or contact your bank.";Xe(Et),g("error"),Ct("card",Et,ne.declineReason?{declineCode:ne.declineReason}:void 0),await new Promise(et=>setTimeout(et,gn)),!o&&g(null)}),z=lt.on("error",async ne=>{let{updateError:Xe,onError:Ct}=Hn.current,Et=ne.message??"There was a problem processing your payment. Please try again.";Xe(Et),g("error"),Ct?.(new Pn(Et,"api_error")),await new Promise(et=>setTimeout(et,gn)),!o&&g(null)});return()=>{o=!0,v(),K(),oe(),z()}},[Se,lt]);let yn=!!je?.clientId,wr=Array.isArray(f),jr=wr&&f.length>0,Li=wr&&f.includes("paypal"),{expressMethods:Kr,paymentElementMethods:kr}=ot(()=>Ls(f,{excludePaypal:yn}),[f,yn]),ma=yn||!!qe,Ni=ot(()=>ma?Kr.filter(o=>o!=="paypal"):Kr,[Kr,ma]),Oi=ot(()=>{let o=[];return U&&o.push("apple_pay"),ie&&o.push("google_pay"),o},[U,ie]),Vr=wr?Ni:Oi,zi=x&&Vr.length>0,wo=jt?We:ke,Hr=ot(()=>{let o=wo?.trim().toUpperCase();return o?ae?kr.filter(v=>{let K=ae[v];return!K||K.length===0||K.includes(o)}):As(kr,wo):kr},[kr,wo,ae]),ko=ot(()=>({mode:"payment",amount:De,currency:Fe.toLowerCase(),paymentMethodCreation:"manual",appearance:Ve}),[De,Fe,Ve]),[ya,fa]=be("loading"),[ga,ha]=be("loading"),[Pa,ba]=be("loading"),[Ui,Ro]=be(!1),[va,Io]=be("loading"),[Wr,$i]=be();mt(()=>{$i(Ya())},[]);let Ca=I&&(yn||(wr?Li:Wr===!1)),Sa=x&&zi,Rr=Ca&&yn,wa=va==="retrying"||va==="exhausted",Ir=Ca&&!!Qe&&(!yn||wa),Er=Sa&&!!he,_r=x&&jr&&Hr.length>0&&!!he,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=ze(!1);mt(()=>{if(!Yr.current){if(!x&&!I){Yr.current=!0;let o=new Pn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(o),j(o.message)}else if(!x&&I&&!yn&&!Qe){Yr.current=!0;let o=new Pn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(o),j(o.message)}else if(Wr!==void 0&&!Je&&!Ra){Yr.current=!0;let o=new Pn("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),j(o.message)}}},[x,I,yn,Qe,Wr,Je,Ra,c,j]);let Ia=ze(!1);mt(()=>{if(Ia.current||!jr)return;let o=[];U!==!0&&o.push("showApplePay"),ie!==!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,U,ie]);let Ea=Ce((o,v)=>st.applyInlineSessionPatch?st.applyInlineSessionPatch(o).then(K=>({error:null,sessionId:K.sessionId||e,nonce:K.session?.clientSecret||t})).catch(K=>{let oe=ii(v,K);return j(oe.message),c?.(oe),{error:oe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[st.applyInlineSessionPatch,t,c,e,j]),cn=Ce(async o=>{if(!ye)return{proceed:!0};try{let v=await ye({method:o,sessionId:e||void 0,createSession:st.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&qn(oe=>({...oe??{},...v.account}));let K=await Ea(v,o);return K.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:K.sessionId,nonce:K.nonce}}return{proceed:!0}}catch(v){let K=ii(o,v);return j(K.message),c?.(K),{proceed:!1}}},[Ea,st.inlineSessionDraft,ye,c,e,j]),_a=Ce(async(o,v)=>{if(N.current)return;N.current=!0,Wt(!0),g("processing"),j(null);let K=v?.sessionId??e,oe=v?.nonce??t,z=$o(O,v?.accountPatch),ne=v?.completionPaymentMethodId??ro(o),Xe=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o;try{let Et=await new Nn(Ie).processPayment(z.userId??"",{sessionId:K,nonce:oe,tokenizedData:Xe,accountData:{userId:z.userId??"",email:z.email??"",firstName:z.firstName??"",lastName:z.lastName??"",...te?(()=>{let Le=Ft.current,Zt=Be(te.state,Le),Qt=Be(te.address_line_1,Le),Jn=Be(te.postal_code,Le),Xn=Qt&&!Zt&&Jn?ti(Le,(Rt.current??"").trim()):null,xt=Zt?pn.current:Xn;return{country:Le,...Jn&&Rt.current?{zip:Rt.current}:{},...Be(te.city,Le)&&Gt.current?{city:Gt.current}:{},...xt?{state:xt}:{},...Qt&&Yt.current?{addressLine1:Yt.current}:{},...Be(te.address_line_2,Le)&&Lt.current?{addressLine2:Lt.current}:{}}})():{}},chv:R,avsCheck:ue??!1,checkoutType:k,checkoutLayout:ee,avsConfig:te?{country:Be(te.country,Ft.current),postal_code:Be(te.postal_code,Ft.current),address_line_1:Be(te.address_line_1,Ft.current),address_line_2:Be(te.address_line_2,Ft.current),city:Be(te.city,Ft.current),state:Be(te.state,Ft.current)}:void 0});if(Et.ok){pr(K),g("success"),Te(null),await new Promise(Le=>setTimeout(Le,Tn)),a?.({status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:ne,checkoutMethod:o.isPaypal?"paypal":"card"});return}let et=await Et.json().catch(()=>null);if(et?.type==="paypal_redirect_required"){let Le=et.threeDSecureToken,Zt=et.paymentMethodId||o.id||"";if(!Ue||!Le){g("error"),j("PayPal authorization required but no token provided.");return}try{let Qt=qe?.getRawProvider();if(!Qt){j("PayPal is not available.");return}let Jn={return_url:window.location.href};Zt&&(Jn.payment_method=Zt);let{error:Xn}=await Qt.confirmPayment({clientSecret:Le,confirmParams:Jn,redirect:"if_required"});if(Xn){g("error");let xt=Xn.message??"PayPal payment failed.";j(xt),ln("paypal",xt,{code:Xn.code})}}catch(Qt){g("error"),j(Qt instanceof Error?Qt.message:"PayPal authorization failed.")}return}if(et?.type==="paypal_direct_required"){let Le=et.orderId;if(!Le){g("error"),j("PayPal retry required but no order id provided.");return}let Zt=ge.current?.attempts??0;if(Zt>=2){g("error"),j("PayPal payment could not be completed after multiple attempts."),ln("paypal","paypal_direct_required retry limit exceeded");return}Ro(!1),Io("loading"),Te({orderId:Le,attempts:Zt+1}),g(null);return}g("error");let _t=et?.message??"Payment failed. Please try again.";j(_t),ln(o.isPaypal?"paypal":"card",_t,{code:et?.code??et?.gatewayErrorCode,declineCode:et?.declineCode??et?.gatewayDeclineReason}),await new Promise(Le=>setTimeout(Le,gn))}catch(Ct){g("error"),j(Ct instanceof Error?Ct.message:"An unexpected error occurred"),await new Promise(Et=>setTimeout(Et,gn))}finally{Wt(!1),g(null),N.current=!1}},[Ie,e,t,O,q,R,Ue,qe,a,c,j,ln]),Xt=Ce((o,v)=>{S?S(o):_a(o,v)},[S,_a]),xa=ze(!1);mt(()=>{if(typeof window>"u"||xa.current)return;let o=new URLSearchParams(window.location.search),v=o.get("payment_intent"),K=o.get("payment_intent_client_secret"),oe=o.get("redirect_status");if(!v||!K)return;let z=_t=>{let Le=localStorage.getItem(_t);if(!Le)return null;try{return JSON.parse(Le)}catch{return localStorage.removeItem(_t),null}},ne=z(bn)??z(oi),Xe;if(ne?.clientSecret){if(ne.clientSecret!==K)return;Xe={...ne.accountPatch?{accountPatch:ne.accountPatch}:{},...ne.sessionId?{sessionId:ne.sessionId}:{},...ne.nonce?{nonce:ne.nonce}:{}}}else if(ne?.sessionId&&ne.sessionId!==e)return;xa.current=!0,localStorage.removeItem(bn),localStorage.removeItem(oi);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=ne?.paymentMethodType??ne?.tokenType??"card",et="card";(async()=>{let _t=Ue?.getRawProvider();if(!_t){let xt="Payment is not available \u2014 please refresh and try again.";j(xt),ln(et,xt);return}if(oe==="failed"){let xt="Payment was declined. Please try again.";j(xt),ln(et,xt);return}let{paymentIntent:Le,error:Zt}=await _t.retrievePaymentIntent(K);if(Zt){let xt=Zt.message??"Failed to retrieve payment status.";j(xt),ln(et,xt,{code:Zt.code});return}let Qt=Le?.status,Jn=no(Qt);if(!Le||!Jn){let xt=Qt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";j(xt),ln(et,xt,{code:Qt??"missing_payment_intent"});return}let Xn=typeof Le.payment_method=="string"?Le.payment_method:Le.payment_method?.id;Xt({id:Xn??ne?.paymentMethodId??ne?.tokenId??Le.id,type:"card",threeDSecureActionResultTokenId:Le.id,gateway:ne?.gateway??"stripe",paymentMethodType:Et},Xe)})()},[e,Xt,Ue,j,ln]);let Eo=Ce(o=>{o.preventDefault()},[]);if(!(Ue!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let xr=X==="buttons",$t=me?.variables,Vi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),_o=$t?.colorBackground,Hi=_o&&!Vi.has(_o)?_o:void 0,Tr=u.cardInputBorder??(xr?"#e5e7eb":"#A4A4FF"),xo=$t?.colorDanger??"#dc2626",Wn=o=>nn&&o?xo:Tr,Gr=(Dt.malformed||Dt.empty)&&(mn||nn),Wi=Gr?xo:Wn(vt.zip),To=u.cardFormContainer?.backgroundColor??Hi??(xr?"white":"#EDEDFF"),Mr=u.cardInputBackground??$t?.colorBackground??"white",Mo=ir(V),Ta=ir(de),ar=u.nameInput,Ma=u.cardInputFontSize??Gs(ar?.fontSize)??$t?.fontSizeBase??"16px",Ba=typeof ar?.fontFamily=="string"?ar.fontFamily:$t?.fontFamily??"Poppins, sans-serif",Aa=si(ar?.fontWeight)??400,Yi=u.cardInputColor??(typeof ar?.color=="string"?ar.color:void 0)??$t?.colorText??"#262833",Gi=u.cardInputPlaceholderColor??"#9ca3af",gt=$t?.borderRadius??"8px",Yn=$t?.borderRadius??u.cardButton?.borderRadius??gt,Gn=$t?.colorPrimary??"#4A49FF",Ji=$t?.colorPrimaryHover??lo(Gn,.12),Bo=$t?.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=u.cardFormContainer??{},Ao=Br.padding??(xr?"0":"1rem"),Fo=Br.borderRadius??gt,Zi=lt&&It?d(No,{capture:lt,html:It.html,messageToken:It.messageToken,expectedOrigin:It.expectedOrigin,theme:b,onReady:()=>{if(!te||typeof document>"u")return;let o=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};o();let v=0,K=window.setInterval(()=>{v+=1;let oe=document.activeElement;!!oe&&oe.tagName==="IFRAME"&&oe.id==="flopay_vault_form_iframe"?(o(),window.clearInterval(K)):v>=50&&window.clearInterval(K)},100)},onError:o=>j(o),onValidation:o=>{j(o),o&&g(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=Ae("div",{style:{backgroundColor:To,borderRadius:Fo,...Br,padding:Ao,...Xi,display:"flex",flexDirection:"column"},children:[d("style",{children:`
30
+ `,mo=44;function ta(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var Zs={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Ci={width:"100%",minHeight:mo,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 el(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function mi(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Si(e){return e==="paypal"?"PayPal":hr(e)}function tl(e,t){let n=`We couldn't open ${Si(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function wi(e){let t=Be(0),n=Be(null),i=Be(null),o=we((d=i.current)=>{let b=d;b?.timer&&(clearTimeout(b.timer),b.timer=null)},[]),a=we((d,b)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(d),d.timer=setTimeout(()=>{d.timer=null,i.current?.generation===d.generation&&(i.current=null,n.current=d.generation,e(d.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},b))},[o,e]),u=we(d=>{d.yieldedControl&&a(d,600)},[a]),l=we(d=>{o();let b=t.current+1;t.current=b,n.current=null;let I={generation:b,method:d,timer:null,yieldedControl:!1};return i.current=I,b},[o]),w=we(d=>{let b=i.current;return typeof d=="number"&&b?.generation!==d?!1:(o(b),i.current=null,(typeof d!="number"||n.current===d)&&(n.current=null),!0)},[o]),B=we(d=>{let b=i.current,I=d??b?.generation??t.current;(!d||b?.generation===d)&&(o(b),i.current=null),n.current=I},[o]),h=we(d=>n.current===(d??t.current),[]),R=we(d=>i.current?.generation===d&&n.current!==d,[]),S=we(()=>{let d=i.current;d&&u(d)},[u]),_=we(()=>{let d=i.current;d&&(d.yieldedControl=!0,o(d))},[o]);return Qe(()=>{let d=()=>{document.visibilityState==="visible"?S():_()},b=()=>{_()};return document.addEventListener("visibilitychange",d),window.addEventListener("blur",b),window.addEventListener("focus",S),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("blur",b),window.removeEventListener("focus",S),o()}},[o,_,S]),{startAttempt:l,finishAttempt:w,invalidateAttempt:B,isAttemptInvalidated:h,isAttemptCurrent:R}}function nl(e){let t=Us(e);return`Enter a valid ${Jo(e)}${t?` (e.g. ${t})`:""}`}function rl(e,t,n){let i=Os(e),o=t.trim(),a=n&&i,u=a&&!o,l=a&&!!o&&!zs(e,o);return{visible:n,supported:i,required:a,empty:u,malformed:l}}function yi(e,t){return t instanceof wn?t:new wn(t instanceof Error?t.message:`${el(e)} before-click hook failed.`,"validation_error")}function Go(){return p("style",{children:Qs})}function ol(e){return typeof e=="number"?`${e}px`:e}function fi(e){if(typeof e=="number"||typeof e=="string")return e}function ki(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function Ri({state:e,placeholderTestId:t,borderRadius:n=8,children:i}){return e==="unavailable"||e==="load_error"?null:Le("div",{style:{position:"relative",minHeight:44},children:[p("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"}}),p("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 gi(e){return e!=="unavailable"&&e!=="load_error"}function na(e){return p(il,{...e})}function hi({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:o,onErrorChange:a,isProcessing:u=!1,onButtonClick:l,onDecline:w,onTechnicalFailure:B,runBeforeButtonClick:h,onLoadStateChange:R,placeholderBorderRadius:S}){let _=vn(),d=Zo(),b=Qo(),[I,x]=ve("loading");Qe(()=>{R?.(I)},[I,R]);let[P,ae]=ve(!1),U=Be(!1),le=Be(null),ee=Be(null),[F,J]=ve(0),[W,ce]=ve(!1),$=Be(!1),K=Be(new Map),{startAttempt:de,finishAttempt:_e,invalidateAttempt:Pe,isAttemptInvalidated:ye,isAttemptCurrent:te}=wi((Y,E,ie)=>{B?.(Y,E,{...ie,popupBlocked:ie?.popupBlocked??Un(E)}),ce(!0),J(Ne=>Ne+1)});Qe(()=>{W&&ee.current?.focus()},[W,F]);let ge=we(()=>{J(Y=>Y+1)},[]),xe=we((Y,E,ie)=>{Pe(ie),B?.("paypal",Y,{code:E,popupBlocked:Un(Y)}),ce(!0),ge()},[Pe,B,ge]),ne=we(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);Qe(()=>{$.current&&($.current=!1,ne())},[ne,F]);let ke=we(()=>{ce(!1),a?.(null),ne()},[ne,a]);Qe(()=>{if(!d||U.current)return;let Y=new URLSearchParams(window.location.search),E=Y.get("payment_intent"),ie=Y.get("payment_intent_client_secret"),Ne=Y.get("redirect_status");if(!E||!ie)return;U.current=!0;let Oe;try{let k=localStorage.getItem(Ur);if(k){let Q=JSON.parse(k);Q.clientSecret===ie&&(Oe={...Q.accountPatch?{accountPatch:Q.accountPatch}:{},...Q.sessionId?{sessionId:Q.sessionId}:{},...Q.nonce?{nonce:Q.nonce}:{}})}}catch{}try{localStorage.removeItem(Ur)}catch{}let ue=new URL(window.location.href);ue.searchParams.delete("payment_intent"),ue.searchParams.delete("payment_intent_client_secret"),ue.searchParams.delete("redirect_status"),window.history.replaceState({},"",ue.toString()),(async()=>{try{if(ae(!0),Ne==="failed"){let Z="PayPal payment was declined. Please try again.";a?.(Z),w?.(kt("paypal",Z));return}let{paymentIntent:k,error:Q}=await d.retrievePaymentIntent(ie);if(Q){a?.(Q.message??"Failed to retrieve PayPal payment status.");return}if(k&&(k.status==="requires_capture"||k.status==="succeeded")){let Z=typeof k.payment_method=="string"?k.payment_method:k.payment_method?.id;o({id:Z??k.id,type:"card",threeDSecureActionResultTokenId:k.id,isPaypal:!0},Oe)}else{let Z="PayPal payment was not completed. Please try again.";a?.(Z),w?.(kt("paypal",Z))}}catch(k){a?.(k instanceof Error?k.message:"Failed to complete PayPal payment.")}finally{ae(!1)}})()},[d,o,a,w]);let Re=we(async Y=>{if(u||P){Y.reject();return}let E=h?await h("paypal"):{proceed:!0};if(!E.proceed){K.current.delete(F),Y.reject();return}let ie=de("paypal");K.current.set(F,{generation:ie,accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}),ce(!1),l?.("paypal"),Y.resolve()},[K,u,l,h,de,P,F]),Ce=we(async Y=>{if(!d||!b)return;let E=K.current.get(F);if(E&&!te(E.generation)){K.current.delete(F);return}if(!E&&ye()||E&&!_e(E.generation))return;E||_e();let ie=E??null;if(K.current.delete(F),!ie&&h){let k=await h("paypal");if(!k.proceed){Y.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ie={accountPatch:k.accountPatch,sessionId:k.sessionId,nonce:k.nonce}}let Ne=ie?.sessionId??e,Oe=ie?.nonce??t,ue=ie?.accountPatch?.email??n;try{if(ae(!0),a?.(null),!Ne||!ue)throw new Error("Missing sessionId or email for PayPal payment");let k=d.createPaymentMethod,{error:Q,paymentMethod:Z}=await k({type:"paypal"});if(Q){xe(Q,"stripe_paypal_create_payment_method_failed",E?.generation),Y.paymentFailed({reason:"fail"});return}let ze=await new $n(i).createSessionIntent(Ne,Oe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Z?.id??null,intentKind:"payment"});if(ze.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ut=ze.clientSecret,qe={return_url:window.location.href};if(Z?.id&&(qe.payment_method=Z.id),typeof window<"u")try{localStorage.setItem(Ur,JSON.stringify({clientSecret:ut,sessionId:Ne,nonce:Oe,accountPatch:ie?.accountPatch}))}catch{}let{error:ot,paymentIntent:N}=await d.confirmPayment({clientSecret:ut,confirmParams:qe,redirect:"if_required"});if(ot){if(typeof window<"u")try{localStorage.removeItem(Ur)}catch{}if(Or(ot)){let Ze=ot.message??"Your payment was declined.";a?.(Ze),w?.(kt("paypal",Ze,{code:Mn(ot),declineCode:yr(ot)})),await yo({billingApiUrl:i,sessionId:Ne,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(ot)??"provider_declined"}})}else xe(ot,"stripe_paypal_confirm_failed",E?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Ur)}catch{}let V=typeof N?.payment_method=="string"?N.payment_method:N?.payment_method?.id;o({id:V??N?.id,type:"card",threeDSecureActionResultTokenId:N?.id,isPaypal:!0},{accountPatch:ie?.accountPatch,sessionId:Ne,nonce:Oe});return}catch(k){xe(k,"stripe_paypal_failed",E?.generation)}finally{ae(!1)}},[d,b,e,t,n,i,o,a,w,h,xe,_e,te,ye,F]);return Le(gr,{children:[p(Ri,{state:I,placeholderTestId:"flopay-paypal-placeholder",borderRadius:S,children:Le("div",{ref:le,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[W&&p("button",{ref:ee,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ke,style:Ci,children:"Try PayPal again"}),p(vi,{onReady:Y=>x(ki(Y,["paypal"])),onLoadError:()=>{x("load_error"),ea(At(_),"paypal","paypal")},onClick:Re,onConfirm:Ce,onCancel:()=>{let Y=K.current.get(F);K.current.delete(F),At(_)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Pe(Y?.generation),ce(!1),$.current=!0,ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},F)]})}),P&&p(Sn,{status:"processing"})]})}function Pi({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:o,expressMethods:a,onTokenizedBody:u,onErrorChange:l,onButtonClick:w,onDecline:B,onTechnicalFailure:h,runBeforeButtonClick:R,onLoadStateChange:S,placeholderBorderRadius:_}){let d=vn(),b=Zo(),I=Qo(),[x,P]=ve("loading");Qe(()=>{S?.(x)},[x,S]);let[ae,U]=ve(!1),le=Be(null),ee=Be(null),[F,J]=ve(0),[W,ce]=ve(!1),[$,K]=ve("google_pay"),de=Be(!1),_e=Be("google_pay"),Pe=Be("google_pay"),ye=Be(new Map),{startAttempt:te,finishAttempt:ge,invalidateAttempt:xe,isAttemptInvalidated:ne,isAttemptCurrent:ke}=wi((ue,k,Q)=>{h?.(ue,k,{...Q,popupBlocked:Q?.popupBlocked??Un(k)}),K(ue),ce(!0),J(Z=>Z+1)});Qe(()=>{W&&ee.current?.focus()},[W,F]);let Re=we(()=>{J(ue=>ue+1)},[]),Ce=we((ue,k,Q,Z)=>{xe(Z),h?.(ue,k,{code:Q,popupBlocked:Un(k)}),K(ue),ce(!0),Re()},[xe,h,Re]),Y=we(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);Qe(()=>{de.current&&(de.current=!1,Y())},[Y,F]);let E=we(()=>{ce(!1),l?.(null),Y()},[Y,l]),ie=we(async ue=>{if(!b||!I)return;let k=ye.current.get(F);if(k&&!ke(k.generation)){ye.current.delete(F);return}if(!k&&ne()||k&&!ge(k.generation))return;k||ge();let Q=ue.expressPaymentType??k?.method??_e.current,Z=k??null;ye.current.delete(F);let ze=mi(Q);if(!Z&&R){let V=await R(ze);if(!V.proceed){ue.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}Z={accountPatch:V.accountPatch,sessionId:V.sessionId,nonce:V.nonce}}let ut=ze,qe=Z?.sessionId??e,ot=Z?.nonce??t,N=Z?.accountPatch?.email??n;try{U(!0),l?.(null);let{error:V}=await I.submit();if(V){Ce(Q,V,"stripe_wallet_submit_failed",k?.generation);return}let{error:Ze,paymentMethod:Te}=await b.createPaymentMethod({elements:I});if(Ze||!Te){Ce(Q,Ze??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",k?.generation);return}if(!qe||!N)throw new Error("Missing sessionId or email for wallet payment");let at=await new $n(i).createSessionIntent(qe,ot??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Q??ze,paymentMethodId:Te.id,intentKind:o});if(at.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let He=at.clientSecret,{error:je,intentId:ln}=Ys(He)?await b.confirmCardSetup(He,{payment_method:Te.id}).then(f=>({error:f.error,intentId:f.setupIntent?.id})):await b.confirmCardPayment(He,{payment_method:Te.id}).then(f=>({error:f.error,intentId:f.paymentIntent?.id}));if(je){if(Or(je)){let f=je.message??"Your payment was declined.";l?.(f),B?.(kt(ut,f,{code:Mn(je),declineCode:yr(je)})),await yo({billingApiUrl:i,sessionId:qe,nonce:ot,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Q??ze,providerDeclineReason:Mn(je)??"provider_declined"}})}else Ce(Q,je,"stripe_wallet_confirm_failed",k?.generation);return}u({id:Te.id,type:"card",threeDSecureActionResultTokenId:ln},{accountPatch:Z?.accountPatch,sessionId:qe,nonce:ot})}catch(V){Ce(Q,V,"stripe_wallet_failed",k?.generation)}finally{U(!1)}},[b,I,e,t,n,i,o,u,l,B,R,Ce,ge,ke,ne,F]),Ne=nt(()=>{let ue=["applePay","googlePay","paypal","link","amazonPay","klarna"],k=new Set(["applePay","googlePay"]),Q=new Set(a.map(di)),Z={};for(let ze of ue)Q.has(ze)?Z[ze]=k.has(ze)?"always":"auto":Z[ze]="never";return Z},[a]),Oe=nt(()=>a.map(di),[a]);return Le(gr,{children:[p(Ri,{state:x,placeholderTestId:"flopay-wallet-placeholder",borderRadius:_,children:Le("div",{ref:le,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[W&&Le("button",{ref:ee,type:"button","data-testid":"flopay-wallet-retry-button",onClick:E,style:Ci,children:["Try ",Si($)," again"]}),p(vi,{onReady:ue=>{P(ki(ue,Oe))},onLoadError:ue=>{P("load_error"),ea(At(d),"stripe","wallet")},onClick:async ue=>{_e.current=ue.expressPaymentType,Pe.current=mi(ue.expressPaymentType);let k=R?await R(Pe.current):{proceed:!0};if(!k.proceed){ye.current.delete(F),ue.reject();return}let Q=te(ue.expressPaymentType);ye.current.set(F,{generation:Q,method:ue.expressPaymentType,accountPatch:k.accountPatch,sessionId:k.sessionId,nonce:k.nonce}),ce(!1),w?.(Pe.current),ue.resolve()},onConfirm:ie,onCancel:()=>{let ue=ye.current.get(F);ye.current.delete(F),At(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),xe(ue?.generation),ce(!1),de.current=!0,Re()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ne,layout:{maxColumns:1,overflow:"never"}}},F)]})}),ae&&p(Sn,{status:"processing"})]})}function al({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:u,backgroundColor:l,borderColor:w,textColor:B,borderRadius:h,fontFamily:R}){let S=js(e,t),_=Ja[e],d=S?.backgroundColor??l??"#ffffff",b=S?.borderColor??w??"#d1d5db",I=S?.textColor??B??"#262833";return p("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!i&&u()},disabled:n||i,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:mo,padding:"0 1rem",backgroundColor:d,color:I,border:`1px solid ${b}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,cursor:n||i?"not-allowed":"pointer",opacity:i&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?p("span",{style:{margin:"0 auto"},children:`Connecting to ${hr(e)}\u2026`}):Le(gr,{children:[Le("span",{style:{display:"inline-flex",alignItems:"center",gap:qs(e)?8:0},children:[_?p("img",{src:_,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"}}):S?.logoSvg?p("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:S.logoSvg}}):null,p("span",{children:hr(e)})]}),a&&p("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:I,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:p("path",{d:"M9 18l6-6-6-6"})})]})})}function Xo({method:e,sessionId:t,nonce:n,email:i,billingName:o,billingApiUrl:a,onTokenizedBody:u,onErrorChange:l,onDecline:w,onCancel:B,runBeforeButtonClick:h,onButtonClick:R,isProcessing:S,submitButtonColor:_,submitButtonBorderRadius:d,submitButtonStyle:b,errorText:I}){let x=vn(),P=Zo(),ae=Qo(),[U,le]=ve(!1),ee=Be(!1),[F,J]=ve(!1),[W,ce]=ve("loading"),$=we(async()=>{if(!P||!ae||S||ee.current||!F)return;ee.current=!0,le(!0);let K=h?await h("card"):{proceed:!0};if(!K.proceed){ee.current=!1,le(!1);return}R?.("card");let de=K.sessionId??t,_e=K.nonce??n,Pe=K.accountPatch?.email??i;try{l?.(null);let ye=await ae.submit();if(ye.error){l?.(ye.error.message??"Payment failed.");return}let te=await P.createPaymentMethod({elements:ae});if(te.error||!te.paymentMethod){l?.(te.error?.message??"Failed to create payment method.");return}let ge=te.paymentMethod;if(!de||!Pe)throw new Error("Missing sessionId or email for payment.");let xe=ge.type||e,ne=await new $n(a).createSessionIntent(de,_e??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:xe,paymentMethodId:null,intentKind:"payment"});if(ne.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ke=ne.clientSecret;if(typeof window<"u")try{localStorage.setItem(kn,JSON.stringify({clientSecret:ke,sessionId:de,nonce:_e,accountPatch:K.accountPatch,paymentMethodId:ge.id,paymentMethodType:ge.type??e,gateway:"stripe"}))}catch{}let{error:Re,paymentIntent:Ce}=await P.confirmPayment({clientSecret:ke,confirmParams:{return_url:window.location.href,payment_method:ge.id},redirect:"if_required"});if(Re){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ie=Re.message??"Payment failed.";l?.(ie),w?.(kt("card",ie,{code:Re.code})),await yo({billingApiUrl:a,sessionId:de,nonce:_e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Re.code??"provider_declined"}});return}let Y=Ce?.status;if(!ao(Y)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ie=Y==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";l?.(ie),w?.(kt("card",ie,{code:Y??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let E=typeof Ce?.payment_method=="string"?Ce.payment_method:Ce?.payment_method?.id;u({id:E??ge.id,type:"card",threeDSecureActionResultTokenId:Ce?.id,gateway:"stripe",paymentMethodType:ge.type??e},{accountPatch:K.accountPatch,sessionId:de,nonce:_e})}catch(ye){l?.(ye instanceof Error?ye.message:"Payment failed. Please try again.")}finally{ee.current=!1,le(!1)}},[P,ae,S,F,h,R,t,n,i,a,e,u,l,w]);return Le("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[p(As,{onReady:()=>ce("ready"),onLoadError:()=>{ce("load_error"),ea(At(x),"stripe","apm")},onChange:K=>{J(!!K.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...i?{email:i}:{}}}}}),p("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{$()},disabled:!F||U||S||W!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:_,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!F||U||S||W!=="ready"?"not-allowed":"pointer",opacity:!F||U||S||W!=="ready"?.5:1,transition:"opacity 120ms ease-out",...b??{}},children:U?"Processing\u2026":`Pay with ${hr(e)}`}),I&&p(ur,{margin:"0.75rem 0 0",children:I})]})}function bi({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:o,paymentElementMethods:a,stripeInstance:u,paymentElementBaseOptions:l,onTokenizedBody:w,onErrorChange:B,onButtonClick:h,onDecline:R,runBeforeButtonClick:S,onLoadStateChange:_,isProcessing:d=!1,submitButtonColor:b="#4A49FF",submitButtonBorderRadius:I=8,submitButtonStyle:x,buttonAppearance:P,themeId:ae,onExpandApm:U,expandedApmMethod:le}){let[ee,F]=ve(null),[J,W]=ve(null),ce=Be(!1);Qe(()=>{a.length>0&&u?_?.("ready"):u||_?.("loading")},[a.length,u,_]);let $=we(async te=>{if(!u||ce.current||d)return;ce.current=!0,W(te);let ge=S?await S("card"):{proceed:!0};if(!ge.proceed){ce.current=!1,W(null);return}h?.("card");let xe=ge.sessionId??e,ne=ge.nonce??t,ke=ge.accountPatch?.email??n;try{if(B?.(null),!xe||!ke)throw new Error("Missing sessionId or email for payment.");let Re=await new $n(o).createSessionIntent(xe,ne??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,paymentMethodId:null,intentKind:"payment"});if(Re.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ce=Re.clientSecret;if(typeof window<"u")try{localStorage.setItem(kn,JSON.stringify({clientSecret:Ce,sessionId:xe,nonce:ne,accountPatch:ge.accountPatch,paymentMethodType:te,gateway:"stripe"}))}catch{}let{error:Y,paymentIntent:E}=await u.confirmPayment({clientSecret:Ce,confirmParams:{return_url:window.location.href,payment_method_data:{type:te,billing_details:{name:i&&i.trim().length>=3?i.trim():"FloPay Customer",...ke?{email:ke}:{}}}},redirect:"if_required"});if(Y){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Oe=Y.message??"Payment failed.";B?.(Oe),R?.(kt("card",Oe,{code:Y.code})),await yo({billingApiUrl:o,sessionId:xe,nonce:ne,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,providerDeclineReason:Y.code??"provider_declined"}});return}let ie=E?.status;if(!ao(ie)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Oe=ie==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";B?.(Oe),R?.(kt("card",Oe,{code:ie??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Ne=typeof E?.payment_method=="string"?E.payment_method:E?.payment_method?.id;w({id:Ne??E?.id,type:"card",threeDSecureActionResultTokenId:E?.id,gateway:"stripe",paymentMethodType:te},{accountPatch:ge.accountPatch,sessionId:xe,nonce:ne})}catch(Re){B?.(Re instanceof Error?Re.message:"Payment failed. Please try again.")}finally{ce.current=!1,W(null)}},[u,d,S,h,e,t,n,o,i,w,B,R]),[K,de]=ve(null),_e=U?le??null:K,Pe=we(te=>{ce.current||d||_e&&_e!==te||(ci(te)?U?U(te):de(te):$(te))},[_e,d,$,U]),ye=nt(()=>K?{...l,paymentMethodTypes:[K]}:null,[K,l]);return p("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(te=>{let ge=le===te,xe=J===te,ne=J!==null&&J!==te||le!=null&&le!==te;return Le(Hs.Fragment,{children:[p(al,{method:te,themeId:ae,submitting:xe,disabled:ne,highlighted:ge,hasNextStep:ci(te),onClick:()=>Pe(te),backgroundColor:P?.backgroundColor,borderColor:P?.borderColor,textColor:P?.textColor,borderRadius:P?.borderRadius,fontFamily:P?.fontFamily}),!U&&K===te&&ye&&u&&p(tr,{stripe:u,options:ye,children:p(Xo,{method:te,sessionId:e,email:n,billingName:i,billingApiUrl:o,onTokenizedBody:w,onErrorChange:B,onDecline:R,onCancel:()=>de(null),runBeforeButtonClick:S,onButtonClick:h,isProcessing:d,submitButtonColor:b,submitButtonBorderRadius:I,submitButtonStyle:x})},te)]},te)})})}function il({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:o,onComplete:a,onError:u,onDecline:l,onTokenizedBody:w,firstName:B,lastName:h,chv:R,className:S,isProcessing:_,error:d,onErrorChange:b,showPayPal:I=!0,showStripe:x=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:ae,showApplePay:U=!0,showGooglePay:le=!0,layout:ee="default",theme:F,buttonsTheme:J,buttonsStyles:W,appearance:ce,cardButtonContent:$,cardBackButtonContent:K,cardTitleContent:de,showSecurityFooter:_e,onButtonClick:Pe,onBeforeButtonClick:ye,enableAVS:te,cardFieldOrder:ge,cardPreFormSlot:xe,avsLayout:ne="row",country:ke,zip:Re,addressLine1:Ce,addressLine2:Y,city:E,state:ie,onCountryChange:Ne,onZipChange:Oe,avsCheck:ue,checkoutType:k,checkoutLayout:Q,totalAmount:Z=0,currency:ze="usd",initialCardOpen:ut=!1,directPaypal:qe,isSubscription:ot=!1,session:N,dataAttachmentPending:V=!1,debug:Ze=!1}){let Te=vn(),at=Uo(),He=Ws(yn),je=V||He.claimPending===!0,ln=oo(),[f,be]=ve(!1),[pt,et]=ve(null),[Je,Ve]=ve(ke??"US"),[Xe,Ie]=ve(Re??""),[$e,It]=ve(Ce??""),[Ye,Fn]=ve(Y??""),[vt,Dn]=ve(E??""),[cn,gn]=ve(ie??""),[tn,Ln]=ve({}),Ut=Be(Re??""),Et=Be(ke??"US"),Vt=Be(Ce??""),Xt=Be(Y??""),Ft=Be(E??""),Kt=Be(ie??""),Dt=Be({});Qe(()=>{let r=(v,z,X,L,fe)=>{if(Dt.current[v])return;let Fe=z?.trim();!Fe||Fe===X.current||(X.current=Fe,L(Fe),fe?.(Fe))};r("country",ke,Et,Ve,Ne),r("zip",Re,Ut,Ie,Oe),r("addressLine1",Ce,Vt,It),r("addressLine2",Y,Xt,Fn),r("city",E,Ft,Dn),r("state",ie,Kt,gn)},[ke,Re,Ce,Y,E,ie,Ne,Oe]);let re=nt(()=>Ns(te),[te]),nn=re!==null,T=!!N?.vault?.html,gt=!!N?.gateways?.pcivault,Ct=!!(N?.gateways?.stripe?.enabledPaymentMethods??P)?.includes("card"),Ee=T||Ct||gt,Ue=!!(x&&Ee&&Te&&e),[Kn,Nn]=ve(()=>ee!=="buttons"||ut?e??null:null),[Hn,or]=ve(0),Ht=ee!=="buttons"||ut||!!e&&Kn===e,it=nt(()=>!Te||!Ue||!e||!Ht?null:Te.cardCapture({sessionId:e}),[Te,Ue,e,Ht]),Lt=nt(()=>{let r=Je,v=re?De(re.postal_code,r):!1;return rl(r,Xe,v)},[re,Je,Xe]),{avsInvalid:Wt,invalidAvsFields:ht}=nt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!Ue||!re)return{avsInvalid:!1,invalidAvsFields:r};let v=Je,z=(fe,Fe)=>De(fe,v)&&!Fe.trim(),X={line1:z(re.address_line_1,$e),city:z(re.city,vt),state:z(re.state,cn),zip:Lt.empty||Lt.malformed};return{avsInvalid:X.line1||X.city||X.state||X.zip,invalidAvsFields:X}},[Ue,re,Je,$e,vt,cn,Lt]),[Qt,Yt]=ve(!1),[dn,hn]=ve(!1),[_t,$t]=ve(()=>Yo(N?.vault)),[Ae,St]=ve(ut&&Ee?"card":"buttons"),[wt,Pn]=ve(null),Wn=Ae==="expanding"||Ae==="card",Gt=280,Zt=Be(null),Nt=we(r=>{Zt.current&&clearTimeout(Zt.current),Zt.current=setTimeout(()=>{Zt.current=null,r()},Gt)},[Gt]);Qe(()=>()=>{Zt.current&&clearTimeout(Zt.current)},[]);let En=we(()=>{Nn(e??null),or(r=>r+1),St("expanding"),Nt(()=>St("card"))},[Nt,e]),On=we(()=>{St("collapsing"),Nt(()=>St("buttons"))},[Nt]),un=we(r=>{Pn(r),St("apm-expanding"),Nt(()=>St("apm-form"))},[Nt]),en=we(()=>{St("apm-collapsing"),Nt(()=>{St("buttons"),Pn(null)})},[Nt]);Qe(()=>{ee==="buttons"&&ut&&Ee&&(Nn(e??null),St("card"))},[ee,ut,Ee,e]);let[xt,g]=ve(null),q=Be(!1),O=Be(null),pe=Be("idle"),[H,se]=ve(null),C=Be(H);Qe(()=>{C.current=H},[H]);let c=n||ln,s=d??pt,M=nt(()=>Gs(F),[F]),m=nt(()=>{let r=M?.buttonsLayout??Fs(J);return W?{...r,...W,cardButton:{...r.cardButton,...W.cardButton},cardFormContainer:{...r.cardFormContainer,...W.cardFormContainer},backButton:{...r.backButton,...W.backButton},backButtonIcon:{...r.backButtonIcon,...W.backButtonIcon},submitButton:{...r.submitButton,...W.submitButton},title:{...r.title,...W.title}}:r},[M,J,W]),G=ce??M?.appearance,Se=nt(()=>{let r=G?.variables,v=Fe=>typeof Fe=="string"&&Fe?Fe:void 0,z=m.submitButton,X=v(r?.colorPrimary)??v(z?.backgroundColor)??"#4A49FF",L=ee==="buttons",fe=m.nameInput;return{primaryColor:X,primaryHoverColor:v(r?.colorPrimaryHover)??po(X,.12),inputBackgroundColor:v(m.cardInputBackground)??v(r?.colorBackground)??"#ffffff",textColor:v(m.cardInputColor)??v(fe?.color)??v(r?.colorText)??"#262833",borderColor:v(m.cardInputBorder)??(L?"#e5e7eb":"#A4A4FF"),placeholderColor:v(m.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(fe?.fontFamily)??v(r?.fontFamily)??"Poppins, sans-serif",fontSize:v(m.cardInputFontSize)??v(r?.fontSizeBase)??"16px",fontWeight:String(fi(fe?.fontWeight)??400),borderRadius:v(r?.borderRadius)??"8px"}},[G,m,ee]),tt=He.inlineSessionPatchProcessing??!1,he=(_??f)||tt,A=c.replace(/\/+$/,""),y=nt(()=>jo({userId:o,email:i,firstName:B,lastName:h,country:ke,zip:Re},tn),[o,i,B,h,ke,Re,tn]),D=[y.firstName,y.lastName].filter(r=>!!r?.trim()).join(" "),j=nt(()=>Te?Te.getRawProvider():null,[Te]),We=nt(()=>at?at.getRawProvider():null,[at]),Tt=Z||100,Ot=nt(()=>G?Ks(G):null,[G]),Kr=Ot?{appearance:Ot}:null,ga=nt(()=>{let r=Ot??{},v=r.rules??{};return{...r,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[Ot]),ha=nt(()=>{let r=ei(Z);return{...r,currency:ze.toLowerCase(),paymentMethodCreation:"manual",...r.mode==="payment"?{captureMethod:"manual"}:{},...Kr}},[Z,ze,Kr]),Pa=nt(()=>({mode:"payment",amount:Tt,currency:ze.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Kr}),[Tt,ze,Kr]),me=we(r=>{et(r),b?.(r)},[b]);Qe(()=>{!Ue||!it||it.setCardFieldOrder?.(ge??null,re==null)},[Ue,it,ge,re]),Qe(()=>{(Ae==="expanding"||Ae==="collapsing"||Ae==="apm-expanding"||Ae==="apm-collapsing")&&me(null)},[Ae,me]);let pn=we((r,v,z)=>{l?.(kt(r,v,z))},[l]),ar=we((r,v,z)=>{let X=z?.popupBlocked??Un(v),L=tl(r,X),fe=Zn(z?.code)??Mn(v)??"external_payment_method_failed",Fe=new wn(L,"api_error",{code:"external_payment_method_failed",param:r});g(null),ee==="buttons"&&(St("buttons"),Pn(null)),me(L),u?.(Fe),console.error("[FloPay] External payment method failed:",{method:r,code:fe,popupBlocked:X})},[ee,u,me]);Qe(()=>{if(!Ue||!e){$t(null);return}let r=Yo(N?.vault);if(r){$t(r);return}if(!Ht){$t(null);return}$t(null);let v=!0;return new $n(A).getVaultCapture(e,t).then(z=>{if(!v)return;let X=Yo(z);X?$t(X):me("Failed to load the secure card form.")}).catch(z=>{v&&me(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{v=!1}},[Ue,Ht,Hn,e,N?.vault?.html,N?.vault?.messageToken,N?.vault?.expectedOrigin,A,t,me]);let _n=Be({onComplete:a,onError:u,updateError:me,emitDecline:pn,resolvedAccount:y,avsConfig:re,avsCheckProp:ue,sessionId:e,nonce:t,baseUrl:A});_n.current={onComplete:a,onError:u,updateError:me,emitDecline:pn,resolvedAccount:y,avsConfig:re,avsCheckProp:ue,sessionId:e,nonce:t,baseUrl:A};let ko=Be(!1),ji=we(()=>{let{resolvedAccount:r,avsConfig:v,avsCheckProp:z}=_n.current,X=Et.current||r.country||"US",L=v?De(v.state,X):!1,fe=v?De(v.address_line_1,X):!1,Fe=v?De(v.postal_code,X):!1,ft=v?De(v.city,X):!1,zt=v?De(v.address_line_2,X):!1,Ge=fe&&!L&&Fe?li(X,(Ut.current??"").trim()):null,Mt=L?Kt.current:Ge;return{accountData:{userId:r.userId??"",email:r.email??"",firstName:r.firstName??"",lastName:r.lastName??"",...Fe&&Ut.current?{zip:Ut.current}:{},...ft&&Ft.current?{city:Ft.current}:{},...Mt?{state:Mt}:{},...fe&&Vt.current?{addressLine1:Vt.current}:{},...zt&&Xt.current?{addressLine2:Xt.current}:{},country:X},...z!==void 0?{avsCheck:z}:{},...v?{avsConfig:{country:De(v.country,X),postal_code:Fe,address_line_1:fe,address_line_2:zt,city:ft,state:L}}:{}}},[]),ba=Be(je);ba.current=je,Qe(()=>{je||s!==pi||_n.current.updateError(null)},[je,s]),Qe(()=>{!Ue||!it||it.setSubmitGate?.(Wt||je)},[Ue,it,Wt,je]),Qe(()=>{if(!Ue||!it)return;ko.current=!1;let r=!1,v=it.on("submitting",()=>{Yt(!0),O.current&&clearTimeout(O.current),pe.current="validation-window",O.current=setTimeout(()=>{O.current=null,pe.current==="validation-window"&&(pe.current="processing")},Js),g("processing");let{baseUrl:Fe,sessionId:ft,nonce:zt,updateError:Ge,onError:Mt}=_n.current;!ft||!zt||new $n(Fe).patchAccountSnapshot(ft,zt,ji(),{telemetryMode:"best_effort"}).catch(Me=>{if(!Xs(Me))return;let qt=Me instanceof Error?Me.message:"Please check your billing address and try again.";Ge(qt),pe.current="idle",g(null),Mt?.(Me instanceof wn?Me:new wn(qt,"api_error"))})}),z=it.on("complete",async Fe=>{mr(Fe.sessionId??_n.current.sessionId),pe.current="terminal",g("success"),await new Promise(ft=>setTimeout(ft,Tn)),!ko.current&&(ko.current=!0,_n.current.onComplete?.({status:"succeeded",paymentIntentId:Fe.intentId,checkoutMethod:"card"}))}),X=it.on("decline",async Fe=>{let{updateError:ft,emitDecline:zt}=_n.current,Ge=Fe.message??"Your payment was declined. Please try another card or contact your bank.";pe.current="terminal",ft(Ge),g("error"),zt("card",Ge,Fe.declineReason?{declineCode:Fe.declineReason}:void 0),await new Promise(Mt=>setTimeout(Mt,Cn)),!r&&(pe.current="idle",g(null))}),L=it.on("error",async Fe=>{let{updateError:ft,onError:zt}=_n.current,Ge=Fe.message??"There was a problem processing your payment. Please try again.";pe.current="terminal",ft(Ge),g("error"),zt?.(new wn(Ge,"api_error")),await new Promise(Mt=>setTimeout(Mt,Cn)),!r&&(pe.current="idle",g(null))}),fe=it.on("blocked",()=>{if(!ba.current){Yt(!0);return}_n.current.updateError(pi)});return()=>{r=!0,O.current&&(clearTimeout(O.current),O.current=null),pe.current="idle",v(),z(),X(),L(),fe()}},[Ue,it]);let bn=!!qe?.clientId,kr=Array.isArray(P),Hr=kr&&P.length>0,Vi=kr&&P.includes("paypal"),{expressMethods:Wr,paymentElementMethods:Rr}=nt(()=>Vs(P,{excludePaypal:bn}),[P,bn]),va=bn||!!at,Ki=nt(()=>va?Wr.filter(r=>r!=="paypal"):Wr,[Wr,va]),Hi=nt(()=>{let r=[];return U&&r.push("apple_pay"),le&&r.push("google_pay"),r},[U,le]),Yr=kr?Ki:Hi,Wi=x&&Yr.length>0,Ro=nn?Je:ke,Gr=nt(()=>{let r=Ro?.trim().toUpperCase();return r?ae?Rr.filter(v=>{let z=ae[v];return!z||z.length===0||z.includes(r)}):$s(Rr,Ro):Rr},[Rr,Ro,ae]),Io=nt(()=>({mode:"payment",amount:Tt,currency:ze.toLowerCase(),paymentMethodCreation:"manual",appearance:ga}),[Tt,ze,ga]),[Ca,Sa]=ve("loading"),[wa,ka]=ve("loading"),[Ra,Ia]=ve("loading"),[Yi,Eo]=ve(!1),[Ea,_o]=ve("loading"),[Jr,Gi]=ve();Qe(()=>{Gi(ti())},[]);let _a=I&&(bn||(kr?Vi:Jr===!1)),xa=x&&Wi,Ir=!je&&_a&&bn,Ta=Ea==="retrying"||Ea==="exhausted",Er=!je&&_a&&!!We&&(!bn||Ta),_r=!je&&xa&&!!j,xr=!je&&x&&Hr&&Gr.length>0&&!!j,Ji=Ir&&!Ta?Yi:Er&&gi(Ca),Xi=_r&&gi(wa),Qi=xr&&Ra!=="load_error",Ma=r=>r==="loading"||r==="ready",Ba=Ir||Er&&Ma(Ca)||_r&&Ma(wa)||xr&&Ra!=="load_error",Xr=Be(!1);Qe(()=>{if(!Xr.current){if(!x&&!I){Xr.current=!0;let r=new wn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(r),me(r.message)}else if(!x&&I&&!bn&&!We){Xr.current=!0;let r=new wn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(r),me(r.message)}else if(Jr!==void 0&&!je&&!Ee&&!Ba){Xr.current=!0;let r=new wn("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});u?.(r),me(r.message)}}},[x,I,bn,We,Jr,je,Ee,Ba,u,me]);let Aa=Be(!1);Qe(()=>{if(Aa.current||!Hr)return;let r=[];U!==!0&&r.push("showApplePay"),le!==!0&&r.push("showGooglePay"),r.length!==0&&(Aa.current=!0,console.warn(`[FloPay] ${r.join(" / ")} ${r.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Hr,U,le]);let Fa=we((r,v)=>He.applyInlineSessionPatch?He.applyInlineSessionPatch(r).then(z=>({error:null,sessionId:z.sessionId||e,nonce:z.session?.clientSecret||t})).catch(z=>{let X=yi(v,z);return me(X.message),u?.(X),{error:X,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[He.applyInlineSessionPatch,t,u,e,me]),mn=we(async r=>{if(!ye)return{proceed:!0};try{let v=await ye({method:r,sessionId:e||void 0,createSession:He.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&Ln(X=>({...X??{},...v.account}));let z=await Fa(v,r);return z.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:z.sessionId,nonce:z.nonce}}return{proceed:!0}}catch(v){let z=yi(r,v);return me(z.message),u?.(z),{proceed:!1}}},[Fa,He.inlineSessionDraft,ye,u,e,me]),Da=we(async(r,v)=>{if(q.current)return;q.current=!0,be(!0),g("processing"),me(null);let z=v?.sessionId??e,X=v?.nonce??t,L=jo(y,v?.accountPatch),fe=v?.completionPaymentMethodId??io(r),Fe=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r;try{let zt=await new $n(A).processPayment(L.userId??"",{sessionId:z,nonce:X,tokenizedData:Fe,accountData:{userId:L.userId??"",email:L.email??"",firstName:L.firstName??"",lastName:L.lastName??"",...re?(()=>{let Me=Et.current,qt=De(re.state,Me),on=De(re.address_line_1,Me),Xn=De(re.postal_code,Me),Qn=on&&!qt&&Xn?li(Me,(Ut.current??"").trim()):null,Bt=qt?Kt.current:Qn;return{country:Me,...Xn&&Ut.current?{zip:Ut.current}:{},...De(re.city,Me)&&Ft.current?{city:Ft.current}:{},...Bt?{state:Bt}:{},...on&&Vt.current?{addressLine1:Vt.current}:{},...De(re.address_line_2,Me)&&Xt.current?{addressLine2:Xt.current}:{}}})():{}},chv:R,avsCheck:ue??!1,checkoutType:k,checkoutLayout:Q,avsConfig:re?{country:De(re.country,Et.current),postal_code:De(re.postal_code,Et.current),address_line_1:De(re.address_line_1,Et.current),address_line_2:De(re.address_line_2,Et.current),city:De(re.city,Et.current),state:De(re.state,Et.current)}:void 0});if(zt.ok){mr(z),g("success"),se(null),await new Promise(Me=>setTimeout(Me,Tn)),a?.({status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:fe,checkoutMethod:r.isPaypal?"paypal":"card"});return}let Ge=await zt.json().catch(()=>null);if(Ge?.type==="paypal_redirect_required"){let Me=Ge.threeDSecureToken,qt=Ge.paymentMethodId||r.id||"";if(!Te||!Me){g("error"),me("PayPal authorization required but no token provided.");return}try{let on=at?.getRawProvider();if(!on){me("PayPal is not available.");return}let Xn={return_url:window.location.href};qt&&(Xn.payment_method=qt);let{error:Qn}=await on.confirmPayment({clientSecret:Me,confirmParams:Xn,redirect:"if_required"});if(Qn){g("error");let Bt=Qn.message??"PayPal payment failed.";me(Bt),pn("paypal",Bt,{code:Qn.code})}}catch(on){g("error"),me(on instanceof Error?on.message:"PayPal authorization failed.")}return}if(Ge?.type==="paypal_direct_required"){let Me=Ge.orderId;if(!Me){g("error"),me("PayPal retry required but no order id provided.");return}let qt=C.current?.attempts??0;if(qt>=2){g("error"),me("PayPal payment could not be completed after multiple attempts."),pn("paypal","paypal_direct_required retry limit exceeded");return}Eo(!1),_o("loading"),se({orderId:Me,attempts:qt+1}),g(null);return}g("error");let Mt=Ge?.message??"Payment failed. Please try again.";me(Mt),pn(r.isPaypal?"paypal":"card",Mt,{code:Ge?.code??Ge?.gatewayErrorCode,declineCode:Ge?.declineCode??Ge?.gatewayDeclineReason}),await new Promise(Me=>setTimeout(Me,Cn))}catch(ft){g("error"),me(ft instanceof Error?ft.message:"An unexpected error occurred"),await new Promise(zt=>setTimeout(zt,Cn))}finally{be(!1),g(null),q.current=!1}},[A,e,t,y,D,R,Te,at,a,u,me,pn]),rn=we((r,v)=>{w?w(r):Da(r,v)},[w,Da]),La=Be(!1);Qe(()=>{if(typeof window>"u"||La.current)return;let r=new URLSearchParams(window.location.search),v=r.get("payment_intent"),z=r.get("payment_intent_client_secret"),X=r.get("redirect_status");if(!v||!z)return;let L=Mt=>{let Me=localStorage.getItem(Mt);if(!Me)return null;try{return JSON.parse(Me)}catch{return localStorage.removeItem(Mt),null}},fe=L(kn)??L(ui),Fe;if(fe?.clientSecret){if(fe.clientSecret!==z)return;Fe={...fe.accountPatch?{accountPatch:fe.accountPatch}:{},...fe.sessionId?{sessionId:fe.sessionId}:{},...fe.nonce?{nonce:fe.nonce}:{}}}else if(fe?.sessionId&&fe.sessionId!==e)return;La.current=!0,localStorage.removeItem(kn),localStorage.removeItem(ui);let ft=new URL(window.location.href);ft.searchParams.delete("payment_intent"),ft.searchParams.delete("payment_intent_client_secret"),ft.searchParams.delete("redirect_status"),window.history.replaceState({},"",ft.toString());let zt=fe?.paymentMethodType??fe?.tokenType??"card",Ge="card";(async()=>{let Mt=Te?.getRawProvider();if(!Mt){let Bt="Payment is not available \u2014 please refresh and try again.";me(Bt),pn(Ge,Bt);return}if(X==="failed"){let Bt="Payment was declined. Please try again.";me(Bt),pn(Ge,Bt);return}let{paymentIntent:Me,error:qt}=await Mt.retrievePaymentIntent(z);if(qt){let Bt=qt.message??"Failed to retrieve payment status.";me(Bt),pn(Ge,Bt,{code:qt.code});return}let on=Me?.status,Xn=ao(on);if(!Me||!Xn){let Bt=on==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";me(Bt),pn(Ge,Bt,{code:on??"missing_payment_intent"});return}let Qn=typeof Me.payment_method=="string"?Me.payment_method:Me.payment_method?.id;rn({id:Qn??fe?.paymentMethodId??fe?.tokenId??Me.id,type:"card",threeDSecureActionResultTokenId:Me.id,gateway:fe?.gateway??"stripe",paymentMethodType:zt},Fe)})()},[e,rn,Te,me,pn]);let xo=we(r=>{r.preventDefault()},[]);if(!(Te!==null))return p("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Tr=ee==="buttons",Jt=G?.variables,Zi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),To=Jt?.colorBackground,es=To&&!Zi.has(To)?To:void 0,Mr=m.cardInputBorder??(Tr?"#e5e7eb":"#A4A4FF"),Mo=Jt?.colorDanger??"#dc2626",Yn=r=>Qt&&r?Mo:Mr,Qr=(Lt.malformed||Lt.empty)&&(dn||Qt),ts=Qr?Mo:Yn(ht.zip),Bo=m.cardFormContainer?.backgroundColor??es??(Tr?"white":"#EDEDFF"),Br=m.cardInputBackground??Jt?.colorBackground??"white",Ao=sr(K),Na=sr(de),ir=m.nameInput,Oa=m.cardInputFontSize??ol(ir?.fontSize)??Jt?.fontSizeBase??"16px",za=typeof ir?.fontFamily=="string"?ir.fontFamily:Jt?.fontFamily??"Poppins, sans-serif",Ua=fi(ir?.fontWeight)??400,ns=m.cardInputColor??(typeof ir?.color=="string"?ir.color:void 0)??Jt?.colorText??"#262833",rs=m.cardInputPlaceholderColor??"#9ca3af",yt=Jt?.borderRadius??"8px",Gn=Jt?.borderRadius??m.cardButton?.borderRadius??yt,Jn=Jt?.colorPrimary??"#4A49FF",os=Jt?.colorPrimaryHover??po(Jn,.12),Fo=Jt?.colorText??"#262833",$a={fontSize:Oa,fontFamily:za,fontWeight:Ua,color:ns,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},as={"--flopay-input-placeholder-color":rs,"--flopay-input-font-size":Oa,"--flopay-input-font-family":za,"--flopay-input-font-weight":String(Ua)},Ar=m.cardFormContainer??{},Do=Ar.padding??(Tr?"0":"1rem"),Lo=Ar.borderRadius??yt,is=it&&_t?p(zo,{capture:it,html:_t.html,messageToken:_t.messageToken,expectedOrigin:_t.expectedOrigin,theme:Se,onReady:()=>{if(!re||typeof document>"u")return;let r=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};r();let v=0,z=window.setInterval(()=>{v+=1;let X=document.activeElement;!!X&&X.tagName==="IFRAME"&&X.id==="flopay_vault_form_iframe"?(r(),window.clearInterval(z)):v>=50&&window.clearInterval(z)},100)},onError:r=>me(r),onValidation:r=>{let v=pe.current;(v==="idle"||v==="validation-window")&&(me(r),r&&pe.current==="validation-window"&&(O.current&&(clearTimeout(O.current),O.current=null),pe.current="idle",g(null)))}}):p("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"}),qa=Le("div",{style:{backgroundColor:Bo,borderRadius:Lo,...Ar,padding:Do,...as,display:"flex",flexDirection:"column"},children:[p("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${je.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),xr&&Kn&&Ae("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Se?-2:0},children:[Ae("button",{type:"button",onClick:Vn,style:{display:"inline-flex",alignItems:"center",gap:Mo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:u.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...u.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...u.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(lr,{content:V})]}),Ta?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:u.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...u.title},children:d(Fr,{content:de})})]}),!xr&&!Ta&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Bo,order:Se?-3:0,...u.title},children:d(Fr,{content:de})}),te&&d("div",{style:{order:Se?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let o=We,v=(z=!1)=>({backgroundColor:Mr,border:`1px solid ${Wn(z)}`,borderRadius:gt,marginTop:"0.5rem",padding:"10px"}),K=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Fa}),oe=Es(o);return Ae(fr,{children:[Be(te.address_line_1,o)&&d("div",{style:v(vt.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:Ze,onChange:z=>{Yt.current=z.target.value,xe(z.target.value)},disabled:T,required:!0,"data-testid":"flopay-address-line1",style:K()})}),Be(te.address_line_2,o)&&d("div",{style:v(),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:Ge,onChange:z=>{Lt.current=z.target.value,At(z.target.value)},disabled:T,"data-testid":"flopay-address-line2",style:K()})}),(Be(te.city,o)||Be(te.state,o))&&Ae("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Be(te.city,o)&&d("div",{style:{flex:1,backgroundColor:Mr,borderTop:`1px solid ${Wn(vt.city)}`,borderRight:`1px solid ${Wn(vt.city)}`,borderBottom:`1px solid ${Wn(vt.city)}`,borderLeft:`1px solid ${Wn(vt.city)}`,padding:"10px",borderTopLeftRadius:gt,borderBottomLeftRadius:gt,...Be(te.state,o)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:gt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Ke,onChange:z=>{Gt.current=z.target.value,$n(z.target.value)},disabled:T,required:!0,"data-testid":"flopay-city",style:K()})}),Be(te.state,o)&&d("div",{style:{flex:1,backgroundColor:Mr,border:`1px solid ${Wn(vt.state)}`,padding:"10px",borderTopRightRadius:gt,borderBottomRightRadius:gt,...Be(te.city,o)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:gt}},children:oe?Ae("select",{id:"flopay-billing-state",name:"billing-state",value:Pt,onChange:z=>{pn.current=z.target.value,Sn(z.target.value)},disabled:T,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...K(),cursor:"pointer"},children:[d("option",{value:"",children:ei(o)}),oe.map(z=>d("option",{value:z.code,children:z.name},z.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:ei(o),autoComplete:"billing address-level1",value:Pt,onChange:z=>{pn.current=z.target.value,Sn(z.target.value)},disabled:T,required:!0,"data-testid":"flopay-state",style:K()})})]}),(Be(te.country,o)||Be(te.postal_code,o))&&Ae("div",{style:{display:"flex",flexDirection:Q==="column"?"column":"row",gap:Q==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Be(te.country,o)&&d("div",{style:{flex:Q==="row"?1:void 0,backgroundColor:Mr,borderTop:`1px solid ${Tr}`,borderRight:`1px solid ${Tr}`,borderBottom:`1px solid ${Tr}`,borderLeft:`1px solid ${Tr}`,padding:"10px",...Q==="row"&&Be(te.postal_code,o)?{borderRadius:"0",borderTopLeftRadius:gt,borderBottomLeftRadius:gt,borderRight:"none"}:{borderRadius:gt}},children:d("select",{id:"flopay-billing-country",name:"billing-country",value:We,onChange:z=>{Ft.current=z.target.value,tt(z.target.value),Ne?.(z.target.value),pn.current="",Sn("")},disabled:T,autoComplete:"billing country","data-testid":"flopay-country",style:{...K(),cursor:"pointer"},children:_s.map(z=>Ae("option",{value:z.code,children:[z.flag," ",z.name]},z.code))})}),Be(te.postal_code,o)&&d("div",{style:{flex:Q==="row"?1:void 0,backgroundColor:Mr,border:`1px solid ${Wi}`,padding:"10px",...Q==="row"&&Be(te.country,o)?{borderRadius:"0",borderTopRightRadius:gt,borderBottomRightRadius:gt}:{borderRadius:gt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Yo(We),autoComplete:"billing postal-code",value:ht,onChange:z=>{Rt.current=z.target.value,Ye(z.target.value),Oe?.(z.target.value)},onBlur:()=>on(!0),disabled:T,required:Dt.required,"aria-invalid":Gr||void 0,"aria-describedby":Gr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:K()})})]}),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:Dt.empty?`${Yo(o)} is required`:Ws(o)})]})})()}),Se&&_e&&d("div",{style:{order:-2,width:"100%"},children:_e}),Se&&Zi,P&&d(dr,{margin:"0.75rem 0",styleOverride:u.errorBanner,children:P})]}),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=>L?!I||!yn?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=${I}`,` directPaypalConfigured=${yn}`,` inAppBrowserDetected=${String(Wr)}`,` shouldRenderDirectPayPal=${Rr}`,` shouldRenderStripePayPal=${Ir}`,` hasPaypalStripeInstance=${!!Qe}`].join(`
39
- `)}):null,Na=o=>L?!x||!he?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=${x}`,` currency=${Fe}`,` amountInCents=${De}`,` 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=${!!he}`,` shouldRenderWallets=${Er}`,` shouldRenderPaymentElement=${_r}`].join(`
40
- `)}):null,Oa=Re==="apm-expanding"||Re==="apm-form"||Re==="apm-collapsing",Xr=Re==="apm-expanding"?`flopay-card-enter ${Ht}ms cubic-bezier(0, 0, 0.2, 1) both`:Re==="apm-collapsing"?`flopay-card-exit ${Ht}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Zr=rt?{...ko,paymentMethodTypes:[rt]}:null;if(X==="buttons"){let o=Re==="buttons"||Re==="expanding"||Re==="apm-expanding",v=Re==="expanding"||Re==="card"||Re==="collapsing",K=$===void 0?{boxSizing:"border-box",height:co,padding:"0 1rem"}:{padding:"0.9rem 1rem"},oe=Re==="expanding"||Re==="apm-expanding"?`flopay-buttons-exit ${Ht}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Re==="collapsing"||Re==="apm-collapsing"?`flopay-buttons-enter ${Ht}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,z=Re==="expanding"?`flopay-card-enter ${Ht}ms cubic-bezier(0, 0, 0.2, 1) both`:Re==="collapsing"?`flopay-card-exit ${Ht}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Ae("form",{onSubmit:Eo,className:C,style:{position:"relative"},children:[d(Wo,{}),bt&&d(hn,{status:bt,errorMessage:P}),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?Ks:{},...oe?{animation:oe,pointerEvents:"none"}:{}},children:[La("flopay-direct-paypal-gate-debug"),Na("flopay-stripe-gate-debug"),Rr&&je&&Ae(fr,{children:[W&&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:D,email:O.email,clientId:je.clientId,environment:je.environment,currency:Fe.toUpperCase(),isSubscription:it,onTokenizedBody:Xt,onComplete:a,onErrorChange:j,onDecline:s,onTechnicalFailure:or,onButtonClick:Pe,runBeforeButtonClick:cn,isProcessing:T,onLoadStateChange:Ro,onInitializationStateChange:Io,session:F??null,existingOrderId:W?.orderId,debug:L},W?.orderId??"fresh")]}),Ir&&d(er,{stripe:Qe,options:sn,children:d(ci,{sessionId:e,nonce:t,email:O.email,billingApiUrl:D,onTokenizedBody:Xt,onErrorChange:j,isProcessing:T,onButtonClick:Pe,onDecline:s,onTechnicalFailure:or,runBeforeButtonClick:cn,onLoadStateChange:fa,placeholderBorderRadius:Yn})}),Er?d(er,{stripe:he,options:an,children:d(di,{sessionId:e,nonce:t,email:O.email,billingApiUrl:D,intentKind:J>0?"payment":"setup",expressMethods:Vr,onTokenizedBody:Xt,onErrorChange:j,onButtonClick:Pe,onDecline:s,onTechnicalFailure:or,runBeforeButtonClick:cn,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:O.email,billingName:[O.firstName,O.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:D,paymentElementMethods:Hr,stripeInstance:he,paymentElementBaseOptions:ko,onTokenizedBody:Xt,onErrorChange:j,onButtonClick:Pe,onDecline:s,runBeforeButtonClick:cn,onLoadStateChange:ba,isProcessing:T,submitButtonColor:Gn,submitButtonBorderRadius:gt,submitButtonStyle:u.submitButton,onExpandApm:Ut,expandedApmMethod:rt,themeId:B,buttonAppearance:{backgroundColor:u.cardButton?.backgroundColor,borderColor:u.cardInputBorder,textColor:u.cardButton?.color,borderRadius:Yn}}),Se&&d("button",{type:"button",onClick:async()=>{T||!(await cn("card")).proceed||(Pe?.("card"),En())},disabled:T,style:{width:"100%",...K,...u.cardButton,...Qo({themeBundle:A,resolvedPrimaryColor:Gn,resolvedBorderRadius:gt,submitButtonStyle:u.submitButton,explicitPrimaryColor:$t?.colorPrimary}),fontSize:u.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:T?"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:T?.6:1},onMouseEnter:ne=>{!T&&(A||$t?.colorPrimary)&&(ne.currentTarget.style.backgroundColor=Ji)},onMouseLeave:ne=>{(A||$t?.colorPrimary)&&(ne.currentTarget.style.backgroundColor=Gn)},onMouseDown:ne=>{ne.currentTarget.style.transform="scale(0.985)"},onMouseUp:ne=>{ne.currentTarget.style.transform="scale(1)"},children:d(sr,{content:$})}),P&&Re==="buttons"&&d(dr,{margin:"0.25rem 0",styleOverride:u.errorBanner,children:P})]}),Se&&v&&d("div",{style:{gridArea:"1 / 1",...z?{animation:z}:{},...Re==="collapsing"?{pointerEvents:"none"}:{}},children:Da}),x&&Oa&&rt&&Zr&&he&&d("div",{style:{gridArea:"1 / 1",...Xr?{animation:Xr}:{},...Re==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ae("div",{style:{backgroundColor:To,borderRadius:Fo,...Br,padding:Ao},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:_n,style:{display:"inline-flex",alignItems:"center",gap:Mo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:u.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...u.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...u.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(lr,{content:V})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:u.titleFontSize??"1.05rem",color:Bo,paddingRight:80,...u.title},children:`Pay with ${gr(rt)}`})]}),d(er,{stripe:he,options:Zr,children:d(Go,{method:rt,sessionId:e,nonce:t,email:O.email,billingName:[O.firstName,O.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:D,onTokenizedBody:Xt,onErrorChange:j,onDecline:s,onCancel:_n,runBeforeButtonClick:cn,onButtonClick:Pe,isProcessing:T,submitButtonColor:Gn,submitButtonBorderRadius:gt,submitButtonStyle:u.submitButton,errorText:P})},rt)]})})]})]})}return Oa&&rt&&Zr&&he&&x?Ae("form",{onSubmit:Eo,className:C,style:{position:"relative"},children:[d(Wo,{}),bt&&d(hn,{status:bt,errorMessage:P}),d("div",{style:{...Xr?{animation:Xr}:{},...Re==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ae("div",{style:{backgroundColor:To,borderRadius:Fo,...Br,padding:Ao},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:_n,style:{display:"inline-flex",alignItems:"center",gap:Mo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:u.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...u.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...u.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(lr,{content:V})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:u.titleFontSize??"1.05rem",color:Bo,paddingRight:80,...u.title},children:`Pay with ${gr(rt)}`})]}),d(er,{stripe:he,options:Zr,children:d(Go,{method:rt,sessionId:e,nonce:t,email:O.email,billingName:[O.firstName,O.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:D,onTokenizedBody:Xt,onErrorChange:j,onDecline:s,onCancel:_n,runBeforeButtonClick:cn,onButtonClick:Pe,isProcessing:T,submitButtonColor:Gn,submitButtonBorderRadius:gt,submitButtonStyle:u.submitButton,errorText:P})},rt)]})})]}):Ae("form",{onSubmit:Eo,className:C,style:{position:"relative"},children:[d(Wo,{}),bt&&d(hn,{status:bt,errorMessage:P}),Ae("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[La("flopay-direct-paypal-gate-debug-default"),Na("flopay-stripe-gate-debug-default"),Rr&&je&&Ae(fr,{children:[W&&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:D,email:O.email,clientId:je.clientId,environment:je.environment,currency:Fe.toUpperCase(),isSubscription:it,onTokenizedBody:Xt,onComplete:a,onErrorChange:j,onDecline:s,onTechnicalFailure:or,onButtonClick:Pe,runBeforeButtonClick:cn,isProcessing:T,onLoadStateChange:Ro,onInitializationStateChange:Io,session:F??null,existingOrderId:W?.orderId,debug:L},W?.orderId??"fresh")]}),Ir&&d(er,{stripe:Qe,options:sn,children:d(ci,{sessionId:e,nonce:t,email:O.email,billingApiUrl:D,onTokenizedBody:Xt,onErrorChange:j,isProcessing:T,onButtonClick:Pe,onDecline:s,onTechnicalFailure:or,runBeforeButtonClick:cn,onLoadStateChange:fa,placeholderBorderRadius:Yn})}),Er&&d(er,{stripe:he,options:an,children:d(di,{sessionId:e,nonce:t,email:O.email,billingApiUrl:D,intentKind:J>0?"payment":"setup",expressMethods:Vr,onTokenizedBody:Xt,onErrorChange:j,onButtonClick:Pe,onDecline:s,onTechnicalFailure:or,runBeforeButtonClick:cn,onLoadStateChange:ha,placeholderBorderRadius:Yn})}),_r&&d(ui,{sessionId:e,nonce:t,email:O.email,billingName:[O.firstName,O.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:D,paymentElementMethods:Hr,stripeInstance:he,paymentElementBaseOptions:ko,onTokenizedBody:Xt,onErrorChange:j,onButtonClick:Pe,onDecline:s,runBeforeButtonClick:cn,onLoadStateChange:ba,isProcessing:T,submitButtonColor:Gn,submitButtonBorderRadius:gt,submitButtonStyle:u.submitButton,themeId:B,onExpandApm:Ut,expandedApmMethod:rt,buttonAppearance:{backgroundColor:u.cardButton?.backgroundColor,borderColor:u.cardInputBorder,textColor:u.cardButton?.color,borderRadius:Yn}})]}),Se&&(ji||qi||Ki)&&Ae("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"}})]}),Se&&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 vn(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 y=new AbortController,R=()=>y.abort();e.signal?.aborted?y.abort():e.signal?.addEventListener("abort",R);let C=window.setTimeout(()=>y.abort(),i);try{let _=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:y.signal});if(!_.ok)return{status:"unknown"};let l=await _.json().catch(()=>null);return nl(l)}catch{return{status:"unknown"}}finally{window.clearTimeout(C),e.signal?.removeEventListener("abort",R)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let S=document.createElement("iframe");S.setAttribute("title","Card authentication"),S.setAttribute("allow","payment"),S.tabIndex=0,S.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),S.src=e.nextActionRedirectUrl,s.appendChild(S),document.body.appendChild(s),S.focus();let M=null;try{M=new URL(e.billingApiUrl,window.location.href).origin}catch{M=null}try{let y=await new Promise((R,C)=>{let _=!1,l=0,h=0,I=0,x=!1,f=()=>{window.clearTimeout(l),window.clearInterval(h),window.clearTimeout(I),window.removeEventListener("message",X),S.removeEventListener("load",U),e.signal?.removeEventListener("abort",ie)},ae=async()=>{if(!(_||x)){x=!0;try{let B=await a();if(_||!tl(B))return;_=!0,f(),R(B)}finally{x=!1}}},U=()=>{window.clearTimeout(I),I=window.setTimeout(()=>{ae()},250)},ie=()=>{_||(_=!0,f(),C(new at("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},X=B=>{if(B.source!==S.contentWindow||M&&B.origin!==M)return;let G=B.data;!G||typeof G!="object"||G.source!=="flopay-vault-3ds-return"||_||(_=!0,f(),R(null))};l=window.setTimeout(()=>{_||(_=!0,f(),C(new at("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),h=window.setInterval(()=>{ae()},n),S.addEventListener("load",U),window.addEventListener("message",X),e.signal?.addEventListener("abort",ie),e.signal?.aborted&&ie()});return y||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 On(e,t="Payment failed. Please try again.",n){let i=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),r=e?.message??t,a=Dn(r)??r;return vn(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 S=s,M=[S.stripeClientSecret,S.clientSecret];for(let y of M)if(typeof y=="string"&&y.length>0&&(!t?.requirePaymentIntentClientSecret||po(y)))return y}}}}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(/\/+$/,""),S=t??n.id,M=i??n.clientSecret,y=n.customer?.id??n.accountData?.userId??"",R=n.customer?.email??n.accountData?.email??"",C=n.customer?.firstName??n.accountData?.firstName??"",_=n.customer?.lastName??n.accountData?.lastName??"",l=n.customer?.country??n.accountData?.country??void 0,h=n.customer?.zip??n.accountData?.zip??void 0,I=new bi(s,c===!1?{telemetry:!1}:void 0),x=await rl(()=>I.processPayment(y,{sessionId:S,nonce:M,tokenizedData:r,accountData:{userId:y,email:R,firstName:C,lastName:_,country:l,zip:h},returnUrl:a??ta(n)}));if(x.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:ro(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=Si(f);if(!ae)throw new at("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 ol({billingApiUrl:s,sessionId:S,nonce:M,responseJson:f});if(ae)return ae;throw vn(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:S}){let M=t?.getRawProvider();if(!M)throw new at("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!i||!e.threeDSecureToken)throw vn(new at("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let y=Zs(e.threeDSecureToken),R=null,C=e.paymentMethodId,_=await Qs(M,e.threeDSecureToken,y);if(_){if(_.error)throw vn(new at(_.error.message??`Failed to retrieve 3DS ${y?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let h=_.intent;!C&&h?.payment_method&&(typeof h.payment_method=="string"?C=h.payment_method:"id"in h.payment_method&&(C=h.payment_method.id??void 0))}let l=C?await el(M,e.threeDSecureToken,{payment_method:C,return_url:s??ta(c)??window.location.href},y):null;if(l){if(l.error)throw vn(new at(l.error.message??"3DS authentication failed.","api_error",{code:l.error.code}),"card");R=l.intent}else{let h=await M.handleNextAction({clientSecret:e.threeDSecureToken});if(h.error)throw vn(new at(h.error.message??"3DS authentication failed.","api_error",{code:h.error.code}),"card");R=(y?h.setupIntent:h.paymentIntent)??null}if(R&&(R.status==="requires_capture"||R.status==="succeeded"||R.status==="processing")){let h=await hr({billingApiUrl:r,sessionId:a,session:c,telemetry:S,tokenizedData:{id:R.id,type:"card",threeDSecureActionResultTokenId:R.id},returnUrl:s});return h.type==="success"?{...h.result,paymentIntentId:h.result.paymentIntentId??R.id,paymentMethodId:h.result.paymentMethodId??C}:mo(h,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:c,returnUrl:s,telemetry:S})}throw vn(new at("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let y=(n??t)?.getRawProvider();if(!y)throw vn(new at("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:C}=await y.handleNextAction({clientSecret:e.threeDSecureToken});if(C)throw vn(new at(C.message??"PayPal authorization failed.","api_error",{code:C.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:R}=await y.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??ta(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(R)throw vn(new at(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new at("Unsupported payment redirect state.","api_error")}function tr(e){if(e instanceof at){let i=Dn(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=Dn(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(S=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",S),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?a?s:c:null}}import{Fragment as Cn,jsx as re,jsxs as kt}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 An(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ul(){if(!An())return null;try{let e=window.sessionStorage.getItem(la);return e?JSON.parse(e):null}catch{return null}}function Ii(e){if(An())try{window.sessionStorage.setItem(la,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function aa(){if(An())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(!An())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(An())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(An())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function yl(e){if(An())try{return window.sessionStorage.getItem(e+ca)??void 0}catch{return}}function fl(e,t){if(An())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),!!An())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:S,onComplete:M,onError:y,onDecline:R,onCountryChange:C,onZipChange:_,showPayPal:l=!0,showStripe:h=!0,enabledPaymentMethods:I,showApplePay:x=!0,showGooglePay:f=!0,debug:ae=!1,layout:U,theme:ie,buttonsTheme:X,buttonsStyles:B,cardButtonContent:G,cardBackButtonContent:H,cardTitleContent:se,showSecurityFooter:$,onButtonClick:V,onBeforeButtonClick:de,enableAVS:Ee,cardFieldOrder:Pe,cardPreFormSlot:ye,avsLayout:Z,className:fe,initialErrorMessage:_e=null,children:Q,checkoutMode:ke,confirmLabel:Me,renderConfirmButton:we,onSessionCompleted:Y}){let E=sl(i),le=un(()=>xi(ie),[ie]),Ne=a??le?.appearance,Oe=n?"embedded_checkout":"standard_checkout",ue=Q?"custom_layout":U==="buttons"?"buttons_layout":"default_layout",[k,ee]=wt(null),[J,Fe]=wt(null),yt=qt(null),[je,it]=wt(null),F=qt(null),[L,Ue]=wt(null),[qe,st]=wt(e??""),ft=e??qe,Bt=n?"":ft,[Wt,m]=wt(!0),[ve,We]=wt(null),[tt,ht]=wt("full"),[Ye,Ze]=wt(!1),[xe,Ge]=wt(_e),[At,Ke]=wt(null),[$n,Pt]=wt(null),[Sn,wn]=wt(void 0),[qn,Rt]=wt(""),[Ft,Yt]=wt(!1),[Lt,Gt]=wt("loading"),[pn,te]=wt(0),jt=qt(!1),kn=qt(!1),Rn=qt(!1),Jt=qt(null),w=un(()=>({checkoutMode:ke??tt,layout:Q?"unknown":U==="buttons"?"buttons":"embedded"}),[ke,Q,tt,U]),Je=qt(M);Je.current=M;let Se=qt(y);Se.current=y;let Fn=qt(R);Fn.current=R,Bn(()=>{Tt(J)?.setCheckoutContext(w),je&&je!==J&&Tt(je)?.setCheckoutContext(w)},[J,je,w]);let $e=qt(Y);$e.current=Y;let jn=nr(g=>{Gt(g),!(g!=="exhausted"||Rn.current)&&(Rn.current=!0,Se.current?.(new Mt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),rr=nr(()=>{Gt("retrying"),te(g=>g+1)},[]);Bn(()=>{Gt("loading"),te(0),Rn.current=!1},[ft]),Bn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:_i,checkout_type:Oe,checkout_layout:ue,billing_api_url:E})},[ue,Oe,E]);let Kt=un(()=>n?on(n,!0):"",[n]),lt=un(()=>qn===Kt?Sn:void 0,[Sn,qn,Kt]),Dt=un(()=>n?Uo(n,lt):void 0,[n,lt]),Vt=ke??Dt?.checkoutMode??"full",vt=un(()=>Dt?{...Dt,checkoutMode:Vt}:void 0,[Dt,Vt]);Bn(()=>{wn(void 0),Rt(Kt)},[Kt]),Bn(()=>{Ge(_e)},[_e]);let nn=nr((g,N,W)=>{ut(()=>{Fn.current?.(St(g,N,W))})},[ut]),rn=nr(async(g,N)=>{Ge(null),Pt(null),Ke("processing");let W=N?.sessionId??g.id,Te=yt.current??F.current,ge=Tt(Te),D=Te?null:Po(E,r,w),P={log:q=>{ge?ge.log(q):D?.log(q)},error:q=>{ge?ge.error(q):D?.error(q)},terminal:q=>{ge?ge.terminal(q):D?.terminal(q)},performance:q=>{ge?ge.performance(q):D?.performance(q)},now:()=>ge?.now()??D?.now()??0,elapsed:q=>ge?.elapsed(q)??Math.max(0,(D?.now()??q)-q)},A=P.now(),u=!!(N?.initialAutoProcessingError||N?.initialAutoProcessingPending),me=!1,b,p=()=>{me||(me=!0,u=!0,b=P.now(),P.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},T=!1,Ie=()=>{T||(T=!0,P.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),P.performance({stage:"processing",durationMs:P.elapsed(A),durationMode:"machine",paymentMethodCategory:"saved"}),b!==void 0&&P.performance({stage:"recovery",durationMs:P.elapsed(b),durationMode:"machine",paymentMethodCategory:"saved"}))};P.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),P.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),u&&p();let O;try{let q=vi(N?.initialAutoProcessingError),he;if(q)p(),q.type==="paypal_redirect_required"&&Jt.current?.publishableKey&&Ii({sessionId:W,publishableKey:Jt.current.publishableKey,paypalPublishableKey:Jt.current.paypalPublishableKey}),he=await mo(q,{flopay:yt.current,paypalFlopay:F.current,attempt3DS:N?.attempt3DS,billingApiUrl:E,sessionId:W,session:g,telemetry:!1}),q.type==="paypal_redirect_required"&&aa();else if(N?.initialAutoProcessingPending){let De=await new go(E,{telemetry:!1}).waitForCheckoutSessionCompletion(N.initialAutoProcessingPending.sessionId,{initialDelayMs:N.initialAutoProcessingPending.retryAfterMs});if(De.data.session?.status!=="complete")throw new Mt("Automatic payment failed. Please try again.","api_error",{code:De.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});he={status:"succeeded"}}else{if(N?.initialAutoProcessingError)throw On(N.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:N.initialAutoProcessingError.checkoutMethod});if(N?.fromCreateSession)return N?.fallbackToFull&&(ht("full"),Ei("full")),!1;{let Qe=await hr({billingApiUrl:E,sessionId:W,session:g,telemetry:!1});Qe.type==="success"?he=Qe.result:(p(),Qe.type==="paypal_redirect_required"&&Jt.current?.publishableKey&&Ii({sessionId:W,publishableKey:Jt.current.publishableKey,paypalPublishableKey:Jt.current.paypalPublishableKey}),he=await mo(Qe,{flopay:yt.current,paypalFlopay:F.current,attempt3DS:N?.attempt3DS,billingApiUrl:E,sessionId:W,session:g,telemetry:!1}),Qe.type==="paypal_redirect_required"&&aa())}}W&&pr(W),Ie(),u&&(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"}),Ke("success"),await $r(Tn),O=()=>Je.current?.(he)}catch(q){let he=tr(q),Qe=he.checkoutMethod??Ur;return Ge(he.message),Pt(he.message),N?.fallbackToFull&&(P.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),ht("full"),Ei("full")),Ie(),!!(he.declineCode||he.code?.toLowerCase().includes("declin"))?P.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):he.type==="validation_error"?P.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):P.error({errorCode:u?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:u?"recovery":"processing",paymentMethodCategory:"saved"}),ut(()=>Se.current?.(he)),nn(Qe,he,{code:he.code,declineCode:he.declineCode}),Ke("error"),await Promise.allSettled([$r(gn),N?.ensureProvidersReady?N.ensureProvidersReady():Promise.resolve()]),u&&(P.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ie(),D&&bo(D),Ke(null),Pt(null)}return ut(O),!0},[nn,ut,tr,E,r,w]);Bn(()=>{if(typeof window>"u"||kn.current)return;let g=new URLSearchParams(window.location.search),N=g.get("payment_intent_client_secret");if(!N)return;let W=ul();W&&(kn.current=!0,(async()=>{let Te,ge=0;Ge(null),Pt(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:D,paypalFlopay:P}=await fo({publishableKey:W.publishableKey,paypalPublishableKey:W.paypalPublishableKey,billingApiUrl:E,locale:c,telemetry:r});Te=Tt(P??D),ge=Te?.now()??0,Te?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Te?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let A=(P??D)?.getRawProvider();if(!A)throw Object.assign(new Mt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:u,error:me}=await A.retrievePaymentIntent(N);if(me)throw Object.assign(new Mt(me.message??"Failed to retrieve PayPal payment status.","api_error",{code:me.code}),{checkoutMethod:"paypal"});let b=Ha(u?.status);if(!u||b==="failed")throw Object.assign(new Mt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let p=typeof u.payment_method=="string"?u.payment_method:u.payment_method?.id,T=b;if(W.sessionId){let q=(await new go(E,{telemetry:!1}).getUnifiedCheckoutSession(W.sessionId)).data.session;if(q&&q.status!=="complete"){let he=await hr({billingApiUrl:E,sessionId:W.sessionId,session:q,telemetry:!1,tokenizedData:{id:p??u.id,type:"card",threeDSecureActionResultTokenId:u.id,isPaypal:!0}});if(he.type!=="success")throw Object.assign(new Mt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});T=he.result.status}}W.sessionId&&pr(W.sessionId),Te?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Te?.performance({stage:"redirect_resume",durationMs:Te.elapsed(ge),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Te?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ke("success"),await $r(Tn),ut(()=>Je.current?.({status:T,paymentIntentId:u.id,paymentMethodId:p,checkoutMethod:"paypal"}))}catch(D){let P=tr(D),A=P.checkoutMethod??"paypal",u=!!(P.declineCode||P.code?.toLowerCase().includes("declin"));if(Te)Te.performance({stage:"redirect_resume",durationMs:Te.elapsed(ge),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),u?Te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Te.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(u){let me=Po(E,r,w);me.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),bo(me)}else ra(E,r,w,"REDIRECT_RESUME_FAILED","redirect_resume");Ge(P.message),Pt(P.message),ut(()=>Se.current?.(P)),nn(A,P,{code:P.code,declineCode:P.declineCode}),Ke("error"),await $r(gn)}finally{aa(),hl(),Ke(null),Pt(null),Ze(!1)}})())},[nn,ut,c,tr,E,r]);let mn=qt(null);function on(g,N=!1){let W=g?.account?.email?.trim().toLowerCase()??"",Te={c:g?.clientId,cur:g?.currency??"",a:{e:W,u:W?"":g?.account?.userId??"",country:g?.account?.country??""},successUrl:g?.successUrl,cancelUrl:g?.cancelUrl,p:g?.products?.map(P=>ia(`${P.type??""}:${P.code??P.providerItemId??P.providerPlanId??""}`,P)).sort(),i:g?.items?.map(P=>ia(P.code??P.providerItemId??"",P)).sort(),s:g?.subscriptions?.map(P=>ia(P.code??P.providerPlanId??"",P)).sort(),couponCodes:g?.couponCodes?[...g.couponCodes].sort():void 0,...N?{tagsData:g?.tagsData,utmMetadata:g?.utmMetadata,tokenizedData:g?.tokenizedData,checkoutMode:g?.checkoutMode??"full"}:{}},ge=JSON.stringify(Te),D=0;for(let P=0;P<ge.length;P++)D=(D<<5)-D+ge.charCodeAt(P)|0;return`flopay_session_${Math.abs(D).toString(36)}`}let It=un(()=>vt?on(vt):"",[vt]),Nt=qt(vt);Nt.current=vt,Bn(()=>{st(e??"")},[e]),Bn(()=>{jt.current=!1,Ge(_e),Pt(null),Ke(null)},[It,_e,e]);async function Re(g,N){let W=Po(E,r,w),Te=new go(E,{telemetry:!1});try{let ge=g.idempotencyKey!==void 0?ki(g.idempotencyKey):void 0,D=ge??yl(N),P,A=!1,u=pl(N);W.log({name:u?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let me=u?.sid??null,b=null;if(me)try{if(b=await Te.getUnifiedCheckoutSession(me,u?.nonce),b.data.session?.status==="complete"){if(qo(me))return{sid:me,result:b};gl(N),me=null,b=null,A=!0}}catch{W.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ti(N),me=null}if(!me){!ge&&(A||!D)&&(D=ki(),P=D),D&&fl(N,D);let p=W.now(),T=0;W.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ie={...g,idempotencyKey:D,avsCheck:!!Ee,avsConfig:typeof Ee=="object"?Ee:void 0,checkoutType:"embedded_checkout",checkoutLayout:Q?"custom_layout":U==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(Ie,al,{configurable:!1,enumerable:!1,value:{onAttempt:O=>{T=Math.max(T,O)}}});try{b=await Te.createAndFetchSession(Ie),W.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),W.performance({stage:"session_create",durationMs:W.now()-p,durationMode:"machine",requestCategory:"session_create",attempt:T,statusClass:"2xx"})}catch(O){let q=il(O,"CHECKOUT_SESSION_CREATE_FAILED","unknown");throw W.performance({stage:"session_create",durationMs:W.now()-p,durationMode:"machine",requestCategory:"session_create",attempt:T,statusClass:q.statusClass}),O instanceof Mt&&O.type==="validation_error"?W.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):q.statusClass==="4xx"?W.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):W.error({...q,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),O}me=b.data.session?.id??"",me&&ml(N,me,b.data.session?.clientSecret)}return{sid:me??"",result:b,sdkGeneratedIdempotencyKey:P}}finally{bo(W)}}let nt=nr(async(g,N)=>{let W=Nt.current;if(!W)throw new Mt("createSession is required to bootstrap checkout.","validation_error");let Te=Uo(W,g),ge=on(Te),D=vo.get(ge);if(!D){let u={promise:Re(Te,ge),consumers:0,settled:!1};D=u,vo.set(ge,u);let me=()=>{u.settled=!0,Ri(ge,u)};u.promise.then(me,me)}D.consumers+=1;let P=!1,A=()=>{P||(P=!0,D.consumers-=1,Ri(ge,D))};N?.(A);try{let u=await D.promise;mn.current=ge,g&&(Rt(Kt),wn(q=>Ka(q,g)));let{sid:me,result:b}=u;ee(b),b.data.session&&Ue(b.data.session),me&&st(me);let{publishableKey:p,paypalPublishableKey:T}=yo(b),{flopay:Ie,paypalFlopay:O}=await fo({publishableKey:p,paypalPublishableKey:T,billingApiUrl:E,locale:c,telemetry:r});return yt.current=Ie,Fe(Ie),F.current=O,it(O),m(!1),u}catch(u){throw mn.current===ge&&(mn.current=null),u}finally{N||A()}},[c,E,r,w]),rt=qt(rn);rt.current=rn;let In=qt(nt);In.current=nt;let Kn=nr(async g=>{if(!Pl(g)||Ft)return{sessionId:qe,session:L};Yt(!0);try{let N=await nt(g);return{sessionId:N.sid,session:N.result.data.session??null}}finally{Yt(!1)}},[nt,Ft,qe,L]);Bn(()=>{let g=!1,N;if(We(null),It){let ge=Nt.current;return ht(Vt),m(!1),mn.current===It?()=>{g=!0}:(Ue(Va(ge,ke)),(async()=>{let D=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),P=Vt==="auto"&&!jt.current&&!D;P&&(Ge(null),Pt(null),Ke("processing"));try{let A=await In.current(void 0,p=>{N=p}),u=A.result.data.session??null;Jt.current=yo(A.result);let me=oa(A.result),b=qo(A.sid||u?.id);if(!g&&P&&u&&!me&&!b){jt.current=!0,await cl(It,A.sdkGeneratedIdempotencyKey,()=>rt.current(u,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:A.result.autoProcessingError,initialAutoProcessingPending:A.result.autoProcessingPending,autoProcessingAttempted:A.result.autoProcessingAttempted,sessionId:A.sid||u.id}));return}!g&&P&&((me||b)&&(jt.current=!0),Ke(null),Pt(null))}catch(A){if(g)return;let u=A instanceof Mt||typeof A=="object"&&A!==null&&"code"in A?A.code:void 0;if(P&&u==="session_auto_completed"){jt.current=!0,Ke("success"),await $r(Tn),g||(ut(()=>{Je.current?.({status:"succeeded"})}),Ke(null),Pt(null));return}P&&(Ke(null),Pt(null));let me=A instanceof Mt?A:new Mt(A instanceof Error?A.message:"Failed to create session","api_error");We(me)}finally{N?.(),N=void 0}})(),()=>{g=!0,N?.()})}m(!0);async function W(){let ge=!1;try{let P=await new go(E,{telemetry:!1}).getUnifiedCheckoutSession(ft,t);if(g)return;ee(P);let A=P.data.session??null;if(Ue(A),!A)throw new Mt("No session data returned","api_error");if(A.status==="complete"){m(!1),ut(()=>{$e.current?.(A.successUrl??"")});return}if(A.status==="expired")throw new Mt("Checkout session has expired.","api_error",{code:"checkout_session_expired"});ge=!0;let u=ke??A.checkoutMode??"full";ht(u);let me=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),b=oa(P);if(u==="auto"&&!jt.current&&!me&&!b){jt.current=!0;let p=Te(P);try{if(await rt.current(A,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>p,sessionId:ft||A.id}),g)return;await p,g||m(!1);return}catch{if(g)return;await p,g||m(!1);return}}await Te(P),g||m(!1)}catch(D){if(g)return;D instanceof Mt?!ge&&!dl(D)&&ra(E,r,w,"NETWORK_REQUEST_FAILED","session_read"):ra(E,r,w,"INTERNAL_SDK_ERROR","checkout_mount");let P=D instanceof Mt?D:new Mt(D instanceof Error?D.message:"Failed to initialize checkout","api_error");We(P),m(!1)}}async function Te(ge){let{publishableKey:D,paypalPublishableKey:P}=yo(ge);Jt.current={publishableKey:D,paypalPublishableKey:P};let{flopay:A,paypalFlopay:u}=await fo({publishableKey:D,paypalPublishableKey:P,billingApiUrl:E,locale:c,telemetry:r});yt.current=A,Fe(A),F.current=u,it(u)}return W(),()=>{g=!0}},[ke,It,Vt,Bt,ut,t]);let Ht=nr(async()=>{if(!(Ye||!L)){Ze(!0),Ge(null);try{await rn(L,{attempt3DS:!0,fallbackToFull:!0,sessionId:ft||L.id})}finally{Ze(!1)}}},[ft,Ye,rn,L]),Ot=sa(k),zt=oa(k),En=un(()=>{if(!k||!L||!k.data.stripe?.publishableKey)return;let g={appearance:Ne,paymentMethodCreation:"manual",billingApiUrl:E};if(k.data.stripe?.clientSecret)g.clientSecret=k.data.stripe.clientSecret;else{let N=wi(L).total;g.amount=Math.round(N*100)||L.amount,g.currency=L.currency?.toLowerCase()}return g},[k,L,Ne,E]),Vn=!!(n&&!Q&&U==="buttons"&&de&&Vt==="full"),Ut=un(()=>({session:L,loading:Wt,error:ve,checkoutMode:tt,inlineSessionDraft:vt,applyInlineSessionPatch:Vn?Kn:void 0,inlineSessionPatchProcessing:Ft}),[L,Wt,ve,tt,vt,Vn,Kn,Ft]),_n=!!n&&U==="buttons"&&!zt&&(!J||!En),bt=At?re(hn,{status:At,errorMessage:$n}):null;if(Wt){if(s)return kt(Cn,{children:[s,bt]});if(U==="buttons"){let g=le?.buttonsLayout?.cardButton?.borderRadius??le?.appearance.variables?.borderRadius??8,N=W=>re("div",{style:{height:W,borderRadius:g,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return kt(Cn,{children:[kt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[l&&N(Pr),h&&(x||f)&&N(Pr),h&&N(Pr),re("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),bt]})}return kt(Cn,{children:[kt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[re("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),re("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),bt]})}return ve?S?re(dn.Provider,{value:Ut,children:S(ve)}):re(dn.Provider,{value:Ut,children:re("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:ve.message})}):_n?kt(Cn,{children:[re(dn.Provider,{value:Ut,children:re(vl,{onButtonClick:V,showPayPal:l,showStripe:h,showApplePay:x,showGooglePay:f,theme:ie,buttonsTheme:X,buttonsStyles:B,cardButtonContent:G,cardBackButtonContent:H,cardTitleContent:se})}),bt]}):zt&&L&&Ot?kt(Cn,{children:[re(dn.Provider,{value:Ut,children:kt("div",{className:fe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[xe&&re(dr,{icon:!1,children:xe}),Lt==="retrying"&&re("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Lt==="exhausted"&&kt("div",{role:"alert",children:[re("div",{children:"PayPal is temporarily unavailable. Please try again."}),re("button",{type:"button",onClick:rr,children:"Retry PayPal"})]}),Lt!=="exhausted"&&re("div",{"aria-hidden":Lt==="retrying"?!0:void 0,style:Lt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:re(Qa,{sessionId:ft,nonce:L.clientSecret||void 0,billingApiUrl:E,email:L.customer?.email,clientId:Ot.clientId,environment:Ot.environment,currency:(L.currency??"usd").toUpperCase(),isSubscription:L.mode==="subscription",onComplete:M,onErrorChange:Ge,onDecline:R,onButtonClick:V,onInitializationStateChange:jn,allowAutomaticRetry:pn===0,session:L,telemetry:r,telemetryContext:w,debug:ae},`paypal-init-${pn}`)})]})}),bt]}):!J||!En?re(Cn,{children:bt}):tt==="confirm"?kt(Cn,{children:[re(dn.Provider,{value:Ut,children:re(eo,{flopay:J,paypalFlopay:je,options:En,children:kt("div",{className:fe,children:[xe&&re("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:xe}),we?we({onConfirm:Ht,isProcessing:Ye}):re("button",{type:"button",onClick:Ht,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"})]})})}),bt]}):kt(Cn,{children:[re(dn.Provider,{value:Ut,children:re(eo,{flopay:J,paypalFlopay:je,options:En,children:Q?kt(Cn,{children:[xe&&re("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:xe}),re(bl,{sessionId:ft,nonce:L?.clientSecret||void 0,billingApiUrl:E,session:L,children:Q})]}):re(ea,{sessionId:ft,nonce:L?.clientSecret||void 0,email:L?.customer?.email,userId:L?.customer?.id,firstName:L?.customer?.firstName,lastName:L?.customer?.lastName,totalAmount:L?Math.round(wi(L).total*100):0,currency:L?.currency?.toLowerCase()??"usd",onComplete:M,onError:y,onDecline:R,error:xe,onErrorChange:Ge,showPayPal:l,showStripe:h,enabledPaymentMethods:I??k?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:k?.data.stripe?.enabledPaymentMethodCountries,showApplePay:x,showGooglePay:f,layout:U,theme:ie,buttonsTheme:X,buttonsStyles:B,appearance:Ne,cardButtonContent:G,cardBackButtonContent:H,cardTitleContent:se,onButtonClick:V,onBeforeButtonClick:de,enableAVS:Ee,...Pe?{cardFieldOrder:Pe}:{},...ye?{cardPreFormSlot:ye}:{},avsLayout:Z,country:L?.customer?.country,city:L?.customer?.city,state:L?.customer?.state,onCountryChange:C,onZipChange:_,avsCheck:!!Ee,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Q?"custom_layout":U==="buttons"?"buttons_layout":"default_layout",className:fe,directPaypal:sa(k),isSubscription:L?.mode==="subscription",session:L,debug:ae})})}),bt]})}function bl({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:r}){return re(Cn,{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:S,cardBackButtonContent:M,cardTitleContent:y}){let[R,C]=wt(!1),_=un(()=>xi(a),[a]),l=un(()=>{let f=_?.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},[_,c,s]),h=_?.buttonsLayout?.cardButton?.borderRadius??_?.appearance.variables?.borderRadius??8,I=f=>re("div",{style:{height:f,borderRadius:h,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),x=S===void 0?{boxSizing:"border-box",height:Pr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(R){let f=l.cardInputBorder??"#e5e7eb",ae=l.cardInputBackground??"white",U=ir(M),ie=ir(y);return kt("div",{style:{backgroundColor:l.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...l.cardFormContainer},children:[kt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[kt("button",{type:"button",onClick:()=>C(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:U?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:[re("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...l.backButtonIcon},children:re("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:re("path",{d:"M15 18l-6-6 6-6"})})}),re(lr,{content:M})]}),ie?re("div",{style:{flex:1}}):re("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...l.title},children:re(Fr,{content:y})})]}),re("div",{style:{backgroundColor:ae,border:`1px solid ${f}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:re("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:[re("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:re("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("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:re("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),re("div",{style:{backgroundColor:ae,border:`1px solid ${f}`,borderRadius:8,marginTop:8,padding:12,height:45},children:re("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...l.submitButton,opacity:.5}}),re("style",{children:`
38
+ `}),Tr&&Wn&&Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ue?-2:0},children:[Le("button",{type:"button",onClick:On,style:{display:"inline-flex",alignItems:"center",gap:Ao?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.backButton},"aria-label":"Back to payment methods",children:[p("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...m.backButtonIcon},children:p("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:p("path",{d:"M15 18l-6-6 6-6"})})}),p(cr,{content:K})]}),Na?p("div",{style:{flex:1}}):p("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:m.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...m.title},children:p(Dr,{content:de})})]}),!Tr&&!Na&&p("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Fo,order:Ue?-3:0,...m.title},children:p(Dr,{content:de})}),re&&p("div",{style:{order:Ue?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=Je,v=(L=!1)=>({backgroundColor:Br,border:`1px solid ${Yn(L)}`,borderRadius:yt,marginTop:"0.5rem",padding:"10px"}),z=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...$a}),X=Ds(r);return Le(gr,{children:[De(re.address_line_1,r)&&p("div",{style:v(ht.line1),children:p("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:$e,onChange:L=>{Dt.current.addressLine1=!0,Vt.current=L.target.value,It(L.target.value)},disabled:he,required:!0,"data-testid":"flopay-address-line1",style:z()})}),De(re.address_line_2,r)&&p("div",{style:v(),children:p("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Ye,onChange:L=>{Dt.current.addressLine2=!0,Xt.current=L.target.value,Fn(L.target.value)},disabled:he,"data-testid":"flopay-address-line2",style:z()})}),(De(re.city,r)||De(re.state,r))&&Le("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[De(re.city,r)&&p("div",{style:{flex:1,backgroundColor:Br,borderTop:`1px solid ${Yn(ht.city)}`,borderRight:`1px solid ${Yn(ht.city)}`,borderBottom:`1px solid ${Yn(ht.city)}`,borderLeft:`1px solid ${Yn(ht.city)}`,padding:"10px",borderTopLeftRadius:yt,borderBottomLeftRadius:yt,...De(re.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:yt}},children:p("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:vt,onChange:L=>{Dt.current.city=!0,Ft.current=L.target.value,Dn(L.target.value)},disabled:he,required:!0,"data-testid":"flopay-city",style:z()})}),De(re.state,r)&&p("div",{style:{flex:1,backgroundColor:Br,border:`1px solid ${Yn(ht.state)}`,padding:"10px",borderTopRightRadius:yt,borderBottomRightRadius:yt,...De(re.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:yt}},children:X?Le("select",{id:"flopay-billing-state",name:"billing-state",value:cn,onChange:L=>{Dt.current.state=!0,Kt.current=L.target.value,gn(L.target.value)},disabled:he,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...z(),cursor:"pointer"},children:[p("option",{value:"",children:si(r)}),X.map(L=>p("option",{value:L.code,children:L.name},L.code))]}):p("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:si(r),autoComplete:"billing address-level1",value:cn,onChange:L=>{Dt.current.state=!0,Kt.current=L.target.value,gn(L.target.value)},disabled:he,required:!0,"data-testid":"flopay-state",style:z()})})]}),(De(re.country,r)||De(re.postal_code,r))&&Le("div",{style:{display:"flex",flexDirection:ne==="column"?"column":"row",gap:ne==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[De(re.country,r)&&p("div",{style:{flex:ne==="row"?1:void 0,backgroundColor:Br,borderTop:`1px solid ${Mr}`,borderRight:`1px solid ${Mr}`,borderBottom:`1px solid ${Mr}`,borderLeft:`1px solid ${Mr}`,padding:"10px",...ne==="row"&&De(re.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:yt,borderBottomLeftRadius:yt,borderRight:"none"}:{borderRadius:yt}},children:p("select",{id:"flopay-billing-country",name:"billing-country",value:Je,onChange:L=>{Dt.current.country=!0,Et.current=L.target.value,Ve(L.target.value),Ne?.(L.target.value),Kt.current="",gn("")},disabled:he,autoComplete:"billing country","data-testid":"flopay-country",style:{...z(),cursor:"pointer"},children:Ls.map(L=>Le("option",{value:L.code,children:[L.flag," ",L.name]},L.code))})}),De(re.postal_code,r)&&p("div",{style:{flex:ne==="row"?1:void 0,backgroundColor:Br,border:`1px solid ${ts}`,padding:"10px",...ne==="row"&&De(re.country,r)?{borderRadius:"0",borderTopRightRadius:yt,borderBottomRightRadius:yt}:{borderRadius:yt}},children:p("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Jo(Je),autoComplete:"billing postal-code",value:Xe,onChange:L=>{Dt.current.zip=!0,Ut.current=L.target.value,Ie(L.target.value),Oe?.(L.target.value)},onBlur:()=>hn(!0),disabled:he,required:Lt.required,"aria-invalid":Qr||void 0,"aria-describedby":Qr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:z()})})]}),Qr&&p("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Mo,...$a,fontSize:"0.75rem"},children:Lt.empty?`${Jo(r)} is required`:nl(r)})]})})()}),Ue&&xe&&p("div",{style:{order:-2,width:"100%"},children:xe}),Ue&&is,s&&p(ur,{margin:"0.75rem 0",styleOverride:m.errorBanner,children:s})]}),Zr={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"},ja=r=>Ze?!I||!bn?p("pre",{"data-testid":r,style:Zr,children:"FloPay/DirectPayPal-debug - not enabled"}):p("pre",{"data-testid":r,style:Zr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${I}`,` directPaypalConfigured=${bn}`,` inAppBrowserDetected=${String(Jr)}`,` shouldRenderDirectPayPal=${Ir}`,` shouldRenderStripePayPal=${Er}`,` hasPaypalStripeInstance=${!!We}`].join(`
39
+ `)}):null,Va=r=>Ze?!x||!j?p("pre",{"data-testid":r,style:Zr,children:"FloPay/Stripe-debug - not enabled"}):p("pre",{"data-testid":r,style:Zr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${x}`,` currency=${ze}`,` amountInCents=${Tt}`,` enabledPaymentMethods: ${JSON.stringify(P??[])}`,` enabledPaymentMethodsProvided=${kr}`,` hasEnabledMethods=${Hr}`,` expressMethods: ${JSON.stringify(Wr)}`,` walletExpressMethods: ${JSON.stringify(Yr)}`,` paymentElementMethods: ${JSON.stringify(Rr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Gr)}`,` hasStripeInstance=${!!j}`,` shouldRenderWallets=${_r}`,` shouldRenderPaymentElement=${xr}`].join(`
40
+ `)}):null,Ka=Ae==="apm-expanding"||Ae==="apm-form"||Ae==="apm-collapsing",eo=Ae==="apm-expanding"?`flopay-card-enter ${Gt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ae==="apm-collapsing"?`flopay-card-exit ${Gt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,to=wt?{...Io,paymentMethodTypes:[wt]}:null;if(ee==="buttons"){let r=Ae==="buttons"||Ae==="expanding"||Ae==="apm-expanding",v=Ae==="expanding"||Ae==="card"||Ae==="collapsing",z=$===void 0?{boxSizing:"border-box",height:mo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},X=Ae==="expanding"||Ae==="apm-expanding"?`flopay-buttons-exit ${Gt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ae==="collapsing"||Ae==="apm-collapsing"?`flopay-buttons-enter ${Gt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,L=Ae==="expanding"?`flopay-card-enter ${Gt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ae==="collapsing"?`flopay-card-exit ${Gt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Le("form",{onSubmit:xo,className:S,style:{position:"relative"},children:[p(Go,{}),xt&&p(Sn,{status:xt,errorMessage:s}),Le("div",{style:{display:"grid"},children:[Le("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!X?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!X?Zs:{},...X?{animation:X,pointerEvents:"none"}:{}},children:[ja("flopay-direct-paypal-gate-debug"),Va("flopay-stripe-gate-debug"),Ir&&qe&&Le(gr,{children:[H&&p("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."}),p(uo,{sessionId:e,nonce:t,billingApiUrl:c,email:y.email,clientId:qe.clientId,environment:qe.environment,currency:ze.toUpperCase(),isSubscription:ot,onTokenizedBody:rn,onComplete:a,onErrorChange:me,onDecline:l,onTechnicalFailure:ar,onButtonClick:Pe,runBeforeButtonClick:mn,isProcessing:he,onLoadStateChange:Eo,onInitializationStateChange:_o,session:N??null,existingOrderId:H?.orderId,debug:Ze},H?.orderId??"fresh")]}),Er&&p(tr,{stripe:We,options:Pa,children:p(hi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:c,onTokenizedBody:rn,onErrorChange:me,isProcessing:he,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:mn,onLoadStateChange:Sa,placeholderBorderRadius:Gn})}),_r?p(tr,{stripe:j,options:ha,children:p(Pi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:c,intentKind:Z>0?"payment":"setup",expressMethods:Yr,onTokenizedBody:rn,onErrorChange:me,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:mn,onLoadStateChange:ka,placeholderBorderRadius:Gn})}):xa?p("div",{style:{height:mo,borderRadius:Gn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,xr&&p(bi,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:c,paymentElementMethods:Gr,stripeInstance:j,paymentElementBaseOptions:Io,onTokenizedBody:rn,onErrorChange:me,onButtonClick:Pe,onDecline:l,runBeforeButtonClick:mn,onLoadStateChange:Ia,isProcessing:he,submitButtonColor:Jn,submitButtonBorderRadius:yt,submitButtonStyle:m.submitButton,onExpandApm:un,expandedApmMethod:wt,themeId:F,buttonAppearance:{backgroundColor:m.cardButton?.backgroundColor,borderColor:m.cardInputBorder,textColor:m.cardButton?.color,borderRadius:Gn}}),Ue&&p("button",{type:"button",onClick:async()=>{he||!(await mn("card")).proceed||(Pe?.("card"),En())},disabled:he,style:{width:"100%",...z,...m.cardButton,...ta({themeBundle:M,resolvedPrimaryColor:Jn,resolvedBorderRadius:yt,submitButtonStyle:m.submitButton,explicitPrimaryColor:Jt?.colorPrimary}),fontSize:m.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:he?"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:he?.6:1},onMouseEnter:fe=>{!he&&(M||Jt?.colorPrimary)&&(fe.currentTarget.style.backgroundColor=os)},onMouseLeave:fe=>{(M||Jt?.colorPrimary)&&(fe.currentTarget.style.backgroundColor=Jn)},onMouseDown:fe=>{fe.currentTarget.style.transform="scale(0.985)"},onMouseUp:fe=>{fe.currentTarget.style.transform="scale(1)"},children:p(lr,{content:$})}),s&&Ae==="buttons"&&p(ur,{margin:"0.25rem 0",styleOverride:m.errorBanner,children:s})]}),Ue&&v&&p("div",{style:{gridArea:"1 / 1",...L?{animation:L}:{},...Ae==="collapsing"?{pointerEvents:"none"}:{}},children:qa}),x&&Ka&&wt&&to&&j&&p("div",{style:{gridArea:"1 / 1",...eo?{animation:eo}:{},...Ae==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Bo,borderRadius:Lo,...Ar,padding:Do},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:en,style:{display:"inline-flex",alignItems:"center",gap:Ao?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.backButton},"aria-label":"Back to payment methods",children:[p("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...m.backButtonIcon},children:p("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:p("path",{d:"M15 18l-6-6 6-6"})})}),p(cr,{content:K})]}),p("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:m.titleFontSize??"1.05rem",color:Fo,paddingRight:80,...m.title},children:`Pay with ${hr(wt)}`})]}),p(tr,{stripe:j,options:to,children:p(Xo,{method:wt,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:c,onTokenizedBody:rn,onErrorChange:me,onDecline:l,onCancel:en,runBeforeButtonClick:mn,onButtonClick:Pe,isProcessing:he,submitButtonColor:Jn,submitButtonBorderRadius:yt,submitButtonStyle:m.submitButton,errorText:s})},wt)]})})]})]})}return Ka&&wt&&to&&j&&x?Le("form",{onSubmit:xo,className:S,style:{position:"relative"},children:[p(Go,{}),xt&&p(Sn,{status:xt,errorMessage:s}),p("div",{style:{...eo?{animation:eo}:{},...Ae==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Bo,borderRadius:Lo,...Ar,padding:Do},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:en,style:{display:"inline-flex",alignItems:"center",gap:Ao?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.backButton},"aria-label":"Back to payment methods",children:[p("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...m.backButtonIcon},children:p("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:p("path",{d:"M15 18l-6-6 6-6"})})}),p(cr,{content:K})]}),p("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:m.titleFontSize??"1.05rem",color:Fo,paddingRight:80,...m.title},children:`Pay with ${hr(wt)}`})]}),p(tr,{stripe:j,options:to,children:p(Xo,{method:wt,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:c,onTokenizedBody:rn,onErrorChange:me,onDecline:l,onCancel:en,runBeforeButtonClick:mn,onButtonClick:Pe,isProcessing:he,submitButtonColor:Jn,submitButtonBorderRadius:yt,submitButtonStyle:m.submitButton,errorText:s})},wt)]})})]}):Le("form",{onSubmit:xo,className:S,style:{position:"relative"},children:[p(Go,{}),xt&&p(Sn,{status:xt,errorMessage:s}),Le("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ja("flopay-direct-paypal-gate-debug-default"),Va("flopay-stripe-gate-debug-default"),Ir&&qe&&Le(gr,{children:[H&&p("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."}),p(uo,{sessionId:e,nonce:t,billingApiUrl:c,email:y.email,clientId:qe.clientId,environment:qe.environment,currency:ze.toUpperCase(),isSubscription:ot,onTokenizedBody:rn,onComplete:a,onErrorChange:me,onDecline:l,onTechnicalFailure:ar,onButtonClick:Pe,runBeforeButtonClick:mn,isProcessing:he,onLoadStateChange:Eo,onInitializationStateChange:_o,session:N??null,existingOrderId:H?.orderId,debug:Ze},H?.orderId??"fresh")]}),Er&&p(tr,{stripe:We,options:Pa,children:p(hi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:c,onTokenizedBody:rn,onErrorChange:me,isProcessing:he,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:mn,onLoadStateChange:Sa,placeholderBorderRadius:Gn})}),_r&&p(tr,{stripe:j,options:ha,children:p(Pi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:c,intentKind:Z>0?"payment":"setup",expressMethods:Yr,onTokenizedBody:rn,onErrorChange:me,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:mn,onLoadStateChange:ka,placeholderBorderRadius:Gn})}),xr&&p(bi,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:c,paymentElementMethods:Gr,stripeInstance:j,paymentElementBaseOptions:Io,onTokenizedBody:rn,onErrorChange:me,onButtonClick:Pe,onDecline:l,runBeforeButtonClick:mn,onLoadStateChange:Ia,isProcessing:he,submitButtonColor:Jn,submitButtonBorderRadius:yt,submitButtonStyle:m.submitButton,themeId:F,onExpandApm:un,expandedApmMethod:wt,buttonAppearance:{backgroundColor:m.cardButton?.backgroundColor,borderColor:m.cardInputBorder,textColor:m.cardButton?.color,borderRadius:Gn}})]}),Ue&&(Xi||Ji||Qi)&&Le("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[p("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),p("span",{children:"or pay with card"}),p("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ue&&qa]})}import{loadFloPay as Ii,PaymentAPI as Ei}from"@flopay/js";import{FloPayError as rt,isSetupIntentClientSecret as sl}from"@flopay/shared";var $r="card";async function ll(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:u}=await e.retrieveSetupIntent(t);return{error:u,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:i,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:i??null}}async function cl(e,t,n,i){if(i){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:u,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:u??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Rn(e,t){return Object.assign(e,{checkoutMethod:t})}function _i(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 dl(e){return e.status==="succeeded"||e.status==="declined"}async function xi(e){if(typeof document>"u"||typeof window>"u")throw new rt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,i=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let h=new AbortController,R=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",R);let S=window.setTimeout(()=>h.abort(),i);try{let _=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!_.ok)return{status:"unknown"};let d=await _.json().catch(()=>null);return ul(d)}catch{return{status:"unknown"}}finally{window.clearTimeout(S),e.signal?.removeEventListener("abort",R)}},u=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 w=document.createElement("iframe");w.setAttribute("title","Card authentication"),w.setAttribute("allow","payment"),w.tabIndex=0,w.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),w.src=e.nextActionRedirectUrl,l.appendChild(w),document.body.appendChild(l),w.focus();let B=null;try{B=new URL(e.billingApiUrl,window.location.href).origin}catch{B=null}try{let h=await new Promise((R,S)=>{let _=!1,d=0,b=0,I=0,x=!1,P=()=>{window.clearTimeout(d),window.clearInterval(b),window.clearTimeout(I),window.removeEventListener("message",ee),w.removeEventListener("load",U),e.signal?.removeEventListener("abort",le)},ae=async()=>{if(!(_||x)){x=!0;try{let F=await a();if(_||!dl(F))return;_=!0,P(),R(F)}finally{x=!1}}},U=()=>{window.clearTimeout(I),I=window.setTimeout(()=>{ae()},250)},le=()=>{_||(_=!0,P(),S(new rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ee=F=>{if(F.source!==w.contentWindow||B&&F.origin!==B)return;let J=F.data;!J||typeof J!="object"||J.source!=="flopay-vault-3ds-return"||_||(_=!0,P(),R(null))};d=window.setTimeout(()=>{_||(_=!0,P(),S(new rt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),b=window.setInterval(()=>{ae()},n),w.addEventListener("load",U),window.addEventListener("message",ee),e.signal?.addEventListener("abort",le),e.signal?.aborted&&le()});return h||await a()}finally{l.parentNode?.removeChild(l),u?.isConnected&&u.focus()}}function ul(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function qn(e,t="Payment failed. Please try again.",n){let i=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=zn(o)??o;return Rn(new rt(a,"api_error",{code:e?.gatewayErrorCode}),i)}function ra(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function fo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function pl(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 Ti(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||fo(o)))return o;let i=e?.data;if(i&&typeof i=="object"){let o=i,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let l of a)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||fo(l)))return l;let u=o.gateways;if(u&&typeof u=="object"){let l=u.stripe;if(l&&typeof l=="object"){let w=l,B=[w.stripeClientSecret,w.clientSecret];for(let h of B)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||fo(h)))return h}}}}async function ml({billingApiUrl:e,sessionId:t,nonce:n,responseJson:i}){let o=Ti(i,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let l=(await new Ei(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(fo(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Pr({billingApiUrl:e,sessionId:t,session:n,nonce:i,tokenizedData:o,returnUrl:a,telemetry:u}){let l=e.replace(/\/+$/,""),w=t??n.id,B=i??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",R=n.customer?.email??n.accountData?.email??"",S=n.customer?.firstName??n.accountData?.firstName??"",_=n.customer?.lastName??n.accountData?.lastName??"",d=n.customer?.country??n.accountData?.country??void 0,b=n.customer?.zip??n.accountData?.zip??void 0,I=new Ei(l,u===!1?{telemetry:!1}:void 0),x=await pl(()=>I.processPayment(h,{sessionId:w,nonce:B,tokenizedData:o,accountData:{userId:h,email:R,firstName:S,lastName:_,country:d,zip:b},returnUrl:a??ra(n)}));if(x.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:io(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let P=await x.json().catch(()=>null);if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let ae=Ti(P);if(!ae)throw new rt("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:P.type,threeDSecureToken:ae,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let ae=await ml({billingApiUrl:l,sessionId:w,nonce:B,responseJson:P});if(ae)return ae;throw Rn(new rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new rt(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason})}async function go(e,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:o,sessionId:a,session:u,returnUrl:l,telemetry:w}){let B=t?.getRawProvider();if(!B)throw new rt("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!i||!e.threeDSecureToken)throw Rn(new rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=sl(e.threeDSecureToken),R=null,S=e.paymentMethodId,_=await ll(B,e.threeDSecureToken,h);if(_){if(_.error)throw Rn(new rt(_.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let b=_.intent;!S&&b?.payment_method&&(typeof b.payment_method=="string"?S=b.payment_method:"id"in b.payment_method&&(S=b.payment_method.id??void 0))}let d=S?await cl(B,e.threeDSecureToken,{payment_method:S,return_url:l??ra(u)??window.location.href},h):null;if(d){if(d.error)throw Rn(new rt(d.error.message??"3DS authentication failed.","api_error",{code:d.error.code}),"card");R=d.intent}else{let b=await B.handleNextAction({clientSecret:e.threeDSecureToken});if(b.error)throw Rn(new rt(b.error.message??"3DS authentication failed.","api_error",{code:b.error.code}),"card");R=(h?b.setupIntent:b.paymentIntent)??null}if(R&&(R.status==="requires_capture"||R.status==="succeeded"||R.status==="processing")){let b=await Pr({billingApiUrl:o,sessionId:a,session:u,telemetry:w,tokenizedData:{id:R.id,type:"card",threeDSecureActionResultTokenId:R.id},returnUrl:l});return b.type==="success"?{...b.result,paymentIntentId:b.result.paymentIntentId??R.id,paymentMethodId:b.result.paymentMethodId??S}:go(b,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:o,sessionId:a,session:u,returnUrl:l,telemetry:w})}throw Rn(new rt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw Rn(new rt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:S}=await h.handleNextAction({clientSecret:e.threeDSecureToken});if(S)throw Rn(new rt(S.message??"PayPal authorization failed.","api_error",{code:S.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:R}=await h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??ra(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(R)throw Rn(new rt(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new rt("Unsupported payment redirect state.","api_error")}function nr(e){if(e instanceof rt){let i=zn(e.message);return i&&i!==e.message?Object.assign(new rt(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=zn(t)??t;return new rt(n,"api_error")}function ho(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new rt("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function Po({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:i,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[u,l]=await Promise.all([Ii(e,{billingApiUrl:n,locale:i,telemetry:o}),a?Ii(t,{billingApiUrl:n,locale:i,telemetry:o}).catch(w=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",w),null)):Promise.resolve(null)]);return{flopay:u,paypalFlopay:t?a?l:u:null}}import{Fragment as In,jsx as oe,jsxs as Rt}from"react/jsx-runtime";var br=44,ua="flopay_checkout_saved_payment_resume",So=new Map,vo=new Map;function Ai(e,t){t.settled&&t.consumers===0&&So.get(e)===t&&So.delete(e)}function bl(e,t,n){let i=vo.get(e);if(i&&(!i.sdkGeneratedIdempotencyKey||!t||i.sdkGeneratedIdempotencyKey===t))return i.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};vo.set(e,a);let u=()=>{vo.get(e)===a&&vo.delete(e)};return o.then(u,u),o}function qr(e){return new Promise(t=>setTimeout(t,e))}function Co(e,t,n){let i=no({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ni,enabled:t!==!1});return i.beginCheckout(n),i}function jr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function aa(e,t,n,i,o){let a=Co(e,t,n);a.error({errorCode:i,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),jr(a)}function vl(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 ca(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function ia(e){return!e||e.data.stripe?.publishableKey?!1:!!ca(e)?.clientId}function An(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Cl(){if(!An())return null;try{let e=window.sessionStorage.getItem(ua);return e?JSON.parse(e):null}catch{return null}}function Fi(e){if(An())try{window.sessionStorage.setItem(ua,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function sa(){if(An())try{window.sessionStorage.removeItem(ua)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var pa=":idempotency-key";function Sl(e){if(!An())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 Di(e,t,n){if(An())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 da(e){if(An())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function wl(e){if(An())try{return window.sessionStorage.getItem(e+pa)??void 0}catch{return}}function kl(e,t){if(An())try{window.sessionStorage.setItem(e+pa,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function Rl(e){if(da(e),!!An())try{window.sessionStorage.removeItem(e+pa)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Il(){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 Li(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 El(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 la(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function ma({sessionId:e,nonce:t,createSession:n,billingApiUrl:i,telemetry:o,appearance:a,locale:u,loading:l,error:w,onComplete:B,onError:h,onDecline:R,onCountryChange:S,onZipChange:_,showPayPal:d=!0,showStripe:b=!0,enabledPaymentMethods:I,showApplePay:x=!0,showGooglePay:P=!0,debug:ae=!1,layout:U,theme:le,buttonsTheme:ee,buttonsStyles:F,cardButtonContent:J,cardBackButtonContent:W,cardTitleContent:ce,showSecurityFooter:$,onButtonClick:K,onBeforeButtonClick:de,enableAVS:_e,cardFieldOrder:Pe,cardPreFormSlot:ye,avsLayout:te,className:ge,initialErrorMessage:xe=null,children:ne,checkoutMode:ke,confirmLabel:Re,renderConfirmButton:Ce,onSessionCompleted:Y}){let E=hl(i),ie=fn(()=>Oi(le),[le]),Ne=a??ie?.appearance,Oe=n?"embedded_checkout":"standard_checkout",ue=ne?"custom_layout":U==="buttons"?"buttons_layout":"default_layout",[k,Q]=bt(null),[Z,ze]=bt(null),ut=jt(null),[qe,ot]=bt(null),N=jt(null),[V,Ze]=bt(null),[Te,at]=bt(e??""),He=e??Te,je=n?"":He,[ln,f]=bt(!0),[be,pt]=bt(null),[et,Je]=bt("full"),[Ve,Xe]=bt(!1),[Ie,$e]=bt(xe),[It,Ye]=bt(null),[Fn,vt]=bt(null),[Dn,cn]=bt(void 0),[gn,tn]=bt(""),[Ln,Ut]=bt(!1),[Et,Vt]=bt(!1),Xt=jt(0),[Ft,Kt]=bt("loading"),[Dt,re]=bt(0),nn=jt(!1),T=jt(!1),gt=jt(!1),mt=jt(null),Ct=fn(()=>({checkoutMode:ke??et,layout:ne?"unknown":U==="buttons"?"buttons":"embedded"}),[ke,ne,et,U]),Ee=jt(B);Ee.current=B;let Ue=jt(h);Ue.current=h;let Kn=jt(R);Kn.current=R,Bn(()=>{At(Z)?.setCheckoutContext(Ct),qe&&qe!==Z&&At(qe)?.setCheckoutContext(Ct)},[Z,qe,Ct]);let Nn=jt(Y);Nn.current=Y;let Hn=rr(g=>{Kt(g),!(g!=="exhausted"||gt.current)&&(gt.current=!0,Ue.current?.(new Pt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),or=rr(()=>{Kt("retrying"),re(g=>g+1)},[]);Bn(()=>{Kt("loading"),re(0),gt.current=!1},[He]),Bn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ni,checkout_type:Oe,checkout_layout:ue,billing_api_url:E})},[ue,Oe,E]);let Ht=fn(()=>n?hn(n,!0):"",[n]),it=fn(()=>gn===Ht?Dn:void 0,[Dn,gn,Ht]),Lt=fn(()=>n?qo(n,it):void 0,[n,it]),Wt=ke??Lt?.checkoutMode??"full",ht=fn(()=>Lt?{...Lt,checkoutMode:Wt}:void 0,[Lt,Wt]);Bn(()=>{cn(void 0),tn(Ht)},[Ht]),Bn(()=>{$e(xe)},[xe]);let Qt=rr((g,q,O)=>{ct(()=>{Kn.current?.(kt(g,q,O))})},[ct]),Yt=rr(async(g,q)=>{$e(null),vt(null),Ye("processing");let O=q?.sessionId??g.id,pe=ut.current??N.current,H=At(pe),se=pe?null:Co(E,o,Ct),C={log:A=>{H?H.log(A):se?.log(A)},error:A=>{H?H.error(A):se?.error(A)},terminal:A=>{H?H.terminal(A):se?.terminal(A)},performance:A=>{H?H.performance(A):se?.performance(A)},now:()=>H?.now()??se?.now()??0,elapsed:A=>H?.elapsed(A)??Math.max(0,(se?.now()??A)-A)},c=C.now(),s=!!(q?.initialAutoProcessingError||q?.initialAutoProcessingPending),M=!1,m,G=()=>{M||(M=!0,s=!0,m=C.now(),C.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),C.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Se=!1,tt=()=>{Se||(Se=!0,C.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),C.performance({stage:"processing",durationMs:C.elapsed(c),durationMode:"machine",paymentMethodCategory:"saved"}),m!==void 0&&C.performance({stage:"recovery",durationMs:C.elapsed(m),durationMode:"machine",paymentMethodCategory:"saved"}))};C.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),C.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),s&&G();let he;try{let A=_i(q?.initialAutoProcessingError),y;if(A)G(),A.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Fi({sessionId:O,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey}),y=await go(A,{flopay:ut.current,paypalFlopay:N.current,attempt3DS:q?.attempt3DS,billingApiUrl:E,sessionId:O,session:g,telemetry:!1}),A.type==="paypal_redirect_required"&&sa();else if(q?.initialAutoProcessingPending){let j=await new bo(E,{telemetry:!1}).waitForCheckoutSessionCompletion(q.initialAutoProcessingPending.sessionId,{initialDelayMs:q.initialAutoProcessingPending.retryAfterMs});if(j.data.session?.status!=="complete")throw new Pt("Automatic payment failed. Please try again.","api_error",{code:j.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});y={status:"succeeded"}}else{if(q?.initialAutoProcessingError)throw qn(q.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:q.initialAutoProcessingError.checkoutMethod});if(q?.fromCreateSession)return q?.fallbackToFull&&(Je("full"),Li("full")),!1;{let D=await Pr({billingApiUrl:E,sessionId:O,session:g,telemetry:!1});D.type==="success"?y=D.result:(G(),D.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Fi({sessionId:O,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey}),y=await go(D,{flopay:ut.current,paypalFlopay:N.current,attempt3DS:q?.attempt3DS,billingApiUrl:E,sessionId:O,session:g,telemetry:!1}),D.type==="paypal_redirect_required"&&sa())}}O&&mr(O),tt(),s&&(C.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),C.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),C.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Ye("success"),await qr(Tn),he=()=>Ee.current?.(y)}catch(A){let y=nr(A),D=y.checkoutMethod??$r;return $e(y.message),vt(y.message),q?.fallbackToFull&&(C.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Je("full"),Li("full")),tt(),!!(y.declineCode||y.code?.toLowerCase().includes("declin"))?C.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):y.type==="validation_error"?C.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):C.error({errorCode:s?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:s?"recovery":"processing",paymentMethodCategory:"saved"}),ct(()=>Ue.current?.(y)),Qt(D,y,{code:y.code,declineCode:y.declineCode}),Ye("error"),await Promise.allSettled([qr(Cn),q?.ensureProvidersReady?q.ensureProvidersReady():Promise.resolve()]),s&&(C.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),C.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{tt(),se&&jr(se),Ye(null),vt(null)}return ct(he),!0},[Qt,ct,nr,E,o,Ct]);Bn(()=>{if(typeof window>"u"||T.current)return;let g=new URLSearchParams(window.location.search),q=g.get("payment_intent_client_secret");if(!q)return;let O=Cl();O&&(T.current=!0,(async()=>{let pe,H=0;$e(null),vt(null),Ye("processing"),Xe(!0);try{if(g.get("redirect_status")==="failed")throw Object.assign(new Pt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:se,paypalFlopay:C}=await Po({publishableKey:O.publishableKey,paypalPublishableKey:O.paypalPublishableKey,billingApiUrl:E,locale:u,telemetry:o});pe=At(C??se),H=pe?.now()??0,pe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),pe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let c=(C??se)?.getRawProvider();if(!c)throw Object.assign(new Pt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:s,error:M}=await c.retrievePaymentIntent(q);if(M)throw Object.assign(new Pt(M.message??"Failed to retrieve PayPal payment status.","api_error",{code:M.code}),{checkoutMethod:"paypal"});let m=Za(s?.status);if(!s||m==="failed")throw Object.assign(new Pt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let G=typeof s.payment_method=="string"?s.payment_method:s.payment_method?.id,Se=m;if(O.sessionId){let A=(await new bo(E,{telemetry:!1}).getUnifiedCheckoutSession(O.sessionId)).data.session;if(A&&A.status!=="complete"){let y=await Pr({billingApiUrl:E,sessionId:O.sessionId,session:A,telemetry:!1,tokenizedData:{id:G??s.id,type:"card",threeDSecureActionResultTokenId:s.id,isPaypal:!0}});if(y.type!=="success")throw Object.assign(new Pt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Se=y.result.status}}O.sessionId&&mr(O.sessionId),pe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),pe?.performance({stage:"redirect_resume",durationMs:pe.elapsed(H),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),pe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ye("success"),await qr(Tn),ct(()=>Ee.current?.({status:Se,paymentIntentId:s.id,paymentMethodId:G,checkoutMethod:"paypal"}))}catch(se){let C=nr(se),c=C.checkoutMethod??"paypal",s=!!(C.declineCode||C.code?.toLowerCase().includes("declin"));if(pe)pe.performance({stage:"redirect_resume",durationMs:pe.elapsed(H),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),s?pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):pe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(s){let M=Co(E,o,Ct);M.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),jr(M)}else aa(E,o,Ct,"REDIRECT_RESUME_FAILED","redirect_resume");$e(C.message),vt(C.message),ct(()=>Ue.current?.(C)),Qt(c,C,{code:C.code,declineCode:C.declineCode}),Ye("error"),await qr(Cn)}finally{sa(),Il(),Ye(null),vt(null),Xe(!1)}})())},[Qt,ct,u,nr,E,o]);let dn=jt(null);function hn(g,q=!1){let O=g?.account?.email?.trim().toLowerCase()??"",pe={c:g?.clientId,cur:g?.currency??"",a:{e:O,u:O?"":g?.account?.userId??"",country:g?.account?.country??""},successUrl:g?.successUrl,cancelUrl:g?.cancelUrl,p:g?.products?.map(C=>la(`${C.type??""}:${C.code??C.providerItemId??C.providerPlanId??""}`,C)).sort(),i:g?.items?.map(C=>la(C.code??C.providerItemId??"",C)).sort(),s:g?.subscriptions?.map(C=>la(C.code??C.providerPlanId??"",C)).sort(),couponCodes:g?.couponCodes?[...g.couponCodes].sort():void 0,...q?{tagsData:g?.tagsData,utmMetadata:g?.utmMetadata,tokenizedData:g?.tokenizedData,checkoutMode:g?.checkoutMode??"full"}:{}},H=JSON.stringify(pe),se=0;for(let C=0;C<H.length;C++)se=(se<<5)-se+H.charCodeAt(C)|0;return`flopay_session_${Math.abs(se).toString(36)}`}let _t=fn(()=>ht?hn(ht):"",[ht]),$t=jt(ht);$t.current=ht,Bn(()=>{at(e??"")},[e]),Bn(()=>{nn.current=!1,$e(xe),vt(null),Ye(null)},[_t,xe,e]);async function Ae(g,q){let O=Co(E,o,Ct),pe=new bo(E,{telemetry:!1}),H=!1;try{let se=g.idempotencyKey!==void 0?Bi(g.idempotencyKey):void 0,C=se??wl(q),c,s=!1,M=Sl(q);O.log({name:M?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let m=M?.sid??null,G=null,Se;if(m)try{if(G=await pe.getUnifiedCheckoutSession(m,M?.nonce),G.data.session?.status==="complete"){if(Vo(m))return{sid:m,result:G};Rl(q),m=null,G=null,s=!0}}catch{O.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),da(q),m=null}if(!m){!se&&(s||!C)&&(C=Bi(),c=C),C&&kl(q,C);let tt=O.now(),he=0;O.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let A={...g,idempotencyKey:C,avsCheck:!!_e,avsConfig:typeof _e=="object"?_e:void 0,checkoutType:"embedded_checkout",checkoutLayout:ne?"custom_layout":U==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(A,yl,{configurable:!1,enumerable:!1,value:{onAttempt:j=>{he=Math.max(he,j)}}});let y=()=>{O.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),O.performance({stage:"session_create",durationMs:O.now()-tt,durationMode:"machine",requestCategory:"session_create",attempt:he,statusClass:"2xx"})},D=j=>{let We=fl(j,"CHECKOUT_SESSION_CREATE_FAILED","unknown");O.performance({stage:"session_create",durationMs:O.now()-tt,durationMode:"machine",requestCategory:"session_create",attempt:he,statusClass:We.statusClass}),j instanceof Pt&&j.type==="validation_error"?O.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):We.statusClass==="4xx"?O.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):O.error({...We,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if(gl(A)){let j=await pe.createDetachedSession(A);j.claimed.catch(()=>{}),G=j.shell,m=j.sessionId,Se=j.claimed.then(We=>{let Tt=We.data.session?.id??j.sessionId;return Tt&&Di(q,Tt,We.data.session?.clientSecret??j.nonce),y(),We},We=>{throw da(q),D(We),We}).finally(()=>jr(O)),Se.catch(()=>{}),H=!0,O.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),O.performance({stage:"session_shell",durationMs:O.now()-tt,durationMode:"machine",requestCategory:"session_create",attempt:he,statusClass:"2xx",paymentMethodCategory:"card"})}else G=await pe.createAndFetchSession(A),y()}catch(j){throw D(j),j}m=G.data.session?.id??m??"",m&&!Se&&Di(q,m,G.data.session?.clientSecret)}return{sid:m??"",result:G,sdkGeneratedIdempotencyKey:c,...Se?{claimed:Se}:{}}}finally{H||jr(O)}}let St=rr(async(g,q)=>{let O=$t.current;if(!O)throw new Pt("createSession is required to bootstrap checkout.","validation_error");let pe=qo(O,g),H=hn(pe),se=So.get(H);if(!se){let s={promise:Ae(pe,H),consumers:0,settled:!1};se=s,So.set(H,s);let M=()=>{s.settled=!0,Ai(H,s)};s.promise.then(M,M)}se.consumers+=1;let C=!1,c=()=>{C||(C=!0,se.consumers-=1,Ai(H,se))};q?.(c);try{let s=await se.promise;dn.current=H,g&&(tn(Ht),cn(y=>Xa(y,g)));let{sid:M,result:m,claimed:G}=s;if(Q(m),m.data.session&&Ze(m.data.session),M&&at(M),G){let y=Xt.current+=1;Vt(!0),G.then(D=>{Xt.current===y&&(Q(D),D.data.session&&Ze(D.data.session),Vt(!1))},D=>{Xt.current===y&&(Vt(!1),pt(D instanceof Pt?D:new Pt(D instanceof Error?D.message:"Failed to create session","api_error")))})}else Xt.current+=1,Vt(!1);let{publishableKey:Se,paypalPublishableKey:tt}=ho(m),{flopay:he,paypalFlopay:A}=await Po({publishableKey:Se,paypalPublishableKey:tt,billingApiUrl:E,locale:u,telemetry:o});return ut.current=he,ze(he),N.current=A,ot(A),f(!1),s}catch(s){throw dn.current===H&&(dn.current=null),s}finally{q||c()}},[u,E,o,Ct]),wt=jt(Yt);wt.current=Yt;let Pn=jt(St);Pn.current=St;let Wn=rr(async g=>{if(!El(g)||Ln)return{sessionId:Te,session:V};Ut(!0);try{let q=await St(g);return{sessionId:q.sid,session:q.result.data.session??null}}finally{Ut(!1)}},[St,Ln,Te,V]);Bn(()=>{let g=!1,q;if(pt(null),_t){let H=$t.current;return Je(Wt),f(!1),dn.current===_t?()=>{g=!0}:(Ze(Qa(H,ke)),(async()=>{let se=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),C=Wt==="auto"&&!nn.current&&!se;C&&($e(null),vt(null),Ye("processing"));try{let c=await Pn.current(void 0,G=>{q=G}),s=c.result.data.session??null;mt.current=ho(c.result);let M=ia(c.result),m=Vo(c.sid||s?.id);if(!g&&C&&s&&!M&&!m){nn.current=!0,await bl(_t,c.sdkGeneratedIdempotencyKey,()=>wt.current(s,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:c.result.autoProcessingError,initialAutoProcessingPending:c.result.autoProcessingPending,autoProcessingAttempted:c.result.autoProcessingAttempted,sessionId:c.sid||s.id}));return}!g&&C&&((M||m)&&(nn.current=!0),Ye(null),vt(null))}catch(c){if(g)return;let s=c instanceof Pt||typeof c=="object"&&c!==null&&"code"in c?c.code:void 0;if(C&&s==="session_auto_completed"){nn.current=!0,Ye("success"),await qr(Tn),g||(ct(()=>{Ee.current?.({status:"succeeded"})}),Ye(null),vt(null));return}C&&(Ye(null),vt(null));let M=c instanceof Pt?c:new Pt(c instanceof Error?c.message:"Failed to create session","api_error");pt(M)}finally{q?.(),q=void 0}})(),()=>{g=!0,q?.()})}f(!0);async function O(){let H=!1;try{let C=await new bo(E,{telemetry:!1}).getUnifiedCheckoutSession(He,t);if(g)return;Q(C);let c=C.data.session??null;if(Ze(c),!c)throw new Pt("No session data returned","api_error");if(c.status==="complete"){f(!1),ct(()=>{Nn.current?.(c.successUrl??"")});return}if(c.status==="expired")throw new Pt("Checkout session has expired.","api_error",{code:"checkout_session_expired"});H=!0;let s=ke??c.checkoutMode??"full";Je(s);let M=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),m=ia(C);if(s==="auto"&&!nn.current&&!M&&!m){nn.current=!0;let G=pe(C);try{if(await wt.current(c,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>G,sessionId:He||c.id}),g)return;await G,g||f(!1);return}catch{if(g)return;await G,g||f(!1);return}}await pe(C),g||f(!1)}catch(se){if(g)return;se instanceof Pt?!H&&!vl(se)&&aa(E,o,Ct,"NETWORK_REQUEST_FAILED","session_read"):aa(E,o,Ct,"INTERNAL_SDK_ERROR","checkout_mount");let C=se instanceof Pt?se:new Pt(se instanceof Error?se.message:"Failed to initialize checkout","api_error");pt(C),f(!1)}}async function pe(H){let{publishableKey:se,paypalPublishableKey:C}=ho(H);mt.current={publishableKey:se,paypalPublishableKey:C};let{flopay:c,paypalFlopay:s}=await Po({publishableKey:se,paypalPublishableKey:C,billingApiUrl:E,locale:u,telemetry:o});ut.current=c,ze(c),N.current=s,ot(s)}return O(),()=>{g=!0}},[ke,_t,Wt,je,ct,t]);let Gt=rr(async()=>{if(!(Ve||!V)){Xe(!0),$e(null);try{await Yt(V,{attempt3DS:!0,fallbackToFull:!0,sessionId:He||V.id})}finally{Xe(!1)}}},[He,Ve,Yt,V]),Zt=ca(k),Nt=ia(k),En=fn(()=>{if(!k||!V||!k.data.stripe?.publishableKey)return;let g={appearance:Ne,paymentMethodCreation:"manual",billingApiUrl:E};if(k.data.stripe?.clientSecret)g.clientSecret=k.data.stripe.clientSecret;else{let q=Mi(V).total;g.amount=Math.round(q*100)||V.amount,g.currency=V.currency?.toLowerCase()}return g},[k,V,Ne,E]),On=!!(n&&!ne&&U==="buttons"&&de&&Wt==="full"),un=fn(()=>({session:V,loading:ln,error:be,checkoutMode:et,inlineSessionDraft:ht,applyInlineSessionPatch:On?Wn:void 0,inlineSessionPatchProcessing:Ln,claimPending:Et}),[V,ln,be,et,ht,On,Wn,Ln,Et]),en=!!n&&U==="buttons"&&!Nt&&(!Z||!En),xt=It?oe(Sn,{status:It,errorMessage:Fn}):null;if(ln){if(l)return Rt(In,{children:[l,xt]});if(U==="buttons"){let g=ie?.buttonsLayout?.cardButton?.borderRadius??ie?.appearance.variables?.borderRadius??8,q=O=>oe("div",{style:{height:O,borderRadius:g,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:[d&&q(br),b&&(x||P)&&q(br),b&&q(br),oe("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),xt]})}return Rt(In,{children:[Rt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[oe("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),oe("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),xt]})}return be?w?oe(yn.Provider,{value:un,children:w(be)}):oe(yn.Provider,{value:un,children:oe("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:be.message})}):en?Rt(In,{children:[oe(yn.Provider,{value:un,children:oe(xl,{onButtonClick:K,showPayPal:d,showStripe:b,showApplePay:x,showGooglePay:P,theme:le,buttonsTheme:ee,buttonsStyles:F,cardButtonContent:J,cardBackButtonContent:W,cardTitleContent:ce})}),xt]}):Nt&&V&&Zt?Rt(In,{children:[oe(yn.Provider,{value:un,children:Rt("div",{className:ge,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ie&&oe(ur,{icon:!1,children:Ie}),Ft==="retrying"&&oe("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ft==="exhausted"&&Rt("div",{role:"alert",children:[oe("div",{children:"PayPal is temporarily unavailable. Please try again."}),oe("button",{type:"button",onClick:or,children:"Retry PayPal"})]}),Ft!=="exhausted"&&oe("div",{"aria-hidden":Ft==="retrying"?!0:void 0,style:Ft==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:oe(ii,{sessionId:He,nonce:V.clientSecret||void 0,billingApiUrl:E,email:V.customer?.email,clientId:Zt.clientId,environment:Zt.environment,currency:(V.currency??"usd").toUpperCase(),isSubscription:V.mode==="subscription",onComplete:B,onErrorChange:$e,onDecline:R,onButtonClick:K,onInitializationStateChange:Hn,allowAutomaticRetry:Dt===0,session:V,telemetry:o,telemetryContext:Ct,debug:ae},`paypal-init-${Dt}`)})]})}),xt]}):!Z||!En?oe(In,{children:xt}):et==="confirm"?Rt(In,{children:[oe(yn.Provider,{value:un,children:oe(ro,{flopay:Z,paypalFlopay:qe,options:En,children:Rt("div",{className:ge,children:[Ie&&oe("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ie}),Ce?Ce({onConfirm:Gt,isProcessing:Ve}):oe("button",{type:"button",onClick:Gt,disabled:Ve,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Ve?"not-allowed":"pointer",opacity:Ve?.6:1},children:Ve?"Processing...":Re??"Confirm Purchase"})]})})}),xt]}):Rt(In,{children:[oe(yn.Provider,{value:un,children:oe(ro,{flopay:Z,paypalFlopay:qe,options:En,children:ne?Rt(In,{children:[Ie&&oe("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ie}),oe(_l,{sessionId:He,nonce:V?.clientSecret||void 0,billingApiUrl:E,session:V,children:ne})]}):oe(na,{sessionId:He,nonce:V?.clientSecret||void 0,email:V?.customer?.email,userId:V?.customer?.id,firstName:V?.customer?.firstName,lastName:V?.customer?.lastName,totalAmount:V?Math.round(Mi(V).total*100):0,currency:V?.currency?.toLowerCase()??"usd",onComplete:B,onError:h,onDecline:R,error:Ie,onErrorChange:$e,showPayPal:d,showStripe:b,enabledPaymentMethods:I??k?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:k?.data.stripe?.enabledPaymentMethodCountries,showApplePay:x,showGooglePay:P,layout:U,theme:le,buttonsTheme:ee,buttonsStyles:F,appearance:Ne,cardButtonContent:J,cardBackButtonContent:W,cardTitleContent:ce,onButtonClick:K,onBeforeButtonClick:de,enableAVS:_e,...Pe?{cardFieldOrder:Pe}:{},...ye?{cardPreFormSlot:ye}:{},avsLayout:te,country:V?.customer?.country,city:V?.customer?.city,state:V?.customer?.state,onCountryChange:S,onZipChange:_,avsCheck:!!_e,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ne?"custom_layout":U==="buttons"?"buttons_layout":"default_layout",className:ge,directPaypal:ca(k),isSubscription:V?.mode==="subscription",session:V,dataAttachmentPending:Et,debug:ae})})}),xt]})}function _l({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:o}){return oe(In,{children:oa.Children.map(o,a=>{if(!oa.isValidElement(a))return a;let u=a.props,l={};return u.sessionId||(l.sessionId=e),!u.nonce&&t&&(l.nonce=t),u.billingApiUrl||(l.billingApiUrl=n),i?.customer&&(u.email||(l.email=i.customer.email),u.userId||(l.userId=i.customer.id),u.firstName||(l.firstName=i.customer.firstName),u.lastName||(l.lastName=i.customer.lastName)),Object.keys(l).length===0?a:oa.cloneElement(a,l)})})}function xl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:i,showGooglePay:o,theme:a,buttonsTheme:u,buttonsStyles:l,cardButtonContent:w,cardBackButtonContent:B,cardTitleContent:h}){let[R,S]=bt(!1),_=fn(()=>Oi(a),[a]),d=fn(()=>{let P=_?.buttonsLayout??Pl(u);return l?{...P,...l,cardButton:{...P.cardButton,...l.cardButton},cardFormContainer:{...P.cardFormContainer,...l.cardFormContainer},backButton:{...P.backButton,...l.backButton},backButtonIcon:{...P.backButtonIcon,...l.backButtonIcon},submitButton:{...P.submitButton,...l.submitButton},title:{...P.title,...l.title}}:P},[_,u,l]),b=_?.buttonsLayout?.cardButton?.borderRadius??_?.appearance.variables?.borderRadius??8,I=P=>oe("div",{style:{height:P,borderRadius:b,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),x=w===void 0?{boxSizing:"border-box",height:br,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(R){let P=d.cardInputBorder??"#e5e7eb",ae=d.cardInputBackground??"white",U=sr(B),le=sr(h);return Rt("div",{style:{backgroundColor:d.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...d.cardFormContainer},children:[Rt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Rt("button",{type:"button",onClick:()=>S(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:U?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...d.backButton},children:[oe("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...d.backButtonIcon},children:oe("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:oe("path",{d:"M15 18l-6-6 6-6"})})}),oe(cr,{content:B})]}),le?oe("div",{style:{flex:1}}):oe("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...d.title},children:oe(Dr,{content:h})})]}),oe("div",{style:{backgroundColor:ae,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:oe("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:[oe("div",{style:{flex:1,backgroundColor:ae,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:oe("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),oe("div",{style:{flex:1,backgroundColor:ae,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:oe("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),oe("div",{style:{backgroundColor:ae,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:oe("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),oe("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...d.submitButton,opacity:.5}}),oe("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 kt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&I(Pr),n&&(i||r)&&I(Pr),n&&re("button",{type:"button",onClick:()=>{e?.("card"),C(!0)},style:{width:"100%",...x,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:re(sr,{content:S})}),re("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:S,onFocus:M,onBlur:y,onEscape:R}){let C=Mi(null),_=Mi(null),{elements:l,reportInteractive:h}=Sl(xn);return Cl(()=>{if(!l||!C.current)return;let I=!0;return(async()=>{let x=l.getElement(e);x||(x=await l.create(e,c)),!(!I||!C.current)&&(x.mount(C.current),_.current=x,s&&x.on("change",s),x.on("ready",()=>{h?.(),S?.()}),M&&x.on("focus",M),y&&x.on("blur",y),R&&x.on("escape",R))})(),()=>{if(I=!1,_.current){try{_.current.unmount()}catch{}_.current=null}}},[l,h]),Rl("div",{ref:C,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:S,onComplete:M,onErrorChange:y,isProcessing:R=!1}){let C=fn(),_=zo(),l=to(),[h,I]=Ai(!1),[x,f]=Ai(!1),ae=xl(!1),U=(n||l).replace(/\/+$/,""),ie=ua(async G=>{try{let se=await new Il(U).processPayment(r??"",{sessionId:e,nonce:t,tokenizedData:G,accountData:{userId:r??"",email:i??"",firstName:a??"",lastName:c??""},chv:s});if(se.ok){M?.();return}let $=await se.json().catch(()=>null);y?.($?.message??"Payment failed. Please try again.")}catch(H){y?.(H instanceof Error?H.message:"An unexpected error occurred")}},[U,e,t,r,i,a,c,s,M,y]),X=ua(G=>{S?S(G):ie(G)},[S,ie]);_l(()=>{if(!C||ae.current)return;let G=new URLSearchParams(window.location.search),H=G.get("payment_intent"),se=G.get("payment_intent_client_secret"),$=G.get("redirect_status");!H||!se||(ae.current=!0,(async()=>{try{if(f(!0),$==="failed"){y?.("PayPal payment was declined. Please try again.");return}let V=C.getRawProvider();if(!V?.retrievePaymentIntent){y?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:de,error:Ee}=await V.retrievePaymentIntent(se);if(Ee){y?.(Ee.message??"Failed to retrieve PayPal payment status.");return}if(de&&(de.status==="requires_capture"||de.status==="succeeded")){let Pe=typeof de.payment_method=="string"?de.payment_method:de.payment_method?.id;X({id:Pe??de.id,type:"card",threeDSecureActionResultTokenId:de.id,isPaypal:!0});let ye=new URL(window.location.href);ye.searchParams.delete("payment_intent"),ye.searchParams.delete("payment_intent_client_secret"),ye.searchParams.delete("redirect_status"),window.history.replaceState({},"",ye.toString())}else y?.("PayPal payment was not completed. Please try again.")}catch(V){y?.(V instanceof Error?V.message:"Failed to complete PayPal payment.")}finally{f(!1)}})())},[C,X,y]);let B=ua(async()=>{if(!(!C||!_))try{if(f(!0),y?.(null),!e||!i)throw new El("Missing sessionId or email for PayPal payment","validation_error");let G=await C.confirmPayPalPayment({billingApiUrl:U,sessionId:e,nonce:t,email:i,returnUrl:window.location.href});if(G.error){y?.(G.error.message);return}G.paymentIntentId&&(G.status==="succeeded"||G.status==="processing"||G.status==="requires_capture")&&X({id:G.paymentMethodId??G.paymentIntentId,type:"card",threeDSecureActionResultTokenId:G.paymentIntentId,isPaypal:!0})}catch(G){y?.(G instanceof Error?G.message:"PayPal payment failed. Please try again.")}finally{f(!1)}},[C,_,e,t,i,U,X,y]);return!C||!_?br("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):Bl(Ml,{children:[!h&&br("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),br("div",{style:h?{}:{display:"none"},children:br("button",{type:"button",onClick:B,disabled:x||R,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:x||R?"not-allowed":"pointer",opacity:x||R?.6:1},ref:()=>I(!0),children:x?"Processing...":"PayPal"})}),(x||R)&&br("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:br("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}import{useCallback as zn,useEffect as vr,useMemo as qr,useRef as Cr,useState as Co}from"react";import{PaymentAPI as pa}from"@flopay/js";import{FloPayError as Un,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 Un?e:new Un(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:S,account:M,successUrl:y,cancelUrl:R,couponCodes:C,tagsData:_,utmMetadata:l,billingApiUrl:h,locale:I,theme:x,appearance:f,buttonsTheme:ae,buttonsStyles:U,onSuccess:ie,onError:X,onDecline:B,children:G,disabled:H=!1,type:se="button",style:$,...V}){let de=qr(()=>Al(h),[h]),Ee=qr(()=>zl({createSession:n,clientId:a,products:c,items:s,subscriptions:S,account:M,successUrl:y,cancelUrl:R,couponCodes:C,tagsData:_,utmMetadata:l}),[M,R,a,C,n,c,s,S,y,_,l]),[Pe,ye]=Co(!1),[Z,fe]=Co(null),[_e,Q]=Co(null),[ke,Me]=Co(null),we=Cr(!0),Y=Cr(null),E=Cr(ke),le=Cr(ie),Ne=Cr(X),Oe=Cr(B);vr(()=>{E.current=ke},[ke]),vr(()=>{le.current=ie},[ie]),vr(()=>{Ne.current=X},[X]),vr(()=>{Oe.current=B},[B]),vr(()=>(we.current=!0,()=>{we.current=!1,Y.current?.abort()}),[]),vr(()=>{if(typeof window>"u")return;let m=ve=>{ve.key==="Escape"&&Me(null)};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[]);let ue=zn((m,ve=Ur)=>{Oe.current?.(St(ve,m,{code:m.code,declineCode:m.declineCode}))},[]),k=zn(async m=>{we.current&&(Q(null),fe("success"),await Fi(Tn),we.current&&le.current?.(m))},[]),ee=zn(async(m,ve)=>{we.current&&(Ne.current?.(m),ve?.emitDecline&&ue(m,ve.method),Q(m.message),fe("error"),await Fi(gn))},[ue]),J=zn(async(m,ve,We)=>{let tt=m.data.session??null;if(!tt)throw new Un("No session data returned","api_error");let ht=tt.clientSecret||t;if(tt.status==="complete"){await k({result:{status:"succeeded"},session:tt,sessionId:tt.id||ve,autoCompleted:!1});return}if(tt.status==="expired")throw new Un("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(m.autoProcessingPending){let Ge=(await new pa(de).waitForCheckoutSessionCompletion(m.autoProcessingPending.sessionId,{initialDelayMs:m.autoProcessingPending.retryAfterMs})).data.session;if(!Ge||Ge.status!=="complete")throw new Un("Automatic payment failed. Please try again.","api_error",{code:Ge?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await k({result:{status:"succeeded"},session:Ge,sessionId:Ge.id||ve,autoCompleted:!1});return}if(m.autoProcessingError){if(m.autoProcessingError.type==="3ds_required"&&m.autoProcessingError.nextActionRedirectUrl&&ve&&ht){let Ze=new AbortController;Y.current=Ze;let xe;try{xe=await Ci({billingApiUrl:de,sessionId:ve,nonce:ht,nextActionRedirectUrl:m.autoProcessingError.nextActionRedirectUrl,signal:Ze.signal})}finally{Y.current===Ze&&(Y.current=null)}if(xe.status==="declined")throw On({type:xe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:xe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:m.autoProcessingError.checkoutMethod});let Ke=(await new pa(de).waitForCheckoutSessionCompletion(ve,{initialDelayMs:0,nonce:ht})).data.session;if(!Ke||Ke.status!=="complete")throw On({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:m.autoProcessingError.checkoutMethod});await k({result:{status:"succeeded"},session:Ke,sessionId:Ke.id||ve,autoCompleted:!1});return}throw On(m.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:m.autoProcessingError.checkoutMethod})}if(We?.fromCreateSession&&m.autoProcessingAttempted===!0)throw On({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ye=await hr({billingApiUrl:de,sessionId:ve??tt.id,session:tt,nonce:ht});if(Ye.type!=="success")throw On({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await k({result:Ye.result,session:tt,sessionId:tt.id||ve,autoCompleted:!1})}catch(Ye){let Ze=tr(Ye),xe=tt.id||ve;await ee(Ze,{emitDecline:!0,method:Ze.checkoutMethod??Ur}),Ol(Ze,xe)&&xe&&we.current&&Me({sessionId:xe,errorMessage:Ze.message,nonce:ht||void 0})}},[t,de,ee,k]),Fe=zn(async m=>{if(V.onClick?.(m),!(m.defaultPrevented||H||Pe)){if(Me(null),e&&Ee){let ve=new Un("Provide either sessionId or create-session props, not both.","validation_error");await ee(ve),we.current&&(fe(null),Q(null));return}if(!e&&!Ee){let ve=new Un("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await ee(ve),we.current&&(fe(null),Q(null));return}ye(!0),Q(null),fe("processing");try{let ve=new pa(de);if(e){let We=await ve.getUnifiedCheckoutSession(e,t);await J(We,e);return}try{let We=await ve.createAndFetchSession({...Ee});await J(We,We.data.session?.id??null,{fromCreateSession:!0})}catch(We){if(We instanceof Un&&We.code==="session_auto_completed"){await k({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw We}}catch(ve){await ee(Nl(ve,"Automatic payment failed. Please try again."))}finally{we.current&&(fe(null),Q(null),ye(!1))}}},[V,Ee,H,Pe,t,J,de,e,ee,k]),yt=zn(m=>{let ve=E.current;Me(null),le.current?.({result:m,session:null,sessionId:ve?.sessionId??null,autoCompleted:!1})},[]),je=zn(m=>{Ne.current?.(m)},[]),it=zn(m=>{Oe.current?.(m)},[]),F=qr(()=>Dl(x),[x]),L=qr(()=>{let m=F?.buttonsLayout??Fl(ae);return U?{...m,...U,cardButton:{...m.cardButton,...U.cardButton}}:m},[F,ae,U]),Ue=qr(()=>{let m=F?.appearance;return f?m?{...m,...f,variables:{...m.variables,...f.variables}}:f:m},[f,F]),qe=Ue?.variables,st=qe?.colorPrimary??"#4A49FF",ft=qe?.colorPrimaryHover??lo(st,.12),Bt=qe?.borderRadius??"8px";return ql($l,{children:[Sr("button",{...V,type:se,onClick:Fe,disabled:H||Pe,"aria-busy":Pe,style:{width:"100%",...G===void 0?{boxSizing:"border-box",height:Ll,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...L.cardButton,...Qo({themeBundle:F,resolvedPrimaryColor:st,resolvedBorderRadius:Bt,submitButtonStyle:L.submitButton,explicitPrimaryColor:qe?.colorPrimary}),fontSize:L.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:H||Pe?"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||Pe?.6:1,...$},onMouseEnter:m=>{V.onMouseEnter?.(m),!m.defaultPrevented&&!H&&!Pe&&(F||qe?.colorPrimary)&&(m.currentTarget.style.backgroundColor=ft)},onMouseLeave:m=>{V.onMouseLeave?.(m),!m.defaultPrevented&&(F||qe?.colorPrimary)&&(m.currentTarget.style.backgroundColor=st)},onMouseDown:m=>{V.onMouseDown?.(m),m.defaultPrevented||(m.currentTarget.style.transform="scale(0.985)")},onMouseUp:m=>{V.onMouseUp?.(m),m.defaultPrevented||(m.currentTarget.style.transform="scale(1)")},children:Sr(sr,{content:G})}),Z&&Sr(hn,{status:Z,errorMessage:_e}),ke&&Sr("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: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:ke.sessionId,nonce:ke.nonce,checkoutMode:"full",billingApiUrl:de,locale:I,theme:x,...Ue?{appearance:Ue}:{},buttonsTheme:ae,buttonsStyles:U,initialErrorMessage:ke.errorMessage,cardTitleContent:null,onComplete:yt,onError:je,onDecline:it})})})]})}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,fn as useFloPay,Oo as usePayPalFloPay};
47
+ `})]})}return Rt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&I(br),n&&(i||o)&&I(br),n&&oe("button",{type:"button",onClick:()=>{e?.("card"),S(!0)},style:{width:"100%",...x,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:d.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,...d.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:oe(lr,{content:w})}),oe("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{useEffect as Tl,useRef as zi,useContext as Ml}from"react";import{jsx as Fl}from"react/jsx-runtime";function Ui(e,t){function n({className:i,id:o,style:a,options:u,onChange:l,onReady:w,onFocus:B,onBlur:h,onEscape:R}){let S=zi(null),_=zi(null),{elements:d,reportInteractive:b}=Ml(xn);return Tl(()=>{if(!d||!S.current)return;let I=!0;return(async()=>{let x=d.getElement(e);x||(x=await d.create(e,u)),!(!I||!S.current)&&(x.mount(S.current),_.current=x,l&&x.on("change",l),x.on("ready",()=>{b?.(),w?.()}),B&&x.on("focus",B),h&&x.on("blur",h),R&&x.on("escape",R))})(),()=>{if(I=!1,_.current){try{_.current.unmount()}catch{}_.current=null}}},[d,b]),Fl("div",{ref:S,className:i,id:o,style:a})}return n.displayName=t,n}var Bl=Ui("payment","PaymentElement"),Al=Ui("address","AddressElement");import{PaymentAPI as Dl}from"@flopay/js";import{FloPayError as Ll}from"@flopay/shared";import{useCallback as ya,useEffect as Nl,useRef as Ol,useState as $i}from"react";import{Fragment as Ul,jsx as vr,jsxs as $l}from"react/jsx-runtime";function zl({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:o,firstName:a,lastName:u,chv:l,onTokenizedBody:w,onComplete:B,onErrorChange:h,isProcessing:R=!1}){let S=vn(),_=$o(),d=oo(),[b,I]=$i(!1),[x,P]=$i(!1),ae=Ol(!1),U=(n||d).replace(/\/+$/,""),le=ya(async J=>{try{let ce=await new Dl(U).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:J,accountData:{userId:o??"",email:i??"",firstName:a??"",lastName:u??""},chv:l});if(ce.ok){B?.();return}let $=await ce.json().catch(()=>null);h?.($?.message??"Payment failed. Please try again.")}catch(W){h?.(W instanceof Error?W.message:"An unexpected error occurred")}},[U,e,t,o,i,a,u,l,B,h]),ee=ya(J=>{w?w(J):le(J)},[w,le]);Nl(()=>{if(!S||ae.current)return;let J=new URLSearchParams(window.location.search),W=J.get("payment_intent"),ce=J.get("payment_intent_client_secret"),$=J.get("redirect_status");!W||!ce||(ae.current=!0,(async()=>{try{if(P(!0),$==="failed"){h?.("PayPal payment was declined. Please try again.");return}let K=S.getRawProvider();if(!K?.retrievePaymentIntent){h?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:de,error:_e}=await K.retrievePaymentIntent(ce);if(_e){h?.(_e.message??"Failed to retrieve PayPal payment status.");return}if(de&&(de.status==="requires_capture"||de.status==="succeeded")){let Pe=typeof de.payment_method=="string"?de.payment_method:de.payment_method?.id;ee({id:Pe??de.id,type:"card",threeDSecureActionResultTokenId:de.id,isPaypal:!0});let ye=new URL(window.location.href);ye.searchParams.delete("payment_intent"),ye.searchParams.delete("payment_intent_client_secret"),ye.searchParams.delete("redirect_status"),window.history.replaceState({},"",ye.toString())}else h?.("PayPal payment was not completed. Please try again.")}catch(K){h?.(K instanceof Error?K.message:"Failed to complete PayPal payment.")}finally{P(!1)}})())},[S,ee,h]);let F=ya(async()=>{if(!(!S||!_))try{if(P(!0),h?.(null),!e||!i)throw new Ll("Missing sessionId or email for PayPal payment","validation_error");let J=await S.confirmPayPalPayment({billingApiUrl:U,sessionId:e,nonce:t,email:i,returnUrl:window.location.href});if(J.error){h?.(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){h?.(J instanceof Error?J.message:"PayPal payment failed. Please try again.")}finally{P(!1)}},[S,_,e,t,i,U,ee,h]);return!S||!_?vr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):$l(Ul,{children:[!b&&vr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),vr("div",{style:b?{}:{display:"none"},children:vr("button",{type:"button",onClick:F,disabled:x||R,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:x||R?"not-allowed":"pointer",opacity:x||R?.6:1},ref:()=>I(!0),children:x?"Processing...":"PayPal"})}),(x||R)&&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 jn,useEffect as Cr,useMemo as Vr,useRef as Sr,useState as wo}from"react";import{PaymentAPI as fa}from"@flopay/js";import{FloPayError as Vn,resolveBillingApiUrl as ql,resolveButtonsLayoutTheme as jl,resolveTheme as Vl}from"@flopay/shared";import{Fragment as Jl,jsx as wr,jsxs as Xl}from"react/jsx-runtime";var Kl=44;function qi(e){return new Promise(t=>setTimeout(t,e))}function Hl(e,t){return e instanceof Vn?e:new Vn(e instanceof Error?e.message:t,"api_error")}function Wl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Yl(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 Gl({sessionId:e,nonce:t,createSession:n,paymentMethodId:i,checkoutMethod:o,clientId:a,products:u,items:l,subscriptions:w,account:B,successUrl:h,cancelUrl:R,couponCodes:S,tagsData:_,utmMetadata:d,billingApiUrl:b,locale:I,theme:x,appearance:P,buttonsTheme:ae,buttonsStyles:U,onSuccess:le,onError:ee,onDecline:F,children:J,disabled:W=!1,type:ce="button",style:$,...K}){let de=Vr(()=>ql(b),[b]),_e=Vr(()=>Yl({createSession:n,clientId:a,products:u,items:l,subscriptions:w,account:B,successUrl:h,cancelUrl:R,couponCodes:S,tagsData:_,utmMetadata:d}),[B,R,a,S,n,u,l,w,h,_,d]),[Pe,ye]=wo(!1),[te,ge]=wo(null),[xe,ne]=wo(null),[ke,Re]=wo(null),Ce=Sr(!0),Y=Sr(null),E=Sr(ke),ie=Sr(le),Ne=Sr(ee),Oe=Sr(F);Cr(()=>{E.current=ke},[ke]),Cr(()=>{ie.current=le},[le]),Cr(()=>{Ne.current=ee},[ee]),Cr(()=>{Oe.current=F},[F]),Cr(()=>(Ce.current=!0,()=>{Ce.current=!1,Y.current?.abort()}),[]),Cr(()=>{if(typeof window>"u")return;let f=be=>{be.key==="Escape"&&Re(null)};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f)}},[]);let ue=jn((f,be=$r)=>{Oe.current?.(kt(be,f,{code:f.code,declineCode:f.declineCode}))},[]),k=jn(async f=>{Ce.current&&(ne(null),ge("success"),await qi(Tn),Ce.current&&ie.current?.(f))},[]),Q=jn(async(f,be)=>{Ce.current&&(Ne.current?.(f),be?.emitDecline&&ue(f,be.method),ne(f.message),ge("error"),await qi(Cn))},[ue]),Z=jn(async(f,be,pt)=>{let et=f.data.session??null;if(!et)throw new Vn("No session data returned","api_error");let Je=et.clientSecret||t;if(et.status==="complete"){await k({result:{status:"succeeded"},session:et,sessionId:et.id||be,autoCompleted:!1});return}if(et.status==="expired")throw new Vn("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(f.autoProcessingPending){let $e=(await new fa(de).waitForCheckoutSessionCompletion(f.autoProcessingPending.sessionId,{initialDelayMs:f.autoProcessingPending.retryAfterMs})).data.session;if(!$e||$e.status!=="complete")throw new Vn("Automatic payment failed. Please try again.","api_error",{code:$e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await k({result:{status:"succeeded"},session:$e,sessionId:$e.id||be,autoCompleted:!1});return}if(f.autoProcessingError){if(f.autoProcessingError.type==="3ds_required"&&f.autoProcessingError.nextActionRedirectUrl&&be&&Je){let Xe=new AbortController;Y.current=Xe;let Ie;try{Ie=await xi({billingApiUrl:de,sessionId:be,nonce:Je,nextActionRedirectUrl:f.autoProcessingError.nextActionRedirectUrl,signal:Xe.signal})}finally{Y.current===Xe&&(Y.current=null)}if(Ie.status==="declined")throw qn({type:Ie.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ie.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:f.autoProcessingError.checkoutMethod});let Ye=(await new fa(de).waitForCheckoutSessionCompletion(be,{initialDelayMs:0,nonce:Je})).data.session;if(!Ye||Ye.status!=="complete")throw qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:f.autoProcessingError.checkoutMethod});await k({result:{status:"succeeded"},session:Ye,sessionId:Ye.id||be,autoCompleted:!1});return}throw qn(f.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:f.autoProcessingError.checkoutMethod})}if(pt?.fromCreateSession&&f.autoProcessingAttempted===!0)throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ve=await Pr({billingApiUrl:de,sessionId:be??et.id,session:et,nonce:Je});if(Ve.type!=="success")throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await k({result:Ve.result,session:et,sessionId:et.id||be,autoCompleted:!1})}catch(Ve){let Xe=nr(Ve),Ie=et.id||be;await Q(Xe,{emitDecline:!0,method:Xe.checkoutMethod??$r}),Wl(Xe,Ie)&&Ie&&Ce.current&&Re({sessionId:Ie,errorMessage:Xe.message,nonce:Je||void 0})}},[t,de,Q,k]),ze=jn(async f=>{if(K.onClick?.(f),!(f.defaultPrevented||W||Pe)){if(Re(null),e&&_e){let be=new Vn("Provide either sessionId or create-session props, not both.","validation_error");await Q(be),Ce.current&&(ge(null),ne(null));return}if(!e&&!_e){let be=new Vn("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Q(be),Ce.current&&(ge(null),ne(null));return}ye(!0),ne(null),ge("processing");try{let be=new fa(de);if(e){let pt=await be.getUnifiedCheckoutSession(e,t);await Z(pt,e);return}try{let pt=await be.createAndFetchSession({..._e});await Z(pt,pt.data.session?.id??null,{fromCreateSession:!0})}catch(pt){if(pt instanceof Vn&&pt.code==="session_auto_completed"){await k({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw pt}}catch(be){await Q(Hl(be,"Automatic payment failed. Please try again."))}finally{Ce.current&&(ge(null),ne(null),ye(!1))}}},[K,_e,W,Pe,t,Z,de,e,Q,k]),ut=jn(f=>{let be=E.current;Re(null),ie.current?.({result:f,session:null,sessionId:be?.sessionId??null,autoCompleted:!1})},[]),qe=jn(f=>{Ne.current?.(f)},[]),ot=jn(f=>{Oe.current?.(f)},[]),N=Vr(()=>Vl(x),[x]),V=Vr(()=>{let f=N?.buttonsLayout??jl(ae);return U?{...f,...U,cardButton:{...f.cardButton,...U.cardButton}}:f},[N,ae,U]),Ze=Vr(()=>{let f=N?.appearance;return P?f?{...f,...P,variables:{...f.variables,...P.variables}}:P:f},[P,N]),Te=Ze?.variables,at=Te?.colorPrimary??"#4A49FF",He=Te?.colorPrimaryHover??po(at,.12),je=Te?.borderRadius??"8px";return Xl(Jl,{children:[wr("button",{...K,type:ce,onClick:ze,disabled:W||Pe,"aria-busy":Pe,style:{width:"100%",...J===void 0?{boxSizing:"border-box",height:Kl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...V.cardButton,...ta({themeBundle:N,resolvedPrimaryColor:at,resolvedBorderRadius:je,submitButtonStyle:V.submitButton,explicitPrimaryColor:Te?.colorPrimary}),fontSize:V.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:W||Pe?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:W||Pe?.6:1,...$},onMouseEnter:f=>{K.onMouseEnter?.(f),!f.defaultPrevented&&!W&&!Pe&&(N||Te?.colorPrimary)&&(f.currentTarget.style.backgroundColor=He)},onMouseLeave:f=>{K.onMouseLeave?.(f),!f.defaultPrevented&&(N||Te?.colorPrimary)&&(f.currentTarget.style.backgroundColor=at)},onMouseDown:f=>{K.onMouseDown?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(0.985)")},onMouseUp:f=>{K.onMouseUp?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(1)")},children:wr(lr,{content:J})}),te&&wr(Sn,{status:te,errorMessage:xe}),ke&&wr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:f=>{f.target===f.currentTarget&&Re(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children: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(ma,{sessionId:ke.sessionId,nonce:ke.nonce,checkoutMode:"full",billingApiUrl:de,locale:I,theme:x,...Ze?{appearance:Ze}:{},buttonsTheme:ae,buttonsStyles:U,initialErrorMessage:ke.errorMessage,cardTitleContent:null,onComplete:ut,onError:qe,onDecline:ot})})})]})}export{Al as AddressElement,uo as DirectPayPalButton,Gl as FloPayAutomaticPaymentButton,ma as FloPayCheckout,ro as FloPayProvider,zl as PayPalButton,Bl as PaymentElement,na as SplitCardForm,zo as VaultCardFields,Cs as useCheckout,$o as useElements,vn as useFloPay,Uo as usePayPalFloPay};