@flopay/react 1.4.7 → 1.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var fi=Object.create;var Fr=Object.defineProperty;var gi=Object.getOwnPropertyDescriptor;var hi=Object.getOwnPropertyNames;var Pi=Object.getPrototypeOf,bi=Object.prototype.hasOwnProperty;var vi=(e,t)=>{for(var n in t)Fr(e,n,{get:t[n],enumerable:!0})},oa=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of hi(t))!bi.call(e,o)&&o!==n&&Fr(e,o,{get:()=>t[o],enumerable:!(l=gi(t,o))||l.enumerable});return e};var aa=(e,t,n)=>(n=e!=null?fi(Pi(e)):{},oa(t||!e||!e.__esModule?Fr(n,"default",{value:e,enumerable:!0}):n,e)),Ci=e=>oa(Fr({},"__esModule",{value:!0}),e);var us={};vi(us,{AddressElement:()=>Ha,DirectPayPalButton:()=>br,FloPayAutomaticPaymentButton:()=>Xa,FloPayCheckout:()=>to,FloPayProvider:()=>fr,PayPalButton:()=>Ga,PaymentElement:()=>Va,SplitCardForm:()=>Yr,VaultCardFields:()=>Lr,useCheckout:()=>ua,useElements:()=>Or,useFloPay:()=>an,usePayPalFloPay:()=>Nr});module.exports=Ci(us);var Si=()=>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,Fe=Si();var St=require("react"),ia=require("@flopay/shared");var go=require("react"),En=(0,go.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),on=(0,go.createContext)({session:null,loading:!1,error:null});var wi=Symbol.for("@flopay/js.telemetry.bridge.v1"),ki=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ri(){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 Ii(e){let t=Ri(),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 Dr(e){let t=globalThis[ki];return Ii(t?.(e)??{})}function xt(e){if(e)return e[wi]}var sa=require("react/jsx-runtime");function fr({flopay:e,paypalFlopay:t,options:n,children:l}){let[o,s]=(0,St.useState)(e instanceof Promise?null:e),[u,c]=(0,St.useState)(t instanceof Promise||!t?null:t),[R,N]=(0,St.useState)(null),m=(0,St.useRef)(null),_=(0,St.useRef)(null),w=(0,St.useRef)(null);(0,St.useEffect)(()=>{if(!o)return;let I=xt(o);return m.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),(0,St.useEffect)(()=>{let I=!1;return e instanceof Promise?e.then(F=>{I||s(F)}):s(e),()=>{I=!0}},[e]),(0,St.useEffect)(()=>{let I=!1;if(!t){c(null);return}return t instanceof Promise?t.then(F=>{I||c(F)}):c(t),()=>{I=!0}},[t]),(0,St.useEffect)(()=>{if(!o){N(null);return}let I=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return N(I),()=>{I.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,St.useEffect)(()=>{if(!o||!R||_.current===R)return;_.current=R;let I=xt(o);I?.log({name:"checkout.rendered",stage:"checkout_render"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(m.current??0),durationMode:"machine"})},[R,o]);let B=(0,St.useCallback)(()=>{if(!o||!R||w.current===R)return;w.current=R;let I=xt(o);I?.log({name:"checkout.interactive",stage:"checkout_interactive"}),I?.performance({stage:"checkout_interactive",durationMs:I.elapsed(m.current??0),durationMode:"machine"})},[R,o]),d=(0,ia.resolveBillingApiUrl)(n?.billingApiUrl),g=(0,St.useMemo)(()=>({flopay:o,paypalFlopay:u,elements:R,billingApiUrl:d,reportInteractive:B}),[o,u,R,d,B]);return(0,sa.jsx)(En.Provider,{value:g,children:l})}var L=aa(require("react"),1),wr=require("@flopay/js"),Be=require("@flopay/shared");var ks=require("react"),rt=require("react/jsx-runtime");function Ei(){return(0,rt.jsxs)(rt.Fragment,{children:[(0,rt.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,rt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,rt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,rt.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,rt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function _i(){return(0,rt.jsx)(rt.Fragment,{children:"Go back"})}function xi(){return(0,rt.jsx)(rt.Fragment,{children:"Secure card checkout"})}function Yn(e){return e!==void 0&&(e===""||e===null||e===!1)}function Gn({content:e}){return(0,rt.jsx)(rt.Fragment,{children:e===void 0?(0,rt.jsx)(Ei,{}):e})}function Jn({content:e}){return(0,rt.jsx)(rt.Fragment,{children:e===void 0?(0,rt.jsx)(_i,{}):e})}function gr({content:e}){return(0,rt.jsx)(rt.Fragment,{children:e===void 0?(0,rt.jsx)(xi,{}):e})}var ut=require("@stripe/react-stripe-js"),k=require("@flopay/shared"),ln=require("@flopay/js");var _n=require("react"),la=require("react/jsx-runtime");function Lr({capture:e,html:t,messageToken:n,expectedOrigin:l,theme:o,containerStyle:s,onReady:u,onError:c,onValidation:R}){let N=(0,_n.useRef)(null),m=(0,_n.useRef)(u),_=(0,_n.useRef)(c),w=(0,_n.useRef)(R);m.current=u,_.current=c,w.current=R;let B=(0,_n.useRef)(o);return B.current=o,(0,_n.useEffect)(()=>{let d=N.current;if(!d)return;let g=!0,I=!1,F=()=>{!g||I||(I=!0,m.current?.())},P=e.on("ready",()=>{F()}),W=e.on("error",le=>{_.current?.(le.message??"There was a problem loading the secure card form.")}),Q=e.on("validation",le=>{w.current?.(le.message??null)}),me={html:t,...n?{messageToken:n}:{},...l?{expectedOrigin:l}:{},...B.current?{theme:B.current}:{}};return e.mount(d,me).then(()=>{F()}).catch(le=>{g&&_.current?.(le instanceof Error?le.message:"Failed to load the secure card form.")}),()=>{g=!1,P(),W(),Q(),e.unmount()}},[e,t,n,l]),(0,_n.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,la.jsx)("div",{ref:N,"data-testid":"flopay-vault-card-fields",style:s})}var Bs=require("react"),hr=require("react/jsx-runtime");function Xn({children:e,margin:t,icon:n=!0,styleOverride:l}){return(0,hr.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,hr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,hr.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 ca={alipay:new URL("./payment-logos/alipay.svg",Fe).href,bancontact:new URL("./payment-logos/bancontact.svg",Fe).href,blik:new URL("./payment-logos/blik.svg",Fe).href,eps:new URL("./payment-logos/eps.svg",Fe).href,giropay:new URL("./payment-logos/giropay.svg",Fe).href,ideal:new URL("./payment-logos/ideal.svg",Fe).href,klarna:new URL("./payment-logos/klarna.svg",Fe).href,p24:new URL("./payment-logos/p24.svg",Fe).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",Fe).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",Fe).href};var r=aa(require("react"),1);var Zn=require("react"),da=require("@flopay/shared");function an(){return(0,Zn.useContext)(En).flopay}function Nr(){return(0,Zn.useContext)(En).paypalFlopay??null}function Or(){return(0,Zn.useContext)(En).elements}function ua(){return(0,Zn.useContext)(on)}function zr(){return(0,Zn.useContext)(En).billingApiUrl||(0,da.resolveBillingApiUrl)()}var Us=require("react"),yt=require("react/jsx-runtime"),xn=1200,bn=1500;function vn({status:e,errorMessage:t}){return(0,yt.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,yt.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,yt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,yt.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,yt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,yt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,yt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,yt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,yt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,yt.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,yt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,yt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,yt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,yt.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,yt.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,yt.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,yt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,yt.jsx)("style",{children:`
1
+ "use strict";var Si=Object.create;var zr=Object.defineProperty;var wi=Object.getOwnPropertyDescriptor;var ki=Object.getOwnPropertyNames;var Ri=Object.getPrototypeOf,Ii=Object.prototype.hasOwnProperty;var Ei=(e,t)=>{for(var n in t)zr(e,n,{get:t[n],enumerable:!0})},da=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ki(t))!Ii.call(e,o)&&o!==n&&zr(e,o,{get:()=>t[o],enumerable:!(l=wi(t,o))||l.enumerable});return e};var ua=(e,t,n)=>(n=e!=null?Si(Ri(e)):{},da(t||!e||!e.__esModule?zr(n,"default",{value:e,enumerable:!0}):n,e)),_i=e=>da(zr({},"__esModule",{value:!0}),e);var Ps={};Ei(Ps,{AddressElement:()=>Xa,DirectPayPalButton:()=>kr,FloPayAutomaticPaymentButton:()=>ri,FloPayCheckout:()=>io,FloPayProvider:()=>vr,PayPalButton:()=>ti,PaymentElement:()=>Ja,SplitCardForm:()=>Qr,VaultCardFields:()=>$r,useCheckout:()=>ha,useElements:()=>jr,useFloPay:()=>ln,usePayPalFloPay:()=>qr});module.exports=_i(Ps);var xi=()=>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,De=xi();var Ct=require("react"),pa=require("@flopay/shared");var So=require("react"),_n=(0,So.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),sn=(0,So.createContext)({session:null,loading:!1,error:null});var Ti=Symbol.for("@flopay/js.telemetry.bridge.v1"),Bi=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Mi(){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 Ai(e){let t=Mi(),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 Ur(e){let t=globalThis[Bi];return Ai(t?.(e)??{})}function xt(e){if(e)return e[Ti]}var ma=require("react/jsx-runtime");function vr({flopay:e,paypalFlopay:t,options:n,children:l}){let[o,s]=(0,Ct.useState)(e instanceof Promise?null:e),[u,c]=(0,Ct.useState)(t instanceof Promise||!t?null:t),[R,L]=(0,Ct.useState)(null),m=(0,Ct.useRef)(null),_=(0,Ct.useRef)(null),S=(0,Ct.useRef)(null);(0,Ct.useEffect)(()=>{if(!o)return;let I=xt(o);return m.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),(0,Ct.useEffect)(()=>{let I=!1;return e instanceof Promise?e.then(F=>{I||s(F)}):s(e),()=>{I=!0}},[e]),(0,Ct.useEffect)(()=>{let I=!1;if(!t){c(null);return}return t instanceof Promise?t.then(F=>{I||c(F)}):c(t),()=>{I=!0}},[t]),(0,Ct.useEffect)(()=>{if(!o){L(null);return}let I=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return L(I),()=>{I.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,Ct.useEffect)(()=>{if(!o||!R||_.current===R)return;_.current=R;let I=xt(o);I?.log({name:"checkout.rendered",stage:"checkout_render"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(m.current??0),durationMode:"machine"})},[R,o]);let T=(0,Ct.useCallback)(()=>{if(!o||!R||S.current===R)return;S.current=R;let I=xt(o);I?.log({name:"checkout.interactive",stage:"checkout_interactive"}),I?.performance({stage:"checkout_interactive",durationMs:I.elapsed(m.current??0),durationMode:"machine"})},[R,o]),d=(0,pa.resolveBillingApiUrl)(n?.billingApiUrl),y=(0,Ct.useMemo)(()=>({flopay:o,paypalFlopay:u,elements:R,billingApiUrl:d,reportInteractive:T}),[o,u,R,d,T]);return(0,ma.jsx)(_n.Provider,{value:y,children:l})}var D=ua(require("react"),1),_r=require("@flopay/js"),Ae=require("@flopay/shared");var Bs=require("react"),at=require("react/jsx-runtime");function Fi(){return(0,at.jsxs)(at.Fragment,{children:[(0,at.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,at.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,at.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,at.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,at.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Di(){return(0,at.jsx)(at.Fragment,{children:"Go back"})}function Li(){return(0,at.jsx)(at.Fragment,{children:"Secure card checkout"})}function Qn(e){return e!==void 0&&(e===""||e===null||e===!1)}function er({content:e}){return(0,at.jsx)(at.Fragment,{children:e===void 0?(0,at.jsx)(Fi,{}):e})}function tr({content:e}){return(0,at.jsx)(at.Fragment,{children:e===void 0?(0,at.jsx)(Di,{}):e})}function Cr({content:e}){return(0,at.jsx)(at.Fragment,{children:e===void 0?(0,at.jsx)(Li,{}):e})}var pt=require("@stripe/react-stripe-js"),k=require("@flopay/shared"),dn=require("@flopay/js");var xn=require("react"),ya=require("react/jsx-runtime");function $r({capture:e,html:t,messageToken:n,expectedOrigin:l,theme:o,containerStyle:s,onReady:u,onError:c,onValidation:R}){let L=(0,xn.useRef)(null),m=(0,xn.useRef)(u),_=(0,xn.useRef)(c),S=(0,xn.useRef)(R);m.current=u,_.current=c,S.current=R;let T=(0,xn.useRef)(o);return T.current=o,(0,xn.useEffect)(()=>{let d=L.current;if(!d)return;let y=!0,I=!1,F=()=>{!y||I||(I=!0,m.current?.())},f=e.on("ready",()=>{F()}),H=e.on("error",ne=>{_.current?.(ne.message??"There was a problem loading the secure card form.")}),X=e.on("validation",ne=>{S.current?.(ne.message??null)}),fe={html:t,...n?{messageToken:n}:{},...l?{expectedOrigin:l}:{},...T.current?{theme:T.current}:{}};return e.mount(d,fe).then(()=>{F()}).catch(ne=>{y&&_.current?.(ne instanceof Error?ne.message:"Failed to load the secure card form.")}),()=>{y=!1,f(),H(),X(),e.unmount()}},[e,t,n,l]),(0,xn.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,ya.jsx)("div",{ref:L,"data-testid":"flopay-vault-card-fields",style:s})}var Os=require("react"),Sr=require("react/jsx-runtime");function nr({children:e,margin:t,icon:n=!0,styleOverride:l}){return(0,Sr.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,Sr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Sr.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",De).href,bancontact:new URL("./payment-logos/bancontact.svg",De).href,blik:new URL("./payment-logos/blik.svg",De).href,eps:new URL("./payment-logos/eps.svg",De).href,giropay:new URL("./payment-logos/giropay.svg",De).href,ideal:new URL("./payment-logos/ideal.svg",De).href,klarna:new URL("./payment-logos/klarna.svg",De).href,p24:new URL("./payment-logos/p24.svg",De).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",De).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",De).href};var r=ua(require("react"),1);var rr=require("react"),ga=require("@flopay/shared");function ln(){return(0,rr.useContext)(_n).flopay}function qr(){return(0,rr.useContext)(_n).paypalFlopay??null}function jr(){return(0,rr.useContext)(_n).elements}function ha(){return(0,rr.useContext)(sn)}function Vr(){return(0,rr.useContext)(_n).billingApiUrl||(0,ga.resolveBillingApiUrl)()}var Ws=require("react"),ft=require("react/jsx-runtime"),Tn=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:`
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 pa=require("@flopay/shared");function ma(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 ho(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 ya(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,u)=>s+(u.overrideAmount??u.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,u)=>({uuid:`synthetic-${s.type??"item"}-${u}`,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 Po(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 Ti=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Fn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:l}of Ti)if(n.test(t))return l;return e}function Ur(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function fa(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function ga(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function $r(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 Qn(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(qr+e,JSON.stringify(t))}catch{}}function ha(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 Pa(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 T=require("react"),Ca=require("@paypal/paypal-js"),jr=require("@flopay/js"),Bn=require("@flopay/shared");function dt(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function Bi(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 Vn(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 Vn(t.code)??Vn(t.type)??Vn(t.name)}function er(e){if(!(typeof e!="object"||e===null))return Vn(e.decline_code)}function Pr(e){return typeof e!="object"||e===null?!1:Vn(e.type)?.toLowerCase()==="card_error"||er(e)!==void 0}function Dn(e){let t=Bi(e)?.toLowerCase()??"",l=`${Tn(e)?.toLowerCase()??""} ${t}`;return l.includes("popup")&&l.includes("block")}var sn=require("react/jsx-runtime"),Vr=45,Mi=1e3,Ai=11e3,Fi=["https://www.paypal.com","https://www.sandbox.paypal.com"],ba="We couldn't open PayPal. Try again or choose another payment method.",Di={width:"100%",minHeight:Vr,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()")&&Fi.some(t=>e.includes(t))&&e.includes("10000ms")}function Li(e){return e?`${ba} Allow pop-ups for this site, then try again.`:ba}function Sa({sessionId:e,nonce:t,billingApiUrl:n,email:l,clientId:o,environment:s,currency:u,isSubscription:c,onTokenizedBody:R,onComplete:N,onErrorChange:m,onDecline:_,onTechnicalFailure:w,isProcessing:B=!1,onLoadStateChange:d,onInitializationStateChange:g,allowAutomaticRetry:I=!0,onButtonClick:F,runBeforeButtonClick:P,session:W,existingOrderId:Q,telemetry:me,telemetryContext:le,debug:U=!1}){let ne=an(),Y=(0,T.useMemo)(()=>{if(ne)return null;let f=Dr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Bn.SDK_VERSION,enabled:me!==!1});return f.setCheckoutContext(le??{}),f.beginCheckout(le??{}),f},[n,ne,me,le?.checkoutMode,le?.layout]),ye=(0,T.useMemo)(()=>xt(ne),[ne]);(0,T.useEffect)(()=>()=>{Y&&Y.flush().catch(()=>{}).finally(()=>Y.destroy())},[Y]);let V=(0,T.useMemo)(()=>({error:f=>{ye?ye.error(f):Y?.error(f)},log:f=>{ye?ye.log(f):Y?.log(f)},performance:f=>{ye?ye.performance(f):Y?.performance(f)},terminal:f=>{ye?ye.terminal(f):Y?.terminal(f)},startTiming:()=>ye?.now()??Y?.now()??0,elapsed:f=>ye?.elapsed(f)??Math.max(0,(Y?.now()??f)-f)}),[ye,Y]),G=(0,T.useRef)(null),ce=(0,T.useRef)(0),De=(0,T.useRef)(null),be=(0,T.useRef)(!1),[Pe,re]=(0,T.useState)(!1),[fe,ve]=(0,T.useState)(!1),[de,Ne]=(0,T.useState)(0),Ie=(0,T.useRef)(0),[Se,E]=(0,T.useState)(!1),ie=(0,T.useRef)(!1),ue=(0,T.useRef)(!1),[ze,Oe]=(0,T.useState)(!1),[ee,A]=(0,T.useState)(!1),J=(0,T.useMemo)(()=>n.replace(/\/+$/,""),[n]),pe=(0,T.useMemo)(()=>JSON.stringify([J,o,u,s??"",c,e,Q??""]),[J,o,u,s,Q,c,e]),Ee=(0,T.useRef)(pe),ft=Ee.current!==pe,[Qe,Ze]=(0,T.useState)([]),y=f=>{U&&Ze(xe=>[...xe,`${new Date().toISOString().slice(11,23)} ${f}`])},qe=(0,T.useRef)(R),Ue=(0,T.useRef)(N),Ke=(0,T.useRef)(m),je=(0,T.useRef)(_),Ht=(0,T.useRef)(w),Pt=(0,T.useRef)(F),kt=(0,T.useRef)(d),h=(0,T.useRef)(g),we=(0,T.useRef)(P),Ve=(0,T.useRef)(W),lt=(0,T.useRef)(l),ot=(0,T.useRef)(t),et=(0,T.useRef)(null),Ge=(0,T.useRef)(0),Ce=(0,T.useRef)(null),bt=(0,T.useRef)(null),He=(0,T.useRef)(new Map),Ft=(0,T.useRef)(new Map),Rt=(0,T.useRef)(!1);(0,T.useEffect)(()=>(Rt.current=!0,()=>{Rt.current=!1}),[]),(0,T.useEffect)(()=>{qe.current=R},[R]),(0,T.useEffect)(()=>{Ue.current=N},[N]),(0,T.useEffect)(()=>{Ke.current=m},[m]),(0,T.useEffect)(()=>{je.current=_},[_]),(0,T.useEffect)(()=>{Ht.current=w},[w]),(0,T.useEffect)(()=>{Pt.current=F},[F]),(0,T.useEffect)(()=>{kt.current=d},[d]),(0,T.useEffect)(()=>{h.current=g},[g]),(0,T.useEffect)(()=>{we.current=P},[P]),(0,T.useEffect)(()=>{Ve.current=W},[W]),(0,T.useEffect)(()=>{lt.current=l},[l]),(0,T.useEffect)(()=>{ot.current=t},[t]),(0,T.useEffect)(()=>{Ie.current=de},[de]),(0,T.useEffect)(()=>{Se&&De.current?.focus()},[Se,de]);let pn=(0,T.useCallback)(()=>{window.setTimeout(()=>{De.current?.focus()},0)},[]),wn=(0,T.useCallback)(()=>{re(!1),Ne(f=>f+1)},[]),kn=(0,T.useCallback)(()=>{E(!1),(G.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??G.current)?.focus?.()},[]);(0,T.useEffect)(()=>{!Pe||!be.current||(be.current=!1,kn())},[kn,Pe,de]);let Nn=(0,T.useCallback)((f,xe)=>{let ct=Ht.current;if(ct){ct("paypal",f,xe);return}Ke.current?.(Li(xe?.popupBlocked??Dn(f)))},[]),gt=()=>{Ce.current?.timer&&(clearTimeout(Ce.current.timer),Ce.current.timer=null)},Dt=()=>{gt();let f=Ge.current+1;return Ge.current=f,bt.current=null,Ce.current={generation:f,timer:null,yieldedControl:!1},E(!1),f},Bt=f=>f!==void 0&&Ce.current?.generation!==f?!1:(gt(),Ce.current=null,bt.current=null,!0),Kt=f=>{let xe=f?.generation??Ce.current?.generation??Ge.current;(!f?.generation||Ce.current?.generation===xe)&&(gt(),Ce.current=null),bt.current=xe,f?.showRetry&&E(!0),f?.remount&&wn(),f?.focus!==!1&&pn()},Qt=f=>Ce.current?.generation===f&&bt.current!==f,mn=f=>{typeof document<"u"&&document.visibilityState!=="visible"||(gt(),f.timer=setTimeout(()=>{Ce.current?.generation===f.generation&&(Ce.current=null,bt.current=f.generation,Nn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),E(!0),wn(),pn())},600))},X=()=>{let f=Ce.current;f?.yieldedControl&&mn(f)},Mn=()=>{let f=Ce.current;f&&(f.yieldedControl=!0,gt())},yn=f=>{let xe=et.current;return xe&&Ft.current.set(f,xe),f};(0,T.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?X():Mn()};return document.addEventListener("visibilitychange",f),window.addEventListener("focus",X),window.addEventListener("blur",Mn),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("focus",X),window.removeEventListener("blur",Mn),gt()}},[]),(0,T.useEffect)(()=>{Ee.current!==pe&&(Ee.current=pe,ie.current=!1,ue.current=!1,re(!1),ve(!1),Oe(!1),h.current?.("loading"))},[pe]),(0,T.useEffect)(()=>{dt(()=>kt.current?.(Pe&&!ze))},[Pe,ze]);let Lt=(0,Bn.normalizeGatewayEnvironment)(s);(0,T.useEffect)(()=>{let f=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",xe=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(y(`mount clientId=${f} env=${s??"(unset)"}\u2192${Lt??"live"} ccy=${u} sub=${c}`),y(`ua=${xe.slice(0,80)}${xe.length>80?"\u2026":""}`),!o){y("FAIL: clientId empty \u2014 gateway misconfigured"),Oe(!0),V.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){y("FAIL: containerRef not attached");return}ce.current=V.startTiming(),V.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ct=!1,Rn=!1,Te=()=>ct||Rn,An,fn=!1,On=()=>{An=(0,Bn.generateIdempotencyKey)(),An||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),fn=!0},gn=null,Nt=!1,Tt=null,ke=!1,pt=()=>{!Tt||ke||(ke=!0,Tt.close().catch(()=>{}))},it=null,en=()=>{it!==null&&(V.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),V.performance({stage:"overlay_return",durationMs:V.elapsed(it),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),it=null)},Wt=!1,ht=G.current,qt=null,vt=null,tn=[],hn=O=>{if(!O||typeof O.getBoundingClientRect!="function")return"(no rect)";let b=O.getBoundingClientRect();return`${Math.round(b.width)}\xD7${Math.round(b.height)}`},In=O=>{if(!O)return"(empty)";try{let b=new URL(O,typeof window<"u"?window.location.href:"https://localhost"),z=b.pathname.toLowerCase();return z.includes("checkcaptcha")||z.includes("captcha")?`CAPTCHA(${b.host}${z})`:z.includes("risk")||z.includes("challenge")?`RISK(${b.host}${z})`:z.includes("smart/buttons")?`smart-buttons(${b.host})`:`${b.host}${z}`.slice(0,100)}catch{return O.slice(0,80)}},Pn=O=>{let b=O.getAttribute("src"),z=O.getAttribute("srcdoc"),he=O.getAttribute("name"),Ae=O.getAttribute("sandbox"),$e=[];return b&&$e.push(`src=${In(b)}`),z&&$e.push(`srcdoc[${z.length}ch]`),!b&&!z&&$e.push("src=(empty) srcdoc=(empty)"),he&&$e.push(`name=${he.slice(0,40)}`),Ae!==null&&$e.push(`sandbox="${Ae.slice(0,40)}"`),$e.join(" ")},jt=O=>{if(!(O instanceof HTMLIFrameElement))return"";try{let b=O.contentDocument;if(!b)return"cd=null";let z=b.body?.children.length??0,he=b.body?.innerHTML.length??0,Ae=b.head?.innerHTML.length??0;return`cd=same-origin readyState=${b.readyState} body[${z}children,${he}ch] head[${Ae}ch]`}catch(b){return`cd=cross-origin(${b.message.slice(0,30)})`}},We=[],Vt=O=>{if(Te())return;let b=O.message??String(O.error??"(no message)");b&&(b.toLowerCase().includes("paypal")||b.toLowerCase().includes("zoid")||b.toLowerCase().includes("postrobot")||b.toLowerCase().includes("storage"))&&(y(`window:error ${b.slice(0,140)}`),We.push(b))},Ot=O=>{if(Te())return;let b=O.reason instanceof Error?O.reason.message:String(O.reason??"(no reason)");b&&(b.toLowerCase().includes("paypal")||b.toLowerCase().includes("zoid")||b.toLowerCase().includes("postrobot")||b.toLowerCase().includes("storage"))&&(y(`window:rejection ${b.slice(0,140)}`),We.push(b))};U&&typeof window<"u"&&(window.addEventListener("error",Vt),window.addEventListener("unhandledrejection",Ot));let zt={value:0};if(U&&typeof PerformanceObserver<"u")try{vt=new PerformanceObserver(O=>{if(!Te())for(let b of O.getEntries()){if(!b.name.toLowerCase().includes("paypal"))continue;zt.value+=1;let z=Math.round(b.duration);y(`net ${z}ms ${b.name.slice(0,90)}`)}}),vt.observe({type:"resource",buffered:!0})}catch{}let M=()=>{for(qt?.disconnect(),qt=null,vt?.disconnect(),vt=null;tn.length;)clearTimeout(tn.pop());U&&typeof window<"u"&&(window.removeEventListener("error",Vt),window.removeEventListener("unhandledrejection",Ot))},$=O=>{if(!O)return!1;let b=O.toLowerCase();return b.includes("zoid destroyed")||b.includes("destroyed all components")||b.includes("window closed")||b.includes("detected container element removed")},q=O=>{if(Te()||$(O))return;let b=Fn(O)??O;dt(()=>Ke.current?.(b))},D=O=>{ct||(Oe(!0),O.includes("paypal_ineligible")||V.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:",O))},p=(O,b=!1)=>{if(ct)return;let z=ie.current||!I;if(Nt)return;Nt=!0,Rn=!0,M(),pt();let he=b||va(O);if(he&&I&&!ie.current){ie.current=!0,re(!1),A(!1),ve(!0),h.current?.("retrying"),gn=setTimeout(()=>{ct||Ne(Ae=>Ae+1)},Mi);return}if(he||z){if(re(!1),A(!1),ve(!1),Oe(!0),h.current?.("exhausted"),!ue.current){ue.current=!0;let Ae=va(O)?"paypal_init_timeout":b?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",Ae)}return}D(O)};Oe(!1);let K=async(O,b=et.current)=>{if(Te())return;let z=b?.sessionId??e;if(qe.current){await qe.current(O,{sessionId:z,accountPatch:b?.accountPatch,nonce:b?.nonce});return}let he=V.startTiming();V.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Ae=()=>{V.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),V.performance({stage:"processing",durationMs:V.elapsed(he),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let $e=Ve.current,nn=b?.accountPatch?.email??lt.current,x=b?.accountPatch?.userId??$e?.customer?.id??$e?.accountData?.userId??"",oe=await new jr.PaymentAPI(J,{telemetry:!1}).processPayment(x,{sessionId:z,nonce:b?.nonce??ot.current,tokenizedData:O,accountData:{userId:x,email:nn??$e?.customer?.email??"",firstName:b?.accountPatch?.firstName??$e?.customer?.firstName??$e?.accountData?.firstName??"",lastName:b?.accountPatch?.lastName??$e?.customer?.lastName??$e?.accountData?.lastName??"",country:b?.accountPatch?.country??$e?.customer?.country??$e?.accountData?.country??void 0,zip:b?.accountPatch?.zip??$e?.customer?.zip??$e?.accountData?.zip??void 0}});if(oe.ok){if(Rn||ct&&Rt.current)return;Ae(),V.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),dt(()=>Ue.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Te())return;let Re=await oe.json().catch(()=>null),Yt=Re?.message??"PayPal payment failed.",Gt=Fn(Yt)??Yt;Ae(),oe.status===400&&(typeof Re?.declineCode=="string"||!Array.isArray(Re?.fields))?V.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):oe.status===400||oe.status===422?V.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):V.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:oe.status>=500?"5xx":oe.status>=400?"4xx":oe.status>=300?"3xx":"unknown",failureCategory:oe.status>=500?"server_error":void 0}),q(Gt),dt(()=>je.current?.(wt("paypal",Gt,{code:Re?.code,declineCode:Re?.declineCode})));return}catch($e){if(Te())return;Ae(),V.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let nn=$e instanceof Error?$e.message:"PayPal payment failed.",x=Fn(nn)??nn;q(x),dt(()=>je.current?.(wt("paypal",x)));return}},v=()=>new Bn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Me=O=>Te()?Promise.reject(v()):Promise.resolve(O),Z=async O=>{if(Te())throw v();fn||On();let b=et.current,z=b?.sessionId??e,he=b?.nonce??ot.current;V.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Ae=await new jr.PaymentAPI(J,{telemetry:!1}).createSessionIntent(z,he??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:An});if(Te())throw v();if(Ae.provider!=="paypal")throw new Error(O);return V.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Ae.providerObjectId},Ye=(O,b)=>{let z=b?.nonce??ot.current;if(!z)return;let he=b?.sessionId??e,Ae=er(O)??Tn(O)??"provider_declined";new jr.PaymentAPI(J,{telemetry:!1}).reportSessionIntentDecline(he,z,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ae}).catch(()=>{})},te=de;y("loadScript:scheduled (deferred 1 tick)");let Ut=null,st=setTimeout(()=>{if(ct){y("loadScript:skipped (cancelled before defer ran)");return}y("loadScript:start");let O=Lt==="live"?"production":Lt;Ut=(0,Ca.loadScript)({clientId:o,currency:u,intent:c?"subscription":"capture",vault:c?!0:void 0,...O?{environment:O}:{},...O==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Ut.then(b=>{if(y(`loadScript:resolved inactive=${Te()} ns=${!!b} buttons=${!!b?.Buttons}`),Te())return;if(!b?.Buttons){y("FAIL: namespace missing Buttons factory"),p("PayPal SDK did not expose the Buttons factory.");return}V.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let z=async x=>{if(Te()||Ie.current!==te)return;let ge=x.subscriptionID??x.orderID??"",oe=ge?Ft.current.get(ge):He.current.get(te);if(!(!oe||!Qt(oe.generation))&&Bt(oe.generation)){Ft.current.delete(ge),He.current.delete(oe.surfaceKey),en();try{if(A(!0),dt(()=>Ke.current?.(null)),!ge)throw new Bn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await K({id:ge,isPaypal:!0},oe)}catch(Re){q(Re instanceof Error?Re.message:"PayPal capture failed.")}finally{Te()||A(!1)}}},he=b.Buttons({style:{layout:"horizontal",height:Vr,tagline:!1},onClick:async(x,ge)=>{if(Te()){await ge.reject();return}On();let oe=we.current,Re={};if(oe)try{let tt=await oe("paypal");if(Te()){await ge.reject();return}if(!tt.proceed){et.current=null,He.current.delete(te),await ge.reject();return}Re={sessionId:tt.sessionId,accountPatch:tt.accountPatch,nonce:tt.nonce}}catch(tt){y(`onClick:runBeforeButtonClick rejected msg=${(tt instanceof Error?tt.message:String(tt)).slice(0,120)}`),et.current=null,He.current.delete(te),await ge.reject();return}dt(()=>Pt.current?.("paypal"));let Gt={generation:Dt(),surfaceKey:te,...Re};et.current=Gt,He.current.set(te,Gt),await ge.resolve(),V.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),V.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),V.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),it=V.startTiming()},createOrder:c?void 0:Q?()=>Me(Q).then(yn):()=>Z("Failed to create PayPal order.").then(yn),createSubscription:c?Q?()=>Me(Q).then(yn):()=>Z("Failed to create PayPal subscription.").then(yn):void 0,onApprove:z,onCancel:()=>{if(Te())return;let x=He.current.get(te)??et.current;x&&He.current.delete(x.surfaceKey),et.current=null,en(),V.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be.current=!0,Kt({generation:x?.generation,remount:!0,focus:!1})},onError:x=>{if(Te()||Ie.current!==te)return;let ge=x instanceof Error?x.message:"PayPal failed to render.";if(y(`onError rendered=${Wt} msg=${ge.slice(0,120)}`),Wt){let oe=He.current.get(te)??et.current;if(oe&&!Qt(oe.generation)||!oe&&bt.current===Ge.current)return;if($(ge)){Bt(oe?.generation);return}if(en(),Pr(x)){V.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ye(x,oe),dt(()=>je.current?.(wt("paypal",ge))),oe&&He.current.delete(oe.surfaceKey),et.current=null,Bt(oe?.generation);return}let Re=ge.toLowerCase();V.error({errorCode:Re.includes("popup")&&Re.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),oe&&He.current.delete(oe.surfaceKey),et.current=null,Kt({generation:oe?.generation,remount:!0,showRetry:!0,focus:!0}),Nn(x,{code:"paypal_runtime_failed"});return}p(ge)}}),Ae=he.isEligible();if(y(`isEligible=${Ae}`),V.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Ae){re(!1),p("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Tt=he,U&&y(`container:dims ${hn(ht)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),U&&typeof MutationObserver<"u"&&(qt=new MutationObserver(x=>{if(!Te()){for(let ge of x)if(ge.type==="childList")ge.addedNodes.forEach(oe=>{if(!(oe instanceof Element))return;let Re=oe.tagName.toLowerCase(),Yt=(oe.getAttribute("title")??"").slice(0,40),Gt=Re==="iframe"?` ${Pn(oe)}`:"";y(`child+ ${Re}${Yt?` title="${Yt}"`:""}${Gt} dims=${hn(oe)}`)});else if(ge.type==="attributes"&&ge.target instanceof Element){let oe=ge.target;if(oe.tagName.toLowerCase()!=="iframe")continue;let Re=ge.attributeName;(Re==="src"||Re==="srcdoc")&&y(`attr~ iframe ${Re}=${Re==="srcdoc"?`[${(oe.getAttribute("srcdoc")??"").length}ch]`:In(oe.getAttribute("src"))} dims=${hn(oe)}`)}}}),qt.observe(ht,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let nn=x=>{if(Te()||Wt)return;let ge=ht.querySelectorAll("iframe"),oe=typeof document<"u"&&"hasStorageAccess"in document;y(`watchdog:${x} container=${hn(ht)} children=${ht.childElementCount} iframes=${ge.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${oe} paypalNetRequests=${zt.value}`),ge.forEach((Re,Yt)=>{let Gt=(Re.getAttribute("title")??"").slice(0,40);y(` iframe[${Yt}] ${hn(Re)}${Gt?` title="${Gt}"`:""} ${Pn(Re)}`);let tt=jt(Re);tt&&y(` ${tt}`)}),We.length===0&&y(" (no PayPal/zoid window errors captured)")};U&&(tn.push(setTimeout(()=>nn("3s"),3e3)),tn.push(setTimeout(()=>nn("8s"),8e3)),tn.push(setTimeout(()=>nn("15s"),15e3))),y("render:start"),tn.push(setTimeout(()=>{Te()||Wt||(y("watchdog:11s retryable render timeout"),p("PayPal Buttons render did not settle within 11000ms.",!0))},Ai)),he.render(ht).then(()=>{if(y(`render:resolved inactive=${Te()}`),M(),Te()){pt();return}Wt=!0,re(!0),ve(!1),h.current?.("ready"),V.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),V.performance({stage:"provider_ready",durationMs:V.elapsed(ce.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(x=>{let ge=x instanceof Error?x.message:"PayPal failed to render.";y(`render:rejected msg=${ge.slice(0,120)}`),M(),p(ge)})}).catch(b=>{let z=b instanceof Error?b.message:"PayPal SDK failed to load.";y(`loadScript:rejected msg=${z.slice(0,120)}`),p(z)})},0);return()=>{ct=!0,clearTimeout(st),gn&&clearTimeout(gn),M(),pt()}},[I,J,o,u,s,c,e,Q,de,V]);let at=U?(0,sn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ze?"#fef2f2":"#f3f4f6",border:`1px solid ${ze?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Pe} failed=${ze})`,Qe.length===0?`
6
+ `})]})})}var Pa=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 wo(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function va(e,t){let n=e.products??[...(e.subscriptions??[]).map(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,u)=>s+(u.overrideAmount??u.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,u)=>({uuid:`synthetic-${s.type??"item"}-${u}`,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 ko(e,t){return t?{...e,...t}:e}function St(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 Ni=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Dn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:l}of Ni)if(n.test(t))return l;return e}function Hr(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Ca(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Sa(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Kr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Wr="flopay_recent_completion_";function or(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Wr+e,JSON.stringify(t))}catch{}}function wa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Wr+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Wr+e),!1):!0}catch{return!1}}function ka(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 x=require("react"),Ea=require("@paypal/paypal-js"),Yr=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 Oi(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 Wn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Bn(e){if(typeof e!="object"||e===null)return;let t=e;return Wn(t.code)??Wn(t.type)??Wn(t.name)}function ar(e){if(!(typeof e!="object"||e===null))return Wn(e.decline_code)}function wr(e){return typeof e!="object"||e===null?!1:Wn(e.type)?.toLowerCase()==="card_error"||ar(e)!==void 0}function Ln(e){let t=Oi(e)?.toLowerCase()??"",l=`${Bn(e)?.toLowerCase()??""} ${t}`;return l.includes("popup")&&l.includes("block")}var cn=require("react/jsx-runtime"),Gr=45,zi=1e3,Ui=11e3,$i=["https://www.paypal.com","https://www.sandbox.paypal.com"],Ra="We couldn't open PayPal. Try again or choose another payment method.",qi={width:"100%",minHeight:Gr,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 Ia(e){return e.includes("No ack for postMessage init()")&&$i.some(t=>e.includes(t))&&e.includes("10000ms")}function ji(e){return e?`${Ra} Allow pop-ups for this site, then try again.`:Ra}function _a({sessionId:e,nonce:t,billingApiUrl:n,email:l,clientId:o,environment:s,currency:u,isSubscription:c,onTokenizedBody:R,onComplete:L,onErrorChange:m,onDecline:_,onTechnicalFailure:S,isProcessing:T=!1,onLoadStateChange:d,onInitializationStateChange:y,allowAutomaticRetry:I=!0,onButtonClick:F,runBeforeButtonClick:f,session:H,existingOrderId:X,telemetry:fe,telemetryContext:ne,debug:N=!1}){let ee=ln(),K=(0,x.useMemo)(()=>{if(ee)return null;let B=Ur({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Mn.SDK_VERSION,enabled:fe!==!1});return B.setCheckoutContext(ne??{}),B.beginCheckout(ne??{}),B},[n,ee,fe,ne?.checkoutMode,ne?.layout]),ge=(0,x.useMemo)(()=>xt(ee),[ee]);(0,x.useEffect)(()=>()=>{K&&K.flush().catch(()=>{}).finally(()=>K.destroy())},[K]);let q=(0,x.useMemo)(()=>({error:B=>{ge?ge.error(B):K?.error(B)},log:B=>{ge?ge.log(B):K?.log(B)},performance:B=>{ge?ge.performance(B):K?.performance(B)},terminal:B=>{ge?ge.terminal(B):K?.terminal(B)},startTiming:()=>ge?.now()??K?.now()??0,elapsed:B=>ge?.elapsed(B)??Math.max(0,(K?.now()??B)-B)}),[ge,K]),W=(0,x.useRef)(null),se=(0,x.useRef)(0),Le=(0,x.useRef)(null),be=(0,x.useRef)(!1),[Pe,te]=(0,x.useState)(!1),[he,Ce]=(0,x.useState)(!1),[le,Oe]=(0,x.useState)(0),Ee=(0,x.useRef)(0),[ke,E]=(0,x.useState)(!1),oe=(0,x.useRef)(!1),de=(0,x.useRef)(!1),[$e,ze]=(0,x.useState)(!1),[Z,A]=(0,x.useState)(!1),Y=(0,x.useMemo)(()=>n.replace(/\/+$/,""),[n]),ue=(0,x.useMemo)(()=>JSON.stringify([Y,o,u,s??"",c,e,X??""]),[Y,o,u,s,X,c,e]),_e=(0,x.useRef)(ue),st=_e.current!==ue,[tt,et]=(0,x.useState)([]),p=B=>{N&&et(Xe=>[...Xe,`${new Date().toISOString().slice(11,23)} ${B}`])},je=(0,x.useRef)(R),qe=(0,x.useRef)(L),Ge=(0,x.useRef)(m),Ve=(0,x.useRef)(_),Wt=(0,x.useRef)(S),ht=(0,x.useRef)(F),wt=(0,x.useRef)(d),g=(0,x.useRef)(y),Re=(0,x.useRef)(f),He=(0,x.useRef)(H),lt=(0,x.useRef)(l),it=(0,x.useRef)(t),nt=(0,x.useRef)(null),Je=(0,x.useRef)(0),Se=(0,x.useRef)(null),Pt=(0,x.useRef)(null),Ke=(0,x.useRef)(new Map),zt=(0,x.useRef)(new Map),kt=(0,x.useRef)(!1);(0,x.useEffect)(()=>(kt.current=!0,()=>{kt.current=!1}),[]),(0,x.useEffect)(()=>{je.current=R},[R]),(0,x.useEffect)(()=>{qe.current=L},[L]),(0,x.useEffect)(()=>{Ge.current=m},[m]),(0,x.useEffect)(()=>{Ve.current=_},[_]),(0,x.useEffect)(()=>{Wt.current=S},[S]),(0,x.useEffect)(()=>{ht.current=F},[F]),(0,x.useEffect)(()=>{wt.current=d},[d]),(0,x.useEffect)(()=>{g.current=y},[y]),(0,x.useEffect)(()=>{Re.current=f},[f]),(0,x.useEffect)(()=>{He.current=H},[H]),(0,x.useEffect)(()=>{lt.current=l},[l]),(0,x.useEffect)(()=>{it.current=t},[t]),(0,x.useEffect)(()=>{Ee.current=le},[le]),(0,x.useEffect)(()=>{ke&&Le.current?.focus()},[ke,le]);let yn=(0,x.useCallback)(()=>{window.setTimeout(()=>{Le.current?.focus()},0)},[]),Rn=(0,x.useCallback)(()=>{te(!1),Oe(B=>B+1)},[]),In=(0,x.useCallback)(()=>{E(!1),(W.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??W.current)?.focus?.()},[]);(0,x.useEffect)(()=>{!Pe||!be.current||(be.current=!1,In())},[In,Pe,le]);let On=(0,x.useCallback)((B,Xe)=>{let Ie=Wt.current;if(Ie){Ie("paypal",B,Xe);return}Ge.current?.(ji(Xe?.popupBlocked??Ln(B)))},[]),gt=()=>{Se.current?.timer&&(clearTimeout(Se.current.timer),Se.current.timer=null)},Ut=()=>{gt();let B=Je.current+1;return Je.current=B,Pt.current=null,Se.current={generation:B,timer:null,yieldedControl:!1},E(!1),B},Mt=B=>B!==void 0&&Se.current?.generation!==B?!1:(gt(),Se.current=null,Pt.current=null,!0),Yt=B=>{let Xe=B?.generation??Se.current?.generation??Je.current;(!B?.generation||Se.current?.generation===Xe)&&(gt(),Se.current=null),Pt.current=Xe,B?.showRetry&&E(!0),B?.remount&&Rn(),B?.focus!==!1&&yn()},tn=B=>Se.current?.generation===B&&Pt.current!==B,fn=B=>{typeof document<"u"&&document.visibilityState!=="visible"||(gt(),B.timer=setTimeout(()=>{Se.current?.generation===B.generation&&(Se.current=null,Pt.current=B.generation,On(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),E(!0),Rn(),yn())},600))},G=()=>{let B=Se.current;B?.yieldedControl&&fn(B)},An=()=>{let B=Se.current;B&&(B.yieldedControl=!0,gt())},gn=B=>{let Xe=nt.current;return Xe&&zt.current.set(B,Xe),B};(0,x.useEffect)(()=>{let B=()=>{document.visibilityState==="visible"?G():An()};return document.addEventListener("visibilitychange",B),window.addEventListener("focus",G),window.addEventListener("blur",An),()=>{document.removeEventListener("visibilitychange",B),window.removeEventListener("focus",G),window.removeEventListener("blur",An),gt()}},[]),(0,x.useEffect)(()=>{_e.current!==ue&&(_e.current=ue,oe.current=!1,de.current=!1,te(!1),Ce(!1),ze(!1),g.current?.("loading"))},[ue]),(0,x.useEffect)(()=>{ut(()=>wt.current?.(Pe&&!$e))},[Pe,$e]);let $t=(0,Mn.normalizeGatewayEnvironment)(s);(0,x.useEffect)(()=>{let B=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",Xe=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(p(`mount clientId=${B} env=${s??"(unset)"}\u2192${$t??"live"} ccy=${u} sub=${c}`),p(`ua=${Xe.slice(0,80)}${Xe.length>80?"\u2026":""}`),!o){p("FAIL: clientId empty \u2014 gateway misconfigured"),ze(!0),q.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!W.current){p("FAIL: containerRef not attached");return}se.current=q.startTiming(),q.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ie=!1,Fn=!1,We=()=>Ie||Fn,zn,hn=!1,Pn=()=>{zn=(0,Mn.generateIdempotencyKey)(),zn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),hn=!0},rt=null,Rt=!1,qt=null,At=!1,Gt=()=>{!qt||At||(At=!0,qt.close().catch(()=>{}))},nn=null,En=()=>{nn!==null&&(q.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),q.performance({stage:"overlay_return",durationMs:q.elapsed(nn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),nn=null)},Jt=!1,Ft=W.current,Xt=null,ve=null,mt=[],ct=z=>{if(!z||typeof z.getBoundingClientRect!="function")return"(no rect)";let P=z.getBoundingClientRect();return`${Math.round(P.width)}\xD7${Math.round(P.height)}`},bn=z=>{if(!z)return"(empty)";try{let P=new URL(z,typeof window<"u"?window.location.href:"https://localhost"),w=P.pathname.toLowerCase();return w.includes("checkcaptcha")||w.includes("captcha")?`CAPTCHA(${P.host}${w})`:w.includes("risk")||w.includes("challenge")?`RISK(${P.host}${w})`:w.includes("smart/buttons")?`smart-buttons(${P.host})`:`${P.host}${w}`.slice(0,100)}catch{return z.slice(0,80)}},Un=z=>{let P=z.getAttribute("src"),w=z.getAttribute("srcdoc"),me=z.getAttribute("name"),J=z.getAttribute("sandbox"),Ye=[];return P&&Ye.push(`src=${bn(P)}`),w&&Ye.push(`srcdoc[${w.length}ch]`),!P&&!w&&Ye.push("src=(empty) srcdoc=(empty)"),me&&Ye.push(`name=${me.slice(0,40)}`),J!==null&&Ye.push(`sandbox="${J.slice(0,40)}"`),Ye.join(" ")},Dt=z=>{if(!(z instanceof HTMLIFrameElement))return"";try{let P=z.contentDocument;if(!P)return"cd=null";let w=P.body?.children.length??0,me=P.body?.innerHTML.length??0,J=P.head?.innerHTML.length??0;return`cd=same-origin readyState=${P.readyState} body[${w}children,${me}ch] head[${J}ch]`}catch(P){return`cd=cross-origin(${P.message.slice(0,30)})`}},Vt=[],bt=z=>{if(We())return;let P=z.message??String(z.error??"(no message)");P&&(P.toLowerCase().includes("paypal")||P.toLowerCase().includes("zoid")||P.toLowerCase().includes("postrobot")||P.toLowerCase().includes("storage"))&&(p(`window:error ${P.slice(0,140)}`),Vt.push(P))},Jn=z=>{if(We())return;let P=z.reason instanceof Error?z.reason.message:String(z.reason??"(no reason)");P&&(P.toLowerCase().includes("paypal")||P.toLowerCase().includes("zoid")||P.toLowerCase().includes("postrobot")||P.toLowerCase().includes("storage"))&&(p(`window:rejection ${P.slice(0,140)}`),Vt.push(P))};N&&typeof window<"u"&&(window.addEventListener("error",bt),window.addEventListener("unhandledrejection",Jn));let Ht={value:0};if(N&&typeof PerformanceObserver<"u")try{ve=new PerformanceObserver(z=>{if(!We())for(let P of z.getEntries()){if(!P.name.toLowerCase().includes("paypal"))continue;Ht.value+=1;let w=Math.round(P.duration);p(`net ${w}ms ${P.name.slice(0,90)}`)}}),ve.observe({type:"resource",buffered:!0})}catch{}let M=()=>{for(Xt?.disconnect(),Xt=null,ve?.disconnect(),ve=null;mt.length;)clearTimeout(mt.pop());N&&typeof window<"u"&&(window.removeEventListener("error",bt),window.removeEventListener("unhandledrejection",Jn))},Q=z=>{if(!z)return!1;let P=z.toLowerCase();return P.includes("zoid destroyed")||P.includes("destroyed all components")||P.includes("window closed")||P.includes("detected container element removed")},j=z=>{if(We()||Q(z))return;let P=Dn(z)??z;ut(()=>Ge.current?.(P))},b=z=>{Ie||(ze(!0),z.includes("paypal_ineligible")||q.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:",z))},ce=(z,P=!1)=>{if(Ie)return;let w=oe.current||!I;if(Rt)return;Rt=!0,Fn=!0,M(),Gt();let me=P||Ia(z);if(me&&I&&!oe.current){oe.current=!0,te(!1),A(!1),Ce(!0),g.current?.("retrying"),rt=setTimeout(()=>{Ie||Oe(J=>J+1)},zi);return}if(me||w){if(te(!1),A(!1),Ce(!1),ze(!0),g.current?.("exhausted"),!de.current){de.current=!0;let J=Ia(z)?"paypal_init_timeout":P?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",J)}return}b(z)};ze(!1);let $=async(z,P=nt.current)=>{if(We())return;let w=P?.sessionId??e;if(je.current){await je.current(z,{sessionId:w,accountPatch:P?.accountPatch,nonce:P?.nonce});return}let me=q.startTiming();q.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let J=()=>{q.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),q.performance({stage:"processing",durationMs:q.elapsed(me),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Ye=He.current,dt=P?.accountPatch?.email??lt.current,Me=P?.accountPatch?.userId??Ye?.customer?.id??Ye?.accountData?.userId??"",ae=await new Yr.PaymentAPI(Y,{telemetry:!1}).processPayment(Me,{sessionId:w,nonce:P?.nonce??it.current,tokenizedData:z,accountData:{userId:Me,email:dt??Ye?.customer?.email??"",firstName:P?.accountPatch?.firstName??Ye?.customer?.firstName??Ye?.accountData?.firstName??"",lastName:P?.accountPatch?.lastName??Ye?.customer?.lastName??Ye?.accountData?.lastName??"",country:P?.accountPatch?.country??Ye?.customer?.country??Ye?.accountData?.country??void 0,zip:P?.accountPatch?.zip??Ye?.customer?.zip??Ye?.accountData?.zip??void 0}});if(ae.ok){if(Fn||Ie&&kt.current)return;J(),q.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ut(()=>qe.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(We())return;let Fe=await ae.json().catch(()=>null),rn=Fe?.message??"PayPal payment failed.",Kt=Dn(rn)??rn;J(),ae.status===400&&(typeof Fe?.declineCode=="string"||!Array.isArray(Fe?.fields))?q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ae.status===400||ae.status===422?q.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):q.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ae.status>=500?"5xx":ae.status>=400?"4xx":ae.status>=300?"3xx":"unknown",failureCategory:ae.status>=500?"server_error":void 0}),j(Kt),ut(()=>Ve.current?.(St("paypal",Kt,{code:Fe?.code,declineCode:Fe?.declineCode})));return}catch(Ye){if(We())return;J(),q.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let dt=Ye instanceof Error?Ye.message:"PayPal payment failed.",Me=Dn(dt)??dt;j(Me),ut(()=>Ve.current?.(St("paypal",Me)));return}},h=()=>new Mn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Be=z=>We()?Promise.reject(h()):Promise.resolve(z),pe=async z=>{if(We())throw h();hn||Pn();let P=nt.current,w=P?.sessionId??e,me=P?.nonce??it.current;q.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let J=await new Yr.PaymentAPI(Y,{telemetry:!1}).createSessionIntent(w,me??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:zn});if(We())throw h();if(J.provider!=="paypal")throw new Error(z);return q.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),J.providerObjectId},Ue=(z,P)=>{let w=P?.nonce??it.current;if(!w)return;let me=P?.sessionId??e,J=ar(z)??Bn(z)??"provider_declined";new Yr.PaymentAPI(Y,{telemetry:!1}).reportSessionIntentDecline(me,w,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:J}).catch(()=>{})},xe=le;p("loadScript:scheduled (deferred 1 tick)");let O=null,Bt=setTimeout(()=>{if(Ie){p("loadScript:skipped (cancelled before defer ran)");return}p("loadScript:start");let z=$t==="live"?"production":$t;O=(0,Ea.loadScript)({clientId:o,currency:u,intent:c?"subscription":"capture",vault:c?!0:void 0,...z?{environment:z}:{},...z==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),O.then(P=>{if(p(`loadScript:resolved inactive=${We()} ns=${!!P} buttons=${!!P?.Buttons}`),We())return;if(!P?.Buttons){p("FAIL: namespace missing Buttons factory"),ce("PayPal SDK did not expose the Buttons factory.");return}q.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let w=async Me=>{if(We()||Ee.current!==xe)return;let we=Me.subscriptionID??Me.orderID??"",ae=we?zt.current.get(we):Ke.current.get(xe);if(!(!ae||!tn(ae.generation))&&Mt(ae.generation)){zt.current.delete(we),Ke.current.delete(ae.surfaceKey),En();try{if(A(!0),ut(()=>Ge.current?.(null)),!we)throw new Mn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await $({id:we,isPaypal:!0},ae)}catch(Fe){j(Fe instanceof Error?Fe.message:"PayPal capture failed.")}finally{We()||A(!1)}}},me=P.Buttons({style:{layout:"horizontal",height:Gr,tagline:!1},onClick:async(Me,we)=>{if(We()){await we.reject();return}Pn();let ae=Re.current,Fe={};if(ae)try{let Lt=await ae("paypal");if(We()){await we.reject();return}if(!Lt.proceed){nt.current=null,Ke.current.delete(xe),await we.reject();return}Fe={sessionId:Lt.sessionId,accountPatch:Lt.accountPatch,nonce:Lt.nonce}}catch(Lt){p(`onClick:runBeforeButtonClick rejected msg=${(Lt instanceof Error?Lt.message:String(Lt)).slice(0,120)}`),nt.current=null,Ke.current.delete(xe),await we.reject();return}ut(()=>ht.current?.("paypal"));let Kt={generation:Ut(),surfaceKey:xe,...Fe};nt.current=Kt,Ke.current.set(xe,Kt),await we.resolve(),q.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),q.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),q.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),nn=q.startTiming()},createOrder:c?void 0:X?()=>Be(X).then(gn):()=>pe("Failed to create PayPal order.").then(gn),createSubscription:c?X?()=>Be(X).then(gn):()=>pe("Failed to create PayPal subscription.").then(gn):void 0,onApprove:w,onCancel:()=>{if(We())return;let Me=Ke.current.get(xe)??nt.current;Me&&Ke.current.delete(Me.surfaceKey),nt.current=null,En(),q.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be.current=!0,Yt({generation:Me?.generation,remount:!0,focus:!1})},onError:Me=>{if(We()||Ee.current!==xe)return;let we=Me instanceof Error?Me.message:"PayPal failed to render.";if(p(`onError rendered=${Jt} msg=${we.slice(0,120)}`),Jt){let ae=Ke.current.get(xe)??nt.current;if(ae&&!tn(ae.generation)||!ae&&Pt.current===Je.current)return;if(Q(we)){Mt(ae?.generation);return}if(En(),wr(Me)){q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ue(Me,ae),ut(()=>Ve.current?.(St("paypal",we))),ae&&Ke.current.delete(ae.surfaceKey),nt.current=null,Mt(ae?.generation);return}let Fe=we.toLowerCase();q.error({errorCode:Fe.includes("popup")&&Fe.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ae&&Ke.current.delete(ae.surfaceKey),nt.current=null,Yt({generation:ae?.generation,remount:!0,showRetry:!0,focus:!0}),On(Me,{code:"paypal_runtime_failed"});return}ce(we)}}),J=me.isEligible();if(p(`isEligible=${J}`),q.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!J){te(!1),ce("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}qt=me,N&&p(`container:dims ${ct(Ft)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),N&&typeof MutationObserver<"u"&&(Xt=new MutationObserver(Me=>{if(!We()){for(let we of Me)if(we.type==="childList")we.addedNodes.forEach(ae=>{if(!(ae instanceof Element))return;let Fe=ae.tagName.toLowerCase(),rn=(ae.getAttribute("title")??"").slice(0,40),Kt=Fe==="iframe"?` ${Un(ae)}`:"";p(`child+ ${Fe}${rn?` title="${rn}"`:""}${Kt} dims=${ct(ae)}`)});else if(we.type==="attributes"&&we.target instanceof Element){let ae=we.target;if(ae.tagName.toLowerCase()!=="iframe")continue;let Fe=we.attributeName;(Fe==="src"||Fe==="srcdoc")&&p(`attr~ iframe ${Fe}=${Fe==="srcdoc"?`[${(ae.getAttribute("srcdoc")??"").length}ch]`:bn(ae.getAttribute("src"))} dims=${ct(ae)}`)}}}),Xt.observe(Ft,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let dt=Me=>{if(We()||Jt)return;let we=Ft.querySelectorAll("iframe"),ae=typeof document<"u"&&"hasStorageAccess"in document;p(`watchdog:${Me} container=${ct(Ft)} children=${Ft.childElementCount} iframes=${we.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${ae} paypalNetRequests=${Ht.value}`),we.forEach((Fe,rn)=>{let Kt=(Fe.getAttribute("title")??"").slice(0,40);p(` iframe[${rn}] ${ct(Fe)}${Kt?` title="${Kt}"`:""} ${Un(Fe)}`);let Lt=Dt(Fe);Lt&&p(` ${Lt}`)}),Vt.length===0&&p(" (no PayPal/zoid window errors captured)")};N&&(mt.push(setTimeout(()=>dt("3s"),3e3)),mt.push(setTimeout(()=>dt("8s"),8e3)),mt.push(setTimeout(()=>dt("15s"),15e3))),p("render:start"),mt.push(setTimeout(()=>{We()||Jt||(p("watchdog:11s retryable render timeout"),ce("PayPal Buttons render did not settle within 11000ms.",!0))},Ui)),me.render(Ft).then(()=>{if(p(`render:resolved inactive=${We()}`),M(),We()){Gt();return}Jt=!0,te(!0),Ce(!1),g.current?.("ready"),q.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),q.performance({stage:"provider_ready",durationMs:q.elapsed(se.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(Me=>{let we=Me instanceof Error?Me.message:"PayPal failed to render.";p(`render:rejected msg=${we.slice(0,120)}`),M(),ce(we)})}).catch(P=>{let w=P instanceof Error?P.message:"PayPal SDK failed to load.";p(`loadScript:rejected msg=${w.slice(0,120)}`),ce(w)})},0);return()=>{Ie=!0,clearTimeout(Bt),rt&&clearTimeout(rt),M(),Gt()}},[I,Y,o,u,s,c,e,X,le,q]);let Tt=N?(0,cn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:$e?"#fef2f2":"#f3f4f6",border:`1px solid ${$e?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Pe} failed=${$e})`,tt.length===0?`
7
7
  (waiting for first lifecycle event\u2026)`:`
8
- ${Qe.join(`
9
- `)}`]}):null;return ze&&!ft?U?(0,sn.jsx)("div",{children:at}):null:(0,sn.jsxs)("div",{children:[at,(0,sn.jsxs)("div",{"aria-hidden":fe?!0:void 0,style:fe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Vr},children:[!Pe&&!fe&&(0,sn.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,sn.jsx)("div",{ref:G,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:Vr,display:"flex",opacity:Pe?1:0},"aria-busy":ee||B},de)]},de),Se&&(0,sn.jsx)("button",{ref:De,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:kn,style:Di,children:"Try PayPal again"})]})}function br(e){return(0,sn.jsx)(Sa,{...e})}function wa(e){return(0,sn.jsx)(Sa,{...e})}var Mt=require("@flopay/shared"),i=require("react/jsx-runtime"),Cn="flopay_stripe_resume",ka="flopay_wallet_resume",vr="flopay_paypal_resume";function wo(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Wr({billingApiUrl:e,sessionId:t,nonce:n,request:l}){if(!(!t||!n))try{await new ln.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,l)}catch{}}function Ni(e){return e instanceof Mt.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function vo(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Hr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let l=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),s=Math.round((l>>16&255)*o),u=Math.round((l>>8&255)*o),c=Math.round((l&255)*o);return`#${(1<<24|s<<16|u<<8|c).toString(16).slice(1)}`}var Oi=`
8
+ ${tt.join(`
9
+ `)}`]}):null;return $e&&!st?N?(0,cn.jsx)("div",{children:Tt}):null:(0,cn.jsxs)("div",{children:[Tt,(0,cn.jsxs)("div",{"aria-hidden":he?!0:void 0,style:he?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Gr},children:[!Pe&&!he&&(0,cn.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,cn.jsx)("div",{ref:W,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:Gr,display:"flex",opacity:Pe?1:0},"aria-busy":Z||T},le)]},le),ke&&(0,cn.jsx)("button",{ref:Le,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:In,style:qi,children:"Try PayPal again"})]})}function kr(e){return(0,cn.jsx)(_a,{...e})}function xa(e){return(0,cn.jsx)(_a,{...e})}var Nt=require("@flopay/shared"),i=require("react/jsx-runtime"),wn="flopay_stripe_resume",Ta="flopay_wallet_resume",Rr="flopay_paypal_resume";function xo(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Zr({billingApiUrl:e,sessionId:t,nonce:n,request:l}){if(!(!t||!n))try{await new dn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,l)}catch{}}function Vi(e){return e instanceof Nt.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Io(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Jr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let l=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),s=Math.round((l>>16&255)*o),u=Math.round((l>>8&255)*o),c=Math.round((l&255)*o);return`#${(1<<24|s<<16|u<<8|c).toString(16).slice(1)}`}var Hi=`
10
10
  .paypal-buttons { margin: 0 !important; vertical-align: top !important; }
11
11
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
12
12
  @keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
@@ -27,7 +27,7 @@ ${Qe.join(`
27
27
  0% { opacity: 1; transform: translateX(0) scale(1); }
28
28
  100% { opacity: 0; transform: translateX(16px) scale(0.97); }
29
29
  }
30
- `,Kr=44;function ko(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var zi={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Ma={width:"100%",minHeight:Kr,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 Ui(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ra(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Aa(e){return e==="paypal"?"PayPal":(0,k.getStripeMethodDisplayName)(e)}function $i(e,t){let n=`We couldn't open ${Aa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Fa(e){let t=(0,r.useRef)(0),n=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useCallback)((d=l.current)=>{let g=d;g?.timer&&(clearTimeout(g.timer),g.timer=null)},[]),s=(0,r.useCallback)((d,g)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(d),d.timer=setTimeout(()=>{d.timer=null,l.current?.generation===d.generation&&(l.current=null,n.current=d.generation,e(d.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},g))},[o,e]),u=(0,r.useCallback)(d=>{d.yieldedControl&&s(d,600)},[s]),c=(0,r.useCallback)(d=>{o();let g=t.current+1;t.current=g,n.current=null;let I={generation:g,method:d,timer:null,yieldedControl:!1};return l.current=I,g},[o]),R=(0,r.useCallback)(d=>{let g=l.current;return typeof d=="number"&&g?.generation!==d?!1:(o(g),l.current=null,(typeof d!="number"||n.current===d)&&(n.current=null),!0)},[o]),N=(0,r.useCallback)(d=>{let g=l.current,I=d??g?.generation??t.current;(!d||g?.generation===d)&&(o(g),l.current=null),n.current=I},[o]),m=(0,r.useCallback)(d=>n.current===(d??t.current),[]),_=(0,r.useCallback)(d=>l.current?.generation===d&&n.current!==d,[]),w=(0,r.useCallback)(()=>{let d=l.current;d&&u(d)},[u]),B=(0,r.useCallback)(()=>{let d=l.current;d&&(d.yieldedControl=!0,o(d))},[o]);return(0,r.useEffect)(()=>{let d=()=>{document.visibilityState==="visible"?w():B()},g=()=>{B()};return document.addEventListener("visibilitychange",d),window.addEventListener("blur",g),window.addEventListener("focus",w),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("blur",g),window.removeEventListener("focus",w),o()}},[o,B,w]),{startAttempt:c,finishAttempt:R,invalidateAttempt:N,isAttemptInvalidated:m,isAttemptCurrent:_}}function qi(e){let t=(0,k.getPostalCodeExample)(e);return`Enter a valid ${(0,k.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function ji(e,t,n){let l=(0,k.isPostalCodeSupported)(e),o=t.trim(),s=n&&l,u=s&&!o,c=s&&!!o&&!(0,k.isValidPostalCode)(e,o);return{visible:n,supported:l,required:s,empty:u,malformed:c}}function Ia(e,t){return t instanceof Mt.FloPayError?t:new Mt.FloPayError(t instanceof Error?t.message:`${Ui(e)} before-click hook failed.`,"validation_error")}function Co(){return(0,i.jsx)("style",{children:Oi})}function Vi(e){return typeof e=="number"?`${e}px`:e}function Ea(e){if(typeof e=="number"||typeof e=="string")return e}function Da(e,t){let n=e.availablePaymentMethods;return n&&t.some(l=>n[l])?"ready":"unavailable"}function La({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 _a(e){return e!=="unavailable"&&e!=="load_error"}function Yr(e){return(0,i.jsx)(Ki,{...e})}function xa({sessionId:e,nonce:t,email:n,billingApiUrl:l,onTokenizedBody:o,onErrorChange:s,isProcessing:u=!1,onButtonClick:c,onDecline:R,onTechnicalFailure:N,runBeforeButtonClick:m,onLoadStateChange:_,placeholderBorderRadius:w}){let B=an(),d=(0,ut.useStripe)(),g=(0,ut.useElements)(),[I,F]=(0,r.useState)("loading");(0,r.useEffect)(()=>{_?.(I)},[I,_]);let[P,W]=(0,r.useState)(!1),Q=(0,r.useRef)(!1),me=(0,r.useRef)(null),le=(0,r.useRef)(null),[U,ne]=(0,r.useState)(0),[Y,ye]=(0,r.useState)(!1),V=(0,r.useRef)(!1),G=(0,r.useRef)(new Map),{startAttempt:ce,finishAttempt:De,invalidateAttempt:be,isAttemptInvalidated:Pe,isAttemptCurrent:re}=Fa((E,ie,ue)=>{N?.(E,ie,{...ue,popupBlocked:ue?.popupBlocked??Dn(ie)}),ye(!0),ne(ze=>ze+1)});(0,r.useEffect)(()=>{Y&&le.current?.focus()},[Y,U]);let fe=(0,r.useCallback)(()=>{ne(E=>E+1)},[]),ve=(0,r.useCallback)((E,ie,ue)=>{be(ue),N?.("paypal",E,{code:ie,popupBlocked:Dn(E)}),ye(!0),fe()},[be,N,fe]),de=(0,r.useCallback)(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{V.current&&(V.current=!1,de())},[de,U]);let Ne=(0,r.useCallback)(()=>{ye(!1),s?.(null),de()},[de,s]);(0,r.useEffect)(()=>{if(!d||Q.current)return;let E=new URLSearchParams(window.location.search),ie=E.get("payment_intent"),ue=E.get("payment_intent_client_secret"),ze=E.get("redirect_status");if(!ie||!ue)return;Q.current=!0;let Oe;try{let A=localStorage.getItem(vr);if(A){let J=JSON.parse(A);J.clientSecret===ue&&(Oe={...J.accountPatch?{accountPatch:J.accountPatch}:{},...J.sessionId?{sessionId:J.sessionId}:{},...J.nonce?{nonce:J.nonce}:{}})}}catch{}try{localStorage.removeItem(vr)}catch{}let ee=new URL(window.location.href);ee.searchParams.delete("payment_intent"),ee.searchParams.delete("payment_intent_client_secret"),ee.searchParams.delete("redirect_status"),window.history.replaceState({},"",ee.toString()),(async()=>{try{if(W(!0),ze==="failed"){let pe="PayPal payment was declined. Please try again.";s?.(pe),R?.(wt("paypal",pe));return}let{paymentIntent:A,error:J}=await d.retrievePaymentIntent(ue);if(J){s?.(J.message??"Failed to retrieve PayPal payment status.");return}if(A&&(A.status==="requires_capture"||A.status==="succeeded")){let pe=typeof A.payment_method=="string"?A.payment_method:A.payment_method?.id;o({id:pe??A.id,type:"card",threeDSecureActionResultTokenId:A.id,isPaypal:!0},Oe)}else{let pe="PayPal payment was not completed. Please try again.";s?.(pe),R?.(wt("paypal",pe))}}catch(A){s?.(A instanceof Error?A.message:"Failed to complete PayPal payment.")}finally{W(!1)}})()},[d,o,s,R]);let Ie=(0,r.useCallback)(async E=>{if(u||P){E.reject();return}let ie=m?await m("paypal"):{proceed:!0};if(!ie.proceed){G.current.delete(U),E.reject();return}let ue=ce("paypal");G.current.set(U,{generation:ue,accountPatch:ie.accountPatch,sessionId:ie.sessionId,nonce:ie.nonce}),ye(!1),c?.("paypal"),E.resolve()},[G,u,c,m,ce,P,U]),Se=(0,r.useCallback)(async E=>{if(!d||!g)return;let ie=G.current.get(U);if(ie&&!re(ie.generation)){G.current.delete(U);return}if(!ie&&Pe()||ie&&!De(ie.generation))return;ie||De();let ue=ie??null;if(G.current.delete(U),!ue&&m){let A=await m("paypal");if(!A.proceed){E.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ue={accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}}let ze=ue?.sessionId??e,Oe=ue?.nonce??t,ee=ue?.accountPatch?.email??n;try{if(W(!0),s?.(null),!ze||!ee)throw new Error("Missing sessionId or email for PayPal payment");let A=d.createPaymentMethod,{error:J,paymentMethod:pe}=await A({type:"paypal"});if(J){ve(J,"stripe_paypal_create_payment_method_failed",ie?.generation),E.paymentFailed({reason:"fail"});return}let Ee=await new ln.PaymentAPI(l).createSessionIntent(ze,Oe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:pe?.id??null,intentKind:"payment"});if(Ee.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ft=Ee.clientSecret,Qe={return_url:window.location.href};if(pe?.id&&(Qe.payment_method=pe.id),typeof window<"u")try{localStorage.setItem(vr,JSON.stringify({clientSecret:ft,sessionId:ze,nonce:Oe,accountPatch:ue?.accountPatch}))}catch{}let{error:Ze,paymentIntent:y}=await d.confirmPayment({clientSecret:ft,confirmParams:Qe,redirect:"if_required"});if(Ze){if(typeof window<"u")try{localStorage.removeItem(vr)}catch{}if(Pr(Ze)){let Ue=Ze.message??"Your payment was declined.";s?.(Ue),R?.(wt("paypal",Ue,{code:Tn(Ze),declineCode:er(Ze)})),await Wr({billingApiUrl:l,sessionId:ze,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Tn(Ze)??"provider_declined"}})}else ve(Ze,"stripe_paypal_confirm_failed",ie?.generation);return}if(typeof window<"u")try{localStorage.removeItem(vr)}catch{}let qe=typeof y?.payment_method=="string"?y.payment_method:y?.payment_method?.id;o({id:qe??y?.id,type:"card",threeDSecureActionResultTokenId:y?.id,isPaypal:!0},{accountPatch:ue?.accountPatch,sessionId:ze,nonce:Oe});return}catch(A){ve(A,"stripe_paypal_failed",ie?.generation)}finally{W(!1)}},[d,g,e,t,n,l,o,s,R,m,ve,De,re,Pe,U]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(La,{state:I,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:(0,i.jsxs)("div",{ref:me,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Y&&(0,i.jsx)("button",{ref:le,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ne,style:Ma,children:"Try PayPal again"}),(0,i.jsx)(ut.ExpressCheckoutElement,{onReady:E=>F(Da(E,["paypal"])),onLoadError:()=>{F("load_error"),wo(xt(B),"paypal","paypal")},onClick:Ie,onConfirm:Se,onCancel:()=>{let E=G.current.get(U);G.current.delete(U),xt(B)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be(E?.generation),ye(!1),V.current=!0,fe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},U)]})}),P&&(0,i.jsx)(vn,{status:"processing"})]})}function Ta({sessionId:e,nonce:t,email:n,billingApiUrl:l,intentKind:o,expressMethods:s,onTokenizedBody:u,onErrorChange:c,onButtonClick:R,onDecline:N,onTechnicalFailure:m,runBeforeButtonClick:_,onLoadStateChange:w,placeholderBorderRadius:B}){let d=an(),g=(0,ut.useStripe)(),I=(0,ut.useElements)(),[F,P]=(0,r.useState)("loading");(0,r.useEffect)(()=>{w?.(F)},[F,w]);let[W,Q]=(0,r.useState)(!1),me=(0,r.useRef)(null),le=(0,r.useRef)(null),[U,ne]=(0,r.useState)(0),[Y,ye]=(0,r.useState)(!1),[V,G]=(0,r.useState)("google_pay"),ce=(0,r.useRef)(!1),De=(0,r.useRef)("google_pay"),be=(0,r.useRef)("google_pay"),Pe=(0,r.useRef)(new Map),{startAttempt:re,finishAttempt:fe,invalidateAttempt:ve,isAttemptInvalidated:de,isAttemptCurrent:Ne}=Fa((ee,A,J)=>{m?.(ee,A,{...J,popupBlocked:J?.popupBlocked??Dn(A)}),G(ee),ye(!0),ne(pe=>pe+1)});(0,r.useEffect)(()=>{Y&&le.current?.focus()},[Y,U]);let Ie=(0,r.useCallback)(()=>{ne(ee=>ee+1)},[]),Se=(0,r.useCallback)((ee,A,J,pe)=>{ve(pe),m?.(ee,A,{code:J,popupBlocked:Dn(A)}),G(ee),ye(!0),Ie()},[ve,m,Ie]),E=(0,r.useCallback)(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{ce.current&&(ce.current=!1,E())},[E,U]);let ie=(0,r.useCallback)(()=>{ye(!1),c?.(null),E()},[E,c]),ue=(0,r.useCallback)(async ee=>{if(!g||!I)return;let A=Pe.current.get(U);if(A&&!Ne(A.generation)){Pe.current.delete(U);return}if(!A&&de()||A&&!fe(A.generation))return;A||fe();let J=ee.expressPaymentType??A?.method??De.current,pe=A??null;Pe.current.delete(U);let Ee=Ra(J);if(!pe&&_){let qe=await _(Ee);if(!qe.proceed){ee.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}pe={accountPatch:qe.accountPatch,sessionId:qe.sessionId,nonce:qe.nonce}}let ft=Ee,Qe=pe?.sessionId??e,Ze=pe?.nonce??t,y=pe?.accountPatch?.email??n;try{Q(!0),c?.(null);let{error:qe}=await I.submit();if(qe){Se(J,qe,"stripe_wallet_submit_failed",A?.generation);return}let{error:Ue,paymentMethod:Ke}=await g.createPaymentMethod({elements:I});if(Ue||!Ke){Se(J,Ue??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",A?.generation);return}if(!Qe||!y)throw new Error("Missing sessionId or email for wallet payment");let je=await new ln.PaymentAPI(l).createSessionIntent(Qe,Ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:J??Ee,paymentMethodId:Ke.id,intentKind:o});if(je.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Ht=je.clientSecret,{error:Pt,intentId:kt}=(0,Mt.isSetupIntentClientSecret)(Ht)?await g.confirmCardSetup(Ht,{payment_method:Ke.id}).then(h=>({error:h.error,intentId:h.setupIntent?.id})):await g.confirmCardPayment(Ht,{payment_method:Ke.id}).then(h=>({error:h.error,intentId:h.paymentIntent?.id}));if(Pt){if(Pr(Pt)){let h=Pt.message??"Your payment was declined.";c?.(h),N?.(wt(ft,h,{code:Tn(Pt),declineCode:er(Pt)})),await Wr({billingApiUrl:l,sessionId:Qe,nonce:Ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:J??Ee,providerDeclineReason:Tn(Pt)??"provider_declined"}})}else Se(J,Pt,"stripe_wallet_confirm_failed",A?.generation);return}u({id:Ke.id,type:"card",threeDSecureActionResultTokenId:kt},{accountPatch:pe?.accountPatch,sessionId:Qe,nonce:Ze})}catch(qe){Se(J,qe,"stripe_wallet_failed",A?.generation)}finally{Q(!1)}},[g,I,e,t,n,l,o,u,c,N,_,Se,fe,Ne,de,U]),ze=(0,r.useMemo)(()=>{let ee=["applePay","googlePay","paypal","link","amazonPay","klarna"],A=new Set(["applePay","googlePay"]),J=new Set(s.map(k.stripeExpressMethodToOptionKey)),pe={};for(let Ee of ee)J.has(Ee)?pe[Ee]=A.has(Ee)?"always":"auto":pe[Ee]="never";return pe},[s]),Oe=(0,r.useMemo)(()=>s.map(k.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(La,{state:F,placeholderTestId:"flopay-wallet-placeholder",borderRadius:B,children:(0,i.jsxs)("div",{ref:me,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Y&&(0,i.jsxs)("button",{ref:le,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ie,style:Ma,children:["Try ",Aa(V)," again"]}),(0,i.jsx)(ut.ExpressCheckoutElement,{onReady:ee=>{P(Da(ee,Oe))},onLoadError:ee=>{P("load_error"),wo(xt(d),"stripe","wallet")},onClick:async ee=>{De.current=ee.expressPaymentType,be.current=Ra(ee.expressPaymentType);let A=_?await _(be.current):{proceed:!0};if(!A.proceed){Pe.current.delete(U),ee.reject();return}let J=re(ee.expressPaymentType);Pe.current.set(U,{generation:J,method:ee.expressPaymentType,accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}),ye(!1),R?.(be.current),ee.resolve()},onConfirm:ue,onCancel:()=>{let ee=Pe.current.get(U);Pe.current.delete(U),xt(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),ve(ee?.generation),ye(!1),ce.current=!0,Ie()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ze,layout:{maxColumns:1,overflow:"never"}}},U)]})}),W&&(0,i.jsx)(vn,{status:"processing"})]})}function Hi({method:e,themeId:t,submitting:n=!1,disabled:l=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:u,backgroundColor:c,borderColor:R,textColor:N,borderRadius:m,fontFamily:_}){let w=(0,k.resolveStripeMethodBrandVariant)(e,t),B=ca[e],d=w?.backgroundColor??c??"#ffffff",g=w?.borderColor??R??"#d1d5db",I=w?.textColor??N??"#262833";return(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!l&&u()},disabled:n||l,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Kr,padding:"0 1rem",backgroundColor:d,color:I,border:`1px solid ${g}`,borderRadius:m??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,k.getStripeMethodDisplayName)(e)}\u2026`}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,k.hasVendoredStripeMethodLogo)(e)?8:0},children:[B?(0,i.jsx)("img",{src:B,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"}}):w?.logoSvg?(0,i.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:w.logoSvg}}):null,(0,i.jsx)("span",{children:(0,k.getStripeMethodDisplayName)(e)})]}),s&&(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:I,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,i.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function So({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:u,onErrorChange:c,onDecline:R,onCancel:N,runBeforeButtonClick:m,onButtonClick:_,isProcessing:w,submitButtonColor:B,submitButtonBorderRadius:d,submitButtonStyle:g,errorText:I}){let F=an(),P=(0,ut.useStripe)(),W=(0,ut.useElements)(),[Q,me]=(0,r.useState)(!1),le=(0,r.useRef)(!1),[U,ne]=(0,r.useState)(!1),[Y,ye]=(0,r.useState)("loading"),V=(0,r.useCallback)(async()=>{if(!P||!W||w||le.current||!U)return;le.current=!0,me(!0);let G=m?await m("card"):{proceed:!0};if(!G.proceed){le.current=!1,me(!1);return}_?.("card");let ce=G.sessionId??t,De=G.nonce??n,be=G.accountPatch?.email??l;try{c?.(null);let Pe=await W.submit();if(Pe.error){c?.(Pe.error.message??"Payment failed.");return}let re=await P.createPaymentMethod({elements:W});if(re.error||!re.paymentMethod){c?.(re.error?.message??"Failed to create payment method.");return}let fe=re.paymentMethod;if(!ce||!be)throw new Error("Missing sessionId or email for payment.");let ve=fe.type||e,de=await new ln.PaymentAPI(s).createSessionIntent(ce,De??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ve,paymentMethodId:null,intentKind:"payment"});if(de.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ne=de.clientSecret;if(typeof window<"u")try{localStorage.setItem(Cn,JSON.stringify({clientSecret:Ne,sessionId:ce,nonce:De,accountPatch:G.accountPatch,paymentMethodId:fe.id,paymentMethodType:fe.type??e,gateway:"stripe"}))}catch{}let{error:Ie,paymentIntent:Se}=await P.confirmPayment({clientSecret:Ne,confirmParams:{return_url:window.location.href,payment_method:fe.id},redirect:"if_required"});if(Ie){if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let ue=Ie.message??"Payment failed.";c?.(ue),R?.(wt("card",ue,{code:Ie.code})),await Wr({billingApiUrl:s,sessionId:ce,nonce:De,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ie.code??"provider_declined"}});return}let E=Se?.status;if(!Ur(E)){if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let ue=E==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";c?.(ue),R?.(wt("card",ue,{code:E??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let ie=typeof Se?.payment_method=="string"?Se.payment_method:Se?.payment_method?.id;u({id:ie??fe.id,type:"card",threeDSecureActionResultTokenId:Se?.id,gateway:"stripe",paymentMethodType:fe.type??e},{accountPatch:G.accountPatch,sessionId:ce,nonce:De})}catch(Pe){c?.(Pe instanceof Error?Pe.message:"Payment failed. Please try again.")}finally{le.current=!1,me(!1)}},[P,W,w,U,m,_,t,n,l,s,e,u,c,R]);return(0,i.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,i.jsx)(ut.PaymentElement,{onReady:()=>ye("ready"),onLoadError:()=>{ye("load_error"),wo(xt(F),"stripe","apm")},onChange:G=>{ne(!!G.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:()=>{V()},disabled:!U||Q||w||Y!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:B,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!U||Q||w||Y!=="ready"?"not-allowed":"pointer",opacity:!U||Q||w||Y!=="ready"?.5:1,transition:"opacity 120ms ease-out",...g??{}},children:Q?"Processing\u2026":`Pay with ${(0,k.getStripeMethodDisplayName)(e)}`}),I&&(0,i.jsx)(Xn,{margin:"0.75rem 0 0",children:I})]})}function Ba({sessionId:e,nonce:t,email:n,billingName:l,billingApiUrl:o,paymentElementMethods:s,stripeInstance:u,paymentElementBaseOptions:c,onTokenizedBody:R,onErrorChange:N,onButtonClick:m,onDecline:_,runBeforeButtonClick:w,onLoadStateChange:B,isProcessing:d=!1,submitButtonColor:g="#4A49FF",submitButtonBorderRadius:I=8,submitButtonStyle:F,buttonAppearance:P,themeId:W,onExpandApm:Q,expandedApmMethod:me}){let[le,U]=(0,r.useState)(null),[ne,Y]=(0,r.useState)(null),ye=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&u?B?.("ready"):u||B?.("loading")},[s.length,u,B]);let V=(0,r.useCallback)(async re=>{if(!u||ye.current||d)return;ye.current=!0,Y(re);let fe=w?await w("card"):{proceed:!0};if(!fe.proceed){ye.current=!1,Y(null);return}m?.("card");let ve=fe.sessionId??e,de=fe.nonce??t,Ne=fe.accountPatch?.email??n;try{if(N?.(null),!ve||!Ne)throw new Error("Missing sessionId or email for payment.");let Ie=await new ln.PaymentAPI(o).createSessionIntent(ve,de??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,paymentMethodId:null,intentKind:"payment"});if(Ie.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Se=Ie.clientSecret;if(typeof window<"u")try{localStorage.setItem(Cn,JSON.stringify({clientSecret:Se,sessionId:ve,nonce:de,accountPatch:fe.accountPatch,paymentMethodType:re,gateway:"stripe"}))}catch{}let{error:E,paymentIntent:ie}=await u.confirmPayment({clientSecret:Se,confirmParams:{return_url:window.location.href,payment_method_data:{type:re,billing_details:{name:l&&l.trim().length>=3?l.trim():"FloPay Customer",...Ne?{email:Ne}:{}}}},redirect:"if_required"});if(E){if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let Oe=E.message??"Payment failed.";N?.(Oe),_?.(wt("card",Oe,{code:E.code})),await Wr({billingApiUrl:o,sessionId:ve,nonce:de,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,providerDeclineReason:E.code??"provider_declined"}});return}let ue=ie?.status;if(!Ur(ue)){if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let Oe=ue==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";N?.(Oe),_?.(wt("card",Oe,{code:ue??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let ze=typeof ie?.payment_method=="string"?ie.payment_method:ie?.payment_method?.id;R({id:ze??ie?.id,type:"card",threeDSecureActionResultTokenId:ie?.id,gateway:"stripe",paymentMethodType:re},{accountPatch:fe.accountPatch,sessionId:ve,nonce:de})}catch(Ie){N?.(Ie instanceof Error?Ie.message:"Payment failed. Please try again.")}finally{ye.current=!1,Y(null)}},[u,d,w,m,e,t,n,o,l,R,N,_]),[G,ce]=(0,r.useState)(null),De=Q?me??null:G,be=(0,r.useCallback)(re=>{ye.current||d||De&&De!==re||((0,k.needsStripeMethodExplicitConfirm)(re)?Q?Q(re):ce(re):V(re))},[De,d,V,Q]),Pe=(0,r.useMemo)(()=>G?{...c,paymentMethodTypes:[G]}:null,[G,c]);return(0,i.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(re=>{let fe=me===re,ve=ne===re,de=ne!==null&&ne!==re||me!=null&&me!==re;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(Hi,{method:re,themeId:W,submitting:ve,disabled:de,highlighted:fe,hasNextStep:(0,k.needsStripeMethodExplicitConfirm)(re),onClick:()=>be(re),backgroundColor:P?.backgroundColor,borderColor:P?.borderColor,textColor:P?.textColor,borderRadius:P?.borderRadius,fontFamily:P?.fontFamily}),!Q&&G===re&&Pe&&u&&(0,i.jsx)(ut.Elements,{stripe:u,options:Pe,children:(0,i.jsx)(So,{method:re,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:R,onErrorChange:N,onDecline:_,onCancel:()=>ce(null),runBeforeButtonClick:w,onButtonClick:m,isProcessing:d,submitButtonColor:g,submitButtonBorderRadius:I,submitButtonStyle:F})},re)]},re)})})}function Ki({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:u,onDecline:c,onTokenizedBody:R,firstName:N,lastName:m,chv:_,className:w,isProcessing:B,error:d,onErrorChange:g,showPayPal:I=!0,showStripe:F=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:W,showApplePay:Q=!0,showGooglePay:me=!0,layout:le="default",theme:U,buttonsTheme:ne,buttonsStyles:Y,appearance:ye,cardButtonContent:V,cardBackButtonContent:G,cardTitleContent:ce,showSecurityFooter:De,onButtonClick:be,onBeforeButtonClick:Pe,enableAVS:re,cardFieldOrder:fe,cardPreFormSlot:ve,avsLayout:de="row",country:Ne,zip:Ie,addressLine1:Se,addressLine2:E,city:ie,state:ue,onCountryChange:ze,onZipChange:Oe,avsCheck:ee,checkoutType:A,checkoutLayout:J,totalAmount:pe=0,currency:Ee="usd",initialCardOpen:ft=!1,directPaypal:Qe,isSubscription:Ze=!1,session:y,debug:qe=!1}){let Ue=an(),Ke=Nr(),je=(0,r.useContext)(on),Ht=zr(),[Pt,kt]=(0,r.useState)(!1),[h,we]=(0,r.useState)(null),[Ve,lt]=(0,r.useState)(Ne??"US"),[ot,et]=(0,r.useState)(Ie??""),[Ge,Ce]=(0,r.useState)(Se??""),[bt,He]=(0,r.useState)(E??""),[Ft,Rt]=(0,r.useState)(ie??""),[pn,wn]=(0,r.useState)(ue??""),[kn,Nn]=(0,r.useState)({}),gt=(0,r.useRef)(Ie??""),Dt=(0,r.useRef)(Ne??"US"),Bt=(0,r.useRef)(Se??""),Kt=(0,r.useRef)(E??""),Qt=(0,r.useRef)(ie??""),mn=(0,r.useRef)(ue??""),X=(0,r.useMemo)(()=>(0,k.resolveAVSConfig)(re),[re]),Mn=X!==null,yn=!!y?.vault?.html,Lt=!!y?.gateways?.pcivault,at=yn||Lt,f=!!(F&&at&&Ue&&e),xe=(0,r.useMemo)(()=>!Ue||!f||!e?null:Ue.cardCapture({sessionId:e}),[Ue,f,e]),ct=(0,r.useMemo)(()=>{let a=Ve,C=X?(0,k.isAVSFieldVisible)(X.postal_code,a):!1;return ji(a,ot,C)},[X,Ve,ot]),{avsInvalid:Rn,invalidAvsFields:Te}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!f||!X)return{avsInvalid:!1,invalidAvsFields:a};let C=Ve,H=(ae,Je)=>(0,k.isAVSFieldVisible)(ae,C)&&!Je.trim(),se={line1:H(X.address_line_1,Ge),city:H(X.city,Ft),state:H(X.state,pn),zip:ct.empty||ct.malformed};return{avsInvalid:se.line1||se.city||se.state||se.zip,invalidAvsFields:se}},[f,X,Ve,Ge,Ft,pn,ct]),[An,fn]=(0,r.useState)(!1),[On,gn]=(0,r.useState)(!1),[Nt,Tt]=(0,r.useState)(()=>vo(y?.vault)),[ke,pt]=(0,r.useState)(ft&&at?"card":"buttons"),[it,en]=(0,r.useState)(null),Wt=ke==="expanding"||ke==="card",ht=280,qt=(0,r.useRef)(null),vt=(0,r.useCallback)(a=>{qt.current&&clearTimeout(qt.current),qt.current=setTimeout(()=>{qt.current=null,a()},ht)},[ht]);(0,r.useEffect)(()=>()=>{qt.current&&clearTimeout(qt.current)},[]);let tn=(0,r.useCallback)(()=>{pt("expanding"),vt(()=>pt("card"))},[vt]),hn=(0,r.useCallback)(()=>{pt("collapsing"),vt(()=>pt("buttons"))},[vt]),In=(0,r.useCallback)(a=>{en(a),pt("apm-expanding"),vt(()=>pt("apm-form"))},[vt]),Pn=(0,r.useCallback)(()=>{pt("apm-collapsing"),vt(()=>{pt("buttons"),en(null)})},[vt]);(0,r.useEffect)(()=>{le==="buttons"&&ft&&at&&pt("card")},[le,ft,at]);let[jt,We]=(0,r.useState)(null),Vt=(0,r.useRef)(!1),[Ot,zt]=(0,r.useState)(null),M=(0,r.useRef)(Ot);(0,r.useEffect)(()=>{M.current=Ot},[Ot]);let $=n||Ht,q=d??h,D=(0,r.useMemo)(()=>(0,Mt.resolveTheme)(U),[U]),p=(0,r.useMemo)(()=>{let a=D?.buttonsLayout??(0,k.resolveButtonsLayoutTheme)(ne);return Y?{...a,...Y,cardButton:{...a.cardButton,...Y.cardButton},cardFormContainer:{...a.cardFormContainer,...Y.cardFormContainer},backButton:{...a.backButton,...Y.backButton},backButtonIcon:{...a.backButtonIcon,...Y.backButtonIcon},submitButton:{...a.submitButton,...Y.submitButton},title:{...a.title,...Y.title}}:a},[D,ne,Y]),K=ye??D?.appearance,v=(0,r.useMemo)(()=>{let a=K?.variables,C=Je=>typeof Je=="string"&&Je?Je:void 0,H=p.submitButton,se=C(a?.colorPrimary)??C(H?.backgroundColor)??"#4A49FF",j=le==="buttons",ae=p.nameInput;return{primaryColor:se,primaryHoverColor:C(a?.colorPrimaryHover)??Hr(se,.12),inputBackgroundColor:C(p.cardInputBackground)??C(a?.colorBackground)??"#ffffff",textColor:C(p.cardInputColor)??C(ae?.color)??C(a?.colorText)??"#262833",borderColor:C(p.cardInputBorder)??(j?"#e5e7eb":"#A4A4FF"),placeholderColor:C(p.cardInputPlaceholderColor)??"#9ca3af",errorColor:C(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:C(ae?.fontFamily)??C(a?.fontFamily)??"Poppins, sans-serif",fontSize:C(p.cardInputFontSize)??C(a?.fontSizeBase)??"16px",fontWeight:String(Ea(ae?.fontWeight)??400),borderRadius:C(a?.borderRadius)??"8px"}},[K,p,le]),Me=je.inlineSessionPatchProcessing??!1,Z=(B??Pt)||Me,Ye=$.replace(/\/+$/,""),te=(0,r.useMemo)(()=>Po({userId:o,email:l,firstName:N,lastName:m,country:Ne,zip:Ie},kn),[o,l,N,m,Ne,Ie,kn]),Ut=[te.firstName,te.lastName].filter(a=>!!a?.trim()).join(" "),st=(0,r.useMemo)(()=>Ue?Ue.getRawProvider():null,[Ue]),O=(0,r.useMemo)(()=>Ke?Ke.getRawProvider():null,[Ke]),b=pe||100,z=(0,r.useMemo)(()=>K?(0,ln.toStripeAppearance)(K):null,[K]),he=z?{appearance:z}:null,Ae=(0,r.useMemo)(()=>{let a=z??{},C=a.rules??{};return{...a,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[z]),$e=(0,r.useMemo)(()=>{let a=ga(pe);return{...a,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...he}},[pe,Ee,he]),nn=(0,r.useMemo)(()=>({mode:"payment",amount:b,currency:Ee.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...he}),[b,Ee,he]),x=(0,r.useCallback)(a=>{we(a),g?.(a)},[g]);(0,r.useEffect)(()=>{!f||!xe||xe.setCardFieldOrder?.(fe??null,X==null)},[f,xe,fe,X]),(0,r.useEffect)(()=>{(ke==="expanding"||ke==="collapsing"||ke==="apm-expanding"||ke==="apm-collapsing")&&x(null)},[ke,x]);let ge=(0,r.useCallback)((a,C,H)=>{c?.(wt(a,C,H))},[c]),oe=(0,r.useCallback)((a,C,H)=>{let se=H?.popupBlocked??Dn(C),j=$i(a,se),ae=Vn(H?.code)??Tn(C)??"external_payment_method_failed",Je=new Mt.FloPayError(j,"api_error",{code:"external_payment_method_failed",param:a});We(null),le==="buttons"&&(pt("buttons"),en(null)),x(j),u?.(Je),console.error("[FloPay] External payment method failed:",{method:a,code:ae,popupBlocked:se})},[le,u,x]);(0,r.useEffect)(()=>{if(!f||!e){Tt(null);return}let a=vo(y?.vault);if(a){Tt(a);return}Tt(null);let C=!0;return new ln.PaymentAPI(Ye).getVaultCapture(e,t).then(H=>{if(!C)return;let se=vo(H);se?Tt(se):x("Failed to load the secure card form.")}).catch(H=>{C&&x(H instanceof Error?H.message:"Failed to load the secure card form.")}),()=>{C=!1}},[f,e,y?.vault?.html,y?.vault?.messageToken,y?.vault?.expectedOrigin,Ye,t,x]);let Re=(0,r.useRef)({onComplete:s,onError:u,updateError:x,emitDecline:ge,resolvedAccount:te,avsConfig:X,avsCheckProp:ee,sessionId:e,nonce:t,baseUrl:Ye});Re.current={onComplete:s,onError:u,updateError:x,emitDecline:ge,resolvedAccount:te,avsConfig:X,avsCheckProp:ee,sessionId:e,nonce:t,baseUrl:Ye};let Yt=(0,r.useRef)(!1),Gt=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:C,avsCheckProp:H}=Re.current,se=Dt.current||a.country||"US",j=C?(0,k.isAVSFieldVisible)(C.state,se):!1,ae=C?(0,k.isAVSFieldVisible)(C.address_line_1,se):!1,Je=C?(0,k.isAVSFieldVisible)(C.postal_code,se):!1,Ct=C?(0,k.isAVSFieldVisible)(C.city,se):!1,It=C?(0,k.isAVSFieldVisible)(C.address_line_2,se):!1,nt=ae&&!j&&Je?(0,k.getStateFromPostalCode)(se,(gt.current??"").trim()):null,Et=j?mn.current:nt;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Je&&gt.current?{zip:gt.current}:{},...Ct&&Qt.current?{city:Qt.current}:{},...Et?{state:Et}:{},...ae&&Bt.current?{addressLine1:Bt.current}:{},...It&&Kt.current?{addressLine2:Kt.current}:{},country:se},...H!==void 0?{avsCheck:H}:{},...C?{avsConfig:{country:(0,k.isAVSFieldVisible)(C.country,se),postal_code:Je,address_line_1:ae,address_line_2:It,city:Ct,state:j}}:{}}},[]);(0,r.useEffect)(()=>{!f||!xe||xe.setSubmitGate?.(Rn)},[f,xe,Rn]),(0,r.useEffect)(()=>{if(!f||!xe)return;Yt.current=!1;let a=!1,C=xe.on("submitting",()=>{fn(!0),We("processing");let{baseUrl:ae,sessionId:Je,nonce:Ct,updateError:It,onError:nt}=Re.current;!Je||!Ct||new ln.PaymentAPI(ae).patchAccountSnapshot(Je,Ct,Gt(),{telemetryMode:"best_effort"}).catch(Et=>{if(!Ni(Et))return;let Le=Et instanceof Error?Et.message:"Please check your billing address and try again.";It(Le),We(null),nt?.(Et instanceof Mt.FloPayError?Et:new Mt.FloPayError(Le,"api_error"))})}),H=xe.on("complete",async ae=>{Qn(ae.sessionId??Re.current.sessionId),We("success"),await new Promise(Je=>setTimeout(Je,xn)),!Yt.current&&(Yt.current=!0,Re.current.onComplete?.({status:"succeeded",paymentIntentId:ae.intentId,checkoutMethod:"card"}))}),se=xe.on("decline",async ae=>{let{updateError:Je,emitDecline:Ct}=Re.current,It=ae.message??"Your payment was declined. Please try another card or contact your bank.";Je(It),We("error"),Ct("card",It,ae.declineReason?{declineCode:ae.declineReason}:void 0),await new Promise(nt=>setTimeout(nt,bn)),!a&&We(null)}),j=xe.on("error",async ae=>{let{updateError:Je,onError:Ct}=Re.current,It=ae.message??"There was a problem processing your payment. Please try again.";Je(It),We("error"),Ct?.(new Mt.FloPayError(It,"api_error")),await new Promise(nt=>setTimeout(nt,bn)),!a&&We(null)});return()=>{a=!0,C(),H(),se(),j()}},[f,xe]);let tt=!!Qe?.clientId,ar=Array.isArray(P),kr=ar&&P.length>0,Za=ar&&P.includes("paypal"),{expressMethods:Rr,paymentElementMethods:ir}=(0,r.useMemo)(()=>(0,k.partitionStripeMethods)(P,{excludePaypal:tt}),[P,tt]),Mo=tt||!!Ke,Qa=(0,r.useMemo)(()=>Mo?Rr.filter(a=>a!=="paypal"):Rr,[Rr,Mo]),ei=(0,r.useMemo)(()=>{let a=[];return Q&&a.push("apple_pay"),me&&a.push("google_pay"),a},[Q,me]),Ir=ar?Qa:ei,ti=F&&Ir.length>0,ro=Mn?Ve:Ne,Er=(0,r.useMemo)(()=>{let a=ro?.trim().toUpperCase();return a?W?ir.filter(C=>{let H=W[C];return!H||H.length===0||H.includes(a)}):(0,k.filterStripeMethodsByCountry)(ir,ro):ir},[ir,ro,W]),oo=(0,r.useMemo)(()=>({mode:"payment",amount:b,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",appearance:Ae}),[b,Ee,Ae]),[Ao,Fo]=(0,r.useState)("loading"),[Do,Lo]=(0,r.useState)("loading"),[No,Oo]=(0,r.useState)("loading"),[ni,ao]=(0,r.useState)(!1),[zo,io]=(0,r.useState)("loading"),[_r,ri]=(0,r.useState)();(0,r.useEffect)(()=>{ri(Pa())},[]);let Uo=I&&(tt||(ar?Za:_r===!1)),$o=F&&ti,sr=Uo&&tt,qo=zo==="retrying"||zo==="exhausted",lr=Uo&&!!O&&(!tt||qo),cr=$o&&!!st,dr=F&&kr&&Er.length>0&&!!st,oi=sr&&!qo?ni:lr&&_a(Ao),ai=cr&&_a(Do),ii=dr&&No!=="load_error",jo=a=>a==="loading"||a==="ready",Vo=sr||lr&&jo(Ao)||cr&&jo(Do)||dr&&No!=="load_error",xr=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!xr.current){if(!F&&!I){xr.current=!0;let a=new Mt.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(a),x(a.message)}else if(!F&&I&&!tt&&!O){xr.current=!0;let a=new Mt.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(a),x(a.message)}else if(_r!==void 0&&!at&&!Vo){xr.current=!0;let a=new Mt.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"});u?.(a),x(a.message)}}},[F,I,tt,O,_r,at,Vo,u,x]);let Ho=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(Ho.current||!kr)return;let a=[];Q!==!0&&a.push("showApplePay"),me!==!0&&a.push("showGooglePay"),a.length!==0&&(Ho.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.`))},[kr,Q,me]);let Ko=(0,r.useCallback)((a,C)=>je.applyInlineSessionPatch?je.applyInlineSessionPatch(a).then(H=>({error:null,sessionId:H.sessionId||e,nonce:H.session?.clientSecret||t})).catch(H=>{let se=Ia(C,H);return x(se.message),u?.(se),{error:se,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[je.applyInlineSessionPatch,t,u,e,x]),rn=(0,r.useCallback)(async a=>{if(!Pe)return{proceed:!0};try{let C=await Pe({method:a,sessionId:e||void 0,createSession:je.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&Nn(se=>({...se??{},...C.account}));let H=await Ko(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=Ia(a,C);return x(H.message),u?.(H),{proceed:!1}}},[Ko,je.inlineSessionDraft,Pe,u,e,x]),Wo=(0,r.useCallback)(async(a,C)=>{if(Vt.current)return;Vt.current=!0,kt(!0),We("processing"),x(null);let H=C?.sessionId??e,se=C?.nonce??t,j=Po(te,C?.accountPatch),ae=C?.completionPaymentMethodId??$r(a),Je=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let It=await new ln.PaymentAPI(Ye).processPayment(j.userId??"",{sessionId:H,nonce:se,tokenizedData:Je,accountData:{userId:j.userId??"",email:j.email??"",firstName:j.firstName??"",lastName:j.lastName??"",...X?(()=>{let Le=Dt.current,Xt=(0,k.isAVSFieldVisible)(X.state,Le),Zt=(0,k.isAVSFieldVisible)(X.address_line_1,Le),qn=(0,k.isAVSFieldVisible)(X.postal_code,Le),jn=Zt&&!Xt&&qn?(0,k.getStateFromPostalCode)(Le,(gt.current??"").trim()):null,_t=Xt?mn.current:jn;return{country:Le,...qn&&gt.current?{zip:gt.current}:{},...(0,k.isAVSFieldVisible)(X.city,Le)&&Qt.current?{city:Qt.current}:{},..._t?{state:_t}:{},...Zt&&Bt.current?{addressLine1:Bt.current}:{},...(0,k.isAVSFieldVisible)(X.address_line_2,Le)&&Kt.current?{addressLine2:Kt.current}:{}}})():{}},chv:_,avsCheck:ee??!1,checkoutType:A,checkoutLayout:J,avsConfig:X?{country:(0,k.isAVSFieldVisible)(X.country,Dt.current),postal_code:(0,k.isAVSFieldVisible)(X.postal_code,Dt.current),address_line_1:(0,k.isAVSFieldVisible)(X.address_line_1,Dt.current),address_line_2:(0,k.isAVSFieldVisible)(X.address_line_2,Dt.current),city:(0,k.isAVSFieldVisible)(X.city,Dt.current),state:(0,k.isAVSFieldVisible)(X.state,Dt.current)}:void 0});if(It.ok){Qn(H),We("success"),zt(null),await new Promise(Le=>setTimeout(Le,xn)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ae,checkoutMethod:a.isPaypal?"paypal":"card"});return}let nt=await It.json().catch(()=>null);if(nt?.type==="paypal_redirect_required"){let Le=nt.threeDSecureToken,Xt=nt.paymentMethodId||a.id||"";if(!Ue||!Le){We("error"),x("PayPal authorization required but no token provided.");return}try{let Zt=Ke?.getRawProvider();if(!Zt){x("PayPal is not available.");return}let qn={return_url:window.location.href};Xt&&(qn.payment_method=Xt);let{error:jn}=await Zt.confirmPayment({clientSecret:Le,confirmParams:qn,redirect:"if_required"});if(jn){We("error");let _t=jn.message??"PayPal payment failed.";x(_t),ge("paypal",_t,{code:jn.code})}}catch(Zt){We("error"),x(Zt instanceof Error?Zt.message:"PayPal authorization failed.")}return}if(nt?.type==="paypal_direct_required"){let Le=nt.orderId;if(!Le){We("error"),x("PayPal retry required but no order id provided.");return}let Xt=M.current?.attempts??0;if(Xt>=2){We("error"),x("PayPal payment could not be completed after multiple attempts."),ge("paypal","paypal_direct_required retry limit exceeded");return}ao(!1),io("loading"),zt({orderId:Le,attempts:Xt+1}),We(null);return}We("error");let Et=nt?.message??"Payment failed. Please try again.";x(Et),ge(a.isPaypal?"paypal":"card",Et,{code:nt?.code??nt?.gatewayErrorCode,declineCode:nt?.declineCode??nt?.gatewayDeclineReason}),await new Promise(Le=>setTimeout(Le,bn))}catch(Ct){We("error"),x(Ct instanceof Error?Ct.message:"An unexpected error occurred"),await new Promise(It=>setTimeout(It,bn))}finally{kt(!1),We(null),Vt.current=!1}},[Ye,e,t,te,Ut,_,Ue,Ke,s,u,x,ge]),Jt=(0,r.useCallback)((a,C)=>{R?R(a):Wo(a,C)},[R,Wo]),Yo=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(typeof window>"u"||Yo.current)return;let a=new URLSearchParams(window.location.search),C=a.get("payment_intent"),H=a.get("payment_intent_client_secret"),se=a.get("redirect_status");if(!C||!H)return;let j=Et=>{let Le=localStorage.getItem(Et);if(!Le)return null;try{return JSON.parse(Le)}catch{return localStorage.removeItem(Et),null}},ae=j(Cn)??j(ka),Je;if(ae?.clientSecret){if(ae.clientSecret!==H)return;Je={...ae.accountPatch?{accountPatch:ae.accountPatch}:{},...ae.sessionId?{sessionId:ae.sessionId}:{},...ae.nonce?{nonce:ae.nonce}:{}}}else if(ae?.sessionId&&ae.sessionId!==e)return;Yo.current=!0,localStorage.removeItem(Cn),localStorage.removeItem(ka);let Ct=new URL(window.location.href);Ct.searchParams.delete("payment_intent"),Ct.searchParams.delete("payment_intent_client_secret"),Ct.searchParams.delete("redirect_status"),window.history.replaceState({},"",Ct.toString());let It=ae?.paymentMethodType??ae?.tokenType??"card",nt="card";(async()=>{let Et=Ue?.getRawProvider();if(!Et){let _t="Payment is not available \u2014 please refresh and try again.";x(_t),ge(nt,_t);return}if(se==="failed"){let _t="Payment was declined. Please try again.";x(_t),ge(nt,_t);return}let{paymentIntent:Le,error:Xt}=await Et.retrievePaymentIntent(H);if(Xt){let _t=Xt.message??"Failed to retrieve payment status.";x(_t),ge(nt,_t,{code:Xt.code});return}let Zt=Le?.status,qn=Ur(Zt);if(!Le||!qn){let _t=Zt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";x(_t),ge(nt,_t,{code:Zt??"missing_payment_intent"});return}let jn=typeof Le.payment_method=="string"?Le.payment_method:Le.payment_method?.id;Jt({id:jn??ae?.paymentMethodId??ae?.tokenId??Le.id,type:"card",threeDSecureActionResultTokenId:Le.id,gateway:ae?.gateway??"stripe",paymentMethodType:It},Je)})()},[e,Jt,Ue,x,ge]);let so=(0,r.useCallback)(a=>{a.preventDefault()},[]);if(!(Ue!==null))return(0,i.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ur=le==="buttons",$t=K?.variables,si=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),lo=$t?.colorBackground,li=lo&&!si.has(lo)?lo:void 0,pr=p.cardInputBorder??(ur?"#e5e7eb":"#A4A4FF"),co=$t?.colorDanger??"#dc2626",zn=a=>An&&a?co:pr,Tr=(ct.malformed||ct.empty)&&(On||An),ci=Tr?co:zn(Te.zip),uo=p.cardFormContainer?.backgroundColor??li??(ur?"white":"#EDEDFF"),mr=p.cardInputBackground??$t?.colorBackground??"white",po=Yn(G),Go=Yn(ce),Wn=p.nameInput,Jo=p.cardInputFontSize??Vi(Wn?.fontSize)??$t?.fontSizeBase??"16px",Xo=typeof Wn?.fontFamily=="string"?Wn.fontFamily:$t?.fontFamily??"Poppins, sans-serif",Zo=Ea(Wn?.fontWeight)??400,di=p.cardInputColor??(typeof Wn?.color=="string"?Wn.color:void 0)??$t?.colorText??"#262833",ui=p.cardInputPlaceholderColor??"#9ca3af",mt=$t?.borderRadius??"8px",Un=$t?.borderRadius??p.cardButton?.borderRadius??mt,$n=$t?.colorPrimary??"#4A49FF",pi=$t?.colorPrimaryHover??Hr($n,.12),mo=$t?.colorText??"#262833",Qo={fontSize:Jo,fontFamily:Xo,fontWeight:Zo,color:di,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},mi={"--flopay-input-placeholder-color":ui,"--flopay-input-font-size":Jo,"--flopay-input-font-family":Xo,"--flopay-input-font-weight":String(Zo)},yr=p.cardFormContainer??{},yo=yr.padding??(ur?"0":"1rem"),fo=yr.borderRadius??mt,yi=xe&&Nt?(0,i.jsx)(Lr,{capture:xe,html:Nt.html,messageToken:Nt.messageToken,expectedOrigin:Nt.expectedOrigin,theme:v,onReady:()=>{if(!X||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 se=document.activeElement;!!se&&se.tagName==="IFRAME"&&se.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(H)):C>=50&&window.clearInterval(H)},100)},onError:a=>x(a),onValidation:a=>{x(a),a&&We(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"}),ea=(0,i.jsxs)("div",{style:{backgroundColor:uo,borderRadius:fo,...yr,padding:yo,...mi,display:"flex",flexDirection:"column"},children:[(0,i.jsx)("style",{children:`
30
+ `,Xr=44;function To(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 Ki={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Oa={width:"100%",minHeight:Xr,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 Wi(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ba(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function za(e){return e==="paypal"?"PayPal":(0,k.getStripeMethodDisplayName)(e)}function Yi(e,t){let n=`We couldn't open ${za(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ua(e){let t=(0,r.useRef)(0),n=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useCallback)((d=l.current)=>{let y=d;y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),s=(0,r.useCallback)((d,y)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(d),d.timer=setTimeout(()=>{d.timer=null,l.current?.generation===d.generation&&(l.current=null,n.current=d.generation,e(d.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},y))},[o,e]),u=(0,r.useCallback)(d=>{d.yieldedControl&&s(d,600)},[s]),c=(0,r.useCallback)(d=>{o();let y=t.current+1;t.current=y,n.current=null;let I={generation:y,method:d,timer:null,yieldedControl:!1};return l.current=I,y},[o]),R=(0,r.useCallback)(d=>{let y=l.current;return typeof d=="number"&&y?.generation!==d?!1:(o(y),l.current=null,(typeof d!="number"||n.current===d)&&(n.current=null),!0)},[o]),L=(0,r.useCallback)(d=>{let y=l.current,I=d??y?.generation??t.current;(!d||y?.generation===d)&&(o(y),l.current=null),n.current=I},[o]),m=(0,r.useCallback)(d=>n.current===(d??t.current),[]),_=(0,r.useCallback)(d=>l.current?.generation===d&&n.current!==d,[]),S=(0,r.useCallback)(()=>{let d=l.current;d&&u(d)},[u]),T=(0,r.useCallback)(()=>{let d=l.current;d&&(d.yieldedControl=!0,o(d))},[o]);return(0,r.useEffect)(()=>{let d=()=>{document.visibilityState==="visible"?S():T()},y=()=>{T()};return document.addEventListener("visibilitychange",d),window.addEventListener("blur",y),window.addEventListener("focus",S),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("blur",y),window.removeEventListener("focus",S),o()}},[o,T,S]),{startAttempt:c,finishAttempt:R,invalidateAttempt:L,isAttemptInvalidated:m,isAttemptCurrent:_}}function Gi(e){let t=(0,k.getPostalCodeExample)(e);return`Enter a valid ${(0,k.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Ji(e,t,n){let l=(0,k.isPostalCodeSupported)(e),o=t.trim(),s=n&&l,u=s&&!o,c=s&&!!o&&!(0,k.isValidPostalCode)(e,o);return{visible:n,supported:l,required:s,empty:u,malformed:c}}function Ma(e,t){return t instanceof Nt.FloPayError?t:new Nt.FloPayError(t instanceof Error?t.message:`${Wi(e)} before-click hook failed.`,"validation_error")}function Eo(){return(0,i.jsx)("style",{children:Hi})}function Xi(e){return typeof e=="number"?`${e}px`:e}function Aa(e){if(typeof e=="number"||typeof e=="string")return e}function $a(e,t){let n=e.availablePaymentMethods;return n&&t.some(l=>n[l])?"ready":"unavailable"}function qa({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 Fa(e){return e!=="unavailable"&&e!=="load_error"}function Qr(e){return(0,i.jsx)(Qi,{...e})}function Da({sessionId:e,nonce:t,email:n,billingApiUrl:l,onTokenizedBody:o,onErrorChange:s,isProcessing:u=!1,onButtonClick:c,onDecline:R,onTechnicalFailure:L,runBeforeButtonClick:m,onLoadStateChange:_,placeholderBorderRadius:S}){let T=ln(),d=(0,pt.useStripe)(),y=(0,pt.useElements)(),[I,F]=(0,r.useState)("loading");(0,r.useEffect)(()=>{_?.(I)},[I,_]);let[f,H]=(0,r.useState)(!1),X=(0,r.useRef)(!1),fe=(0,r.useRef)(null),ne=(0,r.useRef)(null),[N,ee]=(0,r.useState)(0),[K,ge]=(0,r.useState)(!1),q=(0,r.useRef)(!1),W=(0,r.useRef)(new Map),{startAttempt:se,finishAttempt:Le,invalidateAttempt:be,isAttemptInvalidated:Pe,isAttemptCurrent:te}=Ua((E,oe,de)=>{L?.(E,oe,{...de,popupBlocked:de?.popupBlocked??Ln(oe)}),ge(!0),ee($e=>$e+1)});(0,r.useEffect)(()=>{K&&ne.current?.focus()},[K,N]);let he=(0,r.useCallback)(()=>{ee(E=>E+1)},[]),Ce=(0,r.useCallback)((E,oe,de)=>{be(de),L?.("paypal",E,{code:oe,popupBlocked:Ln(E)}),ge(!0),he()},[be,L,he]),le=(0,r.useCallback)(()=>{window.setTimeout(()=>{(fe.current?.querySelector("iframe")??fe.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{q.current&&(q.current=!1,le())},[le,N]);let Oe=(0,r.useCallback)(()=>{ge(!1),s?.(null),le()},[le,s]);(0,r.useEffect)(()=>{if(!d||X.current)return;let E=new URLSearchParams(window.location.search),oe=E.get("payment_intent"),de=E.get("payment_intent_client_secret"),$e=E.get("redirect_status");if(!oe||!de)return;X.current=!0;let ze;try{let A=localStorage.getItem(Rr);if(A){let Y=JSON.parse(A);Y.clientSecret===de&&(ze={...Y.accountPatch?{accountPatch:Y.accountPatch}:{},...Y.sessionId?{sessionId:Y.sessionId}:{},...Y.nonce?{nonce:Y.nonce}:{}})}}catch{}try{localStorage.removeItem(Rr)}catch{}let Z=new URL(window.location.href);Z.searchParams.delete("payment_intent"),Z.searchParams.delete("payment_intent_client_secret"),Z.searchParams.delete("redirect_status"),window.history.replaceState({},"",Z.toString()),(async()=>{try{if(H(!0),$e==="failed"){let ue="PayPal payment was declined. Please try again.";s?.(ue),R?.(St("paypal",ue));return}let{paymentIntent:A,error:Y}=await d.retrievePaymentIntent(de);if(Y){s?.(Y.message??"Failed to retrieve PayPal payment status.");return}if(A&&(A.status==="requires_capture"||A.status==="succeeded")){let ue=typeof A.payment_method=="string"?A.payment_method:A.payment_method?.id;o({id:ue??A.id,type:"card",threeDSecureActionResultTokenId:A.id,isPaypal:!0},ze)}else{let ue="PayPal payment was not completed. Please try again.";s?.(ue),R?.(St("paypal",ue))}}catch(A){s?.(A instanceof Error?A.message:"Failed to complete PayPal payment.")}finally{H(!1)}})()},[d,o,s,R]);let Ee=(0,r.useCallback)(async E=>{if(u||f){E.reject();return}let oe=m?await m("paypal"):{proceed:!0};if(!oe.proceed){W.current.delete(N),E.reject();return}let de=se("paypal");W.current.set(N,{generation:de,accountPatch:oe.accountPatch,sessionId:oe.sessionId,nonce:oe.nonce}),ge(!1),c?.("paypal"),E.resolve()},[W,u,c,m,se,f,N]),ke=(0,r.useCallback)(async E=>{if(!d||!y)return;let oe=W.current.get(N);if(oe&&!te(oe.generation)){W.current.delete(N);return}if(!oe&&Pe()||oe&&!Le(oe.generation))return;oe||Le();let de=oe??null;if(W.current.delete(N),!de&&m){let A=await m("paypal");if(!A.proceed){E.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}de={accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}}let $e=de?.sessionId??e,ze=de?.nonce??t,Z=de?.accountPatch?.email??n;try{if(H(!0),s?.(null),!$e||!Z)throw new Error("Missing sessionId or email for PayPal payment");let A=d.createPaymentMethod,{error:Y,paymentMethod:ue}=await A({type:"paypal"});if(Y){Ce(Y,"stripe_paypal_create_payment_method_failed",oe?.generation),E.paymentFailed({reason:"fail"});return}let _e=await new dn.PaymentAPI(l).createSessionIntent($e,ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ue?.id??null,intentKind:"payment"});if(_e.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let st=_e.clientSecret,tt={return_url:window.location.href};if(ue?.id&&(tt.payment_method=ue.id),typeof window<"u")try{localStorage.setItem(Rr,JSON.stringify({clientSecret:st,sessionId:$e,nonce:ze,accountPatch:de?.accountPatch}))}catch{}let{error:et,paymentIntent:p}=await d.confirmPayment({clientSecret:st,confirmParams:tt,redirect:"if_required"});if(et){if(typeof window<"u")try{localStorage.removeItem(Rr)}catch{}if(wr(et)){let qe=et.message??"Your payment was declined.";s?.(qe),R?.(St("paypal",qe,{code:Bn(et),declineCode:ar(et)})),await Zr({billingApiUrl:l,sessionId:$e,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Bn(et)??"provider_declined"}})}else Ce(et,"stripe_paypal_confirm_failed",oe?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Rr)}catch{}let je=typeof p?.payment_method=="string"?p.payment_method:p?.payment_method?.id;o({id:je??p?.id,type:"card",threeDSecureActionResultTokenId:p?.id,isPaypal:!0},{accountPatch:de?.accountPatch,sessionId:$e,nonce:ze});return}catch(A){Ce(A,"stripe_paypal_failed",oe?.generation)}finally{H(!1)}},[d,y,e,t,n,l,o,s,R,m,Ce,Le,te,Pe,N]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(qa,{state:I,placeholderTestId:"flopay-paypal-placeholder",borderRadius:S,children:(0,i.jsxs)("div",{ref:fe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[K&&(0,i.jsx)("button",{ref:ne,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Oe,style:Oa,children:"Try PayPal again"}),(0,i.jsx)(pt.ExpressCheckoutElement,{onReady:E=>F($a(E,["paypal"])),onLoadError:()=>{F("load_error"),xo(xt(T),"paypal","paypal")},onClick:Ee,onConfirm:ke,onCancel:()=>{let E=W.current.get(N);W.current.delete(N),xt(T)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be(E?.generation),ge(!1),q.current=!0,he()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},N)]})}),f&&(0,i.jsx)(Sn,{status:"processing"})]})}function La({sessionId:e,nonce:t,email:n,billingApiUrl:l,intentKind:o,expressMethods:s,onTokenizedBody:u,onErrorChange:c,onButtonClick:R,onDecline:L,onTechnicalFailure:m,runBeforeButtonClick:_,onLoadStateChange:S,placeholderBorderRadius:T}){let d=ln(),y=(0,pt.useStripe)(),I=(0,pt.useElements)(),[F,f]=(0,r.useState)("loading");(0,r.useEffect)(()=>{S?.(F)},[F,S]);let[H,X]=(0,r.useState)(!1),fe=(0,r.useRef)(null),ne=(0,r.useRef)(null),[N,ee]=(0,r.useState)(0),[K,ge]=(0,r.useState)(!1),[q,W]=(0,r.useState)("google_pay"),se=(0,r.useRef)(!1),Le=(0,r.useRef)("google_pay"),be=(0,r.useRef)("google_pay"),Pe=(0,r.useRef)(new Map),{startAttempt:te,finishAttempt:he,invalidateAttempt:Ce,isAttemptInvalidated:le,isAttemptCurrent:Oe}=Ua((Z,A,Y)=>{m?.(Z,A,{...Y,popupBlocked:Y?.popupBlocked??Ln(A)}),W(Z),ge(!0),ee(ue=>ue+1)});(0,r.useEffect)(()=>{K&&ne.current?.focus()},[K,N]);let Ee=(0,r.useCallback)(()=>{ee(Z=>Z+1)},[]),ke=(0,r.useCallback)((Z,A,Y,ue)=>{Ce(ue),m?.(Z,A,{code:Y,popupBlocked:Ln(A)}),W(Z),ge(!0),Ee()},[Ce,m,Ee]),E=(0,r.useCallback)(()=>{window.setTimeout(()=>{(fe.current?.querySelector("iframe")??fe.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{se.current&&(se.current=!1,E())},[E,N]);let oe=(0,r.useCallback)(()=>{ge(!1),c?.(null),E()},[E,c]),de=(0,r.useCallback)(async Z=>{if(!y||!I)return;let A=Pe.current.get(N);if(A&&!Oe(A.generation)){Pe.current.delete(N);return}if(!A&&le()||A&&!he(A.generation))return;A||he();let Y=Z.expressPaymentType??A?.method??Le.current,ue=A??null;Pe.current.delete(N);let _e=Ba(Y);if(!ue&&_){let je=await _(_e);if(!je.proceed){Z.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}ue={accountPatch:je.accountPatch,sessionId:je.sessionId,nonce:je.nonce}}let st=_e,tt=ue?.sessionId??e,et=ue?.nonce??t,p=ue?.accountPatch?.email??n;try{X(!0),c?.(null);let{error:je}=await I.submit();if(je){ke(Y,je,"stripe_wallet_submit_failed",A?.generation);return}let{error:qe,paymentMethod:Ge}=await y.createPaymentMethod({elements:I});if(qe||!Ge){ke(Y,qe??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",A?.generation);return}if(!tt||!p)throw new Error("Missing sessionId or email for wallet payment");let Ve=await new dn.PaymentAPI(l).createSessionIntent(tt,et??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Y??_e,paymentMethodId:Ge.id,intentKind:o});if(Ve.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Wt=Ve.clientSecret,{error:ht,intentId:wt}=(0,Nt.isSetupIntentClientSecret)(Wt)?await y.confirmCardSetup(Wt,{payment_method:Ge.id}).then(g=>({error:g.error,intentId:g.setupIntent?.id})):await y.confirmCardPayment(Wt,{payment_method:Ge.id}).then(g=>({error:g.error,intentId:g.paymentIntent?.id}));if(ht){if(wr(ht)){let g=ht.message??"Your payment was declined.";c?.(g),L?.(St(st,g,{code:Bn(ht),declineCode:ar(ht)})),await Zr({billingApiUrl:l,sessionId:tt,nonce:et,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Y??_e,providerDeclineReason:Bn(ht)??"provider_declined"}})}else ke(Y,ht,"stripe_wallet_confirm_failed",A?.generation);return}u({id:Ge.id,type:"card",threeDSecureActionResultTokenId:wt},{accountPatch:ue?.accountPatch,sessionId:tt,nonce:et})}catch(je){ke(Y,je,"stripe_wallet_failed",A?.generation)}finally{X(!1)}},[y,I,e,t,n,l,o,u,c,L,_,ke,he,Oe,le,N]),$e=(0,r.useMemo)(()=>{let Z=["applePay","googlePay","paypal","link","amazonPay","klarna"],A=new Set(["applePay","googlePay"]),Y=new Set(s.map(k.stripeExpressMethodToOptionKey)),ue={};for(let _e of Z)Y.has(_e)?ue[_e]=A.has(_e)?"always":"auto":ue[_e]="never";return ue},[s]),ze=(0,r.useMemo)(()=>s.map(k.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(qa,{state:F,placeholderTestId:"flopay-wallet-placeholder",borderRadius:T,children:(0,i.jsxs)("div",{ref:fe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[K&&(0,i.jsxs)("button",{ref:ne,type:"button","data-testid":"flopay-wallet-retry-button",onClick:oe,style:Oa,children:["Try ",za(q)," again"]}),(0,i.jsx)(pt.ExpressCheckoutElement,{onReady:Z=>{f($a(Z,ze))},onLoadError:Z=>{f("load_error"),xo(xt(d),"stripe","wallet")},onClick:async Z=>{Le.current=Z.expressPaymentType,be.current=Ba(Z.expressPaymentType);let A=_?await _(be.current):{proceed:!0};if(!A.proceed){Pe.current.delete(N),Z.reject();return}let Y=te(Z.expressPaymentType);Pe.current.set(N,{generation:Y,method:Z.expressPaymentType,accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}),ge(!1),R?.(be.current),Z.resolve()},onConfirm:de,onCancel:()=>{let Z=Pe.current.get(N);Pe.current.delete(N),xt(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Ce(Z?.generation),ge(!1),se.current=!0,Ee()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:$e,layout:{maxColumns:1,overflow:"never"}}},N)]})}),H&&(0,i.jsx)(Sn,{status:"processing"})]})}function Zi({method:e,themeId:t,submitting:n=!1,disabled:l=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:u,backgroundColor:c,borderColor:R,textColor:L,borderRadius:m,fontFamily:_}){let S=(0,k.resolveStripeMethodBrandVariant)(e,t),T=fa[e],d=S?.backgroundColor??c??"#ffffff",y=S?.borderColor??R??"#d1d5db",I=S?.textColor??L??"#262833";return(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!l&&u()},disabled:n||l,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Xr,padding:"0 1rem",backgroundColor:d,color:I,border:`1px solid ${y}`,borderRadius:m??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,k.getStripeMethodDisplayName)(e)}\u2026`}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,k.hasVendoredStripeMethodLogo)(e)?8:0},children:[T?(0,i.jsx)("img",{src:T,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):S?.logoSvg?(0,i.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:S.logoSvg}}):null,(0,i.jsx)("span",{children:(0,k.getStripeMethodDisplayName)(e)})]}),s&&(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:I,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,i.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function _o({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:u,onErrorChange:c,onDecline:R,onCancel:L,runBeforeButtonClick:m,onButtonClick:_,isProcessing:S,submitButtonColor:T,submitButtonBorderRadius:d,submitButtonStyle:y,errorText:I}){let F=ln(),f=(0,pt.useStripe)(),H=(0,pt.useElements)(),[X,fe]=(0,r.useState)(!1),ne=(0,r.useRef)(!1),[N,ee]=(0,r.useState)(!1),[K,ge]=(0,r.useState)("loading"),q=(0,r.useCallback)(async()=>{if(!f||!H||S||ne.current||!N)return;ne.current=!0,fe(!0);let W=m?await m("card"):{proceed:!0};if(!W.proceed){ne.current=!1,fe(!1);return}_?.("card");let se=W.sessionId??t,Le=W.nonce??n,be=W.accountPatch?.email??l;try{c?.(null);let Pe=await H.submit();if(Pe.error){c?.(Pe.error.message??"Payment failed.");return}let te=await f.createPaymentMethod({elements:H});if(te.error||!te.paymentMethod){c?.(te.error?.message??"Failed to create payment method.");return}let he=te.paymentMethod;if(!se||!be)throw new Error("Missing sessionId or email for payment.");let Ce=he.type||e,le=await new dn.PaymentAPI(s).createSessionIntent(se,Le??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Ce,paymentMethodId:null,intentKind:"payment"});if(le.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Oe=le.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Oe,sessionId:se,nonce:Le,accountPatch:W.accountPatch,paymentMethodId:he.id,paymentMethodType:he.type??e,gateway:"stripe"}))}catch{}let{error:Ee,paymentIntent:ke}=await f.confirmPayment({clientSecret:Oe,confirmParams:{return_url:window.location.href,payment_method:he.id},redirect:"if_required"});if(Ee){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let de=Ee.message??"Payment failed.";c?.(de),R?.(St("card",de,{code:Ee.code})),await Zr({billingApiUrl:s,sessionId:se,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ee.code??"provider_declined"}});return}let E=ke?.status;if(!Hr(E)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let de=E==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";c?.(de),R?.(St("card",de,{code:E??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let oe=typeof ke?.payment_method=="string"?ke.payment_method:ke?.payment_method?.id;u({id:oe??he.id,type:"card",threeDSecureActionResultTokenId:ke?.id,gateway:"stripe",paymentMethodType:he.type??e},{accountPatch:W.accountPatch,sessionId:se,nonce:Le})}catch(Pe){c?.(Pe instanceof Error?Pe.message:"Payment failed. Please try again.")}finally{ne.current=!1,fe(!1)}},[f,H,S,N,m,_,t,n,l,s,e,u,c,R]);return(0,i.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,i.jsx)(pt.PaymentElement,{onReady:()=>ge("ready"),onLoadError:()=>{ge("load_error"),xo(xt(F),"stripe","apm")},onChange:W=>{ee(!!W.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:()=>{q()},disabled:!N||X||S||K!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:T,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!N||X||S||K!=="ready"?"not-allowed":"pointer",opacity:!N||X||S||K!=="ready"?.5:1,transition:"opacity 120ms ease-out",...y??{}},children:X?"Processing\u2026":`Pay with ${(0,k.getStripeMethodDisplayName)(e)}`}),I&&(0,i.jsx)(nr,{margin:"0.75rem 0 0",children:I})]})}function Na({sessionId:e,nonce:t,email:n,billingName:l,billingApiUrl:o,paymentElementMethods:s,stripeInstance:u,paymentElementBaseOptions:c,onTokenizedBody:R,onErrorChange:L,onButtonClick:m,onDecline:_,runBeforeButtonClick:S,onLoadStateChange:T,isProcessing:d=!1,submitButtonColor:y="#4A49FF",submitButtonBorderRadius:I=8,submitButtonStyle:F,buttonAppearance:f,themeId:H,onExpandApm:X,expandedApmMethod:fe}){let[ne,N]=(0,r.useState)(null),[ee,K]=(0,r.useState)(null),ge=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&u?T?.("ready"):u||T?.("loading")},[s.length,u,T]);let q=(0,r.useCallback)(async te=>{if(!u||ge.current||d)return;ge.current=!0,K(te);let he=S?await S("card"):{proceed:!0};if(!he.proceed){ge.current=!1,K(null);return}m?.("card");let Ce=he.sessionId??e,le=he.nonce??t,Oe=he.accountPatch?.email??n;try{if(L?.(null),!Ce||!Oe)throw new Error("Missing sessionId or email for payment.");let Ee=await new dn.PaymentAPI(o).createSessionIntent(Ce,le??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,paymentMethodId:null,intentKind:"payment"});if(Ee.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ke=Ee.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:ke,sessionId:Ce,nonce:le,accountPatch:he.accountPatch,paymentMethodType:te,gateway:"stripe"}))}catch{}let{error:E,paymentIntent:oe}=await u.confirmPayment({clientSecret:ke,confirmParams:{return_url:window.location.href,payment_method_data:{type:te,billing_details:{name:l&&l.trim().length>=3?l.trim():"FloPay Customer",...Oe?{email:Oe}:{}}}},redirect:"if_required"});if(E){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=E.message??"Payment failed.";L?.(ze),_?.(St("card",ze,{code:E.code})),await Zr({billingApiUrl:o,sessionId:Ce,nonce:le,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,providerDeclineReason:E.code??"provider_declined"}});return}let de=oe?.status;if(!Hr(de)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=de==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";L?.(ze),_?.(St("card",ze,{code:de??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let $e=typeof oe?.payment_method=="string"?oe.payment_method:oe?.payment_method?.id;R({id:$e??oe?.id,type:"card",threeDSecureActionResultTokenId:oe?.id,gateway:"stripe",paymentMethodType:te},{accountPatch:he.accountPatch,sessionId:Ce,nonce:le})}catch(Ee){L?.(Ee instanceof Error?Ee.message:"Payment failed. Please try again.")}finally{ge.current=!1,K(null)}},[u,d,S,m,e,t,n,o,l,R,L,_]),[W,se]=(0,r.useState)(null),Le=X?fe??null:W,be=(0,r.useCallback)(te=>{ge.current||d||Le&&Le!==te||((0,k.needsStripeMethodExplicitConfirm)(te)?X?X(te):se(te):q(te))},[Le,d,q,X]),Pe=(0,r.useMemo)(()=>W?{...c,paymentMethodTypes:[W]}:null,[W,c]);return(0,i.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(te=>{let he=fe===te,Ce=ee===te,le=ee!==null&&ee!==te||fe!=null&&fe!==te;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(Zi,{method:te,themeId:H,submitting:Ce,disabled:le,highlighted:he,hasNextStep:(0,k.needsStripeMethodExplicitConfirm)(te),onClick:()=>be(te),backgroundColor:f?.backgroundColor,borderColor:f?.borderColor,textColor:f?.textColor,borderRadius:f?.borderRadius,fontFamily:f?.fontFamily}),!X&&W===te&&Pe&&u&&(0,i.jsx)(pt.Elements,{stripe:u,options:Pe,children:(0,i.jsx)(_o,{method:te,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:R,onErrorChange:L,onDecline:_,onCancel:()=>se(null),runBeforeButtonClick:S,onButtonClick:m,isProcessing:d,submitButtonColor:y,submitButtonBorderRadius:I,submitButtonStyle:F})},te)]},te)})})}function Qi({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:u,onDecline:c,onTokenizedBody:R,firstName:L,lastName:m,chv:_,className:S,isProcessing:T,error:d,onErrorChange:y,showPayPal:I=!0,showStripe:F=!0,enabledPaymentMethods:f,enabledPaymentMethodCountries:H,showApplePay:X=!0,showGooglePay:fe=!0,layout:ne="default",theme:N,buttonsTheme:ee,buttonsStyles:K,appearance:ge,cardButtonContent:q,cardBackButtonContent:W,cardTitleContent:se,showSecurityFooter:Le,onButtonClick:be,onBeforeButtonClick:Pe,enableAVS:te,cardFieldOrder:he,cardPreFormSlot:Ce,avsLayout:le="row",country:Oe,zip:Ee,addressLine1:ke,addressLine2:E,city:oe,state:de,onCountryChange:$e,onZipChange:ze,avsCheck:Z,checkoutType:A,checkoutLayout:Y,totalAmount:ue=0,currency:_e="usd",initialCardOpen:st=!1,directPaypal:tt,isSubscription:et=!1,session:p,debug:je=!1}){let qe=ln(),Ge=qr(),Ve=(0,r.useContext)(sn),Wt=Vr(),[ht,wt]=(0,r.useState)(!1),[g,Re]=(0,r.useState)(null),[He,lt]=(0,r.useState)(Oe??"US"),[it,nt]=(0,r.useState)(Ee??""),[Je,Se]=(0,r.useState)(ke??""),[Pt,Ke]=(0,r.useState)(E??""),[zt,kt]=(0,r.useState)(oe??""),[yn,Rn]=(0,r.useState)(de??""),[In,On]=(0,r.useState)({}),gt=(0,r.useRef)(Ee??""),Ut=(0,r.useRef)(Oe??"US"),Mt=(0,r.useRef)(ke??""),Yt=(0,r.useRef)(E??""),tn=(0,r.useRef)(oe??""),fn=(0,r.useRef)(de??""),G=(0,r.useMemo)(()=>(0,k.resolveAVSConfig)(te),[te]),An=G!==null,gn=!!p?.vault?.html,$t=!!p?.gateways?.pcivault,B=!!(p?.gateways?.stripe?.enabledPaymentMethods??f)?.includes("card"),Xe=gn||B||$t,Ie=!!(F&&Xe&&qe&&e),[Fn,We]=(0,r.useState)(()=>ne!=="buttons"||st?e??null:null),[zn,hn]=(0,r.useState)(0),Pn=ne!=="buttons"||st||!!e&&Fn===e,rt=(0,r.useMemo)(()=>!qe||!Ie||!e||!Pn?null:qe.cardCapture({sessionId:e}),[qe,Ie,e,Pn]),Rt=(0,r.useMemo)(()=>{let a=He,v=G?(0,k.isAVSFieldVisible)(G.postal_code,a):!1;return Ji(a,it,v)},[G,He,it]),{avsInvalid:qt,invalidAvsFields:At}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!Ie||!G)return{avsInvalid:!1,invalidAvsFields:a};let v=He,V=(re,Ze)=>(0,k.isAVSFieldVisible)(re,v)&&!Ze.trim(),ie={line1:V(G.address_line_1,Je),city:V(G.city,zt),state:V(G.state,yn),zip:Rt.empty||Rt.malformed};return{avsInvalid:ie.line1||ie.city||ie.state||ie.zip,invalidAvsFields:ie}},[Ie,G,He,Je,zt,yn,Rt]),[Gt,nn]=(0,r.useState)(!1),[En,Jt]=(0,r.useState)(!1),[Ft,Xt]=(0,r.useState)(()=>Io(p?.vault)),[ve,mt]=(0,r.useState)(st&&Xe?"card":"buttons"),[ct,bn]=(0,r.useState)(null),Un=ve==="expanding"||ve==="card",Dt=280,Vt=(0,r.useRef)(null),bt=(0,r.useCallback)(a=>{Vt.current&&clearTimeout(Vt.current),Vt.current=setTimeout(()=>{Vt.current=null,a()},Dt)},[Dt]);(0,r.useEffect)(()=>()=>{Vt.current&&clearTimeout(Vt.current)},[]);let Jn=(0,r.useCallback)(()=>{We(e??null),hn(a=>a+1),mt("expanding"),bt(()=>mt("card"))},[bt,e]),Ht=(0,r.useCallback)(()=>{mt("collapsing"),bt(()=>mt("buttons"))},[bt]),M=(0,r.useCallback)(a=>{bn(a),mt("apm-expanding"),bt(()=>mt("apm-form"))},[bt]),Q=(0,r.useCallback)(()=>{mt("apm-collapsing"),bt(()=>{mt("buttons"),bn(null)})},[bt]);(0,r.useEffect)(()=>{ne==="buttons"&&st&&Xe&&(We(e??null),mt("card"))},[ne,st,Xe,e]);let[j,b]=(0,r.useState)(null),ce=(0,r.useRef)(!1),[$,h]=(0,r.useState)(null),Be=(0,r.useRef)($);(0,r.useEffect)(()=>{Be.current=$},[$]);let pe=n||Wt,Ue=d??g,xe=(0,r.useMemo)(()=>(0,Nt.resolveTheme)(N),[N]),O=(0,r.useMemo)(()=>{let a=xe?.buttonsLayout??(0,k.resolveButtonsLayoutTheme)(ee);return K?{...a,...K,cardButton:{...a.cardButton,...K.cardButton},cardFormContainer:{...a.cardFormContainer,...K.cardFormContainer},backButton:{...a.backButton,...K.backButton},backButtonIcon:{...a.backButtonIcon,...K.backButtonIcon},submitButton:{...a.submitButton,...K.submitButton},title:{...a.title,...K.title}}:a},[xe,ee,K]),Bt=ge??xe?.appearance,z=(0,r.useMemo)(()=>{let a=Bt?.variables,v=Ze=>typeof Ze=="string"&&Ze?Ze:void 0,V=O.submitButton,ie=v(a?.colorPrimary)??v(V?.backgroundColor)??"#4A49FF",U=ne==="buttons",re=O.nameInput;return{primaryColor:ie,primaryHoverColor:v(a?.colorPrimaryHover)??Jr(ie,.12),inputBackgroundColor:v(O.cardInputBackground)??v(a?.colorBackground)??"#ffffff",textColor:v(O.cardInputColor)??v(re?.color)??v(a?.colorText)??"#262833",borderColor:v(O.cardInputBorder)??(U?"#e5e7eb":"#A4A4FF"),placeholderColor:v(O.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(re?.fontFamily)??v(a?.fontFamily)??"Poppins, sans-serif",fontSize:v(O.cardInputFontSize)??v(a?.fontSizeBase)??"16px",fontWeight:String(Aa(re?.fontWeight)??400),borderRadius:v(a?.borderRadius)??"8px"}},[Bt,O,ne]),P=Ve.inlineSessionPatchProcessing??!1,w=(T??ht)||P,me=pe.replace(/\/+$/,""),J=(0,r.useMemo)(()=>ko({userId:o,email:l,firstName:L,lastName:m,country:Oe,zip:Ee},In),[o,l,L,m,Oe,Ee,In]),Ye=[J.firstName,J.lastName].filter(a=>!!a?.trim()).join(" "),dt=(0,r.useMemo)(()=>qe?qe.getRawProvider():null,[qe]),Me=(0,r.useMemo)(()=>Ge?Ge.getRawProvider():null,[Ge]),we=ue||100,ae=(0,r.useMemo)(()=>Bt?(0,dn.toStripeAppearance)(Bt):null,[Bt]),Fe=ae?{appearance:ae}:null,rn=(0,r.useMemo)(()=>{let a=ae??{},v=a.rules??{};return{...a,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[ae]),Kt=(0,r.useMemo)(()=>{let a=Sa(ue);return{...a,currency:_e.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...Fe}},[ue,_e,Fe]),Lt=(0,r.useMemo)(()=>({mode:"payment",amount:we,currency:_e.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Fe}),[we,_e,Fe]),ye=(0,r.useCallback)(a=>{Re(a),y?.(a)},[y]);(0,r.useEffect)(()=>{!Ie||!rt||rt.setCardFieldOrder?.(he??null,G==null)},[Ie,rt,he,G]),(0,r.useEffect)(()=>{(ve==="expanding"||ve==="collapsing"||ve==="apm-expanding"||ve==="apm-collapsing")&&ye(null)},[ve,ye]);let on=(0,r.useCallback)((a,v,V)=>{c?.(St(a,v,V))},[c]),Xn=(0,r.useCallback)((a,v,V)=>{let ie=V?.popupBlocked??Ln(v),U=Yi(a,ie),re=Wn(V?.code)??Bn(v)??"external_payment_method_failed",Ze=new Nt.FloPayError(U,"api_error",{code:"external_payment_method_failed",param:a});b(null),ne==="buttons"&&(mt("buttons"),bn(null)),ye(U),u?.(Ze),console.error("[FloPay] External payment method failed:",{method:a,code:re,popupBlocked:ie})},[ne,u,ye]);(0,r.useEffect)(()=>{if(!Ie||!e){Xt(null);return}let a=Io(p?.vault);if(a){Xt(a);return}if(!Pn){Xt(null);return}Xt(null);let v=!0;return new dn.PaymentAPI(me).getVaultCapture(e,t).then(V=>{if(!v)return;let ie=Io(V);ie?Xt(ie):ye("Failed to load the secure card form.")}).catch(V=>{v&&ye(V instanceof Error?V.message:"Failed to load the secure card form.")}),()=>{v=!1}},[Ie,Pn,zn,e,p?.vault?.html,p?.vault?.messageToken,p?.vault?.expectedOrigin,me,t,ye]);let $n=(0,r.useRef)({onComplete:s,onError:u,updateError:ye,emitDecline:on,resolvedAccount:J,avsConfig:G,avsCheckProp:Z,sessionId:e,nonce:t,baseUrl:me});$n.current={onComplete:s,onError:u,updateError:ye,emitDecline:on,resolvedAccount:J,avsConfig:G,avsCheckProp:Z,sessionId:e,nonce:t,baseUrl:me};let lo=(0,r.useRef)(!1),oi=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:v,avsCheckProp:V}=$n.current,ie=Ut.current||a.country||"US",U=v?(0,k.isAVSFieldVisible)(v.state,ie):!1,re=v?(0,k.isAVSFieldVisible)(v.address_line_1,ie):!1,Ze=v?(0,k.isAVSFieldVisible)(v.postal_code,ie):!1,vt=v?(0,k.isAVSFieldVisible)(v.city,ie):!1,It=v?(0,k.isAVSFieldVisible)(v.address_line_2,ie):!1,ot=re&&!U&&Ze?(0,k.getStateFromPostalCode)(ie,(gt.current??"").trim()):null,Et=U?fn.current:ot;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Ze&&gt.current?{zip:gt.current}:{},...vt&&tn.current?{city:tn.current}:{},...Et?{state:Et}:{},...re&&Mt.current?{addressLine1:Mt.current}:{},...It&&Yt.current?{addressLine2:Yt.current}:{},country:ie},...V!==void 0?{avsCheck:V}:{},...v?{avsConfig:{country:(0,k.isAVSFieldVisible)(v.country,ie),postal_code:Ze,address_line_1:re,address_line_2:It,city:vt,state:U}}:{}}},[]);(0,r.useEffect)(()=>{!Ie||!rt||rt.setSubmitGate?.(qt)},[Ie,rt,qt]),(0,r.useEffect)(()=>{if(!Ie||!rt)return;lo.current=!1;let a=!1,v=rt.on("submitting",()=>{nn(!0),b("processing");let{baseUrl:re,sessionId:Ze,nonce:vt,updateError:It,onError:ot}=$n.current;!Ze||!vt||new dn.PaymentAPI(re).patchAccountSnapshot(Ze,vt,oi(),{telemetryMode:"best_effort"}).catch(Et=>{if(!Vi(Et))return;let Ne=Et instanceof Error?Et.message:"Please check your billing address and try again.";It(Ne),b(null),ot?.(Et instanceof Nt.FloPayError?Et:new Nt.FloPayError(Ne,"api_error"))})}),V=rt.on("complete",async re=>{or(re.sessionId??$n.current.sessionId),b("success"),await new Promise(Ze=>setTimeout(Ze,Tn)),!lo.current&&(lo.current=!0,$n.current.onComplete?.({status:"succeeded",paymentIntentId:re.intentId,checkoutMethod:"card"}))}),ie=rt.on("decline",async re=>{let{updateError:Ze,emitDecline:vt}=$n.current,It=re.message??"Your payment was declined. Please try another card or contact your bank.";Ze(It),b("error"),vt("card",It,re.declineReason?{declineCode:re.declineReason}:void 0),await new Promise(ot=>setTimeout(ot,Cn)),!a&&b(null)}),U=rt.on("error",async re=>{let{updateError:Ze,onError:vt}=$n.current,It=re.message??"There was a problem processing your payment. Please try again.";Ze(It),b("error"),vt?.(new Nt.FloPayError(It,"api_error")),await new Promise(ot=>setTimeout(ot,Cn)),!a&&b(null)});return()=>{a=!0,v(),V(),ie(),U()}},[Ie,rt]);let vn=!!tt?.clientId,dr=Array.isArray(f),xr=dr&&f.length>0,ai=dr&&f.includes("paypal"),{expressMethods:Tr,paymentElementMethods:ur}=(0,r.useMemo)(()=>(0,k.partitionStripeMethods)(f,{excludePaypal:vn}),[f,vn]),Oo=vn||!!Ge,ii=(0,r.useMemo)(()=>Oo?Tr.filter(a=>a!=="paypal"):Tr,[Tr,Oo]),si=(0,r.useMemo)(()=>{let a=[];return X&&a.push("apple_pay"),fe&&a.push("google_pay"),a},[X,fe]),Br=dr?ii:si,li=F&&Br.length>0,co=An?He:Oe,Mr=(0,r.useMemo)(()=>{let a=co?.trim().toUpperCase();return a?H?ur.filter(v=>{let V=H[v];return!V||V.length===0||V.includes(a)}):(0,k.filterStripeMethodsByCountry)(ur,co):ur},[ur,co,H]),uo=(0,r.useMemo)(()=>({mode:"payment",amount:we,currency:_e.toLowerCase(),paymentMethodCreation:"manual",appearance:rn}),[we,_e,rn]),[zo,Uo]=(0,r.useState)("loading"),[$o,qo]=(0,r.useState)("loading"),[jo,Vo]=(0,r.useState)("loading"),[ci,po]=(0,r.useState)(!1),[Ho,mo]=(0,r.useState)("loading"),[Ar,di]=(0,r.useState)();(0,r.useEffect)(()=>{di(ka())},[]);let Ko=I&&(vn||(dr?ai:Ar===!1)),Wo=F&&li,pr=Ko&&vn,Yo=Ho==="retrying"||Ho==="exhausted",mr=Ko&&!!Me&&(!vn||Yo),yr=Wo&&!!dt,fr=F&&xr&&Mr.length>0&&!!dt,ui=pr&&!Yo?ci:mr&&Fa(zo),pi=yr&&Fa($o),mi=fr&&jo!=="load_error",Go=a=>a==="loading"||a==="ready",Jo=pr||mr&&Go(zo)||yr&&Go($o)||fr&&jo!=="load_error",Fr=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!Fr.current){if(!F&&!I){Fr.current=!0;let a=new Nt.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(a),ye(a.message)}else if(!F&&I&&!vn&&!Me){Fr.current=!0;let a=new Nt.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(a),ye(a.message)}else if(Ar!==void 0&&!Xe&&!Jo){Fr.current=!0;let a=new Nt.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"});u?.(a),ye(a.message)}}},[F,I,vn,Me,Ar,Xe,Jo,u,ye]);let Xo=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(Xo.current||!xr)return;let a=[];X!==!0&&a.push("showApplePay"),fe!==!0&&a.push("showGooglePay"),a.length!==0&&(Xo.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.`))},[xr,X,fe]);let Zo=(0,r.useCallback)((a,v)=>Ve.applyInlineSessionPatch?Ve.applyInlineSessionPatch(a).then(V=>({error:null,sessionId:V.sessionId||e,nonce:V.session?.clientSecret||t})).catch(V=>{let ie=Ma(v,V);return ye(ie.message),u?.(ie),{error:ie,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ve.applyInlineSessionPatch,t,u,e,ye]),an=(0,r.useCallback)(async a=>{if(!Pe)return{proceed:!0};try{let v=await Pe({method:a,sessionId:e||void 0,createSession:Ve.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&On(ie=>({...ie??{},...v.account}));let V=await Zo(v,a);return V.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:V.sessionId,nonce:V.nonce}}return{proceed:!0}}catch(v){let V=Ma(a,v);return ye(V.message),u?.(V),{proceed:!1}}},[Zo,Ve.inlineSessionDraft,Pe,u,e,ye]),Qo=(0,r.useCallback)(async(a,v)=>{if(ce.current)return;ce.current=!0,wt(!0),b("processing"),ye(null);let V=v?.sessionId??e,ie=v?.nonce??t,U=ko(J,v?.accountPatch),re=v?.completionPaymentMethodId??Kr(a),Ze=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let It=await new dn.PaymentAPI(me).processPayment(U.userId??"",{sessionId:V,nonce:ie,tokenizedData:Ze,accountData:{userId:U.userId??"",email:U.email??"",firstName:U.firstName??"",lastName:U.lastName??"",...G?(()=>{let Ne=Ut.current,Qt=(0,k.isAVSFieldVisible)(G.state,Ne),en=(0,k.isAVSFieldVisible)(G.address_line_1,Ne),Hn=(0,k.isAVSFieldVisible)(G.postal_code,Ne),Kn=en&&!Qt&&Hn?(0,k.getStateFromPostalCode)(Ne,(gt.current??"").trim()):null,_t=Qt?fn.current:Kn;return{country:Ne,...Hn&&gt.current?{zip:gt.current}:{},...(0,k.isAVSFieldVisible)(G.city,Ne)&&tn.current?{city:tn.current}:{},..._t?{state:_t}:{},...en&&Mt.current?{addressLine1:Mt.current}:{},...(0,k.isAVSFieldVisible)(G.address_line_2,Ne)&&Yt.current?{addressLine2:Yt.current}:{}}})():{}},chv:_,avsCheck:Z??!1,checkoutType:A,checkoutLayout:Y,avsConfig:G?{country:(0,k.isAVSFieldVisible)(G.country,Ut.current),postal_code:(0,k.isAVSFieldVisible)(G.postal_code,Ut.current),address_line_1:(0,k.isAVSFieldVisible)(G.address_line_1,Ut.current),address_line_2:(0,k.isAVSFieldVisible)(G.address_line_2,Ut.current),city:(0,k.isAVSFieldVisible)(G.city,Ut.current),state:(0,k.isAVSFieldVisible)(G.state,Ut.current)}:void 0});if(It.ok){or(V),b("success"),h(null),await new Promise(Ne=>setTimeout(Ne,Tn)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:re,checkoutMethod:a.isPaypal?"paypal":"card"});return}let ot=await It.json().catch(()=>null);if(ot?.type==="paypal_redirect_required"){let Ne=ot.threeDSecureToken,Qt=ot.paymentMethodId||a.id||"";if(!qe||!Ne){b("error"),ye("PayPal authorization required but no token provided.");return}try{let en=Ge?.getRawProvider();if(!en){ye("PayPal is not available.");return}let Hn={return_url:window.location.href};Qt&&(Hn.payment_method=Qt);let{error:Kn}=await en.confirmPayment({clientSecret:Ne,confirmParams:Hn,redirect:"if_required"});if(Kn){b("error");let _t=Kn.message??"PayPal payment failed.";ye(_t),on("paypal",_t,{code:Kn.code})}}catch(en){b("error"),ye(en instanceof Error?en.message:"PayPal authorization failed.")}return}if(ot?.type==="paypal_direct_required"){let Ne=ot.orderId;if(!Ne){b("error"),ye("PayPal retry required but no order id provided.");return}let Qt=Be.current?.attempts??0;if(Qt>=2){b("error"),ye("PayPal payment could not be completed after multiple attempts."),on("paypal","paypal_direct_required retry limit exceeded");return}po(!1),mo("loading"),h({orderId:Ne,attempts:Qt+1}),b(null);return}b("error");let Et=ot?.message??"Payment failed. Please try again.";ye(Et),on(a.isPaypal?"paypal":"card",Et,{code:ot?.code??ot?.gatewayErrorCode,declineCode:ot?.declineCode??ot?.gatewayDeclineReason}),await new Promise(Ne=>setTimeout(Ne,Cn))}catch(vt){b("error"),ye(vt instanceof Error?vt.message:"An unexpected error occurred"),await new Promise(It=>setTimeout(It,Cn))}finally{wt(!1),b(null),ce.current=!1}},[me,e,t,J,Ye,_,qe,Ge,s,u,ye,on]),Zt=(0,r.useCallback)((a,v)=>{R?R(a):Qo(a,v)},[R,Qo]),ea=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(typeof window>"u"||ea.current)return;let a=new URLSearchParams(window.location.search),v=a.get("payment_intent"),V=a.get("payment_intent_client_secret"),ie=a.get("redirect_status");if(!v||!V)return;let U=Et=>{let Ne=localStorage.getItem(Et);if(!Ne)return null;try{return JSON.parse(Ne)}catch{return localStorage.removeItem(Et),null}},re=U(wn)??U(Ta),Ze;if(re?.clientSecret){if(re.clientSecret!==V)return;Ze={...re.accountPatch?{accountPatch:re.accountPatch}:{},...re.sessionId?{sessionId:re.sessionId}:{},...re.nonce?{nonce:re.nonce}:{}}}else if(re?.sessionId&&re.sessionId!==e)return;ea.current=!0,localStorage.removeItem(wn),localStorage.removeItem(Ta);let vt=new URL(window.location.href);vt.searchParams.delete("payment_intent"),vt.searchParams.delete("payment_intent_client_secret"),vt.searchParams.delete("redirect_status"),window.history.replaceState({},"",vt.toString());let It=re?.paymentMethodType??re?.tokenType??"card",ot="card";(async()=>{let Et=qe?.getRawProvider();if(!Et){let _t="Payment is not available \u2014 please refresh and try again.";ye(_t),on(ot,_t);return}if(ie==="failed"){let _t="Payment was declined. Please try again.";ye(_t),on(ot,_t);return}let{paymentIntent:Ne,error:Qt}=await Et.retrievePaymentIntent(V);if(Qt){let _t=Qt.message??"Failed to retrieve payment status.";ye(_t),on(ot,_t,{code:Qt.code});return}let en=Ne?.status,Hn=Hr(en);if(!Ne||!Hn){let _t=en==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ye(_t),on(ot,_t,{code:en??"missing_payment_intent"});return}let Kn=typeof Ne.payment_method=="string"?Ne.payment_method:Ne.payment_method?.id;Zt({id:Kn??re?.paymentMethodId??re?.tokenId??Ne.id,type:"card",threeDSecureActionResultTokenId:Ne.id,gateway:re?.gateway??"stripe",paymentMethodType:It},Ze)})()},[e,Zt,qe,ye,on]);let yo=(0,r.useCallback)(a=>{a.preventDefault()},[]);if(!(qe!==null))return(0,i.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let gr=ne==="buttons",jt=Bt?.variables,yi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),fo=jt?.colorBackground,fi=fo&&!yi.has(fo)?fo:void 0,hr=O.cardInputBorder??(gr?"#e5e7eb":"#A4A4FF"),go=jt?.colorDanger??"#dc2626",qn=a=>Gt&&a?go:hr,Dr=(Rt.malformed||Rt.empty)&&(En||Gt),gi=Dr?go:qn(At.zip),ho=O.cardFormContainer?.backgroundColor??fi??(gr?"white":"#EDEDFF"),Pr=O.cardInputBackground??jt?.colorBackground??"white",Po=Qn(W),ta=Qn(se),Zn=O.nameInput,na=O.cardInputFontSize??Xi(Zn?.fontSize)??jt?.fontSizeBase??"16px",ra=typeof Zn?.fontFamily=="string"?Zn.fontFamily:jt?.fontFamily??"Poppins, sans-serif",oa=Aa(Zn?.fontWeight)??400,hi=O.cardInputColor??(typeof Zn?.color=="string"?Zn.color:void 0)??jt?.colorText??"#262833",Pi=O.cardInputPlaceholderColor??"#9ca3af",yt=jt?.borderRadius??"8px",jn=jt?.borderRadius??O.cardButton?.borderRadius??yt,Vn=jt?.colorPrimary??"#4A49FF",bi=jt?.colorPrimaryHover??Jr(Vn,.12),bo=jt?.colorText??"#262833",aa={fontSize:na,fontFamily:ra,fontWeight:oa,color:hi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},vi={"--flopay-input-placeholder-color":Pi,"--flopay-input-font-size":na,"--flopay-input-font-family":ra,"--flopay-input-font-weight":String(oa)},br=O.cardFormContainer??{},vo=br.padding??(gr?"0":"1rem"),Co=br.borderRadius??yt,Ci=rt&&Ft?(0,i.jsx)($r,{capture:rt,html:Ft.html,messageToken:Ft.messageToken,expectedOrigin:Ft.expectedOrigin,theme:z,onReady:()=>{if(!G||typeof document>"u")return;let a=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};a();let v=0,V=window.setInterval(()=>{v+=1;let ie=document.activeElement;!!ie&&ie.tagName==="IFRAME"&&ie.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(V)):v>=50&&window.clearInterval(V)},100)},onError:a=>ye(a),onValidation:a=>{ye(a),a&&b(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"}),ia=(0,i.jsxs)("div",{style:{backgroundColor:ho,borderRadius:Co,...br,padding:vo,...vi,display:"flex",flexDirection:"column"},children:[(0,i.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 @@ ${Qe.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),ur&&Wt&&(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:f?-2:0},children:[(0,i.jsxs)("button",{type:"button",onClick:hn,style:{display:"inline-flex",alignItems:"center",gap:po?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.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",...p.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)(Jn,{content:G})]}),Go?(0,i.jsx)("div",{style:{flex:1}}):(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...p.title},children:(0,i.jsx)(gr,{content:ce})})]}),!ur&&!Go&&(0,i.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:mo,order:f?-3:0,...p.title},children:(0,i.jsx)(gr,{content:ce})}),X&&(0,i.jsx)("div",{style:{order:f?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=Ve,C=(j=!1)=>({backgroundColor:mr,border:`1px solid ${zn(j)}`,borderRadius:mt,marginTop:"0.5rem",padding:"10px"}),H=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Qo}),se=(0,k.getStateOptions)(a);return(0,i.jsxs)(i.Fragment,{children:[(0,k.isAVSFieldVisible)(X.address_line_1,a)&&(0,i.jsx)("div",{style:C(Te.line1),children:(0,i.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:Ge,onChange:j=>{Bt.current=j.target.value,Ce(j.target.value)},disabled:Z,required:!0,"data-testid":"flopay-address-line1",style:H()})}),(0,k.isAVSFieldVisible)(X.address_line_2,a)&&(0,i.jsx)("div",{style:C(),children:(0,i.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:bt,onChange:j=>{Kt.current=j.target.value,He(j.target.value)},disabled:Z,"data-testid":"flopay-address-line2",style:H()})}),((0,k.isAVSFieldVisible)(X.city,a)||(0,k.isAVSFieldVisible)(X.state,a))&&(0,i.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,k.isAVSFieldVisible)(X.city,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:mr,borderTop:`1px solid ${zn(Te.city)}`,borderRight:`1px solid ${zn(Te.city)}`,borderBottom:`1px solid ${zn(Te.city)}`,borderLeft:`1px solid ${zn(Te.city)}`,padding:"10px",borderTopLeftRadius:mt,borderBottomLeftRadius:mt,...(0,k.isAVSFieldVisible)(X.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:mt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Ft,onChange:j=>{Qt.current=j.target.value,Rt(j.target.value)},disabled:Z,required:!0,"data-testid":"flopay-city",style:H()})}),(0,k.isAVSFieldVisible)(X.state,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:mr,border:`1px solid ${zn(Te.state)}`,padding:"10px",borderTopRightRadius:mt,borderBottomRightRadius:mt,...(0,k.isAVSFieldVisible)(X.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:mt}},children:se?(0,i.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:pn,onChange:j=>{mn.current=j.target.value,wn(j.target.value)},disabled:Z,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...H(),cursor:"pointer"},children:[(0,i.jsx)("option",{value:"",children:(0,k.getStateLabel)(a)}),se.map(j=>(0,i.jsx)("option",{value:j.code,children:j.name},j.code))]}):(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,k.getStateLabel)(a),autoComplete:"billing address-level1",value:pn,onChange:j=>{mn.current=j.target.value,wn(j.target.value)},disabled:Z,required:!0,"data-testid":"flopay-state",style:H()})})]}),((0,k.isAVSFieldVisible)(X.country,a)||(0,k.isAVSFieldVisible)(X.postal_code,a))&&(0,i.jsxs)("div",{style:{display:"flex",flexDirection:de==="column"?"column":"row",gap:de==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,k.isAVSFieldVisible)(X.country,a)&&(0,i.jsx)("div",{style:{flex:de==="row"?1:void 0,backgroundColor:mr,borderTop:`1px solid ${pr}`,borderRight:`1px solid ${pr}`,borderBottom:`1px solid ${pr}`,borderLeft:`1px solid ${pr}`,padding:"10px",...de==="row"&&(0,k.isAVSFieldVisible)(X.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:mt,borderBottomLeftRadius:mt,borderRight:"none"}:{borderRadius:mt}},children:(0,i.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Ve,onChange:j=>{Dt.current=j.target.value,lt(j.target.value),ze?.(j.target.value),mn.current="",wn("")},disabled:Z,autoComplete:"billing country","data-testid":"flopay-country",style:{...H(),cursor:"pointer"},children:k.COUNTRY_OPTIONS.map(j=>(0,i.jsxs)("option",{value:j.code,children:[j.flag," ",j.name]},j.code))})}),(0,k.isAVSFieldVisible)(X.postal_code,a)&&(0,i.jsx)("div",{style:{flex:de==="row"?1:void 0,backgroundColor:mr,border:`1px solid ${ci}`,padding:"10px",...de==="row"&&(0,k.isAVSFieldVisible)(X.country,a)?{borderRadius:"0",borderTopRightRadius:mt,borderBottomRightRadius:mt}:{borderRadius:mt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,k.getPostalCodeLabel)(Ve),autoComplete:"billing postal-code",value:ot,onChange:j=>{gt.current=j.target.value,et(j.target.value),Oe?.(j.target.value)},onBlur:()=>gn(!0),disabled:Z,required:ct.required,"aria-invalid":Tr||void 0,"aria-describedby":Tr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:H()})})]}),Tr&&(0,i.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:co,...Qo,fontSize:"0.75rem"},children:ct.empty?`${(0,k.getPostalCodeLabel)(a)} is required`:qi(a)})]})})()}),f&&ve&&(0,i.jsx)("div",{style:{order:-2,width:"100%"},children:ve}),f&&yi,q&&(0,i.jsx)(Xn,{margin:"0.75rem 0",styleOverride:p.errorBanner,children:q})]}),Br={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"},ta=a=>qe?!I||!tt?(0,i.jsx)("pre",{"data-testid":a,style:Br,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:Br,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${I}`,` directPaypalConfigured=${tt}`,` inAppBrowserDetected=${String(_r)}`,` shouldRenderDirectPayPal=${sr}`,` shouldRenderStripePayPal=${lr}`,` hasPaypalStripeInstance=${!!O}`].join(`
39
- `)}):null,na=a=>qe?!F||!st?(0,i.jsx)("pre",{"data-testid":a,style:Br,children:"FloPay/Stripe-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:Br,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${F}`,` currency=${Ee}`,` amountInCents=${b}`,` enabledPaymentMethods: ${JSON.stringify(P??[])}`,` enabledPaymentMethodsProvided=${ar}`,` hasEnabledMethods=${kr}`,` expressMethods: ${JSON.stringify(Rr)}`,` walletExpressMethods: ${JSON.stringify(Ir)}`,` paymentElementMethods: ${JSON.stringify(ir)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Er)}`,` hasStripeInstance=${!!st}`,` shouldRenderWallets=${cr}`,` shouldRenderPaymentElement=${dr}`].join(`
40
- `)}):null,ra=ke==="apm-expanding"||ke==="apm-form"||ke==="apm-collapsing",Mr=ke==="apm-expanding"?`flopay-card-enter ${ht}ms cubic-bezier(0, 0, 0.2, 1) both`:ke==="apm-collapsing"?`flopay-card-exit ${ht}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Ar=it?{...oo,paymentMethodTypes:[it]}:null;if(le==="buttons"){let a=ke==="buttons"||ke==="expanding"||ke==="apm-expanding",C=ke==="expanding"||ke==="card"||ke==="collapsing",H=V===void 0?{boxSizing:"border-box",height:Kr,padding:"0 1rem"}:{padding:"0.9rem 1rem"},se=ke==="expanding"||ke==="apm-expanding"?`flopay-buttons-exit ${ht}ms cubic-bezier(0.4, 0, 0.2, 1) both`:ke==="collapsing"||ke==="apm-collapsing"?`flopay-buttons-enter ${ht}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,j=ke==="expanding"?`flopay-card-enter ${ht}ms cubic-bezier(0, 0, 0.2, 1) both`:ke==="collapsing"?`flopay-card-exit ${ht}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,i.jsxs)("form",{onSubmit:so,className:w,style:{position:"relative"},children:[(0,i.jsx)(Co,{}),jt&&(0,i.jsx)(vn,{status:jt,errorMessage:q}),(0,i.jsxs)("div",{style:{display:"grid"},children:[(0,i.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!se?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!se?zi:{},...se?{animation:se,pointerEvents:"none"}:{}},children:[ta("flopay-direct-paypal-gate-debug"),na("flopay-stripe-gate-debug"),sr&&Qe&&(0,i.jsxs)(i.Fragment,{children:[Ot&&(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)(br,{sessionId:e,nonce:t,billingApiUrl:$,email:te.email,clientId:Qe.clientId,environment:Qe.environment,currency:Ee.toUpperCase(),isSubscription:Ze,onTokenizedBody:Jt,onComplete:s,onErrorChange:x,onDecline:c,onTechnicalFailure:oe,onButtonClick:be,runBeforeButtonClick:rn,isProcessing:Z,onLoadStateChange:ao,onInitializationStateChange:io,session:y??null,existingOrderId:Ot?.orderId,debug:qe},Ot?.orderId??"fresh")]}),lr&&(0,i.jsx)(ut.Elements,{stripe:O,options:nn,children:(0,i.jsx)(xa,{sessionId:e,nonce:t,email:te.email,billingApiUrl:$,onTokenizedBody:Jt,onErrorChange:x,isProcessing:Z,onButtonClick:be,onDecline:c,onTechnicalFailure:oe,runBeforeButtonClick:rn,onLoadStateChange:Fo,placeholderBorderRadius:Un})}),cr?(0,i.jsx)(ut.Elements,{stripe:st,options:$e,children:(0,i.jsx)(Ta,{sessionId:e,nonce:t,email:te.email,billingApiUrl:$,intentKind:pe>0?"payment":"setup",expressMethods:Ir,onTokenizedBody:Jt,onErrorChange:x,onButtonClick:be,onDecline:c,onTechnicalFailure:oe,runBeforeButtonClick:rn,onLoadStateChange:Lo,placeholderBorderRadius:Un})}):$o?(0,i.jsx)("div",{style:{height:Kr,borderRadius:Un,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,dr&&(0,i.jsx)(Ba,{sessionId:e,nonce:t,email:te.email,billingName:[te.firstName,te.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:$,paymentElementMethods:Er,stripeInstance:st,paymentElementBaseOptions:oo,onTokenizedBody:Jt,onErrorChange:x,onButtonClick:be,onDecline:c,runBeforeButtonClick:rn,onLoadStateChange:Oo,isProcessing:Z,submitButtonColor:$n,submitButtonBorderRadius:mt,submitButtonStyle:p.submitButton,onExpandApm:In,expandedApmMethod:it,themeId:U,buttonAppearance:{backgroundColor:p.cardButton?.backgroundColor,borderColor:p.cardInputBorder,textColor:p.cardButton?.color,borderRadius:Un}}),f&&(0,i.jsx)("button",{type:"button",onClick:async()=>{Z||!(await rn("card")).proceed||(be?.("card"),tn())},disabled:Z,style:{width:"100%",...H,...p.cardButton,...ko({themeBundle:D,resolvedPrimaryColor:$n,resolvedBorderRadius:mt,submitButtonStyle:p.submitButton,explicitPrimaryColor:$t?.colorPrimary}),fontSize:p.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Z?"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:Z?.6:1},onMouseEnter:ae=>{!Z&&(D||$t?.colorPrimary)&&(ae.currentTarget.style.backgroundColor=pi)},onMouseLeave:ae=>{(D||$t?.colorPrimary)&&(ae.currentTarget.style.backgroundColor=$n)},onMouseDown:ae=>{ae.currentTarget.style.transform="scale(0.985)"},onMouseUp:ae=>{ae.currentTarget.style.transform="scale(1)"},children:(0,i.jsx)(Gn,{content:V})}),q&&ke==="buttons"&&(0,i.jsx)(Xn,{margin:"0.25rem 0",styleOverride:p.errorBanner,children:q})]}),f&&C&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...j?{animation:j}:{},...ke==="collapsing"?{pointerEvents:"none"}:{}},children:ea}),F&&ra&&it&&Ar&&st&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...Mr?{animation:Mr}:{},...ke==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:uo,borderRadius:fo,...yr,padding:yo},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:Pn,style:{display:"inline-flex",alignItems:"center",gap:po?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.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",...p.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)(Jn,{content:G})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:mo,paddingRight:80,...p.title},children:`Pay with ${(0,k.getStripeMethodDisplayName)(it)}`})]}),(0,i.jsx)(ut.Elements,{stripe:st,options:Ar,children:(0,i.jsx)(So,{method:it,sessionId:e,nonce:t,email:te.email,billingName:[te.firstName,te.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:$,onTokenizedBody:Jt,onErrorChange:x,onDecline:c,onCancel:Pn,runBeforeButtonClick:rn,onButtonClick:be,isProcessing:Z,submitButtonColor:$n,submitButtonBorderRadius:mt,submitButtonStyle:p.submitButton,errorText:q})},it)]})})]})]})}return ra&&it&&Ar&&st&&F?(0,i.jsxs)("form",{onSubmit:so,className:w,style:{position:"relative"},children:[(0,i.jsx)(Co,{}),jt&&(0,i.jsx)(vn,{status:jt,errorMessage:q}),(0,i.jsx)("div",{style:{...Mr?{animation:Mr}:{},...ke==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:uo,borderRadius:fo,...yr,padding:yo},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:Pn,style:{display:"inline-flex",alignItems:"center",gap:po?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.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",...p.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)(Jn,{content:G})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:mo,paddingRight:80,...p.title},children:`Pay with ${(0,k.getStripeMethodDisplayName)(it)}`})]}),(0,i.jsx)(ut.Elements,{stripe:st,options:Ar,children:(0,i.jsx)(So,{method:it,sessionId:e,nonce:t,email:te.email,billingName:[te.firstName,te.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:$,onTokenizedBody:Jt,onErrorChange:x,onDecline:c,onCancel:Pn,runBeforeButtonClick:rn,onButtonClick:be,isProcessing:Z,submitButtonColor:$n,submitButtonBorderRadius:mt,submitButtonStyle:p.submitButton,errorText:q})},it)]})})]}):(0,i.jsxs)("form",{onSubmit:so,className:w,style:{position:"relative"},children:[(0,i.jsx)(Co,{}),jt&&(0,i.jsx)(vn,{status:jt,errorMessage:q}),(0,i.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ta("flopay-direct-paypal-gate-debug-default"),na("flopay-stripe-gate-debug-default"),sr&&Qe&&(0,i.jsxs)(i.Fragment,{children:[Ot&&(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)(br,{sessionId:e,nonce:t,billingApiUrl:$,email:te.email,clientId:Qe.clientId,environment:Qe.environment,currency:Ee.toUpperCase(),isSubscription:Ze,onTokenizedBody:Jt,onComplete:s,onErrorChange:x,onDecline:c,onTechnicalFailure:oe,onButtonClick:be,runBeforeButtonClick:rn,isProcessing:Z,onLoadStateChange:ao,onInitializationStateChange:io,session:y??null,existingOrderId:Ot?.orderId,debug:qe},Ot?.orderId??"fresh")]}),lr&&(0,i.jsx)(ut.Elements,{stripe:O,options:nn,children:(0,i.jsx)(xa,{sessionId:e,nonce:t,email:te.email,billingApiUrl:$,onTokenizedBody:Jt,onErrorChange:x,isProcessing:Z,onButtonClick:be,onDecline:c,onTechnicalFailure:oe,runBeforeButtonClick:rn,onLoadStateChange:Fo,placeholderBorderRadius:Un})}),cr&&(0,i.jsx)(ut.Elements,{stripe:st,options:$e,children:(0,i.jsx)(Ta,{sessionId:e,nonce:t,email:te.email,billingApiUrl:$,intentKind:pe>0?"payment":"setup",expressMethods:Ir,onTokenizedBody:Jt,onErrorChange:x,onButtonClick:be,onDecline:c,onTechnicalFailure:oe,runBeforeButtonClick:rn,onLoadStateChange:Lo,placeholderBorderRadius:Un})}),dr&&(0,i.jsx)(Ba,{sessionId:e,nonce:t,email:te.email,billingName:[te.firstName,te.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:$,paymentElementMethods:Er,stripeInstance:st,paymentElementBaseOptions:oo,onTokenizedBody:Jt,onErrorChange:x,onButtonClick:be,onDecline:c,runBeforeButtonClick:rn,onLoadStateChange:Oo,isProcessing:Z,submitButtonColor:$n,submitButtonBorderRadius:mt,submitButtonStyle:p.submitButton,themeId:U,onExpandApm:In,expandedApmMethod:it,buttonAppearance:{backgroundColor:p.cardButton?.backgroundColor,borderColor:p.cardInputBorder,textColor:p.cardButton?.color,borderRadius:Un}})]}),f&&(ai||oi||ii)&&(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"}})]}),f&&ea]})}var tr=require("@flopay/js"),Xe=require("@flopay/shared");var Cr="card";async function Wi(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:u}=await e.retrieveSetupIntent(t);return{error:u,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 Yi(e,t,n,l){if(l){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:u,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:u??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 Sn(e,t){return Object.assign(e,{checkoutMethod:t})}function Na(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 Gi(e){return e.status==="succeeded"||e.status==="declined"}async function Oa(e){if(typeof document>"u"||typeof window>"u")throw new Xe.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Xe.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 m=new AbortController,_=()=>m.abort();e.signal?.aborted?m.abort():e.signal?.addEventListener("abort",_);let w=window.setTimeout(()=>m.abort(),l);try{let B=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:m.signal});if(!B.ok)return{status:"unknown"};let d=await B.json().catch(()=>null);return Ji(d)}catch{return{status:"unknown"}}finally{window.clearTimeout(w),e.signal?.removeEventListener("abort",_)}},u=document.activeElement instanceof HTMLElement?document.activeElement:null,c=document.createElement("div");c.setAttribute("data-flopay-auto-3ds-overlay","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.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 R=document.createElement("iframe");R.setAttribute("title","Card authentication"),R.setAttribute("allow","payment"),R.tabIndex=0,R.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(";"),R.src=e.nextActionRedirectUrl,c.appendChild(R),document.body.appendChild(c),R.focus();let N=null;try{N=new URL(e.billingApiUrl,window.location.href).origin}catch{N=null}try{let m=await new Promise((_,w)=>{let B=!1,d=0,g=0,I=0,F=!1,P=()=>{window.clearTimeout(d),window.clearInterval(g),window.clearTimeout(I),window.removeEventListener("message",le),R.removeEventListener("load",Q),e.signal?.removeEventListener("abort",me)},W=async()=>{if(!(B||F)){F=!0;try{let U=await s();if(B||!Gi(U))return;B=!0,P(),_(U)}finally{F=!1}}},Q=()=>{window.clearTimeout(I),I=window.setTimeout(()=>{W()},250)},me=()=>{B||(B=!0,P(),w(new Xe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},le=U=>{if(U.source!==R.contentWindow||N&&U.origin!==N)return;let ne=U.data;!ne||typeof ne!="object"||ne.source!=="flopay-vault-3ds-return"||B||(B=!0,P(),_(null))};d=window.setTimeout(()=>{B||(B=!0,P(),w(new Xe.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),g=window.setInterval(()=>{W()},n),R.addEventListener("load",Q),window.addEventListener("message",le),e.signal?.addEventListener("abort",me),e.signal?.aborted&&me()});return m||await s()}finally{c.parentNode?.removeChild(c),u?.isConnected&&u.focus()}}function Ji(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 Ln(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=Fn(o)??o;return Sn(new Xe.FloPayError(s,"api_error",{code:e?.gatewayErrorCode}),l)}function Ro(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Gr(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Xi(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 za(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Gr(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 c of s)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||Gr(c)))return c;let u=o.gateways;if(u&&typeof u=="object"){let c=u.stripe;if(c&&typeof c=="object"){let R=c,N=[R.stripeClientSecret,R.clientSecret];for(let m of N)if(typeof m=="string"&&m.length>0&&(!t?.requirePaymentIntentClientSecret||Gr(m)))return m}}}}async function Zi({billingApiUrl:e,sessionId:t,nonce:n,responseJson:l}){let o=za(l,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let c=(await new tr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Gr(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function nr({billingApiUrl:e,sessionId:t,session:n,nonce:l,tokenizedData:o,returnUrl:s,telemetry:u}){let c=e.replace(/\/+$/,""),R=t??n.id,N=l??n.clientSecret,m=n.customer?.id??n.accountData?.userId??"",_=n.customer?.email??n.accountData?.email??"",w=n.customer?.firstName??n.accountData?.firstName??"",B=n.customer?.lastName??n.accountData?.lastName??"",d=n.customer?.country??n.accountData?.country??void 0,g=n.customer?.zip??n.accountData?.zip??void 0,I=new tr.PaymentAPI(c,u===!1?{telemetry:!1}:void 0),F=await Xi(()=>I.processPayment(m,{sessionId:R,nonce:N,tokenizedData:o,accountData:{userId:m,email:_,firstName:w,lastName:B,country:d,zip:g},returnUrl:s??Ro(n)}));if(F.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:$r(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let P=await F.json().catch(()=>null);if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let W=za(P);if(!W)throw new Xe.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:P.type,threeDSecureToken:W,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let W=await Zi({billingApiUrl:c,sessionId:R,nonce:N,responseJson:P});if(W)return W;throw Sn(new Xe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new Xe.FloPayError(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason})}async function Jr(e,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:u,returnUrl:c,telemetry:R}){let N=t?.getRawProvider();if(!N)throw new Xe.FloPayError("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!l||!e.threeDSecureToken)throw Sn(new Xe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let m=(0,Xe.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,w=e.paymentMethodId,B=await Wi(N,e.threeDSecureToken,m);if(B){if(B.error)throw Sn(new Xe.FloPayError(B.error.message??`Failed to retrieve 3DS ${m?"setup":"payment"} status.`,"api_error",{code:B.error.code}),"card");let g=B.intent;!w&&g?.payment_method&&(typeof g.payment_method=="string"?w=g.payment_method:"id"in g.payment_method&&(w=g.payment_method.id??void 0))}let d=w?await Yi(N,e.threeDSecureToken,{payment_method:w,return_url:c??Ro(u)??window.location.href},m):null;if(d){if(d.error)throw Sn(new Xe.FloPayError(d.error.message??"3DS authentication failed.","api_error",{code:d.error.code}),"card");_=d.intent}else{let g=await N.handleNextAction({clientSecret:e.threeDSecureToken});if(g.error)throw Sn(new Xe.FloPayError(g.error.message??"3DS authentication failed.","api_error",{code:g.error.code}),"card");_=(m?g.setupIntent:g.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let g=await nr({billingApiUrl:o,sessionId:s,session:u,telemetry:R,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:c});return g.type==="success"?{...g.result,paymentIntentId:g.result.paymentIntentId??_.id,paymentMethodId:g.result.paymentMethodId??w}:Jr(g,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:u,returnUrl:c,telemetry:R})}throw Sn(new Xe.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let m=(n??t)?.getRawProvider();if(!m)throw Sn(new Xe.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:w}=await m.handleNextAction({clientSecret:e.threeDSecureToken});if(w)throw Sn(new Xe.FloPayError(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await m.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Ro(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(_)throw Sn(new Xe.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Xe.FloPayError("Unsupported payment redirect state.","api_error")}function Hn(e){if(e instanceof Xe.FloPayError){let l=Fn(e.message);return l&&l!==e.message?Object.assign(new Xe.FloPayError(l,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Fn(t)??t;return new Xe.FloPayError(n,"api_error")}function Xr(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Xe.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 Zr({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:l,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let s=!!t&&t!==e,[u,c]=await Promise.all([(0,tr.loadFloPay)(e,{billingApiUrl:n,locale:l,telemetry:o}),s?(0,tr.loadFloPay)(t,{billingApiUrl:n,locale:l,telemetry:o}).catch(R=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",R),null)):Promise.resolve(null)]);return{flopay:u,paypalFlopay:t?s?c:u:null}}var S=require("react/jsx-runtime"),rr=44,Bo="flopay_checkout_saved_payment_resume",Io=new Map;function Sr(e){return new Promise(t=>setTimeout(t,e))}function Qr(e,t,n){let l=Dr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Be.SDK_VERSION,enabled:t!==!1});return l.beginCheckout(n),l}function eo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Eo(e,t,n,l,o){let s=Qr(e,t,n);s.error({errorCode:l,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),eo(s)}function Qi(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 To(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:!!To(e)?.clientId}function or(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function es(){if(!or())return null;try{let e=window.sessionStorage.getItem(Bo);return e?JSON.parse(e):null}catch{return null}}function Ua(e){if(or())try{window.sessionStorage.setItem(Bo,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function xo(){if(or())try{window.sessionStorage.removeItem(Bo)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function ts(e){if(!or())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 ns(e,t,n){if(or())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 $a(e){if(or())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function rs(){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 qa(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 os(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 to({sessionId:e,nonce:t,createSession:n,billingApiUrl:l,telemetry:o,appearance:s,locale:u,loading:c,error:R,onComplete:N,onError:m,onDecline:_,onCountryChange:w,onZipChange:B,showPayPal:d=!0,showStripe:g=!0,showApplePay:I=!0,showGooglePay:F=!0,debug:P=!1,layout:W,theme:Q,buttonsTheme:me,buttonsStyles:le,cardButtonContent:U,cardBackButtonContent:ne,cardTitleContent:Y,showSecurityFooter:ye,onButtonClick:V,onBeforeButtonClick:G,enableAVS:ce,cardFieldOrder:De,cardPreFormSlot:be,avsLayout:Pe,className:re,initialErrorMessage:fe=null,children:ve,checkoutMode:de,confirmLabel:Ne,renderConfirmButton:Ie,onSessionCompleted:Se}){let E=(0,Be.resolveBillingApiUrl)(l),ie=(0,L.useMemo)(()=>(0,Be.resolveTheme)(Q),[Q]),ue=s??ie?.appearance,ze=n?"embedded_checkout":"standard_checkout",Oe=ve?"custom_layout":W==="buttons"?"buttons_layout":"default_layout",[ee,A]=(0,L.useState)(null),[J,pe]=(0,L.useState)(null),Ee=(0,L.useRef)(null),[ft,Qe]=(0,L.useState)(null),Ze=(0,L.useRef)(null),[y,qe]=(0,L.useState)(null),[Ue,Ke]=(0,L.useState)(e??""),je=e??Ue,Ht=n?"":je,[Pt,kt]=(0,L.useState)(!0),[h,we]=(0,L.useState)(null),[Ve,lt]=(0,L.useState)("full"),[ot,et]=(0,L.useState)(!1),[Ge,Ce]=(0,L.useState)(fe),[bt,He]=(0,L.useState)(null),[Ft,Rt]=(0,L.useState)(null),[pn,wn]=(0,L.useState)(void 0),[kn,Nn]=(0,L.useState)(""),[gt,Dt]=(0,L.useState)(!1),[Bt,Kt]=(0,L.useState)("loading"),[Qt,mn]=(0,L.useState)(0),X=(0,L.useRef)(!1),Mn=(0,L.useRef)(!1),yn=(0,L.useRef)(!1),Lt=(0,L.useRef)(null),at=(0,L.useMemo)(()=>({checkoutMode:de??Ve,layout:ve?"unknown":W==="buttons"?"buttons":"embedded"}),[de,ve,Ve,W]),f=(0,L.useRef)(N);f.current=N;let xe=(0,L.useRef)(m);xe.current=m;let ct=(0,L.useRef)(_);ct.current=_,(0,L.useEffect)(()=>{xt(J)?.setCheckoutContext(at),ft&&ft!==J&&xt(ft)?.setCheckoutContext(at)},[J,ft,at]);let Rn=(0,L.useRef)(Se);Rn.current=Se;let Te=(0,L.useCallback)(M=>{Kt(M),!(M!=="exhausted"||yn.current)&&(yn.current=!0,xe.current?.(new Be.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),An=(0,L.useCallback)(()=>{Kt("retrying"),mn(M=>M+1)},[]);(0,L.useEffect)(()=>{Kt("loading"),mn(0),yn.current=!1},[je]),(0,L.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Be.SDK_VERSION,checkout_type:ze,checkout_layout:Oe,billing_api_url:E})},[Oe,ze,E]);let fn=(0,L.useMemo)(()=>n?en(n):"",[n]),On=(0,L.useMemo)(()=>kn===fn?pn:void 0,[pn,kn,fn]),gn=(0,L.useMemo)(()=>n?ho(n,On):void 0,[n,On]),Nt=de??gn?.checkoutMode??"full",Tt=(0,L.useMemo)(()=>gn?{...gn,checkoutMode:Nt}:void 0,[gn,Nt]);(0,L.useEffect)(()=>{wn(void 0),Nn(fn)},[fn]),(0,L.useEffect)(()=>{Ce(fe)},[fe]);let ke=(0,L.useCallback)((M,$,q)=>{dt(()=>{ct.current?.(wt(M,$,q))})},[dt]),pt=(0,L.useCallback)(async(M,$)=>{Ce(null),Rt(null),He("processing");let q=$?.sessionId??M.id,D=Ee.current??Ze.current,p=xt(D),K=D?null:Qr(E,o,at),v={log:z=>{p?p.log(z):K?.log(z)},error:z=>{p?p.error(z):K?.error(z)},terminal:z=>{p?p.terminal(z):K?.terminal(z)},performance:z=>{p?p.performance(z):K?.performance(z)},now:()=>p?.now()??K?.now()??0,elapsed:z=>p?.elapsed(z)??Math.max(0,(K?.now()??z)-z)},Me=v.now(),Z=!!($?.initialAutoProcessingError||$?.initialAutoProcessingPending),Ye=!1,te,Ut=()=>{Ye||(Ye=!0,Z=!0,te=v.now(),v.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),v.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},st=!1,O=()=>{st||(st=!0,v.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),v.performance({stage:"processing",durationMs:v.elapsed(Me),durationMode:"machine",paymentMethodCategory:"saved"}),te!==void 0&&v.performance({stage:"recovery",durationMs:v.elapsed(te),durationMode:"machine",paymentMethodCategory:"saved"}))};v.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),v.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),Z&&Ut();let b;try{let z=Na($?.initialAutoProcessingError),he;if(z)Ut(),z.type==="paypal_redirect_required"&&Lt.current?.publishableKey&&Ua({sessionId:q,publishableKey:Lt.current.publishableKey,paypalPublishableKey:Lt.current.paypalPublishableKey}),he=await Jr(z,{flopay:Ee.current,paypalFlopay:Ze.current,attempt3DS:$?.attempt3DS,billingApiUrl:E,sessionId:q,session:M,telemetry:!1}),z.type==="paypal_redirect_required"&&xo();else if($?.initialAutoProcessingPending){let $e=await new wr.PaymentAPI(E,{telemetry:!1}).waitForCheckoutSessionCompletion($.initialAutoProcessingPending.sessionId,{initialDelayMs:$.initialAutoProcessingPending.retryAfterMs});if($e.data.session?.status!=="complete")throw new Be.FloPayError("Automatic payment failed. Please try again.","api_error",{code:$e.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});he={status:"succeeded"}}else{if($?.initialAutoProcessingError)throw Ln($.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:$.initialAutoProcessingError.checkoutMethod});if($?.fromCreateSession)return $?.fallbackToFull&&(lt("full"),qa("full")),!1;{let Ae=await nr({billingApiUrl:E,sessionId:q,session:M,telemetry:!1});Ae.type==="success"?he=Ae.result:(Ut(),Ae.type==="paypal_redirect_required"&&Lt.current?.publishableKey&&Ua({sessionId:q,publishableKey:Lt.current.publishableKey,paypalPublishableKey:Lt.current.paypalPublishableKey}),he=await Jr(Ae,{flopay:Ee.current,paypalFlopay:Ze.current,attempt3DS:$?.attempt3DS,billingApiUrl:E,sessionId:q,session:M,telemetry:!1}),Ae.type==="paypal_redirect_required"&&xo())}}q&&Qn(q),O(),Z&&(v.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),v.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),v.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),He("success"),await Sr(xn),b=()=>f.current?.(he)}catch(z){let he=Hn(z),Ae=he.checkoutMethod??Cr;return Ce(he.message),Rt(he.message),$?.fallbackToFull&&(v.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),lt("full"),qa("full")),O(),!!(he.declineCode||he.code?.toLowerCase().includes("declin"))?v.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):he.type==="validation_error"?v.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):v.error({errorCode:Z?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:Z?"recovery":"processing",paymentMethodCategory:"saved"}),dt(()=>xe.current?.(he)),ke(Ae,he,{code:he.code,declineCode:he.declineCode}),He("error"),await Promise.allSettled([Sr(bn),$?.ensureProvidersReady?$.ensureProvidersReady():Promise.resolve()]),Z&&(v.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),v.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{O(),K&&eo(K),He(null),Rt(null)}return dt(b),!0},[ke,dt,Hn,E,o,at]);(0,L.useEffect)(()=>{if(typeof window>"u"||Mn.current)return;let M=new URLSearchParams(window.location.search),$=M.get("payment_intent_client_secret");if(!$)return;let q=es();q&&(Mn.current=!0,(async()=>{let D,p=0;Ce(null),Rt(null),He("processing"),et(!0);try{if(M.get("redirect_status")==="failed")throw Object.assign(new Be.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:K,paypalFlopay:v}=await Zr({publishableKey:q.publishableKey,paypalPublishableKey:q.paypalPublishableKey,billingApiUrl:E,locale:u,telemetry:o});D=xt(v??K),p=D?.now()??0,D?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),D?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Me=(v??K)?.getRawProvider();if(!Me)throw Object.assign(new Be.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:Z,error:Ye}=await Me.retrievePaymentIntent($);if(Ye)throw Object.assign(new Be.FloPayError(Ye.message??"Failed to retrieve PayPal payment status.","api_error",{code:Ye.code}),{checkoutMethod:"paypal"});let te=fa(Z?.status);if(!Z||te==="failed")throw Object.assign(new Be.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Ut=typeof Z.payment_method=="string"?Z.payment_method:Z.payment_method?.id,st=te;if(q.sessionId){let z=(await new wr.PaymentAPI(E,{telemetry:!1}).getUnifiedCheckoutSession(q.sessionId)).data.session;if(z&&z.status!=="complete"){let he=await nr({billingApiUrl:E,sessionId:q.sessionId,session:z,telemetry:!1,tokenizedData:{id:Ut??Z.id,type:"card",threeDSecureActionResultTokenId:Z.id,isPaypal:!0}});if(he.type!=="success")throw Object.assign(new Be.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});st=he.result.status}}q.sessionId&&Qn(q.sessionId),D?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),D?.performance({stage:"redirect_resume",durationMs:D.elapsed(p),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),D?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),He("success"),await Sr(xn),dt(()=>f.current?.({status:st,paymentIntentId:Z.id,paymentMethodId:Ut,checkoutMethod:"paypal"}))}catch(K){let v=Hn(K),Me=v.checkoutMethod??"paypal",Z=!!(v.declineCode||v.code?.toLowerCase().includes("declin"));if(D)D.performance({stage:"redirect_resume",durationMs:D.elapsed(p),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Z?D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):D.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(Z){let Ye=Qr(E,o,at);Ye.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),eo(Ye)}else Eo(E,o,at,"REDIRECT_RESUME_FAILED","redirect_resume");Ce(v.message),Rt(v.message),dt(()=>xe.current?.(v)),ke(Me,v,{code:v.code,declineCode:v.declineCode}),He("error"),await Sr(bn)}finally{xo(),rs(),He(null),Rt(null),et(!1)}})())},[ke,dt,u,Hn,E,o]);let it=(0,L.useRef)(null);function en(M){let $=JSON.stringify({c:M?.clientId,cur:M?.currency??"",a:{e:M?.account?.email?.trim().toLowerCase()??"",country:M?.account?.country??""},successUrl:M?.successUrl,cancelUrl:M?.cancelUrl,p:M?.products?.map(D=>`${D.type??""}:${D.code??D.providerItemId??D.providerPlanId??""}:${D.totalAmount??""}:${D.overrideAmount??""}:${D.quantity??1}`).sort(),i:M?.items?.map(D=>`${D.code??D.providerItemId??""}:${D.totalAmount??""}:${D.overrideAmount??""}:${D.quantity??1}`).sort(),s:M?.subscriptions?.map(D=>`${D.code??D.providerPlanId??""}:${D.totalAmount??""}:${D.overrideAmount??""}:${D.quantity??1}`).sort(),couponCodes:M?.couponCodes,tagsData:M?.tagsData,utmMetadata:M?.utmMetadata,tokenizedData:M?.tokenizedData,m:M?.checkoutMode??"full"}),q=0;for(let D=0;D<$.length;D++)q=(q<<5)-q+$.charCodeAt(D)|0;return`flopay_session_${Math.abs(q).toString(36)}`}let Wt=(0,L.useMemo)(()=>Tt?en(Tt):"",[Tt]),ht=(0,L.useRef)(Tt);ht.current=Tt,(0,L.useEffect)(()=>{Ke(e??"")},[e]),(0,L.useEffect)(()=>{X.current=!1,Ce(fe),Rt(null),He(null)},[Wt,fe,e]);async function qt(M,$){let q=Qr(E,o,at),D=new wr.PaymentAPI(E,{telemetry:!1});try{let p=ts($);q.log({name:p?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let K=p?.sid??null,v=null;if(K)try{if(v=await D.getUnifiedCheckoutSession(K,p?.nonce),v.data.session?.status==="complete"){if(ha(K))return{sid:K,result:v};$a($),K=null,v=null}}catch{q.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),$a($),K=null}if(!K){let Me=q.now();q.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Z={...M,avsCheck:!!ce,avsConfig:typeof ce=="object"?ce:void 0,checkoutType:"embedded_checkout",checkoutLayout:ve?"custom_layout":W==="buttons"?"buttons_layout":"default_layout"};try{v=await D.createAndFetchSession(Z),q.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),q.performance({stage:"session_create",durationMs:q.now()-Me,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"})}catch(Ye){let te=(0,Be.classifyTelemetryFailure)(Ye,"CHECKOUT_SESSION_CREATE_FAILED","unknown");throw q.performance({stage:"session_create",durationMs:q.now()-Me,durationMode:"machine",requestCategory:"session_create",statusClass:te.statusClass}),Ye instanceof Be.FloPayError&&Ye.type==="validation_error"?q.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):te.statusClass==="4xx"?q.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):q.error({...te,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Ye}K=v.data.session?.id??"",K&&ns($,K,v.data.session?.clientSecret)}return{sid:K??"",result:v}}finally{eo(q)}}let vt=(0,L.useCallback)(async M=>{let $=ht.current;if(!$)throw new Be.FloPayError("createSession is required to bootstrap checkout.","validation_error");let q=ho($,M),D=en(q),p=Io.get(D);p||(p=qt(q,D),Io.set(D,p));let K;try{K=await p}finally{Io.delete(D)}it.current=D;try{M&&(Nn(fn),wn(st=>ma(st,M)));let{sid:v,result:Me}=K;A(Me),Me.data.session&&qe(Me.data.session),v&&Ke(v);let{publishableKey:Z,paypalPublishableKey:Ye}=Xr(Me),{flopay:te,paypalFlopay:Ut}=await Zr({publishableKey:Z,paypalPublishableKey:Ye,billingApiUrl:E,locale:u,telemetry:o});Ee.current=te,pe(te),Ze.current=Ut,Qe(Ut),kt(!1)}catch(v){throw it.current===D&&(it.current=null),v}return K},[u,E,o,at]),tn=(0,L.useCallback)(async M=>{if(!os(M)||gt)return{sessionId:Ue,session:y};Dt(!0);try{let $=await vt(M);return{sessionId:$.sid,session:$.result.data.session??null}}finally{Dt(!1)}},[vt,gt,Ue,y]);(0,L.useEffect)(()=>{let M=!1;if(we(null),Wt){let D=ht.current;return lt(Nt),kt(!1),it.current===Wt?()=>{M=!0}:(qe(ya(D,de)),(async()=>{let p=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),K=Nt==="auto"&&!X.current&&!p;K&&(Ce(null),Rt(null),He("processing"));try{let v=await vt(),Me=v.result.data.session??null;Lt.current=Xr(v.result);let Z=_o(v.result);if(!M&&K&&Me&&!Z){X.current=!0,await pt(Me,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:v.result.autoProcessingError,initialAutoProcessingPending:v.result.autoProcessingPending,autoProcessingAttempted:v.result.autoProcessingAttempted,sessionId:v.sid||Me.id});return}!M&&K&&(Z&&(X.current=!0),He(null),Rt(null))}catch(v){if(M)return;let Me=v instanceof Be.FloPayError||typeof v=="object"&&v!==null&&"code"in v?v.code:void 0;if(K&&Me==="session_auto_completed"){X.current=!0,He("success"),await Sr(xn),M||(dt(()=>{f.current?.({status:"succeeded"})}),He(null),Rt(null));return}K&&(He(null),Rt(null));let Z=v instanceof Be.FloPayError?v:new Be.FloPayError(v instanceof Error?v.message:"Failed to create session","api_error");we(Z)}})(),()=>{M=!0})}kt(!0);async function $(){let D=!1;try{let K=await new wr.PaymentAPI(E,{telemetry:!1}).getUnifiedCheckoutSession(je,t);if(M)return;A(K);let v=K.data.session??null;if(qe(v),!v)throw new Be.FloPayError("No session data returned","api_error");if(v.status==="complete"){kt(!1),dt(()=>{Rn.current?.(v.successUrl??"")});return}if(v.status==="expired")throw new Be.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});D=!0;let Me=de??v.checkoutMode??"full";lt(Me);let Z=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ye=_o(K);if(Me==="auto"&&!X.current&&!Z&&!Ye){X.current=!0;let te=q(K);try{if(await pt(v,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>te,sessionId:je||v.id}),M)return;await te,M||kt(!1);return}catch{if(M)return;await te,M||kt(!1);return}}await q(K),M||kt(!1)}catch(p){if(M)return;p instanceof Be.FloPayError?!D&&!Qi(p)&&Eo(E,o,at,"NETWORK_REQUEST_FAILED","session_read"):Eo(E,o,at,"INTERNAL_SDK_ERROR","checkout_mount");let K=p instanceof Be.FloPayError?p:new Be.FloPayError(p instanceof Error?p.message:"Failed to initialize checkout","api_error");we(K),kt(!1)}}async function q(D){let{publishableKey:p,paypalPublishableKey:K}=Xr(D);Lt.current={publishableKey:p,paypalPublishableKey:K};let{flopay:v,paypalFlopay:Me}=await Zr({publishableKey:p,paypalPublishableKey:K,billingApiUrl:E,locale:u,telemetry:o});Ee.current=v,pe(v),Ze.current=Me,Qe(Me)}return $(),()=>{M=!0}},[vt,de,Wt,Nt,Ht,dt,t,pt]);let hn=(0,L.useCallback)(async()=>{if(!(ot||!y)){et(!0),Ce(null);try{await pt(y,{fallbackToFull:!0,sessionId:je||y.id})}finally{et(!1)}}},[je,ot,pt,y]),In=To(ee),Pn=_o(ee),jt=(0,L.useMemo)(()=>{if(!ee||!y||!ee.data.stripe?.publishableKey)return;let M={appearance:ue,paymentMethodCreation:"manual",billingApiUrl:E};if(ee.data.stripe?.clientSecret)M.clientSecret=ee.data.stripe.clientSecret;else{let $=(0,Be.buildCheckoutDisplayData)(y).total;M.amount=Math.round($*100)||y.amount,M.currency=y.currency?.toLowerCase()}return M},[ee,y,ue,E]),We=!!(n&&!ve&&W==="buttons"&&G&&Nt==="full"),Vt=(0,L.useMemo)(()=>({session:y,loading:Pt,error:h,checkoutMode:Ve,inlineSessionDraft:Tt,applyInlineSessionPatch:We?tn:void 0,inlineSessionPatchProcessing:gt}),[y,Pt,h,Ve,Tt,We,tn,gt]),Ot=!!n&&W==="buttons"&&!Pn&&(!J||!jt),zt=bt?(0,S.jsx)(vn,{status:bt,errorMessage:Ft}):null;if(Pt){if(c)return(0,S.jsxs)(S.Fragment,{children:[c,zt]});if(W==="buttons"){let M=ie?.buttonsLayout?.cardButton?.borderRadius??ie?.appearance.variables?.borderRadius??8,$=q=>(0,S.jsx)("div",{style:{height:q,borderRadius:M,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[d&&$(rr),g&&(I||F)&&$(rr),g&&$(rr),(0,S.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),zt]})}return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,S.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,S.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),zt]})}return h?R?(0,S.jsx)(on.Provider,{value:Vt,children:R(h)}):(0,S.jsx)(on.Provider,{value:Vt,children:(0,S.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:h.message})}):Ot?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(on.Provider,{value:Vt,children:(0,S.jsx)(is,{onButtonClick:V,showPayPal:d,showStripe:g,showApplePay:I,showGooglePay:F,theme:Q,buttonsTheme:me,buttonsStyles:le,cardButtonContent:U,cardBackButtonContent:ne,cardTitleContent:Y})}),zt]}):Pn&&y&&In?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(on.Provider,{value:Vt,children:(0,S.jsxs)("div",{className:re,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ge&&(0,S.jsx)(Xn,{icon:!1,children:Ge}),Bt==="retrying"&&(0,S.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Bt==="exhausted"&&(0,S.jsxs)("div",{role:"alert",children:[(0,S.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,S.jsx)("button",{type:"button",onClick:An,children:"Retry PayPal"})]}),Bt!=="exhausted"&&(0,S.jsx)("div",{"aria-hidden":Bt==="retrying"?!0:void 0,style:Bt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,S.jsx)(wa,{sessionId:je,nonce:y.clientSecret||void 0,billingApiUrl:E,email:y.customer?.email,clientId:In.clientId,environment:In.environment,currency:(y.currency??"usd").toUpperCase(),isSubscription:y.mode==="subscription",onComplete:N,onErrorChange:Ce,onDecline:_,onButtonClick:V,onInitializationStateChange:Te,allowAutomaticRetry:Qt===0,session:y,telemetry:o,telemetryContext:at,debug:P},`paypal-init-${Qt}`)})]})}),zt]}):!J||!jt?(0,S.jsx)(S.Fragment,{children:zt}):Ve==="confirm"?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(on.Provider,{value:Vt,children:(0,S.jsx)(fr,{flopay:J,paypalFlopay:ft,options:jt,children:(0,S.jsxs)("div",{className:re,children:[Ge&&(0,S.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ge}),Ie?Ie({onConfirm:hn,isProcessing:ot}):(0,S.jsx)("button",{type:"button",onClick:hn,disabled:ot,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:ot?"not-allowed":"pointer",opacity:ot?.6:1},children:ot?"Processing...":Ne??"Confirm Purchase"})]})})}),zt]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(on.Provider,{value:Vt,children:(0,S.jsx)(fr,{flopay:J,paypalFlopay:ft,options:jt,children:ve?(0,S.jsxs)(S.Fragment,{children:[Ge&&(0,S.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ge}),(0,S.jsx)(as,{sessionId:je,nonce:y?.clientSecret||void 0,billingApiUrl:E,session:y,children:ve})]}):(0,S.jsx)(Yr,{sessionId:je,nonce:y?.clientSecret||void 0,email:y?.customer?.email,userId:y?.customer?.id,firstName:y?.customer?.firstName,lastName:y?.customer?.lastName,totalAmount:y?Math.round((0,Be.buildCheckoutDisplayData)(y).total*100):0,currency:y?.currency?.toLowerCase()??"usd",onComplete:N,onError:m,onDecline:_,error:Ge,onErrorChange:Ce,showPayPal:d,showStripe:g,enabledPaymentMethods:ee?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ee?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:F,layout:W,theme:Q,buttonsTheme:me,buttonsStyles:le,appearance:ue,cardButtonContent:U,cardBackButtonContent:ne,cardTitleContent:Y,onButtonClick:V,onBeforeButtonClick:G,enableAVS:ce,...De?{cardFieldOrder:De}:{},...be?{cardPreFormSlot:be}:{},avsLayout:Pe,country:y?.customer?.country,city:y?.customer?.city,state:y?.customer?.state,onCountryChange:w,onZipChange:B,avsCheck:!!ce,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ve?"custom_layout":W==="buttons"?"buttons_layout":"default_layout",className:re,directPaypal:To(ee),isSubscription:y?.mode==="subscription",session:y,debug:P})})}),zt]})}function as({sessionId:e,nonce:t,billingApiUrl:n,session:l,children:o}){return(0,S.jsx)(S.Fragment,{children:L.default.Children.map(o,s=>{if(!L.default.isValidElement(s))return s;let u=s.props,c={};return u.sessionId||(c.sessionId=e),!u.nonce&&t&&(c.nonce=t),u.billingApiUrl||(c.billingApiUrl=n),l?.customer&&(u.email||(c.email=l.customer.email),u.userId||(c.userId=l.customer.id),u.firstName||(c.firstName=l.customer.firstName),u.lastName||(c.lastName=l.customer.lastName)),Object.keys(c).length===0?s:L.default.cloneElement(s,c)})})}function is({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:l,showGooglePay:o,theme:s,buttonsTheme:u,buttonsStyles:c,cardButtonContent:R,cardBackButtonContent:N,cardTitleContent:m}){let[_,w]=(0,L.useState)(!1),B=(0,L.useMemo)(()=>(0,Be.resolveTheme)(s),[s]),d=(0,L.useMemo)(()=>{let P=B?.buttonsLayout??(0,Be.resolveButtonsLayoutTheme)(u);return c?{...P,...c,cardButton:{...P.cardButton,...c.cardButton},cardFormContainer:{...P.cardFormContainer,...c.cardFormContainer},backButton:{...P.backButton,...c.backButton},backButtonIcon:{...P.backButtonIcon,...c.backButtonIcon},submitButton:{...P.submitButton,...c.submitButton},title:{...P.title,...c.title}}:P},[B,u,c]),g=B?.buttonsLayout?.cardButton?.borderRadius??B?.appearance.variables?.borderRadius??8,I=P=>(0,S.jsx)("div",{style:{height:P,borderRadius:g,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),F=R===void 0?{boxSizing:"border-box",height:rr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let P=d.cardInputBorder??"#e5e7eb",W=d.cardInputBackground??"white",Q=Yn(N),me=Yn(m);return(0,S.jsxs)("div",{style:{backgroundColor:d.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...d.cardFormContainer},children:[(0,S.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,S.jsxs)("button",{type:"button",onClick:()=>w(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...d.backButton},children:[(0,S.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...d.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)(Jn,{content:N})]}),me?(0,S.jsx)("div",{style:{flex:1}}):(0,S.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...d.title},children:(0,S.jsx)(gr,{content:m})})]}),(0,S.jsx)("div",{style:{backgroundColor:W,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,S.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,S.jsxs)("div",{style:{display:"flex"},children:[(0,S.jsx)("div",{style:{flex:1,backgroundColor:W,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,S.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,S.jsx)("div",{style:{flex:1,backgroundColor:W,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,S.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,S.jsx)("div",{style:{backgroundColor:W,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,S.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,S.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...d.submitButton,opacity:.5}}),(0,S.jsx)("style",{children:`
38
+ `}),gr&&Un&&(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ie?-2:0},children:[(0,i.jsxs)("button",{type:"button",onClick:Ht,style:{display:"inline-flex",alignItems:"center",gap:Po?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:O.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...O.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",...O.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)(tr,{content:W})]}),ta?(0,i.jsx)("div",{style:{flex:1}}):(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:O.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...O.title},children:(0,i.jsx)(Cr,{content:se})})]}),!gr&&!ta&&(0,i.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:bo,order:Ie?-3:0,...O.title},children:(0,i.jsx)(Cr,{content:se})}),G&&(0,i.jsx)("div",{style:{order:Ie?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=He,v=(U=!1)=>({backgroundColor:Pr,border:`1px solid ${qn(U)}`,borderRadius:yt,marginTop:"0.5rem",padding:"10px"}),V=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...aa}),ie=(0,k.getStateOptions)(a);return(0,i.jsxs)(i.Fragment,{children:[(0,k.isAVSFieldVisible)(G.address_line_1,a)&&(0,i.jsx)("div",{style:v(At.line1),children:(0,i.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:Je,onChange:U=>{Mt.current=U.target.value,Se(U.target.value)},disabled:w,required:!0,"data-testid":"flopay-address-line1",style:V()})}),(0,k.isAVSFieldVisible)(G.address_line_2,a)&&(0,i.jsx)("div",{style:v(),children:(0,i.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:Pt,onChange:U=>{Yt.current=U.target.value,Ke(U.target.value)},disabled:w,"data-testid":"flopay-address-line2",style:V()})}),((0,k.isAVSFieldVisible)(G.city,a)||(0,k.isAVSFieldVisible)(G.state,a))&&(0,i.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,k.isAVSFieldVisible)(G.city,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:Pr,borderTop:`1px solid ${qn(At.city)}`,borderRight:`1px solid ${qn(At.city)}`,borderBottom:`1px solid ${qn(At.city)}`,borderLeft:`1px solid ${qn(At.city)}`,padding:"10px",borderTopLeftRadius:yt,borderBottomLeftRadius:yt,...(0,k.isAVSFieldVisible)(G.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:yt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:zt,onChange:U=>{tn.current=U.target.value,kt(U.target.value)},disabled:w,required:!0,"data-testid":"flopay-city",style:V()})}),(0,k.isAVSFieldVisible)(G.state,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:Pr,border:`1px solid ${qn(At.state)}`,padding:"10px",borderTopRightRadius:yt,borderBottomRightRadius:yt,...(0,k.isAVSFieldVisible)(G.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:yt}},children:ie?(0,i.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:yn,onChange:U=>{fn.current=U.target.value,Rn(U.target.value)},disabled:w,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...V(),cursor:"pointer"},children:[(0,i.jsx)("option",{value:"",children:(0,k.getStateLabel)(a)}),ie.map(U=>(0,i.jsx)("option",{value:U.code,children:U.name},U.code))]}):(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,k.getStateLabel)(a),autoComplete:"billing address-level1",value:yn,onChange:U=>{fn.current=U.target.value,Rn(U.target.value)},disabled:w,required:!0,"data-testid":"flopay-state",style:V()})})]}),((0,k.isAVSFieldVisible)(G.country,a)||(0,k.isAVSFieldVisible)(G.postal_code,a))&&(0,i.jsxs)("div",{style:{display:"flex",flexDirection:le==="column"?"column":"row",gap:le==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,k.isAVSFieldVisible)(G.country,a)&&(0,i.jsx)("div",{style:{flex:le==="row"?1:void 0,backgroundColor:Pr,borderTop:`1px solid ${hr}`,borderRight:`1px solid ${hr}`,borderBottom:`1px solid ${hr}`,borderLeft:`1px solid ${hr}`,padding:"10px",...le==="row"&&(0,k.isAVSFieldVisible)(G.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:yt,borderBottomLeftRadius:yt,borderRight:"none"}:{borderRadius:yt}},children:(0,i.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:He,onChange:U=>{Ut.current=U.target.value,lt(U.target.value),$e?.(U.target.value),fn.current="",Rn("")},disabled:w,autoComplete:"billing country","data-testid":"flopay-country",style:{...V(),cursor:"pointer"},children:k.COUNTRY_OPTIONS.map(U=>(0,i.jsxs)("option",{value:U.code,children:[U.flag," ",U.name]},U.code))})}),(0,k.isAVSFieldVisible)(G.postal_code,a)&&(0,i.jsx)("div",{style:{flex:le==="row"?1:void 0,backgroundColor:Pr,border:`1px solid ${gi}`,padding:"10px",...le==="row"&&(0,k.isAVSFieldVisible)(G.country,a)?{borderRadius:"0",borderTopRightRadius:yt,borderBottomRightRadius:yt}:{borderRadius:yt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,k.getPostalCodeLabel)(He),autoComplete:"billing postal-code",value:it,onChange:U=>{gt.current=U.target.value,nt(U.target.value),ze?.(U.target.value)},onBlur:()=>Jt(!0),disabled:w,required:Rt.required,"aria-invalid":Dr||void 0,"aria-describedby":Dr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:V()})})]}),Dr&&(0,i.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:go,...aa,fontSize:"0.75rem"},children:Rt.empty?`${(0,k.getPostalCodeLabel)(a)} is required`:Gi(a)})]})})()}),Ie&&Ce&&(0,i.jsx)("div",{style:{order:-2,width:"100%"},children:Ce}),Ie&&Ci,Ue&&(0,i.jsx)(nr,{margin:"0.75rem 0",styleOverride:O.errorBanner,children:Ue})]}),Lr={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"},sa=a=>je?!I||!vn?(0,i.jsx)("pre",{"data-testid":a,style:Lr,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:Lr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${I}`,` directPaypalConfigured=${vn}`,` inAppBrowserDetected=${String(Ar)}`,` shouldRenderDirectPayPal=${pr}`,` shouldRenderStripePayPal=${mr}`,` hasPaypalStripeInstance=${!!Me}`].join(`
39
+ `)}):null,la=a=>je?!F||!dt?(0,i.jsx)("pre",{"data-testid":a,style:Lr,children:"FloPay/Stripe-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:Lr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${F}`,` currency=${_e}`,` amountInCents=${we}`,` enabledPaymentMethods: ${JSON.stringify(f??[])}`,` enabledPaymentMethodsProvided=${dr}`,` hasEnabledMethods=${xr}`,` expressMethods: ${JSON.stringify(Tr)}`,` walletExpressMethods: ${JSON.stringify(Br)}`,` paymentElementMethods: ${JSON.stringify(ur)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Mr)}`,` hasStripeInstance=${!!dt}`,` shouldRenderWallets=${yr}`,` shouldRenderPaymentElement=${fr}`].join(`
40
+ `)}):null,ca=ve==="apm-expanding"||ve==="apm-form"||ve==="apm-collapsing",Nr=ve==="apm-expanding"?`flopay-card-enter ${Dt}ms cubic-bezier(0, 0, 0.2, 1) both`:ve==="apm-collapsing"?`flopay-card-exit ${Dt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Or=ct?{...uo,paymentMethodTypes:[ct]}:null;if(ne==="buttons"){let a=ve==="buttons"||ve==="expanding"||ve==="apm-expanding",v=ve==="expanding"||ve==="card"||ve==="collapsing",V=q===void 0?{boxSizing:"border-box",height:Xr,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ie=ve==="expanding"||ve==="apm-expanding"?`flopay-buttons-exit ${Dt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:ve==="collapsing"||ve==="apm-collapsing"?`flopay-buttons-enter ${Dt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,U=ve==="expanding"?`flopay-card-enter ${Dt}ms cubic-bezier(0, 0, 0.2, 1) both`:ve==="collapsing"?`flopay-card-exit ${Dt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,i.jsxs)("form",{onSubmit:yo,className:S,style:{position:"relative"},children:[(0,i.jsx)(Eo,{}),j&&(0,i.jsx)(Sn,{status:j,errorMessage:Ue}),(0,i.jsxs)("div",{style:{display:"grid"},children:[(0,i.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!ie?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!ie?Ki:{},...ie?{animation:ie,pointerEvents:"none"}:{}},children:[sa("flopay-direct-paypal-gate-debug"),la("flopay-stripe-gate-debug"),pr&&tt&&(0,i.jsxs)(i.Fragment,{children:[$&&(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)(kr,{sessionId:e,nonce:t,billingApiUrl:pe,email:J.email,clientId:tt.clientId,environment:tt.environment,currency:_e.toUpperCase(),isSubscription:et,onTokenizedBody:Zt,onComplete:s,onErrorChange:ye,onDecline:c,onTechnicalFailure:Xn,onButtonClick:be,runBeforeButtonClick:an,isProcessing:w,onLoadStateChange:po,onInitializationStateChange:mo,session:p??null,existingOrderId:$?.orderId,debug:je},$?.orderId??"fresh")]}),mr&&(0,i.jsx)(pt.Elements,{stripe:Me,options:Lt,children:(0,i.jsx)(Da,{sessionId:e,nonce:t,email:J.email,billingApiUrl:pe,onTokenizedBody:Zt,onErrorChange:ye,isProcessing:w,onButtonClick:be,onDecline:c,onTechnicalFailure:Xn,runBeforeButtonClick:an,onLoadStateChange:Uo,placeholderBorderRadius:jn})}),yr?(0,i.jsx)(pt.Elements,{stripe:dt,options:Kt,children:(0,i.jsx)(La,{sessionId:e,nonce:t,email:J.email,billingApiUrl:pe,intentKind:ue>0?"payment":"setup",expressMethods:Br,onTokenizedBody:Zt,onErrorChange:ye,onButtonClick:be,onDecline:c,onTechnicalFailure:Xn,runBeforeButtonClick:an,onLoadStateChange:qo,placeholderBorderRadius:jn})}):Wo?(0,i.jsx)("div",{style:{height:Xr,borderRadius:jn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,fr&&(0,i.jsx)(Na,{sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pe,paymentElementMethods:Mr,stripeInstance:dt,paymentElementBaseOptions:uo,onTokenizedBody:Zt,onErrorChange:ye,onButtonClick:be,onDecline:c,runBeforeButtonClick:an,onLoadStateChange:Vo,isProcessing:w,submitButtonColor:Vn,submitButtonBorderRadius:yt,submitButtonStyle:O.submitButton,onExpandApm:M,expandedApmMethod:ct,themeId:N,buttonAppearance:{backgroundColor:O.cardButton?.backgroundColor,borderColor:O.cardInputBorder,textColor:O.cardButton?.color,borderRadius:jn}}),Ie&&(0,i.jsx)("button",{type:"button",onClick:async()=>{w||!(await an("card")).proceed||(be?.("card"),Jn())},disabled:w,style:{width:"100%",...V,...O.cardButton,...To({themeBundle:xe,resolvedPrimaryColor:Vn,resolvedBorderRadius:yt,submitButtonStyle:O.submitButton,explicitPrimaryColor:jt?.colorPrimary}),fontSize:O.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:w?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:w?.6:1},onMouseEnter:re=>{!w&&(xe||jt?.colorPrimary)&&(re.currentTarget.style.backgroundColor=bi)},onMouseLeave:re=>{(xe||jt?.colorPrimary)&&(re.currentTarget.style.backgroundColor=Vn)},onMouseDown:re=>{re.currentTarget.style.transform="scale(0.985)"},onMouseUp:re=>{re.currentTarget.style.transform="scale(1)"},children:(0,i.jsx)(er,{content:q})}),Ue&&ve==="buttons"&&(0,i.jsx)(nr,{margin:"0.25rem 0",styleOverride:O.errorBanner,children:Ue})]}),Ie&&v&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...U?{animation:U}:{},...ve==="collapsing"?{pointerEvents:"none"}:{}},children:ia}),F&&ca&&ct&&Or&&dt&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...Nr?{animation:Nr}:{},...ve==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:ho,borderRadius:Co,...br,padding:vo},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:Q,style:{display:"inline-flex",alignItems:"center",gap:Po?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:O.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...O.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",...O.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)(tr,{content:W})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:O.titleFontSize??"1.05rem",color:bo,paddingRight:80,...O.title},children:`Pay with ${(0,k.getStripeMethodDisplayName)(ct)}`})]}),(0,i.jsx)(pt.Elements,{stripe:dt,options:Or,children:(0,i.jsx)(_o,{method:ct,sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pe,onTokenizedBody:Zt,onErrorChange:ye,onDecline:c,onCancel:Q,runBeforeButtonClick:an,onButtonClick:be,isProcessing:w,submitButtonColor:Vn,submitButtonBorderRadius:yt,submitButtonStyle:O.submitButton,errorText:Ue})},ct)]})})]})]})}return ca&&ct&&Or&&dt&&F?(0,i.jsxs)("form",{onSubmit:yo,className:S,style:{position:"relative"},children:[(0,i.jsx)(Eo,{}),j&&(0,i.jsx)(Sn,{status:j,errorMessage:Ue}),(0,i.jsx)("div",{style:{...Nr?{animation:Nr}:{},...ve==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:ho,borderRadius:Co,...br,padding:vo},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:Q,style:{display:"inline-flex",alignItems:"center",gap:Po?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:O.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...O.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",...O.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)(tr,{content:W})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:O.titleFontSize??"1.05rem",color:bo,paddingRight:80,...O.title},children:`Pay with ${(0,k.getStripeMethodDisplayName)(ct)}`})]}),(0,i.jsx)(pt.Elements,{stripe:dt,options:Or,children:(0,i.jsx)(_o,{method:ct,sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pe,onTokenizedBody:Zt,onErrorChange:ye,onDecline:c,onCancel:Q,runBeforeButtonClick:an,onButtonClick:be,isProcessing:w,submitButtonColor:Vn,submitButtonBorderRadius:yt,submitButtonStyle:O.submitButton,errorText:Ue})},ct)]})})]}):(0,i.jsxs)("form",{onSubmit:yo,className:S,style:{position:"relative"},children:[(0,i.jsx)(Eo,{}),j&&(0,i.jsx)(Sn,{status:j,errorMessage:Ue}),(0,i.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[sa("flopay-direct-paypal-gate-debug-default"),la("flopay-stripe-gate-debug-default"),pr&&tt&&(0,i.jsxs)(i.Fragment,{children:[$&&(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)(kr,{sessionId:e,nonce:t,billingApiUrl:pe,email:J.email,clientId:tt.clientId,environment:tt.environment,currency:_e.toUpperCase(),isSubscription:et,onTokenizedBody:Zt,onComplete:s,onErrorChange:ye,onDecline:c,onTechnicalFailure:Xn,onButtonClick:be,runBeforeButtonClick:an,isProcessing:w,onLoadStateChange:po,onInitializationStateChange:mo,session:p??null,existingOrderId:$?.orderId,debug:je},$?.orderId??"fresh")]}),mr&&(0,i.jsx)(pt.Elements,{stripe:Me,options:Lt,children:(0,i.jsx)(Da,{sessionId:e,nonce:t,email:J.email,billingApiUrl:pe,onTokenizedBody:Zt,onErrorChange:ye,isProcessing:w,onButtonClick:be,onDecline:c,onTechnicalFailure:Xn,runBeforeButtonClick:an,onLoadStateChange:Uo,placeholderBorderRadius:jn})}),yr&&(0,i.jsx)(pt.Elements,{stripe:dt,options:Kt,children:(0,i.jsx)(La,{sessionId:e,nonce:t,email:J.email,billingApiUrl:pe,intentKind:ue>0?"payment":"setup",expressMethods:Br,onTokenizedBody:Zt,onErrorChange:ye,onButtonClick:be,onDecline:c,onTechnicalFailure:Xn,runBeforeButtonClick:an,onLoadStateChange:qo,placeholderBorderRadius:jn})}),fr&&(0,i.jsx)(Na,{sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pe,paymentElementMethods:Mr,stripeInstance:dt,paymentElementBaseOptions:uo,onTokenizedBody:Zt,onErrorChange:ye,onButtonClick:be,onDecline:c,runBeforeButtonClick:an,onLoadStateChange:Vo,isProcessing:w,submitButtonColor:Vn,submitButtonBorderRadius:yt,submitButtonStyle:O.submitButton,themeId:N,onExpandApm:M,expandedApmMethod:ct,buttonAppearance:{backgroundColor:O.cardButton?.backgroundColor,borderColor:O.cardInputBorder,textColor:O.cardButton?.color,borderRadius:jn}})]}),Ie&&(pi||ui||mi)&&(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"}})]}),Ie&&ia]})}var ir=require("@flopay/js"),Qe=require("@flopay/shared");var Ir="card";async function es(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:u}=await e.retrieveSetupIntent(t);return{error:u,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 ts(e,t,n,l){if(l){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:u,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:u??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 kn(e,t){return Object.assign(e,{checkoutMethod:t})}function ja(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 ns(e){return e.status==="succeeded"||e.status==="declined"}async function Va(e){if(typeof document>"u"||typeof window>"u")throw new Qe.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Qe.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 m=new AbortController,_=()=>m.abort();e.signal?.aborted?m.abort():e.signal?.addEventListener("abort",_);let S=window.setTimeout(()=>m.abort(),l);try{let T=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:m.signal});if(!T.ok)return{status:"unknown"};let d=await T.json().catch(()=>null);return rs(d)}catch{return{status:"unknown"}}finally{window.clearTimeout(S),e.signal?.removeEventListener("abort",_)}},u=document.activeElement instanceof HTMLElement?document.activeElement:null,c=document.createElement("div");c.setAttribute("data-flopay-auto-3ds-overlay","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.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 R=document.createElement("iframe");R.setAttribute("title","Card authentication"),R.setAttribute("allow","payment"),R.tabIndex=0,R.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(";"),R.src=e.nextActionRedirectUrl,c.appendChild(R),document.body.appendChild(c),R.focus();let L=null;try{L=new URL(e.billingApiUrl,window.location.href).origin}catch{L=null}try{let m=await new Promise((_,S)=>{let T=!1,d=0,y=0,I=0,F=!1,f=()=>{window.clearTimeout(d),window.clearInterval(y),window.clearTimeout(I),window.removeEventListener("message",ne),R.removeEventListener("load",X),e.signal?.removeEventListener("abort",fe)},H=async()=>{if(!(T||F)){F=!0;try{let N=await s();if(T||!ns(N))return;T=!0,f(),_(N)}finally{F=!1}}},X=()=>{window.clearTimeout(I),I=window.setTimeout(()=>{H()},250)},fe=()=>{T||(T=!0,f(),S(new Qe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ne=N=>{if(N.source!==R.contentWindow||L&&N.origin!==L)return;let ee=N.data;!ee||typeof ee!="object"||ee.source!=="flopay-vault-3ds-return"||T||(T=!0,f(),_(null))};d=window.setTimeout(()=>{T||(T=!0,f(),S(new Qe.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),y=window.setInterval(()=>{H()},n),R.addEventListener("load",X),window.addEventListener("message",ne),e.signal?.addEventListener("abort",fe),e.signal?.aborted&&fe()});return m||await s()}finally{c.parentNode?.removeChild(c),u?.isConnected&&u.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 Nn(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=Dn(o)??o;return kn(new Qe.FloPayError(s,"api_error",{code:e?.gatewayErrorCode}),l)}function Bo(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function eo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function os(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 Ha(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||eo(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 c of s)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||eo(c)))return c;let u=o.gateways;if(u&&typeof u=="object"){let c=u.stripe;if(c&&typeof c=="object"){let R=c,L=[R.stripeClientSecret,R.clientSecret];for(let m of L)if(typeof m=="string"&&m.length>0&&(!t?.requirePaymentIntentClientSecret||eo(m)))return m}}}}async function as({billingApiUrl:e,sessionId:t,nonce:n,responseJson:l}){let o=Ha(l,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let c=(await new ir.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(eo(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function sr({billingApiUrl:e,sessionId:t,session:n,nonce:l,tokenizedData:o,returnUrl:s,telemetry:u}){let c=e.replace(/\/+$/,""),R=t??n.id,L=l??n.clientSecret,m=n.customer?.id??n.accountData?.userId??"",_=n.customer?.email??n.accountData?.email??"",S=n.customer?.firstName??n.accountData?.firstName??"",T=n.customer?.lastName??n.accountData?.lastName??"",d=n.customer?.country??n.accountData?.country??void 0,y=n.customer?.zip??n.accountData?.zip??void 0,I=new ir.PaymentAPI(c,u===!1?{telemetry:!1}:void 0),F=await os(()=>I.processPayment(m,{sessionId:R,nonce:L,tokenizedData:o,accountData:{userId:m,email:_,firstName:S,lastName:T,country:d,zip:y},returnUrl:s??Bo(n)}));if(F.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Kr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let f=await F.json().catch(()=>null);if(f?.type==="paypal_redirect_required"||f?.type==="3ds_required"){let H=Ha(f);if(!H)throw new Qe.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:f.type,threeDSecureToken:H,paymentMethodId:f.paymentMethodId}}if(f?.gatewayErrorCode==="authentication_required"){let H=await as({billingApiUrl:c,sessionId:R,nonce:L,responseJson:f});if(H)return H;throw kn(new Qe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new Qe.FloPayError(f?.message??"Payment failed. Please try again.","api_error",{code:f?.code??f?.gatewayErrorCode,declineCode:f?.declineCode??f?.gatewayDeclineReason})}async function to(e,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:u,returnUrl:c,telemetry:R}){let L=t?.getRawProvider();if(!L)throw new Qe.FloPayError("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!l||!e.threeDSecureToken)throw kn(new Qe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let m=(0,Qe.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,S=e.paymentMethodId,T=await es(L,e.threeDSecureToken,m);if(T){if(T.error)throw kn(new Qe.FloPayError(T.error.message??`Failed to retrieve 3DS ${m?"setup":"payment"} status.`,"api_error",{code:T.error.code}),"card");let y=T.intent;!S&&y?.payment_method&&(typeof y.payment_method=="string"?S=y.payment_method:"id"in y.payment_method&&(S=y.payment_method.id??void 0))}let d=S?await ts(L,e.threeDSecureToken,{payment_method:S,return_url:c??Bo(u)??window.location.href},m):null;if(d){if(d.error)throw kn(new Qe.FloPayError(d.error.message??"3DS authentication failed.","api_error",{code:d.error.code}),"card");_=d.intent}else{let y=await L.handleNextAction({clientSecret:e.threeDSecureToken});if(y.error)throw kn(new Qe.FloPayError(y.error.message??"3DS authentication failed.","api_error",{code:y.error.code}),"card");_=(m?y.setupIntent:y.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let y=await sr({billingApiUrl:o,sessionId:s,session:u,telemetry:R,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:c});return y.type==="success"?{...y.result,paymentIntentId:y.result.paymentIntentId??_.id,paymentMethodId:y.result.paymentMethodId??S}:to(y,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:u,returnUrl:c,telemetry:R})}throw kn(new Qe.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let m=(n??t)?.getRawProvider();if(!m)throw kn(new Qe.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:S}=await m.handleNextAction({clientSecret:e.threeDSecureToken});if(S)throw kn(new Qe.FloPayError(S.message??"PayPal authorization failed.","api_error",{code:S.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await m.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Bo(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(_)throw kn(new Qe.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Qe.FloPayError("Unsupported payment redirect state.","api_error")}function Yn(e){if(e instanceof Qe.FloPayError){let l=Dn(e.message);return l&&l!==e.message?Object.assign(new Qe.FloPayError(l,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Dn(t)??t;return new Qe.FloPayError(n,"api_error")}function no(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Qe.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 ro({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:l,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let s=!!t&&t!==e,[u,c]=await Promise.all([(0,ir.loadFloPay)(e,{billingApiUrl:n,locale:l,telemetry:o}),s?(0,ir.loadFloPay)(t,{billingApiUrl:n,locale:l,telemetry:o}).catch(R=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",R),null)):Promise.resolve(null)]);return{flopay:u,paypalFlopay:t?s?c:u:null}}var C=require("react/jsx-runtime"),lr=44,No="flopay_checkout_saved_payment_resume",Mo=new Map;function Er(e){return new Promise(t=>setTimeout(t,e))}function oo(e,t,n){let l=Ur({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ae.SDK_VERSION,enabled:t!==!1});return l.beginCheckout(n),l}function ao(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ao(e,t,n,l,o){let s=oo(e,t,n);s.error({errorCode:l,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),ao(s)}function is(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 Lo(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function Fo(e){return!e||e.data.stripe?.publishableKey?!1:!!Lo(e)?.clientId}function cr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ss(){if(!cr())return null;try{let e=window.sessionStorage.getItem(No);return e?JSON.parse(e):null}catch{return null}}function Ka(e){if(cr())try{window.sessionStorage.setItem(No,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Do(){if(cr())try{window.sessionStorage.removeItem(No)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function ls(e){if(!cr())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 cs(e,t,n){if(cr())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 Wa(e){if(cr())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",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 l of t)e.searchParams.has(l)&&(e.searchParams.delete(l),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Ya(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 us(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 io({sessionId:e,nonce:t,createSession:n,billingApiUrl:l,telemetry:o,appearance:s,locale:u,loading:c,error:R,onComplete:L,onError:m,onDecline:_,onCountryChange:S,onZipChange:T,showPayPal:d=!0,showStripe:y=!0,showApplePay:I=!0,showGooglePay:F=!0,debug:f=!1,layout:H,theme:X,buttonsTheme:fe,buttonsStyles:ne,cardButtonContent:N,cardBackButtonContent:ee,cardTitleContent:K,showSecurityFooter:ge,onButtonClick:q,onBeforeButtonClick:W,enableAVS:se,cardFieldOrder:Le,cardPreFormSlot:be,avsLayout:Pe,className:te,initialErrorMessage:he=null,children:Ce,checkoutMode:le,confirmLabel:Oe,renderConfirmButton:Ee,onSessionCompleted:ke}){let E=(0,Ae.resolveBillingApiUrl)(l),oe=(0,D.useMemo)(()=>(0,Ae.resolveTheme)(X),[X]),de=s??oe?.appearance,$e=n?"embedded_checkout":"standard_checkout",ze=Ce?"custom_layout":H==="buttons"?"buttons_layout":"default_layout",[Z,A]=(0,D.useState)(null),[Y,ue]=(0,D.useState)(null),_e=(0,D.useRef)(null),[st,tt]=(0,D.useState)(null),et=(0,D.useRef)(null),[p,je]=(0,D.useState)(null),[qe,Ge]=(0,D.useState)(e??""),Ve=e??qe,Wt=n?"":Ve,[ht,wt]=(0,D.useState)(!0),[g,Re]=(0,D.useState)(null),[He,lt]=(0,D.useState)("full"),[it,nt]=(0,D.useState)(!1),[Je,Se]=(0,D.useState)(he),[Pt,Ke]=(0,D.useState)(null),[zt,kt]=(0,D.useState)(null),[yn,Rn]=(0,D.useState)(void 0),[In,On]=(0,D.useState)(""),[gt,Ut]=(0,D.useState)(!1),[Mt,Yt]=(0,D.useState)("loading"),[tn,fn]=(0,D.useState)(0),G=(0,D.useRef)(!1),An=(0,D.useRef)(!1),gn=(0,D.useRef)(!1),$t=(0,D.useRef)(null),Tt=(0,D.useMemo)(()=>({checkoutMode:le??He,layout:Ce?"unknown":H==="buttons"?"buttons":"embedded"}),[le,Ce,He,H]),B=(0,D.useRef)(L);B.current=L;let Xe=(0,D.useRef)(m);Xe.current=m;let Ie=(0,D.useRef)(_);Ie.current=_,(0,D.useEffect)(()=>{xt(Y)?.setCheckoutContext(Tt),st&&st!==Y&&xt(st)?.setCheckoutContext(Tt)},[Y,st,Tt]);let Fn=(0,D.useRef)(ke);Fn.current=ke;let We=(0,D.useCallback)(M=>{Yt(M),!(M!=="exhausted"||gn.current)&&(gn.current=!0,Xe.current?.(new Ae.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),zn=(0,D.useCallback)(()=>{Yt("retrying"),fn(M=>M+1)},[]);(0,D.useEffect)(()=>{Yt("loading"),fn(0),gn.current=!1},[Ve]),(0,D.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ae.SDK_VERSION,checkout_type:$e,checkout_layout:ze,billing_api_url:E})},[ze,$e,E]);let hn=(0,D.useMemo)(()=>n?En(n):"",[n]),Pn=(0,D.useMemo)(()=>In===hn?yn:void 0,[yn,In,hn]),rt=(0,D.useMemo)(()=>n?wo(n,Pn):void 0,[n,Pn]),Rt=le??rt?.checkoutMode??"full",qt=(0,D.useMemo)(()=>rt?{...rt,checkoutMode:Rt}:void 0,[rt,Rt]);(0,D.useEffect)(()=>{Rn(void 0),On(hn)},[hn]),(0,D.useEffect)(()=>{Se(he)},[he]);let At=(0,D.useCallback)((M,Q,j)=>{ut(()=>{Ie.current?.(St(M,Q,j))})},[ut]),Gt=(0,D.useCallback)(async(M,Q)=>{Se(null),kt(null),Ke("processing");let j=Q?.sessionId??M.id,b=_e.current??et.current,ce=xt(b),$=b?null:oo(E,o,Tt),h={log:w=>{ce?ce.log(w):$?.log(w)},error:w=>{ce?ce.error(w):$?.error(w)},terminal:w=>{ce?ce.terminal(w):$?.terminal(w)},performance:w=>{ce?ce.performance(w):$?.performance(w)},now:()=>ce?.now()??$?.now()??0,elapsed:w=>ce?.elapsed(w)??Math.max(0,($?.now()??w)-w)},Be=h.now(),pe=!!(Q?.initialAutoProcessingError||Q?.initialAutoProcessingPending),Ue=!1,xe,O=()=>{Ue||(Ue=!0,pe=!0,xe=h.now(),h.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Bt=!1,z=()=>{Bt||(Bt=!0,h.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),h.performance({stage:"processing",durationMs:h.elapsed(Be),durationMode:"machine",paymentMethodCategory:"saved"}),xe!==void 0&&h.performance({stage:"recovery",durationMs:h.elapsed(xe),durationMode:"machine",paymentMethodCategory:"saved"}))};h.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),h.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),pe&&O();let P;try{let w=ja(Q?.initialAutoProcessingError),me;if(w)O(),w.type==="paypal_redirect_required"&&$t.current?.publishableKey&&Ka({sessionId:j,publishableKey:$t.current.publishableKey,paypalPublishableKey:$t.current.paypalPublishableKey}),me=await to(w,{flopay:_e.current,paypalFlopay:et.current,attempt3DS:Q?.attempt3DS,billingApiUrl:E,sessionId:j,session:M,telemetry:!1}),w.type==="paypal_redirect_required"&&Do();else if(Q?.initialAutoProcessingPending){let Ye=await new _r.PaymentAPI(E,{telemetry:!1}).waitForCheckoutSessionCompletion(Q.initialAutoProcessingPending.sessionId,{initialDelayMs:Q.initialAutoProcessingPending.retryAfterMs});if(Ye.data.session?.status!=="complete")throw new Ae.FloPayError("Automatic payment failed. Please try again.","api_error",{code:Ye.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});me={status:"succeeded"}}else{if(Q?.initialAutoProcessingError)throw Nn(Q.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Q.initialAutoProcessingError.checkoutMethod});if(Q?.fromCreateSession)return Q?.fallbackToFull&&(lt("full"),Ya("full")),!1;{let J=await sr({billingApiUrl:E,sessionId:j,session:M,telemetry:!1});J.type==="success"?me=J.result:(O(),J.type==="paypal_redirect_required"&&$t.current?.publishableKey&&Ka({sessionId:j,publishableKey:$t.current.publishableKey,paypalPublishableKey:$t.current.paypalPublishableKey}),me=await to(J,{flopay:_e.current,paypalFlopay:et.current,attempt3DS:Q?.attempt3DS,billingApiUrl:E,sessionId:j,session:M,telemetry:!1}),J.type==="paypal_redirect_required"&&Do())}}j&&or(j),z(),pe&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),h.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Ke("success"),await Er(Tn),P=()=>B.current?.(me)}catch(w){let me=Yn(w),J=me.checkoutMethod??Ir;return Se(me.message),kt(me.message),Q?.fallbackToFull&&(h.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),lt("full"),Ya("full")),z(),!!(me.declineCode||me.code?.toLowerCase().includes("declin"))?h.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):me.type==="validation_error"?h.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):h.error({errorCode:pe?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:pe?"recovery":"processing",paymentMethodCategory:"saved"}),ut(()=>Xe.current?.(me)),At(J,me,{code:me.code,declineCode:me.declineCode}),Ke("error"),await Promise.allSettled([Er(Cn),Q?.ensureProvidersReady?Q.ensureProvidersReady():Promise.resolve()]),pe&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{z(),$&&ao($),Ke(null),kt(null)}return ut(P),!0},[At,ut,Yn,E,o,Tt]);(0,D.useEffect)(()=>{if(typeof window>"u"||An.current)return;let M=new URLSearchParams(window.location.search),Q=M.get("payment_intent_client_secret");if(!Q)return;let j=ss();j&&(An.current=!0,(async()=>{let b,ce=0;Se(null),kt(null),Ke("processing"),nt(!0);try{if(M.get("redirect_status")==="failed")throw Object.assign(new Ae.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:$,paypalFlopay:h}=await ro({publishableKey:j.publishableKey,paypalPublishableKey:j.paypalPublishableKey,billingApiUrl:E,locale:u,telemetry:o});b=xt(h??$),ce=b?.now()??0,b?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),b?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Be=(h??$)?.getRawProvider();if(!Be)throw Object.assign(new Ae.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:pe,error:Ue}=await Be.retrievePaymentIntent(Q);if(Ue)throw Object.assign(new Ae.FloPayError(Ue.message??"Failed to retrieve PayPal payment status.","api_error",{code:Ue.code}),{checkoutMethod:"paypal"});let xe=Ca(pe?.status);if(!pe||xe==="failed")throw Object.assign(new Ae.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let O=typeof pe.payment_method=="string"?pe.payment_method:pe.payment_method?.id,Bt=xe;if(j.sessionId){let w=(await new _r.PaymentAPI(E,{telemetry:!1}).getUnifiedCheckoutSession(j.sessionId)).data.session;if(w&&w.status!=="complete"){let me=await sr({billingApiUrl:E,sessionId:j.sessionId,session:w,telemetry:!1,tokenizedData:{id:O??pe.id,type:"card",threeDSecureActionResultTokenId:pe.id,isPaypal:!0}});if(me.type!=="success")throw Object.assign(new Ae.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Bt=me.result.status}}j.sessionId&&or(j.sessionId),b?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),b?.performance({stage:"redirect_resume",durationMs:b.elapsed(ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),b?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ke("success"),await Er(Tn),ut(()=>B.current?.({status:Bt,paymentIntentId:pe.id,paymentMethodId:O,checkoutMethod:"paypal"}))}catch($){let h=Yn($),Be=h.checkoutMethod??"paypal",pe=!!(h.declineCode||h.code?.toLowerCase().includes("declin"));if(b)b.performance({stage:"redirect_resume",durationMs:b.elapsed(ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),pe?b.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):b.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(pe){let Ue=oo(E,o,Tt);Ue.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ao(Ue)}else Ao(E,o,Tt,"REDIRECT_RESUME_FAILED","redirect_resume");Se(h.message),kt(h.message),ut(()=>Xe.current?.(h)),At(Be,h,{code:h.code,declineCode:h.declineCode}),Ke("error"),await Er(Cn)}finally{Do(),ds(),Ke(null),kt(null),nt(!1)}})())},[At,ut,u,Yn,E,o]);let nn=(0,D.useRef)(null);function En(M){let Q=JSON.stringify({c:M?.clientId,cur:M?.currency??"",a:{e:M?.account?.email?.trim().toLowerCase()??"",country:M?.account?.country??""},successUrl:M?.successUrl,cancelUrl:M?.cancelUrl,p:M?.products?.map(b=>`${b.type??""}:${b.code??b.providerItemId??b.providerPlanId??""}:${b.totalAmount??""}:${b.overrideAmount??""}:${b.quantity??1}`).sort(),i:M?.items?.map(b=>`${b.code??b.providerItemId??""}:${b.totalAmount??""}:${b.overrideAmount??""}:${b.quantity??1}`).sort(),s:M?.subscriptions?.map(b=>`${b.code??b.providerPlanId??""}:${b.totalAmount??""}:${b.overrideAmount??""}:${b.quantity??1}`).sort(),couponCodes:M?.couponCodes,tagsData:M?.tagsData,utmMetadata:M?.utmMetadata,tokenizedData:M?.tokenizedData,m:M?.checkoutMode??"full"}),j=0;for(let b=0;b<Q.length;b++)j=(j<<5)-j+Q.charCodeAt(b)|0;return`flopay_session_${Math.abs(j).toString(36)}`}let Jt=(0,D.useMemo)(()=>qt?En(qt):"",[qt]),Ft=(0,D.useRef)(qt);Ft.current=qt,(0,D.useEffect)(()=>{Ge(e??"")},[e]),(0,D.useEffect)(()=>{G.current=!1,Se(he),kt(null),Ke(null)},[Jt,he,e]);async function Xt(M,Q){let j=oo(E,o,Tt),b=new _r.PaymentAPI(E,{telemetry:!1});try{let ce=ls(Q);j.log({name:ce?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let $=ce?.sid??null,h=null;if($)try{if(h=await b.getUnifiedCheckoutSession($,ce?.nonce),h.data.session?.status==="complete"){if(wa($))return{sid:$,result:h};Wa(Q),$=null,h=null}}catch{j.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Wa(Q),$=null}if(!$){let Be=j.now();j.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let pe={...M,avsCheck:!!se,avsConfig:typeof se=="object"?se:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ce?"custom_layout":H==="buttons"?"buttons_layout":"default_layout"};try{h=await b.createAndFetchSession(pe),j.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),j.performance({stage:"session_create",durationMs:j.now()-Be,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"})}catch(Ue){let xe=(0,Ae.classifyTelemetryFailure)(Ue,"CHECKOUT_SESSION_CREATE_FAILED","unknown");throw j.performance({stage:"session_create",durationMs:j.now()-Be,durationMode:"machine",requestCategory:"session_create",statusClass:xe.statusClass}),Ue instanceof Ae.FloPayError&&Ue.type==="validation_error"?j.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):xe.statusClass==="4xx"?j.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):j.error({...xe,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Ue}$=h.data.session?.id??"",$&&cs(Q,$,h.data.session?.clientSecret)}return{sid:$??"",result:h}}finally{ao(j)}}let ve=(0,D.useCallback)(async M=>{let Q=Ft.current;if(!Q)throw new Ae.FloPayError("createSession is required to bootstrap checkout.","validation_error");let j=wo(Q,M),b=En(j),ce=Mo.get(b);ce||(ce=Xt(j,b),Mo.set(b,ce));let $;try{$=await ce}finally{Mo.delete(b)}nn.current=b;try{M&&(On(hn),Rn(Bt=>ba(Bt,M)));let{sid:h,result:Be}=$;A(Be),Be.data.session&&je(Be.data.session),h&&Ge(h);let{publishableKey:pe,paypalPublishableKey:Ue}=no(Be),{flopay:xe,paypalFlopay:O}=await ro({publishableKey:pe,paypalPublishableKey:Ue,billingApiUrl:E,locale:u,telemetry:o});_e.current=xe,ue(xe),et.current=O,tt(O),wt(!1)}catch(h){throw nn.current===b&&(nn.current=null),h}return $},[u,E,o,Tt]),mt=(0,D.useCallback)(async M=>{if(!us(M)||gt)return{sessionId:qe,session:p};Ut(!0);try{let Q=await ve(M);return{sessionId:Q.sid,session:Q.result.data.session??null}}finally{Ut(!1)}},[ve,gt,qe,p]);(0,D.useEffect)(()=>{let M=!1;if(Re(null),Jt){let b=Ft.current;return lt(Rt),wt(!1),nn.current===Jt?()=>{M=!0}:(je(va(b,le)),(async()=>{let ce=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),$=Rt==="auto"&&!G.current&&!ce;$&&(Se(null),kt(null),Ke("processing"));try{let h=await ve(),Be=h.result.data.session??null;$t.current=no(h.result);let pe=Fo(h.result);if(!M&&$&&Be&&!pe){G.current=!0,await Gt(Be,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:h.result.autoProcessingError,initialAutoProcessingPending:h.result.autoProcessingPending,autoProcessingAttempted:h.result.autoProcessingAttempted,sessionId:h.sid||Be.id});return}!M&&$&&(pe&&(G.current=!0),Ke(null),kt(null))}catch(h){if(M)return;let Be=h instanceof Ae.FloPayError||typeof h=="object"&&h!==null&&"code"in h?h.code:void 0;if($&&Be==="session_auto_completed"){G.current=!0,Ke("success"),await Er(Tn),M||(ut(()=>{B.current?.({status:"succeeded"})}),Ke(null),kt(null));return}$&&(Ke(null),kt(null));let pe=h instanceof Ae.FloPayError?h:new Ae.FloPayError(h instanceof Error?h.message:"Failed to create session","api_error");Re(pe)}})(),()=>{M=!0})}wt(!0);async function Q(){let b=!1;try{let $=await new _r.PaymentAPI(E,{telemetry:!1}).getUnifiedCheckoutSession(Ve,t);if(M)return;A($);let h=$.data.session??null;if(je(h),!h)throw new Ae.FloPayError("No session data returned","api_error");if(h.status==="complete"){wt(!1),ut(()=>{Fn.current?.(h.successUrl??"")});return}if(h.status==="expired")throw new Ae.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});b=!0;let Be=le??h.checkoutMode??"full";lt(Be);let pe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ue=Fo($);if(Be==="auto"&&!G.current&&!pe&&!Ue){G.current=!0;let xe=j($);try{if(await Gt(h,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>xe,sessionId:Ve||h.id}),M)return;await xe,M||wt(!1);return}catch{if(M)return;await xe,M||wt(!1);return}}await j($),M||wt(!1)}catch(ce){if(M)return;ce instanceof Ae.FloPayError?!b&&!is(ce)&&Ao(E,o,Tt,"NETWORK_REQUEST_FAILED","session_read"):Ao(E,o,Tt,"INTERNAL_SDK_ERROR","checkout_mount");let $=ce instanceof Ae.FloPayError?ce:new Ae.FloPayError(ce instanceof Error?ce.message:"Failed to initialize checkout","api_error");Re($),wt(!1)}}async function j(b){let{publishableKey:ce,paypalPublishableKey:$}=no(b);$t.current={publishableKey:ce,paypalPublishableKey:$};let{flopay:h,paypalFlopay:Be}=await ro({publishableKey:ce,paypalPublishableKey:$,billingApiUrl:E,locale:u,telemetry:o});_e.current=h,ue(h),et.current=Be,tt(Be)}return Q(),()=>{M=!0}},[ve,le,Jt,Rt,Wt,ut,t,Gt]);let ct=(0,D.useCallback)(async()=>{if(!(it||!p)){nt(!0),Se(null);try{await Gt(p,{fallbackToFull:!0,sessionId:Ve||p.id})}finally{nt(!1)}}},[Ve,it,Gt,p]),bn=Lo(Z),Un=Fo(Z),Dt=(0,D.useMemo)(()=>{if(!Z||!p||!Z.data.stripe?.publishableKey)return;let M={appearance:de,paymentMethodCreation:"manual",billingApiUrl:E};if(Z.data.stripe?.clientSecret)M.clientSecret=Z.data.stripe.clientSecret;else{let Q=(0,Ae.buildCheckoutDisplayData)(p).total;M.amount=Math.round(Q*100)||p.amount,M.currency=p.currency?.toLowerCase()}return M},[Z,p,de,E]),Vt=!!(n&&!Ce&&H==="buttons"&&W&&Rt==="full"),bt=(0,D.useMemo)(()=>({session:p,loading:ht,error:g,checkoutMode:He,inlineSessionDraft:qt,applyInlineSessionPatch:Vt?mt:void 0,inlineSessionPatchProcessing:gt}),[p,ht,g,He,qt,Vt,mt,gt]),Jn=!!n&&H==="buttons"&&!Un&&(!Y||!Dt),Ht=Pt?(0,C.jsx)(Sn,{status:Pt,errorMessage:zt}):null;if(ht){if(c)return(0,C.jsxs)(C.Fragment,{children:[c,Ht]});if(H==="buttons"){let M=oe?.buttonsLayout?.cardButton?.borderRadius??oe?.appearance.variables?.borderRadius??8,Q=j=>(0,C.jsx)("div",{style:{height:j,borderRadius:M,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[d&&Q(lr),y&&(I||F)&&Q(lr),y&&Q(lr),(0,C.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ht]})}return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,C.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,C.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ht]})}return g?R?(0,C.jsx)(sn.Provider,{value:bt,children:R(g)}):(0,C.jsx)(sn.Provider,{value:bt,children:(0,C.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:g.message})}):Jn?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(sn.Provider,{value:bt,children:(0,C.jsx)(ms,{onButtonClick:q,showPayPal:d,showStripe:y,showApplePay:I,showGooglePay:F,theme:X,buttonsTheme:fe,buttonsStyles:ne,cardButtonContent:N,cardBackButtonContent:ee,cardTitleContent:K})}),Ht]}):Un&&p&&bn?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(sn.Provider,{value:bt,children:(0,C.jsxs)("div",{className:te,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Je&&(0,C.jsx)(nr,{icon:!1,children:Je}),Mt==="retrying"&&(0,C.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Mt==="exhausted"&&(0,C.jsxs)("div",{role:"alert",children:[(0,C.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,C.jsx)("button",{type:"button",onClick:zn,children:"Retry PayPal"})]}),Mt!=="exhausted"&&(0,C.jsx)("div",{"aria-hidden":Mt==="retrying"?!0:void 0,style:Mt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,C.jsx)(xa,{sessionId:Ve,nonce:p.clientSecret||void 0,billingApiUrl:E,email:p.customer?.email,clientId:bn.clientId,environment:bn.environment,currency:(p.currency??"usd").toUpperCase(),isSubscription:p.mode==="subscription",onComplete:L,onErrorChange:Se,onDecline:_,onButtonClick:q,onInitializationStateChange:We,allowAutomaticRetry:tn===0,session:p,telemetry:o,telemetryContext:Tt,debug:f},`paypal-init-${tn}`)})]})}),Ht]}):!Y||!Dt?(0,C.jsx)(C.Fragment,{children:Ht}):He==="confirm"?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(sn.Provider,{value:bt,children:(0,C.jsx)(vr,{flopay:Y,paypalFlopay:st,options:Dt,children:(0,C.jsxs)("div",{className:te,children:[Je&&(0,C.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Je}),Ee?Ee({onConfirm:ct,isProcessing:it}):(0,C.jsx)("button",{type:"button",onClick:ct,disabled:it,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:it?"not-allowed":"pointer",opacity:it?.6:1},children:it?"Processing...":Oe??"Confirm Purchase"})]})})}),Ht]}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(sn.Provider,{value:bt,children:(0,C.jsx)(vr,{flopay:Y,paypalFlopay:st,options:Dt,children:Ce?(0,C.jsxs)(C.Fragment,{children:[Je&&(0,C.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Je}),(0,C.jsx)(ps,{sessionId:Ve,nonce:p?.clientSecret||void 0,billingApiUrl:E,session:p,children:Ce})]}):(0,C.jsx)(Qr,{sessionId:Ve,nonce:p?.clientSecret||void 0,email:p?.customer?.email,userId:p?.customer?.id,firstName:p?.customer?.firstName,lastName:p?.customer?.lastName,totalAmount:p?Math.round((0,Ae.buildCheckoutDisplayData)(p).total*100):0,currency:p?.currency?.toLowerCase()??"usd",onComplete:L,onError:m,onDecline:_,error:Je,onErrorChange:Se,showPayPal:d,showStripe:y,enabledPaymentMethods:Z?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Z?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:F,layout:H,theme:X,buttonsTheme:fe,buttonsStyles:ne,appearance:de,cardButtonContent:N,cardBackButtonContent:ee,cardTitleContent:K,onButtonClick:q,onBeforeButtonClick:W,enableAVS:se,...Le?{cardFieldOrder:Le}:{},...be?{cardPreFormSlot:be}:{},avsLayout:Pe,country:p?.customer?.country,city:p?.customer?.city,state:p?.customer?.state,onCountryChange:S,onZipChange:T,avsCheck:!!se,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Ce?"custom_layout":H==="buttons"?"buttons_layout":"default_layout",className:te,directPaypal:Lo(Z),isSubscription:p?.mode==="subscription",session:p,debug:f})})}),Ht]})}function ps({sessionId:e,nonce:t,billingApiUrl:n,session:l,children:o}){return(0,C.jsx)(C.Fragment,{children:D.default.Children.map(o,s=>{if(!D.default.isValidElement(s))return s;let u=s.props,c={};return u.sessionId||(c.sessionId=e),!u.nonce&&t&&(c.nonce=t),u.billingApiUrl||(c.billingApiUrl=n),l?.customer&&(u.email||(c.email=l.customer.email),u.userId||(c.userId=l.customer.id),u.firstName||(c.firstName=l.customer.firstName),u.lastName||(c.lastName=l.customer.lastName)),Object.keys(c).length===0?s:D.default.cloneElement(s,c)})})}function ms({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:l,showGooglePay:o,theme:s,buttonsTheme:u,buttonsStyles:c,cardButtonContent:R,cardBackButtonContent:L,cardTitleContent:m}){let[_,S]=(0,D.useState)(!1),T=(0,D.useMemo)(()=>(0,Ae.resolveTheme)(s),[s]),d=(0,D.useMemo)(()=>{let f=T?.buttonsLayout??(0,Ae.resolveButtonsLayoutTheme)(u);return c?{...f,...c,cardButton:{...f.cardButton,...c.cardButton},cardFormContainer:{...f.cardFormContainer,...c.cardFormContainer},backButton:{...f.backButton,...c.backButton},backButtonIcon:{...f.backButtonIcon,...c.backButtonIcon},submitButton:{...f.submitButton,...c.submitButton},title:{...f.title,...c.title}}:f},[T,u,c]),y=T?.buttonsLayout?.cardButton?.borderRadius??T?.appearance.variables?.borderRadius??8,I=f=>(0,C.jsx)("div",{style:{height:f,borderRadius:y,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),F=R===void 0?{boxSizing:"border-box",height:lr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let f=d.cardInputBorder??"#e5e7eb",H=d.cardInputBackground??"white",X=Qn(L),fe=Qn(m);return(0,C.jsxs)("div",{style:{backgroundColor:d.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...d.cardFormContainer},children:[(0,C.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,C.jsxs)("button",{type:"button",onClick:()=>S(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:X?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...d.backButton},children:[(0,C.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...d.backButtonIcon},children:(0,C.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,C.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,C.jsx)(tr,{content:L})]}),fe?(0,C.jsx)("div",{style:{flex:1}}):(0,C.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...d.title},children:(0,C.jsx)(Cr,{content:m})})]}),(0,C.jsx)("div",{style:{backgroundColor:H,border:`1px solid ${f}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,C.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,C.jsxs)("div",{style:{display:"flex"},children:[(0,C.jsx)("div",{style:{flex:1,backgroundColor:H,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,C.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,C.jsx)("div",{style:{flex:1,backgroundColor:H,borderTop:"none",borderRight:`1px solid ${f}`,borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,C.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,C.jsx)("div",{style:{backgroundColor:H,border:`1px solid ${f}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,C.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,C.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...d.submitButton,opacity:.5}}),(0,C.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,S.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&I(rr),n&&(l||o)&&I(rr),n&&(0,S.jsx)("button",{type:"button",onClick:()=>{e?.("card"),w(!0)},style:{width:"100%",...F,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:d.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...d.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:(0,S.jsx)(Gn,{content:R})}),(0,S.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Kn=require("react");var Ka=require("react/jsx-runtime");function ja(e,t){function n({className:l,id:o,style:s,options:u,onChange:c,onReady:R,onFocus:N,onBlur:m,onEscape:_}){let w=(0,Kn.useRef)(null),B=(0,Kn.useRef)(null),{elements:d,reportInteractive:g}=(0,Kn.useContext)(En);return(0,Kn.useEffect)(()=>{if(!d||!w.current)return;let I=!0;return(async()=>{let F=d.getElement(e);F||(F=await d.create(e,u)),!(!I||!w.current)&&(F.mount(w.current),B.current=F,c&&F.on("change",c),F.on("ready",()=>{g?.(),R?.()}),N&&F.on("focus",N),m&&F.on("blur",m),_&&F.on("escape",_))})(),()=>{if(I=!1,B.current){try{B.current.unmount()}catch{}B.current=null}}},[d,g]),(0,Ka.jsx)("div",{ref:w,className:l,id:o,style:s})}return n.displayName=t,n}var Va=ja("payment","PaymentElement"),Ha=ja("address","AddressElement");var Wa=require("@flopay/js"),Ya=require("@flopay/shared"),dn=require("react");var cn=require("react/jsx-runtime");function Ga({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,firstName:s,lastName:u,chv:c,onTokenizedBody:R,onComplete:N,onErrorChange:m,isProcessing:_=!1}){let w=an(),B=Or(),d=zr(),[g,I]=(0,dn.useState)(!1),[F,P]=(0,dn.useState)(!1),W=(0,dn.useRef)(!1),Q=(n||d).replace(/\/+$/,""),me=(0,dn.useCallback)(async ne=>{try{let ye=await new Wa.PaymentAPI(Q).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:ne,accountData:{userId:o??"",email:l??"",firstName:s??"",lastName:u??""},chv:c});if(ye.ok){N?.();return}let V=await ye.json().catch(()=>null);m?.(V?.message??"Payment failed. Please try again.")}catch(Y){m?.(Y instanceof Error?Y.message:"An unexpected error occurred")}},[Q,e,t,o,l,s,u,c,N,m]),le=(0,dn.useCallback)(ne=>{R?R(ne):me(ne)},[R,me]);(0,dn.useEffect)(()=>{if(!w||W.current)return;let ne=new URLSearchParams(window.location.search),Y=ne.get("payment_intent"),ye=ne.get("payment_intent_client_secret"),V=ne.get("redirect_status");!Y||!ye||(W.current=!0,(async()=>{try{if(P(!0),V==="failed"){m?.("PayPal payment was declined. Please try again.");return}let G=w.getRawProvider();if(!G?.retrievePaymentIntent){m?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ce,error:De}=await G.retrievePaymentIntent(ye);if(De){m?.(De.message??"Failed to retrieve PayPal payment status.");return}if(ce&&(ce.status==="requires_capture"||ce.status==="succeeded")){let be=typeof ce.payment_method=="string"?ce.payment_method:ce.payment_method?.id;le({id:be??ce.id,type:"card",threeDSecureActionResultTokenId:ce.id,isPaypal:!0});let Pe=new URL(window.location.href);Pe.searchParams.delete("payment_intent"),Pe.searchParams.delete("payment_intent_client_secret"),Pe.searchParams.delete("redirect_status"),window.history.replaceState({},"",Pe.toString())}else m?.("PayPal payment was not completed. Please try again.")}catch(G){m?.(G instanceof Error?G.message:"Failed to complete PayPal payment.")}finally{P(!1)}})())},[w,le,m]);let U=(0,dn.useCallback)(async()=>{if(!(!w||!B))try{if(P(!0),m?.(null),!e||!l)throw new Ya.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let ne=await w.confirmPayPalPayment({billingApiUrl:Q,sessionId:e,nonce:t,email:l,returnUrl:window.location.href});if(ne.error){m?.(ne.error.message);return}ne.paymentIntentId&&(ne.status==="succeeded"||ne.status==="processing"||ne.status==="requires_capture")&&le({id:ne.paymentMethodId??ne.paymentIntentId,type:"card",threeDSecureActionResultTokenId:ne.paymentIntentId,isPaypal:!0})}catch(ne){m?.(ne instanceof Error?ne.message:"PayPal payment failed. Please try again.")}finally{P(!1)}},[w,B,e,t,l,Q,le,m]);return!w||!B?(0,cn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,cn.jsxs)(cn.Fragment,{children:[!g&&(0,cn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,cn.jsx)("div",{style:g?{}:{display:"none"},children:(0,cn.jsx)("button",{type:"button",onClick:U,disabled:F||_,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:F||_?"not-allowed":"pointer",opacity:F||_?.6:1},ref:()=>I(!0),children:F?"Processing...":"PayPal"})}),(F||_)&&(0,cn.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,cn.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 _e=require("react"),no=require("@flopay/js"),At=require("@flopay/shared");var un=require("react/jsx-runtime"),ss=44;function Ja(e){return new Promise(t=>setTimeout(t,e))}function ls(e,t){return e instanceof At.FloPayError?e:new At.FloPayError(e instanceof Error?e.message:t,"api_error")}function cs(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function ds(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 Xa({sessionId:e,nonce:t,createSession:n,paymentMethodId:l,checkoutMethod:o,clientId:s,products:u,items:c,subscriptions:R,account:N,successUrl:m,cancelUrl:_,couponCodes:w,tagsData:B,utmMetadata:d,billingApiUrl:g,locale:I,theme:F,appearance:P,buttonsTheme:W,buttonsStyles:Q,onSuccess:me,onError:le,onDecline:U,children:ne,disabled:Y=!1,type:ye="button",style:V,...G}){let ce=(0,_e.useMemo)(()=>(0,At.resolveBillingApiUrl)(g),[g]),De=(0,_e.useMemo)(()=>ds({createSession:n,clientId:s,products:u,items:c,subscriptions:R,account:N,successUrl:m,cancelUrl:_,couponCodes:w,tagsData:B,utmMetadata:d}),[N,_,s,w,n,u,c,R,m,B,d]),[be,Pe]=(0,_e.useState)(!1),[re,fe]=(0,_e.useState)(null),[ve,de]=(0,_e.useState)(null),[Ne,Ie]=(0,_e.useState)(null),Se=(0,_e.useRef)(!0),E=(0,_e.useRef)(null),ie=(0,_e.useRef)(Ne),ue=(0,_e.useRef)(me),ze=(0,_e.useRef)(le),Oe=(0,_e.useRef)(U);(0,_e.useEffect)(()=>{ie.current=Ne},[Ne]),(0,_e.useEffect)(()=>{ue.current=me},[me]),(0,_e.useEffect)(()=>{ze.current=le},[le]),(0,_e.useEffect)(()=>{Oe.current=U},[U]),(0,_e.useEffect)(()=>(Se.current=!0,()=>{Se.current=!1,E.current?.abort()}),[]),(0,_e.useEffect)(()=>{if(typeof window>"u")return;let h=we=>{we.key==="Escape"&&Ie(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let ee=(0,_e.useCallback)((h,we=Cr)=>{Oe.current?.(wt(we,h,{code:h.code,declineCode:h.declineCode}))},[]),A=(0,_e.useCallback)(async h=>{Se.current&&(de(null),fe("success"),await Ja(xn),Se.current&&ue.current?.(h))},[]),J=(0,_e.useCallback)(async(h,we)=>{Se.current&&(ze.current?.(h),we?.emitDecline&&ee(h,we.method),de(h.message),fe("error"),await Ja(bn))},[ee]),pe=(0,_e.useCallback)(async(h,we,Ve)=>{let lt=h.data.session??null;if(!lt)throw new At.FloPayError("No session data returned","api_error");let ot=lt.clientSecret||t;if(lt.status==="complete"){await A({result:{status:"succeeded"},session:lt,sessionId:lt.id||we,autoCompleted:!1});return}if(lt.status==="expired")throw new At.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(h.autoProcessingPending){let bt=(await new no.PaymentAPI(ce).waitForCheckoutSessionCompletion(h.autoProcessingPending.sessionId,{initialDelayMs:h.autoProcessingPending.retryAfterMs})).data.session;if(!bt||bt.status!=="complete")throw new At.FloPayError("Automatic payment failed. Please try again.","api_error",{code:bt?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await A({result:{status:"succeeded"},session:bt,sessionId:bt.id||we,autoCompleted:!1});return}if(h.autoProcessingError){if(h.autoProcessingError.type==="3ds_required"&&h.autoProcessingError.nextActionRedirectUrl&&we&&ot){let Ge=new AbortController;E.current=Ge;let Ce;try{Ce=await Oa({billingApiUrl:ce,sessionId:we,nonce:ot,nextActionRedirectUrl:h.autoProcessingError.nextActionRedirectUrl,signal:Ge.signal})}finally{E.current===Ge&&(E.current=null)}if(Ce.status==="declined")throw Ln({type:Ce.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ce.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let Ft=(await new no.PaymentAPI(ce).waitForCheckoutSessionCompletion(we,{initialDelayMs:0,nonce:ot})).data.session;if(!Ft||Ft.status!=="complete")throw Ln({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await A({result:{status:"succeeded"},session:Ft,sessionId:Ft.id||we,autoCompleted:!1});return}throw Ln(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(Ve?.fromCreateSession&&h.autoProcessingAttempted===!0)throw Ln({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let et=await nr({billingApiUrl:ce,sessionId:we??lt.id,session:lt,nonce:ot});if(et.type!=="success")throw Ln({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await A({result:et.result,session:lt,sessionId:lt.id||we,autoCompleted:!1})}catch(et){let Ge=Hn(et),Ce=lt.id||we;await J(Ge,{emitDecline:!0,method:Ge.checkoutMethod??Cr}),cs(Ge,Ce)&&Ce&&Se.current&&Ie({sessionId:Ce,errorMessage:Ge.message,nonce:ot||void 0})}},[t,ce,J,A]),Ee=(0,_e.useCallback)(async h=>{if(G.onClick?.(h),!(h.defaultPrevented||Y||be)){if(Ie(null),e&&De){let we=new At.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await J(we),Se.current&&(fe(null),de(null));return}if(!e&&!De){let we=new At.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await J(we),Se.current&&(fe(null),de(null));return}Pe(!0),de(null),fe("processing");try{let we=new no.PaymentAPI(ce);if(e){let Ve=await we.getUnifiedCheckoutSession(e,t);await pe(Ve,e);return}try{let Ve=await we.createAndFetchSession({...De});await pe(Ve,Ve.data.session?.id??null,{fromCreateSession:!0})}catch(Ve){if(Ve instanceof At.FloPayError&&Ve.code==="session_auto_completed"){await A({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Ve}}catch(we){await J(ls(we,"Automatic payment failed. Please try again."))}finally{Se.current&&(fe(null),de(null),Pe(!1))}}},[G,De,Y,be,t,pe,ce,e,J,A]),ft=(0,_e.useCallback)(h=>{let we=ie.current;Ie(null),ue.current?.({result:h,session:null,sessionId:we?.sessionId??null,autoCompleted:!1})},[]),Qe=(0,_e.useCallback)(h=>{ze.current?.(h)},[]),Ze=(0,_e.useCallback)(h=>{Oe.current?.(h)},[]),y=(0,_e.useMemo)(()=>(0,At.resolveTheme)(F),[F]),qe=(0,_e.useMemo)(()=>{let h=y?.buttonsLayout??(0,At.resolveButtonsLayoutTheme)(W);return Q?{...h,...Q,cardButton:{...h.cardButton,...Q.cardButton}}:h},[y,W,Q]),Ue=(0,_e.useMemo)(()=>{let h=y?.appearance;return P?h?{...h,...P,variables:{...h.variables,...P.variables}}:P:h},[P,y]),Ke=Ue?.variables,je=Ke?.colorPrimary??"#4A49FF",Ht=Ke?.colorPrimaryHover??Hr(je,.12),Pt=Ke?.borderRadius??"8px";return(0,un.jsxs)(un.Fragment,{children:[(0,un.jsx)("button",{...G,type:ye,onClick:Ee,disabled:Y||be,"aria-busy":be,style:{width:"100%",...ne===void 0?{boxSizing:"border-box",height:ss,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...qe.cardButton,...ko({themeBundle:y,resolvedPrimaryColor:je,resolvedBorderRadius:Pt,submitButtonStyle:qe.submitButton,explicitPrimaryColor:Ke?.colorPrimary}),fontSize:qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Y||be?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Y||be?.6:1,...V},onMouseEnter:h=>{G.onMouseEnter?.(h),!h.defaultPrevented&&!Y&&!be&&(y||Ke?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Ht)},onMouseLeave:h=>{G.onMouseLeave?.(h),!h.defaultPrevented&&(y||Ke?.colorPrimary)&&(h.currentTarget.style.backgroundColor=je)},onMouseDown:h=>{G.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{G.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,un.jsx)(Gn,{content:ne})}),re&&(0,un.jsx)(vn,{status:re,errorMessage:ve}),Ne&&(0,un.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&Ie(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,un.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,un.jsx)(to,{sessionId:Ne.sessionId,nonce:Ne.nonce,checkoutMode:"full",billingApiUrl:ce,locale:I,theme:F,...Ue?{appearance:Ue}:{},buttonsTheme:W,buttonsStyles:Q,initialErrorMessage:Ne.errorMessage,cardTitleContent:null,onComplete:ft,onError:Qe,onDecline:Ze})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,useCheckout,useElements,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,C.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&I(lr),n&&(l||o)&&I(lr),n&&(0,C.jsx)("button",{type:"button",onClick:()=>{e?.("card"),S(!0)},style:{width:"100%",...F,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:d.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...d.cardButton},onMouseDown:f=>{f.currentTarget.style.transform="scale(0.985)"},onMouseUp:f=>{f.currentTarget.style.transform="scale(1)"},children:(0,C.jsx)(er,{content:R})}),(0,C.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Gn=require("react");var Za=require("react/jsx-runtime");function Ga(e,t){function n({className:l,id:o,style:s,options:u,onChange:c,onReady:R,onFocus:L,onBlur:m,onEscape:_}){let S=(0,Gn.useRef)(null),T=(0,Gn.useRef)(null),{elements:d,reportInteractive:y}=(0,Gn.useContext)(_n);return(0,Gn.useEffect)(()=>{if(!d||!S.current)return;let I=!0;return(async()=>{let F=d.getElement(e);F||(F=await d.create(e,u)),!(!I||!S.current)&&(F.mount(S.current),T.current=F,c&&F.on("change",c),F.on("ready",()=>{y?.(),R?.()}),L&&F.on("focus",L),m&&F.on("blur",m),_&&F.on("escape",_))})(),()=>{if(I=!1,T.current){try{T.current.unmount()}catch{}T.current=null}}},[d,y]),(0,Za.jsx)("div",{ref:S,className:l,id:o,style:s})}return n.displayName=t,n}var Ja=Ga("payment","PaymentElement"),Xa=Ga("address","AddressElement");var Qa=require("@flopay/js"),ei=require("@flopay/shared"),pn=require("react");var un=require("react/jsx-runtime");function ti({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,firstName:s,lastName:u,chv:c,onTokenizedBody:R,onComplete:L,onErrorChange:m,isProcessing:_=!1}){let S=ln(),T=jr(),d=Vr(),[y,I]=(0,pn.useState)(!1),[F,f]=(0,pn.useState)(!1),H=(0,pn.useRef)(!1),X=(n||d).replace(/\/+$/,""),fe=(0,pn.useCallback)(async ee=>{try{let ge=await new Qa.PaymentAPI(X).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:ee,accountData:{userId:o??"",email:l??"",firstName:s??"",lastName:u??""},chv:c});if(ge.ok){L?.();return}let q=await ge.json().catch(()=>null);m?.(q?.message??"Payment failed. Please try again.")}catch(K){m?.(K instanceof Error?K.message:"An unexpected error occurred")}},[X,e,t,o,l,s,u,c,L,m]),ne=(0,pn.useCallback)(ee=>{R?R(ee):fe(ee)},[R,fe]);(0,pn.useEffect)(()=>{if(!S||H.current)return;let ee=new URLSearchParams(window.location.search),K=ee.get("payment_intent"),ge=ee.get("payment_intent_client_secret"),q=ee.get("redirect_status");!K||!ge||(H.current=!0,(async()=>{try{if(f(!0),q==="failed"){m?.("PayPal payment was declined. Please try again.");return}let W=S.getRawProvider();if(!W?.retrievePaymentIntent){m?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:se,error:Le}=await W.retrievePaymentIntent(ge);if(Le){m?.(Le.message??"Failed to retrieve PayPal payment status.");return}if(se&&(se.status==="requires_capture"||se.status==="succeeded")){let be=typeof se.payment_method=="string"?se.payment_method:se.payment_method?.id;ne({id:be??se.id,type:"card",threeDSecureActionResultTokenId:se.id,isPaypal:!0});let Pe=new URL(window.location.href);Pe.searchParams.delete("payment_intent"),Pe.searchParams.delete("payment_intent_client_secret"),Pe.searchParams.delete("redirect_status"),window.history.replaceState({},"",Pe.toString())}else m?.("PayPal payment was not completed. Please try again.")}catch(W){m?.(W instanceof Error?W.message:"Failed to complete PayPal payment.")}finally{f(!1)}})())},[S,ne,m]);let N=(0,pn.useCallback)(async()=>{if(!(!S||!T))try{if(f(!0),m?.(null),!e||!l)throw new ei.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let ee=await S.confirmPayPalPayment({billingApiUrl:X,sessionId:e,nonce:t,email:l,returnUrl:window.location.href});if(ee.error){m?.(ee.error.message);return}ee.paymentIntentId&&(ee.status==="succeeded"||ee.status==="processing"||ee.status==="requires_capture")&&ne({id:ee.paymentMethodId??ee.paymentIntentId,type:"card",threeDSecureActionResultTokenId:ee.paymentIntentId,isPaypal:!0})}catch(ee){m?.(ee instanceof Error?ee.message:"PayPal payment failed. Please try again.")}finally{f(!1)}},[S,T,e,t,l,X,ne,m]);return!S||!T?(0,un.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,un.jsxs)(un.Fragment,{children:[!y&&(0,un.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,un.jsx)("div",{style:y?{}:{display:"none"},children:(0,un.jsx)("button",{type:"button",onClick:N,disabled:F||_,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:F||_?"not-allowed":"pointer",opacity:F||_?.6:1},ref:()=>I(!0),children:F?"Processing...":"PayPal"})}),(F||_)&&(0,un.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,un.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 Te=require("react"),so=require("@flopay/js"),Ot=require("@flopay/shared");var mn=require("react/jsx-runtime"),ys=44;function ni(e){return new Promise(t=>setTimeout(t,e))}function fs(e,t){return e instanceof Ot.FloPayError?e:new Ot.FloPayError(e instanceof Error?e.message:t,"api_error")}function gs(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function hs(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 ri({sessionId:e,nonce:t,createSession:n,paymentMethodId:l,checkoutMethod:o,clientId:s,products:u,items:c,subscriptions:R,account:L,successUrl:m,cancelUrl:_,couponCodes:S,tagsData:T,utmMetadata:d,billingApiUrl:y,locale:I,theme:F,appearance:f,buttonsTheme:H,buttonsStyles:X,onSuccess:fe,onError:ne,onDecline:N,children:ee,disabled:K=!1,type:ge="button",style:q,...W}){let se=(0,Te.useMemo)(()=>(0,Ot.resolveBillingApiUrl)(y),[y]),Le=(0,Te.useMemo)(()=>hs({createSession:n,clientId:s,products:u,items:c,subscriptions:R,account:L,successUrl:m,cancelUrl:_,couponCodes:S,tagsData:T,utmMetadata:d}),[L,_,s,S,n,u,c,R,m,T,d]),[be,Pe]=(0,Te.useState)(!1),[te,he]=(0,Te.useState)(null),[Ce,le]=(0,Te.useState)(null),[Oe,Ee]=(0,Te.useState)(null),ke=(0,Te.useRef)(!0),E=(0,Te.useRef)(null),oe=(0,Te.useRef)(Oe),de=(0,Te.useRef)(fe),$e=(0,Te.useRef)(ne),ze=(0,Te.useRef)(N);(0,Te.useEffect)(()=>{oe.current=Oe},[Oe]),(0,Te.useEffect)(()=>{de.current=fe},[fe]),(0,Te.useEffect)(()=>{$e.current=ne},[ne]),(0,Te.useEffect)(()=>{ze.current=N},[N]),(0,Te.useEffect)(()=>(ke.current=!0,()=>{ke.current=!1,E.current?.abort()}),[]),(0,Te.useEffect)(()=>{if(typeof window>"u")return;let g=Re=>{Re.key==="Escape"&&Ee(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let Z=(0,Te.useCallback)((g,Re=Ir)=>{ze.current?.(St(Re,g,{code:g.code,declineCode:g.declineCode}))},[]),A=(0,Te.useCallback)(async g=>{ke.current&&(le(null),he("success"),await ni(Tn),ke.current&&de.current?.(g))},[]),Y=(0,Te.useCallback)(async(g,Re)=>{ke.current&&($e.current?.(g),Re?.emitDecline&&Z(g,Re.method),le(g.message),he("error"),await ni(Cn))},[Z]),ue=(0,Te.useCallback)(async(g,Re,He)=>{let lt=g.data.session??null;if(!lt)throw new Ot.FloPayError("No session data returned","api_error");let it=lt.clientSecret||t;if(lt.status==="complete"){await A({result:{status:"succeeded"},session:lt,sessionId:lt.id||Re,autoCompleted:!1});return}if(lt.status==="expired")throw new Ot.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(g.autoProcessingPending){let Pt=(await new so.PaymentAPI(se).waitForCheckoutSessionCompletion(g.autoProcessingPending.sessionId,{initialDelayMs:g.autoProcessingPending.retryAfterMs})).data.session;if(!Pt||Pt.status!=="complete")throw new Ot.FloPayError("Automatic payment failed. Please try again.","api_error",{code:Pt?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await A({result:{status:"succeeded"},session:Pt,sessionId:Pt.id||Re,autoCompleted:!1});return}if(g.autoProcessingError){if(g.autoProcessingError.type==="3ds_required"&&g.autoProcessingError.nextActionRedirectUrl&&Re&&it){let Je=new AbortController;E.current=Je;let Se;try{Se=await Va({billingApiUrl:se,sessionId:Re,nonce:it,nextActionRedirectUrl:g.autoProcessingError.nextActionRedirectUrl,signal:Je.signal})}finally{E.current===Je&&(E.current=null)}if(Se.status==="declined")throw Nn({type:Se.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Se.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let zt=(await new so.PaymentAPI(se).waitForCheckoutSessionCompletion(Re,{initialDelayMs:0,nonce:it})).data.session;if(!zt||zt.status!=="complete")throw Nn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await A({result:{status:"succeeded"},session:zt,sessionId:zt.id||Re,autoCompleted:!1});return}throw Nn(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(He?.fromCreateSession&&g.autoProcessingAttempted===!0)throw Nn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let nt=await sr({billingApiUrl:se,sessionId:Re??lt.id,session:lt,nonce:it});if(nt.type!=="success")throw Nn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await A({result:nt.result,session:lt,sessionId:lt.id||Re,autoCompleted:!1})}catch(nt){let Je=Yn(nt),Se=lt.id||Re;await Y(Je,{emitDecline:!0,method:Je.checkoutMethod??Ir}),gs(Je,Se)&&Se&&ke.current&&Ee({sessionId:Se,errorMessage:Je.message,nonce:it||void 0})}},[t,se,Y,A]),_e=(0,Te.useCallback)(async g=>{if(W.onClick?.(g),!(g.defaultPrevented||K||be)){if(Ee(null),e&&Le){let Re=new Ot.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Y(Re),ke.current&&(he(null),le(null));return}if(!e&&!Le){let Re=new Ot.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Y(Re),ke.current&&(he(null),le(null));return}Pe(!0),le(null),he("processing");try{let Re=new so.PaymentAPI(se);if(e){let He=await Re.getUnifiedCheckoutSession(e,t);await ue(He,e);return}try{let He=await Re.createAndFetchSession({...Le});await ue(He,He.data.session?.id??null,{fromCreateSession:!0})}catch(He){if(He instanceof Ot.FloPayError&&He.code==="session_auto_completed"){await A({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw He}}catch(Re){await Y(fs(Re,"Automatic payment failed. Please try again."))}finally{ke.current&&(he(null),le(null),Pe(!1))}}},[W,Le,K,be,t,ue,se,e,Y,A]),st=(0,Te.useCallback)(g=>{let Re=oe.current;Ee(null),de.current?.({result:g,session:null,sessionId:Re?.sessionId??null,autoCompleted:!1})},[]),tt=(0,Te.useCallback)(g=>{$e.current?.(g)},[]),et=(0,Te.useCallback)(g=>{ze.current?.(g)},[]),p=(0,Te.useMemo)(()=>(0,Ot.resolveTheme)(F),[F]),je=(0,Te.useMemo)(()=>{let g=p?.buttonsLayout??(0,Ot.resolveButtonsLayoutTheme)(H);return X?{...g,...X,cardButton:{...g.cardButton,...X.cardButton}}:g},[p,H,X]),qe=(0,Te.useMemo)(()=>{let g=p?.appearance;return f?g?{...g,...f,variables:{...g.variables,...f.variables}}:f:g},[f,p]),Ge=qe?.variables,Ve=Ge?.colorPrimary??"#4A49FF",Wt=Ge?.colorPrimaryHover??Jr(Ve,.12),ht=Ge?.borderRadius??"8px";return(0,mn.jsxs)(mn.Fragment,{children:[(0,mn.jsx)("button",{...W,type:ge,onClick:_e,disabled:K||be,"aria-busy":be,style:{width:"100%",...ee===void 0?{boxSizing:"border-box",height:ys,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...je.cardButton,...To({themeBundle:p,resolvedPrimaryColor:Ve,resolvedBorderRadius:ht,submitButtonStyle:je.submitButton,explicitPrimaryColor:Ge?.colorPrimary}),fontSize:je.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:K||be?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:K||be?.6:1,...q},onMouseEnter:g=>{W.onMouseEnter?.(g),!g.defaultPrevented&&!K&&!be&&(p||Ge?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Wt)},onMouseLeave:g=>{W.onMouseLeave?.(g),!g.defaultPrevented&&(p||Ge?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Ve)},onMouseDown:g=>{W.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{W.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:(0,mn.jsx)(er,{content:ee})}),te&&(0,mn.jsx)(Sn,{status:te,errorMessage:Ce}),Oe&&(0,mn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&Ee(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,mn.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,mn.jsx)(io,{sessionId:Oe.sessionId,nonce:Oe.nonce,checkoutMode:"full",billingApiUrl:se,locale:I,theme:F,...qe?{appearance:qe}:{},buttonsTheme:H,buttonsStyles:X,initialErrorMessage:Oe.errorMessage,cardTitleContent:null,onComplete:st,onError:tt,onDecline:et})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,useCheckout,useElements,useFloPay,usePayPalFloPay});