@flopay/react 1.4.8 → 1.4.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,12 +1,12 @@
1
- import{useCallback as Yi,useEffect as xr,useState as xo,useMemo as Gi,useRef as To}from"react";import{resolveBillingApiUrl as Ji}from"@flopay/shared";import{createContext as Ma}from"react";var Tn=Ma({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),un=Ma({session:null,loading:!1,error:null});var Vi=Symbol.for("@flopay/js.telemetry.bridge.v1"),Hi=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ki(){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 Wi(e){let t=Ki(),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 Gr(e){let t=globalThis[Hi];return Wi(t?.(e)??{})}function Mt(e){if(e)return e[Vi]}import{jsx as Xi}from"react/jsx-runtime";function Jr({flopay:e,paypalFlopay:t,options:n,children:i}){let[r,a]=xo(e instanceof Promise?null:e),[c,s]=xo(t instanceof Promise||!t?null:t),[w,A]=xo(null),p=To(null),I=To(null),C=To(null);xr(()=>{if(!r)return;let k=Mt(r);return p.current=k?.beginCheckout()??k?.now()??0,k?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{k?.log({name:"checkout.unmount",stage:"unmount"})}},[r]),xr(()=>{let k=!1;return e instanceof Promise?e.then(B=>{k||a(B)}):a(e),()=>{k=!0}},[e]),xr(()=>{let k=!1;if(!t){s(null);return}return t instanceof Promise?t.then(B=>{k||s(B)}):s(t),()=>{k=!0}},[t]),xr(()=>{if(!r){A(null);return}let k=r.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return A(k),()=>{k.destroy()}},[r,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),xr(()=>{if(!r||!w||I.current===w)return;I.current=w;let k=Mt(r);k?.log({name:"checkout.rendered",stage:"checkout_render"}),k?.performance({stage:"checkout_render",durationMs:k.elapsed(p.current??0),durationMode:"machine"})},[w,r]);let T=Yi(()=>{if(!r||!w||C.current===w)return;C.current=w;let k=Mt(r);k?.log({name:"checkout.interactive",stage:"checkout_interactive"}),k?.performance({stage:"checkout_interactive",durationMs:k.elapsed(p.current??0),durationMode:"machine"})},[w,r]),l=Ji(n?.billingApiUrl),f=Gi(()=>({flopay:r,paypalFlopay:c,elements:w,billingApiUrl:l,reportInteractive:T}),[r,c,w,l,T]);return Xi(Tn.Provider,{value:f,children:i})}import Go,{useCallback as Qn,useEffect as An,useMemo as pn,useRef as nn,useState as wt}from"react";import{PaymentAPI as po}from"@flopay/js";import{SDK_VERSION as vi,FloPayError as Bt,classifyTelemetryFailure as Js,resolveBillingApiUrl as Xs,buildCheckoutDisplayData as gi,resolveButtonsLayoutTheme as Zs,resolveTheme as Ci}from"@flopay/shared";import"react";import{Fragment as or,jsx as en,jsxs as Ba}from"react/jsx-runtime";function Zi(){return Ba(or,{children:[Ba("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 Qi(){return en(or,{children:"Go back"})}function es(){return en(or,{children:"Secure card checkout"})}function tr(e){return e!==void 0&&(e===""||e===null||e===!1)}function nr({content:e}){return en(or,{children:e===void 0?en(Zi,{}):e})}function rr({content:e}){return en(or,{children:e===void 0?en(Qi,{}):e})}function Tr({content:e}){return en(or,{children:e===void 0?en(es,{}):e})}import{ExpressCheckoutElement as ai,PaymentElement as gs,Elements as Xn,useElements as jo,useStripe as Vo}from"@stripe/react-stripe-js";import{resolveButtonsLayoutTheme as hs,getPostalCodeLabel as $o,getStateLabel as Wa,getStateOptions as Ps,COUNTRY_OPTIONS as bs,resolveAVSConfig as vs,isAVSFieldVisible as _e,getStateFromPostalCode as Ya,isPostalCodeSupported as Cs,isValidPostalCode as Ss,getPostalCodeExample as ws,filterStripeMethodsByCountry as ks,getStripeMethodDisplayName as ur,hasVendoredStripeMethodLogo as Rs,needsStripeMethodExplicitConfirm as Ga,resolveStripeMethodBrandVariant as Is,partitionStripeMethods as Es,stripeExpressMethodToOptionKey as Ja}from"@flopay/shared";import{PaymentAPI as On,toStripeAppearance as _s}from"@flopay/js";import{useEffect as Aa,useRef as Mr}from"react";import{jsx as ts}from"react/jsx-runtime";function Mo({capture:e,html:t,messageToken:n,expectedOrigin:i,theme:r,containerStyle:a,onReady:c,onError:s,onValidation:w}){let A=Mr(null),p=Mr(c),I=Mr(s),C=Mr(w);p.current=c,I.current=s,C.current=w;let T=Mr(r);return T.current=r,Aa(()=>{let l=A.current;if(!l)return;let f=!0,k=!1,B=()=>{!f||k||(k=!0,p.current?.())},h=e.on("ready",()=>{B()}),q=e.on("error",Z=>{I.current?.(Z.message??"There was a problem loading the secure card form.")}),W=e.on("validation",Z=>{C.current?.(Z.message??null)}),ce={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},...T.current?{theme:T.current}:{}};return e.mount(l,ce).then(()=>{B()}).catch(Z=>{f&&I.current?.(Z instanceof Error?Z.message:"Failed to load the secure card form.")}),()=>{f=!1,h(),q(),W(),e.unmount()}},[e,t,n,i]),Aa(()=>{r&&e.applyTheme?.(r)},[e,r]),ts("div",{ref:A,"data-testid":"flopay-vault-card-fields",style:a})}import"react";import{jsx as Fa,jsxs as ns}from"react/jsx-runtime";function ar({children:e,margin:t,icon:n=!0,styleOverride:i}){return ns("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&&Fa("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Fa("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 Da={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 xs,{useCallback as he,useContext as Ts,useEffect as pt,useMemo as rt,useRef as Le,useState as ge}from"react";import{useContext as Br}from"react";import{resolveBillingApiUrl as rs}from"@flopay/shared";function Pn(){return Br(Tn).flopay}function Bo(){return Br(Tn).paypalFlopay??null}function Ao(){return Br(Tn).elements}function os(){return Br(un)}function Xr(){return Br(Tn).billingApiUrl||rs()}import"react";import{jsx as tn,jsxs as ir}from"react/jsx-runtime";var Mn=1200,bn=1500;function vn({status:e,errorMessage:t}){return tn("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:ir("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:[ir("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&ir("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:ir("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:ir("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"}})]})})]}),ir("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 rs,useEffect as Ar,useState as Do,useMemo as os,useRef as Lo}from"react";import{resolveBillingApiUrl as as}from"@flopay/shared";import{createContext as za}from"react";var Tn=za({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),un=za({session:null,loading:!1,error:null});var Qi=Symbol.for("@flopay/js.telemetry.bridge.v1"),es=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function ts(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},flush:async()=>{},destroy:()=>{}}}function ns(e){let t=ts(),n=(r,a)=>r?r.bind(e):a,i=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:i,elapsed:e.elapsed?e.elapsed.bind(e):r=>Math.max(0,i()-r),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Qr(e){let t=globalThis[es];return ns(t?.(e)??{})}function Bt(e){if(e)return e[Qi]}import{jsx as is}from"react/jsx-runtime";function eo({flopay:e,paypalFlopay:t,options:n,children:i}){let[r,a]=Do(e instanceof Promise?null:e),[c,s]=Do(t instanceof Promise||!t?null:t),[C,B]=Do(null),p=Lo(null),k=Lo(null),v=Lo(null);Ar(()=>{if(!r)return;let S=Bt(r);return p.current=S?.beginCheckout()??S?.now()??0,S?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{S?.log({name:"checkout.unmount",stage:"unmount"})}},[r]),Ar(()=>{let S=!1;return e instanceof Promise?e.then(M=>{S||a(M)}):a(e),()=>{S=!0}},[e]),Ar(()=>{let S=!1;if(!t){s(null);return}return t instanceof Promise?t.then(M=>{S||s(M)}):s(t),()=>{S=!0}},[t]),Ar(()=>{if(!r){B(null);return}let S=r.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return B(S),()=>{S.destroy()}},[r,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),Ar(()=>{if(!r||!C||k.current===C)return;k.current=C;let S=Bt(r);S?.log({name:"checkout.rendered",stage:"checkout_render"}),S?.performance({stage:"checkout_render",durationMs:S.elapsed(p.current??0),durationMode:"machine"})},[C,r]);let E=rs(()=>{if(!r||!C||v.current===C)return;v.current=C;let S=Bt(r);S?.log({name:"checkout.interactive",stage:"checkout_interactive"}),S?.performance({stage:"checkout_interactive",durationMs:S.elapsed(p.current??0),durationMode:"machine"})},[C,r]),l=as(n?.billingApiUrl),y=os(()=>({flopay:r,paypalFlopay:c,elements:C,billingApiUrl:l,reportInteractive:E}),[r,c,C,l,E]);return is(Tn.Provider,{value:y,children:i})}import na,{useCallback as nr,useEffect as An,useMemo as pn,useRef as on,useState as kt}from"react";import{PaymentAPI as go}from"@flopay/js";import{SDK_VERSION as _i,FloPayError as At,classifyTelemetryFailure as al,resolveBillingApiUrl as il,buildCheckoutDisplayData as wi,resolveButtonsLayoutTheme as sl,resolveIdempotencyKey as ki,resolveTheme as xi}from"@flopay/shared";import"react";import{Fragment as cr,jsx as nn,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:[nn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),nn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",nn("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:nn("path",{d:"M9 18l6-6-6-6"})})]})}function ls(){return nn(cr,{children:"Go back"})}function cs(){return nn(cr,{children:"Secure card checkout"})}function ir(e){return e!==void 0&&(e===""||e===null||e===!1)}function sr({content:e}){return nn(cr,{children:e===void 0?nn(ss,{}):e})}function lr({content:e}){return nn(cr,{children:e===void 0?nn(ls,{}):e})}function Fr({content:e}){return nn(cr,{children:e===void 0?nn(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 Me,getStateFromPostalCode as ti,isPostalCodeSupported as Ts,isValidPostalCode as Ms,getPostalCodeExample as Bs,filterStripeMethodsByCountry as As,getStripeMethodDisplayName as gr,hasVendoredStripeMethodLogo as Fs,needsStripeMethodExplicitConfirm as ni,resolveStripeMethodBrandVariant as Ds,partitionStripeMethods as Ls,stripeExpressMethodToOptionKey as ri}from"@flopay/shared";import{PaymentAPI as zn,toStripeAppearance as Ns}from"@flopay/js";import{useEffect as $a,useRef as Dr}from"react";import{jsx as ds}from"react/jsx-runtime";function No({capture:e,html:t,messageToken:n,expectedOrigin:i,theme:r,containerStyle:a,onReady:c,onError:s,onValidation:C}){let B=Dr(null),p=Dr(c),k=Dr(s),v=Dr(C);p.current=c,k.current=s,v.current=C;let E=Dr(r);return E.current=r,$a(()=>{let l=B.current;if(!l)return;let y=!0,S=!1,M=()=>{!y||S||(S=!0,p.current?.())},f=e.on("ready",()=>{M()}),U=e.on("error",Q=>{k.current?.(Q.message??"There was a problem loading the secure card form.")}),W=e.on("validation",Q=>{v.current?.(Q.message??null)}),me={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},...E.current?{theme:E.current}:{}};return e.mount(l,me).then(()=>{M()}).catch(Q=>{y&&k.current?.(Q instanceof Error?Q.message:"Failed to load the secure card form.")}),()=>{y=!1,f(),U(),W(),e.unmount()}},[e,t,n,i]),$a(()=>{r&&e.applyTheme?.(r)},[e,r]),ds("div",{ref:B,"data-testid":"flopay-vault-card-fields",style:a})}import"react";import{jsx as qa,jsxs as us}from"react/jsx-runtime";function dr({children:e,margin:t,icon:n=!0,styleOverride:i}){return us("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...i??{}},children:[n&&qa("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:qa("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var ja={alipay:new URL("./payment-logos/alipay.svg",import.meta.url).href,bancontact:new URL("./payment-logos/bancontact.svg",import.meta.url).href,blik:new URL("./payment-logos/blik.svg",import.meta.url).href,eps:new URL("./payment-logos/eps.svg",import.meta.url).href,giropay:new URL("./payment-logos/giropay.svg",import.meta.url).href,ideal:new URL("./payment-logos/ideal.svg",import.meta.url).href,klarna:new URL("./payment-logos/klarna.svg",import.meta.url).href,p24:new URL("./payment-logos/p24.svg",import.meta.url).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",import.meta.url).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",import.meta.url).href};import Os,{useCallback as Ce,useContext as zs,useEffect as yt,useMemo as ot,useRef as Oe,useState as be}from"react";import{useContext as Lr}from"react";import{resolveBillingApiUrl as ps}from"@flopay/shared";function vn(){return Lr(Tn).flopay}function Oo(){return Lr(Tn).paypalFlopay??null}function zo(){return Lr(Tn).elements}function ms(){return Lr(un)}function to(){return Lr(Tn).billingApiUrl||ps()}import"react";import{jsx as rn,jsxs as ur}from"react/jsx-runtime";var Mn=1200,Cn=1500;function Sn({status:e,errorMessage:t}){return rn("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children: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:[rn("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),rn("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&rn("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:ur("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[rn("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),rn("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&rn("div",{style:{animation:"flopay-shake 0.4s ease"},children:ur("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[rn("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),rn("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),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"&&rn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:"You will be automatically redirected, do not close or navigate away from this window."}),e==="error"&&t&&rn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),rn("style",{children:`
2
2
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
3
3
  @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
4
4
  @keyframes flopay-draw { to { stroke-dashoffset: 0; } }
5
5
  @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
6
- `})]})})}import{FloPayError as hc,isSetupIntentClientSecret as Pc}from"@flopay/shared";function La(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 Fo(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 Na(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 Do(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 as=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Ln(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:i}of as)if(n.test(t))return i;return e}function Zr(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Oa(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function za(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Qr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var eo="flopay_recent_completion_";function sr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(eo+e,JSON.stringify(t))}catch{}}function Ua(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(eo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(eo+e),!1):!0}catch{return!1}}function $a(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 to,useEffect as ut,useMemo as Fr,useRef as Ke,useState as Jn}from"react";import{loadScript as ss}from"@paypal/paypal-js";import{PaymentAPI as Lo}from"@flopay/js";import{FloPayError as qa,SDK_VERSION as ls,generateIdempotencyKey as cs,normalizeGatewayEnvironment as ds}from"@flopay/shared";function dt(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function is(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 Gn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Bn(e){if(typeof e!="object"||e===null)return;let t=e;return Gn(t.code)??Gn(t.type)??Gn(t.name)}function lr(e){if(!(typeof e!="object"||e===null))return Gn(e.decline_code)}function Ar(e){return typeof e!="object"||e===null?!1:Gn(e.type)?.toLowerCase()==="card_error"||lr(e)!==void 0}function Nn(e){let t=is(e)?.toLowerCase()??"",i=`${Bn(e)?.toLowerCase()??""} ${t}`;return i.includes("popup")&&i.includes("block")}import{jsx as cr,jsxs as No}from"react/jsx-runtime";var no=45,us=1e3,ps=11e3,ms=["https://www.paypal.com","https://www.sandbox.paypal.com"],ja="We couldn't open PayPal. Try again or choose another payment method.",ys={width:"100%",minHeight:no,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 Va(e){return e.includes("No ack for postMessage init()")&&ms.some(t=>e.includes(t))&&e.includes("10000ms")}function fs(e){return e?`${ja} Allow pop-ups for this site, then try again.`:ja}function Ha({sessionId:e,nonce:t,billingApiUrl:n,email:i,clientId:r,environment:a,currency:c,isSubscription:s,onTokenizedBody:w,onComplete:A,onErrorChange:p,onDecline:I,onTechnicalFailure:C,isProcessing:T=!1,onLoadStateChange:l,onInitializationStateChange:f,allowAutomaticRetry:k=!0,onButtonClick:B,runBeforeButtonClick:h,session:q,existingOrderId:W,telemetry:ce,telemetryContext:Z,debug:F=!1}){let J=Pn(),j=Fr(()=>{if(J)return null;let y=Gr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:ls,enabled:ce!==!1});return y.setCheckoutContext(Z??{}),y.beginCheckout(Z??{}),y},[n,J,ce,Z?.checkoutMode,Z?.layout]),de=Fr(()=>Mt(J),[J]);ut(()=>()=>{j&&j.flush().catch(()=>{}).finally(()=>j.destroy())},[j]);let z=Fr(()=>({error:y=>{de?de.error(y):j?.error(y)},log:y=>{de?de.log(y):j?.log(y)},performance:y=>{de?de.performance(y):j?.performance(y)},terminal:y=>{de?de.terminal(y):j?.terminal(y)},startTiming:()=>de?.now()??j?.now()??0,elapsed:y=>de?.elapsed(y)??Math.max(0,(j?.now()??y)-y)}),[de,j]),V=Ke(null),re=Ke(0),Me=Ke(null),me=Ke(!1),[pe,X]=Jn(!1),[ue,Pe]=Jn(!1),[oe,Fe]=Jn(0),ke=Ke(0),[ve,R]=Jn(!1),te=Ke(!1),ie=Ke(!1),[Ne,De]=Jn(!1),[Y,M]=Jn(!1),H=Fr(()=>n.replace(/\/+$/,""),[n]),se=Fr(()=>JSON.stringify([H,r,c,a??"",s,e,W??""]),[H,r,c,a,W,s,e]),Re=Ke(se),at=Re.current!==se,[Je,Ge]=Jn([]),m=y=>{F&&Ge(mt=>[...mt,`${new Date().toISOString().slice(11,23)} ${y}`])},$e=Ke(w),Oe=Ke(A),He=Ke(p),qe=Ke(I),Gt=Ke(C),Pt=Ke(B),Rt=Ke(l),g=Ke(f),Ce=Ke(h),je=Ke(q),it=Ke(i),et=Ke(t),Xe=Ke(null),We=Ke(0),be=Ke(null),bt=Ke(null),Ve=Ke(new Map),Ot=Ke(new Map),It=Ke(!1);ut(()=>(It.current=!0,()=>{It.current=!1}),[]),ut(()=>{$e.current=w},[w]),ut(()=>{Oe.current=A},[A]),ut(()=>{He.current=p},[p]),ut(()=>{qe.current=I},[I]),ut(()=>{Gt.current=C},[C]),ut(()=>{Pt.current=B},[B]),ut(()=>{Rt.current=l},[l]),ut(()=>{g.current=f},[f]),ut(()=>{Ce.current=h},[h]),ut(()=>{je.current=q},[q]),ut(()=>{it.current=i},[i]),ut(()=>{et.current=t},[t]),ut(()=>{ke.current=oe},[oe]),ut(()=>{ve&&Me.current?.focus()},[ve,oe]);let mn=to(()=>{window.setTimeout(()=>{Me.current?.focus()},0)},[]),Rn=to(()=>{X(!1),Fe(y=>y+1)},[]),In=to(()=>{R(!1),(V.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??V.current)?.focus?.()},[]);ut(()=>{!pe||!me.current||(me.current=!1,In())},[In,pe,oe]);let qn=to((y,mt)=>{let At=Gt.current;if(At){At("paypal",y,mt);return}He.current?.(fs(mt?.popupBlocked??Nn(y)))},[]),ht=()=>{be.current?.timer&&(clearTimeout(be.current.timer),be.current.timer=null)},zt=()=>{ht();let y=We.current+1;return We.current=y,bt.current=null,be.current={generation:y,timer:null,yieldedControl:!1},R(!1),y},Dt=y=>y!==void 0&&be.current?.generation!==y?!1:(ht(),be.current=null,bt.current=null,!0),Jt=y=>{let mt=y?.generation??be.current?.generation??We.current;(!y?.generation||be.current?.generation===mt)&&(ht(),be.current=null),bt.current=mt,y?.showRetry&&R(!0),y?.remount&&Rn(),y?.focus!==!1&&mn()},rn=y=>be.current?.generation===y&&bt.current!==y,yn=y=>{typeof document<"u"&&document.visibilityState!=="visible"||(ht(),y.timer=setTimeout(()=>{be.current?.generation===y.generation&&(be.current=null,bt.current=y.generation,qn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),R(!0),Rn(),mn())},600))},K=()=>{let y=be.current;y?.yieldedControl&&yn(y)},Fn=()=>{let y=be.current;y&&(y.yieldedControl=!0,ht())},fn=y=>{let mt=Xe.current;return mt&&Ot.current.set(y,mt),y};ut(()=>{let y=()=>{document.visibilityState==="visible"?K():Fn()};return document.addEventListener("visibilitychange",y),window.addEventListener("focus",K),window.addEventListener("blur",Fn),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("focus",K),window.removeEventListener("blur",Fn),ht()}},[]),ut(()=>{Re.current!==se&&(Re.current=se,te.current=!1,ie.current=!1,X(!1),Pe(!1),De(!1),g.current?.("loading"))},[se]),ut(()=>{dt(()=>Rt.current?.(pe&&!Ne))},[pe,Ne]);let Ut=ds(a);ut(()=>{let y=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",mt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(m(`mount clientId=${y} env=${a??"(unset)"}\u2192${Ut??"live"} ccy=${c} sub=${s}`),m(`ua=${mt.slice(0,80)}${mt.length>80?"\u2026":""}`),!r){m("FAIL: clientId empty \u2014 gateway misconfigured"),De(!0),z.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!V.current){m("FAIL: containerRef not attached");return}re.current=z.startTiming(),z.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let At=!1,En=!1,ye=()=>At||En,Ht,on=!1,Kt=()=>{Ht=cs(),Ht||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),on=!0},an=null,sn=!1,Wt=null,_n=!1,$t=()=>{!Wt||_n||(_n=!0,Wt.close().catch(()=>{}))},qt=null,Se=()=>{qt!==null&&(z.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"overlay_return",durationMs:z.elapsed(qt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),qt=null)},st=!1,Ze=V.current,gn=null,ln=null,vt=[],Lt=P=>{if(!P||typeof P.getBoundingClientRect!="function")return"(no rect)";let b=P.getBoundingClientRect();return`${Math.round(b.width)}\xD7${Math.round(b.height)}`},Nt=P=>{if(!P)return"(empty)";try{let b=new URL(P,typeof window<"u"?window.location.href:"https://localhost"),_=b.pathname.toLowerCase();return _.includes("checkcaptcha")||_.includes("captcha")?`CAPTCHA(${b.host}${_})`:_.includes("risk")||_.includes("challenge")?`RISK(${b.host}${_})`:_.includes("smart/buttons")?`smart-buttons(${b.host})`:`${b.host}${_}`.slice(0,100)}catch{return P.slice(0,80)}},jn=P=>{let b=P.getAttribute("src"),_=P.getAttribute("srcdoc"),le=P.getAttribute("name"),we=P.getAttribute("sandbox"),Be=[];return b&&Be.push(`src=${Nt(b)}`),_&&Be.push(`srcdoc[${_.length}ch]`),!b&&!_&&Be.push("src=(empty) srcdoc=(empty)"),le&&Be.push(`name=${le.slice(0,40)}`),we!==null&&Be.push(`sandbox="${we.slice(0,40)}"`),Be.join(" ")},Dn=P=>{if(!(P instanceof HTMLIFrameElement))return"";try{let b=P.contentDocument;if(!b)return"cd=null";let _=b.body?.children.length??0,le=b.body?.innerHTML.length??0,we=b.head?.innerHTML.length??0;return`cd=same-origin readyState=${b.readyState} body[${_}children,${le}ch] head[${we}ch]`}catch(b){return`cd=cross-origin(${b.message.slice(0,30)})`}},xn=[],jt=P=>{if(ye())return;let b=P.message??String(P.error??"(no message)");b&&(b.toLowerCase().includes("paypal")||b.toLowerCase().includes("zoid")||b.toLowerCase().includes("postrobot")||b.toLowerCase().includes("storage"))&&(m(`window:error ${b.slice(0,140)}`),xn.push(b))},cn=P=>{if(ye())return;let b=P.reason instanceof Error?P.reason.message:String(P.reason??"(no reason)");b&&(b.toLowerCase().includes("paypal")||b.toLowerCase().includes("zoid")||b.toLowerCase().includes("postrobot")||b.toLowerCase().includes("storage"))&&(m(`window:rejection ${b.slice(0,140)}`),xn.push(b))};F&&typeof window<"u"&&(window.addEventListener("error",jt),window.addEventListener("unhandledrejection",cn));let Te={value:0};if(F&&typeof PerformanceObserver<"u")try{ln=new PerformanceObserver(P=>{if(!ye())for(let b of P.getEntries()){if(!b.name.toLowerCase().includes("paypal"))continue;Te.value+=1;let _=Math.round(b.duration);m(`net ${_}ms ${b.name.slice(0,90)}`)}}),ln.observe({type:"resource",buffered:!0})}catch{}let x=()=>{for(gn?.disconnect(),gn=null,ln?.disconnect(),ln=null;vt.length;)clearTimeout(vt.pop());F&&typeof window<"u"&&(window.removeEventListener("error",jt),window.removeEventListener("unhandledrejection",cn))},O=P=>{if(!P)return!1;let b=P.toLowerCase();return b.includes("zoid destroyed")||b.includes("destroyed all components")||b.includes("window closed")||b.includes("detected container element removed")},G=P=>{if(ye()||O(P))return;let b=Ln(P)??P;dt(()=>He.current?.(b))},D=P=>{At||(De(!0),P.includes("paypal_ineligible")||z.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",P))},$=(P,b=!1)=>{if(At)return;let _=te.current||!k;if(sn)return;sn=!0,En=!0,x(),$t();let le=b||Va(P);if(le&&k&&!te.current){te.current=!0,X(!1),M(!1),Pe(!0),g.current?.("retrying"),an=setTimeout(()=>{At||Fe(we=>we+1)},us);return}if(le||_){if(X(!1),M(!1),Pe(!1),De(!0),g.current?.("exhausted"),!ie.current){ie.current=!0;let we=Va(P)?"paypal_init_timeout":b?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",we)}return}D(P)};De(!1);let N=async(P,b=Xe.current)=>{if(ye())return;let _=b?.sessionId??e;if($e.current){await $e.current(P,{sessionId:_,accountPatch:b?.accountPatch,nonce:b?.nonce});return}let le=z.startTiming();z.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let we=()=>{z.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"processing",durationMs:z.elapsed(le),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Be=je.current,Yt=b?.accountPatch?.email??it.current,Ue=b?.accountPatch?.userId??Be?.customer?.id??Be?.accountData?.userId??"",ae=await new Lo(H,{telemetry:!1}).processPayment(Ue,{sessionId:_,nonce:b?.nonce??et.current,tokenizedData:P,accountData:{userId:Ue,email:Yt??Be?.customer?.email??"",firstName:b?.accountPatch?.firstName??Be?.customer?.firstName??Be?.accountData?.firstName??"",lastName:b?.accountPatch?.lastName??Be?.customer?.lastName??Be?.accountData?.lastName??"",country:b?.accountPatch?.country??Be?.customer?.country??Be?.accountData?.country??void 0,zip:b?.accountPatch?.zip??Be?.customer?.zip??Be?.accountData?.zip??void 0}});if(ae.ok){if(En||At&&It.current)return;we(),z.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),dt(()=>Oe.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ye())return;let E=await ae.json().catch(()=>null),yt=E?.message??"PayPal payment failed.",Et=Ln(yt)??yt;we(),ae.status===400&&(typeof E?.declineCode=="string"||!Array.isArray(E?.fields))?z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ae.status===400||ae.status===422?z.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):z.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ae.status>=500?"5xx":ae.status>=400?"4xx":ae.status>=300?"3xx":"unknown",failureCategory:ae.status>=500?"server_error":void 0}),G(Et),dt(()=>qe.current?.(St("paypal",Et,{code:E?.code,declineCode:E?.declineCode})));return}catch(Be){if(ye())return;we(),z.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Yt=Be instanceof Error?Be.message:"PayPal payment failed.",Ue=Ln(Yt)??Yt;G(Ue),dt(()=>qe.current?.(St("paypal",Ue)));return}},u=()=>new qa("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),S=P=>ye()?Promise.reject(u()):Promise.resolve(P),fe=async P=>{if(ye())throw u();on||Kt();let b=Xe.current,_=b?.sessionId??e,le=b?.nonce??et.current;z.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let we=await new Lo(H,{telemetry:!1}).createSessionIntent(_,le??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Ht});if(ye())throw u();if(we.provider!=="paypal")throw new Error(P);return z.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),we.providerObjectId},nt=(P,b)=>{let _=b?.nonce??et.current;if(!_)return;let le=b?.sessionId??e,we=lr(P)??Bn(P)??"provider_declined";new Lo(H,{telemetry:!1}).reportSessionIntentDecline(le,_,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:we}).catch(()=>{})},ze=oe;m("loadScript:scheduled (deferred 1 tick)");let Ee=null,Ft=setTimeout(()=>{if(At){m("loadScript:skipped (cancelled before defer ran)");return}m("loadScript:start");let P=Ut==="live"?"production":Ut;Ee=ss({clientId:r,currency:c,intent:s?"subscription":"capture",vault:s?!0:void 0,...P?{environment:P}:{},...P==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Ee.then(b=>{if(m(`loadScript:resolved inactive=${ye()} ns=${!!b} buttons=${!!b?.Buttons}`),ye())return;if(!b?.Buttons){m("FAIL: namespace missing Buttons factory"),$("PayPal SDK did not expose the Buttons factory.");return}z.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let _=async Ue=>{if(ye()||ke.current!==ze)return;let Ie=Ue.subscriptionID??Ue.orderID??"",ae=Ie?Ot.current.get(Ie):Ve.current.get(ze);if(!(!ae||!rn(ae.generation))&&Dt(ae.generation)){Ot.current.delete(Ie),Ve.current.delete(ae.surfaceKey),Se();try{if(M(!0),dt(()=>He.current?.(null)),!Ie)throw new qa("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await N({id:Ie,isPaypal:!0},ae)}catch(E){G(E instanceof Error?E.message:"PayPal capture failed.")}finally{ye()||M(!1)}}},le=b.Buttons({style:{layout:"horizontal",height:no,tagline:!1},onClick:async(Ue,Ie)=>{if(ye()){await Ie.reject();return}Kt();let ae=Ce.current,E={};if(ae)try{let ft=await ae("paypal");if(ye()){await Ie.reject();return}if(!ft.proceed){Xe.current=null,Ve.current.delete(ze),await Ie.reject();return}E={sessionId:ft.sessionId,accountPatch:ft.accountPatch,nonce:ft.nonce}}catch(ft){m(`onClick:runBeforeButtonClick rejected msg=${(ft instanceof Error?ft.message:String(ft)).slice(0,120)}`),Xe.current=null,Ve.current.delete(ze),await Ie.reject();return}dt(()=>Pt.current?.("paypal"));let Et={generation:zt(),surfaceKey:ze,...E};Xe.current=Et,Ve.current.set(ze,Et),await Ie.resolve(),z.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),z.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),z.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),qt=z.startTiming()},createOrder:s?void 0:W?()=>S(W).then(fn):()=>fe("Failed to create PayPal order.").then(fn),createSubscription:s?W?()=>S(W).then(fn):()=>fe("Failed to create PayPal subscription.").then(fn):void 0,onApprove:_,onCancel:()=>{if(ye())return;let Ue=Ve.current.get(ze)??Xe.current;Ue&&Ve.current.delete(Ue.surfaceKey),Xe.current=null,Se(),z.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),me.current=!0,Jt({generation:Ue?.generation,remount:!0,focus:!1})},onError:Ue=>{if(ye()||ke.current!==ze)return;let Ie=Ue instanceof Error?Ue.message:"PayPal failed to render.";if(m(`onError rendered=${st} msg=${Ie.slice(0,120)}`),st){let ae=Ve.current.get(ze)??Xe.current;if(ae&&!rn(ae.generation)||!ae&&bt.current===We.current)return;if(O(Ie)){Dt(ae?.generation);return}if(Se(),Ar(Ue)){z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),nt(Ue,ae),dt(()=>qe.current?.(St("paypal",Ie))),ae&&Ve.current.delete(ae.surfaceKey),Xe.current=null,Dt(ae?.generation);return}let E=Ie.toLowerCase();z.error({errorCode:E.includes("popup")&&E.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ae&&Ve.current.delete(ae.surfaceKey),Xe.current=null,Jt({generation:ae?.generation,remount:!0,showRetry:!0,focus:!0}),qn(Ue,{code:"paypal_runtime_failed"});return}$(Ie)}}),we=le.isEligible();if(m(`isEligible=${we}`),z.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!we){X(!1),$("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Wt=le,F&&m(`container:dims ${Lt(Ze)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),F&&typeof MutationObserver<"u"&&(gn=new MutationObserver(Ue=>{if(!ye()){for(let Ie of Ue)if(Ie.type==="childList")Ie.addedNodes.forEach(ae=>{if(!(ae instanceof Element))return;let E=ae.tagName.toLowerCase(),yt=(ae.getAttribute("title")??"").slice(0,40),Et=E==="iframe"?` ${jn(ae)}`:"";m(`child+ ${E}${yt?` title="${yt}"`:""}${Et} dims=${Lt(ae)}`)});else if(Ie.type==="attributes"&&Ie.target instanceof Element){let ae=Ie.target;if(ae.tagName.toLowerCase()!=="iframe")continue;let E=Ie.attributeName;(E==="src"||E==="srcdoc")&&m(`attr~ iframe ${E}=${E==="srcdoc"?`[${(ae.getAttribute("srcdoc")??"").length}ch]`:Nt(ae.getAttribute("src"))} dims=${Lt(ae)}`)}}}),gn.observe(Ze,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Yt=Ue=>{if(ye()||st)return;let Ie=Ze.querySelectorAll("iframe"),ae=typeof document<"u"&&"hasStorageAccess"in document;m(`watchdog:${Ue} container=${Lt(Ze)} children=${Ze.childElementCount} iframes=${Ie.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${ae} paypalNetRequests=${Te.value}`),Ie.forEach((E,yt)=>{let Et=(E.getAttribute("title")??"").slice(0,40);m(` iframe[${yt}] ${Lt(E)}${Et?` title="${Et}"`:""} ${jn(E)}`);let ft=Dn(E);ft&&m(` ${ft}`)}),xn.length===0&&m(" (no PayPal/zoid window errors captured)")};F&&(vt.push(setTimeout(()=>Yt("3s"),3e3)),vt.push(setTimeout(()=>Yt("8s"),8e3)),vt.push(setTimeout(()=>Yt("15s"),15e3))),m("render:start"),vt.push(setTimeout(()=>{ye()||st||(m("watchdog:11s retryable render timeout"),$("PayPal Buttons render did not settle within 11000ms.",!0))},ps)),le.render(Ze).then(()=>{if(m(`render:resolved inactive=${ye()}`),x(),ye()){$t();return}st=!0,X(!0),Pe(!1),g.current?.("ready"),z.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"provider_ready",durationMs:z.elapsed(re.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(Ue=>{let Ie=Ue instanceof Error?Ue.message:"PayPal failed to render.";m(`render:rejected msg=${Ie.slice(0,120)}`),x(),$(Ie)})}).catch(b=>{let _=b instanceof Error?b.message:"PayPal SDK failed to load.";m(`loadScript:rejected msg=${_.slice(0,120)}`),$(_)})},0);return()=>{At=!0,clearTimeout(Ft),an&&clearTimeout(an),x(),$t()}},[k,H,r,c,a,s,e,W,oe,z]);let tt=F?No("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ne?"#fef2f2":"#f3f4f6",border:`1px solid ${Ne?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${pe} failed=${Ne})`,Je.length===0?`
6
+ `})]})})}import{FloPayError as Tc,isSetupIntentClientSecret as Mc}from"@flopay/shared";function Ka(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Uo(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Va(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],i=n.reduce((a,c)=>a+(c.overrideAmount??c.totalAmount??0),0),r=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(i*100),currency:r,status:"open",customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,c)=>({uuid:`synthetic-${a.type??"item"}-${c}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??r,metadata:a.metadata??null}))}}function $o(e,t){return t?{...e,...t}:e}function wt(e,t,n){let i=typeof t=="string"?t:t.message,r=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:i,...r?{code:r}:{},...a?{declineCode:a}:{}}}var ys=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Nn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:i}of ys)if(n.test(t))return i;return e}function no(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Ha(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Wa(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function ro(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var oo="flopay_recent_completion_";function pr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(oo+e,JSON.stringify(t))}catch{}}function qo(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(oo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(oo+e),!1):!0}catch{return!1}}function Ya(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}import{useCallback as ao,useEffect as mt,useMemo as Or,useRef as Ye,useState as Qn}from"react";import{loadScript as gs}from"@paypal/paypal-js";import{PaymentAPI as jo}from"@flopay/js";import{FloPayError as Ga,SDK_VERSION as hs,generateIdempotencyKey as Ps,normalizeGatewayEnvironment as bs}from"@flopay/shared";function pt(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function fs(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Zn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Bn(e){if(typeof e!="object"||e===null)return;let t=e;return Zn(t.code)??Zn(t.type)??Zn(t.name)}function mr(e){if(!(typeof e!="object"||e===null))return Zn(e.decline_code)}function Nr(e){return typeof e!="object"||e===null?!1:Zn(e.type)?.toLowerCase()==="card_error"||mr(e)!==void 0}function On(e){let t=fs(e)?.toLowerCase()??"",i=`${Bn(e)?.toLowerCase()??""} ${t}`;return i.includes("popup")&&i.includes("block")}import{jsx as yr,jsxs as Ko}from"react/jsx-runtime";var io=45,vs=1e3,Cs=11e3,Ss=["https://www.paypal.com","https://www.sandbox.paypal.com"],Ja="We couldn't open PayPal. Try again or choose another payment method.",ws={width:"100%",minHeight:io,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Xa(e){return e.includes("No ack for postMessage init()")&&Ss.some(t=>e.includes(t))&&e.includes("10000ms")}function ks(e){return e?`${Ja} Allow pop-ups for this site, then try again.`:Ja}function Za({sessionId:e,nonce:t,billingApiUrl:n,email:i,clientId:r,environment:a,currency:c,isSubscription:s,onTokenizedBody:C,onComplete:B,onErrorChange:p,onDecline:k,onTechnicalFailure:v,isProcessing:E=!1,onLoadStateChange:l,onInitializationStateChange:y,allowAutomaticRetry:S=!0,onButtonClick:M,runBeforeButtonClick:f,session:U,existingOrderId:W,telemetry:me,telemetryContext:Q,debug:A=!1}){let G=vn(),$=Or(()=>{if(G)return null;let _=Qr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:hs,enabled:me!==!1});return _.setCheckoutContext(Q??{}),_.beginCheckout(Q??{}),_},[n,G,me,Q?.checkoutMode,Q?.layout]),ye=Or(()=>Bt(G),[G]);mt(()=>()=>{$&&$.flush().catch(()=>{}).finally(()=>$.destroy())},[$]);let N=Or(()=>({error:_=>{ye?ye.error(_):$?.error(_)},log:_=>{ye?ye.log(_):$?.log(_)},performance:_=>{ye?ye.performance(_):$?.performance(_)},terminal:_=>{ye?ye.terminal(_):$?.terminal(_)},startTiming:()=>ye?.now()??$?.now()??0,elapsed:_=>ye?.elapsed(_)??Math.max(0,($?.now()??_)-_)}),[ye,$]),q=Ye(null),ae=Ye(0),Fe=Ye(null),Pe=Ye(!1),[he,J]=Qn(!1),[fe,Se]=Qn(!1),[ie,Le]=Qn(0),_e=Ye(0),[Re,w]=Qn(!1),ne=Ye(!1),ce=Ye(!1),[ze,Ne]=Qn(!1),[Y,x]=Qn(!1),j=Or(()=>n.replace(/\/+$/,""),[n]),de=Or(()=>JSON.stringify([j,r,c,a??"",s,e,W??""]),[j,r,c,a,W,s,e]),xe=Ye(de),it=xe.current!==de,[Qe,Ze]=Qn([]),u=_=>{A&&Ze(Je=>[...Je,`${new Date().toISOString().slice(11,23)} ${_}`])},$e=Ye(C),Ue=Ye(B),We=Ye(p),qe=Ye(k),Gt=Ye(v),Pt=Ye(M),It=Ye(l),g=Ye(y),Ie=Ye(f),je=Ye(U),st=Ye(i),rt=Ye(t),et=Ye(null),Ge=Ye(0),we=Ye(null),bt=Ye(null),Ke=Ye(new Map),Ut=Ye(new Map),Et=Ye(!1);mt(()=>(Et.current=!0,()=>{Et.current=!1}),[]),mt(()=>{$e.current=C},[C]),mt(()=>{Ue.current=B},[B]),mt(()=>{We.current=p},[p]),mt(()=>{qe.current=k},[k]),mt(()=>{Gt.current=v},[v]),mt(()=>{Pt.current=M},[M]),mt(()=>{It.current=l},[l]),mt(()=>{g.current=y},[y]),mt(()=>{Ie.current=f},[f]),mt(()=>{je.current=U},[U]),mt(()=>{st.current=i},[i]),mt(()=>{rt.current=t},[t]),mt(()=>{_e.current=ie},[ie]),mt(()=>{Re&&Fe.current?.focus()},[Re,ie]);let mn=ao(()=>{window.setTimeout(()=>{Fe.current?.focus()},0)},[]),En=ao(()=>{J(!1),Le(_=>_+1)},[]),_n=ao(()=>{w(!1),(q.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??q.current)?.focus?.()},[]);mt(()=>{!he||!Pe.current||(Pe.current=!1,_n())},[_n,he,ie]);let jn=ao((_,Je)=>{let Ee=Gt.current;if(Ee){Ee("paypal",_,Je);return}We.current?.(ks(Je?.popupBlocked??On(_)))},[]),ht=()=>{we.current?.timer&&(clearTimeout(we.current.timer),we.current.timer=null)},$t=()=>{ht();let _=Ge.current+1;return Ge.current=_,bt.current=null,we.current={generation:_,timer:null,yieldedControl:!1},w(!1),_},Dt=_=>_!==void 0&&we.current?.generation!==_?!1:(ht(),we.current=null,bt.current=null,!0),Jt=_=>{let Je=_?.generation??we.current?.generation??Ge.current;(!_?.generation||we.current?.generation===Je)&&(ht(),we.current=null),bt.current=Je,_?.showRetry&&w(!0),_?.remount&&En(),_?.focus!==!1&&mn()},an=_=>we.current?.generation===_&&bt.current!==_,yn=_=>{typeof document<"u"&&document.visibilityState!=="visible"||(ht(),_.timer=setTimeout(()=>{we.current?.generation===_.generation&&(we.current=null,bt.current=_.generation,jn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),w(!0),En(),mn())},600))},K=()=>{let _=we.current;_?.yieldedControl&&yn(_)},Dn=()=>{let _=we.current;_&&(_.yieldedControl=!0,ht())},fn=_=>{let Je=et.current;return Je&&Ut.current.set(_,Je),_};mt(()=>{let _=()=>{document.visibilityState==="visible"?K():Dn()};return document.addEventListener("visibilitychange",_),window.addEventListener("focus",K),window.addEventListener("blur",Dn),()=>{document.removeEventListener("visibilitychange",_),window.removeEventListener("focus",K),window.removeEventListener("blur",Dn),ht()}},[]),mt(()=>{xe.current!==de&&(xe.current=de,ne.current=!1,ce.current=!1,J(!1),Se(!1),Ne(!1),g.current?.("loading"))},[de]),mt(()=>{pt(()=>It.current?.(he&&!ze))},[he,ze]);let qt=bs(a);mt(()=>{let _=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",Je=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(u(`mount clientId=${_} env=${a??"(unset)"}\u2192${qt??"live"} ccy=${c} sub=${s}`),u(`ua=${Je.slice(0,80)}${Je.length>80?"\u2026":""}`),!r){u("FAIL: clientId empty \u2014 gateway misconfigured"),Ne(!0),N.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!q.current){u("FAIL: containerRef not attached");return}ae.current=N.startTiming(),N.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ee=!1,Ln=!1,Ve=()=>Ee||Ln,Kn,gn=!1,hn=()=>{Kn=Ps(),Kn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),gn=!0},tt=null,_t=!1,jt=null,Lt=!1,Xt=()=>{!jt||Lt||(Lt=!0,jt.close().catch(()=>{}))},sn=null,xn=()=>{sn!==null&&(N.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"overlay_return",durationMs:N.elapsed(sn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),sn=null)},Vt=!1,Nt=q.current,Zt=null,ve=null,ft=[],lt=T=>{if(!T||typeof T.getBoundingClientRect!="function")return"(no rect)";let m=T.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},Pn=T=>{if(!T)return"(empty)";try{let m=new URL(T,typeof window<"u"?window.location.href:"https://localhost"),P=m.pathname.toLowerCase();return P.includes("checkcaptcha")||P.includes("captcha")?`CAPTCHA(${m.host}${P})`:P.includes("risk")||P.includes("challenge")?`RISK(${m.host}${P})`:P.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${P}`.slice(0,100)}catch{return T.slice(0,80)}},Vn=T=>{let m=T.getAttribute("src"),P=T.getAttribute("srcdoc"),ue=T.getAttribute("name"),V=T.getAttribute("sandbox"),He=[];return m&&He.push(`src=${Pn(m)}`),P&&He.push(`srcdoc[${P.length}ch]`),!m&&!P&&He.push("src=(empty) srcdoc=(empty)"),ue&&He.push(`name=${ue.slice(0,40)}`),V!==null&&He.push(`sandbox="${V.slice(0,40)}"`),He.join(" ")},Ot=T=>{if(!(T instanceof HTMLIFrameElement))return"";try{let m=T.contentDocument;if(!m)return"cd=null";let P=m.body?.children.length??0,ue=m.body?.innerHTML.length??0,V=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${P}children,${ue}ch] head[${V}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},Ht=[],vt=T=>{if(Ve())return;let m=T.message??String(T.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(u(`window:error ${m.slice(0,140)}`),Ht.push(m))},rr=T=>{if(Ve())return;let m=T.reason instanceof Error?T.reason.message:String(T.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(u(`window:rejection ${m.slice(0,140)}`),Ht.push(m))};A&&typeof window<"u"&&(window.addEventListener("error",vt),window.addEventListener("unhandledrejection",rr));let Wt={value:0};if(A&&typeof PerformanceObserver<"u")try{ve=new PerformanceObserver(T=>{if(!Ve())for(let m of T.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;Wt.value+=1;let P=Math.round(m.duration);u(`net ${P}ms ${m.name.slice(0,90)}`)}}),ve.observe({type:"resource",buffered:!0})}catch{}let R=()=>{for(Zt?.disconnect(),Zt=null,ve?.disconnect(),ve=null;ft.length;)clearTimeout(ft.pop());A&&typeof window<"u"&&(window.removeEventListener("error",vt),window.removeEventListener("unhandledrejection",rr))},O=T=>{if(!T)return!1;let m=T.toLowerCase();return m.includes("zoid destroyed")||m.includes("destroyed all components")||m.includes("window closed")||m.includes("detected container element removed")},H=T=>{if(Ve()||O(T))return;let m=Nn(T)??T;pt(()=>We.current?.(m))},Z=T=>{Ee||(Ne(!0),T.includes("paypal_ineligible")||N.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",T))},se=(T,m=!1)=>{if(Ee)return;let P=ne.current||!S;if(_t)return;_t=!0,Ln=!0,R(),Xt();let ue=m||Xa(T);if(ue&&S&&!ne.current){ne.current=!0,J(!1),x(!1),Se(!0),g.current?.("retrying"),tt=setTimeout(()=>{Ee||Le(V=>V+1)},vs);return}if(ue||P){if(J(!1),x(!1),Se(!1),Ne(!0),g.current?.("exhausted"),!ce.current){ce.current=!0;let V=Xa(T)?"paypal_init_timeout":m?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",V)}return}Z(T)};Ne(!1);let L=async(T,m=et.current)=>{if(Ve())return;let P=m?.sessionId??e;if($e.current){await $e.current(T,{sessionId:P,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let ue=N.startTiming();N.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let V=()=>{N.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"processing",durationMs:N.elapsed(ue),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let He=je.current,ct=m?.accountPatch?.email??st.current,Te=m?.accountPatch?.userId??He?.customer?.id??He?.accountData?.userId??"",re=await new jo(j,{telemetry:!1}).processPayment(Te,{sessionId:P,nonce:m?.nonce??rt.current,tokenizedData:T,accountData:{userId:Te,email:ct??He?.customer?.email??"",firstName:m?.accountPatch?.firstName??He?.customer?.firstName??He?.accountData?.firstName??"",lastName:m?.accountPatch?.lastName??He?.customer?.lastName??He?.accountData?.lastName??"",country:m?.accountPatch?.country??He?.customer?.country??He?.accountData?.country??void 0,zip:m?.accountPatch?.zip??He?.customer?.zip??He?.accountData?.zip??void 0}});if(re.ok){if(Ln||Ee&&Et.current)return;V(),N.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),pt(()=>Ue.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ve())return;let Ae=await re.json().catch(()=>null),ln=Ae?.message??"PayPal payment failed.",Yt=Nn(ln)??ln;V(),re.status===400&&(typeof Ae?.declineCode=="string"||!Array.isArray(Ae?.fields))?N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):re.status===400||re.status===422?N.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):N.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:re.status>=500?"5xx":re.status>=400?"4xx":re.status>=300?"3xx":"unknown",failureCategory:re.status>=500?"server_error":void 0}),H(Yt),pt(()=>qe.current?.(wt("paypal",Yt,{code:Ae?.code,declineCode:Ae?.declineCode})));return}catch(He){if(Ve())return;V(),N.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let ct=He instanceof Error?He.message:"PayPal payment failed.",Te=Nn(ct)??ct;H(Te),pt(()=>qe.current?.(wt("paypal",Te)));return}},h=()=>new Ga("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),X=T=>Ve()?Promise.reject(h()):Promise.resolve(T),F=async T=>{if(Ve())throw h();gn||hn();let m=et.current,P=m?.sessionId??e,ue=m?.nonce??rt.current;N.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let V=await new jo(j,{telemetry:!1}).createSessionIntent(P,ue??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Kn});if(Ve())throw h();if(V.provider!=="paypal")throw new Error(T);return N.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),V.providerObjectId},le=(T,m)=>{let P=m?.nonce??rt.current;if(!P)return;let ue=m?.sessionId??e,V=mr(T)??Bn(T)??"provider_declined";new jo(j,{telemetry:!1}).reportSessionIntentDecline(ue,P,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:V}).catch(()=>{})},ge=ie;u("loadScript:scheduled (deferred 1 tick)");let I=null,Ct=setTimeout(()=>{if(Ee){u("loadScript:skipped (cancelled before defer ran)");return}u("loadScript:start");let T=qt==="live"?"production":qt;I=gs({clientId:r,currency:c,intent:s?"subscription":"capture",vault:s?!0:void 0,...T?{environment:T}:{},...T==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),I.then(m=>{if(u(`loadScript:resolved inactive=${Ve()} ns=${!!m} buttons=${!!m?.Buttons}`),Ve())return;if(!m?.Buttons){u("FAIL: namespace missing Buttons factory"),se("PayPal SDK did not expose the Buttons factory.");return}N.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let P=async Te=>{if(Ve()||_e.current!==ge)return;let ke=Te.subscriptionID??Te.orderID??"",re=ke?Ut.current.get(ke):Ke.current.get(ge);if(!(!re||!an(re.generation))&&Dt(re.generation)){Ut.current.delete(ke),Ke.current.delete(re.surfaceKey),xn();try{if(x(!0),pt(()=>We.current?.(null)),!ke)throw new Ga("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await L({id:ke,isPaypal:!0},re)}catch(Ae){H(Ae instanceof Error?Ae.message:"PayPal capture failed.")}finally{Ve()||x(!1)}}},ue=m.Buttons({style:{layout:"horizontal",height:io,tagline:!1},onClick:async(Te,ke)=>{if(Ve()){await ke.reject();return}hn();let re=Ie.current,Ae={};if(re)try{let zt=await re("paypal");if(Ve()){await ke.reject();return}if(!zt.proceed){et.current=null,Ke.current.delete(ge),await ke.reject();return}Ae={sessionId:zt.sessionId,accountPatch:zt.accountPatch,nonce:zt.nonce}}catch(zt){u(`onClick:runBeforeButtonClick rejected msg=${(zt instanceof Error?zt.message:String(zt)).slice(0,120)}`),et.current=null,Ke.current.delete(ge),await ke.reject();return}pt(()=>Pt.current?.("paypal"));let Yt={generation:$t(),surfaceKey:ge,...Ae};et.current=Yt,Ke.current.set(ge,Yt),await ke.resolve(),N.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),sn=N.startTiming()},createOrder:s?void 0:W?()=>X(W).then(fn):()=>F("Failed to create PayPal order.").then(fn),createSubscription:s?W?()=>X(W).then(fn):()=>F("Failed to create PayPal subscription.").then(fn):void 0,onApprove:P,onCancel:()=>{if(Ve())return;let Te=Ke.current.get(ge)??et.current;Te&&Ke.current.delete(Te.surfaceKey),et.current=null,xn(),N.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Pe.current=!0,Jt({generation:Te?.generation,remount:!0,focus:!1})},onError:Te=>{if(Ve()||_e.current!==ge)return;let ke=Te instanceof Error?Te.message:"PayPal failed to render.";if(u(`onError rendered=${Vt} msg=${ke.slice(0,120)}`),Vt){let re=Ke.current.get(ge)??et.current;if(re&&!an(re.generation)||!re&&bt.current===Ge.current)return;if(O(ke)){Dt(re?.generation);return}if(xn(),Nr(Te)){N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),le(Te,re),pt(()=>qe.current?.(wt("paypal",ke))),re&&Ke.current.delete(re.surfaceKey),et.current=null,Dt(re?.generation);return}let Ae=ke.toLowerCase();N.error({errorCode:Ae.includes("popup")&&Ae.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),re&&Ke.current.delete(re.surfaceKey),et.current=null,Jt({generation:re?.generation,remount:!0,showRetry:!0,focus:!0}),jn(Te,{code:"paypal_runtime_failed"});return}se(ke)}}),V=ue.isEligible();if(u(`isEligible=${V}`),N.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!V){J(!1),se("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}jt=ue,A&&u(`container:dims ${lt(Nt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),A&&typeof MutationObserver<"u"&&(Zt=new MutationObserver(Te=>{if(!Ve()){for(let ke of Te)if(ke.type==="childList")ke.addedNodes.forEach(re=>{if(!(re instanceof Element))return;let Ae=re.tagName.toLowerCase(),ln=(re.getAttribute("title")??"").slice(0,40),Yt=Ae==="iframe"?` ${Vn(re)}`:"";u(`child+ ${Ae}${ln?` title="${ln}"`:""}${Yt} dims=${lt(re)}`)});else if(ke.type==="attributes"&&ke.target instanceof Element){let re=ke.target;if(re.tagName.toLowerCase()!=="iframe")continue;let Ae=ke.attributeName;(Ae==="src"||Ae==="srcdoc")&&u(`attr~ iframe ${Ae}=${Ae==="srcdoc"?`[${(re.getAttribute("srcdoc")??"").length}ch]`:Pn(re.getAttribute("src"))} dims=${lt(re)}`)}}}),Zt.observe(Nt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ct=Te=>{if(Ve()||Vt)return;let ke=Nt.querySelectorAll("iframe"),re=typeof document<"u"&&"hasStorageAccess"in document;u(`watchdog:${Te} container=${lt(Nt)} children=${Nt.childElementCount} iframes=${ke.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${re} paypalNetRequests=${Wt.value}`),ke.forEach((Ae,ln)=>{let Yt=(Ae.getAttribute("title")??"").slice(0,40);u(` iframe[${ln}] ${lt(Ae)}${Yt?` title="${Yt}"`:""} ${Vn(Ae)}`);let zt=Ot(Ae);zt&&u(` ${zt}`)}),Ht.length===0&&u(" (no PayPal/zoid window errors captured)")};A&&(ft.push(setTimeout(()=>ct("3s"),3e3)),ft.push(setTimeout(()=>ct("8s"),8e3)),ft.push(setTimeout(()=>ct("15s"),15e3))),u("render:start"),ft.push(setTimeout(()=>{Ve()||Vt||(u("watchdog:11s retryable render timeout"),se("PayPal Buttons render did not settle within 11000ms.",!0))},Cs)),ue.render(Nt).then(()=>{if(u(`render:resolved inactive=${Ve()}`),R(),Ve()){Xt();return}Vt=!0,J(!0),Se(!1),g.current?.("ready"),N.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"provider_ready",durationMs:N.elapsed(ae.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(Te=>{let ke=Te instanceof Error?Te.message:"PayPal failed to render.";u(`render:rejected msg=${ke.slice(0,120)}`),R(),se(ke)})}).catch(m=>{let P=m instanceof Error?m.message:"PayPal SDK failed to load.";u(`loadScript:rejected msg=${P.slice(0,120)}`),se(P)})},0);return()=>{Ee=!0,clearTimeout(Ct),tt&&clearTimeout(tt),R(),Xt()}},[S,j,r,c,a,s,e,W,ie,N]);let Ft=A?Ko("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ze?"#fef2f2":"#f3f4f6",border:`1px solid ${ze?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${he} failed=${ze})`,Qe.length===0?`
7
7
  (waiting for first lifecycle event\u2026)`:`
8
- ${Je.join(`
9
- `)}`]}):null;return Ne&&!at?F?cr("div",{children:tt}):null:No("div",{children:[tt,No("div",{"aria-hidden":ue?!0:void 0,style:ue?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:no},children:[!pe&&!ue&&cr("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"}}),cr("div",{ref:V,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:no,display:"flex",opacity:pe?1:0},"aria-busy":Y||T},oe)]},oe),ve&&cr("button",{ref:Me,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:In,style:ys,children:"Try PayPal again"})]})}function ro(e){return cr(Ha,{...e})}function Ka(e){return cr(Ha,{...e})}import{FloPayError as Cn,isSetupIntentClientSecret as Ms,resolveTheme as Bs}from"@flopay/shared";import{Fragment as dr,jsx as d,jsxs as xe}from"react/jsx-runtime";var Sn="flopay_stripe_resume",Xa="flopay_wallet_resume",Dr="flopay_paypal_resume";function Ho(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function io({billingApiUrl:e,sessionId:t,nonce:n,request:i}){if(!(!t||!n))try{await new On(e,{telemetry:!1}).reportSessionIntentDecline(t,n,i)}catch{}}function As(e){return e instanceof Cn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function zo(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function oo(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 Fs=`
8
+ ${Qe.join(`
9
+ `)}`]}):null;return ze&&!it?A?yr("div",{children:Ft}):null:Ko("div",{children:[Ft,Ko("div",{"aria-hidden":fe?!0:void 0,style:fe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:io},children:[!he&&!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:q,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:io,display:"flex",opacity:he?1:0},"aria-busy":Y||E},ie)]},ie),Re&&yr("button",{ref:Fe,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:_n,style:ws,children:"Try PayPal again"})]})}function so(e){return yr(Za,{...e})}function Qa(e){return yr(Za,{...e})}import{FloPayError as wn,isSetupIntentClientSecret as Us,resolveTheme as $s}from"@flopay/shared";import{Fragment as fr,jsx as d,jsxs as Be}from"react/jsx-runtime";var kn="flopay_stripe_resume",oi="flopay_wallet_resume",zr="flopay_paypal_resume";function Zo(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function uo({billingApiUrl:e,sessionId:t,nonce:n,request:i}){if(!(!t||!n))try{await new zn(e,{telemetry:!1}).reportSessionIntentDecline(t,n,i)}catch{}}function qs(e){return e instanceof wn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ho(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function lo(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let i=parseInt(n[1],16),r=Math.max(0,Math.min(1,1-t)),a=Math.round((i>>16&255)*r),c=Math.round((i>>8&255)*r),s=Math.round((i&255)*r);return`#${(1<<24|a<<16|c<<8|s).toString(16).slice(1)}`}var js=`
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
- `,ao=44;function Ko(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 Ds={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ii={width:"100%",minHeight:ao,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 Ls(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Za(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function si(e){return e==="paypal"?"PayPal":ur(e)}function Ns(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 li(e){let t=Le(0),n=Le(null),i=Le(null),r=he((l=i.current)=>{let f=l;f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),a=he((l,f)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(l),l.timer=setTimeout(()=>{l.timer=null,i.current?.generation===l.generation&&(i.current=null,n.current=l.generation,e(l.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},f))},[r,e]),c=he(l=>{l.yieldedControl&&a(l,600)},[a]),s=he(l=>{r();let f=t.current+1;t.current=f,n.current=null;let k={generation:f,method:l,timer:null,yieldedControl:!1};return i.current=k,f},[r]),w=he(l=>{let f=i.current;return typeof l=="number"&&f?.generation!==l?!1:(r(f),i.current=null,(typeof l!="number"||n.current===l)&&(n.current=null),!0)},[r]),A=he(l=>{let f=i.current,k=l??f?.generation??t.current;(!l||f?.generation===l)&&(r(f),i.current=null),n.current=k},[r]),p=he(l=>n.current===(l??t.current),[]),I=he(l=>i.current?.generation===l&&n.current!==l,[]),C=he(()=>{let l=i.current;l&&c(l)},[c]),T=he(()=>{let l=i.current;l&&(l.yieldedControl=!0,r(l))},[r]);return pt(()=>{let l=()=>{document.visibilityState==="visible"?C():T()},f=()=>{T()};return document.addEventListener("visibilitychange",l),window.addEventListener("blur",f),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",l),window.removeEventListener("blur",f),window.removeEventListener("focus",C),r()}},[r,T,C]),{startAttempt:s,finishAttempt:w,invalidateAttempt:A,isAttemptInvalidated:p,isAttemptCurrent:I}}function Os(e){let t=ws(e);return`Enter a valid ${$o(e)}${t?` (e.g. ${t})`:""}`}function zs(e,t,n){let i=Cs(e),r=t.trim(),a=n&&i,c=a&&!r,s=a&&!!r&&!Ss(e,r);return{visible:n,supported:i,required:a,empty:c,malformed:s}}function Qa(e,t){return t instanceof Cn?t:new Cn(t instanceof Error?t.message:`${Ls(e)} before-click hook failed.`,"validation_error")}function Uo(){return d("style",{children:Fs})}function Us(e){return typeof e=="number"?`${e}px`:e}function ei(e){if(typeof e=="number"||typeof e=="string")return e}function ci(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function di({state:e,placeholderTestId:t,borderRadius:n=8,children:i}){return e==="unavailable"||e==="load_error"?null:xe("div",{style:{position:"relative",minHeight:44},children:[d("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),d("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:i})]})}function ti(e){return e!=="unavailable"&&e!=="load_error"}function Wo(e){return d(qs,{...e})}function ni({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:r,onErrorChange:a,isProcessing:c=!1,onButtonClick:s,onDecline:w,onTechnicalFailure:A,runBeforeButtonClick:p,onLoadStateChange:I,placeholderBorderRadius:C}){let T=Pn(),l=Vo(),f=jo(),[k,B]=ge("loading");pt(()=>{I?.(k)},[k,I]);let[h,q]=ge(!1),W=Le(!1),ce=Le(null),Z=Le(null),[F,J]=ge(0),[j,de]=ge(!1),z=Le(!1),V=Le(new Map),{startAttempt:re,finishAttempt:Me,invalidateAttempt:me,isAttemptInvalidated:pe,isAttemptCurrent:X}=li((R,te,ie)=>{A?.(R,te,{...ie,popupBlocked:ie?.popupBlocked??Nn(te)}),de(!0),J(Ne=>Ne+1)});pt(()=>{j&&Z.current?.focus()},[j,F]);let ue=he(()=>{J(R=>R+1)},[]),Pe=he((R,te,ie)=>{me(ie),A?.("paypal",R,{code:te,popupBlocked:Nn(R)}),de(!0),ue()},[me,A,ue]),oe=he(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);pt(()=>{z.current&&(z.current=!1,oe())},[oe,F]);let Fe=he(()=>{de(!1),a?.(null),oe()},[oe,a]);pt(()=>{if(!l||W.current)return;let R=new URLSearchParams(window.location.search),te=R.get("payment_intent"),ie=R.get("payment_intent_client_secret"),Ne=R.get("redirect_status");if(!te||!ie)return;W.current=!0;let De;try{let M=localStorage.getItem(Dr);if(M){let H=JSON.parse(M);H.clientSecret===ie&&(De={...H.accountPatch?{accountPatch:H.accountPatch}:{},...H.sessionId?{sessionId:H.sessionId}:{},...H.nonce?{nonce:H.nonce}:{}})}}catch{}try{localStorage.removeItem(Dr)}catch{}let Y=new URL(window.location.href);Y.searchParams.delete("payment_intent"),Y.searchParams.delete("payment_intent_client_secret"),Y.searchParams.delete("redirect_status"),window.history.replaceState({},"",Y.toString()),(async()=>{try{if(q(!0),Ne==="failed"){let se="PayPal payment was declined. Please try again.";a?.(se),w?.(St("paypal",se));return}let{paymentIntent:M,error:H}=await l.retrievePaymentIntent(ie);if(H){a?.(H.message??"Failed to retrieve PayPal payment status.");return}if(M&&(M.status==="requires_capture"||M.status==="succeeded")){let se=typeof M.payment_method=="string"?M.payment_method:M.payment_method?.id;r({id:se??M.id,type:"card",threeDSecureActionResultTokenId:M.id,isPaypal:!0},De)}else{let se="PayPal payment was not completed. Please try again.";a?.(se),w?.(St("paypal",se))}}catch(M){a?.(M instanceof Error?M.message:"Failed to complete PayPal payment.")}finally{q(!1)}})()},[l,r,a,w]);let ke=he(async R=>{if(c||h){R.reject();return}let te=p?await p("paypal"):{proceed:!0};if(!te.proceed){V.current.delete(F),R.reject();return}let ie=re("paypal");V.current.set(F,{generation:ie,accountPatch:te.accountPatch,sessionId:te.sessionId,nonce:te.nonce}),de(!1),s?.("paypal"),R.resolve()},[V,c,s,p,re,h,F]),ve=he(async R=>{if(!l||!f)return;let te=V.current.get(F);if(te&&!X(te.generation)){V.current.delete(F);return}if(!te&&pe()||te&&!Me(te.generation))return;te||Me();let ie=te??null;if(V.current.delete(F),!ie&&p){let M=await p("paypal");if(!M.proceed){R.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ie={accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}}let Ne=ie?.sessionId??e,De=ie?.nonce??t,Y=ie?.accountPatch?.email??n;try{if(q(!0),a?.(null),!Ne||!Y)throw new Error("Missing sessionId or email for PayPal payment");let M=l.createPaymentMethod,{error:H,paymentMethod:se}=await M({type:"paypal"});if(H){Pe(H,"stripe_paypal_create_payment_method_failed",te?.generation),R.paymentFailed({reason:"fail"});return}let Re=await new On(i).createSessionIntent(Ne,De??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:se?.id??null,intentKind:"payment"});if(Re.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let at=Re.clientSecret,Je={return_url:window.location.href};if(se?.id&&(Je.payment_method=se.id),typeof window<"u")try{localStorage.setItem(Dr,JSON.stringify({clientSecret:at,sessionId:Ne,nonce:De,accountPatch:ie?.accountPatch}))}catch{}let{error:Ge,paymentIntent:m}=await l.confirmPayment({clientSecret:at,confirmParams:Je,redirect:"if_required"});if(Ge){if(typeof window<"u")try{localStorage.removeItem(Dr)}catch{}if(Ar(Ge)){let Oe=Ge.message??"Your payment was declined.";a?.(Oe),w?.(St("paypal",Oe,{code:Bn(Ge),declineCode:lr(Ge)})),await io({billingApiUrl:i,sessionId:Ne,nonce:De,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Bn(Ge)??"provider_declined"}})}else Pe(Ge,"stripe_paypal_confirm_failed",te?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Dr)}catch{}let $e=typeof m?.payment_method=="string"?m.payment_method:m?.payment_method?.id;r({id:$e??m?.id,type:"card",threeDSecureActionResultTokenId:m?.id,isPaypal:!0},{accountPatch:ie?.accountPatch,sessionId:Ne,nonce:De});return}catch(M){Pe(M,"stripe_paypal_failed",te?.generation)}finally{q(!1)}},[l,f,e,t,n,i,r,a,w,p,Pe,Me,X,pe,F]);return xe(dr,{children:[d(di,{state:k,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[j&&d("button",{ref:Z,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Fe,style:ii,children:"Try PayPal again"}),d(ai,{onReady:R=>B(ci(R,["paypal"])),onLoadError:()=>{B("load_error"),Ho(Mt(T),"paypal","paypal")},onClick:ke,onConfirm:ve,onCancel:()=>{let R=V.current.get(F);V.current.delete(F),Mt(T)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),me(R?.generation),de(!1),z.current=!0,ue()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},F)]})}),h&&d(vn,{status:"processing"})]})}function ri({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:r,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:w,onDecline:A,onTechnicalFailure:p,runBeforeButtonClick:I,onLoadStateChange:C,placeholderBorderRadius:T}){let l=Pn(),f=Vo(),k=jo(),[B,h]=ge("loading");pt(()=>{C?.(B)},[B,C]);let[q,W]=ge(!1),ce=Le(null),Z=Le(null),[F,J]=ge(0),[j,de]=ge(!1),[z,V]=ge("google_pay"),re=Le(!1),Me=Le("google_pay"),me=Le("google_pay"),pe=Le(new Map),{startAttempt:X,finishAttempt:ue,invalidateAttempt:Pe,isAttemptInvalidated:oe,isAttemptCurrent:Fe}=li((Y,M,H)=>{p?.(Y,M,{...H,popupBlocked:H?.popupBlocked??Nn(M)}),V(Y),de(!0),J(se=>se+1)});pt(()=>{j&&Z.current?.focus()},[j,F]);let ke=he(()=>{J(Y=>Y+1)},[]),ve=he((Y,M,H,se)=>{Pe(se),p?.(Y,M,{code:H,popupBlocked:Nn(M)}),V(Y),de(!0),ke()},[Pe,p,ke]),R=he(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);pt(()=>{re.current&&(re.current=!1,R())},[R,F]);let te=he(()=>{de(!1),s?.(null),R()},[R,s]),ie=he(async Y=>{if(!f||!k)return;let M=pe.current.get(F);if(M&&!Fe(M.generation)){pe.current.delete(F);return}if(!M&&oe()||M&&!ue(M.generation))return;M||ue();let H=Y.expressPaymentType??M?.method??Me.current,se=M??null;pe.current.delete(F);let Re=Za(H);if(!se&&I){let $e=await I(Re);if(!$e.proceed){Y.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}se={accountPatch:$e.accountPatch,sessionId:$e.sessionId,nonce:$e.nonce}}let at=Re,Je=se?.sessionId??e,Ge=se?.nonce??t,m=se?.accountPatch?.email??n;try{W(!0),s?.(null);let{error:$e}=await k.submit();if($e){ve(H,$e,"stripe_wallet_submit_failed",M?.generation);return}let{error:Oe,paymentMethod:He}=await f.createPaymentMethod({elements:k});if(Oe||!He){ve(H,Oe??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",M?.generation);return}if(!Je||!m)throw new Error("Missing sessionId or email for wallet payment");let qe=await new On(i).createSessionIntent(Je,Ge??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H??Re,paymentMethodId:He.id,intentKind:r});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Gt=qe.clientSecret,{error:Pt,intentId:Rt}=Ms(Gt)?await f.confirmCardSetup(Gt,{payment_method:He.id}).then(g=>({error:g.error,intentId:g.setupIntent?.id})):await f.confirmCardPayment(Gt,{payment_method:He.id}).then(g=>({error:g.error,intentId:g.paymentIntent?.id}));if(Pt){if(Ar(Pt)){let g=Pt.message??"Your payment was declined.";s?.(g),A?.(St(at,g,{code:Bn(Pt),declineCode:lr(Pt)})),await io({billingApiUrl:i,sessionId:Je,nonce:Ge,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H??Re,providerDeclineReason:Bn(Pt)??"provider_declined"}})}else ve(H,Pt,"stripe_wallet_confirm_failed",M?.generation);return}c({id:He.id,type:"card",threeDSecureActionResultTokenId:Rt},{accountPatch:se?.accountPatch,sessionId:Je,nonce:Ge})}catch($e){ve(H,$e,"stripe_wallet_failed",M?.generation)}finally{W(!1)}},[f,k,e,t,n,i,r,c,s,A,I,ve,ue,Fe,oe,F]),Ne=rt(()=>{let Y=["applePay","googlePay","paypal","link","amazonPay","klarna"],M=new Set(["applePay","googlePay"]),H=new Set(a.map(Ja)),se={};for(let Re of Y)H.has(Re)?se[Re]=M.has(Re)?"always":"auto":se[Re]="never";return se},[a]),De=rt(()=>a.map(Ja),[a]);return xe(dr,{children:[d(di,{state:B,placeholderTestId:"flopay-wallet-placeholder",borderRadius:T,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[j&&xe("button",{ref:Z,type:"button","data-testid":"flopay-wallet-retry-button",onClick:te,style:ii,children:["Try ",si(z)," again"]}),d(ai,{onReady:Y=>{h(ci(Y,De))},onLoadError:Y=>{h("load_error"),Ho(Mt(l),"stripe","wallet")},onClick:async Y=>{Me.current=Y.expressPaymentType,me.current=Za(Y.expressPaymentType);let M=I?await I(me.current):{proceed:!0};if(!M.proceed){pe.current.delete(F),Y.reject();return}let H=X(Y.expressPaymentType);pe.current.set(F,{generation:H,method:Y.expressPaymentType,accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}),de(!1),w?.(me.current),Y.resolve()},onConfirm:ie,onCancel:()=>{let Y=pe.current.get(F);pe.current.delete(F),Mt(l)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Pe(Y?.generation),de(!1),re.current=!0,ke()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ne,layout:{maxColumns:1,overflow:"never"}}},F)]})}),q&&d(vn,{status:"processing"})]})}function $s({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:r=!1,hasNextStep:a=!1,onClick:c,backgroundColor:s,borderColor:w,textColor:A,borderRadius:p,fontFamily:I}){let C=Is(e,t),T=Da[e],l=C?.backgroundColor??s??"#ffffff",f=C?.borderColor??w??"#d1d5db",k=C?.textColor??A??"#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:ao,padding:"0 1rem",backgroundColor:l,color:k,border:`1px solid ${f}`,borderRadius:p??8,fontSize:"0.95rem",fontWeight:600,fontFamily:I,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 ${ur(e)}\u2026`}):xe(dr,{children:[xe("span",{style:{display:"inline-flex",alignItems:"center",gap:Rs(e)?8:0},children:[T?d("img",{src:T,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:ur(e)})]}),a&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:k,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 qo({method:e,sessionId:t,nonce:n,email:i,billingName:r,billingApiUrl:a,onTokenizedBody:c,onErrorChange:s,onDecline:w,onCancel:A,runBeforeButtonClick:p,onButtonClick:I,isProcessing:C,submitButtonColor:T,submitButtonBorderRadius:l,submitButtonStyle:f,errorText:k}){let B=Pn(),h=Vo(),q=jo(),[W,ce]=ge(!1),Z=Le(!1),[F,J]=ge(!1),[j,de]=ge("loading"),z=he(async()=>{if(!h||!q||C||Z.current||!F)return;Z.current=!0,ce(!0);let V=p?await p("card"):{proceed:!0};if(!V.proceed){Z.current=!1,ce(!1);return}I?.("card");let re=V.sessionId??t,Me=V.nonce??n,me=V.accountPatch?.email??i;try{s?.(null);let pe=await q.submit();if(pe.error){s?.(pe.error.message??"Payment failed.");return}let X=await h.createPaymentMethod({elements:q});if(X.error||!X.paymentMethod){s?.(X.error?.message??"Failed to create payment method.");return}let ue=X.paymentMethod;if(!re||!me)throw new Error("Missing sessionId or email for payment.");let Pe=ue.type||e,oe=await new On(a).createSessionIntent(re,Me??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Pe,paymentMethodId:null,intentKind:"payment"});if(oe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Fe=oe.clientSecret;if(typeof window<"u")try{localStorage.setItem(Sn,JSON.stringify({clientSecret:Fe,sessionId:re,nonce:Me,accountPatch:V.accountPatch,paymentMethodId:ue.id,paymentMethodType:ue.type??e,gateway:"stripe"}))}catch{}let{error:ke,paymentIntent:ve}=await h.confirmPayment({clientSecret:Fe,confirmParams:{return_url:window.location.href,payment_method:ue.id},redirect:"if_required"});if(ke){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let ie=ke.message??"Payment failed.";s?.(ie),w?.(St("card",ie,{code:ke.code})),await io({billingApiUrl:a,sessionId:re,nonce:Me,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ke.code??"provider_declined"}});return}let R=ve?.status;if(!Zr(R)){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let ie=R==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";s?.(ie),w?.(St("card",ie,{code:R??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let te=typeof ve?.payment_method=="string"?ve.payment_method:ve?.payment_method?.id;c({id:te??ue.id,type:"card",threeDSecureActionResultTokenId:ve?.id,gateway:"stripe",paymentMethodType:ue.type??e},{accountPatch:V.accountPatch,sessionId:re,nonce:Me})}catch(pe){s?.(pe instanceof Error?pe.message:"Payment failed. Please try again.")}finally{Z.current=!1,ce(!1)}},[h,q,C,F,p,I,t,n,i,a,e,c,s,w]);return xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(gs,{onReady:()=>de("ready"),onLoadError:()=>{de("load_error"),Ho(Mt(B),"stripe","apm")},onChange:V=>{J(!!V.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...i?{email:i}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{z()},disabled:!F||W||C||j!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:T,color:"white",border:"none",borderRadius:l,fontSize:"1rem",fontWeight:600,cursor:!F||W||C||j!=="ready"?"not-allowed":"pointer",opacity:!F||W||C||j!=="ready"?.5:1,transition:"opacity 120ms ease-out",...f??{}},children:W?"Processing\u2026":`Pay with ${ur(e)}`}),k&&d(ar,{margin:"0.75rem 0 0",children:k})]})}function oi({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:r,paymentElementMethods:a,stripeInstance:c,paymentElementBaseOptions:s,onTokenizedBody:w,onErrorChange:A,onButtonClick:p,onDecline:I,runBeforeButtonClick:C,onLoadStateChange:T,isProcessing:l=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:k=8,submitButtonStyle:B,buttonAppearance:h,themeId:q,onExpandApm:W,expandedApmMethod:ce}){let[Z,F]=ge(null),[J,j]=ge(null),de=Le(!1);pt(()=>{a.length>0&&c?T?.("ready"):c||T?.("loading")},[a.length,c,T]);let z=he(async X=>{if(!c||de.current||l)return;de.current=!0,j(X);let ue=C?await C("card"):{proceed:!0};if(!ue.proceed){de.current=!1,j(null);return}p?.("card");let Pe=ue.sessionId??e,oe=ue.nonce??t,Fe=ue.accountPatch?.email??n;try{if(A?.(null),!Pe||!Fe)throw new Error("Missing sessionId or email for payment.");let ke=await new On(r).createSessionIntent(Pe,oe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,paymentMethodId:null,intentKind:"payment"});if(ke.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ve=ke.clientSecret;if(typeof window<"u")try{localStorage.setItem(Sn,JSON.stringify({clientSecret:ve,sessionId:Pe,nonce:oe,accountPatch:ue.accountPatch,paymentMethodType:X,gateway:"stripe"}))}catch{}let{error:R,paymentIntent:te}=await c.confirmPayment({clientSecret:ve,confirmParams:{return_url:window.location.href,payment_method_data:{type:X,billing_details:{name:i&&i.trim().length>=3?i.trim():"FloPay Customer",...Fe?{email:Fe}:{}}}},redirect:"if_required"});if(R){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let De=R.message??"Payment failed.";A?.(De),I?.(St("card",De,{code:R.code})),await io({billingApiUrl:r,sessionId:Pe,nonce:oe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,providerDeclineReason:R.code??"provider_declined"}});return}let ie=te?.status;if(!Zr(ie)){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let De=ie==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";A?.(De),I?.(St("card",De,{code:ie??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let Ne=typeof te?.payment_method=="string"?te.payment_method:te?.payment_method?.id;w({id:Ne??te?.id,type:"card",threeDSecureActionResultTokenId:te?.id,gateway:"stripe",paymentMethodType:X},{accountPatch:ue.accountPatch,sessionId:Pe,nonce:oe})}catch(ke){A?.(ke instanceof Error?ke.message:"Payment failed. Please try again.")}finally{de.current=!1,j(null)}},[c,l,C,p,e,t,n,r,i,w,A,I]),[V,re]=ge(null),Me=W?ce??null:V,me=he(X=>{de.current||l||Me&&Me!==X||(Ga(X)?W?W(X):re(X):z(X))},[Me,l,z,W]),pe=rt(()=>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(X=>{let ue=ce===X,Pe=J===X,oe=J!==null&&J!==X||ce!=null&&ce!==X;return xe(xs.Fragment,{children:[d($s,{method:X,themeId:q,submitting:Pe,disabled:oe,highlighted:ue,hasNextStep:Ga(X),onClick:()=>me(X),backgroundColor:h?.backgroundColor,borderColor:h?.borderColor,textColor:h?.textColor,borderRadius:h?.borderRadius,fontFamily:h?.fontFamily}),!W&&V===X&&pe&&c&&d(Xn,{stripe:c,options:pe,children:d(qo,{method:X,sessionId:e,email:n,billingName:i,billingApiUrl:r,onTokenizedBody:w,onErrorChange:A,onDecline:I,onCancel:()=>re(null),runBeforeButtonClick:C,onButtonClick:p,isProcessing:l,submitButtonColor:f,submitButtonBorderRadius:k,submitButtonStyle:B})},X)]},X)})})}function qs({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,onComplete:a,onError:c,onDecline:s,onTokenizedBody:w,firstName:A,lastName:p,chv:I,className:C,isProcessing:T,error:l,onErrorChange:f,showPayPal:k=!0,showStripe:B=!0,enabledPaymentMethods:h,enabledPaymentMethodCountries:q,showApplePay:W=!0,showGooglePay:ce=!0,layout:Z="default",theme:F,buttonsTheme:J,buttonsStyles:j,appearance:de,cardButtonContent:z,cardBackButtonContent:V,cardTitleContent:re,showSecurityFooter:Me,onButtonClick:me,onBeforeButtonClick:pe,enableAVS:X,cardFieldOrder:ue,cardPreFormSlot:Pe,avsLayout:oe="row",country:Fe,zip:ke,addressLine1:ve,addressLine2:R,city:te,state:ie,onCountryChange:Ne,onZipChange:De,avsCheck:Y,checkoutType:M,checkoutLayout:H,totalAmount:se=0,currency:Re="usd",initialCardOpen:at=!1,directPaypal:Je,isSubscription:Ge=!1,session:m,debug:$e=!1}){let Oe=Pn(),He=Bo(),qe=Ts(un),Gt=Xr(),[Pt,Rt]=ge(!1),[g,Ce]=ge(null),[je,it]=ge(Fe??"US"),[et,Xe]=ge(ke??""),[We,be]=ge(ve??""),[bt,Ve]=ge(R??""),[Ot,It]=ge(te??""),[mn,Rn]=ge(ie??""),[In,qn]=ge({}),ht=Le(ke??""),zt=Le(Fe??"US"),Dt=Le(ve??""),Jt=Le(R??""),rn=Le(te??""),yn=Le(ie??""),K=rt(()=>vs(X),[X]),Fn=K!==null,fn=!!m?.vault?.html,Ut=!!m?.gateways?.pcivault,tt=fn||Ut,y=!!(B&&tt&&Oe&&e),[mt,At]=ge(()=>Z!=="buttons"||at?e??null:null),En=Z!=="buttons"||at||!!e&&mt===e,ye=rt(()=>!Oe||!y||!e||!En?null:Oe.cardCapture({sessionId:e}),[Oe,y,e,En]),Ht=rt(()=>{let o=je,v=K?_e(K.postal_code,o):!1;return zs(o,et,v)},[K,je,et]),{avsInvalid:on,invalidAvsFields:Kt}=rt(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!y||!K)return{avsInvalid:!1,invalidAvsFields:o};let v=je,U=(Q,Ye)=>_e(Q,v)&&!Ye.trim(),ne={line1:U(K.address_line_1,We),city:U(K.city,Ot),state:U(K.state,mn),zip:Ht.empty||Ht.malformed};return{avsInvalid:ne.line1||ne.city||ne.state||ne.zip,invalidAvsFields:ne}},[y,K,je,We,Ot,mn,Ht]),[an,sn]=ge(!1),[Wt,_n]=ge(!1),[$t,qt]=ge(()=>zo(m?.vault)),[Se,st]=ge(at&&tt?"card":"buttons"),[Ze,gn]=ge(null),ln=Se==="expanding"||Se==="card",vt=280,Lt=Le(null),Nt=he(o=>{Lt.current&&clearTimeout(Lt.current),Lt.current=setTimeout(()=>{Lt.current=null,o()},vt)},[vt]);pt(()=>()=>{Lt.current&&clearTimeout(Lt.current)},[]);let jn=he(()=>{At(e??null),st("expanding"),Nt(()=>st("card"))},[Nt,e]),Dn=he(()=>{st("collapsing"),Nt(()=>st("buttons"))},[Nt]),xn=he(o=>{gn(o),st("apm-expanding"),Nt(()=>st("apm-form"))},[Nt]),jt=he(()=>{st("apm-collapsing"),Nt(()=>{st("buttons"),gn(null)})},[Nt]);pt(()=>{Z==="buttons"&&at&&tt&&(At(e??null),st("card"))},[Z,at,tt,e]);let[cn,Te]=ge(null),x=Le(!1),[O,G]=ge(null),D=Le(O);pt(()=>{D.current=O},[O]);let $=n||Gt,N=l??g,u=rt(()=>Bs(F),[F]),S=rt(()=>{let o=u?.buttonsLayout??hs(J);return j?{...o,...j,cardButton:{...o.cardButton,...j.cardButton},cardFormContainer:{...o.cardFormContainer,...j.cardFormContainer},backButton:{...o.backButton,...j.backButton},backButtonIcon:{...o.backButtonIcon,...j.backButtonIcon},submitButton:{...o.submitButton,...j.submitButton},title:{...o.title,...j.title}}:o},[u,J,j]),fe=de??u?.appearance,nt=rt(()=>{let o=fe?.variables,v=Ye=>typeof Ye=="string"&&Ye?Ye:void 0,U=S.submitButton,ne=v(o?.colorPrimary)??v(U?.backgroundColor)??"#4A49FF",L=Z==="buttons",Q=S.nameInput;return{primaryColor:ne,primaryHoverColor:v(o?.colorPrimaryHover)??oo(ne,.12),inputBackgroundColor:v(S.cardInputBackground)??v(o?.colorBackground)??"#ffffff",textColor:v(S.cardInputColor)??v(Q?.color)??v(o?.colorText)??"#262833",borderColor:v(S.cardInputBorder)??(L?"#e5e7eb":"#A4A4FF"),placeholderColor:v(S.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(o?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(Q?.fontFamily)??v(o?.fontFamily)??"Poppins, sans-serif",fontSize:v(S.cardInputFontSize)??v(o?.fontSizeBase)??"16px",fontWeight:String(ei(Q?.fontWeight)??400),borderRadius:v(o?.borderRadius)??"8px"}},[fe,S,Z]),ze=qe.inlineSessionPatchProcessing??!1,Ee=(T??Pt)||ze,Ft=$.replace(/\/+$/,""),P=rt(()=>Do({userId:r,email:i,firstName:A,lastName:p,country:Fe,zip:ke},In),[r,i,A,p,Fe,ke,In]),b=[P.firstName,P.lastName].filter(o=>!!o?.trim()).join(" "),_=rt(()=>Oe?Oe.getRawProvider():null,[Oe]),le=rt(()=>He?He.getRawProvider():null,[He]),we=se||100,Be=rt(()=>fe?_s(fe):null,[fe]),Yt=Be?{appearance:Be}:null,Ue=rt(()=>{let o=Be??{},v=o.rules??{};return{...o,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[Be]),Ie=rt(()=>{let o=za(se);return{...o,currency:Re.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...Yt}},[se,Re,Yt]),ae=rt(()=>({mode:"payment",amount:we,currency:Re.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Yt}),[we,Re,Yt]),E=he(o=>{Ce(o),f?.(o)},[f]);pt(()=>{!y||!ye||ye.setCardFieldOrder?.(ue??null,K==null)},[y,ye,ue,K]),pt(()=>{(Se==="expanding"||Se==="collapsing"||Se==="apm-expanding"||Se==="apm-collapsing")&&E(null)},[Se,E]);let yt=he((o,v,U)=>{s?.(St(o,v,U))},[s]),Et=he((o,v,U)=>{let ne=U?.popupBlocked??Nn(v),L=Ns(o,ne),Q=Gn(U?.code)??Bn(v)??"external_payment_method_failed",Ye=new Cn(L,"api_error",{code:"external_payment_method_failed",param:o});Te(null),Z==="buttons"&&(st("buttons"),gn(null)),E(L),c?.(Ye),console.error("[FloPay] External payment method failed:",{method:o,code:Q,popupBlocked:ne})},[Z,c,E]);pt(()=>{if(!y||!e){qt(null);return}let o=zo(m?.vault);if(o){qt(o);return}qt(null);let v=!0;return new On(Ft).getVaultCapture(e,t).then(U=>{if(!v)return;let ne=zo(U);ne?qt(ne):E("Failed to load the secure card form.")}).catch(U=>{v&&E(U instanceof Error?U.message:"Failed to load the secure card form.")}),()=>{v=!1}},[y,e,m?.vault?.html,m?.vault?.messageToken,m?.vault?.expectedOrigin,Ft,t,E]);let ft=Le({onComplete:a,onError:c,updateError:E,emitDecline:yt,resolvedAccount:P,avsConfig:K,avsCheckProp:Y,sessionId:e,nonce:t,baseUrl:Ft});ft.current={onComplete:a,onError:c,updateError:E,emitDecline:yt,resolvedAccount:P,avsConfig:K,avsCheckProp:Y,sessionId:e,nonce:t,baseUrl:Ft};let go=Le(!1),Ii=he(()=>{let{resolvedAccount:o,avsConfig:v,avsCheckProp:U}=ft.current,ne=zt.current||o.country||"US",L=v?_e(v.state,ne):!1,Q=v?_e(v.address_line_1,ne):!1,Ye=v?_e(v.postal_code,ne):!1,Ct=v?_e(v.city,ne):!1,_t=v?_e(v.address_line_2,ne):!1,Qe=Q&&!L&&Ye?Ya(ne,(ht.current??"").trim()):null,xt=L?yn.current:Qe;return{accountData:{userId:o.userId??"",email:o.email??"",firstName:o.firstName??"",lastName:o.lastName??"",...Ye&&ht.current?{zip:ht.current}:{},...Ct&&rn.current?{city:rn.current}:{},...xt?{state:xt}:{},...Q&&Dt.current?{addressLine1:Dt.current}:{},..._t&&Jt.current?{addressLine2:Jt.current}:{},country:ne},...U!==void 0?{avsCheck:U}:{},...v?{avsConfig:{country:_e(v.country,ne),postal_code:Ye,address_line_1:Q,address_line_2:_t,city:Ct,state:L}}:{}}},[]);pt(()=>{!y||!ye||ye.setSubmitGate?.(on)},[y,ye,on]),pt(()=>{if(!y||!ye)return;go.current=!1;let o=!1,v=ye.on("submitting",()=>{sn(!0),Te("processing");let{baseUrl:Q,sessionId:Ye,nonce:Ct,updateError:_t,onError:Qe}=ft.current;!Ye||!Ct||new On(Q).patchAccountSnapshot(Ye,Ct,Ii(),{telemetryMode:"best_effort"}).catch(xt=>{if(!As(xt))return;let Ae=xt instanceof Error?xt.message:"Please check your billing address and try again.";_t(Ae),Te(null),Qe?.(xt instanceof Cn?xt:new Cn(Ae,"api_error"))})}),U=ye.on("complete",async Q=>{sr(Q.sessionId??ft.current.sessionId),Te("success"),await new Promise(Ye=>setTimeout(Ye,Mn)),!go.current&&(go.current=!0,ft.current.onComplete?.({status:"succeeded",paymentIntentId:Q.intentId,checkoutMethod:"card"}))}),ne=ye.on("decline",async Q=>{let{updateError:Ye,emitDecline:Ct}=ft.current,_t=Q.message??"Your payment was declined. Please try another card or contact your bank.";Ye(_t),Te("error"),Ct("card",_t,Q.declineReason?{declineCode:Q.declineReason}:void 0),await new Promise(Qe=>setTimeout(Qe,bn)),!o&&Te(null)}),L=ye.on("error",async Q=>{let{updateError:Ye,onError:Ct}=ft.current,_t=Q.message??"There was a problem processing your payment. Please try again.";Ye(_t),Te("error"),Ct?.(new Cn(_t,"api_error")),await new Promise(Qe=>setTimeout(Qe,bn)),!o&&Te(null)});return()=>{o=!0,v(),U(),ne(),L()}},[y,ye]);let hn=!!Je?.clientId,br=Array.isArray(h),zr=br&&h.length>0,Ei=br&&h.includes("paypal"),{expressMethods:Ur,paymentElementMethods:vr}=rt(()=>Es(h,{excludePaypal:hn}),[h,hn]),aa=hn||!!He,_i=rt(()=>aa?Ur.filter(o=>o!=="paypal"):Ur,[Ur,aa]),xi=rt(()=>{let o=[];return W&&o.push("apple_pay"),ce&&o.push("google_pay"),o},[W,ce]),$r=br?_i:xi,Ti=B&&$r.length>0,ho=Fn?je:Fe,qr=rt(()=>{let o=ho?.trim().toUpperCase();return o?q?vr.filter(v=>{let U=q[v];return!U||U.length===0||U.includes(o)}):ks(vr,ho):vr},[vr,ho,q]),Po=rt(()=>({mode:"payment",amount:we,currency:Re.toLowerCase(),paymentMethodCreation:"manual",appearance:Ue}),[we,Re,Ue]),[ia,sa]=ge("loading"),[la,ca]=ge("loading"),[da,ua]=ge("loading"),[Mi,bo]=ge(!1),[pa,vo]=ge("loading"),[jr,Bi]=ge();pt(()=>{Bi($a())},[]);let ma=k&&(hn||(br?Ei:jr===!1)),ya=B&&Ti,Cr=ma&&hn,fa=pa==="retrying"||pa==="exhausted",Sr=ma&&!!le&&(!hn||fa),wr=ya&&!!_,kr=B&&zr&&qr.length>0&&!!_,Ai=Cr&&!fa?Mi:Sr&&ti(ia),Fi=wr&&ti(la),Di=kr&&da!=="load_error",ga=o=>o==="loading"||o==="ready",ha=Cr||Sr&&ga(ia)||wr&&ga(la)||kr&&da!=="load_error",Vr=Le(!1);pt(()=>{if(!Vr.current){if(!B&&!k){Vr.current=!0;let o=new Cn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(o),E(o.message)}else if(!B&&k&&!hn&&!le){Vr.current=!0;let o=new Cn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(o),E(o.message)}else if(jr!==void 0&&!tt&&!ha){Vr.current=!0;let o=new Cn("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});c?.(o),E(o.message)}}},[B,k,hn,le,jr,tt,ha,c,E]);let Pa=Le(!1);pt(()=>{if(Pa.current||!zr)return;let o=[];W!==!0&&o.push("showApplePay"),ce!==!0&&o.push("showGooglePay"),o.length!==0&&(Pa.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.`))},[zr,W,ce]);let ba=he((o,v)=>qe.applyInlineSessionPatch?qe.applyInlineSessionPatch(o).then(U=>({error:null,sessionId:U.sessionId||e,nonce:U.session?.clientSecret||t})).catch(U=>{let ne=Qa(v,U);return E(ne.message),c?.(ne),{error:ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[qe.applyInlineSessionPatch,t,c,e,E]),dn=he(async o=>{if(!pe)return{proceed:!0};try{let v=await pe({method:o,sessionId:e||void 0,createSession:qe.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&qn(ne=>({...ne??{},...v.account}));let U=await ba(v,o);return U.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:U.sessionId,nonce:U.nonce}}return{proceed:!0}}catch(v){let U=Qa(o,v);return E(U.message),c?.(U),{proceed:!1}}},[ba,qe.inlineSessionDraft,pe,c,e,E]),va=he(async(o,v)=>{if(x.current)return;x.current=!0,Rt(!0),Te("processing"),E(null);let U=v?.sessionId??e,ne=v?.nonce??t,L=Do(P,v?.accountPatch),Q=v?.completionPaymentMethodId??Qr(o),Ye=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o;try{let _t=await new On(Ft).processPayment(L.userId??"",{sessionId:U,nonce:ne,tokenizedData:Ye,accountData:{userId:L.userId??"",email:L.email??"",firstName:L.firstName??"",lastName:L.lastName??"",...K?(()=>{let Ae=zt.current,Zt=_e(K.state,Ae),Qt=_e(K.address_line_1,Ae),Wn=_e(K.postal_code,Ae),Yn=Qt&&!Zt&&Wn?Ya(Ae,(ht.current??"").trim()):null,Tt=Zt?yn.current:Yn;return{country:Ae,...Wn&&ht.current?{zip:ht.current}:{},..._e(K.city,Ae)&&rn.current?{city:rn.current}:{},...Tt?{state:Tt}:{},...Qt&&Dt.current?{addressLine1:Dt.current}:{},..._e(K.address_line_2,Ae)&&Jt.current?{addressLine2:Jt.current}:{}}})():{}},chv:I,avsCheck:Y??!1,checkoutType:M,checkoutLayout:H,avsConfig:K?{country:_e(K.country,zt.current),postal_code:_e(K.postal_code,zt.current),address_line_1:_e(K.address_line_1,zt.current),address_line_2:_e(K.address_line_2,zt.current),city:_e(K.city,zt.current),state:_e(K.state,zt.current)}:void 0});if(_t.ok){sr(U),Te("success"),G(null),await new Promise(Ae=>setTimeout(Ae,Mn)),a?.({status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:Q,checkoutMethod:o.isPaypal?"paypal":"card"});return}let Qe=await _t.json().catch(()=>null);if(Qe?.type==="paypal_redirect_required"){let Ae=Qe.threeDSecureToken,Zt=Qe.paymentMethodId||o.id||"";if(!Oe||!Ae){Te("error"),E("PayPal authorization required but no token provided.");return}try{let Qt=He?.getRawProvider();if(!Qt){E("PayPal is not available.");return}let Wn={return_url:window.location.href};Zt&&(Wn.payment_method=Zt);let{error:Yn}=await Qt.confirmPayment({clientSecret:Ae,confirmParams:Wn,redirect:"if_required"});if(Yn){Te("error");let Tt=Yn.message??"PayPal payment failed.";E(Tt),yt("paypal",Tt,{code:Yn.code})}}catch(Qt){Te("error"),E(Qt instanceof Error?Qt.message:"PayPal authorization failed.")}return}if(Qe?.type==="paypal_direct_required"){let Ae=Qe.orderId;if(!Ae){Te("error"),E("PayPal retry required but no order id provided.");return}let Zt=D.current?.attempts??0;if(Zt>=2){Te("error"),E("PayPal payment could not be completed after multiple attempts."),yt("paypal","paypal_direct_required retry limit exceeded");return}bo(!1),vo("loading"),G({orderId:Ae,attempts:Zt+1}),Te(null);return}Te("error");let xt=Qe?.message??"Payment failed. Please try again.";E(xt),yt(o.isPaypal?"paypal":"card",xt,{code:Qe?.code??Qe?.gatewayErrorCode,declineCode:Qe?.declineCode??Qe?.gatewayDeclineReason}),await new Promise(Ae=>setTimeout(Ae,bn))}catch(Ct){Te("error"),E(Ct instanceof Error?Ct.message:"An unexpected error occurred"),await new Promise(_t=>setTimeout(_t,bn))}finally{Rt(!1),Te(null),x.current=!1}},[Ft,e,t,P,b,I,Oe,He,a,c,E,yt]),Xt=he((o,v)=>{w?w(o):va(o,v)},[w,va]),Ca=Le(!1);pt(()=>{if(typeof window>"u"||Ca.current)return;let o=new URLSearchParams(window.location.search),v=o.get("payment_intent"),U=o.get("payment_intent_client_secret"),ne=o.get("redirect_status");if(!v||!U)return;let L=xt=>{let Ae=localStorage.getItem(xt);if(!Ae)return null;try{return JSON.parse(Ae)}catch{return localStorage.removeItem(xt),null}},Q=L(Sn)??L(Xa),Ye;if(Q?.clientSecret){if(Q.clientSecret!==U)return;Ye={...Q.accountPatch?{accountPatch:Q.accountPatch}:{},...Q.sessionId?{sessionId:Q.sessionId}:{},...Q.nonce?{nonce:Q.nonce}:{}}}else if(Q?.sessionId&&Q.sessionId!==e)return;Ca.current=!0,localStorage.removeItem(Sn),localStorage.removeItem(Xa);let Ct=new URL(window.location.href);Ct.searchParams.delete("payment_intent"),Ct.searchParams.delete("payment_intent_client_secret"),Ct.searchParams.delete("redirect_status"),window.history.replaceState({},"",Ct.toString());let _t=Q?.paymentMethodType??Q?.tokenType??"card",Qe="card";(async()=>{let xt=Oe?.getRawProvider();if(!xt){let Tt="Payment is not available \u2014 please refresh and try again.";E(Tt),yt(Qe,Tt);return}if(ne==="failed"){let Tt="Payment was declined. Please try again.";E(Tt),yt(Qe,Tt);return}let{paymentIntent:Ae,error:Zt}=await xt.retrievePaymentIntent(U);if(Zt){let Tt=Zt.message??"Failed to retrieve payment status.";E(Tt),yt(Qe,Tt,{code:Zt.code});return}let Qt=Ae?.status,Wn=Zr(Qt);if(!Ae||!Wn){let Tt=Qt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";E(Tt),yt(Qe,Tt,{code:Qt??"missing_payment_intent"});return}let Yn=typeof Ae.payment_method=="string"?Ae.payment_method:Ae.payment_method?.id;Xt({id:Yn??Q?.paymentMethodId??Q?.tokenId??Ae.id,type:"card",threeDSecureActionResultTokenId:Ae.id,gateway:Q?.gateway??"stripe",paymentMethodType:_t},Ye)})()},[e,Xt,Oe,E,yt]);let Co=he(o=>{o.preventDefault()},[]);if(!(Oe!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Rr=Z==="buttons",Vt=fe?.variables,Li=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),So=Vt?.colorBackground,Ni=So&&!Li.has(So)?So:void 0,Ir=S.cardInputBorder??(Rr?"#e5e7eb":"#A4A4FF"),wo=Vt?.colorDanger??"#dc2626",Vn=o=>an&&o?wo:Ir,Hr=(Ht.malformed||Ht.empty)&&(Wt||an),Oi=Hr?wo:Vn(Kt.zip),ko=S.cardFormContainer?.backgroundColor??Ni??(Rr?"white":"#EDEDFF"),Er=S.cardInputBackground??Vt?.colorBackground??"white",Ro=tr(V),Sa=tr(re),er=S.nameInput,wa=S.cardInputFontSize??Us(er?.fontSize)??Vt?.fontSizeBase??"16px",ka=typeof er?.fontFamily=="string"?er.fontFamily:Vt?.fontFamily??"Poppins, sans-serif",Ra=ei(er?.fontWeight)??400,zi=S.cardInputColor??(typeof er?.color=="string"?er.color:void 0)??Vt?.colorText??"#262833",Ui=S.cardInputPlaceholderColor??"#9ca3af",gt=Vt?.borderRadius??"8px",Hn=Vt?.borderRadius??S.cardButton?.borderRadius??gt,Kn=Vt?.colorPrimary??"#4A49FF",$i=Vt?.colorPrimaryHover??oo(Kn,.12),Io=Vt?.colorText??"#262833",Ia={fontSize:wa,fontFamily:ka,fontWeight:Ra,color:zi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},qi={"--flopay-input-placeholder-color":Ui,"--flopay-input-font-size":wa,"--flopay-input-font-family":ka,"--flopay-input-font-weight":String(Ra)},_r=S.cardFormContainer??{},Eo=_r.padding??(Rr?"0":"1rem"),_o=_r.borderRadius??gt,ji=ye&&$t?d(Mo,{capture:ye,html:$t.html,messageToken:$t.messageToken,expectedOrigin:$t.expectedOrigin,theme:nt,onReady:()=>{if(!K||typeof document>"u")return;let o=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};o();let v=0,U=window.setInterval(()=>{v+=1;let ne=document.activeElement;!!ne&&ne.tagName==="IFRAME"&&ne.id==="flopay_vault_form_iframe"?(o(),window.clearInterval(U)):v>=50&&window.clearInterval(U)},100)},onError:o=>E(o),onValidation:o=>{E(o),o&&Te(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"}),Ea=xe("div",{style:{backgroundColor:ko,borderRadius:_o,..._r,padding:Eo,...qi,display:"flex",flexDirection:"column"},children:[d("style",{children:`
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=Oe(0),n=Oe(null),i=Oe(null),r=Ce((l=i.current)=>{let y=l;y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),a=Ce((l,y)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(l),l.timer=setTimeout(()=>{l.timer=null,i.current?.generation===l.generation&&(i.current=null,n.current=l.generation,e(l.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},y))},[r,e]),c=Ce(l=>{l.yieldedControl&&a(l,600)},[a]),s=Ce(l=>{r();let y=t.current+1;t.current=y,n.current=null;let S={generation:y,method:l,timer:null,yieldedControl:!1};return i.current=S,y},[r]),C=Ce(l=>{let y=i.current;return typeof l=="number"&&y?.generation!==l?!1:(r(y),i.current=null,(typeof l!="number"||n.current===l)&&(n.current=null),!0)},[r]),B=Ce(l=>{let y=i.current,S=l??y?.generation??t.current;(!l||y?.generation===l)&&(r(y),i.current=null),n.current=S},[r]),p=Ce(l=>n.current===(l??t.current),[]),k=Ce(l=>i.current?.generation===l&&n.current!==l,[]),v=Ce(()=>{let l=i.current;l&&c(l)},[c]),E=Ce(()=>{let l=i.current;l&&(l.yieldedControl=!0,r(l))},[r]);return yt(()=>{let l=()=>{document.visibilityState==="visible"?v():E()},y=()=>{E()};return document.addEventListener("visibilitychange",l),window.addEventListener("blur",y),window.addEventListener("focus",v),()=>{document.removeEventListener("visibilitychange",l),window.removeEventListener("blur",y),window.removeEventListener("focus",v),r()}},[r,E,v]),{startAttempt:s,finishAttempt:C,invalidateAttempt:B,isAttemptInvalidated:p,isAttemptCurrent:k}}function Ws(e){let t=Bs(e);return`Enter a valid ${Yo(e)}${t?` (e.g. ${t})`:""}`}function Ys(e,t,n){let i=Ts(e),r=t.trim(),a=n&&i,c=a&&!r,s=a&&!!r&&!Ms(e,r);return{visible:n,supported:i,required:a,empty:c,malformed:s}}function ii(e,t){return t instanceof wn?t:new wn(t instanceof Error?t.message:`${Vs(e)} before-click hook failed.`,"validation_error")}function Wo(){return d("style",{children:js})}function Gs(e){return typeof e=="number"?`${e}px`:e}function si(e){if(typeof e=="number"||typeof e=="string")return e}function gi(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function hi({state:e,placeholderTestId:t,borderRadius:n=8,children:i}){return e==="unavailable"||e==="load_error"?null:Be("div",{style:{position:"relative",minHeight:44},children:[d("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),d("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:i})]})}function li(e){return e!=="unavailable"&&e!=="load_error"}function ea(e){return d(Xs,{...e})}function ci({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:r,onErrorChange:a,isProcessing:c=!1,onButtonClick:s,onDecline:C,onTechnicalFailure:B,runBeforeButtonClick:p,onLoadStateChange:k,placeholderBorderRadius:v}){let E=vn(),l=Xo(),y=Jo(),[S,M]=be("loading");yt(()=>{k?.(S)},[S,k]);let[f,U]=be(!1),W=Oe(!1),me=Oe(null),Q=Oe(null),[A,G]=be(0),[$,ye]=be(!1),N=Oe(!1),q=Oe(new Map),{startAttempt:ae,finishAttempt:Fe,invalidateAttempt:Pe,isAttemptInvalidated:he,isAttemptCurrent:J}=fi((w,ne,ce)=>{B?.(w,ne,{...ce,popupBlocked:ce?.popupBlocked??On(ne)}),ye(!0),G(ze=>ze+1)});yt(()=>{$&&Q.current?.focus()},[$,A]);let fe=Ce(()=>{G(w=>w+1)},[]),Se=Ce((w,ne,ce)=>{Pe(ce),B?.("paypal",w,{code:ne,popupBlocked:On(w)}),ye(!0),fe()},[Pe,B,fe]),ie=Ce(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);yt(()=>{N.current&&(N.current=!1,ie())},[ie,A]);let Le=Ce(()=>{ye(!1),a?.(null),ie()},[ie,a]);yt(()=>{if(!l||W.current)return;let w=new URLSearchParams(window.location.search),ne=w.get("payment_intent"),ce=w.get("payment_intent_client_secret"),ze=w.get("redirect_status");if(!ne||!ce)return;W.current=!0;let Ne;try{let x=localStorage.getItem(zr);if(x){let j=JSON.parse(x);j.clientSecret===ce&&(Ne={...j.accountPatch?{accountPatch:j.accountPatch}:{},...j.sessionId?{sessionId:j.sessionId}:{},...j.nonce?{nonce:j.nonce}:{}})}}catch{}try{localStorage.removeItem(zr)}catch{}let Y=new URL(window.location.href);Y.searchParams.delete("payment_intent"),Y.searchParams.delete("payment_intent_client_secret"),Y.searchParams.delete("redirect_status"),window.history.replaceState({},"",Y.toString()),(async()=>{try{if(U(!0),ze==="failed"){let de="PayPal payment was declined. Please try again.";a?.(de),C?.(wt("paypal",de));return}let{paymentIntent:x,error:j}=await l.retrievePaymentIntent(ce);if(j){a?.(j.message??"Failed to retrieve PayPal payment status.");return}if(x&&(x.status==="requires_capture"||x.status==="succeeded")){let de=typeof x.payment_method=="string"?x.payment_method:x.payment_method?.id;r({id:de??x.id,type:"card",threeDSecureActionResultTokenId:x.id,isPaypal:!0},Ne)}else{let de="PayPal payment was not completed. Please try again.";a?.(de),C?.(wt("paypal",de))}}catch(x){a?.(x instanceof Error?x.message:"Failed to complete PayPal payment.")}finally{U(!1)}})()},[l,r,a,C]);let _e=Ce(async w=>{if(c||f){w.reject();return}let ne=p?await p("paypal"):{proceed:!0};if(!ne.proceed){q.current.delete(A),w.reject();return}let ce=ae("paypal");q.current.set(A,{generation:ce,accountPatch:ne.accountPatch,sessionId:ne.sessionId,nonce:ne.nonce}),ye(!1),s?.("paypal"),w.resolve()},[q,c,s,p,ae,f,A]),Re=Ce(async w=>{if(!l||!y)return;let ne=q.current.get(A);if(ne&&!J(ne.generation)){q.current.delete(A);return}if(!ne&&he()||ne&&!Fe(ne.generation))return;ne||Fe();let ce=ne??null;if(q.current.delete(A),!ce&&p){let x=await p("paypal");if(!x.proceed){w.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ce={accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}}let ze=ce?.sessionId??e,Ne=ce?.nonce??t,Y=ce?.accountPatch?.email??n;try{if(U(!0),a?.(null),!ze||!Y)throw new Error("Missing sessionId or email for PayPal payment");let x=l.createPaymentMethod,{error:j,paymentMethod:de}=await x({type:"paypal"});if(j){Se(j,"stripe_paypal_create_payment_method_failed",ne?.generation),w.paymentFailed({reason:"fail"});return}let xe=await new zn(i).createSessionIntent(ze,Ne??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:de?.id??null,intentKind:"payment"});if(xe.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let it=xe.clientSecret,Qe={return_url:window.location.href};if(de?.id&&(Qe.payment_method=de.id),typeof window<"u")try{localStorage.setItem(zr,JSON.stringify({clientSecret:it,sessionId:ze,nonce:Ne,accountPatch:ce?.accountPatch}))}catch{}let{error:Ze,paymentIntent:u}=await l.confirmPayment({clientSecret:it,confirmParams:Qe,redirect:"if_required"});if(Ze){if(typeof window<"u")try{localStorage.removeItem(zr)}catch{}if(Nr(Ze)){let Ue=Ze.message??"Your payment was declined.";a?.(Ue),C?.(wt("paypal",Ue,{code:Bn(Ze),declineCode:mr(Ze)})),await uo({billingApiUrl:i,sessionId:ze,nonce:Ne,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Bn(Ze)??"provider_declined"}})}else Se(Ze,"stripe_paypal_confirm_failed",ne?.generation);return}if(typeof window<"u")try{localStorage.removeItem(zr)}catch{}let $e=typeof u?.payment_method=="string"?u.payment_method:u?.payment_method?.id;r({id:$e??u?.id,type:"card",threeDSecureActionResultTokenId:u?.id,isPaypal:!0},{accountPatch:ce?.accountPatch,sessionId:ze,nonce:Ne});return}catch(x){Se(x,"stripe_paypal_failed",ne?.generation)}finally{U(!1)}},[l,y,e,t,n,i,r,a,C,p,Se,Fe,J,he,A]);return Be(fr,{children:[d(hi,{state:S,placeholderTestId:"flopay-paypal-placeholder",borderRadius:v,children:Be("div",{ref:me,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[$&&d("button",{ref:Q,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Le,style:mi,children:"Try PayPal again"}),d(pi,{onReady:w=>M(gi(w,["paypal"])),onLoadError:()=>{M("load_error"),Zo(Bt(E),"paypal","paypal")},onClick:_e,onConfirm:Re,onCancel:()=>{let w=q.current.get(A);q.current.delete(A),Bt(E)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Pe(w?.generation),ye(!1),N.current=!0,fe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},A)]})}),f&&d(Sn,{status:"processing"})]})}function di({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:r,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:C,onDecline:B,onTechnicalFailure:p,runBeforeButtonClick:k,onLoadStateChange:v,placeholderBorderRadius:E}){let l=vn(),y=Xo(),S=Jo(),[M,f]=be("loading");yt(()=>{v?.(M)},[M,v]);let[U,W]=be(!1),me=Oe(null),Q=Oe(null),[A,G]=be(0),[$,ye]=be(!1),[N,q]=be("google_pay"),ae=Oe(!1),Fe=Oe("google_pay"),Pe=Oe("google_pay"),he=Oe(new Map),{startAttempt:J,finishAttempt:fe,invalidateAttempt:Se,isAttemptInvalidated:ie,isAttemptCurrent:Le}=fi((Y,x,j)=>{p?.(Y,x,{...j,popupBlocked:j?.popupBlocked??On(x)}),q(Y),ye(!0),G(de=>de+1)});yt(()=>{$&&Q.current?.focus()},[$,A]);let _e=Ce(()=>{G(Y=>Y+1)},[]),Re=Ce((Y,x,j,de)=>{Se(de),p?.(Y,x,{code:j,popupBlocked:On(x)}),q(Y),ye(!0),_e()},[Se,p,_e]),w=Ce(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);yt(()=>{ae.current&&(ae.current=!1,w())},[w,A]);let ne=Ce(()=>{ye(!1),s?.(null),w()},[w,s]),ce=Ce(async Y=>{if(!y||!S)return;let x=he.current.get(A);if(x&&!Le(x.generation)){he.current.delete(A);return}if(!x&&ie()||x&&!fe(x.generation))return;x||fe();let j=Y.expressPaymentType??x?.method??Fe.current,de=x??null;he.current.delete(A);let xe=ai(j);if(!de&&k){let $e=await k(xe);if(!$e.proceed){Y.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}de={accountPatch:$e.accountPatch,sessionId:$e.sessionId,nonce:$e.nonce}}let it=xe,Qe=de?.sessionId??e,Ze=de?.nonce??t,u=de?.accountPatch?.email??n;try{W(!0),s?.(null);let{error:$e}=await S.submit();if($e){Re(j,$e,"stripe_wallet_submit_failed",x?.generation);return}let{error:Ue,paymentMethod:We}=await y.createPaymentMethod({elements:S});if(Ue||!We){Re(j,Ue??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",x?.generation);return}if(!Qe||!u)throw new Error("Missing sessionId or email for wallet payment");let qe=await new zn(i).createSessionIntent(Qe,Ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:j??xe,paymentMethodId:We.id,intentKind:r});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Gt=qe.clientSecret,{error:Pt,intentId:It}=Us(Gt)?await y.confirmCardSetup(Gt,{payment_method:We.id}).then(g=>({error:g.error,intentId:g.setupIntent?.id})):await y.confirmCardPayment(Gt,{payment_method:We.id}).then(g=>({error:g.error,intentId:g.paymentIntent?.id}));if(Pt){if(Nr(Pt)){let g=Pt.message??"Your payment was declined.";s?.(g),B?.(wt(it,g,{code:Bn(Pt),declineCode:mr(Pt)})),await uo({billingApiUrl:i,sessionId:Qe,nonce:Ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:j??xe,providerDeclineReason:Bn(Pt)??"provider_declined"}})}else Re(j,Pt,"stripe_wallet_confirm_failed",x?.generation);return}c({id:We.id,type:"card",threeDSecureActionResultTokenId:It},{accountPatch:de?.accountPatch,sessionId:Qe,nonce:Ze})}catch($e){Re(j,$e,"stripe_wallet_failed",x?.generation)}finally{W(!1)}},[y,S,e,t,n,i,r,c,s,B,k,Re,fe,Le,ie,A]),ze=ot(()=>{let Y=["applePay","googlePay","paypal","link","amazonPay","klarna"],x=new Set(["applePay","googlePay"]),j=new Set(a.map(ri)),de={};for(let xe of Y)j.has(xe)?de[xe]=x.has(xe)?"always":"auto":de[xe]="never";return de},[a]),Ne=ot(()=>a.map(ri),[a]);return Be(fr,{children:[d(hi,{state:M,placeholderTestId:"flopay-wallet-placeholder",borderRadius:E,children:Be("div",{ref:me,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[$&&Be("button",{ref:Q,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ne,style:mi,children:["Try ",yi(N)," again"]}),d(pi,{onReady:Y=>{f(gi(Y,Ne))},onLoadError:Y=>{f("load_error"),Zo(Bt(l),"stripe","wallet")},onClick:async Y=>{Fe.current=Y.expressPaymentType,Pe.current=ai(Y.expressPaymentType);let x=k?await k(Pe.current):{proceed:!0};if(!x.proceed){he.current.delete(A),Y.reject();return}let j=J(Y.expressPaymentType);he.current.set(A,{generation:j,method:Y.expressPaymentType,accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}),ye(!1),C?.(Pe.current),Y.resolve()},onConfirm:ce,onCancel:()=>{let Y=he.current.get(A);he.current.delete(A),Bt(l)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Se(Y?.generation),ye(!1),ae.current=!0,_e()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ze,layout:{maxColumns:1,overflow:"never"}}},A)]})}),U&&d(Sn,{status:"processing"})]})}function Js({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:r=!1,hasNextStep:a=!1,onClick:c,backgroundColor:s,borderColor:C,textColor:B,borderRadius:p,fontFamily:k}){let v=Ds(e,t),E=ja[e],l=v?.backgroundColor??s??"#ffffff",y=v?.borderColor??C??"#d1d5db",S=v?.textColor??B??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!i&&c()},disabled:n||i,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:co,padding:"0 1rem",backgroundColor:l,color:S,border:`1px solid ${y}`,borderRadius:p??8,fontSize:"0.95rem",fontWeight:600,fontFamily:k,cursor:n||i?"not-allowed":"pointer",opacity:i&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:r?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?d("span",{style:{margin:"0 auto"},children:`Connecting to ${gr(e)}\u2026`}):Be(fr,{children:[Be("span",{style:{display:"inline-flex",alignItems:"center",gap:Fs(e)?8:0},children:[E?d("img",{src:E,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):v?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:v.logoSvg}}):null,d("span",{children:gr(e)})]}),a&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:S,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:d("path",{d:"M9 18l6-6-6-6"})})]})})}function Go({method:e,sessionId:t,nonce:n,email:i,billingName:r,billingApiUrl:a,onTokenizedBody:c,onErrorChange:s,onDecline:C,onCancel:B,runBeforeButtonClick:p,onButtonClick:k,isProcessing:v,submitButtonColor:E,submitButtonBorderRadius:l,submitButtonStyle:y,errorText:S}){let M=vn(),f=Xo(),U=Jo(),[W,me]=be(!1),Q=Oe(!1),[A,G]=be(!1),[$,ye]=be("loading"),N=Ce(async()=>{if(!f||!U||v||Q.current||!A)return;Q.current=!0,me(!0);let q=p?await p("card"):{proceed:!0};if(!q.proceed){Q.current=!1,me(!1);return}k?.("card");let ae=q.sessionId??t,Fe=q.nonce??n,Pe=q.accountPatch?.email??i;try{s?.(null);let he=await U.submit();if(he.error){s?.(he.error.message??"Payment failed.");return}let J=await f.createPaymentMethod({elements:U});if(J.error||!J.paymentMethod){s?.(J.error?.message??"Failed to create payment method.");return}let fe=J.paymentMethod;if(!ae||!Pe)throw new Error("Missing sessionId or email for payment.");let Se=fe.type||e,ie=await new zn(a).createSessionIntent(ae,Fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Se,paymentMethodId:null,intentKind:"payment"});if(ie.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Le=ie.clientSecret;if(typeof window<"u")try{localStorage.setItem(kn,JSON.stringify({clientSecret:Le,sessionId:ae,nonce:Fe,accountPatch:q.accountPatch,paymentMethodId:fe.id,paymentMethodType:fe.type??e,gateway:"stripe"}))}catch{}let{error:_e,paymentIntent:Re}=await f.confirmPayment({clientSecret:Le,confirmParams:{return_url:window.location.href,payment_method:fe.id},redirect:"if_required"});if(_e){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ce=_e.message??"Payment failed.";s?.(ce),C?.(wt("card",ce,{code:_e.code})),await uo({billingApiUrl:a,sessionId:ae,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:_e.code??"provider_declined"}});return}let w=Re?.status;if(!no(w)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ce=w==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";s?.(ce),C?.(wt("card",ce,{code:w??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ne=typeof Re?.payment_method=="string"?Re.payment_method:Re?.payment_method?.id;c({id:ne??fe.id,type:"card",threeDSecureActionResultTokenId:Re?.id,gateway:"stripe",paymentMethodType:fe.type??e},{accountPatch:q.accountPatch,sessionId:ae,nonce:Fe})}catch(he){s?.(he instanceof Error?he.message:"Payment failed. Please try again.")}finally{Q.current=!1,me(!1)}},[f,U,v,A,p,k,t,n,i,a,e,c,s,C]);return Be("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(Rs,{onReady:()=>ye("ready"),onLoadError:()=>{ye("load_error"),Zo(Bt(M),"stripe","apm")},onChange:q=>{G(!!q.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:()=>{N()},disabled:!A||W||v||$!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:E,color:"white",border:"none",borderRadius:l,fontSize:"1rem",fontWeight:600,cursor:!A||W||v||$!=="ready"?"not-allowed":"pointer",opacity:!A||W||v||$!=="ready"?.5:1,transition:"opacity 120ms ease-out",...y??{}},children:W?"Processing\u2026":`Pay with ${gr(e)}`}),S&&d(dr,{margin:"0.75rem 0 0",children:S})]})}function ui({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:r,paymentElementMethods:a,stripeInstance:c,paymentElementBaseOptions:s,onTokenizedBody:C,onErrorChange:B,onButtonClick:p,onDecline:k,runBeforeButtonClick:v,onLoadStateChange:E,isProcessing:l=!1,submitButtonColor:y="#4A49FF",submitButtonBorderRadius:S=8,submitButtonStyle:M,buttonAppearance:f,themeId:U,onExpandApm:W,expandedApmMethod:me}){let[Q,A]=be(null),[G,$]=be(null),ye=Oe(!1);yt(()=>{a.length>0&&c?E?.("ready"):c||E?.("loading")},[a.length,c,E]);let N=Ce(async J=>{if(!c||ye.current||l)return;ye.current=!0,$(J);let fe=v?await v("card"):{proceed:!0};if(!fe.proceed){ye.current=!1,$(null);return}p?.("card");let Se=fe.sessionId??e,ie=fe.nonce??t,Le=fe.accountPatch?.email??n;try{if(B?.(null),!Se||!Le)throw new Error("Missing sessionId or email for payment.");let _e=await new zn(r).createSessionIntent(Se,ie??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:J,paymentMethodId:null,intentKind:"payment"});if(_e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Re=_e.clientSecret;if(typeof window<"u")try{localStorage.setItem(kn,JSON.stringify({clientSecret:Re,sessionId:Se,nonce:ie,accountPatch:fe.accountPatch,paymentMethodType:J,gateway:"stripe"}))}catch{}let{error:w,paymentIntent:ne}=await c.confirmPayment({clientSecret:Re,confirmParams:{return_url:window.location.href,payment_method_data:{type:J,billing_details:{name:i&&i.trim().length>=3?i.trim():"FloPay Customer",...Le?{email:Le}:{}}}},redirect:"if_required"});if(w){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Ne=w.message??"Payment failed.";B?.(Ne),k?.(wt("card",Ne,{code:w.code})),await uo({billingApiUrl:r,sessionId:Se,nonce:ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:J,providerDeclineReason:w.code??"provider_declined"}});return}let ce=ne?.status;if(!no(ce)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Ne=ce==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";B?.(Ne),k?.(wt("card",Ne,{code:ce??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ze=typeof ne?.payment_method=="string"?ne.payment_method:ne?.payment_method?.id;C({id:ze??ne?.id,type:"card",threeDSecureActionResultTokenId:ne?.id,gateway:"stripe",paymentMethodType:J},{accountPatch:fe.accountPatch,sessionId:Se,nonce:ie})}catch(_e){B?.(_e instanceof Error?_e.message:"Payment failed. Please try again.")}finally{ye.current=!1,$(null)}},[c,l,v,p,e,t,n,r,i,C,B,k]),[q,ae]=be(null),Fe=W?me??null:q,Pe=Ce(J=>{ye.current||l||Fe&&Fe!==J||(ni(J)?W?W(J):ae(J):N(J))},[Fe,l,N,W]),he=ot(()=>q?{...s,paymentMethodTypes:[q]}:null,[q,s]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(J=>{let fe=me===J,Se=G===J,ie=G!==null&&G!==J||me!=null&&me!==J;return Be(Os.Fragment,{children:[d(Js,{method:J,themeId:U,submitting:Se,disabled:ie,highlighted:fe,hasNextStep:ni(J),onClick:()=>Pe(J),backgroundColor:f?.backgroundColor,borderColor:f?.borderColor,textColor:f?.textColor,borderRadius:f?.borderRadius,fontFamily:f?.fontFamily}),!W&&q===J&&he&&c&&d(er,{stripe:c,options:he,children:d(Go,{method:J,sessionId:e,email:n,billingName:i,billingApiUrl:r,onTokenizedBody:C,onErrorChange:B,onDecline:k,onCancel:()=>ae(null),runBeforeButtonClick:v,onButtonClick:p,isProcessing:l,submitButtonColor:y,submitButtonBorderRadius:S,submitButtonStyle:M})},J)]},J)})})}function Xs({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,onComplete:a,onError:c,onDecline:s,onTokenizedBody:C,firstName:B,lastName:p,chv:k,className:v,isProcessing:E,error:l,onErrorChange:y,showPayPal:S=!0,showStripe:M=!0,enabledPaymentMethods:f,enabledPaymentMethodCountries:U,showApplePay:W=!0,showGooglePay:me=!0,layout:Q="default",theme:A,buttonsTheme:G,buttonsStyles:$,appearance:ye,cardButtonContent:N,cardBackButtonContent:q,cardTitleContent:ae,showSecurityFooter:Fe,onButtonClick:Pe,onBeforeButtonClick:he,enableAVS:J,cardFieldOrder:fe,cardPreFormSlot:Se,avsLayout:ie="row",country:Le,zip:_e,addressLine1:Re,addressLine2:w,city:ne,state:ce,onCountryChange:ze,onZipChange:Ne,avsCheck:Y,checkoutType:x,checkoutLayout:j,totalAmount:de=0,currency:xe="usd",initialCardOpen:it=!1,directPaypal:Qe,isSubscription:Ze=!1,session:u,debug:$e=!1}){let Ue=vn(),We=Oo(),qe=zs(un),Gt=to(),[Pt,It]=be(!1),[g,Ie]=be(null),[je,st]=be(Le??"US"),[rt,et]=be(_e??""),[Ge,we]=be(Re??""),[bt,Ke]=be(w??""),[Ut,Et]=be(ne??""),[mn,En]=be(ce??""),[_n,jn]=be({}),ht=Oe(_e??""),$t=Oe(Le??"US"),Dt=Oe(Re??""),Jt=Oe(w??""),an=Oe(ne??""),yn=Oe(ce??""),K=ot(()=>xs(J),[J]),Dn=K!==null,fn=!!u?.vault?.html,qt=!!u?.gateways?.pcivault,_=!!(u?.gateways?.stripe?.enabledPaymentMethods??f)?.includes("card"),Je=fn||_||qt,Ee=!!(M&&Je&&Ue&&e),[Ln,Ve]=be(()=>Q!=="buttons"||it?e??null:null),[Kn,gn]=be(0),hn=Q!=="buttons"||it||!!e&&Ln===e,tt=ot(()=>!Ue||!Ee||!e||!hn?null:Ue.cardCapture({sessionId:e}),[Ue,Ee,e,hn]),_t=ot(()=>{let o=je,b=K?Me(K.postal_code,o):!1;return Ys(o,rt,b)},[K,je,rt]),{avsInvalid:jt,invalidAvsFields:Lt}=ot(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!Ee||!K)return{avsInvalid:!1,invalidAvsFields:o};let b=je,z=(ee,Xe)=>Me(ee,b)&&!Xe.trim(),oe={line1:z(K.address_line_1,Ge),city:z(K.city,Ut),state:z(K.state,mn),zip:_t.empty||_t.malformed};return{avsInvalid:oe.line1||oe.city||oe.state||oe.zip,invalidAvsFields:oe}},[Ee,K,je,Ge,Ut,mn,_t]),[Xt,sn]=be(!1),[xn,Vt]=be(!1),[Nt,Zt]=be(()=>Ho(u?.vault)),[ve,ft]=be(it&&Je?"card":"buttons"),[lt,Pn]=be(null),Vn=ve==="expanding"||ve==="card",Ot=280,Ht=Oe(null),vt=Ce(o=>{Ht.current&&clearTimeout(Ht.current),Ht.current=setTimeout(()=>{Ht.current=null,o()},Ot)},[Ot]);yt(()=>()=>{Ht.current&&clearTimeout(Ht.current)},[]);let rr=Ce(()=>{Ve(e??null),gn(o=>o+1),ft("expanding"),vt(()=>ft("card"))},[vt,e]),Wt=Ce(()=>{ft("collapsing"),vt(()=>ft("buttons"))},[vt]),R=Ce(o=>{Pn(o),ft("apm-expanding"),vt(()=>ft("apm-form"))},[vt]),O=Ce(()=>{ft("apm-collapsing"),vt(()=>{ft("buttons"),Pn(null)})},[vt]);yt(()=>{Q==="buttons"&&it&&Je&&(Ve(e??null),ft("card"))},[Q,it,Je,e]);let[H,Z]=be(null),se=Oe(!1),[L,h]=be(null),X=Oe(L);yt(()=>{X.current=L},[L]);let F=n||Gt,le=l??g,ge=ot(()=>$s(A),[A]),I=ot(()=>{let o=ge?.buttonsLayout??Is(G);return $?{...o,...$,cardButton:{...o.cardButton,...$.cardButton},cardFormContainer:{...o.cardFormContainer,...$.cardFormContainer},backButton:{...o.backButton,...$.backButton},backButtonIcon:{...o.backButtonIcon,...$.backButtonIcon},submitButton:{...o.submitButton,...$.submitButton},title:{...o.title,...$.title}}:o},[ge,G,$]),Ct=ye??ge?.appearance,T=ot(()=>{let o=Ct?.variables,b=Xe=>typeof Xe=="string"&&Xe?Xe:void 0,z=I.submitButton,oe=b(o?.colorPrimary)??b(z?.backgroundColor)??"#4A49FF",D=Q==="buttons",ee=I.nameInput;return{primaryColor:oe,primaryHoverColor:b(o?.colorPrimaryHover)??lo(oe,.12),inputBackgroundColor:b(I.cardInputBackground)??b(o?.colorBackground)??"#ffffff",textColor:b(I.cardInputColor)??b(ee?.color)??b(o?.colorText)??"#262833",borderColor:b(I.cardInputBorder)??(D?"#e5e7eb":"#A4A4FF"),placeholderColor:b(I.cardInputPlaceholderColor)??"#9ca3af",errorColor:b(o?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:b(ee?.fontFamily)??b(o?.fontFamily)??"Poppins, sans-serif",fontSize:b(I.cardInputFontSize)??b(o?.fontSizeBase)??"16px",fontWeight:String(si(ee?.fontWeight)??400),borderRadius:b(o?.borderRadius)??"8px"}},[Ct,I,Q]),m=qe.inlineSessionPatchProcessing??!1,P=(E??Pt)||m,ue=F.replace(/\/+$/,""),V=ot(()=>$o({userId:r,email:i,firstName:B,lastName:p,country:Le,zip:_e},_n),[r,i,B,p,Le,_e,_n]),He=[V.firstName,V.lastName].filter(o=>!!o?.trim()).join(" "),ct=ot(()=>Ue?Ue.getRawProvider():null,[Ue]),Te=ot(()=>We?We.getRawProvider():null,[We]),ke=de||100,re=ot(()=>Ct?Ns(Ct):null,[Ct]),Ae=re?{appearance:re}:null,ln=ot(()=>{let o=re??{},b=o.rules??{};return{...o,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[re]),Yt=ot(()=>{let o=Wa(de);return{...o,currency:xe.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...Ae}},[de,xe,Ae]),zt=ot(()=>({mode:"payment",amount:ke,currency:xe.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Ae}),[ke,xe,Ae]),pe=Ce(o=>{Ie(o),y?.(o)},[y]);yt(()=>{!Ee||!tt||tt.setCardFieldOrder?.(fe??null,K==null)},[Ee,tt,fe,K]),yt(()=>{(ve==="expanding"||ve==="collapsing"||ve==="apm-expanding"||ve==="apm-collapsing")&&pe(null)},[ve,pe]);let cn=Ce((o,b,z)=>{s?.(wt(o,b,z))},[s]),or=Ce((o,b,z)=>{let oe=z?.popupBlocked??On(b),D=Hs(o,oe),ee=Zn(z?.code)??Bn(b)??"external_payment_method_failed",Xe=new wn(D,"api_error",{code:"external_payment_method_failed",param:o});Z(null),Q==="buttons"&&(ft("buttons"),Pn(null)),pe(D),c?.(Xe),console.error("[FloPay] External payment method failed:",{method:o,code:ee,popupBlocked:oe})},[Q,c,pe]);yt(()=>{if(!Ee||!e){Zt(null);return}let o=Ho(u?.vault);if(o){Zt(o);return}if(!hn){Zt(null);return}Zt(null);let b=!0;return new zn(ue).getVaultCapture(e,t).then(z=>{if(!b)return;let oe=Ho(z);oe?Zt(oe):pe("Failed to load the secure card form.")}).catch(z=>{b&&pe(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{b=!1}},[Ee,hn,Kn,e,u?.vault?.html,u?.vault?.messageToken,u?.vault?.expectedOrigin,ue,t,pe]);let Hn=Oe({onComplete:a,onError:c,updateError:pe,emitDecline:cn,resolvedAccount:V,avsConfig:K,avsCheckProp:Y,sessionId:e,nonce:t,baseUrl:ue});Hn.current={onComplete:a,onError:c,updateError:pe,emitDecline:cn,resolvedAccount:V,avsConfig:K,avsCheckProp:Y,sessionId:e,nonce:t,baseUrl:ue};let So=Oe(!1),Di=Ce(()=>{let{resolvedAccount:o,avsConfig:b,avsCheckProp:z}=Hn.current,oe=$t.current||o.country||"US",D=b?Me(b.state,oe):!1,ee=b?Me(b.address_line_1,oe):!1,Xe=b?Me(b.postal_code,oe):!1,St=b?Me(b.city,oe):!1,xt=b?Me(b.address_line_2,oe):!1,nt=ee&&!D&&Xe?ti(oe,(ht.current??"").trim()):null,Tt=D?yn.current:nt;return{accountData:{userId:o.userId??"",email:o.email??"",firstName:o.firstName??"",lastName:o.lastName??"",...Xe&&ht.current?{zip:ht.current}:{},...St&&an.current?{city:an.current}:{},...Tt?{state:Tt}:{},...ee&&Dt.current?{addressLine1:Dt.current}:{},...xt&&Jt.current?{addressLine2:Jt.current}:{},country:oe},...z!==void 0?{avsCheck:z}:{},...b?{avsConfig:{country:Me(b.country,oe),postal_code:Xe,address_line_1:ee,address_line_2:xt,city:St,state:D}}:{}}},[]);yt(()=>{!Ee||!tt||tt.setSubmitGate?.(jt)},[Ee,tt,jt]),yt(()=>{if(!Ee||!tt)return;So.current=!1;let o=!1,b=tt.on("submitting",()=>{sn(!0),Z("processing");let{baseUrl:ee,sessionId:Xe,nonce:St,updateError:xt,onError:nt}=Hn.current;!Xe||!St||new zn(ee).patchAccountSnapshot(Xe,St,Di(),{telemetryMode:"best_effort"}).catch(Tt=>{if(!qs(Tt))return;let De=Tt instanceof Error?Tt.message:"Please check your billing address and try again.";xt(De),Z(null),nt?.(Tt instanceof wn?Tt:new wn(De,"api_error"))})}),z=tt.on("complete",async ee=>{pr(ee.sessionId??Hn.current.sessionId),Z("success"),await new Promise(Xe=>setTimeout(Xe,Mn)),!So.current&&(So.current=!0,Hn.current.onComplete?.({status:"succeeded",paymentIntentId:ee.intentId,checkoutMethod:"card"}))}),oe=tt.on("decline",async ee=>{let{updateError:Xe,emitDecline:St}=Hn.current,xt=ee.message??"Your payment was declined. Please try another card or contact your bank.";Xe(xt),Z("error"),St("card",xt,ee.declineReason?{declineCode:ee.declineReason}:void 0),await new Promise(nt=>setTimeout(nt,Cn)),!o&&Z(null)}),D=tt.on("error",async ee=>{let{updateError:Xe,onError:St}=Hn.current,xt=ee.message??"There was a problem processing your payment. Please try again.";Xe(xt),Z("error"),St?.(new wn(xt,"api_error")),await new Promise(nt=>setTimeout(nt,Cn)),!o&&Z(null)});return()=>{o=!0,b(),z(),oe(),D()}},[Ee,tt]);let bn=!!Qe?.clientId,wr=Array.isArray(f),jr=wr&&f.length>0,Li=wr&&f.includes("paypal"),{expressMethods:Kr,paymentElementMethods:kr}=ot(()=>Ls(f,{excludePaypal:bn}),[f,bn]),ma=bn||!!We,Ni=ot(()=>ma?Kr.filter(o=>o!=="paypal"):Kr,[Kr,ma]),Oi=ot(()=>{let o=[];return W&&o.push("apple_pay"),me&&o.push("google_pay"),o},[W,me]),Vr=wr?Ni:Oi,zi=M&&Vr.length>0,wo=Dn?je:Le,Hr=ot(()=>{let o=wo?.trim().toUpperCase();return o?U?kr.filter(b=>{let z=U[b];return!z||z.length===0||z.includes(o)}):As(kr,wo):kr},[kr,wo,U]),ko=ot(()=>({mode:"payment",amount:ke,currency:xe.toLowerCase(),paymentMethodCreation:"manual",appearance:ln}),[ke,xe,ln]),[ya,fa]=be("loading"),[ga,ha]=be("loading"),[Pa,ba]=be("loading"),[Ui,Ro]=be(!1),[va,Io]=be("loading"),[Wr,$i]=be();yt(()=>{$i(Ya())},[]);let Ca=S&&(bn||(wr?Li:Wr===!1)),Sa=M&&zi,Rr=Ca&&bn,wa=va==="retrying"||va==="exhausted",Ir=Ca&&!!Te&&(!bn||wa),Er=Sa&&!!ct,_r=M&&jr&&Hr.length>0&&!!ct,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=Oe(!1);yt(()=>{if(!Yr.current){if(!M&&!S){Yr.current=!0;let o=new wn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(o),pe(o.message)}else if(!M&&S&&!bn&&!Te){Yr.current=!0;let o=new wn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(o),pe(o.message)}else if(Wr!==void 0&&!Je&&!Ra){Yr.current=!0;let o=new wn("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});c?.(o),pe(o.message)}}},[M,S,bn,Te,Wr,Je,Ra,c,pe]);let Ia=Oe(!1);yt(()=>{if(Ia.current||!jr)return;let o=[];W!==!0&&o.push("showApplePay"),me!==!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,W,me]);let Ea=Ce((o,b)=>qe.applyInlineSessionPatch?qe.applyInlineSessionPatch(o).then(z=>({error:null,sessionId:z.sessionId||e,nonce:z.session?.clientSecret||t})).catch(z=>{let oe=ii(b,z);return pe(oe.message),c?.(oe),{error:oe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[qe.applyInlineSessionPatch,t,c,e,pe]),dn=Ce(async o=>{if(!he)return{proceed:!0};try{let b=await he({method:o,sessionId:e||void 0,createSession:qe.inlineSessionDraft});if(b===!1)return{proceed:!1};if(b&&typeof b=="object"){b.account&&jn(oe=>({...oe??{},...b.account}));let z=await Ea(b,o);return z.error?{proceed:!1,accountPatch:b.account}:{proceed:!0,accountPatch:b.account,sessionId:z.sessionId,nonce:z.nonce}}return{proceed:!0}}catch(b){let z=ii(o,b);return pe(z.message),c?.(z),{proceed:!1}}},[Ea,qe.inlineSessionDraft,he,c,e,pe]),_a=Ce(async(o,b)=>{if(se.current)return;se.current=!0,It(!0),Z("processing"),pe(null);let z=b?.sessionId??e,oe=b?.nonce??t,D=$o(V,b?.accountPatch),ee=b?.completionPaymentMethodId??ro(o),Xe=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o;try{let xt=await new zn(ue).processPayment(D.userId??"",{sessionId:z,nonce:oe,tokenizedData:Xe,accountData:{userId:D.userId??"",email:D.email??"",firstName:D.firstName??"",lastName:D.lastName??"",...K?(()=>{let De=$t.current,en=Me(K.state,De),tn=Me(K.address_line_1,De),Jn=Me(K.postal_code,De),Xn=tn&&!en&&Jn?ti(De,(ht.current??"").trim()):null,Mt=en?yn.current:Xn;return{country:De,...Jn&&ht.current?{zip:ht.current}:{},...Me(K.city,De)&&an.current?{city:an.current}:{},...Mt?{state:Mt}:{},...tn&&Dt.current?{addressLine1:Dt.current}:{},...Me(K.address_line_2,De)&&Jt.current?{addressLine2:Jt.current}:{}}})():{}},chv:k,avsCheck:Y??!1,checkoutType:x,checkoutLayout:j,avsConfig:K?{country:Me(K.country,$t.current),postal_code:Me(K.postal_code,$t.current),address_line_1:Me(K.address_line_1,$t.current),address_line_2:Me(K.address_line_2,$t.current),city:Me(K.city,$t.current),state:Me(K.state,$t.current)}:void 0});if(xt.ok){pr(z),Z("success"),h(null),await new Promise(De=>setTimeout(De,Mn)),a?.({status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:ee,checkoutMethod:o.isPaypal?"paypal":"card"});return}let nt=await xt.json().catch(()=>null);if(nt?.type==="paypal_redirect_required"){let De=nt.threeDSecureToken,en=nt.paymentMethodId||o.id||"";if(!Ue||!De){Z("error"),pe("PayPal authorization required but no token provided.");return}try{let tn=We?.getRawProvider();if(!tn){pe("PayPal is not available.");return}let Jn={return_url:window.location.href};en&&(Jn.payment_method=en);let{error:Xn}=await tn.confirmPayment({clientSecret:De,confirmParams:Jn,redirect:"if_required"});if(Xn){Z("error");let Mt=Xn.message??"PayPal payment failed.";pe(Mt),cn("paypal",Mt,{code:Xn.code})}}catch(tn){Z("error"),pe(tn instanceof Error?tn.message:"PayPal authorization failed.")}return}if(nt?.type==="paypal_direct_required"){let De=nt.orderId;if(!De){Z("error"),pe("PayPal retry required but no order id provided.");return}let en=X.current?.attempts??0;if(en>=2){Z("error"),pe("PayPal payment could not be completed after multiple attempts."),cn("paypal","paypal_direct_required retry limit exceeded");return}Ro(!1),Io("loading"),h({orderId:De,attempts:en+1}),Z(null);return}Z("error");let Tt=nt?.message??"Payment failed. Please try again.";pe(Tt),cn(o.isPaypal?"paypal":"card",Tt,{code:nt?.code??nt?.gatewayErrorCode,declineCode:nt?.declineCode??nt?.gatewayDeclineReason}),await new Promise(De=>setTimeout(De,Cn))}catch(St){Z("error"),pe(St instanceof Error?St.message:"An unexpected error occurred"),await new Promise(xt=>setTimeout(xt,Cn))}finally{It(!1),Z(null),se.current=!1}},[ue,e,t,V,He,k,Ue,We,a,c,pe,cn]),Qt=Ce((o,b)=>{C?C(o):_a(o,b)},[C,_a]),xa=Oe(!1);yt(()=>{if(typeof window>"u"||xa.current)return;let o=new URLSearchParams(window.location.search),b=o.get("payment_intent"),z=o.get("payment_intent_client_secret"),oe=o.get("redirect_status");if(!b||!z)return;let D=Tt=>{let De=localStorage.getItem(Tt);if(!De)return null;try{return JSON.parse(De)}catch{return localStorage.removeItem(Tt),null}},ee=D(kn)??D(oi),Xe;if(ee?.clientSecret){if(ee.clientSecret!==z)return;Xe={...ee.accountPatch?{accountPatch:ee.accountPatch}:{},...ee.sessionId?{sessionId:ee.sessionId}:{},...ee.nonce?{nonce:ee.nonce}:{}}}else if(ee?.sessionId&&ee.sessionId!==e)return;xa.current=!0,localStorage.removeItem(kn),localStorage.removeItem(oi);let St=new URL(window.location.href);St.searchParams.delete("payment_intent"),St.searchParams.delete("payment_intent_client_secret"),St.searchParams.delete("redirect_status"),window.history.replaceState({},"",St.toString());let xt=ee?.paymentMethodType??ee?.tokenType??"card",nt="card";(async()=>{let Tt=Ue?.getRawProvider();if(!Tt){let Mt="Payment is not available \u2014 please refresh and try again.";pe(Mt),cn(nt,Mt);return}if(oe==="failed"){let Mt="Payment was declined. Please try again.";pe(Mt),cn(nt,Mt);return}let{paymentIntent:De,error:en}=await Tt.retrievePaymentIntent(z);if(en){let Mt=en.message??"Failed to retrieve payment status.";pe(Mt),cn(nt,Mt,{code:en.code});return}let tn=De?.status,Jn=no(tn);if(!De||!Jn){let Mt=tn==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";pe(Mt),cn(nt,Mt,{code:tn??"missing_payment_intent"});return}let Xn=typeof De.payment_method=="string"?De.payment_method:De.payment_method?.id;Qt({id:Xn??ee?.paymentMethodId??ee?.tokenId??De.id,type:"card",threeDSecureActionResultTokenId:De.id,gateway:ee?.gateway??"stripe",paymentMethodType:xt},Xe)})()},[e,Qt,Ue,pe,cn]);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=Q==="buttons",Kt=Ct?.variables,Vi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),_o=Kt?.colorBackground,Hi=_o&&!Vi.has(_o)?_o:void 0,Tr=I.cardInputBorder??(xr?"#e5e7eb":"#A4A4FF"),xo=Kt?.colorDanger??"#dc2626",Wn=o=>Xt&&o?xo:Tr,Gr=(_t.malformed||_t.empty)&&(xn||Xt),Wi=Gr?xo:Wn(Lt.zip),To=I.cardFormContainer?.backgroundColor??Hi??(xr?"white":"#EDEDFF"),Mr=I.cardInputBackground??Kt?.colorBackground??"white",Mo=ir(q),Ta=ir(ae),ar=I.nameInput,Ma=I.cardInputFontSize??Gs(ar?.fontSize)??Kt?.fontSizeBase??"16px",Ba=typeof ar?.fontFamily=="string"?ar.fontFamily:Kt?.fontFamily??"Poppins, sans-serif",Aa=si(ar?.fontWeight)??400,Yi=I.cardInputColor??(typeof ar?.color=="string"?ar.color:void 0)??Kt?.colorText??"#262833",Gi=I.cardInputPlaceholderColor??"#9ca3af",gt=Kt?.borderRadius??"8px",Yn=Kt?.borderRadius??I.cardButton?.borderRadius??gt,Gn=Kt?.colorPrimary??"#4A49FF",Ji=Kt?.colorPrimaryHover??lo(Gn,.12),Bo=Kt?.colorText??"#262833",Fa={fontSize:Ma,fontFamily:Ba,fontWeight:Aa,color:Yi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Xi={"--flopay-input-placeholder-color":Gi,"--flopay-input-font-size":Ma,"--flopay-input-font-family":Ba,"--flopay-input-font-weight":String(Aa)},Br=I.cardFormContainer??{},Ao=Br.padding??(xr?"0":"1rem"),Fo=Br.borderRadius??gt,Zi=tt&&Nt?d(No,{capture:tt,html:Nt.html,messageToken:Nt.messageToken,expectedOrigin:Nt.expectedOrigin,theme:T,onReady:()=>{if(!K||typeof document>"u")return;let o=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};o();let b=0,z=window.setInterval(()=>{b+=1;let oe=document.activeElement;!!oe&&oe.tagName==="IFRAME"&&oe.id==="flopay_vault_form_iframe"?(o(),window.clearInterval(z)):b>=50&&window.clearInterval(z)},100)},onError:o=>pe(o),onValidation:o=>{pe(o),o&&Z(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=Be("div",{style:{backgroundColor:To,borderRadius:Fo,...Br,padding:Ao,...Xi,display:"flex",flexDirection:"column"},children:[d("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${Je.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),Rr&&ln&&xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:y?-2:0},children:[xe("button",{type:"button",onClick:Dn,style:{display:"inline-flex",alignItems:"center",gap:Ro?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:S.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...S.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...S.backButtonIcon},children: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(rr,{content:V})]}),Sa?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:S.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...S.title},children:d(Tr,{content:re})})]}),!Rr&&!Sa&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Io,order:y?-3:0,...S.title},children:d(Tr,{content:re})}),K&&d("div",{style:{order:y?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let o=je,v=(L=!1)=>({backgroundColor:Er,border:`1px solid ${Vn(L)}`,borderRadius:gt,marginTop:"0.5rem",padding:"10px"}),U=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ia}),ne=Ps(o);return xe(dr,{children:[_e(K.address_line_1,o)&&d("div",{style:v(Kt.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:We,onChange:L=>{Dt.current=L.target.value,be(L.target.value)},disabled:Ee,required:!0,"data-testid":"flopay-address-line1",style:U()})}),_e(K.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:bt,onChange:L=>{Jt.current=L.target.value,Ve(L.target.value)},disabled:Ee,"data-testid":"flopay-address-line2",style:U()})}),(_e(K.city,o)||_e(K.state,o))&&xe("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[_e(K.city,o)&&d("div",{style:{flex:1,backgroundColor:Er,borderTop:`1px solid ${Vn(Kt.city)}`,borderRight:`1px solid ${Vn(Kt.city)}`,borderBottom:`1px solid ${Vn(Kt.city)}`,borderLeft:`1px solid ${Vn(Kt.city)}`,padding:"10px",borderTopLeftRadius:gt,borderBottomLeftRadius:gt,..._e(K.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:Ot,onChange:L=>{rn.current=L.target.value,It(L.target.value)},disabled:Ee,required:!0,"data-testid":"flopay-city",style:U()})}),_e(K.state,o)&&d("div",{style:{flex:1,backgroundColor:Er,border:`1px solid ${Vn(Kt.state)}`,padding:"10px",borderTopRightRadius:gt,borderBottomRightRadius:gt,..._e(K.city,o)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:gt}},children:ne?xe("select",{id:"flopay-billing-state",name:"billing-state",value:mn,onChange:L=>{yn.current=L.target.value,Rn(L.target.value)},disabled:Ee,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...U(),cursor:"pointer"},children:[d("option",{value:"",children:Wa(o)}),ne.map(L=>d("option",{value:L.code,children:L.name},L.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Wa(o),autoComplete:"billing address-level1",value:mn,onChange:L=>{yn.current=L.target.value,Rn(L.target.value)},disabled:Ee,required:!0,"data-testid":"flopay-state",style:U()})})]}),(_e(K.country,o)||_e(K.postal_code,o))&&xe("div",{style:{display:"flex",flexDirection:oe==="column"?"column":"row",gap:oe==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[_e(K.country,o)&&d("div",{style:{flex:oe==="row"?1:void 0,backgroundColor:Er,borderTop:`1px solid ${Ir}`,borderRight:`1px solid ${Ir}`,borderBottom:`1px solid ${Ir}`,borderLeft:`1px solid ${Ir}`,padding:"10px",...oe==="row"&&_e(K.postal_code,o)?{borderRadius:"0",borderTopLeftRadius:gt,borderBottomLeftRadius:gt,borderRight:"none"}:{borderRadius:gt}},children:d("select",{id:"flopay-billing-country",name:"billing-country",value:je,onChange:L=>{zt.current=L.target.value,it(L.target.value),Ne?.(L.target.value),yn.current="",Rn("")},disabled:Ee,autoComplete:"billing country","data-testid":"flopay-country",style:{...U(),cursor:"pointer"},children:bs.map(L=>xe("option",{value:L.code,children:[L.flag," ",L.name]},L.code))})}),_e(K.postal_code,o)&&d("div",{style:{flex:oe==="row"?1:void 0,backgroundColor:Er,border:`1px solid ${Oi}`,padding:"10px",...oe==="row"&&_e(K.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:$o(je),autoComplete:"billing postal-code",value:et,onChange:L=>{ht.current=L.target.value,Xe(L.target.value),De?.(L.target.value)},onBlur:()=>_n(!0),disabled:Ee,required:Ht.required,"aria-invalid":Hr||void 0,"aria-describedby":Hr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:U()})})]}),Hr&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:wo,...Ia,fontSize:"0.75rem"},children:Ht.empty?`${$o(o)} is required`:Os(o)})]})})()}),y&&Pe&&d("div",{style:{order:-2,width:"100%"},children:Pe}),y&&ji,N&&d(ar,{margin:"0.75rem 0",styleOverride:S.errorBanner,children:N})]}),Kr={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"},_a=o=>$e?!k||!hn?d("pre",{"data-testid":o,style:Kr,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":o,style:Kr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${k}`,` directPaypalConfigured=${hn}`,` inAppBrowserDetected=${String(jr)}`,` shouldRenderDirectPayPal=${Cr}`,` shouldRenderStripePayPal=${Sr}`,` hasPaypalStripeInstance=${!!le}`].join(`
39
- `)}):null,xa=o=>$e?!B||!_?d("pre",{"data-testid":o,style:Kr,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":o,style:Kr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${B}`,` currency=${Re}`,` amountInCents=${we}`,` enabledPaymentMethods: ${JSON.stringify(h??[])}`,` enabledPaymentMethodsProvided=${br}`,` hasEnabledMethods=${zr}`,` expressMethods: ${JSON.stringify(Ur)}`,` walletExpressMethods: ${JSON.stringify($r)}`,` paymentElementMethods: ${JSON.stringify(vr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(qr)}`,` hasStripeInstance=${!!_}`,` shouldRenderWallets=${wr}`,` shouldRenderPaymentElement=${kr}`].join(`
40
- `)}):null,Ta=Se==="apm-expanding"||Se==="apm-form"||Se==="apm-collapsing",Wr=Se==="apm-expanding"?`flopay-card-enter ${vt}ms cubic-bezier(0, 0, 0.2, 1) both`:Se==="apm-collapsing"?`flopay-card-exit ${vt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Yr=Ze?{...Po,paymentMethodTypes:[Ze]}:null;if(Z==="buttons"){let o=Se==="buttons"||Se==="expanding"||Se==="apm-expanding",v=Se==="expanding"||Se==="card"||Se==="collapsing",U=z===void 0?{boxSizing:"border-box",height:ao,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ne=Se==="expanding"||Se==="apm-expanding"?`flopay-buttons-exit ${vt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Se==="collapsing"||Se==="apm-collapsing"?`flopay-buttons-enter ${vt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,L=Se==="expanding"?`flopay-card-enter ${vt}ms cubic-bezier(0, 0, 0.2, 1) both`:Se==="collapsing"?`flopay-card-exit ${vt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return xe("form",{onSubmit:Co,className:C,style:{position:"relative"},children:[d(Uo,{}),cn&&d(vn,{status:cn,errorMessage:N}),xe("div",{style:{display:"grid"},children:[xe("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!o&&!ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!o&&!ne?Ds:{},...ne?{animation:ne,pointerEvents:"none"}:{}},children:[_a("flopay-direct-paypal-gate-debug"),xa("flopay-stripe-gate-debug"),Cr&&Je&&xe(dr,{children:[O&&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(ro,{sessionId:e,nonce:t,billingApiUrl:$,email:P.email,clientId:Je.clientId,environment:Je.environment,currency:Re.toUpperCase(),isSubscription:Ge,onTokenizedBody:Xt,onComplete:a,onErrorChange:E,onDecline:s,onTechnicalFailure:Et,onButtonClick:me,runBeforeButtonClick:dn,isProcessing:Ee,onLoadStateChange:bo,onInitializationStateChange:vo,session:m??null,existingOrderId:O?.orderId,debug:$e},O?.orderId??"fresh")]}),Sr&&d(Xn,{stripe:le,options:ae,children:d(ni,{sessionId:e,nonce:t,email:P.email,billingApiUrl:$,onTokenizedBody:Xt,onErrorChange:E,isProcessing:Ee,onButtonClick:me,onDecline:s,onTechnicalFailure:Et,runBeforeButtonClick:dn,onLoadStateChange:sa,placeholderBorderRadius:Hn})}),wr?d(Xn,{stripe:_,options:Ie,children:d(ri,{sessionId:e,nonce:t,email:P.email,billingApiUrl:$,intentKind:se>0?"payment":"setup",expressMethods:$r,onTokenizedBody:Xt,onErrorChange:E,onButtonClick:me,onDecline:s,onTechnicalFailure:Et,runBeforeButtonClick:dn,onLoadStateChange:ca,placeholderBorderRadius:Hn})}):ya?d("div",{style:{height:ao,borderRadius:Hn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,kr&&d(oi,{sessionId:e,nonce:t,email:P.email,billingName:[P.firstName,P.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:$,paymentElementMethods:qr,stripeInstance:_,paymentElementBaseOptions:Po,onTokenizedBody:Xt,onErrorChange:E,onButtonClick:me,onDecline:s,runBeforeButtonClick:dn,onLoadStateChange:ua,isProcessing:Ee,submitButtonColor:Kn,submitButtonBorderRadius:gt,submitButtonStyle:S.submitButton,onExpandApm:xn,expandedApmMethod:Ze,themeId:F,buttonAppearance:{backgroundColor:S.cardButton?.backgroundColor,borderColor:S.cardInputBorder,textColor:S.cardButton?.color,borderRadius:Hn}}),y&&d("button",{type:"button",onClick:async()=>{Ee||!(await dn("card")).proceed||(me?.("card"),jn())},disabled:Ee,style:{width:"100%",...U,...S.cardButton,...Ko({themeBundle:u,resolvedPrimaryColor:Kn,resolvedBorderRadius:gt,submitButtonStyle:S.submitButton,explicitPrimaryColor:Vt?.colorPrimary}),fontSize:S.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ee?"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:Ee?.6:1},onMouseEnter:Q=>{!Ee&&(u||Vt?.colorPrimary)&&(Q.currentTarget.style.backgroundColor=$i)},onMouseLeave:Q=>{(u||Vt?.colorPrimary)&&(Q.currentTarget.style.backgroundColor=Kn)},onMouseDown:Q=>{Q.currentTarget.style.transform="scale(0.985)"},onMouseUp:Q=>{Q.currentTarget.style.transform="scale(1)"},children:d(nr,{content:z})}),N&&Se==="buttons"&&d(ar,{margin:"0.25rem 0",styleOverride:S.errorBanner,children:N})]}),y&&v&&d("div",{style:{gridArea:"1 / 1",...L?{animation:L}:{},...Se==="collapsing"?{pointerEvents:"none"}:{}},children:Ea}),B&&Ta&&Ze&&Yr&&_&&d("div",{style:{gridArea:"1 / 1",...Wr?{animation:Wr}:{},...Se==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:ko,borderRadius:_o,..._r,padding:Eo},children:[xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[xe("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:jt,style:{display:"inline-flex",alignItems:"center",gap:Ro?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:S.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...S.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...S.backButtonIcon},children: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(rr,{content:V})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:S.titleFontSize??"1.05rem",color:Io,paddingRight:80,...S.title},children:`Pay with ${ur(Ze)}`})]}),d(Xn,{stripe:_,options:Yr,children:d(qo,{method:Ze,sessionId:e,nonce:t,email:P.email,billingName:[P.firstName,P.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:$,onTokenizedBody:Xt,onErrorChange:E,onDecline:s,onCancel:jt,runBeforeButtonClick:dn,onButtonClick:me,isProcessing:Ee,submitButtonColor:Kn,submitButtonBorderRadius:gt,submitButtonStyle:S.submitButton,errorText:N})},Ze)]})})]})]})}return Ta&&Ze&&Yr&&_&&B?xe("form",{onSubmit:Co,className:C,style:{position:"relative"},children:[d(Uo,{}),cn&&d(vn,{status:cn,errorMessage:N}),d("div",{style:{...Wr?{animation:Wr}:{},...Se==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:ko,borderRadius:_o,..._r,padding:Eo},children:[xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[xe("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:jt,style:{display:"inline-flex",alignItems:"center",gap:Ro?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:S.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...S.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...S.backButtonIcon},children: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(rr,{content:V})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:S.titleFontSize??"1.05rem",color:Io,paddingRight:80,...S.title},children:`Pay with ${ur(Ze)}`})]}),d(Xn,{stripe:_,options:Yr,children:d(qo,{method:Ze,sessionId:e,nonce:t,email:P.email,billingName:[P.firstName,P.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:$,onTokenizedBody:Xt,onErrorChange:E,onDecline:s,onCancel:jt,runBeforeButtonClick:dn,onButtonClick:me,isProcessing:Ee,submitButtonColor:Kn,submitButtonBorderRadius:gt,submitButtonStyle:S.submitButton,errorText:N})},Ze)]})})]}):xe("form",{onSubmit:Co,className:C,style:{position:"relative"},children:[d(Uo,{}),cn&&d(vn,{status:cn,errorMessage:N}),xe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[_a("flopay-direct-paypal-gate-debug-default"),xa("flopay-stripe-gate-debug-default"),Cr&&Je&&xe(dr,{children:[O&&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(ro,{sessionId:e,nonce:t,billingApiUrl:$,email:P.email,clientId:Je.clientId,environment:Je.environment,currency:Re.toUpperCase(),isSubscription:Ge,onTokenizedBody:Xt,onComplete:a,onErrorChange:E,onDecline:s,onTechnicalFailure:Et,onButtonClick:me,runBeforeButtonClick:dn,isProcessing:Ee,onLoadStateChange:bo,onInitializationStateChange:vo,session:m??null,existingOrderId:O?.orderId,debug:$e},O?.orderId??"fresh")]}),Sr&&d(Xn,{stripe:le,options:ae,children:d(ni,{sessionId:e,nonce:t,email:P.email,billingApiUrl:$,onTokenizedBody:Xt,onErrorChange:E,isProcessing:Ee,onButtonClick:me,onDecline:s,onTechnicalFailure:Et,runBeforeButtonClick:dn,onLoadStateChange:sa,placeholderBorderRadius:Hn})}),wr&&d(Xn,{stripe:_,options:Ie,children:d(ri,{sessionId:e,nonce:t,email:P.email,billingApiUrl:$,intentKind:se>0?"payment":"setup",expressMethods:$r,onTokenizedBody:Xt,onErrorChange:E,onButtonClick:me,onDecline:s,onTechnicalFailure:Et,runBeforeButtonClick:dn,onLoadStateChange:ca,placeholderBorderRadius:Hn})}),kr&&d(oi,{sessionId:e,nonce:t,email:P.email,billingName:[P.firstName,P.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:$,paymentElementMethods:qr,stripeInstance:_,paymentElementBaseOptions:Po,onTokenizedBody:Xt,onErrorChange:E,onButtonClick:me,onDecline:s,runBeforeButtonClick:dn,onLoadStateChange:ua,isProcessing:Ee,submitButtonColor:Kn,submitButtonBorderRadius:gt,submitButtonStyle:S.submitButton,themeId:F,onExpandApm:xn,expandedApmMethod:Ze,buttonAppearance:{backgroundColor:S.cardButton?.backgroundColor,borderColor:S.cardInputBorder,textColor:S.cardButton?.color,borderRadius:Hn}})]}),y&&(Fi||Ai||Di)&&xe("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),d("span",{children:"or pay with card"}),d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),y&&Ea]})}import{loadFloPay as ui,PaymentAPI as pi}from"@flopay/js";import{FloPayError as ot,isSetupIntentClientSecret as js}from"@flopay/shared";var Lr="card";async function Vs(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 Hs(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 wn(e,t){return Object.assign(e,{checkoutMethod:t})}function mi(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 Ks(e){return e.status==="succeeded"||e.status==="declined"}async function yi(e){if(typeof document>"u"||typeof window>"u")throw new ot("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new ot("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,i=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let p=new AbortController,I=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",I);let C=window.setTimeout(()=>p.abort(),i);try{let T=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:p.signal});if(!T.ok)return{status:"unknown"};let l=await T.json().catch(()=>null);return Ws(l)}catch{return{status:"unknown"}}finally{window.clearTimeout(C),e.signal?.removeEventListener("abort",I)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let w=document.createElement("iframe");w.setAttribute("title","Card authentication"),w.setAttribute("allow","payment"),w.tabIndex=0,w.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),w.src=e.nextActionRedirectUrl,s.appendChild(w),document.body.appendChild(s),w.focus();let A=null;try{A=new URL(e.billingApiUrl,window.location.href).origin}catch{A=null}try{let p=await new Promise((I,C)=>{let T=!1,l=0,f=0,k=0,B=!1,h=()=>{window.clearTimeout(l),window.clearInterval(f),window.clearTimeout(k),window.removeEventListener("message",Z),w.removeEventListener("load",W),e.signal?.removeEventListener("abort",ce)},q=async()=>{if(!(T||B)){B=!0;try{let F=await a();if(T||!Ks(F))return;T=!0,h(),I(F)}finally{B=!1}}},W=()=>{window.clearTimeout(k),k=window.setTimeout(()=>{q()},250)},ce=()=>{T||(T=!0,h(),C(new ot("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Z=F=>{if(F.source!==w.contentWindow||A&&F.origin!==A)return;let J=F.data;!J||typeof J!="object"||J.source!=="flopay-vault-3ds-return"||T||(T=!0,h(),I(null))};l=window.setTimeout(()=>{T||(T=!0,h(),C(new ot("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),f=window.setInterval(()=>{q()},n),w.addEventListener("load",W),window.addEventListener("message",Z),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return p||await a()}finally{s.parentNode?.removeChild(s),c?.isConnected&&c.focus()}}function Ws(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function zn(e,t="Payment failed. Please try again.",n){let i=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),r=e?.message??t,a=Ln(r)??r;return wn(new ot(a,"api_error",{code:e?.gatewayErrorCode}),i)}function Yo(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function so(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Ys(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 fi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||so(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||so(s)))return s;let c=r.gateways;if(c&&typeof c=="object"){let s=c.stripe;if(s&&typeof s=="object"){let w=s,A=[w.stripeClientSecret,w.clientSecret];for(let p of A)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||so(p)))return p}}}}async function Gs({billingApiUrl:e,sessionId:t,nonce:n,responseJson:i}){let r=fi(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 pi(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(so(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function pr({billingApiUrl:e,sessionId:t,session:n,nonce:i,tokenizedData:r,returnUrl:a,telemetry:c}){let s=e.replace(/\/+$/,""),w=t??n.id,A=i??n.clientSecret,p=n.customer?.id??n.accountData?.userId??"",I=n.customer?.email??n.accountData?.email??"",C=n.customer?.firstName??n.accountData?.firstName??"",T=n.customer?.lastName??n.accountData?.lastName??"",l=n.customer?.country??n.accountData?.country??void 0,f=n.customer?.zip??n.accountData?.zip??void 0,k=new pi(s,c===!1?{telemetry:!1}:void 0),B=await Ys(()=>k.processPayment(p,{sessionId:w,nonce:A,tokenizedData:r,accountData:{userId:p,email:I,firstName:C,lastName:T,country:l,zip:f},returnUrl:a??Yo(n)}));if(B.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:Qr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}};let h=await B.json().catch(()=>null);if(h?.type==="paypal_redirect_required"||h?.type==="3ds_required"){let q=fi(h);if(!q)throw new ot("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:h.type,threeDSecureToken:q,paymentMethodId:h.paymentMethodId}}if(h?.gatewayErrorCode==="authentication_required"){let q=await Gs({billingApiUrl:s,sessionId:w,nonce:A,responseJson:h});if(q)return q;throw wn(new ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new ot(h?.message??"Payment failed. Please try again.","api_error",{code:h?.code??h?.gatewayErrorCode,declineCode:h?.declineCode??h?.gatewayDeclineReason})}async function lo(e,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:c,returnUrl:s,telemetry:w}){let A=t?.getRawProvider();if(!A)throw new ot("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!i||!e.threeDSecureToken)throw wn(new ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let p=js(e.threeDSecureToken),I=null,C=e.paymentMethodId,T=await Vs(A,e.threeDSecureToken,p);if(T){if(T.error)throw wn(new ot(T.error.message??`Failed to retrieve 3DS ${p?"setup":"payment"} status.`,"api_error",{code:T.error.code}),"card");let f=T.intent;!C&&f?.payment_method&&(typeof f.payment_method=="string"?C=f.payment_method:"id"in f.payment_method&&(C=f.payment_method.id??void 0))}let l=C?await Hs(A,e.threeDSecureToken,{payment_method:C,return_url:s??Yo(c)??window.location.href},p):null;if(l){if(l.error)throw wn(new ot(l.error.message??"3DS authentication failed.","api_error",{code:l.error.code}),"card");I=l.intent}else{let f=await A.handleNextAction({clientSecret:e.threeDSecureToken});if(f.error)throw wn(new ot(f.error.message??"3DS authentication failed.","api_error",{code:f.error.code}),"card");I=(p?f.setupIntent:f.paymentIntent)??null}if(I&&(I.status==="requires_capture"||I.status==="succeeded"||I.status==="processing")){let f=await pr({billingApiUrl:r,sessionId:a,session:c,telemetry:w,tokenizedData:{id:I.id,type:"card",threeDSecureActionResultTokenId:I.id},returnUrl:s});return f.type==="success"?{...f.result,paymentIntentId:f.result.paymentIntentId??I.id,paymentMethodId:f.result.paymentMethodId??C}:lo(f,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:c,returnUrl:s,telemetry:w})}throw wn(new ot("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let p=(n??t)?.getRawProvider();if(!p)throw wn(new ot("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:C}=await p.handleNextAction({clientSecret:e.threeDSecureToken});if(C)throw wn(new ot(C.message??"PayPal authorization failed.","api_error",{code:C.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:I}=await p.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Yo(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(I)throw wn(new ot(I.message??"PayPal authorization failed.","api_error",{code:I.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new ot("Unsupported payment redirect state.","api_error")}function Zn(e){if(e instanceof ot){let i=Ln(e.message);return i&&i!==e.message?Object.assign(new ot(i,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Ln(t)??t;return new ot(n,"api_error")}function co(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new ot("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function uo({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([ui(e,{billingApiUrl:n,locale:i,telemetry:r}),a?ui(t,{billingApiUrl:n,locale:i,telemetry:r}).catch(w=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",w),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?a?s:c:null}}import{Fragment as kn,jsx as ee,jsxs as kt}from"react/jsx-runtime";var mr=44,ta="flopay_checkout_saved_payment_resume",Jo=new Map;function Nr(e){return new Promise(t=>setTimeout(t,e))}function mo(e,t,n){let i=Gr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:vi,enabled:t!==!1});return i.beginCheckout(n),i}function yo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Xo(e,t,n,i,r){let a=mo(e,t,n);a.error({errorCode:i,stage:r,paymentMethodCategory:"unknown",...r==="session_read"?{requestCategory:"session_read"}:{}}),yo(a)}function Qs(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 ea(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function Zo(e){return!e||e.data.stripe?.publishableKey?!1:!!ea(e)?.clientId}function yr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function el(){if(!yr())return null;try{let e=window.sessionStorage.getItem(ta);return e?JSON.parse(e):null}catch{return null}}function hi(e){if(yr())try{window.sessionStorage.setItem(ta,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Qo(){if(yr())try{window.sessionStorage.removeItem(ta)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function tl(e){if(!yr())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 nl(e,t,n){if(yr())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 Pi(e){if(yr())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function rl(){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 bi(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 ol(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 na({sessionId:e,nonce:t,createSession:n,billingApiUrl:i,telemetry:r,appearance:a,locale:c,loading:s,error:w,onComplete:A,onError:p,onDecline:I,onCountryChange:C,onZipChange:T,showPayPal:l=!0,showStripe:f=!0,showApplePay:k=!0,showGooglePay:B=!0,debug:h=!1,layout:q,theme:W,buttonsTheme:ce,buttonsStyles:Z,cardButtonContent:F,cardBackButtonContent:J,cardTitleContent:j,showSecurityFooter:de,onButtonClick:z,onBeforeButtonClick:V,enableAVS:re,cardFieldOrder:Me,cardPreFormSlot:me,avsLayout:pe,className:X,initialErrorMessage:ue=null,children:Pe,checkoutMode:oe,confirmLabel:Fe,renderConfirmButton:ke,onSessionCompleted:ve}){let R=Xs(i),te=pn(()=>Ci(W),[W]),ie=a??te?.appearance,Ne=n?"embedded_checkout":"standard_checkout",De=Pe?"custom_layout":q==="buttons"?"buttons_layout":"default_layout",[Y,M]=wt(null),[H,se]=wt(null),Re=nn(null),[at,Je]=wt(null),Ge=nn(null),[m,$e]=wt(null),[Oe,He]=wt(e??""),qe=e??Oe,Gt=n?"":qe,[Pt,Rt]=wt(!0),[g,Ce]=wt(null),[je,it]=wt("full"),[et,Xe]=wt(!1),[We,be]=wt(ue),[bt,Ve]=wt(null),[Ot,It]=wt(null),[mn,Rn]=wt(void 0),[In,qn]=wt(""),[ht,zt]=wt(!1),[Dt,Jt]=wt("loading"),[rn,yn]=wt(0),K=nn(!1),Fn=nn(!1),fn=nn(!1),Ut=nn(null),tt=pn(()=>({checkoutMode:oe??je,layout:Pe?"unknown":q==="buttons"?"buttons":"embedded"}),[oe,Pe,je,q]),y=nn(A);y.current=A;let mt=nn(p);mt.current=p;let At=nn(I);At.current=I,An(()=>{Mt(H)?.setCheckoutContext(tt),at&&at!==H&&Mt(at)?.setCheckoutContext(tt)},[H,at,tt]);let En=nn(ve);En.current=ve;let ye=Qn(x=>{Jt(x),!(x!=="exhausted"||fn.current)&&(fn.current=!0,mt.current?.(new Bt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Ht=Qn(()=>{Jt("retrying"),yn(x=>x+1)},[]);An(()=>{Jt("loading"),yn(0),fn.current=!1},[qe]),An(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:vi,checkout_type:Ne,checkout_layout:De,billing_api_url:R})},[De,Ne,R]);let on=pn(()=>n?Se(n):"",[n]),Kt=pn(()=>In===on?mn:void 0,[mn,In,on]),an=pn(()=>n?Fo(n,Kt):void 0,[n,Kt]),sn=oe??an?.checkoutMode??"full",Wt=pn(()=>an?{...an,checkoutMode:sn}:void 0,[an,sn]);An(()=>{Rn(void 0),qn(on)},[on]),An(()=>{be(ue)},[ue]);let _n=Qn((x,O,G)=>{dt(()=>{At.current?.(St(x,O,G))})},[dt]),$t=Qn(async(x,O)=>{be(null),It(null),Ve("processing");let G=O?.sessionId??x.id,D=Re.current??Ge.current,$=Mt(D),N=D?null:mo(R,r,tt),u={log:_=>{$?$.log(_):N?.log(_)},error:_=>{$?$.error(_):N?.error(_)},terminal:_=>{$?$.terminal(_):N?.terminal(_)},performance:_=>{$?$.performance(_):N?.performance(_)},now:()=>$?.now()??N?.now()??0,elapsed:_=>$?.elapsed(_)??Math.max(0,(N?.now()??_)-_)},S=u.now(),fe=!!(O?.initialAutoProcessingError||O?.initialAutoProcessingPending),nt=!1,ze,Ee=()=>{nt||(nt=!0,fe=!0,ze=u.now(),u.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),u.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ft=!1,P=()=>{Ft||(Ft=!0,u.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),u.performance({stage:"processing",durationMs:u.elapsed(S),durationMode:"machine",paymentMethodCategory:"saved"}),ze!==void 0&&u.performance({stage:"recovery",durationMs:u.elapsed(ze),durationMode:"machine",paymentMethodCategory:"saved"}))};u.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),u.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),fe&&Ee();let b;try{let _=mi(O?.initialAutoProcessingError),le;if(_)Ee(),_.type==="paypal_redirect_required"&&Ut.current?.publishableKey&&hi({sessionId:G,publishableKey:Ut.current.publishableKey,paypalPublishableKey:Ut.current.paypalPublishableKey}),le=await lo(_,{flopay:Re.current,paypalFlopay:Ge.current,attempt3DS:O?.attempt3DS,billingApiUrl:R,sessionId:G,session:x,telemetry:!1}),_.type==="paypal_redirect_required"&&Qo();else if(O?.initialAutoProcessingPending){let Be=await new po(R,{telemetry:!1}).waitForCheckoutSessionCompletion(O.initialAutoProcessingPending.sessionId,{initialDelayMs:O.initialAutoProcessingPending.retryAfterMs});if(Be.data.session?.status!=="complete")throw new Bt("Automatic payment failed. Please try again.","api_error",{code:Be.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});le={status:"succeeded"}}else{if(O?.initialAutoProcessingError)throw zn(O.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:O.initialAutoProcessingError.checkoutMethod});if(O?.fromCreateSession)return O?.fallbackToFull&&(it("full"),bi("full")),!1;{let we=await pr({billingApiUrl:R,sessionId:G,session:x,telemetry:!1});we.type==="success"?le=we.result:(Ee(),we.type==="paypal_redirect_required"&&Ut.current?.publishableKey&&hi({sessionId:G,publishableKey:Ut.current.publishableKey,paypalPublishableKey:Ut.current.paypalPublishableKey}),le=await lo(we,{flopay:Re.current,paypalFlopay:Ge.current,attempt3DS:O?.attempt3DS,billingApiUrl:R,sessionId:G,session:x,telemetry:!1}),we.type==="paypal_redirect_required"&&Qo())}}G&&sr(G),P(),fe&&(u.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),u.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),u.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Ve("success"),await Nr(Mn),b=()=>y.current?.(le)}catch(_){let le=Zn(_),we=le.checkoutMethod??Lr;return be(le.message),It(le.message),O?.fallbackToFull&&(u.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),it("full"),bi("full")),P(),!!(le.declineCode||le.code?.toLowerCase().includes("declin"))?u.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):le.type==="validation_error"?u.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):u.error({errorCode:fe?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:fe?"recovery":"processing",paymentMethodCategory:"saved"}),dt(()=>mt.current?.(le)),_n(we,le,{code:le.code,declineCode:le.declineCode}),Ve("error"),await Promise.allSettled([Nr(bn),O?.ensureProvidersReady?O.ensureProvidersReady():Promise.resolve()]),fe&&(u.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),u.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{P(),N&&yo(N),Ve(null),It(null)}return dt(b),!0},[_n,dt,Zn,R,r,tt]);An(()=>{if(typeof window>"u"||Fn.current)return;let x=new URLSearchParams(window.location.search),O=x.get("payment_intent_client_secret");if(!O)return;let G=el();G&&(Fn.current=!0,(async()=>{let D,$=0;be(null),It(null),Ve("processing"),Xe(!0);try{if(x.get("redirect_status")==="failed")throw Object.assign(new Bt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:N,paypalFlopay:u}=await uo({publishableKey:G.publishableKey,paypalPublishableKey:G.paypalPublishableKey,billingApiUrl:R,locale:c,telemetry:r});D=Mt(u??N),$=D?.now()??0,D?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),D?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let S=(u??N)?.getRawProvider();if(!S)throw Object.assign(new Bt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:fe,error:nt}=await S.retrievePaymentIntent(O);if(nt)throw Object.assign(new Bt(nt.message??"Failed to retrieve PayPal payment status.","api_error",{code:nt.code}),{checkoutMethod:"paypal"});let ze=Oa(fe?.status);if(!fe||ze==="failed")throw Object.assign(new Bt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Ee=typeof fe.payment_method=="string"?fe.payment_method:fe.payment_method?.id,Ft=ze;if(G.sessionId){let _=(await new po(R,{telemetry:!1}).getUnifiedCheckoutSession(G.sessionId)).data.session;if(_&&_.status!=="complete"){let le=await pr({billingApiUrl:R,sessionId:G.sessionId,session:_,telemetry:!1,tokenizedData:{id:Ee??fe.id,type:"card",threeDSecureActionResultTokenId:fe.id,isPaypal:!0}});if(le.type!=="success")throw Object.assign(new Bt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Ft=le.result.status}}G.sessionId&&sr(G.sessionId),D?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),D?.performance({stage:"redirect_resume",durationMs:D.elapsed($),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),D?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ve("success"),await Nr(Mn),dt(()=>y.current?.({status:Ft,paymentIntentId:fe.id,paymentMethodId:Ee,checkoutMethod:"paypal"}))}catch(N){let u=Zn(N),S=u.checkoutMethod??"paypal",fe=!!(u.declineCode||u.code?.toLowerCase().includes("declin"));if(D)D.performance({stage:"redirect_resume",durationMs:D.elapsed($),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),fe?D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):D.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(fe){let nt=mo(R,r,tt);nt.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),yo(nt)}else Xo(R,r,tt,"REDIRECT_RESUME_FAILED","redirect_resume");be(u.message),It(u.message),dt(()=>mt.current?.(u)),_n(S,u,{code:u.code,declineCode:u.declineCode}),Ve("error"),await Nr(bn)}finally{Qo(),rl(),Ve(null),It(null),Xe(!1)}})())},[_n,dt,c,Zn,R,r]);let qt=nn(null);function Se(x){let O=JSON.stringify({c:x?.clientId,cur:x?.currency??"",a:{e:x?.account?.email?.trim().toLowerCase()??"",country:x?.account?.country??""},successUrl:x?.successUrl,cancelUrl:x?.cancelUrl,p:x?.products?.map(D=>`${D.type??""}:${D.code??D.providerItemId??D.providerPlanId??""}:${D.totalAmount??""}:${D.overrideAmount??""}:${D.quantity??1}`).sort(),i:x?.items?.map(D=>`${D.code??D.providerItemId??""}:${D.totalAmount??""}:${D.overrideAmount??""}:${D.quantity??1}`).sort(),s:x?.subscriptions?.map(D=>`${D.code??D.providerPlanId??""}:${D.totalAmount??""}:${D.overrideAmount??""}:${D.quantity??1}`).sort(),couponCodes:x?.couponCodes,tagsData:x?.tagsData,utmMetadata:x?.utmMetadata,tokenizedData:x?.tokenizedData,m:x?.checkoutMode??"full"}),G=0;for(let D=0;D<O.length;D++)G=(G<<5)-G+O.charCodeAt(D)|0;return`flopay_session_${Math.abs(G).toString(36)}`}let st=pn(()=>Wt?Se(Wt):"",[Wt]),Ze=nn(Wt);Ze.current=Wt,An(()=>{He(e??"")},[e]),An(()=>{K.current=!1,be(ue),It(null),Ve(null)},[st,ue,e]);async function gn(x,O){let G=mo(R,r,tt),D=new po(R,{telemetry:!1});try{let $=tl(O);G.log({name:$?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let N=$?.sid??null,u=null;if(N)try{if(u=await D.getUnifiedCheckoutSession(N,$?.nonce),u.data.session?.status==="complete"){if(Ua(N))return{sid:N,result:u};Pi(O),N=null,u=null}}catch{G.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Pi(O),N=null}if(!N){let S=G.now();G.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let fe={...x,avsCheck:!!re,avsConfig:typeof re=="object"?re:void 0,checkoutType:"embedded_checkout",checkoutLayout:Pe?"custom_layout":q==="buttons"?"buttons_layout":"default_layout"};try{u=await D.createAndFetchSession(fe),G.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),G.performance({stage:"session_create",durationMs:G.now()-S,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"})}catch(nt){let ze=Js(nt,"CHECKOUT_SESSION_CREATE_FAILED","unknown");throw G.performance({stage:"session_create",durationMs:G.now()-S,durationMode:"machine",requestCategory:"session_create",statusClass:ze.statusClass}),nt instanceof Bt&&nt.type==="validation_error"?G.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):ze.statusClass==="4xx"?G.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):G.error({...ze,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),nt}N=u.data.session?.id??"",N&&nl(O,N,u.data.session?.clientSecret)}return{sid:N??"",result:u}}finally{yo(G)}}let ln=Qn(async x=>{let O=Ze.current;if(!O)throw new Bt("createSession is required to bootstrap checkout.","validation_error");let G=Fo(O,x),D=Se(G),$=Jo.get(D);$||($=gn(G,D),Jo.set(D,$));let N;try{N=await $}finally{Jo.delete(D)}qt.current=D;try{x&&(qn(on),Rn(Ft=>La(Ft,x)));let{sid:u,result:S}=N;M(S),S.data.session&&$e(S.data.session),u&&He(u);let{publishableKey:fe,paypalPublishableKey:nt}=co(S),{flopay:ze,paypalFlopay:Ee}=await uo({publishableKey:fe,paypalPublishableKey:nt,billingApiUrl:R,locale:c,telemetry:r});Re.current=ze,se(ze),Ge.current=Ee,Je(Ee),Rt(!1)}catch(u){throw qt.current===D&&(qt.current=null),u}return N},[c,R,r,tt]),vt=Qn(async x=>{if(!ol(x)||ht)return{sessionId:Oe,session:m};zt(!0);try{let O=await ln(x);return{sessionId:O.sid,session:O.result.data.session??null}}finally{zt(!1)}},[ln,ht,Oe,m]);An(()=>{let x=!1;if(Ce(null),st){let D=Ze.current;return it(sn),Rt(!1),qt.current===st?()=>{x=!0}:($e(Na(D,oe)),(async()=>{let $=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),N=sn==="auto"&&!K.current&&!$;N&&(be(null),It(null),Ve("processing"));try{let u=await ln(),S=u.result.data.session??null;Ut.current=co(u.result);let fe=Zo(u.result);if(!x&&N&&S&&!fe){K.current=!0,await $t(S,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:u.result.autoProcessingError,initialAutoProcessingPending:u.result.autoProcessingPending,autoProcessingAttempted:u.result.autoProcessingAttempted,sessionId:u.sid||S.id});return}!x&&N&&(fe&&(K.current=!0),Ve(null),It(null))}catch(u){if(x)return;let S=u instanceof Bt||typeof u=="object"&&u!==null&&"code"in u?u.code:void 0;if(N&&S==="session_auto_completed"){K.current=!0,Ve("success"),await Nr(Mn),x||(dt(()=>{y.current?.({status:"succeeded"})}),Ve(null),It(null));return}N&&(Ve(null),It(null));let fe=u instanceof Bt?u:new Bt(u instanceof Error?u.message:"Failed to create session","api_error");Ce(fe)}})(),()=>{x=!0})}Rt(!0);async function O(){let D=!1;try{let N=await new po(R,{telemetry:!1}).getUnifiedCheckoutSession(qe,t);if(x)return;M(N);let u=N.data.session??null;if($e(u),!u)throw new Bt("No session data returned","api_error");if(u.status==="complete"){Rt(!1),dt(()=>{En.current?.(u.successUrl??"")});return}if(u.status==="expired")throw new Bt("Checkout session has expired.","api_error",{code:"checkout_session_expired"});D=!0;let S=oe??u.checkoutMode??"full";it(S);let fe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),nt=Zo(N);if(S==="auto"&&!K.current&&!fe&&!nt){K.current=!0;let ze=G(N);try{if(await $t(u,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ze,sessionId:qe||u.id}),x)return;await ze,x||Rt(!1);return}catch{if(x)return;await ze,x||Rt(!1);return}}await G(N),x||Rt(!1)}catch($){if(x)return;$ instanceof Bt?!D&&!Qs($)&&Xo(R,r,tt,"NETWORK_REQUEST_FAILED","session_read"):Xo(R,r,tt,"INTERNAL_SDK_ERROR","checkout_mount");let N=$ instanceof Bt?$:new Bt($ instanceof Error?$.message:"Failed to initialize checkout","api_error");Ce(N),Rt(!1)}}async function G(D){let{publishableKey:$,paypalPublishableKey:N}=co(D);Ut.current={publishableKey:$,paypalPublishableKey:N};let{flopay:u,paypalFlopay:S}=await uo({publishableKey:$,paypalPublishableKey:N,billingApiUrl:R,locale:c,telemetry:r});Re.current=u,se(u),Ge.current=S,Je(S)}return O(),()=>{x=!0}},[ln,oe,st,sn,Gt,dt,t,$t]);let Lt=Qn(async()=>{if(!(et||!m)){Xe(!0),be(null);try{await $t(m,{fallbackToFull:!0,sessionId:qe||m.id})}finally{Xe(!1)}}},[qe,et,$t,m]),Nt=ea(Y),jn=Zo(Y),Dn=pn(()=>{if(!Y||!m||!Y.data.stripe?.publishableKey)return;let x={appearance:ie,paymentMethodCreation:"manual",billingApiUrl:R};if(Y.data.stripe?.clientSecret)x.clientSecret=Y.data.stripe.clientSecret;else{let O=gi(m).total;x.amount=Math.round(O*100)||m.amount,x.currency=m.currency?.toLowerCase()}return x},[Y,m,ie,R]),xn=!!(n&&!Pe&&q==="buttons"&&V&&sn==="full"),jt=pn(()=>({session:m,loading:Pt,error:g,checkoutMode:je,inlineSessionDraft:Wt,applyInlineSessionPatch:xn?vt:void 0,inlineSessionPatchProcessing:ht}),[m,Pt,g,je,Wt,xn,vt,ht]),cn=!!n&&q==="buttons"&&!jn&&(!H||!Dn),Te=bt?ee(vn,{status:bt,errorMessage:Ot}):null;if(Pt){if(s)return kt(kn,{children:[s,Te]});if(q==="buttons"){let x=te?.buttonsLayout?.cardButton?.borderRadius??te?.appearance.variables?.borderRadius??8,O=G=>ee("div",{style:{height:G,borderRadius:x,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return kt(kn,{children:[kt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[l&&O(mr),f&&(k||B)&&O(mr),f&&O(mr),ee("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Te]})}return kt(kn,{children:[kt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ee("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ee("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Te]})}return g?w?ee(un.Provider,{value:jt,children:w(g)}):ee(un.Provider,{value:jt,children:ee("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:g.message})}):cn?kt(kn,{children:[ee(un.Provider,{value:jt,children:ee(il,{onButtonClick:z,showPayPal:l,showStripe:f,showApplePay:k,showGooglePay:B,theme:W,buttonsTheme:ce,buttonsStyles:Z,cardButtonContent:F,cardBackButtonContent:J,cardTitleContent:j})}),Te]}):jn&&m&&Nt?kt(kn,{children:[ee(un.Provider,{value:jt,children:kt("div",{className:X,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[We&&ee(ar,{icon:!1,children:We}),Dt==="retrying"&&ee("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Dt==="exhausted"&&kt("div",{role:"alert",children:[ee("div",{children:"PayPal is temporarily unavailable. Please try again."}),ee("button",{type:"button",onClick:Ht,children:"Retry PayPal"})]}),Dt!=="exhausted"&&ee("div",{"aria-hidden":Dt==="retrying"?!0:void 0,style:Dt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ee(Ka,{sessionId:qe,nonce:m.clientSecret||void 0,billingApiUrl:R,email:m.customer?.email,clientId:Nt.clientId,environment:Nt.environment,currency:(m.currency??"usd").toUpperCase(),isSubscription:m.mode==="subscription",onComplete:A,onErrorChange:be,onDecline:I,onButtonClick:z,onInitializationStateChange:ye,allowAutomaticRetry:rn===0,session:m,telemetry:r,telemetryContext:tt,debug:h},`paypal-init-${rn}`)})]})}),Te]}):!H||!Dn?ee(kn,{children:Te}):je==="confirm"?kt(kn,{children:[ee(un.Provider,{value:jt,children:ee(Jr,{flopay:H,paypalFlopay:at,options:Dn,children:kt("div",{className:X,children:[We&&ee("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:We}),ke?ke({onConfirm:Lt,isProcessing:et}):ee("button",{type:"button",onClick:Lt,disabled:et,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:et?"not-allowed":"pointer",opacity:et?.6:1},children:et?"Processing...":Fe??"Confirm Purchase"})]})})}),Te]}):kt(kn,{children:[ee(un.Provider,{value:jt,children:ee(Jr,{flopay:H,paypalFlopay:at,options:Dn,children:Pe?kt(kn,{children:[We&&ee("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:We}),ee(al,{sessionId:qe,nonce:m?.clientSecret||void 0,billingApiUrl:R,session:m,children:Pe})]}):ee(Wo,{sessionId:qe,nonce:m?.clientSecret||void 0,email:m?.customer?.email,userId:m?.customer?.id,firstName:m?.customer?.firstName,lastName:m?.customer?.lastName,totalAmount:m?Math.round(gi(m).total*100):0,currency:m?.currency?.toLowerCase()??"usd",onComplete:A,onError:p,onDecline:I,error:We,onErrorChange:be,showPayPal:l,showStripe:f,enabledPaymentMethods:Y?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Y?.data.stripe?.enabledPaymentMethodCountries,showApplePay:k,showGooglePay:B,layout:q,theme:W,buttonsTheme:ce,buttonsStyles:Z,appearance:ie,cardButtonContent:F,cardBackButtonContent:J,cardTitleContent:j,onButtonClick:z,onBeforeButtonClick:V,enableAVS:re,...Me?{cardFieldOrder:Me}:{},...me?{cardPreFormSlot:me}:{},avsLayout:pe,country:m?.customer?.country,city:m?.customer?.city,state:m?.customer?.state,onCountryChange:C,onZipChange:T,avsCheck:!!re,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Pe?"custom_layout":q==="buttons"?"buttons_layout":"default_layout",className:X,directPaypal:ea(Y),isSubscription:m?.mode==="subscription",session:m,debug:h})})}),Te]})}function al({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:r}){return ee(kn,{children:Go.Children.map(r,a=>{if(!Go.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:Go.cloneElement(a,s)})})}function il({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:i,showGooglePay:r,theme:a,buttonsTheme:c,buttonsStyles:s,cardButtonContent:w,cardBackButtonContent:A,cardTitleContent:p}){let[I,C]=wt(!1),T=pn(()=>Ci(a),[a]),l=pn(()=>{let h=T?.buttonsLayout??Zs(c);return s?{...h,...s,cardButton:{...h.cardButton,...s.cardButton},cardFormContainer:{...h.cardFormContainer,...s.cardFormContainer},backButton:{...h.backButton,...s.backButton},backButtonIcon:{...h.backButtonIcon,...s.backButtonIcon},submitButton:{...h.submitButton,...s.submitButton},title:{...h.title,...s.title}}:h},[T,c,s]),f=T?.buttonsLayout?.cardButton?.borderRadius??T?.appearance.variables?.borderRadius??8,k=h=>ee("div",{style:{height:h,borderRadius:f,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),B=w===void 0?{boxSizing:"border-box",height:mr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(I){let h=l.cardInputBorder??"#e5e7eb",q=l.cardInputBackground??"white",W=tr(A),ce=tr(p);return kt("div",{style:{backgroundColor:l.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...l.cardFormContainer},children:[kt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[kt("button",{type:"button",onClick:()=>C(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:W?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:[ee("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...l.backButtonIcon},children:ee("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:ee("path",{d:"M15 18l-6-6 6-6"})})}),ee(rr,{content:A})]}),ce?ee("div",{style:{flex:1}}):ee("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...l.title},children:ee(Tr,{content:p})})]}),ee("div",{style:{backgroundColor:q,border:`1px solid ${h}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ee("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),kt("div",{style:{display:"flex"},children:[ee("div",{style:{flex:1,backgroundColor:q,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomLeftRadius:8,padding:12,height:45},children:ee("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ee("div",{style:{flex:1,backgroundColor:q,borderTop:"none",borderRight:`1px solid ${h}`,borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomRightRadius:8,padding:12,height:45},children:ee("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ee("div",{style:{backgroundColor:q,border:`1px solid ${h}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ee("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ee("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...l.submitButton,opacity:.5}}),ee("style",{children:`
38
+ `}),xr&&Vn&&Be("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ee?-2:0},children:[Be("button",{type:"button",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:Mo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:I.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...I.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...I.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(lr,{content:q})]}),Ta?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:I.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...I.title},children:d(Fr,{content:ae})})]}),!xr&&!Ta&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Bo,order:Ee?-3:0,...I.title},children:d(Fr,{content:ae})}),K&&d("div",{style:{order:Ee?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let o=je,b=(D=!1)=>({backgroundColor:Mr,border:`1px solid ${Wn(D)}`,borderRadius:gt,marginTop:"0.5rem",padding:"10px"}),z=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Fa}),oe=Es(o);return Be(fr,{children:[Me(K.address_line_1,o)&&d("div",{style:b(Lt.line1),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Ge,onChange:D=>{Dt.current=D.target.value,we(D.target.value)},disabled:P,required:!0,"data-testid":"flopay-address-line1",style:z()})}),Me(K.address_line_2,o)&&d("div",{style:b(),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:bt,onChange:D=>{Jt.current=D.target.value,Ke(D.target.value)},disabled:P,"data-testid":"flopay-address-line2",style:z()})}),(Me(K.city,o)||Me(K.state,o))&&Be("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Me(K.city,o)&&d("div",{style:{flex:1,backgroundColor:Mr,borderTop:`1px solid ${Wn(Lt.city)}`,borderRight:`1px solid ${Wn(Lt.city)}`,borderBottom:`1px solid ${Wn(Lt.city)}`,borderLeft:`1px solid ${Wn(Lt.city)}`,padding:"10px",borderTopLeftRadius:gt,borderBottomLeftRadius:gt,...Me(K.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:Ut,onChange:D=>{an.current=D.target.value,Et(D.target.value)},disabled:P,required:!0,"data-testid":"flopay-city",style:z()})}),Me(K.state,o)&&d("div",{style:{flex:1,backgroundColor:Mr,border:`1px solid ${Wn(Lt.state)}`,padding:"10px",borderTopRightRadius:gt,borderBottomRightRadius:gt,...Me(K.city,o)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:gt}},children:oe?Be("select",{id:"flopay-billing-state",name:"billing-state",value:mn,onChange:D=>{yn.current=D.target.value,En(D.target.value)},disabled:P,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...z(),cursor:"pointer"},children:[d("option",{value:"",children:ei(o)}),oe.map(D=>d("option",{value:D.code,children:D.name},D.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:ei(o),autoComplete:"billing address-level1",value:mn,onChange:D=>{yn.current=D.target.value,En(D.target.value)},disabled:P,required:!0,"data-testid":"flopay-state",style:z()})})]}),(Me(K.country,o)||Me(K.postal_code,o))&&Be("div",{style:{display:"flex",flexDirection:ie==="column"?"column":"row",gap:ie==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Me(K.country,o)&&d("div",{style:{flex:ie==="row"?1:void 0,backgroundColor:Mr,borderTop:`1px solid ${Tr}`,borderRight:`1px solid ${Tr}`,borderBottom:`1px solid ${Tr}`,borderLeft:`1px solid ${Tr}`,padding:"10px",...ie==="row"&&Me(K.postal_code,o)?{borderRadius:"0",borderTopLeftRadius:gt,borderBottomLeftRadius:gt,borderRight:"none"}:{borderRadius:gt}},children:d("select",{id:"flopay-billing-country",name:"billing-country",value:je,onChange:D=>{$t.current=D.target.value,st(D.target.value),ze?.(D.target.value),yn.current="",En("")},disabled:P,autoComplete:"billing country","data-testid":"flopay-country",style:{...z(),cursor:"pointer"},children:_s.map(D=>Be("option",{value:D.code,children:[D.flag," ",D.name]},D.code))})}),Me(K.postal_code,o)&&d("div",{style:{flex:ie==="row"?1:void 0,backgroundColor:Mr,border:`1px solid ${Wi}`,padding:"10px",...ie==="row"&&Me(K.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(je),autoComplete:"billing postal-code",value:rt,onChange:D=>{ht.current=D.target.value,et(D.target.value),Ne?.(D.target.value)},onBlur:()=>Vt(!0),disabled:P,required:_t.required,"aria-invalid":Gr||void 0,"aria-describedby":Gr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:z()})})]}),Gr&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:xo,...Fa,fontSize:"0.75rem"},children:_t.empty?`${Yo(o)} is required`:Ws(o)})]})})()}),Ee&&Se&&d("div",{style:{order:-2,width:"100%"},children:Se}),Ee&&Zi,le&&d(dr,{margin:"0.75rem 0",styleOverride:I.errorBanner,children:le})]}),Jr={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},La=o=>$e?!S||!bn?d("pre",{"data-testid":o,style:Jr,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":o,style:Jr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${S}`,` directPaypalConfigured=${bn}`,` inAppBrowserDetected=${String(Wr)}`,` shouldRenderDirectPayPal=${Rr}`,` shouldRenderStripePayPal=${Ir}`,` hasPaypalStripeInstance=${!!Te}`].join(`
39
+ `)}):null,Na=o=>$e?!M||!ct?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=${M}`,` currency=${xe}`,` amountInCents=${ke}`,` 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=${!!ct}`,` shouldRenderWallets=${Er}`,` shouldRenderPaymentElement=${_r}`].join(`
40
+ `)}):null,Oa=ve==="apm-expanding"||ve==="apm-form"||ve==="apm-collapsing",Xr=ve==="apm-expanding"?`flopay-card-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:ve==="apm-collapsing"?`flopay-card-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Zr=lt?{...ko,paymentMethodTypes:[lt]}:null;if(Q==="buttons"){let o=ve==="buttons"||ve==="expanding"||ve==="apm-expanding",b=ve==="expanding"||ve==="card"||ve==="collapsing",z=N===void 0?{boxSizing:"border-box",height:co,padding:"0 1rem"}:{padding:"0.9rem 1rem"},oe=ve==="expanding"||ve==="apm-expanding"?`flopay-buttons-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:ve==="collapsing"||ve==="apm-collapsing"?`flopay-buttons-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,D=ve==="expanding"?`flopay-card-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:ve==="collapsing"?`flopay-card-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Be("form",{onSubmit:Eo,className:v,style:{position:"relative"},children:[d(Wo,{}),H&&d(Sn,{status:H,errorMessage:le}),Be("div",{style:{display:"grid"},children:[Be("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!o&&!oe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!o&&!oe?Ks:{},...oe?{animation:oe,pointerEvents:"none"}:{}},children:[La("flopay-direct-paypal-gate-debug"),Na("flopay-stripe-gate-debug"),Rr&&Qe&&Be(fr,{children:[L&&d("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),d(so,{sessionId:e,nonce:t,billingApiUrl:F,email:V.email,clientId:Qe.clientId,environment:Qe.environment,currency:xe.toUpperCase(),isSubscription:Ze,onTokenizedBody:Qt,onComplete:a,onErrorChange:pe,onDecline:s,onTechnicalFailure:or,onButtonClick:Pe,runBeforeButtonClick:dn,isProcessing:P,onLoadStateChange:Ro,onInitializationStateChange:Io,session:u??null,existingOrderId:L?.orderId,debug:$e},L?.orderId??"fresh")]}),Ir&&d(er,{stripe:Te,options:zt,children:d(ci,{sessionId:e,nonce:t,email:V.email,billingApiUrl:F,onTokenizedBody:Qt,onErrorChange:pe,isProcessing:P,onButtonClick:Pe,onDecline:s,onTechnicalFailure:or,runBeforeButtonClick:dn,onLoadStateChange:fa,placeholderBorderRadius:Yn})}),Er?d(er,{stripe:ct,options:Yt,children:d(di,{sessionId:e,nonce:t,email:V.email,billingApiUrl:F,intentKind:de>0?"payment":"setup",expressMethods:Vr,onTokenizedBody:Qt,onErrorChange:pe,onButtonClick:Pe,onDecline:s,onTechnicalFailure:or,runBeforeButtonClick:dn,onLoadStateChange:ha,placeholderBorderRadius:Yn})}):Sa?d("div",{style:{height:co,borderRadius:Yn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,_r&&d(ui,{sessionId:e,nonce:t,email:V.email,billingName:[V.firstName,V.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:F,paymentElementMethods:Hr,stripeInstance:ct,paymentElementBaseOptions:ko,onTokenizedBody:Qt,onErrorChange:pe,onButtonClick:Pe,onDecline:s,runBeforeButtonClick:dn,onLoadStateChange:ba,isProcessing:P,submitButtonColor:Gn,submitButtonBorderRadius:gt,submitButtonStyle:I.submitButton,onExpandApm:R,expandedApmMethod:lt,themeId:A,buttonAppearance:{backgroundColor:I.cardButton?.backgroundColor,borderColor:I.cardInputBorder,textColor:I.cardButton?.color,borderRadius:Yn}}),Ee&&d("button",{type:"button",onClick:async()=>{P||!(await dn("card")).proceed||(Pe?.("card"),rr())},disabled:P,style:{width:"100%",...z,...I.cardButton,...Qo({themeBundle:ge,resolvedPrimaryColor:Gn,resolvedBorderRadius:gt,submitButtonStyle:I.submitButton,explicitPrimaryColor:Kt?.colorPrimary}),fontSize:I.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:P?"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:P?.6:1},onMouseEnter:ee=>{!P&&(ge||Kt?.colorPrimary)&&(ee.currentTarget.style.backgroundColor=Ji)},onMouseLeave:ee=>{(ge||Kt?.colorPrimary)&&(ee.currentTarget.style.backgroundColor=Gn)},onMouseDown:ee=>{ee.currentTarget.style.transform="scale(0.985)"},onMouseUp:ee=>{ee.currentTarget.style.transform="scale(1)"},children:d(sr,{content:N})}),le&&ve==="buttons"&&d(dr,{margin:"0.25rem 0",styleOverride:I.errorBanner,children:le})]}),Ee&&b&&d("div",{style:{gridArea:"1 / 1",...D?{animation:D}:{},...ve==="collapsing"?{pointerEvents:"none"}:{}},children:Da}),M&&Oa&&lt&&Zr&&ct&&d("div",{style:{gridArea:"1 / 1",...Xr?{animation:Xr}:{},...ve==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Be("div",{style:{backgroundColor:To,borderRadius:Fo,...Br,padding:Ao},children:[Be("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Be("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:O,style:{display:"inline-flex",alignItems:"center",gap:Mo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:I.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...I.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...I.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(lr,{content:q})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:I.titleFontSize??"1.05rem",color:Bo,paddingRight:80,...I.title},children:`Pay with ${gr(lt)}`})]}),d(er,{stripe:ct,options:Zr,children:d(Go,{method:lt,sessionId:e,nonce:t,email:V.email,billingName:[V.firstName,V.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:F,onTokenizedBody:Qt,onErrorChange:pe,onDecline:s,onCancel:O,runBeforeButtonClick:dn,onButtonClick:Pe,isProcessing:P,submitButtonColor:Gn,submitButtonBorderRadius:gt,submitButtonStyle:I.submitButton,errorText:le})},lt)]})})]})]})}return Oa&&lt&&Zr&&ct&&M?Be("form",{onSubmit:Eo,className:v,style:{position:"relative"},children:[d(Wo,{}),H&&d(Sn,{status:H,errorMessage:le}),d("div",{style:{...Xr?{animation:Xr}:{},...ve==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Be("div",{style:{backgroundColor:To,borderRadius:Fo,...Br,padding:Ao},children:[Be("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Be("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:O,style:{display:"inline-flex",alignItems:"center",gap:Mo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:I.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...I.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...I.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(lr,{content:q})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:I.titleFontSize??"1.05rem",color:Bo,paddingRight:80,...I.title},children:`Pay with ${gr(lt)}`})]}),d(er,{stripe:ct,options:Zr,children:d(Go,{method:lt,sessionId:e,nonce:t,email:V.email,billingName:[V.firstName,V.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:F,onTokenizedBody:Qt,onErrorChange:pe,onDecline:s,onCancel:O,runBeforeButtonClick:dn,onButtonClick:Pe,isProcessing:P,submitButtonColor:Gn,submitButtonBorderRadius:gt,submitButtonStyle:I.submitButton,errorText:le})},lt)]})})]}):Be("form",{onSubmit:Eo,className:v,style:{position:"relative"},children:[d(Wo,{}),H&&d(Sn,{status:H,errorMessage:le}),Be("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[La("flopay-direct-paypal-gate-debug-default"),Na("flopay-stripe-gate-debug-default"),Rr&&Qe&&Be(fr,{children:[L&&d("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),d(so,{sessionId:e,nonce:t,billingApiUrl:F,email:V.email,clientId:Qe.clientId,environment:Qe.environment,currency:xe.toUpperCase(),isSubscription:Ze,onTokenizedBody:Qt,onComplete:a,onErrorChange:pe,onDecline:s,onTechnicalFailure:or,onButtonClick:Pe,runBeforeButtonClick:dn,isProcessing:P,onLoadStateChange:Ro,onInitializationStateChange:Io,session:u??null,existingOrderId:L?.orderId,debug:$e},L?.orderId??"fresh")]}),Ir&&d(er,{stripe:Te,options:zt,children:d(ci,{sessionId:e,nonce:t,email:V.email,billingApiUrl:F,onTokenizedBody:Qt,onErrorChange:pe,isProcessing:P,onButtonClick:Pe,onDecline:s,onTechnicalFailure:or,runBeforeButtonClick:dn,onLoadStateChange:fa,placeholderBorderRadius:Yn})}),Er&&d(er,{stripe:ct,options:Yt,children:d(di,{sessionId:e,nonce:t,email:V.email,billingApiUrl:F,intentKind:de>0?"payment":"setup",expressMethods:Vr,onTokenizedBody:Qt,onErrorChange:pe,onButtonClick:Pe,onDecline:s,onTechnicalFailure:or,runBeforeButtonClick:dn,onLoadStateChange:ha,placeholderBorderRadius:Yn})}),_r&&d(ui,{sessionId:e,nonce:t,email:V.email,billingName:[V.firstName,V.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:F,paymentElementMethods:Hr,stripeInstance:ct,paymentElementBaseOptions:ko,onTokenizedBody:Qt,onErrorChange:pe,onButtonClick:Pe,onDecline:s,runBeforeButtonClick:dn,onLoadStateChange:ba,isProcessing:P,submitButtonColor:Gn,submitButtonBorderRadius:gt,submitButtonStyle:I.submitButton,themeId:A,onExpandApm:R,expandedApmMethod:lt,buttonAppearance:{backgroundColor:I.cardButton?.backgroundColor,borderColor:I.cardInputBorder,textColor:I.cardButton?.color,borderRadius:Yn}})]}),Ee&&(ji||qi||Ki)&&Be("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),d("span",{children:"or pay with card"}),d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ee&&Da]})}import{loadFloPay as Pi,PaymentAPI as bi}from"@flopay/js";import{FloPayError as at,isSetupIntentClientSecret as Zs}from"@flopay/shared";var Ur="card";async function Qs(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:i,error:r}=await e.retrievePaymentIntent(t);return{error:r,intent:i??null}}async function el(e,t,n,i){if(i){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:c??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:r,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:r??null}}function Rn(e,t){return Object.assign(e,{checkoutMethod:t})}function vi(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function tl(e){return e.status==="succeeded"||e.status==="declined"}async function Ci(e){if(typeof document>"u"||typeof window>"u")throw new at("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new at("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,i=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let p=new AbortController,k=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",k);let v=window.setTimeout(()=>p.abort(),i);try{let E=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:p.signal});if(!E.ok)return{status:"unknown"};let l=await E.json().catch(()=>null);return nl(l)}catch{return{status:"unknown"}}finally{window.clearTimeout(v),e.signal?.removeEventListener("abort",k)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let C=document.createElement("iframe");C.setAttribute("title","Card authentication"),C.setAttribute("allow","payment"),C.tabIndex=0,C.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),C.src=e.nextActionRedirectUrl,s.appendChild(C),document.body.appendChild(s),C.focus();let B=null;try{B=new URL(e.billingApiUrl,window.location.href).origin}catch{B=null}try{let p=await new Promise((k,v)=>{let E=!1,l=0,y=0,S=0,M=!1,f=()=>{window.clearTimeout(l),window.clearInterval(y),window.clearTimeout(S),window.removeEventListener("message",Q),C.removeEventListener("load",W),e.signal?.removeEventListener("abort",me)},U=async()=>{if(!(E||M)){M=!0;try{let A=await a();if(E||!tl(A))return;E=!0,f(),k(A)}finally{M=!1}}},W=()=>{window.clearTimeout(S),S=window.setTimeout(()=>{U()},250)},me=()=>{E||(E=!0,f(),v(new at("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Q=A=>{if(A.source!==C.contentWindow||B&&A.origin!==B)return;let G=A.data;!G||typeof G!="object"||G.source!=="flopay-vault-3ds-return"||E||(E=!0,f(),k(null))};l=window.setTimeout(()=>{E||(E=!0,f(),v(new at("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),y=window.setInterval(()=>{U()},n),C.addEventListener("load",W),window.addEventListener("message",Q),e.signal?.addEventListener("abort",me),e.signal?.aborted&&me()});return p||await a()}finally{s.parentNode?.removeChild(s),c?.isConnected&&c.focus()}}function nl(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Un(e,t="Payment failed. Please try again.",n){let i=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),r=e?.message??t,a=Nn(r)??r;return Rn(new at(a,"api_error",{code:e?.gatewayErrorCode}),i)}function ta(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function po(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function rl(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function Si(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||po(r)))return r;let i=e?.data;if(i&&typeof i=="object"){let r=i,a=[r.threeDSecureToken,r.clientSecret,r.stripeClientSecret,r.id];for(let s of a)if(typeof s=="string"&&s.length>0&&(!t?.requirePaymentIntentClientSecret||po(s)))return s;let c=r.gateways;if(c&&typeof c=="object"){let s=c.stripe;if(s&&typeof s=="object"){let C=s,B=[C.stripeClientSecret,C.clientSecret];for(let p of B)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||po(p)))return p}}}}async function ol({billingApiUrl:e,sessionId:t,nonce:n,responseJson:i}){let r=Si(i,{requirePaymentIntentClientSecret:!0});if(typeof r=="string"&&r.length>0)return{type:"3ds_required",threeDSecureToken:r};if(!t)return null;try{let s=(await new bi(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(po(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function hr({billingApiUrl:e,sessionId:t,session:n,nonce:i,tokenizedData:r,returnUrl:a,telemetry:c}){let s=e.replace(/\/+$/,""),C=t??n.id,B=i??n.clientSecret,p=n.customer?.id??n.accountData?.userId??"",k=n.customer?.email??n.accountData?.email??"",v=n.customer?.firstName??n.accountData?.firstName??"",E=n.customer?.lastName??n.accountData?.lastName??"",l=n.customer?.country??n.accountData?.country??void 0,y=n.customer?.zip??n.accountData?.zip??void 0,S=new bi(s,c===!1?{telemetry:!1}:void 0),M=await rl(()=>S.processPayment(p,{sessionId:C,nonce:B,tokenizedData:r,accountData:{userId:p,email:k,firstName:v,lastName:E,country:l,zip:y},returnUrl:a??ta(n)}));if(M.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:ro(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}};let f=await M.json().catch(()=>null);if(f?.type==="paypal_redirect_required"||f?.type==="3ds_required"){let U=Si(f);if(!U)throw new at("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:f.type,threeDSecureToken:U,paymentMethodId:f.paymentMethodId}}if(f?.gatewayErrorCode==="authentication_required"){let U=await ol({billingApiUrl:s,sessionId:C,nonce:B,responseJson:f});if(U)return U;throw Rn(new at("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new at(f?.message??"Payment failed. Please try again.","api_error",{code:f?.code??f?.gatewayErrorCode,declineCode:f?.declineCode??f?.gatewayDeclineReason})}async function mo(e,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:c,returnUrl:s,telemetry:C}){let B=t?.getRawProvider();if(!B)throw new at("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!i||!e.threeDSecureToken)throw Rn(new at("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let p=Zs(e.threeDSecureToken),k=null,v=e.paymentMethodId,E=await Qs(B,e.threeDSecureToken,p);if(E){if(E.error)throw Rn(new at(E.error.message??`Failed to retrieve 3DS ${p?"setup":"payment"} status.`,"api_error",{code:E.error.code}),"card");let y=E.intent;!v&&y?.payment_method&&(typeof y.payment_method=="string"?v=y.payment_method:"id"in y.payment_method&&(v=y.payment_method.id??void 0))}let l=v?await el(B,e.threeDSecureToken,{payment_method:v,return_url:s??ta(c)??window.location.href},p):null;if(l){if(l.error)throw Rn(new at(l.error.message??"3DS authentication failed.","api_error",{code:l.error.code}),"card");k=l.intent}else{let y=await B.handleNextAction({clientSecret:e.threeDSecureToken});if(y.error)throw Rn(new at(y.error.message??"3DS authentication failed.","api_error",{code:y.error.code}),"card");k=(p?y.setupIntent:y.paymentIntent)??null}if(k&&(k.status==="requires_capture"||k.status==="succeeded"||k.status==="processing")){let y=await hr({billingApiUrl:r,sessionId:a,session:c,telemetry:C,tokenizedData:{id:k.id,type:"card",threeDSecureActionResultTokenId:k.id},returnUrl:s});return y.type==="success"?{...y.result,paymentIntentId:y.result.paymentIntentId??k.id,paymentMethodId:y.result.paymentMethodId??v}:mo(y,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:c,returnUrl:s,telemetry:C})}throw Rn(new at("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let p=(n??t)?.getRawProvider();if(!p)throw Rn(new at("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:v}=await p.handleNextAction({clientSecret:e.threeDSecureToken});if(v)throw Rn(new at(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:k}=await p.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??ta(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(k)throw Rn(new at(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new at("Unsupported payment redirect state.","api_error")}function tr(e){if(e instanceof at){let i=Nn(e.message);return i&&i!==e.message?Object.assign(new at(i,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Nn(t)??t;return new at(n,"api_error")}function yo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new at("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function fo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:i,telemetry:r}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[c,s]=await Promise.all([Pi(e,{billingApiUrl:n,locale:i,telemetry:r}),a?Pi(t,{billingApiUrl:n,locale:i,telemetry:r}).catch(C=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",C),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?a?s:c:null}}import{Fragment as In,jsx as te,jsxs as Rt}from"react/jsx-runtime";var Pr=44,la="flopay_checkout_saved_payment_resume",vo=new Map,ho=new Map;function Ri(e,t){t.settled&&t.consumers===0&&vo.get(e)===t&&vo.delete(e)}function ll(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 cl(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function sa(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function oa(e){return!e||e.data.stripe?.publishableKey?!1:!!sa(e)?.clientId}function Fn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function dl(){if(!Fn())return null;try{let e=window.sessionStorage.getItem(la);return e?JSON.parse(e):null}catch{return null}}function Ii(e){if(Fn())try{window.sessionStorage.setItem(la,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function aa(){if(Fn())try{window.sessionStorage.removeItem(la)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ca=":idempotency-key";function ul(e){if(!Fn())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function pl(e,t,n){if(Fn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(i){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",i)}}function Ti(e){if(Fn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function ml(e){if(Fn())try{return window.sessionStorage.getItem(e+ca)??void 0}catch{return}}function yl(e,t){if(Fn())try{window.sessionStorage.setItem(e+ca,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function fl(e){if(Ti(e),!!Fn())try{window.sessionStorage.removeItem(e+ca)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function gl(){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 hl(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function ia(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function da({sessionId:e,nonce:t,createSession:n,billingApiUrl:i,telemetry:r,appearance:a,locale:c,loading:s,error:C,onComplete:B,onError:p,onDecline:k,onCountryChange:v,onZipChange:E,showPayPal:l=!0,showStripe:y=!0,showApplePay:S=!0,showGooglePay:M=!0,debug:f=!1,layout:U,theme:W,buttonsTheme:me,buttonsStyles:Q,cardButtonContent:A,cardBackButtonContent:G,cardTitleContent:$,showSecurityFooter:ye,onButtonClick:N,onBeforeButtonClick:q,enableAVS:ae,cardFieldOrder:Fe,cardPreFormSlot:Pe,avsLayout:he,className:J,initialErrorMessage:fe=null,children:Se,checkoutMode:ie,confirmLabel:Le,renderConfirmButton:_e,onSessionCompleted:Re}){let w=il(i),ne=pn(()=>xi(W),[W]),ce=a??ne?.appearance,ze=n?"embedded_checkout":"standard_checkout",Ne=Se?"custom_layout":U==="buttons"?"buttons_layout":"default_layout",[Y,x]=kt(null),[j,de]=kt(null),xe=on(null),[it,Qe]=kt(null),Ze=on(null),[u,$e]=kt(null),[Ue,We]=kt(e??""),qe=e??Ue,Gt=n?"":qe,[Pt,It]=kt(!0),[g,Ie]=kt(null),[je,st]=kt("full"),[rt,et]=kt(!1),[Ge,we]=kt(fe),[bt,Ke]=kt(null),[Ut,Et]=kt(null),[mn,En]=kt(void 0),[_n,jn]=kt(""),[ht,$t]=kt(!1),[Dt,Jt]=kt("loading"),[an,yn]=kt(0),K=on(!1),Dn=on(!1),fn=on(!1),qt=on(null),Ft=pn(()=>({checkoutMode:ie??je,layout:Se?"unknown":U==="buttons"?"buttons":"embedded"}),[ie,Se,je,U]),_=on(B);_.current=B;let Je=on(p);Je.current=p;let Ee=on(k);Ee.current=k,An(()=>{Bt(j)?.setCheckoutContext(Ft),it&&it!==j&&Bt(it)?.setCheckoutContext(Ft)},[j,it,Ft]);let Ln=on(Re);Ln.current=Re;let Ve=nr(R=>{Jt(R),!(R!=="exhausted"||fn.current)&&(fn.current=!0,Je.current?.(new At("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Kn=nr(()=>{Jt("retrying"),yn(R=>R+1)},[]);An(()=>{Jt("loading"),yn(0),fn.current=!1},[qe]),An(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:_i,checkout_type:ze,checkout_layout:Ne,billing_api_url:w})},[Ne,ze,w]);let gn=pn(()=>n?xn(n,!0):"",[n]),hn=pn(()=>_n===gn?mn:void 0,[mn,_n,gn]),tt=pn(()=>n?Uo(n,hn):void 0,[n,hn]),_t=ie??tt?.checkoutMode??"full",jt=pn(()=>tt?{...tt,checkoutMode:_t}:void 0,[tt,_t]);An(()=>{En(void 0),jn(gn)},[gn]),An(()=>{we(fe)},[fe]);let Lt=nr((R,O,H)=>{pt(()=>{Ee.current?.(wt(R,O,H))})},[pt]),Xt=nr(async(R,O)=>{we(null),Et(null),Ke("processing");let H=O?.sessionId??R.id,Z=xe.current??Ze.current,se=Bt(Z),L=Z?null:Po(w,r,Ft),h={log:P=>{se?se.log(P):L?.log(P)},error:P=>{se?se.error(P):L?.error(P)},terminal:P=>{se?se.terminal(P):L?.terminal(P)},performance:P=>{se?se.performance(P):L?.performance(P)},now:()=>se?.now()??L?.now()??0,elapsed:P=>se?.elapsed(P)??Math.max(0,(L?.now()??P)-P)},X=h.now(),F=!!(O?.initialAutoProcessingError||O?.initialAutoProcessingPending),le=!1,ge,I=()=>{le||(le=!0,F=!0,ge=h.now(),h.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ct=!1,T=()=>{Ct||(Ct=!0,h.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),h.performance({stage:"processing",durationMs:h.elapsed(X),durationMode:"machine",paymentMethodCategory:"saved"}),ge!==void 0&&h.performance({stage:"recovery",durationMs:h.elapsed(ge),durationMode:"machine",paymentMethodCategory:"saved"}))};h.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),h.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),F&&I();let m;try{let P=vi(O?.initialAutoProcessingError),ue;if(P)I(),P.type==="paypal_redirect_required"&&qt.current?.publishableKey&&Ii({sessionId:H,publishableKey:qt.current.publishableKey,paypalPublishableKey:qt.current.paypalPublishableKey}),ue=await mo(P,{flopay:xe.current,paypalFlopay:Ze.current,attempt3DS:O?.attempt3DS,billingApiUrl:w,sessionId:H,session:R,telemetry:!1}),P.type==="paypal_redirect_required"&&aa();else if(O?.initialAutoProcessingPending){let He=await new go(w,{telemetry:!1}).waitForCheckoutSessionCompletion(O.initialAutoProcessingPending.sessionId,{initialDelayMs:O.initialAutoProcessingPending.retryAfterMs});if(He.data.session?.status!=="complete")throw new At("Automatic payment failed. Please try again.","api_error",{code:He.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});ue={status:"succeeded"}}else{if(O?.initialAutoProcessingError)throw Un(O.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:O.initialAutoProcessingError.checkoutMethod});if(O?.fromCreateSession)return O?.fallbackToFull&&(st("full"),Ei("full")),!1;{let V=await hr({billingApiUrl:w,sessionId:H,session:R,telemetry:!1});V.type==="success"?ue=V.result:(I(),V.type==="paypal_redirect_required"&&qt.current?.publishableKey&&Ii({sessionId:H,publishableKey:qt.current.publishableKey,paypalPublishableKey:qt.current.paypalPublishableKey}),ue=await mo(V,{flopay:xe.current,paypalFlopay:Ze.current,attempt3DS:O?.attempt3DS,billingApiUrl:w,sessionId:H,session:R,telemetry:!1}),V.type==="paypal_redirect_required"&&aa())}}H&&pr(H),T(),F&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),h.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Ke("success"),await $r(Mn),m=()=>_.current?.(ue)}catch(P){let ue=tr(P),V=ue.checkoutMethod??Ur;return we(ue.message),Et(ue.message),O?.fallbackToFull&&(h.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),st("full"),Ei("full")),T(),!!(ue.declineCode||ue.code?.toLowerCase().includes("declin"))?h.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):ue.type==="validation_error"?h.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):h.error({errorCode:F?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:F?"recovery":"processing",paymentMethodCategory:"saved"}),pt(()=>Je.current?.(ue)),Lt(V,ue,{code:ue.code,declineCode:ue.declineCode}),Ke("error"),await Promise.allSettled([$r(Cn),O?.ensureProvidersReady?O.ensureProvidersReady():Promise.resolve()]),F&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{T(),L&&bo(L),Ke(null),Et(null)}return pt(m),!0},[Lt,pt,tr,w,r,Ft]);An(()=>{if(typeof window>"u"||Dn.current)return;let R=new URLSearchParams(window.location.search),O=R.get("payment_intent_client_secret");if(!O)return;let H=dl();H&&(Dn.current=!0,(async()=>{let Z,se=0;we(null),Et(null),Ke("processing"),et(!0);try{if(R.get("redirect_status")==="failed")throw Object.assign(new At("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:L,paypalFlopay:h}=await fo({publishableKey:H.publishableKey,paypalPublishableKey:H.paypalPublishableKey,billingApiUrl:w,locale:c,telemetry:r});Z=Bt(h??L),se=Z?.now()??0,Z?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let X=(h??L)?.getRawProvider();if(!X)throw Object.assign(new At("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:F,error:le}=await X.retrievePaymentIntent(O);if(le)throw Object.assign(new At(le.message??"Failed to retrieve PayPal payment status.","api_error",{code:le.code}),{checkoutMethod:"paypal"});let ge=Ha(F?.status);if(!F||ge==="failed")throw Object.assign(new At("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let I=typeof F.payment_method=="string"?F.payment_method:F.payment_method?.id,Ct=ge;if(H.sessionId){let P=(await new go(w,{telemetry:!1}).getUnifiedCheckoutSession(H.sessionId)).data.session;if(P&&P.status!=="complete"){let ue=await hr({billingApiUrl:w,sessionId:H.sessionId,session:P,telemetry:!1,tokenizedData:{id:I??F.id,type:"card",threeDSecureActionResultTokenId:F.id,isPaypal:!0}});if(ue.type!=="success")throw Object.assign(new At("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Ct=ue.result.status}}H.sessionId&&pr(H.sessionId),Z?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.performance({stage:"redirect_resume",durationMs:Z.elapsed(se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ke("success"),await $r(Mn),pt(()=>_.current?.({status:Ct,paymentIntentId:F.id,paymentMethodId:I,checkoutMethod:"paypal"}))}catch(L){let h=tr(L),X=h.checkoutMethod??"paypal",F=!!(h.declineCode||h.code?.toLowerCase().includes("declin"));if(Z)Z.performance({stage:"redirect_resume",durationMs:Z.elapsed(se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),F?Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Z.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(F){let le=Po(w,r,Ft);le.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),bo(le)}else ra(w,r,Ft,"REDIRECT_RESUME_FAILED","redirect_resume");we(h.message),Et(h.message),pt(()=>Je.current?.(h)),Lt(X,h,{code:h.code,declineCode:h.declineCode}),Ke("error"),await $r(Cn)}finally{aa(),gl(),Ke(null),Et(null),et(!1)}})())},[Lt,pt,c,tr,w,r]);let sn=on(null);function xn(R,O=!1){let H=R?.account?.email?.trim().toLowerCase()??"",Z={c:R?.clientId,cur:R?.currency??"",a:{e:H,u:H?"":R?.account?.userId??"",country:R?.account?.country??""},successUrl:R?.successUrl,cancelUrl:R?.cancelUrl,p:R?.products?.map(h=>ia(`${h.type??""}:${h.code??h.providerItemId??h.providerPlanId??""}`,h)).sort(),i:R?.items?.map(h=>ia(h.code??h.providerItemId??"",h)).sort(),s:R?.subscriptions?.map(h=>ia(h.code??h.providerPlanId??"",h)).sort(),couponCodes:R?.couponCodes?[...R.couponCodes].sort():void 0,...O?{tagsData:R?.tagsData,utmMetadata:R?.utmMetadata,tokenizedData:R?.tokenizedData,checkoutMode:R?.checkoutMode??"full"}:{}},se=JSON.stringify(Z),L=0;for(let h=0;h<se.length;h++)L=(L<<5)-L+se.charCodeAt(h)|0;return`flopay_session_${Math.abs(L).toString(36)}`}let Vt=pn(()=>jt?xn(jt):"",[jt]),Nt=on(jt);Nt.current=jt,An(()=>{We(e??"")},[e]),An(()=>{K.current=!1,we(fe),Et(null),Ke(null)},[Vt,fe,e]);async function Zt(R,O){let H=Po(w,r,Ft),Z=new go(w,{telemetry:!1});try{let se=R.idempotencyKey!==void 0?ki(R.idempotencyKey):void 0,L=se??ml(O),h,X=!1,F=ul(O);H.log({name:F?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let le=F?.sid??null,ge=null;if(le)try{if(ge=await Z.getUnifiedCheckoutSession(le,F?.nonce),ge.data.session?.status==="complete"){if(qo(le))return{sid:le,result:ge};fl(O),le=null,ge=null,X=!0}}catch{H.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ti(O),le=null}if(!le){!se&&(X||!L)&&(L=ki(),h=L),L&&yl(O,L);let I=H.now();H.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ct={...R,idempotencyKey:L,avsCheck:!!ae,avsConfig:typeof ae=="object"?ae:void 0,checkoutType:"embedded_checkout",checkoutLayout:Se?"custom_layout":U==="buttons"?"buttons_layout":"default_layout"};try{ge=await Z.createAndFetchSession(Ct),H.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),H.performance({stage:"session_create",durationMs:H.now()-I,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"})}catch(T){let m=al(T,"CHECKOUT_SESSION_CREATE_FAILED","unknown");throw H.performance({stage:"session_create",durationMs:H.now()-I,durationMode:"machine",requestCategory:"session_create",statusClass:m.statusClass}),T instanceof At&&T.type==="validation_error"?H.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):m.statusClass==="4xx"?H.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):H.error({...m,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),T}le=ge.data.session?.id??"",le&&pl(O,le,ge.data.session?.clientSecret)}return{sid:le??"",result:ge,sdkGeneratedIdempotencyKey:h}}finally{bo(H)}}let ve=nr(async(R,O)=>{let H=Nt.current;if(!H)throw new At("createSession is required to bootstrap checkout.","validation_error");let Z=Uo(H,R),se=xn(Z),L=vo.get(se);if(!L){let F={promise:Zt(Z,se),consumers:0,settled:!1};L=F,vo.set(se,F);let le=()=>{F.settled=!0,Ri(se,F)};F.promise.then(le,le)}L.consumers+=1;let h=!1,X=()=>{h||(h=!0,L.consumers-=1,Ri(se,L))};O?.(X);try{let F=await L.promise;sn.current=se,R&&(jn(gn),En(P=>Ka(P,R)));let{sid:le,result:ge}=F;x(ge),ge.data.session&&$e(ge.data.session),le&&We(le);let{publishableKey:I,paypalPublishableKey:Ct}=yo(ge),{flopay:T,paypalFlopay:m}=await fo({publishableKey:I,paypalPublishableKey:Ct,billingApiUrl:w,locale:c,telemetry:r});return xe.current=T,de(T),Ze.current=m,Qe(m),It(!1),F}catch(F){throw sn.current===se&&(sn.current=null),F}finally{O||X()}},[c,w,r,Ft]),ft=nr(async R=>{if(!hl(R)||ht)return{sessionId:Ue,session:u};$t(!0);try{let O=await ve(R);return{sessionId:O.sid,session:O.result.data.session??null}}finally{$t(!1)}},[ve,ht,Ue,u]);An(()=>{let R=!1,O;if(Ie(null),Vt){let se=Nt.current;return st(_t),It(!1),sn.current===Vt?()=>{R=!0}:($e(Va(se,ie)),(async()=>{let L=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),h=_t==="auto"&&!K.current&&!L;h&&(we(null),Et(null),Ke("processing"));try{let X=await ve(void 0,I=>{O=I}),F=X.result.data.session??null;qt.current=yo(X.result);let le=oa(X.result),ge=qo(X.sid||F?.id);if(!R&&h&&F&&!le&&!ge){K.current=!0,await ll(Vt,X.sdkGeneratedIdempotencyKey,()=>Xt(F,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:X.result.autoProcessingError,initialAutoProcessingPending:X.result.autoProcessingPending,autoProcessingAttempted:X.result.autoProcessingAttempted,sessionId:X.sid||F.id}));return}!R&&h&&((le||ge)&&(K.current=!0),Ke(null),Et(null))}catch(X){if(R)return;let F=X instanceof At||typeof X=="object"&&X!==null&&"code"in X?X.code:void 0;if(h&&F==="session_auto_completed"){K.current=!0,Ke("success"),await $r(Mn),R||(pt(()=>{_.current?.({status:"succeeded"})}),Ke(null),Et(null));return}h&&(Ke(null),Et(null));let le=X instanceof At?X:new At(X instanceof Error?X.message:"Failed to create session","api_error");Ie(le)}finally{O?.(),O=void 0}})(),()=>{R=!0,O?.()})}It(!0);async function H(){let se=!1;try{let h=await new go(w,{telemetry:!1}).getUnifiedCheckoutSession(qe,t);if(R)return;x(h);let X=h.data.session??null;if($e(X),!X)throw new At("No session data returned","api_error");if(X.status==="complete"){It(!1),pt(()=>{Ln.current?.(X.successUrl??"")});return}if(X.status==="expired")throw new At("Checkout session has expired.","api_error",{code:"checkout_session_expired"});se=!0;let F=ie??X.checkoutMode??"full";st(F);let le=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ge=oa(h);if(F==="auto"&&!K.current&&!le&&!ge){K.current=!0;let I=Z(h);try{if(await Xt(X,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>I,sessionId:qe||X.id}),R)return;await I,R||It(!1);return}catch{if(R)return;await I,R||It(!1);return}}await Z(h),R||It(!1)}catch(L){if(R)return;L instanceof At?!se&&!cl(L)&&ra(w,r,Ft,"NETWORK_REQUEST_FAILED","session_read"):ra(w,r,Ft,"INTERNAL_SDK_ERROR","checkout_mount");let h=L instanceof At?L:new At(L instanceof Error?L.message:"Failed to initialize checkout","api_error");Ie(h),It(!1)}}async function Z(se){let{publishableKey:L,paypalPublishableKey:h}=yo(se);qt.current={publishableKey:L,paypalPublishableKey:h};let{flopay:X,paypalFlopay:F}=await fo({publishableKey:L,paypalPublishableKey:h,billingApiUrl:w,locale:c,telemetry:r});xe.current=X,de(X),Ze.current=F,Qe(F)}return H(),()=>{R=!0}},[ve,ie,Vt,_t,Gt,pt,t,Xt]);let lt=nr(async()=>{if(!(rt||!u)){et(!0),we(null);try{await Xt(u,{fallbackToFull:!0,sessionId:qe||u.id})}finally{et(!1)}}},[qe,rt,Xt,u]),Pn=sa(Y),Vn=oa(Y),Ot=pn(()=>{if(!Y||!u||!Y.data.stripe?.publishableKey)return;let R={appearance:ce,paymentMethodCreation:"manual",billingApiUrl:w};if(Y.data.stripe?.clientSecret)R.clientSecret=Y.data.stripe.clientSecret;else{let O=wi(u).total;R.amount=Math.round(O*100)||u.amount,R.currency=u.currency?.toLowerCase()}return R},[Y,u,ce,w]),Ht=!!(n&&!Se&&U==="buttons"&&q&&_t==="full"),vt=pn(()=>({session:u,loading:Pt,error:g,checkoutMode:je,inlineSessionDraft:jt,applyInlineSessionPatch:Ht?ft:void 0,inlineSessionPatchProcessing:ht}),[u,Pt,g,je,jt,Ht,ft,ht]),rr=!!n&&U==="buttons"&&!Vn&&(!j||!Ot),Wt=bt?te(Sn,{status:bt,errorMessage:Ut}):null;if(Pt){if(s)return Rt(In,{children:[s,Wt]});if(U==="buttons"){let R=ne?.buttonsLayout?.cardButton?.borderRadius??ne?.appearance.variables?.borderRadius??8,O=H=>te("div",{style:{height:H,borderRadius:R,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Rt(In,{children:[Rt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[l&&O(Pr),y&&(S||M)&&O(Pr),y&&O(Pr),te("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Wt]})}return Rt(In,{children:[Rt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[te("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),te("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Wt]})}return g?C?te(un.Provider,{value:vt,children:C(g)}):te(un.Provider,{value:vt,children:te("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:g.message})}):rr?Rt(In,{children:[te(un.Provider,{value:vt,children:te(bl,{onButtonClick:N,showPayPal:l,showStripe:y,showApplePay:S,showGooglePay:M,theme:W,buttonsTheme:me,buttonsStyles:Q,cardButtonContent:A,cardBackButtonContent:G,cardTitleContent:$})}),Wt]}):Vn&&u&&Pn?Rt(In,{children:[te(un.Provider,{value:vt,children:Rt("div",{className:J,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ge&&te(dr,{icon:!1,children:Ge}),Dt==="retrying"&&te("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Dt==="exhausted"&&Rt("div",{role:"alert",children:[te("div",{children:"PayPal is temporarily unavailable. Please try again."}),te("button",{type:"button",onClick:Kn,children:"Retry PayPal"})]}),Dt!=="exhausted"&&te("div",{"aria-hidden":Dt==="retrying"?!0:void 0,style:Dt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:te(Qa,{sessionId:qe,nonce:u.clientSecret||void 0,billingApiUrl:w,email:u.customer?.email,clientId:Pn.clientId,environment:Pn.environment,currency:(u.currency??"usd").toUpperCase(),isSubscription:u.mode==="subscription",onComplete:B,onErrorChange:we,onDecline:k,onButtonClick:N,onInitializationStateChange:Ve,allowAutomaticRetry:an===0,session:u,telemetry:r,telemetryContext:Ft,debug:f},`paypal-init-${an}`)})]})}),Wt]}):!j||!Ot?te(In,{children:Wt}):je==="confirm"?Rt(In,{children:[te(un.Provider,{value:vt,children:te(eo,{flopay:j,paypalFlopay:it,options:Ot,children:Rt("div",{className:J,children:[Ge&&te("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ge}),_e?_e({onConfirm:lt,isProcessing:rt}):te("button",{type:"button",onClick:lt,disabled:rt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:rt?"not-allowed":"pointer",opacity:rt?.6:1},children:rt?"Processing...":Le??"Confirm Purchase"})]})})}),Wt]}):Rt(In,{children:[te(un.Provider,{value:vt,children:te(eo,{flopay:j,paypalFlopay:it,options:Ot,children:Se?Rt(In,{children:[Ge&&te("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ge}),te(Pl,{sessionId:qe,nonce:u?.clientSecret||void 0,billingApiUrl:w,session:u,children:Se})]}):te(ea,{sessionId:qe,nonce:u?.clientSecret||void 0,email:u?.customer?.email,userId:u?.customer?.id,firstName:u?.customer?.firstName,lastName:u?.customer?.lastName,totalAmount:u?Math.round(wi(u).total*100):0,currency:u?.currency?.toLowerCase()??"usd",onComplete:B,onError:p,onDecline:k,error:Ge,onErrorChange:we,showPayPal:l,showStripe:y,enabledPaymentMethods:Y?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Y?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:M,layout:U,theme:W,buttonsTheme:me,buttonsStyles:Q,appearance:ce,cardButtonContent:A,cardBackButtonContent:G,cardTitleContent:$,onButtonClick:N,onBeforeButtonClick:q,enableAVS:ae,...Fe?{cardFieldOrder:Fe}:{},...Pe?{cardPreFormSlot:Pe}:{},avsLayout:he,country:u?.customer?.country,city:u?.customer?.city,state:u?.customer?.state,onCountryChange:v,onZipChange:E,avsCheck:!!ae,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Se?"custom_layout":U==="buttons"?"buttons_layout":"default_layout",className:J,directPaypal:sa(Y),isSubscription:u?.mode==="subscription",session:u,debug:f})})}),Wt]})}function Pl({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:r}){return te(In,{children:na.Children.map(r,a=>{if(!na.isValidElement(a))return a;let c=a.props,s={};return c.sessionId||(s.sessionId=e),!c.nonce&&t&&(s.nonce=t),c.billingApiUrl||(s.billingApiUrl=n),i?.customer&&(c.email||(s.email=i.customer.email),c.userId||(s.userId=i.customer.id),c.firstName||(s.firstName=i.customer.firstName),c.lastName||(s.lastName=i.customer.lastName)),Object.keys(s).length===0?a:na.cloneElement(a,s)})})}function bl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:i,showGooglePay:r,theme:a,buttonsTheme:c,buttonsStyles:s,cardButtonContent:C,cardBackButtonContent:B,cardTitleContent:p}){let[k,v]=kt(!1),E=pn(()=>xi(a),[a]),l=pn(()=>{let f=E?.buttonsLayout??sl(c);return s?{...f,...s,cardButton:{...f.cardButton,...s.cardButton},cardFormContainer:{...f.cardFormContainer,...s.cardFormContainer},backButton:{...f.backButton,...s.backButton},backButtonIcon:{...f.backButtonIcon,...s.backButtonIcon},submitButton:{...f.submitButton,...s.submitButton},title:{...f.title,...s.title}}:f},[E,c,s]),y=E?.buttonsLayout?.cardButton?.borderRadius??E?.appearance.variables?.borderRadius??8,S=f=>te("div",{style:{height:f,borderRadius:y,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),M=C===void 0?{boxSizing:"border-box",height:Pr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(k){let f=l.cardInputBorder??"#e5e7eb",U=l.cardInputBackground??"white",W=ir(B),me=ir(p);return Rt("div",{style:{backgroundColor:l.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...l.cardFormContainer},children:[Rt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Rt("button",{type:"button",onClick:()=>v(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:W?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...l.backButton},children:[te("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...l.backButtonIcon},children:te("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:te("path",{d:"M15 18l-6-6 6-6"})})}),te(lr,{content:B})]}),me?te("div",{style:{flex:1}}):te("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...l.title},children:te(Fr,{content:p})})]}),te("div",{style:{backgroundColor:U,border:`1px solid ${f}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:te("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Rt("div",{style:{display:"flex"},children:[te("div",{style:{flex:1,backgroundColor:U,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomLeftRadius:8,padding:12,height:45},children:te("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),te("div",{style:{flex:1,backgroundColor:U,borderTop:"none",borderRight:`1px solid ${f}`,borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomRightRadius:8,padding:12,height:45},children:te("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),te("div",{style:{backgroundColor:U,border:`1px solid ${f}`,borderRadius:8,marginTop:8,padding:12,height:45},children:te("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),te("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...l.submitButton,opacity:.5}}),te("style",{children:`
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&&k(mr),n&&(i||r)&&k(mr),n&&ee("button",{type:"button",onClick:()=>{e?.("card"),C(!0)},style:{width:"100%",...B,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:l.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...l.cardButton},onMouseDown:h=>{h.currentTarget.style.transform="scale(0.985)"},onMouseUp:h=>{h.currentTarget.style.transform="scale(1)"},children:ee(nr,{content:w})}),ee("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{useEffect as sl,useRef as Si,useContext as ll}from"react";import{jsx as ul}from"react/jsx-runtime";function wi(e,t){function n({className:i,id:r,style:a,options:c,onChange:s,onReady:w,onFocus:A,onBlur:p,onEscape:I}){let C=Si(null),T=Si(null),{elements:l,reportInteractive:f}=ll(Tn);return sl(()=>{if(!l||!C.current)return;let k=!0;return(async()=>{let B=l.getElement(e);B||(B=await l.create(e,c)),!(!k||!C.current)&&(B.mount(C.current),T.current=B,s&&B.on("change",s),B.on("ready",()=>{f?.(),w?.()}),A&&B.on("focus",A),p&&B.on("blur",p),I&&B.on("escape",I))})(),()=>{if(k=!1,T.current){try{T.current.unmount()}catch{}T.current=null}}},[l,f]),ul("div",{ref:C,className:i,id:r,style:a})}return n.displayName=t,n}var cl=wi("payment","PaymentElement"),dl=wi("address","AddressElement");import{PaymentAPI as pl}from"@flopay/js";import{FloPayError as ml}from"@flopay/shared";import{useCallback as ra,useEffect as yl,useRef as fl,useState as ki}from"react";import{Fragment as hl,jsx as fr,jsxs as Pl}from"react/jsx-runtime";function gl({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,firstName:a,lastName:c,chv:s,onTokenizedBody:w,onComplete:A,onErrorChange:p,isProcessing:I=!1}){let C=Pn(),T=Ao(),l=Xr(),[f,k]=ki(!1),[B,h]=ki(!1),q=fl(!1),W=(n||l).replace(/\/+$/,""),ce=ra(async J=>{try{let de=await new pl(W).processPayment(r??"",{sessionId:e,nonce:t,tokenizedData:J,accountData:{userId:r??"",email:i??"",firstName:a??"",lastName:c??""},chv:s});if(de.ok){A?.();return}let z=await de.json().catch(()=>null);p?.(z?.message??"Payment failed. Please try again.")}catch(j){p?.(j instanceof Error?j.message:"An unexpected error occurred")}},[W,e,t,r,i,a,c,s,A,p]),Z=ra(J=>{w?w(J):ce(J)},[w,ce]);yl(()=>{if(!C||q.current)return;let J=new URLSearchParams(window.location.search),j=J.get("payment_intent"),de=J.get("payment_intent_client_secret"),z=J.get("redirect_status");!j||!de||(q.current=!0,(async()=>{try{if(h(!0),z==="failed"){p?.("PayPal payment was declined. Please try again.");return}let V=C.getRawProvider();if(!V?.retrievePaymentIntent){p?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:re,error:Me}=await V.retrievePaymentIntent(de);if(Me){p?.(Me.message??"Failed to retrieve PayPal payment status.");return}if(re&&(re.status==="requires_capture"||re.status==="succeeded")){let me=typeof re.payment_method=="string"?re.payment_method:re.payment_method?.id;Z({id:me??re.id,type:"card",threeDSecureActionResultTokenId:re.id,isPaypal:!0});let pe=new URL(window.location.href);pe.searchParams.delete("payment_intent"),pe.searchParams.delete("payment_intent_client_secret"),pe.searchParams.delete("redirect_status"),window.history.replaceState({},"",pe.toString())}else p?.("PayPal payment was not completed. Please try again.")}catch(V){p?.(V instanceof Error?V.message:"Failed to complete PayPal payment.")}finally{h(!1)}})())},[C,Z,p]);let F=ra(async()=>{if(!(!C||!T))try{if(h(!0),p?.(null),!e||!i)throw new ml("Missing sessionId or email for PayPal payment","validation_error");let J=await C.confirmPayPalPayment({billingApiUrl:W,sessionId:e,nonce:t,email:i,returnUrl:window.location.href});if(J.error){p?.(J.error.message);return}J.paymentIntentId&&(J.status==="succeeded"||J.status==="processing"||J.status==="requires_capture")&&Z({id:J.paymentMethodId??J.paymentIntentId,type:"card",threeDSecureActionResultTokenId:J.paymentIntentId,isPaypal:!0})}catch(J){p?.(J instanceof Error?J.message:"PayPal payment failed. Please try again.")}finally{h(!1)}},[C,T,e,t,i,W,Z,p]);return!C||!T?fr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):Pl(hl,{children:[!f&&fr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),fr("div",{style:f?{}:{display:"none"},children:fr("button",{type:"button",onClick:F,disabled:B||I,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:B||I?"not-allowed":"pointer",opacity:B||I?.6:1},ref:()=>k(!0),children:B?"Processing...":"PayPal"})}),(B||I)&&fr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:fr("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}import{useCallback as Un,useEffect as gr,useMemo as Or,useRef as hr,useState as fo}from"react";import{PaymentAPI as oa}from"@flopay/js";import{FloPayError as $n,resolveBillingApiUrl as bl,resolveButtonsLayoutTheme as vl,resolveTheme as Cl}from"@flopay/shared";import{Fragment as El,jsx as Pr,jsxs as _l}from"react/jsx-runtime";var Sl=44;function Ri(e){return new Promise(t=>setTimeout(t,e))}function wl(e,t){return e instanceof $n?e:new $n(e instanceof Error?e.message:t,"api_error")}function kl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Rl(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 Il({sessionId:e,nonce:t,createSession:n,paymentMethodId:i,checkoutMethod:r,clientId:a,products:c,items:s,subscriptions:w,account:A,successUrl:p,cancelUrl:I,couponCodes:C,tagsData:T,utmMetadata:l,billingApiUrl:f,locale:k,theme:B,appearance:h,buttonsTheme:q,buttonsStyles:W,onSuccess:ce,onError:Z,onDecline:F,children:J,disabled:j=!1,type:de="button",style:z,...V}){let re=Or(()=>bl(f),[f]),Me=Or(()=>Rl({createSession:n,clientId:a,products:c,items:s,subscriptions:w,account:A,successUrl:p,cancelUrl:I,couponCodes:C,tagsData:T,utmMetadata:l}),[A,I,a,C,n,c,s,w,p,T,l]),[me,pe]=fo(!1),[X,ue]=fo(null),[Pe,oe]=fo(null),[Fe,ke]=fo(null),ve=hr(!0),R=hr(null),te=hr(Fe),ie=hr(ce),Ne=hr(Z),De=hr(F);gr(()=>{te.current=Fe},[Fe]),gr(()=>{ie.current=ce},[ce]),gr(()=>{Ne.current=Z},[Z]),gr(()=>{De.current=F},[F]),gr(()=>(ve.current=!0,()=>{ve.current=!1,R.current?.abort()}),[]),gr(()=>{if(typeof window>"u")return;let g=Ce=>{Ce.key==="Escape"&&ke(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let Y=Un((g,Ce=Lr)=>{De.current?.(St(Ce,g,{code:g.code,declineCode:g.declineCode}))},[]),M=Un(async g=>{ve.current&&(oe(null),ue("success"),await Ri(Mn),ve.current&&ie.current?.(g))},[]),H=Un(async(g,Ce)=>{ve.current&&(Ne.current?.(g),Ce?.emitDecline&&Y(g,Ce.method),oe(g.message),ue("error"),await Ri(bn))},[Y]),se=Un(async(g,Ce,je)=>{let it=g.data.session??null;if(!it)throw new $n("No session data returned","api_error");let et=it.clientSecret||t;if(it.status==="complete"){await M({result:{status:"succeeded"},session:it,sessionId:it.id||Ce,autoCompleted:!1});return}if(it.status==="expired")throw new $n("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(g.autoProcessingPending){let bt=(await new oa(re).waitForCheckoutSessionCompletion(g.autoProcessingPending.sessionId,{initialDelayMs:g.autoProcessingPending.retryAfterMs})).data.session;if(!bt||bt.status!=="complete")throw new $n("Automatic payment failed. Please try again.","api_error",{code:bt?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await M({result:{status:"succeeded"},session:bt,sessionId:bt.id||Ce,autoCompleted:!1});return}if(g.autoProcessingError){if(g.autoProcessingError.type==="3ds_required"&&g.autoProcessingError.nextActionRedirectUrl&&Ce&&et){let We=new AbortController;R.current=We;let be;try{be=await yi({billingApiUrl:re,sessionId:Ce,nonce:et,nextActionRedirectUrl:g.autoProcessingError.nextActionRedirectUrl,signal:We.signal})}finally{R.current===We&&(R.current=null)}if(be.status==="declined")throw zn({type:be.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:be.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let Ot=(await new oa(re).waitForCheckoutSessionCompletion(Ce,{initialDelayMs:0,nonce:et})).data.session;if(!Ot||Ot.status!=="complete")throw zn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await M({result:{status:"succeeded"},session:Ot,sessionId:Ot.id||Ce,autoCompleted:!1});return}throw zn(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(je?.fromCreateSession&&g.autoProcessingAttempted===!0)throw zn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Xe=await pr({billingApiUrl:re,sessionId:Ce??it.id,session:it,nonce:et});if(Xe.type!=="success")throw zn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await M({result:Xe.result,session:it,sessionId:it.id||Ce,autoCompleted:!1})}catch(Xe){let We=Zn(Xe),be=it.id||Ce;await H(We,{emitDecline:!0,method:We.checkoutMethod??Lr}),kl(We,be)&&be&&ve.current&&ke({sessionId:be,errorMessage:We.message,nonce:et||void 0})}},[t,re,H,M]),Re=Un(async g=>{if(V.onClick?.(g),!(g.defaultPrevented||j||me)){if(ke(null),e&&Me){let Ce=new $n("Provide either sessionId or create-session props, not both.","validation_error");await H(Ce),ve.current&&(ue(null),oe(null));return}if(!e&&!Me){let Ce=new $n("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await H(Ce),ve.current&&(ue(null),oe(null));return}pe(!0),oe(null),ue("processing");try{let Ce=new oa(re);if(e){let je=await Ce.getUnifiedCheckoutSession(e,t);await se(je,e);return}try{let je=await Ce.createAndFetchSession({...Me});await se(je,je.data.session?.id??null,{fromCreateSession:!0})}catch(je){if(je instanceof $n&&je.code==="session_auto_completed"){await M({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw je}}catch(Ce){await H(wl(Ce,"Automatic payment failed. Please try again."))}finally{ve.current&&(ue(null),oe(null),pe(!1))}}},[V,Me,j,me,t,se,re,e,H,M]),at=Un(g=>{let Ce=te.current;ke(null),ie.current?.({result:g,session:null,sessionId:Ce?.sessionId??null,autoCompleted:!1})},[]),Je=Un(g=>{Ne.current?.(g)},[]),Ge=Un(g=>{De.current?.(g)},[]),m=Or(()=>Cl(B),[B]),$e=Or(()=>{let g=m?.buttonsLayout??vl(q);return W?{...g,...W,cardButton:{...g.cardButton,...W.cardButton}}:g},[m,q,W]),Oe=Or(()=>{let g=m?.appearance;return h?g?{...g,...h,variables:{...g.variables,...h.variables}}:h:g},[h,m]),He=Oe?.variables,qe=He?.colorPrimary??"#4A49FF",Gt=He?.colorPrimaryHover??oo(qe,.12),Pt=He?.borderRadius??"8px";return _l(El,{children:[Pr("button",{...V,type:de,onClick:Re,disabled:j||me,"aria-busy":me,style:{width:"100%",...J===void 0?{boxSizing:"border-box",height:Sl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...$e.cardButton,...Ko({themeBundle:m,resolvedPrimaryColor:qe,resolvedBorderRadius:Pt,submitButtonStyle:$e.submitButton,explicitPrimaryColor:He?.colorPrimary}),fontSize:$e.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:j||me?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:j||me?.6:1,...z},onMouseEnter:g=>{V.onMouseEnter?.(g),!g.defaultPrevented&&!j&&!me&&(m||He?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Gt)},onMouseLeave:g=>{V.onMouseLeave?.(g),!g.defaultPrevented&&(m||He?.colorPrimary)&&(g.currentTarget.style.backgroundColor=qe)},onMouseDown:g=>{V.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{V.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:Pr(nr,{content:J})}),X&&Pr(vn,{status:X,errorMessage:Pe}),Fe&&Pr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&ke(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:Pr("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:Pr(na,{sessionId:Fe.sessionId,nonce:Fe.nonce,checkoutMode:"full",billingApiUrl:re,locale:k,theme:B,...Oe?{appearance:Oe}:{},buttonsTheme:q,buttonsStyles:W,initialErrorMessage:Fe.errorMessage,cardTitleContent:null,onComplete:at,onError:Je,onDecline:Ge})})})]})}export{dl as AddressElement,ro as DirectPayPalButton,Il as FloPayAutomaticPaymentButton,na as FloPayCheckout,Jr as FloPayProvider,gl as PayPalButton,cl as PaymentElement,Wo as SplitCardForm,Mo as VaultCardFields,os as useCheckout,Ao as useElements,Pn as useFloPay,Bo as usePayPalFloPay};
47
+ `})]})}return Rt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&S(Pr),n&&(i||r)&&S(Pr),n&&te("button",{type:"button",onClick:()=>{e?.("card"),v(!0)},style:{width:"100%",...M,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:te(sr,{content:C})}),te("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{useEffect as vl,useRef as Mi,useContext as Cl}from"react";import{jsx as kl}from"react/jsx-runtime";function Bi(e,t){function n({className:i,id:r,style:a,options:c,onChange:s,onReady:C,onFocus:B,onBlur:p,onEscape:k}){let v=Mi(null),E=Mi(null),{elements:l,reportInteractive:y}=Cl(Tn);return vl(()=>{if(!l||!v.current)return;let S=!0;return(async()=>{let M=l.getElement(e);M||(M=await l.create(e,c)),!(!S||!v.current)&&(M.mount(v.current),E.current=M,s&&M.on("change",s),M.on("ready",()=>{y?.(),C?.()}),B&&M.on("focus",B),p&&M.on("blur",p),k&&M.on("escape",k))})(),()=>{if(S=!1,E.current){try{E.current.unmount()}catch{}E.current=null}}},[l,y]),kl("div",{ref:v,className:i,id:r,style:a})}return n.displayName=t,n}var Sl=Bi("payment","PaymentElement"),wl=Bi("address","AddressElement");import{PaymentAPI as Rl}from"@flopay/js";import{FloPayError as Il}from"@flopay/shared";import{useCallback as ua,useEffect as El,useRef as _l,useState as Ai}from"react";import{Fragment as Tl,jsx as br,jsxs as Ml}from"react/jsx-runtime";function xl({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,firstName:a,lastName:c,chv:s,onTokenizedBody:C,onComplete:B,onErrorChange:p,isProcessing:k=!1}){let v=vn(),E=zo(),l=to(),[y,S]=Ai(!1),[M,f]=Ai(!1),U=_l(!1),W=(n||l).replace(/\/+$/,""),me=ua(async G=>{try{let ye=await new Rl(W).processPayment(r??"",{sessionId:e,nonce:t,tokenizedData:G,accountData:{userId:r??"",email:i??"",firstName:a??"",lastName:c??""},chv:s});if(ye.ok){B?.();return}let N=await ye.json().catch(()=>null);p?.(N?.message??"Payment failed. Please try again.")}catch($){p?.($ instanceof Error?$.message:"An unexpected error occurred")}},[W,e,t,r,i,a,c,s,B,p]),Q=ua(G=>{C?C(G):me(G)},[C,me]);El(()=>{if(!v||U.current)return;let G=new URLSearchParams(window.location.search),$=G.get("payment_intent"),ye=G.get("payment_intent_client_secret"),N=G.get("redirect_status");!$||!ye||(U.current=!0,(async()=>{try{if(f(!0),N==="failed"){p?.("PayPal payment was declined. Please try again.");return}let q=v.getRawProvider();if(!q?.retrievePaymentIntent){p?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ae,error:Fe}=await q.retrievePaymentIntent(ye);if(Fe){p?.(Fe.message??"Failed to retrieve PayPal payment status.");return}if(ae&&(ae.status==="requires_capture"||ae.status==="succeeded")){let Pe=typeof ae.payment_method=="string"?ae.payment_method:ae.payment_method?.id;Q({id:Pe??ae.id,type:"card",threeDSecureActionResultTokenId:ae.id,isPaypal:!0});let he=new URL(window.location.href);he.searchParams.delete("payment_intent"),he.searchParams.delete("payment_intent_client_secret"),he.searchParams.delete("redirect_status"),window.history.replaceState({},"",he.toString())}else p?.("PayPal payment was not completed. Please try again.")}catch(q){p?.(q instanceof Error?q.message:"Failed to complete PayPal payment.")}finally{f(!1)}})())},[v,Q,p]);let A=ua(async()=>{if(!(!v||!E))try{if(f(!0),p?.(null),!e||!i)throw new Il("Missing sessionId or email for PayPal payment","validation_error");let G=await v.confirmPayPalPayment({billingApiUrl:W,sessionId:e,nonce:t,email:i,returnUrl:window.location.href});if(G.error){p?.(G.error.message);return}G.paymentIntentId&&(G.status==="succeeded"||G.status==="processing"||G.status==="requires_capture")&&Q({id:G.paymentMethodId??G.paymentIntentId,type:"card",threeDSecureActionResultTokenId:G.paymentIntentId,isPaypal:!0})}catch(G){p?.(G instanceof Error?G.message:"PayPal payment failed. Please try again.")}finally{f(!1)}},[v,E,e,t,i,W,Q,p]);return!v||!E?br("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):Ml(Tl,{children:[!y&&br("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),br("div",{style:y?{}:{display:"none"},children:br("button",{type:"button",onClick:A,disabled:M||k,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:M||k?"not-allowed":"pointer",opacity:M||k?.6:1},ref:()=>S(!0),children:M?"Processing...":"PayPal"})}),(M||k)&&br("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:br("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}import{useCallback as $n,useEffect as vr,useMemo as qr,useRef as Cr,useState as Co}from"react";import{PaymentAPI as pa}from"@flopay/js";import{FloPayError as qn,resolveBillingApiUrl as Bl,resolveButtonsLayoutTheme as Al,resolveTheme as Fl}from"@flopay/shared";import{Fragment as Ul,jsx as Sr,jsxs as $l}from"react/jsx-runtime";var Dl=44;function Fi(e){return new Promise(t=>setTimeout(t,e))}function Ll(e,t){return e instanceof qn?e:new qn(e instanceof Error?e.message:t,"api_error")}function Nl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Ol(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 zl({sessionId:e,nonce:t,createSession:n,paymentMethodId:i,checkoutMethod:r,clientId:a,products:c,items:s,subscriptions:C,account:B,successUrl:p,cancelUrl:k,couponCodes:v,tagsData:E,utmMetadata:l,billingApiUrl:y,locale:S,theme:M,appearance:f,buttonsTheme:U,buttonsStyles:W,onSuccess:me,onError:Q,onDecline:A,children:G,disabled:$=!1,type:ye="button",style:N,...q}){let ae=qr(()=>Bl(y),[y]),Fe=qr(()=>Ol({createSession:n,clientId:a,products:c,items:s,subscriptions:C,account:B,successUrl:p,cancelUrl:k,couponCodes:v,tagsData:E,utmMetadata:l}),[B,k,a,v,n,c,s,C,p,E,l]),[Pe,he]=Co(!1),[J,fe]=Co(null),[Se,ie]=Co(null),[Le,_e]=Co(null),Re=Cr(!0),w=Cr(null),ne=Cr(Le),ce=Cr(me),ze=Cr(Q),Ne=Cr(A);vr(()=>{ne.current=Le},[Le]),vr(()=>{ce.current=me},[me]),vr(()=>{ze.current=Q},[Q]),vr(()=>{Ne.current=A},[A]),vr(()=>(Re.current=!0,()=>{Re.current=!1,w.current?.abort()}),[]),vr(()=>{if(typeof window>"u")return;let g=Ie=>{Ie.key==="Escape"&&_e(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let Y=$n((g,Ie=Ur)=>{Ne.current?.(wt(Ie,g,{code:g.code,declineCode:g.declineCode}))},[]),x=$n(async g=>{Re.current&&(ie(null),fe("success"),await Fi(Mn),Re.current&&ce.current?.(g))},[]),j=$n(async(g,Ie)=>{Re.current&&(ze.current?.(g),Ie?.emitDecline&&Y(g,Ie.method),ie(g.message),fe("error"),await Fi(Cn))},[Y]),de=$n(async(g,Ie,je)=>{let st=g.data.session??null;if(!st)throw new qn("No session data returned","api_error");let rt=st.clientSecret||t;if(st.status==="complete"){await x({result:{status:"succeeded"},session:st,sessionId:st.id||Ie,autoCompleted:!1});return}if(st.status==="expired")throw new qn("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(g.autoProcessingPending){let bt=(await new pa(ae).waitForCheckoutSessionCompletion(g.autoProcessingPending.sessionId,{initialDelayMs:g.autoProcessingPending.retryAfterMs})).data.session;if(!bt||bt.status!=="complete")throw new qn("Automatic payment failed. Please try again.","api_error",{code:bt?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await x({result:{status:"succeeded"},session:bt,sessionId:bt.id||Ie,autoCompleted:!1});return}if(g.autoProcessingError){if(g.autoProcessingError.type==="3ds_required"&&g.autoProcessingError.nextActionRedirectUrl&&Ie&&rt){let Ge=new AbortController;w.current=Ge;let we;try{we=await Ci({billingApiUrl:ae,sessionId:Ie,nonce:rt,nextActionRedirectUrl:g.autoProcessingError.nextActionRedirectUrl,signal:Ge.signal})}finally{w.current===Ge&&(w.current=null)}if(we.status==="declined")throw Un({type:we.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:we.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let Ut=(await new pa(ae).waitForCheckoutSessionCompletion(Ie,{initialDelayMs:0,nonce:rt})).data.session;if(!Ut||Ut.status!=="complete")throw Un({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await x({result:{status:"succeeded"},session:Ut,sessionId:Ut.id||Ie,autoCompleted:!1});return}throw Un(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(je?.fromCreateSession&&g.autoProcessingAttempted===!0)throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let et=await hr({billingApiUrl:ae,sessionId:Ie??st.id,session:st,nonce:rt});if(et.type!=="success")throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await x({result:et.result,session:st,sessionId:st.id||Ie,autoCompleted:!1})}catch(et){let Ge=tr(et),we=st.id||Ie;await j(Ge,{emitDecline:!0,method:Ge.checkoutMethod??Ur}),Nl(Ge,we)&&we&&Re.current&&_e({sessionId:we,errorMessage:Ge.message,nonce:rt||void 0})}},[t,ae,j,x]),xe=$n(async g=>{if(q.onClick?.(g),!(g.defaultPrevented||$||Pe)){if(_e(null),e&&Fe){let Ie=new qn("Provide either sessionId or create-session props, not both.","validation_error");await j(Ie),Re.current&&(fe(null),ie(null));return}if(!e&&!Fe){let Ie=new qn("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await j(Ie),Re.current&&(fe(null),ie(null));return}he(!0),ie(null),fe("processing");try{let Ie=new pa(ae);if(e){let je=await Ie.getUnifiedCheckoutSession(e,t);await de(je,e);return}try{let je=await Ie.createAndFetchSession({...Fe});await de(je,je.data.session?.id??null,{fromCreateSession:!0})}catch(je){if(je instanceof qn&&je.code==="session_auto_completed"){await x({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw je}}catch(Ie){await j(Ll(Ie,"Automatic payment failed. Please try again."))}finally{Re.current&&(fe(null),ie(null),he(!1))}}},[q,Fe,$,Pe,t,de,ae,e,j,x]),it=$n(g=>{let Ie=ne.current;_e(null),ce.current?.({result:g,session:null,sessionId:Ie?.sessionId??null,autoCompleted:!1})},[]),Qe=$n(g=>{ze.current?.(g)},[]),Ze=$n(g=>{Ne.current?.(g)},[]),u=qr(()=>Fl(M),[M]),$e=qr(()=>{let g=u?.buttonsLayout??Al(U);return W?{...g,...W,cardButton:{...g.cardButton,...W.cardButton}}:g},[u,U,W]),Ue=qr(()=>{let g=u?.appearance;return f?g?{...g,...f,variables:{...g.variables,...f.variables}}:f:g},[f,u]),We=Ue?.variables,qe=We?.colorPrimary??"#4A49FF",Gt=We?.colorPrimaryHover??lo(qe,.12),Pt=We?.borderRadius??"8px";return $l(Ul,{children:[Sr("button",{...q,type:ye,onClick:xe,disabled:$||Pe,"aria-busy":Pe,style:{width:"100%",...G===void 0?{boxSizing:"border-box",height:Dl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...$e.cardButton,...Qo({themeBundle:u,resolvedPrimaryColor:qe,resolvedBorderRadius:Pt,submitButtonStyle:$e.submitButton,explicitPrimaryColor:We?.colorPrimary}),fontSize:$e.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:$||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:$||Pe?.6:1,...N},onMouseEnter:g=>{q.onMouseEnter?.(g),!g.defaultPrevented&&!$&&!Pe&&(u||We?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Gt)},onMouseLeave:g=>{q.onMouseLeave?.(g),!g.defaultPrevented&&(u||We?.colorPrimary)&&(g.currentTarget.style.backgroundColor=qe)},onMouseDown:g=>{q.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{q.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:Sr(sr,{content:G})}),J&&Sr(Sn,{status:J,errorMessage:Se}),Le&&Sr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&_e(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:Sr("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:Sr(da,{sessionId:Le.sessionId,nonce:Le.nonce,checkoutMode:"full",billingApiUrl:ae,locale:S,theme:M,...Ue?{appearance:Ue}:{},buttonsTheme:U,buttonsStyles:W,initialErrorMessage:Le.errorMessage,cardTitleContent:null,onComplete:it,onError:Qe,onDecline:Ze})})})]})}export{wl as AddressElement,so as DirectPayPalButton,zl as FloPayAutomaticPaymentButton,da as FloPayCheckout,eo as FloPayProvider,xl as PayPalButton,Sl as PaymentElement,ea as SplitCardForm,No as VaultCardFields,ms as useCheckout,zo as useElements,vn as useFloPay,Oo as usePayPalFloPay};