@flopay/react 1.4.19 → 1.4.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -0
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +9 -9
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var Ni=Object.create;var Vr=Object.defineProperty;var Oi=Object.getOwnPropertyDescriptor;var zi=Object.getOwnPropertyNames;var Ui=Object.getPrototypeOf,$i=Object.prototype.hasOwnProperty;var qi=(e,t)=>{for(var n in t)Vr(e,n,{get:t[n],enumerable:!0})},wa=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of zi(t))!$i.call(e,o)&&o!==n&&Vr(e,o,{get:()=>t[o],enumerable:!(l=Oi(t,o))||l.enumerable});return e};var ka=(e,t,n)=>(n=e!=null?Ni(Ui(e)):{},wa(t||!e||!e.__esModule?Vr(n,"default",{value:e,enumerable:!0}):n,e)),ji=e=>wa(Vr({},"__esModule",{value:!0}),e);var Ns={};qi(Ns,{AddressElement:()=>ui,DirectPayPalButton:()=>Er,FloPayAutomaticPaymentButton:()=>hi,FloPayCheckout:()=>mo,FloPayProvider:()=>wr,PayPalButton:()=>fi,PaymentElement:()=>di,SplitCardForm:()=>oo,VaultCardFields:()=>Hr,dropThirdPartyOnlyError:()=>Pi.dropThirdPartyOnlyError,useCheckout:()=>Ta,useElements:()=>Yr,useFloPay:()=>un,usePayPalFloPay:()=>Wr});module.exports=ji(Ns);var Vi=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,Ue=Vi();var St=require("react"),Ra=require("@flopay/shared");var _o=require("react"),In=(0,_o.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),dn=(0,_o.createContext)({session:null,loading:!1,error:null});var Ki=Symbol.for("@flopay/js.telemetry.bridge.v1"),Hi=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Wi(){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 Yi(e){let t=Wi(),n=(o,s)=>o?o.bind(e):s,l=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:l,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,l()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Kr(e){let t=globalThis[Hi];return Yi(t?.(e)??{})}function Mt(e){if(e)return e[Ki]}var Ia=require("react/jsx-runtime");function wr({flopay:e,paypalFlopay:t,options:n,children:l}){let[o,s]=(0,St.useState)(e instanceof Promise?null:e),[m,d]=(0,St.useState)(t instanceof Promise||!t?null:t),[I,N]=(0,St.useState)(null),b=(0,St.useRef)(null),_=(0,St.useRef)(null),k=(0,St.useRef)(null);(0,St.useEffect)(()=>{if(!o)return;let x=Mt(o);return b.current=x?.beginCheckout()??x?.now()??0,x?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{x?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),(0,St.useEffect)(()=>{let x=!1;return e instanceof Promise?e.then(M=>{x||s(M)}):s(e),()=>{x=!0}},[e]),(0,St.useEffect)(()=>{let x=!1;if(!t){d(null);return}return t instanceof Promise?t.then(M=>{x||d(M)}):d(t),()=>{x=!0}},[t]),(0,St.useEffect)(()=>{if(!o){N(null);return}let x=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return N(x),()=>{x.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,St.useEffect)(()=>{if(!o||!I||_.current===I)return;_.current=I;let x=Mt(o);x?.log({name:"checkout.rendered",stage:"checkout_render"}),x?.performance({stage:"checkout_render",durationMs:x.elapsed(b.current??0),durationMode:"machine"})},[I,o]);let F=(0,St.useCallback)(()=>{if(!o||!I||k.current===I)return;k.current=I;let x=Mt(o);x?.log({name:"checkout.interactive",stage:"checkout_interactive"}),x?.performance({stage:"checkout_interactive",durationMs:x.elapsed(b.current??0),durationMode:"machine"})},[I,o]),p=(0,Ra.resolveBillingApiUrl)(n?.billingApiUrl),v=(0,St.useMemo)(()=>({flopay:o,paypalFlopay:m,elements:I,billingApiUrl:p,reportInteractive:F}),[o,m,I,p,F]);return(0,Ia.jsx)(In.Provider,{value:v,children:l})}var B=ka(require("react"),1),Xn=require("@flopay/js"),Pe=require("@flopay/shared");var Js=require("react"),et=require("react/jsx-runtime");function Gi(){return(0,et.jsxs)(et.Fragment,{children:[(0,et.jsxs)("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:[(0,et.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,et.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,et.jsx)("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:(0,et.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Ji(){return(0,et.jsx)(et.Fragment,{children:"Go back"})}function Xi(){return(0,et.jsx)(et.Fragment,{children:"Secure card checkout"})}function nr(e){return e!==void 0&&(e===""||e===null||e===!1)}function rr({content:e}){return(0,et.jsx)(et.Fragment,{children:e===void 0?(0,et.jsx)(Gi,{}):e})}function or({content:e}){return(0,et.jsx)(et.Fragment,{children:e===void 0?(0,et.jsx)(Ji,{}):e})}function kr({content:e}){return(0,et.jsx)(et.Fragment,{children:e===void 0?(0,et.jsx)(Xi,{}):e})}var lt=require("@stripe/react-stripe-js"),R=require("@flopay/shared"),mn=require("@flopay/js");var En=require("react"),Ea=require("react/jsx-runtime");function Hr({capture:e,html:t,messageToken:n,expectedOrigin:l,theme:o,containerStyle:s,onReady:m,onError:d,onValidation:I}){let N=(0,En.useRef)(null),b=(0,En.useRef)(m),_=(0,En.useRef)(d),k=(0,En.useRef)(I);b.current=m,_.current=d,k.current=I;let F=(0,En.useRef)(o);return F.current=o,(0,En.useEffect)(()=>{let p=N.current;if(!p)return;let v=!0,x=!1,M=()=>{!v||x||(x=!0,b.current?.())},g=e.on("ready",()=>{M()}),he=e.on("error",ae=>{_.current?.(ae.message??"There was a problem loading the secure card form.")}),z=e.on("validation",ae=>{k.current?.(ae.message??null)}),ue={html:t,...n?{messageToken:n}:{},...l?{expectedOrigin:l}:{},...F.current?{theme:F.current}:{}};return e.mount(p,ue).then(()=>{M()}).catch(ae=>{v&&_.current?.(ae instanceof Error?ae.message:"Failed to load the secure card form.")}),()=>{v=!1,g(),he(),z(),e.unmount()}},[e,t,n,l]),(0,En.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,Ea.jsx)("div",{ref:N,"data-testid":"flopay-vault-card-fields",style:s})}var rl=require("react"),Rr=require("react/jsx-runtime");function ar({children:e,margin:t,icon:n=!0,styleOverride:l}){return(0,Rr.jsxs)("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"}:{},...l??{}},children:[n&&(0,Rr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Rr.jsx)("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 _a={alipay:new URL("./payment-logos/alipay.svg",Ue).href,bancontact:new URL("./payment-logos/bancontact.svg",Ue).href,blik:new URL("./payment-logos/blik.svg",Ue).href,eps:new URL("./payment-logos/eps.svg",Ue).href,giropay:new URL("./payment-logos/giropay.svg",Ue).href,ideal:new URL("./payment-logos/ideal.svg",Ue).href,klarna:new URL("./payment-logos/klarna.svg",Ue).href,p24:new URL("./payment-logos/p24.svg",Ue).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",Ue).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",Ue).href};var r=ka(require("react"),1);var ir=require("react"),xa=require("@flopay/shared");function un(){return(0,ir.useContext)(In).flopay}function Wr(){return(0,ir.useContext)(In).paypalFlopay??null}function Yr(){return(0,ir.useContext)(In).elements}function Ta(){return(0,ir.useContext)(dn)}function Gr(){return(0,ir.useContext)(In).billingApiUrl||(0,xa.resolveBillingApiUrl)()}var pl=require("react"),ft=require("react/jsx-runtime"),_n=1200,Cn=1500;function Sn({status:e,errorMessage:t}){return(0,ft.jsx)("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:(0,ft.jsxs)("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:[(0,ft.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,ft.jsxs)("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:[(0,ft.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,ft.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,ft.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,ft.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,ft.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,ft.jsx)("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"&&(0,ft.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,ft.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,ft.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,ft.jsx)("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"}})]})})]}),(0,ft.jsxs)("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"&&(0,ft.jsx)("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&&(0,ft.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,ft.jsx)("style",{children:`
|
|
1
|
+
"use strict";var ji=Object.create;var Gr=Object.defineProperty;var Vi=Object.getOwnPropertyDescriptor;var Ki=Object.getOwnPropertyNames;var Hi=Object.getPrototypeOf,Wi=Object.prototype.hasOwnProperty;var Yi=(e,t)=>{for(var n in t)Gr(e,n,{get:t[n],enumerable:!0})},xa=(e,t,n,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ki(t))!Wi.call(e,a)&&a!==n&&Gr(e,a,{get:()=>t[a],enumerable:!(c=Vi(t,a))||c.enumerable});return e};var Ta=(e,t,n)=>(n=e!=null?ji(Hi(e)):{},xa(t||!e||!e.__esModule?Gr(n,"default",{value:e,enumerable:!0}):n,e)),Gi=e=>xa(Gr({},"__esModule",{value:!0}),e);var js={};Yi(js,{AddressElement:()=>hi,DirectPayPalButton:()=>Ar,FloPayAutomaticPaymentButton:()=>wi,FloPayCheckout:()=>bo,FloPayProvider:()=>Er,PayPalButton:()=>Ci,PaymentElement:()=>gi,SplitCardForm:()=>uo,VaultCardFields:()=>Xr,dropThirdPartyOnlyError:()=>ki.dropThirdPartyOnlyError,useCheckout:()=>La,useElements:()=>Zr,useFloPay:()=>cn,usePayPalFloPay:()=>Qr});module.exports=Gi(js);var Ji=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,qe=Ji();var kt=require("react"),Ma=require("@flopay/shared");var Do=require("react"),En=(0,Do.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),ln=(0,Do.createContext)({session:null,loading:!1,error:null});var Xi=Symbol.for("@flopay/js.telemetry.bridge.v1"),Qi=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Zi(){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 es(e){let t=Zi(),n=(a,l)=>a?a.bind(e):l,c=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:c,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,c()-a),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 Jr(e){let t=globalThis[Qi];return es(t?.(e)??{})}function xt(e){if(e)return e[Xi]}var Aa=require("react/jsx-runtime");function Er({flopay:e,paypalFlopay:t,options:n,children:c}){let[a,l]=(0,kt.useState)(e instanceof Promise?null:e),[p,d]=(0,kt.useState)(t instanceof Promise||!t?null:t),[k,U]=(0,kt.useState)(null),P=(0,kt.useRef)(null),I=(0,kt.useRef)(null),R=(0,kt.useRef)(null);(0,kt.useEffect)(()=>{if(!a)return;let E=xt(a);return P.current=E?.beginCheckout()??E?.now()??0,E?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{E?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,kt.useEffect)(()=>{let E=!1;return e instanceof Promise?e.then(x=>{E||l(x)}):l(e),()=>{E=!0}},[e]),(0,kt.useEffect)(()=>{let E=!1;if(!t){d(null);return}return t instanceof Promise?t.then(x=>{E||d(x)}):d(t),()=>{E=!0}},[t]),(0,kt.useEffect)(()=>{if(!a){U(null);return}let E=a.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return U(E),()=>{E.destroy()}},[a,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,kt.useEffect)(()=>{if(!a||!k||I.current===k)return;I.current=k;let E=xt(a);E?.log({name:"checkout.rendered",stage:"checkout_render"}),E?.performance({stage:"checkout_render",durationMs:E.elapsed(P.current??0),durationMode:"machine"})},[k,a]);let O=(0,kt.useCallback)(()=>{if(!a||!k||R.current===k)return;R.current=k;let E=xt(a);E?.log({name:"checkout.interactive",stage:"checkout_interactive"}),E?.performance({stage:"checkout_interactive",durationMs:E.elapsed(P.current??0),durationMode:"machine"})},[k,a]),u=(0,Ma.resolveBillingApiUrl)(n?.billingApiUrl),b=(0,kt.useMemo)(()=>({flopay:a,paypalFlopay:p,elements:k,billingApiUrl:u,reportInteractive:O}),[a,p,k,u,O]);return(0,Aa.jsx)(En.Provider,{value:b,children:c})}var F=Ta(require("react"),1),Zn=require("@flopay/js"),Se=require("@flopay/shared");var nl=require("react"),ct=require("react/jsx-runtime");function ts(){return(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsxs)("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:[(0,ct.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,ct.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,ct.jsx)("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:(0,ct.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function ns(){return(0,ct.jsx)(ct.Fragment,{children:"Go back"})}function rs(){return(0,ct.jsx)(ct.Fragment,{children:"Secure card checkout"})}function or(e){return e!==void 0&&(e===""||e===null||e===!1)}function ar({content:e}){return(0,ct.jsx)(ct.Fragment,{children:e===void 0?(0,ct.jsx)(ts,{}):e})}function ir({content:e}){return(0,ct.jsx)(ct.Fragment,{children:e===void 0?(0,ct.jsx)(ns,{}):e})}function _r({content:e}){return(0,ct.jsx)(ct.Fragment,{children:e===void 0?(0,ct.jsx)(rs,{}):e})}var ft=require("@stripe/react-stripe-js"),C=require("@flopay/shared"),un=require("@flopay/js");var _n=require("react"),Ba=require("react/jsx-runtime");function Xr({capture:e,html:t,messageToken:n,expectedOrigin:c,theme:a,containerStyle:l,onReady:p,onError:d,onValidation:k}){let U=(0,_n.useRef)(null),P=(0,_n.useRef)(p),I=(0,_n.useRef)(d),R=(0,_n.useRef)(k);P.current=p,I.current=d,R.current=k;let O=(0,_n.useRef)(a);return O.current=a,(0,_n.useEffect)(()=>{let u=U.current;if(!u)return;let b=!0,E=!1,x=()=>{!b||E||(E=!0,P.current?.())},h=e.on("ready",()=>{x()}),ye=e.on("error",oe=>{I.current?.(oe.message??"There was a problem loading the secure card form.")}),M=e.on("validation",oe=>{R.current?.(oe.message??null)}),ce={html:t,...n?{messageToken:n}:{},...c?{expectedOrigin:c}:{},...O.current?{theme:O.current}:{}};return e.mount(u,ce).then(()=>{x()}).catch(oe=>{b&&I.current?.(oe instanceof Error?oe.message:"Failed to load the secure card form.")}),()=>{b=!1,h(),ye(),M(),e.unmount()}},[e,t,n,c]),(0,_n.useEffect)(()=>{a&&e.applyTheme?.(a)},[e,a]),(0,Ba.jsx)("div",{ref:U,"data-testid":"flopay-vault-card-fields",style:l})}var cl=require("react"),xr=require("react/jsx-runtime");function sr({children:e,margin:t,icon:n=!0,styleOverride:c}){return(0,xr.jsxs)("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"}:{},...c??{}},children:[n&&(0,xr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,xr.jsx)("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 Fa={alipay:new URL("./payment-logos/alipay.svg",qe).href,bancontact:new URL("./payment-logos/bancontact.svg",qe).href,blik:new URL("./payment-logos/blik.svg",qe).href,eps:new URL("./payment-logos/eps.svg",qe).href,giropay:new URL("./payment-logos/giropay.svg",qe).href,ideal:new URL("./payment-logos/ideal.svg",qe).href,klarna:new URL("./payment-logos/klarna.svg",qe).href,p24:new URL("./payment-logos/p24.svg",qe).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",qe).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",qe).href};var o=Ta(require("react"),1);var lr=require("react"),Da=require("@flopay/shared");function cn(){return(0,lr.useContext)(En).flopay}function Qr(){return(0,lr.useContext)(En).paypalFlopay??null}function Zr(){return(0,lr.useContext)(En).elements}function La(){return(0,lr.useContext)(ln)}function eo(){return(0,lr.useContext)(En).billingApiUrl||(0,Da.resolveBillingApiUrl)()}var Pl=require("react"),bt=require("react/jsx-runtime"),xn=1200,vn=1500;function Cn({status:e,errorMessage:t,authorized:n=!1}){return(0,bt.jsx)("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:(0,bt.jsxs)("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:[(0,bt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,bt.jsxs)("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:[(0,bt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,bt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,bt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,bt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,bt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,bt.jsx)("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"&&(0,bt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,bt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,bt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,bt.jsx)("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"}})]})})]}),(0,bt.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&"PROCESSING...",e==="success"&&(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL"),e==="error"&&"PAYMENT FAILED"]}),e==="success"&&(0,bt.jsx)("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&&(0,bt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,bt.jsx)("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
|
-
`})]})})}var Ma=require("@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 xo(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(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],l=n.reduce((s,m)=>s+(m.overrideAmount??m.totalAmount??0),0),o=e.currency??n.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(l*100),currency:o,status:"open",customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((s,m)=>({uuid:`synthetic-${s.type??"item"}-${m}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??o,metadata:s.metadata??null}))}}function To(e,t){return t?{...e,...t}:e}function wt(e,t,n){let l=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,s=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:l,...o?{code:o}:{},...s?{declineCode:s}:{}}}var Qi=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function On(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:l}of Qi)if(n.test(t))return l;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 Qr="flopay_recent_completion_";function sr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Qr+e,JSON.stringify(t))}catch{}}function Mo(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 La(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}var A=require("react"),za=require("@paypal/paypal-js"),Zr=require("@flopay/js"),Tn=require("@flopay/shared");function st(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 Zi(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Gn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function xn(e){if(typeof e!="object"||e===null)return;let t=e;return Gn(t.code)??Gn(t.type)??Gn(t.name)}function lr(e){if(!(typeof e!="object"||e===null))return Gn(e.decline_code)}function Ir(e){return typeof e!="object"||e===null?!1:Gn(e.type)?.toLowerCase()==="card_error"||lr(e)!==void 0}function zn(e){let t=Zi(e)?.toLowerCase()??"",l=`${xn(e)?.toLowerCase()??""} ${t}`;return l.includes("popup")&&l.includes("block")}var pn=require("react/jsx-runtime"),eo=45,es=1e3,ts=11e3,ns=["https://www.paypal.com","https://www.sandbox.paypal.com"],Na="We couldn't open PayPal. Try again or choose another payment method.",rs={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 Oa(e){return e.includes("No ack for postMessage init()")&&ns.some(t=>e.includes(t))&&e.includes("10000ms")}function os(e){return e?`${Na} Allow pop-ups for this site, then try again.`:Na}function Ua({sessionId:e,nonce:t,billingApiUrl:n,email:l,clientId:o,environment:s,currency:m,isSubscription:d,onTokenizedBody:I,onComplete:N,onErrorChange:b,onDecline:_,onTechnicalFailure:k,isProcessing:F=!1,onLoadStateChange:p,onInitializationStateChange:v,allowAutomaticRetry:x=!0,onButtonClick:M,runBeforeButtonClick:g,session:he,existingOrderId:z,telemetry:ue,telemetryContext:ae,debug:U=!1}){let te=un(),Q=(0,A.useMemo)(()=>{if(te)return null;let D=Kr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Tn.SDK_VERSION,enabled:ue!==!1});return D.setCheckoutContext(ae??{}),D.beginCheckout(ae??{}),D},[n,te,ue,ae?.checkoutMode,ae?.layout]),pe=(0,A.useMemo)(()=>Mt(te),[te]);(0,A.useEffect)(()=>()=>{Q&&Q.flush().catch(()=>{}).finally(()=>Q.destroy())},[Q]);let W=(0,A.useMemo)(()=>({error:D=>{pe?pe.error(D):Q?.error(D)},log:D=>{pe?pe.log(D):Q?.log(D)},performance:D=>{pe?pe.performance(D):Q?.performance(D)},terminal:D=>{pe?pe.terminal(D):Q?.terminal(D)},startTiming:()=>pe?.now()??Q?.now()??0,elapsed:D=>pe?.elapsed(D)??Math.max(0,(Q?.now()??D)-D)}),[pe,Q]),J=(0,A.useRef)(null),me=(0,A.useRef)(0),Me=(0,A.useRef)(null),we=(0,A.useRef)(!1),[be,ie]=(0,A.useState)(!1),[Ce,Be]=(0,A.useState)(!1),[se,Ee]=(0,A.useState)(0),_e=(0,A.useRef)(0),[Re,Z]=(0,A.useState)(!1),T=(0,A.useRef)(!1),ce=(0,A.useRef)(!1),[Oe,ze]=(0,A.useState)(!1),[ye,E]=(0,A.useState)(!1),re=(0,A.useMemo)(()=>n.replace(/\/+$/,""),[n]),oe=(0,A.useMemo)(()=>JSON.stringify([re,o,m,s??"",d,e,z??""]),[re,o,m,s,z,d,e]),$e=(0,A.useRef)(oe),ct=$e.current!==oe,[He,ot]=(0,A.useState)([]),V=D=>{U&&ot(gt=>[...gt,`${new Date().toISOString().slice(11,23)} ${D}`])},G=(0,A.useRef)(I),tt=(0,A.useRef)(N),Ae=(0,A.useRef)(b),at=(0,A.useRef)(_),Ge=(0,A.useRef)(k),We=(0,A.useRef)(M),rn=(0,A.useRef)(p),h=(0,A.useRef)(v),ke=(0,A.useRef)(g),dt=(0,A.useRef)(he),nt=(0,A.useRef)(l),Qe=(0,A.useRef)(t),Ye=(0,A.useRef)(null),Ze=(0,A.useRef)(0),xe=(0,A.useRef)(null),Ke=(0,A.useRef)(null),kt=(0,A.useRef)(new Map),Je=(0,A.useRef)(new Map),An=(0,A.useRef)(!1);(0,A.useEffect)(()=>(An.current=!0,()=>{An.current=!1}),[]),(0,A.useEffect)(()=>{G.current=I},[I]),(0,A.useEffect)(()=>{tt.current=N},[N]),(0,A.useEffect)(()=>{Ae.current=b},[b]),(0,A.useEffect)(()=>{at.current=_},[_]),(0,A.useEffect)(()=>{Ge.current=k},[k]),(0,A.useEffect)(()=>{We.current=M},[M]),(0,A.useEffect)(()=>{rn.current=p},[p]),(0,A.useEffect)(()=>{h.current=v},[v]),(0,A.useEffect)(()=>{ke.current=g},[g]),(0,A.useEffect)(()=>{dt.current=he},[he]),(0,A.useEffect)(()=>{nt.current=l},[l]),(0,A.useEffect)(()=>{Qe.current=t},[t]),(0,A.useEffect)(()=>{_e.current=se},[se]),(0,A.useEffect)(()=>{Re&&Me.current?.focus()},[Re,se]);let Pt=(0,A.useCallback)(()=>{window.setTimeout(()=>{Me.current?.focus()},0)},[]),Fn=(0,A.useCallback)(()=>{ie(!1),Ee(D=>D+1)},[]),on=(0,A.useCallback)(()=>{Z(!1),(J.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??J.current)?.focus?.()},[]);(0,A.useEffect)(()=>{!be||!we.current||(we.current=!1,on())},[on,be,se]);let hn=(0,A.useCallback)((D,gt)=>{let ut=Ge.current;if(ut){ut("paypal",D,gt);return}Ae.current?.(os(gt?.popupBlocked??zn(D)))},[]),Zt=()=>{xe.current?.timer&&(clearTimeout(xe.current.timer),xe.current.timer=null)},Dn=()=>{Zt();let D=Ze.current+1;return Ze.current=D,Ke.current=null,xe.current={generation:D,timer:null,yieldedControl:!1},Z(!1),D},Nt=D=>D!==void 0&&xe.current?.generation!==D?!1:(Zt(),xe.current=null,Ke.current=null,!0),Rt=D=>{let gt=D?.generation??xe.current?.generation??Ze.current;(!D?.generation||xe.current?.generation===gt)&&(Zt(),xe.current=null),Ke.current=gt,D?.showRetry&&Z(!0),D?.remount&&Fn(),D?.focus!==!1&&Pt()},qt=D=>xe.current?.generation===D&&Ke.current!==D,Gt=D=>{typeof document<"u"&&document.visibilityState!=="visible"||(Zt(),D.timer=setTimeout(()=>{xe.current?.generation===D.generation&&(xe.current=null,Ke.current=D.generation,hn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),Z(!0),Fn(),Pt())},600))},Bt=()=>{let D=xe.current;D?.yieldedControl&&Gt(D)},jt=()=>{let D=xe.current;D&&(D.yieldedControl=!0,Zt())},At=D=>{let gt=Ye.current;return gt&&Je.current.set(D,gt),D};(0,A.useEffect)(()=>{let D=()=>{document.visibilityState==="visible"?Bt():jt()};return document.addEventListener("visibilitychange",D),window.addEventListener("focus",Bt),window.addEventListener("blur",jt),()=>{document.removeEventListener("visibilitychange",D),window.removeEventListener("focus",Bt),window.removeEventListener("blur",jt),Zt()}},[]),(0,A.useEffect)(()=>{$e.current!==oe&&($e.current=oe,T.current=!1,ce.current=!1,ie(!1),Be(!1),ze(!1),h.current?.("loading"))},[oe]),(0,A.useEffect)(()=>{st(()=>rn.current?.(be&&!Oe))},[be,Oe]);let le=(0,Tn.normalizeGatewayEnvironment)(s);(0,A.useEffect)(()=>{let D=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",gt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(V(`mount clientId=${D} env=${s??"(unset)"}\u2192${le??"live"} ccy=${m} sub=${d}`),V(`ua=${gt.slice(0,80)}${gt.length>80?"\u2026":""}`),!o){V("FAIL: clientId empty \u2014 gateway misconfigured"),ze(!0),W.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){V("FAIL: containerRef not attached");return}me.current=W.startTiming(),W.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ut=!1,bt=!1,Te=()=>ut||bt,qe,$n=!1,Ln=()=>{qe=(0,Tn.generateIdempotencyKey)(),qe||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),$n=!0},qn=null,Zn=!1,Vt=null,it=!1,Ft=()=>{!Vt||it||(it=!0,Vt.close().catch(()=>{}))},Kt=null,ht=()=>{Kt!==null&&(W.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"overlay_return",durationMs:W.elapsed(Kt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Kt=null)},Jt=!1,Ht=J.current,an=null,Pn=null,It=[],Ot=u=>{if(!u||typeof u.getBoundingClientRect!="function")return"(no rect)";let c=u.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},Le=u=>{if(!u)return"(empty)";try{let c=new URL(u,typeof window<"u"?window.location.href:"https://localhost"),L=c.pathname.toLowerCase();return L.includes("checkcaptcha")||L.includes("captcha")?`CAPTCHA(${c.host}${L})`:L.includes("risk")||L.includes("challenge")?`RISK(${c.host}${L})`:L.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${L}`.slice(0,100)}catch{return u.slice(0,80)}},vt=u=>{let c=u.getAttribute("src"),L=u.getAttribute("srcdoc"),f=u.getAttribute("name"),ee=u.getAttribute("sandbox"),Ie=[];return c&&Ie.push(`src=${Le(c)}`),L&&Ie.push(`srcdoc[${L.length}ch]`),!c&&!L&&Ie.push("src=(empty) srcdoc=(empty)"),f&&Ie.push(`name=${f.slice(0,40)}`),ee!==null&&Ie.push(`sandbox="${ee.slice(0,40)}"`),Ie.join(" ")},Ct=u=>{if(!(u instanceof HTMLIFrameElement))return"";try{let c=u.contentDocument;if(!c)return"cd=null";let L=c.body?.children.length??0,f=c.body?.innerHTML.length??0,ee=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${L}children,${f}ch] head[${ee}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},bn=[],jn=u=>{if(Te())return;let c=u.message??String(u.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(V(`window:error ${c.slice(0,140)}`),bn.push(c))},Wt=u=>{if(Te())return;let c=u.reason instanceof Error?u.reason.message:String(u.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(V(`window:rejection ${c.slice(0,140)}`),bn.push(c))};U&&typeof window<"u"&&(window.addEventListener("error",jn),window.addEventListener("unhandledrejection",Wt));let Xt={value:0};if(U&&typeof PerformanceObserver<"u")try{Pn=new PerformanceObserver(u=>{if(!Te())for(let c of u.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;Xt.value+=1;let L=Math.round(c.duration);V(`net ${L}ms ${c.name.slice(0,90)}`)}}),Pn.observe({type:"resource",buffered:!0})}catch{}let Dt=()=>{for(an?.disconnect(),an=null,Pn?.disconnect(),Pn=null;It.length;)clearTimeout(It.pop());U&&typeof window<"u"&&(window.removeEventListener("error",jn),window.removeEventListener("unhandledrejection",Wt))},kn=u=>{if(!u)return!1;let c=u.toLowerCase();return c.includes("zoid destroyed")||c.includes("destroyed all components")||c.includes("window closed")||c.includes("detected container element removed")},Nn=u=>{if(Te()||kn(u))return;let c=On(u)??u;st(()=>Ae.current?.(c))},sn=u=>{ut||(ze(!0),u.includes("paypal_ineligible")||W.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",u))},Qt=(u,c=!1)=>{if(ut)return;let L=T.current||!x;if(Zn)return;Zn=!0,bt=!0,Dt(),Ft();let f=c||Oa(u);if(f&&x&&!T.current){T.current=!0,ie(!1),E(!1),Be(!0),h.current?.("retrying"),qn=setTimeout(()=>{ut||Ee(ee=>ee+1)},es);return}if(f||L){if(ie(!1),E(!1),Be(!1),ze(!0),h.current?.("exhausted"),!ce.current){ce.current=!0;let ee=Oa(u)?"paypal_init_timeout":c?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",ee)}return}sn(u)};ze(!1);let Et=async(u,c=Ye.current)=>{if(Te())return;let L=c?.sessionId??e;if(G.current){await G.current(u,{sessionId:L,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let f=W.startTiming();W.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ee=()=>{W.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"processing",durationMs:W.elapsed(f),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Ie=dt.current,rt=c?.accountPatch?.email??nt.current,Se=c?.accountPatch?.userId??Ie?.customer?.id??Ie?.accountData?.userId??"",y=await new Zr.PaymentAPI(re,{telemetry:!1}).processPayment(Se,{sessionId:L,nonce:c?.nonce??Qe.current,tokenizedData:u,accountData:{userId:Se,email:rt??Ie?.customer?.email??"",firstName:c?.accountPatch?.firstName??Ie?.customer?.firstName??Ie?.accountData?.firstName??"",lastName:c?.accountPatch?.lastName??Ie?.customer?.lastName??Ie?.accountData?.lastName??"",country:c?.accountPatch?.country??Ie?.customer?.country??Ie?.accountData?.country??void 0,zip:c?.accountPatch?.zip??Ie?.customer?.zip??Ie?.accountData?.zip??void 0}});if(y.ok){if(bt||ut&&An.current)return;ee(),W.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),st(()=>tt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Te())return;let $=await y.json().catch(()=>null),q=$?.message??"PayPal payment failed.",Ve=On(q)??q;ee(),y.status===400&&(typeof $?.declineCode=="string"||!Array.isArray($?.fields))?W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):y.status===400||y.status===422?W.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):W.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:y.status>=500?"5xx":y.status>=400?"4xx":y.status>=300?"3xx":"unknown",failureCategory:y.status>=500?"server_error":void 0}),Nn(Ve),st(()=>at.current?.(wt("paypal",Ve,{code:$?.code,declineCode:$?.declineCode})));return}catch(Ie){if(Te())return;ee(),W.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let rt=Ie instanceof Error?Ie.message:"PayPal payment failed.",Se=On(rt)??rt;Nn(Se),st(()=>at.current?.(wt("paypal",Se)));return}},P=()=>new Tn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Y=u=>Te()?Promise.reject(P()):Promise.resolve(u),K=async u=>{if(Te())throw P();$n||Ln();let c=Ye.current,L=c?.sessionId??e,f=c?.nonce??Qe.current;W.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ee=await new Zr.PaymentAPI(re,{telemetry:!1}).createSessionIntent(L,f??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:qe});if(Te())throw P();if(ee.provider!=="paypal")throw new Error(u);return W.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ee.providerObjectId},fe=(u,c)=>{let L=c?.nonce??Qe.current;if(!L)return;let f=c?.sessionId??e,ee=lr(u)??xn(u)??"provider_declined";new Zr.PaymentAPI(re,{telemetry:!1}).reportSessionIntentDecline(f,L,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ee}).catch(()=>{})},X=se;V("loadScript:scheduled (deferred 1 tick)");let de=null,S=setTimeout(()=>{if(ut){V("loadScript:skipped (cancelled before defer ran)");return}V("loadScript:start");let u=le==="live"?"production":le;de=(0,za.loadScript)({clientId:o,currency:m,intent:d?"subscription":"capture",vault:d?!0:void 0,...u?{environment:u}:{},...u==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),de.then(c=>{if(V(`loadScript:resolved inactive=${Te()} ns=${!!c} buttons=${!!c?.Buttons}`),Te())return;if(!c?.Buttons){V("FAIL: namespace missing Buttons factory"),Qt("PayPal SDK did not expose the Buttons factory.");return}W.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"provider_ready",durationMs:W.elapsed(me.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),W.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let L=async O=>{if(Te()||_e.current!==X)return;let y=O.subscriptionID??O.orderID??"",$=y?Je.current.get(y):kt.current.get(X);if(!(!$||!qt($.generation))&&Nt($.generation)){Je.current.delete(y),kt.current.delete($.surfaceKey),ht();try{if(E(!0),st(()=>Ae.current?.(null)),!y)throw new Tn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Et({id:y,isPaypal:!0},$)}catch(q){Nn(q instanceof Error?q.message:"PayPal capture failed.")}finally{Te()||E(!1)}}},f=c.Buttons({style:{layout:"horizontal",height:eo,tagline:!1},onClick:async(O,y)=>{if(Te()){await y.reject();return}Ln();let $=ke.current,q={};if($)try{let _t=await $("paypal");if(Te()){await y.reject();return}if(!_t.proceed){Ye.current=null,kt.current.delete(X),await y.reject();return}q={sessionId:_t.sessionId,accountPatch:_t.accountPatch,nonce:_t.nonce}}catch(_t){V(`onClick:runBeforeButtonClick rejected msg=${(_t instanceof Error?_t.message:String(_t)).slice(0,120)}`),Ye.current=null,kt.current.delete(X),await y.reject();return}st(()=>We.current?.("paypal"));let pt={generation:Dn(),surfaceKey:X,...q};Ye.current=pt,kt.current.set(X,pt),await y.resolve(),W.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),W.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Kt=W.startTiming()},createOrder:d?void 0:z?()=>Y(z).then(At):()=>K("Failed to create PayPal order.").then(At),createSubscription:d?z?()=>Y(z).then(At):()=>K("Failed to create PayPal subscription.").then(At):void 0,onApprove:L,onCancel:()=>{if(Te())return;let O=kt.current.get(X)??Ye.current;O&&kt.current.delete(O.surfaceKey),Ye.current=null,ht(),W.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we.current=!0,Rt({generation:O?.generation,remount:!0,focus:!1})},onError:O=>{if(Te()||_e.current!==X)return;let y=O instanceof Error?O.message:"PayPal failed to render.";if(V(`onError rendered=${Jt} msg=${y.slice(0,120)}`),Jt){let $=kt.current.get(X)??Ye.current;if($&&!qt($.generation)||!$&&Ke.current===Ze.current)return;if(kn(y)){Nt($?.generation);return}if(ht(),Ir(O)){W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),fe(O,$),st(()=>at.current?.(wt("paypal",y))),$&&kt.current.delete($.surfaceKey),Ye.current=null,Nt($?.generation);return}let q=y.toLowerCase();W.error({errorCode:q.includes("popup")&&q.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),$&&kt.current.delete($.surfaceKey),Ye.current=null,Rt({generation:$?.generation,remount:!0,showRetry:!0,focus:!0}),hn(O,{code:"paypal_runtime_failed"});return}Qt(y)}}),ee=f.isEligible();if(V(`isEligible=${ee}`),W.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ee){ie(!1),Qt("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Vt=f,U&&V(`container:dims ${Ot(Ht)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),U&&typeof MutationObserver<"u"&&(an=new MutationObserver(O=>{if(!Te()){for(let y of O)if(y.type==="childList")y.addedNodes.forEach($=>{if(!($ instanceof Element))return;let q=$.tagName.toLowerCase(),Ve=($.getAttribute("title")??"").slice(0,40),pt=q==="iframe"?` ${vt($)}`:"";V(`child+ ${q}${Ve?` title="${Ve}"`:""}${pt} dims=${Ot($)}`)});else if(y.type==="attributes"&&y.target instanceof Element){let $=y.target;if($.tagName.toLowerCase()!=="iframe")continue;let q=y.attributeName;(q==="src"||q==="srcdoc")&&V(`attr~ iframe ${q}=${q==="srcdoc"?`[${($.getAttribute("srcdoc")??"").length}ch]`:Le($.getAttribute("src"))} dims=${Ot($)}`)}}}),an.observe(Ht,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let rt=O=>{if(Te()||Jt)return;let y=Ht.querySelectorAll("iframe"),$=typeof document<"u"&&"hasStorageAccess"in document;V(`watchdog:${O} container=${Ot(Ht)} children=${Ht.childElementCount} iframes=${y.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${$} paypalNetRequests=${Xt.value}`),y.forEach((q,Ve)=>{let pt=(q.getAttribute("title")??"").slice(0,40);V(` iframe[${Ve}] ${Ot(q)}${pt?` title="${pt}"`:""} ${vt(q)}`);let _t=Ct(q);_t&&V(` ${_t}`)}),bn.length===0&&V(" (no PayPal/zoid window errors captured)")};U&&(It.push(setTimeout(()=>rt("3s"),3e3)),It.push(setTimeout(()=>rt("8s"),8e3)),It.push(setTimeout(()=>rt("15s"),15e3))),V("render:start");let Se=W.startTiming();It.push(setTimeout(()=>{Te()||Jt||(V("watchdog:11s retryable render timeout"),Qt("PayPal Buttons render did not settle within 11000ms.",!0))},ts)),f.render(Ht).then(()=>{if(V(`render:resolved inactive=${Te()}`),Dt(),Te()){Ft();return}Jt=!0,ie(!0),Be(!1),h.current?.("ready"),W.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"checkout_render",durationMs:W.elapsed(Se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(O=>{let y=O instanceof Error?O.message:"PayPal failed to render.";V(`render:rejected msg=${y.slice(0,120)}`),Dt(),Qt(y)})}).catch(c=>{let L=c instanceof Error?c.message:"PayPal SDK failed to load.";V(`loadScript:rejected msg=${L.slice(0,120)}`),Qt(L)})},0);return()=>{ut=!0,clearTimeout(S),qn&&clearTimeout(qn),Dt(),Ft()}},[x,re,o,m,s,d,e,z,se,W]);let en=U?(0,pn.jsxs)("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=${be} failed=${Oe})`,He.length===0?`
|
|
6
|
+
`})]})})}var cr=require("@flopay/shared");function za(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 Lo(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 Oa(e,t){let n=e.products??[...(e.subscriptions??[]).map(l=>({type:"subscription",code:l.code??l.providerPlanId,name:l.subscriptionName??l.providerPlanName??l.code??l.providerPlanId??null,quantity:l.quantity??1,totalAmount:l.totalAmount,overrideAmount:l.overrideAmount,currency:l.currency,metadata:l.metadata})),...(e.items??[]).map(l=>({type:"item",code:l.code??l.providerItemId,name:l.itemName??l.providerItemName??l.code??l.providerItemId??null,quantity:l.quantity??1,totalAmount:l.totalAmount,overrideAmount:l.overrideAmount,currency:l.currency,metadata:l.metadata}))],c=n.reduce((l,p)=>l+(p.overrideAmount??p.totalAmount??0),0),a=e.currency??n.find(l=>l.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(l=>l.type==="subscription")?"subscription":"payment",amount:Math.round(c*100),currency:a,status:"open",captureMethod:e.captureMethod,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((l,p)=>({uuid:`synthetic-${l.type??"item"}-${p}`,checkoutSessionId:"",type:l.type??"item",code:l.code,name:l.name??null,quantity:l.quantity??1,totalAmount:l.totalAmount,overrideAmount:l.overrideAmount??null,currency:l.currency??a,metadata:l.metadata??null}))}}function zo(e,t){return t?{...e,...t}:e}function Rt(e,t,n){let c=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,l=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:c,...a?{code:a}:{},...l?{declineCode:l}:{}}}var os=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function On(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:c}of os)if(n.test(t))return c;return e}function Jn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function dr(e){return e?.status==="authorized"||e?.status==="complete"}function Na(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function to(e){let t=Na(e);return new cr.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function no(e){let t=Na(e);return new cr.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function ro(e,t){return e==="processing"||(0,cr.isMoneySettledOutcome)(e,t)}function Ua(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function $a(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Tr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var oo="flopay_recent_completion_";function ur(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(oo+e,JSON.stringify(t))}catch{}}function Oo(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(oo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(oo+e),!1):!0}catch{return!1}}function qa(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}var z=require("react"),Ka=require("@paypal/paypal-js"),ao=require("@flopay/js"),Mn=require("@flopay/shared");function ut(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function as(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Xn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Tn(e){if(typeof e!="object"||e===null)return;let t=e;return Xn(t.code)??Xn(t.type)??Xn(t.name)}function pr(e){if(!(typeof e!="object"||e===null))return Xn(e.decline_code)}function Mr(e){return typeof e!="object"||e===null?!1:Xn(e.type)?.toLowerCase()==="card_error"||pr(e)!==void 0}function Nn(e){let t=as(e)?.toLowerCase()??"",c=`${Tn(e)?.toLowerCase()??""} ${t}`;return c.includes("popup")&&c.includes("block")}var dn=require("react/jsx-runtime"),io=45,is=1e3,ss=11e3,ls=["https://www.paypal.com","https://www.sandbox.paypal.com"],ja="We couldn't open PayPal. Try again or choose another payment method.",cs={width:"100%",minHeight:io,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Va(e){return e.includes("No ack for postMessage init()")&&ls.some(t=>e.includes(t))&&e.includes("10000ms")}function ds(e){return e?`${ja} Allow pop-ups for this site, then try again.`:ja}function Ha({sessionId:e,nonce:t,billingApiUrl:n,email:c,clientId:a,environment:l,currency:p,isSubscription:d,onTokenizedBody:k,onComplete:U,onErrorChange:P,onDecline:I,onTechnicalFailure:R,isProcessing:O=!1,onLoadStateChange:u,onInitializationStateChange:b,allowAutomaticRetry:E=!0,onButtonClick:x,runBeforeButtonClick:h,session:ye,existingOrderId:M,telemetry:ce,telemetryContext:oe,debug:j=!1}){let te=cn(),X=(0,z.useMemo)(()=>{if(te)return null;let N=Jr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Mn.SDK_VERSION,enabled:ce!==!1});return N.setCheckoutContext(oe??{}),N.beginCheckout(oe??{}),N},[n,te,ce,oe?.checkoutMode,oe?.layout]),de=(0,z.useMemo)(()=>xt(te),[te]);(0,z.useEffect)(()=>()=>{X&&X.flush().catch(()=>{}).finally(()=>X.destroy())},[X]);let Y=(0,z.useMemo)(()=>({error:N=>{de?de.error(N):X?.error(N)},log:N=>{de?de.log(N):X?.log(N)},performance:N=>{de?de.performance(N):X?.performance(N)},terminal:N=>{de?de.terminal(N):X?.terminal(N)},startTiming:()=>de?.now()??X?.now()??0,elapsed:N=>de?.elapsed(N)??Math.max(0,(X?.now()??N)-N)}),[de,X]),G=(0,z.useRef)(null),pe=(0,z.useRef)(0),De=(0,z.useRef)(null),we=(0,z.useRef)(!1),[ge,ae]=(0,z.useState)(!1),[be,Le]=(0,z.useState)(!1),[ie,je]=(0,z.useState)(0),Oe=(0,z.useRef)(0),[Ee,J]=(0,z.useState)(!1),S=(0,z.useRef)(!1),se=(0,z.useRef)(!1),[Ve,Ne]=(0,z.useState)(!1),[ue,A]=(0,z.useState)(!1),le=(0,z.useMemo)(()=>n.replace(/\/+$/,""),[n]),Q=(0,z.useMemo)(()=>JSON.stringify([le,a,p,l??"",d,e,M??""]),[le,a,p,l,M,d,e]),_e=(0,z.useRef)(Q),dt=_e.current!==Q,[Qe,pt]=(0,z.useState)([]),D=N=>{j&&pt(at=>[...at,`${new Date().toISOString().slice(11,23)} ${N}`])},Z=(0,z.useRef)(k),tt=(0,z.useRef)(U),Ke=(0,z.useRef)(P),mt=(0,z.useRef)(I),Ue=(0,z.useRef)(R),Ge=(0,z.useRef)(x),Yt=(0,z.useRef)(u),Xe=(0,z.useRef)(b),Gt=(0,z.useRef)(h),_=(0,z.useRef)(ye),ve=(0,z.useRef)(c),Je=(0,z.useRef)(t),xe=(0,z.useRef)(null),vt=(0,z.useRef)(0),We=(0,z.useRef)(null),He=(0,z.useRef)(null),nt=(0,z.useRef)(new Map),Ze=(0,z.useRef)(new Map),wn=(0,z.useRef)(!1);(0,z.useEffect)(()=>(wn.current=!0,()=>{wn.current=!1}),[]),(0,z.useEffect)(()=>{Z.current=k},[k]),(0,z.useEffect)(()=>{tt.current=U},[U]),(0,z.useEffect)(()=>{Ke.current=P},[P]),(0,z.useEffect)(()=>{mt.current=I},[I]),(0,z.useEffect)(()=>{Ue.current=R},[R]),(0,z.useEffect)(()=>{Ge.current=x},[x]),(0,z.useEffect)(()=>{Yt.current=u},[u]),(0,z.useEffect)(()=>{Xe.current=b},[b]),(0,z.useEffect)(()=>{Gt.current=h},[h]),(0,z.useEffect)(()=>{_.current=ye},[ye]),(0,z.useEffect)(()=>{ve.current=c},[c]),(0,z.useEffect)(()=>{Je.current=t},[t]),(0,z.useEffect)(()=>{Oe.current=ie},[ie]),(0,z.useEffect)(()=>{Ee&&De.current?.focus()},[Ee,ie]);let ot=(0,z.useCallback)(()=>{window.setTimeout(()=>{De.current?.focus()},0)},[]),$n=(0,z.useCallback)(()=>{ae(!1),je(N=>N+1)},[]),Vt=(0,z.useCallback)(()=>{J(!1),(G.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??G.current)?.focus?.()},[]);(0,z.useEffect)(()=>{!ge||!we.current||(we.current=!1,Vt())},[Vt,ge,ie]);let fn=(0,z.useCallback)((N,at)=>{let Bt=Ue.current;if(Bt){Bt("paypal",N,at);return}Ke.current?.(ds(at?.popupBlocked??Nn(N)))},[]),Jt=()=>{We.current?.timer&&(clearTimeout(We.current.timer),We.current.timer=null)},tr=()=>{Jt();let N=vt.current+1;return vt.current=N,He.current=null,We.current={generation:N,timer:null,yieldedControl:!1},J(!1),N},Tt=N=>N!==void 0&&We.current?.generation!==N?!1:(Jt(),We.current=null,He.current=null,!0),St=N=>{let at=N?.generation??We.current?.generation??vt.current;(!N?.generation||We.current?.generation===at)&&(Jt(),We.current=null),He.current=at,N?.showRetry&&J(!0),N?.remount&&$n(),N?.focus!==!1&&ot()},Xt=N=>We.current?.generation===N&&He.current!==N,Qt=N=>{typeof document<"u"&&document.visibilityState!=="visible"||(Jt(),N.timer=setTimeout(()=>{We.current?.generation===N.generation&&(We.current=null,He.current=N.generation,fn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),J(!0),$n(),ot())},600))},Mt=()=>{let N=We.current;N?.yieldedControl&&Qt(N)},At=()=>{let N=We.current;N&&(N.yieldedControl=!0,Jt())},Ct=N=>{let at=xe.current;return at&&Ze.current.set(N,at),N};(0,z.useEffect)(()=>{let N=()=>{document.visibilityState==="visible"?Mt():At()};return document.addEventListener("visibilitychange",N),window.addEventListener("focus",Mt),window.addEventListener("blur",At),()=>{document.removeEventListener("visibilitychange",N),window.removeEventListener("focus",Mt),window.removeEventListener("blur",At),Jt()}},[]),(0,z.useEffect)(()=>{_e.current!==Q&&(_e.current=Q,S.current=!1,se.current=!1,ae(!1),Le(!1),Ne(!1),Xe.current?.("loading"))},[Q]),(0,z.useEffect)(()=>{ut(()=>Yt.current?.(ge&&!Ve))},[ge,Ve]);let re=(0,Mn.normalizeGatewayEnvironment)(l);(0,z.useEffect)(()=>{let N=a?`${a.slice(0,6)}\u2026(len ${a.length})`:"(empty)",at=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(D(`mount clientId=${N} env=${l??"(unset)"}\u2192${re??"live"} ccy=${p} sub=${d}`),D(`ua=${at.slice(0,80)}${at.length>80?"\u2026":""}`),!a){D("FAIL: clientId empty \u2014 gateway misconfigured"),Ne(!0),Y.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(!G.current){D("FAIL: containerRef not attached");return}pe.current=Y.startTiming(),Y.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Bt=!1,Fn=!1,ze=()=>Bt||Fn,it,Ye=!1,kn=()=>{it=(0,Mn.generateIdempotencyKey)(),it||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Ye=!0},Rn=null,Dn=!1,jn=null,In=!1,rt=()=>{!jn||In||(In=!0,jn.close().catch(()=>{}))},Ft=null,rn=()=>{Ft!==null&&(Y.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),Y.performance({stage:"overlay_return",durationMs:Y.elapsed(Ft),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Ft=null)},gt=!1,It=G.current,Zt=null,on=null,Kt=[],zt=y=>{if(!y||typeof y.getBoundingClientRect!="function")return"(no rect)";let r=y.getBoundingClientRect();return`${Math.round(r.width)}\xD7${Math.round(r.height)}`},Ot=y=>{if(!y)return"(empty)";try{let r=new URL(y,typeof window<"u"?window.location.href:"https://localhost"),g=r.pathname.toLowerCase();return g.includes("checkcaptcha")||g.includes("captcha")?`CAPTCHA(${r.host}${g})`:g.includes("risk")||g.includes("challenge")?`RISK(${r.host}${g})`:g.includes("smart/buttons")?`smart-buttons(${r.host})`:`${r.host}${g}`.slice(0,100)}catch{return y.slice(0,80)}},Me=y=>{let r=y.getAttribute("src"),g=y.getAttribute("srcdoc"),L=y.getAttribute("name"),f=y.getAttribute("sandbox"),K=[];return r&&K.push(`src=${Ot(r)}`),g&&K.push(`srcdoc[${g.length}ch]`),!r&&!g&&K.push("src=(empty) srcdoc=(empty)"),L&&K.push(`name=${L.slice(0,40)}`),f!==null&&K.push(`sandbox="${f.slice(0,40)}"`),K.join(" ")},Nt=y=>{if(!(y instanceof HTMLIFrameElement))return"";try{let r=y.contentDocument;if(!r)return"cd=null";let g=r.body?.children.length??0,L=r.body?.innerHTML.length??0,f=r.head?.innerHTML.length??0;return`cd=same-origin readyState=${r.readyState} body[${g}children,${L}ch] head[${f}ch]`}catch(r){return`cd=cross-origin(${r.message.slice(0,30)})`}},yt=[],gn=y=>{if(ze())return;let r=y.message??String(y.error??"(no message)");r&&(r.toLowerCase().includes("paypal")||r.toLowerCase().includes("zoid")||r.toLowerCase().includes("postrobot")||r.toLowerCase().includes("storage"))&&(D(`window:error ${r.slice(0,140)}`),yt.push(r))},Vn=y=>{if(ze())return;let r=y.reason instanceof Error?y.reason.message:String(y.reason??"(no reason)");r&&(r.toLowerCase().includes("paypal")||r.toLowerCase().includes("zoid")||r.toLowerCase().includes("postrobot")||r.toLowerCase().includes("storage"))&&(D(`window:rejection ${r.slice(0,140)}`),yt.push(r))};j&&typeof window<"u"&&(window.addEventListener("error",gn),window.addEventListener("unhandledrejection",Vn));let Ut={value:0};if(j&&typeof PerformanceObserver<"u")try{on=new PerformanceObserver(y=>{if(!ze())for(let r of y.getEntries()){if(!r.name.toLowerCase().includes("paypal"))continue;Ut.value+=1;let g=Math.round(r.duration);D(`net ${g}ms ${r.name.slice(0,90)}`)}}),on.observe({type:"resource",buffered:!0})}catch{}let $t=()=>{for(Zt?.disconnect(),Zt=null,on?.disconnect(),on=null;Kt.length;)clearTimeout(Kt.pop());j&&typeof window<"u"&&(window.removeEventListener("error",gn),window.removeEventListener("unhandledrejection",Vn))},Dt=y=>{if(!y)return!1;let r=y.toLowerCase();return r.includes("zoid destroyed")||r.includes("destroyed all components")||r.includes("window closed")||r.includes("detected container element removed")},Ln=y=>{if(ze()||Dt(y))return;let r=On(y)??y;ut(()=>Ke.current?.(r))},zn=y=>{Bt||(Ne(!0),y.includes("paypal_ineligible")||Y.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",y))},en=(y,r=!1)=>{if(Bt)return;let g=S.current||!E;if(Dn)return;Dn=!0,Fn=!0,$t(),rt();let L=r||Va(y);if(L&&E&&!S.current){S.current=!0,ae(!1),A(!1),Le(!0),Xe.current?.("retrying"),Rn=setTimeout(()=>{Bt||je(f=>f+1)},is);return}if(L||g){if(ae(!1),A(!1),Le(!1),Ne(!0),Xe.current?.("exhausted"),!se.current){se.current=!0;let f=Va(y)?"paypal_init_timeout":r?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",f)}return}zn(y)};Ne(!1);let Ht=async(y,r=xe.current)=>{if(ze())return;let g=r?.sessionId??e;if(Z.current){await Z.current(y,{sessionId:g,accountPatch:r?.accountPatch,nonce:r?.nonce});return}let L=Y.startTiming();Y.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let f=()=>{Y.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Y.performance({stage:"processing",durationMs:Y.elapsed(L),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let K=_.current,Te=r?.accountPatch?.email??ve.current,st=r?.accountPatch?.userId??K?.customer?.id??K?.accountData?.userId??"",H=await new ao.PaymentAPI(le,{telemetry:!1}).processPayment(st,{sessionId:g,nonce:r?.nonce??Je.current,tokenizedData:y,accountData:{userId:st,email:Te??K?.customer?.email??"",firstName:r?.accountPatch?.firstName??K?.customer?.firstName??K?.accountData?.firstName??"",lastName:r?.accountPatch?.lastName??K?.customer?.lastName??K?.accountData?.lastName??"",country:r?.accountPatch?.country??K?.customer?.country??K?.accountData?.country??void 0,zip:r?.accountPatch?.zip??K?.customer?.zip??K?.accountData?.zip??void 0}});if(H.ok){if(Fn||Bt&&wn.current)return;f(),Y.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ut(()=>tt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ze())return;let m=await H.json().catch(()=>null),q=m?.message??"PayPal payment failed.",he=On(q)??q;f(),H.status===400&&(typeof m?.declineCode=="string"||!Array.isArray(m?.fields))?Y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):H.status===400||H.status===422?Y.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):Y.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:H.status>=500?"5xx":H.status>=400?"4xx":H.status>=300?"3xx":"unknown",failureCategory:H.status>=500?"server_error":void 0}),Ln(he),ut(()=>mt.current?.(Rt("paypal",he,{code:m?.code,declineCode:m?.declineCode})));return}catch(K){if(ze())return;f(),Y.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Te=K instanceof Error?K.message:"PayPal payment failed.",st=On(Te)??Te;Ln(st),ut(()=>mt.current?.(Rt("paypal",st)));return}},tn=()=>new Mn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),$e=y=>ze()?Promise.reject(tn()):Promise.resolve(y),T=async y=>{if(ze())throw tn();Ye||kn();let r=xe.current,g=r?.sessionId??e,L=r?.nonce??Je.current;Y.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let f=await new ao.PaymentAPI(le,{telemetry:!1}).createSessionIntent(g,L??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:it});if(ze())throw tn();if(f.provider!=="paypal")throw new Error(y);return Y.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),f.providerObjectId},$=(y,r)=>{let g=r?.nonce??Je.current;if(!g)return;let L=r?.sessionId??e,f=pr(y)??Tn(y)??"provider_declined";new ao.PaymentAPI(le,{telemetry:!1}).reportSessionIntentDecline(L,g,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:f}).catch(()=>{})},B=ie;D("loadScript:scheduled (deferred 1 tick)");let Ce=null,ke=setTimeout(()=>{if(Bt){D("loadScript:skipped (cancelled before defer ran)");return}D("loadScript:start");let y=re==="live"?"production":re;Ce=(0,Ka.loadScript)({clientId:a,currency:p,intent:d?"subscription":"capture",vault:d?!0:void 0,...y?{environment:y}:{},...y==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Ce.then(r=>{if(D(`loadScript:resolved inactive=${ze()} ns=${!!r} buttons=${!!r?.Buttons}`),ze())return;if(!r?.Buttons){D("FAIL: namespace missing Buttons factory"),en("PayPal SDK did not expose the Buttons factory.");return}Y.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),Y.performance({stage:"provider_ready",durationMs:Y.elapsed(pe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Y.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let g=async ee=>{if(ze()||Oe.current!==B)return;let H=ee.subscriptionID??ee.orderID??"",m=H?Ze.current.get(H):nt.current.get(B);if(!(!m||!Xt(m.generation))&&Tt(m.generation)){Ze.current.delete(H),nt.current.delete(m.surfaceKey),rn();try{if(A(!0),ut(()=>Ke.current?.(null)),!H)throw new Mn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Ht({id:H,isPaypal:!0},m)}catch(q){Ln(q instanceof Error?q.message:"PayPal capture failed.")}finally{ze()||A(!1)}}},L=r.Buttons({style:{layout:"horizontal",height:io,tagline:!1},onClick:async(ee,H)=>{if(ze()){await H.reject();return}kn();let m=Gt.current,q={};if(m)try{let Ae=await m("paypal");if(ze()){await H.reject();return}if(!Ae.proceed){xe.current=null,nt.current.delete(B),await H.reject();return}q={sessionId:Ae.sessionId,accountPatch:Ae.accountPatch,nonce:Ae.nonce}}catch(Ae){D(`onClick:runBeforeButtonClick rejected msg=${(Ae instanceof Error?Ae.message:String(Ae)).slice(0,120)}`),xe.current=null,nt.current.delete(B),await H.reject();return}ut(()=>Ge.current?.("paypal"));let Ie={generation:tr(),surfaceKey:B,...q};xe.current=Ie,nt.current.set(B,Ie),await H.resolve(),Y.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Y.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Y.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Ft=Y.startTiming()},createOrder:d?void 0:M?()=>$e(M).then(Ct):()=>T("Failed to create PayPal order.").then(Ct),createSubscription:d?M?()=>$e(M).then(Ct):()=>T("Failed to create PayPal subscription.").then(Ct):void 0,onApprove:g,onCancel:()=>{if(ze())return;let ee=nt.current.get(B)??xe.current;ee&&nt.current.delete(ee.surfaceKey),xe.current=null,rn(),Y.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we.current=!0,St({generation:ee?.generation,remount:!0,focus:!1})},onError:ee=>{if(ze()||Oe.current!==B)return;let H=ee instanceof Error?ee.message:"PayPal failed to render.";if(D(`onError rendered=${gt} msg=${H.slice(0,120)}`),gt){let m=nt.current.get(B)??xe.current;if(m&&!Xt(m.generation)||!m&&He.current===vt.current)return;if(Dt(H)){Tt(m?.generation);return}if(rn(),Mr(ee)){Y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),$(ee,m),ut(()=>mt.current?.(Rt("paypal",H))),m&&nt.current.delete(m.surfaceKey),xe.current=null,Tt(m?.generation);return}let q=H.toLowerCase();Y.error({errorCode:q.includes("popup")&&q.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),m&&nt.current.delete(m.surfaceKey),xe.current=null,St({generation:m?.generation,remount:!0,showRetry:!0,focus:!0}),fn(ee,{code:"paypal_runtime_failed"});return}en(H)}}),f=L.isEligible();if(D(`isEligible=${f}`),Y.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!f){ae(!1),en("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}jn=L,j&&D(`container:dims ${zt(It)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),j&&typeof MutationObserver<"u"&&(Zt=new MutationObserver(ee=>{if(!ze()){for(let H of ee)if(H.type==="childList")H.addedNodes.forEach(m=>{if(!(m instanceof Element))return;let q=m.tagName.toLowerCase(),he=(m.getAttribute("title")??"").slice(0,40),Ie=q==="iframe"?` ${Me(m)}`:"";D(`child+ ${q}${he?` title="${he}"`:""}${Ie} dims=${zt(m)}`)});else if(H.type==="attributes"&&H.target instanceof Element){let m=H.target;if(m.tagName.toLowerCase()!=="iframe")continue;let q=H.attributeName;(q==="src"||q==="srcdoc")&&D(`attr~ iframe ${q}=${q==="srcdoc"?`[${(m.getAttribute("srcdoc")??"").length}ch]`:Ot(m.getAttribute("src"))} dims=${zt(m)}`)}}}),Zt.observe(It,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Te=ee=>{if(ze()||gt)return;let H=It.querySelectorAll("iframe"),m=typeof document<"u"&&"hasStorageAccess"in document;D(`watchdog:${ee} container=${zt(It)} children=${It.childElementCount} iframes=${H.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${m} paypalNetRequests=${Ut.value}`),H.forEach((q,he)=>{let Ie=(q.getAttribute("title")??"").slice(0,40);D(` iframe[${he}] ${zt(q)}${Ie?` title="${Ie}"`:""} ${Me(q)}`);let Ae=Nt(q);Ae&&D(` ${Ae}`)}),yt.length===0&&D(" (no PayPal/zoid window errors captured)")};j&&(Kt.push(setTimeout(()=>Te("3s"),3e3)),Kt.push(setTimeout(()=>Te("8s"),8e3)),Kt.push(setTimeout(()=>Te("15s"),15e3))),D("render:start");let st=Y.startTiming();Kt.push(setTimeout(()=>{ze()||gt||(D("watchdog:11s retryable render timeout"),en("PayPal Buttons render did not settle within 11000ms.",!0))},ss)),L.render(It).then(()=>{if(D(`render:resolved inactive=${ze()}`),$t(),ze()){rt();return}gt=!0,ae(!0),Le(!1),Xe.current?.("ready"),Y.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),Y.performance({stage:"checkout_render",durationMs:Y.elapsed(st),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(ee=>{let H=ee instanceof Error?ee.message:"PayPal failed to render.";D(`render:rejected msg=${H.slice(0,120)}`),$t(),en(H)})}).catch(r=>{let g=r instanceof Error?r.message:"PayPal SDK failed to load.";D(`loadScript:rejected msg=${g.slice(0,120)}`),en(g)})},0);return()=>{Bt=!0,clearTimeout(ke),Rn&&clearTimeout(Rn),$t(),rt()}},[E,le,a,p,l,d,e,M,ie,Y]);let qn=j?(0,dn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ve?"#fef2f2":"#f3f4f6",border:`1px solid ${Ve?"#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=${ge} failed=${Ve})`,Qe.length===0?`
|
|
7
7
|
(waiting for first lifecycle event\u2026)`:`
|
|
8
|
-
${
|
|
9
|
-
`)}`]}):null;return
|
|
8
|
+
${Qe.join(`
|
|
9
|
+
`)}`]}):null;return Ve&&!dt?j?(0,dn.jsx)("div",{children:qn}):null:(0,dn.jsxs)("div",{children:[qn,(0,dn.jsxs)("div",{"aria-hidden":be?!0:void 0,style:be?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:io},children:[!ge&&!be&&(0,dn.jsx)("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"}}),(0,dn.jsx)("div",{ref:G,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:io,display:"flex",opacity:ge?1:0},"aria-busy":ue||O},ie)]},ie),Ee&&(0,dn.jsx)("button",{ref:De,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Vt,style:cs,children:"Try PayPal again"})]})}function Ar(e){return(0,dn.jsx)(Ha,{...e})}function Wa(e){return(0,dn.jsx)(Ha,{...e})}var Lt=require("@flopay/shared"),s=require("react/jsx-runtime"),Sn="flopay_stripe_resume",Ya="flopay_wallet_resume",Br="flopay_paypal_resume",us=250,Ga="Just a moment \u2014 we are finalizing your order. Please press pay again.";function jo(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function co({billingApiUrl:e,sessionId:t,nonce:n,request:c}){if(!(!t||!n))try{await new un.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,c)}catch{}}function ps(e){return e instanceof Lt.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Uo(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function so(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let c=parseInt(n[1],16),a=Math.max(0,Math.min(1,1-t)),l=Math.round((c>>16&255)*a),p=Math.round((c>>8&255)*a),d=Math.round((c&255)*a);return`#${(1<<24|l<<16|p<<8|d).toString(16).slice(1)}`}var ms=`
|
|
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 @@ ${He.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
|
-
`,no=44;function No(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 ls={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Xa={width:"100%",minHeight:no,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function cs(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Va(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Qa(e){return e==="paypal"?"PayPal":(0,R.getStripeMethodDisplayName)(e)}function ds(e,t){let n=`We couldn't open ${Qa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Za(e){let t=(0,r.useRef)(0),n=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useCallback)((p=l.current)=>{let v=p;v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),s=(0,r.useCallback)((p,v)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(p),p.timer=setTimeout(()=>{p.timer=null,l.current?.generation===p.generation&&(l.current=null,n.current=p.generation,e(p.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},v))},[o,e]),m=(0,r.useCallback)(p=>{p.yieldedControl&&s(p,600)},[s]),d=(0,r.useCallback)(p=>{o();let v=t.current+1;t.current=v,n.current=null;let x={generation:v,method:p,timer:null,yieldedControl:!1};return l.current=x,v},[o]),I=(0,r.useCallback)(p=>{let v=l.current;return typeof p=="number"&&v?.generation!==p?!1:(o(v),l.current=null,(typeof p!="number"||n.current===p)&&(n.current=null),!0)},[o]),N=(0,r.useCallback)(p=>{let v=l.current,x=p??v?.generation??t.current;(!p||v?.generation===p)&&(o(v),l.current=null),n.current=x},[o]),b=(0,r.useCallback)(p=>n.current===(p??t.current),[]),_=(0,r.useCallback)(p=>l.current?.generation===p&&n.current!==p,[]),k=(0,r.useCallback)(()=>{let p=l.current;p&&m(p)},[m]),F=(0,r.useCallback)(()=>{let p=l.current;p&&(p.yieldedControl=!0,o(p))},[o]);return(0,r.useEffect)(()=>{let p=()=>{document.visibilityState==="visible"?k():F()},v=()=>{F()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",v),window.addEventListener("focus",k),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",v),window.removeEventListener("focus",k),o()}},[o,F,k]),{startAttempt:d,finishAttempt:I,invalidateAttempt:N,isAttemptInvalidated:b,isAttemptCurrent:_}}function us(e){let t=(0,R.getPostalCodeExample)(e);return`Enter a valid ${(0,R.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function ps(e,t,n){let l=(0,R.isPostalCodeSupported)(e),o=t.trim(),s=n&&l,m=s&&!o,d=s&&!!o&&!(0,R.isValidPostalCode)(e,o);return{visible:n,supported:l,required:s,empty:m,malformed:d}}function Ka(e,t){return t instanceof Ut.FloPayError?t:new Ut.FloPayError(t instanceof Error?t.message:`${cs(e)} before-click hook failed.`,"validation_error")}function Fo(){return(0,i.jsx)("style",{children:ss})}function ms(e){return typeof e=="number"?`${e}px`:e}function Ha(e){if(typeof e=="number"||typeof e=="string")return e}function ei(e,t){let n=e.availablePaymentMethods;return n&&t.some(l=>n[l])?"ready":"unavailable"}function ti({state:e,placeholderTestId:t,borderRadius:n=8,children:l}){return e==="unavailable"||e==="load_error"?null:(0,i.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,i.jsx)("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"}}),(0,i.jsx)("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:l})]})}function Wa(e){return e!=="unavailable"&&e!=="load_error"}function oo(e){return(0,i.jsx)(fs,{...e})}function Ya({sessionId:e,nonce:t,email:n,billingApiUrl:l,onTokenizedBody:o,onErrorChange:s,isProcessing:m=!1,onButtonClick:d,onDecline:I,onTechnicalFailure:N,runBeforeButtonClick:b,onLoadStateChange:_,placeholderBorderRadius:k}){let F=un(),p=(0,lt.useStripe)(),v=(0,lt.useElements)(),[x,M]=(0,r.useState)("loading");(0,r.useEffect)(()=>{_?.(x)},[x,_]);let[g,he]=(0,r.useState)(!1),z=(0,r.useRef)(!1),ue=(0,r.useRef)(null),ae=(0,r.useRef)(null),[U,te]=(0,r.useState)(0),[Q,pe]=(0,r.useState)(!1),W=(0,r.useRef)(!1),J=(0,r.useRef)(new Map),{startAttempt:me,finishAttempt:Me,invalidateAttempt:we,isAttemptInvalidated:be,isAttemptCurrent:ie}=Za((Z,T,ce)=>{N?.(Z,T,{...ce,popupBlocked:ce?.popupBlocked??zn(T)}),pe(!0),te(Oe=>Oe+1)});(0,r.useEffect)(()=>{Q&&ae.current?.focus()},[Q,U]);let Ce=(0,r.useCallback)(()=>{te(Z=>Z+1)},[]),Be=(0,r.useCallback)((Z,T,ce)=>{we(ce),N?.("paypal",Z,{code:T,popupBlocked:zn(Z)}),pe(!0),Ce()},[we,N,Ce]),se=(0,r.useCallback)(()=>{window.setTimeout(()=>{(ue.current?.querySelector("iframe")??ue.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{W.current&&(W.current=!1,se())},[se,U]);let Ee=(0,r.useCallback)(()=>{pe(!1),s?.(null),se()},[se,s]);(0,r.useEffect)(()=>{if(!p||z.current)return;let Z=new URLSearchParams(window.location.search),T=Z.get("payment_intent"),ce=Z.get("payment_intent_client_secret"),Oe=Z.get("redirect_status");if(!T||!ce)return;z.current=!0;let ze;try{let E=localStorage.getItem(_r);if(E){let re=JSON.parse(E);re.clientSecret===ce&&(ze={...re.accountPatch?{accountPatch:re.accountPatch}:{},...re.sessionId?{sessionId:re.sessionId}:{},...re.nonce?{nonce:re.nonce}:{}})}}catch{}try{localStorage.removeItem(_r)}catch{}let ye=new URL(window.location.href);ye.searchParams.delete("payment_intent"),ye.searchParams.delete("payment_intent_client_secret"),ye.searchParams.delete("redirect_status"),window.history.replaceState({},"",ye.toString()),(async()=>{try{if(he(!0),Oe==="failed"){let oe="PayPal payment was declined. Please try again.";s?.(oe),I?.(wt("paypal",oe));return}let{paymentIntent:E,error:re}=await p.retrievePaymentIntent(ce);if(re){s?.(re.message??"Failed to retrieve PayPal payment status.");return}if(E&&(E.status==="requires_capture"||E.status==="succeeded")){let oe=typeof E.payment_method=="string"?E.payment_method:E.payment_method?.id;o({id:oe??E.id,type:"card",threeDSecureActionResultTokenId:E.id,isPaypal:!0},ze)}else{let oe="PayPal payment was not completed. Please try again.";s?.(oe),I?.(wt("paypal",oe))}}catch(E){s?.(E instanceof Error?E.message:"Failed to complete PayPal payment.")}finally{he(!1)}})()},[p,o,s,I]);let _e=(0,r.useCallback)(async Z=>{if(m||g){Z.reject();return}let T=b?await b("paypal"):{proceed:!0};if(!T.proceed){J.current.delete(U),Z.reject();return}let ce=me("paypal");J.current.set(U,{generation:ce,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),pe(!1),d?.("paypal"),Z.resolve()},[J,m,d,b,me,g,U]),Re=(0,r.useCallback)(async Z=>{if(!p||!v)return;let T=J.current.get(U);if(T&&!ie(T.generation)){J.current.delete(U);return}if(!T&&be()||T&&!Me(T.generation))return;T||Me();let ce=T??null;if(J.current.delete(U),!ce&&b){let E=await b("paypal");if(!E.proceed){Z.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ce={accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}}let Oe=ce?.sessionId??e,ze=ce?.nonce??t,ye=ce?.accountPatch?.email??n;try{if(he(!0),s?.(null),!Oe||!ye)throw new Error("Missing sessionId or email for PayPal payment");let E=p.createPaymentMethod,{error:re,paymentMethod:oe}=await E({type:"paypal"});if(re){Be(re,"stripe_paypal_create_payment_method_failed",T?.generation),Z.paymentFailed({reason:"fail"});return}let $e=await new mn.PaymentAPI(l).createSessionIntent(Oe,ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:oe?.id??null,intentKind:"payment"});if($e.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ct=$e.clientSecret,He={return_url:window.location.href};if(oe?.id&&(He.payment_method=oe.id),typeof window<"u")try{localStorage.setItem(_r,JSON.stringify({clientSecret:ct,sessionId:Oe,nonce:ze,accountPatch:ce?.accountPatch}))}catch{}let{error:ot,paymentIntent:V}=await p.confirmPayment({clientSecret:ct,confirmParams:He,redirect:"if_required"});if(ot){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}if(Ir(ot)){let tt=ot.message??"Your payment was declined.";s?.(tt),I?.(wt("paypal",tt,{code:xn(ot),declineCode:lr(ot)})),await ro({billingApiUrl:l,sessionId:Oe,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:xn(ot)??"provider_declined"}})}else Be(ot,"stripe_paypal_confirm_failed",T?.generation);return}if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let G=typeof V?.payment_method=="string"?V.payment_method:V?.payment_method?.id;o({id:G??V?.id,type:"card",threeDSecureActionResultTokenId:V?.id,isPaypal:!0},{accountPatch:ce?.accountPatch,sessionId:Oe,nonce:ze});return}catch(E){Be(E,"stripe_paypal_failed",T?.generation)}finally{he(!1)}},[p,v,e,t,n,l,o,s,I,b,Be,Me,ie,be,U]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(ti,{state:x,placeholderTestId:"flopay-paypal-placeholder",borderRadius:k,children:(0,i.jsxs)("div",{ref:ue,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Q&&(0,i.jsx)("button",{ref:ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ee,style:Xa,children:"Try PayPal again"}),(0,i.jsx)(lt.ExpressCheckoutElement,{onReady:Z=>M(ei(Z,["paypal"])),onLoadError:()=>{M("load_error"),Lo(Mt(F),"paypal","paypal")},onClick:_e,onConfirm:Re,onCancel:()=>{let Z=J.current.get(U);J.current.delete(U),Mt(F)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we(Z?.generation),pe(!1),W.current=!0,Ce()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},U)]})}),g&&(0,i.jsx)(Sn,{status:"processing"})]})}function Ga({sessionId:e,nonce:t,email:n,billingApiUrl:l,intentKind:o,expressMethods:s,onTokenizedBody:m,onErrorChange:d,onButtonClick:I,onDecline:N,onTechnicalFailure:b,runBeforeButtonClick:_,onLoadStateChange:k,placeholderBorderRadius:F}){let p=un(),v=(0,lt.useStripe)(),x=(0,lt.useElements)(),[M,g]=(0,r.useState)("loading");(0,r.useEffect)(()=>{k?.(M)},[M,k]);let[he,z]=(0,r.useState)(!1),ue=(0,r.useRef)(null),ae=(0,r.useRef)(null),[U,te]=(0,r.useState)(0),[Q,pe]=(0,r.useState)(!1),[W,J]=(0,r.useState)("google_pay"),me=(0,r.useRef)(!1),Me=(0,r.useRef)("google_pay"),we=(0,r.useRef)("google_pay"),be=(0,r.useRef)(new Map),{startAttempt:ie,finishAttempt:Ce,invalidateAttempt:Be,isAttemptInvalidated:se,isAttemptCurrent:Ee}=Za((ye,E,re)=>{b?.(ye,E,{...re,popupBlocked:re?.popupBlocked??zn(E)}),J(ye),pe(!0),te(oe=>oe+1)});(0,r.useEffect)(()=>{Q&&ae.current?.focus()},[Q,U]);let _e=(0,r.useCallback)(()=>{te(ye=>ye+1)},[]),Re=(0,r.useCallback)((ye,E,re,oe)=>{Be(oe),b?.(ye,E,{code:re,popupBlocked:zn(E)}),J(ye),pe(!0),_e()},[Be,b,_e]),Z=(0,r.useCallback)(()=>{window.setTimeout(()=>{(ue.current?.querySelector("iframe")??ue.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{me.current&&(me.current=!1,Z())},[Z,U]);let T=(0,r.useCallback)(()=>{pe(!1),d?.(null),Z()},[Z,d]),ce=(0,r.useCallback)(async ye=>{if(!v||!x)return;let E=be.current.get(U);if(E&&!Ee(E.generation)){be.current.delete(U);return}if(!E&&se()||E&&!Ce(E.generation))return;E||Ce();let re=ye.expressPaymentType??E?.method??Me.current,oe=E??null;be.current.delete(U);let $e=Va(re);if(!oe&&_){let G=await _($e);if(!G.proceed){ye.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}oe={accountPatch:G.accountPatch,sessionId:G.sessionId,nonce:G.nonce}}let ct=$e,He=oe?.sessionId??e,ot=oe?.nonce??t,V=oe?.accountPatch?.email??n;try{z(!0),d?.(null);let{error:G}=await x.submit();if(G){Re(re,G,"stripe_wallet_submit_failed",E?.generation);return}let{error:tt,paymentMethod:Ae}=await v.createPaymentMethod({elements:x});if(tt||!Ae){Re(re,tt??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",E?.generation);return}if(!He||!V)throw new Error("Missing sessionId or email for wallet payment");let at=await new mn.PaymentAPI(l).createSessionIntent(He,ot??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:re??$e,paymentMethodId:Ae.id,intentKind:o});if(at.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Ge=at.clientSecret,{error:We,intentId:rn}=(0,Ut.isSetupIntentClientSecret)(Ge)?await v.confirmCardSetup(Ge,{payment_method:Ae.id}).then(h=>({error:h.error,intentId:h.setupIntent?.id})):await v.confirmCardPayment(Ge,{payment_method:Ae.id}).then(h=>({error:h.error,intentId:h.paymentIntent?.id}));if(We){if(Ir(We)){let h=We.message??"Your payment was declined.";d?.(h),N?.(wt(ct,h,{code:xn(We),declineCode:lr(We)})),await ro({billingApiUrl:l,sessionId:He,nonce:ot,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:re??$e,providerDeclineReason:xn(We)??"provider_declined"}})}else Re(re,We,"stripe_wallet_confirm_failed",E?.generation);return}m({id:Ae.id,type:"card",threeDSecureActionResultTokenId:rn},{accountPatch:oe?.accountPatch,sessionId:He,nonce:ot})}catch(G){Re(re,G,"stripe_wallet_failed",E?.generation)}finally{z(!1)}},[v,x,e,t,n,l,o,m,d,N,_,Re,Ce,Ee,se,U]),Oe=(0,r.useMemo)(()=>{let ye=["applePay","googlePay","paypal","link","amazonPay","klarna"],E=new Set(["applePay","googlePay"]),re=new Set(s.map(R.stripeExpressMethodToOptionKey)),oe={};for(let $e of ye)re.has($e)?oe[$e]=E.has($e)?"always":"auto":oe[$e]="never";return oe},[s]),ze=(0,r.useMemo)(()=>s.map(R.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(ti,{state:M,placeholderTestId:"flopay-wallet-placeholder",borderRadius:F,children:(0,i.jsxs)("div",{ref:ue,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Q&&(0,i.jsxs)("button",{ref:ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:T,style:Xa,children:["Try ",Qa(W)," again"]}),(0,i.jsx)(lt.ExpressCheckoutElement,{onReady:ye=>{g(ei(ye,ze))},onLoadError:ye=>{g("load_error"),Lo(Mt(p),"stripe","wallet")},onClick:async ye=>{Me.current=ye.expressPaymentType,we.current=Va(ye.expressPaymentType);let E=_?await _(we.current):{proceed:!0};if(!E.proceed){be.current.delete(U),ye.reject();return}let re=ie(ye.expressPaymentType);be.current.set(U,{generation:re,method:ye.expressPaymentType,accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}),pe(!1),I?.(we.current),ye.resolve()},onConfirm:ce,onCancel:()=>{let ye=be.current.get(U);be.current.delete(U),Mt(p)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Be(ye?.generation),pe(!1),me.current=!0,_e()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Oe,layout:{maxColumns:1,overflow:"never"}}},U)]})}),he&&(0,i.jsx)(Sn,{status:"processing"})]})}function ys({method:e,themeId:t,submitting:n=!1,disabled:l=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:m,backgroundColor:d,borderColor:I,textColor:N,borderRadius:b,fontFamily:_}){let k=(0,R.resolveStripeMethodBrandVariant)(e,t),F=_a[e],p=k?.backgroundColor??d??"#ffffff",v=k?.borderColor??I??"#d1d5db",x=k?.textColor??N??"#262833";return(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!l&&m()},disabled:n||l,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:no,padding:"0 1rem",backgroundColor:p,color:x,border:`1px solid ${v}`,borderRadius:b??8,fontSize:"0.95rem",fontWeight:600,fontFamily:_,cursor:n||l?"not-allowed":"pointer",opacity:l&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,i.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,R.getStripeMethodDisplayName)(e)}\u2026`}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,R.hasVendoredStripeMethodLogo)(e)?8:0},children:[F?(0,i.jsx)("img",{src:F,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"}}):k?.logoSvg?(0,i.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:k.logoSvg}}):null,(0,i.jsx)("span",{children:(0,R.getStripeMethodDisplayName)(e)})]}),s&&(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:x,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:(0,i.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Do({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:m,onErrorChange:d,onDecline:I,onCancel:N,runBeforeButtonClick:b,onButtonClick:_,isProcessing:k,submitButtonColor:F,submitButtonBorderRadius:p,submitButtonStyle:v,errorText:x}){let M=un(),g=(0,lt.useStripe)(),he=(0,lt.useElements)(),[z,ue]=(0,r.useState)(!1),ae=(0,r.useRef)(!1),[U,te]=(0,r.useState)(!1),[Q,pe]=(0,r.useState)("loading"),W=(0,r.useCallback)(async()=>{if(!g||!he||k||ae.current||!U)return;ae.current=!0,ue(!0);let J=b?await b("card"):{proceed:!0};if(!J.proceed){ae.current=!1,ue(!1);return}_?.("card");let me=J.sessionId??t,Me=J.nonce??n,we=J.accountPatch?.email??l;try{d?.(null);let be=await he.submit();if(be.error){d?.(be.error.message??"Payment failed.");return}let ie=await g.createPaymentMethod({elements:he});if(ie.error||!ie.paymentMethod){d?.(ie.error?.message??"Failed to create payment method.");return}let Ce=ie.paymentMethod;if(!me||!we)throw new Error("Missing sessionId or email for payment.");let Be=Ce.type||e,se=await new mn.PaymentAPI(s).createSessionIntent(me,Me??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Be,paymentMethodId:null,intentKind:"payment"});if(se.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ee=se.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Ee,sessionId:me,nonce:Me,accountPatch:J.accountPatch,paymentMethodId:Ce.id,paymentMethodType:Ce.type??e,gateway:"stripe"}))}catch{}let{error:_e,paymentIntent:Re}=await g.confirmPayment({clientSecret:Ee,confirmParams:{return_url:window.location.href,payment_method:Ce.id},redirect:"if_required"});if(_e){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ce=_e.message??"Payment failed.";d?.(ce),I?.(wt("card",ce,{code:_e.code})),await ro({billingApiUrl:s,sessionId:me,nonce:Me,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:_e.code??"provider_declined"}});return}let Z=Re?.status;if(!Jr(Z)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ce=Z==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(ce),I?.(wt("card",ce,{code:Z??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let T=typeof Re?.payment_method=="string"?Re.payment_method:Re?.payment_method?.id;m({id:T??Ce.id,type:"card",threeDSecureActionResultTokenId:Re?.id,gateway:"stripe",paymentMethodType:Ce.type??e},{accountPatch:J.accountPatch,sessionId:me,nonce:Me})}catch(be){d?.(be instanceof Error?be.message:"Payment failed. Please try again.")}finally{ae.current=!1,ue(!1)}},[g,he,k,U,b,_,t,n,l,s,e,m,d,I]);return(0,i.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,i.jsx)(lt.PaymentElement,{onReady:()=>pe("ready"),onLoadError:()=>{pe("load_error"),Lo(Mt(M),"stripe","apm")},onChange:J=>{te(!!J.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...l?{email:l}:{}}}}}),(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{W()},disabled:!U||z||k||Q!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:F,color:"white",border:"none",borderRadius:p,fontSize:"1rem",fontWeight:600,cursor:!U||z||k||Q!=="ready"?"not-allowed":"pointer",opacity:!U||z||k||Q!=="ready"?.5:1,transition:"opacity 120ms ease-out",...v??{}},children:z?"Processing\u2026":`Pay with ${(0,R.getStripeMethodDisplayName)(e)}`}),x&&(0,i.jsx)(ar,{margin:"0.75rem 0 0",children:x})]})}function Ja({sessionId:e,nonce:t,email:n,billingName:l,billingApiUrl:o,paymentElementMethods:s,stripeInstance:m,paymentElementBaseOptions:d,onTokenizedBody:I,onErrorChange:N,onButtonClick:b,onDecline:_,runBeforeButtonClick:k,onLoadStateChange:F,isProcessing:p=!1,submitButtonColor:v="#4A49FF",submitButtonBorderRadius:x=8,submitButtonStyle:M,buttonAppearance:g,themeId:he,onExpandApm:z,expandedApmMethod:ue}){let[ae,U]=(0,r.useState)(null),[te,Q]=(0,r.useState)(null),pe=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&m?F?.("ready"):m||F?.("loading")},[s.length,m,F]);let W=(0,r.useCallback)(async ie=>{if(!m||pe.current||p)return;pe.current=!0,Q(ie);let Ce=k?await k("card"):{proceed:!0};if(!Ce.proceed){pe.current=!1,Q(null);return}b?.("card");let Be=Ce.sessionId??e,se=Ce.nonce??t,Ee=Ce.accountPatch?.email??n;try{if(N?.(null),!Be||!Ee)throw new Error("Missing sessionId or email for payment.");let _e=await new mn.PaymentAPI(o).createSessionIntent(Be,se??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ie,paymentMethodId:null,intentKind:"payment"});if(_e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Re=_e.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Re,sessionId:Be,nonce:se,accountPatch:Ce.accountPatch,paymentMethodType:ie,gateway:"stripe"}))}catch{}let{error:Z,paymentIntent:T}=await m.confirmPayment({clientSecret:Re,confirmParams:{return_url:window.location.href,payment_method_data:{type:ie,billing_details:{name:l&&l.trim().length>=3?l.trim():"FloPay Customer",...Ee?{email:Ee}:{}}}},redirect:"if_required"});if(Z){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=Z.message??"Payment failed.";N?.(ze),_?.(wt("card",ze,{code:Z.code})),await ro({billingApiUrl:o,sessionId:Be,nonce:se,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ie,providerDeclineReason:Z.code??"provider_declined"}});return}let ce=T?.status;if(!Jr(ce)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=ce==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";N?.(ze),_?.(wt("card",ze,{code:ce??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let Oe=typeof T?.payment_method=="string"?T.payment_method:T?.payment_method?.id;I({id:Oe??T?.id,type:"card",threeDSecureActionResultTokenId:T?.id,gateway:"stripe",paymentMethodType:ie},{accountPatch:Ce.accountPatch,sessionId:Be,nonce:se})}catch(_e){N?.(_e instanceof Error?_e.message:"Payment failed. Please try again.")}finally{pe.current=!1,Q(null)}},[m,p,k,b,e,t,n,o,l,I,N,_]),[J,me]=(0,r.useState)(null),Me=z?ue??null:J,we=(0,r.useCallback)(ie=>{pe.current||p||Me&&Me!==ie||((0,R.needsStripeMethodExplicitConfirm)(ie)?z?z(ie):me(ie):W(ie))},[Me,p,W,z]),be=(0,r.useMemo)(()=>J?{...d,paymentMethodTypes:[J]}:null,[J,d]);return(0,i.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(ie=>{let Ce=ue===ie,Be=te===ie,se=te!==null&&te!==ie||ue!=null&&ue!==ie;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(ys,{method:ie,themeId:he,submitting:Be,disabled:se,highlighted:Ce,hasNextStep:(0,R.needsStripeMethodExplicitConfirm)(ie),onClick:()=>we(ie),backgroundColor:g?.backgroundColor,borderColor:g?.borderColor,textColor:g?.textColor,borderRadius:g?.borderRadius,fontFamily:g?.fontFamily}),!z&&J===ie&&be&&m&&(0,i.jsx)(lt.Elements,{stripe:m,options:be,children:(0,i.jsx)(Do,{method:ie,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:I,onErrorChange:N,onDecline:_,onCancel:()=>me(null),runBeforeButtonClick:k,onButtonClick:b,isProcessing:p,submitButtonColor:v,submitButtonBorderRadius:x,submitButtonStyle:M})},ie)]},ie)})})}function fs({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:m,onDecline:d,onTokenizedBody:I,firstName:N,lastName:b,chv:_,className:k,isProcessing:F,error:p,onErrorChange:v,showPayPal:x=!0,showStripe:M=!0,enabledPaymentMethods:g,enabledPaymentMethodCountries:he,showApplePay:z=!0,showGooglePay:ue=!0,layout:ae="default",theme:U,buttonsTheme:te,buttonsStyles:Q,appearance:pe,cardButtonContent:W,cardBackButtonContent:J,cardTitleContent:me,showSecurityFooter:Me,onButtonClick:we,onBeforeButtonClick:be,enableAVS:ie,cardFieldOrder:Ce,cardPreFormSlot:Be,avsLayout:se="row",country:Ee,zip:_e,addressLine1:Re,addressLine2:Z,city:T,state:ce,onCountryChange:Oe,onZipChange:ze,avsCheck:ye,checkoutType:E,checkoutLayout:re,totalAmount:oe=0,currency:$e="usd",initialCardOpen:ct=!1,directPaypal:He,isSubscription:ot=!1,session:V,dataAttachmentPending:G=!1,debug:tt=!1}){let Ae=un(),at=Wr(),Ge=(0,r.useContext)(dn),We=G||Ge.claimPending===!0,rn=Gr(),[h,ke]=(0,r.useState)(!1),[dt,nt]=(0,r.useState)(null),[Qe,Ye]=(0,r.useState)(Ee??"US"),[Ze,xe]=(0,r.useState)(_e??""),[Ke,kt]=(0,r.useState)(Re??""),[Je,An]=(0,r.useState)(Z??""),[Pt,Fn]=(0,r.useState)(T??""),[on,hn]=(0,r.useState)(ce??""),[Zt,Dn]=(0,r.useState)({}),Nt=(0,r.useRef)(_e??""),Rt=(0,r.useRef)(Ee??"US"),qt=(0,r.useRef)(Re??""),Gt=(0,r.useRef)(Z??""),Bt=(0,r.useRef)(T??""),jt=(0,r.useRef)(ce??""),At=(0,r.useRef)({});(0,r.useEffect)(()=>{let a=(C,H,ne,j,ve)=>{if(At.current[C])return;let Ne=H?.trim();!Ne||Ne===ne.current||(ne.current=Ne,j(Ne),ve?.(Ne))};a("country",Ee,Rt,Ye,Oe),a("zip",_e,Nt,xe,ze),a("addressLine1",Re,qt,kt),a("addressLine2",Z,Gt,An),a("city",T,Bt,Fn),a("state",ce,jt,hn)},[Ee,_e,Re,Z,T,ce,Oe,ze]);let le=(0,r.useMemo)(()=>(0,R.resolveAVSConfig)(ie),[ie]),en=le!==null,D=!!V?.vault?.html,gt=!!V?.gateways?.pcivault,bt=!!(V?.gateways?.stripe?.enabledPaymentMethods??g)?.includes("card"),Te=D||bt||gt,qe=!!(M&&Te&&Ae&&e),[$n,Ln]=(0,r.useState)(()=>ae!=="buttons"||ct?e??null:null),[qn,Zn]=(0,r.useState)(0),Vt=ae!=="buttons"||ct||!!e&&$n===e,it=(0,r.useMemo)(()=>!Ae||!qe||!e||!Vt?null:Ae.cardCapture({sessionId:e}),[Ae,qe,e,Vt]),Ft=(0,r.useMemo)(()=>{let a=Qe,C=le?(0,R.isAVSFieldVisible)(le.postal_code,a):!1;return ps(a,Ze,C)},[le,Qe,Ze]),{avsInvalid:Kt,invalidAvsFields:ht}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!qe||!le)return{avsInvalid:!1,invalidAvsFields:a};let C=Qe,H=(ve,Ne)=>(0,R.isAVSFieldVisible)(ve,C)&&!Ne.trim(),ne={line1:H(le.address_line_1,Ke),city:H(le.city,Pt),state:H(le.state,on),zip:Ft.empty||Ft.malformed};return{avsInvalid:ne.line1||ne.city||ne.state||ne.zip,invalidAvsFields:ne}},[qe,le,Qe,Ke,Pt,on,Ft]),[Jt,Ht]=(0,r.useState)(!1),[an,Pn]=(0,r.useState)(!1),[It,Ot]=(0,r.useState)(()=>Ao(V?.vault)),[Le,vt]=(0,r.useState)(ct&&Te?"card":"buttons"),[Ct,bn]=(0,r.useState)(null),jn=Le==="expanding"||Le==="card",Wt=280,Xt=(0,r.useRef)(null),Dt=(0,r.useCallback)(a=>{Xt.current&&clearTimeout(Xt.current),Xt.current=setTimeout(()=>{Xt.current=null,a()},Wt)},[Wt]);(0,r.useEffect)(()=>()=>{Xt.current&&clearTimeout(Xt.current)},[]);let kn=(0,r.useCallback)(()=>{Ln(e??null),Zn(a=>a+1),vt("expanding"),Dt(()=>vt("card"))},[Dt,e]),Nn=(0,r.useCallback)(()=>{vt("collapsing"),Dt(()=>vt("buttons"))},[Dt]),sn=(0,r.useCallback)(a=>{bn(a),vt("apm-expanding"),Dt(()=>vt("apm-form"))},[Dt]),Qt=(0,r.useCallback)(()=>{vt("apm-collapsing"),Dt(()=>{vt("buttons"),bn(null)})},[Dt]);(0,r.useEffect)(()=>{ae==="buttons"&&ct&&Te&&(Ln(e??null),vt("card"))},[ae,ct,Te,e]);let[Et,P]=(0,r.useState)(null),Y=(0,r.useRef)(!1),K=(0,r.useRef)(null),fe=(0,r.useRef)("idle"),[X,de]=(0,r.useState)(null),S=(0,r.useRef)(X);(0,r.useEffect)(()=>{S.current=X},[X]);let u=n||rn,c=p??dt,L=(0,r.useMemo)(()=>(0,Ut.resolveTheme)(U),[U]),f=(0,r.useMemo)(()=>{let a=L?.buttonsLayout??(0,R.resolveButtonsLayoutTheme)(te);return Q?{...a,...Q,cardButton:{...a.cardButton,...Q.cardButton},cardFormContainer:{...a.cardFormContainer,...Q.cardFormContainer},backButton:{...a.backButton,...Q.backButton},backButtonIcon:{...a.backButtonIcon,...Q.backButtonIcon},submitButton:{...a.submitButton,...Q.submitButton},title:{...a.title,...Q.title}}:a},[L,te,Q]),ee=pe??L?.appearance,Ie=(0,r.useMemo)(()=>{let a=ee?.variables,C=Ne=>typeof Ne=="string"&&Ne?Ne:void 0,H=f.submitButton,ne=C(a?.colorPrimary)??C(H?.backgroundColor)??"#4A49FF",j=ae==="buttons",ve=f.nameInput;return{primaryColor:ne,primaryHoverColor:C(a?.colorPrimaryHover)??to(ne,.12),inputBackgroundColor:C(f.cardInputBackground)??C(a?.colorBackground)??"#ffffff",textColor:C(f.cardInputColor)??C(ve?.color)??C(a?.colorText)??"#262833",borderColor:C(f.cardInputBorder)??(j?"#e5e7eb":"#A4A4FF"),placeholderColor:C(f.cardInputPlaceholderColor)??"#9ca3af",errorColor:C(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:C(ve?.fontFamily)??C(a?.fontFamily)??"Poppins, sans-serif",fontSize:C(f.cardInputFontSize)??C(a?.fontSizeBase)??"16px",fontWeight:String(Ha(ve?.fontWeight)??400),borderRadius:C(a?.borderRadius)??"8px"}},[ee,f,ae]),rt=Ge.inlineSessionPatchProcessing??!1,Se=(F??h)||rt,O=u.replace(/\/+$/,""),y=(0,r.useMemo)(()=>To({userId:o,email:l,firstName:N,lastName:b,country:Ee,zip:_e},Zt),[o,l,N,b,Ee,_e,Zt]),$=[y.firstName,y.lastName].filter(a=>!!a?.trim()).join(" "),q=(0,r.useMemo)(()=>Ae?Ae.getRawProvider():null,[Ae]),Ve=(0,r.useMemo)(()=>at?at.getRawProvider():null,[at]),pt=oe||100,_t=(0,r.useMemo)(()=>ee?(0,mn.toStripeAppearance)(ee):null,[ee]),pr=_t?{appearance:_t}:null,Ar=(0,r.useMemo)(()=>{let a=_t??{},C=a.rules??{};return{...a,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[_t]),Yo=(0,r.useMemo)(()=>{let a=Da(oe);return{...a,currency:$e.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...pr}},[oe,$e,pr]),Go=(0,r.useMemo)(()=>({mode:"payment",amount:pt,currency:$e.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...pr}),[pt,$e,pr]),ge=(0,r.useCallback)(a=>{nt(a),v?.(a)},[v]);(0,r.useEffect)(()=>{!qe||!it||it.setCardFieldOrder?.(Ce??null,le==null)},[qe,it,Ce,le]),(0,r.useEffect)(()=>{(Le==="expanding"||Le==="collapsing"||Le==="apm-expanding"||Le==="apm-collapsing")&&ge(null)},[Le,ge]);let ln=(0,r.useCallback)((a,C,H)=>{d?.(wt(a,C,H))},[d]),er=(0,r.useCallback)((a,C,H)=>{let ne=H?.popupBlocked??zn(C),j=ds(a,ne),ve=Gn(H?.code)??xn(C)??"external_payment_method_failed",Ne=new Ut.FloPayError(j,"api_error",{code:"external_payment_method_failed",param:a});P(null),ae==="buttons"&&(vt("buttons"),bn(null)),ge(j),m?.(Ne),console.error("[FloPay] External payment method failed:",{method:a,code:ve,popupBlocked:ne})},[ae,m,ge]);(0,r.useEffect)(()=>{if(!qe||!e){Ot(null);return}let a=Ao(V?.vault);if(a){Ot(a);return}if(!Vt){Ot(null);return}Ot(null);let C=!0;return new mn.PaymentAPI(O).getVaultCapture(e,t).then(H=>{if(!C)return;let ne=Ao(H);ne?Ot(ne):ge("Failed to load the secure card form.")}).catch(H=>{C&&ge(H instanceof Error?H.message:"Failed to load the secure card form.")}),()=>{C=!1}},[qe,Vt,qn,e,V?.vault?.html,V?.vault?.messageToken,V?.vault?.expectedOrigin,O,t,ge]);let Rn=(0,r.useRef)({onComplete:s,onError:m,updateError:ge,emitDecline:ln,resolvedAccount:y,avsConfig:le,avsCheckProp:ye,sessionId:e,nonce:t,baseUrl:O});Rn.current={onComplete:s,onError:m,updateError:ge,emitDecline:ln,resolvedAccount:y,avsConfig:le,avsCheckProp:ye,sessionId:e,nonce:t,baseUrl:O};let fo=(0,r.useRef)(!1),bi=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:C,avsCheckProp:H}=Rn.current,ne=Rt.current||a.country||"US",j=C?(0,R.isAVSFieldVisible)(C.state,ne):!1,ve=C?(0,R.isAVSFieldVisible)(C.address_line_1,ne):!1,Ne=C?(0,R.isAVSFieldVisible)(C.postal_code,ne):!1,yt=C?(0,R.isAVSFieldVisible)(C.city,ne):!1,Lt=C?(0,R.isAVSFieldVisible)(C.address_line_2,ne):!1,Xe=ve&&!j&&Ne?(0,R.getStateFromPostalCode)(ne,(Nt.current??"").trim()):null,xt=j?jt.current:Xe;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Ne&&Nt.current?{zip:Nt.current}:{},...yt&&Bt.current?{city:Bt.current}:{},...xt?{state:xt}:{},...ve&&qt.current?{addressLine1:qt.current}:{},...Lt&&Gt.current?{addressLine2:Gt.current}:{},country:ne},...H!==void 0?{avsCheck:H}:{},...C?{avsConfig:{country:(0,R.isAVSFieldVisible)(C.country,ne),postal_code:Ne,address_line_1:ve,address_line_2:Lt,city:yt,state:j}}:{}}},[]),Jo=(0,r.useRef)(We);Jo.current=We,(0,r.useEffect)(()=>{We||c!==ja||Rn.current.updateError(null)},[We,c]),(0,r.useEffect)(()=>{!qe||!it||it.setSubmitGate?.(Kt||We)},[qe,it,Kt,We]),(0,r.useEffect)(()=>{if(!qe||!it)return;fo.current=!1;let a=!1,C=it.on("submitting",()=>{Ht(!0),K.current&&clearTimeout(K.current),fe.current="validation-window",K.current=setTimeout(()=>{K.current=null,fe.current==="validation-window"&&(fe.current="processing")},as),P("processing");let{baseUrl:Ne,sessionId:yt,nonce:Lt,updateError:Xe,onError:xt}=Rn.current;!yt||!Lt||new mn.PaymentAPI(Ne).patchAccountSnapshot(yt,Lt,bi(),{telemetryMode:"best_effort"}).catch(Fe=>{if(!is(Fe))return;let zt=Fe instanceof Error?Fe.message:"Please check your billing address and try again.";Xe(zt),fe.current="idle",P(null),xt?.(Fe instanceof Ut.FloPayError?Fe:new Ut.FloPayError(zt,"api_error"))})}),H=it.on("complete",async Ne=>{sr(Ne.sessionId??Rn.current.sessionId),fe.current="terminal",P("success"),await new Promise(yt=>setTimeout(yt,_n)),!fo.current&&(fo.current=!0,Rn.current.onComplete?.({status:"succeeded",paymentIntentId:Ne.intentId,checkoutMethod:"card"}))}),ne=it.on("decline",async Ne=>{let{updateError:yt,emitDecline:Lt}=Rn.current,Xe=Ne.message??"Your payment was declined. Please try another card or contact your bank.";fe.current="terminal",yt(Xe),P("error"),Lt("card",Xe,Ne.declineReason?{declineCode:Ne.declineReason}:void 0),await new Promise(xt=>setTimeout(xt,Cn)),!a&&(fe.current="idle",P(null))}),j=it.on("error",async Ne=>{let{updateError:yt,onError:Lt}=Rn.current,Xe=Ne.message??"There was a problem processing your payment. Please try again.";fe.current="terminal",yt(Xe),P("error"),Lt?.(new Ut.FloPayError(Xe,"api_error")),await new Promise(xt=>setTimeout(xt,Cn)),!a&&(fe.current="idle",P(null))}),ve=it.on("blocked",()=>{if(!Jo.current){Ht(!0);return}Rn.current.updateError(ja)});return()=>{a=!0,K.current&&(clearTimeout(K.current),K.current=null),fe.current="idle",C(),H(),ne(),j(),ve()}},[qe,it]);let vn=!!He?.clientId,mr=Array.isArray(g),Fr=mr&&g.length>0,vi=mr&&g.includes("paypal"),{expressMethods:Dr,paymentElementMethods:yr}=(0,r.useMemo)(()=>(0,R.partitionStripeMethods)(g,{excludePaypal:vn}),[g,vn]),Xo=vn||!!at,Ci=(0,r.useMemo)(()=>Xo?Dr.filter(a=>a!=="paypal"):Dr,[Dr,Xo]),Si=(0,r.useMemo)(()=>{let a=[];return z&&a.push("apple_pay"),ue&&a.push("google_pay"),a},[z,ue]),Lr=mr?Ci:Si,wi=M&&Lr.length>0,go=en?Qe:Ee,Nr=(0,r.useMemo)(()=>{let a=go?.trim().toUpperCase();return a?he?yr.filter(C=>{let H=he[C];return!H||H.length===0||H.includes(a)}):(0,R.filterStripeMethodsByCountry)(yr,go):yr},[yr,go,he]),ho=(0,r.useMemo)(()=>({mode:"payment",amount:pt,currency:$e.toLowerCase(),paymentMethodCreation:"manual",appearance:Ar}),[pt,$e,Ar]),[Qo,Zo]=(0,r.useState)("loading"),[ea,ta]=(0,r.useState)("loading"),[na,ra]=(0,r.useState)("loading"),[ki,Po]=(0,r.useState)(!1),[oa,bo]=(0,r.useState)("loading"),[Or,Ri]=(0,r.useState)();(0,r.useEffect)(()=>{Ri(La())},[]);let aa=x&&(vn||(mr?vi:Or===!1)),ia=M&&wi,fr=!We&&aa&&vn,sa=oa==="retrying"||oa==="exhausted",gr=!We&&aa&&!!Ve&&(!vn||sa),hr=!We&&ia&&!!q,Pr=!We&&M&&Fr&&Nr.length>0&&!!q,Ii=fr&&!sa?ki:gr&&Wa(Qo),Ei=hr&&Wa(ea),_i=Pr&&na!=="load_error",la=a=>a==="loading"||a==="ready",ca=fr||gr&&la(Qo)||hr&&la(ea)||Pr&&na!=="load_error",zr=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!zr.current){if(!M&&!x){zr.current=!0;let a=new Ut.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");m?.(a),ge(a.message)}else if(!M&&x&&!vn&&!Ve){zr.current=!0;let a=new Ut.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");m?.(a),ge(a.message)}else if(Or!==void 0&&!We&&!Te&&!ca){zr.current=!0;let a=new Ut.FloPayError("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"});m?.(a),ge(a.message)}}},[M,x,vn,Ve,Or,We,Te,ca,m,ge]);let da=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(da.current||!Fr)return;let a=[];z!==!0&&a.push("showApplePay"),ue!==!0&&a.push("showGooglePay"),a.length!==0&&(da.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.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.`))},[Fr,z,ue]);let ua=(0,r.useCallback)((a,C)=>Ge.applyInlineSessionPatch?Ge.applyInlineSessionPatch(a).then(H=>({error:null,sessionId:H.sessionId||e,nonce:H.session?.clientSecret||t})).catch(H=>{let ne=Ka(C,H);return ge(ne.message),m?.(ne),{error:ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ge.applyInlineSessionPatch,t,m,e,ge]),cn=(0,r.useCallback)(async a=>{if(!be)return{proceed:!0};try{let C=await be({method:a,sessionId:e||void 0,createSession:Ge.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&Dn(ne=>({...ne??{},...C.account}));let H=await ua(C,a);return H.error?{proceed:!1,accountPatch:C.account}:{proceed:!0,accountPatch:C.account,sessionId:H.sessionId,nonce:H.nonce}}return{proceed:!0}}catch(C){let H=Ka(a,C);return ge(H.message),m?.(H),{proceed:!1}}},[ua,Ge.inlineSessionDraft,be,m,e,ge]),pa=(0,r.useCallback)(async(a,C)=>{if(Y.current)return;Y.current=!0,ke(!0),P("processing"),ge(null);let H=C?.sessionId??e,ne=C?.nonce??t,j=To(y,C?.accountPatch),ve=C?.completionPaymentMethodId??Xr(a),Ne=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let Lt=await new mn.PaymentAPI(O).processPayment(j.userId??"",{sessionId:H,nonce:ne,tokenizedData:Ne,accountData:{userId:j.userId??"",email:j.email??"",firstName:j.firstName??"",lastName:j.lastName??"",...le?(()=>{let Fe=Rt.current,zt=(0,R.isAVSFieldVisible)(le.state,Fe),nn=(0,R.isAVSFieldVisible)(le.address_line_1,Fe),Wn=(0,R.isAVSFieldVisible)(le.postal_code,Fe),Yn=nn&&!zt&&Wn?(0,R.getStateFromPostalCode)(Fe,(Nt.current??"").trim()):null,Tt=zt?jt.current:Yn;return{country:Fe,...Wn&&Nt.current?{zip:Nt.current}:{},...(0,R.isAVSFieldVisible)(le.city,Fe)&&Bt.current?{city:Bt.current}:{},...Tt?{state:Tt}:{},...nn&&qt.current?{addressLine1:qt.current}:{},...(0,R.isAVSFieldVisible)(le.address_line_2,Fe)&&Gt.current?{addressLine2:Gt.current}:{}}})():{}},chv:_,avsCheck:ye??!1,checkoutType:E,checkoutLayout:re,avsConfig:le?{country:(0,R.isAVSFieldVisible)(le.country,Rt.current),postal_code:(0,R.isAVSFieldVisible)(le.postal_code,Rt.current),address_line_1:(0,R.isAVSFieldVisible)(le.address_line_1,Rt.current),address_line_2:(0,R.isAVSFieldVisible)(le.address_line_2,Rt.current),city:(0,R.isAVSFieldVisible)(le.city,Rt.current),state:(0,R.isAVSFieldVisible)(le.state,Rt.current)}:void 0});if(Lt.ok){sr(H),P("success"),de(null),await new Promise(Fe=>setTimeout(Fe,_n)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ve,checkoutMethod:a.isPaypal?"paypal":"card"});return}let Xe=await Lt.json().catch(()=>null);if(Xe?.type==="paypal_redirect_required"){let Fe=Xe.threeDSecureToken,zt=Xe.paymentMethodId||a.id||"";if(!Ae||!Fe){P("error"),ge("PayPal authorization required but no token provided.");return}try{let nn=at?.getRawProvider();if(!nn){ge("PayPal is not available.");return}let Wn={return_url:window.location.href};zt&&(Wn.payment_method=zt);let{error:Yn}=await nn.confirmPayment({clientSecret:Fe,confirmParams:Wn,redirect:"if_required"});if(Yn){P("error");let Tt=Yn.message??"PayPal payment failed.";ge(Tt),ln("paypal",Tt,{code:Yn.code})}}catch(nn){P("error"),ge(nn instanceof Error?nn.message:"PayPal authorization failed.")}return}if(Xe?.type==="paypal_direct_required"){let Fe=Xe.orderId;if(!Fe){P("error"),ge("PayPal retry required but no order id provided.");return}let zt=S.current?.attempts??0;if(zt>=2){P("error"),ge("PayPal payment could not be completed after multiple attempts."),ln("paypal","paypal_direct_required retry limit exceeded");return}Po(!1),bo("loading"),de({orderId:Fe,attempts:zt+1}),P(null);return}P("error");let xt=Xe?.message??"Payment failed. Please try again.";ge(xt),ln(a.isPaypal?"paypal":"card",xt,{code:Xe?.code??Xe?.gatewayErrorCode,declineCode:Xe?.declineCode??Xe?.gatewayDeclineReason}),await new Promise(Fe=>setTimeout(Fe,Cn))}catch(yt){P("error"),ge(yt instanceof Error?yt.message:"An unexpected error occurred"),await new Promise(Lt=>setTimeout(Lt,Cn))}finally{ke(!1),P(null),Y.current=!1}},[O,e,t,y,$,_,Ae,at,s,m,ge,ln]),tn=(0,r.useCallback)((a,C)=>{I?I(a):pa(a,C)},[I,pa]),ma=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(typeof window>"u"||ma.current)return;let a=new URLSearchParams(window.location.search),C=a.get("payment_intent"),H=a.get("payment_intent_client_secret"),ne=a.get("redirect_status");if(!C||!H)return;let j=xt=>{let Fe=localStorage.getItem(xt);if(!Fe)return null;try{return JSON.parse(Fe)}catch{return localStorage.removeItem(xt),null}},ve=j(wn)??j(qa),Ne;if(ve?.clientSecret){if(ve.clientSecret!==H)return;Ne={...ve.accountPatch?{accountPatch:ve.accountPatch}:{},...ve.sessionId?{sessionId:ve.sessionId}:{},...ve.nonce?{nonce:ve.nonce}:{}}}else if(ve?.sessionId&&ve.sessionId!==e)return;ma.current=!0,localStorage.removeItem(wn),localStorage.removeItem(qa);let yt=new URL(window.location.href);yt.searchParams.delete("payment_intent"),yt.searchParams.delete("payment_intent_client_secret"),yt.searchParams.delete("redirect_status"),window.history.replaceState({},"",yt.toString());let Lt=ve?.paymentMethodType??ve?.tokenType??"card",Xe="card";(async()=>{let xt=Ae?.getRawProvider();if(!xt){let Tt="Payment is not available \u2014 please refresh and try again.";ge(Tt),ln(Xe,Tt);return}if(ne==="failed"){let Tt="Payment was declined. Please try again.";ge(Tt),ln(Xe,Tt);return}let{paymentIntent:Fe,error:zt}=await xt.retrievePaymentIntent(H);if(zt){let Tt=zt.message??"Failed to retrieve payment status.";ge(Tt),ln(Xe,Tt,{code:zt.code});return}let nn=Fe?.status,Wn=Jr(nn);if(!Fe||!Wn){let Tt=nn==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ge(Tt),ln(Xe,Tt,{code:nn??"missing_payment_intent"});return}let Yn=typeof Fe.payment_method=="string"?Fe.payment_method:Fe.payment_method?.id;tn({id:Yn??ve?.paymentMethodId??ve?.tokenId??Fe.id,type:"card",threeDSecureActionResultTokenId:Fe.id,gateway:ve?.gateway??"stripe",paymentMethodType:Lt},Ne)})()},[e,tn,Ae,ge,ln]);let vo=(0,r.useCallback)(a=>{a.preventDefault()},[]);if(!(Ae!==null))return(0,i.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let br=ae==="buttons",Yt=ee?.variables,xi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Co=Yt?.colorBackground,Ti=Co&&!xi.has(Co)?Co:void 0,vr=f.cardInputBorder??(br?"#e5e7eb":"#A4A4FF"),So=Yt?.colorDanger??"#dc2626",Vn=a=>Jt&&a?So:vr,Ur=(Ft.malformed||Ft.empty)&&(an||Jt),Mi=Ur?So:Vn(ht.zip),wo=f.cardFormContainer?.backgroundColor??Ti??(br?"white":"#EDEDFF"),Cr=f.cardInputBackground??Yt?.colorBackground??"white",ko=nr(J),ya=nr(me),tr=f.nameInput,fa=f.cardInputFontSize??ms(tr?.fontSize)??Yt?.fontSizeBase??"16px",ga=typeof tr?.fontFamily=="string"?tr.fontFamily:Yt?.fontFamily??"Poppins, sans-serif",ha=Ha(tr?.fontWeight)??400,Bi=f.cardInputColor??(typeof tr?.color=="string"?tr.color:void 0)??Yt?.colorText??"#262833",Ai=f.cardInputPlaceholderColor??"#9ca3af",mt=Yt?.borderRadius??"8px",Kn=Yt?.borderRadius??f.cardButton?.borderRadius??mt,Hn=Yt?.colorPrimary??"#4A49FF",Fi=Yt?.colorPrimaryHover??to(Hn,.12),Ro=Yt?.colorText??"#262833",Pa={fontSize:fa,fontFamily:ga,fontWeight:ha,color:Bi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Di={"--flopay-input-placeholder-color":Ai,"--flopay-input-font-size":fa,"--flopay-input-font-family":ga,"--flopay-input-font-weight":String(ha)},Sr=f.cardFormContainer??{},Io=Sr.padding??(br?"0":"1rem"),Eo=Sr.borderRadius??mt,Li=it&&It?(0,i.jsx)(Hr,{capture:it,html:It.html,messageToken:It.messageToken,expectedOrigin:It.expectedOrigin,theme:Ie,onReady:()=>{if(!le||typeof document>"u")return;let a=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};a();let C=0,H=window.setInterval(()=>{C+=1;let ne=document.activeElement;!!ne&&ne.tagName==="IFRAME"&&ne.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(H)):C>=50&&window.clearInterval(H)},100)},onError:a=>ge(a),onValidation:a=>{let C=fe.current;(C==="idle"||C==="validation-window")&&(ge(a),a&&fe.current==="validation-window"&&(K.current&&(clearTimeout(K.current),K.current=null),fe.current="idle",P(null)))}}):(0,i.jsx)("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"}),ba=(0,i.jsxs)("div",{style:{backgroundColor:wo,borderRadius:Eo,...Sr,padding:Io,...Di,display:"flex",flexDirection:"column"},children:[(0,i.jsx)("style",{children:`
|
|
30
|
+
`,lo=44;function Vo(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var ys={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ri={width:"100%",minHeight:lo,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 fs(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ja(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function oi(e){return e==="paypal"?"PayPal":(0,C.getStripeMethodDisplayName)(e)}function gs(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=(0,o.useRef)(0),n=(0,o.useRef)(null),c=(0,o.useRef)(null),a=(0,o.useCallback)((u=c.current)=>{let b=u;b?.timer&&(clearTimeout(b.timer),b.timer=null)},[]),l=(0,o.useCallback)((u,b)=>{typeof document<"u"&&document.visibilityState!=="visible"||(a(u),u.timer=setTimeout(()=>{u.timer=null,c.current?.generation===u.generation&&(c.current=null,n.current=u.generation,e(u.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},b))},[a,e]),p=(0,o.useCallback)(u=>{u.yieldedControl&&l(u,600)},[l]),d=(0,o.useCallback)(u=>{a();let b=t.current+1;t.current=b,n.current=null;let E={generation:b,method:u,timer:null,yieldedControl:!1};return c.current=E,b},[a]),k=(0,o.useCallback)(u=>{let b=c.current;return typeof u=="number"&&b?.generation!==u?!1:(a(b),c.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[a]),U=(0,o.useCallback)(u=>{let b=c.current,E=u??b?.generation??t.current;(!u||b?.generation===u)&&(a(b),c.current=null),n.current=E},[a]),P=(0,o.useCallback)(u=>n.current===(u??t.current),[]),I=(0,o.useCallback)(u=>c.current?.generation===u&&n.current!==u,[]),R=(0,o.useCallback)(()=>{let u=c.current;u&&p(u)},[p]),O=(0,o.useCallback)(()=>{let u=c.current;u&&(u.yieldedControl=!0,a(u))},[a]);return(0,o.useEffect)(()=>{let u=()=>{document.visibilityState==="visible"?R():O()},b=()=>{O()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",b),window.addEventListener("focus",R),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",b),window.removeEventListener("focus",R),a()}},[a,O,R]),{startAttempt:d,finishAttempt:k,invalidateAttempt:U,isAttemptInvalidated:P,isAttemptCurrent:I}}function hs(e){let t=(0,C.getPostalCodeExample)(e);return`Enter a valid ${(0,C.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Ps(e,t,n){let c=(0,C.isPostalCodeSupported)(e),a=t.trim(),l=n&&c,p=l&&!a,d=l&&!!a&&!(0,C.isValidPostalCode)(e,a);return{visible:n,supported:c,required:l,empty:p,malformed:d}}function Xa(e,t){return t instanceof Lt.FloPayError?t:new Lt.FloPayError(t instanceof Error?t.message:`${fs(e)} before-click hook failed.`,"validation_error")}function $o(){return(0,s.jsx)("style",{children:ms})}function bs(e){return typeof e=="number"?`${e}px`:e}function Qa(e){if(typeof e=="number"||typeof e=="string")return e}function ii(e,t){let n=e.availablePaymentMethods;return n&&t.some(c=>n[c])?"ready":"unavailable"}function si({state:e,placeholderTestId:t,borderRadius:n=8,children:c}){return e==="unavailable"||e==="load_error"?null:(0,s.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,s.jsx)("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"}}),(0,s.jsx)("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:c})]})}function Za(e){return e!=="unavailable"&&e!=="load_error"}function uo(e){return(0,s.jsx)(Cs,{...e})}function ei({sessionId:e,nonce:t,email:n,billingApiUrl:c,onTokenizedBody:a,onErrorChange:l,isProcessing:p=!1,onButtonClick:d,onDecline:k,onTechnicalFailure:U,runBeforeButtonClick:P,onLoadStateChange:I,placeholderBorderRadius:R}){let O=cn(),u=(0,ft.useStripe)(),b=(0,ft.useElements)(),[E,x]=(0,o.useState)("loading");(0,o.useEffect)(()=>{I?.(E)},[E,I]);let[h,ye]=(0,o.useState)(!1),M=(0,o.useRef)(!1),ce=(0,o.useRef)(null),oe=(0,o.useRef)(null),[j,te]=(0,o.useState)(0),[X,de]=(0,o.useState)(!1),Y=(0,o.useRef)(!1),G=(0,o.useRef)(new Map),{startAttempt:pe,finishAttempt:De,invalidateAttempt:we,isAttemptInvalidated:ge,isAttemptCurrent:ae}=ai((J,S,se)=>{U?.(J,S,{...se,popupBlocked:se?.popupBlocked??Nn(S)}),de(!0),te(Ve=>Ve+1)});(0,o.useEffect)(()=>{X&&oe.current?.focus()},[X,j]);let be=(0,o.useCallback)(()=>{te(J=>J+1)},[]),Le=(0,o.useCallback)((J,S,se)=>{we(se),U?.("paypal",J,{code:S,popupBlocked:Nn(J)}),de(!0),be()},[we,U,be]),ie=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Y.current&&(Y.current=!1,ie())},[ie,j]);let je=(0,o.useCallback)(()=>{de(!1),l?.(null),ie()},[ie,l]);(0,o.useEffect)(()=>{if(!u||M.current)return;let J=new URLSearchParams(window.location.search),S=J.get("payment_intent"),se=J.get("payment_intent_client_secret"),Ve=J.get("redirect_status");if(!S||!se)return;M.current=!0;let Ne;try{let A=localStorage.getItem(Br);if(A){let le=JSON.parse(A);le.clientSecret===se&&(Ne={...le.accountPatch?{accountPatch:le.accountPatch}:{},...le.sessionId?{sessionId:le.sessionId}:{},...le.nonce?{nonce:le.nonce}:{}})}}catch{}try{localStorage.removeItem(Br)}catch{}let ue=new URL(window.location.href);ue.searchParams.delete("payment_intent"),ue.searchParams.delete("payment_intent_client_secret"),ue.searchParams.delete("redirect_status"),window.history.replaceState({},"",ue.toString()),(async()=>{try{if(ye(!0),Ve==="failed"){let Q="PayPal payment was declined. Please try again.";l?.(Q),k?.(Rt("paypal",Q));return}let{paymentIntent:A,error:le}=await u.retrievePaymentIntent(se);if(le){l?.(le.message??"Failed to retrieve PayPal payment status.");return}if(A&&(A.status==="requires_capture"||A.status==="succeeded")){let Q=typeof A.payment_method=="string"?A.payment_method:A.payment_method?.id;a({id:Q??A.id,type:"card",threeDSecureActionResultTokenId:A.id,isPaypal:!0},Ne)}else{let Q="PayPal payment was not completed. Please try again.";l?.(Q),k?.(Rt("paypal",Q))}}catch(A){l?.(A instanceof Error?A.message:"Failed to complete PayPal payment.")}finally{ye(!1)}})()},[u,a,l,k]);let Oe=(0,o.useCallback)(async J=>{if(p||h){J.reject();return}let S=P?await P("paypal"):{proceed:!0};if(!S.proceed){G.current.delete(j),J.reject();return}let se=pe("paypal");G.current.set(j,{generation:se,accountPatch:S.accountPatch,sessionId:S.sessionId,nonce:S.nonce}),de(!1),d?.("paypal"),J.resolve()},[G,p,d,P,pe,h,j]),Ee=(0,o.useCallback)(async J=>{if(!u||!b)return;let S=G.current.get(j);if(S&&!ae(S.generation)){G.current.delete(j);return}if(!S&&ge()||S&&!De(S.generation))return;S||De();let se=S??null;if(G.current.delete(j),!se&&P){let A=await P("paypal");if(!A.proceed){J.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}se={accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}}let Ve=se?.sessionId??e,Ne=se?.nonce??t,ue=se?.accountPatch?.email??n;try{if(ye(!0),l?.(null),!Ve||!ue)throw new Error("Missing sessionId or email for PayPal payment");let A=u.createPaymentMethod,{error:le,paymentMethod:Q}=await A({type:"paypal"});if(le){Le(le,"stripe_paypal_create_payment_method_failed",S?.generation),J.paymentFailed({reason:"fail"});return}let _e=await new un.PaymentAPI(c).createSessionIntent(Ve,Ne??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Q?.id??null,intentKind:"payment"});if(_e.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let dt=_e.clientSecret,Qe={return_url:window.location.href};if(Q?.id&&(Qe.payment_method=Q.id),typeof window<"u")try{localStorage.setItem(Br,JSON.stringify({clientSecret:dt,sessionId:Ve,nonce:Ne,accountPatch:se?.accountPatch}))}catch{}let{error:pt,paymentIntent:D}=await u.confirmPayment({clientSecret:dt,confirmParams:Qe,redirect:"if_required"});if(pt){if(typeof window<"u")try{localStorage.removeItem(Br)}catch{}if(Mr(pt)){let tt=pt.message??"Your payment was declined.";l?.(tt),k?.(Rt("paypal",tt,{code:Tn(pt),declineCode:pr(pt)})),await co({billingApiUrl:c,sessionId:Ve,nonce:Ne,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Tn(pt)??"provider_declined"}})}else Le(pt,"stripe_paypal_confirm_failed",S?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Br)}catch{}let Z=typeof D?.payment_method=="string"?D.payment_method:D?.payment_method?.id;a({id:Z??D?.id,type:"card",threeDSecureActionResultTokenId:D?.id,isPaypal:!0},{accountPatch:se?.accountPatch,sessionId:Ve,nonce:Ne});return}catch(A){Le(A,"stripe_paypal_failed",S?.generation)}finally{ye(!1)}},[u,b,e,t,n,c,a,l,k,P,Le,De,ae,ge,j]);return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(si,{state:E,placeholderTestId:"flopay-paypal-placeholder",borderRadius:R,children:(0,s.jsxs)("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[X&&(0,s.jsx)("button",{ref:oe,type:"button","data-testid":"flopay-paypal-retry-button",onClick:je,style:ri,children:"Try PayPal again"}),(0,s.jsx)(ft.ExpressCheckoutElement,{onReady:J=>x(ii(J,["paypal"])),onLoadError:()=>{x("load_error"),jo(xt(O),"paypal","paypal")},onClick:Oe,onConfirm:Ee,onCancel:()=>{let J=G.current.get(j);G.current.delete(j),xt(O)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we(J?.generation),de(!1),Y.current=!0,be()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},j)]})}),h&&(0,s.jsx)(Cn,{status:"processing"})]})}function ti({sessionId:e,nonce:t,email:n,billingApiUrl:c,intentKind:a,expressMethods:l,onTokenizedBody:p,onErrorChange:d,onButtonClick:k,onDecline:U,onTechnicalFailure:P,runBeforeButtonClick:I,onLoadStateChange:R,placeholderBorderRadius:O}){let u=cn(),b=(0,ft.useStripe)(),E=(0,ft.useElements)(),[x,h]=(0,o.useState)("loading");(0,o.useEffect)(()=>{R?.(x)},[x,R]);let[ye,M]=(0,o.useState)(!1),ce=(0,o.useRef)(null),oe=(0,o.useRef)(null),[j,te]=(0,o.useState)(0),[X,de]=(0,o.useState)(!1),[Y,G]=(0,o.useState)("google_pay"),pe=(0,o.useRef)(!1),De=(0,o.useRef)("google_pay"),we=(0,o.useRef)("google_pay"),ge=(0,o.useRef)(new Map),{startAttempt:ae,finishAttempt:be,invalidateAttempt:Le,isAttemptInvalidated:ie,isAttemptCurrent:je}=ai((ue,A,le)=>{P?.(ue,A,{...le,popupBlocked:le?.popupBlocked??Nn(A)}),G(ue),de(!0),te(Q=>Q+1)});(0,o.useEffect)(()=>{X&&oe.current?.focus()},[X,j]);let Oe=(0,o.useCallback)(()=>{te(ue=>ue+1)},[]),Ee=(0,o.useCallback)((ue,A,le,Q)=>{Le(Q),P?.(ue,A,{code:le,popupBlocked:Nn(A)}),G(ue),de(!0),Oe()},[Le,P,Oe]),J=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{pe.current&&(pe.current=!1,J())},[J,j]);let S=(0,o.useCallback)(()=>{de(!1),d?.(null),J()},[J,d]),se=(0,o.useCallback)(async ue=>{if(!b||!E)return;let A=ge.current.get(j);if(A&&!je(A.generation)){ge.current.delete(j);return}if(!A&&ie()||A&&!be(A.generation))return;A||be();let le=ue.expressPaymentType??A?.method??De.current,Q=A??null;ge.current.delete(j);let _e=Ja(le);if(!Q&&I){let Z=await I(_e);if(!Z.proceed){ue.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}Q={accountPatch:Z.accountPatch,sessionId:Z.sessionId,nonce:Z.nonce}}let dt=_e,Qe=Q?.sessionId??e,pt=Q?.nonce??t,D=Q?.accountPatch?.email??n;try{M(!0),d?.(null);let{error:Z}=await E.submit();if(Z){Ee(le,Z,"stripe_wallet_submit_failed",A?.generation);return}let{error:tt,paymentMethod:Ke}=await b.createPaymentMethod({elements:E});if(tt||!Ke){Ee(le,tt??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",A?.generation);return}if(!Qe||!D)throw new Error("Missing sessionId or email for wallet payment");let mt=await new un.PaymentAPI(c).createSessionIntent(Qe,pt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:le??_e,paymentMethodId:Ke.id,intentKind:a});if(mt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Ue=mt.clientSecret,{error:Ge,intentId:Yt}=(0,Lt.isSetupIntentClientSecret)(Ue)?await b.confirmCardSetup(Ue,{payment_method:Ke.id}).then(Xe=>({error:Xe.error,intentId:Xe.setupIntent?.id})):await b.confirmCardPayment(Ue,{payment_method:Ke.id}).then(Xe=>({error:Xe.error,intentId:Xe.paymentIntent?.id}));if(Ge){if(Mr(Ge)){let Xe=Ge.message??"Your payment was declined.";d?.(Xe),U?.(Rt(dt,Xe,{code:Tn(Ge),declineCode:pr(Ge)})),await co({billingApiUrl:c,sessionId:Qe,nonce:pt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:le??_e,providerDeclineReason:Tn(Ge)??"provider_declined"}})}else Ee(le,Ge,"stripe_wallet_confirm_failed",A?.generation);return}p({id:Ke.id,type:"card",threeDSecureActionResultTokenId:Yt},{accountPatch:Q?.accountPatch,sessionId:Qe,nonce:pt})}catch(Z){Ee(le,Z,"stripe_wallet_failed",A?.generation)}finally{M(!1)}},[b,E,e,t,n,c,a,p,d,U,I,Ee,be,je,ie,j]),Ve=(0,o.useMemo)(()=>{let ue=["applePay","googlePay","paypal","link","amazonPay","klarna"],A=new Set(["applePay","googlePay"]),le=new Set(l.map(C.stripeExpressMethodToOptionKey)),Q={};for(let _e of ue)le.has(_e)?Q[_e]=A.has(_e)?"always":"auto":Q[_e]="never";return Q},[l]),Ne=(0,o.useMemo)(()=>l.map(C.stripeExpressMethodToOptionKey),[l]);return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(si,{state:x,placeholderTestId:"flopay-wallet-placeholder",borderRadius:O,children:(0,s.jsxs)("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[X&&(0,s.jsxs)("button",{ref:oe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:S,style:ri,children:["Try ",oi(Y)," again"]}),(0,s.jsx)(ft.ExpressCheckoutElement,{onReady:ue=>{h(ii(ue,Ne))},onLoadError:ue=>{h("load_error"),jo(xt(u),"stripe","wallet")},onClick:async ue=>{De.current=ue.expressPaymentType,we.current=Ja(ue.expressPaymentType);let A=I?await I(we.current):{proceed:!0};if(!A.proceed){ge.current.delete(j),ue.reject();return}let le=ae(ue.expressPaymentType);ge.current.set(j,{generation:le,method:ue.expressPaymentType,accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}),de(!1),k?.(we.current),ue.resolve()},onConfirm:se,onCancel:()=>{let ue=ge.current.get(j);ge.current.delete(j),xt(u)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Le(ue?.generation),de(!1),pe.current=!0,Oe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ve,layout:{maxColumns:1,overflow:"never"}}},j)]})}),ye&&(0,s.jsx)(Cn,{status:"processing"})]})}function vs({method:e,themeId:t,submitting:n=!1,disabled:c=!1,highlighted:a=!1,hasNextStep:l=!1,onClick:p,backgroundColor:d,borderColor:k,textColor:U,borderRadius:P,fontFamily:I}){let R=(0,C.resolveStripeMethodBrandVariant)(e,t),O=Fa[e],u=R?.backgroundColor??d??"#ffffff",b=R?.borderColor??k??"#d1d5db",E=R?.textColor??U??"#262833";return(0,s.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!c&&p()},disabled:n||c,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:lo,padding:"0 1rem",backgroundColor:u,color:E,border:`1px solid ${b}`,borderRadius:P??8,fontSize:"0.95rem",fontWeight:600,fontFamily:I,cursor:n||c?"not-allowed":"pointer",opacity:c&&!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:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,s.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,C.getStripeMethodDisplayName)(e)}\u2026`}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,C.hasVendoredStripeMethodLogo)(e)?8:0},children:[O?(0,s.jsx)("img",{src:O,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"}}):R?.logoSvg?(0,s.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:R.logoSvg}}):null,(0,s.jsx)("span",{children:(0,C.getStripeMethodDisplayName)(e)})]}),l&&(0,s.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:E,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:(0,s.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function qo({method:e,sessionId:t,nonce:n,email:c,billingName:a,billingApiUrl:l,onTokenizedBody:p,onErrorChange:d,onDecline:k,onCancel:U,runBeforeButtonClick:P,onButtonClick:I,isProcessing:R,submitButtonColor:O,submitButtonBorderRadius:u,submitButtonStyle:b,errorText:E}){let x=cn(),h=(0,ft.useStripe)(),ye=(0,ft.useElements)(),[M,ce]=(0,o.useState)(!1),oe=(0,o.useRef)(!1),[j,te]=(0,o.useState)(!1),[X,de]=(0,o.useState)("loading"),Y=(0,o.useCallback)(async()=>{if(!h||!ye||R||oe.current||!j)return;oe.current=!0,ce(!0);let G=P?await P("card"):{proceed:!0};if(!G.proceed){oe.current=!1,ce(!1);return}I?.("card");let pe=G.sessionId??t,De=G.nonce??n,we=G.accountPatch?.email??c;try{d?.(null);let ge=await ye.submit();if(ge.error){d?.(ge.error.message??"Payment failed.");return}let ae=await h.createPaymentMethod({elements:ye});if(ae.error||!ae.paymentMethod){d?.(ae.error?.message??"Failed to create payment method.");return}let be=ae.paymentMethod;if(!pe||!we)throw new Error("Missing sessionId or email for payment.");let Le=be.type||e,ie=await new un.PaymentAPI(l).createSessionIntent(pe,De??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Le,paymentMethodId:null,intentKind:"payment"});if(ie.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let je=ie.clientSecret;if(typeof window<"u")try{localStorage.setItem(Sn,JSON.stringify({clientSecret:je,sessionId:pe,nonce:De,accountPatch:G.accountPatch,paymentMethodId:be.id,paymentMethodType:be.type??e,gateway:"stripe"}))}catch{}let{error:Oe,paymentIntent:Ee}=await h.confirmPayment({clientSecret:je,confirmParams:{return_url:window.location.href,payment_method:be.id},redirect:"if_required"});if(Oe){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let se=Oe.message??"Payment failed.";d?.(se),k?.(Rt("card",se,{code:Oe.code})),await co({billingApiUrl:l,sessionId:pe,nonce:De,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Oe.code??"provider_declined"}});return}let J=Ee?.status;if(!ro(J)){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let se=J==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(se),k?.(Rt("card",se,{code:J??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let S=typeof Ee?.payment_method=="string"?Ee.payment_method:Ee?.payment_method?.id;p({id:S??be.id,type:"card",threeDSecureActionResultTokenId:Ee?.id,gateway:"stripe",paymentMethodType:be.type??e},{accountPatch:G.accountPatch,sessionId:pe,nonce:De})}catch(ge){d?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{oe.current=!1,ce(!1)}},[h,ye,R,j,P,I,t,n,c,l,e,p,d,k]);return(0,s.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,s.jsx)(ft.PaymentElement,{onReady:()=>de("ready"),onLoadError:()=>{de("load_error"),jo(xt(x),"stripe","apm")},onChange:G=>{te(!!G.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:a&&a.trim().length>=3?a.trim():"FloPay Customer",...c?{email:c}:{}}}}}),(0,s.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Y()},disabled:!j||M||R||X!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:O,color:"white",border:"none",borderRadius:u,fontSize:"1rem",fontWeight:600,cursor:!j||M||R||X!=="ready"?"not-allowed":"pointer",opacity:!j||M||R||X!=="ready"?.5:1,transition:"opacity 120ms ease-out",...b??{}},children:M?"Processing\u2026":`Pay with ${(0,C.getStripeMethodDisplayName)(e)}`}),E&&(0,s.jsx)(sr,{margin:"0.75rem 0 0",children:E})]})}function ni({sessionId:e,nonce:t,email:n,billingName:c,billingApiUrl:a,paymentElementMethods:l,stripeInstance:p,paymentElementBaseOptions:d,onTokenizedBody:k,onErrorChange:U,onButtonClick:P,onDecline:I,runBeforeButtonClick:R,onLoadStateChange:O,isProcessing:u=!1,submitButtonColor:b="#4A49FF",submitButtonBorderRadius:E=8,submitButtonStyle:x,buttonAppearance:h,themeId:ye,onExpandApm:M,expandedApmMethod:ce}){let[oe,j]=(0,o.useState)(null),[te,X]=(0,o.useState)(null),de=(0,o.useRef)(!1);(0,o.useEffect)(()=>{l.length>0&&p?O?.("ready"):p||O?.("loading")},[l.length,p,O]);let Y=(0,o.useCallback)(async ae=>{if(!p||de.current||u)return;de.current=!0,X(ae);let be=R?await R("card"):{proceed:!0};if(!be.proceed){de.current=!1,X(null);return}P?.("card");let Le=be.sessionId??e,ie=be.nonce??t,je=be.accountPatch?.email??n;try{if(U?.(null),!Le||!je)throw new Error("Missing sessionId or email for payment.");let Oe=await new un.PaymentAPI(a).createSessionIntent(Le,ie??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ae,paymentMethodId:null,intentKind:"payment"});if(Oe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ee=Oe.clientSecret;if(typeof window<"u")try{localStorage.setItem(Sn,JSON.stringify({clientSecret:Ee,sessionId:Le,nonce:ie,accountPatch:be.accountPatch,paymentMethodType:ae,gateway:"stripe"}))}catch{}let{error:J,paymentIntent:S}=await p.confirmPayment({clientSecret:Ee,confirmParams:{return_url:window.location.href,payment_method_data:{type:ae,billing_details:{name:c&&c.trim().length>=3?c.trim():"FloPay Customer",...je?{email:je}:{}}}},redirect:"if_required"});if(J){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let Ne=J.message??"Payment failed.";U?.(Ne),I?.(Rt("card",Ne,{code:J.code})),await co({billingApiUrl:a,sessionId:Le,nonce:ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ae,providerDeclineReason:J.code??"provider_declined"}});return}let se=S?.status;if(!ro(se)){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let Ne=se==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";U?.(Ne),I?.(Rt("card",Ne,{code:se??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let Ve=typeof S?.payment_method=="string"?S.payment_method:S?.payment_method?.id;k({id:Ve??S?.id,type:"card",threeDSecureActionResultTokenId:S?.id,gateway:"stripe",paymentMethodType:ae},{accountPatch:be.accountPatch,sessionId:Le,nonce:ie})}catch(Oe){U?.(Oe instanceof Error?Oe.message:"Payment failed. Please try again.")}finally{de.current=!1,X(null)}},[p,u,R,P,e,t,n,a,c,k,U,I]),[G,pe]=(0,o.useState)(null),De=M?ce??null:G,we=(0,o.useCallback)(ae=>{de.current||u||De&&De!==ae||((0,C.needsStripeMethodExplicitConfirm)(ae)?M?M(ae):pe(ae):Y(ae))},[De,u,Y,M]),ge=(0,o.useMemo)(()=>G?{...d,paymentMethodTypes:[G]}:null,[G,d]);return(0,s.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:l.map(ae=>{let be=ce===ae,Le=te===ae,ie=te!==null&&te!==ae||ce!=null&&ce!==ae;return(0,s.jsxs)(o.default.Fragment,{children:[(0,s.jsx)(vs,{method:ae,themeId:ye,submitting:Le,disabled:ie,highlighted:be,hasNextStep:(0,C.needsStripeMethodExplicitConfirm)(ae),onClick:()=>we(ae),backgroundColor:h?.backgroundColor,borderColor:h?.borderColor,textColor:h?.textColor,borderRadius:h?.borderRadius,fontFamily:h?.fontFamily}),!M&&G===ae&&ge&&p&&(0,s.jsx)(ft.Elements,{stripe:p,options:ge,children:(0,s.jsx)(qo,{method:ae,sessionId:e,email:n,billingName:c,billingApiUrl:a,onTokenizedBody:k,onErrorChange:U,onDecline:I,onCancel:()=>pe(null),runBeforeButtonClick:R,onButtonClick:P,isProcessing:u,submitButtonColor:b,submitButtonBorderRadius:E,submitButtonStyle:x})},ae)]},ae)})})}function Cs({sessionId:e,nonce:t,billingApiUrl:n,email:c,userId:a,onComplete:l,onError:p,onDecline:d,onTokenizedBody:k,firstName:U,lastName:P,chv:I,className:R,isProcessing:O,error:u,onErrorChange:b,showPayPal:E=!0,showStripe:x=!0,enabledPaymentMethods:h,enabledPaymentMethodCountries:ye,showApplePay:M=!0,showGooglePay:ce=!0,layout:oe="default",theme:j,buttonsTheme:te,buttonsStyles:X,appearance:de,cardButtonContent:Y,cardBackButtonContent:G,cardTitleContent:pe,showSecurityFooter:De,onButtonClick:we,onBeforeButtonClick:ge,enableAVS:ae,cardFieldOrder:be,cardPreFormSlot:Le,avsLayout:ie="row",country:je,zip:Oe,addressLine1:Ee,addressLine2:J,city:S,state:se,onCountryChange:Ve,onZipChange:Ne,avsCheck:ue,checkoutType:A,checkoutLayout:le,totalAmount:Q=0,currency:_e="usd",initialCardOpen:dt=!1,directPaypal:Qe,isSubscription:pt=!1,session:D,dataAttachmentPending:Z=!1,debug:tt=!1}){let Ke=cn(),mt=Qr(),Ue=(0,o.useContext)(ln),Ge=Z||Ue.claimPending===!0,Yt=eo(),[Xe,Gt]=(0,o.useState)(!1),[_,ve]=(0,o.useState)(null),[Je,xe]=(0,o.useState)(je??"US"),[vt,We]=(0,o.useState)(Oe??""),[He,nt]=(0,o.useState)(Ee??""),[Ze,wn]=(0,o.useState)(J??""),[ot,$n]=(0,o.useState)(S??""),[Vt,fn]=(0,o.useState)(se??""),[Jt,tr]=(0,o.useState)({}),Tt=(0,o.useRef)(Oe??""),St=(0,o.useRef)(je??"US"),Xt=(0,o.useRef)(Ee??""),Qt=(0,o.useRef)(J??""),Mt=(0,o.useRef)(S??""),At=(0,o.useRef)(se??""),Ct=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(v,W,ne,V,fe)=>{if(Ct.current[v])return;let Re=W?.trim();!Re||Re===ne.current||(ne.current=Re,V(Re),fe?.(Re))};i("country",je,St,xe,Ve),i("zip",Oe,Tt,We,Ne),i("addressLine1",Ee,Xt,nt),i("addressLine2",J,Qt,wn),i("city",S,Mt,$n),i("state",se,At,fn)},[je,Oe,Ee,J,S,se,Ve,Ne]);let re=(0,o.useMemo)(()=>(0,C.resolveAVSConfig)(ae),[ae]),qn=re!==null,N=(0,o.useMemo)(()=>(0,C.isAuthorizationOnlySession)(D),[D]),at=!!D?.vault?.html,Bt=!!D?.gateways?.pcivault,ze=!!(D?.gateways?.stripe?.enabledPaymentMethods??h)?.includes("card"),it=at||ze||Bt,Ye=!!(x&&it&&Ke&&e),[kn,Rn]=(0,o.useState)(()=>oe!=="buttons"||dt?e??null:null),[Dn,jn]=(0,o.useState)(0),In=oe!=="buttons"||dt||!!e&&kn===e,rt=(0,o.useMemo)(()=>!Ke||!Ye||!e||!In?null:Ke.cardCapture({sessionId:e,captureMethod:D?.captureMethod}),[Ke,Ye,e,In,D?.captureMethod]),Ft=(0,o.useMemo)(()=>{let i=Je,v=re?(0,C.isAVSFieldVisible)(re.postal_code,i):!1;return Ps(i,vt,v)},[re,Je,vt]),{avsInvalid:rn,invalidAvsFields:gt}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Ye||!re)return{avsInvalid:!1,invalidAvsFields:i};let v=Je,W=(fe,Re)=>(0,C.isAVSFieldVisible)(fe,v)&&!Re.trim(),ne={line1:W(re.address_line_1,He),city:W(re.city,ot),state:W(re.state,Vt),zip:Ft.empty||Ft.malformed};return{avsInvalid:ne.line1||ne.city||ne.state||ne.zip,invalidAvsFields:ne}},[Ye,re,Je,He,ot,Vt,Ft]),[It,Zt]=(0,o.useState)(!1),[on,Kt]=(0,o.useState)(!1),[zt,Ot]=(0,o.useState)(()=>Uo(D?.vault)),[Me,Nt]=(0,o.useState)(dt&&it?"card":"buttons"),[yt,gn]=(0,o.useState)(null),Vn=Me==="expanding"||Me==="card",Ut=280,$t=(0,o.useRef)(null),Dt=(0,o.useCallback)(i=>{$t.current&&clearTimeout($t.current),$t.current=setTimeout(()=>{$t.current=null,i()},Ut)},[Ut]);(0,o.useEffect)(()=>()=>{$t.current&&clearTimeout($t.current)},[]);let Ln=(0,o.useCallback)(()=>{Rn(e??null),jn(i=>i+1),Nt("expanding"),Dt(()=>Nt("card"))},[Dt,e]),zn=(0,o.useCallback)(()=>{Nt("collapsing"),Dt(()=>Nt("buttons"))},[Dt]),en=(0,o.useCallback)(i=>{gn(i),Nt("apm-expanding"),Dt(()=>Nt("apm-form"))},[Dt]),Ht=(0,o.useCallback)(()=>{Nt("apm-collapsing"),Dt(()=>{Nt("buttons"),gn(null)})},[Dt]);(0,o.useEffect)(()=>{oe==="buttons"&&dt&&it&&(Rn(e??null),Nt("card"))},[oe,dt,it,e]);let[tn,$e]=(0,o.useState)(null),T=(0,o.useRef)(!1),$=(0,o.useRef)(null),B=(0,o.useRef)("idle"),[Ce,ke]=(0,o.useState)(null),y=(0,o.useRef)(Ce);(0,o.useEffect)(()=>{y.current=Ce},[Ce]);let r=n||Yt,g=u??_,L=(0,o.useMemo)(()=>(0,Lt.resolveTheme)(j),[j]),f=(0,o.useMemo)(()=>{let i=L?.buttonsLayout??(0,C.resolveButtonsLayoutTheme)(te);return X?{...i,...X,cardButton:{...i.cardButton,...X.cardButton},cardFormContainer:{...i.cardFormContainer,...X.cardFormContainer},backButton:{...i.backButton,...X.backButton},backButtonIcon:{...i.backButtonIcon,...X.backButtonIcon},submitButton:{...i.submitButton,...X.submitButton},title:{...i.title,...X.title}}:i},[L,te,X]),K=de??L?.appearance,Te=(0,o.useMemo)(()=>{let i=K?.variables,v=Re=>typeof Re=="string"&&Re?Re:void 0,W=f.submitButton,ne=v(i?.colorPrimary)??v(W?.backgroundColor)??"#4A49FF",V=oe==="buttons",fe=f.nameInput;return{primaryColor:ne,primaryHoverColor:v(i?.colorPrimaryHover)??so(ne,.12),inputBackgroundColor:v(f.cardInputBackground)??v(i?.colorBackground)??"#ffffff",textColor:v(f.cardInputColor)??v(fe?.color)??v(i?.colorText)??"#262833",borderColor:v(f.cardInputBorder)??(V?"#e5e7eb":"#A4A4FF"),placeholderColor:v(f.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(i?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(fe?.fontFamily)??v(i?.fontFamily)??"Poppins, sans-serif",fontSize:v(f.cardInputFontSize)??v(i?.fontSizeBase)??"16px",fontWeight:String(Qa(fe?.fontWeight)??400),borderRadius:v(i?.borderRadius)??"8px"}},[K,f,oe]),st=Ue.inlineSessionPatchProcessing??!1,ee=(O??Xe)||st,H=r.replace(/\/+$/,""),m=(0,o.useMemo)(()=>zo({userId:a,email:c,firstName:U,lastName:P,country:je,zip:Oe},Jt),[a,c,U,P,je,Oe,Jt]),q=[m.firstName,m.lastName].filter(i=>!!i?.trim()).join(" "),he=(0,o.useMemo)(()=>Ke?Ke.getRawProvider():null,[Ke]),Ie=(0,o.useMemo)(()=>mt?mt.getRawProvider():null,[mt]),Ae=Q||100,hn=(0,o.useMemo)(()=>K?(0,un.toStripeAppearance)(K):null,[K]),gr=hn?{appearance:hn}:null,Co=(0,o.useMemo)(()=>{let i=hn??{},v=i.rules??{};return{...i,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[hn]),Or=(0,o.useMemo)(()=>{let i=$a(Q);return{...i,currency:_e.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...gr}},[Q,_e,gr]),ta=(0,o.useMemo)(()=>({mode:"payment",amount:Ae,currency:_e.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...gr}),[Ae,_e,gr]),me=(0,o.useCallback)(i=>{ve(i),b?.(i)},[b]);(0,o.useEffect)(()=>{!Ye||!rt||rt.setCardFieldOrder?.(be??null,re==null)},[Ye,rt,be,re]),(0,o.useEffect)(()=>{(Me==="expanding"||Me==="collapsing"||Me==="apm-expanding"||Me==="apm-collapsing")&&me(null)},[Me,me]);let an=(0,o.useCallback)((i,v,W)=>{d?.(Rt(i,v,W))},[d]),nr=(0,o.useCallback)((i,v,W)=>{let ne=W?.popupBlocked??Nn(v),V=gs(i,ne),fe=Xn(W?.code)??Tn(v)??"external_payment_method_failed",Re=new Lt.FloPayError(V,"api_error",{code:"external_payment_method_failed",param:i});$e(null),oe==="buttons"&&(Nt("buttons"),gn(null)),me(V),p?.(Re),console.error("[FloPay] External payment method failed:",{method:i,code:fe,popupBlocked:ne})},[oe,p,me]);(0,o.useEffect)(()=>{if(!Ye||!e){Ot(null);return}let i=Uo(D?.vault);if(i){Ot(i);return}if(!In){Ot(null);return}Ot(null);let v=!0;return new un.PaymentAPI(H).getVaultCapture(e,t).then(W=>{if(!v)return;let ne=Uo(W);ne?Ot(ne):me("Failed to load the secure card form.")}).catch(W=>{v&&me(W instanceof Error?W.message:"Failed to load the secure card form.")}),()=>{v=!1}},[Ye,In,Dn,e,D?.vault?.html,D?.vault?.messageToken,D?.vault?.expectedOrigin,H,t,me]);let Pn=(0,o.useRef)({onComplete:l,onError:p,updateError:me,emitDecline:an,resolvedAccount:m,avsConfig:re,avsCheckProp:ue,sessionId:e,nonce:t,baseUrl:H,captureMethod:D?.captureMethod,paymentId:D?.paymentId,authorizationExpiresAt:D?.authorizationExpiresAt});Pn.current={onComplete:l,onError:p,updateError:me,emitDecline:an,resolvedAccount:m,avsConfig:re,avsCheckProp:ue,sessionId:e,nonce:t,baseUrl:H,captureMethod:D?.captureMethod,paymentId:D?.paymentId,authorizationExpiresAt:D?.authorizationExpiresAt};let So=(0,o.useRef)(!1),Ri=(0,o.useCallback)(()=>{let{resolvedAccount:i,avsConfig:v,avsCheckProp:W}=Pn.current,ne=St.current||i.country||"US",V=v?(0,C.isAVSFieldVisible)(v.state,ne):!1,fe=v?(0,C.isAVSFieldVisible)(v.address_line_1,ne):!1,Re=v?(0,C.isAVSFieldVisible)(v.postal_code,ne):!1,lt=v?(0,C.isAVSFieldVisible)(v.city,ne):!1,Pt=v?(0,C.isAVSFieldVisible)(v.address_line_2,ne):!1,et=fe&&!V&&Re?(0,C.getStateFromPostalCode)(ne,(Tt.current??"").trim()):null,wt=V?At.current:et;return{accountData:{userId:i.userId??"",email:i.email??"",firstName:i.firstName??"",lastName:i.lastName??"",...Re&&Tt.current?{zip:Tt.current}:{},...lt&&Mt.current?{city:Mt.current}:{},...wt?{state:wt}:{},...fe&&Xt.current?{addressLine1:Xt.current}:{},...Pt&&Qt.current?{addressLine2:Qt.current}:{},country:ne},...W!==void 0?{avsCheck:W}:{},...v?{avsConfig:{country:(0,C.isAVSFieldVisible)(v.country,ne),postal_code:Re,address_line_1:fe,address_line_2:Pt,city:lt,state:V}}:{}}},[]),na=(0,o.useRef)(Ge);na.current=Ge,(0,o.useEffect)(()=>{Ge||g!==Ga||Pn.current.updateError(null)},[Ge,g]),(0,o.useEffect)(()=>{!Ye||!rt||rt.setSubmitGate?.(rn||Ge)},[Ye,rt,rn,Ge]),(0,o.useEffect)(()=>{if(!Ye||!rt)return;So.current=!1;let i=!1,v=rt.on("submitting",()=>{Zt(!0),$.current&&clearTimeout($.current),B.current="validation-window",$.current=setTimeout(()=>{$.current=null,B.current==="validation-window"&&(B.current="processing")},us),$e("processing");let{baseUrl:Re,sessionId:lt,nonce:Pt,updateError:et,onError:wt}=Pn.current;!lt||!Pt||new un.PaymentAPI(Re).patchAccountSnapshot(lt,Pt,Ri(),{telemetryMode:"best_effort"}).catch(Pe=>{if(!ps(Pe))return;let Et=Pe instanceof Error?Pe.message:"Please check your billing address and try again.";et(Et),B.current="idle",$e(null),wt?.(Pe instanceof Lt.FloPayError?Pe:new Lt.FloPayError(Et,"api_error"))})}),W=rt.on("complete",async Re=>{if(ur(Re.sessionId??Pn.current.sessionId),B.current="terminal",$e("success"),await new Promise(et=>setTimeout(et,xn)),So.current)return;So.current=!0;let lt=Pn.current,Pt=(0,C.isAuthorizationOnlySession)(lt)||Re.outcome==="authorized";Pn.current.onComplete?.(Pt?{status:"authorized",paymentIntentId:Re.intentId,paymentId:Re.paymentId??lt.paymentId,sessionId:Re.sessionId??lt.sessionId,authorizationExpiresAt:Re.authorizationExpiresAt??lt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Re.intentId,checkoutMethod:"card"})}),ne=rt.on("decline",async Re=>{let{updateError:lt,emitDecline:Pt}=Pn.current,et=Re.message??"Your payment was declined. Please try another card or contact your bank.";B.current="terminal",lt(et),$e("error");let wt=Re.failureOutcome??(0,C.normalizeCheckoutFailureOutcome)(Re.declineReason)??"authorization_declined";Pt("card",et,{code:wt,declineCode:wt}),await new Promise(Pe=>setTimeout(Pe,vn)),!i&&(B.current="idle",$e(null))}),V=rt.on("error",async Re=>{let{updateError:lt,onError:Pt}=Pn.current,et=Re.message??"There was a problem processing your payment. Please try again.";B.current="terminal",lt(et),$e("error"),Pt?.(new Lt.FloPayError(et,"api_error",{code:Re.failureOutcome??"capture_failed"})),await new Promise(wt=>setTimeout(wt,vn)),!i&&(B.current="idle",$e(null))}),fe=rt.on("blocked",()=>{if(!na.current){Zt(!0);return}Pn.current.updateError(Ga)});return()=>{i=!0,$.current&&(clearTimeout($.current),$.current=null),B.current="idle",v(),W(),ne(),V(),fe()}},[Ye,rt]);let bn=!!Qe?.clientId,hr=Array.isArray(h),Nr=hr&&h.length>0,Ii=hr&&h.includes("paypal"),{expressMethods:Ur,paymentElementMethods:Pr}=(0,o.useMemo)(()=>(0,C.partitionStripeMethods)(h,{excludePaypal:bn}),[h,bn]),ra=bn||!!mt,Ei=(0,o.useMemo)(()=>ra?Ur.filter(i=>i!=="paypal"):Ur,[Ur,ra]),_i=(0,o.useMemo)(()=>{let i=[];return M&&i.push("apple_pay"),ce&&i.push("google_pay"),i},[M,ce]),$r=hr?Ei:_i,xi=x&&$r.length>0,wo=qn?Je:je,qr=(0,o.useMemo)(()=>{let i=wo?.trim().toUpperCase();return i?ye?Pr.filter(v=>{let W=ye[v];return!W||W.length===0||W.includes(i)}):(0,C.filterStripeMethodsByCountry)(Pr,wo):Pr},[Pr,wo,ye]),ko=(0,o.useMemo)(()=>({mode:"payment",amount:Ae,currency:_e.toLowerCase(),paymentMethodCreation:"manual",appearance:Co}),[Ae,_e,Co]),[oa,aa]=(0,o.useState)("loading"),[ia,sa]=(0,o.useState)("loading"),[la,ca]=(0,o.useState)("loading"),[Ti,Ro]=(0,o.useState)(!1),[da,Io]=(0,o.useState)("loading"),[jr,Mi]=(0,o.useState)();(0,o.useEffect)(()=>{Mi(qa())},[]);let ua=E&&(bn||(hr?Ii:jr===!1)),pa=x&&xi,br=!Ge&&ua&&bn,ma=da==="retrying"||da==="exhausted",vr=!Ge&&ua&&!!Ie&&(!bn||ma),Cr=!Ge&&pa&&!!he,Sr=!Ge&&x&&Nr&&qr.length>0&&!!he,Ai=br&&!ma?Ti:vr&&Za(oa),Bi=Cr&&Za(ia),Fi=Sr&&la!=="load_error",ya=i=>i==="loading"||i==="ready",fa=br||vr&&ya(oa)||Cr&&ya(ia)||Sr&&la!=="load_error",Vr=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Vr.current){if(!x&&!E){Vr.current=!0;let i=new Lt.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(i),me(i.message)}else if(!x&&E&&!bn&&!Ie){Vr.current=!0;let i=new Lt.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(i),me(i.message)}else if(jr!==void 0&&!Ge&&!it&&!fa){Vr.current=!0;let i=new Lt.FloPayError("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"});p?.(i),me(i.message)}}},[x,E,bn,Ie,jr,Ge,it,fa,p,me]);let ga=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(ga.current||!Nr)return;let i=[];M!==!0&&i.push("showApplePay"),ce!==!0&&i.push("showGooglePay"),i.length!==0&&(ga.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.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,M,ce]);let ha=(0,o.useCallback)((i,v)=>Ue.applyInlineSessionPatch?Ue.applyInlineSessionPatch(i).then(W=>({error:null,sessionId:W.sessionId||e,nonce:W.session?.clientSecret||t})).catch(W=>{let ne=Xa(v,W);return me(ne.message),p?.(ne),{error:ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ue.applyInlineSessionPatch,t,p,e,me]),sn=(0,o.useCallback)(async i=>{if(!ge)return{proceed:!0};try{let v=await ge({method:i,sessionId:e||void 0,createSession:Ue.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&tr(ne=>({...ne??{},...v.account}));let W=await ha(v,i);return W.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:W.sessionId,nonce:W.nonce}}return{proceed:!0}}catch(v){let W=Xa(i,v);return me(W.message),p?.(W),{proceed:!1}}},[ha,Ue.inlineSessionDraft,ge,p,e,me]),Pa=(0,o.useCallback)(async(i,v)=>{if(T.current)return;T.current=!0,Gt(!0),$e("processing"),me(null);let W=v?.sessionId??e,ne=v?.nonce??t,V=zo(m,v?.accountPatch),fe=v?.completionPaymentMethodId??Tr(i),Re=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i;try{let Pt=await new un.PaymentAPI(H).processPayment(V.userId??"",{sessionId:W,nonce:ne,tokenizedData:Re,accountData:{userId:V.userId??"",email:V.email??"",firstName:V.firstName??"",lastName:V.lastName??"",...re?(()=>{let Pe=St.current,Et=(0,C.isAVSFieldVisible)(re.state,Pe),jt=(0,C.isAVSFieldVisible)(re.address_line_1,Pe),Yn=(0,C.isAVSFieldVisible)(re.postal_code,Pe),Gn=jt&&!Et&&Yn?(0,C.getStateFromPostalCode)(Pe,(Tt.current??"").trim()):null,_t=Et?At.current:Gn;return{country:Pe,...Yn&&Tt.current?{zip:Tt.current}:{},...(0,C.isAVSFieldVisible)(re.city,Pe)&&Mt.current?{city:Mt.current}:{},..._t?{state:_t}:{},...jt&&Xt.current?{addressLine1:Xt.current}:{},...(0,C.isAVSFieldVisible)(re.address_line_2,Pe)&&Qt.current?{addressLine2:Qt.current}:{}}})():{}},chv:I,avsCheck:ue??!1,checkoutType:A,checkoutLayout:le,avsConfig:re?{country:(0,C.isAVSFieldVisible)(re.country,St.current),postal_code:(0,C.isAVSFieldVisible)(re.postal_code,St.current),address_line_1:(0,C.isAVSFieldVisible)(re.address_line_1,St.current),address_line_2:(0,C.isAVSFieldVisible)(re.address_line_2,St.current),city:(0,C.isAVSFieldVisible)(re.city,St.current),state:(0,C.isAVSFieldVisible)(re.state,St.current)}:void 0});if(Pt.ok){let Pe=Pt.status===204?null:await Pt.json().catch(()=>null),Et=(0,C.isAuthorizationOnlySession)(D)||Pe?.status==="authorized";ur(W),$e("success"),ke(null),await new Promise(jt=>setTimeout(jt,xn)),l?.(Et?{status:"authorized",...typeof Pe?.paymentId=="string"?{paymentId:Pe.paymentId}:D?.paymentId?{paymentId:D.paymentId}:{},sessionId:typeof Pe?.sessionId=="string"?Pe.sessionId:W,...typeof Pe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Pe.authorizationExpiresAt}:D?.authorizationExpiresAt?{authorizationExpiresAt:D.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:fe,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:fe,checkoutMethod:i.isPaypal?"paypal":"card"});return}let et=await Pt.json().catch(()=>null);if(et?.type==="paypal_redirect_required"){let Pe=et.threeDSecureToken,Et=et.paymentMethodId||i.id||"";if(!Ke||!Pe){$e("error"),me("PayPal authorization required but no token provided.");return}try{let jt=mt?.getRawProvider();if(!jt){me("PayPal is not available.");return}let Yn={return_url:window.location.href};Et&&(Yn.payment_method=Et);let{error:Gn}=await jt.confirmPayment({clientSecret:Pe,confirmParams:Yn,redirect:"if_required"});if(Gn){$e("error");let _t=Gn.message??"PayPal payment failed.";me(_t),an("paypal",_t,{code:Gn.code})}}catch(jt){$e("error"),me(jt instanceof Error?jt.message:"PayPal authorization failed.")}return}if(et?.type==="paypal_direct_required"){let Pe=et.orderId;if(!Pe){$e("error"),me("PayPal retry required but no order id provided.");return}let Et=y.current?.attempts??0;if(Et>=2){$e("error"),me("PayPal payment could not be completed after multiple attempts."),an("paypal","paypal_direct_required retry limit exceeded");return}Ro(!1),Io("loading"),ke({orderId:Pe,attempts:Et+1}),$e(null);return}$e("error");let wt=et?.message??"Payment failed. Please try again.";me(wt),an(i.isPaypal?"paypal":"card",wt,{code:et?.code??et?.gatewayErrorCode,declineCode:et?.declineCode??et?.gatewayDeclineReason}),await new Promise(Pe=>setTimeout(Pe,vn))}catch(lt){$e("error"),me(lt instanceof Error?lt.message:"An unexpected error occurred"),await new Promise(Pt=>setTimeout(Pt,vn))}finally{Gt(!1),$e(null),T.current=!1}},[H,e,t,m,q,I,Ke,mt,D,l,p,me,an]),nn=(0,o.useCallback)((i,v)=>{k?k(i):Pa(i,v)},[k,Pa]),ba=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||ba.current)return;let i=new URLSearchParams(window.location.search),v=i.get("payment_intent"),W=i.get("payment_intent_client_secret"),ne=i.get("redirect_status");if(!v||!W)return;let V=wt=>{let Pe=localStorage.getItem(wt);if(!Pe)return null;try{return JSON.parse(Pe)}catch{return localStorage.removeItem(wt),null}},fe=V(Sn)??V(Ya),Re;if(fe?.clientSecret){if(fe.clientSecret!==W)return;Re={...fe.accountPatch?{accountPatch:fe.accountPatch}:{},...fe.sessionId?{sessionId:fe.sessionId}:{},...fe.nonce?{nonce:fe.nonce}:{}}}else if(fe?.sessionId&&fe.sessionId!==e)return;ba.current=!0,localStorage.removeItem(Sn),localStorage.removeItem(Ya);let lt=new URL(window.location.href);lt.searchParams.delete("payment_intent"),lt.searchParams.delete("payment_intent_client_secret"),lt.searchParams.delete("redirect_status"),window.history.replaceState({},"",lt.toString());let Pt=fe?.paymentMethodType??fe?.tokenType??"card",et="card";(async()=>{let wt=Ke?.getRawProvider();if(!wt){let _t="Payment is not available \u2014 please refresh and try again.";me(_t),an(et,_t);return}if(ne==="failed"){let _t="Payment was declined. Please try again.";me(_t),an(et,_t);return}let{paymentIntent:Pe,error:Et}=await wt.retrievePaymentIntent(W);if(Et){let _t=Et.message??"Failed to retrieve payment status.";me(_t),an(et,_t,{code:Et.code});return}let jt=Pe?.status,Yn=ro(jt);if(!Pe||!Yn){let _t=jt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";me(_t),an(et,_t,{code:jt??"missing_payment_intent"});return}let Gn=typeof Pe.payment_method=="string"?Pe.payment_method:Pe.payment_method?.id;nn({id:Gn??fe?.paymentMethodId??fe?.tokenId??Pe.id,type:"card",threeDSecureActionResultTokenId:Pe.id,gateway:fe?.gateway??"stripe",paymentMethodType:Pt},Re)})()},[e,nn,Ke,me,an]);let Eo=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(Ke!==null))return(0,s.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let wr=oe==="buttons",qt=K?.variables,Di=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),_o=qt?.colorBackground,Li=_o&&!Di.has(_o)?_o:void 0,kr=f.cardInputBorder??(wr?"#e5e7eb":"#A4A4FF"),xo=qt?.colorDanger??"#dc2626",Kn=i=>It&&i?xo:kr,Kr=(Ft.malformed||Ft.empty)&&(on||It),zi=Kr?xo:Kn(gt.zip),To=f.cardFormContainer?.backgroundColor??Li??(wr?"white":"#EDEDFF"),Rr=f.cardInputBackground??qt?.colorBackground??"white",Mo=or(G),va=or(pe),rr=f.nameInput,Ca=f.cardInputFontSize??bs(rr?.fontSize)??qt?.fontSizeBase??"16px",Sa=typeof rr?.fontFamily=="string"?rr.fontFamily:qt?.fontFamily??"Poppins, sans-serif",wa=Qa(rr?.fontWeight)??400,Oi=f.cardInputColor??(typeof rr?.color=="string"?rr.color:void 0)??qt?.colorText??"#262833",Ni=f.cardInputPlaceholderColor??"#9ca3af",ht=qt?.borderRadius??"8px",Hn=qt?.borderRadius??f.cardButton?.borderRadius??ht,Wn=qt?.colorPrimary??"#4A49FF",Ui=qt?.colorPrimaryHover??so(Wn,.12),Ao=qt?.colorText??"#262833",ka={fontSize:Ca,fontFamily:Sa,fontWeight:wa,color:Oi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},$i={"--flopay-input-placeholder-color":Ni,"--flopay-input-font-size":Ca,"--flopay-input-font-family":Sa,"--flopay-input-font-weight":String(wa)},Ir=f.cardFormContainer??{},Bo=Ir.padding??(wr?"0":"1rem"),Fo=Ir.borderRadius??ht,qi=rt&&zt?(0,s.jsx)(Xr,{capture:rt,html:zt.html,messageToken:zt.messageToken,expectedOrigin:zt.expectedOrigin,theme:Te,onReady:()=>{if(!re||typeof document>"u")return;let i=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};i();let v=0,W=window.setInterval(()=>{v+=1;let ne=document.activeElement;!!ne&&ne.tagName==="IFRAME"&&ne.id==="flopay_vault_form_iframe"?(i(),window.clearInterval(W)):v>=50&&window.clearInterval(W)},100)},onError:i=>me(i),onValidation:i=>{let v=B.current;(v==="idle"||v==="validation-window")&&(me(i),i&&B.current==="validation-window"&&($.current&&(clearTimeout($.current),$.current=null),B.current="idle",$e(null)))}}):(0,s.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Ra=(0,s.jsxs)("div",{style:{backgroundColor:To,borderRadius:Fo,...Ir,padding:Bo,...$i,display:"flex",flexDirection:"column"},children:[(0,s.jsx)("style",{children:`
|
|
31
31
|
.flopay-shared-input::placeholder {
|
|
32
32
|
color: var(--flopay-input-placeholder-color);
|
|
33
33
|
opacity: 1;
|
|
@@ -35,13 +35,13 @@ ${He.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,Sa=Le==="apm-expanding"||Le==="apm-form"||Le==="apm-collapsing",qr=Le==="apm-expanding"?`flopay-card-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:Le==="apm-collapsing"?`flopay-card-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,jr=Ct?{...ho,paymentMethodTypes:[Ct]}:null;if(ae==="buttons"){let a=Le==="buttons"||Le==="expanding"||Le==="apm-expanding",C=Le==="expanding"||Le==="card"||Le==="collapsing",H=W===void 0?{boxSizing:"border-box",height:no,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ne=Le==="expanding"||Le==="apm-expanding"?`flopay-buttons-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Le==="collapsing"||Le==="apm-collapsing"?`flopay-buttons-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,j=Le==="expanding"?`flopay-card-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:Le==="collapsing"?`flopay-card-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,i.jsxs)("form",{onSubmit:vo,className:k,style:{position:"relative"},children:[(0,i.jsx)(Fo,{}),Et&&(0,i.jsx)(Sn,{status:Et,errorMessage:c}),(0,i.jsxs)("div",{style:{display:"grid"},children:[(0,i.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!ne?ls:{},...ne?{animation:ne,pointerEvents:"none"}:{}},children:[va("flopay-direct-paypal-gate-debug"),Ca("flopay-stripe-gate-debug"),fr&&He&&(0,i.jsxs)(i.Fragment,{children:[X&&(0,i.jsx)("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."}),(0,i.jsx)(Er,{sessionId:e,nonce:t,billingApiUrl:u,email:y.email,clientId:He.clientId,environment:He.environment,currency:$e.toUpperCase(),isSubscription:ot,onTokenizedBody:tn,onComplete:s,onErrorChange:ge,onDecline:d,onTechnicalFailure:er,onButtonClick:we,runBeforeButtonClick:cn,isProcessing:Se,onLoadStateChange:Po,onInitializationStateChange:bo,session:V??null,existingOrderId:X?.orderId,debug:tt},X?.orderId??"fresh")]}),gr&&(0,i.jsx)(lt.Elements,{stripe:Ve,options:Go,children:(0,i.jsx)(Ya,{sessionId:e,nonce:t,email:y.email,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:ge,isProcessing:Se,onButtonClick:we,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:Zo,placeholderBorderRadius:Kn})}),hr?(0,i.jsx)(lt.Elements,{stripe:q,options:Yo,children:(0,i.jsx)(Ga,{sessionId:e,nonce:t,email:y.email,billingApiUrl:u,intentKind:oe>0?"payment":"setup",expressMethods:Lr,onTokenizedBody:tn,onErrorChange:ge,onButtonClick:we,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:ta,placeholderBorderRadius:Kn})}):ia?(0,i.jsx)("div",{style:{height:no,borderRadius:Kn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Pr&&(0,i.jsx)(Ja,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,paymentElementMethods:Nr,stripeInstance:q,paymentElementBaseOptions:ho,onTokenizedBody:tn,onErrorChange:ge,onButtonClick:we,onDecline:d,runBeforeButtonClick:cn,onLoadStateChange:ra,isProcessing:Se,submitButtonColor:Hn,submitButtonBorderRadius:mt,submitButtonStyle:f.submitButton,onExpandApm:sn,expandedApmMethod:Ct,themeId:U,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Kn}}),qe&&(0,i.jsx)("button",{type:"button",onClick:async()=>{Se||!(await cn("card")).proceed||(we?.("card"),kn())},disabled:Se,style:{width:"100%",...H,...f.cardButton,...No({themeBundle:L,resolvedPrimaryColor:Hn,resolvedBorderRadius:mt,submitButtonStyle:f.submitButton,explicitPrimaryColor:Yt?.colorPrimary}),fontSize:f.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Se?"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:Se?.6:1},onMouseEnter:ve=>{!Se&&(L||Yt?.colorPrimary)&&(ve.currentTarget.style.backgroundColor=Fi)},onMouseLeave:ve=>{(L||Yt?.colorPrimary)&&(ve.currentTarget.style.backgroundColor=Hn)},onMouseDown:ve=>{ve.currentTarget.style.transform="scale(0.985)"},onMouseUp:ve=>{ve.currentTarget.style.transform="scale(1)"},children:(0,i.jsx)(rr,{content:W})}),c&&Le==="buttons"&&(0,i.jsx)(ar,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:c})]}),qe&&C&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...j?{animation:j}:{},...Le==="collapsing"?{pointerEvents:"none"}:{}},children:ba}),M&&Sa&&Ct&&jr&&q&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...qr?{animation:qr}:{},...Le==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:wo,borderRadius:Eo,...Sr,padding:Io},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,i.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Qt,style:{display:"inline-flex",alignItems:"center",gap:ko?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(or,{content:J})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Ro,paddingRight:80,...f.title},children:`Pay with ${(0,R.getStripeMethodDisplayName)(Ct)}`})]}),(0,i.jsx)(lt.Elements,{stripe:q,options:jr,children:(0,i.jsx)(Do,{method:Ct,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:ge,onDecline:d,onCancel:Qt,runBeforeButtonClick:cn,onButtonClick:we,isProcessing:Se,submitButtonColor:Hn,submitButtonBorderRadius:mt,submitButtonStyle:f.submitButton,errorText:c})},Ct)]})})]})]})}return Sa&&Ct&&jr&&q&&M?(0,i.jsxs)("form",{onSubmit:vo,className:k,style:{position:"relative"},children:[(0,i.jsx)(Fo,{}),Et&&(0,i.jsx)(Sn,{status:Et,errorMessage:c}),(0,i.jsx)("div",{style:{...qr?{animation:qr}:{},...Le==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:wo,borderRadius:Eo,...Sr,padding:Io},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,i.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Qt,style:{display:"inline-flex",alignItems:"center",gap:ko?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(or,{content:J})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Ro,paddingRight:80,...f.title},children:`Pay with ${(0,R.getStripeMethodDisplayName)(Ct)}`})]}),(0,i.jsx)(lt.Elements,{stripe:q,options:jr,children:(0,i.jsx)(Do,{method:Ct,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:ge,onDecline:d,onCancel:Qt,runBeforeButtonClick:cn,onButtonClick:we,isProcessing:Se,submitButtonColor:Hn,submitButtonBorderRadius:mt,submitButtonStyle:f.submitButton,errorText:c})},Ct)]})})]}):(0,i.jsxs)("form",{onSubmit:vo,className:k,style:{position:"relative"},children:[(0,i.jsx)(Fo,{}),Et&&(0,i.jsx)(Sn,{status:Et,errorMessage:c}),(0,i.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[va("flopay-direct-paypal-gate-debug-default"),Ca("flopay-stripe-gate-debug-default"),fr&&He&&(0,i.jsxs)(i.Fragment,{children:[X&&(0,i.jsx)("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."}),(0,i.jsx)(Er,{sessionId:e,nonce:t,billingApiUrl:u,email:y.email,clientId:He.clientId,environment:He.environment,currency:$e.toUpperCase(),isSubscription:ot,onTokenizedBody:tn,onComplete:s,onErrorChange:ge,onDecline:d,onTechnicalFailure:er,onButtonClick:we,runBeforeButtonClick:cn,isProcessing:Se,onLoadStateChange:Po,onInitializationStateChange:bo,session:V??null,existingOrderId:X?.orderId,debug:tt},X?.orderId??"fresh")]}),gr&&(0,i.jsx)(lt.Elements,{stripe:Ve,options:Go,children:(0,i.jsx)(Ya,{sessionId:e,nonce:t,email:y.email,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:ge,isProcessing:Se,onButtonClick:we,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:Zo,placeholderBorderRadius:Kn})}),hr&&(0,i.jsx)(lt.Elements,{stripe:q,options:Yo,children:(0,i.jsx)(Ga,{sessionId:e,nonce:t,email:y.email,billingApiUrl:u,intentKind:oe>0?"payment":"setup",expressMethods:Lr,onTokenizedBody:tn,onErrorChange:ge,onButtonClick:we,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:ta,placeholderBorderRadius:Kn})}),Pr&&(0,i.jsx)(Ja,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,paymentElementMethods:Nr,stripeInstance:q,paymentElementBaseOptions:ho,onTokenizedBody:tn,onErrorChange:ge,onButtonClick:we,onDecline:d,runBeforeButtonClick:cn,onLoadStateChange:ra,isProcessing:Se,submitButtonColor:Hn,submitButtonBorderRadius:mt,submitButtonStyle:f.submitButton,themeId:U,onExpandApm:sn,expandedApmMethod:Ct,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Kn}})]}),qe&&(Ei||Ii||_i)&&(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,i.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,i.jsx)("span",{children:"or pay with card"}),(0,i.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),qe&&ba]})}var cr=require("@flopay/js"),je=require("@flopay/shared");var Tr="card";async function gs(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:m}=await e.retrieveSetupIntent(t);return{error:m,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:l,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:l??null}}async function hs(e,t,n,l){if(l){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:m,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:m??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:s}=await e.confirmCardPayment(t,n);return{error:s,intent:o??null}}function zo(e,t){return Object.assign(e,{checkoutMethod:t})}function Mn(e,t){let n=e instanceof je.FloPayError?e:new je.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function xr(e,t){try{return await e()}catch(n){throw Mn(n,t)}}function ni(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 Ps(e){return e.status==="succeeded"||e.status==="declined"}async function ri(e){if(typeof document>"u"||typeof window>"u")throw new je.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,l=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,s=async()=>{let b=new AbortController,_=()=>b.abort();e.signal?.aborted?b.abort():e.signal?.addEventListener("abort",_);let k=window.setTimeout(()=>b.abort(),l);try{let F=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:b.signal});if(!F.ok)return{status:"unknown"};let p=await F.json().catch(()=>null);return bs(p)}catch{return{status:"unknown"}}finally{window.clearTimeout(k),e.signal?.removeEventListener("abort",_)}},m=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.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 I=document.createElement("iframe");I.setAttribute("title","Card authentication"),I.setAttribute("allow","payment"),I.tabIndex=0,I.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(";"),I.src=e.nextActionRedirectUrl,d.appendChild(I),document.body.appendChild(d),I.focus();let N=null;try{N=new URL(e.billingApiUrl,window.location.href).origin}catch{N=null}try{let b=await new Promise((_,k)=>{let F=!1,p=0,v=0,x=0,M=!1,g=()=>{window.clearTimeout(p),window.clearInterval(v),window.clearTimeout(x),window.removeEventListener("message",ae),I.removeEventListener("load",z),e.signal?.removeEventListener("abort",ue)},he=async()=>{if(!(F||M)){M=!0;try{let U=await s();if(F||!Ps(U))return;F=!0,g(),_(U)}finally{M=!1}}},z=()=>{window.clearTimeout(x),x=window.setTimeout(()=>{he()},250)},ue=()=>{F||(F=!0,g(),k(new je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ae=U=>{if(U.source!==I.contentWindow||N&&U.origin!==N)return;let te=U.data;!te||typeof te!="object"||te.source!=="flopay-vault-3ds-return"||F||(F=!0,g(),_(null))};p=window.setTimeout(()=>{F||(F=!0,g(),k(new je.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),v=window.setInterval(()=>{he()},n),I.addEventListener("load",z),window.addEventListener("message",ae),e.signal?.addEventListener("abort",ue),e.signal?.aborted&&ue()});return b||await s()}finally{d.parentNode?.removeChild(d),m?.isConnected&&m.focus()}}function bs(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Un(e,t="Payment failed. Please try again.",n){let l=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,s=On(o)??o;return zo(new je.FloPayError(s,"api_error",{code:e?.gatewayErrorCode}),l)}function Oo(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 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 oi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ao(o)))return o;let l=e?.data;if(l&&typeof l=="object"){let o=l,s=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let d of s)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||ao(d)))return d;let m=o.gateways;if(m&&typeof m=="object"){let d=m.stripe;if(d&&typeof d=="object"){let I=d,N=[I.stripeClientSecret,I.clientSecret];for(let b of N)if(typeof b=="string"&&b.length>0&&(!t?.requirePaymentIntentClientSecret||ao(b)))return b}}}}async function Cs({billingApiUrl:e,sessionId:t,nonce:n,responseJson:l}){let o=oi(l,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new cr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ao(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function dr({billingApiUrl:e,sessionId:t,session:n,nonce:l,tokenizedData:o,returnUrl:s,telemetry:m}){let d=e.replace(/\/+$/,""),I=t??n.id,N=l??n.clientSecret,b=n.customer?.id??n.accountData?.userId??"",_=n.customer?.email??n.accountData?.email??"",k=n.customer?.firstName??n.accountData?.firstName??"",F=n.customer?.lastName??n.accountData?.lastName??"",p=n.customer?.country??n.accountData?.country??void 0,v=n.customer?.zip??n.accountData?.zip??void 0,x=new cr.PaymentAPI(d,m===!1?{telemetry:!1}:void 0),M=await vs(()=>x.processPayment(b,{sessionId:I,nonce:N,tokenizedData:o,accountData:{userId:b,email:_,firstName:k,lastName:F,country:p,zip:v},returnUrl:s??Oo(n)}));if(M.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Xr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let g;try{g=await M.json()}catch{throw new je.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:M.status})}if(g?.type==="paypal_redirect_required"||g?.type==="3ds_required"){let z=oi(g);if(!z)throw new je.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:M.status});return{type:g.type,threeDSecureToken:z,paymentMethodId:g.paymentMethodId}}if(g?.gatewayErrorCode==="authentication_required"){let z=await Cs({billingApiUrl:d,sessionId:I,nonce:N,responseJson:g});if(z)return z;throw zo(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let he=new je.FloPayError(g?.message??"Payment failed. Please try again.","api_error",{code:g?.code??g?.gatewayErrorCode,declineCode:g?.declineCode??g?.gatewayDeclineReason,statusCode:M.status});throw Object.assign(he,{telemetryOutcome:(0,je.classifyPaymentRejection)(M.status,g)})}async function io(e,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:m,returnUrl:d,telemetry:I}){let N=t?.getRawProvider();if(!N)throw Mn(new je.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!l||!e.threeDSecureToken)throw zo(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let b=(0,je.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,k=e.paymentMethodId,F=await xr(()=>gs(N,e.threeDSecureToken,b),"card");if(F){if(F.error)throw Mn(new je.FloPayError(F.error.message??`Failed to retrieve 3DS ${b?"setup":"payment"} status.`,"api_error",{code:F.error.code}),"card");let v=F.intent;!k&&v?.payment_method&&(typeof v.payment_method=="string"?k=v.payment_method:"id"in v.payment_method&&(k=v.payment_method.id??void 0))}let p=k?await xr(()=>hs(N,e.threeDSecureToken,{payment_method:k,return_url:d??Oo(m)??window.location.href},b),"card"):null;if(p){if(p.error)throw Mn(new je.FloPayError(p.error.message??"3DS authentication failed.","api_error",{code:p.error.code}),"card");_=p.intent}else{let v=await xr(()=>N.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(v.error)throw Mn(new je.FloPayError(v.error.message??"3DS authentication failed.","api_error",{code:v.error.code}),"card");_=(b?v.setupIntent:v.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let v=await dr({billingApiUrl:o,sessionId:s,session:m,telemetry:I,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:d});return v.type==="success"?{...v.result,paymentIntentId:v.result.paymentIntentId??_.id,paymentMethodId:v.result.paymentMethodId??k}:io(v,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:m,returnUrl:d,telemetry:I})}throw Mn(new je.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let b=(n??t)?.getRawProvider();if(!b)throw Mn(new je.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:k}=await xr(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(k)throw Mn(new je.FloPayError(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await xr(()=>b.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Oo(m)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(_)throw Mn(new je.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new je.FloPayError("Unsupported payment redirect state.","api_error")}function Jn(e){if(e instanceof je.FloPayError){let l=On(e.message);return l&&l!==e.message?Object.assign(new je.FloPayError(l,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=On(t)??t;return new je.FloPayError(n,"api_error")}function so(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new je.FloPayError("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:l,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let s=!!t&&t!==e,[m,d]=await Promise.all([(0,cr.loadFloPay)(e,{billingApiUrl:n,locale:l,telemetry:o}),s?(0,cr.loadFloPay)(t,{billingApiUrl:n,locale:l,telemetry:o}).catch(I=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",I),null)):Promise.resolve(null)]);return{flopay:m,paypalFlopay:t?s?d:m:null}}var w=require("react/jsx-runtime"),ur=44,Ho="flopay_checkout_saved_payment_resume",po=new Map,co=new Map;function ai(e,t){t.settled&&t.consumers===0&&po.get(e)===t&&po.delete(e)}function Ss(e,t,n){let l=co.get(e);if(l&&(!l.sdkGeneratedIdempotencyKey||!t||l.sdkGeneratedIdempotencyKey===t))return l.attempt;let o=n(),s={attempt:o,sdkGeneratedIdempotencyKey:t};co.set(e,s);let m=()=>{co.get(e)===s&&co.delete(e)};return o.then(m,m),o}function Mr(e){return new Promise(t=>setTimeout(t,e))}function uo(e,t,n){let l=Kr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Pe.SDK_VERSION,enabled:t!==!1});return l.beginCheckout(n),l}function Br(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Uo(e,t,n,l,o){let s=uo(e,t,n);s.error({errorCode:l,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Br(s)}function ws(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 Vo(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function $o(e){return!e||e.data.stripe?.publishableKey?!1:!!Vo(e)?.clientId}function Bn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ks(){if(!Bn())return null;try{let e=window.sessionStorage.getItem(Ho);return e?JSON.parse(e):null}catch{return null}}function ii(e){if(Bn())try{window.sessionStorage.setItem(Ho,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function qo(){if(Bn())try{window.sessionStorage.removeItem(Ho)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var Wo=":idempotency-key";function Rs(e){if(!Bn())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 si(e,t,n){if(Bn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(l){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",l)}}function Ko(e){if(Bn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function Is(e){if(Bn())try{return window.sessionStorage.getItem(e+Wo)??void 0}catch{return}}function Es(e,t){if(Bn())try{window.sessionStorage.setItem(e+Wo,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function _s(e){if(Ko(e),!!Bn())try{window.sessionStorage.removeItem(e+Wo)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function xs(){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 l of t)e.searchParams.has(l)&&(e.searchParams.delete(l),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function li(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function Ts(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 jo(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function mo({sessionId:e,nonce:t,createSession:n,billingApiUrl:l,telemetry:o,appearance:s,locale:m,loading:d,error:I,onComplete:N,onError:b,onDecline:_,onCountryChange:k,onZipChange:F,showPayPal:p=!0,showStripe:v=!0,enabledPaymentMethods:x,showApplePay:M=!0,showGooglePay:g=!0,debug:he=!1,layout:z,theme:ue,buttonsTheme:ae,buttonsStyles:U,cardButtonContent:te,cardBackButtonContent:Q,cardTitleContent:pe,showSecurityFooter:W,onButtonClick:J,onBeforeButtonClick:me,enableAVS:Me,cardFieldOrder:we,cardPreFormSlot:be,avsLayout:ie,className:Ce,initialErrorMessage:Be=null,children:se,checkoutMode:Ee,confirmLabel:_e,renderConfirmButton:Re,onSessionCompleted:Z}){let T=(0,Pe.resolveBillingApiUrl)(l),ce=(0,B.useMemo)(()=>(0,Pe.resolveTheme)(ue),[ue]),Oe=s??ce?.appearance,ze=n?"embedded_checkout":"standard_checkout",ye=se?"custom_layout":z==="buttons"?"buttons_layout":"default_layout",[E,re]=(0,B.useState)(null),[oe,$e]=(0,B.useState)(null),ct=(0,B.useRef)(null),[He,ot]=(0,B.useState)(null),V=(0,B.useRef)(null),[G,tt]=(0,B.useState)(null),[Ae,at]=(0,B.useState)(e??""),Ge=e??Ae,We=n?"":Ge,[rn,h]=(0,B.useState)(!0),[ke,dt]=(0,B.useState)(null),[nt,Qe]=(0,B.useState)("full"),[Ye,Ze]=(0,B.useState)(!1),[xe,Ke]=(0,B.useState)(Be),[kt,Je]=(0,B.useState)(null),[An,Pt]=(0,B.useState)(null),[Fn,on]=(0,B.useState)(void 0),[hn,Zt]=(0,B.useState)(""),[Dn,Nt]=(0,B.useState)(!1),[Rt,qt]=(0,B.useState)(!1),Gt=(0,B.useRef)(0),[Bt,jt]=(0,B.useState)("loading"),[At,le]=(0,B.useState)(0),en=(0,B.useRef)(!1),D=(0,B.useRef)(!1),gt=(0,B.useRef)(!1),ut=(0,B.useRef)(null),bt=(0,B.useMemo)(()=>({checkoutMode:Ee??nt,layout:se?"unknown":z==="buttons"?"buttons":"embedded"}),[Ee,se,nt,z]),Te=(0,B.useRef)(N);Te.current=N;let qe=(0,B.useRef)(b);qe.current=b;let $n=(0,B.useRef)(_);$n.current=_,(0,B.useEffect)(()=>{Mt(oe)?.setCheckoutContext(bt),He&&He!==oe&&Mt(He)?.setCheckoutContext(bt)},[oe,He,bt]);let Ln=(0,B.useRef)(Z);Ln.current=Z;let qn=(0,B.useCallback)(P=>{jt(P),!(P!=="exhausted"||gt.current)&&(gt.current=!0,qe.current?.(new Pe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Zn=(0,B.useCallback)(()=>{jt("retrying"),le(P=>P+1)},[]);(0,B.useEffect)(()=>{jt("loading"),le(0),gt.current=!1},[Ge]),(0,B.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Pe.SDK_VERSION,checkout_type:ze,checkout_layout:ye,billing_api_url:T})},[ye,ze,T]);let Vt=(0,B.useMemo)(()=>n?Pn(n,!0):"",[n]),it=(0,B.useMemo)(()=>hn===Vt?Fn:void 0,[Fn,hn,Vt]),Ft=(0,B.useMemo)(()=>n?xo(n,it):void 0,[n,it]),Kt=Ee??Ft?.checkoutMode??"full",ht=(0,B.useMemo)(()=>Ft?{...Ft,checkoutMode:Kt}:void 0,[Ft,Kt]);(0,B.useEffect)(()=>{on(void 0),Zt(Vt)},[Vt]),(0,B.useEffect)(()=>{Ke(Be)},[Be]);let Jt=(0,B.useCallback)((P,Y,K)=>{st(()=>{$n.current?.(wt(P,Y,K))})},[st]),Ht=(0,B.useCallback)(async(P,Y)=>{Ke(null),Pt(null),Je("processing");let K=Y?.sessionId??P.id,fe=ct.current??V.current,X=Mt(fe),de=fe?null:uo(T,o,bt),S={log:O=>{X?X.log(O):de?.log(O)},error:O=>{X?X.error(O):de?.error(O)},terminal:O=>{X?X.terminal(O):de?.terminal(O)},performance:O=>{X?X.performance(O):de?.performance(O)},now:()=>X?.now()??de?.now()??0,elapsed:O=>X?.elapsed(O)??Math.max(0,(de?.now()??O)-O)},u=S.now(),c=!!(Y?.initialAutoProcessingError||Y?.initialAutoProcessingPending),L=!1,f,ee=()=>{L||(L=!0,c=!0,f=S.now(),S.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ie=!1,rt=()=>{Ie||(Ie=!0,S.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),S.performance({stage:"processing",durationMs:S.elapsed(u),durationMode:"machine",paymentMethodCategory:"saved"}),f!==void 0&&S.performance({stage:"recovery",durationMs:S.elapsed(f),durationMode:"machine",paymentMethodCategory:"saved"}))};S.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),S.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),c&&ee();let Se;try{let O=ni(Y?.initialAutoProcessingError),y;if(O)ee(),O.type==="paypal_redirect_required"&&ut.current?.publishableKey&&ii({sessionId:K,publishableKey:ut.current.publishableKey,paypalPublishableKey:ut.current.paypalPublishableKey}),y=await io(O,{flopay:ct.current,paypalFlopay:V.current,attempt3DS:Y?.attempt3DS,billingApiUrl:T,sessionId:K,session:P,telemetry:!1}),O.type==="paypal_redirect_required"&&qo();else if(Y?.initialAutoProcessingPending){let q=await new Xn.PaymentAPI(T,{telemetry:!1}).waitForCheckoutSessionCompletion(Y.initialAutoProcessingPending.sessionId,{initialDelayMs:Y.initialAutoProcessingPending.retryAfterMs});if(q.data.session?.status!=="complete")throw new Pe.FloPayError("Automatic payment failed. Please try again.","api_error",{code:q.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});y={status:"succeeded"}}else{if(Y?.initialAutoProcessingError)throw Un(Y.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Y.initialAutoProcessingError.checkoutMethod});if(Y?.fromCreateSession)return Y?.fallbackToFull&&(Qe("full"),li("full")),!1;{let $=await dr({billingApiUrl:T,sessionId:K,session:P,telemetry:!1});$.type==="success"?y=$.result:(ee(),$.type==="paypal_redirect_required"&&ut.current?.publishableKey&&ii({sessionId:K,publishableKey:ut.current.publishableKey,paypalPublishableKey:ut.current.paypalPublishableKey}),y=await io($,{flopay:ct.current,paypalFlopay:V.current,attempt3DS:Y?.attempt3DS,billingApiUrl:T,sessionId:K,session:P,telemetry:!1}),$.type==="paypal_redirect_required"&&qo())}}K&&sr(K),rt(),c&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),S.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Je("success"),await Mr(_n),Se=()=>Te.current?.(y)}catch(O){let y=Jn(O),$=y.checkoutMethod??Tr;Ke(y.message),Pt(y.message),Y?.fallbackToFull&&(S.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Qe("full"),li("full")),rt();let q=y.statusCode!==void 0?(0,Pe.telemetryStatusClass)(y.statusCode,"unknown"):void 0,Ve=q==="4xx"?{requestCategory:"process_payment",statusClass:q}:{},pt=q===void 0||q==="4xx";if(pt&&(y.telemetryOutcome==="payment_declined"||!!(y.declineCode||y.code?.toLowerCase().includes("declin"))))S.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ve});else if(pt&&(y.telemetryOutcome==="validation_rejected"||y.type==="validation_error"))S.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ve});else{let Ar=(0,Pe.classifyTelemetryFailure)(O,c?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");S.error({...Ar,...y.telemetryFailureCategory?{failureCategory:y.telemetryFailureCategory}:{},stage:c?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:y.telemetryRequestCategory??"process_payment"})}return st(()=>qe.current?.(y)),Jt($,y,{code:y.code,declineCode:y.declineCode}),Je("error"),await Promise.allSettled([Mr(Cn),Y?.ensureProvidersReady?Y.ensureProvidersReady():Promise.resolve()]),c&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{rt(),de&&Br(de),Je(null),Pt(null)}return st(Se),!0},[Jt,st,Jn,T,o,bt]);(0,B.useEffect)(()=>{if(typeof window>"u"||D.current)return;let P=new URLSearchParams(window.location.search),Y=P.get("payment_intent_client_secret");if(!Y)return;let K=ks();K&&(D.current=!0,(async()=>{let fe,X=0;Ke(null),Pt(null),Je("processing"),Ze(!0);try{if(P.get("redirect_status")==="failed")throw Object.assign(new Pe.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:de,paypalFlopay:S}=await lo({publishableKey:K.publishableKey,paypalPublishableKey:K.paypalPublishableKey,billingApiUrl:T,locale:m,telemetry:o});fe=Mt(S??de),X=fe?.now()??0,fe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let u=(S??de)?.getRawProvider();if(!u)throw Object.assign(new Pe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:c,error:L}=await u.retrievePaymentIntent(Y);if(L)throw Object.assign(new Pe.FloPayError(L.message??"Failed to retrieve PayPal payment status.","api_error",{code:L.code}),{checkoutMethod:"paypal"});let f=Fa(c?.status);if(!c||f==="failed")throw Object.assign(new Pe.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let ee=typeof c.payment_method=="string"?c.payment_method:c.payment_method?.id,Ie=f;if(K.sessionId){let O=(await new Xn.PaymentAPI(T,{telemetry:!1}).getUnifiedCheckoutSession(K.sessionId)).data.session;if(O&&O.status!=="complete"){let y=await dr({billingApiUrl:T,sessionId:K.sessionId,session:O,telemetry:!1,tokenizedData:{id:ee??c.id,type:"card",threeDSecureActionResultTokenId:c.id,isPaypal:!0}});if(y.type!=="success")throw Object.assign(new Pe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Ie=y.result.status}}K.sessionId&&sr(K.sessionId),fe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.performance({stage:"redirect_resume",durationMs:fe.elapsed(X),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Je("success"),await Mr(_n),st(()=>Te.current?.({status:Ie,paymentIntentId:c.id,paymentMethodId:ee,checkoutMethod:"paypal"}))}catch(de){let S=Jn(de),u=S.checkoutMethod??"paypal",c=!!(S.declineCode||S.code?.toLowerCase().includes("declin"));if(fe)fe.performance({stage:"redirect_resume",durationMs:fe.elapsed(X),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),c?fe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):fe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(c){let L=uo(T,o,bt);L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Br(L)}else Uo(T,o,bt,"REDIRECT_RESUME_FAILED","redirect_resume");Ke(S.message),Pt(S.message),st(()=>qe.current?.(S)),Jt(u,S,{code:S.code,declineCode:S.declineCode}),Je("error"),await Mr(Cn)}finally{qo(),xs(),Je(null),Pt(null),Ze(!1)}})())},[Jt,st,m,Jn,T,o]);let an=(0,B.useRef)(null);function Pn(P,Y=!1){let K=P?.account?.email?.trim().toLowerCase()??"",fe={c:P?.clientId,cur:P?.currency??"",a:{e:K,u:K?"":P?.account?.userId??"",country:P?.account?.country??""},successUrl:P?.successUrl,cancelUrl:P?.cancelUrl,p:P?.products?.map(S=>jo(`${S.type??""}:${S.code??S.providerItemId??S.providerPlanId??""}`,S)).sort(),i:P?.items?.map(S=>jo(S.code??S.providerItemId??"",S)).sort(),s:P?.subscriptions?.map(S=>jo(S.code??S.providerPlanId??"",S)).sort(),couponCodes:P?.couponCodes?[...P.couponCodes].sort():void 0,...Y?{tagsData:P?.tagsData,utmMetadata:P?.utmMetadata,tokenizedData:P?.tokenizedData,checkoutMode:P?.checkoutMode??"full"}:{}},X=JSON.stringify(fe),de=0;for(let S=0;S<X.length;S++)de=(de<<5)-de+X.charCodeAt(S)|0;return`flopay_session_${Math.abs(de).toString(36)}`}let It=(0,B.useMemo)(()=>ht?Pn(ht):"",[ht]),Ot=(0,B.useRef)(ht);Ot.current=ht,(0,B.useEffect)(()=>{at(e??"")},[e]),(0,B.useEffect)(()=>{en.current=!1,Ke(Be),Pt(null),Je(null)},[It,Be,e]);async function Le(P,Y){let K=uo(T,o,bt),fe=new Xn.PaymentAPI(T,{telemetry:!1}),X=!1;try{let de=P.idempotencyKey!==void 0?(0,Pe.resolveIdempotencyKey)(P.idempotencyKey):void 0,S=de??Is(Y),u,c=!1,L=Rs(Y);K.log({name:L?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let f=L?.sid??null,ee=null,Ie;if(f)try{if(ee=await fe.getUnifiedCheckoutSession(f,L?.nonce),ee.data.session?.status==="complete"){if(Mo(f))return{sid:f,result:ee};_s(Y),f=null,ee=null,c=!0}}catch{K.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ko(Y),f=null}if(!f){!de&&(c||!S)&&(S=(0,Pe.resolveIdempotencyKey)(),u=S),S&&Es(Y,S);let rt=K.now(),Se=0;K.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let O={...P,idempotencyKey:S,avsCheck:!!Me,avsConfig:typeof Me=="object"?Me:void 0,checkoutType:"embedded_checkout",checkoutLayout:se?"custom_layout":z==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(O,Xn.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:q=>{Se=Math.max(Se,q)}}});let y=()=>{K.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),K.performance({stage:"session_create",durationMs:K.now()-rt,durationMode:"machine",requestCategory:"session_create",attempt:Se,statusClass:"2xx"})},$=q=>{let Ve=(0,Pe.classifyTelemetryFailure)(q,"CHECKOUT_SESSION_CREATE_FAILED","unknown");K.performance({stage:"session_create",durationMs:K.now()-rt,durationMode:"machine",requestCategory:"session_create",attempt:Se,statusClass:Ve.statusClass}),q instanceof Pe.FloPayError&&q.type==="validation_error"?K.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):Ve.statusClass==="4xx"?K.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):K.error({...Ve,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if((0,Pe.isDetachedSessionEligible)(O)){let q=await fe.createDetachedSession(O);q.claimed.catch(()=>{}),ee=q.shell,f=q.sessionId,Ie=q.claimed.then(Ve=>{let pt=Ve.data.session?.id??q.sessionId;return pt&&si(Y,pt,Ve.data.session?.clientSecret??q.nonce),y(),Ve},Ve=>{throw Ko(Y),$(Ve),Ve}).finally(()=>Br(K)),Ie.catch(()=>{}),X=!0,K.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),K.performance({stage:"session_shell",durationMs:K.now()-rt,durationMode:"machine",requestCategory:"session_create",attempt:Se,statusClass:"2xx",paymentMethodCategory:"card"})}else ee=await fe.createAndFetchSession(O),y()}catch(q){throw $(q),q}f=ee.data.session?.id??f??"",f&&!Ie&&si(Y,f,ee.data.session?.clientSecret)}return{sid:f??"",result:ee,sdkGeneratedIdempotencyKey:u,...Ie?{claimed:Ie}:{}}}finally{X||Br(K)}}let vt=(0,B.useCallback)(async(P,Y)=>{let K=Ot.current;if(!K)throw new Pe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let fe=xo(K,P),X=Pn(fe),de=po.get(X);if(!de){let c={promise:Le(fe,X),consumers:0,settled:!1};de=c,po.set(X,c);let L=()=>{c.settled=!0,ai(X,c)};c.promise.then(L,L)}de.consumers+=1;let S=!1,u=()=>{S||(S=!0,de.consumers-=1,ai(X,de))};Y?.(u);try{let c=await de.promise;an.current=X,P&&(Zt(Vt),on(y=>Ba(y,P)));let{sid:L,result:f,claimed:ee}=c;if(re(f),f.data.session&&tt(f.data.session),L&&at(L),ee){let y=Gt.current+=1;qt(!0),ee.then($=>{Gt.current===y&&(re($),$.data.session&&tt($.data.session),qt(!1))},$=>{Gt.current===y&&(qt(!1),dt($ instanceof Pe.FloPayError?$:new Pe.FloPayError($ instanceof Error?$.message:"Failed to create session","api_error")))})}else Gt.current+=1,qt(!1);let{publishableKey:Ie,paypalPublishableKey:rt}=so(f),{flopay:Se,paypalFlopay:O}=await lo({publishableKey:Ie,paypalPublishableKey:rt,billingApiUrl:T,locale:m,telemetry:o});return ct.current=Se,$e(Se),V.current=O,ot(O),h(!1),c}catch(c){throw an.current===X&&(an.current=null),c}finally{Y||u()}},[m,T,o,bt]),Ct=(0,B.useRef)(Ht);Ct.current=Ht;let bn=(0,B.useRef)(vt);bn.current=vt;let jn=(0,B.useCallback)(async P=>{if(!Ts(P)||Dn)return{sessionId:Ae,session:G};Nt(!0);try{let Y=await vt(P);return{sessionId:Y.sid,session:Y.result.data.session??null}}finally{Nt(!1)}},[vt,Dn,Ae,G]);(0,B.useEffect)(()=>{let P=!1,Y;if(dt(null),It){let X=Ot.current;return Qe(Kt),h(!1),an.current===It?()=>{P=!0}:(tt(Aa(X,Ee)),(async()=>{let de=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),S=Kt==="auto"&&!en.current&&!de;S&&(Ke(null),Pt(null),Je("processing"));try{let u=await bn.current(void 0,ee=>{Y=ee}),c=u.result.data.session??null;ut.current=so(u.result);let L=$o(u.result),f=Mo(u.sid||c?.id);if(!P&&S&&c&&!L&&!f){en.current=!0,await Ss(It,u.sdkGeneratedIdempotencyKey,()=>Ct.current(c,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:u.result.autoProcessingError,initialAutoProcessingPending:u.result.autoProcessingPending,autoProcessingAttempted:u.result.autoProcessingAttempted,sessionId:u.sid||c.id}));return}!P&&S&&((L||f)&&(en.current=!0),Je(null),Pt(null))}catch(u){if(P)return;let c=u instanceof Pe.FloPayError||typeof u=="object"&&u!==null&&"code"in u?u.code:void 0;if(S&&c==="session_auto_completed"){en.current=!0,Je("success"),await Mr(_n),P||(st(()=>{Te.current?.({status:"succeeded"})}),Je(null),Pt(null));return}S&&(Je(null),Pt(null));let L=u instanceof Pe.FloPayError?u:new Pe.FloPayError(u instanceof Error?u.message:"Failed to create session","api_error");dt(L)}finally{Y?.(),Y=void 0}})(),()=>{P=!0,Y?.()})}h(!0);async function K(){let X=!1;try{let S=await new Xn.PaymentAPI(T,{telemetry:!1}).getUnifiedCheckoutSession(Ge,t);if(P)return;re(S);let u=S.data.session??null;if(tt(u),!u)throw new Pe.FloPayError("No session data returned","api_error");if(u.status==="complete"){h(!1),st(()=>{Ln.current?.(u.successUrl??"")});return}if(u.status==="expired")throw new Pe.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});X=!0;let c=Ee??u.checkoutMode??"full";Qe(c);let L=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),f=$o(S);if(c==="auto"&&!en.current&&!L&&!f){en.current=!0;let ee=fe(S);try{if(await Ct.current(u,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ee,sessionId:Ge||u.id}),P)return;await ee,P||h(!1);return}catch{if(P)return;await ee,P||h(!1);return}}await fe(S),P||h(!1)}catch(de){if(P)return;de instanceof Pe.FloPayError?!X&&!ws(de)&&Uo(T,o,bt,"NETWORK_REQUEST_FAILED","session_read"):Uo(T,o,bt,"INTERNAL_SDK_ERROR","checkout_mount");let S=de instanceof Pe.FloPayError?de:new Pe.FloPayError(de instanceof Error?de.message:"Failed to initialize checkout","api_error");dt(S),h(!1)}}async function fe(X){let{publishableKey:de,paypalPublishableKey:S}=so(X);ut.current={publishableKey:de,paypalPublishableKey:S};let{flopay:u,paypalFlopay:c}=await lo({publishableKey:de,paypalPublishableKey:S,billingApiUrl:T,locale:m,telemetry:o});ct.current=u,$e(u),V.current=c,ot(c)}return K(),()=>{P=!0}},[Ee,It,Kt,We,st,t]);let Wt=(0,B.useCallback)(async()=>{if(!(Ye||!G)){Ze(!0),Ke(null);try{await Ht(G,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ge||G.id})}finally{Ze(!1)}}},[Ge,Ye,Ht,G]),Xt=Vo(E),Dt=$o(E),kn=(0,B.useMemo)(()=>{if(!E||!G||!E.data.stripe?.publishableKey)return;let P={appearance:Oe,paymentMethodCreation:"manual",billingApiUrl:T};if(E.data.stripe?.clientSecret)P.clientSecret=E.data.stripe.clientSecret;else{let Y=(0,Pe.buildCheckoutDisplayData)(G).total;P.amount=Math.round(Y*100)||G.amount,P.currency=G.currency?.toLowerCase()}return P},[E,G,Oe,T]),Nn=!!(n&&!se&&z==="buttons"&&me&&Kt==="full"),sn=(0,B.useMemo)(()=>({session:G,loading:rn,error:ke,checkoutMode:nt,inlineSessionDraft:ht,applyInlineSessionPatch:Nn?jn:void 0,inlineSessionPatchProcessing:Dn,claimPending:Rt}),[G,rn,ke,nt,ht,Nn,jn,Dn,Rt]),Qt=!!n&&z==="buttons"&&!Dt&&(!oe||!kn),Et=kt?(0,w.jsx)(Sn,{status:kt,errorMessage:An}):null;if(rn){if(d)return(0,w.jsxs)(w.Fragment,{children:[d,Et]});if(z==="buttons"){let P=ce?.buttonsLayout?.cardButton?.borderRadius??ce?.appearance.variables?.borderRadius??8,Y=K=>(0,w.jsx)("div",{style:{height:K,borderRadius:P,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[p&&Y(ur),v&&(M||g)&&Y(ur),v&&Y(ur),(0,w.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Et]})}return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,w.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,w.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Et]})}return ke?I?(0,w.jsx)(dn.Provider,{value:sn,children:I(ke)}):(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:ke.message})}):Qt?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)(Bs,{onButtonClick:J,showPayPal:p,showStripe:v,showApplePay:M,showGooglePay:g,theme:ue,buttonsTheme:ae,buttonsStyles:U,cardButtonContent:te,cardBackButtonContent:Q,cardTitleContent:pe})}),Et]}):Dt&&G&&Xt?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsxs)("div",{className:Ce,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[xe&&(0,w.jsx)(ar,{icon:!1,children:xe}),Bt==="retrying"&&(0,w.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Bt==="exhausted"&&(0,w.jsxs)("div",{role:"alert",children:[(0,w.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,w.jsx)("button",{type:"button",onClick:Zn,children:"Retry PayPal"})]}),Bt!=="exhausted"&&(0,w.jsx)("div",{"aria-hidden":Bt==="retrying"?!0:void 0,style:Bt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,w.jsx)($a,{sessionId:Ge,nonce:G.clientSecret||void 0,billingApiUrl:T,email:G.customer?.email,clientId:Xt.clientId,environment:Xt.environment,currency:(G.currency??"usd").toUpperCase(),isSubscription:G.mode==="subscription",onComplete:N,onErrorChange:Ke,onDecline:_,onButtonClick:J,onInitializationStateChange:qn,allowAutomaticRetry:At===0,session:G,telemetry:o,telemetryContext:bt,debug:he},`paypal-init-${At}`)})]})}),Et]}):!oe||!kn?(0,w.jsx)(w.Fragment,{children:Et}):nt==="confirm"?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)(wr,{flopay:oe,paypalFlopay:He,options:kn,children:(0,w.jsxs)("div",{className:Ce,children:[xe&&(0,w.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:xe}),Re?Re({onConfirm:Wt,isProcessing:Ye}):(0,w.jsx)("button",{type:"button",onClick:Wt,disabled:Ye,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Ye?"not-allowed":"pointer",opacity:Ye?.6:1},children:Ye?"Processing...":_e??"Confirm Purchase"})]})})}),Et]}):(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)(wr,{flopay:oe,paypalFlopay:He,options:kn,children:se?(0,w.jsxs)(w.Fragment,{children:[xe&&(0,w.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:xe}),(0,w.jsx)(Ms,{sessionId:Ge,nonce:G?.clientSecret||void 0,billingApiUrl:T,session:G,children:se})]}):(0,w.jsx)(oo,{sessionId:Ge,nonce:G?.clientSecret||void 0,email:G?.customer?.email,userId:G?.customer?.id,firstName:G?.customer?.firstName,lastName:G?.customer?.lastName,totalAmount:G?Math.round((0,Pe.buildCheckoutDisplayData)(G).total*100):0,currency:G?.currency?.toLowerCase()??"usd",onComplete:N,onError:b,onDecline:_,error:xe,onErrorChange:Ke,showPayPal:p,showStripe:v,enabledPaymentMethods:x??E?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:E?.data.stripe?.enabledPaymentMethodCountries,showApplePay:M,showGooglePay:g,layout:z,theme:ue,buttonsTheme:ae,buttonsStyles:U,appearance:Oe,cardButtonContent:te,cardBackButtonContent:Q,cardTitleContent:pe,onButtonClick:J,onBeforeButtonClick:me,enableAVS:Me,...we?{cardFieldOrder:we}:{},...be?{cardPreFormSlot:be}:{},avsLayout:ie,country:G?.customer?.country,city:G?.customer?.city,state:G?.customer?.state,onCountryChange:k,onZipChange:F,avsCheck:!!Me,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:se?"custom_layout":z==="buttons"?"buttons_layout":"default_layout",className:Ce,directPaypal:Vo(E),isSubscription:G?.mode==="subscription",session:G,dataAttachmentPending:Rt,debug:he})})}),Et]})}function Ms({sessionId:e,nonce:t,billingApiUrl:n,session:l,children:o}){return(0,w.jsx)(w.Fragment,{children:B.default.Children.map(o,s=>{if(!B.default.isValidElement(s))return s;let m=s.props,d={};return m.sessionId||(d.sessionId=e),!m.nonce&&t&&(d.nonce=t),m.billingApiUrl||(d.billingApiUrl=n),l?.customer&&(m.email||(d.email=l.customer.email),m.userId||(d.userId=l.customer.id),m.firstName||(d.firstName=l.customer.firstName),m.lastName||(d.lastName=l.customer.lastName)),Object.keys(d).length===0?s:B.default.cloneElement(s,d)})})}function Bs({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:l,showGooglePay:o,theme:s,buttonsTheme:m,buttonsStyles:d,cardButtonContent:I,cardBackButtonContent:N,cardTitleContent:b}){let[_,k]=(0,B.useState)(!1),F=(0,B.useMemo)(()=>(0,Pe.resolveTheme)(s),[s]),p=(0,B.useMemo)(()=>{let g=F?.buttonsLayout??(0,Pe.resolveButtonsLayoutTheme)(m);return d?{...g,...d,cardButton:{...g.cardButton,...d.cardButton},cardFormContainer:{...g.cardFormContainer,...d.cardFormContainer},backButton:{...g.backButton,...d.backButton},backButtonIcon:{...g.backButtonIcon,...d.backButtonIcon},submitButton:{...g.submitButton,...d.submitButton},title:{...g.title,...d.title}}:g},[F,m,d]),v=F?.buttonsLayout?.cardButton?.borderRadius??F?.appearance.variables?.borderRadius??8,x=g=>(0,w.jsx)("div",{style:{height:g,borderRadius:v,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),M=I===void 0?{boxSizing:"border-box",height:ur,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let g=p.cardInputBorder??"#e5e7eb",he=p.cardInputBackground??"white",z=nr(N),ue=nr(b);return(0,w.jsxs)("div",{style:{backgroundColor:p.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...p.cardFormContainer},children:[(0,w.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,w.jsxs)("button",{type:"button",onClick:()=>k(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:z?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...p.backButton},children:[(0,w.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...p.backButtonIcon},children:(0,w.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,w.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,w.jsx)(or,{content:N})]}),ue?(0,w.jsx)("div",{style:{flex:1}}):(0,w.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...p.title},children:(0,w.jsx)(kr,{content:b})})]}),(0,w.jsx)("div",{style:{backgroundColor:he,border:`1px solid ${g}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsxs)("div",{style:{display:"flex"},children:[(0,w.jsx)("div",{style:{flex:1,backgroundColor:he,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsx)("div",{style:{flex:1,backgroundColor:he,borderTop:"none",borderRight:`1px solid ${g}`,borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,w.jsx)("div",{style:{backgroundColor:he,border:`1px solid ${g}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...p.submitButton,opacity:.5}}),(0,w.jsx)("style",{children:`
|
|
38
|
+
`}),wr&&Vn&&(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ye?-2:0},children:[(0,s.jsxs)("button",{type:"button",onClick:zn,style:{display:"inline-flex",alignItems:"center",gap:Mo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[(0,s.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:(0,s.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,s.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,s.jsx)(ir,{content:G})]}),va?(0,s.jsx)("div",{style:{flex:1}}):(0,s.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...f.title},children:(0,s.jsx)(_r,{content:pe})})]}),!wr&&!va&&(0,s.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ao,order:Ye?-3:0,...f.title},children:(0,s.jsx)(_r,{content:pe})}),re&&(0,s.jsx)("div",{style:{order:Ye?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Je,v=(V=!1)=>({backgroundColor:Rr,border:`1px solid ${Kn(V)}`,borderRadius:ht,marginTop:"0.5rem",padding:"10px"}),W=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ka}),ne=(0,C.getStateOptions)(i);return(0,s.jsxs)(s.Fragment,{children:[(0,C.isAVSFieldVisible)(re.address_line_1,i)&&(0,s.jsx)("div",{style:v(gt.line1),children:(0,s.jsx)("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:He,onChange:V=>{Ct.current.addressLine1=!0,Xt.current=V.target.value,nt(V.target.value)},disabled:ee,required:!0,"data-testid":"flopay-address-line1",style:W()})}),(0,C.isAVSFieldVisible)(re.address_line_2,i)&&(0,s.jsx)("div",{style:v(),children:(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Ze,onChange:V=>{Ct.current.addressLine2=!0,Qt.current=V.target.value,wn(V.target.value)},disabled:ee,"data-testid":"flopay-address-line2",style:W()})}),((0,C.isAVSFieldVisible)(re.city,i)||(0,C.isAVSFieldVisible)(re.state,i))&&(0,s.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,C.isAVSFieldVisible)(re.city,i)&&(0,s.jsx)("div",{style:{flex:1,backgroundColor:Rr,borderTop:`1px solid ${Kn(gt.city)}`,borderRight:`1px solid ${Kn(gt.city)}`,borderBottom:`1px solid ${Kn(gt.city)}`,borderLeft:`1px solid ${Kn(gt.city)}`,padding:"10px",borderTopLeftRadius:ht,borderBottomLeftRadius:ht,...(0,C.isAVSFieldVisible)(re.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:ht}},children:(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:ot,onChange:V=>{Ct.current.city=!0,Mt.current=V.target.value,$n(V.target.value)},disabled:ee,required:!0,"data-testid":"flopay-city",style:W()})}),(0,C.isAVSFieldVisible)(re.state,i)&&(0,s.jsx)("div",{style:{flex:1,backgroundColor:Rr,border:`1px solid ${Kn(gt.state)}`,padding:"10px",borderTopRightRadius:ht,borderBottomRightRadius:ht,...(0,C.isAVSFieldVisible)(re.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:ht}},children:ne?(0,s.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Vt,onChange:V=>{Ct.current.state=!0,At.current=V.target.value,fn(V.target.value)},disabled:ee,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...W(),cursor:"pointer"},children:[(0,s.jsx)("option",{value:"",children:(0,C.getStateLabel)(i)}),ne.map(V=>(0,s.jsx)("option",{value:V.code,children:V.name},V.code))]}):(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,C.getStateLabel)(i),autoComplete:"billing address-level1",value:Vt,onChange:V=>{Ct.current.state=!0,At.current=V.target.value,fn(V.target.value)},disabled:ee,required:!0,"data-testid":"flopay-state",style:W()})})]}),((0,C.isAVSFieldVisible)(re.country,i)||(0,C.isAVSFieldVisible)(re.postal_code,i))&&(0,s.jsxs)("div",{style:{display:"flex",flexDirection:ie==="column"?"column":"row",gap:ie==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,C.isAVSFieldVisible)(re.country,i)&&(0,s.jsx)("div",{style:{flex:ie==="row"?1:void 0,backgroundColor:Rr,borderTop:`1px solid ${kr}`,borderRight:`1px solid ${kr}`,borderBottom:`1px solid ${kr}`,borderLeft:`1px solid ${kr}`,padding:"10px",...ie==="row"&&(0,C.isAVSFieldVisible)(re.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:ht,borderBottomLeftRadius:ht,borderRight:"none"}:{borderRadius:ht}},children:(0,s.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Je,onChange:V=>{Ct.current.country=!0,St.current=V.target.value,xe(V.target.value),Ve?.(V.target.value),At.current="",fn("")},disabled:ee,autoComplete:"billing country","data-testid":"flopay-country",style:{...W(),cursor:"pointer"},children:C.COUNTRY_OPTIONS.map(V=>(0,s.jsxs)("option",{value:V.code,children:[V.flag," ",V.name]},V.code))})}),(0,C.isAVSFieldVisible)(re.postal_code,i)&&(0,s.jsx)("div",{style:{flex:ie==="row"?1:void 0,backgroundColor:Rr,border:`1px solid ${zi}`,padding:"10px",...ie==="row"&&(0,C.isAVSFieldVisible)(re.country,i)?{borderRadius:"0",borderTopRightRadius:ht,borderBottomRightRadius:ht}:{borderRadius:ht}},children:(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,C.getPostalCodeLabel)(Je),autoComplete:"billing postal-code",value:vt,onChange:V=>{Ct.current.zip=!0,Tt.current=V.target.value,We(V.target.value),Ne?.(V.target.value)},onBlur:()=>Kt(!0),disabled:ee,required:Ft.required,"aria-invalid":Kr||void 0,"aria-describedby":Kr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:W()})})]}),Kr&&(0,s.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:xo,...ka,fontSize:"0.75rem"},children:Ft.empty?`${(0,C.getPostalCodeLabel)(i)} is required`:hs(i)})]})})()}),Ye&&Le&&(0,s.jsx)("div",{style:{order:-2,width:"100%"},children:Le}),Ye&&qi,g&&(0,s.jsx)(sr,{margin:"0.75rem 0",styleOverride:f.errorBanner,children:g})]}),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"},Ia=i=>tt?!E||!bn?(0,s.jsx)("pre",{"data-testid":i,style:Hr,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,s.jsx)("pre",{"data-testid":i,style:Hr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${E}`,` directPaypalConfigured=${bn}`,` inAppBrowserDetected=${String(jr)}`,` shouldRenderDirectPayPal=${br}`,` shouldRenderStripePayPal=${vr}`,` hasPaypalStripeInstance=${!!Ie}`].join(`
|
|
39
|
+
`)}):null,Ea=i=>tt?!x||!he?(0,s.jsx)("pre",{"data-testid":i,style:Hr,children:"FloPay/Stripe-debug - not enabled"}):(0,s.jsx)("pre",{"data-testid":i,style:Hr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${x}`,` currency=${_e}`,` amountInCents=${Ae}`,` enabledPaymentMethods: ${JSON.stringify(h??[])}`,` enabledPaymentMethodsProvided=${hr}`,` hasEnabledMethods=${Nr}`,` expressMethods: ${JSON.stringify(Ur)}`,` walletExpressMethods: ${JSON.stringify($r)}`,` paymentElementMethods: ${JSON.stringify(Pr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(qr)}`,` hasStripeInstance=${!!he}`,` shouldRenderWallets=${Cr}`,` shouldRenderPaymentElement=${Sr}`].join(`
|
|
40
|
+
`)}):null,_a=Me==="apm-expanding"||Me==="apm-form"||Me==="apm-collapsing",Wr=Me==="apm-expanding"?`flopay-card-enter ${Ut}ms cubic-bezier(0, 0, 0.2, 1) both`:Me==="apm-collapsing"?`flopay-card-exit ${Ut}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Yr=yt?{...ko,paymentMethodTypes:[yt]}:null;if(oe==="buttons"){let i=Me==="buttons"||Me==="expanding"||Me==="apm-expanding",v=Me==="expanding"||Me==="card"||Me==="collapsing",W=Y===void 0?{boxSizing:"border-box",height:lo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ne=Me==="expanding"||Me==="apm-expanding"?`flopay-buttons-exit ${Ut}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Me==="collapsing"||Me==="apm-collapsing"?`flopay-buttons-enter ${Ut}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,V=Me==="expanding"?`flopay-card-enter ${Ut}ms cubic-bezier(0, 0, 0.2, 1) both`:Me==="collapsing"?`flopay-card-exit ${Ut}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,s.jsxs)("form",{onSubmit:Eo,className:R,style:{position:"relative"},children:[(0,s.jsx)($o,{}),tn&&(0,s.jsx)(Cn,{status:tn,errorMessage:g,authorized:N}),(0,s.jsxs)("div",{style:{display:"grid"},children:[(0,s.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!ne?ys:{},...ne?{animation:ne,pointerEvents:"none"}:{}},children:[Ia("flopay-direct-paypal-gate-debug"),Ea("flopay-stripe-gate-debug"),br&&Qe&&(0,s.jsxs)(s.Fragment,{children:[Ce&&(0,s.jsx)("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."}),(0,s.jsx)(Ar,{sessionId:e,nonce:t,billingApiUrl:r,email:m.email,clientId:Qe.clientId,environment:Qe.environment,currency:_e.toUpperCase(),isSubscription:pt,onTokenizedBody:nn,onComplete:l,onErrorChange:me,onDecline:d,onTechnicalFailure:nr,onButtonClick:we,runBeforeButtonClick:sn,isProcessing:ee,onLoadStateChange:Ro,onInitializationStateChange:Io,session:D??null,existingOrderId:Ce?.orderId,debug:tt},Ce?.orderId??"fresh")]}),vr&&(0,s.jsx)(ft.Elements,{stripe:Ie,options:ta,children:(0,s.jsx)(ei,{sessionId:e,nonce:t,email:m.email,billingApiUrl:r,onTokenizedBody:nn,onErrorChange:me,isProcessing:ee,onButtonClick:we,onDecline:d,onTechnicalFailure:nr,runBeforeButtonClick:sn,onLoadStateChange:aa,placeholderBorderRadius:Hn})}),Cr?(0,s.jsx)(ft.Elements,{stripe:he,options:Or,children:(0,s.jsx)(ti,{sessionId:e,nonce:t,email:m.email,billingApiUrl:r,intentKind:Q>0?"payment":"setup",expressMethods:$r,onTokenizedBody:nn,onErrorChange:me,onButtonClick:we,onDecline:d,onTechnicalFailure:nr,runBeforeButtonClick:sn,onLoadStateChange:sa,placeholderBorderRadius:Hn})}):pa?(0,s.jsx)("div",{style:{height:lo,borderRadius:Hn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Sr&&(0,s.jsx)(ni,{sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,paymentElementMethods:qr,stripeInstance:he,paymentElementBaseOptions:ko,onTokenizedBody:nn,onErrorChange:me,onButtonClick:we,onDecline:d,runBeforeButtonClick:sn,onLoadStateChange:ca,isProcessing:ee,submitButtonColor:Wn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,onExpandApm:en,expandedApmMethod:yt,themeId:j,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Hn}}),Ye&&(0,s.jsx)("button",{type:"button",onClick:async()=>{ee||!(await sn("card")).proceed||(we?.("card"),Ln())},disabled:ee,style:{width:"100%",...W,...f.cardButton,...Vo({themeBundle:L,resolvedPrimaryColor:Wn,resolvedBorderRadius:ht,submitButtonStyle:f.submitButton,explicitPrimaryColor:qt?.colorPrimary}),fontSize:f.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ee?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ee?.6:1},onMouseEnter:fe=>{!ee&&(L||qt?.colorPrimary)&&(fe.currentTarget.style.backgroundColor=Ui)},onMouseLeave:fe=>{(L||qt?.colorPrimary)&&(fe.currentTarget.style.backgroundColor=Wn)},onMouseDown:fe=>{fe.currentTarget.style.transform="scale(0.985)"},onMouseUp:fe=>{fe.currentTarget.style.transform="scale(1)"},children:(0,s.jsx)(ar,{content:Y})}),g&&Me==="buttons"&&(0,s.jsx)(sr,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:g})]}),Ye&&v&&(0,s.jsx)("div",{style:{gridArea:"1 / 1",...V?{animation:V}:{},...Me==="collapsing"?{pointerEvents:"none"}:{}},children:Ra}),x&&_a&&yt&&Yr&&he&&(0,s.jsx)("div",{style:{gridArea:"1 / 1",...Wr?{animation:Wr}:{},...Me==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,s.jsxs)("div",{style:{backgroundColor:To,borderRadius:Fo,...Ir,padding:Bo},children:[(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,s.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Ht,style:{display:"inline-flex",alignItems:"center",gap:Mo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[(0,s.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:(0,s.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,s.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,s.jsx)(ir,{content:G})]}),(0,s.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Ao,paddingRight:80,...f.title},children:`Pay with ${(0,C.getStripeMethodDisplayName)(yt)}`})]}),(0,s.jsx)(ft.Elements,{stripe:he,options:Yr,children:(0,s.jsx)(qo,{method:yt,sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,onTokenizedBody:nn,onErrorChange:me,onDecline:d,onCancel:Ht,runBeforeButtonClick:sn,onButtonClick:we,isProcessing:ee,submitButtonColor:Wn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,errorText:g})},yt)]})})]})]})}return _a&&yt&&Yr&&he&&x?(0,s.jsxs)("form",{onSubmit:Eo,className:R,style:{position:"relative"},children:[(0,s.jsx)($o,{}),tn&&(0,s.jsx)(Cn,{status:tn,errorMessage:g,authorized:N}),(0,s.jsx)("div",{style:{...Wr?{animation:Wr}:{},...Me==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,s.jsxs)("div",{style:{backgroundColor:To,borderRadius:Fo,...Ir,padding:Bo},children:[(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,s.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Ht,style:{display:"inline-flex",alignItems:"center",gap:Mo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[(0,s.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:(0,s.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,s.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,s.jsx)(ir,{content:G})]}),(0,s.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Ao,paddingRight:80,...f.title},children:`Pay with ${(0,C.getStripeMethodDisplayName)(yt)}`})]}),(0,s.jsx)(ft.Elements,{stripe:he,options:Yr,children:(0,s.jsx)(qo,{method:yt,sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,onTokenizedBody:nn,onErrorChange:me,onDecline:d,onCancel:Ht,runBeforeButtonClick:sn,onButtonClick:we,isProcessing:ee,submitButtonColor:Wn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,errorText:g})},yt)]})})]}):(0,s.jsxs)("form",{onSubmit:Eo,className:R,style:{position:"relative"},children:[(0,s.jsx)($o,{}),tn&&(0,s.jsx)(Cn,{status:tn,errorMessage:g,authorized:N}),(0,s.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ia("flopay-direct-paypal-gate-debug-default"),Ea("flopay-stripe-gate-debug-default"),br&&Qe&&(0,s.jsxs)(s.Fragment,{children:[Ce&&(0,s.jsx)("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."}),(0,s.jsx)(Ar,{sessionId:e,nonce:t,billingApiUrl:r,email:m.email,clientId:Qe.clientId,environment:Qe.environment,currency:_e.toUpperCase(),isSubscription:pt,onTokenizedBody:nn,onComplete:l,onErrorChange:me,onDecline:d,onTechnicalFailure:nr,onButtonClick:we,runBeforeButtonClick:sn,isProcessing:ee,onLoadStateChange:Ro,onInitializationStateChange:Io,session:D??null,existingOrderId:Ce?.orderId,debug:tt},Ce?.orderId??"fresh")]}),vr&&(0,s.jsx)(ft.Elements,{stripe:Ie,options:ta,children:(0,s.jsx)(ei,{sessionId:e,nonce:t,email:m.email,billingApiUrl:r,onTokenizedBody:nn,onErrorChange:me,isProcessing:ee,onButtonClick:we,onDecline:d,onTechnicalFailure:nr,runBeforeButtonClick:sn,onLoadStateChange:aa,placeholderBorderRadius:Hn})}),Cr&&(0,s.jsx)(ft.Elements,{stripe:he,options:Or,children:(0,s.jsx)(ti,{sessionId:e,nonce:t,email:m.email,billingApiUrl:r,intentKind:Q>0?"payment":"setup",expressMethods:$r,onTokenizedBody:nn,onErrorChange:me,onButtonClick:we,onDecline:d,onTechnicalFailure:nr,runBeforeButtonClick:sn,onLoadStateChange:sa,placeholderBorderRadius:Hn})}),Sr&&(0,s.jsx)(ni,{sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,paymentElementMethods:qr,stripeInstance:he,paymentElementBaseOptions:ko,onTokenizedBody:nn,onErrorChange:me,onButtonClick:we,onDecline:d,runBeforeButtonClick:sn,onLoadStateChange:ca,isProcessing:ee,submitButtonColor:Wn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,themeId:j,onExpandApm:en,expandedApmMethod:yt,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Hn}})]}),Ye&&(Bi||Ai||Fi)&&(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,s.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,s.jsx)("span",{children:"or pay with card"}),(0,s.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ye&&Ra]})}var mr=require("@flopay/js"),Be=require("@flopay/shared");var Dr="card";async function Ss(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:l,error:p}=await e.retrieveSetupIntent(t);return{error:p,intent:l??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:c,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:c??null}}async function ws(e,t,n,c){if(c){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:p,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:p??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:l}=await e.confirmCardPayment(t,n);return{error:l,intent:a??null}}function Ho(e,t){return Object.assign(e,{checkoutMethod:t})}function An(e,t){let n=e instanceof Be.FloPayError?e:new Be.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Fr(e,t){try{return await e()}catch(n){throw An(n,t)}}function li(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function ks(e){return e.status==="succeeded"||e.status==="declined"}async function ci(e){if(typeof document>"u"||typeof window>"u")throw new Be.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Be.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,c=15e3,a=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,l=async()=>{let P=new AbortController,I=()=>P.abort();e.signal?.aborted?P.abort():e.signal?.addEventListener("abort",I);let R=window.setTimeout(()=>P.abort(),c);try{let O=await fetch(a,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:P.signal});if(!O.ok)return{status:"unknown"};let u=await O.json().catch(()=>null);return Rs(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(R),e.signal?.removeEventListener("abort",I)}},p=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.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 k=document.createElement("iframe");k.setAttribute("title","Card authentication"),k.setAttribute("allow","payment"),k.tabIndex=0,k.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(";"),k.src=e.nextActionRedirectUrl,d.appendChild(k),document.body.appendChild(d),k.focus();let U=null;try{U=new URL(e.billingApiUrl,window.location.href).origin}catch{U=null}try{let P=await new Promise((I,R)=>{let O=!1,u=0,b=0,E=0,x=!1,h=()=>{window.clearTimeout(u),window.clearInterval(b),window.clearTimeout(E),window.removeEventListener("message",oe),k.removeEventListener("load",M),e.signal?.removeEventListener("abort",ce)},ye=async()=>{if(!(O||x)){x=!0;try{let j=await l();if(O||!ks(j))return;O=!0,h(),I(j)}finally{x=!1}}},M=()=>{window.clearTimeout(E),E=window.setTimeout(()=>{ye()},250)},ce=()=>{O||(O=!0,h(),R(new Be.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},oe=j=>{if(j.source!==k.contentWindow||U&&j.origin!==U)return;let te=j.data;!te||typeof te!="object"||te.source!=="flopay-vault-3ds-return"||O||(O=!0,h(),I(null))};u=window.setTimeout(()=>{O||(O=!0,h(),R(new Be.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),b=window.setInterval(()=>{ye()},n),k.addEventListener("load",M),window.addEventListener("message",oe),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return P||await l()}finally{d.parentNode?.removeChild(d),p?.isConnected&&p.focus()}}function Rs(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Un(e,t="Payment failed. Please try again.",n){let c=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,l=On(a)??a;return Ho(new Be.FloPayError(l,"api_error",{code:(0,Be.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Be.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),c)}function Ko(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function po(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Is(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 di(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||po(a)))return a;let c=e?.data;if(c&&typeof c=="object"){let a=c,l=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let d of l)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||po(d)))return d;let p=a.gateways;if(p&&typeof p=="object"){let d=p.stripe;if(d&&typeof d=="object"){let k=d,U=[k.stripeClientSecret,k.clientSecret];for(let P of U)if(typeof P=="string"&&P.length>0&&(!t?.requirePaymentIntentClientSecret||po(P)))return P}}}}async function Es({billingApiUrl:e,sessionId:t,nonce:n,responseJson:c}){let a=di(c,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let d=(await new mr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(po(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function yr({billingApiUrl:e,sessionId:t,session:n,nonce:c,tokenizedData:a,returnUrl:l,telemetry:p}){let d=e.replace(/\/+$/,""),k=t??n.id,U=c??n.clientSecret,P=n.customer?.id??n.accountData?.userId??"",I=n.customer?.email??n.accountData?.email??"",R=n.customer?.firstName??n.accountData?.firstName??"",O=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,b=n.customer?.zip??n.accountData?.zip??void 0,E=new mr.PaymentAPI(d,p===!1?{telemetry:!1}:void 0),x=await Is(()=>E.processPayment(P,{sessionId:k,nonce:U,tokenizedData:a,accountData:{userId:P,email:I,firstName:R,lastName:O,country:u,zip:b},returnUrl:l??Ko(n)}));if(x.ok){let M=typeof x.json=="function"?await x.json().catch(()=>null):null;return(0,Be.isAuthorizationOnlySession)(n)||M?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof M?.paymentId=="string"?M.paymentId:n.paymentId,sessionId:typeof M?.sessionId=="string"?M.sessionId:k,authorizationExpiresAt:typeof M?.authorizationExpiresAt=="string"?M.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Tr(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:a?.threeDSecureActionResultTokenId,paymentMethodId:Tr(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}}let h;try{h=await x.json()}catch{throw new Be.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:x.status})}if(h?.type==="paypal_redirect_required"||h?.type==="3ds_required"){let M=di(h);if(!M)throw new Be.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:x.status});return{type:h.type,threeDSecureToken:M,paymentMethodId:h.paymentMethodId}}if(h?.gatewayErrorCode==="authentication_required"){let M=await Es({billingApiUrl:d,sessionId:k,nonce:U,responseJson:h});if(M)return M;throw Ho(new Be.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ye=new Be.FloPayError(h?.message??"Payment failed. Please try again.","api_error",{code:h?.code??h?.gatewayErrorCode,declineCode:h?.declineCode??h?.gatewayDeclineReason,statusCode:x.status});throw Object.assign(ye,{telemetryOutcome:(0,Be.classifyPaymentRejection)(x.status,h)})}async function mo(e,{flopay:t,paypalFlopay:n,attempt3DS:c,billingApiUrl:a,sessionId:l,session:p,returnUrl:d,telemetry:k}){let U=t?.getRawProvider();if(!U)throw An(new Be.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!c||!e.threeDSecureToken)throw Ho(new Be.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let P=(0,Be.isSetupIntentClientSecret)(e.threeDSecureToken),I=null,R=e.paymentMethodId,O=await Fr(()=>Ss(U,e.threeDSecureToken,P),"card");if(O){if(O.error)throw An(new Be.FloPayError(O.error.message??`Failed to retrieve 3DS ${P?"setup":"payment"} status.`,"api_error",{code:O.error.code}),"card");let b=O.intent;!R&&b?.payment_method&&(typeof b.payment_method=="string"?R=b.payment_method:"id"in b.payment_method&&(R=b.payment_method.id??void 0))}let u=R?await Fr(()=>ws(U,e.threeDSecureToken,{payment_method:R,return_url:d??Ko(p)??window.location.href},P),"card"):null;if(u){if(u.error)throw An(new Be.FloPayError(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");I=u.intent}else{let b=await Fr(()=>U.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(b.error)throw An(new Be.FloPayError(b.error.message??"3DS authentication failed.","api_error",{code:b.error.code}),"card");I=(P?b.setupIntent:b.paymentIntent)??null}if(I&&(I.status==="requires_capture"||I.status==="succeeded"||I.status==="processing")){let b=await yr({billingApiUrl:a,sessionId:l,session:p,telemetry:k,tokenizedData:{id:I.id,type:"card",threeDSecureActionResultTokenId:I.id},returnUrl:d});return b.type==="success"?{...b.result,paymentIntentId:b.result.paymentIntentId??I.id,paymentMethodId:b.result.paymentMethodId??R}:mo(b,{flopay:t,paypalFlopay:n,attempt3DS:c,billingApiUrl:a,sessionId:l,session:p,returnUrl:d,telemetry:k})}throw An(new Be.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let P=(n??t)?.getRawProvider();if(!P)throw An(new Be.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:R}=await Fr(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(R)throw An(new Be.FloPayError(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:I}=await Fr(()=>P.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Ko(p)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(I)throw An(new Be.FloPayError(I.message??"PayPal authorization failed.","api_error",{code:I.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Be.FloPayError("Unsupported payment redirect state.","api_error")}function Qn(e){if(e instanceof Be.FloPayError){let c=On(e.message);return c&&c!==e.message?Object.assign(new Be.FloPayError(c,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=On(t)??t;return new Be.FloPayError(n,"api_error")}function yo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Be.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function fo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:c,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let l=!!t&&t!==e,[p,d]=await Promise.all([(0,mr.loadFloPay)(e,{billingApiUrl:n,locale:c,telemetry:a}),l?(0,mr.loadFloPay)(t,{billingApiUrl:n,locale:c,telemetry:a}).catch(k=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",k),null)):Promise.resolve(null)]);return{flopay:p,paypalFlopay:t?l?d:p:null}}var w=require("react/jsx-runtime"),fr=44,Zo="flopay_checkout_saved_payment_resume",Po=new Map,go=new Map;function ui(e,t){t.settled&&t.consumers===0&&Po.get(e)===t&&Po.delete(e)}function _s(e,t,n){let c=go.get(e);if(c&&(!c.sdkGeneratedIdempotencyKey||!t||c.sdkGeneratedIdempotencyKey===t))return c.attempt;let a=n(),l={attempt:a,sdkGeneratedIdempotencyKey:t};go.set(e,l);let p=()=>{go.get(e)===l&&go.delete(e)};return a.then(p,p),a}function Lr(e){return new Promise(t=>setTimeout(t,e))}function ho(e,t,n){let c=Jr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Se.SDK_VERSION,enabled:t!==!1});return c.beginCheckout(n),c}function zr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Wo(e,t,n,c,a){let l=ho(e,t,n);l.error({errorCode:c,stage:a,paymentMethodCategory:"unknown",...a==="session_read"?{requestCategory:"session_read"}:{}}),zr(l)}function xs(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 Yo(e){return!e||e.data.stripe?.publishableKey?!1:!!Xo(e)?.clientId}function Bn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Ts(){if(!Bn())return null;try{let e=window.sessionStorage.getItem(Zo);return e?JSON.parse(e):null}catch{return null}}function pi(e){if(Bn())try{window.sessionStorage.setItem(Zo,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Go(){if(Bn())try{window.sessionStorage.removeItem(Zo)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ea=":idempotency-key";function Ms(e){if(!Bn())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 mi(e,t,n){if(Bn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(c){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",c)}}function Qo(e){if(Bn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function As(e){if(Bn())try{return window.sessionStorage.getItem(e+ea)??void 0}catch{return}}function Bs(e,t){if(Bn())try{window.sessionStorage.setItem(e+ea,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function Fs(e){if(Qo(e),!!Bn())try{window.sessionStorage.removeItem(e+ea)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Ds(){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 c of t)e.searchParams.has(c)&&(e.searchParams.delete(c),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function yi(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 Ls(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 Jo(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function bo({sessionId:e,nonce:t,createSession:n,billingApiUrl:c,telemetry:a,appearance:l,locale:p,loading:d,error:k,onComplete:U,onError:P,onDecline:I,onCountryChange:R,onZipChange:O,showPayPal:u=!0,showStripe:b=!0,enabledPaymentMethods:E,showApplePay:x=!0,showGooglePay:h=!0,debug:ye=!1,layout:M,theme:ce,buttonsTheme:oe,buttonsStyles:j,cardButtonContent:te,cardBackButtonContent:X,cardTitleContent:de,showSecurityFooter:Y,onButtonClick:G,onBeforeButtonClick:pe,enableAVS:De,cardFieldOrder:we,cardPreFormSlot:ge,avsLayout:ae,className:be,initialErrorMessage:Le=null,children:ie,checkoutMode:je,confirmLabel:Oe,renderConfirmButton:Ee,onSessionCompleted:J}){let S=(0,Se.resolveBillingApiUrl)(c),se=(0,F.useMemo)(()=>(0,Se.resolveTheme)(ce),[ce]),Ve=l??se?.appearance,Ne=n?"embedded_checkout":"standard_checkout",ue=ie?"custom_layout":M==="buttons"?"buttons_layout":"default_layout",[A,le]=(0,F.useState)(null),[Q,_e]=(0,F.useState)(null),dt=(0,F.useRef)(null),[Qe,pt]=(0,F.useState)(null),D=(0,F.useRef)(null),[Z,tt]=(0,F.useState)(null),[Ke,mt]=(0,F.useState)(e??""),Ue=e??Ke,Ge=n?"":Ue,[Yt,Xe]=(0,F.useState)(!0),[Gt,_]=(0,F.useState)(null),[ve,Je]=(0,F.useState)("full"),[xe,vt]=(0,F.useState)(!1),[We,He]=(0,F.useState)(Le),[nt,Ze]=(0,F.useState)(null),[wn,ot]=(0,F.useState)(null),[$n,Vt]=(0,F.useState)(!1),[fn,Jt]=(0,F.useState)(void 0),[tr,Tt]=(0,F.useState)(""),[St,Xt]=(0,F.useState)(!1),[Qt,Mt]=(0,F.useState)(!1),At=(0,F.useRef)(0),[Ct,re]=(0,F.useState)("loading"),[qn,N]=(0,F.useState)(0),at=(0,F.useRef)(!1),Bt=(0,F.useRef)(!1),Fn=(0,F.useRef)(!1),ze=(0,F.useRef)(null),it=(0,F.useMemo)(()=>({checkoutMode:je??ve,layout:ie?"unknown":M==="buttons"?"buttons":"embedded"}),[je,ie,ve,M]),Ye=(0,F.useRef)(U);Ye.current=U;let kn=(0,F.useRef)(P);kn.current=P;let Rn=(0,F.useRef)(I);Rn.current=I,(0,F.useEffect)(()=>{xt(Q)?.setCheckoutContext(it),Qe&&Qe!==Q&&xt(Qe)?.setCheckoutContext(it)},[Q,Qe,it]);let Dn=(0,F.useRef)(J);Dn.current=J;let jn=(0,F.useCallback)(T=>{re(T),!(T!=="exhausted"||Fn.current)&&(Fn.current=!0,kn.current?.(new Se.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),In=(0,F.useCallback)(()=>{re("retrying"),N(T=>T+1)},[]);(0,F.useEffect)(()=>{re("loading"),N(0),Fn.current=!1},[Ue]),(0,F.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Se.SDK_VERSION,checkout_type:Ne,checkout_layout:ue,billing_api_url:S})},[ue,Ne,S]);let rt=(0,F.useMemo)(()=>n?zt(n,!0):"",[n]),Ft=(0,F.useMemo)(()=>tr===rt?fn:void 0,[fn,tr,rt]),rn=(0,F.useMemo)(()=>n?Lo(n,Ft):void 0,[n,Ft]),gt=je??rn?.checkoutMode??"full",It=(0,F.useMemo)(()=>rn?{...rn,checkoutMode:gt}:void 0,[rn,gt]);(0,F.useEffect)(()=>{Jt(void 0),Tt(rt)},[rt]),(0,F.useEffect)(()=>{He(Le)},[Le]);let Zt=(0,F.useCallback)((T,$,B)=>{ut(()=>{Rn.current?.(Rt(T,$,B))})},[ut]),on=(0,F.useCallback)(async(T,$)=>{He(null),ot(null),Vt(!1),Ze("processing");let B=$?.sessionId??T.id,Ce=dt.current??D.current,ke=xt(Ce),y=Ce?null:ho(S,a,it),r={log:m=>{ke?ke.log(m):y?.log(m)},error:m=>{ke?ke.error(m):y?.error(m)},terminal:m=>{ke?ke.terminal(m):y?.terminal(m)},performance:m=>{ke?ke.performance(m):y?.performance(m)},now:()=>ke?.now()??y?.now()??0,elapsed:m=>ke?.elapsed(m)??Math.max(0,(y?.now()??m)-m)},g=r.now(),L=!!($?.initialAutoProcessingError||$?.initialAutoProcessingPending),f=!1,K,Te=()=>{f||(f=!0,L=!0,K=r.now(),r.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},st=!1,ee=()=>{st||(st=!0,r.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),r.performance({stage:"processing",durationMs:r.elapsed(g),durationMode:"machine",paymentMethodCategory:"saved"}),K!==void 0&&r.performance({stage:"recovery",durationMs:r.elapsed(K),durationMode:"machine",paymentMethodCategory:"saved"}))};r.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),r.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),L&&Te();let H;try{let m=li($?.initialAutoProcessingError),q;if(m)Te(),m.type==="paypal_redirect_required"&&ze.current?.publishableKey&&pi({sessionId:B,publishableKey:ze.current.publishableKey,paypalPublishableKey:ze.current.paypalPublishableKey}),q=await mo(m,{flopay:dt.current,paypalFlopay:D.current,attempt3DS:$?.attempt3DS,billingApiUrl:S,sessionId:B,session:T,telemetry:!1}),m.type==="paypal_redirect_required"&&Go();else if($?.initialAutoProcessingPending){let Ae=(await new Zn.PaymentAPI(S,{telemetry:!1}).waitForCheckoutSessionCompletion($.initialAutoProcessingPending.sessionId,{initialDelayMs:$.initialAutoProcessingPending.retryAfterMs})).data.session;if(!dr(Ae))throw no(Ae);q=Jn(Ae,B)}else{if($?.initialAutoProcessingError)throw Un($.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:$.initialAutoProcessingError.checkoutMethod});if($?.fromCreateSession)return $?.fallbackToFull&&(Je("full"),yi("full")),!1;{let he=await yr({billingApiUrl:S,sessionId:B,session:T,telemetry:!1});he.type==="success"?q=he.result:(Te(),he.type==="paypal_redirect_required"&&ze.current?.publishableKey&&pi({sessionId:B,publishableKey:ze.current.publishableKey,paypalPublishableKey:ze.current.paypalPublishableKey}),q=await mo(he,{flopay:dt.current,paypalFlopay:D.current,attempt3DS:$?.attempt3DS,billingApiUrl:S,sessionId:B,session:T,telemetry:!1}),he.type==="paypal_redirect_required"&&Go())}}B&&ur(B),ee(),L&&(r.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),r.terminal({outcome:q.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Vt(q.status==="authorized"),Ze("success"),await Lr(xn),H=()=>Ye.current?.(q)}catch(m){let q=Qn(m),he=q.checkoutMethod??Dr;He(q.message),ot(q.message),Vt(!1),$?.fallbackToFull&&(r.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Je("full"),yi("full")),ee();let Ie=q.statusCode!==void 0?(0,Se.telemetryStatusClass)(q.statusCode,"unknown"):void 0,Ae=Ie==="4xx"?{requestCategory:"process_payment",statusClass:Ie}:{},hn=Ie===void 0||Ie==="4xx";if(hn&&(q.telemetryOutcome==="payment_declined"||!!(q.declineCode||q.code?.toLowerCase().includes("declin"))))r.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ae});else if(hn&&(q.telemetryOutcome==="validation_rejected"||q.type==="validation_error"))r.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ae});else{let Or=(0,Se.classifyTelemetryFailure)(m,L?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");r.error({...Or,...q.telemetryFailureCategory?{failureCategory:q.telemetryFailureCategory}:{},stage:L?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:q.telemetryRequestCategory??"process_payment"})}return ut(()=>kn.current?.(q)),Zt(he,q,{code:q.code,declineCode:q.declineCode}),Ze("error"),await Promise.allSettled([Lr(vn),$?.ensureProvidersReady?$.ensureProvidersReady():Promise.resolve()]),L&&(r.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{ee(),y&&zr(y),Ze(null),ot(null)}return ut(H),!0},[Zt,ut,Qn,S,a,it]);(0,F.useEffect)(()=>{if(typeof window>"u"||Bt.current)return;let T=new URLSearchParams(window.location.search),$=T.get("payment_intent_client_secret");if(!$)return;let B=Ts();B&&(Bt.current=!0,(async()=>{let Ce,ke=0;He(null),ot(null),Ze("processing"),vt(!0);try{if(T.get("redirect_status")==="failed")throw Object.assign(new Se.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:y,paypalFlopay:r}=await fo({publishableKey:B.publishableKey,paypalPublishableKey:B.paypalPublishableKey,billingApiUrl:S,locale:p,telemetry:a});Ce=xt(r??y),ke=Ce?.now()??0,Ce?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Ce?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let g=(r??y)?.getRawProvider();if(!g)throw Object.assign(new Se.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:L,error:f}=await g.retrievePaymentIntent($);if(f)throw Object.assign(new Se.FloPayError(f.message??"Failed to retrieve PayPal payment status.","api_error",{code:f.code}),{checkoutMethod:"paypal"});let K=Ua(L?.status);if(!L||K==="failed")throw Object.assign(new Se.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Te=typeof L.payment_method=="string"?L.payment_method:L.payment_method?.id,st=K;if(B.sessionId){let m=(await new Zn.PaymentAPI(S,{telemetry:!1}).getUnifiedCheckoutSession(B.sessionId)).data.session;if(m&&m.status!=="complete"){let q=await yr({billingApiUrl:S,sessionId:B.sessionId,session:m,telemetry:!1,tokenizedData:{id:Te??L.id,type:"card",threeDSecureActionResultTokenId:L.id,isPaypal:!0}});if(q.type!=="success")throw Object.assign(new Se.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});st=q.result.status}}B.sessionId&&ur(B.sessionId),Ce?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Ce?.performance({stage:"redirect_resume",durationMs:Ce.elapsed(ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Ce?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ze("success"),await Lr(xn),ut(()=>Ye.current?.({status:st,paymentIntentId:L.id,paymentMethodId:Te,checkoutMethod:"paypal"}))}catch(y){let r=Qn(y),g=r.checkoutMethod??"paypal",L=!!(r.declineCode||r.code?.toLowerCase().includes("declin"));if(Ce)Ce.performance({stage:"redirect_resume",durationMs:Ce.elapsed(ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),L?Ce.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Ce.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(L){let f=ho(S,a,it);f.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),zr(f)}else Wo(S,a,it,"REDIRECT_RESUME_FAILED","redirect_resume");He(r.message),ot(r.message),ut(()=>kn.current?.(r)),Zt(g,r,{code:r.code,declineCode:r.declineCode}),Ze("error"),await Lr(vn)}finally{Go(),Ds(),Ze(null),ot(null),vt(!1)}})())},[Zt,ut,p,Qn,S,a]);let Kt=(0,F.useRef)(null);function zt(T,$=!1){let B=T?.account?.email?.trim().toLowerCase()??"",Ce={c:T?.clientId,cur:T?.currency??"",captureMethod:T?.captureMethod??"",a:{e:B,u:B?"":T?.account?.userId??"",country:T?.account?.country??""},successUrl:T?.successUrl,cancelUrl:T?.cancelUrl,p:T?.products?.map(r=>Jo(`${r.type??""}:${r.code??r.providerItemId??r.providerPlanId??""}`,r)).sort(),i:T?.items?.map(r=>Jo(r.code??r.providerItemId??"",r)).sort(),s:T?.subscriptions?.map(r=>Jo(r.code??r.providerPlanId??"",r)).sort(),couponCodes:T?.couponCodes?[...T.couponCodes].sort():void 0,...$?{tagsData:T?.tagsData,utmMetadata:T?.utmMetadata,tokenizedData:T?.tokenizedData,checkoutMode:T?.checkoutMode??"full"}:{}},ke=JSON.stringify(Ce),y=0;for(let r=0;r<ke.length;r++)y=(y<<5)-y+ke.charCodeAt(r)|0;return`flopay_session_${Math.abs(y).toString(36)}`}let Ot=(0,F.useMemo)(()=>It?zt(It):"",[It]),Me=(0,F.useRef)(It);Me.current=It,(0,F.useEffect)(()=>{mt(e??"")},[e]),(0,F.useEffect)(()=>{at.current=!1,He(Le),ot(null),Vt(!1),Ze(null)},[Ot,Le,e]);async function Nt(T,$){let B=ho(S,a,it),Ce=new Zn.PaymentAPI(S,{telemetry:!1}),ke=!1;try{let y=T.idempotencyKey!==void 0?(0,Se.resolveIdempotencyKey)(T.idempotencyKey):void 0,r=y??As($),g,L=!1,f=Ms($);B.log({name:f?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let K=f?.sid??null,Te=null,st;if(K)try{if(Te=await Ce.getUnifiedCheckoutSession(K,f?.nonce),Te.data.session?.status==="complete"){if(Oo(K))return{sid:K,result:Te};Fs($),K=null,Te=null,L=!0}}catch{B.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Qo($),K=null}if(!K){!y&&(L||!r)&&(r=(0,Se.resolveIdempotencyKey)(),g=r),r&&Bs($,r);let ee=B.now(),H=0;B.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let m={...T,idempotencyKey:r,avsCheck:!!De,avsConfig:typeof De=="object"?De:void 0,checkoutType:"embedded_checkout",checkoutLayout:ie?"custom_layout":M==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(m,Zn.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Ie=>{H=Math.max(H,Ie)}}});let q=()=>{B.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),B.performance({stage:"session_create",durationMs:B.now()-ee,durationMode:"machine",requestCategory:"session_create",attempt:H,statusClass:"2xx"})},he=Ie=>{let Ae=(0,Se.classifyTelemetryFailure)(Ie,"CHECKOUT_SESSION_CREATE_FAILED","unknown");B.performance({stage:"session_create",durationMs:B.now()-ee,durationMode:"machine",requestCategory:"session_create",attempt:H,statusClass:Ae.statusClass}),Ie instanceof Se.FloPayError&&Ie.type==="validation_error"?B.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):Ae.statusClass==="4xx"?B.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):B.error({...Ae,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if((0,Se.isDetachedSessionEligible)(m)){let Ie=await Ce.createDetachedSession(m);Ie.claimed.catch(()=>{}),Te=Ie.shell,K=Ie.sessionId,st=Ie.claimed.then(Ae=>{let hn=Ae.data.session?.id??Ie.sessionId;return hn&&mi($,hn,Ae.data.session?.clientSecret??Ie.nonce),q(),Ae},Ae=>{throw Qo($),he(Ae),Ae}).finally(()=>zr(B)),st.catch(()=>{}),ke=!0,B.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),B.performance({stage:"session_shell",durationMs:B.now()-ee,durationMode:"machine",requestCategory:"session_create",attempt:H,statusClass:"2xx",paymentMethodCategory:"card"})}else Te=await Ce.createAndFetchSession(m),q()}catch(Ie){throw he(Ie),Ie}K=Te.data.session?.id??K??"",K&&!st&&mi($,K,Te.data.session?.clientSecret)}return{sid:K??"",result:Te,sdkGeneratedIdempotencyKey:g,...st?{claimed:st}:{}}}finally{ke||zr(B)}}let yt=(0,F.useCallback)(async(T,$)=>{let B=Me.current;if(!B)throw new Se.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Ce=Lo(B,T),ke=zt(Ce),y=Po.get(ke);if(!y){let L={promise:Nt(Ce,ke),consumers:0,settled:!1};y=L,Po.set(ke,L);let f=()=>{L.settled=!0,ui(ke,L)};L.promise.then(f,f)}y.consumers+=1;let r=!1,g=()=>{r||(r=!0,y.consumers-=1,ui(ke,y))};$?.(g);try{let L=await y.promise;Kt.current=ke,T&&(Tt(rt),Jt(q=>za(q,T)));let{sid:f,result:K,claimed:Te}=L;if(le(K),K.data.session&&tt(K.data.session),f&&mt(f),Te){let q=At.current+=1;Mt(!0),Te.then(he=>{At.current===q&&(le(he),he.data.session&&tt(he.data.session),Mt(!1))},he=>{At.current===q&&(Mt(!1),_(he instanceof Se.FloPayError?he:new Se.FloPayError(he instanceof Error?he.message:"Failed to create session","api_error")))})}else At.current+=1,Mt(!1);let{publishableKey:st,paypalPublishableKey:ee}=yo(K),{flopay:H,paypalFlopay:m}=await fo({publishableKey:st,paypalPublishableKey:ee,billingApiUrl:S,locale:p,telemetry:a});return dt.current=H,_e(H),D.current=m,pt(m),Xe(!1),L}catch(L){throw Kt.current===ke&&(Kt.current=null),L}finally{$||g()}},[p,S,a,it]),gn=(0,F.useRef)(on);gn.current=on;let Vn=(0,F.useRef)(yt);Vn.current=yt;let Ut=(0,F.useCallback)(async T=>{if(!Ls(T)||St)return{sessionId:Ke,session:Z};Xt(!0);try{let $=await yt(T);return{sessionId:$.sid,session:$.result.data.session??null}}finally{Xt(!1)}},[yt,St,Ke,Z]);(0,F.useEffect)(()=>{let T=!1,$;if(_(null),Ot){let ke=Me.current;return Je(gt),Xe(!1),Kt.current===Ot?()=>{T=!0}:(tt(Oa(ke,je)),(async()=>{let y=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),r=gt==="auto"&&!at.current&&!y;r&&(He(null),ot(null),Ze("processing"));try{let g=await Vn.current(void 0,Te=>{$=Te}),L=g.result.data.session??null;ze.current=yo(g.result);let f=Yo(g.result),K=Oo(g.sid||L?.id);if(!T&&r&&L&&!f&&!K){at.current=!0,await _s(Ot,g.sdkGeneratedIdempotencyKey,()=>gn.current(L,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:g.result.autoProcessingError,initialAutoProcessingPending:g.result.autoProcessingPending,autoProcessingAttempted:g.result.autoProcessingAttempted,sessionId:g.sid||L.id}));return}!T&&r&&((f||K)&&(at.current=!0),Ze(null),ot(null))}catch(g){if(T)return;let L=g instanceof Se.FloPayError||typeof g=="object"&&g!==null&&"code"in g?g.code:void 0;if(r&&L==="session_auto_completed"){at.current=!0,Ze("success"),await Lr(xn),T||(ut(()=>{Ye.current?.({status:"succeeded"})}),Ze(null),ot(null));return}r&&(Ze(null),ot(null));let f=g instanceof Se.FloPayError?g:new Se.FloPayError(g instanceof Error?g.message:"Failed to create session","api_error");_(f)}finally{$?.(),$=void 0}})(),()=>{T=!0,$?.()})}Xe(!0);async function B(){let ke=!1;try{let r=await new Zn.PaymentAPI(S,{telemetry:!1}).getUnifiedCheckoutSession(Ue,t);if(T)return;le(r);let g=r.data.session??null;if(tt(g),!g)throw new Se.FloPayError("No session data returned","api_error");if(g.status==="authorized"){Xe(!1),ut(()=>{Ye.current?.(Jn(g,Ue)),Dn.current?.(g.successUrl??"")});return}if(g.status==="complete"){Xe(!1),ut(()=>{Dn.current?.(g.successUrl??"")});return}if(g.status==="expired")throw to(g);ke=!0;let L=je??g.checkoutMode??"full";Je(L);let f=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),K=Yo(r);if(L==="auto"&&!at.current&&!f&&!K){at.current=!0;let Te=Ce(r);try{if(await gn.current(g,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Te,sessionId:Ue||g.id}),T)return;await Te,T||Xe(!1);return}catch{if(T)return;await Te,T||Xe(!1);return}}await Ce(r),T||Xe(!1)}catch(y){if(T)return;y instanceof Se.FloPayError?!ke&&!xs(y)&&Wo(S,a,it,"NETWORK_REQUEST_FAILED","session_read"):Wo(S,a,it,"INTERNAL_SDK_ERROR","checkout_mount");let r=y instanceof Se.FloPayError?y:new Se.FloPayError(y instanceof Error?y.message:"Failed to initialize checkout","api_error");_(r),Xe(!1)}}async function Ce(ke){let{publishableKey:y,paypalPublishableKey:r}=yo(ke);ze.current={publishableKey:y,paypalPublishableKey:r};let{flopay:g,paypalFlopay:L}=await fo({publishableKey:y,paypalPublishableKey:r,billingApiUrl:S,locale:p,telemetry:a});dt.current=g,_e(g),D.current=L,pt(L)}return B(),()=>{T=!0}},[je,Ot,gt,Ge,ut,t]);let $t=(0,F.useCallback)(async()=>{if(!(xe||!Z)){vt(!0),He(null);try{await on(Z,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ue||Z.id})}finally{vt(!1)}}},[Ue,xe,on,Z]),Dt=Xo(A),Ln=Yo(A),zn=(0,F.useMemo)(()=>{if(!A||!Z||!A.data.stripe?.publishableKey)return;let T={appearance:Ve,paymentMethodCreation:"manual",billingApiUrl:S};if(A.data.stripe?.clientSecret)T.clientSecret=A.data.stripe.clientSecret;else{let $=(0,Se.buildCheckoutDisplayData)(Z).total;T.amount=Math.round($*100)||Z.amount,T.currency=Z.currency?.toLowerCase()}return T},[A,Z,Ve,S]),en=!!(n&&!ie&&M==="buttons"&&pe&>==="full"),Ht=(0,F.useMemo)(()=>({session:Z,loading:Yt,error:Gt,checkoutMode:ve,inlineSessionDraft:It,applyInlineSessionPatch:en?Ut:void 0,inlineSessionPatchProcessing:St,claimPending:Qt}),[Z,Yt,Gt,ve,It,en,Ut,St,Qt]),tn=!!n&&M==="buttons"&&!Ln&&(!Q||!zn),$e=nt?(0,w.jsx)(Cn,{status:nt,errorMessage:wn,authorized:$n}):null;if(Yt){if(d)return(0,w.jsxs)(w.Fragment,{children:[d,$e]});if(M==="buttons"){let T=se?.buttonsLayout?.cardButton?.borderRadius??se?.appearance.variables?.borderRadius??8,$=B=>(0,w.jsx)("div",{style:{height:B,borderRadius:T,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[u&&$(fr),b&&(x||h)&&$(fr),b&&$(fr),(0,w.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),$e]})}return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,w.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,w.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),$e]})}return Gt?k?(0,w.jsx)(ln.Provider,{value:Ht,children:k(Gt)}):(0,w.jsx)(ln.Provider,{value:Ht,children:(0,w.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Gt.message})}):tn?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(ln.Provider,{value:Ht,children:(0,w.jsx)(Os,{onButtonClick:G,showPayPal:u,showStripe:b,showApplePay:x,showGooglePay:h,theme:ce,buttonsTheme:oe,buttonsStyles:j,cardButtonContent:te,cardBackButtonContent:X,cardTitleContent:de})}),$e]}):Ln&&Z&&Dt?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(ln.Provider,{value:Ht,children:(0,w.jsxs)("div",{className:be,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[We&&(0,w.jsx)(sr,{icon:!1,children:We}),Ct==="retrying"&&(0,w.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ct==="exhausted"&&(0,w.jsxs)("div",{role:"alert",children:[(0,w.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,w.jsx)("button",{type:"button",onClick:In,children:"Retry PayPal"})]}),Ct!=="exhausted"&&(0,w.jsx)("div",{"aria-hidden":Ct==="retrying"?!0:void 0,style:Ct==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,w.jsx)(Wa,{sessionId:Ue,nonce:Z.clientSecret||void 0,billingApiUrl:S,email:Z.customer?.email,clientId:Dt.clientId,environment:Dt.environment,currency:(Z.currency??"usd").toUpperCase(),isSubscription:Z.mode==="subscription",onComplete:U,onErrorChange:He,onDecline:I,onButtonClick:G,onInitializationStateChange:jn,allowAutomaticRetry:qn===0,session:Z,telemetry:a,telemetryContext:it,debug:ye},`paypal-init-${qn}`)})]})}),$e]}):!Q||!zn?(0,w.jsx)(w.Fragment,{children:$e}):ve==="confirm"?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(ln.Provider,{value:Ht,children:(0,w.jsx)(Er,{flopay:Q,paypalFlopay:Qe,options:zn,children:(0,w.jsxs)("div",{className:be,children:[We&&(0,w.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:We}),Ee?Ee({onConfirm:$t,isProcessing:xe}):(0,w.jsx)("button",{type:"button",onClick:$t,disabled:xe,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:xe?"not-allowed":"pointer",opacity:xe?.6:1},children:xe?"Processing...":Oe??"Confirm Purchase"})]})})}),$e]}):(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(ln.Provider,{value:Ht,children:(0,w.jsx)(Er,{flopay:Q,paypalFlopay:Qe,options:zn,children:ie?(0,w.jsxs)(w.Fragment,{children:[We&&(0,w.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:We}),(0,w.jsx)(zs,{sessionId:Ue,nonce:Z?.clientSecret||void 0,billingApiUrl:S,session:Z,children:ie})]}):(0,w.jsx)(uo,{sessionId:Ue,nonce:Z?.clientSecret||void 0,email:Z?.customer?.email,userId:Z?.customer?.id,firstName:Z?.customer?.firstName,lastName:Z?.customer?.lastName,totalAmount:Z?Math.round((0,Se.buildCheckoutDisplayData)(Z).total*100):0,currency:Z?.currency?.toLowerCase()??"usd",onComplete:U,onError:P,onDecline:I,error:We,onErrorChange:He,showPayPal:u,showStripe:b,enabledPaymentMethods:E??A?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:A?.data.stripe?.enabledPaymentMethodCountries,showApplePay:x,showGooglePay:h,layout:M,theme:ce,buttonsTheme:oe,buttonsStyles:j,appearance:Ve,cardButtonContent:te,cardBackButtonContent:X,cardTitleContent:de,onButtonClick:G,onBeforeButtonClick:pe,enableAVS:De,...we?{cardFieldOrder:we}:{},...ge?{cardPreFormSlot:ge}:{},avsLayout:ae,country:Z?.customer?.country,city:Z?.customer?.city,state:Z?.customer?.state,onCountryChange:R,onZipChange:O,avsCheck:!!De,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ie?"custom_layout":M==="buttons"?"buttons_layout":"default_layout",className:be,directPaypal:Xo(A),isSubscription:Z?.mode==="subscription",session:Z,dataAttachmentPending:Qt,debug:ye})})}),$e]})}function zs({sessionId:e,nonce:t,billingApiUrl:n,session:c,children:a}){return(0,w.jsx)(w.Fragment,{children:F.default.Children.map(a,l=>{if(!F.default.isValidElement(l))return l;let p=l.props,d={};return p.sessionId||(d.sessionId=e),!p.nonce&&t&&(d.nonce=t),p.billingApiUrl||(d.billingApiUrl=n),c?.customer&&(p.email||(d.email=c.customer.email),p.userId||(d.userId=c.customer.id),p.firstName||(d.firstName=c.customer.firstName),p.lastName||(d.lastName=c.customer.lastName)),Object.keys(d).length===0?l:F.default.cloneElement(l,d)})})}function Os({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:c,showGooglePay:a,theme:l,buttonsTheme:p,buttonsStyles:d,cardButtonContent:k,cardBackButtonContent:U,cardTitleContent:P}){let[I,R]=(0,F.useState)(!1),O=(0,F.useMemo)(()=>(0,Se.resolveTheme)(l),[l]),u=(0,F.useMemo)(()=>{let h=O?.buttonsLayout??(0,Se.resolveButtonsLayoutTheme)(p);return d?{...h,...d,cardButton:{...h.cardButton,...d.cardButton},cardFormContainer:{...h.cardFormContainer,...d.cardFormContainer},backButton:{...h.backButton,...d.backButton},backButtonIcon:{...h.backButtonIcon,...d.backButtonIcon},submitButton:{...h.submitButton,...d.submitButton},title:{...h.title,...d.title}}:h},[O,p,d]),b=O?.buttonsLayout?.cardButton?.borderRadius??O?.appearance.variables?.borderRadius??8,E=h=>(0,w.jsx)("div",{style:{height:h,borderRadius:b,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),x=k===void 0?{boxSizing:"border-box",height:fr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(I){let h=u.cardInputBorder??"#e5e7eb",ye=u.cardInputBackground??"white",M=or(U),ce=or(P);return(0,w.jsxs)("div",{style:{backgroundColor:u.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...u.cardFormContainer},children:[(0,w.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,w.jsxs)("button",{type:"button",onClick:()=>R(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:M?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...u.backButton},children:[(0,w.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:(0,w.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,w.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,w.jsx)(ir,{content:U})]}),ce?(0,w.jsx)("div",{style:{flex:1}}):(0,w.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:(0,w.jsx)(_r,{content:P})})]}),(0,w.jsx)("div",{style:{backgroundColor:ye,border:`1px solid ${h}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsxs)("div",{style:{display:"flex"},children:[(0,w.jsx)("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsx)("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:`1px solid ${h}`,borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,w.jsx)("div",{style:{backgroundColor:ye,border:`1px solid ${h}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...u.submitButton,opacity:.5}}),(0,w.jsx)("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(0,w.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&x(ur),n&&(l||o)&&x(ur),n&&(0,w.jsx)("button",{type:"button",onClick:()=>{e?.("card"),k(!0)},style:{width:"100%",...M,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:p.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,...p.cardButton},onMouseDown:g=>{g.currentTarget.style.transform="scale(0.985)"},onMouseUp:g=>{g.currentTarget.style.transform="scale(1)"},children:(0,w.jsx)(rr,{content:I})}),(0,w.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Pi=require("@flopay/shared");var Qn=require("react");var pi=require("react/jsx-runtime");function ci(e,t){function n({className:l,id:o,style:s,options:m,onChange:d,onReady:I,onFocus:N,onBlur:b,onEscape:_}){let k=(0,Qn.useRef)(null),F=(0,Qn.useRef)(null),{elements:p,reportInteractive:v}=(0,Qn.useContext)(In);return(0,Qn.useEffect)(()=>{if(!p||!k.current)return;let x=!0;return(async()=>{let M=p.getElement(e);M||(M=await p.create(e,m)),!(!x||!k.current)&&(M.mount(k.current),F.current=M,d&&M.on("change",d),M.on("ready",()=>{v?.(),I?.()}),N&&M.on("focus",N),b&&M.on("blur",b),_&&M.on("escape",_))})(),()=>{if(x=!1,F.current){try{F.current.unmount()}catch{}F.current=null}}},[p,v]),(0,pi.jsx)("div",{ref:k,className:l,id:o,style:s})}return n.displayName=t,n}var di=ci("payment","PaymentElement"),ui=ci("address","AddressElement");var mi=require("@flopay/js"),yi=require("@flopay/shared"),fn=require("react");var yn=require("react/jsx-runtime");function fi({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,firstName:s,lastName:m,chv:d,onTokenizedBody:I,onComplete:N,onErrorChange:b,isProcessing:_=!1}){let k=un(),F=Yr(),p=Gr(),[v,x]=(0,fn.useState)(!1),[M,g]=(0,fn.useState)(!1),he=(0,fn.useRef)(!1),z=(n||p).replace(/\/+$/,""),ue=(0,fn.useCallback)(async te=>{try{let pe=await new mi.PaymentAPI(z).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:te,accountData:{userId:o??"",email:l??"",firstName:s??"",lastName:m??""},chv:d});if(pe.ok){N?.();return}let W=await pe.json().catch(()=>null);b?.(W?.message??"Payment failed. Please try again.")}catch(Q){b?.(Q instanceof Error?Q.message:"An unexpected error occurred")}},[z,e,t,o,l,s,m,d,N,b]),ae=(0,fn.useCallback)(te=>{I?I(te):ue(te)},[I,ue]);(0,fn.useEffect)(()=>{if(!k||he.current)return;let te=new URLSearchParams(window.location.search),Q=te.get("payment_intent"),pe=te.get("payment_intent_client_secret"),W=te.get("redirect_status");!Q||!pe||(he.current=!0,(async()=>{try{if(g(!0),W==="failed"){b?.("PayPal payment was declined. Please try again.");return}let J=k.getRawProvider();if(!J?.retrievePaymentIntent){b?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:me,error:Me}=await J.retrievePaymentIntent(pe);if(Me){b?.(Me.message??"Failed to retrieve PayPal payment status.");return}if(me&&(me.status==="requires_capture"||me.status==="succeeded")){let we=typeof me.payment_method=="string"?me.payment_method:me.payment_method?.id;ae({id:we??me.id,type:"card",threeDSecureActionResultTokenId:me.id,isPaypal:!0});let be=new URL(window.location.href);be.searchParams.delete("payment_intent"),be.searchParams.delete("payment_intent_client_secret"),be.searchParams.delete("redirect_status"),window.history.replaceState({},"",be.toString())}else b?.("PayPal payment was not completed. Please try again.")}catch(J){b?.(J instanceof Error?J.message:"Failed to complete PayPal payment.")}finally{g(!1)}})())},[k,ae,b]);let U=(0,fn.useCallback)(async()=>{if(!(!k||!F))try{if(g(!0),b?.(null),!e||!l)throw new yi.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let te=await k.confirmPayPalPayment({billingApiUrl:z,sessionId:e,nonce:t,email:l,returnUrl:window.location.href});if(te.error){b?.(te.error.message);return}te.paymentIntentId&&(te.status==="succeeded"||te.status==="processing"||te.status==="requires_capture")&&ae({id:te.paymentMethodId??te.paymentIntentId,type:"card",threeDSecureActionResultTokenId:te.paymentIntentId,isPaypal:!0})}catch(te){b?.(te instanceof Error?te.message:"PayPal payment failed. Please try again.")}finally{g(!1)}},[k,F,e,t,l,z,ae,b]);return!k||!F?(0,yn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,yn.jsxs)(yn.Fragment,{children:[!v&&(0,yn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,yn.jsx)("div",{style:v?{}:{display:"none"},children:(0,yn.jsx)("button",{type:"button",onClick:U,disabled:M||_,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:M||_?"not-allowed":"pointer",opacity:M||_?.6:1},ref:()=>x(!0),children:M?"Processing...":"PayPal"})}),(M||_)&&(0,yn.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,yn.jsx)("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..."})})]})}var De=require("react"),yo=require("@flopay/js"),$t=require("@flopay/shared");var gn=require("react/jsx-runtime"),As=44;function gi(e){return new Promise(t=>setTimeout(t,e))}function Fs(e,t){return e instanceof $t.FloPayError?e:new $t.FloPayError(e instanceof Error?e.message:t,"api_error")}function Ds(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Ls(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 hi({sessionId:e,nonce:t,createSession:n,paymentMethodId:l,checkoutMethod:o,clientId:s,products:m,items:d,subscriptions:I,account:N,successUrl:b,cancelUrl:_,couponCodes:k,tagsData:F,utmMetadata:p,billingApiUrl:v,locale:x,theme:M,appearance:g,buttonsTheme:he,buttonsStyles:z,onSuccess:ue,onError:ae,onDecline:U,children:te,disabled:Q=!1,type:pe="button",style:W,...J}){let me=(0,De.useMemo)(()=>(0,$t.resolveBillingApiUrl)(v),[v]),Me=(0,De.useMemo)(()=>Ls({createSession:n,clientId:s,products:m,items:d,subscriptions:I,account:N,successUrl:b,cancelUrl:_,couponCodes:k,tagsData:F,utmMetadata:p}),[N,_,s,k,n,m,d,I,b,F,p]),[we,be]=(0,De.useState)(!1),[ie,Ce]=(0,De.useState)(null),[Be,se]=(0,De.useState)(null),[Ee,_e]=(0,De.useState)(null),Re=(0,De.useRef)(!0),Z=(0,De.useRef)(null),T=(0,De.useRef)(Ee),ce=(0,De.useRef)(ue),Oe=(0,De.useRef)(ae),ze=(0,De.useRef)(U);(0,De.useEffect)(()=>{T.current=Ee},[Ee]),(0,De.useEffect)(()=>{ce.current=ue},[ue]),(0,De.useEffect)(()=>{Oe.current=ae},[ae]),(0,De.useEffect)(()=>{ze.current=U},[U]),(0,De.useEffect)(()=>(Re.current=!0,()=>{Re.current=!1,Z.current?.abort()}),[]),(0,De.useEffect)(()=>{if(typeof window>"u")return;let h=ke=>{ke.key==="Escape"&&_e(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let ye=(0,De.useCallback)((h,ke=Tr)=>{ze.current?.(wt(ke,h,{code:h.code,declineCode:h.declineCode}))},[]),E=(0,De.useCallback)(async h=>{Re.current&&(se(null),Ce("success"),await gi(_n),Re.current&&ce.current?.(h))},[]),re=(0,De.useCallback)(async(h,ke)=>{Re.current&&(Oe.current?.(h),ke?.emitDecline&&ye(h,ke.method),se(h.message),Ce("error"),await gi(Cn))},[ye]),oe=(0,De.useCallback)(async(h,ke,dt)=>{let nt=h.data.session??null;if(!nt)throw new $t.FloPayError("No session data returned","api_error");let Qe=nt.clientSecret||t;if(nt.status==="complete"){await E({result:{status:"succeeded"},session:nt,sessionId:nt.id||ke,autoCompleted:!1});return}if(nt.status==="expired")throw new $t.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(h.autoProcessingPending){let Ke=(await new yo.PaymentAPI(me).waitForCheckoutSessionCompletion(h.autoProcessingPending.sessionId,{initialDelayMs:h.autoProcessingPending.retryAfterMs})).data.session;if(!Ke||Ke.status!=="complete")throw new $t.FloPayError("Automatic payment failed. Please try again.","api_error",{code:Ke?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await E({result:{status:"succeeded"},session:Ke,sessionId:Ke.id||ke,autoCompleted:!1});return}if(h.autoProcessingError){if(h.autoProcessingError.type==="3ds_required"&&h.autoProcessingError.nextActionRedirectUrl&&ke&&Qe){let Ze=new AbortController;Z.current=Ze;let xe;try{xe=await ri({billingApiUrl:me,sessionId:ke,nonce:Qe,nextActionRedirectUrl:h.autoProcessingError.nextActionRedirectUrl,signal:Ze.signal})}finally{Z.current===Ze&&(Z.current=null)}if(xe.status==="declined")throw Un({type:xe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:xe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let Je=(await new yo.PaymentAPI(me).waitForCheckoutSessionCompletion(ke,{initialDelayMs:0,nonce:Qe})).data.session;if(!Je||Je.status!=="complete")throw Un({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await E({result:{status:"succeeded"},session:Je,sessionId:Je.id||ke,autoCompleted:!1});return}throw Un(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(dt?.fromCreateSession&&h.autoProcessingAttempted===!0)throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ye=await dr({billingApiUrl:me,sessionId:ke??nt.id,session:nt,nonce:Qe});if(Ye.type!=="success")throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await E({result:Ye.result,session:nt,sessionId:nt.id||ke,autoCompleted:!1})}catch(Ye){let Ze=Jn(Ye),xe=nt.id||ke;await re(Ze,{emitDecline:!0,method:Ze.checkoutMethod??Tr}),Ds(Ze,xe)&&xe&&Re.current&&_e({sessionId:xe,errorMessage:Ze.message,nonce:Qe||void 0})}},[t,me,re,E]),$e=(0,De.useCallback)(async h=>{if(J.onClick?.(h),!(h.defaultPrevented||Q||we)){if(_e(null),e&&Me){let ke=new $t.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await re(ke),Re.current&&(Ce(null),se(null));return}if(!e&&!Me){let ke=new $t.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await re(ke),Re.current&&(Ce(null),se(null));return}be(!0),se(null),Ce("processing");try{let ke=new yo.PaymentAPI(me);if(e){let dt=await ke.getUnifiedCheckoutSession(e,t);await oe(dt,e);return}try{let dt=await ke.createAndFetchSession({...Me});await oe(dt,dt.data.session?.id??null,{fromCreateSession:!0})}catch(dt){if(dt instanceof $t.FloPayError&&dt.code==="session_auto_completed"){await E({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw dt}}catch(ke){await re(Fs(ke,"Automatic payment failed. Please try again."))}finally{Re.current&&(Ce(null),se(null),be(!1))}}},[J,Me,Q,we,t,oe,me,e,re,E]),ct=(0,De.useCallback)(h=>{let ke=T.current;_e(null),ce.current?.({result:h,session:null,sessionId:ke?.sessionId??null,autoCompleted:!1})},[]),He=(0,De.useCallback)(h=>{Oe.current?.(h)},[]),ot=(0,De.useCallback)(h=>{ze.current?.(h)},[]),V=(0,De.useMemo)(()=>(0,$t.resolveTheme)(M),[M]),G=(0,De.useMemo)(()=>{let h=V?.buttonsLayout??(0,$t.resolveButtonsLayoutTheme)(he);return z?{...h,...z,cardButton:{...h.cardButton,...z.cardButton}}:h},[V,he,z]),tt=(0,De.useMemo)(()=>{let h=V?.appearance;return g?h?{...h,...g,variables:{...h.variables,...g.variables}}:g:h},[g,V]),Ae=tt?.variables,at=Ae?.colorPrimary??"#4A49FF",Ge=Ae?.colorPrimaryHover??to(at,.12),We=Ae?.borderRadius??"8px";return(0,gn.jsxs)(gn.Fragment,{children:[(0,gn.jsx)("button",{...J,type:pe,onClick:$e,disabled:Q||we,"aria-busy":we,style:{width:"100%",...te===void 0?{boxSizing:"border-box",height:As,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...G.cardButton,...No({themeBundle:V,resolvedPrimaryColor:at,resolvedBorderRadius:We,submitButtonStyle:G.submitButton,explicitPrimaryColor:Ae?.colorPrimary}),fontSize:G.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Q||we?"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||we?.6:1,...W},onMouseEnter:h=>{J.onMouseEnter?.(h),!h.defaultPrevented&&!Q&&!we&&(V||Ae?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Ge)},onMouseLeave:h=>{J.onMouseLeave?.(h),!h.defaultPrevented&&(V||Ae?.colorPrimary)&&(h.currentTarget.style.backgroundColor=at)},onMouseDown:h=>{J.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{J.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,gn.jsx)(rr,{content:te})}),ie&&(0,gn.jsx)(Sn,{status:ie,errorMessage:Be}),Ee&&(0,gn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&_e(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,gn.jsx)("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:(0,gn.jsx)(mo,{sessionId:Ee.sessionId,nonce:Ee.nonce,checkoutMode:"full",billingApiUrl:me,locale:x,theme:M,...tt?{appearance:tt}:{},buttonsTheme:he,buttonsStyles:z,initialErrorMessage:Ee.errorMessage,cardTitleContent:null,onComplete:ct,onError:He,onDecline:ot})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useElements,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}return(0,w.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&E(fr),n&&(c||a)&&E(fr),n&&(0,w.jsx)("button",{type:"button",onClick:()=>{e?.("card"),R(!0)},style:{width:"100%",...x,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:u.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,...u.cardButton},onMouseDown:h=>{h.currentTarget.style.transform="scale(0.985)"},onMouseUp:h=>{h.currentTarget.style.transform="scale(1)"},children:(0,w.jsx)(ar,{content:k})}),(0,w.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var ki=require("@flopay/shared");var er=require("react");var Pi=require("react/jsx-runtime");function fi(e,t){function n({className:c,id:a,style:l,options:p,onChange:d,onReady:k,onFocus:U,onBlur:P,onEscape:I}){let R=(0,er.useRef)(null),O=(0,er.useRef)(null),{elements:u,reportInteractive:b}=(0,er.useContext)(En);return(0,er.useEffect)(()=>{if(!u||!R.current)return;let E=!0;return(async()=>{let x=u.getElement(e);x||(x=await u.create(e,p)),!(!E||!R.current)&&(x.mount(R.current),O.current=x,d&&x.on("change",d),x.on("ready",()=>{b?.(),k?.()}),U&&x.on("focus",U),P&&x.on("blur",P),I&&x.on("escape",I))})(),()=>{if(E=!1,O.current){try{O.current.unmount()}catch{}O.current=null}}},[u,b]),(0,Pi.jsx)("div",{ref:R,className:c,id:a,style:l})}return n.displayName=t,n}var gi=fi("payment","PaymentElement"),hi=fi("address","AddressElement");var bi=require("@flopay/js"),vi=require("@flopay/shared"),mn=require("react");var pn=require("react/jsx-runtime");function Ci({sessionId:e,nonce:t,billingApiUrl:n,email:c,userId:a,firstName:l,lastName:p,chv:d,onTokenizedBody:k,onComplete:U,onErrorChange:P,isProcessing:I=!1}){let R=cn(),O=Zr(),u=eo(),[b,E]=(0,mn.useState)(!1),[x,h]=(0,mn.useState)(!1),ye=(0,mn.useRef)(!1),M=(n||u).replace(/\/+$/,""),ce=(0,mn.useCallback)(async te=>{try{let de=await new bi.PaymentAPI(M).processPayment(a??"",{sessionId:e,nonce:t,tokenizedData:te,accountData:{userId:a??"",email:c??"",firstName:l??"",lastName:p??""},chv:d});if(de.ok){U?.();return}let Y=await de.json().catch(()=>null);P?.(Y?.message??"Payment failed. Please try again.")}catch(X){P?.(X instanceof Error?X.message:"An unexpected error occurred")}},[M,e,t,a,c,l,p,d,U,P]),oe=(0,mn.useCallback)(te=>{k?k(te):ce(te)},[k,ce]);(0,mn.useEffect)(()=>{if(!R||ye.current)return;let te=new URLSearchParams(window.location.search),X=te.get("payment_intent"),de=te.get("payment_intent_client_secret"),Y=te.get("redirect_status");!X||!de||(ye.current=!0,(async()=>{try{if(h(!0),Y==="failed"){P?.("PayPal payment was declined. Please try again.");return}let G=R.getRawProvider();if(!G?.retrievePaymentIntent){P?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:pe,error:De}=await G.retrievePaymentIntent(de);if(De){P?.(De.message??"Failed to retrieve PayPal payment status.");return}if(pe&&(pe.status==="requires_capture"||pe.status==="succeeded")){let we=typeof pe.payment_method=="string"?pe.payment_method:pe.payment_method?.id;oe({id:we??pe.id,type:"card",threeDSecureActionResultTokenId:pe.id,isPaypal:!0});let ge=new URL(window.location.href);ge.searchParams.delete("payment_intent"),ge.searchParams.delete("payment_intent_client_secret"),ge.searchParams.delete("redirect_status"),window.history.replaceState({},"",ge.toString())}else P?.("PayPal payment was not completed. Please try again.")}catch(G){P?.(G instanceof Error?G.message:"Failed to complete PayPal payment.")}finally{h(!1)}})())},[R,oe,P]);let j=(0,mn.useCallback)(async()=>{if(!(!R||!O))try{if(h(!0),P?.(null),!e||!c)throw new vi.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let te=await R.confirmPayPalPayment({billingApiUrl:M,sessionId:e,nonce:t,email:c,returnUrl:window.location.href});if(te.error){P?.(te.error.message);return}te.paymentIntentId&&(te.status==="succeeded"||te.status==="processing"||te.status==="requires_capture")&&oe({id:te.paymentMethodId??te.paymentIntentId,type:"card",threeDSecureActionResultTokenId:te.paymentIntentId,isPaypal:!0})}catch(te){P?.(te instanceof Error?te.message:"PayPal payment failed. Please try again.")}finally{h(!1)}},[R,O,e,t,c,M,oe,P]);return!R||!O?(0,pn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,pn.jsxs)(pn.Fragment,{children:[!b&&(0,pn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,pn.jsx)("div",{style:b?{}:{display:"none"},children:(0,pn.jsx)("button",{type:"button",onClick:j,disabled:x||I,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:x||I?"not-allowed":"pointer",opacity:x||I?.6:1},ref:()=>E(!0),children:x?"Processing...":"PayPal"})}),(x||I)&&(0,pn.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,pn.jsx)("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..."})})]})}var Fe=require("react"),vo=require("@flopay/js"),Wt=require("@flopay/shared");var yn=require("react/jsx-runtime"),Ns=44;function Si(e){return new Promise(t=>setTimeout(t,e))}function Us(e,t){return e instanceof Wt.FloPayError?e:new Wt.FloPayError(e instanceof Error?e.message:t,"api_error")}function $s(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function qs(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 wi({sessionId:e,nonce:t,createSession:n,paymentMethodId:c,checkoutMethod:a,clientId:l,products:p,items:d,subscriptions:k,account:U,successUrl:P,cancelUrl:I,couponCodes:R,tagsData:O,utmMetadata:u,billingApiUrl:b,locale:E,theme:x,appearance:h,buttonsTheme:ye,buttonsStyles:M,onSuccess:ce,onError:oe,onDecline:j,children:te,disabled:X=!1,type:de="button",style:Y,...G}){let pe=(0,Fe.useMemo)(()=>(0,Wt.resolveBillingApiUrl)(b),[b]),De=(0,Fe.useMemo)(()=>qs({createSession:n,clientId:l,products:p,items:d,subscriptions:k,account:U,successUrl:P,cancelUrl:I,couponCodes:R,tagsData:O,utmMetadata:u}),[U,I,l,R,n,p,d,k,P,O,u]),[we,ge]=(0,Fe.useState)(!1),[ae,be]=(0,Fe.useState)(null),[Le,ie]=(0,Fe.useState)(null),[je,Oe]=(0,Fe.useState)(!1),[Ee,J]=(0,Fe.useState)(null),S=(0,Fe.useRef)(!0),se=(0,Fe.useRef)(null),Ve=(0,Fe.useRef)(Ee),Ne=(0,Fe.useRef)(ce),ue=(0,Fe.useRef)(oe),A=(0,Fe.useRef)(j);(0,Fe.useEffect)(()=>{Ve.current=Ee},[Ee]),(0,Fe.useEffect)(()=>{Ne.current=ce},[ce]),(0,Fe.useEffect)(()=>{ue.current=oe},[oe]),(0,Fe.useEffect)(()=>{A.current=j},[j]),(0,Fe.useEffect)(()=>(S.current=!0,()=>{S.current=!1,se.current?.abort()}),[]),(0,Fe.useEffect)(()=>{if(typeof window>"u")return;let _=ve=>{ve.key==="Escape"&&J(null)};return window.addEventListener("keydown",_),()=>{window.removeEventListener("keydown",_)}},[]);let le=(0,Fe.useCallback)((_,ve=Dr)=>{A.current?.(Rt(ve,_,{code:_.code,declineCode:_.declineCode}))},[]),Q=(0,Fe.useCallback)(async _=>{S.current&&(ie(null),Oe(_.result.status==="authorized"),be("success"),await Si(xn),S.current&&Ne.current?.(_))},[]),_e=(0,Fe.useCallback)(async(_,ve)=>{S.current&&(ue.current?.(_),ve?.emitDecline&&le(_,ve.method),ie(_.message),Oe(!1),be("error"),await Si(vn))},[le]),dt=(0,Fe.useCallback)(async(_,ve,Je)=>{let xe=_.data.session??null;if(!xe)throw new Wt.FloPayError("No session data returned","api_error");let vt=xe.clientSecret||t;if(dr(xe)){await Q({result:Jn(xe,ve),session:xe,sessionId:xe.id||ve,autoCompleted:!1});return}if(xe.status==="expired")throw to(xe);try{if(_.autoProcessingPending){let Ze=(await new vo.PaymentAPI(pe).waitForCheckoutSessionCompletion(_.autoProcessingPending.sessionId,{initialDelayMs:_.autoProcessingPending.retryAfterMs})).data.session;if(!dr(Ze))throw no(Ze);await Q({result:Jn(Ze,ve),session:Ze,sessionId:Ze.id||ve,autoCompleted:!1});return}if(_.autoProcessingError){if(_.autoProcessingError.type==="3ds_required"&&_.autoProcessingError.nextActionRedirectUrl&&ve&&vt){let He=new AbortController;se.current=He;let nt;try{nt=await ci({billingApiUrl:pe,sessionId:ve,nonce:vt,nextActionRedirectUrl:_.autoProcessingError.nextActionRedirectUrl,signal:He.signal})}finally{se.current===He&&(se.current=null)}if(nt.status==="declined")throw Un({type:nt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:nt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:_.autoProcessingError.checkoutMethod});let ot=(await new vo.PaymentAPI(pe).waitForCheckoutSessionCompletion(ve,{initialDelayMs:0,nonce:vt})).data.session;if(!dr(ot))throw Un({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:_.autoProcessingError.checkoutMethod});await Q({result:Jn(ot,ve),session:ot,sessionId:ot.id||ve,autoCompleted:!1});return}throw Un(_.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:_.autoProcessingError.checkoutMethod})}if(Je?.fromCreateSession&&_.autoProcessingAttempted===!0)throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let We=await yr({billingApiUrl:pe,sessionId:ve??xe.id,session:xe,nonce:vt});if(We.type!=="success")throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Q({result:We.result,session:xe,sessionId:xe.id||ve,autoCompleted:!1})}catch(We){let He=Qn(We),nt=xe.id||ve;await _e(He,{emitDecline:!0,method:He.checkoutMethod??Dr}),$s(He,nt)&&nt&&S.current&&J({sessionId:nt,errorMessage:He.message,nonce:vt||void 0})}},[t,pe,_e,Q]),Qe=(0,Fe.useCallback)(async _=>{if(G.onClick?.(_),!(_.defaultPrevented||X||we)){if(J(null),e&&De){let ve=new Wt.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await _e(ve),S.current&&(be(null),ie(null));return}if(!e&&!De){let ve=new Wt.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await _e(ve),S.current&&(be(null),ie(null));return}ge(!0),ie(null),Oe(!1),be("processing");try{let ve=new vo.PaymentAPI(pe);if(e){let Je=await ve.getUnifiedCheckoutSession(e,t);await dt(Je,e);return}try{let Je=await ve.createAndFetchSession({...De});await dt(Je,Je.data.session?.id??null,{fromCreateSession:!0})}catch(Je){if(Je instanceof Wt.FloPayError&&Je.code==="session_auto_completed"){await Q({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Je}}catch(ve){await _e(Us(ve,"Automatic payment failed. Please try again."))}finally{S.current&&(be(null),ie(null),ge(!1))}}},[G,De,X,we,t,dt,pe,e,_e,Q]),pt=(0,Fe.useCallback)(_=>{let ve=Ve.current;J(null),Ne.current?.({result:_,session:null,sessionId:ve?.sessionId??null,autoCompleted:!1})},[]),D=(0,Fe.useCallback)(_=>{ue.current?.(_)},[]),Z=(0,Fe.useCallback)(_=>{A.current?.(_)},[]),tt=(0,Fe.useMemo)(()=>(0,Wt.resolveTheme)(x),[x]),Ke=(0,Fe.useMemo)(()=>{let _=tt?.buttonsLayout??(0,Wt.resolveButtonsLayoutTheme)(ye);return M?{..._,...M,cardButton:{..._.cardButton,...M.cardButton}}:_},[tt,ye,M]),mt=(0,Fe.useMemo)(()=>{let _=tt?.appearance;return h?_?{..._,...h,variables:{..._.variables,...h.variables}}:h:_},[h,tt]),Ue=mt?.variables,Ge=Ue?.colorPrimary??"#4A49FF",Yt=Ue?.colorPrimaryHover??so(Ge,.12),Xe=Ue?.borderRadius??"8px";return(0,yn.jsxs)(yn.Fragment,{children:[(0,yn.jsx)("button",{...G,type:de,onClick:Qe,disabled:X||we,"aria-busy":we,style:{width:"100%",...te===void 0?{boxSizing:"border-box",height:Ns,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Ke.cardButton,...Vo({themeBundle:tt,resolvedPrimaryColor:Ge,resolvedBorderRadius:Xe,submitButtonStyle:Ke.submitButton,explicitPrimaryColor:Ue?.colorPrimary}),fontSize:Ke.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:X||we?"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:X||we?.6:1,...Y},onMouseEnter:_=>{G.onMouseEnter?.(_),!_.defaultPrevented&&!X&&!we&&(tt||Ue?.colorPrimary)&&(_.currentTarget.style.backgroundColor=Yt)},onMouseLeave:_=>{G.onMouseLeave?.(_),!_.defaultPrevented&&(tt||Ue?.colorPrimary)&&(_.currentTarget.style.backgroundColor=Ge)},onMouseDown:_=>{G.onMouseDown?.(_),_.defaultPrevented||(_.currentTarget.style.transform="scale(0.985)")},onMouseUp:_=>{G.onMouseUp?.(_),_.defaultPrevented||(_.currentTarget.style.transform="scale(1)")},children:(0,yn.jsx)(ar,{content:te})}),ae&&(0,yn.jsx)(Cn,{status:ae,errorMessage:Le,authorized:je}),Ee&&(0,yn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:_=>{_.target===_.currentTarget&&J(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:(0,yn.jsx)("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:(0,yn.jsx)(bo,{sessionId:Ee.sessionId,nonce:Ee.nonce,checkoutMode:"full",billingApiUrl:pe,locale:E,theme:x,...mt?{appearance:mt}:{},buttonsTheme:ye,buttonsStyles:M,initialErrorMessage:Ee.errorMessage,cardTitleContent:null,onComplete:pt,onError:D,onDecline:Z})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useElements,useFloPay,usePayPalFloPay});
|