@flopay/react 1.4.13 → 1.4.16

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 Ii=Object.create;var zr=Object.defineProperty;var Ei=Object.getOwnPropertyDescriptor;var _i=Object.getOwnPropertyNames;var xi=Object.getPrototypeOf,Ti=Object.prototype.hasOwnProperty;var Mi=(e,t)=>{for(var n in t)zr(e,n,{get:t[n],enumerable:!0})},ya=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _i(t))!Ti.call(e,o)&&o!==n&&zr(e,o,{get:()=>t[o],enumerable:!(l=Ei(t,o))||l.enumerable});return e};var fa=(e,t,n)=>(n=e!=null?Ii(xi(e)):{},ya(t||!e||!e.__esModule?zr(n,"default",{value:e,enumerable:!0}):n,e)),Bi=e=>ya(zr({},"__esModule",{value:!0}),e);var Is={};Mi(Is,{AddressElement:()=>ti,DirectPayPalButton:()=>Rr,FloPayAutomaticPaymentButton:()=>si,FloPayCheckout:()=>lo,FloPayProvider:()=>Cr,PayPalButton:()=>ai,PaymentElement:()=>ei,SplitCardForm:()=>Qr,VaultCardFields:()=>$r,useCheckout:()=>Ca,useElements:()=>jr,useFloPay:()=>ln,usePayPalFloPay:()=>qr});module.exports=Bi(Is);var Ai=()=>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=Ai();var St=require("react"),ga=require("@flopay/shared");var ko=require("react"),_n=(0,ko.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),sn=(0,ko.createContext)({session:null,loading:!1,error:null});var Fi=Symbol.for("@flopay/js.telemetry.bridge.v1"),Di=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Li(){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 Ni(e){let t=Li(),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[Di];return Ni(t?.(e)??{})}function Tt(e){if(e)return e[Fi]}var ha=require("react/jsx-runtime");function Cr({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),[k,N]=(0,St.useState)(null),y=(0,St.useRef)(null),E=(0,St.useRef)(null),S=(0,St.useRef)(null);(0,St.useEffect)(()=>{if(!o)return;let R=Tt(o);return y.current=R?.beginCheckout()??R?.now()??0,R?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{R?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),(0,St.useEffect)(()=>{let R=!1;return e instanceof Promise?e.then(F=>{R||s(F)}):s(e),()=>{R=!0}},[e]),(0,St.useEffect)(()=>{let R=!1;if(!t){c(null);return}return t instanceof Promise?t.then(F=>{R||c(F)}):c(t),()=>{R=!0}},[t]),(0,St.useEffect)(()=>{if(!o){N(null);return}let R=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return N(R),()=>{R.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,St.useEffect)(()=>{if(!o||!k||E.current===k)return;E.current=k;let R=Tt(o);R?.log({name:"checkout.rendered",stage:"checkout_render"}),R?.performance({stage:"checkout_render",durationMs:R.elapsed(y.current??0),durationMode:"machine"})},[k,o]);let M=(0,St.useCallback)(()=>{if(!o||!k||S.current===k)return;S.current=k;let R=Tt(o);R?.log({name:"checkout.interactive",stage:"checkout_interactive"}),R?.performance({stage:"checkout_interactive",durationMs:R.elapsed(y.current??0),durationMode:"machine"})},[k,o]),d=(0,ga.resolveBillingApiUrl)(n?.billingApiUrl),f=(0,St.useMemo)(()=>({flopay:o,paypalFlopay:u,elements:k,billingApiUrl:d,reportInteractive:M}),[o,u,k,d,M]);return(0,ha.jsx)(_n.Provider,{value:f,children:l})}var D=fa(require("react"),1),Jn=require("@flopay/js"),xe=require("@flopay/shared");var zs=require("react"),at=require("react/jsx-runtime");function Oi(){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 zi(){return(0,at.jsx)(at.Fragment,{children:"Go back"})}function Ui(){return(0,at.jsx)(at.Fragment,{children:"Secure card checkout"})}function tr(e){return e!==void 0&&(e===""||e===null||e===!1)}function nr({content:e}){return(0,at.jsx)(at.Fragment,{children:e===void 0?(0,at.jsx)(Oi,{}):e})}function rr({content:e}){return(0,at.jsx)(at.Fragment,{children:e===void 0?(0,at.jsx)(zi,{}):e})}function Sr({content:e}){return(0,at.jsx)(at.Fragment,{children:e===void 0?(0,at.jsx)(Ui,{}):e})}var mt=require("@stripe/react-stripe-js"),w=require("@flopay/shared"),dn=require("@flopay/js");var xn=require("react"),Pa=require("react/jsx-runtime");function $r({capture:e,html:t,messageToken:n,expectedOrigin:l,theme:o,containerStyle:s,onReady:u,onError:c,onValidation:k}){let N=(0,xn.useRef)(null),y=(0,xn.useRef)(u),E=(0,xn.useRef)(c),S=(0,xn.useRef)(k);y.current=u,E.current=c,S.current=k;let M=(0,xn.useRef)(o);return M.current=o,(0,xn.useEffect)(()=>{let d=N.current;if(!d)return;let f=!0,R=!1,F=()=>{!f||R||(R=!0,y.current?.())},g=e.on("ready",()=>{F()}),H=e.on("error",ae=>{E.current?.(ae.message??"There was a problem loading the secure card form.")}),Q=e.on("validation",ae=>{S.current?.(ae.message??null)}),Pe={html:t,...n?{messageToken:n}:{},...l?{expectedOrigin:l}:{},...M.current?{theme:M.current}:{}};return e.mount(d,Pe).then(()=>{F()}).catch(ae=>{f&&E.current?.(ae instanceof Error?ae.message:"Failed to load the secure card form.")}),()=>{f=!1,g(),H(),Q(),e.unmount()}},[e,t,n,l]),(0,xn.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,Pa.jsx)("div",{ref:N,"data-testid":"flopay-vault-card-fields",style:s})}var Hs=require("react"),wr=require("react/jsx-runtime");function or({children:e,margin:t,icon:n=!0,styleOverride:l}){return(0,wr.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,wr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,wr.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 ba={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=fa(require("react"),1);var ar=require("react"),va=require("@flopay/shared");function ln(){return(0,ar.useContext)(_n).flopay}function qr(){return(0,ar.useContext)(_n).paypalFlopay??null}function jr(){return(0,ar.useContext)(_n).elements}function Ca(){return(0,ar.useContext)(sn)}function Kr(){return(0,ar.useContext)(_n).billingApiUrl||(0,va.resolveBillingApiUrl)()}var tl=require("react"),gt=require("react/jsx-runtime"),Tn=1200,Cn=1500;function Sn({status:e,errorMessage:t}){return(0,gt.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,gt.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,gt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,gt.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,gt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,gt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,gt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,gt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,gt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,gt.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,gt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,gt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,gt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,gt.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,gt.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,gt.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,gt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,gt.jsx)("style",{children:`
1
+ "use strict";var _i=Object.create;var Ur=Object.defineProperty;var xi=Object.getOwnPropertyDescriptor;var Ti=Object.getOwnPropertyNames;var Mi=Object.getPrototypeOf,Bi=Object.prototype.hasOwnProperty;var Ai=(e,t)=>{for(var n in t)Ur(e,n,{get:t[n],enumerable:!0})},ga=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ti(t))!Bi.call(e,o)&&o!==n&&Ur(e,o,{get:()=>t[o],enumerable:!(l=xi(t,o))||l.enumerable});return e};var ha=(e,t,n)=>(n=e!=null?_i(Mi(e)):{},ga(t||!e||!e.__esModule?Ur(n,"default",{value:e,enumerable:!0}):n,e)),Fi=e=>ga(Ur({},"__esModule",{value:!0}),e);var xs={};Ai(xs,{AddressElement:()=>ri,DirectPayPalButton:()=>Ir,FloPayAutomaticPaymentButton:()=>ci,FloPayCheckout:()=>co,FloPayProvider:()=>Sr,PayPalButton:()=>si,PaymentElement:()=>ni,SplitCardForm:()=>eo,VaultCardFields:()=>qr,useCheckout:()=>wa,useElements:()=>Vr,useFloPay:()=>ln,usePayPalFloPay:()=>jr});module.exports=Fi(xs);var Di=()=>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,Le=Di();var Ct=require("react"),Pa=require("@flopay/shared");var Ro=require("react"),_n=(0,Ro.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),sn=(0,Ro.createContext)({session:null,loading:!1,error:null});var Li=Symbol.for("@flopay/js.telemetry.bridge.v1"),Ni=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Oi(){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 zi(e){let t=Oi(),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 $r(e){let t=globalThis[Ni];return zi(t?.(e)??{})}function _t(e){if(e)return e[Li]}var ba=require("react/jsx-runtime");function Sr({flopay:e,paypalFlopay:t,options:n,children:l}){let[o,s]=(0,Ct.useState)(e instanceof Promise?null:e),[p,d]=(0,Ct.useState)(t instanceof Promise||!t?null:t),[k,D]=(0,Ct.useState)(null),f=(0,Ct.useRef)(null),E=(0,Ct.useRef)(null),C=(0,Ct.useRef)(null);(0,Ct.useEffect)(()=>{if(!o)return;let _=_t(o);return f.current=_?.beginCheckout()??_?.now()??0,_?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{_?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),(0,Ct.useEffect)(()=>{let _=!1;return e instanceof Promise?e.then(F=>{_||s(F)}):s(e),()=>{_=!0}},[e]),(0,Ct.useEffect)(()=>{let _=!1;if(!t){d(null);return}return t instanceof Promise?t.then(F=>{_||d(F)}):d(t),()=>{_=!0}},[t]),(0,Ct.useEffect)(()=>{if(!o){D(null);return}let _=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return D(_),()=>{_.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,Ct.useEffect)(()=>{if(!o||!k||E.current===k)return;E.current=k;let _=_t(o);_?.log({name:"checkout.rendered",stage:"checkout_render"}),_?.performance({stage:"checkout_render",durationMs:_.elapsed(f.current??0),durationMode:"machine"})},[k,o]);let M=(0,Ct.useCallback)(()=>{if(!o||!k||C.current===k)return;C.current=k;let _=_t(o);_?.log({name:"checkout.interactive",stage:"checkout_interactive"}),_?.performance({stage:"checkout_interactive",durationMs:_.elapsed(f.current??0),durationMode:"machine"})},[k,o]),u=(0,Pa.resolveBillingApiUrl)(n?.billingApiUrl),P=(0,Ct.useMemo)(()=>({flopay:o,paypalFlopay:p,elements:k,billingApiUrl:u,reportInteractive:M}),[o,p,k,u,M]);return(0,ba.jsx)(_n.Provider,{value:P,children:l})}var B=ha(require("react"),1),Xn=require("@flopay/js"),_e=require("@flopay/shared");var qs=require("react"),nt=require("react/jsx-runtime");function Ui(){return(0,nt.jsxs)(nt.Fragment,{children:[(0,nt.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,nt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,nt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,nt.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,nt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function $i(){return(0,nt.jsx)(nt.Fragment,{children:"Go back"})}function qi(){return(0,nt.jsx)(nt.Fragment,{children:"Secure card checkout"})}function nr(e){return e!==void 0&&(e===""||e===null||e===!1)}function rr({content:e}){return(0,nt.jsx)(nt.Fragment,{children:e===void 0?(0,nt.jsx)(Ui,{}):e})}function or({content:e}){return(0,nt.jsx)(nt.Fragment,{children:e===void 0?(0,nt.jsx)($i,{}):e})}function wr({content:e}){return(0,nt.jsx)(nt.Fragment,{children:e===void 0?(0,nt.jsx)(qi,{}):e})}var dt=require("@stripe/react-stripe-js"),w=require("@flopay/shared"),dn=require("@flopay/js");var xn=require("react"),va=require("react/jsx-runtime");function qr({capture:e,html:t,messageToken:n,expectedOrigin:l,theme:o,containerStyle:s,onReady:p,onError:d,onValidation:k}){let D=(0,xn.useRef)(null),f=(0,xn.useRef)(p),E=(0,xn.useRef)(d),C=(0,xn.useRef)(k);f.current=p,E.current=d,C.current=k;let M=(0,xn.useRef)(o);return M.current=o,(0,xn.useEffect)(()=>{let u=D.current;if(!u)return;let P=!0,_=!1,F=()=>{!P||_||(_=!0,f.current?.())},g=e.on("ready",()=>{F()}),ce=e.on("error",te=>{E.current?.(te.message??"There was a problem loading the secure card form.")}),j=e.on("validation",te=>{C.current?.(te.message??null)}),pe={html:t,...n?{messageToken:n}:{},...l?{expectedOrigin:l}:{},...M.current?{theme:M.current}:{}};return e.mount(u,pe).then(()=>{F()}).catch(te=>{P&&E.current?.(te instanceof Error?te.message:"Failed to load the secure card form.")}),()=>{P=!1,g(),ce(),j(),e.unmount()}},[e,t,n,l]),(0,xn.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,va.jsx)("div",{ref:D,"data-testid":"flopay-vault-card-fields",style:s})}var Gs=require("react"),kr=require("react/jsx-runtime");function ar({children:e,margin:t,icon:n=!0,styleOverride:l}){return(0,kr.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,kr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,kr.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",Le).href,bancontact:new URL("./payment-logos/bancontact.svg",Le).href,blik:new URL("./payment-logos/blik.svg",Le).href,eps:new URL("./payment-logos/eps.svg",Le).href,giropay:new URL("./payment-logos/giropay.svg",Le).href,ideal:new URL("./payment-logos/ideal.svg",Le).href,klarna:new URL("./payment-logos/klarna.svg",Le).href,p24:new URL("./payment-logos/p24.svg",Le).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",Le).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",Le).href};var r=ha(require("react"),1);var ir=require("react"),Sa=require("@flopay/shared");function ln(){return(0,ir.useContext)(_n).flopay}function jr(){return(0,ir.useContext)(_n).paypalFlopay??null}function Vr(){return(0,ir.useContext)(_n).elements}function wa(){return(0,ir.useContext)(sn)}function Kr(){return(0,ir.useContext)(_n).billingApiUrl||(0,Sa.resolveBillingApiUrl)()}var ol=require("react"),yt=require("react/jsx-runtime"),Tn=1200,hn=1500;function Pn({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:`
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 Sa=require("@flopay/shared");function wa(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 Ro(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 ka(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 Io(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 $i=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Ln(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:l}of $i)if(n.test(t))return l;return e}function Vr(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Ra(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Ia(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Hr(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 ir(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Wr+e,JSON.stringify(t))}catch{}}function Eo(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 Ea(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"),Ta=require("@paypal/paypal-js"),Yr=require("@flopay/js"),Bn=require("@flopay/shared");function pt(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function qi(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Yn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Mn(e){if(typeof e!="object"||e===null)return;let t=e;return Yn(t.code)??Yn(t.type)??Yn(t.name)}function sr(e){if(!(typeof e!="object"||e===null))return Yn(e.decline_code)}function kr(e){return typeof e!="object"||e===null?!1:Yn(e.type)?.toLowerCase()==="card_error"||sr(e)!==void 0}function Nn(e){let t=qi(e)?.toLowerCase()??"",l=`${Mn(e)?.toLowerCase()??""} ${t}`;return l.includes("popup")&&l.includes("block")}var cn=require("react/jsx-runtime"),Gr=45,ji=1e3,Ki=11e3,Vi=["https://www.paypal.com","https://www.sandbox.paypal.com"],_a="We couldn't open PayPal. Try again or choose another payment method.",Hi={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 xa(e){return e.includes("No ack for postMessage init()")&&Vi.some(t=>e.includes(t))&&e.includes("10000ms")}function Wi(e){return e?`${_a} Allow pop-ups for this site, then try again.`:_a}function Ma({sessionId:e,nonce:t,billingApiUrl:n,email:l,clientId:o,environment:s,currency:u,isSubscription:c,onTokenizedBody:k,onComplete:N,onErrorChange:y,onDecline:E,onTechnicalFailure:S,isProcessing:M=!1,onLoadStateChange:d,onInitializationStateChange:f,allowAutomaticRetry:R=!0,onButtonClick:F,runBeforeButtonClick:g,session:H,existingOrderId:Q,telemetry:Pe,telemetryContext:ae,debug:O=!1}){let te=ln(),W=(0,T.useMemo)(()=>{if(te)return null;let B=Ur({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Bn.SDK_VERSION,enabled:Pe!==!1});return B.setCheckoutContext(ae??{}),B.beginCheckout(ae??{}),B},[n,te,Pe,ae?.checkoutMode,ae?.layout]),be=(0,T.useMemo)(()=>Tt(te),[te]);(0,T.useEffect)(()=>()=>{W&&W.flush().catch(()=>{}).finally(()=>W.destroy())},[W]);let U=(0,T.useMemo)(()=>({error:B=>{be?be.error(B):W?.error(B)},log:B=>{be?be.log(B):W?.log(B)},performance:B=>{be?be.performance(B):W?.performance(B)},terminal:B=>{be?be.terminal(B):W?.terminal(B)},startTiming:()=>be?.now()??W?.now()??0,elapsed:B=>be?.elapsed(B)??Math.max(0,(W?.now()??B)-B)}),[be,W]),Y=(0,T.useRef)(null),ce=(0,T.useRef)(0),De=(0,T.useRef)(null),we=(0,T.useRef)(!1),[Se,ne]=(0,T.useState)(!1),[ve,Re]=(0,T.useState)(!1),[de,Ne]=(0,T.useState)(0),Me=(0,T.useRef)(0),[Ee,I]=(0,T.useState)(!1),se=(0,T.useRef)(!1),me=(0,T.useRef)(!1),[ze,Oe]=(0,T.useState)(!1),[ee,A]=(0,T.useState)(!1),G=(0,T.useMemo)(()=>n.replace(/\/+$/,""),[n]),ye=(0,T.useMemo)(()=>JSON.stringify([G,o,u,s??"",c,e,Q??""]),[G,o,u,s,Q,c,e]),Be=(0,T.useRef)(ye),st=Be.current!==ye,[tt,et]=(0,T.useState)([]),m=B=>{O&&et(Xe=>[...Xe,`${new Date().toISOString().slice(11,23)} ${B}`])},$e=(0,T.useRef)(k),Ue=(0,T.useRef)(N),We=(0,T.useRef)(y),qe=(0,T.useRef)(E),Wt=(0,T.useRef)(S),Pt=(0,T.useRef)(F),kt=(0,T.useRef)(d),h=(0,T.useRef)(f),_e=(0,T.useRef)(g),je=(0,T.useRef)(H),lt=(0,T.useRef)(l),it=(0,T.useRef)(t),nt=(0,T.useRef)(null),Je=(0,T.useRef)(0),Ie=(0,T.useRef)(null),bt=(0,T.useRef)(null),Ke=(0,T.useRef)(new Map),Ot=(0,T.useRef)(new Map),Rt=(0,T.useRef)(!1);(0,T.useEffect)(()=>(Rt.current=!0,()=>{Rt.current=!1}),[]),(0,T.useEffect)(()=>{$e.current=k},[k]),(0,T.useEffect)(()=>{Ue.current=N},[N]),(0,T.useEffect)(()=>{We.current=y},[y]),(0,T.useEffect)(()=>{qe.current=E},[E]),(0,T.useEffect)(()=>{Wt.current=S},[S]),(0,T.useEffect)(()=>{Pt.current=F},[F]),(0,T.useEffect)(()=>{kt.current=d},[d]),(0,T.useEffect)(()=>{h.current=f},[f]),(0,T.useEffect)(()=>{_e.current=g},[g]),(0,T.useEffect)(()=>{je.current=H},[H]),(0,T.useEffect)(()=>{lt.current=l},[l]),(0,T.useEffect)(()=>{it.current=t},[t]),(0,T.useEffect)(()=>{Me.current=de},[de]),(0,T.useEffect)(()=>{Ee&&De.current?.focus()},[Ee,de]);let yn=(0,T.useCallback)(()=>{window.setTimeout(()=>{De.current?.focus()},0)},[]),Rn=(0,T.useCallback)(()=>{ne(!1),Ne(B=>B+1)},[]),In=(0,T.useCallback)(()=>{I(!1),(Y.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Y.current)?.focus?.()},[]);(0,T.useEffect)(()=>{!Se||!we.current||(we.current=!1,In())},[In,Se,de]);let zn=(0,T.useCallback)((B,Xe)=>{let Te=Wt.current;if(Te){Te("paypal",B,Xe);return}We.current?.(Wi(Xe?.popupBlocked??Nn(B)))},[]),ht=()=>{Ie.current?.timer&&(clearTimeout(Ie.current.timer),Ie.current.timer=null)},zt=()=>{ht();let B=Je.current+1;return Je.current=B,bt.current=null,Ie.current={generation:B,timer:null,yieldedControl:!1},I(!1),B},Bt=B=>B!==void 0&&Ie.current?.generation!==B?!1:(ht(),Ie.current=null,bt.current=null,!0),Yt=B=>{let Xe=B?.generation??Ie.current?.generation??Je.current;(!B?.generation||Ie.current?.generation===Xe)&&(ht(),Ie.current=null),bt.current=Xe,B?.showRetry&&I(!0),B?.remount&&Rn(),B?.focus!==!1&&yn()},en=B=>Ie.current?.generation===B&&bt.current!==B,fn=B=>{typeof document<"u"&&document.visibilityState!=="visible"||(ht(),B.timer=setTimeout(()=>{Ie.current?.generation===B.generation&&(Ie.current=null,bt.current=B.generation,zn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),I(!0),Rn(),yn())},600))},J=()=>{let B=Ie.current;B?.yieldedControl&&fn(B)},Fn=()=>{let B=Ie.current;B&&(B.yieldedControl=!0,ht())},gn=B=>{let Xe=nt.current;return Xe&&Ot.current.set(B,Xe),B};(0,T.useEffect)(()=>{let B=()=>{document.visibilityState==="visible"?J():Fn()};return document.addEventListener("visibilitychange",B),window.addEventListener("focus",J),window.addEventListener("blur",Fn),()=>{document.removeEventListener("visibilitychange",B),window.removeEventListener("focus",J),window.removeEventListener("blur",Fn),ht()}},[]),(0,T.useEffect)(()=>{Be.current!==ye&&(Be.current=ye,se.current=!1,me.current=!1,ne(!1),Re(!1),Oe(!1),h.current?.("loading"))},[ye]),(0,T.useEffect)(()=>{pt(()=>kt.current?.(Se&&!ze))},[Se,ze]);let Ut=(0,Bn.normalizeGatewayEnvironment)(s);(0,T.useEffect)(()=>{let B=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",Xe=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(m(`mount clientId=${B} env=${s??"(unset)"}\u2192${Ut??"live"} ccy=${u} sub=${c}`),m(`ua=${Xe.slice(0,80)}${Xe.length>80?"\u2026":""}`),!o){m("FAIL: clientId empty \u2014 gateway misconfigured"),Oe(!0),U.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(!Y.current){m("FAIL: containerRef not attached");return}ce.current=U.startTiming(),U.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Te=!1,Dn=!1,Ve=()=>Te||Dn,Un,hn=!1,Pn=()=>{Un=(0,Bn.generateIdempotencyKey)(),Un||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),hn=!0},rt=null,It=!1,$t=null,At=!1,Gt=()=>{!$t||At||(At=!0,$t.close().catch(()=>{}))},tn=null,En=()=>{tn!==null&&(U.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),U.performance({stage:"overlay_return",durationMs:U.elapsed(tn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),tn=null)},Kt=!1,Ft=Y.current,Jt=null,ke=null,yt=[],ct=L=>{if(!L||typeof L.getBoundingClientRect!="function")return"(no rect)";let p=L.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},bn=L=>{if(!L)return"(empty)";try{let p=new URL(L,typeof window<"u"?window.location.href:"https://localhost"),P=p.pathname.toLowerCase();return P.includes("checkcaptcha")||P.includes("captcha")?`CAPTCHA(${p.host}${P})`:P.includes("risk")||P.includes("challenge")?`RISK(${p.host}${P})`:P.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${P}`.slice(0,100)}catch{return L.slice(0,80)}},$n=L=>{let p=L.getAttribute("src"),P=L.getAttribute("srcdoc"),ge=L.getAttribute("name"),X=L.getAttribute("sandbox"),He=[];return p&&He.push(`src=${bn(p)}`),P&&He.push(`srcdoc[${P.length}ch]`),!p&&!P&&He.push("src=(empty) srcdoc=(empty)"),ge&&He.push(`name=${ge.slice(0,40)}`),X!==null&&He.push(`sandbox="${X.slice(0,40)}"`),He.join(" ")},Dt=L=>{if(!(L instanceof HTMLIFrameElement))return"";try{let p=L.contentDocument;if(!p)return"cd=null";let P=p.body?.children.length??0,ge=p.body?.innerHTML.length??0,X=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${P}children,${ge}ch] head[${X}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},Vt=[],vt=L=>{if(Ve())return;let p=L.message??String(L.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(m(`window:error ${p.slice(0,140)}`),Vt.push(p))},Zn=L=>{if(Ve())return;let p=L.reason instanceof Error?L.reason.message:String(L.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(m(`window:rejection ${p.slice(0,140)}`),Vt.push(p))};O&&typeof window<"u"&&(window.addEventListener("error",vt),window.addEventListener("unhandledrejection",Zn));let Ht={value:0};if(O&&typeof PerformanceObserver<"u")try{ke=new PerformanceObserver(L=>{if(!Ve())for(let p of L.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;Ht.value+=1;let P=Math.round(p.duration);m(`net ${P}ms ${p.name.slice(0,90)}`)}}),ke.observe({type:"resource",buffered:!0})}catch{}let _=()=>{for(Jt?.disconnect(),Jt=null,ke?.disconnect(),ke=null;yt.length;)clearTimeout(yt.pop());O&&typeof window<"u"&&(window.removeEventListener("error",vt),window.removeEventListener("unhandledrejection",Zn))},j=L=>{if(!L)return!1;let p=L.toLowerCase();return p.includes("zoid destroyed")||p.includes("destroyed all components")||p.includes("window closed")||p.includes("detected container element removed")},Z=L=>{if(Ve()||j(L))return;let p=Ln(L)??L;pt(()=>We.current?.(p))},oe=L=>{Te||(Oe(!0),L.includes("paypal_ineligible")||U.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:",L))},ue=(L,p=!1)=>{if(Te)return;let P=se.current||!R;if(It)return;It=!0,Dn=!0,_(),Gt();let ge=p||xa(L);if(ge&&R&&!se.current){se.current=!0,ne(!1),A(!1),Re(!0),h.current?.("retrying"),rt=setTimeout(()=>{Te||Ne(X=>X+1)},ji);return}if(ge||P){if(ne(!1),A(!1),Re(!1),Oe(!0),h.current?.("exhausted"),!me.current){me.current=!0;let X=xa(L)?"paypal_init_timeout":p?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",X)}return}oe(L)};Oe(!1);let q=async(L,p=nt.current)=>{if(Ve())return;let P=p?.sessionId??e;if($e.current){await $e.current(L,{sessionId:P,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let ge=U.startTiming();U.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let X=()=>{U.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),U.performance({stage:"processing",durationMs:U.elapsed(ge),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let He=je.current,ut=p?.accountPatch?.email??lt.current,qt=p?.accountPatch?.userId??He?.customer?.id??He?.accountData?.userId??"",fe=await new Yr.PaymentAPI(G,{telemetry:!1}).processPayment(qt,{sessionId:P,nonce:p?.nonce??it.current,tokenizedData:L,accountData:{userId:qt,email:ut??He?.customer?.email??"",firstName:p?.accountPatch?.firstName??He?.customer?.firstName??He?.accountData?.firstName??"",lastName:p?.accountPatch?.lastName??He?.customer?.lastName??He?.accountData?.lastName??"",country:p?.accountPatch?.country??He?.customer?.country??He?.accountData?.country??void 0,zip:p?.accountPatch?.zip??He?.customer?.zip??He?.accountData?.zip??void 0}});if(fe.ok){if(Dn||Te&&Rt.current)return;X(),U.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),pt(()=>Ue.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ve())return;let he=await fe.json().catch(()=>null),Ge=he?.message??"PayPal payment failed.",nn=Ln(Ge)??Ge;X(),fe.status===400&&(typeof he?.declineCode=="string"||!Array.isArray(he?.fields))?U.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):fe.status===400||fe.status===422?U.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):U.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:fe.status>=500?"5xx":fe.status>=400?"4xx":fe.status>=300?"3xx":"unknown",failureCategory:fe.status>=500?"server_error":void 0}),Z(nn),pt(()=>qe.current?.(wt("paypal",nn,{code:he?.code,declineCode:he?.declineCode})));return}catch(He){if(Ve())return;X(),U.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let ut=He instanceof Error?He.message:"PayPal payment failed.",qt=Ln(ut)??ut;Z(qt),pt(()=>qe.current?.(wt("paypal",qt)));return}},b=()=>new Bn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),re=L=>Ve()?Promise.reject(b()):Promise.resolve(L),z=async L=>{if(Ve())throw b();hn||Pn();let p=nt.current,P=p?.sessionId??e,ge=p?.nonce??it.current;U.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let X=await new Yr.PaymentAPI(G,{telemetry:!1}).createSessionIntent(P,ge??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Un});if(Ve())throw b();if(X.provider!=="paypal")throw new Error(L);return U.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),X.providerObjectId},pe=(L,p)=>{let P=p?.nonce??it.current;if(!P)return;let ge=p?.sessionId??e,X=sr(L)??Mn(L)??"provider_declined";new Yr.PaymentAPI(G,{telemetry:!1}).reportSessionIntentDecline(ge,P,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:X}).catch(()=>{})},Ce=de;m("loadScript:scheduled (deferred 1 tick)");let x=null,dt=setTimeout(()=>{if(Te){m("loadScript:skipped (cancelled before defer ran)");return}m("loadScript:start");let L=Ut==="live"?"production":Ut;x=(0,Ta.loadScript)({clientId:o,currency:u,intent:c?"subscription":"capture",vault:c?!0:void 0,...L?{environment:L}:{},...L==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),x.then(p=>{if(m(`loadScript:resolved inactive=${Ve()} ns=${!!p} buttons=${!!p?.Buttons}`),Ve())return;if(!p?.Buttons){m("FAIL: namespace missing Buttons factory"),ue("PayPal SDK did not expose the Buttons factory.");return}U.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),U.performance({stage:"provider_ready",durationMs:U.elapsed(ce.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),U.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let P=async Ye=>{if(Ve()||Me.current!==Ce)return;let fe=Ye.subscriptionID??Ye.orderID??"",he=fe?Ot.current.get(fe):Ke.current.get(Ce);if(!(!he||!en(he.generation))&&Bt(he.generation)){Ot.current.delete(fe),Ke.current.delete(he.surfaceKey),En();try{if(A(!0),pt(()=>We.current?.(null)),!fe)throw new Bn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await q({id:fe,isPaypal:!0},he)}catch(Ge){Z(Ge instanceof Error?Ge.message:"PayPal capture failed.")}finally{Ve()||A(!1)}}},ge=p.Buttons({style:{layout:"horizontal",height:Gr,tagline:!1},onClick:async(Ye,fe)=>{if(Ve()){await fe.reject();return}Pn();let he=_e.current,Ge={};if(he)try{let K=await he("paypal");if(Ve()){await fe.reject();return}if(!K.proceed){nt.current=null,Ke.current.delete(Ce),await fe.reject();return}Ge={sessionId:K.sessionId,accountPatch:K.accountPatch,nonce:K.nonce}}catch(K){m(`onClick:runBeforeButtonClick rejected msg=${(K instanceof Error?K.message:String(K)).slice(0,120)}`),nt.current=null,Ke.current.delete(Ce),await fe.reject();return}pt(()=>Pt.current?.("paypal"));let rn={generation:zt(),surfaceKey:Ce,...Ge};nt.current=rn,Ke.current.set(Ce,rn),await fe.resolve(),U.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),U.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),U.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),tn=U.startTiming()},createOrder:c?void 0:Q?()=>re(Q).then(gn):()=>z("Failed to create PayPal order.").then(gn),createSubscription:c?Q?()=>re(Q).then(gn):()=>z("Failed to create PayPal subscription.").then(gn):void 0,onApprove:P,onCancel:()=>{if(Ve())return;let Ye=Ke.current.get(Ce)??nt.current;Ye&&Ke.current.delete(Ye.surfaceKey),nt.current=null,En(),U.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we.current=!0,Yt({generation:Ye?.generation,remount:!0,focus:!1})},onError:Ye=>{if(Ve()||Me.current!==Ce)return;let fe=Ye instanceof Error?Ye.message:"PayPal failed to render.";if(m(`onError rendered=${Kt} msg=${fe.slice(0,120)}`),Kt){let he=Ke.current.get(Ce)??nt.current;if(he&&!en(he.generation)||!he&&bt.current===Je.current)return;if(j(fe)){Bt(he?.generation);return}if(En(),kr(Ye)){U.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),pe(Ye,he),pt(()=>qe.current?.(wt("paypal",fe))),he&&Ke.current.delete(he.surfaceKey),nt.current=null,Bt(he?.generation);return}let Ge=fe.toLowerCase();U.error({errorCode:Ge.includes("popup")&&Ge.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),he&&Ke.current.delete(he.surfaceKey),nt.current=null,Yt({generation:he?.generation,remount:!0,showRetry:!0,focus:!0}),zn(Ye,{code:"paypal_runtime_failed"});return}ue(fe)}}),X=ge.isEligible();if(m(`isEligible=${X}`),U.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!X){ne(!1),ue("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}$t=ge,O&&m(`container:dims ${ct(Ft)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),O&&typeof MutationObserver<"u"&&(Jt=new MutationObserver(Ye=>{if(!Ve()){for(let fe of Ye)if(fe.type==="childList")fe.addedNodes.forEach(he=>{if(!(he instanceof Element))return;let Ge=he.tagName.toLowerCase(),nn=(he.getAttribute("title")??"").slice(0,40),rn=Ge==="iframe"?` ${$n(he)}`:"";m(`child+ ${Ge}${nn?` title="${nn}"`:""}${rn} dims=${ct(he)}`)});else if(fe.type==="attributes"&&fe.target instanceof Element){let he=fe.target;if(he.tagName.toLowerCase()!=="iframe")continue;let Ge=fe.attributeName;(Ge==="src"||Ge==="srcdoc")&&m(`attr~ iframe ${Ge}=${Ge==="srcdoc"?`[${(he.getAttribute("srcdoc")??"").length}ch]`:bn(he.getAttribute("src"))} dims=${ct(he)}`)}}}),Jt.observe(Ft,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ut=Ye=>{if(Ve()||Kt)return;let fe=Ft.querySelectorAll("iframe"),he=typeof document<"u"&&"hasStorageAccess"in document;m(`watchdog:${Ye} container=${ct(Ft)} children=${Ft.childElementCount} iframes=${fe.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${he} paypalNetRequests=${Ht.value}`),fe.forEach((Ge,nn)=>{let rn=(Ge.getAttribute("title")??"").slice(0,40);m(` iframe[${nn}] ${ct(Ge)}${rn?` title="${rn}"`:""} ${$n(Ge)}`);let K=Dt(Ge);K&&m(` ${K}`)}),Vt.length===0&&m(" (no PayPal/zoid window errors captured)")};O&&(yt.push(setTimeout(()=>ut("3s"),3e3)),yt.push(setTimeout(()=>ut("8s"),8e3)),yt.push(setTimeout(()=>ut("15s"),15e3))),m("render:start");let qt=U.startTiming();yt.push(setTimeout(()=>{Ve()||Kt||(m("watchdog:11s retryable render timeout"),ue("PayPal Buttons render did not settle within 11000ms.",!0))},Ki)),ge.render(Ft).then(()=>{if(m(`render:resolved inactive=${Ve()}`),_(),Ve()){Gt();return}Kt=!0,ne(!0),Re(!1),h.current?.("ready"),U.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),U.performance({stage:"checkout_render",durationMs:U.elapsed(qt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(Ye=>{let fe=Ye instanceof Error?Ye.message:"PayPal failed to render.";m(`render:rejected msg=${fe.slice(0,120)}`),_(),ue(fe)})}).catch(p=>{let P=p instanceof Error?p.message:"PayPal SDK failed to load.";m(`loadScript:rejected msg=${P.slice(0,120)}`),ue(P)})},0);return()=>{Te=!0,clearTimeout(dt),rt&&clearTimeout(rt),_(),Gt()}},[R,G,o,u,s,c,e,Q,de,U]);let Mt=O?(0,cn.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=${Se} failed=${ze})`,tt.length===0?`
6
+ `})]})})}var ka=require("@flopay/shared");function Ra(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 Io(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 Ia(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,p)=>s+(p.overrideAmount??p.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,p)=>({uuid:`synthetic-${s.type??"item"}-${p}`,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 Eo(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 ji=[{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 ji)if(n.test(t))return l;return e}function Hr(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Ea(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function _a(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Wr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Yr="flopay_recent_completion_";function sr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Yr+e,JSON.stringify(t))}catch{}}function _o(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Yr+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Yr+e),!1):!0}catch{return!1}}function xa(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"),Ba=require("@paypal/paypal-js"),Gr=require("@flopay/js"),Bn=require("@flopay/shared");function ct(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function Vi(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Gn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Mn(e){if(typeof e!="object"||e===null)return;let t=e;return Gn(t.code)??Gn(t.type)??Gn(t.name)}function lr(e){if(!(typeof e!="object"||e===null))return Gn(e.decline_code)}function Rr(e){return typeof e!="object"||e===null?!1:Gn(e.type)?.toLowerCase()==="card_error"||lr(e)!==void 0}function Ln(e){let t=Vi(e)?.toLowerCase()??"",l=`${Mn(e)?.toLowerCase()??""} ${t}`;return l.includes("popup")&&l.includes("block")}var cn=require("react/jsx-runtime"),Jr=45,Ki=1e3,Hi=11e3,Wi=["https://www.paypal.com","https://www.sandbox.paypal.com"],Ta="We couldn't open PayPal. Try again or choose another payment method.",Yi={width:"100%",minHeight:Jr,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 Ma(e){return e.includes("No ack for postMessage init()")&&Wi.some(t=>e.includes(t))&&e.includes("10000ms")}function Gi(e){return e?`${Ta} Allow pop-ups for this site, then try again.`:Ta}function Aa({sessionId:e,nonce:t,billingApiUrl:n,email:l,clientId:o,environment:s,currency:p,isSubscription:d,onTokenizedBody:k,onComplete:D,onErrorChange:f,onDecline:E,onTechnicalFailure:C,isProcessing:M=!1,onLoadStateChange:u,onInitializationStateChange:P,allowAutomaticRetry:_=!0,onButtonClick:F,runBeforeButtonClick:g,session:ce,existingOrderId:j,telemetry:pe,telemetryContext:te,debug:L=!1}){let Z=ln(),G=(0,T.useMemo)(()=>{if(Z)return null;let R=$r({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Bn.SDK_VERSION,enabled:pe!==!1});return R.setCheckoutContext(te??{}),R.beginCheckout(te??{}),R},[n,Z,pe,te?.checkoutMode,te?.layout]),me=(0,T.useMemo)(()=>_t(Z),[Z]);(0,T.useEffect)(()=>()=>{G&&G.flush().catch(()=>{}).finally(()=>G.destroy())},[G]);let V=(0,T.useMemo)(()=>({error:R=>{me?me.error(R):G?.error(R)},log:R=>{me?me.log(R):G?.log(R)},performance:R=>{me?me.performance(R):G?.performance(R)},terminal:R=>{me?me.terminal(R):G?.terminal(R)},startTiming:()=>me?.now()??G?.now()??0,elapsed:R=>me?.elapsed(R)??Math.max(0,(G?.now()??R)-R)}),[me,G]),H=(0,T.useRef)(null),he=(0,T.useRef)(0),Me=(0,T.useRef)(null),we=(0,T.useRef)(!1),[Ce,ne]=(0,T.useState)(!1),[Se,Be]=(0,T.useState)(!1),[re,xe]=(0,T.useState)(0),De=(0,T.useRef)(0),[Ee,X]=(0,T.useState)(!1),x=(0,T.useRef)(!1),ye=(0,T.useRef)(!1),[ze,Ue]=(0,T.useState)(!1),[Pe,I]=(0,T.useState)(!1),oe=(0,T.useMemo)(()=>n.replace(/\/+$/,""),[n]),ee=(0,T.useMemo)(()=>JSON.stringify([oe,o,p,s??"",d,e,j??""]),[oe,o,p,s,j,d,e]),Ne=(0,T.useRef)(ee),ut=Ne.current!==ee,[He,it]=(0,T.useState)([]),O=R=>{L&&it(Xe=>[...Xe,`${new Date().toISOString().slice(11,23)} ${R}`])},z=(0,T.useRef)(k),qe=(0,T.useRef)(D),Ke=(0,T.useRef)(f),st=(0,T.useRef)(E),pt=(0,T.useRef)(C),xt=(0,T.useRef)(F),Wt=(0,T.useRef)(u),y=(0,T.useRef)(P),ke=(0,T.useRef)(g),Ye=(0,T.useRef)(ce),rt=(0,T.useRef)(l),ft=(0,T.useRef)(t),Ge=(0,T.useRef)(null),et=(0,T.useRef)(0),Ae=(0,T.useRef)(null),Je=(0,T.useRef)(null),Tt=(0,T.useRef)(new Map),We=(0,T.useRef)(new Map),On=(0,T.useRef)(!1);(0,T.useEffect)(()=>(On.current=!0,()=>{On.current=!1}),[]),(0,T.useEffect)(()=>{z.current=k},[k]),(0,T.useEffect)(()=>{qe.current=D},[D]),(0,T.useEffect)(()=>{Ke.current=f},[f]),(0,T.useEffect)(()=>{st.current=E},[E]),(0,T.useEffect)(()=>{pt.current=C},[C]),(0,T.useEffect)(()=>{xt.current=F},[F]),(0,T.useEffect)(()=>{Wt.current=u},[u]),(0,T.useEffect)(()=>{y.current=P},[P]),(0,T.useEffect)(()=>{ke.current=g},[g]),(0,T.useEffect)(()=>{Ye.current=ce},[ce]),(0,T.useEffect)(()=>{rt.current=l},[l]),(0,T.useEffect)(()=>{ft.current=t},[t]),(0,T.useEffect)(()=>{De.current=re},[re]),(0,T.useEffect)(()=>{Ee&&Me.current?.focus()},[Ee,re]);let gt=(0,T.useCallback)(()=>{window.setTimeout(()=>{Me.current?.focus()},0)},[]),Cn=(0,T.useCallback)(()=>{ne(!1),xe(R=>R+1)},[]),Sn=(0,T.useCallback)(()=>{X(!1),(H.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??H.current)?.focus?.()},[]);(0,T.useEffect)(()=>{!Ce||!we.current||(we.current=!1,Sn())},[Sn,Ce,re]);let zn=(0,T.useCallback)((R,Xe)=>{let Ie=pt.current;if(Ie){Ie("paypal",R,Xe);return}Ke.current?.(Gi(Xe?.popupBlocked??Ln(R)))},[]),wt=()=>{Ae.current?.timer&&(clearTimeout(Ae.current.timer),Ae.current.timer=null)},Mt=()=>{wt();let R=et.current+1;return et.current=R,Je.current=null,Ae.current={generation:R,timer:null,yieldedControl:!1},X(!1),R},Yt=R=>R!==void 0&&Ae.current?.generation!==R?!1:(wt(),Ae.current=null,Je.current=null,!0),Dt=R=>{let Xe=R?.generation??Ae.current?.generation??et.current;(!R?.generation||Ae.current?.generation===Xe)&&(wt(),Ae.current=null),Je.current=Xe,R?.showRetry&&X(!0),R?.remount&&Cn(),R?.focus!==!1&&gt()},Gt=R=>Ae.current?.generation===R&&Je.current!==R,yn=R=>{typeof document<"u"&&document.visibilityState!=="visible"||(wt(),R.timer=setTimeout(()=>{Ae.current?.generation===R.generation&&(Ae.current=null,Je.current=R.generation,zn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),X(!0),Cn(),gt())},600))},ae=()=>{let R=Ae.current;R?.yieldedControl&&yn(R)},qt=()=>{let R=Ae.current;R&&(R.yieldedControl=!0,wt())},wn=R=>{let Xe=Ge.current;return Xe&&We.current.set(R,Xe),R};(0,T.useEffect)(()=>{let R=()=>{document.visibilityState==="visible"?ae():qt()};return document.addEventListener("visibilitychange",R),window.addEventListener("focus",ae),window.addEventListener("blur",qt),()=>{document.removeEventListener("visibilitychange",R),window.removeEventListener("focus",ae),window.removeEventListener("blur",qt),wt()}},[]),(0,T.useEffect)(()=>{Ne.current!==ee&&(Ne.current=ee,x.current=!1,ye.current=!1,ne(!1),Be(!1),Ue(!1),y.current?.("loading"))},[ee]),(0,T.useEffect)(()=>{ct(()=>Wt.current?.(Ce&&!ze))},[Ce,ze]);let kn=(0,Bn.normalizeGatewayEnvironment)(s);(0,T.useEffect)(()=>{let R=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",Xe=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(O(`mount clientId=${R} env=${s??"(unset)"}\u2192${kn??"live"} ccy=${p} sub=${d}`),O(`ua=${Xe.slice(0,80)}${Xe.length>80?"\u2026":""}`),!o){O("FAIL: clientId empty \u2014 gateway misconfigured"),Ue(!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(!H.current){O("FAIL: containerRef not attached");return}he.current=V.startTiming(),V.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ie=!1,Fn=!1,je=()=>Ie||Fn,Un,Qn=!1,jt=()=>{Un=(0,Bn.generateIdempotencyKey)(),Un||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Qn=!0},lt=null,Bt=!1,Vt=null,Pt=!1,en=()=>{!Vt||Pt||(Pt=!0,Vt.close().catch(()=>{}))},tn=null,fn=()=>{tn!==null&&(V.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),V.performance({stage:"overlay_return",durationMs:V.elapsed(tn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),tn=null)},nn=!1,kt=H.current,Lt=null,Te=null,ot=[],at=c=>{if(!c||typeof c.getBoundingClientRect!="function")return"(no rect)";let m=c.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},Rn=c=>{if(!c)return"(empty)";try{let m=new URL(c,typeof window<"u"?window.location.href:"https://localhost"),ue=m.pathname.toLowerCase();return ue.includes("checkcaptcha")||ue.includes("captcha")?`CAPTCHA(${m.host}${ue})`:ue.includes("risk")||ue.includes("challenge")?`RISK(${m.host}${ue})`:ue.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${ue}`.slice(0,100)}catch{return c.slice(0,80)}},$n=c=>{let m=c.getAttribute("src"),ue=c.getAttribute("srcdoc"),$e=c.getAttribute("name"),Y=c.getAttribute("sandbox"),N=[];return m&&N.push(`src=${Rn(m)}`),ue&&N.push(`srcdoc[${ue.length}ch]`),!m&&!ue&&N.push("src=(empty) srcdoc=(empty)"),$e&&N.push(`name=${$e.slice(0,40)}`),Y!==null&&N.push(`sandbox="${Y.slice(0,40)}"`),N.join(" ")},Kt=c=>{if(!(c instanceof HTMLIFrameElement))return"";try{let m=c.contentDocument;if(!m)return"cd=null";let ue=m.body?.children.length??0,$e=m.body?.innerHTML.length??0,Y=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${ue}children,${$e}ch] head[${Y}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},Nt=[],Ot=c=>{if(je())return;let m=c.message??String(c.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(O(`window:error ${m.slice(0,140)}`),Nt.push(m))},In=c=>{if(je())return;let m=c.reason instanceof Error?c.reason.message:String(c.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(O(`window:rejection ${m.slice(0,140)}`),Nt.push(m))};L&&typeof window<"u"&&(window.addEventListener("error",Ot),window.addEventListener("unhandledrejection",In));let qn={value:0};if(L&&typeof PerformanceObserver<"u")try{Te=new PerformanceObserver(c=>{if(!je())for(let m of c.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;qn.value+=1;let ue=Math.round(m.duration);O(`net ${ue}ms ${m.name.slice(0,90)}`)}}),Te.observe({type:"resource",buffered:!0})}catch{}let zt=()=>{for(Lt?.disconnect(),Lt=null,Te?.disconnect(),Te=null;ot.length;)clearTimeout(ot.pop());L&&typeof window<"u"&&(window.removeEventListener("error",Ot),window.removeEventListener("unhandledrejection",In))},En=c=>{if(!c)return!1;let m=c.toLowerCase();return m.includes("zoid destroyed")||m.includes("destroyed all components")||m.includes("window closed")||m.includes("detected container element removed")},ht=c=>{if(je()||En(c))return;let m=Dn(c)??c;ct(()=>Ke.current?.(m))},h=c=>{Ie||(Ue(!0),c.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:",c))},U=(c,m=!1)=>{if(Ie)return;let ue=x.current||!_;if(Bt)return;Bt=!0,Fn=!0,zt(),en();let $e=m||Ma(c);if($e&&_&&!x.current){x.current=!0,ne(!1),I(!1),Be(!0),y.current?.("retrying"),lt=setTimeout(()=>{Ie||xe(Y=>Y+1)},Ki);return}if($e||ue){if(ne(!1),I(!1),Be(!1),Ue(!0),y.current?.("exhausted"),!ye.current){ye.current=!0;let Y=Ma(c)?"paypal_init_timeout":m?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",Y)}return}h(c)};Ue(!1);let W=async(c,m=Ge.current)=>{if(je())return;let ue=m?.sessionId??e;if(z.current){await z.current(c,{sessionId:ue,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let $e=V.startTiming();V.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Y=()=>{V.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),V.performance({stage:"processing",durationMs:V.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let N=Ye.current,J=m?.accountPatch?.email??rt.current,bt=m?.accountPatch?.userId??N?.customer?.id??N?.accountData?.userId??"",de=await new Gr.PaymentAPI(oe,{telemetry:!1}).processPayment(bt,{sessionId:ue,nonce:m?.nonce??ft.current,tokenizedData:c,accountData:{userId:bt,email:J??N?.customer?.email??"",firstName:m?.accountPatch?.firstName??N?.customer?.firstName??N?.accountData?.firstName??"",lastName:m?.accountPatch?.lastName??N?.customer?.lastName??N?.accountData?.lastName??"",country:m?.accountPatch?.country??N?.customer?.country??N?.accountData?.country??void 0,zip:m?.accountPatch?.zip??N?.customer?.zip??N?.accountData?.zip??void 0}});if(de.ok){if(Fn||Ie&&On.current)return;Y(),V.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ct(()=>qe.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(je())return;let ge=await de.json().catch(()=>null),Ve=ge?.message??"PayPal payment failed.",Ht=Dn(Ve)??Ve;Y(),de.status===400&&(typeof ge?.declineCode=="string"||!Array.isArray(ge?.fields))?V.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):de.status===400||de.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:de.status>=500?"5xx":de.status>=400?"4xx":de.status>=300?"3xx":"unknown",failureCategory:de.status>=500?"server_error":void 0}),ht(Ht),ct(()=>st.current?.(St("paypal",Ht,{code:ge?.code,declineCode:ge?.declineCode})));return}catch(N){if(je())return;Y(),V.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let J=N instanceof Error?N.message:"PayPal payment failed.",bt=Dn(J)??J;ht(bt),ct(()=>st.current?.(St("paypal",bt)));return}},fe=()=>new Bn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),se=c=>je()?Promise.reject(fe()):Promise.resolve(c),Q=async c=>{if(je())throw fe();Qn||jt();let m=Ge.current,ue=m?.sessionId??e,$e=m?.nonce??ft.current;V.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Y=await new Gr.PaymentAPI(oe,{telemetry:!1}).createSessionIntent(ue,$e??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Un});if(je())throw fe();if(Y.provider!=="paypal")throw new Error(c);return V.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Y.providerObjectId},S=(c,m)=>{let ue=m?.nonce??ft.current;if(!ue)return;let $e=m?.sessionId??e,Y=lr(c)??Mn(c)??"provider_declined";new Gr.PaymentAPI(oe,{telemetry:!1}).reportSessionIntentDecline($e,ue,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Y}).catch(()=>{})},A=re;O("loadScript:scheduled (deferred 1 tick)");let $=null,ve=setTimeout(()=>{if(Ie){O("loadScript:skipped (cancelled before defer ran)");return}O("loadScript:start");let c=kn==="live"?"production":kn;$=(0,Ba.loadScript)({clientId:o,currency:p,intent:d?"subscription":"capture",vault:d?!0:void 0,...c?{environment:c}:{},...c==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),$.then(m=>{if(O(`loadScript:resolved inactive=${je()} ns=${!!m} buttons=${!!m?.Buttons}`),je())return;if(!m?.Buttons){O("FAIL: namespace missing Buttons factory"),U("PayPal SDK did not expose the Buttons factory.");return}V.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),V.performance({stage:"provider_ready",durationMs:V.elapsed(he.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),V.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let ue=async Re=>{if(je()||De.current!==A)return;let de=Re.subscriptionID??Re.orderID??"",ge=de?We.current.get(de):Tt.current.get(A);if(!(!ge||!Gt(ge.generation))&&Yt(ge.generation)){We.current.delete(de),Tt.current.delete(ge.surfaceKey),fn();try{if(I(!0),ct(()=>Ke.current?.(null)),!de)throw new Bn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await W({id:de,isPaypal:!0},ge)}catch(Ve){ht(Ve instanceof Error?Ve.message:"PayPal capture failed.")}finally{je()||I(!1)}}},$e=m.Buttons({style:{layout:"horizontal",height:Jr,tagline:!1},onClick:async(Re,de)=>{if(je()){await de.reject();return}jt();let ge=ke.current,Ve={};if(ge)try{let Ut=await ge("paypal");if(je()){await de.reject();return}if(!Ut.proceed){Ge.current=null,Tt.current.delete(A),await de.reject();return}Ve={sessionId:Ut.sessionId,accountPatch:Ut.accountPatch,nonce:Ut.nonce}}catch(Ut){O(`onClick:runBeforeButtonClick rejected msg=${(Ut instanceof Error?Ut.message:String(Ut)).slice(0,120)}`),Ge.current=null,Tt.current.delete(A),await de.reject();return}ct(()=>xt.current?.("paypal"));let rn={generation:Mt(),surfaceKey:A,...Ve};Ge.current=rn,Tt.current.set(A,rn),await de.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"}),tn=V.startTiming()},createOrder:d?void 0:j?()=>se(j).then(wn):()=>Q("Failed to create PayPal order.").then(wn),createSubscription:d?j?()=>se(j).then(wn):()=>Q("Failed to create PayPal subscription.").then(wn):void 0,onApprove:ue,onCancel:()=>{if(je())return;let Re=Tt.current.get(A)??Ge.current;Re&&Tt.current.delete(Re.surfaceKey),Ge.current=null,fn(),V.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we.current=!0,Dt({generation:Re?.generation,remount:!0,focus:!1})},onError:Re=>{if(je()||De.current!==A)return;let de=Re instanceof Error?Re.message:"PayPal failed to render.";if(O(`onError rendered=${nn} msg=${de.slice(0,120)}`),nn){let ge=Tt.current.get(A)??Ge.current;if(ge&&!Gt(ge.generation)||!ge&&Je.current===et.current)return;if(En(de)){Yt(ge?.generation);return}if(fn(),Rr(Re)){V.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),S(Re,ge),ct(()=>st.current?.(St("paypal",de))),ge&&Tt.current.delete(ge.surfaceKey),Ge.current=null,Yt(ge?.generation);return}let Ve=de.toLowerCase();V.error({errorCode:Ve.includes("popup")&&Ve.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ge&&Tt.current.delete(ge.surfaceKey),Ge.current=null,Dt({generation:ge?.generation,remount:!0,showRetry:!0,focus:!0}),zn(Re,{code:"paypal_runtime_failed"});return}U(de)}}),Y=$e.isEligible();if(O(`isEligible=${Y}`),V.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Y){ne(!1),U("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Vt=$e,L&&O(`container:dims ${at(kt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),L&&typeof MutationObserver<"u"&&(Lt=new MutationObserver(Re=>{if(!je()){for(let de of Re)if(de.type==="childList")de.addedNodes.forEach(ge=>{if(!(ge instanceof Element))return;let Ve=ge.tagName.toLowerCase(),Ht=(ge.getAttribute("title")??"").slice(0,40),rn=Ve==="iframe"?` ${$n(ge)}`:"";O(`child+ ${Ve}${Ht?` title="${Ht}"`:""}${rn} dims=${at(ge)}`)});else if(de.type==="attributes"&&de.target instanceof Element){let ge=de.target;if(ge.tagName.toLowerCase()!=="iframe")continue;let Ve=de.attributeName;(Ve==="src"||Ve==="srcdoc")&&O(`attr~ iframe ${Ve}=${Ve==="srcdoc"?`[${(ge.getAttribute("srcdoc")??"").length}ch]`:Rn(ge.getAttribute("src"))} dims=${at(ge)}`)}}}),Lt.observe(kt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let J=Re=>{if(je()||nn)return;let de=kt.querySelectorAll("iframe"),ge=typeof document<"u"&&"hasStorageAccess"in document;O(`watchdog:${Re} container=${at(kt)} children=${kt.childElementCount} iframes=${de.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${ge} paypalNetRequests=${qn.value}`),de.forEach((Ve,Ht)=>{let rn=(Ve.getAttribute("title")??"").slice(0,40);O(` iframe[${Ht}] ${at(Ve)}${rn?` title="${rn}"`:""} ${$n(Ve)}`);let Ut=Kt(Ve);Ut&&O(` ${Ut}`)}),Nt.length===0&&O(" (no PayPal/zoid window errors captured)")};L&&(ot.push(setTimeout(()=>J("3s"),3e3)),ot.push(setTimeout(()=>J("8s"),8e3)),ot.push(setTimeout(()=>J("15s"),15e3))),O("render:start");let bt=V.startTiming();ot.push(setTimeout(()=>{je()||nn||(O("watchdog:11s retryable render timeout"),U("PayPal Buttons render did not settle within 11000ms.",!0))},Hi)),$e.render(kt).then(()=>{if(O(`render:resolved inactive=${je()}`),zt(),je()){en();return}nn=!0,ne(!0),Be(!1),y.current?.("ready"),V.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),V.performance({stage:"checkout_render",durationMs:V.elapsed(bt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(Re=>{let de=Re instanceof Error?Re.message:"PayPal failed to render.";O(`render:rejected msg=${de.slice(0,120)}`),zt(),U(de)})}).catch(m=>{let ue=m instanceof Error?m.message:"PayPal SDK failed to load.";O(`loadScript:rejected msg=${ue.slice(0,120)}`),U(ue)})},0);return()=>{Ie=!0,clearTimeout(ve),lt&&clearTimeout(lt),zt(),en()}},[_,oe,o,p,s,d,e,j,re,V]);let Jt=L?(0,cn.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=${Ce} failed=${ze})`,He.length===0?`
7
7
  (waiting for first lifecycle event\u2026)`:`
8
- ${tt.join(`
9
- `)}`]}):null;return ze&&!st?O?(0,cn.jsx)("div",{children:Mt}):null:(0,cn.jsxs)("div",{children:[Mt,(0,cn.jsxs)("div",{"aria-hidden":ve?!0:void 0,style:ve?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Gr},children:[!Se&&!ve&&(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:Y,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:Gr,display:"flex",opacity:Se?1:0},"aria-busy":ee||M},de)]},de),Ee&&(0,cn.jsx)("button",{ref:De,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:In,style:Hi,children:"Try PayPal again"})]})}function Rr(e){return(0,cn.jsx)(Ma,{...e})}function Ba(e){return(0,cn.jsx)(Ma,{...e})}var Lt=require("@flopay/shared"),i=require("react/jsx-runtime"),wn="flopay_stripe_resume",Aa="flopay_wallet_resume",Ir="flopay_paypal_resume";function Bo(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 Yi(e){return e instanceof Lt.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function xo(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 Gi=`
8
+ ${He.join(`
9
+ `)}`]}):null;return ze&&!ut?L?(0,cn.jsx)("div",{children:Jt}):null:(0,cn.jsxs)("div",{children:[Jt,(0,cn.jsxs)("div",{"aria-hidden":Se?!0:void 0,style:Se?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Jr},children:[!Ce&&!Se&&(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:H,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:Jr,display:"flex",opacity:Ce?1:0},"aria-busy":Pe||M},re)]},re),Ee&&(0,cn.jsx)("button",{ref:Me,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Sn,style:Yi,children:"Try PayPal again"})]})}function Ir(e){return(0,cn.jsx)(Aa,{...e})}function Fa(e){return(0,cn.jsx)(Aa,{...e})}var At=require("@flopay/shared"),i=require("react/jsx-runtime"),bn="flopay_stripe_resume",Da="flopay_wallet_resume",Er="flopay_paypal_resume",Ji=250;function Ao(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Qr({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 Xi(e){return e instanceof At.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function To(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Xr(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),p=Math.round((l>>8&255)*o),d=Math.round((l&255)*o);return`#${(1<<24|s<<16|p<<8|d).toString(16).slice(1)}`}var Zi=`
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 @@ ${tt.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
- `,Xr=44;function Ao(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 Ji={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},$a={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 Xi(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Fa(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function qa(e){return e==="paypal"?"PayPal":(0,w.getStripeMethodDisplayName)(e)}function Zi(e,t){let n=`We couldn't open ${qa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function ja(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 f=d;f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),s=(0,r.useCallback)((d,f)=>{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"}))},f))},[o,e]),u=(0,r.useCallback)(d=>{d.yieldedControl&&s(d,600)},[s]),c=(0,r.useCallback)(d=>{o();let f=t.current+1;t.current=f,n.current=null;let R={generation:f,method:d,timer:null,yieldedControl:!1};return l.current=R,f},[o]),k=(0,r.useCallback)(d=>{let f=l.current;return typeof d=="number"&&f?.generation!==d?!1:(o(f),l.current=null,(typeof d!="number"||n.current===d)&&(n.current=null),!0)},[o]),N=(0,r.useCallback)(d=>{let f=l.current,R=d??f?.generation??t.current;(!d||f?.generation===d)&&(o(f),l.current=null),n.current=R},[o]),y=(0,r.useCallback)(d=>n.current===(d??t.current),[]),E=(0,r.useCallback)(d=>l.current?.generation===d&&n.current!==d,[]),S=(0,r.useCallback)(()=>{let d=l.current;d&&u(d)},[u]),M=(0,r.useCallback)(()=>{let d=l.current;d&&(d.yieldedControl=!0,o(d))},[o]);return(0,r.useEffect)(()=>{let d=()=>{document.visibilityState==="visible"?S():M()},f=()=>{M()};return document.addEventListener("visibilitychange",d),window.addEventListener("blur",f),window.addEventListener("focus",S),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("blur",f),window.removeEventListener("focus",S),o()}},[o,M,S]),{startAttempt:c,finishAttempt:k,invalidateAttempt:N,isAttemptInvalidated:y,isAttemptCurrent:E}}function Qi(e){let t=(0,w.getPostalCodeExample)(e);return`Enter a valid ${(0,w.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function es(e,t,n){let l=(0,w.isPostalCodeSupported)(e),o=t.trim(),s=n&&l,u=s&&!o,c=s&&!!o&&!(0,w.isValidPostalCode)(e,o);return{visible:n,supported:l,required:s,empty:u,malformed:c}}function Da(e,t){return t instanceof Lt.FloPayError?t:new Lt.FloPayError(t instanceof Error?t.message:`${Xi(e)} before-click hook failed.`,"validation_error")}function To(){return(0,i.jsx)("style",{children:Gi})}function ts(e){return typeof e=="number"?`${e}px`:e}function La(e){if(typeof e=="number"||typeof e=="string")return e}function Ka(e,t){let n=e.availablePaymentMethods;return n&&t.some(l=>n[l])?"ready":"unavailable"}function Va({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 Na(e){return e!=="unavailable"&&e!=="load_error"}function Qr(e){return(0,i.jsx)(rs,{...e})}function Oa({sessionId:e,nonce:t,email:n,billingApiUrl:l,onTokenizedBody:o,onErrorChange:s,isProcessing:u=!1,onButtonClick:c,onDecline:k,onTechnicalFailure:N,runBeforeButtonClick:y,onLoadStateChange:E,placeholderBorderRadius:S}){let M=ln(),d=(0,mt.useStripe)(),f=(0,mt.useElements)(),[R,F]=(0,r.useState)("loading");(0,r.useEffect)(()=>{E?.(R)},[R,E]);let[g,H]=(0,r.useState)(!1),Q=(0,r.useRef)(!1),Pe=(0,r.useRef)(null),ae=(0,r.useRef)(null),[O,te]=(0,r.useState)(0),[W,be]=(0,r.useState)(!1),U=(0,r.useRef)(!1),Y=(0,r.useRef)(new Map),{startAttempt:ce,finishAttempt:De,invalidateAttempt:we,isAttemptInvalidated:Se,isAttemptCurrent:ne}=ja((I,se,me)=>{N?.(I,se,{...me,popupBlocked:me?.popupBlocked??Nn(se)}),be(!0),te(ze=>ze+1)});(0,r.useEffect)(()=>{W&&ae.current?.focus()},[W,O]);let ve=(0,r.useCallback)(()=>{te(I=>I+1)},[]),Re=(0,r.useCallback)((I,se,me)=>{we(me),N?.("paypal",I,{code:se,popupBlocked:Nn(I)}),be(!0),ve()},[we,N,ve]),de=(0,r.useCallback)(()=>{window.setTimeout(()=>{(Pe.current?.querySelector("iframe")??Pe.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{U.current&&(U.current=!1,de())},[de,O]);let Ne=(0,r.useCallback)(()=>{be(!1),s?.(null),de()},[de,s]);(0,r.useEffect)(()=>{if(!d||Q.current)return;let I=new URLSearchParams(window.location.search),se=I.get("payment_intent"),me=I.get("payment_intent_client_secret"),ze=I.get("redirect_status");if(!se||!me)return;Q.current=!0;let Oe;try{let A=localStorage.getItem(Ir);if(A){let G=JSON.parse(A);G.clientSecret===me&&(Oe={...G.accountPatch?{accountPatch:G.accountPatch}:{},...G.sessionId?{sessionId:G.sessionId}:{},...G.nonce?{nonce:G.nonce}:{}})}}catch{}try{localStorage.removeItem(Ir)}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(H(!0),ze==="failed"){let ye="PayPal payment was declined. Please try again.";s?.(ye),k?.(wt("paypal",ye));return}let{paymentIntent:A,error:G}=await d.retrievePaymentIntent(me);if(G){s?.(G.message??"Failed to retrieve PayPal payment status.");return}if(A&&(A.status==="requires_capture"||A.status==="succeeded")){let ye=typeof A.payment_method=="string"?A.payment_method:A.payment_method?.id;o({id:ye??A.id,type:"card",threeDSecureActionResultTokenId:A.id,isPaypal:!0},Oe)}else{let ye="PayPal payment was not completed. Please try again.";s?.(ye),k?.(wt("paypal",ye))}}catch(A){s?.(A instanceof Error?A.message:"Failed to complete PayPal payment.")}finally{H(!1)}})()},[d,o,s,k]);let Me=(0,r.useCallback)(async I=>{if(u||g){I.reject();return}let se=y?await y("paypal"):{proceed:!0};if(!se.proceed){Y.current.delete(O),I.reject();return}let me=ce("paypal");Y.current.set(O,{generation:me,accountPatch:se.accountPatch,sessionId:se.sessionId,nonce:se.nonce}),be(!1),c?.("paypal"),I.resolve()},[Y,u,c,y,ce,g,O]),Ee=(0,r.useCallback)(async I=>{if(!d||!f)return;let se=Y.current.get(O);if(se&&!ne(se.generation)){Y.current.delete(O);return}if(!se&&Se()||se&&!De(se.generation))return;se||De();let me=se??null;if(Y.current.delete(O),!me&&y){let A=await y("paypal");if(!A.proceed){I.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}me={accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}}let ze=me?.sessionId??e,Oe=me?.nonce??t,ee=me?.accountPatch?.email??n;try{if(H(!0),s?.(null),!ze||!ee)throw new Error("Missing sessionId or email for PayPal payment");let A=d.createPaymentMethod,{error:G,paymentMethod:ye}=await A({type:"paypal"});if(G){Re(G,"stripe_paypal_create_payment_method_failed",se?.generation),I.paymentFailed({reason:"fail"});return}let Be=await new dn.PaymentAPI(l).createSessionIntent(ze,Oe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ye?.id??null,intentKind:"payment"});if(Be.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let st=Be.clientSecret,tt={return_url:window.location.href};if(ye?.id&&(tt.payment_method=ye.id),typeof window<"u")try{localStorage.setItem(Ir,JSON.stringify({clientSecret:st,sessionId:ze,nonce:Oe,accountPatch:me?.accountPatch}))}catch{}let{error:et,paymentIntent:m}=await d.confirmPayment({clientSecret:st,confirmParams:tt,redirect:"if_required"});if(et){if(typeof window<"u")try{localStorage.removeItem(Ir)}catch{}if(kr(et)){let Ue=et.message??"Your payment was declined.";s?.(Ue),k?.(wt("paypal",Ue,{code:Mn(et),declineCode:sr(et)})),await Zr({billingApiUrl:l,sessionId:ze,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(et)??"provider_declined"}})}else Re(et,"stripe_paypal_confirm_failed",se?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Ir)}catch{}let $e=typeof m?.payment_method=="string"?m.payment_method:m?.payment_method?.id;o({id:$e??m?.id,type:"card",threeDSecureActionResultTokenId:m?.id,isPaypal:!0},{accountPatch:me?.accountPatch,sessionId:ze,nonce:Oe});return}catch(A){Re(A,"stripe_paypal_failed",se?.generation)}finally{H(!1)}},[d,f,e,t,n,l,o,s,k,y,Re,De,ne,Se,O]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Va,{state:R,placeholderTestId:"flopay-paypal-placeholder",borderRadius:S,children:(0,i.jsxs)("div",{ref:Pe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[W&&(0,i.jsx)("button",{ref:ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ne,style:$a,children:"Try PayPal again"}),(0,i.jsx)(mt.ExpressCheckoutElement,{onReady:I=>F(Ka(I,["paypal"])),onLoadError:()=>{F("load_error"),Bo(Tt(M),"paypal","paypal")},onClick:Me,onConfirm:Ee,onCancel:()=>{let I=Y.current.get(O);Y.current.delete(O),Tt(M)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we(I?.generation),be(!1),U.current=!0,ve()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},O)]})}),g&&(0,i.jsx)(Sn,{status:"processing"})]})}function za({sessionId:e,nonce:t,email:n,billingApiUrl:l,intentKind:o,expressMethods:s,onTokenizedBody:u,onErrorChange:c,onButtonClick:k,onDecline:N,onTechnicalFailure:y,runBeforeButtonClick:E,onLoadStateChange:S,placeholderBorderRadius:M}){let d=ln(),f=(0,mt.useStripe)(),R=(0,mt.useElements)(),[F,g]=(0,r.useState)("loading");(0,r.useEffect)(()=>{S?.(F)},[F,S]);let[H,Q]=(0,r.useState)(!1),Pe=(0,r.useRef)(null),ae=(0,r.useRef)(null),[O,te]=(0,r.useState)(0),[W,be]=(0,r.useState)(!1),[U,Y]=(0,r.useState)("google_pay"),ce=(0,r.useRef)(!1),De=(0,r.useRef)("google_pay"),we=(0,r.useRef)("google_pay"),Se=(0,r.useRef)(new Map),{startAttempt:ne,finishAttempt:ve,invalidateAttempt:Re,isAttemptInvalidated:de,isAttemptCurrent:Ne}=ja((ee,A,G)=>{y?.(ee,A,{...G,popupBlocked:G?.popupBlocked??Nn(A)}),Y(ee),be(!0),te(ye=>ye+1)});(0,r.useEffect)(()=>{W&&ae.current?.focus()},[W,O]);let Me=(0,r.useCallback)(()=>{te(ee=>ee+1)},[]),Ee=(0,r.useCallback)((ee,A,G,ye)=>{Re(ye),y?.(ee,A,{code:G,popupBlocked:Nn(A)}),Y(ee),be(!0),Me()},[Re,y,Me]),I=(0,r.useCallback)(()=>{window.setTimeout(()=>{(Pe.current?.querySelector("iframe")??Pe.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{ce.current&&(ce.current=!1,I())},[I,O]);let se=(0,r.useCallback)(()=>{be(!1),c?.(null),I()},[I,c]),me=(0,r.useCallback)(async ee=>{if(!f||!R)return;let A=Se.current.get(O);if(A&&!Ne(A.generation)){Se.current.delete(O);return}if(!A&&de()||A&&!ve(A.generation))return;A||ve();let G=ee.expressPaymentType??A?.method??De.current,ye=A??null;Se.current.delete(O);let Be=Fa(G);if(!ye&&E){let $e=await E(Be);if(!$e.proceed){ee.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}ye={accountPatch:$e.accountPatch,sessionId:$e.sessionId,nonce:$e.nonce}}let st=Be,tt=ye?.sessionId??e,et=ye?.nonce??t,m=ye?.accountPatch?.email??n;try{Q(!0),c?.(null);let{error:$e}=await R.submit();if($e){Ee(G,$e,"stripe_wallet_submit_failed",A?.generation);return}let{error:Ue,paymentMethod:We}=await f.createPaymentMethod({elements:R});if(Ue||!We){Ee(G,Ue??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",A?.generation);return}if(!tt||!m)throw new Error("Missing sessionId or email for wallet payment");let qe=await new dn.PaymentAPI(l).createSessionIntent(tt,et??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:G??Be,paymentMethodId:We.id,intentKind:o});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Wt=qe.clientSecret,{error:Pt,intentId:kt}=(0,Lt.isSetupIntentClientSecret)(Wt)?await f.confirmCardSetup(Wt,{payment_method:We.id}).then(h=>({error:h.error,intentId:h.setupIntent?.id})):await f.confirmCardPayment(Wt,{payment_method:We.id}).then(h=>({error:h.error,intentId:h.paymentIntent?.id}));if(Pt){if(kr(Pt)){let h=Pt.message??"Your payment was declined.";c?.(h),N?.(wt(st,h,{code:Mn(Pt),declineCode:sr(Pt)})),await Zr({billingApiUrl:l,sessionId:tt,nonce:et,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:G??Be,providerDeclineReason:Mn(Pt)??"provider_declined"}})}else Ee(G,Pt,"stripe_wallet_confirm_failed",A?.generation);return}u({id:We.id,type:"card",threeDSecureActionResultTokenId:kt},{accountPatch:ye?.accountPatch,sessionId:tt,nonce:et})}catch($e){Ee(G,$e,"stripe_wallet_failed",A?.generation)}finally{Q(!1)}},[f,R,e,t,n,l,o,u,c,N,E,Ee,ve,Ne,de,O]),ze=(0,r.useMemo)(()=>{let ee=["applePay","googlePay","paypal","link","amazonPay","klarna"],A=new Set(["applePay","googlePay"]),G=new Set(s.map(w.stripeExpressMethodToOptionKey)),ye={};for(let Be of ee)G.has(Be)?ye[Be]=A.has(Be)?"always":"auto":ye[Be]="never";return ye},[s]),Oe=(0,r.useMemo)(()=>s.map(w.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Va,{state:F,placeholderTestId:"flopay-wallet-placeholder",borderRadius:M,children:(0,i.jsxs)("div",{ref:Pe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[W&&(0,i.jsxs)("button",{ref:ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:se,style:$a,children:["Try ",qa(U)," again"]}),(0,i.jsx)(mt.ExpressCheckoutElement,{onReady:ee=>{g(Ka(ee,Oe))},onLoadError:ee=>{g("load_error"),Bo(Tt(d),"stripe","wallet")},onClick:async ee=>{De.current=ee.expressPaymentType,we.current=Fa(ee.expressPaymentType);let A=E?await E(we.current):{proceed:!0};if(!A.proceed){Se.current.delete(O),ee.reject();return}let G=ne(ee.expressPaymentType);Se.current.set(O,{generation:G,method:ee.expressPaymentType,accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}),be(!1),k?.(we.current),ee.resolve()},onConfirm:me,onCancel:()=>{let ee=Se.current.get(O);Se.current.delete(O),Tt(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Re(ee?.generation),be(!1),ce.current=!0,Me()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ze,layout:{maxColumns:1,overflow:"never"}}},O)]})}),H&&(0,i.jsx)(Sn,{status:"processing"})]})}function ns({method:e,themeId:t,submitting:n=!1,disabled:l=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:u,backgroundColor:c,borderColor:k,textColor:N,borderRadius:y,fontFamily:E}){let S=(0,w.resolveStripeMethodBrandVariant)(e,t),M=ba[e],d=S?.backgroundColor??c??"#ffffff",f=S?.borderColor??k??"#d1d5db",R=S?.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:Xr,padding:"0 1rem",backgroundColor:d,color:R,border:`1px solid ${f}`,borderRadius:y??8,fontSize:"0.95rem",fontWeight:600,fontFamily:E,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,w.getStripeMethodDisplayName)(e)}\u2026`}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,w.hasVendoredStripeMethodLogo)(e)?8:0},children:[M?(0,i.jsx)("img",{src:M,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,w.getStripeMethodDisplayName)(e)})]}),s&&(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:R,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 Mo({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:u,onErrorChange:c,onDecline:k,onCancel:N,runBeforeButtonClick:y,onButtonClick:E,isProcessing:S,submitButtonColor:M,submitButtonBorderRadius:d,submitButtonStyle:f,errorText:R}){let F=ln(),g=(0,mt.useStripe)(),H=(0,mt.useElements)(),[Q,Pe]=(0,r.useState)(!1),ae=(0,r.useRef)(!1),[O,te]=(0,r.useState)(!1),[W,be]=(0,r.useState)("loading"),U=(0,r.useCallback)(async()=>{if(!g||!H||S||ae.current||!O)return;ae.current=!0,Pe(!0);let Y=y?await y("card"):{proceed:!0};if(!Y.proceed){ae.current=!1,Pe(!1);return}E?.("card");let ce=Y.sessionId??t,De=Y.nonce??n,we=Y.accountPatch?.email??l;try{c?.(null);let Se=await H.submit();if(Se.error){c?.(Se.error.message??"Payment failed.");return}let ne=await g.createPaymentMethod({elements:H});if(ne.error||!ne.paymentMethod){c?.(ne.error?.message??"Failed to create payment method.");return}let ve=ne.paymentMethod;if(!ce||!we)throw new Error("Missing sessionId or email for payment.");let Re=ve.type||e,de=await new dn.PaymentAPI(s).createSessionIntent(ce,De??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Re,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(wn,JSON.stringify({clientSecret:Ne,sessionId:ce,nonce:De,accountPatch:Y.accountPatch,paymentMethodId:ve.id,paymentMethodType:ve.type??e,gateway:"stripe"}))}catch{}let{error:Me,paymentIntent:Ee}=await g.confirmPayment({clientSecret:Ne,confirmParams:{return_url:window.location.href,payment_method:ve.id},redirect:"if_required"});if(Me){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let me=Me.message??"Payment failed.";c?.(me),k?.(wt("card",me,{code:Me.code})),await Zr({billingApiUrl:s,sessionId:ce,nonce:De,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Me.code??"provider_declined"}});return}let I=Ee?.status;if(!Vr(I)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let me=I==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";c?.(me),k?.(wt("card",me,{code:I??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let se=typeof Ee?.payment_method=="string"?Ee.payment_method:Ee?.payment_method?.id;u({id:se??ve.id,type:"card",threeDSecureActionResultTokenId:Ee?.id,gateway:"stripe",paymentMethodType:ve.type??e},{accountPatch:Y.accountPatch,sessionId:ce,nonce:De})}catch(Se){c?.(Se instanceof Error?Se.message:"Payment failed. Please try again.")}finally{ae.current=!1,Pe(!1)}},[g,H,S,O,y,E,t,n,l,s,e,u,c,k]);return(0,i.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,i.jsx)(mt.PaymentElement,{onReady:()=>be("ready"),onLoadError:()=>{be("load_error"),Bo(Tt(F),"stripe","apm")},onChange:Y=>{te(!!Y.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:()=>{U()},disabled:!O||Q||S||W!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:M,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!O||Q||S||W!=="ready"?"not-allowed":"pointer",opacity:!O||Q||S||W!=="ready"?.5:1,transition:"opacity 120ms ease-out",...f??{}},children:Q?"Processing\u2026":`Pay with ${(0,w.getStripeMethodDisplayName)(e)}`}),R&&(0,i.jsx)(or,{margin:"0.75rem 0 0",children:R})]})}function Ua({sessionId:e,nonce:t,email:n,billingName:l,billingApiUrl:o,paymentElementMethods:s,stripeInstance:u,paymentElementBaseOptions:c,onTokenizedBody:k,onErrorChange:N,onButtonClick:y,onDecline:E,runBeforeButtonClick:S,onLoadStateChange:M,isProcessing:d=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:R=8,submitButtonStyle:F,buttonAppearance:g,themeId:H,onExpandApm:Q,expandedApmMethod:Pe}){let[ae,O]=(0,r.useState)(null),[te,W]=(0,r.useState)(null),be=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&u?M?.("ready"):u||M?.("loading")},[s.length,u,M]);let U=(0,r.useCallback)(async ne=>{if(!u||be.current||d)return;be.current=!0,W(ne);let ve=S?await S("card"):{proceed:!0};if(!ve.proceed){be.current=!1,W(null);return}y?.("card");let Re=ve.sessionId??e,de=ve.nonce??t,Ne=ve.accountPatch?.email??n;try{if(N?.(null),!Re||!Ne)throw new Error("Missing sessionId or email for payment.");let Me=await new dn.PaymentAPI(o).createSessionIntent(Re,de??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,paymentMethodId:null,intentKind:"payment"});if(Me.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ee=Me.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Ee,sessionId:Re,nonce:de,accountPatch:ve.accountPatch,paymentMethodType:ne,gateway:"stripe"}))}catch{}let{error:I,paymentIntent:se}=await u.confirmPayment({clientSecret:Ee,confirmParams:{return_url:window.location.href,payment_method_data:{type:ne,billing_details:{name:l&&l.trim().length>=3?l.trim():"FloPay Customer",...Ne?{email:Ne}:{}}}},redirect:"if_required"});if(I){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let Oe=I.message??"Payment failed.";N?.(Oe),E?.(wt("card",Oe,{code:I.code})),await Zr({billingApiUrl:o,sessionId:Re,nonce:de,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,providerDeclineReason:I.code??"provider_declined"}});return}let me=se?.status;if(!Vr(me)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let Oe=me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";N?.(Oe),E?.(wt("card",Oe,{code:me??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=typeof se?.payment_method=="string"?se.payment_method:se?.payment_method?.id;k({id:ze??se?.id,type:"card",threeDSecureActionResultTokenId:se?.id,gateway:"stripe",paymentMethodType:ne},{accountPatch:ve.accountPatch,sessionId:Re,nonce:de})}catch(Me){N?.(Me instanceof Error?Me.message:"Payment failed. Please try again.")}finally{be.current=!1,W(null)}},[u,d,S,y,e,t,n,o,l,k,N,E]),[Y,ce]=(0,r.useState)(null),De=Q?Pe??null:Y,we=(0,r.useCallback)(ne=>{be.current||d||De&&De!==ne||((0,w.needsStripeMethodExplicitConfirm)(ne)?Q?Q(ne):ce(ne):U(ne))},[De,d,U,Q]),Se=(0,r.useMemo)(()=>Y?{...c,paymentMethodTypes:[Y]}:null,[Y,c]);return(0,i.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(ne=>{let ve=Pe===ne,Re=te===ne,de=te!==null&&te!==ne||Pe!=null&&Pe!==ne;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(ns,{method:ne,themeId:H,submitting:Re,disabled:de,highlighted:ve,hasNextStep:(0,w.needsStripeMethodExplicitConfirm)(ne),onClick:()=>we(ne),backgroundColor:g?.backgroundColor,borderColor:g?.borderColor,textColor:g?.textColor,borderRadius:g?.borderRadius,fontFamily:g?.fontFamily}),!Q&&Y===ne&&Se&&u&&(0,i.jsx)(mt.Elements,{stripe:u,options:Se,children:(0,i.jsx)(Mo,{method:ne,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:k,onErrorChange:N,onDecline:E,onCancel:()=>ce(null),runBeforeButtonClick:S,onButtonClick:y,isProcessing:d,submitButtonColor:f,submitButtonBorderRadius:R,submitButtonStyle:F})},ne)]},ne)})})}function rs({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:u,onDecline:c,onTokenizedBody:k,firstName:N,lastName:y,chv:E,className:S,isProcessing:M,error:d,onErrorChange:f,showPayPal:R=!0,showStripe:F=!0,enabledPaymentMethods:g,enabledPaymentMethodCountries:H,showApplePay:Q=!0,showGooglePay:Pe=!0,layout:ae="default",theme:O,buttonsTheme:te,buttonsStyles:W,appearance:be,cardButtonContent:U,cardBackButtonContent:Y,cardTitleContent:ce,showSecurityFooter:De,onButtonClick:we,onBeforeButtonClick:Se,enableAVS:ne,cardFieldOrder:ve,cardPreFormSlot:Re,avsLayout:de="row",country:Ne,zip:Me,addressLine1:Ee,addressLine2:I,city:se,state:me,onCountryChange:ze,onZipChange:Oe,avsCheck:ee,checkoutType:A,checkoutLayout:G,totalAmount:ye=0,currency:Be="usd",initialCardOpen:st=!1,directPaypal:tt,isSubscription:et=!1,session:m,debug:$e=!1}){let Ue=ln(),We=qr(),qe=(0,r.useContext)(sn),Wt=Kr(),[Pt,kt]=(0,r.useState)(!1),[h,_e]=(0,r.useState)(null),[je,lt]=(0,r.useState)(Ne??"US"),[it,nt]=(0,r.useState)(Me??""),[Je,Ie]=(0,r.useState)(Ee??""),[bt,Ke]=(0,r.useState)(I??""),[Ot,Rt]=(0,r.useState)(se??""),[yn,Rn]=(0,r.useState)(me??""),[In,zn]=(0,r.useState)({}),ht=(0,r.useRef)(Me??""),zt=(0,r.useRef)(Ne??"US"),Bt=(0,r.useRef)(Ee??""),Yt=(0,r.useRef)(I??""),en=(0,r.useRef)(se??""),fn=(0,r.useRef)(me??""),J=(0,r.useMemo)(()=>(0,w.resolveAVSConfig)(ne),[ne]),Fn=J!==null,gn=!!m?.vault?.html,Ut=!!m?.gateways?.pcivault,B=!!(m?.gateways?.stripe?.enabledPaymentMethods??g)?.includes("card"),Xe=gn||B||Ut,Te=!!(F&&Xe&&Ue&&e),[Dn,Ve]=(0,r.useState)(()=>ae!=="buttons"||st?e??null:null),[Un,hn]=(0,r.useState)(0),Pn=ae!=="buttons"||st||!!e&&Dn===e,rt=(0,r.useMemo)(()=>!Ue||!Te||!e||!Pn?null:Ue.cardCapture({sessionId:e}),[Ue,Te,e,Pn]),It=(0,r.useMemo)(()=>{let a=je,v=J?(0,w.isAVSFieldVisible)(J.postal_code,a):!1;return es(a,it,v)},[J,je,it]),{avsInvalid:$t,invalidAvsFields:At}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!Te||!J)return{avsInvalid:!1,invalidAvsFields:a};let v=je,V=(ie,Ze)=>(0,w.isAVSFieldVisible)(ie,v)&&!Ze.trim(),le={line1:V(J.address_line_1,Je),city:V(J.city,Ot),state:V(J.state,yn),zip:It.empty||It.malformed};return{avsInvalid:le.line1||le.city||le.state||le.zip,invalidAvsFields:le}},[Te,J,je,Je,Ot,yn,It]),[Gt,tn]=(0,r.useState)(!1),[En,Kt]=(0,r.useState)(!1),[Ft,Jt]=(0,r.useState)(()=>xo(m?.vault)),[ke,yt]=(0,r.useState)(st&&Xe?"card":"buttons"),[ct,bn]=(0,r.useState)(null),$n=ke==="expanding"||ke==="card",Dt=280,Vt=(0,r.useRef)(null),vt=(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 Zn=(0,r.useCallback)(()=>{Ve(e??null),hn(a=>a+1),yt("expanding"),vt(()=>yt("card"))},[vt,e]),Ht=(0,r.useCallback)(()=>{yt("collapsing"),vt(()=>yt("buttons"))},[vt]),_=(0,r.useCallback)(a=>{bn(a),yt("apm-expanding"),vt(()=>yt("apm-form"))},[vt]),j=(0,r.useCallback)(()=>{yt("apm-collapsing"),vt(()=>{yt("buttons"),bn(null)})},[vt]);(0,r.useEffect)(()=>{ae==="buttons"&&st&&Xe&&(Ve(e??null),yt("card"))},[ae,st,Xe,e]);let[Z,oe]=(0,r.useState)(null),ue=(0,r.useRef)(!1),[q,b]=(0,r.useState)(null),re=(0,r.useRef)(q);(0,r.useEffect)(()=>{re.current=q},[q]);let z=n||Wt,pe=d??h,Ce=(0,r.useMemo)(()=>(0,Lt.resolveTheme)(O),[O]),x=(0,r.useMemo)(()=>{let a=Ce?.buttonsLayout??(0,w.resolveButtonsLayoutTheme)(te);return W?{...a,...W,cardButton:{...a.cardButton,...W.cardButton},cardFormContainer:{...a.cardFormContainer,...W.cardFormContainer},backButton:{...a.backButton,...W.backButton},backButtonIcon:{...a.backButtonIcon,...W.backButtonIcon},submitButton:{...a.submitButton,...W.submitButton},title:{...a.title,...W.title}}:a},[Ce,te,W]),dt=be??Ce?.appearance,L=(0,r.useMemo)(()=>{let a=dt?.variables,v=Ze=>typeof Ze=="string"&&Ze?Ze:void 0,V=x.submitButton,le=v(a?.colorPrimary)??v(V?.backgroundColor)??"#4A49FF",$=ae==="buttons",ie=x.nameInput;return{primaryColor:le,primaryHoverColor:v(a?.colorPrimaryHover)??Jr(le,.12),inputBackgroundColor:v(x.cardInputBackground)??v(a?.colorBackground)??"#ffffff",textColor:v(x.cardInputColor)??v(ie?.color)??v(a?.colorText)??"#262833",borderColor:v(x.cardInputBorder)??($?"#e5e7eb":"#A4A4FF"),placeholderColor:v(x.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(ie?.fontFamily)??v(a?.fontFamily)??"Poppins, sans-serif",fontSize:v(x.cardInputFontSize)??v(a?.fontSizeBase)??"16px",fontWeight:String(La(ie?.fontWeight)??400),borderRadius:v(a?.borderRadius)??"8px"}},[dt,x,ae]),p=qe.inlineSessionPatchProcessing??!1,P=(M??Pt)||p,ge=z.replace(/\/+$/,""),X=(0,r.useMemo)(()=>Io({userId:o,email:l,firstName:N,lastName:y,country:Ne,zip:Me},In),[o,l,N,y,Ne,Me,In]),He=[X.firstName,X.lastName].filter(a=>!!a?.trim()).join(" "),ut=(0,r.useMemo)(()=>Ue?Ue.getRawProvider():null,[Ue]),qt=(0,r.useMemo)(()=>We?We.getRawProvider():null,[We]),Ye=ye||100,fe=(0,r.useMemo)(()=>dt?(0,dn.toStripeAppearance)(dt):null,[dt]),he=fe?{appearance:fe}:null,Ge=(0,r.useMemo)(()=>{let a=fe??{},v=a.rules??{};return{...a,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[fe]),nn=(0,r.useMemo)(()=>{let a=Ia(ye);return{...a,currency:Be.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...he}},[ye,Be,he]),rn=(0,r.useMemo)(()=>({mode:"payment",amount:Ye,currency:Be.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...he}),[Ye,Be,he]),K=(0,r.useCallback)(a=>{_e(a),f?.(a)},[f]);(0,r.useEffect)(()=>{!Te||!rt||rt.setCardFieldOrder?.(ve??null,J==null)},[Te,rt,ve,J]),(0,r.useEffect)(()=>{(ke==="expanding"||ke==="collapsing"||ke==="apm-expanding"||ke==="apm-collapsing")&&K(null)},[ke,K]);let on=(0,r.useCallback)((a,v,V)=>{c?.(wt(a,v,V))},[c]),Qn=(0,r.useCallback)((a,v,V)=>{let le=V?.popupBlocked??Nn(v),$=Zi(a,le),ie=Yn(V?.code)??Mn(v)??"external_payment_method_failed",Ze=new Lt.FloPayError($,"api_error",{code:"external_payment_method_failed",param:a});oe(null),ae==="buttons"&&(yt("buttons"),bn(null)),K($),u?.(Ze),console.error("[FloPay] External payment method failed:",{method:a,code:ie,popupBlocked:le})},[ae,u,K]);(0,r.useEffect)(()=>{if(!Te||!e){Jt(null);return}let a=xo(m?.vault);if(a){Jt(a);return}if(!Pn){Jt(null);return}Jt(null);let v=!0;return new dn.PaymentAPI(ge).getVaultCapture(e,t).then(V=>{if(!v)return;let le=xo(V);le?Jt(le):K("Failed to load the secure card form.")}).catch(V=>{v&&K(V instanceof Error?V.message:"Failed to load the secure card form.")}),()=>{v=!1}},[Te,Pn,Un,e,m?.vault?.html,m?.vault?.messageToken,m?.vault?.expectedOrigin,ge,t,K]);let qn=(0,r.useRef)({onComplete:s,onError:u,updateError:K,emitDecline:on,resolvedAccount:X,avsConfig:J,avsCheckProp:ee,sessionId:e,nonce:t,baseUrl:ge});qn.current={onComplete:s,onError:u,updateError:K,emitDecline:on,resolvedAccount:X,avsConfig:J,avsCheckProp:ee,sessionId:e,nonce:t,baseUrl:ge};let uo=(0,r.useRef)(!1),li=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:v,avsCheckProp:V}=qn.current,le=zt.current||a.country||"US",$=v?(0,w.isAVSFieldVisible)(v.state,le):!1,ie=v?(0,w.isAVSFieldVisible)(v.address_line_1,le):!1,Ze=v?(0,w.isAVSFieldVisible)(v.postal_code,le):!1,Ct=v?(0,w.isAVSFieldVisible)(v.city,le):!1,Et=v?(0,w.isAVSFieldVisible)(v.address_line_2,le):!1,ot=ie&&!$&&Ze?(0,w.getStateFromPostalCode)(le,(ht.current??"").trim()):null,_t=$?fn.current:ot;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Ze&&ht.current?{zip:ht.current}:{},...Ct&&en.current?{city:en.current}:{},..._t?{state:_t}:{},...ie&&Bt.current?{addressLine1:Bt.current}:{},...Et&&Yt.current?{addressLine2:Yt.current}:{},country:le},...V!==void 0?{avsCheck:V}:{},...v?{avsConfig:{country:(0,w.isAVSFieldVisible)(v.country,le),postal_code:Ze,address_line_1:ie,address_line_2:Et,city:Ct,state:$}}:{}}},[]);(0,r.useEffect)(()=>{!Te||!rt||rt.setSubmitGate?.($t)},[Te,rt,$t]),(0,r.useEffect)(()=>{if(!Te||!rt)return;uo.current=!1;let a=!1,v=rt.on("submitting",()=>{tn(!0),oe("processing");let{baseUrl:ie,sessionId:Ze,nonce:Ct,updateError:Et,onError:ot}=qn.current;!Ze||!Ct||new dn.PaymentAPI(ie).patchAccountSnapshot(Ze,Ct,li(),{telemetryMode:"best_effort"}).catch(_t=>{if(!Yi(_t))return;let Le=_t instanceof Error?_t.message:"Please check your billing address and try again.";Et(Le),oe(null),ot?.(_t instanceof Lt.FloPayError?_t:new Lt.FloPayError(Le,"api_error"))})}),V=rt.on("complete",async ie=>{ir(ie.sessionId??qn.current.sessionId),oe("success"),await new Promise(Ze=>setTimeout(Ze,Tn)),!uo.current&&(uo.current=!0,qn.current.onComplete?.({status:"succeeded",paymentIntentId:ie.intentId,checkoutMethod:"card"}))}),le=rt.on("decline",async ie=>{let{updateError:Ze,emitDecline:Ct}=qn.current,Et=ie.message??"Your payment was declined. Please try another card or contact your bank.";Ze(Et),oe("error"),Ct("card",Et,ie.declineReason?{declineCode:ie.declineReason}:void 0),await new Promise(ot=>setTimeout(ot,Cn)),!a&&oe(null)}),$=rt.on("error",async ie=>{let{updateError:Ze,onError:Ct}=qn.current,Et=ie.message??"There was a problem processing your payment. Please try again.";Ze(Et),oe("error"),Ct?.(new Lt.FloPayError(Et,"api_error")),await new Promise(ot=>setTimeout(ot,Cn)),!a&&oe(null)});return()=>{a=!0,v(),V(),le(),$()}},[Te,rt]);let vn=!!tt?.clientId,ur=Array.isArray(g),xr=ur&&g.length>0,ci=ur&&g.includes("paypal"),{expressMethods:Tr,paymentElementMethods:pr}=(0,r.useMemo)(()=>(0,w.partitionStripeMethods)(g,{excludePaypal:vn}),[g,vn]),qo=vn||!!We,di=(0,r.useMemo)(()=>qo?Tr.filter(a=>a!=="paypal"):Tr,[Tr,qo]),ui=(0,r.useMemo)(()=>{let a=[];return Q&&a.push("apple_pay"),Pe&&a.push("google_pay"),a},[Q,Pe]),Mr=ur?di:ui,pi=F&&Mr.length>0,po=Fn?je:Ne,Br=(0,r.useMemo)(()=>{let a=po?.trim().toUpperCase();return a?H?pr.filter(v=>{let V=H[v];return!V||V.length===0||V.includes(a)}):(0,w.filterStripeMethodsByCountry)(pr,po):pr},[pr,po,H]),mo=(0,r.useMemo)(()=>({mode:"payment",amount:Ye,currency:Be.toLowerCase(),paymentMethodCreation:"manual",appearance:Ge}),[Ye,Be,Ge]),[jo,Ko]=(0,r.useState)("loading"),[Vo,Ho]=(0,r.useState)("loading"),[Wo,Yo]=(0,r.useState)("loading"),[mi,yo]=(0,r.useState)(!1),[Go,fo]=(0,r.useState)("loading"),[Ar,yi]=(0,r.useState)();(0,r.useEffect)(()=>{yi(Ea())},[]);let Jo=R&&(vn||(ur?ci:Ar===!1)),Xo=F&&pi,mr=Jo&&vn,Zo=Go==="retrying"||Go==="exhausted",yr=Jo&&!!qt&&(!vn||Zo),fr=Xo&&!!ut,gr=F&&xr&&Br.length>0&&!!ut,fi=mr&&!Zo?mi:yr&&Na(jo),gi=fr&&Na(Vo),hi=gr&&Wo!=="load_error",Qo=a=>a==="loading"||a==="ready",ea=mr||yr&&Qo(jo)||fr&&Qo(Vo)||gr&&Wo!=="load_error",Fr=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!Fr.current){if(!F&&!R){Fr.current=!0;let a=new Lt.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(a),K(a.message)}else if(!F&&R&&!vn&&!qt){Fr.current=!0;let a=new Lt.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(a),K(a.message)}else if(Ar!==void 0&&!Xe&&!ea){Fr.current=!0;let a=new Lt.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});u?.(a),K(a.message)}}},[F,R,vn,qt,Ar,Xe,ea,u,K]);let ta=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(ta.current||!xr)return;let a=[];Q!==!0&&a.push("showApplePay"),Pe!==!0&&a.push("showGooglePay"),a.length!==0&&(ta.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,Q,Pe]);let na=(0,r.useCallback)((a,v)=>qe.applyInlineSessionPatch?qe.applyInlineSessionPatch(a).then(V=>({error:null,sessionId:V.sessionId||e,nonce:V.session?.clientSecret||t})).catch(V=>{let le=Da(v,V);return K(le.message),u?.(le),{error:le,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[qe.applyInlineSessionPatch,t,u,e,K]),an=(0,r.useCallback)(async a=>{if(!Se)return{proceed:!0};try{let v=await Se({method:a,sessionId:e||void 0,createSession:qe.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&zn(le=>({...le??{},...v.account}));let V=await na(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=Da(a,v);return K(V.message),u?.(V),{proceed:!1}}},[na,qe.inlineSessionDraft,Se,u,e,K]),ra=(0,r.useCallback)(async(a,v)=>{if(ue.current)return;ue.current=!0,kt(!0),oe("processing"),K(null);let V=v?.sessionId??e,le=v?.nonce??t,$=Io(X,v?.accountPatch),ie=v?.completionPaymentMethodId??Hr(a),Ze=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let Et=await new dn.PaymentAPI(ge).processPayment($.userId??"",{sessionId:V,nonce:le,tokenizedData:Ze,accountData:{userId:$.userId??"",email:$.email??"",firstName:$.firstName??"",lastName:$.lastName??"",...J?(()=>{let Le=zt.current,Zt=(0,w.isAVSFieldVisible)(J.state,Le),Qt=(0,w.isAVSFieldVisible)(J.address_line_1,Le),Hn=(0,w.isAVSFieldVisible)(J.postal_code,Le),Wn=Qt&&!Zt&&Hn?(0,w.getStateFromPostalCode)(Le,(ht.current??"").trim()):null,xt=Zt?fn.current:Wn;return{country:Le,...Hn&&ht.current?{zip:ht.current}:{},...(0,w.isAVSFieldVisible)(J.city,Le)&&en.current?{city:en.current}:{},...xt?{state:xt}:{},...Qt&&Bt.current?{addressLine1:Bt.current}:{},...(0,w.isAVSFieldVisible)(J.address_line_2,Le)&&Yt.current?{addressLine2:Yt.current}:{}}})():{}},chv:E,avsCheck:ee??!1,checkoutType:A,checkoutLayout:G,avsConfig:J?{country:(0,w.isAVSFieldVisible)(J.country,zt.current),postal_code:(0,w.isAVSFieldVisible)(J.postal_code,zt.current),address_line_1:(0,w.isAVSFieldVisible)(J.address_line_1,zt.current),address_line_2:(0,w.isAVSFieldVisible)(J.address_line_2,zt.current),city:(0,w.isAVSFieldVisible)(J.city,zt.current),state:(0,w.isAVSFieldVisible)(J.state,zt.current)}:void 0});if(Et.ok){ir(V),oe("success"),b(null),await new Promise(Le=>setTimeout(Le,Tn)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ie,checkoutMethod:a.isPaypal?"paypal":"card"});return}let ot=await Et.json().catch(()=>null);if(ot?.type==="paypal_redirect_required"){let Le=ot.threeDSecureToken,Zt=ot.paymentMethodId||a.id||"";if(!Ue||!Le){oe("error"),K("PayPal authorization required but no token provided.");return}try{let Qt=We?.getRawProvider();if(!Qt){K("PayPal is not available.");return}let Hn={return_url:window.location.href};Zt&&(Hn.payment_method=Zt);let{error:Wn}=await Qt.confirmPayment({clientSecret:Le,confirmParams:Hn,redirect:"if_required"});if(Wn){oe("error");let xt=Wn.message??"PayPal payment failed.";K(xt),on("paypal",xt,{code:Wn.code})}}catch(Qt){oe("error"),K(Qt instanceof Error?Qt.message:"PayPal authorization failed.")}return}if(ot?.type==="paypal_direct_required"){let Le=ot.orderId;if(!Le){oe("error"),K("PayPal retry required but no order id provided.");return}let Zt=re.current?.attempts??0;if(Zt>=2){oe("error"),K("PayPal payment could not be completed after multiple attempts."),on("paypal","paypal_direct_required retry limit exceeded");return}yo(!1),fo("loading"),b({orderId:Le,attempts:Zt+1}),oe(null);return}oe("error");let _t=ot?.message??"Payment failed. Please try again.";K(_t),on(a.isPaypal?"paypal":"card",_t,{code:ot?.code??ot?.gatewayErrorCode,declineCode:ot?.declineCode??ot?.gatewayDeclineReason}),await new Promise(Le=>setTimeout(Le,Cn))}catch(Ct){oe("error"),K(Ct instanceof Error?Ct.message:"An unexpected error occurred"),await new Promise(Et=>setTimeout(Et,Cn))}finally{kt(!1),oe(null),ue.current=!1}},[ge,e,t,X,He,E,Ue,We,s,u,K,on]),Xt=(0,r.useCallback)((a,v)=>{k?k(a):ra(a,v)},[k,ra]),oa=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(typeof window>"u"||oa.current)return;let a=new URLSearchParams(window.location.search),v=a.get("payment_intent"),V=a.get("payment_intent_client_secret"),le=a.get("redirect_status");if(!v||!V)return;let $=_t=>{let Le=localStorage.getItem(_t);if(!Le)return null;try{return JSON.parse(Le)}catch{return localStorage.removeItem(_t),null}},ie=$(wn)??$(Aa),Ze;if(ie?.clientSecret){if(ie.clientSecret!==V)return;Ze={...ie.accountPatch?{accountPatch:ie.accountPatch}:{},...ie.sessionId?{sessionId:ie.sessionId}:{},...ie.nonce?{nonce:ie.nonce}:{}}}else if(ie?.sessionId&&ie.sessionId!==e)return;oa.current=!0,localStorage.removeItem(wn),localStorage.removeItem(Aa);let Ct=new URL(window.location.href);Ct.searchParams.delete("payment_intent"),Ct.searchParams.delete("payment_intent_client_secret"),Ct.searchParams.delete("redirect_status"),window.history.replaceState({},"",Ct.toString());let Et=ie?.paymentMethodType??ie?.tokenType??"card",ot="card";(async()=>{let _t=Ue?.getRawProvider();if(!_t){let xt="Payment is not available \u2014 please refresh and try again.";K(xt),on(ot,xt);return}if(le==="failed"){let xt="Payment was declined. Please try again.";K(xt),on(ot,xt);return}let{paymentIntent:Le,error:Zt}=await _t.retrievePaymentIntent(V);if(Zt){let xt=Zt.message??"Failed to retrieve payment status.";K(xt),on(ot,xt,{code:Zt.code});return}let Qt=Le?.status,Hn=Vr(Qt);if(!Le||!Hn){let xt=Qt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";K(xt),on(ot,xt,{code:Qt??"missing_payment_intent"});return}let Wn=typeof Le.payment_method=="string"?Le.payment_method:Le.payment_method?.id;Xt({id:Wn??ie?.paymentMethodId??ie?.tokenId??Le.id,type:"card",threeDSecureActionResultTokenId:Le.id,gateway:ie?.gateway??"stripe",paymentMethodType:Et},Ze)})()},[e,Xt,Ue,K,on]);let go=(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 hr=ae==="buttons",jt=dt?.variables,Pi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ho=jt?.colorBackground,bi=ho&&!Pi.has(ho)?ho:void 0,Pr=x.cardInputBorder??(hr?"#e5e7eb":"#A4A4FF"),Po=jt?.colorDanger??"#dc2626",jn=a=>Gt&&a?Po:Pr,Dr=(It.malformed||It.empty)&&(En||Gt),vi=Dr?Po:jn(At.zip),bo=x.cardFormContainer?.backgroundColor??bi??(hr?"white":"#EDEDFF"),br=x.cardInputBackground??jt?.colorBackground??"white",vo=tr(Y),aa=tr(ce),er=x.nameInput,ia=x.cardInputFontSize??ts(er?.fontSize)??jt?.fontSizeBase??"16px",sa=typeof er?.fontFamily=="string"?er.fontFamily:jt?.fontFamily??"Poppins, sans-serif",la=La(er?.fontWeight)??400,Ci=x.cardInputColor??(typeof er?.color=="string"?er.color:void 0)??jt?.colorText??"#262833",Si=x.cardInputPlaceholderColor??"#9ca3af",ft=jt?.borderRadius??"8px",Kn=jt?.borderRadius??x.cardButton?.borderRadius??ft,Vn=jt?.colorPrimary??"#4A49FF",wi=jt?.colorPrimaryHover??Jr(Vn,.12),Co=jt?.colorText??"#262833",ca={fontSize:ia,fontFamily:sa,fontWeight:la,color:Ci,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ki={"--flopay-input-placeholder-color":Si,"--flopay-input-font-size":ia,"--flopay-input-font-family":sa,"--flopay-input-font-weight":String(la)},vr=x.cardFormContainer??{},So=vr.padding??(hr?"0":"1rem"),wo=vr.borderRadius??ft,Ri=rt&&Ft?(0,i.jsx)($r,{capture:rt,html:Ft.html,messageToken:Ft.messageToken,expectedOrigin:Ft.expectedOrigin,theme:L,onReady:()=>{if(!J||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 le=document.activeElement;!!le&&le.tagName==="IFRAME"&&le.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(V)):v>=50&&window.clearInterval(V)},100)},onError:a=>K(a),onValidation:a=>{K(a),a&&oe(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"}),da=(0,i.jsxs)("div",{style:{backgroundColor:bo,borderRadius:wo,...vr,padding:So,...ki,display:"flex",flexDirection:"column"},children:[(0,i.jsx)("style",{children:`
30
+ `,Zr=44;function Fo(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 Qi={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ja={width:"100%",minHeight:Zr,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 es(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function La(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Va(e){return e==="paypal"?"PayPal":(0,w.getStripeMethodDisplayName)(e)}function ts(e,t){let n=`We couldn't open ${Va(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ka(e){let t=(0,r.useRef)(0),n=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useCallback)((u=l.current)=>{let P=u;P?.timer&&(clearTimeout(P.timer),P.timer=null)},[]),s=(0,r.useCallback)((u,P)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(u),u.timer=setTimeout(()=>{u.timer=null,l.current?.generation===u.generation&&(l.current=null,n.current=u.generation,e(u.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},P))},[o,e]),p=(0,r.useCallback)(u=>{u.yieldedControl&&s(u,600)},[s]),d=(0,r.useCallback)(u=>{o();let P=t.current+1;t.current=P,n.current=null;let _={generation:P,method:u,timer:null,yieldedControl:!1};return l.current=_,P},[o]),k=(0,r.useCallback)(u=>{let P=l.current;return typeof u=="number"&&P?.generation!==u?!1:(o(P),l.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[o]),D=(0,r.useCallback)(u=>{let P=l.current,_=u??P?.generation??t.current;(!u||P?.generation===u)&&(o(P),l.current=null),n.current=_},[o]),f=(0,r.useCallback)(u=>n.current===(u??t.current),[]),E=(0,r.useCallback)(u=>l.current?.generation===u&&n.current!==u,[]),C=(0,r.useCallback)(()=>{let u=l.current;u&&p(u)},[p]),M=(0,r.useCallback)(()=>{let u=l.current;u&&(u.yieldedControl=!0,o(u))},[o]);return(0,r.useEffect)(()=>{let u=()=>{document.visibilityState==="visible"?C():M()},P=()=>{M()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",P),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",P),window.removeEventListener("focus",C),o()}},[o,M,C]),{startAttempt:d,finishAttempt:k,invalidateAttempt:D,isAttemptInvalidated:f,isAttemptCurrent:E}}function ns(e){let t=(0,w.getPostalCodeExample)(e);return`Enter a valid ${(0,w.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function rs(e,t,n){let l=(0,w.isPostalCodeSupported)(e),o=t.trim(),s=n&&l,p=s&&!o,d=s&&!!o&&!(0,w.isValidPostalCode)(e,o);return{visible:n,supported:l,required:s,empty:p,malformed:d}}function Na(e,t){return t instanceof At.FloPayError?t:new At.FloPayError(t instanceof Error?t.message:`${es(e)} before-click hook failed.`,"validation_error")}function Mo(){return(0,i.jsx)("style",{children:Zi})}function os(e){return typeof e=="number"?`${e}px`:e}function Oa(e){if(typeof e=="number"||typeof e=="string")return e}function Ha(e,t){let n=e.availablePaymentMethods;return n&&t.some(l=>n[l])?"ready":"unavailable"}function Wa({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 za(e){return e!=="unavailable"&&e!=="load_error"}function eo(e){return(0,i.jsx)(is,{...e})}function Ua({sessionId:e,nonce:t,email:n,billingApiUrl:l,onTokenizedBody:o,onErrorChange:s,isProcessing:p=!1,onButtonClick:d,onDecline:k,onTechnicalFailure:D,runBeforeButtonClick:f,onLoadStateChange:E,placeholderBorderRadius:C}){let M=ln(),u=(0,dt.useStripe)(),P=(0,dt.useElements)(),[_,F]=(0,r.useState)("loading");(0,r.useEffect)(()=>{E?.(_)},[_,E]);let[g,ce]=(0,r.useState)(!1),j=(0,r.useRef)(!1),pe=(0,r.useRef)(null),te=(0,r.useRef)(null),[L,Z]=(0,r.useState)(0),[G,me]=(0,r.useState)(!1),V=(0,r.useRef)(!1),H=(0,r.useRef)(new Map),{startAttempt:he,finishAttempt:Me,invalidateAttempt:we,isAttemptInvalidated:Ce,isAttemptCurrent:ne}=Ka((X,x,ye)=>{D?.(X,x,{...ye,popupBlocked:ye?.popupBlocked??Ln(x)}),me(!0),Z(ze=>ze+1)});(0,r.useEffect)(()=>{G&&te.current?.focus()},[G,L]);let Se=(0,r.useCallback)(()=>{Z(X=>X+1)},[]),Be=(0,r.useCallback)((X,x,ye)=>{we(ye),D?.("paypal",X,{code:x,popupBlocked:Ln(X)}),me(!0),Se()},[we,D,Se]),re=(0,r.useCallback)(()=>{window.setTimeout(()=>{(pe.current?.querySelector("iframe")??pe.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{V.current&&(V.current=!1,re())},[re,L]);let xe=(0,r.useCallback)(()=>{me(!1),s?.(null),re()},[re,s]);(0,r.useEffect)(()=>{if(!u||j.current)return;let X=new URLSearchParams(window.location.search),x=X.get("payment_intent"),ye=X.get("payment_intent_client_secret"),ze=X.get("redirect_status");if(!x||!ye)return;j.current=!0;let Ue;try{let I=localStorage.getItem(Er);if(I){let oe=JSON.parse(I);oe.clientSecret===ye&&(Ue={...oe.accountPatch?{accountPatch:oe.accountPatch}:{},...oe.sessionId?{sessionId:oe.sessionId}:{},...oe.nonce?{nonce:oe.nonce}:{}})}}catch{}try{localStorage.removeItem(Er)}catch{}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()),(async()=>{try{if(ce(!0),ze==="failed"){let ee="PayPal payment was declined. Please try again.";s?.(ee),k?.(St("paypal",ee));return}let{paymentIntent:I,error:oe}=await u.retrievePaymentIntent(ye);if(oe){s?.(oe.message??"Failed to retrieve PayPal payment status.");return}if(I&&(I.status==="requires_capture"||I.status==="succeeded")){let ee=typeof I.payment_method=="string"?I.payment_method:I.payment_method?.id;o({id:ee??I.id,type:"card",threeDSecureActionResultTokenId:I.id,isPaypal:!0},Ue)}else{let ee="PayPal payment was not completed. Please try again.";s?.(ee),k?.(St("paypal",ee))}}catch(I){s?.(I instanceof Error?I.message:"Failed to complete PayPal payment.")}finally{ce(!1)}})()},[u,o,s,k]);let De=(0,r.useCallback)(async X=>{if(p||g){X.reject();return}let x=f?await f("paypal"):{proceed:!0};if(!x.proceed){H.current.delete(L),X.reject();return}let ye=he("paypal");H.current.set(L,{generation:ye,accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}),me(!1),d?.("paypal"),X.resolve()},[H,p,d,f,he,g,L]),Ee=(0,r.useCallback)(async X=>{if(!u||!P)return;let x=H.current.get(L);if(x&&!ne(x.generation)){H.current.delete(L);return}if(!x&&Ce()||x&&!Me(x.generation))return;x||Me();let ye=x??null;if(H.current.delete(L),!ye&&f){let I=await f("paypal");if(!I.proceed){X.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ye={accountPatch:I.accountPatch,sessionId:I.sessionId,nonce:I.nonce}}let ze=ye?.sessionId??e,Ue=ye?.nonce??t,Pe=ye?.accountPatch?.email??n;try{if(ce(!0),s?.(null),!ze||!Pe)throw new Error("Missing sessionId or email for PayPal payment");let I=u.createPaymentMethod,{error:oe,paymentMethod:ee}=await I({type:"paypal"});if(oe){Be(oe,"stripe_paypal_create_payment_method_failed",x?.generation),X.paymentFailed({reason:"fail"});return}let Ne=await new dn.PaymentAPI(l).createSessionIntent(ze,Ue??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ee?.id??null,intentKind:"payment"});if(Ne.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ut=Ne.clientSecret,He={return_url:window.location.href};if(ee?.id&&(He.payment_method=ee.id),typeof window<"u")try{localStorage.setItem(Er,JSON.stringify({clientSecret:ut,sessionId:ze,nonce:Ue,accountPatch:ye?.accountPatch}))}catch{}let{error:it,paymentIntent:O}=await u.confirmPayment({clientSecret:ut,confirmParams:He,redirect:"if_required"});if(it){if(typeof window<"u")try{localStorage.removeItem(Er)}catch{}if(Rr(it)){let qe=it.message??"Your payment was declined.";s?.(qe),k?.(St("paypal",qe,{code:Mn(it),declineCode:lr(it)})),await Qr({billingApiUrl:l,sessionId:ze,nonce:Ue,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(it)??"provider_declined"}})}else Be(it,"stripe_paypal_confirm_failed",x?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Er)}catch{}let z=typeof O?.payment_method=="string"?O.payment_method:O?.payment_method?.id;o({id:z??O?.id,type:"card",threeDSecureActionResultTokenId:O?.id,isPaypal:!0},{accountPatch:ye?.accountPatch,sessionId:ze,nonce:Ue});return}catch(I){Be(I,"stripe_paypal_failed",x?.generation)}finally{ce(!1)}},[u,P,e,t,n,l,o,s,k,f,Be,Me,ne,Ce,L]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Wa,{state:_,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:(0,i.jsxs)("div",{ref:pe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[G&&(0,i.jsx)("button",{ref:te,type:"button","data-testid":"flopay-paypal-retry-button",onClick:xe,style:ja,children:"Try PayPal again"}),(0,i.jsx)(dt.ExpressCheckoutElement,{onReady:X=>F(Ha(X,["paypal"])),onLoadError:()=>{F("load_error"),Ao(_t(M),"paypal","paypal")},onClick:De,onConfirm:Ee,onCancel:()=>{let X=H.current.get(L);H.current.delete(L),_t(M)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we(X?.generation),me(!1),V.current=!0,Se()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},L)]})}),g&&(0,i.jsx)(Pn,{status:"processing"})]})}function $a({sessionId:e,nonce:t,email:n,billingApiUrl:l,intentKind:o,expressMethods:s,onTokenizedBody:p,onErrorChange:d,onButtonClick:k,onDecline:D,onTechnicalFailure:f,runBeforeButtonClick:E,onLoadStateChange:C,placeholderBorderRadius:M}){let u=ln(),P=(0,dt.useStripe)(),_=(0,dt.useElements)(),[F,g]=(0,r.useState)("loading");(0,r.useEffect)(()=>{C?.(F)},[F,C]);let[ce,j]=(0,r.useState)(!1),pe=(0,r.useRef)(null),te=(0,r.useRef)(null),[L,Z]=(0,r.useState)(0),[G,me]=(0,r.useState)(!1),[V,H]=(0,r.useState)("google_pay"),he=(0,r.useRef)(!1),Me=(0,r.useRef)("google_pay"),we=(0,r.useRef)("google_pay"),Ce=(0,r.useRef)(new Map),{startAttempt:ne,finishAttempt:Se,invalidateAttempt:Be,isAttemptInvalidated:re,isAttemptCurrent:xe}=Ka((Pe,I,oe)=>{f?.(Pe,I,{...oe,popupBlocked:oe?.popupBlocked??Ln(I)}),H(Pe),me(!0),Z(ee=>ee+1)});(0,r.useEffect)(()=>{G&&te.current?.focus()},[G,L]);let De=(0,r.useCallback)(()=>{Z(Pe=>Pe+1)},[]),Ee=(0,r.useCallback)((Pe,I,oe,ee)=>{Be(ee),f?.(Pe,I,{code:oe,popupBlocked:Ln(I)}),H(Pe),me(!0),De()},[Be,f,De]),X=(0,r.useCallback)(()=>{window.setTimeout(()=>{(pe.current?.querySelector("iframe")??pe.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{he.current&&(he.current=!1,X())},[X,L]);let x=(0,r.useCallback)(()=>{me(!1),d?.(null),X()},[X,d]),ye=(0,r.useCallback)(async Pe=>{if(!P||!_)return;let I=Ce.current.get(L);if(I&&!xe(I.generation)){Ce.current.delete(L);return}if(!I&&re()||I&&!Se(I.generation))return;I||Se();let oe=Pe.expressPaymentType??I?.method??Me.current,ee=I??null;Ce.current.delete(L);let Ne=La(oe);if(!ee&&E){let z=await E(Ne);if(!z.proceed){Pe.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}ee={accountPatch:z.accountPatch,sessionId:z.sessionId,nonce:z.nonce}}let ut=Ne,He=ee?.sessionId??e,it=ee?.nonce??t,O=ee?.accountPatch?.email??n;try{j(!0),d?.(null);let{error:z}=await _.submit();if(z){Ee(oe,z,"stripe_wallet_submit_failed",I?.generation);return}let{error:qe,paymentMethod:Ke}=await P.createPaymentMethod({elements:_});if(qe||!Ke){Ee(oe,qe??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",I?.generation);return}if(!He||!O)throw new Error("Missing sessionId or email for wallet payment");let st=await new dn.PaymentAPI(l).createSessionIntent(He,it??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:oe??Ne,paymentMethodId:Ke.id,intentKind:o});if(st.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let pt=st.clientSecret,{error:xt,intentId:Wt}=(0,At.isSetupIntentClientSecret)(pt)?await P.confirmCardSetup(pt,{payment_method:Ke.id}).then(y=>({error:y.error,intentId:y.setupIntent?.id})):await P.confirmCardPayment(pt,{payment_method:Ke.id}).then(y=>({error:y.error,intentId:y.paymentIntent?.id}));if(xt){if(Rr(xt)){let y=xt.message??"Your payment was declined.";d?.(y),D?.(St(ut,y,{code:Mn(xt),declineCode:lr(xt)})),await Qr({billingApiUrl:l,sessionId:He,nonce:it,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:oe??Ne,providerDeclineReason:Mn(xt)??"provider_declined"}})}else Ee(oe,xt,"stripe_wallet_confirm_failed",I?.generation);return}p({id:Ke.id,type:"card",threeDSecureActionResultTokenId:Wt},{accountPatch:ee?.accountPatch,sessionId:He,nonce:it})}catch(z){Ee(oe,z,"stripe_wallet_failed",I?.generation)}finally{j(!1)}},[P,_,e,t,n,l,o,p,d,D,E,Ee,Se,xe,re,L]),ze=(0,r.useMemo)(()=>{let Pe=["applePay","googlePay","paypal","link","amazonPay","klarna"],I=new Set(["applePay","googlePay"]),oe=new Set(s.map(w.stripeExpressMethodToOptionKey)),ee={};for(let Ne of Pe)oe.has(Ne)?ee[Ne]=I.has(Ne)?"always":"auto":ee[Ne]="never";return ee},[s]),Ue=(0,r.useMemo)(()=>s.map(w.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Wa,{state:F,placeholderTestId:"flopay-wallet-placeholder",borderRadius:M,children:(0,i.jsxs)("div",{ref:pe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[G&&(0,i.jsxs)("button",{ref:te,type:"button","data-testid":"flopay-wallet-retry-button",onClick:x,style:ja,children:["Try ",Va(V)," again"]}),(0,i.jsx)(dt.ExpressCheckoutElement,{onReady:Pe=>{g(Ha(Pe,Ue))},onLoadError:Pe=>{g("load_error"),Ao(_t(u),"stripe","wallet")},onClick:async Pe=>{Me.current=Pe.expressPaymentType,we.current=La(Pe.expressPaymentType);let I=E?await E(we.current):{proceed:!0};if(!I.proceed){Ce.current.delete(L),Pe.reject();return}let oe=ne(Pe.expressPaymentType);Ce.current.set(L,{generation:oe,method:Pe.expressPaymentType,accountPatch:I.accountPatch,sessionId:I.sessionId,nonce:I.nonce}),me(!1),k?.(we.current),Pe.resolve()},onConfirm:ye,onCancel:()=>{let Pe=Ce.current.get(L);Ce.current.delete(L),_t(u)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Be(Pe?.generation),me(!1),he.current=!0,De()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ze,layout:{maxColumns:1,overflow:"never"}}},L)]})}),ce&&(0,i.jsx)(Pn,{status:"processing"})]})}function as({method:e,themeId:t,submitting:n=!1,disabled:l=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:p,backgroundColor:d,borderColor:k,textColor:D,borderRadius:f,fontFamily:E}){let C=(0,w.resolveStripeMethodBrandVariant)(e,t),M=Ca[e],u=C?.backgroundColor??d??"#ffffff",P=C?.borderColor??k??"#d1d5db",_=C?.textColor??D??"#262833";return(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!l&&p()},disabled:n||l,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Zr,padding:"0 1rem",backgroundColor:u,color:_,border:`1px solid ${P}`,borderRadius:f??8,fontSize:"0.95rem",fontWeight:600,fontFamily:E,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,w.getStripeMethodDisplayName)(e)}\u2026`}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,w.hasVendoredStripeMethodLogo)(e)?8:0},children:[M?(0,i.jsx)("img",{src:M,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):C?.logoSvg?(0,i.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:C.logoSvg}}):null,(0,i.jsx)("span",{children:(0,w.getStripeMethodDisplayName)(e)})]}),s&&(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:_,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 Bo({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:p,onErrorChange:d,onDecline:k,onCancel:D,runBeforeButtonClick:f,onButtonClick:E,isProcessing:C,submitButtonColor:M,submitButtonBorderRadius:u,submitButtonStyle:P,errorText:_}){let F=ln(),g=(0,dt.useStripe)(),ce=(0,dt.useElements)(),[j,pe]=(0,r.useState)(!1),te=(0,r.useRef)(!1),[L,Z]=(0,r.useState)(!1),[G,me]=(0,r.useState)("loading"),V=(0,r.useCallback)(async()=>{if(!g||!ce||C||te.current||!L)return;te.current=!0,pe(!0);let H=f?await f("card"):{proceed:!0};if(!H.proceed){te.current=!1,pe(!1);return}E?.("card");let he=H.sessionId??t,Me=H.nonce??n,we=H.accountPatch?.email??l;try{d?.(null);let Ce=await ce.submit();if(Ce.error){d?.(Ce.error.message??"Payment failed.");return}let ne=await g.createPaymentMethod({elements:ce});if(ne.error||!ne.paymentMethod){d?.(ne.error?.message??"Failed to create payment method.");return}let Se=ne.paymentMethod;if(!he||!we)throw new Error("Missing sessionId or email for payment.");let Be=Se.type||e,re=await new dn.PaymentAPI(s).createSessionIntent(he,Me??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Be,paymentMethodId:null,intentKind:"payment"});if(re.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let xe=re.clientSecret;if(typeof window<"u")try{localStorage.setItem(bn,JSON.stringify({clientSecret:xe,sessionId:he,nonce:Me,accountPatch:H.accountPatch,paymentMethodId:Se.id,paymentMethodType:Se.type??e,gateway:"stripe"}))}catch{}let{error:De,paymentIntent:Ee}=await g.confirmPayment({clientSecret:xe,confirmParams:{return_url:window.location.href,payment_method:Se.id},redirect:"if_required"});if(De){if(typeof window<"u")try{localStorage.removeItem(bn)}catch{}let ye=De.message??"Payment failed.";d?.(ye),k?.(St("card",ye,{code:De.code})),await Qr({billingApiUrl:s,sessionId:he,nonce:Me,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:De.code??"provider_declined"}});return}let X=Ee?.status;if(!Hr(X)){if(typeof window<"u")try{localStorage.removeItem(bn)}catch{}let ye=X==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(ye),k?.(St("card",ye,{code:X??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(bn)}catch{}let x=typeof Ee?.payment_method=="string"?Ee.payment_method:Ee?.payment_method?.id;p({id:x??Se.id,type:"card",threeDSecureActionResultTokenId:Ee?.id,gateway:"stripe",paymentMethodType:Se.type??e},{accountPatch:H.accountPatch,sessionId:he,nonce:Me})}catch(Ce){d?.(Ce instanceof Error?Ce.message:"Payment failed. Please try again.")}finally{te.current=!1,pe(!1)}},[g,ce,C,L,f,E,t,n,l,s,e,p,d,k]);return(0,i.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,i.jsx)(dt.PaymentElement,{onReady:()=>me("ready"),onLoadError:()=>{me("load_error"),Ao(_t(F),"stripe","apm")},onChange:H=>{Z(!!H.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:!L||j||C||G!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:M,color:"white",border:"none",borderRadius:u,fontSize:"1rem",fontWeight:600,cursor:!L||j||C||G!=="ready"?"not-allowed":"pointer",opacity:!L||j||C||G!=="ready"?.5:1,transition:"opacity 120ms ease-out",...P??{}},children:j?"Processing\u2026":`Pay with ${(0,w.getStripeMethodDisplayName)(e)}`}),_&&(0,i.jsx)(ar,{margin:"0.75rem 0 0",children:_})]})}function qa({sessionId:e,nonce:t,email:n,billingName:l,billingApiUrl:o,paymentElementMethods:s,stripeInstance:p,paymentElementBaseOptions:d,onTokenizedBody:k,onErrorChange:D,onButtonClick:f,onDecline:E,runBeforeButtonClick:C,onLoadStateChange:M,isProcessing:u=!1,submitButtonColor:P="#4A49FF",submitButtonBorderRadius:_=8,submitButtonStyle:F,buttonAppearance:g,themeId:ce,onExpandApm:j,expandedApmMethod:pe}){let[te,L]=(0,r.useState)(null),[Z,G]=(0,r.useState)(null),me=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&p?M?.("ready"):p||M?.("loading")},[s.length,p,M]);let V=(0,r.useCallback)(async ne=>{if(!p||me.current||u)return;me.current=!0,G(ne);let Se=C?await C("card"):{proceed:!0};if(!Se.proceed){me.current=!1,G(null);return}f?.("card");let Be=Se.sessionId??e,re=Se.nonce??t,xe=Se.accountPatch?.email??n;try{if(D?.(null),!Be||!xe)throw new Error("Missing sessionId or email for payment.");let De=await new dn.PaymentAPI(o).createSessionIntent(Be,re??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,paymentMethodId:null,intentKind:"payment"});if(De.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ee=De.clientSecret;if(typeof window<"u")try{localStorage.setItem(bn,JSON.stringify({clientSecret:Ee,sessionId:Be,nonce:re,accountPatch:Se.accountPatch,paymentMethodType:ne,gateway:"stripe"}))}catch{}let{error:X,paymentIntent:x}=await p.confirmPayment({clientSecret:Ee,confirmParams:{return_url:window.location.href,payment_method_data:{type:ne,billing_details:{name:l&&l.trim().length>=3?l.trim():"FloPay Customer",...xe?{email:xe}:{}}}},redirect:"if_required"});if(X){if(typeof window<"u")try{localStorage.removeItem(bn)}catch{}let Ue=X.message??"Payment failed.";D?.(Ue),E?.(St("card",Ue,{code:X.code})),await Qr({billingApiUrl:o,sessionId:Be,nonce:re,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,providerDeclineReason:X.code??"provider_declined"}});return}let ye=x?.status;if(!Hr(ye)){if(typeof window<"u")try{localStorage.removeItem(bn)}catch{}let Ue=ye==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";D?.(Ue),E?.(St("card",Ue,{code:ye??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(bn)}catch{}let ze=typeof x?.payment_method=="string"?x.payment_method:x?.payment_method?.id;k({id:ze??x?.id,type:"card",threeDSecureActionResultTokenId:x?.id,gateway:"stripe",paymentMethodType:ne},{accountPatch:Se.accountPatch,sessionId:Be,nonce:re})}catch(De){D?.(De instanceof Error?De.message:"Payment failed. Please try again.")}finally{me.current=!1,G(null)}},[p,u,C,f,e,t,n,o,l,k,D,E]),[H,he]=(0,r.useState)(null),Me=j?pe??null:H,we=(0,r.useCallback)(ne=>{me.current||u||Me&&Me!==ne||((0,w.needsStripeMethodExplicitConfirm)(ne)?j?j(ne):he(ne):V(ne))},[Me,u,V,j]),Ce=(0,r.useMemo)(()=>H?{...d,paymentMethodTypes:[H]}:null,[H,d]);return(0,i.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(ne=>{let Se=pe===ne,Be=Z===ne,re=Z!==null&&Z!==ne||pe!=null&&pe!==ne;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(as,{method:ne,themeId:ce,submitting:Be,disabled:re,highlighted:Se,hasNextStep:(0,w.needsStripeMethodExplicitConfirm)(ne),onClick:()=>we(ne),backgroundColor:g?.backgroundColor,borderColor:g?.borderColor,textColor:g?.textColor,borderRadius:g?.borderRadius,fontFamily:g?.fontFamily}),!j&&H===ne&&Ce&&p&&(0,i.jsx)(dt.Elements,{stripe:p,options:Ce,children:(0,i.jsx)(Bo,{method:ne,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:k,onErrorChange:D,onDecline:E,onCancel:()=>he(null),runBeforeButtonClick:C,onButtonClick:f,isProcessing:u,submitButtonColor:P,submitButtonBorderRadius:_,submitButtonStyle:F})},ne)]},ne)})})}function is({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:p,onDecline:d,onTokenizedBody:k,firstName:D,lastName:f,chv:E,className:C,isProcessing:M,error:u,onErrorChange:P,showPayPal:_=!0,showStripe:F=!0,enabledPaymentMethods:g,enabledPaymentMethodCountries:ce,showApplePay:j=!0,showGooglePay:pe=!0,layout:te="default",theme:L,buttonsTheme:Z,buttonsStyles:G,appearance:me,cardButtonContent:V,cardBackButtonContent:H,cardTitleContent:he,showSecurityFooter:Me,onButtonClick:we,onBeforeButtonClick:Ce,enableAVS:ne,cardFieldOrder:Se,cardPreFormSlot:Be,avsLayout:re="row",country:xe,zip:De,addressLine1:Ee,addressLine2:X,city:x,state:ye,onCountryChange:ze,onZipChange:Ue,avsCheck:Pe,checkoutType:I,checkoutLayout:oe,totalAmount:ee=0,currency:Ne="usd",initialCardOpen:ut=!1,directPaypal:He,isSubscription:it=!1,session:O,debug:z=!1}){let qe=ln(),Ke=jr(),st=(0,r.useContext)(sn),pt=Kr(),[xt,Wt]=(0,r.useState)(!1),[y,ke]=(0,r.useState)(null),[Ye,rt]=(0,r.useState)(xe??"US"),[ft,Ge]=(0,r.useState)(De??""),[et,Ae]=(0,r.useState)(Ee??""),[Je,Tt]=(0,r.useState)(X??""),[We,On]=(0,r.useState)(x??""),[gt,Cn]=(0,r.useState)(ye??""),[Sn,zn]=(0,r.useState)({}),wt=(0,r.useRef)(De??""),Mt=(0,r.useRef)(xe??"US"),Yt=(0,r.useRef)(Ee??""),Dt=(0,r.useRef)(X??""),Gt=(0,r.useRef)(x??""),yn=(0,r.useRef)(ye??""),ae=(0,r.useMemo)(()=>(0,w.resolveAVSConfig)(ne),[ne]),qt=ae!==null,wn=!!O?.vault?.html,kn=!!O?.gateways?.pcivault,R=!!(O?.gateways?.stripe?.enabledPaymentMethods??g)?.includes("card"),Xe=wn||R||kn,Ie=!!(F&&Xe&&qe&&e),[Fn,je]=(0,r.useState)(()=>te!=="buttons"||ut?e??null:null),[Un,Qn]=(0,r.useState)(0),jt=te!=="buttons"||ut||!!e&&Fn===e,lt=(0,r.useMemo)(()=>!qe||!Ie||!e||!jt?null:qe.cardCapture({sessionId:e}),[qe,Ie,e,jt]),Bt=(0,r.useMemo)(()=>{let a=Ye,b=ae?(0,w.isAVSFieldVisible)(ae.postal_code,a):!1;return rs(a,ft,b)},[ae,Ye,ft]),{avsInvalid:Vt,invalidAvsFields:Pt}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!Ie||!ae)return{avsInvalid:!1,invalidAvsFields:a};let b=Ye,K=(ie,Ze)=>(0,w.isAVSFieldVisible)(ie,b)&&!Ze.trim(),le={line1:K(ae.address_line_1,et),city:K(ae.city,We),state:K(ae.state,gt),zip:Bt.empty||Bt.malformed};return{avsInvalid:le.line1||le.city||le.state||le.zip,invalidAvsFields:le}},[Ie,ae,Ye,et,We,gt,Bt]),[en,tn]=(0,r.useState)(!1),[fn,nn]=(0,r.useState)(!1),[kt,Lt]=(0,r.useState)(()=>To(O?.vault)),[Te,ot]=(0,r.useState)(ut&&Xe?"card":"buttons"),[at,Rn]=(0,r.useState)(null),$n=Te==="expanding"||Te==="card",Kt=280,Nt=(0,r.useRef)(null),Ot=(0,r.useCallback)(a=>{Nt.current&&clearTimeout(Nt.current),Nt.current=setTimeout(()=>{Nt.current=null,a()},Kt)},[Kt]);(0,r.useEffect)(()=>()=>{Nt.current&&clearTimeout(Nt.current)},[]);let In=(0,r.useCallback)(()=>{je(e??null),Qn(a=>a+1),ot("expanding"),Ot(()=>ot("card"))},[Ot,e]),qn=(0,r.useCallback)(()=>{ot("collapsing"),Ot(()=>ot("buttons"))},[Ot]),zt=(0,r.useCallback)(a=>{Rn(a),ot("apm-expanding"),Ot(()=>ot("apm-form"))},[Ot]),En=(0,r.useCallback)(()=>{ot("apm-collapsing"),Ot(()=>{ot("buttons"),Rn(null)})},[Ot]);(0,r.useEffect)(()=>{te==="buttons"&&ut&&Xe&&(je(e??null),ot("card"))},[te,ut,Xe,e]);let[ht,h]=(0,r.useState)(null),U=(0,r.useRef)(!1),W=(0,r.useRef)(null),fe=(0,r.useRef)("idle"),[se,Q]=(0,r.useState)(null),S=(0,r.useRef)(se);(0,r.useEffect)(()=>{S.current=se},[se]);let A=n||pt,$=u??y,ve=(0,r.useMemo)(()=>(0,At.resolveTheme)(L),[L]),c=(0,r.useMemo)(()=>{let a=ve?.buttonsLayout??(0,w.resolveButtonsLayoutTheme)(Z);return G?{...a,...G,cardButton:{...a.cardButton,...G.cardButton},cardFormContainer:{...a.cardFormContainer,...G.cardFormContainer},backButton:{...a.backButton,...G.backButton},backButtonIcon:{...a.backButtonIcon,...G.backButtonIcon},submitButton:{...a.submitButton,...G.submitButton},title:{...a.title,...G.title}}:a},[ve,Z,G]),m=me??ve?.appearance,ue=(0,r.useMemo)(()=>{let a=m?.variables,b=Ze=>typeof Ze=="string"&&Ze?Ze:void 0,K=c.submitButton,le=b(a?.colorPrimary)??b(K?.backgroundColor)??"#4A49FF",q=te==="buttons",ie=c.nameInput;return{primaryColor:le,primaryHoverColor:b(a?.colorPrimaryHover)??Xr(le,.12),inputBackgroundColor:b(c.cardInputBackground)??b(a?.colorBackground)??"#ffffff",textColor:b(c.cardInputColor)??b(ie?.color)??b(a?.colorText)??"#262833",borderColor:b(c.cardInputBorder)??(q?"#e5e7eb":"#A4A4FF"),placeholderColor:b(c.cardInputPlaceholderColor)??"#9ca3af",errorColor:b(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:b(ie?.fontFamily)??b(a?.fontFamily)??"Poppins, sans-serif",fontSize:b(c.cardInputFontSize)??b(a?.fontSizeBase)??"16px",fontWeight:String(Oa(ie?.fontWeight)??400),borderRadius:b(a?.borderRadius)??"8px"}},[m,c,te]),$e=st.inlineSessionPatchProcessing??!1,Y=(M??xt)||$e,N=A.replace(/\/+$/,""),J=(0,r.useMemo)(()=>Eo({userId:o,email:l,firstName:D,lastName:f,country:xe,zip:De},Sn),[o,l,D,f,xe,De,Sn]),bt=[J.firstName,J.lastName].filter(a=>!!a?.trim()).join(" "),Re=(0,r.useMemo)(()=>qe?qe.getRawProvider():null,[qe]),de=(0,r.useMemo)(()=>Ke?Ke.getRawProvider():null,[Ke]),ge=ee||100,Ve=(0,r.useMemo)(()=>m?(0,dn.toStripeAppearance)(m):null,[m]),Ht=Ve?{appearance:Ve}:null,rn=(0,r.useMemo)(()=>{let a=Ve??{},b=a.rules??{};return{...a,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[Ve]),Ut=(0,r.useMemo)(()=>{let a=_a(ee);return{...a,currency:Ne.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...Ht}},[ee,Ne,Ht]),jo=(0,r.useMemo)(()=>({mode:"payment",amount:ge,currency:Ne.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Ht}),[ge,Ne,Ht]),be=(0,r.useCallback)(a=>{ke(a),P?.(a)},[P]);(0,r.useEffect)(()=>{!Ie||!lt||lt.setCardFieldOrder?.(Se??null,ae==null)},[Ie,lt,Se,ae]),(0,r.useEffect)(()=>{(Te==="expanding"||Te==="collapsing"||Te==="apm-expanding"||Te==="apm-collapsing")&&be(null)},[Te,be]);let on=(0,r.useCallback)((a,b,K)=>{d?.(St(a,b,K))},[d]),er=(0,r.useCallback)((a,b,K)=>{let le=K?.popupBlocked??Ln(b),q=ts(a,le),ie=Gn(K?.code)??Mn(b)??"external_payment_method_failed",Ze=new At.FloPayError(q,"api_error",{code:"external_payment_method_failed",param:a});h(null),te==="buttons"&&(ot("buttons"),Rn(null)),be(q),p?.(Ze),console.error("[FloPay] External payment method failed:",{method:a,code:ie,popupBlocked:le})},[te,p,be]);(0,r.useEffect)(()=>{if(!Ie||!e){Lt(null);return}let a=To(O?.vault);if(a){Lt(a);return}if(!jt){Lt(null);return}Lt(null);let b=!0;return new dn.PaymentAPI(N).getVaultCapture(e,t).then(K=>{if(!b)return;let le=To(K);le?Lt(le):be("Failed to load the secure card form.")}).catch(K=>{b&&be(K instanceof Error?K.message:"Failed to load the secure card form.")}),()=>{b=!1}},[Ie,jt,Un,e,O?.vault?.html,O?.vault?.messageToken,O?.vault?.expectedOrigin,N,t,be]);let jn=(0,r.useRef)({onComplete:s,onError:p,updateError:be,emitDecline:on,resolvedAccount:J,avsConfig:ae,avsCheckProp:Pe,sessionId:e,nonce:t,baseUrl:N});jn.current={onComplete:s,onError:p,updateError:be,emitDecline:on,resolvedAccount:J,avsConfig:ae,avsCheckProp:Pe,sessionId:e,nonce:t,baseUrl:N};let po=(0,r.useRef)(!1),di=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:b,avsCheckProp:K}=jn.current,le=Mt.current||a.country||"US",q=b?(0,w.isAVSFieldVisible)(b.state,le):!1,ie=b?(0,w.isAVSFieldVisible)(b.address_line_1,le):!1,Ze=b?(0,w.isAVSFieldVisible)(b.postal_code,le):!1,vt=b?(0,w.isAVSFieldVisible)(b.city,le):!1,Rt=b?(0,w.isAVSFieldVisible)(b.address_line_2,le):!1,tt=ie&&!q&&Ze?(0,w.getStateFromPostalCode)(le,(wt.current??"").trim()):null,It=q?yn.current:tt;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Ze&&wt.current?{zip:wt.current}:{},...vt&&Gt.current?{city:Gt.current}:{},...It?{state:It}:{},...ie&&Yt.current?{addressLine1:Yt.current}:{},...Rt&&Dt.current?{addressLine2:Dt.current}:{},country:le},...K!==void 0?{avsCheck:K}:{},...b?{avsConfig:{country:(0,w.isAVSFieldVisible)(b.country,le),postal_code:Ze,address_line_1:ie,address_line_2:Rt,city:vt,state:q}}:{}}},[]);(0,r.useEffect)(()=>{!Ie||!lt||lt.setSubmitGate?.(Vt)},[Ie,lt,Vt]),(0,r.useEffect)(()=>{if(!Ie||!lt)return;po.current=!1;let a=!1,b=lt.on("submitting",()=>{tn(!0),W.current&&clearTimeout(W.current),fe.current="validation-window",W.current=setTimeout(()=>{W.current=null,fe.current==="validation-window"&&(fe.current="processing")},Ji),h("processing");let{baseUrl:ie,sessionId:Ze,nonce:vt,updateError:Rt,onError:tt}=jn.current;!Ze||!vt||new dn.PaymentAPI(ie).patchAccountSnapshot(Ze,vt,di(),{telemetryMode:"best_effort"}).catch(It=>{if(!Xi(It))return;let Oe=It instanceof Error?It.message:"Please check your billing address and try again.";Rt(Oe),fe.current="idle",h(null),tt?.(It instanceof At.FloPayError?It:new At.FloPayError(Oe,"api_error"))})}),K=lt.on("complete",async ie=>{sr(ie.sessionId??jn.current.sessionId),fe.current="terminal",h("success"),await new Promise(Ze=>setTimeout(Ze,Tn)),!po.current&&(po.current=!0,jn.current.onComplete?.({status:"succeeded",paymentIntentId:ie.intentId,checkoutMethod:"card"}))}),le=lt.on("decline",async ie=>{let{updateError:Ze,emitDecline:vt}=jn.current,Rt=ie.message??"Your payment was declined. Please try another card or contact your bank.";fe.current="terminal",Ze(Rt),h("error"),vt("card",Rt,ie.declineReason?{declineCode:ie.declineReason}:void 0),await new Promise(tt=>setTimeout(tt,hn)),!a&&(fe.current="idle",h(null))}),q=lt.on("error",async ie=>{let{updateError:Ze,onError:vt}=jn.current,Rt=ie.message??"There was a problem processing your payment. Please try again.";fe.current="terminal",Ze(Rt),h("error"),vt?.(new At.FloPayError(Rt,"api_error")),await new Promise(tt=>setTimeout(tt,hn)),!a&&(fe.current="idle",h(null))});return()=>{a=!0,W.current&&(clearTimeout(W.current),W.current=null),fe.current="idle",b(),K(),le(),q()}},[Ie,lt]);let gn=!!He?.clientId,pr=Array.isArray(g),Tr=pr&&g.length>0,ui=pr&&g.includes("paypal"),{expressMethods:Mr,paymentElementMethods:mr}=(0,r.useMemo)(()=>(0,w.partitionStripeMethods)(g,{excludePaypal:gn}),[g,gn]),Vo=gn||!!Ke,pi=(0,r.useMemo)(()=>Vo?Mr.filter(a=>a!=="paypal"):Mr,[Mr,Vo]),mi=(0,r.useMemo)(()=>{let a=[];return j&&a.push("apple_pay"),pe&&a.push("google_pay"),a},[j,pe]),Br=pr?pi:mi,yi=F&&Br.length>0,mo=qt?Ye:xe,Ar=(0,r.useMemo)(()=>{let a=mo?.trim().toUpperCase();return a?ce?mr.filter(b=>{let K=ce[b];return!K||K.length===0||K.includes(a)}):(0,w.filterStripeMethodsByCountry)(mr,mo):mr},[mr,mo,ce]),yo=(0,r.useMemo)(()=>({mode:"payment",amount:ge,currency:Ne.toLowerCase(),paymentMethodCreation:"manual",appearance:rn}),[ge,Ne,rn]),[Ko,Ho]=(0,r.useState)("loading"),[Wo,Yo]=(0,r.useState)("loading"),[Go,Jo]=(0,r.useState)("loading"),[fi,fo]=(0,r.useState)(!1),[Xo,go]=(0,r.useState)("loading"),[Fr,gi]=(0,r.useState)();(0,r.useEffect)(()=>{gi(xa())},[]);let Zo=_&&(gn||(pr?ui:Fr===!1)),Qo=F&&yi,yr=Zo&&gn,ea=Xo==="retrying"||Xo==="exhausted",fr=Zo&&!!de&&(!gn||ea),gr=Qo&&!!Re,hr=F&&Tr&&Ar.length>0&&!!Re,hi=yr&&!ea?fi:fr&&za(Ko),Pi=gr&&za(Wo),bi=hr&&Go!=="load_error",ta=a=>a==="loading"||a==="ready",na=yr||fr&&ta(Ko)||gr&&ta(Wo)||hr&&Go!=="load_error",Dr=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!Dr.current){if(!F&&!_){Dr.current=!0;let a=new At.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(a),be(a.message)}else if(!F&&_&&!gn&&!de){Dr.current=!0;let a=new At.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(a),be(a.message)}else if(Fr!==void 0&&!Xe&&!na){Dr.current=!0;let a=new At.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});p?.(a),be(a.message)}}},[F,_,gn,de,Fr,Xe,na,p,be]);let ra=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(ra.current||!Tr)return;let a=[];j!==!0&&a.push("showApplePay"),pe!==!0&&a.push("showGooglePay"),a.length!==0&&(ra.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.`))},[Tr,j,pe]);let oa=(0,r.useCallback)((a,b)=>st.applyInlineSessionPatch?st.applyInlineSessionPatch(a).then(K=>({error:null,sessionId:K.sessionId||e,nonce:K.session?.clientSecret||t})).catch(K=>{let le=Na(b,K);return be(le.message),p?.(le),{error:le,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[st.applyInlineSessionPatch,t,p,e,be]),an=(0,r.useCallback)(async a=>{if(!Ce)return{proceed:!0};try{let b=await Ce({method:a,sessionId:e||void 0,createSession:st.inlineSessionDraft});if(b===!1)return{proceed:!1};if(b&&typeof b=="object"){b.account&&zn(le=>({...le??{},...b.account}));let K=await oa(b,a);return K.error?{proceed:!1,accountPatch:b.account}:{proceed:!0,accountPatch:b.account,sessionId:K.sessionId,nonce:K.nonce}}return{proceed:!0}}catch(b){let K=Na(a,b);return be(K.message),p?.(K),{proceed:!1}}},[oa,st.inlineSessionDraft,Ce,p,e,be]),aa=(0,r.useCallback)(async(a,b)=>{if(U.current)return;U.current=!0,Wt(!0),h("processing"),be(null);let K=b?.sessionId??e,le=b?.nonce??t,q=Eo(J,b?.accountPatch),ie=b?.completionPaymentMethodId??Wr(a),Ze=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let Rt=await new dn.PaymentAPI(N).processPayment(q.userId??"",{sessionId:K,nonce:le,tokenizedData:Ze,accountData:{userId:q.userId??"",email:q.email??"",firstName:q.firstName??"",lastName:q.lastName??"",...ae?(()=>{let Oe=Mt.current,Zt=(0,w.isAVSFieldVisible)(ae.state,Oe),Qt=(0,w.isAVSFieldVisible)(ae.address_line_1,Oe),Wn=(0,w.isAVSFieldVisible)(ae.postal_code,Oe),Yn=Qt&&!Zt&&Wn?(0,w.getStateFromPostalCode)(Oe,(wt.current??"").trim()):null,Et=Zt?yn.current:Yn;return{country:Oe,...Wn&&wt.current?{zip:wt.current}:{},...(0,w.isAVSFieldVisible)(ae.city,Oe)&&Gt.current?{city:Gt.current}:{},...Et?{state:Et}:{},...Qt&&Yt.current?{addressLine1:Yt.current}:{},...(0,w.isAVSFieldVisible)(ae.address_line_2,Oe)&&Dt.current?{addressLine2:Dt.current}:{}}})():{}},chv:E,avsCheck:Pe??!1,checkoutType:I,checkoutLayout:oe,avsConfig:ae?{country:(0,w.isAVSFieldVisible)(ae.country,Mt.current),postal_code:(0,w.isAVSFieldVisible)(ae.postal_code,Mt.current),address_line_1:(0,w.isAVSFieldVisible)(ae.address_line_1,Mt.current),address_line_2:(0,w.isAVSFieldVisible)(ae.address_line_2,Mt.current),city:(0,w.isAVSFieldVisible)(ae.city,Mt.current),state:(0,w.isAVSFieldVisible)(ae.state,Mt.current)}:void 0});if(Rt.ok){sr(K),h("success"),Q(null),await new Promise(Oe=>setTimeout(Oe,Tn)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ie,checkoutMethod:a.isPaypal?"paypal":"card"});return}let tt=await Rt.json().catch(()=>null);if(tt?.type==="paypal_redirect_required"){let Oe=tt.threeDSecureToken,Zt=tt.paymentMethodId||a.id||"";if(!qe||!Oe){h("error"),be("PayPal authorization required but no token provided.");return}try{let Qt=Ke?.getRawProvider();if(!Qt){be("PayPal is not available.");return}let Wn={return_url:window.location.href};Zt&&(Wn.payment_method=Zt);let{error:Yn}=await Qt.confirmPayment({clientSecret:Oe,confirmParams:Wn,redirect:"if_required"});if(Yn){h("error");let Et=Yn.message??"PayPal payment failed.";be(Et),on("paypal",Et,{code:Yn.code})}}catch(Qt){h("error"),be(Qt instanceof Error?Qt.message:"PayPal authorization failed.")}return}if(tt?.type==="paypal_direct_required"){let Oe=tt.orderId;if(!Oe){h("error"),be("PayPal retry required but no order id provided.");return}let Zt=S.current?.attempts??0;if(Zt>=2){h("error"),be("PayPal payment could not be completed after multiple attempts."),on("paypal","paypal_direct_required retry limit exceeded");return}fo(!1),go("loading"),Q({orderId:Oe,attempts:Zt+1}),h(null);return}h("error");let It=tt?.message??"Payment failed. Please try again.";be(It),on(a.isPaypal?"paypal":"card",It,{code:tt?.code??tt?.gatewayErrorCode,declineCode:tt?.declineCode??tt?.gatewayDeclineReason}),await new Promise(Oe=>setTimeout(Oe,hn))}catch(vt){h("error"),be(vt instanceof Error?vt.message:"An unexpected error occurred"),await new Promise(Rt=>setTimeout(Rt,hn))}finally{Wt(!1),h(null),U.current=!1}},[N,e,t,J,bt,E,qe,Ke,s,p,be,on]),Xt=(0,r.useCallback)((a,b)=>{k?k(a):aa(a,b)},[k,aa]),ia=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(typeof window>"u"||ia.current)return;let a=new URLSearchParams(window.location.search),b=a.get("payment_intent"),K=a.get("payment_intent_client_secret"),le=a.get("redirect_status");if(!b||!K)return;let q=It=>{let Oe=localStorage.getItem(It);if(!Oe)return null;try{return JSON.parse(Oe)}catch{return localStorage.removeItem(It),null}},ie=q(bn)??q(Da),Ze;if(ie?.clientSecret){if(ie.clientSecret!==K)return;Ze={...ie.accountPatch?{accountPatch:ie.accountPatch}:{},...ie.sessionId?{sessionId:ie.sessionId}:{},...ie.nonce?{nonce:ie.nonce}:{}}}else if(ie?.sessionId&&ie.sessionId!==e)return;ia.current=!0,localStorage.removeItem(bn),localStorage.removeItem(Da);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 Rt=ie?.paymentMethodType??ie?.tokenType??"card",tt="card";(async()=>{let It=qe?.getRawProvider();if(!It){let Et="Payment is not available \u2014 please refresh and try again.";be(Et),on(tt,Et);return}if(le==="failed"){let Et="Payment was declined. Please try again.";be(Et),on(tt,Et);return}let{paymentIntent:Oe,error:Zt}=await It.retrievePaymentIntent(K);if(Zt){let Et=Zt.message??"Failed to retrieve payment status.";be(Et),on(tt,Et,{code:Zt.code});return}let Qt=Oe?.status,Wn=Hr(Qt);if(!Oe||!Wn){let Et=Qt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";be(Et),on(tt,Et,{code:Qt??"missing_payment_intent"});return}let Yn=typeof Oe.payment_method=="string"?Oe.payment_method:Oe.payment_method?.id;Xt({id:Yn??ie?.paymentMethodId??ie?.tokenId??Oe.id,type:"card",threeDSecureActionResultTokenId:Oe.id,gateway:ie?.gateway??"stripe",paymentMethodType:Rt},Ze)})()},[e,Xt,qe,be,on]);let ho=(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 Pr=te==="buttons",$t=m?.variables,vi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Po=$t?.colorBackground,Ci=Po&&!vi.has(Po)?Po:void 0,br=c.cardInputBorder??(Pr?"#e5e7eb":"#A4A4FF"),bo=$t?.colorDanger??"#dc2626",Vn=a=>en&&a?bo:br,Lr=(Bt.malformed||Bt.empty)&&(fn||en),Si=Lr?bo:Vn(Pt.zip),vo=c.cardFormContainer?.backgroundColor??Ci??(Pr?"white":"#EDEDFF"),vr=c.cardInputBackground??$t?.colorBackground??"white",Co=nr(H),sa=nr(he),tr=c.nameInput,la=c.cardInputFontSize??os(tr?.fontSize)??$t?.fontSizeBase??"16px",ca=typeof tr?.fontFamily=="string"?tr.fontFamily:$t?.fontFamily??"Poppins, sans-serif",da=Oa(tr?.fontWeight)??400,wi=c.cardInputColor??(typeof tr?.color=="string"?tr.color:void 0)??$t?.colorText??"#262833",ki=c.cardInputPlaceholderColor??"#9ca3af",mt=$t?.borderRadius??"8px",Kn=$t?.borderRadius??c.cardButton?.borderRadius??mt,Hn=$t?.colorPrimary??"#4A49FF",Ri=$t?.colorPrimaryHover??Xr(Hn,.12),So=$t?.colorText??"#262833",ua={fontSize:la,fontFamily:ca,fontWeight:da,color:wi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ii={"--flopay-input-placeholder-color":ki,"--flopay-input-font-size":la,"--flopay-input-font-family":ca,"--flopay-input-font-weight":String(da)},Cr=c.cardFormContainer??{},wo=Cr.padding??(Pr?"0":"1rem"),ko=Cr.borderRadius??mt,Ei=lt&&kt?(0,i.jsx)(qr,{capture:lt,html:kt.html,messageToken:kt.messageToken,expectedOrigin:kt.expectedOrigin,theme:ue,onReady:()=>{if(!ae||typeof document>"u")return;let a=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};a();let b=0,K=window.setInterval(()=>{b+=1;let le=document.activeElement;!!le&&le.tagName==="IFRAME"&&le.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(K)):b>=50&&window.clearInterval(K)},100)},onError:a=>be(a),onValidation:a=>{let b=fe.current;(b==="idle"||b==="validation-window")&&(be(a),a&&fe.current==="validation-window"&&(W.current&&(clearTimeout(W.current),W.current=null),fe.current="idle",h(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"}),pa=(0,i.jsxs)("div",{style:{backgroundColor:vo,borderRadius:ko,...Cr,padding:wo,...Ii,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 @@ ${tt.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),hr&&$n&&(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Te?-2:0},children:[(0,i.jsxs)("button",{type:"button",onClick:Ht,style:{display:"inline-flex",alignItems:"center",gap:vo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:x.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...x.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",...x.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)(rr,{content:Y})]}),aa?(0,i.jsx)("div",{style:{flex:1}}):(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:x.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...x.title},children:(0,i.jsx)(Sr,{content:ce})})]}),!hr&&!aa&&(0,i.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Co,order:Te?-3:0,...x.title},children:(0,i.jsx)(Sr,{content:ce})}),J&&(0,i.jsx)("div",{style:{order:Te?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=je,v=($=!1)=>({backgroundColor:br,border:`1px solid ${jn($)}`,borderRadius:ft,marginTop:"0.5rem",padding:"10px"}),V=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ca}),le=(0,w.getStateOptions)(a);return(0,i.jsxs)(i.Fragment,{children:[(0,w.isAVSFieldVisible)(J.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:$=>{Bt.current=$.target.value,Ie($.target.value)},disabled:P,required:!0,"data-testid":"flopay-address-line1",style:V()})}),(0,w.isAVSFieldVisible)(J.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:bt,onChange:$=>{Yt.current=$.target.value,Ke($.target.value)},disabled:P,"data-testid":"flopay-address-line2",style:V()})}),((0,w.isAVSFieldVisible)(J.city,a)||(0,w.isAVSFieldVisible)(J.state,a))&&(0,i.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,w.isAVSFieldVisible)(J.city,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:br,borderTop:`1px solid ${jn(At.city)}`,borderRight:`1px solid ${jn(At.city)}`,borderBottom:`1px solid ${jn(At.city)}`,borderLeft:`1px solid ${jn(At.city)}`,padding:"10px",borderTopLeftRadius:ft,borderBottomLeftRadius:ft,...(0,w.isAVSFieldVisible)(J.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:ft}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Ot,onChange:$=>{en.current=$.target.value,Rt($.target.value)},disabled:P,required:!0,"data-testid":"flopay-city",style:V()})}),(0,w.isAVSFieldVisible)(J.state,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:br,border:`1px solid ${jn(At.state)}`,padding:"10px",borderTopRightRadius:ft,borderBottomRightRadius:ft,...(0,w.isAVSFieldVisible)(J.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:ft}},children:le?(0,i.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:yn,onChange:$=>{fn.current=$.target.value,Rn($.target.value)},disabled:P,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...V(),cursor:"pointer"},children:[(0,i.jsx)("option",{value:"",children:(0,w.getStateLabel)(a)}),le.map($=>(0,i.jsx)("option",{value:$.code,children:$.name},$.code))]}):(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,w.getStateLabel)(a),autoComplete:"billing address-level1",value:yn,onChange:$=>{fn.current=$.target.value,Rn($.target.value)},disabled:P,required:!0,"data-testid":"flopay-state",style:V()})})]}),((0,w.isAVSFieldVisible)(J.country,a)||(0,w.isAVSFieldVisible)(J.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,w.isAVSFieldVisible)(J.country,a)&&(0,i.jsx)("div",{style:{flex:de==="row"?1:void 0,backgroundColor:br,borderTop:`1px solid ${Pr}`,borderRight:`1px solid ${Pr}`,borderBottom:`1px solid ${Pr}`,borderLeft:`1px solid ${Pr}`,padding:"10px",...de==="row"&&(0,w.isAVSFieldVisible)(J.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:ft,borderBottomLeftRadius:ft,borderRight:"none"}:{borderRadius:ft}},children:(0,i.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:je,onChange:$=>{zt.current=$.target.value,lt($.target.value),ze?.($.target.value),fn.current="",Rn("")},disabled:P,autoComplete:"billing country","data-testid":"flopay-country",style:{...V(),cursor:"pointer"},children:w.COUNTRY_OPTIONS.map($=>(0,i.jsxs)("option",{value:$.code,children:[$.flag," ",$.name]},$.code))})}),(0,w.isAVSFieldVisible)(J.postal_code,a)&&(0,i.jsx)("div",{style:{flex:de==="row"?1:void 0,backgroundColor:br,border:`1px solid ${vi}`,padding:"10px",...de==="row"&&(0,w.isAVSFieldVisible)(J.country,a)?{borderRadius:"0",borderTopRightRadius:ft,borderBottomRightRadius:ft}:{borderRadius:ft}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,w.getPostalCodeLabel)(je),autoComplete:"billing postal-code",value:it,onChange:$=>{ht.current=$.target.value,nt($.target.value),Oe?.($.target.value)},onBlur:()=>Kt(!0),disabled:P,required:It.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:Po,...ca,fontSize:"0.75rem"},children:It.empty?`${(0,w.getPostalCodeLabel)(a)} is required`:Qi(a)})]})})()}),Te&&Re&&(0,i.jsx)("div",{style:{order:-2,width:"100%"},children:Re}),Te&&Ri,pe&&(0,i.jsx)(or,{margin:"0.75rem 0",styleOverride:x.errorBanner,children:pe})]}),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"},ua=a=>$e?!R||!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=${R}`,` directPaypalConfigured=${vn}`,` inAppBrowserDetected=${String(Ar)}`,` shouldRenderDirectPayPal=${mr}`,` shouldRenderStripePayPal=${yr}`,` hasPaypalStripeInstance=${!!qt}`].join(`
39
- `)}):null,pa=a=>$e?!F||!ut?(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=${Be}`,` amountInCents=${Ye}`,` enabledPaymentMethods: ${JSON.stringify(g??[])}`,` enabledPaymentMethodsProvided=${ur}`,` hasEnabledMethods=${xr}`,` expressMethods: ${JSON.stringify(Tr)}`,` walletExpressMethods: ${JSON.stringify(Mr)}`,` paymentElementMethods: ${JSON.stringify(pr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Br)}`,` hasStripeInstance=${!!ut}`,` shouldRenderWallets=${fr}`,` shouldRenderPaymentElement=${gr}`].join(`
40
- `)}):null,ma=ke==="apm-expanding"||ke==="apm-form"||ke==="apm-collapsing",Nr=ke==="apm-expanding"?`flopay-card-enter ${Dt}ms cubic-bezier(0, 0, 0.2, 1) both`:ke==="apm-collapsing"?`flopay-card-exit ${Dt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Or=ct?{...mo,paymentMethodTypes:[ct]}:null;if(ae==="buttons"){let a=ke==="buttons"||ke==="expanding"||ke==="apm-expanding",v=ke==="expanding"||ke==="card"||ke==="collapsing",V=U===void 0?{boxSizing:"border-box",height:Xr,padding:"0 1rem"}:{padding:"0.9rem 1rem"},le=ke==="expanding"||ke==="apm-expanding"?`flopay-buttons-exit ${Dt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:ke==="collapsing"||ke==="apm-collapsing"?`flopay-buttons-enter ${Dt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,$=ke==="expanding"?`flopay-card-enter ${Dt}ms cubic-bezier(0, 0, 0.2, 1) both`:ke==="collapsing"?`flopay-card-exit ${Dt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,i.jsxs)("form",{onSubmit:go,className:S,style:{position:"relative"},children:[(0,i.jsx)(To,{}),Z&&(0,i.jsx)(Sn,{status:Z,errorMessage:pe}),(0,i.jsxs)("div",{style:{display:"grid"},children:[(0,i.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!le?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!le?Ji:{},...le?{animation:le,pointerEvents:"none"}:{}},children:[ua("flopay-direct-paypal-gate-debug"),pa("flopay-stripe-gate-debug"),mr&&tt&&(0,i.jsxs)(i.Fragment,{children:[q&&(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)(Rr,{sessionId:e,nonce:t,billingApiUrl:z,email:X.email,clientId:tt.clientId,environment:tt.environment,currency:Be.toUpperCase(),isSubscription:et,onTokenizedBody:Xt,onComplete:s,onErrorChange:K,onDecline:c,onTechnicalFailure:Qn,onButtonClick:we,runBeforeButtonClick:an,isProcessing:P,onLoadStateChange:yo,onInitializationStateChange:fo,session:m??null,existingOrderId:q?.orderId,debug:$e},q?.orderId??"fresh")]}),yr&&(0,i.jsx)(mt.Elements,{stripe:qt,options:rn,children:(0,i.jsx)(Oa,{sessionId:e,nonce:t,email:X.email,billingApiUrl:z,onTokenizedBody:Xt,onErrorChange:K,isProcessing:P,onButtonClick:we,onDecline:c,onTechnicalFailure:Qn,runBeforeButtonClick:an,onLoadStateChange:Ko,placeholderBorderRadius:Kn})}),fr?(0,i.jsx)(mt.Elements,{stripe:ut,options:nn,children:(0,i.jsx)(za,{sessionId:e,nonce:t,email:X.email,billingApiUrl:z,intentKind:ye>0?"payment":"setup",expressMethods:Mr,onTokenizedBody:Xt,onErrorChange:K,onButtonClick:we,onDecline:c,onTechnicalFailure:Qn,runBeforeButtonClick:an,onLoadStateChange:Ho,placeholderBorderRadius:Kn})}):Xo?(0,i.jsx)("div",{style:{height:Xr,borderRadius:Kn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,gr&&(0,i.jsx)(Ua,{sessionId:e,nonce:t,email:X.email,billingName:[X.firstName,X.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:z,paymentElementMethods:Br,stripeInstance:ut,paymentElementBaseOptions:mo,onTokenizedBody:Xt,onErrorChange:K,onButtonClick:we,onDecline:c,runBeforeButtonClick:an,onLoadStateChange:Yo,isProcessing:P,submitButtonColor:Vn,submitButtonBorderRadius:ft,submitButtonStyle:x.submitButton,onExpandApm:_,expandedApmMethod:ct,themeId:O,buttonAppearance:{backgroundColor:x.cardButton?.backgroundColor,borderColor:x.cardInputBorder,textColor:x.cardButton?.color,borderRadius:Kn}}),Te&&(0,i.jsx)("button",{type:"button",onClick:async()=>{P||!(await an("card")).proceed||(we?.("card"),Zn())},disabled:P,style:{width:"100%",...V,...x.cardButton,...Ao({themeBundle:Ce,resolvedPrimaryColor:Vn,resolvedBorderRadius:ft,submitButtonStyle:x.submitButton,explicitPrimaryColor:jt?.colorPrimary}),fontSize:x.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:P?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:P?.6:1},onMouseEnter:ie=>{!P&&(Ce||jt?.colorPrimary)&&(ie.currentTarget.style.backgroundColor=wi)},onMouseLeave:ie=>{(Ce||jt?.colorPrimary)&&(ie.currentTarget.style.backgroundColor=Vn)},onMouseDown:ie=>{ie.currentTarget.style.transform="scale(0.985)"},onMouseUp:ie=>{ie.currentTarget.style.transform="scale(1)"},children:(0,i.jsx)(nr,{content:U})}),pe&&ke==="buttons"&&(0,i.jsx)(or,{margin:"0.25rem 0",styleOverride:x.errorBanner,children:pe})]}),Te&&v&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...$?{animation:$}:{},...ke==="collapsing"?{pointerEvents:"none"}:{}},children:da}),F&&ma&&ct&&Or&&ut&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...Nr?{animation:Nr}:{},...ke==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:bo,borderRadius:wo,...vr,padding:So},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:j,style:{display:"inline-flex",alignItems:"center",gap:vo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:x.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...x.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",...x.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)(rr,{content:Y})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:x.titleFontSize??"1.05rem",color:Co,paddingRight:80,...x.title},children:`Pay with ${(0,w.getStripeMethodDisplayName)(ct)}`})]}),(0,i.jsx)(mt.Elements,{stripe:ut,options:Or,children:(0,i.jsx)(Mo,{method:ct,sessionId:e,nonce:t,email:X.email,billingName:[X.firstName,X.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:z,onTokenizedBody:Xt,onErrorChange:K,onDecline:c,onCancel:j,runBeforeButtonClick:an,onButtonClick:we,isProcessing:P,submitButtonColor:Vn,submitButtonBorderRadius:ft,submitButtonStyle:x.submitButton,errorText:pe})},ct)]})})]})]})}return ma&&ct&&Or&&ut&&F?(0,i.jsxs)("form",{onSubmit:go,className:S,style:{position:"relative"},children:[(0,i.jsx)(To,{}),Z&&(0,i.jsx)(Sn,{status:Z,errorMessage:pe}),(0,i.jsx)("div",{style:{...Nr?{animation:Nr}:{},...ke==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:bo,borderRadius:wo,...vr,padding:So},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:j,style:{display:"inline-flex",alignItems:"center",gap:vo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:x.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...x.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",...x.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)(rr,{content:Y})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:x.titleFontSize??"1.05rem",color:Co,paddingRight:80,...x.title},children:`Pay with ${(0,w.getStripeMethodDisplayName)(ct)}`})]}),(0,i.jsx)(mt.Elements,{stripe:ut,options:Or,children:(0,i.jsx)(Mo,{method:ct,sessionId:e,nonce:t,email:X.email,billingName:[X.firstName,X.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:z,onTokenizedBody:Xt,onErrorChange:K,onDecline:c,onCancel:j,runBeforeButtonClick:an,onButtonClick:we,isProcessing:P,submitButtonColor:Vn,submitButtonBorderRadius:ft,submitButtonStyle:x.submitButton,errorText:pe})},ct)]})})]}):(0,i.jsxs)("form",{onSubmit:go,className:S,style:{position:"relative"},children:[(0,i.jsx)(To,{}),Z&&(0,i.jsx)(Sn,{status:Z,errorMessage:pe}),(0,i.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ua("flopay-direct-paypal-gate-debug-default"),pa("flopay-stripe-gate-debug-default"),mr&&tt&&(0,i.jsxs)(i.Fragment,{children:[q&&(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)(Rr,{sessionId:e,nonce:t,billingApiUrl:z,email:X.email,clientId:tt.clientId,environment:tt.environment,currency:Be.toUpperCase(),isSubscription:et,onTokenizedBody:Xt,onComplete:s,onErrorChange:K,onDecline:c,onTechnicalFailure:Qn,onButtonClick:we,runBeforeButtonClick:an,isProcessing:P,onLoadStateChange:yo,onInitializationStateChange:fo,session:m??null,existingOrderId:q?.orderId,debug:$e},q?.orderId??"fresh")]}),yr&&(0,i.jsx)(mt.Elements,{stripe:qt,options:rn,children:(0,i.jsx)(Oa,{sessionId:e,nonce:t,email:X.email,billingApiUrl:z,onTokenizedBody:Xt,onErrorChange:K,isProcessing:P,onButtonClick:we,onDecline:c,onTechnicalFailure:Qn,runBeforeButtonClick:an,onLoadStateChange:Ko,placeholderBorderRadius:Kn})}),fr&&(0,i.jsx)(mt.Elements,{stripe:ut,options:nn,children:(0,i.jsx)(za,{sessionId:e,nonce:t,email:X.email,billingApiUrl:z,intentKind:ye>0?"payment":"setup",expressMethods:Mr,onTokenizedBody:Xt,onErrorChange:K,onButtonClick:we,onDecline:c,onTechnicalFailure:Qn,runBeforeButtonClick:an,onLoadStateChange:Ho,placeholderBorderRadius:Kn})}),gr&&(0,i.jsx)(Ua,{sessionId:e,nonce:t,email:X.email,billingName:[X.firstName,X.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:z,paymentElementMethods:Br,stripeInstance:ut,paymentElementBaseOptions:mo,onTokenizedBody:Xt,onErrorChange:K,onButtonClick:we,onDecline:c,runBeforeButtonClick:an,onLoadStateChange:Yo,isProcessing:P,submitButtonColor:Vn,submitButtonBorderRadius:ft,submitButtonStyle:x.submitButton,themeId:O,onExpandApm:_,expandedApmMethod:ct,buttonAppearance:{backgroundColor:x.cardButton?.backgroundColor,borderColor:x.cardInputBorder,textColor:x.cardButton?.color,borderRadius:Kn}})]}),Te&&(gi||fi||hi)&&(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"}})]}),Te&&da]})}var lr=require("@flopay/js"),Qe=require("@flopay/shared");var Er="card";async function os(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 as(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 Ha(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 is(e){return e.status==="succeeded"||e.status==="declined"}async function Wa(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 y=new AbortController,E=()=>y.abort();e.signal?.aborted?y.abort():e.signal?.addEventListener("abort",E);let S=window.setTimeout(()=>y.abort(),l);try{let M=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:y.signal});if(!M.ok)return{status:"unknown"};let d=await M.json().catch(()=>null);return ss(d)}catch{return{status:"unknown"}}finally{window.clearTimeout(S),e.signal?.removeEventListener("abort",E)}},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 k=document.createElement("iframe");k.setAttribute("title","Card authentication"),k.setAttribute("allow","payment"),k.tabIndex=0,k.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),k.src=e.nextActionRedirectUrl,c.appendChild(k),document.body.appendChild(c),k.focus();let N=null;try{N=new URL(e.billingApiUrl,window.location.href).origin}catch{N=null}try{let y=await new Promise((E,S)=>{let M=!1,d=0,f=0,R=0,F=!1,g=()=>{window.clearTimeout(d),window.clearInterval(f),window.clearTimeout(R),window.removeEventListener("message",ae),k.removeEventListener("load",Q),e.signal?.removeEventListener("abort",Pe)},H=async()=>{if(!(M||F)){F=!0;try{let O=await s();if(M||!is(O))return;M=!0,g(),E(O)}finally{F=!1}}},Q=()=>{window.clearTimeout(R),R=window.setTimeout(()=>{H()},250)},Pe=()=>{M||(M=!0,g(),S(new Qe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ae=O=>{if(O.source!==k.contentWindow||N&&O.origin!==N)return;let te=O.data;!te||typeof te!="object"||te.source!=="flopay-vault-3ds-return"||M||(M=!0,g(),E(null))};d=window.setTimeout(()=>{M||(M=!0,g(),S(new Qe.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),f=window.setInterval(()=>{H()},n),k.addEventListener("load",Q),window.addEventListener("message",ae),e.signal?.addEventListener("abort",Pe),e.signal?.aborted&&Pe()});return y||await s()}finally{c.parentNode?.removeChild(c),u?.isConnected&&u.focus()}}function ss(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function On(e,t="Payment failed. Please try again.",n){let l=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,s=Ln(o)??o;return kn(new Qe.FloPayError(s,"api_error",{code:e?.gatewayErrorCode}),l)}function Fo(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 ls(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 Ya(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 k=c,N=[k.stripeClientSecret,k.clientSecret];for(let y of N)if(typeof y=="string"&&y.length>0&&(!t?.requirePaymentIntentClientSecret||eo(y)))return y}}}}async function cs({billingApiUrl:e,sessionId:t,nonce:n,responseJson:l}){let o=Ya(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 lr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(eo(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function cr({billingApiUrl:e,sessionId:t,session:n,nonce:l,tokenizedData:o,returnUrl:s,telemetry:u}){let c=e.replace(/\/+$/,""),k=t??n.id,N=l??n.clientSecret,y=n.customer?.id??n.accountData?.userId??"",E=n.customer?.email??n.accountData?.email??"",S=n.customer?.firstName??n.accountData?.firstName??"",M=n.customer?.lastName??n.accountData?.lastName??"",d=n.customer?.country??n.accountData?.country??void 0,f=n.customer?.zip??n.accountData?.zip??void 0,R=new lr.PaymentAPI(c,u===!1?{telemetry:!1}:void 0),F=await ls(()=>R.processPayment(y,{sessionId:k,nonce:N,tokenizedData:o,accountData:{userId:y,email:E,firstName:S,lastName:M,country:d,zip:f},returnUrl:s??Fo(n)}));if(F.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Hr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let g=await F.json().catch(()=>null);if(g?.type==="paypal_redirect_required"||g?.type==="3ds_required"){let H=Ya(g);if(!H)throw new Qe.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:g.type,threeDSecureToken:H,paymentMethodId:g.paymentMethodId}}if(g?.gatewayErrorCode==="authentication_required"){let H=await cs({billingApiUrl:c,sessionId:k,nonce:N,responseJson:g});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(g?.message??"Payment failed. Please try again.","api_error",{code:g?.code??g?.gatewayErrorCode,declineCode:g?.declineCode??g?.gatewayDeclineReason})}async function to(e,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:u,returnUrl:c,telemetry:k}){let N=t?.getRawProvider();if(!N)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 y=(0,Qe.isSetupIntentClientSecret)(e.threeDSecureToken),E=null,S=e.paymentMethodId,M=await os(N,e.threeDSecureToken,y);if(M){if(M.error)throw kn(new Qe.FloPayError(M.error.message??`Failed to retrieve 3DS ${y?"setup":"payment"} status.`,"api_error",{code:M.error.code}),"card");let f=M.intent;!S&&f?.payment_method&&(typeof f.payment_method=="string"?S=f.payment_method:"id"in f.payment_method&&(S=f.payment_method.id??void 0))}let d=S?await as(N,e.threeDSecureToken,{payment_method:S,return_url:c??Fo(u)??window.location.href},y):null;if(d){if(d.error)throw kn(new Qe.FloPayError(d.error.message??"3DS authentication failed.","api_error",{code:d.error.code}),"card");E=d.intent}else{let f=await N.handleNextAction({clientSecret:e.threeDSecureToken});if(f.error)throw kn(new Qe.FloPayError(f.error.message??"3DS authentication failed.","api_error",{code:f.error.code}),"card");E=(y?f.setupIntent:f.paymentIntent)??null}if(E&&(E.status==="requires_capture"||E.status==="succeeded"||E.status==="processing")){let f=await cr({billingApiUrl:o,sessionId:s,session:u,telemetry:k,tokenizedData:{id:E.id,type:"card",threeDSecureActionResultTokenId:E.id},returnUrl:c});return f.type==="success"?{...f.result,paymentIntentId:f.result.paymentIntentId??E.id,paymentMethodId:f.result.paymentMethodId??S}:to(f,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:u,returnUrl:c,telemetry:k})}throw kn(new Qe.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let y=(n??t)?.getRawProvider();if(!y)throw kn(new Qe.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:S}=await y.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:E}=await y.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Fo(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(E)throw kn(new Qe.FloPayError(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Qe.FloPayError("Unsupported payment redirect state.","api_error")}function Gn(e){if(e instanceof Qe.FloPayError){let l=Ln(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=Ln(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,lr.loadFloPay)(e,{billingApiUrl:n,locale:l,telemetry:o}),s?(0,lr.loadFloPay)(t,{billingApiUrl:n,locale:l,telemetry:o}).catch(k=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",k),null)):Promise.resolve(null)]);return{flopay:u,paypalFlopay:t?s?c:u:null}}var C=require("react/jsx-runtime"),dr=44,Uo="flopay_checkout_saved_payment_resume",so=new Map,oo=new Map;function Ga(e,t){t.settled&&t.consumers===0&&so.get(e)===t&&so.delete(e)}function ds(e,t,n){let l=oo.get(e);if(l&&(!l.sdkGeneratedIdempotencyKey||!t||l.sdkGeneratedIdempotencyKey===t))return l.attempt;let o=n(),s={attempt:o,sdkGeneratedIdempotencyKey:t};oo.set(e,s);let u=()=>{oo.get(e)===s&&oo.delete(e)};return o.then(u,u),o}function _r(e){return new Promise(t=>setTimeout(t,e))}function ao(e,t,n){let l=Ur({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:xe.SDK_VERSION,enabled:t!==!1});return l.beginCheckout(n),l}function io(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Do(e,t,n,l,o){let s=ao(e,t,n);s.error({errorCode:l,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),io(s)}function us(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 zo(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function Lo(e){return!e||e.data.stripe?.publishableKey?!1:!!zo(e)?.clientId}function An(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ps(){if(!An())return null;try{let e=window.sessionStorage.getItem(Uo);return e?JSON.parse(e):null}catch{return null}}function Ja(e){if(An())try{window.sessionStorage.setItem(Uo,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function No(){if(An())try{window.sessionStorage.removeItem(Uo)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var $o=":idempotency-key";function ms(e){if(!An())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function ys(e,t,n){if(An())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 Za(e){if(An())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function fs(e){if(An())try{return window.sessionStorage.getItem(e+$o)??void 0}catch{return}}function gs(e,t){if(An())try{window.sessionStorage.setItem(e+$o,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function hs(e){if(Za(e),!!An())try{window.sessionStorage.removeItem(e+$o)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Ps(){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 Xa(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 bs(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 Oo(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function lo({sessionId:e,nonce:t,createSession:n,billingApiUrl:l,telemetry:o,appearance:s,locale:u,loading:c,error:k,onComplete:N,onError:y,onDecline:E,onCountryChange:S,onZipChange:M,showPayPal:d=!0,showStripe:f=!0,showApplePay:R=!0,showGooglePay:F=!0,debug:g=!1,layout:H,theme:Q,buttonsTheme:Pe,buttonsStyles:ae,cardButtonContent:O,cardBackButtonContent:te,cardTitleContent:W,showSecurityFooter:be,onButtonClick:U,onBeforeButtonClick:Y,enableAVS:ce,cardFieldOrder:De,cardPreFormSlot:we,avsLayout:Se,className:ne,initialErrorMessage:ve=null,children:Re,checkoutMode:de,confirmLabel:Ne,renderConfirmButton:Me,onSessionCompleted:Ee}){let I=(0,xe.resolveBillingApiUrl)(l),se=(0,D.useMemo)(()=>(0,xe.resolveTheme)(Q),[Q]),me=s??se?.appearance,ze=n?"embedded_checkout":"standard_checkout",Oe=Re?"custom_layout":H==="buttons"?"buttons_layout":"default_layout",[ee,A]=(0,D.useState)(null),[G,ye]=(0,D.useState)(null),Be=(0,D.useRef)(null),[st,tt]=(0,D.useState)(null),et=(0,D.useRef)(null),[m,$e]=(0,D.useState)(null),[Ue,We]=(0,D.useState)(e??""),qe=e??Ue,Wt=n?"":qe,[Pt,kt]=(0,D.useState)(!0),[h,_e]=(0,D.useState)(null),[je,lt]=(0,D.useState)("full"),[it,nt]=(0,D.useState)(!1),[Je,Ie]=(0,D.useState)(ve),[bt,Ke]=(0,D.useState)(null),[Ot,Rt]=(0,D.useState)(null),[yn,Rn]=(0,D.useState)(void 0),[In,zn]=(0,D.useState)(""),[ht,zt]=(0,D.useState)(!1),[Bt,Yt]=(0,D.useState)("loading"),[en,fn]=(0,D.useState)(0),J=(0,D.useRef)(!1),Fn=(0,D.useRef)(!1),gn=(0,D.useRef)(!1),Ut=(0,D.useRef)(null),Mt=(0,D.useMemo)(()=>({checkoutMode:de??je,layout:Re?"unknown":H==="buttons"?"buttons":"embedded"}),[de,Re,je,H]),B=(0,D.useRef)(N);B.current=N;let Xe=(0,D.useRef)(y);Xe.current=y;let Te=(0,D.useRef)(E);Te.current=E,(0,D.useEffect)(()=>{Tt(G)?.setCheckoutContext(Mt),st&&st!==G&&Tt(st)?.setCheckoutContext(Mt)},[G,st,Mt]);let Dn=(0,D.useRef)(Ee);Dn.current=Ee;let Ve=(0,D.useCallback)(_=>{Yt(_),!(_!=="exhausted"||gn.current)&&(gn.current=!0,Xe.current?.(new xe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Un=(0,D.useCallback)(()=>{Yt("retrying"),fn(_=>_+1)},[]);(0,D.useEffect)(()=>{Yt("loading"),fn(0),gn.current=!1},[qe]),(0,D.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:xe.SDK_VERSION,checkout_type:ze,checkout_layout:Oe,billing_api_url:I})},[Oe,ze,I]);let hn=(0,D.useMemo)(()=>n?En(n,!0):"",[n]),Pn=(0,D.useMemo)(()=>In===hn?yn:void 0,[yn,In,hn]),rt=(0,D.useMemo)(()=>n?Ro(n,Pn):void 0,[n,Pn]),It=de??rt?.checkoutMode??"full",$t=(0,D.useMemo)(()=>rt?{...rt,checkoutMode:It}:void 0,[rt,It]);(0,D.useEffect)(()=>{Rn(void 0),zn(hn)},[hn]),(0,D.useEffect)(()=>{Ie(ve)},[ve]);let At=(0,D.useCallback)((_,j,Z)=>{pt(()=>{Te.current?.(wt(_,j,Z))})},[pt]),Gt=(0,D.useCallback)(async(_,j)=>{Ie(null),Rt(null),Ke("processing");let Z=j?.sessionId??_.id,oe=Be.current??et.current,ue=Tt(oe),q=oe?null:ao(I,o,Mt),b={log:P=>{ue?ue.log(P):q?.log(P)},error:P=>{ue?ue.error(P):q?.error(P)},terminal:P=>{ue?ue.terminal(P):q?.terminal(P)},performance:P=>{ue?ue.performance(P):q?.performance(P)},now:()=>ue?.now()??q?.now()??0,elapsed:P=>ue?.elapsed(P)??Math.max(0,(q?.now()??P)-P)},re=b.now(),z=!!(j?.initialAutoProcessingError||j?.initialAutoProcessingPending),pe=!1,Ce,x=()=>{pe||(pe=!0,z=!0,Ce=b.now(),b.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},dt=!1,L=()=>{dt||(dt=!0,b.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),b.performance({stage:"processing",durationMs:b.elapsed(re),durationMode:"machine",paymentMethodCategory:"saved"}),Ce!==void 0&&b.performance({stage:"recovery",durationMs:b.elapsed(Ce),durationMode:"machine",paymentMethodCategory:"saved"}))};b.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),b.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),z&&x();let p;try{let P=Ha(j?.initialAutoProcessingError),ge;if(P)x(),P.type==="paypal_redirect_required"&&Ut.current?.publishableKey&&Ja({sessionId:Z,publishableKey:Ut.current.publishableKey,paypalPublishableKey:Ut.current.paypalPublishableKey}),ge=await to(P,{flopay:Be.current,paypalFlopay:et.current,attempt3DS:j?.attempt3DS,billingApiUrl:I,sessionId:Z,session:_,telemetry:!1}),P.type==="paypal_redirect_required"&&No();else if(j?.initialAutoProcessingPending){let He=await new Jn.PaymentAPI(I,{telemetry:!1}).waitForCheckoutSessionCompletion(j.initialAutoProcessingPending.sessionId,{initialDelayMs:j.initialAutoProcessingPending.retryAfterMs});if(He.data.session?.status!=="complete")throw new xe.FloPayError("Automatic payment failed. Please try again.","api_error",{code:He.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});ge={status:"succeeded"}}else{if(j?.initialAutoProcessingError)throw On(j.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:j.initialAutoProcessingError.checkoutMethod});if(j?.fromCreateSession)return j?.fallbackToFull&&(lt("full"),Xa("full")),!1;{let X=await cr({billingApiUrl:I,sessionId:Z,session:_,telemetry:!1});X.type==="success"?ge=X.result:(x(),X.type==="paypal_redirect_required"&&Ut.current?.publishableKey&&Ja({sessionId:Z,publishableKey:Ut.current.publishableKey,paypalPublishableKey:Ut.current.paypalPublishableKey}),ge=await to(X,{flopay:Be.current,paypalFlopay:et.current,attempt3DS:j?.attempt3DS,billingApiUrl:I,sessionId:Z,session:_,telemetry:!1}),X.type==="paypal_redirect_required"&&No())}}Z&&ir(Z),L(),z&&(b.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),b.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Ke("success"),await _r(Tn),p=()=>B.current?.(ge)}catch(P){let ge=Gn(P),X=ge.checkoutMethod??Er;return Ie(ge.message),Rt(ge.message),j?.fallbackToFull&&(b.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),lt("full"),Xa("full")),L(),!!(ge.declineCode||ge.code?.toLowerCase().includes("declin"))?b.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):ge.type==="validation_error"?b.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):b.error({errorCode:z?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:z?"recovery":"processing",paymentMethodCategory:"saved"}),pt(()=>Xe.current?.(ge)),At(X,ge,{code:ge.code,declineCode:ge.declineCode}),Ke("error"),await Promise.allSettled([_r(Cn),j?.ensureProvidersReady?j.ensureProvidersReady():Promise.resolve()]),z&&(b.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{L(),q&&io(q),Ke(null),Rt(null)}return pt(p),!0},[At,pt,Gn,I,o,Mt]);(0,D.useEffect)(()=>{if(typeof window>"u"||Fn.current)return;let _=new URLSearchParams(window.location.search),j=_.get("payment_intent_client_secret");if(!j)return;let Z=ps();Z&&(Fn.current=!0,(async()=>{let oe,ue=0;Ie(null),Rt(null),Ke("processing"),nt(!0);try{if(_.get("redirect_status")==="failed")throw Object.assign(new xe.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:q,paypalFlopay:b}=await ro({publishableKey:Z.publishableKey,paypalPublishableKey:Z.paypalPublishableKey,billingApiUrl:I,locale:u,telemetry:o});oe=Tt(b??q),ue=oe?.now()??0,oe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),oe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let re=(b??q)?.getRawProvider();if(!re)throw Object.assign(new xe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:z,error:pe}=await re.retrievePaymentIntent(j);if(pe)throw Object.assign(new xe.FloPayError(pe.message??"Failed to retrieve PayPal payment status.","api_error",{code:pe.code}),{checkoutMethod:"paypal"});let Ce=Ra(z?.status);if(!z||Ce==="failed")throw Object.assign(new xe.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let x=typeof z.payment_method=="string"?z.payment_method:z.payment_method?.id,dt=Ce;if(Z.sessionId){let P=(await new Jn.PaymentAPI(I,{telemetry:!1}).getUnifiedCheckoutSession(Z.sessionId)).data.session;if(P&&P.status!=="complete"){let ge=await cr({billingApiUrl:I,sessionId:Z.sessionId,session:P,telemetry:!1,tokenizedData:{id:x??z.id,type:"card",threeDSecureActionResultTokenId:z.id,isPaypal:!0}});if(ge.type!=="success")throw Object.assign(new xe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});dt=ge.result.status}}Z.sessionId&&ir(Z.sessionId),oe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),oe?.performance({stage:"redirect_resume",durationMs:oe.elapsed(ue),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),oe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ke("success"),await _r(Tn),pt(()=>B.current?.({status:dt,paymentIntentId:z.id,paymentMethodId:x,checkoutMethod:"paypal"}))}catch(q){let b=Gn(q),re=b.checkoutMethod??"paypal",z=!!(b.declineCode||b.code?.toLowerCase().includes("declin"));if(oe)oe.performance({stage:"redirect_resume",durationMs:oe.elapsed(ue),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),z?oe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):oe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(z){let pe=ao(I,o,Mt);pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),io(pe)}else Do(I,o,Mt,"REDIRECT_RESUME_FAILED","redirect_resume");Ie(b.message),Rt(b.message),pt(()=>Xe.current?.(b)),At(re,b,{code:b.code,declineCode:b.declineCode}),Ke("error"),await _r(Cn)}finally{No(),Ps(),Ke(null),Rt(null),nt(!1)}})())},[At,pt,u,Gn,I,o]);let tn=(0,D.useRef)(null);function En(_,j=!1){let Z=_?.account?.email?.trim().toLowerCase()??"",oe={c:_?.clientId,cur:_?.currency??"",a:{e:Z,u:Z?"":_?.account?.userId??"",country:_?.account?.country??""},successUrl:_?.successUrl,cancelUrl:_?.cancelUrl,p:_?.products?.map(b=>Oo(`${b.type??""}:${b.code??b.providerItemId??b.providerPlanId??""}`,b)).sort(),i:_?.items?.map(b=>Oo(b.code??b.providerItemId??"",b)).sort(),s:_?.subscriptions?.map(b=>Oo(b.code??b.providerPlanId??"",b)).sort(),couponCodes:_?.couponCodes?[..._.couponCodes].sort():void 0,...j?{tagsData:_?.tagsData,utmMetadata:_?.utmMetadata,tokenizedData:_?.tokenizedData,checkoutMode:_?.checkoutMode??"full"}:{}},ue=JSON.stringify(oe),q=0;for(let b=0;b<ue.length;b++)q=(q<<5)-q+ue.charCodeAt(b)|0;return`flopay_session_${Math.abs(q).toString(36)}`}let Kt=(0,D.useMemo)(()=>$t?En($t):"",[$t]),Ft=(0,D.useRef)($t);Ft.current=$t,(0,D.useEffect)(()=>{We(e??"")},[e]),(0,D.useEffect)(()=>{J.current=!1,Ie(ve),Rt(null),Ke(null)},[Kt,ve,e]);async function Jt(_,j){let Z=ao(I,o,Mt),oe=new Jn.PaymentAPI(I,{telemetry:!1});try{let ue=_.idempotencyKey!==void 0?(0,xe.resolveIdempotencyKey)(_.idempotencyKey):void 0,q=ue??fs(j),b,re=!1,z=ms(j);Z.log({name:z?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let pe=z?.sid??null,Ce=null;if(pe)try{if(Ce=await oe.getUnifiedCheckoutSession(pe,z?.nonce),Ce.data.session?.status==="complete"){if(Eo(pe))return{sid:pe,result:Ce};hs(j),pe=null,Ce=null,re=!0}}catch{Z.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Za(j),pe=null}if(!pe){!ue&&(re||!q)&&(q=(0,xe.resolveIdempotencyKey)(),b=q),q&&gs(j,q);let x=Z.now(),dt=0;Z.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let L={..._,idempotencyKey:q,avsCheck:!!ce,avsConfig:typeof ce=="object"?ce:void 0,checkoutType:"embedded_checkout",checkoutLayout:Re?"custom_layout":H==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(L,Jn.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:p=>{dt=Math.max(dt,p)}}});try{Ce=await oe.createAndFetchSession(L),Z.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),Z.performance({stage:"session_create",durationMs:Z.now()-x,durationMode:"machine",requestCategory:"session_create",attempt:dt,statusClass:"2xx"})}catch(p){let P=(0,xe.classifyTelemetryFailure)(p,"CHECKOUT_SESSION_CREATE_FAILED","unknown");throw Z.performance({stage:"session_create",durationMs:Z.now()-x,durationMode:"machine",requestCategory:"session_create",attempt:dt,statusClass:P.statusClass}),p instanceof xe.FloPayError&&p.type==="validation_error"?Z.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):P.statusClass==="4xx"?Z.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):Z.error({...P,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),p}pe=Ce.data.session?.id??"",pe&&ys(j,pe,Ce.data.session?.clientSecret)}return{sid:pe??"",result:Ce,sdkGeneratedIdempotencyKey:b}}finally{io(Z)}}let ke=(0,D.useCallback)(async(_,j)=>{let Z=Ft.current;if(!Z)throw new xe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let oe=Ro(Z,_),ue=En(oe),q=so.get(ue);if(!q){let z={promise:Jt(oe,ue),consumers:0,settled:!1};q=z,so.set(ue,z);let pe=()=>{z.settled=!0,Ga(ue,z)};z.promise.then(pe,pe)}q.consumers+=1;let b=!1,re=()=>{b||(b=!0,q.consumers-=1,Ga(ue,q))};j?.(re);try{let z=await q.promise;tn.current=ue,_&&(zn(hn),Rn(P=>wa(P,_)));let{sid:pe,result:Ce}=z;A(Ce),Ce.data.session&&$e(Ce.data.session),pe&&We(pe);let{publishableKey:x,paypalPublishableKey:dt}=no(Ce),{flopay:L,paypalFlopay:p}=await ro({publishableKey:x,paypalPublishableKey:dt,billingApiUrl:I,locale:u,telemetry:o});return Be.current=L,ye(L),et.current=p,tt(p),kt(!1),z}catch(z){throw tn.current===ue&&(tn.current=null),z}finally{j||re()}},[u,I,o,Mt]),yt=(0,D.useCallback)(async _=>{if(!bs(_)||ht)return{sessionId:Ue,session:m};zt(!0);try{let j=await ke(_);return{sessionId:j.sid,session:j.result.data.session??null}}finally{zt(!1)}},[ke,ht,Ue,m]);(0,D.useEffect)(()=>{let _=!1,j;if(_e(null),Kt){let ue=Ft.current;return lt(It),kt(!1),tn.current===Kt?()=>{_=!0}:($e(ka(ue,de)),(async()=>{let q=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),b=It==="auto"&&!J.current&&!q;b&&(Ie(null),Rt(null),Ke("processing"));try{let re=await ke(void 0,x=>{j=x}),z=re.result.data.session??null;Ut.current=no(re.result);let pe=Lo(re.result),Ce=Eo(re.sid||z?.id);if(!_&&b&&z&&!pe&&!Ce){J.current=!0,await ds(Kt,re.sdkGeneratedIdempotencyKey,()=>Gt(z,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:re.result.autoProcessingError,initialAutoProcessingPending:re.result.autoProcessingPending,autoProcessingAttempted:re.result.autoProcessingAttempted,sessionId:re.sid||z.id}));return}!_&&b&&((pe||Ce)&&(J.current=!0),Ke(null),Rt(null))}catch(re){if(_)return;let z=re instanceof xe.FloPayError||typeof re=="object"&&re!==null&&"code"in re?re.code:void 0;if(b&&z==="session_auto_completed"){J.current=!0,Ke("success"),await _r(Tn),_||(pt(()=>{B.current?.({status:"succeeded"})}),Ke(null),Rt(null));return}b&&(Ke(null),Rt(null));let pe=re instanceof xe.FloPayError?re:new xe.FloPayError(re instanceof Error?re.message:"Failed to create session","api_error");_e(pe)}finally{j?.(),j=void 0}})(),()=>{_=!0,j?.()})}kt(!0);async function Z(){let ue=!1;try{let b=await new Jn.PaymentAPI(I,{telemetry:!1}).getUnifiedCheckoutSession(qe,t);if(_)return;A(b);let re=b.data.session??null;if($e(re),!re)throw new xe.FloPayError("No session data returned","api_error");if(re.status==="complete"){kt(!1),pt(()=>{Dn.current?.(re.successUrl??"")});return}if(re.status==="expired")throw new xe.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});ue=!0;let z=de??re.checkoutMode??"full";lt(z);let pe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ce=Lo(b);if(z==="auto"&&!J.current&&!pe&&!Ce){J.current=!0;let x=oe(b);try{if(await Gt(re,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>x,sessionId:qe||re.id}),_)return;await x,_||kt(!1);return}catch{if(_)return;await x,_||kt(!1);return}}await oe(b),_||kt(!1)}catch(q){if(_)return;q instanceof xe.FloPayError?!ue&&!us(q)&&Do(I,o,Mt,"NETWORK_REQUEST_FAILED","session_read"):Do(I,o,Mt,"INTERNAL_SDK_ERROR","checkout_mount");let b=q instanceof xe.FloPayError?q:new xe.FloPayError(q instanceof Error?q.message:"Failed to initialize checkout","api_error");_e(b),kt(!1)}}async function oe(ue){let{publishableKey:q,paypalPublishableKey:b}=no(ue);Ut.current={publishableKey:q,paypalPublishableKey:b};let{flopay:re,paypalFlopay:z}=await ro({publishableKey:q,paypalPublishableKey:b,billingApiUrl:I,locale:u,telemetry:o});Be.current=re,ye(re),et.current=z,tt(z)}return Z(),()=>{_=!0}},[ke,de,Kt,It,Wt,pt,t,Gt]);let ct=(0,D.useCallback)(async()=>{if(!(it||!m)){nt(!0),Ie(null);try{await Gt(m,{fallbackToFull:!0,sessionId:qe||m.id})}finally{nt(!1)}}},[qe,it,Gt,m]),bn=zo(ee),$n=Lo(ee),Dt=(0,D.useMemo)(()=>{if(!ee||!m||!ee.data.stripe?.publishableKey)return;let _={appearance:me,paymentMethodCreation:"manual",billingApiUrl:I};if(ee.data.stripe?.clientSecret)_.clientSecret=ee.data.stripe.clientSecret;else{let j=(0,xe.buildCheckoutDisplayData)(m).total;_.amount=Math.round(j*100)||m.amount,_.currency=m.currency?.toLowerCase()}return _},[ee,m,me,I]),Vt=!!(n&&!Re&&H==="buttons"&&Y&&It==="full"),vt=(0,D.useMemo)(()=>({session:m,loading:Pt,error:h,checkoutMode:je,inlineSessionDraft:$t,applyInlineSessionPatch:Vt?yt:void 0,inlineSessionPatchProcessing:ht}),[m,Pt,h,je,$t,Vt,yt,ht]),Zn=!!n&&H==="buttons"&&!$n&&(!G||!Dt),Ht=bt?(0,C.jsx)(Sn,{status:bt,errorMessage:Ot}):null;if(Pt){if(c)return(0,C.jsxs)(C.Fragment,{children:[c,Ht]});if(H==="buttons"){let _=se?.buttonsLayout?.cardButton?.borderRadius??se?.appearance.variables?.borderRadius??8,j=Z=>(0,C.jsx)("div",{style:{height:Z,borderRadius:_,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&&j(dr),f&&(R||F)&&j(dr),f&&j(dr),(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 h?k?(0,C.jsx)(sn.Provider,{value:vt,children:k(h)}):(0,C.jsx)(sn.Provider,{value:vt,children:(0,C.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:h.message})}):Zn?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(sn.Provider,{value:vt,children:(0,C.jsx)(Cs,{onButtonClick:U,showPayPal:d,showStripe:f,showApplePay:R,showGooglePay:F,theme:Q,buttonsTheme:Pe,buttonsStyles:ae,cardButtonContent:O,cardBackButtonContent:te,cardTitleContent:W})}),Ht]}):$n&&m&&bn?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(sn.Provider,{value:vt,children:(0,C.jsxs)("div",{className:ne,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Je&&(0,C.jsx)(or,{icon:!1,children:Je}),Bt==="retrying"&&(0,C.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Bt==="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:Un,children:"Retry PayPal"})]}),Bt!=="exhausted"&&(0,C.jsx)("div",{"aria-hidden":Bt==="retrying"?!0:void 0,style:Bt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,C.jsx)(Ba,{sessionId:qe,nonce:m.clientSecret||void 0,billingApiUrl:I,email:m.customer?.email,clientId:bn.clientId,environment:bn.environment,currency:(m.currency??"usd").toUpperCase(),isSubscription:m.mode==="subscription",onComplete:N,onErrorChange:Ie,onDecline:E,onButtonClick:U,onInitializationStateChange:Ve,allowAutomaticRetry:en===0,session:m,telemetry:o,telemetryContext:Mt,debug:g},`paypal-init-${en}`)})]})}),Ht]}):!G||!Dt?(0,C.jsx)(C.Fragment,{children:Ht}):je==="confirm"?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(sn.Provider,{value:vt,children:(0,C.jsx)(Cr,{flopay:G,paypalFlopay:st,options:Dt,children:(0,C.jsxs)("div",{className:ne,children:[Je&&(0,C.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Je}),Me?Me({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...":Ne??"Confirm Purchase"})]})})}),Ht]}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(sn.Provider,{value:vt,children:(0,C.jsx)(Cr,{flopay:G,paypalFlopay:st,options:Dt,children:Re?(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)(vs,{sessionId:qe,nonce:m?.clientSecret||void 0,billingApiUrl:I,session:m,children:Re})]}):(0,C.jsx)(Qr,{sessionId:qe,nonce:m?.clientSecret||void 0,email:m?.customer?.email,userId:m?.customer?.id,firstName:m?.customer?.firstName,lastName:m?.customer?.lastName,totalAmount:m?Math.round((0,xe.buildCheckoutDisplayData)(m).total*100):0,currency:m?.currency?.toLowerCase()??"usd",onComplete:N,onError:y,onDecline:E,error:Je,onErrorChange:Ie,showPayPal:d,showStripe:f,enabledPaymentMethods:ee?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ee?.data.stripe?.enabledPaymentMethodCountries,showApplePay:R,showGooglePay:F,layout:H,theme:Q,buttonsTheme:Pe,buttonsStyles:ae,appearance:me,cardButtonContent:O,cardBackButtonContent:te,cardTitleContent:W,onButtonClick:U,onBeforeButtonClick:Y,enableAVS:ce,...De?{cardFieldOrder:De}:{},...we?{cardPreFormSlot:we}:{},avsLayout:Se,country:m?.customer?.country,city:m?.customer?.city,state:m?.customer?.state,onCountryChange:S,onZipChange:M,avsCheck:!!ce,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Re?"custom_layout":H==="buttons"?"buttons_layout":"default_layout",className:ne,directPaypal:zo(ee),isSubscription:m?.mode==="subscription",session:m,debug:g})})}),Ht]})}function vs({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 Cs({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:l,showGooglePay:o,theme:s,buttonsTheme:u,buttonsStyles:c,cardButtonContent:k,cardBackButtonContent:N,cardTitleContent:y}){let[E,S]=(0,D.useState)(!1),M=(0,D.useMemo)(()=>(0,xe.resolveTheme)(s),[s]),d=(0,D.useMemo)(()=>{let g=M?.buttonsLayout??(0,xe.resolveButtonsLayoutTheme)(u);return c?{...g,...c,cardButton:{...g.cardButton,...c.cardButton},cardFormContainer:{...g.cardFormContainer,...c.cardFormContainer},backButton:{...g.backButton,...c.backButton},backButtonIcon:{...g.backButtonIcon,...c.backButtonIcon},submitButton:{...g.submitButton,...c.submitButton},title:{...g.title,...c.title}}:g},[M,u,c]),f=M?.buttonsLayout?.cardButton?.borderRadius??M?.appearance.variables?.borderRadius??8,R=g=>(0,C.jsx)("div",{style:{height:g,borderRadius:f,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),F=k===void 0?{boxSizing:"border-box",height:dr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(E){let g=d.cardInputBorder??"#e5e7eb",H=d.cardInputBackground??"white",Q=tr(N),Pe=tr(y);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: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,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)(rr,{content:N})]}),Pe?(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)(Sr,{content:y})})]}),(0,C.jsx)("div",{style:{backgroundColor:H,border:`1px solid ${g}`,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 ${g}`,borderLeft:`1px solid ${g}`,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 ${g}`,borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,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 ${g}`,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:`
38
+ `}),Pr&&$n&&(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:qn,style:{display:"inline-flex",alignItems:"center",gap:Co?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:c.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...c.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",...c.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(or,{content:H})]}),sa?(0,i.jsx)("div",{style:{flex:1}}):(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:c.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...c.title},children:(0,i.jsx)(wr,{content:he})})]}),!Pr&&!sa&&(0,i.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:So,order:Ie?-3:0,...c.title},children:(0,i.jsx)(wr,{content:he})}),ae&&(0,i.jsx)("div",{style:{order:Ie?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=Ye,b=(q=!1)=>({backgroundColor:vr,border:`1px solid ${Vn(q)}`,borderRadius:mt,marginTop:"0.5rem",padding:"10px"}),K=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ua}),le=(0,w.getStateOptions)(a);return(0,i.jsxs)(i.Fragment,{children:[(0,w.isAVSFieldVisible)(ae.address_line_1,a)&&(0,i.jsx)("div",{style:b(Pt.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:et,onChange:q=>{Yt.current=q.target.value,Ae(q.target.value)},disabled:Y,required:!0,"data-testid":"flopay-address-line1",style:K()})}),(0,w.isAVSFieldVisible)(ae.address_line_2,a)&&(0,i.jsx)("div",{style:b(),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:Je,onChange:q=>{Dt.current=q.target.value,Tt(q.target.value)},disabled:Y,"data-testid":"flopay-address-line2",style:K()})}),((0,w.isAVSFieldVisible)(ae.city,a)||(0,w.isAVSFieldVisible)(ae.state,a))&&(0,i.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,w.isAVSFieldVisible)(ae.city,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:vr,borderTop:`1px solid ${Vn(Pt.city)}`,borderRight:`1px solid ${Vn(Pt.city)}`,borderBottom:`1px solid ${Vn(Pt.city)}`,borderLeft:`1px solid ${Vn(Pt.city)}`,padding:"10px",borderTopLeftRadius:mt,borderBottomLeftRadius:mt,...(0,w.isAVSFieldVisible)(ae.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:We,onChange:q=>{Gt.current=q.target.value,On(q.target.value)},disabled:Y,required:!0,"data-testid":"flopay-city",style:K()})}),(0,w.isAVSFieldVisible)(ae.state,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:vr,border:`1px solid ${Vn(Pt.state)}`,padding:"10px",borderTopRightRadius:mt,borderBottomRightRadius:mt,...(0,w.isAVSFieldVisible)(ae.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:mt}},children:le?(0,i.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:gt,onChange:q=>{yn.current=q.target.value,Cn(q.target.value)},disabled:Y,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...K(),cursor:"pointer"},children:[(0,i.jsx)("option",{value:"",children:(0,w.getStateLabel)(a)}),le.map(q=>(0,i.jsx)("option",{value:q.code,children:q.name},q.code))]}):(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,w.getStateLabel)(a),autoComplete:"billing address-level1",value:gt,onChange:q=>{yn.current=q.target.value,Cn(q.target.value)},disabled:Y,required:!0,"data-testid":"flopay-state",style:K()})})]}),((0,w.isAVSFieldVisible)(ae.country,a)||(0,w.isAVSFieldVisible)(ae.postal_code,a))&&(0,i.jsxs)("div",{style:{display:"flex",flexDirection:re==="column"?"column":"row",gap:re==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,w.isAVSFieldVisible)(ae.country,a)&&(0,i.jsx)("div",{style:{flex:re==="row"?1:void 0,backgroundColor:vr,borderTop:`1px solid ${br}`,borderRight:`1px solid ${br}`,borderBottom:`1px solid ${br}`,borderLeft:`1px solid ${br}`,padding:"10px",...re==="row"&&(0,w.isAVSFieldVisible)(ae.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:Ye,onChange:q=>{Mt.current=q.target.value,rt(q.target.value),ze?.(q.target.value),yn.current="",Cn("")},disabled:Y,autoComplete:"billing country","data-testid":"flopay-country",style:{...K(),cursor:"pointer"},children:w.COUNTRY_OPTIONS.map(q=>(0,i.jsxs)("option",{value:q.code,children:[q.flag," ",q.name]},q.code))})}),(0,w.isAVSFieldVisible)(ae.postal_code,a)&&(0,i.jsx)("div",{style:{flex:re==="row"?1:void 0,backgroundColor:vr,border:`1px solid ${Si}`,padding:"10px",...re==="row"&&(0,w.isAVSFieldVisible)(ae.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,w.getPostalCodeLabel)(Ye),autoComplete:"billing postal-code",value:ft,onChange:q=>{wt.current=q.target.value,Ge(q.target.value),Ue?.(q.target.value)},onBlur:()=>nn(!0),disabled:Y,required:Bt.required,"aria-invalid":Lr||void 0,"aria-describedby":Lr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:K()})})]}),Lr&&(0,i.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:bo,...ua,fontSize:"0.75rem"},children:Bt.empty?`${(0,w.getPostalCodeLabel)(a)} is required`:ns(a)})]})})()}),Ie&&Be&&(0,i.jsx)("div",{style:{order:-2,width:"100%"},children:Be}),Ie&&Ei,$&&(0,i.jsx)(ar,{margin:"0.75rem 0",styleOverride:c.errorBanner,children:$})]}),Nr={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"},ma=a=>z?!_||!gn?(0,i.jsx)("pre",{"data-testid":a,style:Nr,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:Nr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${_}`,` directPaypalConfigured=${gn}`,` inAppBrowserDetected=${String(Fr)}`,` shouldRenderDirectPayPal=${yr}`,` shouldRenderStripePayPal=${fr}`,` hasPaypalStripeInstance=${!!de}`].join(`
39
+ `)}):null,ya=a=>z?!F||!Re?(0,i.jsx)("pre",{"data-testid":a,style:Nr,children:"FloPay/Stripe-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:Nr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${F}`,` currency=${Ne}`,` amountInCents=${ge}`,` enabledPaymentMethods: ${JSON.stringify(g??[])}`,` enabledPaymentMethodsProvided=${pr}`,` hasEnabledMethods=${Tr}`,` expressMethods: ${JSON.stringify(Mr)}`,` walletExpressMethods: ${JSON.stringify(Br)}`,` paymentElementMethods: ${JSON.stringify(mr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ar)}`,` hasStripeInstance=${!!Re}`,` shouldRenderWallets=${gr}`,` shouldRenderPaymentElement=${hr}`].join(`
40
+ `)}):null,fa=Te==="apm-expanding"||Te==="apm-form"||Te==="apm-collapsing",Or=Te==="apm-expanding"?`flopay-card-enter ${Kt}ms cubic-bezier(0, 0, 0.2, 1) both`:Te==="apm-collapsing"?`flopay-card-exit ${Kt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,zr=at?{...yo,paymentMethodTypes:[at]}:null;if(te==="buttons"){let a=Te==="buttons"||Te==="expanding"||Te==="apm-expanding",b=Te==="expanding"||Te==="card"||Te==="collapsing",K=V===void 0?{boxSizing:"border-box",height:Zr,padding:"0 1rem"}:{padding:"0.9rem 1rem"},le=Te==="expanding"||Te==="apm-expanding"?`flopay-buttons-exit ${Kt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Te==="collapsing"||Te==="apm-collapsing"?`flopay-buttons-enter ${Kt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,q=Te==="expanding"?`flopay-card-enter ${Kt}ms cubic-bezier(0, 0, 0.2, 1) both`:Te==="collapsing"?`flopay-card-exit ${Kt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,i.jsxs)("form",{onSubmit:ho,className:C,style:{position:"relative"},children:[(0,i.jsx)(Mo,{}),ht&&(0,i.jsx)(Pn,{status:ht,errorMessage:$}),(0,i.jsxs)("div",{style:{display:"grid"},children:[(0,i.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!le?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!le?Qi:{},...le?{animation:le,pointerEvents:"none"}:{}},children:[ma("flopay-direct-paypal-gate-debug"),ya("flopay-stripe-gate-debug"),yr&&He&&(0,i.jsxs)(i.Fragment,{children:[se&&(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)(Ir,{sessionId:e,nonce:t,billingApiUrl:A,email:J.email,clientId:He.clientId,environment:He.environment,currency:Ne.toUpperCase(),isSubscription:it,onTokenizedBody:Xt,onComplete:s,onErrorChange:be,onDecline:d,onTechnicalFailure:er,onButtonClick:we,runBeforeButtonClick:an,isProcessing:Y,onLoadStateChange:fo,onInitializationStateChange:go,session:O??null,existingOrderId:se?.orderId,debug:z},se?.orderId??"fresh")]}),fr&&(0,i.jsx)(dt.Elements,{stripe:de,options:jo,children:(0,i.jsx)(Ua,{sessionId:e,nonce:t,email:J.email,billingApiUrl:A,onTokenizedBody:Xt,onErrorChange:be,isProcessing:Y,onButtonClick:we,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:an,onLoadStateChange:Ho,placeholderBorderRadius:Kn})}),gr?(0,i.jsx)(dt.Elements,{stripe:Re,options:Ut,children:(0,i.jsx)($a,{sessionId:e,nonce:t,email:J.email,billingApiUrl:A,intentKind:ee>0?"payment":"setup",expressMethods:Br,onTokenizedBody:Xt,onErrorChange:be,onButtonClick:we,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:an,onLoadStateChange:Yo,placeholderBorderRadius:Kn})}):Qo?(0,i.jsx)("div",{style:{height:Zr,borderRadius:Kn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,hr&&(0,i.jsx)(qa,{sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:A,paymentElementMethods:Ar,stripeInstance:Re,paymentElementBaseOptions:yo,onTokenizedBody:Xt,onErrorChange:be,onButtonClick:we,onDecline:d,runBeforeButtonClick:an,onLoadStateChange:Jo,isProcessing:Y,submitButtonColor:Hn,submitButtonBorderRadius:mt,submitButtonStyle:c.submitButton,onExpandApm:zt,expandedApmMethod:at,themeId:L,buttonAppearance:{backgroundColor:c.cardButton?.backgroundColor,borderColor:c.cardInputBorder,textColor:c.cardButton?.color,borderRadius:Kn}}),Ie&&(0,i.jsx)("button",{type:"button",onClick:async()=>{Y||!(await an("card")).proceed||(we?.("card"),In())},disabled:Y,style:{width:"100%",...K,...c.cardButton,...Fo({themeBundle:ve,resolvedPrimaryColor:Hn,resolvedBorderRadius:mt,submitButtonStyle:c.submitButton,explicitPrimaryColor:$t?.colorPrimary}),fontSize:c.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Y?"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?.6:1},onMouseEnter:ie=>{!Y&&(ve||$t?.colorPrimary)&&(ie.currentTarget.style.backgroundColor=Ri)},onMouseLeave:ie=>{(ve||$t?.colorPrimary)&&(ie.currentTarget.style.backgroundColor=Hn)},onMouseDown:ie=>{ie.currentTarget.style.transform="scale(0.985)"},onMouseUp:ie=>{ie.currentTarget.style.transform="scale(1)"},children:(0,i.jsx)(rr,{content:V})}),$&&Te==="buttons"&&(0,i.jsx)(ar,{margin:"0.25rem 0",styleOverride:c.errorBanner,children:$})]}),Ie&&b&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...q?{animation:q}:{},...Te==="collapsing"?{pointerEvents:"none"}:{}},children:pa}),F&&fa&&at&&zr&&Re&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...Or?{animation:Or}:{},...Te==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:vo,borderRadius:ko,...Cr,padding:wo},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:En,style:{display:"inline-flex",alignItems:"center",gap:Co?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:c.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...c.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",...c.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(or,{content:H})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:c.titleFontSize??"1.05rem",color:So,paddingRight:80,...c.title},children:`Pay with ${(0,w.getStripeMethodDisplayName)(at)}`})]}),(0,i.jsx)(dt.Elements,{stripe:Re,options:zr,children:(0,i.jsx)(Bo,{method:at,sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:A,onTokenizedBody:Xt,onErrorChange:be,onDecline:d,onCancel:En,runBeforeButtonClick:an,onButtonClick:we,isProcessing:Y,submitButtonColor:Hn,submitButtonBorderRadius:mt,submitButtonStyle:c.submitButton,errorText:$})},at)]})})]})]})}return fa&&at&&zr&&Re&&F?(0,i.jsxs)("form",{onSubmit:ho,className:C,style:{position:"relative"},children:[(0,i.jsx)(Mo,{}),ht&&(0,i.jsx)(Pn,{status:ht,errorMessage:$}),(0,i.jsx)("div",{style:{...Or?{animation:Or}:{},...Te==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:vo,borderRadius:ko,...Cr,padding:wo},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:En,style:{display:"inline-flex",alignItems:"center",gap:Co?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:c.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...c.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",...c.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(or,{content:H})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:c.titleFontSize??"1.05rem",color:So,paddingRight:80,...c.title},children:`Pay with ${(0,w.getStripeMethodDisplayName)(at)}`})]}),(0,i.jsx)(dt.Elements,{stripe:Re,options:zr,children:(0,i.jsx)(Bo,{method:at,sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:A,onTokenizedBody:Xt,onErrorChange:be,onDecline:d,onCancel:En,runBeforeButtonClick:an,onButtonClick:we,isProcessing:Y,submitButtonColor:Hn,submitButtonBorderRadius:mt,submitButtonStyle:c.submitButton,errorText:$})},at)]})})]}):(0,i.jsxs)("form",{onSubmit:ho,className:C,style:{position:"relative"},children:[(0,i.jsx)(Mo,{}),ht&&(0,i.jsx)(Pn,{status:ht,errorMessage:$}),(0,i.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ma("flopay-direct-paypal-gate-debug-default"),ya("flopay-stripe-gate-debug-default"),yr&&He&&(0,i.jsxs)(i.Fragment,{children:[se&&(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)(Ir,{sessionId:e,nonce:t,billingApiUrl:A,email:J.email,clientId:He.clientId,environment:He.environment,currency:Ne.toUpperCase(),isSubscription:it,onTokenizedBody:Xt,onComplete:s,onErrorChange:be,onDecline:d,onTechnicalFailure:er,onButtonClick:we,runBeforeButtonClick:an,isProcessing:Y,onLoadStateChange:fo,onInitializationStateChange:go,session:O??null,existingOrderId:se?.orderId,debug:z},se?.orderId??"fresh")]}),fr&&(0,i.jsx)(dt.Elements,{stripe:de,options:jo,children:(0,i.jsx)(Ua,{sessionId:e,nonce:t,email:J.email,billingApiUrl:A,onTokenizedBody:Xt,onErrorChange:be,isProcessing:Y,onButtonClick:we,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:an,onLoadStateChange:Ho,placeholderBorderRadius:Kn})}),gr&&(0,i.jsx)(dt.Elements,{stripe:Re,options:Ut,children:(0,i.jsx)($a,{sessionId:e,nonce:t,email:J.email,billingApiUrl:A,intentKind:ee>0?"payment":"setup",expressMethods:Br,onTokenizedBody:Xt,onErrorChange:be,onButtonClick:we,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:an,onLoadStateChange:Yo,placeholderBorderRadius:Kn})}),hr&&(0,i.jsx)(qa,{sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:A,paymentElementMethods:Ar,stripeInstance:Re,paymentElementBaseOptions:yo,onTokenizedBody:Xt,onErrorChange:be,onButtonClick:we,onDecline:d,runBeforeButtonClick:an,onLoadStateChange:Jo,isProcessing:Y,submitButtonColor:Hn,submitButtonBorderRadius:mt,submitButtonStyle:c.submitButton,themeId:L,onExpandApm:zt,expandedApmMethod:at,buttonAppearance:{backgroundColor:c.cardButton?.backgroundColor,borderColor:c.cardInputBorder,textColor:c.cardButton?.color,borderRadius:Kn}})]}),Ie&&(Pi||hi||bi)&&(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&&pa]})}var cr=require("@flopay/js"),Qe=require("@flopay/shared");var _r="card";async function ss(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:p}=await e.retrieveSetupIntent(t);return{error:p,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 ls(e,t,n,l){if(l){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:p,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:p??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:s}=await e.confirmCardPayment(t,n);return{error:s,intent:o??null}}function vn(e,t){return Object.assign(e,{checkoutMethod:t})}function Ya(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 cs(e){return e.status==="succeeded"||e.status==="declined"}async function Ga(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 f=new AbortController,E=()=>f.abort();e.signal?.aborted?f.abort():e.signal?.addEventListener("abort",E);let C=window.setTimeout(()=>f.abort(),l);try{let M=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:f.signal});if(!M.ok)return{status:"unknown"};let u=await M.json().catch(()=>null);return ds(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(C),e.signal?.removeEventListener("abort",E)}},p=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let k=document.createElement("iframe");k.setAttribute("title","Card authentication"),k.setAttribute("allow","payment"),k.tabIndex=0,k.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),k.src=e.nextActionRedirectUrl,d.appendChild(k),document.body.appendChild(d),k.focus();let D=null;try{D=new URL(e.billingApiUrl,window.location.href).origin}catch{D=null}try{let f=await new Promise((E,C)=>{let M=!1,u=0,P=0,_=0,F=!1,g=()=>{window.clearTimeout(u),window.clearInterval(P),window.clearTimeout(_),window.removeEventListener("message",te),k.removeEventListener("load",j),e.signal?.removeEventListener("abort",pe)},ce=async()=>{if(!(M||F)){F=!0;try{let L=await s();if(M||!cs(L))return;M=!0,g(),E(L)}finally{F=!1}}},j=()=>{window.clearTimeout(_),_=window.setTimeout(()=>{ce()},250)},pe=()=>{M||(M=!0,g(),C(new Qe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},te=L=>{if(L.source!==k.contentWindow||D&&L.origin!==D)return;let Z=L.data;!Z||typeof Z!="object"||Z.source!=="flopay-vault-3ds-return"||M||(M=!0,g(),E(null))};u=window.setTimeout(()=>{M||(M=!0,g(),C(new Qe.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),P=window.setInterval(()=>{ce()},n),k.addEventListener("load",j),window.addEventListener("message",te),e.signal?.addEventListener("abort",pe),e.signal?.aborted&&pe()});return f||await s()}finally{d.parentNode?.removeChild(d),p?.isConnected&&p.focus()}}function ds(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 vn(new Qe.FloPayError(s,"api_error",{code:e?.gatewayErrorCode}),l)}function Do(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function to(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function us(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 Ja(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||to(o)))return o;let l=e?.data;if(l&&typeof l=="object"){let o=l,s=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let d of s)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||to(d)))return d;let p=o.gateways;if(p&&typeof p=="object"){let d=p.stripe;if(d&&typeof d=="object"){let k=d,D=[k.stripeClientSecret,k.clientSecret];for(let f of D)if(typeof f=="string"&&f.length>0&&(!t?.requirePaymentIntentClientSecret||to(f)))return f}}}}async function ps({billingApiUrl:e,sessionId:t,nonce:n,responseJson:l}){let o=Ja(l,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new cr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(to(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function dr({billingApiUrl:e,sessionId:t,session:n,nonce:l,tokenizedData:o,returnUrl:s,telemetry:p}){let d=e.replace(/\/+$/,""),k=t??n.id,D=l??n.clientSecret,f=n.customer?.id??n.accountData?.userId??"",E=n.customer?.email??n.accountData?.email??"",C=n.customer?.firstName??n.accountData?.firstName??"",M=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,P=n.customer?.zip??n.accountData?.zip??void 0,_=new cr.PaymentAPI(d,p===!1?{telemetry:!1}:void 0),F=await us(()=>_.processPayment(f,{sessionId:k,nonce:D,tokenizedData:o,accountData:{userId:f,email:E,firstName:C,lastName:M,country:u,zip:P},returnUrl:s??Do(n)}));if(F.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Wr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let g=await F.json().catch(()=>null);if(g?.type==="paypal_redirect_required"||g?.type==="3ds_required"){let ce=Ja(g);if(!ce)throw new Qe.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:g.type,threeDSecureToken:ce,paymentMethodId:g.paymentMethodId}}if(g?.gatewayErrorCode==="authentication_required"){let ce=await ps({billingApiUrl:d,sessionId:k,nonce:D,responseJson:g});if(ce)return ce;throw vn(new Qe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new Qe.FloPayError(g?.message??"Payment failed. Please try again.","api_error",{code:g?.code??g?.gatewayErrorCode,declineCode:g?.declineCode??g?.gatewayDeclineReason})}async function no(e,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:p,returnUrl:d,telemetry:k}){let D=t?.getRawProvider();if(!D)throw new Qe.FloPayError("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!l||!e.threeDSecureToken)throw vn(new Qe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let f=(0,Qe.isSetupIntentClientSecret)(e.threeDSecureToken),E=null,C=e.paymentMethodId,M=await ss(D,e.threeDSecureToken,f);if(M){if(M.error)throw vn(new Qe.FloPayError(M.error.message??`Failed to retrieve 3DS ${f?"setup":"payment"} status.`,"api_error",{code:M.error.code}),"card");let P=M.intent;!C&&P?.payment_method&&(typeof P.payment_method=="string"?C=P.payment_method:"id"in P.payment_method&&(C=P.payment_method.id??void 0))}let u=C?await ls(D,e.threeDSecureToken,{payment_method:C,return_url:d??Do(p)??window.location.href},f):null;if(u){if(u.error)throw vn(new Qe.FloPayError(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");E=u.intent}else{let P=await D.handleNextAction({clientSecret:e.threeDSecureToken});if(P.error)throw vn(new Qe.FloPayError(P.error.message??"3DS authentication failed.","api_error",{code:P.error.code}),"card");E=(f?P.setupIntent:P.paymentIntent)??null}if(E&&(E.status==="requires_capture"||E.status==="succeeded"||E.status==="processing")){let P=await dr({billingApiUrl:o,sessionId:s,session:p,telemetry:k,tokenizedData:{id:E.id,type:"card",threeDSecureActionResultTokenId:E.id},returnUrl:d});return P.type==="success"?{...P.result,paymentIntentId:P.result.paymentIntentId??E.id,paymentMethodId:P.result.paymentMethodId??C}:no(P,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:p,returnUrl:d,telemetry:k})}throw vn(new Qe.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let f=(n??t)?.getRawProvider();if(!f)throw vn(new Qe.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:C}=await f.handleNextAction({clientSecret:e.threeDSecureToken});if(C)throw vn(new Qe.FloPayError(C.message??"PayPal authorization failed.","api_error",{code:C.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:E}=await f.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Do(p)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(E)throw vn(new Qe.FloPayError(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Qe.FloPayError("Unsupported payment redirect state.","api_error")}function Jn(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 ro(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 oo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:l,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let s=!!t&&t!==e,[p,d]=await Promise.all([(0,cr.loadFloPay)(e,{billingApiUrl:n,locale:l,telemetry:o}),s?(0,cr.loadFloPay)(t,{billingApiUrl:n,locale:l,telemetry:o}).catch(k=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",k),null)):Promise.resolve(null)]);return{flopay:p,paypalFlopay:t?s?d:p:null}}var v=require("react/jsx-runtime"),ur=44,$o="flopay_checkout_saved_payment_resume",lo=new Map,ao=new Map;function Xa(e,t){t.settled&&t.consumers===0&&lo.get(e)===t&&lo.delete(e)}function ms(e,t,n){let l=ao.get(e);if(l&&(!l.sdkGeneratedIdempotencyKey||!t||l.sdkGeneratedIdempotencyKey===t))return l.attempt;let o=n(),s={attempt:o,sdkGeneratedIdempotencyKey:t};ao.set(e,s);let p=()=>{ao.get(e)===s&&ao.delete(e)};return o.then(p,p),o}function xr(e){return new Promise(t=>setTimeout(t,e))}function io(e,t,n){let l=$r({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:_e.SDK_VERSION,enabled:t!==!1});return l.beginCheckout(n),l}function so(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Lo(e,t,n,l,o){let s=io(e,t,n);s.error({errorCode:l,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),so(s)}function ys(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function Uo(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function No(e){return!e||e.data.stripe?.publishableKey?!1:!!Uo(e)?.clientId}function An(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function fs(){if(!An())return null;try{let e=window.sessionStorage.getItem($o);return e?JSON.parse(e):null}catch{return null}}function Za(e){if(An())try{window.sessionStorage.setItem($o,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Oo(){if(An())try{window.sessionStorage.removeItem($o)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var qo=":idempotency-key";function gs(e){if(!An())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function hs(e,t,n){if(An())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 ei(e){if(An())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function Ps(e){if(An())try{return window.sessionStorage.getItem(e+qo)??void 0}catch{return}}function bs(e,t){if(An())try{window.sessionStorage.setItem(e+qo,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function vs(e){if(ei(e),!!An())try{window.sessionStorage.removeItem(e+qo)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Cs(){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 Ss(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function zo(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function co({sessionId:e,nonce:t,createSession:n,billingApiUrl:l,telemetry:o,appearance:s,locale:p,loading:d,error:k,onComplete:D,onError:f,onDecline:E,onCountryChange:C,onZipChange:M,showPayPal:u=!0,showStripe:P=!0,enabledPaymentMethods:_,showApplePay:F=!0,showGooglePay:g=!0,debug:ce=!1,layout:j,theme:pe,buttonsTheme:te,buttonsStyles:L,cardButtonContent:Z,cardBackButtonContent:G,cardTitleContent:me,showSecurityFooter:V,onButtonClick:H,onBeforeButtonClick:he,enableAVS:Me,cardFieldOrder:we,cardPreFormSlot:Ce,avsLayout:ne,className:Se,initialErrorMessage:Be=null,children:re,checkoutMode:xe,confirmLabel:De,renderConfirmButton:Ee,onSessionCompleted:X}){let x=(0,_e.resolveBillingApiUrl)(l),ye=(0,B.useMemo)(()=>(0,_e.resolveTheme)(pe),[pe]),ze=s??ye?.appearance,Ue=n?"embedded_checkout":"standard_checkout",Pe=re?"custom_layout":j==="buttons"?"buttons_layout":"default_layout",[I,oe]=(0,B.useState)(null),[ee,Ne]=(0,B.useState)(null),ut=(0,B.useRef)(null),[He,it]=(0,B.useState)(null),O=(0,B.useRef)(null),[z,qe]=(0,B.useState)(null),[Ke,st]=(0,B.useState)(e??""),pt=e??Ke,xt=n?"":pt,[Wt,y]=(0,B.useState)(!0),[ke,Ye]=(0,B.useState)(null),[rt,ft]=(0,B.useState)("full"),[Ge,et]=(0,B.useState)(!1),[Ae,Je]=(0,B.useState)(Be),[Tt,We]=(0,B.useState)(null),[On,gt]=(0,B.useState)(null),[Cn,Sn]=(0,B.useState)(void 0),[zn,wt]=(0,B.useState)(""),[Mt,Yt]=(0,B.useState)(!1),[Dt,Gt]=(0,B.useState)("loading"),[yn,ae]=(0,B.useState)(0),qt=(0,B.useRef)(!1),wn=(0,B.useRef)(!1),kn=(0,B.useRef)(!1),Jt=(0,B.useRef)(null),R=(0,B.useMemo)(()=>({checkoutMode:xe??rt,layout:re?"unknown":j==="buttons"?"buttons":"embedded"}),[xe,re,rt,j]),Xe=(0,B.useRef)(D);Xe.current=D;let Ie=(0,B.useRef)(f);Ie.current=f;let Fn=(0,B.useRef)(E);Fn.current=E,(0,B.useEffect)(()=>{_t(ee)?.setCheckoutContext(R),He&&He!==ee&&_t(He)?.setCheckoutContext(R)},[ee,He,R]);let je=(0,B.useRef)(X);je.current=X;let Un=(0,B.useCallback)(h=>{Gt(h),!(h!=="exhausted"||kn.current)&&(kn.current=!0,Ie.current?.(new _e.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Qn=(0,B.useCallback)(()=>{Gt("retrying"),ae(h=>h+1)},[]);(0,B.useEffect)(()=>{Gt("loading"),ae(0),kn.current=!1},[pt]),(0,B.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:_e.SDK_VERSION,checkout_type:Ue,checkout_layout:Pe,billing_api_url:x})},[Pe,Ue,x]);let jt=(0,B.useMemo)(()=>n?nn(n,!0):"",[n]),lt=(0,B.useMemo)(()=>zn===jt?Cn:void 0,[Cn,zn,jt]),Bt=(0,B.useMemo)(()=>n?Io(n,lt):void 0,[n,lt]),Vt=xe??Bt?.checkoutMode??"full",Pt=(0,B.useMemo)(()=>Bt?{...Bt,checkoutMode:Vt}:void 0,[Bt,Vt]);(0,B.useEffect)(()=>{Sn(void 0),wt(jt)},[jt]),(0,B.useEffect)(()=>{Je(Be)},[Be]);let en=(0,B.useCallback)((h,U,W)=>{ct(()=>{Fn.current?.(St(h,U,W))})},[ct]),tn=(0,B.useCallback)(async(h,U)=>{Je(null),gt(null),We("processing");let W=U?.sessionId??h.id,fe=ut.current??O.current,se=_t(fe),Q=fe?null:io(x,o,R),S={log:N=>{se?se.log(N):Q?.log(N)},error:N=>{se?se.error(N):Q?.error(N)},terminal:N=>{se?se.terminal(N):Q?.terminal(N)},performance:N=>{se?se.performance(N):Q?.performance(N)},now:()=>se?.now()??Q?.now()??0,elapsed:N=>se?.elapsed(N)??Math.max(0,(Q?.now()??N)-N)},A=S.now(),$=!!(U?.initialAutoProcessingError||U?.initialAutoProcessingPending),ve=!1,c,m=()=>{ve||(ve=!0,$=!0,c=S.now(),S.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ue=!1,$e=()=>{ue||(ue=!0,S.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),S.performance({stage:"processing",durationMs:S.elapsed(A),durationMode:"machine",paymentMethodCategory:"saved"}),c!==void 0&&S.performance({stage:"recovery",durationMs:S.elapsed(c),durationMode:"machine",paymentMethodCategory:"saved"}))};S.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),S.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),$&&m();let Y;try{let N=Ya(U?.initialAutoProcessingError),J;if(N)m(),N.type==="paypal_redirect_required"&&Jt.current?.publishableKey&&Za({sessionId:W,publishableKey:Jt.current.publishableKey,paypalPublishableKey:Jt.current.paypalPublishableKey}),J=await no(N,{flopay:ut.current,paypalFlopay:O.current,attempt3DS:U?.attempt3DS,billingApiUrl:x,sessionId:W,session:h,telemetry:!1}),N.type==="paypal_redirect_required"&&Oo();else if(U?.initialAutoProcessingPending){let Re=await new Xn.PaymentAPI(x,{telemetry:!1}).waitForCheckoutSessionCompletion(U.initialAutoProcessingPending.sessionId,{initialDelayMs:U.initialAutoProcessingPending.retryAfterMs});if(Re.data.session?.status!=="complete")throw new _e.FloPayError("Automatic payment failed. Please try again.","api_error",{code:Re.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});J={status:"succeeded"}}else{if(U?.initialAutoProcessingError)throw Nn(U.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:U.initialAutoProcessingError.checkoutMethod});if(U?.fromCreateSession)return U?.fallbackToFull&&(ft("full"),Qa("full")),!1;{let bt=await dr({billingApiUrl:x,sessionId:W,session:h,telemetry:!1});bt.type==="success"?J=bt.result:(m(),bt.type==="paypal_redirect_required"&&Jt.current?.publishableKey&&Za({sessionId:W,publishableKey:Jt.current.publishableKey,paypalPublishableKey:Jt.current.paypalPublishableKey}),J=await no(bt,{flopay:ut.current,paypalFlopay:O.current,attempt3DS:U?.attempt3DS,billingApiUrl:x,sessionId:W,session:h,telemetry:!1}),bt.type==="paypal_redirect_required"&&Oo())}}W&&sr(W),$e(),$&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),S.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),We("success"),await xr(Tn),Y=()=>Xe.current?.(J)}catch(N){let J=Jn(N),bt=J.checkoutMethod??_r;return Je(J.message),gt(J.message),U?.fallbackToFull&&(S.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),ft("full"),Qa("full")),$e(),!!(J.declineCode||J.code?.toLowerCase().includes("declin"))?S.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):J.type==="validation_error"?S.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):S.error({errorCode:$?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:$?"recovery":"processing",paymentMethodCategory:"saved"}),ct(()=>Ie.current?.(J)),en(bt,J,{code:J.code,declineCode:J.declineCode}),We("error"),await Promise.allSettled([xr(hn),U?.ensureProvidersReady?U.ensureProvidersReady():Promise.resolve()]),$&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{$e(),Q&&so(Q),We(null),gt(null)}return ct(Y),!0},[en,ct,Jn,x,o,R]);(0,B.useEffect)(()=>{if(typeof window>"u"||wn.current)return;let h=new URLSearchParams(window.location.search),U=h.get("payment_intent_client_secret");if(!U)return;let W=fs();W&&(wn.current=!0,(async()=>{let fe,se=0;Je(null),gt(null),We("processing"),et(!0);try{if(h.get("redirect_status")==="failed")throw Object.assign(new _e.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Q,paypalFlopay:S}=await oo({publishableKey:W.publishableKey,paypalPublishableKey:W.paypalPublishableKey,billingApiUrl:x,locale:p,telemetry:o});fe=_t(S??Q),se=fe?.now()??0,fe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let A=(S??Q)?.getRawProvider();if(!A)throw Object.assign(new _e.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:$,error:ve}=await A.retrievePaymentIntent(U);if(ve)throw Object.assign(new _e.FloPayError(ve.message??"Failed to retrieve PayPal payment status.","api_error",{code:ve.code}),{checkoutMethod:"paypal"});let c=Ea($?.status);if(!$||c==="failed")throw Object.assign(new _e.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let m=typeof $.payment_method=="string"?$.payment_method:$.payment_method?.id,ue=c;if(W.sessionId){let N=(await new Xn.PaymentAPI(x,{telemetry:!1}).getUnifiedCheckoutSession(W.sessionId)).data.session;if(N&&N.status!=="complete"){let J=await dr({billingApiUrl:x,sessionId:W.sessionId,session:N,telemetry:!1,tokenizedData:{id:m??$.id,type:"card",threeDSecureActionResultTokenId:$.id,isPaypal:!0}});if(J.type!=="success")throw Object.assign(new _e.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});ue=J.result.status}}W.sessionId&&sr(W.sessionId),fe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.performance({stage:"redirect_resume",durationMs:fe.elapsed(se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),We("success"),await xr(Tn),ct(()=>Xe.current?.({status:ue,paymentIntentId:$.id,paymentMethodId:m,checkoutMethod:"paypal"}))}catch(Q){let S=Jn(Q),A=S.checkoutMethod??"paypal",$=!!(S.declineCode||S.code?.toLowerCase().includes("declin"));if(fe)fe.performance({stage:"redirect_resume",durationMs:fe.elapsed(se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),$?fe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):fe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if($){let ve=io(x,o,R);ve.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),so(ve)}else Lo(x,o,R,"REDIRECT_RESUME_FAILED","redirect_resume");Je(S.message),gt(S.message),ct(()=>Ie.current?.(S)),en(A,S,{code:S.code,declineCode:S.declineCode}),We("error"),await xr(hn)}finally{Oo(),Cs(),We(null),gt(null),et(!1)}})())},[en,ct,p,Jn,x,o]);let fn=(0,B.useRef)(null);function nn(h,U=!1){let W=h?.account?.email?.trim().toLowerCase()??"",fe={c:h?.clientId,cur:h?.currency??"",a:{e:W,u:W?"":h?.account?.userId??"",country:h?.account?.country??""},successUrl:h?.successUrl,cancelUrl:h?.cancelUrl,p:h?.products?.map(S=>zo(`${S.type??""}:${S.code??S.providerItemId??S.providerPlanId??""}`,S)).sort(),i:h?.items?.map(S=>zo(S.code??S.providerItemId??"",S)).sort(),s:h?.subscriptions?.map(S=>zo(S.code??S.providerPlanId??"",S)).sort(),couponCodes:h?.couponCodes?[...h.couponCodes].sort():void 0,...U?{tagsData:h?.tagsData,utmMetadata:h?.utmMetadata,tokenizedData:h?.tokenizedData,checkoutMode:h?.checkoutMode??"full"}:{}},se=JSON.stringify(fe),Q=0;for(let S=0;S<se.length;S++)Q=(Q<<5)-Q+se.charCodeAt(S)|0;return`flopay_session_${Math.abs(Q).toString(36)}`}let kt=(0,B.useMemo)(()=>Pt?nn(Pt):"",[Pt]),Lt=(0,B.useRef)(Pt);Lt.current=Pt,(0,B.useEffect)(()=>{st(e??"")},[e]),(0,B.useEffect)(()=>{qt.current=!1,Je(Be),gt(null),We(null)},[kt,Be,e]);async function Te(h,U){let W=io(x,o,R),fe=new Xn.PaymentAPI(x,{telemetry:!1});try{let se=h.idempotencyKey!==void 0?(0,_e.resolveIdempotencyKey)(h.idempotencyKey):void 0,Q=se??Ps(U),S,A=!1,$=gs(U);W.log({name:$?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let ve=$?.sid??null,c=null;if(ve)try{if(c=await fe.getUnifiedCheckoutSession(ve,$?.nonce),c.data.session?.status==="complete"){if(_o(ve))return{sid:ve,result:c};vs(U),ve=null,c=null,A=!0}}catch{W.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),ei(U),ve=null}if(!ve){!se&&(A||!Q)&&(Q=(0,_e.resolveIdempotencyKey)(),S=Q),Q&&bs(U,Q);let m=W.now(),ue=0;W.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let $e={...h,idempotencyKey:Q,avsCheck:!!Me,avsConfig:typeof Me=="object"?Me:void 0,checkoutType:"embedded_checkout",checkoutLayout:re?"custom_layout":j==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty($e,Xn.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Y=>{ue=Math.max(ue,Y)}}});try{c=await fe.createAndFetchSession($e),W.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),W.performance({stage:"session_create",durationMs:W.now()-m,durationMode:"machine",requestCategory:"session_create",attempt:ue,statusClass:"2xx"})}catch(Y){let N=(0,_e.classifyTelemetryFailure)(Y,"CHECKOUT_SESSION_CREATE_FAILED","unknown");throw W.performance({stage:"session_create",durationMs:W.now()-m,durationMode:"machine",requestCategory:"session_create",attempt:ue,statusClass:N.statusClass}),Y instanceof _e.FloPayError&&Y.type==="validation_error"?W.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):N.statusClass==="4xx"?W.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):W.error({...N,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Y}ve=c.data.session?.id??"",ve&&hs(U,ve,c.data.session?.clientSecret)}return{sid:ve??"",result:c,sdkGeneratedIdempotencyKey:S}}finally{so(W)}}let ot=(0,B.useCallback)(async(h,U)=>{let W=Lt.current;if(!W)throw new _e.FloPayError("createSession is required to bootstrap checkout.","validation_error");let fe=Io(W,h),se=nn(fe),Q=lo.get(se);if(!Q){let $={promise:Te(fe,se),consumers:0,settled:!1};Q=$,lo.set(se,$);let ve=()=>{$.settled=!0,Xa(se,$)};$.promise.then(ve,ve)}Q.consumers+=1;let S=!1,A=()=>{S||(S=!0,Q.consumers-=1,Xa(se,Q))};U?.(A);try{let $=await Q.promise;fn.current=se,h&&(wt(jt),Sn(N=>Ra(N,h)));let{sid:ve,result:c}=$;oe(c),c.data.session&&qe(c.data.session),ve&&st(ve);let{publishableKey:m,paypalPublishableKey:ue}=ro(c),{flopay:$e,paypalFlopay:Y}=await oo({publishableKey:m,paypalPublishableKey:ue,billingApiUrl:x,locale:p,telemetry:o});return ut.current=$e,Ne($e),O.current=Y,it(Y),y(!1),$}catch($){throw fn.current===se&&(fn.current=null),$}finally{U||A()}},[p,x,o,R]),at=(0,B.useRef)(tn);at.current=tn;let Rn=(0,B.useRef)(ot);Rn.current=ot;let $n=(0,B.useCallback)(async h=>{if(!Ss(h)||Mt)return{sessionId:Ke,session:z};Yt(!0);try{let U=await ot(h);return{sessionId:U.sid,session:U.result.data.session??null}}finally{Yt(!1)}},[ot,Mt,Ke,z]);(0,B.useEffect)(()=>{let h=!1,U;if(Ye(null),kt){let se=Lt.current;return ft(Vt),y(!1),fn.current===kt?()=>{h=!0}:(qe(Ia(se,xe)),(async()=>{let Q=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),S=Vt==="auto"&&!qt.current&&!Q;S&&(Je(null),gt(null),We("processing"));try{let A=await Rn.current(void 0,m=>{U=m}),$=A.result.data.session??null;Jt.current=ro(A.result);let ve=No(A.result),c=_o(A.sid||$?.id);if(!h&&S&&$&&!ve&&!c){qt.current=!0,await ms(kt,A.sdkGeneratedIdempotencyKey,()=>at.current($,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:A.result.autoProcessingError,initialAutoProcessingPending:A.result.autoProcessingPending,autoProcessingAttempted:A.result.autoProcessingAttempted,sessionId:A.sid||$.id}));return}!h&&S&&((ve||c)&&(qt.current=!0),We(null),gt(null))}catch(A){if(h)return;let $=A instanceof _e.FloPayError||typeof A=="object"&&A!==null&&"code"in A?A.code:void 0;if(S&&$==="session_auto_completed"){qt.current=!0,We("success"),await xr(Tn),h||(ct(()=>{Xe.current?.({status:"succeeded"})}),We(null),gt(null));return}S&&(We(null),gt(null));let ve=A instanceof _e.FloPayError?A:new _e.FloPayError(A instanceof Error?A.message:"Failed to create session","api_error");Ye(ve)}finally{U?.(),U=void 0}})(),()=>{h=!0,U?.()})}y(!0);async function W(){let se=!1;try{let S=await new Xn.PaymentAPI(x,{telemetry:!1}).getUnifiedCheckoutSession(pt,t);if(h)return;oe(S);let A=S.data.session??null;if(qe(A),!A)throw new _e.FloPayError("No session data returned","api_error");if(A.status==="complete"){y(!1),ct(()=>{je.current?.(A.successUrl??"")});return}if(A.status==="expired")throw new _e.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});se=!0;let $=xe??A.checkoutMode??"full";ft($);let ve=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),c=No(S);if($==="auto"&&!qt.current&&!ve&&!c){qt.current=!0;let m=fe(S);try{if(await at.current(A,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>m,sessionId:pt||A.id}),h)return;await m,h||y(!1);return}catch{if(h)return;await m,h||y(!1);return}}await fe(S),h||y(!1)}catch(Q){if(h)return;Q instanceof _e.FloPayError?!se&&!ys(Q)&&Lo(x,o,R,"NETWORK_REQUEST_FAILED","session_read"):Lo(x,o,R,"INTERNAL_SDK_ERROR","checkout_mount");let S=Q instanceof _e.FloPayError?Q:new _e.FloPayError(Q instanceof Error?Q.message:"Failed to initialize checkout","api_error");Ye(S),y(!1)}}async function fe(se){let{publishableKey:Q,paypalPublishableKey:S}=ro(se);Jt.current={publishableKey:Q,paypalPublishableKey:S};let{flopay:A,paypalFlopay:$}=await oo({publishableKey:Q,paypalPublishableKey:S,billingApiUrl:x,locale:p,telemetry:o});ut.current=A,Ne(A),O.current=$,it($)}return W(),()=>{h=!0}},[xe,kt,Vt,xt,ct,t]);let Kt=(0,B.useCallback)(async()=>{if(!(Ge||!z)){et(!0),Je(null);try{await tn(z,{attempt3DS:!0,fallbackToFull:!0,sessionId:pt||z.id})}finally{et(!1)}}},[pt,Ge,tn,z]),Nt=Uo(I),Ot=No(I),In=(0,B.useMemo)(()=>{if(!I||!z||!I.data.stripe?.publishableKey)return;let h={appearance:ze,paymentMethodCreation:"manual",billingApiUrl:x};if(I.data.stripe?.clientSecret)h.clientSecret=I.data.stripe.clientSecret;else{let U=(0,_e.buildCheckoutDisplayData)(z).total;h.amount=Math.round(U*100)||z.amount,h.currency=z.currency?.toLowerCase()}return h},[I,z,ze,x]),qn=!!(n&&!re&&j==="buttons"&&he&&Vt==="full"),zt=(0,B.useMemo)(()=>({session:z,loading:Wt,error:ke,checkoutMode:rt,inlineSessionDraft:Pt,applyInlineSessionPatch:qn?$n:void 0,inlineSessionPatchProcessing:Mt}),[z,Wt,ke,rt,Pt,qn,$n,Mt]),En=!!n&&j==="buttons"&&!Ot&&(!ee||!In),ht=Tt?(0,v.jsx)(Pn,{status:Tt,errorMessage:On}):null;if(Wt){if(d)return(0,v.jsxs)(v.Fragment,{children:[d,ht]});if(j==="buttons"){let h=ye?.buttonsLayout?.cardButton?.borderRadius??ye?.appearance.variables?.borderRadius??8,U=W=>(0,v.jsx)("div",{style:{height:W,borderRadius:h,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,v.jsxs)(v.Fragment,{children:[(0,v.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[u&&U(ur),P&&(F||g)&&U(ur),P&&U(ur),(0,v.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),ht]})}return(0,v.jsxs)(v.Fragment,{children:[(0,v.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,v.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,v.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),ht]})}return ke?k?(0,v.jsx)(sn.Provider,{value:zt,children:k(ke)}):(0,v.jsx)(sn.Provider,{value:zt,children:(0,v.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:ke.message})}):En?(0,v.jsxs)(v.Fragment,{children:[(0,v.jsx)(sn.Provider,{value:zt,children:(0,v.jsx)(ks,{onButtonClick:H,showPayPal:u,showStripe:P,showApplePay:F,showGooglePay:g,theme:pe,buttonsTheme:te,buttonsStyles:L,cardButtonContent:Z,cardBackButtonContent:G,cardTitleContent:me})}),ht]}):Ot&&z&&Nt?(0,v.jsxs)(v.Fragment,{children:[(0,v.jsx)(sn.Provider,{value:zt,children:(0,v.jsxs)("div",{className:Se,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ae&&(0,v.jsx)(ar,{icon:!1,children:Ae}),Dt==="retrying"&&(0,v.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Dt==="exhausted"&&(0,v.jsxs)("div",{role:"alert",children:[(0,v.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,v.jsx)("button",{type:"button",onClick:Qn,children:"Retry PayPal"})]}),Dt!=="exhausted"&&(0,v.jsx)("div",{"aria-hidden":Dt==="retrying"?!0:void 0,style:Dt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,v.jsx)(Fa,{sessionId:pt,nonce:z.clientSecret||void 0,billingApiUrl:x,email:z.customer?.email,clientId:Nt.clientId,environment:Nt.environment,currency:(z.currency??"usd").toUpperCase(),isSubscription:z.mode==="subscription",onComplete:D,onErrorChange:Je,onDecline:E,onButtonClick:H,onInitializationStateChange:Un,allowAutomaticRetry:yn===0,session:z,telemetry:o,telemetryContext:R,debug:ce},`paypal-init-${yn}`)})]})}),ht]}):!ee||!In?(0,v.jsx)(v.Fragment,{children:ht}):rt==="confirm"?(0,v.jsxs)(v.Fragment,{children:[(0,v.jsx)(sn.Provider,{value:zt,children:(0,v.jsx)(Sr,{flopay:ee,paypalFlopay:He,options:In,children:(0,v.jsxs)("div",{className:Se,children:[Ae&&(0,v.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ae}),Ee?Ee({onConfirm:Kt,isProcessing:Ge}):(0,v.jsx)("button",{type:"button",onClick:Kt,disabled:Ge,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Ge?"not-allowed":"pointer",opacity:Ge?.6:1},children:Ge?"Processing...":De??"Confirm Purchase"})]})})}),ht]}):(0,v.jsxs)(v.Fragment,{children:[(0,v.jsx)(sn.Provider,{value:zt,children:(0,v.jsx)(Sr,{flopay:ee,paypalFlopay:He,options:In,children:re?(0,v.jsxs)(v.Fragment,{children:[Ae&&(0,v.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ae}),(0,v.jsx)(ws,{sessionId:pt,nonce:z?.clientSecret||void 0,billingApiUrl:x,session:z,children:re})]}):(0,v.jsx)(eo,{sessionId:pt,nonce:z?.clientSecret||void 0,email:z?.customer?.email,userId:z?.customer?.id,firstName:z?.customer?.firstName,lastName:z?.customer?.lastName,totalAmount:z?Math.round((0,_e.buildCheckoutDisplayData)(z).total*100):0,currency:z?.currency?.toLowerCase()??"usd",onComplete:D,onError:f,onDecline:E,error:Ae,onErrorChange:Je,showPayPal:u,showStripe:P,enabledPaymentMethods:_??I?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:I?.data.stripe?.enabledPaymentMethodCountries,showApplePay:F,showGooglePay:g,layout:j,theme:pe,buttonsTheme:te,buttonsStyles:L,appearance:ze,cardButtonContent:Z,cardBackButtonContent:G,cardTitleContent:me,onButtonClick:H,onBeforeButtonClick:he,enableAVS:Me,...we?{cardFieldOrder:we}:{},...Ce?{cardPreFormSlot:Ce}:{},avsLayout:ne,country:z?.customer?.country,city:z?.customer?.city,state:z?.customer?.state,onCountryChange:C,onZipChange:M,avsCheck:!!Me,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:re?"custom_layout":j==="buttons"?"buttons_layout":"default_layout",className:Se,directPaypal:Uo(I),isSubscription:z?.mode==="subscription",session:z,debug:ce})})}),ht]})}function ws({sessionId:e,nonce:t,billingApiUrl:n,session:l,children:o}){return(0,v.jsx)(v.Fragment,{children:B.default.Children.map(o,s=>{if(!B.default.isValidElement(s))return s;let p=s.props,d={};return p.sessionId||(d.sessionId=e),!p.nonce&&t&&(d.nonce=t),p.billingApiUrl||(d.billingApiUrl=n),l?.customer&&(p.email||(d.email=l.customer.email),p.userId||(d.userId=l.customer.id),p.firstName||(d.firstName=l.customer.firstName),p.lastName||(d.lastName=l.customer.lastName)),Object.keys(d).length===0?s:B.default.cloneElement(s,d)})})}function ks({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:l,showGooglePay:o,theme:s,buttonsTheme:p,buttonsStyles:d,cardButtonContent:k,cardBackButtonContent:D,cardTitleContent:f}){let[E,C]=(0,B.useState)(!1),M=(0,B.useMemo)(()=>(0,_e.resolveTheme)(s),[s]),u=(0,B.useMemo)(()=>{let g=M?.buttonsLayout??(0,_e.resolveButtonsLayoutTheme)(p);return d?{...g,...d,cardButton:{...g.cardButton,...d.cardButton},cardFormContainer:{...g.cardFormContainer,...d.cardFormContainer},backButton:{...g.backButton,...d.backButton},backButtonIcon:{...g.backButtonIcon,...d.backButtonIcon},submitButton:{...g.submitButton,...d.submitButton},title:{...g.title,...d.title}}:g},[M,p,d]),P=M?.buttonsLayout?.cardButton?.borderRadius??M?.appearance.variables?.borderRadius??8,_=g=>(0,v.jsx)("div",{style:{height:g,borderRadius:P,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),F=k===void 0?{boxSizing:"border-box",height:ur,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(E){let g=u.cardInputBorder??"#e5e7eb",ce=u.cardInputBackground??"white",j=nr(D),pe=nr(f);return(0,v.jsxs)("div",{style:{backgroundColor:u.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...u.cardFormContainer},children:[(0,v.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,v.jsxs)("button",{type:"button",onClick:()=>C(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:j?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...u.backButton},children:[(0,v.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:(0,v.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,v.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,v.jsx)(or,{content:D})]}),pe?(0,v.jsx)("div",{style:{flex:1}}):(0,v.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:(0,v.jsx)(wr,{content:f})})]}),(0,v.jsx)("div",{style:{backgroundColor:ce,border:`1px solid ${g}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,v.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,v.jsxs)("div",{style:{display:"flex"},children:[(0,v.jsx)("div",{style:{flex:1,backgroundColor:ce,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,v.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,v.jsx)("div",{style:{flex:1,backgroundColor:ce,borderTop:"none",borderRight:`1px solid ${g}`,borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,v.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,v.jsx)("div",{style:{backgroundColor:ce,border:`1px solid ${g}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,v.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,v.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...u.submitButton,opacity:.5}}),(0,v.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,C.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&R(dr),n&&(l||o)&&R(dr),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:g=>{g.currentTarget.style.transform="scale(0.985)"},onMouseUp:g=>{g.currentTarget.style.transform="scale(1)"},children:(0,C.jsx)(nr,{content:k})}),(0,C.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Xn=require("react");var ni=require("react/jsx-runtime");function Qa(e,t){function n({className:l,id:o,style:s,options:u,onChange:c,onReady:k,onFocus:N,onBlur:y,onEscape:E}){let S=(0,Xn.useRef)(null),M=(0,Xn.useRef)(null),{elements:d,reportInteractive:f}=(0,Xn.useContext)(_n);return(0,Xn.useEffect)(()=>{if(!d||!S.current)return;let R=!0;return(async()=>{let F=d.getElement(e);F||(F=await d.create(e,u)),!(!R||!S.current)&&(F.mount(S.current),M.current=F,c&&F.on("change",c),F.on("ready",()=>{f?.(),k?.()}),N&&F.on("focus",N),y&&F.on("blur",y),E&&F.on("escape",E))})(),()=>{if(R=!1,M.current){try{M.current.unmount()}catch{}M.current=null}}},[d,f]),(0,ni.jsx)("div",{ref:S,className:l,id:o,style:s})}return n.displayName=t,n}var ei=Qa("payment","PaymentElement"),ti=Qa("address","AddressElement");var ri=require("@flopay/js"),oi=require("@flopay/shared"),pn=require("react");var un=require("react/jsx-runtime");function ai({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,firstName:s,lastName:u,chv:c,onTokenizedBody:k,onComplete:N,onErrorChange:y,isProcessing:E=!1}){let S=ln(),M=jr(),d=Kr(),[f,R]=(0,pn.useState)(!1),[F,g]=(0,pn.useState)(!1),H=(0,pn.useRef)(!1),Q=(n||d).replace(/\/+$/,""),Pe=(0,pn.useCallback)(async te=>{try{let be=await new ri.PaymentAPI(Q).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:te,accountData:{userId:o??"",email:l??"",firstName:s??"",lastName:u??""},chv:c});if(be.ok){N?.();return}let U=await be.json().catch(()=>null);y?.(U?.message??"Payment failed. Please try again.")}catch(W){y?.(W instanceof Error?W.message:"An unexpected error occurred")}},[Q,e,t,o,l,s,u,c,N,y]),ae=(0,pn.useCallback)(te=>{k?k(te):Pe(te)},[k,Pe]);(0,pn.useEffect)(()=>{if(!S||H.current)return;let te=new URLSearchParams(window.location.search),W=te.get("payment_intent"),be=te.get("payment_intent_client_secret"),U=te.get("redirect_status");!W||!be||(H.current=!0,(async()=>{try{if(g(!0),U==="failed"){y?.("PayPal payment was declined. Please try again.");return}let Y=S.getRawProvider();if(!Y?.retrievePaymentIntent){y?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ce,error:De}=await Y.retrievePaymentIntent(be);if(De){y?.(De.message??"Failed to retrieve PayPal payment status.");return}if(ce&&(ce.status==="requires_capture"||ce.status==="succeeded")){let we=typeof ce.payment_method=="string"?ce.payment_method:ce.payment_method?.id;ae({id:we??ce.id,type:"card",threeDSecureActionResultTokenId:ce.id,isPaypal:!0});let Se=new URL(window.location.href);Se.searchParams.delete("payment_intent"),Se.searchParams.delete("payment_intent_client_secret"),Se.searchParams.delete("redirect_status"),window.history.replaceState({},"",Se.toString())}else y?.("PayPal payment was not completed. Please try again.")}catch(Y){y?.(Y instanceof Error?Y.message:"Failed to complete PayPal payment.")}finally{g(!1)}})())},[S,ae,y]);let O=(0,pn.useCallback)(async()=>{if(!(!S||!M))try{if(g(!0),y?.(null),!e||!l)throw new oi.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let te=await S.confirmPayPalPayment({billingApiUrl:Q,sessionId:e,nonce:t,email:l,returnUrl:window.location.href});if(te.error){y?.(te.error.message);return}te.paymentIntentId&&(te.status==="succeeded"||te.status==="processing"||te.status==="requires_capture")&&ae({id:te.paymentMethodId??te.paymentIntentId,type:"card",threeDSecureActionResultTokenId:te.paymentIntentId,isPaypal:!0})}catch(te){y?.(te instanceof Error?te.message:"PayPal payment failed. Please try again.")}finally{g(!1)}},[S,M,e,t,l,Q,ae,y]);return!S||!M?(0,un.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,un.jsxs)(un.Fragment,{children:[!f&&(0,un.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,un.jsx)("div",{style:f?{}:{display:"none"},children:(0,un.jsx)("button",{type:"button",onClick:O,disabled:F||E,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:F||E?"not-allowed":"pointer",opacity:F||E?.6:1},ref:()=>R(!0),children:F?"Processing...":"PayPal"})}),(F||E)&&(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 Ae=require("react"),co=require("@flopay/js"),Nt=require("@flopay/shared");var mn=require("react/jsx-runtime"),Ss=44;function ii(e){return new Promise(t=>setTimeout(t,e))}function ws(e,t){return e instanceof Nt.FloPayError?e:new Nt.FloPayError(e instanceof Error?e.message:t,"api_error")}function ks(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Rs(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 si({sessionId:e,nonce:t,createSession:n,paymentMethodId:l,checkoutMethod:o,clientId:s,products:u,items:c,subscriptions:k,account:N,successUrl:y,cancelUrl:E,couponCodes:S,tagsData:M,utmMetadata:d,billingApiUrl:f,locale:R,theme:F,appearance:g,buttonsTheme:H,buttonsStyles:Q,onSuccess:Pe,onError:ae,onDecline:O,children:te,disabled:W=!1,type:be="button",style:U,...Y}){let ce=(0,Ae.useMemo)(()=>(0,Nt.resolveBillingApiUrl)(f),[f]),De=(0,Ae.useMemo)(()=>Rs({createSession:n,clientId:s,products:u,items:c,subscriptions:k,account:N,successUrl:y,cancelUrl:E,couponCodes:S,tagsData:M,utmMetadata:d}),[N,E,s,S,n,u,c,k,y,M,d]),[we,Se]=(0,Ae.useState)(!1),[ne,ve]=(0,Ae.useState)(null),[Re,de]=(0,Ae.useState)(null),[Ne,Me]=(0,Ae.useState)(null),Ee=(0,Ae.useRef)(!0),I=(0,Ae.useRef)(null),se=(0,Ae.useRef)(Ne),me=(0,Ae.useRef)(Pe),ze=(0,Ae.useRef)(ae),Oe=(0,Ae.useRef)(O);(0,Ae.useEffect)(()=>{se.current=Ne},[Ne]),(0,Ae.useEffect)(()=>{me.current=Pe},[Pe]),(0,Ae.useEffect)(()=>{ze.current=ae},[ae]),(0,Ae.useEffect)(()=>{Oe.current=O},[O]),(0,Ae.useEffect)(()=>(Ee.current=!0,()=>{Ee.current=!1,I.current?.abort()}),[]),(0,Ae.useEffect)(()=>{if(typeof window>"u")return;let h=_e=>{_e.key==="Escape"&&Me(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let ee=(0,Ae.useCallback)((h,_e=Er)=>{Oe.current?.(wt(_e,h,{code:h.code,declineCode:h.declineCode}))},[]),A=(0,Ae.useCallback)(async h=>{Ee.current&&(de(null),ve("success"),await ii(Tn),Ee.current&&me.current?.(h))},[]),G=(0,Ae.useCallback)(async(h,_e)=>{Ee.current&&(ze.current?.(h),_e?.emitDecline&&ee(h,_e.method),de(h.message),ve("error"),await ii(Cn))},[ee]),ye=(0,Ae.useCallback)(async(h,_e,je)=>{let lt=h.data.session??null;if(!lt)throw new Nt.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||_e,autoCompleted:!1});return}if(lt.status==="expired")throw new Nt.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(h.autoProcessingPending){let bt=(await new co.PaymentAPI(ce).waitForCheckoutSessionCompletion(h.autoProcessingPending.sessionId,{initialDelayMs:h.autoProcessingPending.retryAfterMs})).data.session;if(!bt||bt.status!=="complete")throw new Nt.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||_e,autoCompleted:!1});return}if(h.autoProcessingError){if(h.autoProcessingError.type==="3ds_required"&&h.autoProcessingError.nextActionRedirectUrl&&_e&&it){let Je=new AbortController;I.current=Je;let Ie;try{Ie=await Wa({billingApiUrl:ce,sessionId:_e,nonce:it,nextActionRedirectUrl:h.autoProcessingError.nextActionRedirectUrl,signal:Je.signal})}finally{I.current===Je&&(I.current=null)}if(Ie.status==="declined")throw On({type:Ie.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ie.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let Ot=(await new co.PaymentAPI(ce).waitForCheckoutSessionCompletion(_e,{initialDelayMs:0,nonce:it})).data.session;if(!Ot||Ot.status!=="complete")throw On({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await A({result:{status:"succeeded"},session:Ot,sessionId:Ot.id||_e,autoCompleted:!1});return}throw On(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(je?.fromCreateSession&&h.autoProcessingAttempted===!0)throw On({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let nt=await cr({billingApiUrl:ce,sessionId:_e??lt.id,session:lt,nonce:it});if(nt.type!=="success")throw On({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||_e,autoCompleted:!1})}catch(nt){let Je=Gn(nt),Ie=lt.id||_e;await G(Je,{emitDecline:!0,method:Je.checkoutMethod??Er}),ks(Je,Ie)&&Ie&&Ee.current&&Me({sessionId:Ie,errorMessage:Je.message,nonce:it||void 0})}},[t,ce,G,A]),Be=(0,Ae.useCallback)(async h=>{if(Y.onClick?.(h),!(h.defaultPrevented||W||we)){if(Me(null),e&&De){let _e=new Nt.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await G(_e),Ee.current&&(ve(null),de(null));return}if(!e&&!De){let _e=new Nt.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await G(_e),Ee.current&&(ve(null),de(null));return}Se(!0),de(null),ve("processing");try{let _e=new co.PaymentAPI(ce);if(e){let je=await _e.getUnifiedCheckoutSession(e,t);await ye(je,e);return}try{let je=await _e.createAndFetchSession({...De});await ye(je,je.data.session?.id??null,{fromCreateSession:!0})}catch(je){if(je instanceof Nt.FloPayError&&je.code==="session_auto_completed"){await A({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw je}}catch(_e){await G(ws(_e,"Automatic payment failed. Please try again."))}finally{Ee.current&&(ve(null),de(null),Se(!1))}}},[Y,De,W,we,t,ye,ce,e,G,A]),st=(0,Ae.useCallback)(h=>{let _e=se.current;Me(null),me.current?.({result:h,session:null,sessionId:_e?.sessionId??null,autoCompleted:!1})},[]),tt=(0,Ae.useCallback)(h=>{ze.current?.(h)},[]),et=(0,Ae.useCallback)(h=>{Oe.current?.(h)},[]),m=(0,Ae.useMemo)(()=>(0,Nt.resolveTheme)(F),[F]),$e=(0,Ae.useMemo)(()=>{let h=m?.buttonsLayout??(0,Nt.resolveButtonsLayoutTheme)(H);return Q?{...h,...Q,cardButton:{...h.cardButton,...Q.cardButton}}:h},[m,H,Q]),Ue=(0,Ae.useMemo)(()=>{let h=m?.appearance;return g?h?{...h,...g,variables:{...h.variables,...g.variables}}:g:h},[g,m]),We=Ue?.variables,qe=We?.colorPrimary??"#4A49FF",Wt=We?.colorPrimaryHover??Jr(qe,.12),Pt=We?.borderRadius??"8px";return(0,mn.jsxs)(mn.Fragment,{children:[(0,mn.jsx)("button",{...Y,type:be,onClick:Be,disabled:W||we,"aria-busy":we,style:{width:"100%",...te===void 0?{boxSizing:"border-box",height:Ss,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...$e.cardButton,...Ao({themeBundle:m,resolvedPrimaryColor:qe,resolvedBorderRadius:Pt,submitButtonStyle:$e.submitButton,explicitPrimaryColor:We?.colorPrimary}),fontSize:$e.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:W||we?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:W||we?.6:1,...U},onMouseEnter:h=>{Y.onMouseEnter?.(h),!h.defaultPrevented&&!W&&!we&&(m||We?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Wt)},onMouseLeave:h=>{Y.onMouseLeave?.(h),!h.defaultPrevented&&(m||We?.colorPrimary)&&(h.currentTarget.style.backgroundColor=qe)},onMouseDown:h=>{Y.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{Y.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,mn.jsx)(nr,{content:te})}),ne&&(0,mn.jsx)(Sn,{status:ne,errorMessage:Re}),Ne&&(0,mn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&Me(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(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)(lo,{sessionId:Ne.sessionId,nonce:Ne.nonce,checkoutMode:"full",billingApiUrl:ce,locale:R,theme:F,...Ue?{appearance:Ue}:{},buttonsTheme:H,buttonsStyles:Q,initialErrorMessage:Ne.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});
47
+ `})]})}return(0,v.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&_(ur),n&&(l||o)&&_(ur),n&&(0,v.jsx)("button",{type:"button",onClick:()=>{e?.("card"),C(!0)},style:{width:"100%",...F,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:u.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...u.cardButton},onMouseDown:g=>{g.currentTarget.style.transform="scale(0.985)"},onMouseUp:g=>{g.currentTarget.style.transform="scale(1)"},children:(0,v.jsx)(rr,{content:k})}),(0,v.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Zn=require("react");var oi=require("react/jsx-runtime");function ti(e,t){function n({className:l,id:o,style:s,options:p,onChange:d,onReady:k,onFocus:D,onBlur:f,onEscape:E}){let C=(0,Zn.useRef)(null),M=(0,Zn.useRef)(null),{elements:u,reportInteractive:P}=(0,Zn.useContext)(_n);return(0,Zn.useEffect)(()=>{if(!u||!C.current)return;let _=!0;return(async()=>{let F=u.getElement(e);F||(F=await u.create(e,p)),!(!_||!C.current)&&(F.mount(C.current),M.current=F,d&&F.on("change",d),F.on("ready",()=>{P?.(),k?.()}),D&&F.on("focus",D),f&&F.on("blur",f),E&&F.on("escape",E))})(),()=>{if(_=!1,M.current){try{M.current.unmount()}catch{}M.current=null}}},[u,P]),(0,oi.jsx)("div",{ref:C,className:l,id:o,style:s})}return n.displayName=t,n}var ni=ti("payment","PaymentElement"),ri=ti("address","AddressElement");var ai=require("@flopay/js"),ii=require("@flopay/shared"),pn=require("react");var un=require("react/jsx-runtime");function si({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,firstName:s,lastName:p,chv:d,onTokenizedBody:k,onComplete:D,onErrorChange:f,isProcessing:E=!1}){let C=ln(),M=Vr(),u=Kr(),[P,_]=(0,pn.useState)(!1),[F,g]=(0,pn.useState)(!1),ce=(0,pn.useRef)(!1),j=(n||u).replace(/\/+$/,""),pe=(0,pn.useCallback)(async Z=>{try{let me=await new ai.PaymentAPI(j).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:Z,accountData:{userId:o??"",email:l??"",firstName:s??"",lastName:p??""},chv:d});if(me.ok){D?.();return}let V=await me.json().catch(()=>null);f?.(V?.message??"Payment failed. Please try again.")}catch(G){f?.(G instanceof Error?G.message:"An unexpected error occurred")}},[j,e,t,o,l,s,p,d,D,f]),te=(0,pn.useCallback)(Z=>{k?k(Z):pe(Z)},[k,pe]);(0,pn.useEffect)(()=>{if(!C||ce.current)return;let Z=new URLSearchParams(window.location.search),G=Z.get("payment_intent"),me=Z.get("payment_intent_client_secret"),V=Z.get("redirect_status");!G||!me||(ce.current=!0,(async()=>{try{if(g(!0),V==="failed"){f?.("PayPal payment was declined. Please try again.");return}let H=C.getRawProvider();if(!H?.retrievePaymentIntent){f?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:he,error:Me}=await H.retrievePaymentIntent(me);if(Me){f?.(Me.message??"Failed to retrieve PayPal payment status.");return}if(he&&(he.status==="requires_capture"||he.status==="succeeded")){let we=typeof he.payment_method=="string"?he.payment_method:he.payment_method?.id;te({id:we??he.id,type:"card",threeDSecureActionResultTokenId:he.id,isPaypal:!0});let Ce=new URL(window.location.href);Ce.searchParams.delete("payment_intent"),Ce.searchParams.delete("payment_intent_client_secret"),Ce.searchParams.delete("redirect_status"),window.history.replaceState({},"",Ce.toString())}else f?.("PayPal payment was not completed. Please try again.")}catch(H){f?.(H instanceof Error?H.message:"Failed to complete PayPal payment.")}finally{g(!1)}})())},[C,te,f]);let L=(0,pn.useCallback)(async()=>{if(!(!C||!M))try{if(g(!0),f?.(null),!e||!l)throw new ii.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let Z=await C.confirmPayPalPayment({billingApiUrl:j,sessionId:e,nonce:t,email:l,returnUrl:window.location.href});if(Z.error){f?.(Z.error.message);return}Z.paymentIntentId&&(Z.status==="succeeded"||Z.status==="processing"||Z.status==="requires_capture")&&te({id:Z.paymentMethodId??Z.paymentIntentId,type:"card",threeDSecureActionResultTokenId:Z.paymentIntentId,isPaypal:!0})}catch(Z){f?.(Z instanceof Error?Z.message:"PayPal payment failed. Please try again.")}finally{g(!1)}},[C,M,e,t,l,j,te,f]);return!C||!M?(0,un.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,un.jsxs)(un.Fragment,{children:[!P&&(0,un.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,un.jsx)("div",{style:P?{}:{display:"none"},children:(0,un.jsx)("button",{type:"button",onClick:L,disabled:F||E,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:F||E?"not-allowed":"pointer",opacity:F||E?.6:1},ref:()=>_(!0),children:F?"Processing...":"PayPal"})}),(F||E)&&(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 Fe=require("react"),uo=require("@flopay/js"),Ft=require("@flopay/shared");var mn=require("react/jsx-runtime"),Rs=44;function li(e){return new Promise(t=>setTimeout(t,e))}function Is(e,t){return e instanceof Ft.FloPayError?e:new Ft.FloPayError(e instanceof Error?e.message:t,"api_error")}function Es(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function _s(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 ci({sessionId:e,nonce:t,createSession:n,paymentMethodId:l,checkoutMethod:o,clientId:s,products:p,items:d,subscriptions:k,account:D,successUrl:f,cancelUrl:E,couponCodes:C,tagsData:M,utmMetadata:u,billingApiUrl:P,locale:_,theme:F,appearance:g,buttonsTheme:ce,buttonsStyles:j,onSuccess:pe,onError:te,onDecline:L,children:Z,disabled:G=!1,type:me="button",style:V,...H}){let he=(0,Fe.useMemo)(()=>(0,Ft.resolveBillingApiUrl)(P),[P]),Me=(0,Fe.useMemo)(()=>_s({createSession:n,clientId:s,products:p,items:d,subscriptions:k,account:D,successUrl:f,cancelUrl:E,couponCodes:C,tagsData:M,utmMetadata:u}),[D,E,s,C,n,p,d,k,f,M,u]),[we,Ce]=(0,Fe.useState)(!1),[ne,Se]=(0,Fe.useState)(null),[Be,re]=(0,Fe.useState)(null),[xe,De]=(0,Fe.useState)(null),Ee=(0,Fe.useRef)(!0),X=(0,Fe.useRef)(null),x=(0,Fe.useRef)(xe),ye=(0,Fe.useRef)(pe),ze=(0,Fe.useRef)(te),Ue=(0,Fe.useRef)(L);(0,Fe.useEffect)(()=>{x.current=xe},[xe]),(0,Fe.useEffect)(()=>{ye.current=pe},[pe]),(0,Fe.useEffect)(()=>{ze.current=te},[te]),(0,Fe.useEffect)(()=>{Ue.current=L},[L]),(0,Fe.useEffect)(()=>(Ee.current=!0,()=>{Ee.current=!1,X.current?.abort()}),[]),(0,Fe.useEffect)(()=>{if(typeof window>"u")return;let y=ke=>{ke.key==="Escape"&&De(null)};return window.addEventListener("keydown",y),()=>{window.removeEventListener("keydown",y)}},[]);let Pe=(0,Fe.useCallback)((y,ke=_r)=>{Ue.current?.(St(ke,y,{code:y.code,declineCode:y.declineCode}))},[]),I=(0,Fe.useCallback)(async y=>{Ee.current&&(re(null),Se("success"),await li(Tn),Ee.current&&ye.current?.(y))},[]),oe=(0,Fe.useCallback)(async(y,ke)=>{Ee.current&&(ze.current?.(y),ke?.emitDecline&&Pe(y,ke.method),re(y.message),Se("error"),await li(hn))},[Pe]),ee=(0,Fe.useCallback)(async(y,ke,Ye)=>{let rt=y.data.session??null;if(!rt)throw new Ft.FloPayError("No session data returned","api_error");let ft=rt.clientSecret||t;if(rt.status==="complete"){await I({result:{status:"succeeded"},session:rt,sessionId:rt.id||ke,autoCompleted:!1});return}if(rt.status==="expired")throw new Ft.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(y.autoProcessingPending){let Je=(await new uo.PaymentAPI(he).waitForCheckoutSessionCompletion(y.autoProcessingPending.sessionId,{initialDelayMs:y.autoProcessingPending.retryAfterMs})).data.session;if(!Je||Je.status!=="complete")throw new Ft.FloPayError("Automatic payment failed. Please try again.","api_error",{code:Je?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await I({result:{status:"succeeded"},session:Je,sessionId:Je.id||ke,autoCompleted:!1});return}if(y.autoProcessingError){if(y.autoProcessingError.type==="3ds_required"&&y.autoProcessingError.nextActionRedirectUrl&&ke&&ft){let et=new AbortController;X.current=et;let Ae;try{Ae=await Ga({billingApiUrl:he,sessionId:ke,nonce:ft,nextActionRedirectUrl:y.autoProcessingError.nextActionRedirectUrl,signal:et.signal})}finally{X.current===et&&(X.current=null)}if(Ae.status==="declined")throw Nn({type:Ae.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ae.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:y.autoProcessingError.checkoutMethod});let We=(await new uo.PaymentAPI(he).waitForCheckoutSessionCompletion(ke,{initialDelayMs:0,nonce:ft})).data.session;if(!We||We.status!=="complete")throw Nn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:y.autoProcessingError.checkoutMethod});await I({result:{status:"succeeded"},session:We,sessionId:We.id||ke,autoCompleted:!1});return}throw Nn(y.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:y.autoProcessingError.checkoutMethod})}if(Ye?.fromCreateSession&&y.autoProcessingAttempted===!0)throw Nn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ge=await dr({billingApiUrl:he,sessionId:ke??rt.id,session:rt,nonce:ft});if(Ge.type!=="success")throw Nn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await I({result:Ge.result,session:rt,sessionId:rt.id||ke,autoCompleted:!1})}catch(Ge){let et=Jn(Ge),Ae=rt.id||ke;await oe(et,{emitDecline:!0,method:et.checkoutMethod??_r}),Es(et,Ae)&&Ae&&Ee.current&&De({sessionId:Ae,errorMessage:et.message,nonce:ft||void 0})}},[t,he,oe,I]),Ne=(0,Fe.useCallback)(async y=>{if(H.onClick?.(y),!(y.defaultPrevented||G||we)){if(De(null),e&&Me){let ke=new Ft.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await oe(ke),Ee.current&&(Se(null),re(null));return}if(!e&&!Me){let ke=new Ft.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await oe(ke),Ee.current&&(Se(null),re(null));return}Ce(!0),re(null),Se("processing");try{let ke=new uo.PaymentAPI(he);if(e){let Ye=await ke.getUnifiedCheckoutSession(e,t);await ee(Ye,e);return}try{let Ye=await ke.createAndFetchSession({...Me});await ee(Ye,Ye.data.session?.id??null,{fromCreateSession:!0})}catch(Ye){if(Ye instanceof Ft.FloPayError&&Ye.code==="session_auto_completed"){await I({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Ye}}catch(ke){await oe(Is(ke,"Automatic payment failed. Please try again."))}finally{Ee.current&&(Se(null),re(null),Ce(!1))}}},[H,Me,G,we,t,ee,he,e,oe,I]),ut=(0,Fe.useCallback)(y=>{let ke=x.current;De(null),ye.current?.({result:y,session:null,sessionId:ke?.sessionId??null,autoCompleted:!1})},[]),He=(0,Fe.useCallback)(y=>{ze.current?.(y)},[]),it=(0,Fe.useCallback)(y=>{Ue.current?.(y)},[]),O=(0,Fe.useMemo)(()=>(0,Ft.resolveTheme)(F),[F]),z=(0,Fe.useMemo)(()=>{let y=O?.buttonsLayout??(0,Ft.resolveButtonsLayoutTheme)(ce);return j?{...y,...j,cardButton:{...y.cardButton,...j.cardButton}}:y},[O,ce,j]),qe=(0,Fe.useMemo)(()=>{let y=O?.appearance;return g?y?{...y,...g,variables:{...y.variables,...g.variables}}:g:y},[g,O]),Ke=qe?.variables,st=Ke?.colorPrimary??"#4A49FF",pt=Ke?.colorPrimaryHover??Xr(st,.12),xt=Ke?.borderRadius??"8px";return(0,mn.jsxs)(mn.Fragment,{children:[(0,mn.jsx)("button",{...H,type:me,onClick:Ne,disabled:G||we,"aria-busy":we,style:{width:"100%",...Z===void 0?{boxSizing:"border-box",height:Rs,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...z.cardButton,...Fo({themeBundle:O,resolvedPrimaryColor:st,resolvedBorderRadius:xt,submitButtonStyle:z.submitButton,explicitPrimaryColor:Ke?.colorPrimary}),fontSize:z.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:G||we?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:G||we?.6:1,...V},onMouseEnter:y=>{H.onMouseEnter?.(y),!y.defaultPrevented&&!G&&!we&&(O||Ke?.colorPrimary)&&(y.currentTarget.style.backgroundColor=pt)},onMouseLeave:y=>{H.onMouseLeave?.(y),!y.defaultPrevented&&(O||Ke?.colorPrimary)&&(y.currentTarget.style.backgroundColor=st)},onMouseDown:y=>{H.onMouseDown?.(y),y.defaultPrevented||(y.currentTarget.style.transform="scale(0.985)")},onMouseUp:y=>{H.onMouseUp?.(y),y.defaultPrevented||(y.currentTarget.style.transform="scale(1)")},children:(0,mn.jsx)(rr,{content:Z})}),ne&&(0,mn.jsx)(Pn,{status:ne,errorMessage:Be}),xe&&(0,mn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:y=>{y.target===y.currentTarget&&De(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)(co,{sessionId:xe.sessionId,nonce:xe.nonce,checkoutMode:"full",billingApiUrl:he,locale:_,theme:F,...qe?{appearance:qe}:{},buttonsTheme:ce,buttonsStyles:j,initialErrorMessage:xe.errorMessage,cardTitleContent:null,onComplete:ut,onError:He,onDecline:it})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,useCheckout,useElements,useFloPay,usePayPalFloPay});