@flopay/react 1.4.5 → 1.4.6
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.cjs +9 -9
- package/dist/index.mjs +9 -9
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{useCallback as ji,useEffect as Er,useState as Io,useMemo as Vi,useRef as Eo}from"react";import{resolveBillingApiUrl as Hi}from"@flopay/shared";import{createContext as Ea}from"react";var xn=Ea({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),ln=Ea({session:null,loading:!1,error:null});var zi=Symbol.for("@flopay/js.telemetry.bridge.v1"),Ui=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function $i(){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 qi(e){let t=$i(),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 Wr(e){let t=globalThis[Ui];return qi(t?.(e)??{})}function Dt(e){if(e)return e[zi]}import{jsx as Ki}from"react/jsx-runtime";function Yr({flopay:e,paypalFlopay:t,options:n,children:i}){let[r,a]=Io(e instanceof Promise?null:e),[c,s]=Io(t instanceof Promise||!t?null:t),[w,M]=Io(null),p=Eo(null),R=Eo(null),C=Eo(null);Er(()=>{if(!r)return;let S=Dt(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]),Er(()=>{let S=!1;return e instanceof Promise?e.then(x=>{S||a(x)}):a(e),()=>{S=!0}},[e]),Er(()=>{let S=!1;if(!t){s(null);return}return t instanceof Promise?t.then(x=>{S||s(x)}):s(t),()=>{S=!0}},[t]),Er(()=>{if(!r){M(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 M(S),()=>{S.destroy()}},[r,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),Er(()=>{if(!r||!w||R.current===w)return;R.current=w;let S=Dt(r);S?.log({name:"checkout.rendered",stage:"checkout_render"}),S?.performance({stage:"checkout_render",durationMs:S.elapsed(p.current??0),durationMode:"machine"})},[w,r]);let E=ji(()=>{if(!r||!w||C.current===w)return;C.current=w;let S=Dt(r);S?.log({name:"checkout.interactive",stage:"checkout_interactive"}),S?.performance({stage:"checkout_interactive",durationMs:S.elapsed(p.current??0),durationMode:"machine"})},[w,r]),l=Hi(n?.billingApiUrl),f=Vi(()=>({flopay:r,paypalFlopay:c,elements:w,billingApiUrl:l,reportInteractive:E}),[r,c,w,l,E]);return Ki(xn.Provider,{value:f,children:i})}import Ho,{useCallback as Zn,useEffect as Bn,useMemo as cn,useRef as nn,useState as kt}from"react";import{PaymentAPI as co}from"@flopay/js";import{SDK_VERSION as gi,FloPayError as At,resolveBillingApiUrl as Vs,buildCheckoutDisplayData as pi,resolveButtonsLayoutTheme as Hs,resolveTheme as hi}from"@flopay/shared";import"react";import{Fragment as rr,jsx as en,jsxs as _a}from"react/jsx-runtime";function Wi(){return _a(rr,{children:[_a("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 Yi(){return en(rr,{children:"Go back"})}function Gi(){return en(rr,{children:"Secure card checkout"})}function er(e){return e!==void 0&&(e===""||e===null||e===!1)}function tr({content:e}){return en(rr,{children:e===void 0?en(Wi,{}):e})}function nr({content:e}){return en(rr,{children:e===void 0?en(Yi,{}):e})}function _r({content:e}){return en(rr,{children:e===void 0?en(Gi,{}):e})}import{ExpressCheckoutElement as ti,PaymentElement as us,Elements as Jn,useElements as Uo,useStripe as $o}from"@stripe/react-stripe-js";import{resolveButtonsLayoutTheme as ps,getPostalCodeLabel as Oo,getStateLabel as ja,getStateOptions as ms,COUNTRY_OPTIONS as ys,resolveAVSConfig as fs,isAVSFieldVisible as _e,getStateFromPostalCode as Va,isPostalCodeSupported as gs,isValidPostalCode as hs,getPostalCodeExample as Ps,filterStripeMethodsByCountry as bs,getStripeMethodDisplayName as dr,hasVendoredStripeMethodLogo as vs,needsStripeMethodExplicitConfirm as Ha,resolveStripeMethodBrandVariant as Cs,partitionStripeMethods as ws,stripeExpressMethodToOptionKey as Ka}from"@flopay/shared";import{PaymentAPI as Nn}from"@flopay/js";import{useEffect as xa,useRef as xr}from"react";import{jsx as Ji}from"react/jsx-runtime";function _o({capture:e,html:t,messageToken:n,expectedOrigin:i,theme:r,containerStyle:a,onReady:c,onError:s,onValidation:w}){let M=xr(null),p=xr(c),R=xr(s),C=xr(w);p.current=c,R.current=s,C.current=w;let E=xr(r);return E.current=r,xa(()=>{let l=M.current;if(!l)return;let f=!0,S=!1,x=()=>{!f||S||(S=!0,p.current?.())},h=e.on("ready",()=>{x()}),U=e.on("error",re=>{R.current?.(re.message??"There was a problem loading the secure card form.")}),Y=e.on("validation",re=>{C.current?.(re.message??null)}),ce={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},...E.current?{theme:E.current}:{}};return e.mount(l,ce).then(()=>{x()}).catch(re=>{f&&R.current?.(re instanceof Error?re.message:"Failed to load the secure card form.")}),()=>{f=!1,h(),U(),Y(),e.unmount()}},[e,t,n,i]),xa(()=>{r&&e.applyTheme?.(r)},[e,r]),Ji("div",{ref:M,"data-testid":"flopay-vault-card-fields",style:a})}import"react";import{jsx as Ta,jsxs as Xi}from"react/jsx-runtime";function or({children:e,margin:t,icon:n=!0,styleOverride:i}){return Xi("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&&Ta("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Ta("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 Ma={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 Ss,{useCallback as ge,useContext as ks,useEffect as mt,useMemo as pt,useRef as Ne,useState as ve}from"react";import{useContext as Tr}from"react";import{resolveBillingApiUrl as Zi}from"@flopay/shared";function Pn(){return Tr(xn).flopay}function xo(){return Tr(xn).paypalFlopay??null}function To(){return Tr(xn).elements}function Qi(){return Tr(ln)}function Gr(){return Tr(xn).billingApiUrl||Zi()}import"react";import{jsx as tn,jsxs as ar}from"react/jsx-runtime";var Tn=1200,bn=1500;function vn({status:e,errorMessage:t}){return tn("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:ar("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[ar("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&ar("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[tn("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),tn("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&tn("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:ar("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[tn("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),tn("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&tn("div",{style:{animation:"flopay-shake 0.4s ease"},children:ar("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[tn("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),tn("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),ar("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&"PROCESSING...",e==="success"&&"PAYMENT SUCCESSFUL",e==="error"&&"PAYMENT FAILED"]}),e==="success"&&tn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:"You will be automatically redirected, do not close or navigate away from this window."}),e==="error"&&t&&tn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),tn("style",{children:`
|
|
1
|
+
import{useCallback as Vi,useEffect as _r,useState as Eo,useMemo as Hi,useRef as _o}from"react";import{resolveBillingApiUrl as Ki}from"@flopay/shared";import{createContext as _a}from"react";var xn=_a({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),cn=_a({session:null,loading:!1,error:null});var Ui=Symbol.for("@flopay/js.telemetry.bridge.v1"),$i=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function qi(){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 ji(e){let t=qi(),n=(r,a)=>r?r.bind(e):a,i=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:i,elapsed:e.elapsed?e.elapsed.bind(e):r=>Math.max(0,i()-r),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Yr(e){let t=globalThis[$i];return ji(t?.(e)??{})}function At(e){if(e)return e[Ui]}import{jsx as Wi}from"react/jsx-runtime";function Gr({flopay:e,paypalFlopay:t,options:n,children:i}){let[r,a]=Eo(e instanceof Promise?null:e),[c,s]=Eo(t instanceof Promise||!t?null:t),[S,B]=Eo(null),p=_o(null),R=_o(null),C=_o(null);_r(()=>{if(!r)return;let w=At(r);return p.current=w?.beginCheckout()??w?.now()??0,w?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{w?.log({name:"checkout.unmount",stage:"unmount"})}},[r]),_r(()=>{let w=!1;return e instanceof Promise?e.then(T=>{w||a(T)}):a(e),()=>{w=!0}},[e]),_r(()=>{let w=!1;if(!t){s(null);return}return t instanceof Promise?t.then(T=>{w||s(T)}):s(t),()=>{w=!0}},[t]),_r(()=>{if(!r){B(null);return}let w=r.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return B(w),()=>{w.destroy()}},[r,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),_r(()=>{if(!r||!S||R.current===S)return;R.current=S;let w=At(r);w?.log({name:"checkout.rendered",stage:"checkout_render"}),w?.performance({stage:"checkout_render",durationMs:w.elapsed(p.current??0),durationMode:"machine"})},[S,r]);let _=Vi(()=>{if(!r||!S||C.current===S)return;C.current=S;let w=At(r);w?.log({name:"checkout.interactive",stage:"checkout_interactive"}),w?.performance({stage:"checkout_interactive",durationMs:w.elapsed(p.current??0),durationMode:"machine"})},[S,r]),l=Ki(n?.billingApiUrl),f=Hi(()=>({flopay:r,paypalFlopay:c,elements:S,billingApiUrl:l,reportInteractive:_}),[r,c,S,l,_]);return Wi(xn.Provider,{value:f,children:i})}import Ko,{useCallback as Zn,useEffect as Bn,useMemo as dn,useRef as nn,useState as wt}from"react";import{PaymentAPI as uo}from"@flopay/js";import{SDK_VERSION as hi,FloPayError as Mt,resolveBillingApiUrl as Ks,buildCheckoutDisplayData as mi,resolveButtonsLayoutTheme as Ws,resolveTheme as Pi}from"@flopay/shared";import"react";import{Fragment as rr,jsx as en,jsxs as xa}from"react/jsx-runtime";function Yi(){return xa(rr,{children:[xa("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 Gi(){return en(rr,{children:"Go back"})}function Ji(){return en(rr,{children:"Secure card checkout"})}function er(e){return e!==void 0&&(e===""||e===null||e===!1)}function tr({content:e}){return en(rr,{children:e===void 0?en(Yi,{}):e})}function nr({content:e}){return en(rr,{children:e===void 0?en(Gi,{}):e})}function xr({content:e}){return en(rr,{children:e===void 0?en(Ji,{}):e})}import{ExpressCheckoutElement as ni,PaymentElement as ps,Elements as Jn,useElements as $o,useStripe as qo}from"@stripe/react-stripe-js";import{resolveButtonsLayoutTheme as ms,getPostalCodeLabel as zo,getStateLabel as Va,getStateOptions as ys,COUNTRY_OPTIONS as fs,resolveAVSConfig as gs,isAVSFieldVisible as _e,getStateFromPostalCode as Ha,isPostalCodeSupported as hs,isValidPostalCode as Ps,getPostalCodeExample as bs,filterStripeMethodsByCountry as vs,getStripeMethodDisplayName as dr,hasVendoredStripeMethodLogo as Cs,needsStripeMethodExplicitConfirm as Ka,resolveStripeMethodBrandVariant as Ss,partitionStripeMethods as ws,stripeExpressMethodToOptionKey as Wa}from"@flopay/shared";import{PaymentAPI as Nn,toStripeAppearance as ks}from"@flopay/js";import{useEffect as Ta,useRef as Tr}from"react";import{jsx as Xi}from"react/jsx-runtime";function xo({capture:e,html:t,messageToken:n,expectedOrigin:i,theme:r,containerStyle:a,onReady:c,onError:s,onValidation:S}){let B=Tr(null),p=Tr(c),R=Tr(s),C=Tr(S);p.current=c,R.current=s,C.current=S;let _=Tr(r);return _.current=r,Ta(()=>{let l=B.current;if(!l)return;let f=!0,w=!1,T=()=>{!f||w||(w=!0,p.current?.())},h=e.on("ready",()=>{T()}),$=e.on("error",re=>{R.current?.(re.message??"There was a problem loading the secure card form.")}),Y=e.on("validation",re=>{C.current?.(re.message??null)}),le={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},..._.current?{theme:_.current}:{}};return e.mount(l,le).then(()=>{T()}).catch(re=>{f&&R.current?.(re instanceof Error?re.message:"Failed to load the secure card form.")}),()=>{f=!1,h(),$(),Y(),e.unmount()}},[e,t,n,i]),Ta(()=>{r&&e.applyTheme?.(r)},[e,r]),Xi("div",{ref:B,"data-testid":"flopay-vault-card-fields",style:a})}import"react";import{jsx as Ma,jsxs as Zi}from"react/jsx-runtime";function or({children:e,margin:t,icon:n=!0,styleOverride:i}){return Zi("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&&Ma("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Ma("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 Ba={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 Rs,{useCallback as ge,useContext as Is,useEffect as pt,useMemo as at,useRef as Le,useState as be}from"react";import{useContext as Mr}from"react";import{resolveBillingApiUrl as Qi}from"@flopay/shared";function Pn(){return Mr(xn).flopay}function To(){return Mr(xn).paypalFlopay??null}function Mo(){return Mr(xn).elements}function es(){return Mr(cn)}function Jr(){return Mr(xn).billingApiUrl||Qi()}import"react";import{jsx as tn,jsxs as ar}from"react/jsx-runtime";var Tn=1200,bn=1500;function vn({status:e,errorMessage:t}){return tn("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:ar("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[ar("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&ar("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[tn("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),tn("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&tn("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:ar("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[tn("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),tn("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&tn("div",{style:{animation:"flopay-shake 0.4s ease"},children:ar("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[tn("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),tn("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),ar("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&"PROCESSING...",e==="success"&&"PAYMENT SUCCESSFUL",e==="error"&&"PAYMENT FAILED"]}),e==="success"&&tn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:"You will be automatically redirected, do not close or navigate away from this window."}),e==="error"&&t&&tn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),tn("style",{children:`
|
|
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 dc,isSetupIntentClientSecret as uc}from"@flopay/shared";function Ba(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 Mo(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 Aa(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 Bo(e,t){return t?{...e,...t}:e}function Bt(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 es=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Dn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:i}of es)if(n.test(t))return i;return e}function Jr(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Fa(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Da(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Xr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Zr="flopay_recent_completion_";function ir(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Zr+e,JSON.stringify(t))}catch{}}function La(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Zr+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Zr+e),!1):!0}catch{return!1}}function Na(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 Qr,useEffect as ut,useMemo as Br,useRef as We,useState as Gn}from"react";import{loadScript as ns}from"@paypal/paypal-js";import{PaymentAPI as Ao}from"@flopay/js";import{FloPayError as Oa,SDK_VERSION as rs,generateIdempotencyKey as os,normalizeGatewayEnvironment as as}from"@flopay/shared";function gt(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 ts(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Yn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Mn(e){if(typeof e!="object"||e===null)return;let t=e;return Yn(t.code)??Yn(t.type)??Yn(t.name)}function sr(e){if(!(typeof e!="object"||e===null))return Yn(e.decline_code)}function Mr(e){return typeof e!="object"||e===null?!1:Yn(e.type)?.toLowerCase()==="card_error"||sr(e)!==void 0}function Ln(e){let t=ts(e)?.toLowerCase()??"",i=`${Mn(e)?.toLowerCase()??""} ${t}`;return i.includes("popup")&&i.includes("block")}import{jsx as lr,jsxs as Fo}from"react/jsx-runtime";var eo=45,is=1e3,ss=11e3,ls=["https://www.paypal.com","https://www.sandbox.paypal.com"],za="We couldn't open PayPal. Try again or choose another payment method.",cs={width:"100%",minHeight:eo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Ua(e){return e.includes("No ack for postMessage init()")&&ls.some(t=>e.includes(t))&&e.includes("10000ms")}function ds(e){return e?`${za} Allow pop-ups for this site, then try again.`:za}function $a({sessionId:e,nonce:t,billingApiUrl:n,email:i,clientId:r,environment:a,currency:c,isSubscription:s,onTokenizedBody:w,onComplete:M,onErrorChange:p,onDecline:R,onTechnicalFailure:C,isProcessing:E=!1,onLoadStateChange:l,onInitializationStateChange:f,allowAutomaticRetry:S=!0,onButtonClick:x,runBeforeButtonClick:h,session:U,existingOrderId:Y,telemetry:ce,telemetryContext:re,debug:F=!1}){let J=Pn(),$=Br(()=>{if(J)return null;let y=Wr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:rs,enabled:ce!==!1});return y.setCheckoutContext(re??{}),y.beginCheckout(re??{}),y},[n,J,ce,re?.checkoutMode,re?.layout]),de=Br(()=>Dt(J),[J]);ut(()=>()=>{$&&$.flush().catch(()=>{}).finally(()=>$.destroy())},[$]);let q=Br(()=>({error:y=>{de?de.error(y):$?.error(y)},log:y=>{de?de.log(y):$?.log(y)},performance:y=>{de?de.performance(y):$?.performance(y)},terminal:y=>{de?de.terminal(y):$?.terminal(y)},startTiming:()=>de?.now()??$?.now()??0,elapsed:y=>de?.elapsed(y)??Math.max(0,($?.now()??y)-y)}),[de,$]),j=We(null),oe=We(0),Be=We(null),me=We(!1),[pe,X]=Gn(!1),[ue,he]=Gn(!1),[ae,Fe]=Gn(0),ke=We(0),[Ce,k]=Gn(!1),ee=We(!1),ie=We(!1),[Oe,De]=Gn(!1),[G,_]=Gn(!1),V=Br(()=>n.replace(/\/+$/,""),[n]),se=Br(()=>JSON.stringify([V,r,c,a??"",s,e,Y??""]),[V,r,c,a,Y,s,e]),Re=We(se),ht=Re.current!==se,[Ze,Xe]=Gn([]),m=y=>{F&&Xe(Ie=>[...Ie,`${new Date().toISOString().slice(11,23)} ${y}`])},$e=We(w),ze=We(M),je=We(p),Ve=We(R),Yt=We(C),vt=We(x),It=We(l),g=We(f),we=We(h),qe=We(U),it=We(i),et=We(t),tt=We(null),Ye=We(0),Pe=We(null),Ct=We(null),He=We(new Map),Lt=We(new Map),Et=We(!1);ut(()=>(Et.current=!0,()=>{Et.current=!1}),[]),ut(()=>{$e.current=w},[w]),ut(()=>{ze.current=M},[M]),ut(()=>{je.current=p},[p]),ut(()=>{Ve.current=R},[R]),ut(()=>{Yt.current=C},[C]),ut(()=>{vt.current=x},[x]),ut(()=>{It.current=l},[l]),ut(()=>{g.current=f},[f]),ut(()=>{we.current=h},[h]),ut(()=>{qe.current=U},[U]),ut(()=>{it.current=i},[i]),ut(()=>{et.current=t},[t]),ut(()=>{ke.current=ae},[ae]),ut(()=>{Ce&&Be.current?.focus()},[Ce,ae]);let dn=Qr(()=>{window.setTimeout(()=>{Be.current?.focus()},0)},[]),Rn=Qr(()=>{X(!1),Fe(y=>y+1)},[]),In=Qr(()=>{k(!1),(j.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??j.current)?.focus?.()},[]);ut(()=>{!pe||!me.current||(me.current=!1,In())},[In,pe,ae]);let $n=Qr((y,Ie)=>{let st=Yt.current;if(st){st("paypal",y,Ie);return}je.current?.(ds(Ie?.popupBlocked??Ln(y)))},[]),Pt=()=>{Pe.current?.timer&&(clearTimeout(Pe.current.timer),Pe.current.timer=null)},Nt=()=>{Pt();let y=Ye.current+1;return Ye.current=y,Ct.current=null,Pe.current={generation:y,timer:null,yieldedControl:!1},k(!1),y},Ot=y=>y!==void 0&&Pe.current?.generation!==y?!1:(Pt(),Pe.current=null,Ct.current=null,!0),Gt=y=>{let Ie=y?.generation??Pe.current?.generation??Ye.current;(!y?.generation||Pe.current?.generation===Ie)&&(Pt(),Pe.current=null),Ct.current=Ie,y?.showRetry&&k(!0),y?.remount&&Rn(),y?.focus!==!1&&dn()},rn=y=>Pe.current?.generation===y&&Ct.current!==y,un=y=>{typeof document<"u"&&document.visibilityState!=="visible"||(Pt(),y.timer=setTimeout(()=>{Pe.current?.generation===y.generation&&(Pe.current=null,Ct.current=y.generation,$n(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),k(!0),Rn(),dn())},600))},H=()=>{let y=Pe.current;y?.yieldedControl&&un(y)},An=()=>{let y=Pe.current;y&&(y.yieldedControl=!0,Pt())},pn=y=>{let Ie=tt.current;return Ie&&Lt.current.set(y,Ie),y};ut(()=>{let y=()=>{document.visibilityState==="visible"?H():An()};return document.addEventListener("visibilitychange",y),window.addEventListener("focus",H),window.addEventListener("blur",An),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("focus",H),window.removeEventListener("blur",An),Pt()}},[]),ut(()=>{Re.current!==se&&(Re.current=se,ee.current=!1,ie.current=!1,X(!1),he(!1),De(!1),g.current?.("loading"))},[se]),ut(()=>{gt(()=>It.current?.(pe&&!Oe))},[pe,Oe]);let zt=as(a);ut(()=>{let y=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",Ie=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(m(`mount clientId=${y} env=${a??"(unset)"}\u2192${zt??"live"} ccy=${c} sub=${s}`),m(`ua=${Ie.slice(0,80)}${Ie.length>80?"\u2026":""}`),!r){m("FAIL: clientId empty \u2014 gateway misconfigured"),De(!0),q.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!j.current){m("FAIL: containerRef not attached");return}oe.current=q.startTiming(),q.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let st=!1,En=!1,Ee=()=>st||En,Fn,mn=!1,qn=()=>{Fn=os(),Fn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),mn=!0},yn=null,Ut=!1,Ft=null,Se=!1,yt=()=>{!Ft||Se||(Se=!0,Ft.close().catch(()=>{}))},rt=null,on=()=>{rt!==null&&(q.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),q.performance({stage:"overlay_return",durationMs:q.elapsed(rt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),rt=null)},Jt=!1,bt=j.current,Ht=null,wt=null,an=[],fn=B=>{if(!B||typeof B.getBoundingClientRect!="function")return"(no rect)";let P=B.getBoundingClientRect();return`${Math.round(P.width)}\xD7${Math.round(P.height)}`},_n=B=>{if(!B)return"(empty)";try{let P=new URL(B,typeof window<"u"?window.location.href:"https://localhost"),A=P.pathname.toLowerCase();return A.includes("checkcaptcha")||A.includes("captcha")?`CAPTCHA(${P.host}${A})`:A.includes("risk")||A.includes("challenge")?`RISK(${P.host}${A})`:A.includes("smart/buttons")?`smart-buttons(${P.host})`:`${P.host}${A}`.slice(0,100)}catch{return B.slice(0,80)}},gn=B=>{let P=B.getAttribute("src"),A=B.getAttribute("srcdoc"),ye=B.getAttribute("name"),Me=B.getAttribute("sandbox"),Ue=[];return P&&Ue.push(`src=${_n(P)}`),A&&Ue.push(`srcdoc[${A.length}ch]`),!P&&!A&&Ue.push("src=(empty) srcdoc=(empty)"),ye&&Ue.push(`name=${ye.slice(0,40)}`),Me!==null&&Ue.push(`sandbox="${Me.slice(0,40)}"`),Ue.join(" ")},Kt=B=>{if(!(B instanceof HTMLIFrameElement))return"";try{let P=B.contentDocument;if(!P)return"cd=null";let A=P.body?.children.length??0,ye=P.body?.innerHTML.length??0,Me=P.head?.innerHTML.length??0;return`cd=same-origin readyState=${P.readyState} body[${A}children,${ye}ch] head[${Me}ch]`}catch(P){return`cd=cross-origin(${P.message.slice(0,30)})`}},Ke=[],Wt=B=>{if(Ee())return;let P=B.message??String(B.error??"(no message)");P&&(P.toLowerCase().includes("paypal")||P.toLowerCase().includes("zoid")||P.toLowerCase().includes("postrobot")||P.toLowerCase().includes("storage"))&&(m(`window:error ${P.slice(0,140)}`),Ke.push(P))},$t=B=>{if(Ee())return;let P=B.reason instanceof Error?B.reason.message:String(B.reason??"(no reason)");P&&(P.toLowerCase().includes("paypal")||P.toLowerCase().includes("zoid")||P.toLowerCase().includes("postrobot")||P.toLowerCase().includes("storage"))&&(m(`window:rejection ${P.slice(0,140)}`),Ke.push(P))};F&&typeof window<"u"&&(window.addEventListener("error",Wt),window.addEventListener("unhandledrejection",$t));let qt={value:0};if(F&&typeof PerformanceObserver<"u")try{wt=new PerformanceObserver(B=>{if(!Ee())for(let P of B.getEntries()){if(!P.name.toLowerCase().includes("paypal"))continue;qt.value+=1;let A=Math.round(P.duration);m(`net ${A}ms ${P.name.slice(0,90)}`)}}),wt.observe({type:"resource",buffered:!0})}catch{}let I=()=>{for(Ht?.disconnect(),Ht=null,wt?.disconnect(),wt=null;an.length;)clearTimeout(an.pop());F&&typeof window<"u"&&(window.removeEventListener("error",Wt),window.removeEventListener("unhandledrejection",$t))},D=B=>{if(!B)return!1;let P=B.toLowerCase();return P.includes("zoid destroyed")||P.includes("destroyed all components")||P.includes("window closed")||P.includes("detected container element removed")},N=B=>{if(Ee()||D(B))return;let P=Dn(B)??B;gt(()=>je.current?.(P))},T=B=>{st||(De(!0),B.includes("paypal_ineligible")||q.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal load/render failure:",B))},u=(B,P=!1)=>{if(st)return;let A=ee.current||!S;if(Ut)return;Ut=!0,En=!0,I(),yt();let ye=P||Ua(B);if(ye&&S&&!ee.current){ee.current=!0,X(!1),_(!1),he(!0),g.current?.("retrying"),yn=setTimeout(()=>{st||Fe(Me=>Me+1)},is);return}if(ye||A){if(X(!1),_(!1),he(!1),De(!0),g.current?.("exhausted"),!ie.current){ie.current=!0;let Me=Ua(B)?"paypal_init_timeout":P?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",Me)}return}T(B)};De(!1);let O=async(B,P=tt.current)=>{if(Ee())return;let A=P?.sessionId??e;if($e.current){await $e.current(B,{sessionId:A,accountPatch:P?.accountPatch,nonce:P?.nonce});return}let ye=q.startTiming();q.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Me=()=>{q.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),q.performance({stage:"processing",durationMs:q.elapsed(ye),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Ue=qe.current,W=P?.accountPatch?.email??it.current,fe=P?.accountPatch?.userId??Ue?.customer?.id??Ue?.accountData?.userId??"",le=await new Ao(V,{telemetry:!1}).processPayment(fe,{sessionId:A,nonce:P?.nonce??et.current,tokenizedData:B,accountData:{userId:fe,email:W??Ue?.customer?.email??"",firstName:P?.accountPatch?.firstName??Ue?.customer?.firstName??Ue?.accountData?.firstName??"",lastName:P?.accountPatch?.lastName??Ue?.customer?.lastName??Ue?.accountData?.lastName??"",country:P?.accountPatch?.country??Ue?.customer?.country??Ue?.accountData?.country??void 0,zip:P?.accountPatch?.zip??Ue?.customer?.zip??Ue?.accountData?.zip??void 0}});if(le.ok){if(En||st&&Et.current)return;Me(),q.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),gt(()=>ze.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ee())return;let Le=await le.json().catch(()=>null),hn=Le?.message??"PayPal payment failed.",lt=Dn(hn)??hn;Me(),typeof Le?.declineCode=="string"?q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):q.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:le.status>=500?"5xx":le.status>=400?"4xx":le.status>=300?"3xx":"unknown"}),N(lt),gt(()=>Ve.current?.(Bt("paypal",lt,{code:Le?.code,declineCode:Le?.declineCode})));return}catch(Ue){if(Ee())return;Me(),q.error({errorCode:"NETWORK_REQUEST_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let W=Ue instanceof Error?Ue.message:"PayPal payment failed.",fe=Dn(W)??W;N(fe),gt(()=>Ve.current?.(Bt("paypal",fe)));return}},b=()=>new Oa("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Te=B=>Ee()?Promise.reject(b()):Promise.resolve(B),K=async B=>{if(Ee())throw b();mn||qn();let P=tt.current,A=P?.sessionId??e,ye=P?.nonce??et.current;q.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Me=await new Ao(V,{telemetry:!1}).createSessionIntent(A,ye??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Fn});if(Ee())throw b();if(Me.provider!=="paypal")throw new Error(B);return q.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Me.providerObjectId},Ge=(B,P)=>{let A=P?.nonce??et.current;if(!A)return;let ye=P?.sessionId??e,Me=sr(B)??Mn(B)??"provider_declined";new Ao(V,{telemetry:!1}).reportSessionIntentDecline(ye,A,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Me}).catch(()=>{})},te=ae;m("loadScript:scheduled (deferred 1 tick)");let jt=null,ot=setTimeout(()=>{if(st){m("loadScript:skipped (cancelled before defer ran)");return}m("loadScript:start");let B=zt==="live"?"production":zt;jt=ns({clientId:r,currency:c,intent:s?"subscription":"capture",vault:s?!0:void 0,...B?{environment:B}:{},...B==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),jt.then(P=>{if(m(`loadScript:resolved inactive=${Ee()} ns=${!!P} buttons=${!!P?.Buttons}`),Ee())return;if(!P?.Buttons){m("FAIL: namespace missing Buttons factory"),u("PayPal SDK did not expose the Buttons factory.");return}q.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let A=async fe=>{if(Ee()||ke.current!==te)return;let be=fe.subscriptionID??fe.orderID??"",le=be?Lt.current.get(be):He.current.get(te);if(!(!le||!rn(le.generation))&&Ot(le.generation)){Lt.current.delete(be),He.current.delete(le.surfaceKey),on();try{if(_(!0),gt(()=>je.current?.(null)),!be)throw new Oa("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await O({id:be,isPaypal:!0},le)}catch(Le){N(Le instanceof Error?Le.message:"PayPal capture failed.")}finally{Ee()||_(!1)}}},ye=P.Buttons({style:{layout:"horizontal",height:eo,tagline:!1},onClick:async(fe,be)=>{if(Ee()){await be.reject();return}qn();let le=we.current,Le={};if(le)try{let _t=await le("paypal");if(Ee()){await be.reject();return}if(!_t.proceed){tt.current=null,He.current.delete(te),await be.reject();return}Le={sessionId:_t.sessionId,accountPatch:_t.accountPatch,nonce:_t.nonce}}catch(_t){m(`onClick:runBeforeButtonClick rejected msg=${(_t instanceof Error?_t.message:String(_t)).slice(0,120)}`),tt.current=null,He.current.delete(te),await be.reject();return}gt(()=>vt.current?.("paypal"));let lt={generation:Nt(),surfaceKey:te,...Le};tt.current=lt,He.current.set(te,lt),await be.resolve(),q.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),q.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),q.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),rt=q.startTiming()},createOrder:s?void 0:Y?()=>Te(Y).then(pn):()=>K("Failed to create PayPal order.").then(pn),createSubscription:s?Y?()=>Te(Y).then(pn):()=>K("Failed to create PayPal subscription.").then(pn):void 0,onApprove:A,onCancel:()=>{if(Ee())return;let fe=He.current.get(te)??tt.current;fe&&He.current.delete(fe.surfaceKey),tt.current=null,on(),q.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),me.current=!0,Gt({generation:fe?.generation,remount:!0,focus:!1})},onError:fe=>{if(Ee()||ke.current!==te)return;let be=fe instanceof Error?fe.message:"PayPal failed to render.";if(m(`onError rendered=${Jt} msg=${be.slice(0,120)}`),Jt){let le=He.current.get(te)??tt.current;if(le&&!rn(le.generation)||!le&&Ct.current===Ye.current)return;if(D(be)){Ot(le?.generation);return}on();let Le=be.toLowerCase();q.error({errorCode:Le.includes("popup")&&Le.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),Mr(fe)&&Ge(fe,le),le&&He.current.delete(le.surfaceKey),tt.current=null,Gt({generation:le?.generation,remount:!0,showRetry:!0,focus:!0}),$n(fe,{code:"paypal_runtime_failed"});return}u(be)}}),Me=ye.isEligible();if(m(`isEligible=${Me}`),q.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Me){X(!1),u("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ft=ye,F&&m(`container:dims ${fn(bt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),F&&typeof MutationObserver<"u"&&(Ht=new MutationObserver(fe=>{if(!Ee()){for(let be of fe)if(be.type==="childList")be.addedNodes.forEach(le=>{if(!(le instanceof Element))return;let Le=le.tagName.toLowerCase(),hn=(le.getAttribute("title")??"").slice(0,40),lt=Le==="iframe"?` ${gn(le)}`:"";m(`child+ ${Le}${hn?` title="${hn}"`:""}${lt} dims=${fn(le)}`)});else if(be.type==="attributes"&&be.target instanceof Element){let le=be.target;if(le.tagName.toLowerCase()!=="iframe")continue;let Le=be.attributeName;(Le==="src"||Le==="srcdoc")&&m(`attr~ iframe ${Le}=${Le==="srcdoc"?`[${(le.getAttribute("srcdoc")??"").length}ch]`:_n(le.getAttribute("src"))} dims=${fn(le)}`)}}}),Ht.observe(bt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let W=fe=>{if(Ee()||Jt)return;let be=bt.querySelectorAll("iframe"),le=typeof document<"u"&&"hasStorageAccess"in document;m(`watchdog:${fe} container=${fn(bt)} children=${bt.childElementCount} iframes=${be.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${le} paypalNetRequests=${qt.value}`),be.forEach((Le,hn)=>{let lt=(Le.getAttribute("title")??"").slice(0,40);m(` iframe[${hn}] ${fn(Le)}${lt?` title="${lt}"`:""} ${gn(Le)}`);let _t=Kt(Le);_t&&m(` ${_t}`)}),Ke.length===0&&m(" (no PayPal/zoid window errors captured)")};F&&(an.push(setTimeout(()=>W("3s"),3e3)),an.push(setTimeout(()=>W("8s"),8e3)),an.push(setTimeout(()=>W("15s"),15e3))),m("render:start"),an.push(setTimeout(()=>{Ee()||Jt||(m("watchdog:11s retryable render timeout"),u("PayPal Buttons render did not settle within 11000ms.",!0))},ss)),ye.render(bt).then(()=>{if(m(`render:resolved inactive=${Ee()}`),I(),Ee()){yt();return}Jt=!0,X(!0),he(!1),g.current?.("ready"),q.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),q.performance({stage:"provider_ready",durationMs:q.elapsed(oe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(fe=>{let be=fe instanceof Error?fe.message:"PayPal failed to render.";m(`render:rejected msg=${be.slice(0,120)}`),I(),u(be)})}).catch(P=>{let A=P instanceof Error?P.message:"PayPal SDK failed to load.";m(`loadScript:rejected msg=${A.slice(0,120)}`),u(A)})},0);return()=>{st=!0,clearTimeout(ot),yn&&clearTimeout(yn),I(),yt()}},[S,V,r,c,a,s,e,Y,ae,q]);let nt=F?Fo("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Oe?"#fef2f2":"#f3f4f6",border:`1px solid ${Oe?"#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=${Oe})`,Ze.length===0?`
|
|
6
|
+
`})]})})}import{FloPayError as pc,isSetupIntentClientSecret as mc}from"@flopay/shared";function Aa(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Bo(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Fa(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],i=n.reduce((a,c)=>a+(c.overrideAmount??c.totalAmount??0),0),r=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(i*100),currency:r,status:"open",customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,c)=>({uuid:`synthetic-${a.type??"item"}-${c}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??r,metadata:a.metadata??null}))}}function Ao(e,t){return t?{...e,...t}:e}function Tt(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 ts=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Dn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:i}of ts)if(n.test(t))return i;return e}function Xr(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Da(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function La(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Zr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Qr="flopay_recent_completion_";function ir(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Qr+e,JSON.stringify(t))}catch{}}function Na(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Qr+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Qr+e),!1):!0}catch{return!1}}function Oa(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}import{useCallback as eo,useEffect as ut,useMemo as Ar,useRef as Ke,useState as Gn}from"react";import{loadScript as rs}from"@paypal/paypal-js";import{PaymentAPI as Fo}from"@flopay/js";import{FloPayError as za,SDK_VERSION as os,generateIdempotencyKey as as,normalizeGatewayEnvironment as is}from"@flopay/shared";function ft(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 ns(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Yn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Mn(e){if(typeof e!="object"||e===null)return;let t=e;return Yn(t.code)??Yn(t.type)??Yn(t.name)}function sr(e){if(!(typeof e!="object"||e===null))return Yn(e.decline_code)}function Br(e){return typeof e!="object"||e===null?!1:Yn(e.type)?.toLowerCase()==="card_error"||sr(e)!==void 0}function Ln(e){let t=ns(e)?.toLowerCase()??"",i=`${Mn(e)?.toLowerCase()??""} ${t}`;return i.includes("popup")&&i.includes("block")}import{jsx as lr,jsxs as Do}from"react/jsx-runtime";var to=45,ss=1e3,ls=11e3,cs=["https://www.paypal.com","https://www.sandbox.paypal.com"],Ua="We couldn't open PayPal. Try again or choose another payment method.",ds={width:"100%",minHeight:to,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function $a(e){return e.includes("No ack for postMessage init()")&&cs.some(t=>e.includes(t))&&e.includes("10000ms")}function us(e){return e?`${Ua} Allow pop-ups for this site, then try again.`:Ua}function qa({sessionId:e,nonce:t,billingApiUrl:n,email:i,clientId:r,environment:a,currency:c,isSubscription:s,onTokenizedBody:S,onComplete:B,onErrorChange:p,onDecline:R,onTechnicalFailure:C,isProcessing:_=!1,onLoadStateChange:l,onInitializationStateChange:f,allowAutomaticRetry:w=!0,onButtonClick:T,runBeforeButtonClick:h,session:$,existingOrderId:Y,telemetry:le,telemetryContext:re,debug:D=!1}){let J=Pn(),q=Ar(()=>{if(J)return null;let y=Yr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:os,enabled:le!==!1});return y.setCheckoutContext(re??{}),y.beginCheckout(re??{}),y},[n,J,le,re?.checkoutMode,re?.layout]),ce=Ar(()=>At(J),[J]);ut(()=>()=>{q&&q.flush().catch(()=>{}).finally(()=>q.destroy())},[q]);let j=Ar(()=>({error:y=>{ce?ce.error(y):q?.error(y)},log:y=>{ce?ce.log(y):q?.log(y)},performance:y=>{ce?ce.performance(y):q?.performance(y)},terminal:y=>{ce?ce.terminal(y):q?.terminal(y)},startTiming:()=>ce?.now()??q?.now()??0,elapsed:y=>ce?.elapsed(y)??Math.max(0,(q?.now()??y)-y)}),[ce,q]),V=Ke(null),oe=Ke(0),Be=Ke(null),fe=Ke(!1),[me,X]=Gn(!1),[de,he]=Gn(!1),[ae,Fe]=Gn(0),we=Ke(0),[ve,k]=Gn(!1),ee=Ke(!1),ie=Ke(!1),[Ne,De]=Gn(!1),[G,x]=Gn(!1),H=Ar(()=>n.replace(/\/+$/,""),[n]),se=Ar(()=>JSON.stringify([H,r,c,a??"",s,e,Y??""]),[H,r,c,a,Y,s,e]),ke=Ke(se),gt=ke.current!==se,[Xe,Je]=Gn([]),m=y=>{D&&Je(Ie=>[...Ie,`${new Date().toISOString().slice(11,23)} ${y}`])},Ue=Ke(S),Oe=Ke(B),qe=Ke(p),je=Ke(R),Kt=Ke(C),bt=Ke(T),Rt=Ke(l),g=Ke(f),Ce=Ke(h),$e=Ke($),st=Ke(i),Qe=Ke(t),et=Ke(null),We=Ke(0),Pe=Ke(null),vt=Ke(null),Ve=Ke(new Map),Ft=Ke(new Map),It=Ke(!1);ut(()=>(It.current=!0,()=>{It.current=!1}),[]),ut(()=>{Ue.current=S},[S]),ut(()=>{Oe.current=B},[B]),ut(()=>{qe.current=p},[p]),ut(()=>{je.current=R},[R]),ut(()=>{Kt.current=C},[C]),ut(()=>{bt.current=T},[T]),ut(()=>{Rt.current=l},[l]),ut(()=>{g.current=f},[f]),ut(()=>{Ce.current=h},[h]),ut(()=>{$e.current=$},[$]),ut(()=>{st.current=i},[i]),ut(()=>{Qe.current=t},[t]),ut(()=>{we.current=ae},[ae]),ut(()=>{ve&&Be.current?.focus()},[ve,ae]);let un=eo(()=>{window.setTimeout(()=>{Be.current?.focus()},0)},[]),Rn=eo(()=>{X(!1),Fe(y=>y+1)},[]),In=eo(()=>{k(!1),(V.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??V.current)?.focus?.()},[]);ut(()=>{!me||!fe.current||(fe.current=!1,In())},[In,me,ae]);let $n=eo((y,Ie)=>{let lt=Kt.current;if(lt){lt("paypal",y,Ie);return}qe.current?.(us(Ie?.popupBlocked??Ln(y)))},[]),ht=()=>{Pe.current?.timer&&(clearTimeout(Pe.current.timer),Pe.current.timer=null)},Dt=()=>{ht();let y=We.current+1;return We.current=y,vt.current=null,Pe.current={generation:y,timer:null,yieldedControl:!1},k(!1),y},Lt=y=>y!==void 0&&Pe.current?.generation!==y?!1:(ht(),Pe.current=null,vt.current=null,!0),Wt=y=>{let Ie=y?.generation??Pe.current?.generation??We.current;(!y?.generation||Pe.current?.generation===Ie)&&(ht(),Pe.current=null),vt.current=Ie,y?.showRetry&&k(!0),y?.remount&&Rn(),y?.focus!==!1&&un()},rn=y=>Pe.current?.generation===y&&vt.current!==y,pn=y=>{typeof document<"u"&&document.visibilityState!=="visible"||(ht(),y.timer=setTimeout(()=>{Pe.current?.generation===y.generation&&(Pe.current=null,vt.current=y.generation,$n(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),k(!0),Rn(),un())},600))},K=()=>{let y=Pe.current;y?.yieldedControl&&pn(y)},An=()=>{let y=Pe.current;y&&(y.yieldedControl=!0,ht())},mn=y=>{let Ie=et.current;return Ie&&Ft.current.set(y,Ie),y};ut(()=>{let y=()=>{document.visibilityState==="visible"?K():An()};return document.addEventListener("visibilitychange",y),window.addEventListener("focus",K),window.addEventListener("blur",An),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("focus",K),window.removeEventListener("blur",An),ht()}},[]),ut(()=>{ke.current!==se&&(ke.current=se,ee.current=!1,ie.current=!1,X(!1),he(!1),De(!1),g.current?.("loading"))},[se]),ut(()=>{ft(()=>Rt.current?.(me&&!Ne))},[me,Ne]);let Nt=is(a);ut(()=>{let y=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",Ie=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(m(`mount clientId=${y} env=${a??"(unset)"}\u2192${Nt??"live"} ccy=${c} sub=${s}`),m(`ua=${Ie.slice(0,80)}${Ie.length>80?"\u2026":""}`),!r){m("FAIL: clientId empty \u2014 gateway misconfigured"),De(!0),j.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}oe.current=j.startTiming(),j.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let lt=!1,En=!1,Ee=()=>lt||En,Fn,yn=!1,qn=()=>{Fn=as(),Fn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),yn=!0},fn=null,Ot=!1,Bt=null,Se=!1,mt=()=>{!Bt||Se||(Se=!0,Bt.close().catch(()=>{}))},nt=null,on=()=>{nt!==null&&(j.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"overlay_return",durationMs:j.elapsed(nt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),nt=null)},Yt=!1,Pt=V.current,jt=null,Ct=null,an=[],gn=A=>{if(!A||typeof A.getBoundingClientRect!="function")return"(no rect)";let P=A.getBoundingClientRect();return`${Math.round(P.width)}\xD7${Math.round(P.height)}`},_n=A=>{if(!A)return"(empty)";try{let P=new URL(A,typeof window<"u"?window.location.href:"https://localhost"),F=P.pathname.toLowerCase();return F.includes("checkcaptcha")||F.includes("captcha")?`CAPTCHA(${P.host}${F})`:F.includes("risk")||F.includes("challenge")?`RISK(${P.host}${F})`:F.includes("smart/buttons")?`smart-buttons(${P.host})`:`${P.host}${F}`.slice(0,100)}catch{return A.slice(0,80)}},hn=A=>{let P=A.getAttribute("src"),F=A.getAttribute("srcdoc"),ye=A.getAttribute("name"),Me=A.getAttribute("sandbox"),ze=[];return P&&ze.push(`src=${_n(P)}`),F&&ze.push(`srcdoc[${F.length}ch]`),!P&&!F&&ze.push("src=(empty) srcdoc=(empty)"),ye&&ze.push(`name=${ye.slice(0,40)}`),Me!==null&&ze.push(`sandbox="${Me.slice(0,40)}"`),ze.join(" ")},Vt=A=>{if(!(A instanceof HTMLIFrameElement))return"";try{let P=A.contentDocument;if(!P)return"cd=null";let F=P.body?.children.length??0,ye=P.body?.innerHTML.length??0,Me=P.head?.innerHTML.length??0;return`cd=same-origin readyState=${P.readyState} body[${F}children,${ye}ch] head[${Me}ch]`}catch(P){return`cd=cross-origin(${P.message.slice(0,30)})`}},He=[],Ht=A=>{if(Ee())return;let P=A.message??String(A.error??"(no message)");P&&(P.toLowerCase().includes("paypal")||P.toLowerCase().includes("zoid")||P.toLowerCase().includes("postrobot")||P.toLowerCase().includes("storage"))&&(m(`window:error ${P.slice(0,140)}`),He.push(P))},zt=A=>{if(Ee())return;let P=A.reason instanceof Error?A.reason.message:String(A.reason??"(no reason)");P&&(P.toLowerCase().includes("paypal")||P.toLowerCase().includes("zoid")||P.toLowerCase().includes("postrobot")||P.toLowerCase().includes("storage"))&&(m(`window:rejection ${P.slice(0,140)}`),He.push(P))};D&&typeof window<"u"&&(window.addEventListener("error",Ht),window.addEventListener("unhandledrejection",zt));let Ut={value:0};if(D&&typeof PerformanceObserver<"u")try{Ct=new PerformanceObserver(A=>{if(!Ee())for(let P of A.getEntries()){if(!P.name.toLowerCase().includes("paypal"))continue;Ut.value+=1;let F=Math.round(P.duration);m(`net ${F}ms ${P.name.slice(0,90)}`)}}),Ct.observe({type:"resource",buffered:!0})}catch{}let E=()=>{for(jt?.disconnect(),jt=null,Ct?.disconnect(),Ct=null;an.length;)clearTimeout(an.pop());D&&typeof window<"u"&&(window.removeEventListener("error",Ht),window.removeEventListener("unhandledrejection",zt))},L=A=>{if(!A)return!1;let P=A.toLowerCase();return P.includes("zoid destroyed")||P.includes("destroyed all components")||P.includes("window closed")||P.includes("detected container element removed")},O=A=>{if(Ee()||L(A))return;let P=Dn(A)??A;ft(()=>qe.current?.(P))},M=A=>{lt||(De(!0),A.includes("paypal_ineligible")||j.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal load/render failure:",A))},u=(A,P=!1)=>{if(lt)return;let F=ee.current||!w;if(Ot)return;Ot=!0,En=!0,E(),mt();let ye=P||$a(A);if(ye&&w&&!ee.current){ee.current=!0,X(!1),x(!1),he(!0),g.current?.("retrying"),fn=setTimeout(()=>{lt||Fe(Me=>Me+1)},ss);return}if(ye||F){if(X(!1),x(!1),he(!1),De(!0),g.current?.("exhausted"),!ie.current){ie.current=!0;let Me=$a(A)?"paypal_init_timeout":P?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",Me)}return}M(A)};De(!1);let U=async(A,P=et.current)=>{if(Ee())return;let F=P?.sessionId??e;if(Ue.current){await Ue.current(A,{sessionId:F,accountPatch:P?.accountPatch,nonce:P?.nonce});return}let ye=j.startTiming();j.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Me=()=>{j.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"processing",durationMs:j.elapsed(ye),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let ze=$e.current,sn=P?.accountPatch?.email??st.current,I=P?.accountPatch?.userId??ze?.customer?.id??ze?.accountData?.userId??"",ue=await new Fo(H,{telemetry:!1}).processPayment(I,{sessionId:F,nonce:P?.nonce??Qe.current,tokenizedData:A,accountData:{userId:I,email:sn??ze?.customer?.email??"",firstName:P?.accountPatch?.firstName??ze?.customer?.firstName??ze?.accountData?.firstName??"",lastName:P?.accountPatch?.lastName??ze?.customer?.lastName??ze?.accountData?.lastName??"",country:P?.accountPatch?.country??ze?.customer?.country??ze?.accountData?.country??void 0,zip:P?.accountPatch?.zip??ze?.customer?.zip??ze?.accountData?.zip??void 0}});if(ue.ok){if(En||lt&&It.current)return;Me(),j.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ft(()=>Oe.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ee())return;let Re=await ue.json().catch(()=>null),Gt=Re?.message??"PayPal payment failed.",Jt=Dn(Gt)??Gt;Me(),typeof Re?.declineCode=="string"?j.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):j.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ue.status>=500?"5xx":ue.status>=400?"4xx":ue.status>=300?"3xx":"unknown"}),O(Jt),ft(()=>je.current?.(Tt("paypal",Jt,{code:Re?.code,declineCode:Re?.declineCode})));return}catch(ze){if(Ee())return;Me(),j.error({errorCode:"NETWORK_REQUEST_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let sn=ze instanceof Error?ze.message:"PayPal payment failed.",I=Dn(sn)??sn;O(I),ft(()=>je.current?.(Tt("paypal",I)));return}},b=()=>new za("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Te=A=>Ee()?Promise.reject(b()):Promise.resolve(A),W=async A=>{if(Ee())throw b();yn||qn();let P=et.current,F=P?.sessionId??e,ye=P?.nonce??Qe.current;j.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Me=await new Fo(H,{telemetry:!1}).createSessionIntent(F,ye??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Fn});if(Ee())throw b();if(Me.provider!=="paypal")throw new Error(A);return j.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Me.providerObjectId},Ye=(A,P)=>{let F=P?.nonce??Qe.current;if(!F)return;let ye=P?.sessionId??e,Me=sr(A)??Mn(A)??"provider_declined";new Fo(H,{telemetry:!1}).reportSessionIntentDecline(ye,F,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Me}).catch(()=>{})},te=ae;m("loadScript:scheduled (deferred 1 tick)");let $t=null,rt=setTimeout(()=>{if(lt){m("loadScript:skipped (cancelled before defer ran)");return}m("loadScript:start");let A=Nt==="live"?"production":Nt;$t=rs({clientId:r,currency:c,intent:s?"subscription":"capture",vault:s?!0:void 0,...A?{environment:A}:{},...A==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),$t.then(P=>{if(m(`loadScript:resolved inactive=${Ee()} ns=${!!P} buttons=${!!P?.Buttons}`),Ee())return;if(!P?.Buttons){m("FAIL: namespace missing Buttons factory"),u("PayPal SDK did not expose the Buttons factory.");return}j.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let F=async I=>{if(Ee()||we.current!==te)return;let pe=I.subscriptionID??I.orderID??"",ue=pe?Ft.current.get(pe):Ve.current.get(te);if(!(!ue||!rn(ue.generation))&&Lt(ue.generation)){Ft.current.delete(pe),Ve.current.delete(ue.surfaceKey),on();try{if(x(!0),ft(()=>qe.current?.(null)),!pe)throw new za("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await U({id:pe,isPaypal:!0},ue)}catch(Re){O(Re instanceof Error?Re.message:"PayPal capture failed.")}finally{Ee()||x(!1)}}},ye=P.Buttons({style:{layout:"horizontal",height:to,tagline:!1},onClick:async(I,pe)=>{if(Ee()){await pe.reject();return}qn();let ue=Ce.current,Re={};if(ue)try{let ot=await ue("paypal");if(Ee()){await pe.reject();return}if(!ot.proceed){et.current=null,Ve.current.delete(te),await pe.reject();return}Re={sessionId:ot.sessionId,accountPatch:ot.accountPatch,nonce:ot.nonce}}catch(ot){m(`onClick:runBeforeButtonClick rejected msg=${(ot instanceof Error?ot.message:String(ot)).slice(0,120)}`),et.current=null,Ve.current.delete(te),await pe.reject();return}ft(()=>bt.current?.("paypal"));let Jt={generation:Dt(),surfaceKey:te,...Re};et.current=Jt,Ve.current.set(te,Jt),await pe.resolve(),j.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),nt=j.startTiming()},createOrder:s?void 0:Y?()=>Te(Y).then(mn):()=>W("Failed to create PayPal order.").then(mn),createSubscription:s?Y?()=>Te(Y).then(mn):()=>W("Failed to create PayPal subscription.").then(mn):void 0,onApprove:F,onCancel:()=>{if(Ee())return;let I=Ve.current.get(te)??et.current;I&&Ve.current.delete(I.surfaceKey),et.current=null,on(),j.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),fe.current=!0,Wt({generation:I?.generation,remount:!0,focus:!1})},onError:I=>{if(Ee()||we.current!==te)return;let pe=I instanceof Error?I.message:"PayPal failed to render.";if(m(`onError rendered=${Yt} msg=${pe.slice(0,120)}`),Yt){let ue=Ve.current.get(te)??et.current;if(ue&&!rn(ue.generation)||!ue&&vt.current===We.current)return;if(L(pe)){Lt(ue?.generation);return}on();let Re=pe.toLowerCase();j.error({errorCode:Re.includes("popup")&&Re.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),Br(I)&&Ye(I,ue),ue&&Ve.current.delete(ue.surfaceKey),et.current=null,Wt({generation:ue?.generation,remount:!0,showRetry:!0,focus:!0}),$n(I,{code:"paypal_runtime_failed"});return}u(pe)}}),Me=ye.isEligible();if(m(`isEligible=${Me}`),j.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Me){X(!1),u("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Bt=ye,D&&m(`container:dims ${gn(Pt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),D&&typeof MutationObserver<"u"&&(jt=new MutationObserver(I=>{if(!Ee()){for(let pe of I)if(pe.type==="childList")pe.addedNodes.forEach(ue=>{if(!(ue instanceof Element))return;let Re=ue.tagName.toLowerCase(),Gt=(ue.getAttribute("title")??"").slice(0,40),Jt=Re==="iframe"?` ${hn(ue)}`:"";m(`child+ ${Re}${Gt?` title="${Gt}"`:""}${Jt} dims=${gn(ue)}`)});else if(pe.type==="attributes"&&pe.target instanceof Element){let ue=pe.target;if(ue.tagName.toLowerCase()!=="iframe")continue;let Re=pe.attributeName;(Re==="src"||Re==="srcdoc")&&m(`attr~ iframe ${Re}=${Re==="srcdoc"?`[${(ue.getAttribute("srcdoc")??"").length}ch]`:_n(ue.getAttribute("src"))} dims=${gn(ue)}`)}}}),jt.observe(Pt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let sn=I=>{if(Ee()||Yt)return;let pe=Pt.querySelectorAll("iframe"),ue=typeof document<"u"&&"hasStorageAccess"in document;m(`watchdog:${I} container=${gn(Pt)} children=${Pt.childElementCount} iframes=${pe.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${ue} paypalNetRequests=${Ut.value}`),pe.forEach((Re,Gt)=>{let Jt=(Re.getAttribute("title")??"").slice(0,40);m(` iframe[${Gt}] ${gn(Re)}${Jt?` title="${Jt}"`:""} ${hn(Re)}`);let ot=Vt(Re);ot&&m(` ${ot}`)}),He.length===0&&m(" (no PayPal/zoid window errors captured)")};D&&(an.push(setTimeout(()=>sn("3s"),3e3)),an.push(setTimeout(()=>sn("8s"),8e3)),an.push(setTimeout(()=>sn("15s"),15e3))),m("render:start"),an.push(setTimeout(()=>{Ee()||Yt||(m("watchdog:11s retryable render timeout"),u("PayPal Buttons render did not settle within 11000ms.",!0))},ls)),ye.render(Pt).then(()=>{if(m(`render:resolved inactive=${Ee()}`),E(),Ee()){mt();return}Yt=!0,X(!0),he(!1),g.current?.("ready"),j.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"provider_ready",durationMs:j.elapsed(oe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(I=>{let pe=I instanceof Error?I.message:"PayPal failed to render.";m(`render:rejected msg=${pe.slice(0,120)}`),E(),u(pe)})}).catch(P=>{let F=P instanceof Error?P.message:"PayPal SDK failed to load.";m(`loadScript:rejected msg=${F.slice(0,120)}`),u(F)})},0);return()=>{lt=!0,clearTimeout(rt),fn&&clearTimeout(fn),E(),mt()}},[w,H,r,c,a,s,e,Y,ae,j]);let tt=D?Do("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ne?"#fef2f2":"#f3f4f6",border:`1px solid ${Ne?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${me} failed=${Ne})`,Xe.length===0?`
|
|
7
7
|
(waiting for first lifecycle event\u2026)`:`
|
|
8
|
-
${
|
|
9
|
-
`)}`]}):null;return
|
|
8
|
+
${Xe.join(`
|
|
9
|
+
`)}`]}):null;return Ne&&!gt?D?lr("div",{children:tt}):null:Do("div",{children:[tt,Do("div",{"aria-hidden":de?!0:void 0,style:de?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:to},children:[!me&&!de&&lr("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"}}),lr("div",{ref:V,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:to,display:"flex",opacity:me?1:0},"aria-busy":G||_},ae)]},ae),ve&&lr("button",{ref:Be,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:In,style:ds,children:"Try PayPal again"})]})}function no(e){return lr(qa,{...e})}function ja(e){return lr(qa,{...e})}import{FloPayError as Cn,isSetupIntentClientSecret as Es,resolveTheme as _s}from"@flopay/shared";import{Fragment as cr,jsx as d,jsxs as xe}from"react/jsx-runtime";var Sn="flopay_stripe_resume",Ya="flopay_wallet_resume",Fr="flopay_paypal_resume";async function ao({billingApiUrl:e,sessionId:t,nonce:n,request:i}){if(!(!t||!n))try{await new Nn(e,{telemetry:!1}).reportSessionIntentDecline(t,n,i)}catch{}}function xs(e){return e instanceof Cn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function No(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function ro(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 Ts=`
|
|
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 @@ ${Ze.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
|
-
`,ro=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 xs={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ni={width:"100%",minHeight:ro,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 Ts(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ya(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ri(e){return e==="paypal"?"PayPal":dr(e)}function Ms(e,t){let n=`We couldn't open ${ri(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function oi(e){let t=Ne(0),n=Ne(null),i=Ne(null),r=ge((l=i.current)=>{let f=l;f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),a=ge((l,f)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(l),l.timer=setTimeout(()=>{l.timer=null,i.current?.generation===l.generation&&(i.current=null,n.current=l.generation,e(l.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},f))},[r,e]),c=ge(l=>{l.yieldedControl&&a(l,600)},[a]),s=ge(l=>{r();let f=t.current+1;t.current=f,n.current=null;let S={generation:f,method:l,timer:null,yieldedControl:!1};return i.current=S,f},[r]),w=ge(l=>{let f=i.current;return typeof l=="number"&&f?.generation!==l?!1:(r(f),i.current=null,(typeof l!="number"||n.current===l)&&(n.current=null),!0)},[r]),M=ge(l=>{let f=i.current,S=l??f?.generation??t.current;(!l||f?.generation===l)&&(r(f),i.current=null),n.current=S},[r]),p=ge(l=>n.current===(l??t.current),[]),R=ge(l=>i.current?.generation===l&&n.current!==l,[]),C=ge(()=>{let l=i.current;l&&c(l)},[c]),E=ge(()=>{let l=i.current;l&&(l.yieldedControl=!0,r(l))},[r]);return mt(()=>{let l=()=>{document.visibilityState==="visible"?C():E()},f=()=>{E()};return document.addEventListener("visibilitychange",l),window.addEventListener("blur",f),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",l),window.removeEventListener("blur",f),window.removeEventListener("focus",C),r()}},[r,E,C]),{startAttempt:s,finishAttempt:w,invalidateAttempt:M,isAttemptInvalidated:p,isAttemptCurrent:R}}function Bs(e){let t=Ps(e);return`Enter a valid ${Oo(e)}${t?` (e.g. ${t})`:""}`}function As(e,t,n){let i=gs(e),r=t.trim(),a=n&&i,c=a&&!r,s=a&&!!r&&!hs(e,r);return{visible:n,supported:i,required:a,empty:c,malformed:s}}function Ga(e,t){return t instanceof Cn?t:new Cn(t instanceof Error?t.message:`${Ts(e)} before-click hook failed.`,"validation_error")}function No(){return d("style",{children:_s})}function Fs(e){return typeof e=="number"?`${e}px`:e}function Ja(e){if(typeof e=="number"||typeof e=="string")return e}function ai(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function ii({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 Xa(e){return e!=="unavailable"&&e!=="load_error"}function jo(e){return d(Ls,{...e})}function Za({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:r,onErrorChange:a,isProcessing:c=!1,onButtonClick:s,onDecline:w,onTechnicalFailure:M,runBeforeButtonClick:p,onLoadStateChange:R,placeholderBorderRadius:C}){let E=Pn(),l=$o(),f=Uo(),[S,x]=ve("loading");mt(()=>{R?.(S)},[S,R]);let[h,U]=ve(!1),Y=Ne(!1),ce=Ne(null),re=Ne(null),[F,J]=ve(0),[$,de]=ve(!1),q=Ne(!1),j=Ne(new Map),{startAttempt:oe,finishAttempt:Be,invalidateAttempt:me,isAttemptInvalidated:pe,isAttemptCurrent:X}=oi((k,ee,ie)=>{M?.(k,ee,{...ie,popupBlocked:ie?.popupBlocked??Ln(ee)}),de(!0),J(Oe=>Oe+1)});mt(()=>{$&&re.current?.focus()},[$,F]);let ue=ge(()=>{J(k=>k+1)},[]),he=ge((k,ee,ie)=>{me(ie),M?.("paypal",k,{code:ee,popupBlocked:Ln(k)}),de(!0),ue()},[me,M,ue]),ae=ge(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);mt(()=>{q.current&&(q.current=!1,ae())},[ae,F]);let Fe=ge(()=>{de(!1),a?.(null),ae()},[ae,a]);mt(()=>{if(!l||Y.current)return;let k=new URLSearchParams(window.location.search),ee=k.get("payment_intent"),ie=k.get("payment_intent_client_secret"),Oe=k.get("redirect_status");if(!ee||!ie)return;Y.current=!0;let De;try{let _=localStorage.getItem(Ar);if(_){let V=JSON.parse(_);V.clientSecret===ie&&(De={...V.accountPatch?{accountPatch:V.accountPatch}:{},...V.sessionId?{sessionId:V.sessionId}:{},...V.nonce?{nonce:V.nonce}:{}})}}catch{}try{localStorage.removeItem(Ar)}catch{}let G=new URL(window.location.href);G.searchParams.delete("payment_intent"),G.searchParams.delete("payment_intent_client_secret"),G.searchParams.delete("redirect_status"),window.history.replaceState({},"",G.toString()),(async()=>{try{if(U(!0),Oe==="failed"){let se="PayPal payment was declined. Please try again.";a?.(se),w?.(Bt("paypal",se));return}let{paymentIntent:_,error:V}=await l.retrievePaymentIntent(ie);if(V){a?.(V.message??"Failed to retrieve PayPal payment status.");return}if(_&&(_.status==="requires_capture"||_.status==="succeeded")){let se=typeof _.payment_method=="string"?_.payment_method:_.payment_method?.id;r({id:se??_.id,type:"card",threeDSecureActionResultTokenId:_.id,isPaypal:!0},De)}else{let se="PayPal payment was not completed. Please try again.";a?.(se),w?.(Bt("paypal",se))}}catch(_){a?.(_ instanceof Error?_.message:"Failed to complete PayPal payment.")}finally{U(!1)}})()},[l,r,a,w]);let ke=ge(async k=>{if(c||h){k.reject();return}let ee=p?await p("paypal"):{proceed:!0};if(!ee.proceed){j.current.delete(F),k.reject();return}let ie=oe("paypal");j.current.set(F,{generation:ie,accountPatch:ee.accountPatch,sessionId:ee.sessionId,nonce:ee.nonce}),de(!1),s?.("paypal"),k.resolve()},[j,c,s,p,oe,h,F]),Ce=ge(async k=>{if(!l||!f)return;let ee=j.current.get(F);if(ee&&!X(ee.generation)){j.current.delete(F);return}if(!ee&&pe()||ee&&!Be(ee.generation))return;ee||Be();let ie=ee??null;if(j.current.delete(F),!ie&&p){let _=await p("paypal");if(!_.proceed){k.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ie={accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}}let Oe=ie?.sessionId??e,De=ie?.nonce??t,G=ie?.accountPatch?.email??n;try{if(U(!0),a?.(null),!Oe||!G)throw new Error("Missing sessionId or email for PayPal payment");let _=l.createPaymentMethod,{error:V,paymentMethod:se}=await _({type:"paypal"});if(V){he(V,"stripe_paypal_create_payment_method_failed",ee?.generation),k.paymentFailed({reason:"fail"});return}let Re=await new Nn(i).createSessionIntent(Oe,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 ht=Re.clientSecret,Ze={return_url:window.location.href};if(se?.id&&(Ze.payment_method=se.id),typeof window<"u")try{localStorage.setItem(Ar,JSON.stringify({clientSecret:ht,sessionId:Oe,nonce:De,accountPatch:ie?.accountPatch}))}catch{}let{error:Xe,paymentIntent:m}=await l.confirmPayment({clientSecret:ht,confirmParams:Ze,redirect:"if_required"});if(Xe){if(typeof window<"u")try{localStorage.removeItem(Ar)}catch{}if(Mr(Xe)){let ze=Xe.message??"Your payment was declined.";a?.(ze),w?.(Bt("paypal",ze,{code:Mn(Xe),declineCode:sr(Xe)})),await oo({billingApiUrl:i,sessionId:Oe,nonce:De,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(Xe)??"provider_declined"}})}else he(Xe,"stripe_paypal_confirm_failed",ee?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Ar)}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:Oe,nonce:De});return}catch(_){he(_,"stripe_paypal_failed",ee?.generation)}finally{U(!1)}},[l,f,e,t,n,i,r,a,w,p,he,Be,X,pe,F]);return xe(cr,{children:[d(ii,{state:S,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[$&&d("button",{ref:re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Fe,style:ni,children:"Try PayPal again"}),d(ti,{onReady:k=>x(ai(k,["paypal"])),onLoadError:()=>x("load_error"),onClick:ke,onConfirm:Ce,onCancel:()=>{let k=j.current.get(F);j.current.delete(F),Dt(E)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),me(k?.generation),de(!1),q.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 Qa({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:r,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:w,onDecline:M,onTechnicalFailure:p,runBeforeButtonClick:R,onLoadStateChange:C,placeholderBorderRadius:E}){let l=Pn(),f=$o(),S=Uo(),[x,h]=ve("loading");mt(()=>{C?.(x)},[x,C]);let[U,Y]=ve(!1),ce=Ne(null),re=Ne(null),[F,J]=ve(0),[$,de]=ve(!1),[q,j]=ve("google_pay"),oe=Ne(!1),Be=Ne("google_pay"),me=Ne("google_pay"),pe=Ne(new Map),{startAttempt:X,finishAttempt:ue,invalidateAttempt:he,isAttemptInvalidated:ae,isAttemptCurrent:Fe}=oi((G,_,V)=>{p?.(G,_,{...V,popupBlocked:V?.popupBlocked??Ln(_)}),j(G),de(!0),J(se=>se+1)});mt(()=>{$&&re.current?.focus()},[$,F]);let ke=ge(()=>{J(G=>G+1)},[]),Ce=ge((G,_,V,se)=>{he(se),p?.(G,_,{code:V,popupBlocked:Ln(_)}),j(G),de(!0),ke()},[he,p,ke]),k=ge(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);mt(()=>{oe.current&&(oe.current=!1,k())},[k,F]);let ee=ge(()=>{de(!1),s?.(null),k()},[k,s]),ie=ge(async G=>{if(!f||!S)return;let _=pe.current.get(F);if(_&&!Fe(_.generation)){pe.current.delete(F);return}if(!_&&ae()||_&&!ue(_.generation))return;_||ue();let V=G.expressPaymentType??_?.method??Be.current,se=_??null;pe.current.delete(F);let Re=Ya(V);if(!se&&R){let $e=await R(Re);if(!$e.proceed){G.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}se={accountPatch:$e.accountPatch,sessionId:$e.sessionId,nonce:$e.nonce}}let ht=Re,Ze=se?.sessionId??e,Xe=se?.nonce??t,m=se?.accountPatch?.email??n;try{Y(!0),s?.(null);let{error:$e}=await S.submit();if($e){Ce(V,$e,"stripe_wallet_submit_failed",_?.generation);return}let{error:ze,paymentMethod:je}=await f.createPaymentMethod({elements:S});if(ze||!je){Ce(V,ze??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",_?.generation);return}if(!Ze||!m)throw new Error("Missing sessionId or email for wallet payment");let Ve=await new Nn(i).createSessionIntent(Ze,Xe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:V??Re,paymentMethodId:je.id,intentKind:r});if(Ve.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Yt=Ve.clientSecret,{error:vt,intentId:It}=Rs(Yt)?await f.confirmCardSetup(Yt,{payment_method:je.id}).then(g=>({error:g.error,intentId:g.setupIntent?.id})):await f.confirmCardPayment(Yt,{payment_method:je.id}).then(g=>({error:g.error,intentId:g.paymentIntent?.id}));if(vt){if(Mr(vt)){let g=vt.message??"Your payment was declined.";s?.(g),M?.(Bt(ht,g,{code:Mn(vt),declineCode:sr(vt)})),await oo({billingApiUrl:i,sessionId:Ze,nonce:Xe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:V??Re,providerDeclineReason:Mn(vt)??"provider_declined"}})}else Ce(V,vt,"stripe_wallet_confirm_failed",_?.generation);return}c({id:je.id,type:"card",threeDSecureActionResultTokenId:It},{accountPatch:se?.accountPatch,sessionId:Ze,nonce:Xe})}catch($e){Ce(V,$e,"stripe_wallet_failed",_?.generation)}finally{Y(!1)}},[f,S,e,t,n,i,r,c,s,M,R,Ce,ue,Fe,ae,F]),Oe=pt(()=>{let G=["applePay","googlePay","paypal","link","amazonPay","klarna"],_=new Set(["applePay","googlePay"]),V=new Set(a.map(Ka)),se={};for(let Re of G)V.has(Re)?se[Re]=_.has(Re)?"always":"auto":se[Re]="never";return se},[a]),De=pt(()=>a.map(Ka),[a]);return xe(cr,{children:[d(ii,{state:x,placeholderTestId:"flopay-wallet-placeholder",borderRadius:E,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[$&&xe("button",{ref:re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ee,style:ni,children:["Try ",ri(q)," again"]}),d(ti,{onReady:G=>{h(ai(G,De))},onLoadError:G=>{h("load_error"),Dt(l)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk"})},onClick:async G=>{Be.current=G.expressPaymentType,me.current=Ya(G.expressPaymentType);let _=R?await R(me.current):{proceed:!0};if(!_.proceed){pe.current.delete(F),G.reject();return}let V=X(G.expressPaymentType);pe.current.set(F,{generation:V,method:G.expressPaymentType,accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}),de(!1),w?.(me.current),G.resolve()},onConfirm:ie,onCancel:()=>{let G=pe.current.get(F);pe.current.delete(F),Dt(l)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),he(G?.generation),de(!1),oe.current=!0,ke()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Oe,layout:{maxColumns:1,overflow:"never"}}},F)]})}),U&&d(vn,{status:"processing"})]})}function Ds({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:r=!1,hasNextStep:a=!1,onClick:c,backgroundColor:s,borderColor:w,textColor:M,borderRadius:p,fontFamily:R}){let C=Cs(e,t),E=Ma[e],l=C?.backgroundColor??s??"#ffffff",f=C?.borderColor??w??"#d1d5db",S=C?.textColor??M??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!i&&c()},disabled:n||i,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ro,padding:"0 1rem",backgroundColor:l,color:S,border:`1px solid ${f}`,borderRadius:p??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,cursor:n||i?"not-allowed":"pointer",opacity:i&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:r?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?d("span",{style:{margin:"0 auto"},children:`Connecting to ${dr(e)}\u2026`}):xe(cr,{children:[xe("span",{style:{display:"inline-flex",alignItems:"center",gap:vs(e)?8:0},children:[E?d("img",{src:E,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):C?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:C.logoSvg}}):null,d("span",{children:dr(e)})]}),a&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:S,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:d("path",{d:"M9 18l6-6-6-6"})})]})})}function zo({method:e,sessionId:t,nonce:n,email:i,billingName:r,billingApiUrl:a,onTokenizedBody:c,onErrorChange:s,onDecline:w,onCancel:M,runBeforeButtonClick:p,onButtonClick:R,isProcessing:C,submitButtonColor:E,submitButtonBorderRadius:l,submitButtonStyle:f,errorText:S}){let x=Pn(),h=$o(),U=Uo(),[Y,ce]=ve(!1),re=Ne(!1),[F,J]=ve(!1),[$,de]=ve("loading"),q=ge(async()=>{if(!h||!U||C||re.current||!F)return;re.current=!0,ce(!0);let j=p?await p("card"):{proceed:!0};if(!j.proceed){re.current=!1,ce(!1);return}R?.("card");let oe=j.sessionId??t,Be=j.nonce??n,me=j.accountPatch?.email??i;try{s?.(null);let pe=await U.submit();if(pe.error){s?.(pe.error.message??"Payment failed.");return}let X=await h.createPaymentMethod({elements:U});if(X.error||!X.paymentMethod){s?.(X.error?.message??"Failed to create payment method.");return}let ue=X.paymentMethod;if(!oe||!me)throw new Error("Missing sessionId or email for payment.");let he=ue.type||e,ae=await new Nn(a).createSessionIntent(oe,Be??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:he,paymentMethodId:null,intentKind:"payment"});if(ae.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Fe=ae.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Fe,sessionId:oe,nonce:Be,accountPatch:j.accountPatch,paymentMethodId:ue.id,paymentMethodType:ue.type??e,gateway:"stripe"}))}catch{}let{error:ke,paymentIntent:Ce}=await h.confirmPayment({clientSecret:Fe,confirmParams:{return_url:window.location.href,payment_method:ue.id},redirect:"if_required"});if(ke){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ie=ke.message??"Payment failed.";s?.(ie),w?.(Bt("card",ie,{code:ke.code})),await oo({billingApiUrl:a,sessionId:oe,nonce:Be,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ke.code??"provider_declined"}});return}let k=Ce?.status;if(!Jr(k)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ie=k==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";s?.(ie),w?.(Bt("card",ie,{code:k??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ee=typeof Ce?.payment_method=="string"?Ce.payment_method:Ce?.payment_method?.id;c({id:ee??ue.id,type:"card",threeDSecureActionResultTokenId:Ce?.id,gateway:"stripe",paymentMethodType:ue.type??e},{accountPatch:j.accountPatch,sessionId:oe,nonce:Be})}catch(pe){s?.(pe instanceof Error?pe.message:"Payment failed. Please try again.")}finally{re.current=!1,ce(!1)}},[h,U,C,F,p,R,t,n,i,a,e,c,s,w]);return xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(us,{onReady:()=>de("ready"),onLoadError:()=>{de("load_error"),Dt(x)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"apm",requestCategory:"provider_sdk"})},onChange:j=>{J(!!j.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...i?{email:i}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{q()},disabled:!F||Y||C||$!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:E,color:"white",border:"none",borderRadius:l,fontSize:"1rem",fontWeight:600,cursor:!F||Y||C||$!=="ready"?"not-allowed":"pointer",opacity:!F||Y||C||$!=="ready"?.5:1,transition:"opacity 120ms ease-out",...f??{}},children:Y?"Processing\u2026":`Pay with ${dr(e)}`}),S&&d(or,{margin:"0.75rem 0 0",children:S})]})}function ei({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:r,paymentElementMethods:a,stripeInstance:c,paymentElementBaseOptions:s,onTokenizedBody:w,onErrorChange:M,onButtonClick:p,onDecline:R,runBeforeButtonClick:C,onLoadStateChange:E,isProcessing:l=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:S=8,submitButtonStyle:x,buttonAppearance:h,themeId:U,onExpandApm:Y,expandedApmMethod:ce}){let[re,F]=ve(null),[J,$]=ve(null),de=Ne(!1);mt(()=>{a.length>0&&c?E?.("ready"):c||E?.("loading")},[a.length,c,E]);let q=ge(async X=>{if(!c||de.current||l)return;de.current=!0,$(X);let ue=C?await C("card"):{proceed:!0};if(!ue.proceed){de.current=!1,$(null);return}p?.("card");let he=ue.sessionId??e,ae=ue.nonce??t,Fe=ue.accountPatch?.email??n;try{if(M?.(null),!he||!Fe)throw new Error("Missing sessionId or email for payment.");let ke=await new Nn(r).createSessionIntent(he,ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,paymentMethodId:null,intentKind:"payment"});if(ke.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ce=ke.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Ce,sessionId:he,nonce:ae,accountPatch:ue.accountPatch,paymentMethodType:X,gateway:"stripe"}))}catch{}let{error:k,paymentIntent:ee}=await c.confirmPayment({clientSecret:Ce,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(k){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let De=k.message??"Payment failed.";M?.(De),R?.(Bt("card",De,{code:k.code})),await oo({billingApiUrl:r,sessionId:he,nonce:ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,providerDeclineReason:k.code??"provider_declined"}});return}let ie=ee?.status;if(!Jr(ie)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let De=ie==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";M?.(De),R?.(Bt("card",De,{code:ie??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let Oe=typeof ee?.payment_method=="string"?ee.payment_method:ee?.payment_method?.id;w({id:Oe??ee?.id,type:"card",threeDSecureActionResultTokenId:ee?.id,gateway:"stripe",paymentMethodType:X},{accountPatch:ue.accountPatch,sessionId:he,nonce:ae})}catch(ke){M?.(ke instanceof Error?ke.message:"Payment failed. Please try again.")}finally{de.current=!1,$(null)}},[c,l,C,p,e,t,n,r,i,w,M,R]),[j,oe]=ve(null),Be=Y?ce??null:j,me=ge(X=>{de.current||l||Be&&Be!==X||(Ha(X)?Y?Y(X):oe(X):q(X))},[Be,l,q,Y]),pe=pt(()=>j?{...s,paymentMethodTypes:[j]}:null,[j,s]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(X=>{let ue=ce===X,he=J===X,ae=J!==null&&J!==X||ce!=null&&ce!==X;return xe(Ss.Fragment,{children:[d(Ds,{method:X,themeId:U,submitting:he,disabled:ae,highlighted:ue,hasNextStep:Ha(X),onClick:()=>me(X),backgroundColor:h?.backgroundColor,borderColor:h?.borderColor,textColor:h?.textColor,borderRadius:h?.borderRadius,fontFamily:h?.fontFamily}),!Y&&j===X&&pe&&c&&d(Jn,{stripe:c,options:pe,children:d(zo,{method:X,sessionId:e,email:n,billingName:i,billingApiUrl:r,onTokenizedBody:w,onErrorChange:M,onDecline:R,onCancel:()=>oe(null),runBeforeButtonClick:C,onButtonClick:p,isProcessing:l,submitButtonColor:f,submitButtonBorderRadius:S,submitButtonStyle:x})},X)]},X)})})}function Ls({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,onComplete:a,onError:c,onDecline:s,onTokenizedBody:w,firstName:M,lastName:p,chv:R,className:C,isProcessing:E,error:l,onErrorChange:f,showPayPal:S=!0,showStripe:x=!0,enabledPaymentMethods:h,enabledPaymentMethodCountries:U,showApplePay:Y=!0,showGooglePay:ce=!0,layout:re="default",theme:F,buttonsTheme:J,buttonsStyles:$,appearance:de,cardButtonContent:q,cardBackButtonContent:j,cardTitleContent:oe,showSecurityFooter:Be,onButtonClick:me,onBeforeButtonClick:pe,enableAVS:X,cardFieldOrder:ue,cardPreFormSlot:he,avsLayout:ae="row",country:Fe,zip:ke,addressLine1:Ce,addressLine2:k,city:ee,state:ie,onCountryChange:Oe,onZipChange:De,avsCheck:G,checkoutType:_,checkoutLayout:V,totalAmount:se=0,currency:Re="usd",initialCardOpen:ht=!1,directPaypal:Ze,isSubscription:Xe=!1,session:m,debug:$e=!1}){let ze=Pn(),je=xo(),Ve=ks(ln),Yt=Gr(),[vt,It]=ve(!1),[g,we]=ve(null),[qe,it]=ve(Fe??"US"),[et,tt]=ve(ke??""),[Ye,Pe]=ve(Ce??""),[Ct,He]=ve(k??""),[Lt,Et]=ve(ee??""),[dn,Rn]=ve(ie??""),[In,$n]=ve({}),Pt=Ne(ke??""),Nt=Ne(Fe??"US"),Ot=Ne(Ce??""),Gt=Ne(k??""),rn=Ne(ee??""),un=Ne(ie??""),H=pt(()=>fs(X),[X]),An=H!==null,pn=!!m?.vault?.html,zt=!!m?.gateways?.pcivault,nt=pn||zt,y=!!(x&&nt&&ze&&e),Ie=pt(()=>!ze||!y||!e?null:ze.cardCapture({sessionId:e}),[ze,y,e]),st=pt(()=>{let o=qe,v=H?_e(H.postal_code,o):!1;return As(o,et,v)},[H,qe,et]),{avsInvalid:En,invalidAvsFields:Ee}=pt(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!y||!H)return{avsInvalid:!1,invalidAvsFields:o};let v=qe,z=(Z,Je)=>_e(Z,v)&&!Je.trim(),ne={line1:z(H.address_line_1,Ye),city:z(H.city,Lt),state:z(H.state,dn),zip:st.empty||st.malformed};return{avsInvalid:ne.line1||ne.city||ne.state||ne.zip,invalidAvsFields:ne}},[y,H,qe,Ye,Lt,dn,st]),[Fn,mn]=ve(!1),[qn,yn]=ve(!1),[Ut,Ft]=ve(()=>Lo(m?.vault)),[Se,yt]=ve(ht&&nt?"card":"buttons"),[rt,on]=ve(null),Jt=Se==="expanding"||Se==="card",bt=280,Ht=Ne(null),wt=ge(o=>{Ht.current&&clearTimeout(Ht.current),Ht.current=setTimeout(()=>{Ht.current=null,o()},bt)},[bt]);mt(()=>()=>{Ht.current&&clearTimeout(Ht.current)},[]);let an=ge(()=>{yt("expanding"),wt(()=>yt("card"))},[wt]),fn=ge(()=>{yt("collapsing"),wt(()=>yt("buttons"))},[wt]),_n=ge(o=>{on(o),yt("apm-expanding"),wt(()=>yt("apm-form"))},[wt]),gn=ge(()=>{yt("apm-collapsing"),wt(()=>{yt("buttons"),on(null)})},[wt]);mt(()=>{re==="buttons"&&ht&&nt&&yt("card")},[re,ht,nt]);let[Kt,Ke]=ve(null),Wt=Ne(!1),[$t,qt]=ve(null),I=Ne($t);mt(()=>{I.current=$t},[$t]);let D=n||Yt,N=l??g,T=pt(()=>Is(F),[F]),u=pt(()=>{let o=T?.buttonsLayout??ps(J);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},[T,J,$]),O=de??T?.appearance,b=pt(()=>{let o=O?.variables,v=Je=>typeof Je=="string"&&Je?Je:void 0,z=u.submitButton,ne=v(o?.colorPrimary)??v(z?.backgroundColor)??"#4A49FF",L=re==="buttons",Z=u.nameInput;return{primaryColor:ne,primaryHoverColor:v(o?.colorPrimaryHover)??no(ne,.12),inputBackgroundColor:v(u.cardInputBackground)??v(o?.colorBackground)??"#ffffff",textColor:v(u.cardInputColor)??v(Z?.color)??v(o?.colorText)??"#262833",borderColor:v(u.cardInputBorder)??(L?"#e5e7eb":"#A4A4FF"),placeholderColor:v(u.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(o?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(Z?.fontFamily)??v(o?.fontFamily)??"Poppins, sans-serif",fontSize:v(u.cardInputFontSize)??v(o?.fontSizeBase)??"16px",fontWeight:String(Ja(Z?.fontWeight)??400),borderRadius:v(o?.borderRadius)??"8px"}},[O,u,re]),Te=Ve.inlineSessionPatchProcessing??!1,K=(E??vt)||Te,Ge=D.replace(/\/+$/,""),te=pt(()=>Bo({userId:r,email:i,firstName:M,lastName:p,country:Fe,zip:ke},In),[r,i,M,p,Fe,ke,In]),jt=[te.firstName,te.lastName].filter(o=>!!o?.trim()).join(" "),ot=pt(()=>ze?ze.getRawProvider():null,[ze]),B=pt(()=>je?je.getRawProvider():null,[je]),P=se||100,A=O?{appearance:O}:null,ye=pt(()=>{let o=O??{},v=o.rules??{};return{...o,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[O]),Me=pt(()=>{let o=Da(se);return{...o,currency:Re.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...A}},[se,Re,A]),Ue=pt(()=>({mode:"payment",amount:P,currency:Re.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...A}),[P,Re,A]),W=ge(o=>{we(o),f?.(o)},[f]);mt(()=>{!y||!Ie||Ie.setCardFieldOrder?.(ue??null,H==null)},[y,Ie,ue,H]),mt(()=>{(Se==="expanding"||Se==="collapsing"||Se==="apm-expanding"||Se==="apm-collapsing")&&W(null)},[Se,W]);let fe=ge((o,v,z)=>{s?.(Bt(o,v,z))},[s]),be=ge((o,v,z)=>{let ne=z?.popupBlocked??Ln(v),L=Ms(o,ne),Z=Yn(z?.code)??Mn(v)??"external_payment_method_failed",Je=new Cn(L,"api_error",{code:"external_payment_method_failed",param:o});Ke(null),re==="buttons"&&(yt("buttons"),on(null)),W(L),c?.(Je),console.error("[FloPay] External payment method failed:",{method:o,code:Z,popupBlocked:ne})},[re,c,W]);mt(()=>{if(!y||!e){Ft(null);return}let o=Lo(m?.vault);if(o){Ft(o);return}Ft(null);let v=!0;return new Nn(Ge).getVaultCapture(e,t).then(z=>{if(!v)return;let ne=Lo(z);ne?Ft(ne):W("Failed to load the secure card form.")}).catch(z=>{v&&W(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{v=!1}},[y,e,m?.vault?.html,m?.vault?.messageToken,m?.vault?.expectedOrigin,Ge,t,W]);let le=Ne({onComplete:a,onError:c,updateError:W,emitDecline:fe,resolvedAccount:te,avsConfig:H,avsCheckProp:G,sessionId:e,nonce:t,baseUrl:Ge});le.current={onComplete:a,onError:c,updateError:W,emitDecline:fe,resolvedAccount:te,avsConfig:H,avsCheckProp:G,sessionId:e,nonce:t,baseUrl:Ge};let Le=Ne(!1),hn=ge(()=>{let{resolvedAccount:o,avsConfig:v,avsCheckProp:z}=le.current,ne=Nt.current||o.country||"US",L=v?_e(v.state,ne):!1,Z=v?_e(v.address_line_1,ne):!1,Je=v?_e(v.postal_code,ne):!1,St=v?_e(v.city,ne):!1,xt=v?_e(v.address_line_2,ne):!1,Qe=Z&&!L&&Je?Va(ne,(Pt.current??"").trim()):null,Tt=L?un.current:Qe;return{accountData:{userId:o.userId??"",email:o.email??"",firstName:o.firstName??"",lastName:o.lastName??"",...Je&&Pt.current?{zip:Pt.current}:{},...St&&rn.current?{city:rn.current}:{},...Tt?{state:Tt}:{},...Z&&Ot.current?{addressLine1:Ot.current}:{},...xt&&Gt.current?{addressLine2:Gt.current}:{},country:ne},...z!==void 0?{avsCheck:z}:{},...v?{avsConfig:{country:_e(v.country,ne),postal_code:Je,address_line_1:Z,address_line_2:xt,city:St,state:L}}:{}}},[]);mt(()=>{!y||!Ie||Ie.setSubmitGate?.(En)},[y,Ie,En]),mt(()=>{if(!y||!Ie)return;Le.current=!1;let o=!1,v=Ie.on("submitting",()=>{mn(!0),Ke("processing");let{baseUrl:Z,sessionId:Je,nonce:St,updateError:xt,onError:Qe}=le.current;!Je||!St||new Nn(Z).patchAccountSnapshot(Je,St,hn(),{telemetryMode:"best_effort"}).catch(Tt=>{if(!Es(Tt))return;let Ae=Tt instanceof Error?Tt.message:"Please check your billing address and try again.";xt(Ae),Ke(null),Qe?.(Tt instanceof Cn?Tt:new Cn(Ae,"api_error"))})}),z=Ie.on("complete",async Z=>{ir(Z.sessionId??le.current.sessionId),Ke("success"),await new Promise(Je=>setTimeout(Je,Tn)),!Le.current&&(Le.current=!0,le.current.onComplete?.({status:"succeeded",paymentIntentId:Z.intentId,checkoutMethod:"card"}))}),ne=Ie.on("decline",async Z=>{let{updateError:Je,emitDecline:St}=le.current,xt=Z.message??"Your payment was declined. Please try another card or contact your bank.";Je(xt),Ke("error"),St("card",xt,Z.declineReason?{declineCode:Z.declineReason}:void 0),await new Promise(Qe=>setTimeout(Qe,bn)),!o&&Ke(null)}),L=Ie.on("error",async Z=>{let{updateError:Je,onError:St}=le.current,xt=Z.message??"There was a problem processing your payment. Please try again.";Je(xt),Ke("error"),St?.(new Cn(xt,"api_error")),await new Promise(Qe=>setTimeout(Qe,bn)),!o&&Ke(null)});return()=>{o=!0,v(),z(),ne(),L()}},[y,Ie]);let lt=!!Ze?.clientId,_t=Array.isArray(h),Nr=_t&&h.length>0,wi=_t&&h.includes("paypal"),{expressMethods:Or,paymentElementMethods:Pr}=pt(()=>ws(h,{excludePaypal:lt}),[h,lt]),ta=lt||!!je,Si=pt(()=>ta?Or.filter(o=>o!=="paypal"):Or,[Or,ta]),ki=pt(()=>{let o=[];return Y&&o.push("apple_pay"),ce&&o.push("google_pay"),o},[Y,ce]),zr=_t?Si:ki,Ri=x&&zr.length>0,yo=An?qe:Fe,Ur=pt(()=>{let o=yo?.trim().toUpperCase();return o?U?Pr.filter(v=>{let z=U[v];return!z||z.length===0||z.includes(o)}):bs(Pr,yo):Pr},[Pr,yo,U]),fo=pt(()=>({mode:"payment",amount:P,currency:Re.toLowerCase(),paymentMethodCreation:"manual",appearance:ye}),[P,Re,ye]),[na,ra]=ve("loading"),[oa,aa]=ve("loading"),[ia,sa]=ve("loading"),[Ii,go]=ve(!1),[la,ho]=ve("loading"),[$r,Ei]=ve();mt(()=>{Ei(Na())},[]);let ca=S&&(lt||(_t?wi:$r===!1)),da=x&&Ri,br=ca&<,ua=la==="retrying"||la==="exhausted",vr=ca&&!!B&&(!lt||ua),Cr=da&&!!ot,wr=x&&Nr&&Ur.length>0&&!!ot,_i=br&&!ua?Ii:vr&&Xa(na),xi=Cr&&Xa(oa),Ti=wr&&ia!=="load_error",pa=o=>o==="loading"||o==="ready",ma=br||vr&&pa(na)||Cr&&pa(oa)||wr&&ia!=="load_error",qr=Ne(!1);mt(()=>{if(!qr.current){if(!x&&!S){qr.current=!0;let o=new Cn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(o),W(o.message)}else if(!x&&S&&!lt&&!B){qr.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),W(o.message)}else if($r!==void 0&&!nt&&!ma){qr.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),W(o.message)}}},[x,S,lt,B,$r,nt,ma,c,W]);let ya=Ne(!1);mt(()=>{if(ya.current||!Nr)return;let o=[];Y!==!0&&o.push("showApplePay"),ce!==!0&&o.push("showGooglePay"),o.length!==0&&(ya.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.`))},[Nr,Y,ce]);let fa=ge((o,v)=>Ve.applyInlineSessionPatch?Ve.applyInlineSessionPatch(o).then(z=>({error:null,sessionId:z.sessionId||e,nonce:z.session?.clientSecret||t})).catch(z=>{let ne=Ga(v,z);return W(ne.message),c?.(ne),{error:ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ve.applyInlineSessionPatch,t,c,e,W]),sn=ge(async o=>{if(!pe)return{proceed:!0};try{let v=await pe({method:o,sessionId:e||void 0,createSession:Ve.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&$n(ne=>({...ne??{},...v.account}));let z=await fa(v,o);return z.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:z.sessionId,nonce:z.nonce}}return{proceed:!0}}catch(v){let z=Ga(o,v);return W(z.message),c?.(z),{proceed:!1}}},[fa,Ve.inlineSessionDraft,pe,c,e,W]),ga=ge(async(o,v)=>{if(Wt.current)return;Wt.current=!0,It(!0),Ke("processing"),W(null);let z=v?.sessionId??e,ne=v?.nonce??t,L=Bo(te,v?.accountPatch),Z=v?.completionPaymentMethodId??Xr(o),Je=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o;try{let xt=await new Nn(Ge).processPayment(L.userId??"",{sessionId:z,nonce:ne,tokenizedData:Je,accountData:{userId:L.userId??"",email:L.email??"",firstName:L.firstName??"",lastName:L.lastName??"",...H?(()=>{let Ae=Nt.current,Zt=_e(H.state,Ae),Qt=_e(H.address_line_1,Ae),Kn=_e(H.postal_code,Ae),Wn=Qt&&!Zt&&Kn?Va(Ae,(Pt.current??"").trim()):null,Mt=Zt?un.current:Wn;return{country:Ae,...Kn&&Pt.current?{zip:Pt.current}:{},..._e(H.city,Ae)&&rn.current?{city:rn.current}:{},...Mt?{state:Mt}:{},...Qt&&Ot.current?{addressLine1:Ot.current}:{},..._e(H.address_line_2,Ae)&&Gt.current?{addressLine2:Gt.current}:{}}})():{}},chv:R,avsCheck:G??!1,checkoutType:_,checkoutLayout:V,avsConfig:H?{country:_e(H.country,Nt.current),postal_code:_e(H.postal_code,Nt.current),address_line_1:_e(H.address_line_1,Nt.current),address_line_2:_e(H.address_line_2,Nt.current),city:_e(H.city,Nt.current),state:_e(H.state,Nt.current)}:void 0});if(xt.ok){ir(z),Ke("success"),qt(null),await new Promise(Ae=>setTimeout(Ae,Tn)),a?.({status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:Z,checkoutMethod:o.isPaypal?"paypal":"card"});return}let Qe=await xt.json().catch(()=>null);if(Qe?.type==="paypal_redirect_required"){let Ae=Qe.threeDSecureToken,Zt=Qe.paymentMethodId||o.id||"";if(!ze||!Ae){Ke("error"),W("PayPal authorization required but no token provided.");return}try{let Qt=je?.getRawProvider();if(!Qt){W("PayPal is not available.");return}let Kn={return_url:window.location.href};Zt&&(Kn.payment_method=Zt);let{error:Wn}=await Qt.confirmPayment({clientSecret:Ae,confirmParams:Kn,redirect:"if_required"});if(Wn){Ke("error");let Mt=Wn.message??"PayPal payment failed.";W(Mt),fe("paypal",Mt,{code:Wn.code})}}catch(Qt){Ke("error"),W(Qt instanceof Error?Qt.message:"PayPal authorization failed.")}return}if(Qe?.type==="paypal_direct_required"){let Ae=Qe.orderId;if(!Ae){Ke("error"),W("PayPal retry required but no order id provided.");return}let Zt=I.current?.attempts??0;if(Zt>=2){Ke("error"),W("PayPal payment could not be completed after multiple attempts."),fe("paypal","paypal_direct_required retry limit exceeded");return}go(!1),ho("loading"),qt({orderId:Ae,attempts:Zt+1}),Ke(null);return}Ke("error");let Tt=Qe?.message??"Payment failed. Please try again.";W(Tt),fe(o.isPaypal?"paypal":"card",Tt,{code:Qe?.code??Qe?.gatewayErrorCode,declineCode:Qe?.declineCode??Qe?.gatewayDeclineReason}),await new Promise(Ae=>setTimeout(Ae,bn))}catch(St){Ke("error"),W(St instanceof Error?St.message:"An unexpected error occurred"),await new Promise(xt=>setTimeout(xt,bn))}finally{It(!1),Ke(null),Wt.current=!1}},[Ge,e,t,te,jt,R,ze,je,a,c,W,fe]),Xt=ge((o,v)=>{w?w(o):ga(o,v)},[w,ga]),ha=Ne(!1);mt(()=>{if(typeof window>"u"||ha.current)return;let o=new URLSearchParams(window.location.search),v=o.get("payment_intent"),z=o.get("payment_intent_client_secret"),ne=o.get("redirect_status");if(!v||!z)return;let L=Tt=>{let Ae=localStorage.getItem(Tt);if(!Ae)return null;try{return JSON.parse(Ae)}catch{return localStorage.removeItem(Tt),null}},Z=L(wn)??L(Wa),Je;if(Z?.clientSecret){if(Z.clientSecret!==z)return;Je={...Z.accountPatch?{accountPatch:Z.accountPatch}:{},...Z.sessionId?{sessionId:Z.sessionId}:{},...Z.nonce?{nonce:Z.nonce}:{}}}else if(Z?.sessionId&&Z.sessionId!==e)return;ha.current=!0,localStorage.removeItem(wn),localStorage.removeItem(Wa);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=Z?.paymentMethodType??Z?.tokenType??"card",Qe="card";(async()=>{let Tt=ze?.getRawProvider();if(!Tt){let Mt="Payment is not available \u2014 please refresh and try again.";W(Mt),fe(Qe,Mt);return}if(ne==="failed"){let Mt="Payment was declined. Please try again.";W(Mt),fe(Qe,Mt);return}let{paymentIntent:Ae,error:Zt}=await Tt.retrievePaymentIntent(z);if(Zt){let Mt=Zt.message??"Failed to retrieve payment status.";W(Mt),fe(Qe,Mt,{code:Zt.code});return}let Qt=Ae?.status,Kn=Jr(Qt);if(!Ae||!Kn){let Mt=Qt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";W(Mt),fe(Qe,Mt,{code:Qt??"missing_payment_intent"});return}let Wn=typeof Ae.payment_method=="string"?Ae.payment_method:Ae.payment_method?.id;Xt({id:Wn??Z?.paymentMethodId??Z?.tokenId??Ae.id,type:"card",threeDSecureActionResultTokenId:Ae.id,gateway:Z?.gateway??"stripe",paymentMethodType:xt},Je)})()},[e,Xt,ze,W,fe]);let Po=ge(o=>{o.preventDefault()},[]);if(!(ze!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Sr=re==="buttons",Vt=O?.variables,Mi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),bo=Vt?.colorBackground,Bi=bo&&!Mi.has(bo)?bo:void 0,kr=u.cardInputBorder??(Sr?"#e5e7eb":"#A4A4FF"),vo=Vt?.colorDanger??"#dc2626",jn=o=>Fn&&o?vo:kr,jr=(st.malformed||st.empty)&&(qn||Fn),Ai=jr?vo:jn(Ee.zip),Co=u.cardFormContainer?.backgroundColor??Bi??(Sr?"white":"#EDEDFF"),Rr=u.cardInputBackground??Vt?.colorBackground??"white",wo=er(j),Pa=er(oe),Qn=u.nameInput,ba=u.cardInputFontSize??Fs(Qn?.fontSize)??Vt?.fontSizeBase??"16px",va=typeof Qn?.fontFamily=="string"?Qn.fontFamily:Vt?.fontFamily??"Poppins, sans-serif",Ca=Ja(Qn?.fontWeight)??400,Fi=u.cardInputColor??(typeof Qn?.color=="string"?Qn.color:void 0)??Vt?.colorText??"#262833",Di=u.cardInputPlaceholderColor??"#9ca3af",ft=Vt?.borderRadius??"8px",Vn=Vt?.borderRadius??u.cardButton?.borderRadius??ft,Hn=Vt?.colorPrimary??"#4A49FF",Li=Vt?.colorPrimaryHover??no(Hn,.12),So=Vt?.colorText??"#262833",wa={fontSize:ba,fontFamily:va,fontWeight:Ca,color:Fi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ni={"--flopay-input-placeholder-color":Di,"--flopay-input-font-size":ba,"--flopay-input-font-family":va,"--flopay-input-font-weight":String(Ca)},Ir=u.cardFormContainer??{},ko=Ir.padding??(Sr?"0":"1rem"),Ro=Ir.borderRadius??ft,Oi=Ie&&Ut?d(_o,{capture:Ie,html:Ut.html,messageToken:Ut.messageToken,expectedOrigin:Ut.expectedOrigin,theme:b,onReady:()=>{if(!H||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,z=window.setInterval(()=>{v+=1;let ne=document.activeElement;!!ne&&ne.tagName==="IFRAME"&&ne.id==="flopay_vault_form_iframe"?(o(),window.clearInterval(z)):v>=50&&window.clearInterval(z)},100)},onError:o=>W(o),onValidation:o=>{W(o),o&&Ke(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"}),Sa=xe("div",{style:{backgroundColor:Co,borderRadius:Ro,...Ir,padding:ko,...Ni,display:"flex",flexDirection:"column"},children:[d("style",{children:`
|
|
30
|
+
`,oo=44;function jo(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var Ms={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ri={width:"100%",minHeight:oo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Bs(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ga(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function oi(e){return e==="paypal"?"PayPal":dr(e)}function As(e,t){let n=`We couldn't open ${oi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function ai(e){let t=Le(0),n=Le(null),i=Le(null),r=ge((l=i.current)=>{let f=l;f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),a=ge((l,f)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(l),l.timer=setTimeout(()=>{l.timer=null,i.current?.generation===l.generation&&(i.current=null,n.current=l.generation,e(l.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},f))},[r,e]),c=ge(l=>{l.yieldedControl&&a(l,600)},[a]),s=ge(l=>{r();let f=t.current+1;t.current=f,n.current=null;let w={generation:f,method:l,timer:null,yieldedControl:!1};return i.current=w,f},[r]),S=ge(l=>{let f=i.current;return typeof l=="number"&&f?.generation!==l?!1:(r(f),i.current=null,(typeof l!="number"||n.current===l)&&(n.current=null),!0)},[r]),B=ge(l=>{let f=i.current,w=l??f?.generation??t.current;(!l||f?.generation===l)&&(r(f),i.current=null),n.current=w},[r]),p=ge(l=>n.current===(l??t.current),[]),R=ge(l=>i.current?.generation===l&&n.current!==l,[]),C=ge(()=>{let l=i.current;l&&c(l)},[c]),_=ge(()=>{let l=i.current;l&&(l.yieldedControl=!0,r(l))},[r]);return pt(()=>{let l=()=>{document.visibilityState==="visible"?C():_()},f=()=>{_()};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,_,C]),{startAttempt:s,finishAttempt:S,invalidateAttempt:B,isAttemptInvalidated:p,isAttemptCurrent:R}}function Fs(e){let t=bs(e);return`Enter a valid ${zo(e)}${t?` (e.g. ${t})`:""}`}function Ds(e,t,n){let i=hs(e),r=t.trim(),a=n&&i,c=a&&!r,s=a&&!!r&&!Ps(e,r);return{visible:n,supported:i,required:a,empty:c,malformed:s}}function Ja(e,t){return t instanceof Cn?t:new Cn(t instanceof Error?t.message:`${Bs(e)} before-click hook failed.`,"validation_error")}function Oo(){return d("style",{children:Ts})}function Ls(e){return typeof e=="number"?`${e}px`:e}function Xa(e){if(typeof e=="number"||typeof e=="string")return e}function ii(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function si({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 Za(e){return e!=="unavailable"&&e!=="load_error"}function Vo(e){return d(Os,{...e})}function Qa({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:r,onErrorChange:a,isProcessing:c=!1,onButtonClick:s,onDecline:S,onTechnicalFailure:B,runBeforeButtonClick:p,onLoadStateChange:R,placeholderBorderRadius:C}){let _=Pn(),l=qo(),f=$o(),[w,T]=be("loading");pt(()=>{R?.(w)},[w,R]);let[h,$]=be(!1),Y=Le(!1),le=Le(null),re=Le(null),[D,J]=be(0),[q,ce]=be(!1),j=Le(!1),V=Le(new Map),{startAttempt:oe,finishAttempt:Be,invalidateAttempt:fe,isAttemptInvalidated:me,isAttemptCurrent:X}=ai((k,ee,ie)=>{B?.(k,ee,{...ie,popupBlocked:ie?.popupBlocked??Ln(ee)}),ce(!0),J(Ne=>Ne+1)});pt(()=>{q&&re.current?.focus()},[q,D]);let de=ge(()=>{J(k=>k+1)},[]),he=ge((k,ee,ie)=>{fe(ie),B?.("paypal",k,{code:ee,popupBlocked:Ln(k)}),ce(!0),de()},[fe,B,de]),ae=ge(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);pt(()=>{j.current&&(j.current=!1,ae())},[ae,D]);let Fe=ge(()=>{ce(!1),a?.(null),ae()},[ae,a]);pt(()=>{if(!l||Y.current)return;let k=new URLSearchParams(window.location.search),ee=k.get("payment_intent"),ie=k.get("payment_intent_client_secret"),Ne=k.get("redirect_status");if(!ee||!ie)return;Y.current=!0;let De;try{let x=localStorage.getItem(Fr);if(x){let H=JSON.parse(x);H.clientSecret===ie&&(De={...H.accountPatch?{accountPatch:H.accountPatch}:{},...H.sessionId?{sessionId:H.sessionId}:{},...H.nonce?{nonce:H.nonce}:{}})}}catch{}try{localStorage.removeItem(Fr)}catch{}let G=new URL(window.location.href);G.searchParams.delete("payment_intent"),G.searchParams.delete("payment_intent_client_secret"),G.searchParams.delete("redirect_status"),window.history.replaceState({},"",G.toString()),(async()=>{try{if($(!0),Ne==="failed"){let se="PayPal payment was declined. Please try again.";a?.(se),S?.(Tt("paypal",se));return}let{paymentIntent:x,error:H}=await l.retrievePaymentIntent(ie);if(H){a?.(H.message??"Failed to retrieve PayPal payment status.");return}if(x&&(x.status==="requires_capture"||x.status==="succeeded")){let se=typeof x.payment_method=="string"?x.payment_method:x.payment_method?.id;r({id:se??x.id,type:"card",threeDSecureActionResultTokenId:x.id,isPaypal:!0},De)}else{let se="PayPal payment was not completed. Please try again.";a?.(se),S?.(Tt("paypal",se))}}catch(x){a?.(x instanceof Error?x.message:"Failed to complete PayPal payment.")}finally{$(!1)}})()},[l,r,a,S]);let we=ge(async k=>{if(c||h){k.reject();return}let ee=p?await p("paypal"):{proceed:!0};if(!ee.proceed){V.current.delete(D),k.reject();return}let ie=oe("paypal");V.current.set(D,{generation:ie,accountPatch:ee.accountPatch,sessionId:ee.sessionId,nonce:ee.nonce}),ce(!1),s?.("paypal"),k.resolve()},[V,c,s,p,oe,h,D]),ve=ge(async k=>{if(!l||!f)return;let ee=V.current.get(D);if(ee&&!X(ee.generation)){V.current.delete(D);return}if(!ee&&me()||ee&&!Be(ee.generation))return;ee||Be();let ie=ee??null;if(V.current.delete(D),!ie&&p){let x=await p("paypal");if(!x.proceed){k.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ie={accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}}let Ne=ie?.sessionId??e,De=ie?.nonce??t,G=ie?.accountPatch?.email??n;try{if($(!0),a?.(null),!Ne||!G)throw new Error("Missing sessionId or email for PayPal payment");let x=l.createPaymentMethod,{error:H,paymentMethod:se}=await x({type:"paypal"});if(H){he(H,"stripe_paypal_create_payment_method_failed",ee?.generation),k.paymentFailed({reason:"fail"});return}let ke=await new Nn(i).createSessionIntent(Ne,De??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:se?.id??null,intentKind:"payment"});if(ke.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let gt=ke.clientSecret,Xe={return_url:window.location.href};if(se?.id&&(Xe.payment_method=se.id),typeof window<"u")try{localStorage.setItem(Fr,JSON.stringify({clientSecret:gt,sessionId:Ne,nonce:De,accountPatch:ie?.accountPatch}))}catch{}let{error:Je,paymentIntent:m}=await l.confirmPayment({clientSecret:gt,confirmParams:Xe,redirect:"if_required"});if(Je){if(typeof window<"u")try{localStorage.removeItem(Fr)}catch{}if(Br(Je)){let Oe=Je.message??"Your payment was declined.";a?.(Oe),S?.(Tt("paypal",Oe,{code:Mn(Je),declineCode:sr(Je)})),await ao({billingApiUrl:i,sessionId:Ne,nonce:De,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(Je)??"provider_declined"}})}else he(Je,"stripe_paypal_confirm_failed",ee?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Fr)}catch{}let Ue=typeof m?.payment_method=="string"?m.payment_method:m?.payment_method?.id;r({id:Ue??m?.id,type:"card",threeDSecureActionResultTokenId:m?.id,isPaypal:!0},{accountPatch:ie?.accountPatch,sessionId:Ne,nonce:De});return}catch(x){he(x,"stripe_paypal_failed",ee?.generation)}finally{$(!1)}},[l,f,e,t,n,i,r,a,S,p,he,Be,X,me,D]);return xe(cr,{children:[d(si,{state:w,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:xe("div",{ref:le,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[q&&d("button",{ref:re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Fe,style:ri,children:"Try PayPal again"}),d(ni,{onReady:k=>T(ii(k,["paypal"])),onLoadError:()=>T("load_error"),onClick:we,onConfirm:ve,onCancel:()=>{let k=V.current.get(D);V.current.delete(D),At(_)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),fe(k?.generation),ce(!1),j.current=!0,de()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},D)]})}),h&&d(vn,{status:"processing"})]})}function ei({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:r,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:S,onDecline:B,onTechnicalFailure:p,runBeforeButtonClick:R,onLoadStateChange:C,placeholderBorderRadius:_}){let l=Pn(),f=qo(),w=$o(),[T,h]=be("loading");pt(()=>{C?.(T)},[T,C]);let[$,Y]=be(!1),le=Le(null),re=Le(null),[D,J]=be(0),[q,ce]=be(!1),[j,V]=be("google_pay"),oe=Le(!1),Be=Le("google_pay"),fe=Le("google_pay"),me=Le(new Map),{startAttempt:X,finishAttempt:de,invalidateAttempt:he,isAttemptInvalidated:ae,isAttemptCurrent:Fe}=ai((G,x,H)=>{p?.(G,x,{...H,popupBlocked:H?.popupBlocked??Ln(x)}),V(G),ce(!0),J(se=>se+1)});pt(()=>{q&&re.current?.focus()},[q,D]);let we=ge(()=>{J(G=>G+1)},[]),ve=ge((G,x,H,se)=>{he(se),p?.(G,x,{code:H,popupBlocked:Ln(x)}),V(G),ce(!0),we()},[he,p,we]),k=ge(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);pt(()=>{oe.current&&(oe.current=!1,k())},[k,D]);let ee=ge(()=>{ce(!1),s?.(null),k()},[k,s]),ie=ge(async G=>{if(!f||!w)return;let x=me.current.get(D);if(x&&!Fe(x.generation)){me.current.delete(D);return}if(!x&&ae()||x&&!de(x.generation))return;x||de();let H=G.expressPaymentType??x?.method??Be.current,se=x??null;me.current.delete(D);let ke=Ga(H);if(!se&&R){let Ue=await R(ke);if(!Ue.proceed){G.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}se={accountPatch:Ue.accountPatch,sessionId:Ue.sessionId,nonce:Ue.nonce}}let gt=ke,Xe=se?.sessionId??e,Je=se?.nonce??t,m=se?.accountPatch?.email??n;try{Y(!0),s?.(null);let{error:Ue}=await w.submit();if(Ue){ve(H,Ue,"stripe_wallet_submit_failed",x?.generation);return}let{error:Oe,paymentMethod:qe}=await f.createPaymentMethod({elements:w});if(Oe||!qe){ve(H,Oe??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",x?.generation);return}if(!Xe||!m)throw new Error("Missing sessionId or email for wallet payment");let je=await new Nn(i).createSessionIntent(Xe,Je??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H??ke,paymentMethodId:qe.id,intentKind:r});if(je.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Kt=je.clientSecret,{error:bt,intentId:Rt}=Es(Kt)?await f.confirmCardSetup(Kt,{payment_method:qe.id}).then(g=>({error:g.error,intentId:g.setupIntent?.id})):await f.confirmCardPayment(Kt,{payment_method:qe.id}).then(g=>({error:g.error,intentId:g.paymentIntent?.id}));if(bt){if(Br(bt)){let g=bt.message??"Your payment was declined.";s?.(g),B?.(Tt(gt,g,{code:Mn(bt),declineCode:sr(bt)})),await ao({billingApiUrl:i,sessionId:Xe,nonce:Je,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H??ke,providerDeclineReason:Mn(bt)??"provider_declined"}})}else ve(H,bt,"stripe_wallet_confirm_failed",x?.generation);return}c({id:qe.id,type:"card",threeDSecureActionResultTokenId:Rt},{accountPatch:se?.accountPatch,sessionId:Xe,nonce:Je})}catch(Ue){ve(H,Ue,"stripe_wallet_failed",x?.generation)}finally{Y(!1)}},[f,w,e,t,n,i,r,c,s,B,R,ve,de,Fe,ae,D]),Ne=at(()=>{let G=["applePay","googlePay","paypal","link","amazonPay","klarna"],x=new Set(["applePay","googlePay"]),H=new Set(a.map(Wa)),se={};for(let ke of G)H.has(ke)?se[ke]=x.has(ke)?"always":"auto":se[ke]="never";return se},[a]),De=at(()=>a.map(Wa),[a]);return xe(cr,{children:[d(si,{state:T,placeholderTestId:"flopay-wallet-placeholder",borderRadius:_,children:xe("div",{ref:le,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[q&&xe("button",{ref:re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ee,style:ri,children:["Try ",oi(j)," again"]}),d(ni,{onReady:G=>{h(ii(G,De))},onLoadError:G=>{h("load_error"),At(l)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk"})},onClick:async G=>{Be.current=G.expressPaymentType,fe.current=Ga(G.expressPaymentType);let x=R?await R(fe.current):{proceed:!0};if(!x.proceed){me.current.delete(D),G.reject();return}let H=X(G.expressPaymentType);me.current.set(D,{generation:H,method:G.expressPaymentType,accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}),ce(!1),S?.(fe.current),G.resolve()},onConfirm:ie,onCancel:()=>{let G=me.current.get(D);me.current.delete(D),At(l)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),he(G?.generation),ce(!1),oe.current=!0,we()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ne,layout:{maxColumns:1,overflow:"never"}}},D)]})}),$&&d(vn,{status:"processing"})]})}function Ns({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:r=!1,hasNextStep:a=!1,onClick:c,backgroundColor:s,borderColor:S,textColor:B,borderRadius:p,fontFamily:R}){let C=Ss(e,t),_=Ba[e],l=C?.backgroundColor??s??"#ffffff",f=C?.borderColor??S??"#d1d5db",w=C?.textColor??B??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!i&&c()},disabled:n||i,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:oo,padding:"0 1rem",backgroundColor:l,color:w,border:`1px solid ${f}`,borderRadius:p??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,cursor:n||i?"not-allowed":"pointer",opacity:i&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:r?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?d("span",{style:{margin:"0 auto"},children:`Connecting to ${dr(e)}\u2026`}):xe(cr,{children:[xe("span",{style:{display:"inline-flex",alignItems:"center",gap:Cs(e)?8:0},children:[_?d("img",{src:_,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):C?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:C.logoSvg}}):null,d("span",{children:dr(e)})]}),a&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:w,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:d("path",{d:"M9 18l6-6-6-6"})})]})})}function Uo({method:e,sessionId:t,nonce:n,email:i,billingName:r,billingApiUrl:a,onTokenizedBody:c,onErrorChange:s,onDecline:S,onCancel:B,runBeforeButtonClick:p,onButtonClick:R,isProcessing:C,submitButtonColor:_,submitButtonBorderRadius:l,submitButtonStyle:f,errorText:w}){let T=Pn(),h=qo(),$=$o(),[Y,le]=be(!1),re=Le(!1),[D,J]=be(!1),[q,ce]=be("loading"),j=ge(async()=>{if(!h||!$||C||re.current||!D)return;re.current=!0,le(!0);let V=p?await p("card"):{proceed:!0};if(!V.proceed){re.current=!1,le(!1);return}R?.("card");let oe=V.sessionId??t,Be=V.nonce??n,fe=V.accountPatch?.email??i;try{s?.(null);let me=await $.submit();if(me.error){s?.(me.error.message??"Payment failed.");return}let X=await h.createPaymentMethod({elements:$});if(X.error||!X.paymentMethod){s?.(X.error?.message??"Failed to create payment method.");return}let de=X.paymentMethod;if(!oe||!fe)throw new Error("Missing sessionId or email for payment.");let he=de.type||e,ae=await new Nn(a).createSessionIntent(oe,Be??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:he,paymentMethodId:null,intentKind:"payment"});if(ae.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Fe=ae.clientSecret;if(typeof window<"u")try{localStorage.setItem(Sn,JSON.stringify({clientSecret:Fe,sessionId:oe,nonce:Be,accountPatch:V.accountPatch,paymentMethodId:de.id,paymentMethodType:de.type??e,gateway:"stripe"}))}catch{}let{error:we,paymentIntent:ve}=await h.confirmPayment({clientSecret:Fe,confirmParams:{return_url:window.location.href,payment_method:de.id},redirect:"if_required"});if(we){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let ie=we.message??"Payment failed.";s?.(ie),S?.(Tt("card",ie,{code:we.code})),await ao({billingApiUrl:a,sessionId:oe,nonce:Be,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:we.code??"provider_declined"}});return}let k=ve?.status;if(!Xr(k)){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let ie=k==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";s?.(ie),S?.(Tt("card",ie,{code:k??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let ee=typeof ve?.payment_method=="string"?ve.payment_method:ve?.payment_method?.id;c({id:ee??de.id,type:"card",threeDSecureActionResultTokenId:ve?.id,gateway:"stripe",paymentMethodType:de.type??e},{accountPatch:V.accountPatch,sessionId:oe,nonce:Be})}catch(me){s?.(me instanceof Error?me.message:"Payment failed. Please try again.")}finally{re.current=!1,le(!1)}},[h,$,C,D,p,R,t,n,i,a,e,c,s,S]);return xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(ps,{onReady:()=>ce("ready"),onLoadError:()=>{ce("load_error"),At(T)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"apm",requestCategory:"provider_sdk"})},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:()=>{j()},disabled:!D||Y||C||q!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:_,color:"white",border:"none",borderRadius:l,fontSize:"1rem",fontWeight:600,cursor:!D||Y||C||q!=="ready"?"not-allowed":"pointer",opacity:!D||Y||C||q!=="ready"?.5:1,transition:"opacity 120ms ease-out",...f??{}},children:Y?"Processing\u2026":`Pay with ${dr(e)}`}),w&&d(or,{margin:"0.75rem 0 0",children:w})]})}function ti({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:r,paymentElementMethods:a,stripeInstance:c,paymentElementBaseOptions:s,onTokenizedBody:S,onErrorChange:B,onButtonClick:p,onDecline:R,runBeforeButtonClick:C,onLoadStateChange:_,isProcessing:l=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:w=8,submitButtonStyle:T,buttonAppearance:h,themeId:$,onExpandApm:Y,expandedApmMethod:le}){let[re,D]=be(null),[J,q]=be(null),ce=Le(!1);pt(()=>{a.length>0&&c?_?.("ready"):c||_?.("loading")},[a.length,c,_]);let j=ge(async X=>{if(!c||ce.current||l)return;ce.current=!0,q(X);let de=C?await C("card"):{proceed:!0};if(!de.proceed){ce.current=!1,q(null);return}p?.("card");let he=de.sessionId??e,ae=de.nonce??t,Fe=de.accountPatch?.email??n;try{if(B?.(null),!he||!Fe)throw new Error("Missing sessionId or email for payment.");let we=await new Nn(r).createSessionIntent(he,ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,paymentMethodId:null,intentKind:"payment"});if(we.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ve=we.clientSecret;if(typeof window<"u")try{localStorage.setItem(Sn,JSON.stringify({clientSecret:ve,sessionId:he,nonce:ae,accountPatch:de.accountPatch,paymentMethodType:X,gateway:"stripe"}))}catch{}let{error:k,paymentIntent:ee}=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(k){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let De=k.message??"Payment failed.";B?.(De),R?.(Tt("card",De,{code:k.code})),await ao({billingApiUrl:r,sessionId:he,nonce:ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,providerDeclineReason:k.code??"provider_declined"}});return}let ie=ee?.status;if(!Xr(ie)){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let De=ie==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";B?.(De),R?.(Tt("card",De,{code:ie??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let Ne=typeof ee?.payment_method=="string"?ee.payment_method:ee?.payment_method?.id;S({id:Ne??ee?.id,type:"card",threeDSecureActionResultTokenId:ee?.id,gateway:"stripe",paymentMethodType:X},{accountPatch:de.accountPatch,sessionId:he,nonce:ae})}catch(we){B?.(we instanceof Error?we.message:"Payment failed. Please try again.")}finally{ce.current=!1,q(null)}},[c,l,C,p,e,t,n,r,i,S,B,R]),[V,oe]=be(null),Be=Y?le??null:V,fe=ge(X=>{ce.current||l||Be&&Be!==X||(Ka(X)?Y?Y(X):oe(X):j(X))},[Be,l,j,Y]),me=at(()=>V?{...s,paymentMethodTypes:[V]}:null,[V,s]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(X=>{let de=le===X,he=J===X,ae=J!==null&&J!==X||le!=null&&le!==X;return xe(Rs.Fragment,{children:[d(Ns,{method:X,themeId:$,submitting:he,disabled:ae,highlighted:de,hasNextStep:Ka(X),onClick:()=>fe(X),backgroundColor:h?.backgroundColor,borderColor:h?.borderColor,textColor:h?.textColor,borderRadius:h?.borderRadius,fontFamily:h?.fontFamily}),!Y&&V===X&&me&&c&&d(Jn,{stripe:c,options:me,children:d(Uo,{method:X,sessionId:e,email:n,billingName:i,billingApiUrl:r,onTokenizedBody:S,onErrorChange:B,onDecline:R,onCancel:()=>oe(null),runBeforeButtonClick:C,onButtonClick:p,isProcessing:l,submitButtonColor:f,submitButtonBorderRadius:w,submitButtonStyle:T})},X)]},X)})})}function Os({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,onComplete:a,onError:c,onDecline:s,onTokenizedBody:S,firstName:B,lastName:p,chv:R,className:C,isProcessing:_,error:l,onErrorChange:f,showPayPal:w=!0,showStripe:T=!0,enabledPaymentMethods:h,enabledPaymentMethodCountries:$,showApplePay:Y=!0,showGooglePay:le=!0,layout:re="default",theme:D,buttonsTheme:J,buttonsStyles:q,appearance:ce,cardButtonContent:j,cardBackButtonContent:V,cardTitleContent:oe,showSecurityFooter:Be,onButtonClick:fe,onBeforeButtonClick:me,enableAVS:X,cardFieldOrder:de,cardPreFormSlot:he,avsLayout:ae="row",country:Fe,zip:we,addressLine1:ve,addressLine2:k,city:ee,state:ie,onCountryChange:Ne,onZipChange:De,avsCheck:G,checkoutType:x,checkoutLayout:H,totalAmount:se=0,currency:ke="usd",initialCardOpen:gt=!1,directPaypal:Xe,isSubscription:Je=!1,session:m,debug:Ue=!1}){let Oe=Pn(),qe=To(),je=Is(cn),Kt=Jr(),[bt,Rt]=be(!1),[g,Ce]=be(null),[$e,st]=be(Fe??"US"),[Qe,et]=be(we??""),[We,Pe]=be(ve??""),[vt,Ve]=be(k??""),[Ft,It]=be(ee??""),[un,Rn]=be(ie??""),[In,$n]=be({}),ht=Le(we??""),Dt=Le(Fe??"US"),Lt=Le(ve??""),Wt=Le(k??""),rn=Le(ee??""),pn=Le(ie??""),K=at(()=>gs(X),[X]),An=K!==null,mn=!!m?.vault?.html,Nt=!!m?.gateways?.pcivault,tt=mn||Nt,y=!!(T&&tt&&Oe&&e),Ie=at(()=>!Oe||!y||!e?null:Oe.cardCapture({sessionId:e}),[Oe,y,e]),lt=at(()=>{let o=$e,v=K?_e(K.postal_code,o):!1;return Ds(o,Qe,v)},[K,$e,Qe]),{avsInvalid:En,invalidAvsFields:Ee}=at(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!y||!K)return{avsInvalid:!1,invalidAvsFields:o};let v=$e,z=(Z,Ge)=>_e(Z,v)&&!Ge.trim(),ne={line1:z(K.address_line_1,We),city:z(K.city,Ft),state:z(K.state,un),zip:lt.empty||lt.malformed};return{avsInvalid:ne.line1||ne.city||ne.state||ne.zip,invalidAvsFields:ne}},[y,K,$e,We,Ft,un,lt]),[Fn,yn]=be(!1),[qn,fn]=be(!1),[Ot,Bt]=be(()=>No(m?.vault)),[Se,mt]=be(gt&&tt?"card":"buttons"),[nt,on]=be(null),Yt=Se==="expanding"||Se==="card",Pt=280,jt=Le(null),Ct=ge(o=>{jt.current&&clearTimeout(jt.current),jt.current=setTimeout(()=>{jt.current=null,o()},Pt)},[Pt]);pt(()=>()=>{jt.current&&clearTimeout(jt.current)},[]);let an=ge(()=>{mt("expanding"),Ct(()=>mt("card"))},[Ct]),gn=ge(()=>{mt("collapsing"),Ct(()=>mt("buttons"))},[Ct]),_n=ge(o=>{on(o),mt("apm-expanding"),Ct(()=>mt("apm-form"))},[Ct]),hn=ge(()=>{mt("apm-collapsing"),Ct(()=>{mt("buttons"),on(null)})},[Ct]);pt(()=>{re==="buttons"&>&&tt&&mt("card")},[re,gt,tt]);let[Vt,He]=be(null),Ht=Le(!1),[zt,Ut]=be(null),E=Le(zt);pt(()=>{E.current=zt},[zt]);let L=n||Kt,O=l??g,M=at(()=>_s(D),[D]),u=at(()=>{let o=M?.buttonsLayout??ms(J);return q?{...o,...q,cardButton:{...o.cardButton,...q.cardButton},cardFormContainer:{...o.cardFormContainer,...q.cardFormContainer},backButton:{...o.backButton,...q.backButton},backButtonIcon:{...o.backButtonIcon,...q.backButtonIcon},submitButton:{...o.submitButton,...q.submitButton},title:{...o.title,...q.title}}:o},[M,J,q]),U=ce??M?.appearance,b=at(()=>{let o=U?.variables,v=Ge=>typeof Ge=="string"&&Ge?Ge:void 0,z=u.submitButton,ne=v(o?.colorPrimary)??v(z?.backgroundColor)??"#4A49FF",N=re==="buttons",Z=u.nameInput;return{primaryColor:ne,primaryHoverColor:v(o?.colorPrimaryHover)??ro(ne,.12),inputBackgroundColor:v(u.cardInputBackground)??v(o?.colorBackground)??"#ffffff",textColor:v(u.cardInputColor)??v(Z?.color)??v(o?.colorText)??"#262833",borderColor:v(u.cardInputBorder)??(N?"#e5e7eb":"#A4A4FF"),placeholderColor:v(u.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(o?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(Z?.fontFamily)??v(o?.fontFamily)??"Poppins, sans-serif",fontSize:v(u.cardInputFontSize)??v(o?.fontSizeBase)??"16px",fontWeight:String(Xa(Z?.fontWeight)??400),borderRadius:v(o?.borderRadius)??"8px"}},[U,u,re]),Te=je.inlineSessionPatchProcessing??!1,W=(_??bt)||Te,Ye=L.replace(/\/+$/,""),te=at(()=>Ao({userId:r,email:i,firstName:B,lastName:p,country:Fe,zip:we},In),[r,i,B,p,Fe,we,In]),$t=[te.firstName,te.lastName].filter(o=>!!o?.trim()).join(" "),rt=at(()=>Oe?Oe.getRawProvider():null,[Oe]),A=at(()=>qe?qe.getRawProvider():null,[qe]),P=se||100,F=at(()=>U?ks(U):null,[U]),ye=F?{appearance:F}:null,Me=at(()=>{let o=F??{},v=o.rules??{};return{...o,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[F]),ze=at(()=>{let o=La(se);return{...o,currency:ke.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...ye}},[se,ke,ye]),sn=at(()=>({mode:"payment",amount:P,currency:ke.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...ye}),[P,ke,ye]),I=ge(o=>{Ce(o),f?.(o)},[f]);pt(()=>{!y||!Ie||Ie.setCardFieldOrder?.(de??null,K==null)},[y,Ie,de,K]),pt(()=>{(Se==="expanding"||Se==="collapsing"||Se==="apm-expanding"||Se==="apm-collapsing")&&I(null)},[Se,I]);let pe=ge((o,v,z)=>{s?.(Tt(o,v,z))},[s]),ue=ge((o,v,z)=>{let ne=z?.popupBlocked??Ln(v),N=As(o,ne),Z=Yn(z?.code)??Mn(v)??"external_payment_method_failed",Ge=new Cn(N,"api_error",{code:"external_payment_method_failed",param:o});He(null),re==="buttons"&&(mt("buttons"),on(null)),I(N),c?.(Ge),console.error("[FloPay] External payment method failed:",{method:o,code:Z,popupBlocked:ne})},[re,c,I]);pt(()=>{if(!y||!e){Bt(null);return}let o=No(m?.vault);if(o){Bt(o);return}Bt(null);let v=!0;return new Nn(Ye).getVaultCapture(e,t).then(z=>{if(!v)return;let ne=No(z);ne?Bt(ne):I("Failed to load the secure card form.")}).catch(z=>{v&&I(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{v=!1}},[y,e,m?.vault?.html,m?.vault?.messageToken,m?.vault?.expectedOrigin,Ye,t,I]);let Re=Le({onComplete:a,onError:c,updateError:I,emitDecline:pe,resolvedAccount:te,avsConfig:K,avsCheckProp:G,sessionId:e,nonce:t,baseUrl:Ye});Re.current={onComplete:a,onError:c,updateError:I,emitDecline:pe,resolvedAccount:te,avsConfig:K,avsCheckProp:G,sessionId:e,nonce:t,baseUrl:Ye};let Gt=Le(!1),Jt=ge(()=>{let{resolvedAccount:o,avsConfig:v,avsCheckProp:z}=Re.current,ne=Dt.current||o.country||"US",N=v?_e(v.state,ne):!1,Z=v?_e(v.address_line_1,ne):!1,Ge=v?_e(v.postal_code,ne):!1,St=v?_e(v.city,ne):!1,Et=v?_e(v.address_line_2,ne):!1,Ze=Z&&!N&&Ge?Ha(ne,(ht.current??"").trim()):null,_t=N?pn.current:Ze;return{accountData:{userId:o.userId??"",email:o.email??"",firstName:o.firstName??"",lastName:o.lastName??"",...Ge&&ht.current?{zip:ht.current}:{},...St&&rn.current?{city:rn.current}:{},..._t?{state:_t}:{},...Z&&Lt.current?{addressLine1:Lt.current}:{},...Et&&Wt.current?{addressLine2:Wt.current}:{},country:ne},...z!==void 0?{avsCheck:z}:{},...v?{avsConfig:{country:_e(v.country,ne),postal_code:Ge,address_line_1:Z,address_line_2:Et,city:St,state:N}}:{}}},[]);pt(()=>{!y||!Ie||Ie.setSubmitGate?.(En)},[y,Ie,En]),pt(()=>{if(!y||!Ie)return;Gt.current=!1;let o=!1,v=Ie.on("submitting",()=>{yn(!0),He("processing");let{baseUrl:Z,sessionId:Ge,nonce:St,updateError:Et,onError:Ze}=Re.current;!Ge||!St||new Nn(Z).patchAccountSnapshot(Ge,St,Jt(),{telemetryMode:"best_effort"}).catch(_t=>{if(!xs(_t))return;let Ae=_t instanceof Error?_t.message:"Please check your billing address and try again.";Et(Ae),He(null),Ze?.(_t instanceof Cn?_t:new Cn(Ae,"api_error"))})}),z=Ie.on("complete",async Z=>{ir(Z.sessionId??Re.current.sessionId),He("success"),await new Promise(Ge=>setTimeout(Ge,Tn)),!Gt.current&&(Gt.current=!0,Re.current.onComplete?.({status:"succeeded",paymentIntentId:Z.intentId,checkoutMethod:"card"}))}),ne=Ie.on("decline",async Z=>{let{updateError:Ge,emitDecline:St}=Re.current,Et=Z.message??"Your payment was declined. Please try another card or contact your bank.";Ge(Et),He("error"),St("card",Et,Z.declineReason?{declineCode:Z.declineReason}:void 0),await new Promise(Ze=>setTimeout(Ze,bn)),!o&&He(null)}),N=Ie.on("error",async Z=>{let{updateError:Ge,onError:St}=Re.current,Et=Z.message??"There was a problem processing your payment. Please try again.";Ge(Et),He("error"),St?.(new Cn(Et,"api_error")),await new Promise(Ze=>setTimeout(Ze,bn)),!o&&He(null)});return()=>{o=!0,v(),z(),ne(),N()}},[y,Ie]);let ot=!!Xe?.clientId,Pr=Array.isArray(h),Or=Pr&&h.length>0,wi=Pr&&h.includes("paypal"),{expressMethods:zr,paymentElementMethods:br}=at(()=>ws(h,{excludePaypal:ot}),[h,ot]),na=ot||!!qe,ki=at(()=>na?zr.filter(o=>o!=="paypal"):zr,[zr,na]),Ri=at(()=>{let o=[];return Y&&o.push("apple_pay"),le&&o.push("google_pay"),o},[Y,le]),Ur=Pr?ki:Ri,Ii=T&&Ur.length>0,fo=An?$e:Fe,$r=at(()=>{let o=fo?.trim().toUpperCase();return o?$?br.filter(v=>{let z=$[v];return!z||z.length===0||z.includes(o)}):vs(br,fo):br},[br,fo,$]),go=at(()=>({mode:"payment",amount:P,currency:ke.toLowerCase(),paymentMethodCreation:"manual",appearance:Me}),[P,ke,Me]),[ra,oa]=be("loading"),[aa,ia]=be("loading"),[sa,la]=be("loading"),[Ei,ho]=be(!1),[ca,Po]=be("loading"),[qr,_i]=be();pt(()=>{_i(Oa())},[]);let da=w&&(ot||(Pr?wi:qr===!1)),ua=T&&Ii,vr=da&&ot,pa=ca==="retrying"||ca==="exhausted",Cr=da&&!!A&&(!ot||pa),Sr=ua&&!!rt,wr=T&&Or&&$r.length>0&&!!rt,xi=vr&&!pa?Ei:Cr&&Za(ra),Ti=Sr&&Za(aa),Mi=wr&&sa!=="load_error",ma=o=>o==="loading"||o==="ready",ya=vr||Cr&&ma(ra)||Sr&&ma(aa)||wr&&sa!=="load_error",jr=Le(!1);pt(()=>{if(!jr.current){if(!T&&!w){jr.current=!0;let o=new Cn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(o),I(o.message)}else if(!T&&w&&!ot&&!A){jr.current=!0;let o=new Cn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(o),I(o.message)}else if(qr!==void 0&&!tt&&!ya){jr.current=!0;let o=new Cn("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});c?.(o),I(o.message)}}},[T,w,ot,A,qr,tt,ya,c,I]);let fa=Le(!1);pt(()=>{if(fa.current||!Or)return;let o=[];Y!==!0&&o.push("showApplePay"),le!==!0&&o.push("showGooglePay"),o.length!==0&&(fa.current=!0,console.warn(`[FloPay] ${o.join(" / ")} ${o.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Or,Y,le]);let ga=ge((o,v)=>je.applyInlineSessionPatch?je.applyInlineSessionPatch(o).then(z=>({error:null,sessionId:z.sessionId||e,nonce:z.session?.clientSecret||t})).catch(z=>{let ne=Ja(v,z);return I(ne.message),c?.(ne),{error:ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[je.applyInlineSessionPatch,t,c,e,I]),ln=ge(async o=>{if(!me)return{proceed:!0};try{let v=await me({method:o,sessionId:e||void 0,createSession:je.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&$n(ne=>({...ne??{},...v.account}));let z=await ga(v,o);return z.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:z.sessionId,nonce:z.nonce}}return{proceed:!0}}catch(v){let z=Ja(o,v);return I(z.message),c?.(z),{proceed:!1}}},[ga,je.inlineSessionDraft,me,c,e,I]),ha=ge(async(o,v)=>{if(Ht.current)return;Ht.current=!0,Rt(!0),He("processing"),I(null);let z=v?.sessionId??e,ne=v?.nonce??t,N=Ao(te,v?.accountPatch),Z=v?.completionPaymentMethodId??Zr(o),Ge=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o;try{let Et=await new Nn(Ye).processPayment(N.userId??"",{sessionId:z,nonce:ne,tokenizedData:Ge,accountData:{userId:N.userId??"",email:N.email??"",firstName:N.firstName??"",lastName:N.lastName??"",...K?(()=>{let Ae=Dt.current,Zt=_e(K.state,Ae),Qt=_e(K.address_line_1,Ae),Kn=_e(K.postal_code,Ae),Wn=Qt&&!Zt&&Kn?Ha(Ae,(ht.current??"").trim()):null,xt=Zt?pn.current:Wn;return{country:Ae,...Kn&&ht.current?{zip:ht.current}:{},..._e(K.city,Ae)&&rn.current?{city:rn.current}:{},...xt?{state:xt}:{},...Qt&&Lt.current?{addressLine1:Lt.current}:{},..._e(K.address_line_2,Ae)&&Wt.current?{addressLine2:Wt.current}:{}}})():{}},chv:R,avsCheck:G??!1,checkoutType:x,checkoutLayout:H,avsConfig:K?{country:_e(K.country,Dt.current),postal_code:_e(K.postal_code,Dt.current),address_line_1:_e(K.address_line_1,Dt.current),address_line_2:_e(K.address_line_2,Dt.current),city:_e(K.city,Dt.current),state:_e(K.state,Dt.current)}:void 0});if(Et.ok){ir(z),He("success"),Ut(null),await new Promise(Ae=>setTimeout(Ae,Tn)),a?.({status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:Z,checkoutMethod:o.isPaypal?"paypal":"card"});return}let Ze=await Et.json().catch(()=>null);if(Ze?.type==="paypal_redirect_required"){let Ae=Ze.threeDSecureToken,Zt=Ze.paymentMethodId||o.id||"";if(!Oe||!Ae){He("error"),I("PayPal authorization required but no token provided.");return}try{let Qt=qe?.getRawProvider();if(!Qt){I("PayPal is not available.");return}let Kn={return_url:window.location.href};Zt&&(Kn.payment_method=Zt);let{error:Wn}=await Qt.confirmPayment({clientSecret:Ae,confirmParams:Kn,redirect:"if_required"});if(Wn){He("error");let xt=Wn.message??"PayPal payment failed.";I(xt),pe("paypal",xt,{code:Wn.code})}}catch(Qt){He("error"),I(Qt instanceof Error?Qt.message:"PayPal authorization failed.")}return}if(Ze?.type==="paypal_direct_required"){let Ae=Ze.orderId;if(!Ae){He("error"),I("PayPal retry required but no order id provided.");return}let Zt=E.current?.attempts??0;if(Zt>=2){He("error"),I("PayPal payment could not be completed after multiple attempts."),pe("paypal","paypal_direct_required retry limit exceeded");return}ho(!1),Po("loading"),Ut({orderId:Ae,attempts:Zt+1}),He(null);return}He("error");let _t=Ze?.message??"Payment failed. Please try again.";I(_t),pe(o.isPaypal?"paypal":"card",_t,{code:Ze?.code??Ze?.gatewayErrorCode,declineCode:Ze?.declineCode??Ze?.gatewayDeclineReason}),await new Promise(Ae=>setTimeout(Ae,bn))}catch(St){He("error"),I(St instanceof Error?St.message:"An unexpected error occurred"),await new Promise(Et=>setTimeout(Et,bn))}finally{Rt(!1),He(null),Ht.current=!1}},[Ye,e,t,te,$t,R,Oe,qe,a,c,I,pe]),Xt=ge((o,v)=>{S?S(o):ha(o,v)},[S,ha]),Pa=Le(!1);pt(()=>{if(typeof window>"u"||Pa.current)return;let o=new URLSearchParams(window.location.search),v=o.get("payment_intent"),z=o.get("payment_intent_client_secret"),ne=o.get("redirect_status");if(!v||!z)return;let N=_t=>{let Ae=localStorage.getItem(_t);if(!Ae)return null;try{return JSON.parse(Ae)}catch{return localStorage.removeItem(_t),null}},Z=N(Sn)??N(Ya),Ge;if(Z?.clientSecret){if(Z.clientSecret!==z)return;Ge={...Z.accountPatch?{accountPatch:Z.accountPatch}:{},...Z.sessionId?{sessionId:Z.sessionId}:{},...Z.nonce?{nonce:Z.nonce}:{}}}else if(Z?.sessionId&&Z.sessionId!==e)return;Pa.current=!0,localStorage.removeItem(Sn),localStorage.removeItem(Ya);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 Et=Z?.paymentMethodType??Z?.tokenType??"card",Ze="card";(async()=>{let _t=Oe?.getRawProvider();if(!_t){let xt="Payment is not available \u2014 please refresh and try again.";I(xt),pe(Ze,xt);return}if(ne==="failed"){let xt="Payment was declined. Please try again.";I(xt),pe(Ze,xt);return}let{paymentIntent:Ae,error:Zt}=await _t.retrievePaymentIntent(z);if(Zt){let xt=Zt.message??"Failed to retrieve payment status.";I(xt),pe(Ze,xt,{code:Zt.code});return}let Qt=Ae?.status,Kn=Xr(Qt);if(!Ae||!Kn){let xt=Qt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";I(xt),pe(Ze,xt,{code:Qt??"missing_payment_intent"});return}let Wn=typeof Ae.payment_method=="string"?Ae.payment_method:Ae.payment_method?.id;Xt({id:Wn??Z?.paymentMethodId??Z?.tokenId??Ae.id,type:"card",threeDSecureActionResultTokenId:Ae.id,gateway:Z?.gateway??"stripe",paymentMethodType:Et},Ge)})()},[e,Xt,Oe,I,pe]);let bo=ge(o=>{o.preventDefault()},[]);if(!(Oe!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let kr=re==="buttons",qt=U?.variables,Bi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),vo=qt?.colorBackground,Ai=vo&&!Bi.has(vo)?vo:void 0,Rr=u.cardInputBorder??(kr?"#e5e7eb":"#A4A4FF"),Co=qt?.colorDanger??"#dc2626",jn=o=>Fn&&o?Co:Rr,Vr=(lt.malformed||lt.empty)&&(qn||Fn),Fi=Vr?Co:jn(Ee.zip),So=u.cardFormContainer?.backgroundColor??Ai??(kr?"white":"#EDEDFF"),Ir=u.cardInputBackground??qt?.colorBackground??"white",wo=er(V),ba=er(oe),Qn=u.nameInput,va=u.cardInputFontSize??Ls(Qn?.fontSize)??qt?.fontSizeBase??"16px",Ca=typeof Qn?.fontFamily=="string"?Qn.fontFamily:qt?.fontFamily??"Poppins, sans-serif",Sa=Xa(Qn?.fontWeight)??400,Di=u.cardInputColor??(typeof Qn?.color=="string"?Qn.color:void 0)??qt?.colorText??"#262833",Li=u.cardInputPlaceholderColor??"#9ca3af",yt=qt?.borderRadius??"8px",Vn=qt?.borderRadius??u.cardButton?.borderRadius??yt,Hn=qt?.colorPrimary??"#4A49FF",Ni=qt?.colorPrimaryHover??ro(Hn,.12),ko=qt?.colorText??"#262833",wa={fontSize:va,fontFamily:Ca,fontWeight:Sa,color:Di,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Oi={"--flopay-input-placeholder-color":Li,"--flopay-input-font-size":va,"--flopay-input-font-family":Ca,"--flopay-input-font-weight":String(Sa)},Er=u.cardFormContainer??{},Ro=Er.padding??(kr?"0":"1rem"),Io=Er.borderRadius??yt,zi=Ie&&Ot?d(xo,{capture:Ie,html:Ot.html,messageToken:Ot.messageToken,expectedOrigin:Ot.expectedOrigin,theme:b,onReady:()=>{if(!K||typeof document>"u")return;let o=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};o();let v=0,z=window.setInterval(()=>{v+=1;let ne=document.activeElement;!!ne&&ne.tagName==="IFRAME"&&ne.id==="flopay_vault_form_iframe"?(o(),window.clearInterval(z)):v>=50&&window.clearInterval(z)},100)},onError:o=>I(o),onValidation:o=>{I(o),o&&He(null)}}):d("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),ka=xe("div",{style:{backgroundColor:So,borderRadius:Io,...Er,padding:Ro,...Oi,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 @@ ${Ze.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),
|
|
39
|
-
`)}):null,
|
|
40
|
-
`)}):null,Ia=Se==="apm-expanding"||Se==="apm-form"||Se==="apm-collapsing",Hr=Se==="apm-expanding"?`flopay-card-enter ${bt}ms cubic-bezier(0, 0, 0.2, 1) both`:Se==="apm-collapsing"?`flopay-card-exit ${bt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Kr=rt?{...fo,paymentMethodTypes:[rt]}:null;if(re==="buttons"){let o=Se==="buttons"||Se==="expanding"||Se==="apm-expanding",v=Se==="expanding"||Se==="card"||Se==="collapsing",z=q===void 0?{boxSizing:"border-box",height:ro,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ne=Se==="expanding"||Se==="apm-expanding"?`flopay-buttons-exit ${bt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Se==="collapsing"||Se==="apm-collapsing"?`flopay-buttons-enter ${bt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,L=Se==="expanding"?`flopay-card-enter ${bt}ms cubic-bezier(0, 0, 0.2, 1) both`:Se==="collapsing"?`flopay-card-exit ${bt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return xe("form",{onSubmit:Po,className:C,style:{position:"relative"},children:[d(No,{}),Kt&&d(vn,{status:Kt,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?xs:{},...ne?{animation:ne,pointerEvents:"none"}:{}},children:[ka("flopay-direct-paypal-gate-debug"),Ra("flopay-stripe-gate-debug"),br&&Ze&&xe(cr,{children:[$t&&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(to,{sessionId:e,nonce:t,billingApiUrl:D,email:te.email,clientId:Ze.clientId,environment:Ze.environment,currency:Re.toUpperCase(),isSubscription:Xe,onTokenizedBody:Xt,onComplete:a,onErrorChange:W,onDecline:s,onTechnicalFailure:be,onButtonClick:me,runBeforeButtonClick:sn,isProcessing:K,onLoadStateChange:go,onInitializationStateChange:ho,session:m??null,existingOrderId:$t?.orderId,debug:$e},$t?.orderId??"fresh")]}),vr&&d(Jn,{stripe:B,options:Ue,children:d(Za,{sessionId:e,nonce:t,email:te.email,billingApiUrl:D,onTokenizedBody:Xt,onErrorChange:W,isProcessing:K,onButtonClick:me,onDecline:s,onTechnicalFailure:be,runBeforeButtonClick:sn,onLoadStateChange:ra,placeholderBorderRadius:Vn})}),Cr?d(Jn,{stripe:ot,options:Me,children:d(Qa,{sessionId:e,nonce:t,email:te.email,billingApiUrl:D,intentKind:se>0?"payment":"setup",expressMethods:zr,onTokenizedBody:Xt,onErrorChange:W,onButtonClick:me,onDecline:s,onTechnicalFailure:be,runBeforeButtonClick:sn,onLoadStateChange:aa,placeholderBorderRadius:Vn})}):da?d("div",{style:{height:ro,borderRadius:Vn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,wr&&d(ei,{sessionId:e,nonce:t,email:te.email,billingName:[te.firstName,te.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:D,paymentElementMethods:Ur,stripeInstance:ot,paymentElementBaseOptions:fo,onTokenizedBody:Xt,onErrorChange:W,onButtonClick:me,onDecline:s,runBeforeButtonClick:sn,onLoadStateChange:sa,isProcessing:K,submitButtonColor:Hn,submitButtonBorderRadius:ft,submitButtonStyle:u.submitButton,onExpandApm:_n,expandedApmMethod:rt,themeId:F,buttonAppearance:{backgroundColor:u.cardButton?.backgroundColor,borderColor:u.cardInputBorder,textColor:u.cardButton?.color,borderRadius:Vn}}),y&&d("button",{type:"button",onClick:async()=>{K||!(await sn("card")).proceed||(me?.("card"),an())},disabled:K,style:{width:"100%",...z,...u.cardButton,...qo({themeBundle:T,resolvedPrimaryColor:Hn,resolvedBorderRadius:ft,submitButtonStyle:u.submitButton,explicitPrimaryColor:Vt?.colorPrimary}),fontSize:u.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:K?"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:K?.6:1},onMouseEnter:Z=>{!K&&(T||Vt?.colorPrimary)&&(Z.currentTarget.style.backgroundColor=Li)},onMouseLeave:Z=>{(T||Vt?.colorPrimary)&&(Z.currentTarget.style.backgroundColor=Hn)},onMouseDown:Z=>{Z.currentTarget.style.transform="scale(0.985)"},onMouseUp:Z=>{Z.currentTarget.style.transform="scale(1)"},children:d(tr,{content:q})}),N&&Se==="buttons"&&d(or,{margin:"0.25rem 0",styleOverride:u.errorBanner,children:N})]}),y&&v&&d("div",{style:{gridArea:"1 / 1",...L?{animation:L}:{},...Se==="collapsing"?{pointerEvents:"none"}:{}},children:Sa}),x&&Ia&&rt&&Kr&&ot&&d("div",{style:{gridArea:"1 / 1",...Hr?{animation:Hr}:{},...Se==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:Co,borderRadius:Ro,...Ir,padding:ko},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:gn,style:{display:"inline-flex",alignItems:"center",gap:wo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:u.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...u.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...u.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(nr,{content:j})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:u.titleFontSize??"1.05rem",color:So,paddingRight:80,...u.title},children:`Pay with ${dr(rt)}`})]}),d(Jn,{stripe:ot,options:Kr,children:d(zo,{method:rt,sessionId:e,nonce:t,email:te.email,billingName:[te.firstName,te.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:D,onTokenizedBody:Xt,onErrorChange:W,onDecline:s,onCancel:gn,runBeforeButtonClick:sn,onButtonClick:me,isProcessing:K,submitButtonColor:Hn,submitButtonBorderRadius:ft,submitButtonStyle:u.submitButton,errorText:N})},rt)]})})]})]})}return Ia&&rt&&Kr&&ot&&x?xe("form",{onSubmit:Po,className:C,style:{position:"relative"},children:[d(No,{}),Kt&&d(vn,{status:Kt,errorMessage:N}),d("div",{style:{...Hr?{animation:Hr}:{},...Se==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:Co,borderRadius:Ro,...Ir,padding:ko},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:gn,style:{display:"inline-flex",alignItems:"center",gap:wo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:u.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...u.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...u.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(nr,{content:j})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:u.titleFontSize??"1.05rem",color:So,paddingRight:80,...u.title},children:`Pay with ${dr(rt)}`})]}),d(Jn,{stripe:ot,options:Kr,children:d(zo,{method:rt,sessionId:e,nonce:t,email:te.email,billingName:[te.firstName,te.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:D,onTokenizedBody:Xt,onErrorChange:W,onDecline:s,onCancel:gn,runBeforeButtonClick:sn,onButtonClick:me,isProcessing:K,submitButtonColor:Hn,submitButtonBorderRadius:ft,submitButtonStyle:u.submitButton,errorText:N})},rt)]})})]}):xe("form",{onSubmit:Po,className:C,style:{position:"relative"},children:[d(No,{}),Kt&&d(vn,{status:Kt,errorMessage:N}),xe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ka("flopay-direct-paypal-gate-debug-default"),Ra("flopay-stripe-gate-debug-default"),br&&Ze&&xe(cr,{children:[$t&&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(to,{sessionId:e,nonce:t,billingApiUrl:D,email:te.email,clientId:Ze.clientId,environment:Ze.environment,currency:Re.toUpperCase(),isSubscription:Xe,onTokenizedBody:Xt,onComplete:a,onErrorChange:W,onDecline:s,onTechnicalFailure:be,onButtonClick:me,runBeforeButtonClick:sn,isProcessing:K,onLoadStateChange:go,onInitializationStateChange:ho,session:m??null,existingOrderId:$t?.orderId,debug:$e},$t?.orderId??"fresh")]}),vr&&d(Jn,{stripe:B,options:Ue,children:d(Za,{sessionId:e,nonce:t,email:te.email,billingApiUrl:D,onTokenizedBody:Xt,onErrorChange:W,isProcessing:K,onButtonClick:me,onDecline:s,onTechnicalFailure:be,runBeforeButtonClick:sn,onLoadStateChange:ra,placeholderBorderRadius:Vn})}),Cr&&d(Jn,{stripe:ot,options:Me,children:d(Qa,{sessionId:e,nonce:t,email:te.email,billingApiUrl:D,intentKind:se>0?"payment":"setup",expressMethods:zr,onTokenizedBody:Xt,onErrorChange:W,onButtonClick:me,onDecline:s,onTechnicalFailure:be,runBeforeButtonClick:sn,onLoadStateChange:aa,placeholderBorderRadius:Vn})}),wr&&d(ei,{sessionId:e,nonce:t,email:te.email,billingName:[te.firstName,te.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:D,paymentElementMethods:Ur,stripeInstance:ot,paymentElementBaseOptions:fo,onTokenizedBody:Xt,onErrorChange:W,onButtonClick:me,onDecline:s,runBeforeButtonClick:sn,onLoadStateChange:sa,isProcessing:K,submitButtonColor:Hn,submitButtonBorderRadius:ft,submitButtonStyle:u.submitButton,themeId:F,onExpandApm:_n,expandedApmMethod:rt,buttonAppearance:{backgroundColor:u.cardButton?.backgroundColor,borderColor:u.cardInputBorder,textColor:u.cardButton?.color,borderRadius:Vn}})]}),y&&(xi||_i||Ti)&&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&&Sa]})}import{loadFloPay as si,PaymentAPI as li}from"@flopay/js";import{FloPayError as at,isSetupIntentClientSecret as Ns}from"@flopay/shared";var Fr="card";async function Os(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 zs(e,t,n,i){if(i){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:c??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:r,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:r??null}}function Sn(e,t){return Object.assign(e,{checkoutMethod:t})}function ci(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 Us(e){return e.status==="succeeded"||e.status==="declined"}async function di(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,R=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",R);let C=window.setTimeout(()=>p.abort(),i);try{let E=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:p.signal});if(!E.ok)return{status:"unknown"};let l=await E.json().catch(()=>null);return $s(l)}catch{return{status:"unknown"}}finally{window.clearTimeout(C),e.signal?.removeEventListener("abort",R)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let w=document.createElement("iframe");w.setAttribute("title","Card authentication"),w.setAttribute("allow","payment"),w.tabIndex=0,w.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),w.src=e.nextActionRedirectUrl,s.appendChild(w),document.body.appendChild(s),w.focus();let M=null;try{M=new URL(e.billingApiUrl,window.location.href).origin}catch{M=null}try{let p=await new Promise((R,C)=>{let E=!1,l=0,f=0,S=0,x=!1,h=()=>{window.clearTimeout(l),window.clearInterval(f),window.clearTimeout(S),window.removeEventListener("message",re),w.removeEventListener("load",Y),e.signal?.removeEventListener("abort",ce)},U=async()=>{if(!(E||x)){x=!0;try{let F=await a();if(E||!Us(F))return;E=!0,h(),R(F)}finally{x=!1}}},Y=()=>{window.clearTimeout(S),S=window.setTimeout(()=>{U()},250)},ce=()=>{E||(E=!0,h(),C(new at("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},re=F=>{if(F.source!==w.contentWindow||M&&F.origin!==M)return;let J=F.data;!J||typeof J!="object"||J.source!=="flopay-vault-3ds-return"||E||(E=!0,h(),R(null))};l=window.setTimeout(()=>{E||(E=!0,h(),C(new at("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),f=window.setInterval(()=>{U()},n),w.addEventListener("load",Y),window.addEventListener("message",re),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return p||await a()}finally{s.parentNode?.removeChild(s),c?.isConnected&&c.focus()}}function $s(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function On(e,t="Payment failed. Please try again.",n){let i=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),r=e?.message??t,a=Dn(r)??r;return Sn(new at(a,"api_error",{code:e?.gatewayErrorCode}),i)}function Vo(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ao(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function qs(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 ui(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||ao(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||ao(s)))return s;let c=r.gateways;if(c&&typeof c=="object"){let s=c.stripe;if(s&&typeof s=="object"){let w=s,M=[w.stripeClientSecret,w.clientSecret];for(let p of M)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||ao(p)))return p}}}}async function js({billingApiUrl:e,sessionId:t,nonce:n,responseJson:i}){let r=ui(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 li(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ao(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function ur({billingApiUrl:e,sessionId:t,session:n,nonce:i,tokenizedData:r,returnUrl:a,telemetry:c}){let s=e.replace(/\/+$/,""),w=t??n.id,M=i??n.clientSecret,p=n.customer?.id??n.accountData?.userId??"",R=n.customer?.email??n.accountData?.email??"",C=n.customer?.firstName??n.accountData?.firstName??"",E=n.customer?.lastName??n.accountData?.lastName??"",l=n.customer?.country??n.accountData?.country??void 0,f=n.customer?.zip??n.accountData?.zip??void 0,S=new li(s,c===!1?{telemetry:!1}:void 0),x=await qs(()=>S.processPayment(p,{sessionId:w,nonce:M,tokenizedData:r,accountData:{userId:p,email:R,firstName:C,lastName:E,country:l,zip:f},returnUrl:a??Vo(n)}));if(x.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:Xr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}};let h=await x.json().catch(()=>null);if(h?.type==="paypal_redirect_required"||h?.type==="3ds_required"){let U=ui(h);if(!U)throw new at("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:h.type,threeDSecureToken:U,paymentMethodId:h.paymentMethodId}}if(h?.gatewayErrorCode==="authentication_required"){let U=await js({billingApiUrl:s,sessionId:w,nonce:M,responseJson:h});if(U)return U;throw Sn(new at("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new at(h?.message??"Payment failed. Please try again.","api_error",{code:h?.code??h?.gatewayErrorCode,declineCode:h?.declineCode??h?.gatewayDeclineReason})}async function io(e,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:c,returnUrl:s,telemetry:w}){let M=t?.getRawProvider();if(!M)throw new at("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!i||!e.threeDSecureToken)throw Sn(new at("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let p=Ns(e.threeDSecureToken),R=null,C=e.paymentMethodId,E=await Os(M,e.threeDSecureToken,p);if(E){if(E.error)throw Sn(new at(E.error.message??`Failed to retrieve 3DS ${p?"setup":"payment"} status.`,"api_error",{code:E.error.code}),"card");let f=E.intent;!C&&f?.payment_method&&(typeof f.payment_method=="string"?C=f.payment_method:"id"in f.payment_method&&(C=f.payment_method.id??void 0))}let l=C?await zs(M,e.threeDSecureToken,{payment_method:C,return_url:s??Vo(c)??window.location.href},p):null;if(l){if(l.error)throw Sn(new at(l.error.message??"3DS authentication failed.","api_error",{code:l.error.code}),"card");R=l.intent}else{let f=await M.handleNextAction({clientSecret:e.threeDSecureToken});if(f.error)throw Sn(new at(f.error.message??"3DS authentication failed.","api_error",{code:f.error.code}),"card");R=(p?f.setupIntent:f.paymentIntent)??null}if(R&&(R.status==="requires_capture"||R.status==="succeeded"||R.status==="processing")){let f=await ur({billingApiUrl:r,sessionId:a,session:c,telemetry:w,tokenizedData:{id:R.id,type:"card",threeDSecureActionResultTokenId:R.id},returnUrl:s});return f.type==="success"?{...f.result,paymentIntentId:f.result.paymentIntentId??R.id,paymentMethodId:f.result.paymentMethodId??C}:io(f,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:c,returnUrl:s,telemetry:w})}throw Sn(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 Sn(new at("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:C}=await p.handleNextAction({clientSecret:e.threeDSecureToken});if(C)throw Sn(new at(C.message??"PayPal authorization failed.","api_error",{code:C.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:R}=await p.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Vo(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(R)throw Sn(new at(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new at("Unsupported payment redirect state.","api_error")}function Xn(e){if(e instanceof at){let i=Dn(e.message);return i&&i!==e.message?Object.assign(new at(i,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Dn(t)??t;return new at(n,"api_error")}function so(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 lo({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([si(e,{billingApiUrl:n,locale:i,telemetry:r}),a?si(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 Q,jsxs as Rt}from"react/jsx-runtime";var pr=44,Xo="flopay_checkout_saved_payment_resume",Ko=new Map;function Dr(e){return new Promise(t=>setTimeout(t,e))}function uo(e,t,n){let i=Wr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:gi,enabled:t!==!1});return i.beginCheckout(n),i}function po(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Wo(e,t,n,i,r){let a=uo(e,t,n);a.error({errorCode:i,stage:r,paymentMethodCategory:"unknown",...r==="session_read"?{requestCategory:"session_read"}:{}}),po(a)}function Ks(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 Jo(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function Yo(e){return!e||e.data.stripe?.publishableKey?!1:!!Jo(e)?.clientId}function mr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Ws(){if(!mr())return null;try{let e=window.sessionStorage.getItem(Xo);return e?JSON.parse(e):null}catch{return null}}function mi(e){if(mr())try{window.sessionStorage.setItem(Xo,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Go(){if(mr())try{window.sessionStorage.removeItem(Xo)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Ys(e){if(!mr())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function Gs(e,t,n){if(mr())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(i){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",i)}}function yi(e){if(mr())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function Js(){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 fi(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 Xs(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 Zo({sessionId:e,nonce:t,createSession:n,billingApiUrl:i,telemetry:r,appearance:a,locale:c,loading:s,error:w,onComplete:M,onError:p,onDecline:R,onCountryChange:C,onZipChange:E,showPayPal:l=!0,showStripe:f=!0,showApplePay:S=!0,showGooglePay:x=!0,debug:h=!1,layout:U,theme:Y,buttonsTheme:ce,buttonsStyles:re,cardButtonContent:F,cardBackButtonContent:J,cardTitleContent:$,showSecurityFooter:de,onButtonClick:q,onBeforeButtonClick:j,enableAVS:oe,cardFieldOrder:Be,cardPreFormSlot:me,avsLayout:pe,className:X,initialErrorMessage:ue=null,children:he,checkoutMode:ae,confirmLabel:Fe,renderConfirmButton:ke,onSessionCompleted:Ce}){let k=Vs(i),ee=cn(()=>hi(Y),[Y]),ie=a??ee?.appearance,Oe=n?"embedded_checkout":"standard_checkout",De=he?"custom_layout":U==="buttons"?"buttons_layout":"default_layout",[G,_]=kt(null),[V,se]=kt(null),Re=nn(null),[ht,Ze]=kt(null),Xe=nn(null),[m,$e]=kt(null),[ze,je]=kt(e??""),Ve=e??ze,Yt=n?"":Ve,[vt,It]=kt(!0),[g,we]=kt(null),[qe,it]=kt("full"),[et,tt]=kt(!1),[Ye,Pe]=kt(ue),[Ct,He]=kt(null),[Lt,Et]=kt(null),[dn,Rn]=kt(void 0),[In,$n]=kt(""),[Pt,Nt]=kt(!1),[Ot,Gt]=kt("loading"),[rn,un]=kt(0),H=nn(!1),An=nn(!1),pn=nn(!1),zt=nn(null),nt=cn(()=>({checkoutMode:ae??qe,layout:he?"unknown":U==="buttons"?"buttons":"embedded"}),[ae,he,qe,U]),y=nn(M);y.current=M;let Ie=nn(p);Ie.current=p;let st=nn(R);st.current=R,Bn(()=>{Dt(V)?.setCheckoutContext(nt),ht&&ht!==V&&Dt(ht)?.setCheckoutContext(nt)},[V,ht,nt]);let En=nn(Ce);En.current=Ce;let Ee=Zn(I=>{Gt(I),!(I!=="exhausted"||pn.current)&&(pn.current=!0,Ie.current?.(new At("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Fn=Zn(()=>{Gt("retrying"),un(I=>I+1)},[]);Bn(()=>{Gt("loading"),un(0),pn.current=!1},[Ve]),Bn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:gi,checkout_type:Oe,checkout_layout:De,billing_api_url:k})},[De,Oe,k]);let mn=cn(()=>n?on(n):"",[n]),qn=cn(()=>In===mn?dn:void 0,[dn,In,mn]),yn=cn(()=>n?Mo(n,qn):void 0,[n,qn]),Ut=ae??yn?.checkoutMode??"full",Ft=cn(()=>yn?{...yn,checkoutMode:Ut}:void 0,[yn,Ut]);Bn(()=>{Rn(void 0),$n(mn)},[mn]),Bn(()=>{Pe(ue)},[ue]);let Se=Zn((I,D,N)=>{gt(()=>{st.current?.(Bt(I,D,N))})},[gt]),yt=Zn(async(I,D)=>{Pe(null),Et(null),He("processing");let N=D?.sessionId??I.id,T=Re.current??Xe.current,u=Dt(T),O=T?null:uo(k,r,nt),b={log:A=>{u?u.log(A):O?.log(A)},error:A=>{u?u.error(A):O?.error(A)},terminal:A=>{u?u.terminal(A):O?.terminal(A)},performance:A=>{u?u.performance(A):O?.performance(A)},now:()=>u?.now()??O?.now()??0,elapsed:A=>u?.elapsed(A)??Math.max(0,(O?.now()??A)-A)},Te=b.now(),K=!!(D?.initialAutoProcessingError||D?.initialAutoProcessingPending),Ge=!1,te,jt=()=>{Ge||(Ge=!0,K=!0,te=b.now(),b.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ot=!1,B=()=>{ot||(ot=!0,b.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),b.performance({stage:"processing",durationMs:b.elapsed(Te),durationMode:"machine",paymentMethodCategory:"saved"}),te!==void 0&&b.performance({stage:"recovery",durationMs:b.elapsed(te),durationMode:"machine",paymentMethodCategory:"saved"}))};b.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),b.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),K&&jt();let P;try{let A=ci(D?.initialAutoProcessingError),ye;if(A)jt(),A.type==="paypal_redirect_required"&&zt.current?.publishableKey&&mi({sessionId:N,publishableKey:zt.current.publishableKey,paypalPublishableKey:zt.current.paypalPublishableKey}),ye=await io(A,{flopay:Re.current,paypalFlopay:Xe.current,attempt3DS:D?.attempt3DS,billingApiUrl:k,sessionId:N,session:I,telemetry:!1}),A.type==="paypal_redirect_required"&&Go();else if(D?.initialAutoProcessingPending){let Ue=await new co(k,{telemetry:!1}).waitForCheckoutSessionCompletion(D.initialAutoProcessingPending.sessionId,{initialDelayMs:D.initialAutoProcessingPending.retryAfterMs});if(Ue.data.session?.status!=="complete")throw new At("Automatic payment failed. Please try again.","api_error",{code:Ue.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});ye={status:"succeeded"}}else{if(D?.initialAutoProcessingError)throw On(D.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:D.initialAutoProcessingError.checkoutMethod});if(D?.fromCreateSession)return D?.fallbackToFull&&(it("full"),fi("full")),!1;{let Me=await ur({billingApiUrl:k,sessionId:N,session:I,telemetry:!1});Me.type==="success"?ye=Me.result:(jt(),Me.type==="paypal_redirect_required"&&zt.current?.publishableKey&&mi({sessionId:N,publishableKey:zt.current.publishableKey,paypalPublishableKey:zt.current.paypalPublishableKey}),ye=await io(Me,{flopay:Re.current,paypalFlopay:Xe.current,attempt3DS:D?.attempt3DS,billingApiUrl:k,sessionId:N,session:I,telemetry:!1}),Me.type==="paypal_redirect_required"&&Go())}}N&&ir(N),B(),K&&(b.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),b.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),He("success"),await Dr(Tn),P=()=>y.current?.(ye)}catch(A){let ye=Xn(A),Me=ye.checkoutMethod??Fr;return Pe(ye.message),Et(ye.message),D?.fallbackToFull&&(b.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),it("full"),fi("full")),B(),!!(ye.declineCode||ye.code?.toLowerCase().includes("declin"))?b.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):b.error({errorCode:K?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:K?"recovery":"processing",paymentMethodCategory:"saved"}),gt(()=>Ie.current?.(ye)),Se(Me,ye,{code:ye.code,declineCode:ye.declineCode}),He("error"),await Promise.allSettled([Dr(bn),D?.ensureProvidersReady?D.ensureProvidersReady():Promise.resolve()]),K&&(b.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{B(),O&&po(O),He(null),Et(null)}return gt(P),!0},[Se,gt,Xn,k,r,nt]);Bn(()=>{if(typeof window>"u"||An.current)return;let I=new URLSearchParams(window.location.search),D=I.get("payment_intent_client_secret");if(!D)return;let N=Ws();N&&(An.current=!0,(async()=>{let T,u=0;Pe(null),Et(null),He("processing"),tt(!0);try{if(I.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:O,paypalFlopay:b}=await lo({publishableKey:N.publishableKey,paypalPublishableKey:N.paypalPublishableKey,billingApiUrl:k,locale:c,telemetry:r});T=Dt(b??O),u=T?.now()??0,T?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),T?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Te=(b??O)?.getRawProvider();if(!Te)throw Object.assign(new At("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:K,error:Ge}=await Te.retrievePaymentIntent(D);if(Ge)throw Object.assign(new At(Ge.message??"Failed to retrieve PayPal payment status.","api_error",{code:Ge.code}),{checkoutMethod:"paypal"});let te=Fa(K?.status);if(!K||te==="failed")throw Object.assign(new At("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let jt=typeof K.payment_method=="string"?K.payment_method:K.payment_method?.id,ot=te;if(N.sessionId){let A=(await new co(k,{telemetry:!1}).getUnifiedCheckoutSession(N.sessionId)).data.session;if(A&&A.status!=="complete"){let ye=await ur({billingApiUrl:k,sessionId:N.sessionId,session:A,telemetry:!1,tokenizedData:{id:jt??K.id,type:"card",threeDSecureActionResultTokenId:K.id,isPaypal:!0}});if(ye.type!=="success")throw Object.assign(new At("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});ot=ye.result.status}}N.sessionId&&ir(N.sessionId),T?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),T?.performance({stage:"redirect_resume",durationMs:T.elapsed(u),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),T?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),He("success"),await Dr(Tn),gt(()=>y.current?.({status:ot,paymentIntentId:K.id,paymentMethodId:jt,checkoutMethod:"paypal"}))}catch(O){let b=Xn(O),Te=b.checkoutMethod??"paypal",K=!!(b.declineCode||b.code?.toLowerCase().includes("declin"));if(T)T.performance({stage:"redirect_resume",durationMs:T.elapsed(u),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),K?T.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):T.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(K){let Ge=uo(k,r,nt);Ge.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),po(Ge)}else Wo(k,r,nt,"REDIRECT_RESUME_FAILED","redirect_resume");Pe(b.message),Et(b.message),gt(()=>Ie.current?.(b)),Se(Te,b,{code:b.code,declineCode:b.declineCode}),He("error"),await Dr(bn)}finally{Go(),Js(),He(null),Et(null),tt(!1)}})())},[Se,gt,c,Xn,k,r]);let rt=nn(null);function on(I){let D=JSON.stringify({c:I?.clientId,cur:I?.currency??"",a:{e:I?.account?.email?.trim().toLowerCase()??"",country:I?.account?.country??""},successUrl:I?.successUrl,cancelUrl:I?.cancelUrl,p:I?.products?.map(T=>`${T.type??""}:${T.code??T.providerItemId??T.providerPlanId??""}:${T.totalAmount??""}:${T.overrideAmount??""}:${T.quantity??1}`).sort(),i:I?.items?.map(T=>`${T.code??T.providerItemId??""}:${T.totalAmount??""}:${T.overrideAmount??""}:${T.quantity??1}`).sort(),s:I?.subscriptions?.map(T=>`${T.code??T.providerPlanId??""}:${T.totalAmount??""}:${T.overrideAmount??""}:${T.quantity??1}`).sort(),couponCodes:I?.couponCodes,tagsData:I?.tagsData,utmMetadata:I?.utmMetadata,tokenizedData:I?.tokenizedData,m:I?.checkoutMode??"full"}),N=0;for(let T=0;T<D.length;T++)N=(N<<5)-N+D.charCodeAt(T)|0;return`flopay_session_${Math.abs(N).toString(36)}`}let Jt=cn(()=>Ft?on(Ft):"",[Ft]),bt=nn(Ft);bt.current=Ft,Bn(()=>{je(e??"")},[e]),Bn(()=>{H.current=!1,Pe(ue),Et(null),He(null)},[Jt,ue,e]);async function Ht(I,D){let N=uo(k,r,nt),T=new co(k,{telemetry:!1});try{let u=Ys(D);N.log({name:u?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let O=u?.sid??null,b=null;if(O)try{if(b=await T.getUnifiedCheckoutSession(O,u?.nonce),b.data.session?.status==="complete"){if(La(O))return{sid:O,result:b};yi(D),O=null,b=null}}catch{N.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),yi(D),O=null}if(!O){let Te=N.now();N.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let K={...I,avsCheck:!!oe,avsConfig:typeof oe=="object"?oe:void 0,checkoutType:"embedded_checkout",checkoutLayout:he?"custom_layout":U==="buttons"?"buttons_layout":"default_layout"};try{b=await T.createAndFetchSession(K),N.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),N.performance({stage:"session_create",durationMs:N.now()-Te,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"})}catch(Ge){throw N.performance({stage:"session_create",durationMs:N.now()-Te,durationMode:"machine",requestCategory:"session_create",statusClass:"network_error"}),Ge instanceof At&&Ge.type==="validation_error"?N.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):N.error({errorCode:"CHECKOUT_SESSION_CREATE_FAILED",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Ge}O=b.data.session?.id??"",O&&Gs(D,O,b.data.session?.clientSecret)}return{sid:O??"",result:b}}finally{po(N)}}let wt=Zn(async I=>{let D=bt.current;if(!D)throw new At("createSession is required to bootstrap checkout.","validation_error");let N=Mo(D,I),T=on(N),u=Ko.get(T);u||(u=Ht(N,T),Ko.set(T,u));let O;try{O=await u}finally{Ko.delete(T)}rt.current=T;try{I&&($n(mn),Rn(ot=>Ba(ot,I)));let{sid:b,result:Te}=O;_(Te),Te.data.session&&$e(Te.data.session),b&&je(b);let{publishableKey:K,paypalPublishableKey:Ge}=so(Te),{flopay:te,paypalFlopay:jt}=await lo({publishableKey:K,paypalPublishableKey:Ge,billingApiUrl:k,locale:c,telemetry:r});Re.current=te,se(te),Xe.current=jt,Ze(jt),It(!1)}catch(b){throw rt.current===T&&(rt.current=null),b}return O},[c,k,r,nt]),an=Zn(async I=>{if(!Xs(I)||Pt)return{sessionId:ze,session:m};Nt(!0);try{let D=await wt(I);return{sessionId:D.sid,session:D.result.data.session??null}}finally{Nt(!1)}},[wt,Pt,ze,m]);Bn(()=>{let I=!1;if(we(null),Jt){let T=bt.current;return it(Ut),It(!1),rt.current===Jt?()=>{I=!0}:($e(Aa(T,ae)),(async()=>{let u=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),O=Ut==="auto"&&!H.current&&!u;O&&(Pe(null),Et(null),He("processing"));try{let b=await wt(),Te=b.result.data.session??null;zt.current=so(b.result);let K=Yo(b.result);if(!I&&O&&Te&&!K){H.current=!0,await yt(Te,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:b.result.autoProcessingError,initialAutoProcessingPending:b.result.autoProcessingPending,autoProcessingAttempted:b.result.autoProcessingAttempted,sessionId:b.sid||Te.id});return}!I&&O&&(K&&(H.current=!0),He(null),Et(null))}catch(b){if(I)return;let Te=b instanceof At||typeof b=="object"&&b!==null&&"code"in b?b.code:void 0;if(O&&Te==="session_auto_completed"){H.current=!0,He("success"),await Dr(Tn),I||(gt(()=>{y.current?.({status:"succeeded"})}),He(null),Et(null));return}O&&(He(null),Et(null));let K=b instanceof At?b:new At(b instanceof Error?b.message:"Failed to create session","api_error");we(K)}})(),()=>{I=!0})}It(!0);async function D(){let T=!1;try{let O=await new co(k,{telemetry:!1}).getUnifiedCheckoutSession(Ve,t);if(I)return;_(O);let b=O.data.session??null;if($e(b),!b)throw new At("No session data returned","api_error");if(b.status==="complete"){It(!1),gt(()=>{En.current?.(b.successUrl??"")});return}if(b.status==="expired")throw new At("Checkout session has expired.","api_error",{code:"checkout_session_expired"});T=!0;let Te=ae??b.checkoutMode??"full";it(Te);let K=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ge=Yo(O);if(Te==="auto"&&!H.current&&!K&&!Ge){H.current=!0;let te=N(O);try{if(await yt(b,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>te,sessionId:Ve||b.id}),I)return;await te,I||It(!1);return}catch{if(I)return;await te,I||It(!1);return}}await N(O),I||It(!1)}catch(u){if(I)return;u instanceof At?!T&&!Ks(u)&&Wo(k,r,nt,"NETWORK_REQUEST_FAILED","session_read"):Wo(k,r,nt,"INTERNAL_SDK_ERROR","checkout_mount");let O=u instanceof At?u:new At(u instanceof Error?u.message:"Failed to initialize checkout","api_error");we(O),It(!1)}}async function N(T){let{publishableKey:u,paypalPublishableKey:O}=so(T);zt.current={publishableKey:u,paypalPublishableKey:O};let{flopay:b,paypalFlopay:Te}=await lo({publishableKey:u,paypalPublishableKey:O,billingApiUrl:k,locale:c,telemetry:r});Re.current=b,se(b),Xe.current=Te,Ze(Te)}return D(),()=>{I=!0}},[wt,ae,Jt,Ut,Yt,gt,t,yt]);let fn=Zn(async()=>{if(!(et||!m)){tt(!0),Pe(null);try{await yt(m,{fallbackToFull:!0,sessionId:Ve||m.id})}finally{tt(!1)}}},[Ve,et,yt,m]),_n=Jo(G),gn=Yo(G),Kt=cn(()=>{if(!G||!m||!G.data.stripe?.publishableKey)return;let I={appearance:ie,paymentMethodCreation:"manual",billingApiUrl:k};if(G.data.stripe?.clientSecret)I.clientSecret=G.data.stripe.clientSecret;else{let D=pi(m).total;I.amount=Math.round(D*100)||m.amount,I.currency=m.currency?.toLowerCase()}return I},[G,m,ie,k]),Ke=!!(n&&!he&&U==="buttons"&&j&&Ut==="full"),Wt=cn(()=>({session:m,loading:vt,error:g,checkoutMode:qe,inlineSessionDraft:Ft,applyInlineSessionPatch:Ke?an:void 0,inlineSessionPatchProcessing:Pt}),[m,vt,g,qe,Ft,Ke,an,Pt]),$t=!!n&&U==="buttons"&&!gn&&(!V||!Kt),qt=Ct?Q(vn,{status:Ct,errorMessage:Lt}):null;if(vt){if(s)return Rt(kn,{children:[s,qt]});if(U==="buttons"){let I=ee?.buttonsLayout?.cardButton?.borderRadius??ee?.appearance.variables?.borderRadius??8,D=N=>Q("div",{style:{height:N,borderRadius:I,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Rt(kn,{children:[Rt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[l&&D(pr),f&&(S||x)&&D(pr),f&&D(pr),Q("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),qt]})}return Rt(kn,{children:[Rt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[Q("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),Q("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),qt]})}return g?w?Q(ln.Provider,{value:Wt,children:w(g)}):Q(ln.Provider,{value:Wt,children:Q("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:g.message})}):$t?Rt(kn,{children:[Q(ln.Provider,{value:Wt,children:Q(Qs,{onButtonClick:q,showPayPal:l,showStripe:f,showApplePay:S,showGooglePay:x,theme:Y,buttonsTheme:ce,buttonsStyles:re,cardButtonContent:F,cardBackButtonContent:J,cardTitleContent:$})}),qt]}):gn&&m&&_n?Rt(kn,{children:[Q(ln.Provider,{value:Wt,children:Rt("div",{className:X,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ye&&Q(or,{icon:!1,children:Ye}),Ot==="retrying"&&Q("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ot==="exhausted"&&Rt("div",{role:"alert",children:[Q("div",{children:"PayPal is temporarily unavailable. Please try again."}),Q("button",{type:"button",onClick:Fn,children:"Retry PayPal"})]}),Ot!=="exhausted"&&Q("div",{"aria-hidden":Ot==="retrying"?!0:void 0,style:Ot==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:Q(qa,{sessionId:Ve,nonce:m.clientSecret||void 0,billingApiUrl:k,email:m.customer?.email,clientId:_n.clientId,environment:_n.environment,currency:(m.currency??"usd").toUpperCase(),isSubscription:m.mode==="subscription",onComplete:M,onErrorChange:Pe,onDecline:R,onButtonClick:q,onInitializationStateChange:Ee,allowAutomaticRetry:rn===0,session:m,telemetry:r,telemetryContext:nt,debug:h},`paypal-init-${rn}`)})]})}),qt]}):!V||!Kt?Q(kn,{children:qt}):qe==="confirm"?Rt(kn,{children:[Q(ln.Provider,{value:Wt,children:Q(Yr,{flopay:V,paypalFlopay:ht,options:Kt,children:Rt("div",{className:X,children:[Ye&&Q("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ye}),ke?ke({onConfirm:fn,isProcessing:et}):Q("button",{type:"button",onClick:fn,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"})]})})}),qt]}):Rt(kn,{children:[Q(ln.Provider,{value:Wt,children:Q(Yr,{flopay:V,paypalFlopay:ht,options:Kt,children:he?Rt(kn,{children:[Ye&&Q("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ye}),Q(Zs,{sessionId:Ve,nonce:m?.clientSecret||void 0,billingApiUrl:k,session:m,children:he})]}):Q(jo,{sessionId:Ve,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(pi(m).total*100):0,currency:m?.currency?.toLowerCase()??"usd",onComplete:M,onError:p,onDecline:R,error:Ye,onErrorChange:Pe,showPayPal:l,showStripe:f,enabledPaymentMethods:G?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:G?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:x,layout:U,theme:Y,buttonsTheme:ce,buttonsStyles:re,appearance:ie,cardButtonContent:F,cardBackButtonContent:J,cardTitleContent:$,onButtonClick:q,onBeforeButtonClick:j,enableAVS:oe,...Be?{cardFieldOrder:Be}:{},...me?{cardPreFormSlot:me}:{},avsLayout:pe,country:m?.customer?.country,city:m?.customer?.city,state:m?.customer?.state,onCountryChange:C,onZipChange:E,avsCheck:!!oe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:he?"custom_layout":U==="buttons"?"buttons_layout":"default_layout",className:X,directPaypal:Jo(G),isSubscription:m?.mode==="subscription",session:m,debug:h})})}),qt]})}function Zs({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:r}){return Q(kn,{children:Ho.Children.map(r,a=>{if(!Ho.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:Ho.cloneElement(a,s)})})}function Qs({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:i,showGooglePay:r,theme:a,buttonsTheme:c,buttonsStyles:s,cardButtonContent:w,cardBackButtonContent:M,cardTitleContent:p}){let[R,C]=kt(!1),E=cn(()=>hi(a),[a]),l=cn(()=>{let h=E?.buttonsLayout??Hs(c);return s?{...h,...s,cardButton:{...h.cardButton,...s.cardButton},cardFormContainer:{...h.cardFormContainer,...s.cardFormContainer},backButton:{...h.backButton,...s.backButton},backButtonIcon:{...h.backButtonIcon,...s.backButtonIcon},submitButton:{...h.submitButton,...s.submitButton},title:{...h.title,...s.title}}:h},[E,c,s]),f=E?.buttonsLayout?.cardButton?.borderRadius??E?.appearance.variables?.borderRadius??8,S=h=>Q("div",{style:{height:h,borderRadius:f,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),x=w===void 0?{boxSizing:"border-box",height:pr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(R){let h=l.cardInputBorder??"#e5e7eb",U=l.cardInputBackground??"white",Y=er(M),ce=er(p);return Rt("div",{style:{backgroundColor:l.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...l.cardFormContainer},children:[Rt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Rt("button",{type:"button",onClick:()=>C(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Y?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...l.backButton},children:[Q("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...l.backButtonIcon},children:Q("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:Q("path",{d:"M15 18l-6-6 6-6"})})}),Q(nr,{content:M})]}),ce?Q("div",{style:{flex:1}}):Q("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...l.title},children:Q(_r,{content:p})})]}),Q("div",{style:{backgroundColor:U,border:`1px solid ${h}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:Q("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Rt("div",{style:{display:"flex"},children:[Q("div",{style:{flex:1,backgroundColor:U,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomLeftRadius:8,padding:12,height:45},children:Q("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Q("div",{style:{flex:1,backgroundColor:U,borderTop:"none",borderRight:`1px solid ${h}`,borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomRightRadius:8,padding:12,height:45},children:Q("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),Q("div",{style:{backgroundColor:U,border:`1px solid ${h}`,borderRadius:8,marginTop:8,padding:12,height:45},children:Q("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Q("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...l.submitButton,opacity:.5}}),Q("style",{children:`
|
|
38
|
+
`}),kr&&Yt&&xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:y?-2:0},children:[xe("button",{type:"button",onClick:gn,style:{display:"inline-flex",alignItems:"center",gap:wo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:u.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...u.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...u.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(nr,{content:V})]}),ba?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:u.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...u.title},children:d(xr,{content:oe})})]}),!kr&&!ba&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ko,order:y?-3:0,...u.title},children:d(xr,{content:oe})}),K&&d("div",{style:{order:y?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let o=$e,v=(N=!1)=>({backgroundColor:Ir,border:`1px solid ${jn(N)}`,borderRadius:yt,marginTop:"0.5rem",padding:"10px"}),z=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...wa}),ne=ys(o);return xe(cr,{children:[_e(K.address_line_1,o)&&d("div",{style:v(Ee.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:N=>{Lt.current=N.target.value,Pe(N.target.value)},disabled:W,required:!0,"data-testid":"flopay-address-line1",style:z()})}),_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:vt,onChange:N=>{Wt.current=N.target.value,Ve(N.target.value)},disabled:W,"data-testid":"flopay-address-line2",style:z()})}),(_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:Ir,borderTop:`1px solid ${jn(Ee.city)}`,borderRight:`1px solid ${jn(Ee.city)}`,borderBottom:`1px solid ${jn(Ee.city)}`,borderLeft:`1px solid ${jn(Ee.city)}`,padding:"10px",borderTopLeftRadius:yt,borderBottomLeftRadius:yt,..._e(K.state,o)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:yt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Ft,onChange:N=>{rn.current=N.target.value,It(N.target.value)},disabled:W,required:!0,"data-testid":"flopay-city",style:z()})}),_e(K.state,o)&&d("div",{style:{flex:1,backgroundColor:Ir,border:`1px solid ${jn(Ee.state)}`,padding:"10px",borderTopRightRadius:yt,borderBottomRightRadius:yt,..._e(K.city,o)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:yt}},children:ne?xe("select",{id:"flopay-billing-state",name:"billing-state",value:un,onChange:N=>{pn.current=N.target.value,Rn(N.target.value)},disabled:W,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...z(),cursor:"pointer"},children:[d("option",{value:"",children:Va(o)}),ne.map(N=>d("option",{value:N.code,children:N.name},N.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Va(o),autoComplete:"billing address-level1",value:un,onChange:N=>{pn.current=N.target.value,Rn(N.target.value)},disabled:W,required:!0,"data-testid":"flopay-state",style:z()})})]}),(_e(K.country,o)||_e(K.postal_code,o))&&xe("div",{style:{display:"flex",flexDirection:ae==="column"?"column":"row",gap:ae==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[_e(K.country,o)&&d("div",{style:{flex:ae==="row"?1:void 0,backgroundColor:Ir,borderTop:`1px solid ${Rr}`,borderRight:`1px solid ${Rr}`,borderBottom:`1px solid ${Rr}`,borderLeft:`1px solid ${Rr}`,padding:"10px",...ae==="row"&&_e(K.postal_code,o)?{borderRadius:"0",borderTopLeftRadius:yt,borderBottomLeftRadius:yt,borderRight:"none"}:{borderRadius:yt}},children:d("select",{id:"flopay-billing-country",name:"billing-country",value:$e,onChange:N=>{Dt.current=N.target.value,st(N.target.value),Ne?.(N.target.value),pn.current="",Rn("")},disabled:W,autoComplete:"billing country","data-testid":"flopay-country",style:{...z(),cursor:"pointer"},children:fs.map(N=>xe("option",{value:N.code,children:[N.flag," ",N.name]},N.code))})}),_e(K.postal_code,o)&&d("div",{style:{flex:ae==="row"?1:void 0,backgroundColor:Ir,border:`1px solid ${Fi}`,padding:"10px",...ae==="row"&&_e(K.country,o)?{borderRadius:"0",borderTopRightRadius:yt,borderBottomRightRadius:yt}:{borderRadius:yt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:zo($e),autoComplete:"billing postal-code",value:Qe,onChange:N=>{ht.current=N.target.value,et(N.target.value),De?.(N.target.value)},onBlur:()=>fn(!0),disabled:W,required:lt.required,"aria-invalid":Vr||void 0,"aria-describedby":Vr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:z()})})]}),Vr&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Co,...wa,fontSize:"0.75rem"},children:lt.empty?`${zo(o)} is required`:Fs(o)})]})})()}),y&&he&&d("div",{style:{order:-2,width:"100%"},children:he}),y&&zi,O&&d(or,{margin:"0.75rem 0",styleOverride:u.errorBanner,children:O})]}),Hr={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"},Ra=o=>Ue?!w||!ot?d("pre",{"data-testid":o,style:Hr,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":o,style:Hr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${w}`,` directPaypalConfigured=${ot}`,` inAppBrowserDetected=${String(qr)}`,` shouldRenderDirectPayPal=${vr}`,` shouldRenderStripePayPal=${Cr}`,` hasPaypalStripeInstance=${!!A}`].join(`
|
|
39
|
+
`)}):null,Ia=o=>Ue?!T||!rt?d("pre",{"data-testid":o,style:Hr,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":o,style:Hr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${T}`,` currency=${ke}`,` amountInCents=${P}`,` enabledPaymentMethods: ${JSON.stringify(h??[])}`,` enabledPaymentMethodsProvided=${Pr}`,` hasEnabledMethods=${Or}`,` expressMethods: ${JSON.stringify(zr)}`,` walletExpressMethods: ${JSON.stringify(Ur)}`,` paymentElementMethods: ${JSON.stringify(br)}`,` paymentElementMethodsForCurrency: ${JSON.stringify($r)}`,` hasStripeInstance=${!!rt}`,` shouldRenderWallets=${Sr}`,` shouldRenderPaymentElement=${wr}`].join(`
|
|
40
|
+
`)}):null,Ea=Se==="apm-expanding"||Se==="apm-form"||Se==="apm-collapsing",Kr=Se==="apm-expanding"?`flopay-card-enter ${Pt}ms cubic-bezier(0, 0, 0.2, 1) both`:Se==="apm-collapsing"?`flopay-card-exit ${Pt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Wr=nt?{...go,paymentMethodTypes:[nt]}:null;if(re==="buttons"){let o=Se==="buttons"||Se==="expanding"||Se==="apm-expanding",v=Se==="expanding"||Se==="card"||Se==="collapsing",z=j===void 0?{boxSizing:"border-box",height:oo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ne=Se==="expanding"||Se==="apm-expanding"?`flopay-buttons-exit ${Pt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Se==="collapsing"||Se==="apm-collapsing"?`flopay-buttons-enter ${Pt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,N=Se==="expanding"?`flopay-card-enter ${Pt}ms cubic-bezier(0, 0, 0.2, 1) both`:Se==="collapsing"?`flopay-card-exit ${Pt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return xe("form",{onSubmit:bo,className:C,style:{position:"relative"},children:[d(Oo,{}),Vt&&d(vn,{status:Vt,errorMessage:O}),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?Ms:{},...ne?{animation:ne,pointerEvents:"none"}:{}},children:[Ra("flopay-direct-paypal-gate-debug"),Ia("flopay-stripe-gate-debug"),vr&&Xe&&xe(cr,{children:[zt&&d("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),d(no,{sessionId:e,nonce:t,billingApiUrl:L,email:te.email,clientId:Xe.clientId,environment:Xe.environment,currency:ke.toUpperCase(),isSubscription:Je,onTokenizedBody:Xt,onComplete:a,onErrorChange:I,onDecline:s,onTechnicalFailure:ue,onButtonClick:fe,runBeforeButtonClick:ln,isProcessing:W,onLoadStateChange:ho,onInitializationStateChange:Po,session:m??null,existingOrderId:zt?.orderId,debug:Ue},zt?.orderId??"fresh")]}),Cr&&d(Jn,{stripe:A,options:sn,children:d(Qa,{sessionId:e,nonce:t,email:te.email,billingApiUrl:L,onTokenizedBody:Xt,onErrorChange:I,isProcessing:W,onButtonClick:fe,onDecline:s,onTechnicalFailure:ue,runBeforeButtonClick:ln,onLoadStateChange:oa,placeholderBorderRadius:Vn})}),Sr?d(Jn,{stripe:rt,options:ze,children:d(ei,{sessionId:e,nonce:t,email:te.email,billingApiUrl:L,intentKind:se>0?"payment":"setup",expressMethods:Ur,onTokenizedBody:Xt,onErrorChange:I,onButtonClick:fe,onDecline:s,onTechnicalFailure:ue,runBeforeButtonClick:ln,onLoadStateChange:ia,placeholderBorderRadius:Vn})}):ua?d("div",{style:{height:oo,borderRadius:Vn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,wr&&d(ti,{sessionId:e,nonce:t,email:te.email,billingName:[te.firstName,te.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:L,paymentElementMethods:$r,stripeInstance:rt,paymentElementBaseOptions:go,onTokenizedBody:Xt,onErrorChange:I,onButtonClick:fe,onDecline:s,runBeforeButtonClick:ln,onLoadStateChange:la,isProcessing:W,submitButtonColor:Hn,submitButtonBorderRadius:yt,submitButtonStyle:u.submitButton,onExpandApm:_n,expandedApmMethod:nt,themeId:D,buttonAppearance:{backgroundColor:u.cardButton?.backgroundColor,borderColor:u.cardInputBorder,textColor:u.cardButton?.color,borderRadius:Vn}}),y&&d("button",{type:"button",onClick:async()=>{W||!(await ln("card")).proceed||(fe?.("card"),an())},disabled:W,style:{width:"100%",...z,...u.cardButton,...jo({themeBundle:M,resolvedPrimaryColor:Hn,resolvedBorderRadius:yt,submitButtonStyle:u.submitButton,explicitPrimaryColor:qt?.colorPrimary}),fontSize:u.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:W?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:W?.6:1},onMouseEnter:Z=>{!W&&(M||qt?.colorPrimary)&&(Z.currentTarget.style.backgroundColor=Ni)},onMouseLeave:Z=>{(M||qt?.colorPrimary)&&(Z.currentTarget.style.backgroundColor=Hn)},onMouseDown:Z=>{Z.currentTarget.style.transform="scale(0.985)"},onMouseUp:Z=>{Z.currentTarget.style.transform="scale(1)"},children:d(tr,{content:j})}),O&&Se==="buttons"&&d(or,{margin:"0.25rem 0",styleOverride:u.errorBanner,children:O})]}),y&&v&&d("div",{style:{gridArea:"1 / 1",...N?{animation:N}:{},...Se==="collapsing"?{pointerEvents:"none"}:{}},children:ka}),T&&Ea&&nt&&Wr&&rt&&d("div",{style:{gridArea:"1 / 1",...Kr?{animation:Kr}:{},...Se==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:So,borderRadius:Io,...Er,padding:Ro},children:[xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[xe("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:hn,style:{display:"inline-flex",alignItems:"center",gap:wo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:u.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...u.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...u.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(nr,{content:V})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:u.titleFontSize??"1.05rem",color:ko,paddingRight:80,...u.title},children:`Pay with ${dr(nt)}`})]}),d(Jn,{stripe:rt,options:Wr,children:d(Uo,{method:nt,sessionId:e,nonce:t,email:te.email,billingName:[te.firstName,te.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:L,onTokenizedBody:Xt,onErrorChange:I,onDecline:s,onCancel:hn,runBeforeButtonClick:ln,onButtonClick:fe,isProcessing:W,submitButtonColor:Hn,submitButtonBorderRadius:yt,submitButtonStyle:u.submitButton,errorText:O})},nt)]})})]})]})}return Ea&&nt&&Wr&&rt&&T?xe("form",{onSubmit:bo,className:C,style:{position:"relative"},children:[d(Oo,{}),Vt&&d(vn,{status:Vt,errorMessage:O}),d("div",{style:{...Kr?{animation:Kr}:{},...Se==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:So,borderRadius:Io,...Er,padding:Ro},children:[xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[xe("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:hn,style:{display:"inline-flex",alignItems:"center",gap:wo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:u.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...u.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...u.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(nr,{content:V})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:u.titleFontSize??"1.05rem",color:ko,paddingRight:80,...u.title},children:`Pay with ${dr(nt)}`})]}),d(Jn,{stripe:rt,options:Wr,children:d(Uo,{method:nt,sessionId:e,nonce:t,email:te.email,billingName:[te.firstName,te.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:L,onTokenizedBody:Xt,onErrorChange:I,onDecline:s,onCancel:hn,runBeforeButtonClick:ln,onButtonClick:fe,isProcessing:W,submitButtonColor:Hn,submitButtonBorderRadius:yt,submitButtonStyle:u.submitButton,errorText:O})},nt)]})})]}):xe("form",{onSubmit:bo,className:C,style:{position:"relative"},children:[d(Oo,{}),Vt&&d(vn,{status:Vt,errorMessage:O}),xe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ra("flopay-direct-paypal-gate-debug-default"),Ia("flopay-stripe-gate-debug-default"),vr&&Xe&&xe(cr,{children:[zt&&d("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),d(no,{sessionId:e,nonce:t,billingApiUrl:L,email:te.email,clientId:Xe.clientId,environment:Xe.environment,currency:ke.toUpperCase(),isSubscription:Je,onTokenizedBody:Xt,onComplete:a,onErrorChange:I,onDecline:s,onTechnicalFailure:ue,onButtonClick:fe,runBeforeButtonClick:ln,isProcessing:W,onLoadStateChange:ho,onInitializationStateChange:Po,session:m??null,existingOrderId:zt?.orderId,debug:Ue},zt?.orderId??"fresh")]}),Cr&&d(Jn,{stripe:A,options:sn,children:d(Qa,{sessionId:e,nonce:t,email:te.email,billingApiUrl:L,onTokenizedBody:Xt,onErrorChange:I,isProcessing:W,onButtonClick:fe,onDecline:s,onTechnicalFailure:ue,runBeforeButtonClick:ln,onLoadStateChange:oa,placeholderBorderRadius:Vn})}),Sr&&d(Jn,{stripe:rt,options:ze,children:d(ei,{sessionId:e,nonce:t,email:te.email,billingApiUrl:L,intentKind:se>0?"payment":"setup",expressMethods:Ur,onTokenizedBody:Xt,onErrorChange:I,onButtonClick:fe,onDecline:s,onTechnicalFailure:ue,runBeforeButtonClick:ln,onLoadStateChange:ia,placeholderBorderRadius:Vn})}),wr&&d(ti,{sessionId:e,nonce:t,email:te.email,billingName:[te.firstName,te.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:L,paymentElementMethods:$r,stripeInstance:rt,paymentElementBaseOptions:go,onTokenizedBody:Xt,onErrorChange:I,onButtonClick:fe,onDecline:s,runBeforeButtonClick:ln,onLoadStateChange:la,isProcessing:W,submitButtonColor:Hn,submitButtonBorderRadius:yt,submitButtonStyle:u.submitButton,themeId:D,onExpandApm:_n,expandedApmMethod:nt,buttonAppearance:{backgroundColor:u.cardButton?.backgroundColor,borderColor:u.cardInputBorder,textColor:u.cardButton?.color,borderRadius:Vn}})]}),y&&(Ti||xi||Mi)&&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&&ka]})}import{loadFloPay as li,PaymentAPI as ci}from"@flopay/js";import{FloPayError as it,isSetupIntentClientSecret as zs}from"@flopay/shared";var Dr="card";async function Us(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 $s(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 di(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 qs(e){return e.status==="succeeded"||e.status==="declined"}async function ui(e){if(typeof document>"u"||typeof window>"u")throw new it("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new it("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,i=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let p=new AbortController,R=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",R);let C=window.setTimeout(()=>p.abort(),i);try{let _=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:p.signal});if(!_.ok)return{status:"unknown"};let l=await _.json().catch(()=>null);return js(l)}catch{return{status:"unknown"}}finally{window.clearTimeout(C),e.signal?.removeEventListener("abort",R)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let S=document.createElement("iframe");S.setAttribute("title","Card authentication"),S.setAttribute("allow","payment"),S.tabIndex=0,S.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),S.src=e.nextActionRedirectUrl,s.appendChild(S),document.body.appendChild(s),S.focus();let B=null;try{B=new URL(e.billingApiUrl,window.location.href).origin}catch{B=null}try{let p=await new Promise((R,C)=>{let _=!1,l=0,f=0,w=0,T=!1,h=()=>{window.clearTimeout(l),window.clearInterval(f),window.clearTimeout(w),window.removeEventListener("message",re),S.removeEventListener("load",Y),e.signal?.removeEventListener("abort",le)},$=async()=>{if(!(_||T)){T=!0;try{let D=await a();if(_||!qs(D))return;_=!0,h(),R(D)}finally{T=!1}}},Y=()=>{window.clearTimeout(w),w=window.setTimeout(()=>{$()},250)},le=()=>{_||(_=!0,h(),C(new it("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},re=D=>{if(D.source!==S.contentWindow||B&&D.origin!==B)return;let J=D.data;!J||typeof J!="object"||J.source!=="flopay-vault-3ds-return"||_||(_=!0,h(),R(null))};l=window.setTimeout(()=>{_||(_=!0,h(),C(new it("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),f=window.setInterval(()=>{$()},n),S.addEventListener("load",Y),window.addEventListener("message",re),e.signal?.addEventListener("abort",le),e.signal?.aborted&&le()});return p||await a()}finally{s.parentNode?.removeChild(s),c?.isConnected&&c.focus()}}function js(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function On(e,t="Payment failed. Please try again.",n){let i=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),r=e?.message??t,a=Dn(r)??r;return wn(new it(a,"api_error",{code:e?.gatewayErrorCode}),i)}function Ho(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function io(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Vs(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 pi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||io(r)))return r;let i=e?.data;if(i&&typeof i=="object"){let r=i,a=[r.threeDSecureToken,r.clientSecret,r.stripeClientSecret,r.id];for(let s of a)if(typeof s=="string"&&s.length>0&&(!t?.requirePaymentIntentClientSecret||io(s)))return s;let c=r.gateways;if(c&&typeof c=="object"){let s=c.stripe;if(s&&typeof s=="object"){let S=s,B=[S.stripeClientSecret,S.clientSecret];for(let p of B)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||io(p)))return p}}}}async function Hs({billingApiUrl:e,sessionId:t,nonce:n,responseJson:i}){let r=pi(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 ci(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(io(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function ur({billingApiUrl:e,sessionId:t,session:n,nonce:i,tokenizedData:r,returnUrl:a,telemetry:c}){let s=e.replace(/\/+$/,""),S=t??n.id,B=i??n.clientSecret,p=n.customer?.id??n.accountData?.userId??"",R=n.customer?.email??n.accountData?.email??"",C=n.customer?.firstName??n.accountData?.firstName??"",_=n.customer?.lastName??n.accountData?.lastName??"",l=n.customer?.country??n.accountData?.country??void 0,f=n.customer?.zip??n.accountData?.zip??void 0,w=new ci(s,c===!1?{telemetry:!1}:void 0),T=await Vs(()=>w.processPayment(p,{sessionId:S,nonce:B,tokenizedData:r,accountData:{userId:p,email:R,firstName:C,lastName:_,country:l,zip:f},returnUrl:a??Ho(n)}));if(T.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:Zr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}};let h=await T.json().catch(()=>null);if(h?.type==="paypal_redirect_required"||h?.type==="3ds_required"){let $=pi(h);if(!$)throw new it("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:h.type,threeDSecureToken:$,paymentMethodId:h.paymentMethodId}}if(h?.gatewayErrorCode==="authentication_required"){let $=await Hs({billingApiUrl:s,sessionId:S,nonce:B,responseJson:h});if($)return $;throw wn(new it("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new it(h?.message??"Payment failed. Please try again.","api_error",{code:h?.code??h?.gatewayErrorCode,declineCode:h?.declineCode??h?.gatewayDeclineReason})}async function so(e,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:c,returnUrl:s,telemetry:S}){let B=t?.getRawProvider();if(!B)throw new it("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!i||!e.threeDSecureToken)throw wn(new it("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let p=zs(e.threeDSecureToken),R=null,C=e.paymentMethodId,_=await Us(B,e.threeDSecureToken,p);if(_){if(_.error)throw wn(new it(_.error.message??`Failed to retrieve 3DS ${p?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let f=_.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 $s(B,e.threeDSecureToken,{payment_method:C,return_url:s??Ho(c)??window.location.href},p):null;if(l){if(l.error)throw wn(new it(l.error.message??"3DS authentication failed.","api_error",{code:l.error.code}),"card");R=l.intent}else{let f=await B.handleNextAction({clientSecret:e.threeDSecureToken});if(f.error)throw wn(new it(f.error.message??"3DS authentication failed.","api_error",{code:f.error.code}),"card");R=(p?f.setupIntent:f.paymentIntent)??null}if(R&&(R.status==="requires_capture"||R.status==="succeeded"||R.status==="processing")){let f=await ur({billingApiUrl:r,sessionId:a,session:c,telemetry:S,tokenizedData:{id:R.id,type:"card",threeDSecureActionResultTokenId:R.id},returnUrl:s});return f.type==="success"?{...f.result,paymentIntentId:f.result.paymentIntentId??R.id,paymentMethodId:f.result.paymentMethodId??C}:so(f,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:c,returnUrl:s,telemetry:S})}throw wn(new it("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let p=(n??t)?.getRawProvider();if(!p)throw wn(new it("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:C}=await p.handleNextAction({clientSecret:e.threeDSecureToken});if(C)throw wn(new it(C.message??"PayPal authorization failed.","api_error",{code:C.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:R}=await p.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Ho(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(R)throw wn(new it(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new it("Unsupported payment redirect state.","api_error")}function Xn(e){if(e instanceof it){let i=Dn(e.message);return i&&i!==e.message?Object.assign(new it(i,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Dn(t)??t;return new it(n,"api_error")}function lo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new it("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function co({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:i,telemetry:r}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[c,s]=await Promise.all([li(e,{billingApiUrl:n,locale:i,telemetry:r}),a?li(t,{billingApiUrl:n,locale:i,telemetry:r}).catch(S=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",S),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?a?s:c:null}}import{Fragment as kn,jsx as Q,jsxs as kt}from"react/jsx-runtime";var pr=44,Zo="flopay_checkout_saved_payment_resume",Wo=new Map;function Lr(e){return new Promise(t=>setTimeout(t,e))}function po(e,t,n){let i=Yr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:hi,enabled:t!==!1});return i.beginCheckout(n),i}function mo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Yo(e,t,n,i,r){let a=po(e,t,n);a.error({errorCode:i,stage:r,paymentMethodCategory:"unknown",...r==="session_read"?{requestCategory:"session_read"}:{}}),mo(a)}function Ys(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 Xo(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function Go(e){return!e||e.data.stripe?.publishableKey?!1:!!Xo(e)?.clientId}function mr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Gs(){if(!mr())return null;try{let e=window.sessionStorage.getItem(Zo);return e?JSON.parse(e):null}catch{return null}}function yi(e){if(mr())try{window.sessionStorage.setItem(Zo,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Jo(){if(mr())try{window.sessionStorage.removeItem(Zo)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Js(e){if(!mr())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function Xs(e,t,n){if(mr())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(i){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",i)}}function fi(e){if(mr())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function Zs(){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 gi(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 Qs(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 Qo({sessionId:e,nonce:t,createSession:n,billingApiUrl:i,telemetry:r,appearance:a,locale:c,loading:s,error:S,onComplete:B,onError:p,onDecline:R,onCountryChange:C,onZipChange:_,showPayPal:l=!0,showStripe:f=!0,showApplePay:w=!0,showGooglePay:T=!0,debug:h=!1,layout:$,theme:Y,buttonsTheme:le,buttonsStyles:re,cardButtonContent:D,cardBackButtonContent:J,cardTitleContent:q,showSecurityFooter:ce,onButtonClick:j,onBeforeButtonClick:V,enableAVS:oe,cardFieldOrder:Be,cardPreFormSlot:fe,avsLayout:me,className:X,initialErrorMessage:de=null,children:he,checkoutMode:ae,confirmLabel:Fe,renderConfirmButton:we,onSessionCompleted:ve}){let k=Ks(i),ee=dn(()=>Pi(Y),[Y]),ie=a??ee?.appearance,Ne=n?"embedded_checkout":"standard_checkout",De=he?"custom_layout":$==="buttons"?"buttons_layout":"default_layout",[G,x]=wt(null),[H,se]=wt(null),ke=nn(null),[gt,Xe]=wt(null),Je=nn(null),[m,Ue]=wt(null),[Oe,qe]=wt(e??""),je=e??Oe,Kt=n?"":je,[bt,Rt]=wt(!0),[g,Ce]=wt(null),[$e,st]=wt("full"),[Qe,et]=wt(!1),[We,Pe]=wt(de),[vt,Ve]=wt(null),[Ft,It]=wt(null),[un,Rn]=wt(void 0),[In,$n]=wt(""),[ht,Dt]=wt(!1),[Lt,Wt]=wt("loading"),[rn,pn]=wt(0),K=nn(!1),An=nn(!1),mn=nn(!1),Nt=nn(null),tt=dn(()=>({checkoutMode:ae??$e,layout:he?"unknown":$==="buttons"?"buttons":"embedded"}),[ae,he,$e,$]),y=nn(B);y.current=B;let Ie=nn(p);Ie.current=p;let lt=nn(R);lt.current=R,Bn(()=>{At(H)?.setCheckoutContext(tt),gt&>!==H&&At(gt)?.setCheckoutContext(tt)},[H,gt,tt]);let En=nn(ve);En.current=ve;let Ee=Zn(E=>{Wt(E),!(E!=="exhausted"||mn.current)&&(mn.current=!0,Ie.current?.(new Mt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Fn=Zn(()=>{Wt("retrying"),pn(E=>E+1)},[]);Bn(()=>{Wt("loading"),pn(0),mn.current=!1},[je]),Bn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:hi,checkout_type:Ne,checkout_layout:De,billing_api_url:k})},[De,Ne,k]);let yn=dn(()=>n?on(n):"",[n]),qn=dn(()=>In===yn?un:void 0,[un,In,yn]),fn=dn(()=>n?Bo(n,qn):void 0,[n,qn]),Ot=ae??fn?.checkoutMode??"full",Bt=dn(()=>fn?{...fn,checkoutMode:Ot}:void 0,[fn,Ot]);Bn(()=>{Rn(void 0),$n(yn)},[yn]),Bn(()=>{Pe(de)},[de]);let Se=Zn((E,L,O)=>{ft(()=>{lt.current?.(Tt(E,L,O))})},[ft]),mt=Zn(async(E,L)=>{Pe(null),It(null),Ve("processing");let O=L?.sessionId??E.id,M=ke.current??Je.current,u=At(M),U=M?null:po(k,r,tt),b={log:F=>{u?u.log(F):U?.log(F)},error:F=>{u?u.error(F):U?.error(F)},terminal:F=>{u?u.terminal(F):U?.terminal(F)},performance:F=>{u?u.performance(F):U?.performance(F)},now:()=>u?.now()??U?.now()??0,elapsed:F=>u?.elapsed(F)??Math.max(0,(U?.now()??F)-F)},Te=b.now(),W=!!(L?.initialAutoProcessingError||L?.initialAutoProcessingPending),Ye=!1,te,$t=()=>{Ye||(Ye=!0,W=!0,te=b.now(),b.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},rt=!1,A=()=>{rt||(rt=!0,b.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),b.performance({stage:"processing",durationMs:b.elapsed(Te),durationMode:"machine",paymentMethodCategory:"saved"}),te!==void 0&&b.performance({stage:"recovery",durationMs:b.elapsed(te),durationMode:"machine",paymentMethodCategory:"saved"}))};b.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),b.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),W&&$t();let P;try{let F=di(L?.initialAutoProcessingError),ye;if(F)$t(),F.type==="paypal_redirect_required"&&Nt.current?.publishableKey&&yi({sessionId:O,publishableKey:Nt.current.publishableKey,paypalPublishableKey:Nt.current.paypalPublishableKey}),ye=await so(F,{flopay:ke.current,paypalFlopay:Je.current,attempt3DS:L?.attempt3DS,billingApiUrl:k,sessionId:O,session:E,telemetry:!1}),F.type==="paypal_redirect_required"&&Jo();else if(L?.initialAutoProcessingPending){let ze=await new uo(k,{telemetry:!1}).waitForCheckoutSessionCompletion(L.initialAutoProcessingPending.sessionId,{initialDelayMs:L.initialAutoProcessingPending.retryAfterMs});if(ze.data.session?.status!=="complete")throw new Mt("Automatic payment failed. Please try again.","api_error",{code:ze.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});ye={status:"succeeded"}}else{if(L?.initialAutoProcessingError)throw On(L.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:L.initialAutoProcessingError.checkoutMethod});if(L?.fromCreateSession)return L?.fallbackToFull&&(st("full"),gi("full")),!1;{let Me=await ur({billingApiUrl:k,sessionId:O,session:E,telemetry:!1});Me.type==="success"?ye=Me.result:($t(),Me.type==="paypal_redirect_required"&&Nt.current?.publishableKey&&yi({sessionId:O,publishableKey:Nt.current.publishableKey,paypalPublishableKey:Nt.current.paypalPublishableKey}),ye=await so(Me,{flopay:ke.current,paypalFlopay:Je.current,attempt3DS:L?.attempt3DS,billingApiUrl:k,sessionId:O,session:E,telemetry:!1}),Me.type==="paypal_redirect_required"&&Jo())}}O&&ir(O),A(),W&&(b.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),b.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Ve("success"),await Lr(Tn),P=()=>y.current?.(ye)}catch(F){let ye=Xn(F),Me=ye.checkoutMethod??Dr;return Pe(ye.message),It(ye.message),L?.fallbackToFull&&(b.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),st("full"),gi("full")),A(),!!(ye.declineCode||ye.code?.toLowerCase().includes("declin"))?b.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):b.error({errorCode:W?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:W?"recovery":"processing",paymentMethodCategory:"saved"}),ft(()=>Ie.current?.(ye)),Se(Me,ye,{code:ye.code,declineCode:ye.declineCode}),Ve("error"),await Promise.allSettled([Lr(bn),L?.ensureProvidersReady?L.ensureProvidersReady():Promise.resolve()]),W&&(b.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{A(),U&&mo(U),Ve(null),It(null)}return ft(P),!0},[Se,ft,Xn,k,r,tt]);Bn(()=>{if(typeof window>"u"||An.current)return;let E=new URLSearchParams(window.location.search),L=E.get("payment_intent_client_secret");if(!L)return;let O=Gs();O&&(An.current=!0,(async()=>{let M,u=0;Pe(null),It(null),Ve("processing"),et(!0);try{if(E.get("redirect_status")==="failed")throw Object.assign(new Mt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:U,paypalFlopay:b}=await co({publishableKey:O.publishableKey,paypalPublishableKey:O.paypalPublishableKey,billingApiUrl:k,locale:c,telemetry:r});M=At(b??U),u=M?.now()??0,M?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),M?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Te=(b??U)?.getRawProvider();if(!Te)throw Object.assign(new Mt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:W,error:Ye}=await Te.retrievePaymentIntent(L);if(Ye)throw Object.assign(new Mt(Ye.message??"Failed to retrieve PayPal payment status.","api_error",{code:Ye.code}),{checkoutMethod:"paypal"});let te=Da(W?.status);if(!W||te==="failed")throw Object.assign(new Mt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let $t=typeof W.payment_method=="string"?W.payment_method:W.payment_method?.id,rt=te;if(O.sessionId){let F=(await new uo(k,{telemetry:!1}).getUnifiedCheckoutSession(O.sessionId)).data.session;if(F&&F.status!=="complete"){let ye=await ur({billingApiUrl:k,sessionId:O.sessionId,session:F,telemetry:!1,tokenizedData:{id:$t??W.id,type:"card",threeDSecureActionResultTokenId:W.id,isPaypal:!0}});if(ye.type!=="success")throw Object.assign(new Mt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});rt=ye.result.status}}O.sessionId&&ir(O.sessionId),M?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),M?.performance({stage:"redirect_resume",durationMs:M.elapsed(u),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),M?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ve("success"),await Lr(Tn),ft(()=>y.current?.({status:rt,paymentIntentId:W.id,paymentMethodId:$t,checkoutMethod:"paypal"}))}catch(U){let b=Xn(U),Te=b.checkoutMethod??"paypal",W=!!(b.declineCode||b.code?.toLowerCase().includes("declin"));if(M)M.performance({stage:"redirect_resume",durationMs:M.elapsed(u),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),W?M.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):M.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(W){let Ye=po(k,r,tt);Ye.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),mo(Ye)}else Yo(k,r,tt,"REDIRECT_RESUME_FAILED","redirect_resume");Pe(b.message),It(b.message),ft(()=>Ie.current?.(b)),Se(Te,b,{code:b.code,declineCode:b.declineCode}),Ve("error"),await Lr(bn)}finally{Jo(),Zs(),Ve(null),It(null),et(!1)}})())},[Se,ft,c,Xn,k,r]);let nt=nn(null);function on(E){let L=JSON.stringify({c:E?.clientId,cur:E?.currency??"",a:{e:E?.account?.email?.trim().toLowerCase()??"",country:E?.account?.country??""},successUrl:E?.successUrl,cancelUrl:E?.cancelUrl,p:E?.products?.map(M=>`${M.type??""}:${M.code??M.providerItemId??M.providerPlanId??""}:${M.totalAmount??""}:${M.overrideAmount??""}:${M.quantity??1}`).sort(),i:E?.items?.map(M=>`${M.code??M.providerItemId??""}:${M.totalAmount??""}:${M.overrideAmount??""}:${M.quantity??1}`).sort(),s:E?.subscriptions?.map(M=>`${M.code??M.providerPlanId??""}:${M.totalAmount??""}:${M.overrideAmount??""}:${M.quantity??1}`).sort(),couponCodes:E?.couponCodes,tagsData:E?.tagsData,utmMetadata:E?.utmMetadata,tokenizedData:E?.tokenizedData,m:E?.checkoutMode??"full"}),O=0;for(let M=0;M<L.length;M++)O=(O<<5)-O+L.charCodeAt(M)|0;return`flopay_session_${Math.abs(O).toString(36)}`}let Yt=dn(()=>Bt?on(Bt):"",[Bt]),Pt=nn(Bt);Pt.current=Bt,Bn(()=>{qe(e??"")},[e]),Bn(()=>{K.current=!1,Pe(de),It(null),Ve(null)},[Yt,de,e]);async function jt(E,L){let O=po(k,r,tt),M=new uo(k,{telemetry:!1});try{let u=Js(L);O.log({name:u?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let U=u?.sid??null,b=null;if(U)try{if(b=await M.getUnifiedCheckoutSession(U,u?.nonce),b.data.session?.status==="complete"){if(Na(U))return{sid:U,result:b};fi(L),U=null,b=null}}catch{O.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),fi(L),U=null}if(!U){let Te=O.now();O.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let W={...E,avsCheck:!!oe,avsConfig:typeof oe=="object"?oe:void 0,checkoutType:"embedded_checkout",checkoutLayout:he?"custom_layout":$==="buttons"?"buttons_layout":"default_layout"};try{b=await M.createAndFetchSession(W),O.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),O.performance({stage:"session_create",durationMs:O.now()-Te,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"})}catch(Ye){throw O.performance({stage:"session_create",durationMs:O.now()-Te,durationMode:"machine",requestCategory:"session_create",statusClass:"network_error"}),Ye instanceof Mt&&Ye.type==="validation_error"?O.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):O.error({errorCode:"CHECKOUT_SESSION_CREATE_FAILED",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Ye}U=b.data.session?.id??"",U&&Xs(L,U,b.data.session?.clientSecret)}return{sid:U??"",result:b}}finally{mo(O)}}let Ct=Zn(async E=>{let L=Pt.current;if(!L)throw new Mt("createSession is required to bootstrap checkout.","validation_error");let O=Bo(L,E),M=on(O),u=Wo.get(M);u||(u=jt(O,M),Wo.set(M,u));let U;try{U=await u}finally{Wo.delete(M)}nt.current=M;try{E&&($n(yn),Rn(rt=>Aa(rt,E)));let{sid:b,result:Te}=U;x(Te),Te.data.session&&Ue(Te.data.session),b&&qe(b);let{publishableKey:W,paypalPublishableKey:Ye}=lo(Te),{flopay:te,paypalFlopay:$t}=await co({publishableKey:W,paypalPublishableKey:Ye,billingApiUrl:k,locale:c,telemetry:r});ke.current=te,se(te),Je.current=$t,Xe($t),Rt(!1)}catch(b){throw nt.current===M&&(nt.current=null),b}return U},[c,k,r,tt]),an=Zn(async E=>{if(!Qs(E)||ht)return{sessionId:Oe,session:m};Dt(!0);try{let L=await Ct(E);return{sessionId:L.sid,session:L.result.data.session??null}}finally{Dt(!1)}},[Ct,ht,Oe,m]);Bn(()=>{let E=!1;if(Ce(null),Yt){let M=Pt.current;return st(Ot),Rt(!1),nt.current===Yt?()=>{E=!0}:(Ue(Fa(M,ae)),(async()=>{let u=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),U=Ot==="auto"&&!K.current&&!u;U&&(Pe(null),It(null),Ve("processing"));try{let b=await Ct(),Te=b.result.data.session??null;Nt.current=lo(b.result);let W=Go(b.result);if(!E&&U&&Te&&!W){K.current=!0,await mt(Te,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:b.result.autoProcessingError,initialAutoProcessingPending:b.result.autoProcessingPending,autoProcessingAttempted:b.result.autoProcessingAttempted,sessionId:b.sid||Te.id});return}!E&&U&&(W&&(K.current=!0),Ve(null),It(null))}catch(b){if(E)return;let Te=b instanceof Mt||typeof b=="object"&&b!==null&&"code"in b?b.code:void 0;if(U&&Te==="session_auto_completed"){K.current=!0,Ve("success"),await Lr(Tn),E||(ft(()=>{y.current?.({status:"succeeded"})}),Ve(null),It(null));return}U&&(Ve(null),It(null));let W=b instanceof Mt?b:new Mt(b instanceof Error?b.message:"Failed to create session","api_error");Ce(W)}})(),()=>{E=!0})}Rt(!0);async function L(){let M=!1;try{let U=await new uo(k,{telemetry:!1}).getUnifiedCheckoutSession(je,t);if(E)return;x(U);let b=U.data.session??null;if(Ue(b),!b)throw new Mt("No session data returned","api_error");if(b.status==="complete"){Rt(!1),ft(()=>{En.current?.(b.successUrl??"")});return}if(b.status==="expired")throw new Mt("Checkout session has expired.","api_error",{code:"checkout_session_expired"});M=!0;let Te=ae??b.checkoutMode??"full";st(Te);let W=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ye=Go(U);if(Te==="auto"&&!K.current&&!W&&!Ye){K.current=!0;let te=O(U);try{if(await mt(b,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>te,sessionId:je||b.id}),E)return;await te,E||Rt(!1);return}catch{if(E)return;await te,E||Rt(!1);return}}await O(U),E||Rt(!1)}catch(u){if(E)return;u instanceof Mt?!M&&!Ys(u)&&Yo(k,r,tt,"NETWORK_REQUEST_FAILED","session_read"):Yo(k,r,tt,"INTERNAL_SDK_ERROR","checkout_mount");let U=u instanceof Mt?u:new Mt(u instanceof Error?u.message:"Failed to initialize checkout","api_error");Ce(U),Rt(!1)}}async function O(M){let{publishableKey:u,paypalPublishableKey:U}=lo(M);Nt.current={publishableKey:u,paypalPublishableKey:U};let{flopay:b,paypalFlopay:Te}=await co({publishableKey:u,paypalPublishableKey:U,billingApiUrl:k,locale:c,telemetry:r});ke.current=b,se(b),Je.current=Te,Xe(Te)}return L(),()=>{E=!0}},[Ct,ae,Yt,Ot,Kt,ft,t,mt]);let gn=Zn(async()=>{if(!(Qe||!m)){et(!0),Pe(null);try{await mt(m,{fallbackToFull:!0,sessionId:je||m.id})}finally{et(!1)}}},[je,Qe,mt,m]),_n=Xo(G),hn=Go(G),Vt=dn(()=>{if(!G||!m||!G.data.stripe?.publishableKey)return;let E={appearance:ie,paymentMethodCreation:"manual",billingApiUrl:k};if(G.data.stripe?.clientSecret)E.clientSecret=G.data.stripe.clientSecret;else{let L=mi(m).total;E.amount=Math.round(L*100)||m.amount,E.currency=m.currency?.toLowerCase()}return E},[G,m,ie,k]),He=!!(n&&!he&&$==="buttons"&&V&&Ot==="full"),Ht=dn(()=>({session:m,loading:bt,error:g,checkoutMode:$e,inlineSessionDraft:Bt,applyInlineSessionPatch:He?an:void 0,inlineSessionPatchProcessing:ht}),[m,bt,g,$e,Bt,He,an,ht]),zt=!!n&&$==="buttons"&&!hn&&(!H||!Vt),Ut=vt?Q(vn,{status:vt,errorMessage:Ft}):null;if(bt){if(s)return kt(kn,{children:[s,Ut]});if($==="buttons"){let E=ee?.buttonsLayout?.cardButton?.borderRadius??ee?.appearance.variables?.borderRadius??8,L=O=>Q("div",{style:{height:O,borderRadius:E,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&&L(pr),f&&(w||T)&&L(pr),f&&L(pr),Q("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ut]})}return kt(kn,{children:[kt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[Q("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),Q("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ut]})}return g?S?Q(cn.Provider,{value:Ht,children:S(g)}):Q(cn.Provider,{value:Ht,children:Q("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:g.message})}):zt?kt(kn,{children:[Q(cn.Provider,{value:Ht,children:Q(tl,{onButtonClick:j,showPayPal:l,showStripe:f,showApplePay:w,showGooglePay:T,theme:Y,buttonsTheme:le,buttonsStyles:re,cardButtonContent:D,cardBackButtonContent:J,cardTitleContent:q})}),Ut]}):hn&&m&&_n?kt(kn,{children:[Q(cn.Provider,{value:Ht,children:kt("div",{className:X,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[We&&Q(or,{icon:!1,children:We}),Lt==="retrying"&&Q("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Lt==="exhausted"&&kt("div",{role:"alert",children:[Q("div",{children:"PayPal is temporarily unavailable. Please try again."}),Q("button",{type:"button",onClick:Fn,children:"Retry PayPal"})]}),Lt!=="exhausted"&&Q("div",{"aria-hidden":Lt==="retrying"?!0:void 0,style:Lt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:Q(ja,{sessionId:je,nonce:m.clientSecret||void 0,billingApiUrl:k,email:m.customer?.email,clientId:_n.clientId,environment:_n.environment,currency:(m.currency??"usd").toUpperCase(),isSubscription:m.mode==="subscription",onComplete:B,onErrorChange:Pe,onDecline:R,onButtonClick:j,onInitializationStateChange:Ee,allowAutomaticRetry:rn===0,session:m,telemetry:r,telemetryContext:tt,debug:h},`paypal-init-${rn}`)})]})}),Ut]}):!H||!Vt?Q(kn,{children:Ut}):$e==="confirm"?kt(kn,{children:[Q(cn.Provider,{value:Ht,children:Q(Gr,{flopay:H,paypalFlopay:gt,options:Vt,children:kt("div",{className:X,children:[We&&Q("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:We}),we?we({onConfirm:gn,isProcessing:Qe}):Q("button",{type:"button",onClick:gn,disabled:Qe,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Qe?"not-allowed":"pointer",opacity:Qe?.6:1},children:Qe?"Processing...":Fe??"Confirm Purchase"})]})})}),Ut]}):kt(kn,{children:[Q(cn.Provider,{value:Ht,children:Q(Gr,{flopay:H,paypalFlopay:gt,options:Vt,children:he?kt(kn,{children:[We&&Q("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:We}),Q(el,{sessionId:je,nonce:m?.clientSecret||void 0,billingApiUrl:k,session:m,children:he})]}):Q(Vo,{sessionId:je,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(mi(m).total*100):0,currency:m?.currency?.toLowerCase()??"usd",onComplete:B,onError:p,onDecline:R,error:We,onErrorChange:Pe,showPayPal:l,showStripe:f,enabledPaymentMethods:G?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:G?.data.stripe?.enabledPaymentMethodCountries,showApplePay:w,showGooglePay:T,layout:$,theme:Y,buttonsTheme:le,buttonsStyles:re,appearance:ie,cardButtonContent:D,cardBackButtonContent:J,cardTitleContent:q,onButtonClick:j,onBeforeButtonClick:V,enableAVS:oe,...Be?{cardFieldOrder:Be}:{},...fe?{cardPreFormSlot:fe}:{},avsLayout:me,country:m?.customer?.country,city:m?.customer?.city,state:m?.customer?.state,onCountryChange:C,onZipChange:_,avsCheck:!!oe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:he?"custom_layout":$==="buttons"?"buttons_layout":"default_layout",className:X,directPaypal:Xo(G),isSubscription:m?.mode==="subscription",session:m,debug:h})})}),Ut]})}function el({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:r}){return Q(kn,{children:Ko.Children.map(r,a=>{if(!Ko.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:Ko.cloneElement(a,s)})})}function tl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:i,showGooglePay:r,theme:a,buttonsTheme:c,buttonsStyles:s,cardButtonContent:S,cardBackButtonContent:B,cardTitleContent:p}){let[R,C]=wt(!1),_=dn(()=>Pi(a),[a]),l=dn(()=>{let h=_?.buttonsLayout??Ws(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},[_,c,s]),f=_?.buttonsLayout?.cardButton?.borderRadius??_?.appearance.variables?.borderRadius??8,w=h=>Q("div",{style:{height:h,borderRadius:f,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),T=S===void 0?{boxSizing:"border-box",height:pr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(R){let h=l.cardInputBorder??"#e5e7eb",$=l.cardInputBackground??"white",Y=er(B),le=er(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:Y?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...l.backButton},children:[Q("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...l.backButtonIcon},children:Q("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:Q("path",{d:"M15 18l-6-6 6-6"})})}),Q(nr,{content:B})]}),le?Q("div",{style:{flex:1}}):Q("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...l.title},children:Q(xr,{content:p})})]}),Q("div",{style:{backgroundColor:$,border:`1px solid ${h}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:Q("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),kt("div",{style:{display:"flex"},children:[Q("div",{style:{flex:1,backgroundColor:$,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomLeftRadius:8,padding:12,height:45},children:Q("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Q("div",{style:{flex:1,backgroundColor:$,borderTop:"none",borderRight:`1px solid ${h}`,borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomRightRadius:8,padding:12,height:45},children:Q("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),Q("div",{style:{backgroundColor:$,border:`1px solid ${h}`,borderRadius:8,marginTop:8,padding:12,height:45},children:Q("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Q("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...l.submitButton,opacity:.5}}),Q("style",{children:`
|
|
41
41
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
42
42
|
@keyframes flopay-interim-expand {
|
|
43
43
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
44
44
|
40% { opacity: 1; }
|
|
45
45
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
46
46
|
}
|
|
47
|
-
`})]})}return Rt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&S(pr),n&&(i||r)&&S(pr),n&&Q("button",{type:"button",onClick:()=>{e?.("card"),C(!0)},style:{width:"100%",...x,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:l.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...l.cardButton},onMouseDown:h=>{h.currentTarget.style.transform="scale(0.985)"},onMouseUp:h=>{h.currentTarget.style.transform="scale(1)"},children:Q(tr,{content:w})}),Q("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{useEffect as el,useRef as Pi,useContext as tl}from"react";import{jsx as ol}from"react/jsx-runtime";function bi(e,t){function n({className:i,id:r,style:a,options:c,onChange:s,onReady:w,onFocus:M,onBlur:p,onEscape:R}){let C=Pi(null),E=Pi(null),{elements:l,reportInteractive:f}=tl(xn);return el(()=>{if(!l||!C.current)return;let S=!0;return(async()=>{let x=l.getElement(e);x||(x=await l.create(e,c)),!(!S||!C.current)&&(x.mount(C.current),E.current=x,s&&x.on("change",s),x.on("ready",()=>{f?.(),w?.()}),M&&x.on("focus",M),p&&x.on("blur",p),R&&x.on("escape",R))})(),()=>{if(S=!1,E.current){try{E.current.unmount()}catch{}E.current=null}}},[l,f]),ol("div",{ref:C,className:i,id:r,style:a})}return n.displayName=t,n}var nl=bi("payment","PaymentElement"),rl=bi("address","AddressElement");import{PaymentAPI as al}from"@flopay/js";import{FloPayError as il}from"@flopay/shared";import{useCallback as Qo,useEffect as sl,useRef as ll,useState as vi}from"react";import{Fragment as dl,jsx as yr,jsxs as ul}from"react/jsx-runtime";function cl({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,firstName:a,lastName:c,chv:s,onTokenizedBody:w,onComplete:M,onErrorChange:p,isProcessing:R=!1}){let C=Pn(),E=To(),l=Gr(),[f,S]=vi(!1),[x,h]=vi(!1),U=ll(!1),Y=(n||l).replace(/\/+$/,""),ce=Qo(async J=>{try{let de=await new al(Y).processPayment(r??"",{sessionId:e,nonce:t,tokenizedData:J,accountData:{userId:r??"",email:i??"",firstName:a??"",lastName:c??""},chv:s});if(de.ok){M?.();return}let q=await de.json().catch(()=>null);p?.(q?.message??"Payment failed. Please try again.")}catch($){p?.($ instanceof Error?$.message:"An unexpected error occurred")}},[Y,e,t,r,i,a,c,s,M,p]),re=Qo(J=>{w?w(J):ce(J)},[w,ce]);sl(()=>{if(!C||U.current)return;let J=new URLSearchParams(window.location.search),$=J.get("payment_intent"),de=J.get("payment_intent_client_secret"),q=J.get("redirect_status");!$||!de||(U.current=!0,(async()=>{try{if(h(!0),q==="failed"){p?.("PayPal payment was declined. Please try again.");return}let j=C.getRawProvider();if(!j?.retrievePaymentIntent){p?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:oe,error:Be}=await j.retrievePaymentIntent(de);if(Be){p?.(Be.message??"Failed to retrieve PayPal payment status.");return}if(oe&&(oe.status==="requires_capture"||oe.status==="succeeded")){let me=typeof oe.payment_method=="string"?oe.payment_method:oe.payment_method?.id;re({id:me??oe.id,type:"card",threeDSecureActionResultTokenId:oe.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(j){p?.(j instanceof Error?j.message:"Failed to complete PayPal payment.")}finally{h(!1)}})())},[C,re,p]);let F=Qo(async()=>{if(!(!C||!E))try{if(h(!0),p?.(null),!e||!i)throw new il("Missing sessionId or email for PayPal payment","validation_error");let J=await C.confirmPayPalPayment({billingApiUrl:Y,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")&&re({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,E,e,t,i,Y,re,p]);return!C||!E?yr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):ul(dl,{children:[!f&&yr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),yr("div",{style:f?{}:{display:"none"},children:yr("button",{type:"button",onClick:F,disabled:x||R,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:x||R?"not-allowed":"pointer",opacity:x||R?.6:1},ref:()=>S(!0),children:x?"Processing...":"PayPal"})}),(x||R)&&yr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:yr("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}import{useCallback as zn,useEffect as fr,useMemo as Lr,useRef as gr,useState as mo}from"react";import{PaymentAPI as ea}from"@flopay/js";import{FloPayError as Un,resolveBillingApiUrl as pl,resolveButtonsLayoutTheme as ml,resolveTheme as yl}from"@flopay/shared";import{Fragment as vl,jsx as hr,jsxs as Cl}from"react/jsx-runtime";var fl=44;function Ci(e){return new Promise(t=>setTimeout(t,e))}function gl(e,t){return e instanceof Un?e:new Un(e instanceof Error?e.message:t,"api_error")}function hl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Pl(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 bl({sessionId:e,nonce:t,createSession:n,paymentMethodId:i,checkoutMethod:r,clientId:a,products:c,items:s,subscriptions:w,account:M,successUrl:p,cancelUrl:R,couponCodes:C,tagsData:E,utmMetadata:l,billingApiUrl:f,locale:S,theme:x,appearance:h,buttonsTheme:U,buttonsStyles:Y,onSuccess:ce,onError:re,onDecline:F,children:J,disabled:$=!1,type:de="button",style:q,...j}){let oe=Lr(()=>pl(f),[f]),Be=Lr(()=>Pl({createSession:n,clientId:a,products:c,items:s,subscriptions:w,account:M,successUrl:p,cancelUrl:R,couponCodes:C,tagsData:E,utmMetadata:l}),[M,R,a,C,n,c,s,w,p,E,l]),[me,pe]=mo(!1),[X,ue]=mo(null),[he,ae]=mo(null),[Fe,ke]=mo(null),Ce=gr(!0),k=gr(null),ee=gr(Fe),ie=gr(ce),Oe=gr(re),De=gr(F);fr(()=>{ee.current=Fe},[Fe]),fr(()=>{ie.current=ce},[ce]),fr(()=>{Oe.current=re},[re]),fr(()=>{De.current=F},[F]),fr(()=>(Ce.current=!0,()=>{Ce.current=!1,k.current?.abort()}),[]),fr(()=>{if(typeof window>"u")return;let g=we=>{we.key==="Escape"&&ke(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let G=zn((g,we=Fr)=>{De.current?.(Bt(we,g,{code:g.code,declineCode:g.declineCode}))},[]),_=zn(async g=>{Ce.current&&(ae(null),ue("success"),await Ci(Tn),Ce.current&&ie.current?.(g))},[]),V=zn(async(g,we)=>{Ce.current&&(Oe.current?.(g),we?.emitDecline&&G(g,we.method),ae(g.message),ue("error"),await Ci(bn))},[G]),se=zn(async(g,we,qe)=>{let it=g.data.session??null;if(!it)throw new Un("No session data returned","api_error");let et=it.clientSecret||t;if(it.status==="complete"){await _({result:{status:"succeeded"},session:it,sessionId:it.id||we,autoCompleted:!1});return}if(it.status==="expired")throw new Un("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(g.autoProcessingPending){let Ct=(await new ea(oe).waitForCheckoutSessionCompletion(g.autoProcessingPending.sessionId,{initialDelayMs:g.autoProcessingPending.retryAfterMs})).data.session;if(!Ct||Ct.status!=="complete")throw new Un("Automatic payment failed. Please try again.","api_error",{code:Ct?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await _({result:{status:"succeeded"},session:Ct,sessionId:Ct.id||we,autoCompleted:!1});return}if(g.autoProcessingError){if(g.autoProcessingError.type==="3ds_required"&&g.autoProcessingError.nextActionRedirectUrl&&we&&et){let Ye=new AbortController;k.current=Ye;let Pe;try{Pe=await di({billingApiUrl:oe,sessionId:we,nonce:et,nextActionRedirectUrl:g.autoProcessingError.nextActionRedirectUrl,signal:Ye.signal})}finally{k.current===Ye&&(k.current=null)}if(Pe.status==="declined")throw On({type:Pe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Pe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let Lt=(await new ea(oe).waitForCheckoutSessionCompletion(we,{initialDelayMs:0,nonce:et})).data.session;if(!Lt||Lt.status!=="complete")throw On({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await _({result:{status:"succeeded"},session:Lt,sessionId:Lt.id||we,autoCompleted:!1});return}throw On(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(qe?.fromCreateSession&&g.autoProcessingAttempted===!0)throw On({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let tt=await ur({billingApiUrl:oe,sessionId:we??it.id,session:it,nonce:et});if(tt.type!=="success")throw On({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await _({result:tt.result,session:it,sessionId:it.id||we,autoCompleted:!1})}catch(tt){let Ye=Xn(tt),Pe=it.id||we;await V(Ye,{emitDecline:!0,method:Ye.checkoutMethod??Fr}),hl(Ye,Pe)&&Pe&&Ce.current&&ke({sessionId:Pe,errorMessage:Ye.message,nonce:et||void 0})}},[t,oe,V,_]),Re=zn(async g=>{if(j.onClick?.(g),!(g.defaultPrevented||$||me)){if(ke(null),e&&Be){let we=new Un("Provide either sessionId or create-session props, not both.","validation_error");await V(we),Ce.current&&(ue(null),ae(null));return}if(!e&&!Be){let we=new Un("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await V(we),Ce.current&&(ue(null),ae(null));return}pe(!0),ae(null),ue("processing");try{let we=new ea(oe);if(e){let qe=await we.getUnifiedCheckoutSession(e,t);await se(qe,e);return}try{let qe=await we.createAndFetchSession({...Be});await se(qe,qe.data.session?.id??null,{fromCreateSession:!0})}catch(qe){if(qe instanceof Un&&qe.code==="session_auto_completed"){await _({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw qe}}catch(we){await V(gl(we,"Automatic payment failed. Please try again."))}finally{Ce.current&&(ue(null),ae(null),pe(!1))}}},[j,Be,$,me,t,se,oe,e,V,_]),ht=zn(g=>{let we=ee.current;ke(null),ie.current?.({result:g,session:null,sessionId:we?.sessionId??null,autoCompleted:!1})},[]),Ze=zn(g=>{Oe.current?.(g)},[]),Xe=zn(g=>{De.current?.(g)},[]),m=Lr(()=>yl(x),[x]),$e=Lr(()=>{let g=m?.buttonsLayout??ml(U);return Y?{...g,...Y,cardButton:{...g.cardButton,...Y.cardButton}}:g},[m,U,Y]),ze=Lr(()=>{let g=m?.appearance;return h?g?{...g,...h,variables:{...g.variables,...h.variables}}:h:g},[h,m]),je=ze?.variables,Ve=je?.colorPrimary??"#4A49FF",Yt=je?.colorPrimaryHover??no(Ve,.12),vt=je?.borderRadius??"8px";return Cl(vl,{children:[hr("button",{...j,type:de,onClick:Re,disabled:$||me,"aria-busy":me,style:{width:"100%",...J===void 0?{boxSizing:"border-box",height:fl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...$e.cardButton,...qo({themeBundle:m,resolvedPrimaryColor:Ve,resolvedBorderRadius:vt,submitButtonStyle:$e.submitButton,explicitPrimaryColor:je?.colorPrimary}),fontSize:$e.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:$||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:$||me?.6:1,...q},onMouseEnter:g=>{j.onMouseEnter?.(g),!g.defaultPrevented&&!$&&!me&&(m||je?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Yt)},onMouseLeave:g=>{j.onMouseLeave?.(g),!g.defaultPrevented&&(m||je?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Ve)},onMouseDown:g=>{j.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{j.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:hr(tr,{content:J})}),X&&hr(vn,{status:X,errorMessage:he}),Fe&&hr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&ke(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:hr("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:hr(Zo,{sessionId:Fe.sessionId,nonce:Fe.nonce,checkoutMode:"full",billingApiUrl:oe,locale:S,theme:x,...ze?{appearance:ze}:{},buttonsTheme:U,buttonsStyles:Y,initialErrorMessage:Fe.errorMessage,cardTitleContent:null,onComplete:ht,onError:Ze,onDecline:Xe})})})]})}export{rl as AddressElement,to as DirectPayPalButton,bl as FloPayAutomaticPaymentButton,Zo as FloPayCheckout,Yr as FloPayProvider,cl as PayPalButton,nl as PaymentElement,jo as SplitCardForm,_o as VaultCardFields,Qi as useCheckout,To as useElements,Pn as useFloPay,xo as usePayPalFloPay};
|
|
47
|
+
`})]})}return kt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&w(pr),n&&(i||r)&&w(pr),n&&Q("button",{type:"button",onClick:()=>{e?.("card"),C(!0)},style:{width:"100%",...T,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:l.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...l.cardButton},onMouseDown:h=>{h.currentTarget.style.transform="scale(0.985)"},onMouseUp:h=>{h.currentTarget.style.transform="scale(1)"},children:Q(tr,{content:S})}),Q("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{useEffect as nl,useRef as bi,useContext as rl}from"react";import{jsx as il}from"react/jsx-runtime";function vi(e,t){function n({className:i,id:r,style:a,options:c,onChange:s,onReady:S,onFocus:B,onBlur:p,onEscape:R}){let C=bi(null),_=bi(null),{elements:l,reportInteractive:f}=rl(xn);return nl(()=>{if(!l||!C.current)return;let w=!0;return(async()=>{let T=l.getElement(e);T||(T=await l.create(e,c)),!(!w||!C.current)&&(T.mount(C.current),_.current=T,s&&T.on("change",s),T.on("ready",()=>{f?.(),S?.()}),B&&T.on("focus",B),p&&T.on("blur",p),R&&T.on("escape",R))})(),()=>{if(w=!1,_.current){try{_.current.unmount()}catch{}_.current=null}}},[l,f]),il("div",{ref:C,className:i,id:r,style:a})}return n.displayName=t,n}var ol=vi("payment","PaymentElement"),al=vi("address","AddressElement");import{PaymentAPI as sl}from"@flopay/js";import{FloPayError as ll}from"@flopay/shared";import{useCallback as ea,useEffect as cl,useRef as dl,useState as Ci}from"react";import{Fragment as pl,jsx as yr,jsxs as ml}from"react/jsx-runtime";function ul({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,firstName:a,lastName:c,chv:s,onTokenizedBody:S,onComplete:B,onErrorChange:p,isProcessing:R=!1}){let C=Pn(),_=Mo(),l=Jr(),[f,w]=Ci(!1),[T,h]=Ci(!1),$=dl(!1),Y=(n||l).replace(/\/+$/,""),le=ea(async J=>{try{let ce=await new sl(Y).processPayment(r??"",{sessionId:e,nonce:t,tokenizedData:J,accountData:{userId:r??"",email:i??"",firstName:a??"",lastName:c??""},chv:s});if(ce.ok){B?.();return}let j=await ce.json().catch(()=>null);p?.(j?.message??"Payment failed. Please try again.")}catch(q){p?.(q instanceof Error?q.message:"An unexpected error occurred")}},[Y,e,t,r,i,a,c,s,B,p]),re=ea(J=>{S?S(J):le(J)},[S,le]);cl(()=>{if(!C||$.current)return;let J=new URLSearchParams(window.location.search),q=J.get("payment_intent"),ce=J.get("payment_intent_client_secret"),j=J.get("redirect_status");!q||!ce||($.current=!0,(async()=>{try{if(h(!0),j==="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:oe,error:Be}=await V.retrievePaymentIntent(ce);if(Be){p?.(Be.message??"Failed to retrieve PayPal payment status.");return}if(oe&&(oe.status==="requires_capture"||oe.status==="succeeded")){let fe=typeof oe.payment_method=="string"?oe.payment_method:oe.payment_method?.id;re({id:fe??oe.id,type:"card",threeDSecureActionResultTokenId:oe.id,isPaypal:!0});let me=new URL(window.location.href);me.searchParams.delete("payment_intent"),me.searchParams.delete("payment_intent_client_secret"),me.searchParams.delete("redirect_status"),window.history.replaceState({},"",me.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,re,p]);let D=ea(async()=>{if(!(!C||!_))try{if(h(!0),p?.(null),!e||!i)throw new ll("Missing sessionId or email for PayPal payment","validation_error");let J=await C.confirmPayPalPayment({billingApiUrl:Y,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")&&re({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,_,e,t,i,Y,re,p]);return!C||!_?yr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):ml(pl,{children:[!f&&yr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),yr("div",{style:f?{}:{display:"none"},children:yr("button",{type:"button",onClick:D,disabled:T||R,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:T||R?"not-allowed":"pointer",opacity:T||R?.6:1},ref:()=>w(!0),children:T?"Processing...":"PayPal"})}),(T||R)&&yr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:yr("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}import{useCallback as zn,useEffect as fr,useMemo as Nr,useRef as gr,useState as yo}from"react";import{PaymentAPI as ta}from"@flopay/js";import{FloPayError as Un,resolveBillingApiUrl as yl,resolveButtonsLayoutTheme as fl,resolveTheme as gl}from"@flopay/shared";import{Fragment as Sl,jsx as hr,jsxs as wl}from"react/jsx-runtime";var hl=44;function Si(e){return new Promise(t=>setTimeout(t,e))}function Pl(e,t){return e instanceof Un?e:new Un(e instanceof Error?e.message:t,"api_error")}function bl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function vl(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 Cl({sessionId:e,nonce:t,createSession:n,paymentMethodId:i,checkoutMethod:r,clientId:a,products:c,items:s,subscriptions:S,account:B,successUrl:p,cancelUrl:R,couponCodes:C,tagsData:_,utmMetadata:l,billingApiUrl:f,locale:w,theme:T,appearance:h,buttonsTheme:$,buttonsStyles:Y,onSuccess:le,onError:re,onDecline:D,children:J,disabled:q=!1,type:ce="button",style:j,...V}){let oe=Nr(()=>yl(f),[f]),Be=Nr(()=>vl({createSession:n,clientId:a,products:c,items:s,subscriptions:S,account:B,successUrl:p,cancelUrl:R,couponCodes:C,tagsData:_,utmMetadata:l}),[B,R,a,C,n,c,s,S,p,_,l]),[fe,me]=yo(!1),[X,de]=yo(null),[he,ae]=yo(null),[Fe,we]=yo(null),ve=gr(!0),k=gr(null),ee=gr(Fe),ie=gr(le),Ne=gr(re),De=gr(D);fr(()=>{ee.current=Fe},[Fe]),fr(()=>{ie.current=le},[le]),fr(()=>{Ne.current=re},[re]),fr(()=>{De.current=D},[D]),fr(()=>(ve.current=!0,()=>{ve.current=!1,k.current?.abort()}),[]),fr(()=>{if(typeof window>"u")return;let g=Ce=>{Ce.key==="Escape"&&we(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let G=zn((g,Ce=Dr)=>{De.current?.(Tt(Ce,g,{code:g.code,declineCode:g.declineCode}))},[]),x=zn(async g=>{ve.current&&(ae(null),de("success"),await Si(Tn),ve.current&&ie.current?.(g))},[]),H=zn(async(g,Ce)=>{ve.current&&(Ne.current?.(g),Ce?.emitDecline&&G(g,Ce.method),ae(g.message),de("error"),await Si(bn))},[G]),se=zn(async(g,Ce,$e)=>{let st=g.data.session??null;if(!st)throw new Un("No session data returned","api_error");let Qe=st.clientSecret||t;if(st.status==="complete"){await x({result:{status:"succeeded"},session:st,sessionId:st.id||Ce,autoCompleted:!1});return}if(st.status==="expired")throw new Un("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(g.autoProcessingPending){let vt=(await new ta(oe).waitForCheckoutSessionCompletion(g.autoProcessingPending.sessionId,{initialDelayMs:g.autoProcessingPending.retryAfterMs})).data.session;if(!vt||vt.status!=="complete")throw new Un("Automatic payment failed. Please try again.","api_error",{code:vt?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await x({result:{status:"succeeded"},session:vt,sessionId:vt.id||Ce,autoCompleted:!1});return}if(g.autoProcessingError){if(g.autoProcessingError.type==="3ds_required"&&g.autoProcessingError.nextActionRedirectUrl&&Ce&&Qe){let We=new AbortController;k.current=We;let Pe;try{Pe=await ui({billingApiUrl:oe,sessionId:Ce,nonce:Qe,nextActionRedirectUrl:g.autoProcessingError.nextActionRedirectUrl,signal:We.signal})}finally{k.current===We&&(k.current=null)}if(Pe.status==="declined")throw On({type:Pe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Pe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let Ft=(await new ta(oe).waitForCheckoutSessionCompletion(Ce,{initialDelayMs:0,nonce:Qe})).data.session;if(!Ft||Ft.status!=="complete")throw On({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await x({result:{status:"succeeded"},session:Ft,sessionId:Ft.id||Ce,autoCompleted:!1});return}throw On(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if($e?.fromCreateSession&&g.autoProcessingAttempted===!0)throw On({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let et=await ur({billingApiUrl:oe,sessionId:Ce??st.id,session:st,nonce:Qe});if(et.type!=="success")throw On({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||Ce,autoCompleted:!1})}catch(et){let We=Xn(et),Pe=st.id||Ce;await H(We,{emitDecline:!0,method:We.checkoutMethod??Dr}),bl(We,Pe)&&Pe&&ve.current&&we({sessionId:Pe,errorMessage:We.message,nonce:Qe||void 0})}},[t,oe,H,x]),ke=zn(async g=>{if(V.onClick?.(g),!(g.defaultPrevented||q||fe)){if(we(null),e&&Be){let Ce=new Un("Provide either sessionId or create-session props, not both.","validation_error");await H(Ce),ve.current&&(de(null),ae(null));return}if(!e&&!Be){let Ce=new Un("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await H(Ce),ve.current&&(de(null),ae(null));return}me(!0),ae(null),de("processing");try{let Ce=new ta(oe);if(e){let $e=await Ce.getUnifiedCheckoutSession(e,t);await se($e,e);return}try{let $e=await Ce.createAndFetchSession({...Be});await se($e,$e.data.session?.id??null,{fromCreateSession:!0})}catch($e){if($e instanceof Un&&$e.code==="session_auto_completed"){await x({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw $e}}catch(Ce){await H(Pl(Ce,"Automatic payment failed. Please try again."))}finally{ve.current&&(de(null),ae(null),me(!1))}}},[V,Be,q,fe,t,se,oe,e,H,x]),gt=zn(g=>{let Ce=ee.current;we(null),ie.current?.({result:g,session:null,sessionId:Ce?.sessionId??null,autoCompleted:!1})},[]),Xe=zn(g=>{Ne.current?.(g)},[]),Je=zn(g=>{De.current?.(g)},[]),m=Nr(()=>gl(T),[T]),Ue=Nr(()=>{let g=m?.buttonsLayout??fl($);return Y?{...g,...Y,cardButton:{...g.cardButton,...Y.cardButton}}:g},[m,$,Y]),Oe=Nr(()=>{let g=m?.appearance;return h?g?{...g,...h,variables:{...g.variables,...h.variables}}:h:g},[h,m]),qe=Oe?.variables,je=qe?.colorPrimary??"#4A49FF",Kt=qe?.colorPrimaryHover??ro(je,.12),bt=qe?.borderRadius??"8px";return wl(Sl,{children:[hr("button",{...V,type:ce,onClick:ke,disabled:q||fe,"aria-busy":fe,style:{width:"100%",...J===void 0?{boxSizing:"border-box",height:hl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Ue.cardButton,...jo({themeBundle:m,resolvedPrimaryColor:je,resolvedBorderRadius:bt,submitButtonStyle:Ue.submitButton,explicitPrimaryColor:qe?.colorPrimary}),fontSize:Ue.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:q||fe?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:q||fe?.6:1,...j},onMouseEnter:g=>{V.onMouseEnter?.(g),!g.defaultPrevented&&!q&&!fe&&(m||qe?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Kt)},onMouseLeave:g=>{V.onMouseLeave?.(g),!g.defaultPrevented&&(m||qe?.colorPrimary)&&(g.currentTarget.style.backgroundColor=je)},onMouseDown:g=>{V.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{V.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:hr(tr,{content:J})}),X&&hr(vn,{status:X,errorMessage:he}),Fe&&hr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&we(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:hr("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:hr(Qo,{sessionId:Fe.sessionId,nonce:Fe.nonce,checkoutMode:"full",billingApiUrl:oe,locale:w,theme:T,...Oe?{appearance:Oe}:{},buttonsTheme:$,buttonsStyles:Y,initialErrorMessage:Fe.errorMessage,cardTitleContent:null,onComplete:gt,onError:Xe,onDecline:Je})})})]})}export{al as AddressElement,no as DirectPayPalButton,Cl as FloPayAutomaticPaymentButton,Qo as FloPayCheckout,Gr as FloPayProvider,ul as PayPalButton,ol as PaymentElement,Vo as SplitCardForm,xo as VaultCardFields,es as useCheckout,Mo as useElements,Pn as useFloPay,To as usePayPalFloPay};
|