@flopay/react 1.4.8 → 1.4.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var Pi=Object.create;var Dr=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var vi=Object.getOwnPropertyNames;var Ci=Object.getPrototypeOf,Si=Object.prototype.hasOwnProperty;var wi=(e,t)=>{for(var n in t)Dr(e,n,{get:t[n],enumerable:!0})},ia=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of vi(t))!Si.call(e,o)&&o!==n&&Dr(e,o,{get:()=>t[o],enumerable:!(l=bi(t,o))||l.enumerable});return e};var sa=(e,t,n)=>(n=e!=null?Pi(Ci(e)):{},ia(t||!e||!e.__esModule?Dr(n,"default",{value:e,enumerable:!0}):n,e)),ki=e=>ia(Dr({},"__esModule",{value:!0}),e);var ys={};wi(ys,{AddressElement:()=>Wa,DirectPayPalButton:()=>vr,FloPayAutomaticPaymentButton:()=>Qa,FloPayCheckout:()=>no,FloPayProvider:()=>gr,PayPalButton:()=>Xa,PaymentElement:()=>Ka,SplitCardForm:()=>Gr,VaultCardFields:()=>Nr,useCheckout:()=>ma,useElements:()=>zr,useFloPay:()=>ln,usePayPalFloPay:()=>Or});module.exports=ki(ys);var Ri=()=>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,Ae=Ri();var Ct=require("react"),la=require("@flopay/shared");var Po=require("react"),_n=(0,Po.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),sn=(0,Po.createContext)({session:null,loading:!1,error:null});var Ii=Symbol.for("@flopay/js.telemetry.bridge.v1"),Ei=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function _i(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},flush:async()=>{},destroy:()=>{}}}function xi(e){let t=_i(),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 Lr(e){let t=globalThis[Ei];return xi(t?.(e)??{})}function xt(e){if(e)return e[Ii]}var ca=require("react/jsx-runtime");function gr({flopay:e,paypalFlopay:t,options:n,children:l}){let[o,s]=(0,Ct.useState)(e instanceof Promise?null:e),[u,c]=(0,Ct.useState)(t instanceof Promise||!t?null:t),[I,O]=(0,Ct.useState)(null),m=(0,Ct.useRef)(null),x=(0,Ct.useRef)(null),w=(0,Ct.useRef)(null);(0,Ct.useEffect)(()=>{if(!o)return;let E=xt(o);return m.current=E?.beginCheckout()??E?.now()??0,E?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{E?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),(0,Ct.useEffect)(()=>{let E=!1;return e instanceof Promise?e.then(L=>{E||s(L)}):s(e),()=>{E=!0}},[e]),(0,Ct.useEffect)(()=>{let E=!1;if(!t){c(null);return}return t instanceof Promise?t.then(L=>{E||c(L)}):c(t),()=>{E=!0}},[t]),(0,Ct.useEffect)(()=>{if(!o){O(null);return}let E=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return O(E),()=>{E.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,Ct.useEffect)(()=>{if(!o||!I||x.current===I)return;x.current=I;let E=xt(o);E?.log({name:"checkout.rendered",stage:"checkout_render"}),E?.performance({stage:"checkout_render",durationMs:E.elapsed(m.current??0),durationMode:"machine"})},[I,o]);let F=(0,Ct.useCallback)(()=>{if(!o||!I||w.current===I)return;w.current=I;let E=xt(o);E?.log({name:"checkout.interactive",stage:"checkout_interactive"}),E?.performance({stage:"checkout_interactive",durationMs:E.elapsed(m.current??0),durationMode:"machine"})},[I,o]),d=(0,la.resolveBillingApiUrl)(n?.billingApiUrl),g=(0,Ct.useMemo)(()=>({flopay:o,paypalFlopay:u,elements:I,billingApiUrl:d,reportInteractive:F}),[o,u,I,d,F]);return(0,ca.jsx)(_n.Provider,{value:g,children:l})}var N=sa(require("react"),1),kr=require("@flopay/js"),Be=require("@flopay/shared");var Es=require("react"),nt=require("react/jsx-runtime");function Ti(){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 Bi(){return(0,nt.jsx)(nt.Fragment,{children:"Go back"})}function Mi(){return(0,nt.jsx)(nt.Fragment,{children:"Secure card checkout"})}function Gn(e){return e!==void 0&&(e===""||e===null||e===!1)}function Jn({content:e}){return(0,nt.jsx)(nt.Fragment,{children:e===void 0?(0,nt.jsx)(Ti,{}):e})}function Xn({content:e}){return(0,nt.jsx)(nt.Fragment,{children:e===void 0?(0,nt.jsx)(Bi,{}):e})}function hr({content:e}){return(0,nt.jsx)(nt.Fragment,{children:e===void 0?(0,nt.jsx)(Mi,{}):e})}var dt=require("@stripe/react-stripe-js"),R=require("@flopay/shared"),dn=require("@flopay/js");var xn=require("react"),da=require("react/jsx-runtime");function Nr({capture:e,html:t,messageToken:n,expectedOrigin:l,theme:o,containerStyle:s,onReady:u,onError:c,onValidation:I}){let O=(0,xn.useRef)(null),m=(0,xn.useRef)(u),x=(0,xn.useRef)(c),w=(0,xn.useRef)(I);m.current=u,x.current=c,w.current=I;let F=(0,xn.useRef)(o);return F.current=o,(0,xn.useEffect)(()=>{let d=O.current;if(!d)return;let g=!0,E=!1,L=()=>{!g||E||(E=!0,m.current?.())},P=e.on("ready",()=>{L()}),W=e.on("error",re=>{x.current?.(re.message??"There was a problem loading the secure card form.")}),Z=e.on("validation",re=>{w.current?.(re.message??null)}),me={html:t,...n?{messageToken:n}:{},...l?{expectedOrigin:l}:{},...F.current?{theme:F.current}:{}};return e.mount(d,me).then(()=>{L()}).catch(re=>{g&&x.current?.(re instanceof Error?re.message:"Failed to load the secure card form.")}),()=>{g=!1,P(),W(),Z(),e.unmount()}},[e,t,n,l]),(0,xn.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,da.jsx)("div",{ref:O,"data-testid":"flopay-vault-card-fields",style:s})}var Fs=require("react"),Pr=require("react/jsx-runtime");function Zn({children:e,margin:t,icon:n=!0,styleOverride:l}){return(0,Pr.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,Pr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Pr.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 ua={alipay:new URL("./payment-logos/alipay.svg",Ae).href,bancontact:new URL("./payment-logos/bancontact.svg",Ae).href,blik:new URL("./payment-logos/blik.svg",Ae).href,eps:new URL("./payment-logos/eps.svg",Ae).href,giropay:new URL("./payment-logos/giropay.svg",Ae).href,ideal:new URL("./payment-logos/ideal.svg",Ae).href,klarna:new URL("./payment-logos/klarna.svg",Ae).href,p24:new URL("./payment-logos/p24.svg",Ae).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",Ae).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",Ae).href};var r=sa(require("react"),1);var Qn=require("react"),pa=require("@flopay/shared");function ln(){return(0,Qn.useContext)(_n).flopay}function Or(){return(0,Qn.useContext)(_n).paypalFlopay??null}function zr(){return(0,Qn.useContext)(_n).elements}function ma(){return(0,Qn.useContext)(sn)}function Ur(){return(0,Qn.useContext)(_n).billingApiUrl||(0,pa.resolveBillingApiUrl)()}var js=require("react"),ft=require("react/jsx-runtime"),Tn=1200,bn=1500;function vn({status:e,errorMessage:t}){return(0,ft.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,ft.jsxs)("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,ft.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,ft.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,ft.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,ft.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,ft.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,ft.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,ft.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,ft.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,ft.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,ft.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,ft.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,ft.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,ft.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&"PROCESSING...",e==="success"&&"PAYMENT SUCCESSFUL",e==="error"&&"PAYMENT FAILED"]}),e==="success"&&(0,ft.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:"You will be automatically redirected, do not close or navigate away from this window."}),e==="error"&&t&&(0,ft.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,ft.jsx)("style",{children:`
1
+ "use strict";var Ii=Object.create;var zr=Object.defineProperty;var Ei=Object.getOwnPropertyDescriptor;var _i=Object.getOwnPropertyNames;var xi=Object.getPrototypeOf,Ti=Object.prototype.hasOwnProperty;var Bi=(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)),Mi=e=>ya(zr({},"__esModule",{value:!0}),e);var Is={};Bi(Is,{AddressElement:()=>ti,DirectPayPalButton:()=>kr,FloPayAutomaticPaymentButton:()=>si,FloPayCheckout:()=>lo,FloPayProvider:()=>vr,PayPalButton:()=>ai,PaymentElement:()=>ei,SplitCardForm:()=>Qr,VaultCardFields:()=>$r,useCheckout:()=>Ca,useElements:()=>jr,useFloPay:()=>ln,usePayPalFloPay:()=>qr});module.exports=Mi(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,Le=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 vr({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),m=(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 m.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(D=>{R||s(D)}):s(e),()=>{R=!0}},[e]),(0,St.useEffect)(()=>{let R=!1;if(!t){c(null);return}return t instanceof Promise?t.then(D=>{R||c(D)}):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(m.current??0),durationMode:"machine"})},[k,o]);let B=(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(m.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:B}),[o,u,k,d,B]);return(0,ha.jsx)(_n.Provider,{value:f,children:l})}var L=fa(require("react"),1),_r=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 er(e){return e!==void 0&&(e===""||e===null||e===!1)}function tr({content:e}){return(0,at.jsx)(at.Fragment,{children:e===void 0?(0,at.jsx)(Oi,{}):e})}function nr({content:e}){return(0,at.jsx)(at.Fragment,{children:e===void 0?(0,at.jsx)(zi,{}):e})}function Cr({content:e}){return(0,at.jsx)(at.Fragment,{children:e===void 0?(0,at.jsx)(Ui,{}):e})}var pt=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),m=(0,xn.useRef)(u),E=(0,xn.useRef)(c),S=(0,xn.useRef)(k);m.current=u,E.current=c,S.current=k;let B=(0,xn.useRef)(o);return B.current=o,(0,xn.useEffect)(()=>{let d=N.current;if(!d)return;let f=!0,R=!1,D=()=>{!f||R||(R=!0,m.current?.())},g=e.on("ready",()=>{D()}),V=e.on("error",oe=>{E.current?.(oe.message??"There was a problem loading the secure card form.")}),Z=e.on("validation",oe=>{S.current?.(oe.message??null)}),he={html:t,...n?{messageToken:n}:{},...l?{expectedOrigin:l}:{},...B.current?{theme:B.current}:{}};return e.mount(d,he).then(()=>{D()}).catch(oe=>{f&&E.current?.(oe instanceof Error?oe.message:"Failed to load the secure card form.")}),()=>{f=!1,g(),V(),Z(),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"),Sr=require("react/jsx-runtime");function rr({children:e,margin:t,icon:n=!0,styleOverride:l}){return(0,Sr.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...l??{}},children:[n&&(0,Sr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Sr.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var ba={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=fa(require("react"),1);var or=require("react"),va=require("@flopay/shared");function ln(){return(0,or.useContext)(_n).flopay}function qr(){return(0,or.useContext)(_n).paypalFlopay??null}function jr(){return(0,or.useContext)(_n).elements}function Ca(){return(0,or.useContext)(sn)}function Kr(){return(0,or.useContext)(_n).billingApiUrl||(0,va.resolveBillingApiUrl)()}var tl=require("react"),ft=require("react/jsx-runtime"),Tn=1200,Cn=1500;function Sn({status:e,errorMessage:t}){return(0,ft.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,ft.jsxs)("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,ft.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,ft.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,ft.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,ft.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,ft.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,ft.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,ft.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,ft.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,ft.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,ft.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,ft.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,ft.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,ft.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&"PROCESSING...",e==="success"&&"PAYMENT SUCCESSFUL",e==="error"&&"PAYMENT FAILED"]}),e==="success"&&(0,ft.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:"You will be automatically redirected, do not close or navigate away from this window."}),e==="error"&&t&&(0,ft.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,ft.jsx)("style",{children:`
2
2
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
3
3
  @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
4
4
  @keyframes flopay-draw { to { stroke-dashoffset: 0; } }
5
5
  @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
6
- `})]})})}var ya=require("@flopay/shared");function fa(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function bo(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ga(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 vo(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 Ai=[{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 Ai)if(n.test(t))return l;return e}function $r(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function ha(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Pa(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function qr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var jr="flopay_recent_completion_";function er(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(jr+e,JSON.stringify(t))}catch{}}function ba(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(jr+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(jr+e),!1):!0}catch{return!1}}function va(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var A=require("react"),wa=require("@paypal/paypal-js"),Vr=require("@flopay/js"),Mn=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 Fi(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 Hn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Bn(e){if(typeof e!="object"||e===null)return;let t=e;return Hn(t.code)??Hn(t.type)??Hn(t.name)}function tr(e){if(!(typeof e!="object"||e===null))return Hn(e.decline_code)}function br(e){return typeof e!="object"||e===null?!1:Hn(e.type)?.toLowerCase()==="card_error"||tr(e)!==void 0}function Ln(e){let t=Fi(e)?.toLowerCase()??"",l=`${Bn(e)?.toLowerCase()??""} ${t}`;return l.includes("popup")&&l.includes("block")}var cn=require("react/jsx-runtime"),Hr=45,Di=1e3,Li=11e3,Ni=["https://www.paypal.com","https://www.sandbox.paypal.com"],Ca="We couldn't open PayPal. Try again or choose another payment method.",Oi={width:"100%",minHeight:Hr,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 Sa(e){return e.includes("No ack for postMessage init()")&&Ni.some(t=>e.includes(t))&&e.includes("10000ms")}function zi(e){return e?`${Ca} Allow pop-ups for this site, then try again.`:Ca}function ka({sessionId:e,nonce:t,billingApiUrl:n,email:l,clientId:o,environment:s,currency:u,isSubscription:c,onTokenizedBody:I,onComplete:O,onErrorChange:m,onDecline:x,onTechnicalFailure:w,isProcessing:F=!1,onLoadStateChange:d,onInitializationStateChange:g,allowAutomaticRetry:E=!0,onButtonClick:L,runBeforeButtonClick:P,session:W,existingOrderId:Z,telemetry:me,telemetryContext:re,debug:z=!1}){let te=ln(),Y=(0,A.useMemo)(()=>{if(te)return null;let f=Lr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Mn.SDK_VERSION,enabled:me!==!1});return f.setCheckoutContext(re??{}),f.beginCheckout(re??{}),f},[n,te,me,re?.checkoutMode,re?.layout]),ye=(0,A.useMemo)(()=>xt(te),[te]);(0,A.useEffect)(()=>()=>{Y&&Y.flush().catch(()=>{}).finally(()=>Y.destroy())},[Y]);let V=(0,A.useMemo)(()=>({error:f=>{ye?ye.error(f):Y?.error(f)},log:f=>{ye?ye.log(f):Y?.log(f)},performance:f=>{ye?ye.performance(f):Y?.performance(f)},terminal:f=>{ye?ye.terminal(f):Y?.terminal(f)},startTiming:()=>ye?.now()??Y?.now()??0,elapsed:f=>ye?.elapsed(f)??Math.max(0,(Y?.now()??f)-f)}),[ye,Y]),G=(0,A.useRef)(null),se=(0,A.useRef)(0),Fe=(0,A.useRef)(null),he=(0,A.useRef)(!1),[ge,ne]=(0,A.useState)(!1),[fe,ve]=(0,A.useState)(!1),[le,Ne]=(0,A.useState)(0),Ie=(0,A.useRef)(0),[Se,_]=(0,A.useState)(!1),ae=(0,A.useRef)(!1),de=(0,A.useRef)(!1),[ze,Oe]=(0,A.useState)(!1),[Q,D]=(0,A.useState)(!1),J=(0,A.useMemo)(()=>n.replace(/\/+$/,""),[n]),ue=(0,A.useMemo)(()=>JSON.stringify([J,o,u,s??"",c,e,Z??""]),[J,o,u,s,Z,c,e]),Ee=(0,A.useRef)(ue),it=Ee.current!==ue,[Ze,Xe]=(0,A.useState)([]),y=f=>{z&&Xe(ut=>[...ut,`${new Date().toISOString().slice(11,23)} ${f}`])},je=(0,A.useRef)(I),Ue=(0,A.useRef)(O),We=(0,A.useRef)(m),Ve=(0,A.useRef)(x),Yt=(0,A.useRef)(w),ht=(0,A.useRef)(L),wt=(0,A.useRef)(d),h=(0,A.useRef)(g),we=(0,A.useRef)(P),He=(0,A.useRef)(W),st=(0,A.useRef)(l),rt=(0,A.useRef)(t),Qe=(0,A.useRef)(null),Ye=(0,A.useRef)(0),Ce=(0,A.useRef)(null),Pt=(0,A.useRef)(null),Ke=(0,A.useRef)(new Map),Nt=(0,A.useRef)(new Map),kt=(0,A.useRef)(!1);(0,A.useEffect)(()=>(kt.current=!0,()=>{kt.current=!1}),[]),(0,A.useEffect)(()=>{je.current=I},[I]),(0,A.useEffect)(()=>{Ue.current=O},[O]),(0,A.useEffect)(()=>{We.current=m},[m]),(0,A.useEffect)(()=>{Ve.current=x},[x]),(0,A.useEffect)(()=>{Yt.current=w},[w]),(0,A.useEffect)(()=>{ht.current=L},[L]),(0,A.useEffect)(()=>{wt.current=d},[d]),(0,A.useEffect)(()=>{h.current=g},[g]),(0,A.useEffect)(()=>{we.current=P},[P]),(0,A.useEffect)(()=>{He.current=W},[W]),(0,A.useEffect)(()=>{st.current=l},[l]),(0,A.useEffect)(()=>{rt.current=t},[t]),(0,A.useEffect)(()=>{Ie.current=le},[le]),(0,A.useEffect)(()=>{Se&&Fe.current?.focus()},[Se,le]);let yn=(0,A.useCallback)(()=>{window.setTimeout(()=>{Fe.current?.focus()},0)},[]),wn=(0,A.useCallback)(()=>{ne(!1),Ne(f=>f+1)},[]),kn=(0,A.useCallback)(()=>{_(!1),(G.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??G.current)?.focus?.()},[]);(0,A.useEffect)(()=>{!ge||!he.current||(he.current=!1,kn())},[kn,ge,le]);let On=(0,A.useCallback)((f,ut)=>{let Tt=Yt.current;if(Tt){Tt("paypal",f,ut);return}We.current?.(zi(ut?.popupBlocked??Ln(f)))},[]),gt=()=>{Ce.current?.timer&&(clearTimeout(Ce.current.timer),Ce.current.timer=null)},Ot=()=>{gt();let f=Ye.current+1;return Ye.current=f,Pt.current=null,Ce.current={generation:f,timer:null,yieldedControl:!1},_(!1),f},Mt=f=>f!==void 0&&Ce.current?.generation!==f?!1:(gt(),Ce.current=null,Pt.current=null,!0),Gt=f=>{let ut=f?.generation??Ce.current?.generation??Ye.current;(!f?.generation||Ce.current?.generation===ut)&&(gt(),Ce.current=null),Pt.current=ut,f?.showRetry&&_(!0),f?.remount&&wn(),f?.focus!==!1&&yn()},Qt=f=>Ce.current?.generation===f&&Pt.current!==f,fn=f=>{typeof document<"u"&&document.visibilityState!=="visible"||(gt(),f.timer=setTimeout(()=>{Ce.current?.generation===f.generation&&(Ce.current=null,Pt.current=f.generation,On(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),_(!0),wn(),yn())},600))},X=()=>{let f=Ce.current;f?.yieldedControl&&fn(f)},An=()=>{let f=Ce.current;f&&(f.yieldedControl=!0,gt())},gn=f=>{let ut=Qe.current;return ut&&Nt.current.set(f,ut),f};(0,A.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?X():An()};return document.addEventListener("visibilitychange",f),window.addEventListener("focus",X),window.addEventListener("blur",An),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("focus",X),window.removeEventListener("blur",An),gt()}},[]),(0,A.useEffect)(()=>{Ee.current!==ue&&(Ee.current=ue,ae.current=!1,de.current=!1,ne(!1),ve(!1),Oe(!1),h.current?.("loading"))},[ue]),(0,A.useEffect)(()=>{ct(()=>wt.current?.(ge&&!ze))},[ge,ze]);let zt=(0,Mn.normalizeGatewayEnvironment)(s);(0,A.useEffect)(()=>{let f=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",ut=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(y(`mount clientId=${f} env=${s??"(unset)"}\u2192${zt??"live"} ccy=${u} sub=${c}`),y(`ua=${ut.slice(0,80)}${ut.length>80?"\u2026":""}`),!o){y("FAIL: clientId empty \u2014 gateway misconfigured"),Oe(!0),V.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!G.current){y("FAIL: containerRef not attached");return}se.current=V.startTiming(),V.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Tt=!1,Rn=!1,Pe=()=>Tt||Rn,Vt,en=!1,Ht=()=>{Vt=(0,Mn.generateIdempotencyKey)(),Vt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),en=!0},tn=null,nn=!1,Kt=null,In=!1,Ut=()=>{!Kt||In||(In=!0,Kt.close().catch(()=>{}))},$t=null,ke=()=>{$t!==null&&(V.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),V.performance({stage:"overlay_return",durationMs:V.elapsed($t),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),$t=null)},lt=!1,et=G.current,hn=null,rn=null,bt=[],At=b=>{if(!b||typeof b.getBoundingClientRect!="function")return"(no rect)";let v=b.getBoundingClientRect();return`${Math.round(v.width)}\xD7${Math.round(v.height)}`},Ft=b=>{if(!b)return"(empty)";try{let v=new URL(b,typeof window<"u"?window.location.href:"https://localhost"),B=v.pathname.toLowerCase();return B.includes("checkcaptcha")||B.includes("captcha")?`CAPTCHA(${v.host}${B})`:B.includes("risk")||B.includes("challenge")?`RISK(${v.host}${B})`:B.includes("smart/buttons")?`smart-buttons(${v.host})`:`${v.host}${B}`.slice(0,100)}catch{return b.slice(0,80)}},zn=b=>{let v=b.getAttribute("src"),B=b.getAttribute("srcdoc"),pe=b.getAttribute("name"),Re=b.getAttribute("sandbox"),De=[];return v&&De.push(`src=${Ft(v)}`),B&&De.push(`srcdoc[${B.length}ch]`),!v&&!B&&De.push("src=(empty) srcdoc=(empty)"),pe&&De.push(`name=${pe.slice(0,40)}`),Re!==null&&De.push(`sandbox="${Re.slice(0,40)}"`),De.join(" ")},Fn=b=>{if(!(b instanceof HTMLIFrameElement))return"";try{let v=b.contentDocument;if(!v)return"cd=null";let B=v.body?.children.length??0,pe=v.body?.innerHTML.length??0,Re=v.head?.innerHTML.length??0;return`cd=same-origin readyState=${v.readyState} body[${B}children,${pe}ch] head[${Re}ch]`}catch(v){return`cd=cross-origin(${v.message.slice(0,30)})`}},En=[],qt=b=>{if(Pe())return;let v=b.message??String(b.error??"(no message)");v&&(v.toLowerCase().includes("paypal")||v.toLowerCase().includes("zoid")||v.toLowerCase().includes("postrobot")||v.toLowerCase().includes("storage"))&&(y(`window:error ${v.slice(0,140)}`),En.push(v))},on=b=>{if(Pe())return;let v=b.reason instanceof Error?b.reason.message:String(b.reason??"(no reason)");v&&(v.toLowerCase().includes("paypal")||v.toLowerCase().includes("zoid")||v.toLowerCase().includes("postrobot")||v.toLowerCase().includes("storage"))&&(y(`window:rejection ${v.slice(0,140)}`),En.push(v))};z&&typeof window<"u"&&(window.addEventListener("error",qt),window.addEventListener("unhandledrejection",on));let Me={value:0};if(z&&typeof PerformanceObserver<"u")try{rn=new PerformanceObserver(b=>{if(!Pe())for(let v of b.getEntries()){if(!v.name.toLowerCase().includes("paypal"))continue;Me.value+=1;let B=Math.round(v.duration);y(`net ${B}ms ${v.name.slice(0,90)}`)}}),rn.observe({type:"resource",buffered:!0})}catch{}let M=()=>{for(hn?.disconnect(),hn=null,rn?.disconnect(),rn=null;bt.length;)clearTimeout(bt.pop());z&&typeof window<"u"&&(window.removeEventListener("error",qt),window.removeEventListener("unhandledrejection",on))},j=b=>{if(!b)return!1;let v=b.toLowerCase();return v.includes("zoid destroyed")||v.includes("destroyed all components")||v.includes("window closed")||v.includes("detected container element removed")},ee=b=>{if(Pe()||j(b))return;let v=Dn(b)??b;ct(()=>We.current?.(v))},U=b=>{Tt||(Oe(!0),b.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:",b))},K=(b,v=!1)=>{if(Tt)return;let B=ae.current||!E;if(nn)return;nn=!0,Rn=!0,M(),Ut();let pe=v||Sa(b);if(pe&&E&&!ae.current){ae.current=!0,ne(!1),D(!1),ve(!0),h.current?.("retrying"),tn=setTimeout(()=>{Tt||Ne(Re=>Re+1)},Di);return}if(pe||B){if(ne(!1),D(!1),ve(!1),Oe(!0),h.current?.("exhausted"),!de.current){de.current=!0;let Re=Sa(b)?"paypal_init_timeout":v?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",Re)}return}U(b)};Oe(!1);let q=async(b,v=Qe.current)=>{if(Pe())return;let B=v?.sessionId??e;if(je.current){await je.current(b,{sessionId:B,accountPatch:v?.accountPatch,nonce:v?.nonce});return}let pe=V.startTiming();V.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Re=()=>{V.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),V.performance({stage:"processing",durationMs:V.elapsed(pe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let De=He.current,Wt=v?.accountPatch?.email??st.current,qe=v?.accountPatch?.userId??De?.customer?.id??De?.accountData?.userId??"",ce=await new Vr.PaymentAPI(J,{telemetry:!1}).processPayment(qe,{sessionId:B,nonce:v?.nonce??rt.current,tokenizedData:b,accountData:{userId:qe,email:Wt??De?.customer?.email??"",firstName:v?.accountPatch?.firstName??De?.customer?.firstName??De?.accountData?.firstName??"",lastName:v?.accountPatch?.lastName??De?.customer?.lastName??De?.accountData?.lastName??"",country:v?.accountPatch?.country??De?.customer?.country??De?.accountData?.country??void 0,zip:v?.accountPatch?.zip??De?.customer?.zip??De?.accountData?.zip??void 0}});if(ce.ok){if(Rn||Tt&&kt.current)return;Re(),V.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ct(()=>Ue.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Pe())return;let T=await ce.json().catch(()=>null),pt=T?.message??"PayPal payment failed.",Rt=Dn(pt)??pt;Re(),ce.status===400&&(typeof T?.declineCode=="string"||!Array.isArray(T?.fields))?V.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ce.status===400||ce.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:ce.status>=500?"5xx":ce.status>=400?"4xx":ce.status>=300?"3xx":"unknown",failureCategory:ce.status>=500?"server_error":void 0}),ee(Rt),ct(()=>Ve.current?.(St("paypal",Rt,{code:T?.code,declineCode:T?.declineCode})));return}catch(De){if(Pe())return;Re(),V.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Wt=De instanceof Error?De.message:"PayPal payment failed.",qe=Dn(Wt)??Wt;ee(qe),ct(()=>Ve.current?.(St("paypal",qe)));return}},p=()=>new Mn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),k=b=>Pe()?Promise.reject(p()):Promise.resolve(b),be=async b=>{if(Pe())throw p();en||Ht();let v=Qe.current,B=v?.sessionId??e,pe=v?.nonce??rt.current;V.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Re=await new Vr.PaymentAPI(J,{telemetry:!1}).createSessionIntent(B,pe??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Vt});if(Pe())throw p();if(Re.provider!=="paypal")throw new Error(b);return V.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Re.providerObjectId},at=(b,v)=>{let B=v?.nonce??rt.current;if(!B)return;let pe=v?.sessionId??e,Re=tr(b)??Bn(b)??"provider_declined";new Vr.PaymentAPI(J,{telemetry:!1}).reportSessionIntentDecline(pe,B,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Re}).catch(()=>{})},$e=le;y("loadScript:scheduled (deferred 1 tick)");let Te=null,Bt=setTimeout(()=>{if(Tt){y("loadScript:skipped (cancelled before defer ran)");return}y("loadScript:start");let b=zt==="live"?"production":zt;Te=(0,wa.loadScript)({clientId:o,currency:u,intent:c?"subscription":"capture",vault:c?!0:void 0,...b?{environment:b}:{},...b==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Te.then(v=>{if(y(`loadScript:resolved inactive=${Pe()} ns=${!!v} buttons=${!!v?.Buttons}`),Pe())return;if(!v?.Buttons){y("FAIL: namespace missing Buttons factory"),K("PayPal SDK did not expose the Buttons factory.");return}V.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let B=async qe=>{if(Pe()||Ie.current!==$e)return;let _e=qe.subscriptionID??qe.orderID??"",ce=_e?Nt.current.get(_e):Ke.current.get($e);if(!(!ce||!Qt(ce.generation))&&Mt(ce.generation)){Nt.current.delete(_e),Ke.current.delete(ce.surfaceKey),ke();try{if(D(!0),ct(()=>We.current?.(null)),!_e)throw new Mn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await q({id:_e,isPaypal:!0},ce)}catch(T){ee(T instanceof Error?T.message:"PayPal capture failed.")}finally{Pe()||D(!1)}}},pe=v.Buttons({style:{layout:"horizontal",height:Hr,tagline:!1},onClick:async(qe,_e)=>{if(Pe()){await _e.reject();return}Ht();let ce=we.current,T={};if(ce)try{let mt=await ce("paypal");if(Pe()){await _e.reject();return}if(!mt.proceed){Qe.current=null,Ke.current.delete($e),await _e.reject();return}T={sessionId:mt.sessionId,accountPatch:mt.accountPatch,nonce:mt.nonce}}catch(mt){y(`onClick:runBeforeButtonClick rejected msg=${(mt instanceof Error?mt.message:String(mt)).slice(0,120)}`),Qe.current=null,Ke.current.delete($e),await _e.reject();return}ct(()=>ht.current?.("paypal"));let Rt={generation:Ot(),surfaceKey:$e,...T};Qe.current=Rt,Ke.current.set($e,Rt),await _e.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"}),$t=V.startTiming()},createOrder:c?void 0:Z?()=>k(Z).then(gn):()=>be("Failed to create PayPal order.").then(gn),createSubscription:c?Z?()=>k(Z).then(gn):()=>be("Failed to create PayPal subscription.").then(gn):void 0,onApprove:B,onCancel:()=>{if(Pe())return;let qe=Ke.current.get($e)??Qe.current;qe&&Ke.current.delete(qe.surfaceKey),Qe.current=null,ke(),V.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),he.current=!0,Gt({generation:qe?.generation,remount:!0,focus:!1})},onError:qe=>{if(Pe()||Ie.current!==$e)return;let _e=qe instanceof Error?qe.message:"PayPal failed to render.";if(y(`onError rendered=${lt} msg=${_e.slice(0,120)}`),lt){let ce=Ke.current.get($e)??Qe.current;if(ce&&!Qt(ce.generation)||!ce&&Pt.current===Ye.current)return;if(j(_e)){Mt(ce?.generation);return}if(ke(),br(qe)){V.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),at(qe,ce),ct(()=>Ve.current?.(St("paypal",_e))),ce&&Ke.current.delete(ce.surfaceKey),Qe.current=null,Mt(ce?.generation);return}let T=_e.toLowerCase();V.error({errorCode:T.includes("popup")&&T.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ce&&Ke.current.delete(ce.surfaceKey),Qe.current=null,Gt({generation:ce?.generation,remount:!0,showRetry:!0,focus:!0}),On(qe,{code:"paypal_runtime_failed"});return}K(_e)}}),Re=pe.isEligible();if(y(`isEligible=${Re}`),V.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Re){ne(!1),K("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Kt=pe,z&&y(`container:dims ${At(et)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),z&&typeof MutationObserver<"u"&&(hn=new MutationObserver(qe=>{if(!Pe()){for(let _e of qe)if(_e.type==="childList")_e.addedNodes.forEach(ce=>{if(!(ce instanceof Element))return;let T=ce.tagName.toLowerCase(),pt=(ce.getAttribute("title")??"").slice(0,40),Rt=T==="iframe"?` ${zn(ce)}`:"";y(`child+ ${T}${pt?` title="${pt}"`:""}${Rt} dims=${At(ce)}`)});else if(_e.type==="attributes"&&_e.target instanceof Element){let ce=_e.target;if(ce.tagName.toLowerCase()!=="iframe")continue;let T=_e.attributeName;(T==="src"||T==="srcdoc")&&y(`attr~ iframe ${T}=${T==="srcdoc"?`[${(ce.getAttribute("srcdoc")??"").length}ch]`:Ft(ce.getAttribute("src"))} dims=${At(ce)}`)}}}),hn.observe(et,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Wt=qe=>{if(Pe()||lt)return;let _e=et.querySelectorAll("iframe"),ce=typeof document<"u"&&"hasStorageAccess"in document;y(`watchdog:${qe} container=${At(et)} children=${et.childElementCount} iframes=${_e.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${ce} paypalNetRequests=${Me.value}`),_e.forEach((T,pt)=>{let Rt=(T.getAttribute("title")??"").slice(0,40);y(` iframe[${pt}] ${At(T)}${Rt?` title="${Rt}"`:""} ${zn(T)}`);let mt=Fn(T);mt&&y(` ${mt}`)}),En.length===0&&y(" (no PayPal/zoid window errors captured)")};z&&(bt.push(setTimeout(()=>Wt("3s"),3e3)),bt.push(setTimeout(()=>Wt("8s"),8e3)),bt.push(setTimeout(()=>Wt("15s"),15e3))),y("render:start"),bt.push(setTimeout(()=>{Pe()||lt||(y("watchdog:11s retryable render timeout"),K("PayPal Buttons render did not settle within 11000ms.",!0))},Li)),pe.render(et).then(()=>{if(y(`render:resolved inactive=${Pe()}`),M(),Pe()){Ut();return}lt=!0,ne(!0),ve(!1),h.current?.("ready"),V.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),V.performance({stage:"provider_ready",durationMs:V.elapsed(se.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(qe=>{let _e=qe instanceof Error?qe.message:"PayPal failed to render.";y(`render:rejected msg=${_e.slice(0,120)}`),M(),K(_e)})}).catch(v=>{let B=v instanceof Error?v.message:"PayPal SDK failed to load.";y(`loadScript:rejected msg=${B.slice(0,120)}`),K(B)})},0);return()=>{Tt=!0,clearTimeout(Bt),tn&&clearTimeout(tn),M(),Ut()}},[E,J,o,u,s,c,e,Z,le,V]);let ot=z?(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=${ge} failed=${ze})`,Ze.length===0?`
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 ar(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"),Mn=require("@flopay/shared");function ut(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function 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 Bn(e){if(typeof e!="object"||e===null)return;let t=e;return Yn(t.code)??Yn(t.type)??Yn(t.name)}function ir(e){if(!(typeof e!="object"||e===null))return Yn(e.decline_code)}function wr(e){return typeof e!="object"||e===null?!1:Yn(e.type)?.toLowerCase()==="card_error"||ir(e)!==void 0}function Nn(e){let t=qi(e)?.toLowerCase()??"",l=`${Bn(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 Ba({sessionId:e,nonce:t,billingApiUrl:n,email:l,clientId:o,environment:s,currency:u,isSubscription:c,onTokenizedBody:k,onComplete:N,onErrorChange:m,onDecline:E,onTechnicalFailure:S,isProcessing:B=!1,onLoadStateChange:d,onInitializationStateChange:f,allowAutomaticRetry:R=!0,onButtonClick:D,runBeforeButtonClick:g,session:V,existingOrderId:Z,telemetry:he,telemetryContext:oe,debug:O=!1}){let ee=ln(),H=(0,T.useMemo)(()=>{if(ee)return null;let M=Ur({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Mn.SDK_VERSION,enabled:he!==!1});return M.setCheckoutContext(oe??{}),M.beginCheckout(oe??{}),M},[n,ee,he,oe?.checkoutMode,oe?.layout]),Pe=(0,T.useMemo)(()=>Tt(ee),[ee]);(0,T.useEffect)(()=>()=>{H&&H.flush().catch(()=>{}).finally(()=>H.destroy())},[H]);let q=(0,T.useMemo)(()=>({error:M=>{Pe?Pe.error(M):H?.error(M)},log:M=>{Pe?Pe.log(M):H?.log(M)},performance:M=>{Pe?Pe.performance(M):H?.performance(M)},terminal:M=>{Pe?Pe.terminal(M):H?.terminal(M)},startTiming:()=>Pe?.now()??H?.now()??0,elapsed:M=>Pe?.elapsed(M)??Math.max(0,(H?.now()??M)-M)}),[Pe,H]),W=(0,T.useRef)(null),ce=(0,T.useRef)(0),Ne=(0,T.useRef)(null),Se=(0,T.useRef)(!1),[Ce,te]=(0,T.useState)(!1),[be,ke]=(0,T.useState)(!1),[de,ze]=(0,T.useState)(0),Be=(0,T.useRef)(0),[Ee,I]=(0,T.useState)(!1),ie=(0,T.useRef)(!1),me=(0,T.useRef)(!1),[$e,Ue]=(0,T.useState)(!1),[Q,A]=(0,T.useState)(!1),Y=(0,T.useMemo)(()=>n.replace(/\/+$/,""),[n]),ye=(0,T.useMemo)(()=>JSON.stringify([Y,o,u,s??"",c,e,Z??""]),[Y,o,u,s,Z,c,e]),Me=(0,T.useRef)(ye),st=Me.current!==ye,[tt,et]=(0,T.useState)([]),p=M=>{O&&et(Xe=>[...Xe,`${new Date().toISOString().slice(11,23)} ${M}`])},je=(0,T.useRef)(k),qe=(0,T.useRef)(N),Ge=(0,T.useRef)(m),Ke=(0,T.useRef)(E),Yt=(0,T.useRef)(S),ht=(0,T.useRef)(D),kt=(0,T.useRef)(d),h=(0,T.useRef)(f),_e=(0,T.useRef)(g),Ve=(0,T.useRef)(V),lt=(0,T.useRef)(l),it=(0,T.useRef)(t),nt=(0,T.useRef)(null),Je=(0,T.useRef)(0),Re=(0,T.useRef)(null),Pt=(0,T.useRef)(null),He=(0,T.useRef)(new Map),zt=(0,T.useRef)(new Map),Rt=(0,T.useRef)(!1);(0,T.useEffect)(()=>(Rt.current=!0,()=>{Rt.current=!1}),[]),(0,T.useEffect)(()=>{je.current=k},[k]),(0,T.useEffect)(()=>{qe.current=N},[N]),(0,T.useEffect)(()=>{Ge.current=m},[m]),(0,T.useEffect)(()=>{Ke.current=E},[E]),(0,T.useEffect)(()=>{Yt.current=S},[S]),(0,T.useEffect)(()=>{ht.current=D},[D]),(0,T.useEffect)(()=>{kt.current=d},[d]),(0,T.useEffect)(()=>{h.current=f},[f]),(0,T.useEffect)(()=>{_e.current=g},[g]),(0,T.useEffect)(()=>{Ve.current=V},[V]),(0,T.useEffect)(()=>{lt.current=l},[l]),(0,T.useEffect)(()=>{it.current=t},[t]),(0,T.useEffect)(()=>{Be.current=de},[de]),(0,T.useEffect)(()=>{Ee&&Ne.current?.focus()},[Ee,de]);let yn=(0,T.useCallback)(()=>{window.setTimeout(()=>{Ne.current?.focus()},0)},[]),Rn=(0,T.useCallback)(()=>{te(!1),ze(M=>M+1)},[]),In=(0,T.useCallback)(()=>{I(!1),(W.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??W.current)?.focus?.()},[]);(0,T.useEffect)(()=>{!Ce||!Se.current||(Se.current=!1,In())},[In,Ce,de]);let zn=(0,T.useCallback)((M,Xe)=>{let Te=Yt.current;if(Te){Te("paypal",M,Xe);return}Ge.current?.(Wi(Xe?.popupBlocked??Nn(M)))},[]),gt=()=>{Re.current?.timer&&(clearTimeout(Re.current.timer),Re.current.timer=null)},Ut=()=>{gt();let M=Je.current+1;return Je.current=M,Pt.current=null,Re.current={generation:M,timer:null,yieldedControl:!1},I(!1),M},Mt=M=>M!==void 0&&Re.current?.generation!==M?!1:(gt(),Re.current=null,Pt.current=null,!0),Gt=M=>{let Xe=M?.generation??Re.current?.generation??Je.current;(!M?.generation||Re.current?.generation===Xe)&&(gt(),Re.current=null),Pt.current=Xe,M?.showRetry&&I(!0),M?.remount&&Rn(),M?.focus!==!1&&yn()},tn=M=>Re.current?.generation===M&&Pt.current!==M,fn=M=>{typeof document<"u"&&document.visibilityState!=="visible"||(gt(),M.timer=setTimeout(()=>{Re.current?.generation===M.generation&&(Re.current=null,Pt.current=M.generation,zn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),I(!0),Rn(),yn())},600))},G=()=>{let M=Re.current;M?.yieldedControl&&fn(M)},Fn=()=>{let M=Re.current;M&&(M.yieldedControl=!0,gt())},gn=M=>{let Xe=nt.current;return Xe&&zt.current.set(M,Xe),M};(0,T.useEffect)(()=>{let M=()=>{document.visibilityState==="visible"?G():Fn()};return document.addEventListener("visibilitychange",M),window.addEventListener("focus",G),window.addEventListener("blur",Fn),()=>{document.removeEventListener("visibilitychange",M),window.removeEventListener("focus",G),window.removeEventListener("blur",Fn),gt()}},[]),(0,T.useEffect)(()=>{Me.current!==ye&&(Me.current=ye,ie.current=!1,me.current=!1,te(!1),ke(!1),Ue(!1),h.current?.("loading"))},[ye]),(0,T.useEffect)(()=>{ut(()=>kt.current?.(Ce&&!$e))},[Ce,$e]);let $t=(0,Mn.normalizeGatewayEnvironment)(s);(0,T.useEffect)(()=>{let M=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",Xe=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(p(`mount clientId=${M} env=${s??"(unset)"}\u2192${$t??"live"} ccy=${u} sub=${c}`),p(`ua=${Xe.slice(0,80)}${Xe.length>80?"\u2026":""}`),!o){p("FAIL: clientId empty \u2014 gateway misconfigured"),Ue(!0),q.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!W.current){p("FAIL: containerRef not attached");return}ce.current=q.startTiming(),q.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Te=!1,Dn=!1,We=()=>Te||Dn,Un,hn=!1,Pn=()=>{Un=(0,Mn.generateIdempotencyKey)(),Un||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),hn=!0},rt=null,It=!1,qt=null,At=!1,Jt=()=>{!qt||At||(At=!0,qt.close().catch(()=>{}))},nn=null,En=()=>{nn!==null&&(q.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),q.performance({stage:"overlay_return",durationMs:q.elapsed(nn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),nn=null)},Kt=!1,Ft=W.current,Xt=null,we=null,mt=[],ct=F=>{if(!F||typeof F.getBoundingClientRect!="function")return"(no rect)";let y=F.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},bn=F=>{if(!F)return"(empty)";try{let y=new URL(F,typeof window<"u"?window.location.href:"https://localhost"),b=y.pathname.toLowerCase();return b.includes("checkcaptcha")||b.includes("captcha")?`CAPTCHA(${y.host}${b})`:b.includes("risk")||b.includes("challenge")?`RISK(${y.host}${b})`:b.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${b}`.slice(0,100)}catch{return F.slice(0,80)}},$n=F=>{let y=F.getAttribute("src"),b=F.getAttribute("srcdoc"),fe=F.getAttribute("name"),J=F.getAttribute("sandbox"),Ye=[];return y&&Ye.push(`src=${bn(y)}`),b&&Ye.push(`srcdoc[${b.length}ch]`),!y&&!b&&Ye.push("src=(empty) srcdoc=(empty)"),fe&&Ye.push(`name=${fe.slice(0,40)}`),J!==null&&Ye.push(`sandbox="${J.slice(0,40)}"`),Ye.join(" ")},Dt=F=>{if(!(F instanceof HTMLIFrameElement))return"";try{let y=F.contentDocument;if(!y)return"cd=null";let b=y.body?.children.length??0,fe=y.body?.innerHTML.length??0,J=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${b}children,${fe}ch] head[${J}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},Vt=[],bt=F=>{if(We())return;let y=F.message??String(F.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(p(`window:error ${y.slice(0,140)}`),Vt.push(y))},Xn=F=>{if(We())return;let y=F.reason instanceof Error?F.reason.message:String(F.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(p(`window:rejection ${y.slice(0,140)}`),Vt.push(y))};O&&typeof window<"u"&&(window.addEventListener("error",bt),window.addEventListener("unhandledrejection",Xn));let Ht={value:0};if(O&&typeof PerformanceObserver<"u")try{we=new PerformanceObserver(F=>{if(!We())for(let y of F.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;Ht.value+=1;let b=Math.round(y.duration);p(`net ${b}ms ${y.name.slice(0,90)}`)}}),we.observe({type:"resource",buffered:!0})}catch{}let _=()=>{for(Xt?.disconnect(),Xt=null,we?.disconnect(),we=null;mt.length;)clearTimeout(mt.pop());O&&typeof window<"u"&&(window.removeEventListener("error",bt),window.removeEventListener("unhandledrejection",Xn))},j=F=>{if(!F)return!1;let y=F.toLowerCase();return y.includes("zoid destroyed")||y.includes("destroyed all components")||y.includes("window closed")||y.includes("detected container element removed")},X=F=>{if(We()||j(F))return;let y=Ln(F)??F;ut(()=>Ge.current?.(y))},re=F=>{Te||(Ue(!0),F.includes("paypal_ineligible")||q.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",F))},ue=(F,y=!1)=>{if(Te)return;let b=ie.current||!R;if(It)return;It=!0,Dn=!0,_(),Jt();let fe=y||xa(F);if(fe&&R&&!ie.current){ie.current=!0,te(!1),A(!1),ke(!0),h.current?.("retrying"),rt=setTimeout(()=>{Te||ze(J=>J+1)},ji);return}if(fe||b){if(te(!1),A(!1),ke(!1),Ue(!0),h.current?.("exhausted"),!me.current){me.current=!0;let J=xa(F)?"paypal_init_timeout":y?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",J)}return}re(F)};Ue(!1);let $=async(F,y=nt.current)=>{if(We())return;let b=y?.sessionId??e;if(je.current){await je.current(F,{sessionId:b,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let fe=q.startTiming();q.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let J=()=>{q.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),q.performance({stage:"processing",durationMs:q.elapsed(fe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Ye=Ve.current,dt=y?.accountPatch?.email??lt.current,Fe=y?.accountPatch?.userId??Ye?.customer?.id??Ye?.accountData?.userId??"",se=await new Yr.PaymentAPI(Y,{telemetry:!1}).processPayment(Fe,{sessionId:b,nonce:y?.nonce??it.current,tokenizedData:F,accountData:{userId:Fe,email:dt??Ye?.customer?.email??"",firstName:y?.accountPatch?.firstName??Ye?.customer?.firstName??Ye?.accountData?.firstName??"",lastName:y?.accountPatch?.lastName??Ye?.customer?.lastName??Ye?.accountData?.lastName??"",country:y?.accountPatch?.country??Ye?.customer?.country??Ye?.accountData?.country??void 0,zip:y?.accountPatch?.zip??Ye?.customer?.zip??Ye?.accountData?.zip??void 0}});if(se.ok){if(Dn||Te&&Rt.current)return;J(),q.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ut(()=>qe.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(We())return;let De=await se.json().catch(()=>null),rn=De?.message??"PayPal payment failed.",Wt=Ln(rn)??rn;J(),se.status===400&&(typeof De?.declineCode=="string"||!Array.isArray(De?.fields))?q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):se.status===400||se.status===422?q.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):q.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:se.status>=500?"5xx":se.status>=400?"4xx":se.status>=300?"3xx":"unknown",failureCategory:se.status>=500?"server_error":void 0}),X(Wt),ut(()=>Ke.current?.(wt("paypal",Wt,{code:De?.code,declineCode:De?.declineCode})));return}catch(Ye){if(We())return;J(),q.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let dt=Ye instanceof Error?Ye.message:"PayPal payment failed.",Fe=Ln(dt)??dt;X(Fe),ut(()=>Ke.current?.(wt("paypal",Fe)));return}},P=()=>new Mn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ne=F=>We()?Promise.reject(P()):Promise.resolve(F),z=async F=>{if(We())throw P();hn||Pn();let y=nt.current,b=y?.sessionId??e,fe=y?.nonce??it.current;q.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let J=await new Yr.PaymentAPI(Y,{telemetry:!1}).createSessionIntent(b,fe??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Un});if(We())throw P();if(J.provider!=="paypal")throw new Error(F);return q.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),J.providerObjectId},pe=(F,y)=>{let b=y?.nonce??it.current;if(!b)return;let fe=y?.sessionId??e,J=ir(F)??Bn(F)??"provider_declined";new Yr.PaymentAPI(Y,{telemetry:!1}).reportSessionIntentDecline(fe,b,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:J}).catch(()=>{})},ve=de;p("loadScript:scheduled (deferred 1 tick)");let x=null,vt=setTimeout(()=>{if(Te){p("loadScript:skipped (cancelled before defer ran)");return}p("loadScript:start");let F=$t==="live"?"production":$t;x=(0,Ta.loadScript)({clientId:o,currency:u,intent:c?"subscription":"capture",vault:c?!0:void 0,...F?{environment:F}:{},...F==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),x.then(y=>{if(p(`loadScript:resolved inactive=${We()} ns=${!!y} buttons=${!!y?.Buttons}`),We())return;if(!y?.Buttons){p("FAIL: namespace missing Buttons factory"),ue("PayPal SDK did not expose the Buttons factory.");return}q.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let b=async Fe=>{if(We()||Be.current!==ve)return;let Ie=Fe.subscriptionID??Fe.orderID??"",se=Ie?zt.current.get(Ie):He.current.get(ve);if(!(!se||!tn(se.generation))&&Mt(se.generation)){zt.current.delete(Ie),He.current.delete(se.surfaceKey),En();try{if(A(!0),ut(()=>Ge.current?.(null)),!Ie)throw new Mn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await $({id:Ie,isPaypal:!0},se)}catch(De){X(De instanceof Error?De.message:"PayPal capture failed.")}finally{We()||A(!1)}}},fe=y.Buttons({style:{layout:"horizontal",height:Gr,tagline:!1},onClick:async(Fe,Ie)=>{if(We()){await Ie.reject();return}Pn();let se=_e.current,De={};if(se)try{let Lt=await se("paypal");if(We()){await Ie.reject();return}if(!Lt.proceed){nt.current=null,He.current.delete(ve),await Ie.reject();return}De={sessionId:Lt.sessionId,accountPatch:Lt.accountPatch,nonce:Lt.nonce}}catch(Lt){p(`onClick:runBeforeButtonClick rejected msg=${(Lt instanceof Error?Lt.message:String(Lt)).slice(0,120)}`),nt.current=null,He.current.delete(ve),await Ie.reject();return}ut(()=>ht.current?.("paypal"));let Wt={generation:Ut(),surfaceKey:ve,...De};nt.current=Wt,He.current.set(ve,Wt),await Ie.resolve(),q.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),q.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),q.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),nn=q.startTiming()},createOrder:c?void 0:Z?()=>ne(Z).then(gn):()=>z("Failed to create PayPal order.").then(gn),createSubscription:c?Z?()=>ne(Z).then(gn):()=>z("Failed to create PayPal subscription.").then(gn):void 0,onApprove:b,onCancel:()=>{if(We())return;let Fe=He.current.get(ve)??nt.current;Fe&&He.current.delete(Fe.surfaceKey),nt.current=null,En(),q.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Se.current=!0,Gt({generation:Fe?.generation,remount:!0,focus:!1})},onError:Fe=>{if(We()||Be.current!==ve)return;let Ie=Fe instanceof Error?Fe.message:"PayPal failed to render.";if(p(`onError rendered=${Kt} msg=${Ie.slice(0,120)}`),Kt){let se=He.current.get(ve)??nt.current;if(se&&!tn(se.generation)||!se&&Pt.current===Je.current)return;if(j(Ie)){Mt(se?.generation);return}if(En(),wr(Fe)){q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),pe(Fe,se),ut(()=>Ke.current?.(wt("paypal",Ie))),se&&He.current.delete(se.surfaceKey),nt.current=null,Mt(se?.generation);return}let De=Ie.toLowerCase();q.error({errorCode:De.includes("popup")&&De.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),se&&He.current.delete(se.surfaceKey),nt.current=null,Gt({generation:se?.generation,remount:!0,showRetry:!0,focus:!0}),zn(Fe,{code:"paypal_runtime_failed"});return}ue(Ie)}}),J=fe.isEligible();if(p(`isEligible=${J}`),q.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!J){te(!1),ue("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}qt=fe,O&&p(`container:dims ${ct(Ft)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),O&&typeof MutationObserver<"u"&&(Xt=new MutationObserver(Fe=>{if(!We()){for(let Ie of Fe)if(Ie.type==="childList")Ie.addedNodes.forEach(se=>{if(!(se instanceof Element))return;let De=se.tagName.toLowerCase(),rn=(se.getAttribute("title")??"").slice(0,40),Wt=De==="iframe"?` ${$n(se)}`:"";p(`child+ ${De}${rn?` title="${rn}"`:""}${Wt} dims=${ct(se)}`)});else if(Ie.type==="attributes"&&Ie.target instanceof Element){let se=Ie.target;if(se.tagName.toLowerCase()!=="iframe")continue;let De=Ie.attributeName;(De==="src"||De==="srcdoc")&&p(`attr~ iframe ${De}=${De==="srcdoc"?`[${(se.getAttribute("srcdoc")??"").length}ch]`:bn(se.getAttribute("src"))} dims=${ct(se)}`)}}}),Xt.observe(Ft,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let dt=Fe=>{if(We()||Kt)return;let Ie=Ft.querySelectorAll("iframe"),se=typeof document<"u"&&"hasStorageAccess"in document;p(`watchdog:${Fe} container=${ct(Ft)} children=${Ft.childElementCount} iframes=${Ie.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${se} paypalNetRequests=${Ht.value}`),Ie.forEach((De,rn)=>{let Wt=(De.getAttribute("title")??"").slice(0,40);p(` iframe[${rn}] ${ct(De)}${Wt?` title="${Wt}"`:""} ${$n(De)}`);let Lt=Dt(De);Lt&&p(` ${Lt}`)}),Vt.length===0&&p(" (no PayPal/zoid window errors captured)")};O&&(mt.push(setTimeout(()=>dt("3s"),3e3)),mt.push(setTimeout(()=>dt("8s"),8e3)),mt.push(setTimeout(()=>dt("15s"),15e3))),p("render:start"),mt.push(setTimeout(()=>{We()||Kt||(p("watchdog:11s retryable render timeout"),ue("PayPal Buttons render did not settle within 11000ms.",!0))},Ki)),fe.render(Ft).then(()=>{if(p(`render:resolved inactive=${We()}`),_(),We()){Jt();return}Kt=!0,te(!0),ke(!1),h.current?.("ready"),q.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),q.performance({stage:"provider_ready",durationMs:q.elapsed(ce.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(Fe=>{let Ie=Fe instanceof Error?Fe.message:"PayPal failed to render.";p(`render:rejected msg=${Ie.slice(0,120)}`),_(),ue(Ie)})}).catch(y=>{let b=y instanceof Error?y.message:"PayPal SDK failed to load.";p(`loadScript:rejected msg=${b.slice(0,120)}`),ue(b)})},0);return()=>{Te=!0,clearTimeout(vt),rt&&clearTimeout(rt),_(),Jt()}},[R,Y,o,u,s,c,e,Z,de,q]);let Bt=O?(0,cn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:$e?"#fef2f2":"#f3f4f6",border:`1px solid ${$e?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Ce} failed=${$e})`,tt.length===0?`
7
7
  (waiting for first lifecycle event\u2026)`:`
8
- ${Ze.join(`
9
- `)}`]}):null;return ze&&!it?z?(0,cn.jsx)("div",{children:ot}):null:(0,cn.jsxs)("div",{children:[ot,(0,cn.jsxs)("div",{"aria-hidden":fe?!0:void 0,style:fe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Hr},children:[!ge&&!fe&&(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:G,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:Hr,display:"flex",opacity:ge?1:0},"aria-busy":Q||F},le)]},le),Se&&(0,cn.jsx)("button",{ref:Fe,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:kn,style:Oi,children:"Try PayPal again"})]})}function vr(e){return(0,cn.jsx)(ka,{...e})}function Ra(e){return(0,cn.jsx)(ka,{...e})}var Dt=require("@flopay/shared"),i=require("react/jsx-runtime"),Cn="flopay_stripe_resume",Ia="flopay_wallet_resume",Cr="flopay_paypal_resume";function Ro(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Yr({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 Ui(e){return e instanceof Dt.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function So(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Kr(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 $i=`
8
+ ${tt.join(`
9
+ `)}`]}):null;return $e&&!st?O?(0,cn.jsx)("div",{children:Bt}):null:(0,cn.jsxs)("div",{children:[Bt,(0,cn.jsxs)("div",{"aria-hidden":be?!0:void 0,style:be?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Gr},children:[!Ce&&!be&&(0,cn.jsx)("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),(0,cn.jsx)("div",{ref:W,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:Gr,display:"flex",opacity:Ce?1:0},"aria-busy":Q||B},de)]},de),Ee&&(0,cn.jsx)("button",{ref:Ne,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:In,style:Hi,children:"Try PayPal again"})]})}function kr(e){return(0,cn.jsx)(Ba,{...e})}function Ma(e){return(0,cn.jsx)(Ba,{...e})}var Nt=require("@flopay/shared"),i=require("react/jsx-runtime"),wn="flopay_stripe_resume",Aa="flopay_wallet_resume",Rr="flopay_paypal_resume";function Mo(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 Nt.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=`
10
10
  .paypal-buttons { margin: 0 !important; vertical-align: top !important; }
11
11
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
12
12
  @keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
@@ -27,7 +27,7 @@ ${Ze.join(`
27
27
  0% { opacity: 1; transform: translateX(0) scale(1); }
28
28
  100% { opacity: 0; transform: translateX(16px) scale(0.97); }
29
29
  }
30
- `,Wr=44;function Io(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"},Fa={width:"100%",minHeight:Wr,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 ji(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ea(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Da(e){return e==="paypal"?"PayPal":(0,R.getStripeMethodDisplayName)(e)}function Vi(e,t){let n=`We couldn't open ${Da(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function La(e){let t=(0,r.useRef)(0),n=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useCallback)((d=l.current)=>{let g=d;g?.timer&&(clearTimeout(g.timer),g.timer=null)},[]),s=(0,r.useCallback)((d,g)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(d),d.timer=setTimeout(()=>{d.timer=null,l.current?.generation===d.generation&&(l.current=null,n.current=d.generation,e(d.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},g))},[o,e]),u=(0,r.useCallback)(d=>{d.yieldedControl&&s(d,600)},[s]),c=(0,r.useCallback)(d=>{o();let g=t.current+1;t.current=g,n.current=null;let E={generation:g,method:d,timer:null,yieldedControl:!1};return l.current=E,g},[o]),I=(0,r.useCallback)(d=>{let g=l.current;return typeof d=="number"&&g?.generation!==d?!1:(o(g),l.current=null,(typeof d!="number"||n.current===d)&&(n.current=null),!0)},[o]),O=(0,r.useCallback)(d=>{let g=l.current,E=d??g?.generation??t.current;(!d||g?.generation===d)&&(o(g),l.current=null),n.current=E},[o]),m=(0,r.useCallback)(d=>n.current===(d??t.current),[]),x=(0,r.useCallback)(d=>l.current?.generation===d&&n.current!==d,[]),w=(0,r.useCallback)(()=>{let d=l.current;d&&u(d)},[u]),F=(0,r.useCallback)(()=>{let d=l.current;d&&(d.yieldedControl=!0,o(d))},[o]);return(0,r.useEffect)(()=>{let d=()=>{document.visibilityState==="visible"?w():F()},g=()=>{F()};return document.addEventListener("visibilitychange",d),window.addEventListener("blur",g),window.addEventListener("focus",w),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("blur",g),window.removeEventListener("focus",w),o()}},[o,F,w]),{startAttempt:c,finishAttempt:I,invalidateAttempt:O,isAttemptInvalidated:m,isAttemptCurrent:x}}function Hi(e){let t=(0,R.getPostalCodeExample)(e);return`Enter a valid ${(0,R.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Ki(e,t,n){let l=(0,R.isPostalCodeSupported)(e),o=t.trim(),s=n&&l,u=s&&!o,c=s&&!!o&&!(0,R.isValidPostalCode)(e,o);return{visible:n,supported:l,required:s,empty:u,malformed:c}}function _a(e,t){return t instanceof Dt.FloPayError?t:new Dt.FloPayError(t instanceof Error?t.message:`${ji(e)} before-click hook failed.`,"validation_error")}function wo(){return(0,i.jsx)("style",{children:$i})}function Wi(e){return typeof e=="number"?`${e}px`:e}function xa(e){if(typeof e=="number"||typeof e=="string")return e}function Na(e,t){let n=e.availablePaymentMethods;return n&&t.some(l=>n[l])?"ready":"unavailable"}function Oa({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 Ta(e){return e!=="unavailable"&&e!=="load_error"}function Gr(e){return(0,i.jsx)(Gi,{...e})}function Ba({sessionId:e,nonce:t,email:n,billingApiUrl:l,onTokenizedBody:o,onErrorChange:s,isProcessing:u=!1,onButtonClick:c,onDecline:I,onTechnicalFailure:O,runBeforeButtonClick:m,onLoadStateChange:x,placeholderBorderRadius:w}){let F=ln(),d=(0,dt.useStripe)(),g=(0,dt.useElements)(),[E,L]=(0,r.useState)("loading");(0,r.useEffect)(()=>{x?.(E)},[E,x]);let[P,W]=(0,r.useState)(!1),Z=(0,r.useRef)(!1),me=(0,r.useRef)(null),re=(0,r.useRef)(null),[z,te]=(0,r.useState)(0),[Y,ye]=(0,r.useState)(!1),V=(0,r.useRef)(!1),G=(0,r.useRef)(new Map),{startAttempt:se,finishAttempt:Fe,invalidateAttempt:he,isAttemptInvalidated:ge,isAttemptCurrent:ne}=La((_,ae,de)=>{O?.(_,ae,{...de,popupBlocked:de?.popupBlocked??Ln(ae)}),ye(!0),te(ze=>ze+1)});(0,r.useEffect)(()=>{Y&&re.current?.focus()},[Y,z]);let fe=(0,r.useCallback)(()=>{te(_=>_+1)},[]),ve=(0,r.useCallback)((_,ae,de)=>{he(de),O?.("paypal",_,{code:ae,popupBlocked:Ln(_)}),ye(!0),fe()},[he,O,fe]),le=(0,r.useCallback)(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{V.current&&(V.current=!1,le())},[le,z]);let Ne=(0,r.useCallback)(()=>{ye(!1),s?.(null),le()},[le,s]);(0,r.useEffect)(()=>{if(!d||Z.current)return;let _=new URLSearchParams(window.location.search),ae=_.get("payment_intent"),de=_.get("payment_intent_client_secret"),ze=_.get("redirect_status");if(!ae||!de)return;Z.current=!0;let Oe;try{let D=localStorage.getItem(Cr);if(D){let J=JSON.parse(D);J.clientSecret===de&&(Oe={...J.accountPatch?{accountPatch:J.accountPatch}:{},...J.sessionId?{sessionId:J.sessionId}:{},...J.nonce?{nonce:J.nonce}:{}})}}catch{}try{localStorage.removeItem(Cr)}catch{}let Q=new URL(window.location.href);Q.searchParams.delete("payment_intent"),Q.searchParams.delete("payment_intent_client_secret"),Q.searchParams.delete("redirect_status"),window.history.replaceState({},"",Q.toString()),(async()=>{try{if(W(!0),ze==="failed"){let ue="PayPal payment was declined. Please try again.";s?.(ue),I?.(St("paypal",ue));return}let{paymentIntent:D,error:J}=await d.retrievePaymentIntent(de);if(J){s?.(J.message??"Failed to retrieve PayPal payment status.");return}if(D&&(D.status==="requires_capture"||D.status==="succeeded")){let ue=typeof D.payment_method=="string"?D.payment_method:D.payment_method?.id;o({id:ue??D.id,type:"card",threeDSecureActionResultTokenId:D.id,isPaypal:!0},Oe)}else{let ue="PayPal payment was not completed. Please try again.";s?.(ue),I?.(St("paypal",ue))}}catch(D){s?.(D instanceof Error?D.message:"Failed to complete PayPal payment.")}finally{W(!1)}})()},[d,o,s,I]);let Ie=(0,r.useCallback)(async _=>{if(u||P){_.reject();return}let ae=m?await m("paypal"):{proceed:!0};if(!ae.proceed){G.current.delete(z),_.reject();return}let de=se("paypal");G.current.set(z,{generation:de,accountPatch:ae.accountPatch,sessionId:ae.sessionId,nonce:ae.nonce}),ye(!1),c?.("paypal"),_.resolve()},[G,u,c,m,se,P,z]),Se=(0,r.useCallback)(async _=>{if(!d||!g)return;let ae=G.current.get(z);if(ae&&!ne(ae.generation)){G.current.delete(z);return}if(!ae&&ge()||ae&&!Fe(ae.generation))return;ae||Fe();let de=ae??null;if(G.current.delete(z),!de&&m){let D=await m("paypal");if(!D.proceed){_.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}de={accountPatch:D.accountPatch,sessionId:D.sessionId,nonce:D.nonce}}let ze=de?.sessionId??e,Oe=de?.nonce??t,Q=de?.accountPatch?.email??n;try{if(W(!0),s?.(null),!ze||!Q)throw new Error("Missing sessionId or email for PayPal payment");let D=d.createPaymentMethod,{error:J,paymentMethod:ue}=await D({type:"paypal"});if(J){ve(J,"stripe_paypal_create_payment_method_failed",ae?.generation),_.paymentFailed({reason:"fail"});return}let Ee=await new dn.PaymentAPI(l).createSessionIntent(ze,Oe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ue?.id??null,intentKind:"payment"});if(Ee.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let it=Ee.clientSecret,Ze={return_url:window.location.href};if(ue?.id&&(Ze.payment_method=ue.id),typeof window<"u")try{localStorage.setItem(Cr,JSON.stringify({clientSecret:it,sessionId:ze,nonce:Oe,accountPatch:de?.accountPatch}))}catch{}let{error:Xe,paymentIntent:y}=await d.confirmPayment({clientSecret:it,confirmParams:Ze,redirect:"if_required"});if(Xe){if(typeof window<"u")try{localStorage.removeItem(Cr)}catch{}if(br(Xe)){let Ue=Xe.message??"Your payment was declined.";s?.(Ue),I?.(St("paypal",Ue,{code:Bn(Xe),declineCode:tr(Xe)})),await Yr({billingApiUrl:l,sessionId:ze,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Bn(Xe)??"provider_declined"}})}else ve(Xe,"stripe_paypal_confirm_failed",ae?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Cr)}catch{}let je=typeof y?.payment_method=="string"?y.payment_method:y?.payment_method?.id;o({id:je??y?.id,type:"card",threeDSecureActionResultTokenId:y?.id,isPaypal:!0},{accountPatch:de?.accountPatch,sessionId:ze,nonce:Oe});return}catch(D){ve(D,"stripe_paypal_failed",ae?.generation)}finally{W(!1)}},[d,g,e,t,n,l,o,s,I,m,ve,Fe,ne,ge,z]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Oa,{state:E,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:(0,i.jsxs)("div",{ref:me,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Y&&(0,i.jsx)("button",{ref:re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ne,style:Fa,children:"Try PayPal again"}),(0,i.jsx)(dt.ExpressCheckoutElement,{onReady:_=>L(Na(_,["paypal"])),onLoadError:()=>{L("load_error"),Ro(xt(F),"paypal","paypal")},onClick:Ie,onConfirm:Se,onCancel:()=>{let _=G.current.get(z);G.current.delete(z),xt(F)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),he(_?.generation),ye(!1),V.current=!0,fe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},z)]})}),P&&(0,i.jsx)(vn,{status:"processing"})]})}function Ma({sessionId:e,nonce:t,email:n,billingApiUrl:l,intentKind:o,expressMethods:s,onTokenizedBody:u,onErrorChange:c,onButtonClick:I,onDecline:O,onTechnicalFailure:m,runBeforeButtonClick:x,onLoadStateChange:w,placeholderBorderRadius:F}){let d=ln(),g=(0,dt.useStripe)(),E=(0,dt.useElements)(),[L,P]=(0,r.useState)("loading");(0,r.useEffect)(()=>{w?.(L)},[L,w]);let[W,Z]=(0,r.useState)(!1),me=(0,r.useRef)(null),re=(0,r.useRef)(null),[z,te]=(0,r.useState)(0),[Y,ye]=(0,r.useState)(!1),[V,G]=(0,r.useState)("google_pay"),se=(0,r.useRef)(!1),Fe=(0,r.useRef)("google_pay"),he=(0,r.useRef)("google_pay"),ge=(0,r.useRef)(new Map),{startAttempt:ne,finishAttempt:fe,invalidateAttempt:ve,isAttemptInvalidated:le,isAttemptCurrent:Ne}=La((Q,D,J)=>{m?.(Q,D,{...J,popupBlocked:J?.popupBlocked??Ln(D)}),G(Q),ye(!0),te(ue=>ue+1)});(0,r.useEffect)(()=>{Y&&re.current?.focus()},[Y,z]);let Ie=(0,r.useCallback)(()=>{te(Q=>Q+1)},[]),Se=(0,r.useCallback)((Q,D,J,ue)=>{ve(ue),m?.(Q,D,{code:J,popupBlocked:Ln(D)}),G(Q),ye(!0),Ie()},[ve,m,Ie]),_=(0,r.useCallback)(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{se.current&&(se.current=!1,_())},[_,z]);let ae=(0,r.useCallback)(()=>{ye(!1),c?.(null),_()},[_,c]),de=(0,r.useCallback)(async Q=>{if(!g||!E)return;let D=ge.current.get(z);if(D&&!Ne(D.generation)){ge.current.delete(z);return}if(!D&&le()||D&&!fe(D.generation))return;D||fe();let J=Q.expressPaymentType??D?.method??Fe.current,ue=D??null;ge.current.delete(z);let Ee=Ea(J);if(!ue&&x){let je=await x(Ee);if(!je.proceed){Q.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}ue={accountPatch:je.accountPatch,sessionId:je.sessionId,nonce:je.nonce}}let it=Ee,Ze=ue?.sessionId??e,Xe=ue?.nonce??t,y=ue?.accountPatch?.email??n;try{Z(!0),c?.(null);let{error:je}=await E.submit();if(je){Se(J,je,"stripe_wallet_submit_failed",D?.generation);return}let{error:Ue,paymentMethod:We}=await g.createPaymentMethod({elements:E});if(Ue||!We){Se(J,Ue??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",D?.generation);return}if(!Ze||!y)throw new Error("Missing sessionId or email for wallet payment");let Ve=await new dn.PaymentAPI(l).createSessionIntent(Ze,Xe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:J??Ee,paymentMethodId:We.id,intentKind:o});if(Ve.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Yt=Ve.clientSecret,{error:ht,intentId:wt}=(0,Dt.isSetupIntentClientSecret)(Yt)?await g.confirmCardSetup(Yt,{payment_method:We.id}).then(h=>({error:h.error,intentId:h.setupIntent?.id})):await g.confirmCardPayment(Yt,{payment_method:We.id}).then(h=>({error:h.error,intentId:h.paymentIntent?.id}));if(ht){if(br(ht)){let h=ht.message??"Your payment was declined.";c?.(h),O?.(St(it,h,{code:Bn(ht),declineCode:tr(ht)})),await Yr({billingApiUrl:l,sessionId:Ze,nonce:Xe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:J??Ee,providerDeclineReason:Bn(ht)??"provider_declined"}})}else Se(J,ht,"stripe_wallet_confirm_failed",D?.generation);return}u({id:We.id,type:"card",threeDSecureActionResultTokenId:wt},{accountPatch:ue?.accountPatch,sessionId:Ze,nonce:Xe})}catch(je){Se(J,je,"stripe_wallet_failed",D?.generation)}finally{Z(!1)}},[g,E,e,t,n,l,o,u,c,O,x,Se,fe,Ne,le,z]),ze=(0,r.useMemo)(()=>{let Q=["applePay","googlePay","paypal","link","amazonPay","klarna"],D=new Set(["applePay","googlePay"]),J=new Set(s.map(R.stripeExpressMethodToOptionKey)),ue={};for(let Ee of Q)J.has(Ee)?ue[Ee]=D.has(Ee)?"always":"auto":ue[Ee]="never";return ue},[s]),Oe=(0,r.useMemo)(()=>s.map(R.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Oa,{state:L,placeholderTestId:"flopay-wallet-placeholder",borderRadius:F,children:(0,i.jsxs)("div",{ref:me,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Y&&(0,i.jsxs)("button",{ref:re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ae,style:Fa,children:["Try ",Da(V)," again"]}),(0,i.jsx)(dt.ExpressCheckoutElement,{onReady:Q=>{P(Na(Q,Oe))},onLoadError:Q=>{P("load_error"),Ro(xt(d),"stripe","wallet")},onClick:async Q=>{Fe.current=Q.expressPaymentType,he.current=Ea(Q.expressPaymentType);let D=x?await x(he.current):{proceed:!0};if(!D.proceed){ge.current.delete(z),Q.reject();return}let J=ne(Q.expressPaymentType);ge.current.set(z,{generation:J,method:Q.expressPaymentType,accountPatch:D.accountPatch,sessionId:D.sessionId,nonce:D.nonce}),ye(!1),I?.(he.current),Q.resolve()},onConfirm:de,onCancel:()=>{let Q=ge.current.get(z);ge.current.delete(z),xt(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),ve(Q?.generation),ye(!1),se.current=!0,Ie()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ze,layout:{maxColumns:1,overflow:"never"}}},z)]})}),W&&(0,i.jsx)(vn,{status:"processing"})]})}function Yi({method:e,themeId:t,submitting:n=!1,disabled:l=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:u,backgroundColor:c,borderColor:I,textColor:O,borderRadius:m,fontFamily:x}){let w=(0,R.resolveStripeMethodBrandVariant)(e,t),F=ua[e],d=w?.backgroundColor??c??"#ffffff",g=w?.borderColor??I??"#d1d5db",E=w?.textColor??O??"#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:Wr,padding:"0 1rem",backgroundColor:d,color:E,border:`1px solid ${g}`,borderRadius:m??8,fontSize:"0.95rem",fontWeight:600,fontFamily:x,cursor:n||l?"not-allowed":"pointer",opacity:l&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,i.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,R.getStripeMethodDisplayName)(e)}\u2026`}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,R.hasVendoredStripeMethodLogo)(e)?8:0},children:[F?(0,i.jsx)("img",{src:F,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):w?.logoSvg?(0,i.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:w.logoSvg}}):null,(0,i.jsx)("span",{children:(0,R.getStripeMethodDisplayName)(e)})]}),s&&(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:E,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,i.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function ko({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:u,onErrorChange:c,onDecline:I,onCancel:O,runBeforeButtonClick:m,onButtonClick:x,isProcessing:w,submitButtonColor:F,submitButtonBorderRadius:d,submitButtonStyle:g,errorText:E}){let L=ln(),P=(0,dt.useStripe)(),W=(0,dt.useElements)(),[Z,me]=(0,r.useState)(!1),re=(0,r.useRef)(!1),[z,te]=(0,r.useState)(!1),[Y,ye]=(0,r.useState)("loading"),V=(0,r.useCallback)(async()=>{if(!P||!W||w||re.current||!z)return;re.current=!0,me(!0);let G=m?await m("card"):{proceed:!0};if(!G.proceed){re.current=!1,me(!1);return}x?.("card");let se=G.sessionId??t,Fe=G.nonce??n,he=G.accountPatch?.email??l;try{c?.(null);let ge=await W.submit();if(ge.error){c?.(ge.error.message??"Payment failed.");return}let ne=await P.createPaymentMethod({elements:W});if(ne.error||!ne.paymentMethod){c?.(ne.error?.message??"Failed to create payment method.");return}let fe=ne.paymentMethod;if(!se||!he)throw new Error("Missing sessionId or email for payment.");let ve=fe.type||e,le=await new dn.PaymentAPI(s).createSessionIntent(se,Fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ve,paymentMethodId:null,intentKind:"payment"});if(le.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ne=le.clientSecret;if(typeof window<"u")try{localStorage.setItem(Cn,JSON.stringify({clientSecret:Ne,sessionId:se,nonce:Fe,accountPatch:G.accountPatch,paymentMethodId:fe.id,paymentMethodType:fe.type??e,gateway:"stripe"}))}catch{}let{error:Ie,paymentIntent:Se}=await P.confirmPayment({clientSecret:Ne,confirmParams:{return_url:window.location.href,payment_method:fe.id},redirect:"if_required"});if(Ie){if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let de=Ie.message??"Payment failed.";c?.(de),I?.(St("card",de,{code:Ie.code})),await Yr({billingApiUrl:s,sessionId:se,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ie.code??"provider_declined"}});return}let _=Se?.status;if(!$r(_)){if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let de=_==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";c?.(de),I?.(St("card",de,{code:_??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let ae=typeof Se?.payment_method=="string"?Se.payment_method:Se?.payment_method?.id;u({id:ae??fe.id,type:"card",threeDSecureActionResultTokenId:Se?.id,gateway:"stripe",paymentMethodType:fe.type??e},{accountPatch:G.accountPatch,sessionId:se,nonce:Fe})}catch(ge){c?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{re.current=!1,me(!1)}},[P,W,w,z,m,x,t,n,l,s,e,u,c,I]);return(0,i.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,i.jsx)(dt.PaymentElement,{onReady:()=>ye("ready"),onLoadError:()=>{ye("load_error"),Ro(xt(L),"stripe","apm")},onChange:G=>{te(!!G.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...l?{email:l}:{}}}}}),(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{V()},disabled:!z||Z||w||Y!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:F,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!z||Z||w||Y!=="ready"?"not-allowed":"pointer",opacity:!z||Z||w||Y!=="ready"?.5:1,transition:"opacity 120ms ease-out",...g??{}},children:Z?"Processing\u2026":`Pay with ${(0,R.getStripeMethodDisplayName)(e)}`}),E&&(0,i.jsx)(Zn,{margin:"0.75rem 0 0",children:E})]})}function Aa({sessionId:e,nonce:t,email:n,billingName:l,billingApiUrl:o,paymentElementMethods:s,stripeInstance:u,paymentElementBaseOptions:c,onTokenizedBody:I,onErrorChange:O,onButtonClick:m,onDecline:x,runBeforeButtonClick:w,onLoadStateChange:F,isProcessing:d=!1,submitButtonColor:g="#4A49FF",submitButtonBorderRadius:E=8,submitButtonStyle:L,buttonAppearance:P,themeId:W,onExpandApm:Z,expandedApmMethod:me}){let[re,z]=(0,r.useState)(null),[te,Y]=(0,r.useState)(null),ye=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&u?F?.("ready"):u||F?.("loading")},[s.length,u,F]);let V=(0,r.useCallback)(async ne=>{if(!u||ye.current||d)return;ye.current=!0,Y(ne);let fe=w?await w("card"):{proceed:!0};if(!fe.proceed){ye.current=!1,Y(null);return}m?.("card");let ve=fe.sessionId??e,le=fe.nonce??t,Ne=fe.accountPatch?.email??n;try{if(O?.(null),!ve||!Ne)throw new Error("Missing sessionId or email for payment.");let Ie=await new dn.PaymentAPI(o).createSessionIntent(ve,le??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,paymentMethodId:null,intentKind:"payment"});if(Ie.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Se=Ie.clientSecret;if(typeof window<"u")try{localStorage.setItem(Cn,JSON.stringify({clientSecret:Se,sessionId:ve,nonce:le,accountPatch:fe.accountPatch,paymentMethodType:ne,gateway:"stripe"}))}catch{}let{error:_,paymentIntent:ae}=await u.confirmPayment({clientSecret:Se,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(_){if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let Oe=_.message??"Payment failed.";O?.(Oe),x?.(St("card",Oe,{code:_.code})),await Yr({billingApiUrl:o,sessionId:ve,nonce:le,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,providerDeclineReason:_.code??"provider_declined"}});return}let de=ae?.status;if(!$r(de)){if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let Oe=de==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";O?.(Oe),x?.(St("card",Oe,{code:de??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let ze=typeof ae?.payment_method=="string"?ae.payment_method:ae?.payment_method?.id;I({id:ze??ae?.id,type:"card",threeDSecureActionResultTokenId:ae?.id,gateway:"stripe",paymentMethodType:ne},{accountPatch:fe.accountPatch,sessionId:ve,nonce:le})}catch(Ie){O?.(Ie instanceof Error?Ie.message:"Payment failed. Please try again.")}finally{ye.current=!1,Y(null)}},[u,d,w,m,e,t,n,o,l,I,O,x]),[G,se]=(0,r.useState)(null),Fe=Z?me??null:G,he=(0,r.useCallback)(ne=>{ye.current||d||Fe&&Fe!==ne||((0,R.needsStripeMethodExplicitConfirm)(ne)?Z?Z(ne):se(ne):V(ne))},[Fe,d,V,Z]),ge=(0,r.useMemo)(()=>G?{...c,paymentMethodTypes:[G]}:null,[G,c]);return(0,i.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(ne=>{let fe=me===ne,ve=te===ne,le=te!==null&&te!==ne||me!=null&&me!==ne;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(Yi,{method:ne,themeId:W,submitting:ve,disabled:le,highlighted:fe,hasNextStep:(0,R.needsStripeMethodExplicitConfirm)(ne),onClick:()=>he(ne),backgroundColor:P?.backgroundColor,borderColor:P?.borderColor,textColor:P?.textColor,borderRadius:P?.borderRadius,fontFamily:P?.fontFamily}),!Z&&G===ne&&ge&&u&&(0,i.jsx)(dt.Elements,{stripe:u,options:ge,children:(0,i.jsx)(ko,{method:ne,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:I,onErrorChange:O,onDecline:x,onCancel:()=>se(null),runBeforeButtonClick:w,onButtonClick:m,isProcessing:d,submitButtonColor:g,submitButtonBorderRadius:E,submitButtonStyle:L})},ne)]},ne)})})}function Gi({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:u,onDecline:c,onTokenizedBody:I,firstName:O,lastName:m,chv:x,className:w,isProcessing:F,error:d,onErrorChange:g,showPayPal:E=!0,showStripe:L=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:W,showApplePay:Z=!0,showGooglePay:me=!0,layout:re="default",theme:z,buttonsTheme:te,buttonsStyles:Y,appearance:ye,cardButtonContent:V,cardBackButtonContent:G,cardTitleContent:se,showSecurityFooter:Fe,onButtonClick:he,onBeforeButtonClick:ge,enableAVS:ne,cardFieldOrder:fe,cardPreFormSlot:ve,avsLayout:le="row",country:Ne,zip:Ie,addressLine1:Se,addressLine2:_,city:ae,state:de,onCountryChange:ze,onZipChange:Oe,avsCheck:Q,checkoutType:D,checkoutLayout:J,totalAmount:ue=0,currency:Ee="usd",initialCardOpen:it=!1,directPaypal:Ze,isSubscription:Xe=!1,session:y,debug:je=!1}){let Ue=ln(),We=Or(),Ve=(0,r.useContext)(sn),Yt=Ur(),[ht,wt]=(0,r.useState)(!1),[h,we]=(0,r.useState)(null),[He,st]=(0,r.useState)(Ne??"US"),[rt,Qe]=(0,r.useState)(Ie??""),[Ye,Ce]=(0,r.useState)(Se??""),[Pt,Ke]=(0,r.useState)(_??""),[Nt,kt]=(0,r.useState)(ae??""),[yn,wn]=(0,r.useState)(de??""),[kn,On]=(0,r.useState)({}),gt=(0,r.useRef)(Ie??""),Ot=(0,r.useRef)(Ne??"US"),Mt=(0,r.useRef)(Se??""),Gt=(0,r.useRef)(_??""),Qt=(0,r.useRef)(ae??""),fn=(0,r.useRef)(de??""),X=(0,r.useMemo)(()=>(0,R.resolveAVSConfig)(ne),[ne]),An=X!==null,gn=!!y?.vault?.html,zt=!!y?.gateways?.pcivault,ot=gn||zt,f=!!(L&&ot&&Ue&&e),[ut,Tt]=(0,r.useState)(()=>re!=="buttons"||it?e??null:null),Rn=re!=="buttons"||it||!!e&&ut===e,Pe=(0,r.useMemo)(()=>!Ue||!f||!e||!Rn?null:Ue.cardCapture({sessionId:e}),[Ue,f,e,Rn]),Vt=(0,r.useMemo)(()=>{let a=He,C=X?(0,R.isAVSFieldVisible)(X.postal_code,a):!1;return Ki(a,rt,C)},[X,He,rt]),{avsInvalid:en,invalidAvsFields:Ht}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!f||!X)return{avsInvalid:!1,invalidAvsFields:a};let C=He,H=(oe,Ge)=>(0,R.isAVSFieldVisible)(oe,C)&&!Ge.trim(),ie={line1:H(X.address_line_1,Ye),city:H(X.city,Nt),state:H(X.state,yn),zip:Vt.empty||Vt.malformed};return{avsInvalid:ie.line1||ie.city||ie.state||ie.zip,invalidAvsFields:ie}},[f,X,He,Ye,Nt,yn,Vt]),[tn,nn]=(0,r.useState)(!1),[Kt,In]=(0,r.useState)(!1),[Ut,$t]=(0,r.useState)(()=>So(y?.vault)),[ke,lt]=(0,r.useState)(it&&ot?"card":"buttons"),[et,hn]=(0,r.useState)(null),rn=ke==="expanding"||ke==="card",bt=280,At=(0,r.useRef)(null),Ft=(0,r.useCallback)(a=>{At.current&&clearTimeout(At.current),At.current=setTimeout(()=>{At.current=null,a()},bt)},[bt]);(0,r.useEffect)(()=>()=>{At.current&&clearTimeout(At.current)},[]);let zn=(0,r.useCallback)(()=>{Tt(e??null),lt("expanding"),Ft(()=>lt("card"))},[Ft,e]),Fn=(0,r.useCallback)(()=>{lt("collapsing"),Ft(()=>lt("buttons"))},[Ft]),En=(0,r.useCallback)(a=>{hn(a),lt("apm-expanding"),Ft(()=>lt("apm-form"))},[Ft]),qt=(0,r.useCallback)(()=>{lt("apm-collapsing"),Ft(()=>{lt("buttons"),hn(null)})},[Ft]);(0,r.useEffect)(()=>{re==="buttons"&&it&&ot&&(Tt(e??null),lt("card"))},[re,it,ot,e]);let[on,Me]=(0,r.useState)(null),M=(0,r.useRef)(!1),[j,ee]=(0,r.useState)(null),U=(0,r.useRef)(j);(0,r.useEffect)(()=>{U.current=j},[j]);let K=n||Yt,q=d??h,p=(0,r.useMemo)(()=>(0,Dt.resolveTheme)(z),[z]),k=(0,r.useMemo)(()=>{let a=p?.buttonsLayout??(0,R.resolveButtonsLayoutTheme)(te);return Y?{...a,...Y,cardButton:{...a.cardButton,...Y.cardButton},cardFormContainer:{...a.cardFormContainer,...Y.cardFormContainer},backButton:{...a.backButton,...Y.backButton},backButtonIcon:{...a.backButtonIcon,...Y.backButtonIcon},submitButton:{...a.submitButton,...Y.submitButton},title:{...a.title,...Y.title}}:a},[p,te,Y]),be=ye??p?.appearance,at=(0,r.useMemo)(()=>{let a=be?.variables,C=Ge=>typeof Ge=="string"&&Ge?Ge:void 0,H=k.submitButton,ie=C(a?.colorPrimary)??C(H?.backgroundColor)??"#4A49FF",$=re==="buttons",oe=k.nameInput;return{primaryColor:ie,primaryHoverColor:C(a?.colorPrimaryHover)??Kr(ie,.12),inputBackgroundColor:C(k.cardInputBackground)??C(a?.colorBackground)??"#ffffff",textColor:C(k.cardInputColor)??C(oe?.color)??C(a?.colorText)??"#262833",borderColor:C(k.cardInputBorder)??($?"#e5e7eb":"#A4A4FF"),placeholderColor:C(k.cardInputPlaceholderColor)??"#9ca3af",errorColor:C(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:C(oe?.fontFamily)??C(a?.fontFamily)??"Poppins, sans-serif",fontSize:C(k.cardInputFontSize)??C(a?.fontSizeBase)??"16px",fontWeight:String(xa(oe?.fontWeight)??400),borderRadius:C(a?.borderRadius)??"8px"}},[be,k,re]),$e=Ve.inlineSessionPatchProcessing??!1,Te=(F??ht)||$e,Bt=K.replace(/\/+$/,""),b=(0,r.useMemo)(()=>vo({userId:o,email:l,firstName:O,lastName:m,country:Ne,zip:Ie},kn),[o,l,O,m,Ne,Ie,kn]),v=[b.firstName,b.lastName].filter(a=>!!a?.trim()).join(" "),B=(0,r.useMemo)(()=>Ue?Ue.getRawProvider():null,[Ue]),pe=(0,r.useMemo)(()=>We?We.getRawProvider():null,[We]),Re=ue||100,De=(0,r.useMemo)(()=>be?(0,dn.toStripeAppearance)(be):null,[be]),Wt=De?{appearance:De}:null,qe=(0,r.useMemo)(()=>{let a=De??{},C=a.rules??{};return{...a,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[De]),_e=(0,r.useMemo)(()=>{let a=Pa(ue);return{...a,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...Wt}},[ue,Ee,Wt]),ce=(0,r.useMemo)(()=>({mode:"payment",amount:Re,currency:Ee.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Wt}),[Re,Ee,Wt]),T=(0,r.useCallback)(a=>{we(a),g?.(a)},[g]);(0,r.useEffect)(()=>{!f||!Pe||Pe.setCardFieldOrder?.(fe??null,X==null)},[f,Pe,fe,X]),(0,r.useEffect)(()=>{(ke==="expanding"||ke==="collapsing"||ke==="apm-expanding"||ke==="apm-collapsing")&&T(null)},[ke,T]);let pt=(0,r.useCallback)((a,C,H)=>{c?.(St(a,C,H))},[c]),Rt=(0,r.useCallback)((a,C,H)=>{let ie=H?.popupBlocked??Ln(C),$=Vi(a,ie),oe=Hn(H?.code)??Bn(C)??"external_payment_method_failed",Ge=new Dt.FloPayError($,"api_error",{code:"external_payment_method_failed",param:a});Me(null),re==="buttons"&&(lt("buttons"),hn(null)),T($),u?.(Ge),console.error("[FloPay] External payment method failed:",{method:a,code:oe,popupBlocked:ie})},[re,u,T]);(0,r.useEffect)(()=>{if(!f||!e){$t(null);return}let a=So(y?.vault);if(a){$t(a);return}$t(null);let C=!0;return new dn.PaymentAPI(Bt).getVaultCapture(e,t).then(H=>{if(!C)return;let ie=So(H);ie?$t(ie):T("Failed to load the secure card form.")}).catch(H=>{C&&T(H instanceof Error?H.message:"Failed to load the secure card form.")}),()=>{C=!1}},[f,e,y?.vault?.html,y?.vault?.messageToken,y?.vault?.expectedOrigin,Bt,t,T]);let mt=(0,r.useRef)({onComplete:s,onError:u,updateError:T,emitDecline:pt,resolvedAccount:b,avsConfig:X,avsCheckProp:Q,sessionId:e,nonce:t,baseUrl:Bt});mt.current={onComplete:s,onError:u,updateError:T,emitDecline:pt,resolvedAccount:b,avsConfig:X,avsCheckProp:Q,sessionId:e,nonce:t,baseUrl:Bt};let oo=(0,r.useRef)(!1),ei=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:C,avsCheckProp:H}=mt.current,ie=Ot.current||a.country||"US",$=C?(0,R.isAVSFieldVisible)(C.state,ie):!1,oe=C?(0,R.isAVSFieldVisible)(C.address_line_1,ie):!1,Ge=C?(0,R.isAVSFieldVisible)(C.postal_code,ie):!1,vt=C?(0,R.isAVSFieldVisible)(C.city,ie):!1,It=C?(0,R.isAVSFieldVisible)(C.address_line_2,ie):!1,tt=oe&&!$&&Ge?(0,R.getStateFromPostalCode)(ie,(gt.current??"").trim()):null,Et=$?fn.current:tt;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Ge&&gt.current?{zip:gt.current}:{},...vt&&Qt.current?{city:Qt.current}:{},...Et?{state:Et}:{},...oe&&Mt.current?{addressLine1:Mt.current}:{},...It&&Gt.current?{addressLine2:Gt.current}:{},country:ie},...H!==void 0?{avsCheck:H}:{},...C?{avsConfig:{country:(0,R.isAVSFieldVisible)(C.country,ie),postal_code:Ge,address_line_1:oe,address_line_2:It,city:vt,state:$}}:{}}},[]);(0,r.useEffect)(()=>{!f||!Pe||Pe.setSubmitGate?.(en)},[f,Pe,en]),(0,r.useEffect)(()=>{if(!f||!Pe)return;oo.current=!1;let a=!1,C=Pe.on("submitting",()=>{nn(!0),Me("processing");let{baseUrl:oe,sessionId:Ge,nonce:vt,updateError:It,onError:tt}=mt.current;!Ge||!vt||new dn.PaymentAPI(oe).patchAccountSnapshot(Ge,vt,ei(),{telemetryMode:"best_effort"}).catch(Et=>{if(!Ui(Et))return;let Le=Et instanceof Error?Et.message:"Please check your billing address and try again.";It(Le),Me(null),tt?.(Et instanceof Dt.FloPayError?Et:new Dt.FloPayError(Le,"api_error"))})}),H=Pe.on("complete",async oe=>{er(oe.sessionId??mt.current.sessionId),Me("success"),await new Promise(Ge=>setTimeout(Ge,Tn)),!oo.current&&(oo.current=!0,mt.current.onComplete?.({status:"succeeded",paymentIntentId:oe.intentId,checkoutMethod:"card"}))}),ie=Pe.on("decline",async oe=>{let{updateError:Ge,emitDecline:vt}=mt.current,It=oe.message??"Your payment was declined. Please try another card or contact your bank.";Ge(It),Me("error"),vt("card",It,oe.declineReason?{declineCode:oe.declineReason}:void 0),await new Promise(tt=>setTimeout(tt,bn)),!a&&Me(null)}),$=Pe.on("error",async oe=>{let{updateError:Ge,onError:vt}=mt.current,It=oe.message??"There was a problem processing your payment. Please try again.";Ge(It),Me("error"),vt?.(new Dt.FloPayError(It,"api_error")),await new Promise(tt=>setTimeout(tt,bn)),!a&&Me(null)});return()=>{a=!0,C(),H(),ie(),$()}},[f,Pe]);let Pn=!!Ze?.clientId,ir=Array.isArray(P),Rr=ir&&P.length>0,ti=ir&&P.includes("paypal"),{expressMethods:Ir,paymentElementMethods:sr}=(0,r.useMemo)(()=>(0,R.partitionStripeMethods)(P,{excludePaypal:Pn}),[P,Pn]),Fo=Pn||!!We,ni=(0,r.useMemo)(()=>Fo?Ir.filter(a=>a!=="paypal"):Ir,[Ir,Fo]),ri=(0,r.useMemo)(()=>{let a=[];return Z&&a.push("apple_pay"),me&&a.push("google_pay"),a},[Z,me]),Er=ir?ni:ri,oi=L&&Er.length>0,ao=An?He:Ne,_r=(0,r.useMemo)(()=>{let a=ao?.trim().toUpperCase();return a?W?sr.filter(C=>{let H=W[C];return!H||H.length===0||H.includes(a)}):(0,R.filterStripeMethodsByCountry)(sr,ao):sr},[sr,ao,W]),io=(0,r.useMemo)(()=>({mode:"payment",amount:Re,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",appearance:qe}),[Re,Ee,qe]),[Do,Lo]=(0,r.useState)("loading"),[No,Oo]=(0,r.useState)("loading"),[zo,Uo]=(0,r.useState)("loading"),[ai,so]=(0,r.useState)(!1),[$o,lo]=(0,r.useState)("loading"),[xr,ii]=(0,r.useState)();(0,r.useEffect)(()=>{ii(va())},[]);let qo=E&&(Pn||(ir?ti:xr===!1)),jo=L&&oi,lr=qo&&Pn,Vo=$o==="retrying"||$o==="exhausted",cr=qo&&!!pe&&(!Pn||Vo),dr=jo&&!!B,ur=L&&Rr&&_r.length>0&&!!B,si=lr&&!Vo?ai:cr&&Ta(Do),li=dr&&Ta(No),ci=ur&&zo!=="load_error",Ho=a=>a==="loading"||a==="ready",Ko=lr||cr&&Ho(Do)||dr&&Ho(No)||ur&&zo!=="load_error",Tr=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!Tr.current){if(!L&&!E){Tr.current=!0;let a=new Dt.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(a),T(a.message)}else if(!L&&E&&!Pn&&!pe){Tr.current=!0;let a=new Dt.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(a),T(a.message)}else if(xr!==void 0&&!ot&&!Ko){Tr.current=!0;let a=new Dt.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),T(a.message)}}},[L,E,Pn,pe,xr,ot,Ko,u,T]);let Wo=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(Wo.current||!Rr)return;let a=[];Z!==!0&&a.push("showApplePay"),me!==!0&&a.push("showGooglePay"),a.length!==0&&(Wo.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.`))},[Rr,Z,me]);let Yo=(0,r.useCallback)((a,C)=>Ve.applyInlineSessionPatch?Ve.applyInlineSessionPatch(a).then(H=>({error:null,sessionId:H.sessionId||e,nonce:H.session?.clientSecret||t})).catch(H=>{let ie=_a(C,H);return T(ie.message),u?.(ie),{error:ie,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ve.applyInlineSessionPatch,t,u,e,T]),an=(0,r.useCallback)(async a=>{if(!ge)return{proceed:!0};try{let C=await ge({method:a,sessionId:e||void 0,createSession:Ve.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&On(ie=>({...ie??{},...C.account}));let H=await Yo(C,a);return H.error?{proceed:!1,accountPatch:C.account}:{proceed:!0,accountPatch:C.account,sessionId:H.sessionId,nonce:H.nonce}}return{proceed:!0}}catch(C){let H=_a(a,C);return T(H.message),u?.(H),{proceed:!1}}},[Yo,Ve.inlineSessionDraft,ge,u,e,T]),Go=(0,r.useCallback)(async(a,C)=>{if(M.current)return;M.current=!0,wt(!0),Me("processing"),T(null);let H=C?.sessionId??e,ie=C?.nonce??t,$=vo(b,C?.accountPatch),oe=C?.completionPaymentMethodId??qr(a),Ge=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let It=await new dn.PaymentAPI(Bt).processPayment($.userId??"",{sessionId:H,nonce:ie,tokenizedData:Ge,accountData:{userId:$.userId??"",email:$.email??"",firstName:$.firstName??"",lastName:$.lastName??"",...X?(()=>{let Le=Ot.current,Xt=(0,R.isAVSFieldVisible)(X.state,Le),Zt=(0,R.isAVSFieldVisible)(X.address_line_1,Le),jn=(0,R.isAVSFieldVisible)(X.postal_code,Le),Vn=Zt&&!Xt&&jn?(0,R.getStateFromPostalCode)(Le,(gt.current??"").trim()):null,_t=Xt?fn.current:Vn;return{country:Le,...jn&&gt.current?{zip:gt.current}:{},...(0,R.isAVSFieldVisible)(X.city,Le)&&Qt.current?{city:Qt.current}:{},..._t?{state:_t}:{},...Zt&&Mt.current?{addressLine1:Mt.current}:{},...(0,R.isAVSFieldVisible)(X.address_line_2,Le)&&Gt.current?{addressLine2:Gt.current}:{}}})():{}},chv:x,avsCheck:Q??!1,checkoutType:D,checkoutLayout:J,avsConfig:X?{country:(0,R.isAVSFieldVisible)(X.country,Ot.current),postal_code:(0,R.isAVSFieldVisible)(X.postal_code,Ot.current),address_line_1:(0,R.isAVSFieldVisible)(X.address_line_1,Ot.current),address_line_2:(0,R.isAVSFieldVisible)(X.address_line_2,Ot.current),city:(0,R.isAVSFieldVisible)(X.city,Ot.current),state:(0,R.isAVSFieldVisible)(X.state,Ot.current)}:void 0});if(It.ok){er(H),Me("success"),ee(null),await new Promise(Le=>setTimeout(Le,Tn)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:oe,checkoutMethod:a.isPaypal?"paypal":"card"});return}let tt=await It.json().catch(()=>null);if(tt?.type==="paypal_redirect_required"){let Le=tt.threeDSecureToken,Xt=tt.paymentMethodId||a.id||"";if(!Ue||!Le){Me("error"),T("PayPal authorization required but no token provided.");return}try{let Zt=We?.getRawProvider();if(!Zt){T("PayPal is not available.");return}let jn={return_url:window.location.href};Xt&&(jn.payment_method=Xt);let{error:Vn}=await Zt.confirmPayment({clientSecret:Le,confirmParams:jn,redirect:"if_required"});if(Vn){Me("error");let _t=Vn.message??"PayPal payment failed.";T(_t),pt("paypal",_t,{code:Vn.code})}}catch(Zt){Me("error"),T(Zt instanceof Error?Zt.message:"PayPal authorization failed.")}return}if(tt?.type==="paypal_direct_required"){let Le=tt.orderId;if(!Le){Me("error"),T("PayPal retry required but no order id provided.");return}let Xt=U.current?.attempts??0;if(Xt>=2){Me("error"),T("PayPal payment could not be completed after multiple attempts."),pt("paypal","paypal_direct_required retry limit exceeded");return}so(!1),lo("loading"),ee({orderId:Le,attempts:Xt+1}),Me(null);return}Me("error");let Et=tt?.message??"Payment failed. Please try again.";T(Et),pt(a.isPaypal?"paypal":"card",Et,{code:tt?.code??tt?.gatewayErrorCode,declineCode:tt?.declineCode??tt?.gatewayDeclineReason}),await new Promise(Le=>setTimeout(Le,bn))}catch(vt){Me("error"),T(vt instanceof Error?vt.message:"An unexpected error occurred"),await new Promise(It=>setTimeout(It,bn))}finally{wt(!1),Me(null),M.current=!1}},[Bt,e,t,b,v,x,Ue,We,s,u,T,pt]),Jt=(0,r.useCallback)((a,C)=>{I?I(a):Go(a,C)},[I,Go]),Jo=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(typeof window>"u"||Jo.current)return;let a=new URLSearchParams(window.location.search),C=a.get("payment_intent"),H=a.get("payment_intent_client_secret"),ie=a.get("redirect_status");if(!C||!H)return;let $=Et=>{let Le=localStorage.getItem(Et);if(!Le)return null;try{return JSON.parse(Le)}catch{return localStorage.removeItem(Et),null}},oe=$(Cn)??$(Ia),Ge;if(oe?.clientSecret){if(oe.clientSecret!==H)return;Ge={...oe.accountPatch?{accountPatch:oe.accountPatch}:{},...oe.sessionId?{sessionId:oe.sessionId}:{},...oe.nonce?{nonce:oe.nonce}:{}}}else if(oe?.sessionId&&oe.sessionId!==e)return;Jo.current=!0,localStorage.removeItem(Cn),localStorage.removeItem(Ia);let vt=new URL(window.location.href);vt.searchParams.delete("payment_intent"),vt.searchParams.delete("payment_intent_client_secret"),vt.searchParams.delete("redirect_status"),window.history.replaceState({},"",vt.toString());let It=oe?.paymentMethodType??oe?.tokenType??"card",tt="card";(async()=>{let Et=Ue?.getRawProvider();if(!Et){let _t="Payment is not available \u2014 please refresh and try again.";T(_t),pt(tt,_t);return}if(ie==="failed"){let _t="Payment was declined. Please try again.";T(_t),pt(tt,_t);return}let{paymentIntent:Le,error:Xt}=await Et.retrievePaymentIntent(H);if(Xt){let _t=Xt.message??"Failed to retrieve payment status.";T(_t),pt(tt,_t,{code:Xt.code});return}let Zt=Le?.status,jn=$r(Zt);if(!Le||!jn){let _t=Zt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";T(_t),pt(tt,_t,{code:Zt??"missing_payment_intent"});return}let Vn=typeof Le.payment_method=="string"?Le.payment_method:Le.payment_method?.id;Jt({id:Vn??oe?.paymentMethodId??oe?.tokenId??Le.id,type:"card",threeDSecureActionResultTokenId:Le.id,gateway:oe?.gateway??"stripe",paymentMethodType:It},Ge)})()},[e,Jt,Ue,T,pt]);let co=(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 pr=re==="buttons",jt=be?.variables,di=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),uo=jt?.colorBackground,ui=uo&&!di.has(uo)?uo:void 0,mr=k.cardInputBorder??(pr?"#e5e7eb":"#A4A4FF"),po=jt?.colorDanger??"#dc2626",Un=a=>tn&&a?po:mr,Br=(Vt.malformed||Vt.empty)&&(Kt||tn),pi=Br?po:Un(Ht.zip),mo=k.cardFormContainer?.backgroundColor??ui??(pr?"white":"#EDEDFF"),yr=k.cardInputBackground??jt?.colorBackground??"white",yo=Gn(G),Xo=Gn(se),Yn=k.nameInput,Zo=k.cardInputFontSize??Wi(Yn?.fontSize)??jt?.fontSizeBase??"16px",Qo=typeof Yn?.fontFamily=="string"?Yn.fontFamily:jt?.fontFamily??"Poppins, sans-serif",ea=xa(Yn?.fontWeight)??400,mi=k.cardInputColor??(typeof Yn?.color=="string"?Yn.color:void 0)??jt?.colorText??"#262833",yi=k.cardInputPlaceholderColor??"#9ca3af",yt=jt?.borderRadius??"8px",$n=jt?.borderRadius??k.cardButton?.borderRadius??yt,qn=jt?.colorPrimary??"#4A49FF",fi=jt?.colorPrimaryHover??Kr(qn,.12),fo=jt?.colorText??"#262833",ta={fontSize:Zo,fontFamily:Qo,fontWeight:ea,color:mi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},gi={"--flopay-input-placeholder-color":yi,"--flopay-input-font-size":Zo,"--flopay-input-font-family":Qo,"--flopay-input-font-weight":String(ea)},fr=k.cardFormContainer??{},go=fr.padding??(pr?"0":"1rem"),ho=fr.borderRadius??yt,hi=Pe&&Ut?(0,i.jsx)(Nr,{capture:Pe,html:Ut.html,messageToken:Ut.messageToken,expectedOrigin:Ut.expectedOrigin,theme:at,onReady:()=>{if(!X||typeof document>"u")return;let a=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};a();let C=0,H=window.setInterval(()=>{C+=1;let ie=document.activeElement;!!ie&&ie.tagName==="IFRAME"&&ie.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(H)):C>=50&&window.clearInterval(H)},100)},onError:a=>T(a),onValidation:a=>{T(a),a&&Me(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"}),na=(0,i.jsxs)("div",{style:{backgroundColor:mo,borderRadius:ho,...fr,padding:go,...gi,display:"flex",flexDirection:"column"},children:[(0,i.jsx)("style",{children:`
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]),m=(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]),B=(0,r.useCallback)(()=>{let d=l.current;d&&(d.yieldedControl=!0,o(d))},[o]);return(0,r.useEffect)(()=>{let d=()=>{document.visibilityState==="visible"?S():B()},f=()=>{B()};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,B,S]),{startAttempt:c,finishAttempt:k,invalidateAttempt:N,isAttemptInvalidated:m,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 Nt.FloPayError?t:new Nt.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:m,onLoadStateChange:E,placeholderBorderRadius:S}){let B=ln(),d=(0,pt.useStripe)(),f=(0,pt.useElements)(),[R,D]=(0,r.useState)("loading");(0,r.useEffect)(()=>{E?.(R)},[R,E]);let[g,V]=(0,r.useState)(!1),Z=(0,r.useRef)(!1),he=(0,r.useRef)(null),oe=(0,r.useRef)(null),[O,ee]=(0,r.useState)(0),[H,Pe]=(0,r.useState)(!1),q=(0,r.useRef)(!1),W=(0,r.useRef)(new Map),{startAttempt:ce,finishAttempt:Ne,invalidateAttempt:Se,isAttemptInvalidated:Ce,isAttemptCurrent:te}=ja((I,ie,me)=>{N?.(I,ie,{...me,popupBlocked:me?.popupBlocked??Nn(ie)}),Pe(!0),ee($e=>$e+1)});(0,r.useEffect)(()=>{H&&oe.current?.focus()},[H,O]);let be=(0,r.useCallback)(()=>{ee(I=>I+1)},[]),ke=(0,r.useCallback)((I,ie,me)=>{Se(me),N?.("paypal",I,{code:ie,popupBlocked:Nn(I)}),Pe(!0),be()},[Se,N,be]),de=(0,r.useCallback)(()=>{window.setTimeout(()=>{(he.current?.querySelector("iframe")??he.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{q.current&&(q.current=!1,de())},[de,O]);let ze=(0,r.useCallback)(()=>{Pe(!1),s?.(null),de()},[de,s]);(0,r.useEffect)(()=>{if(!d||Z.current)return;let I=new URLSearchParams(window.location.search),ie=I.get("payment_intent"),me=I.get("payment_intent_client_secret"),$e=I.get("redirect_status");if(!ie||!me)return;Z.current=!0;let Ue;try{let A=localStorage.getItem(Rr);if(A){let Y=JSON.parse(A);Y.clientSecret===me&&(Ue={...Y.accountPatch?{accountPatch:Y.accountPatch}:{},...Y.sessionId?{sessionId:Y.sessionId}:{},...Y.nonce?{nonce:Y.nonce}:{}})}}catch{}try{localStorage.removeItem(Rr)}catch{}let Q=new URL(window.location.href);Q.searchParams.delete("payment_intent"),Q.searchParams.delete("payment_intent_client_secret"),Q.searchParams.delete("redirect_status"),window.history.replaceState({},"",Q.toString()),(async()=>{try{if(V(!0),$e==="failed"){let ye="PayPal payment was declined. Please try again.";s?.(ye),k?.(wt("paypal",ye));return}let{paymentIntent:A,error:Y}=await d.retrievePaymentIntent(me);if(Y){s?.(Y.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},Ue)}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{V(!1)}})()},[d,o,s,k]);let Be=(0,r.useCallback)(async I=>{if(u||g){I.reject();return}let ie=m?await m("paypal"):{proceed:!0};if(!ie.proceed){W.current.delete(O),I.reject();return}let me=ce("paypal");W.current.set(O,{generation:me,accountPatch:ie.accountPatch,sessionId:ie.sessionId,nonce:ie.nonce}),Pe(!1),c?.("paypal"),I.resolve()},[W,u,c,m,ce,g,O]),Ee=(0,r.useCallback)(async I=>{if(!d||!f)return;let ie=W.current.get(O);if(ie&&!te(ie.generation)){W.current.delete(O);return}if(!ie&&Ce()||ie&&!Ne(ie.generation))return;ie||Ne();let me=ie??null;if(W.current.delete(O),!me&&m){let A=await m("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 $e=me?.sessionId??e,Ue=me?.nonce??t,Q=me?.accountPatch?.email??n;try{if(V(!0),s?.(null),!$e||!Q)throw new Error("Missing sessionId or email for PayPal payment");let A=d.createPaymentMethod,{error:Y,paymentMethod:ye}=await A({type:"paypal"});if(Y){ke(Y,"stripe_paypal_create_payment_method_failed",ie?.generation),I.paymentFailed({reason:"fail"});return}let Me=await new dn.PaymentAPI(l).createSessionIntent($e,Ue??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ye?.id??null,intentKind:"payment"});if(Me.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let st=Me.clientSecret,tt={return_url:window.location.href};if(ye?.id&&(tt.payment_method=ye.id),typeof window<"u")try{localStorage.setItem(Rr,JSON.stringify({clientSecret:st,sessionId:$e,nonce:Ue,accountPatch:me?.accountPatch}))}catch{}let{error:et,paymentIntent:p}=await d.confirmPayment({clientSecret:st,confirmParams:tt,redirect:"if_required"});if(et){if(typeof window<"u")try{localStorage.removeItem(Rr)}catch{}if(wr(et)){let qe=et.message??"Your payment was declined.";s?.(qe),k?.(wt("paypal",qe,{code:Bn(et),declineCode:ir(et)})),await Zr({billingApiUrl:l,sessionId:$e,nonce:Ue,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Bn(et)??"provider_declined"}})}else ke(et,"stripe_paypal_confirm_failed",ie?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Rr)}catch{}let je=typeof p?.payment_method=="string"?p.payment_method:p?.payment_method?.id;o({id:je??p?.id,type:"card",threeDSecureActionResultTokenId:p?.id,isPaypal:!0},{accountPatch:me?.accountPatch,sessionId:$e,nonce:Ue});return}catch(A){ke(A,"stripe_paypal_failed",ie?.generation)}finally{V(!1)}},[d,f,e,t,n,l,o,s,k,m,ke,Ne,te,Ce,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:he,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[H&&(0,i.jsx)("button",{ref:oe,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ze,style:$a,children:"Try PayPal again"}),(0,i.jsx)(pt.ExpressCheckoutElement,{onReady:I=>D(Ka(I,["paypal"])),onLoadError:()=>{D("load_error"),Mo(Tt(B),"paypal","paypal")},onClick:Be,onConfirm:Ee,onCancel:()=>{let I=W.current.get(O);W.current.delete(O),Tt(B)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Se(I?.generation),Pe(!1),q.current=!0,be()},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:m,runBeforeButtonClick:E,onLoadStateChange:S,placeholderBorderRadius:B}){let d=ln(),f=(0,pt.useStripe)(),R=(0,pt.useElements)(),[D,g]=(0,r.useState)("loading");(0,r.useEffect)(()=>{S?.(D)},[D,S]);let[V,Z]=(0,r.useState)(!1),he=(0,r.useRef)(null),oe=(0,r.useRef)(null),[O,ee]=(0,r.useState)(0),[H,Pe]=(0,r.useState)(!1),[q,W]=(0,r.useState)("google_pay"),ce=(0,r.useRef)(!1),Ne=(0,r.useRef)("google_pay"),Se=(0,r.useRef)("google_pay"),Ce=(0,r.useRef)(new Map),{startAttempt:te,finishAttempt:be,invalidateAttempt:ke,isAttemptInvalidated:de,isAttemptCurrent:ze}=ja((Q,A,Y)=>{m?.(Q,A,{...Y,popupBlocked:Y?.popupBlocked??Nn(A)}),W(Q),Pe(!0),ee(ye=>ye+1)});(0,r.useEffect)(()=>{H&&oe.current?.focus()},[H,O]);let Be=(0,r.useCallback)(()=>{ee(Q=>Q+1)},[]),Ee=(0,r.useCallback)((Q,A,Y,ye)=>{ke(ye),m?.(Q,A,{code:Y,popupBlocked:Nn(A)}),W(Q),Pe(!0),Be()},[ke,m,Be]),I=(0,r.useCallback)(()=>{window.setTimeout(()=>{(he.current?.querySelector("iframe")??he.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{ce.current&&(ce.current=!1,I())},[I,O]);let ie=(0,r.useCallback)(()=>{Pe(!1),c?.(null),I()},[I,c]),me=(0,r.useCallback)(async Q=>{if(!f||!R)return;let A=Ce.current.get(O);if(A&&!ze(A.generation)){Ce.current.delete(O);return}if(!A&&de()||A&&!be(A.generation))return;A||be();let Y=Q.expressPaymentType??A?.method??Ne.current,ye=A??null;Ce.current.delete(O);let Me=Fa(Y);if(!ye&&E){let je=await E(Me);if(!je.proceed){Q.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}ye={accountPatch:je.accountPatch,sessionId:je.sessionId,nonce:je.nonce}}let st=Me,tt=ye?.sessionId??e,et=ye?.nonce??t,p=ye?.accountPatch?.email??n;try{Z(!0),c?.(null);let{error:je}=await R.submit();if(je){Ee(Y,je,"stripe_wallet_submit_failed",A?.generation);return}let{error:qe,paymentMethod:Ge}=await f.createPaymentMethod({elements:R});if(qe||!Ge){Ee(Y,qe??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",A?.generation);return}if(!tt||!p)throw new Error("Missing sessionId or email for wallet payment");let Ke=await new dn.PaymentAPI(l).createSessionIntent(tt,et??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Y??Me,paymentMethodId:Ge.id,intentKind:o});if(Ke.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Yt=Ke.clientSecret,{error:ht,intentId:kt}=(0,Nt.isSetupIntentClientSecret)(Yt)?await f.confirmCardSetup(Yt,{payment_method:Ge.id}).then(h=>({error:h.error,intentId:h.setupIntent?.id})):await f.confirmCardPayment(Yt,{payment_method:Ge.id}).then(h=>({error:h.error,intentId:h.paymentIntent?.id}));if(ht){if(wr(ht)){let h=ht.message??"Your payment was declined.";c?.(h),N?.(wt(st,h,{code:Bn(ht),declineCode:ir(ht)})),await Zr({billingApiUrl:l,sessionId:tt,nonce:et,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Y??Me,providerDeclineReason:Bn(ht)??"provider_declined"}})}else Ee(Y,ht,"stripe_wallet_confirm_failed",A?.generation);return}u({id:Ge.id,type:"card",threeDSecureActionResultTokenId:kt},{accountPatch:ye?.accountPatch,sessionId:tt,nonce:et})}catch(je){Ee(Y,je,"stripe_wallet_failed",A?.generation)}finally{Z(!1)}},[f,R,e,t,n,l,o,u,c,N,E,Ee,be,ze,de,O]),$e=(0,r.useMemo)(()=>{let Q=["applePay","googlePay","paypal","link","amazonPay","klarna"],A=new Set(["applePay","googlePay"]),Y=new Set(s.map(w.stripeExpressMethodToOptionKey)),ye={};for(let Me of Q)Y.has(Me)?ye[Me]=A.has(Me)?"always":"auto":ye[Me]="never";return ye},[s]),Ue=(0,r.useMemo)(()=>s.map(w.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Va,{state:D,placeholderTestId:"flopay-wallet-placeholder",borderRadius:B,children:(0,i.jsxs)("div",{ref:he,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[H&&(0,i.jsxs)("button",{ref:oe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ie,style:$a,children:["Try ",qa(q)," again"]}),(0,i.jsx)(pt.ExpressCheckoutElement,{onReady:Q=>{g(Ka(Q,Ue))},onLoadError:Q=>{g("load_error"),Mo(Tt(d),"stripe","wallet")},onClick:async Q=>{Ne.current=Q.expressPaymentType,Se.current=Fa(Q.expressPaymentType);let A=E?await E(Se.current):{proceed:!0};if(!A.proceed){Ce.current.delete(O),Q.reject();return}let Y=te(Q.expressPaymentType);Ce.current.set(O,{generation:Y,method:Q.expressPaymentType,accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}),Pe(!1),k?.(Se.current),Q.resolve()},onConfirm:me,onCancel:()=>{let Q=Ce.current.get(O);Ce.current.delete(O),Tt(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),ke(Q?.generation),Pe(!1),ce.current=!0,Be()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:$e,layout:{maxColumns:1,overflow:"never"}}},O)]})}),V&&(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:m,fontFamily:E}){let S=(0,w.resolveStripeMethodBrandVariant)(e,t),B=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:m??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:[B?(0,i.jsx)("img",{src:B,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):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 Bo({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:u,onErrorChange:c,onDecline:k,onCancel:N,runBeforeButtonClick:m,onButtonClick:E,isProcessing:S,submitButtonColor:B,submitButtonBorderRadius:d,submitButtonStyle:f,errorText:R}){let D=ln(),g=(0,pt.useStripe)(),V=(0,pt.useElements)(),[Z,he]=(0,r.useState)(!1),oe=(0,r.useRef)(!1),[O,ee]=(0,r.useState)(!1),[H,Pe]=(0,r.useState)("loading"),q=(0,r.useCallback)(async()=>{if(!g||!V||S||oe.current||!O)return;oe.current=!0,he(!0);let W=m?await m("card"):{proceed:!0};if(!W.proceed){oe.current=!1,he(!1);return}E?.("card");let ce=W.sessionId??t,Ne=W.nonce??n,Se=W.accountPatch?.email??l;try{c?.(null);let Ce=await V.submit();if(Ce.error){c?.(Ce.error.message??"Payment failed.");return}let te=await g.createPaymentMethod({elements:V});if(te.error||!te.paymentMethod){c?.(te.error?.message??"Failed to create payment method.");return}let be=te.paymentMethod;if(!ce||!Se)throw new Error("Missing sessionId or email for payment.");let ke=be.type||e,de=await new dn.PaymentAPI(s).createSessionIntent(ce,Ne??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ke,paymentMethodId:null,intentKind:"payment"});if(de.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ze=de.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:ze,sessionId:ce,nonce:Ne,accountPatch:W.accountPatch,paymentMethodId:be.id,paymentMethodType:be.type??e,gateway:"stripe"}))}catch{}let{error:Be,paymentIntent:Ee}=await g.confirmPayment({clientSecret:ze,confirmParams:{return_url:window.location.href,payment_method:be.id},redirect:"if_required"});if(Be){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let me=Be.message??"Payment failed.";c?.(me),k?.(wt("card",me,{code:Be.code})),await Zr({billingApiUrl:s,sessionId:ce,nonce:Ne,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Be.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 ie=typeof Ee?.payment_method=="string"?Ee.payment_method:Ee?.payment_method?.id;u({id:ie??be.id,type:"card",threeDSecureActionResultTokenId:Ee?.id,gateway:"stripe",paymentMethodType:be.type??e},{accountPatch:W.accountPatch,sessionId:ce,nonce:Ne})}catch(Ce){c?.(Ce instanceof Error?Ce.message:"Payment failed. Please try again.")}finally{oe.current=!1,he(!1)}},[g,V,S,O,m,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)(pt.PaymentElement,{onReady:()=>Pe("ready"),onLoadError:()=>{Pe("load_error"),Mo(Tt(D),"stripe","apm")},onChange:W=>{ee(!!W.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...l?{email:l}:{}}}}}),(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{q()},disabled:!O||Z||S||H!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:B,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!O||Z||S||H!=="ready"?"not-allowed":"pointer",opacity:!O||Z||S||H!=="ready"?.5:1,transition:"opacity 120ms ease-out",...f??{}},children:Z?"Processing\u2026":`Pay with ${(0,w.getStripeMethodDisplayName)(e)}`}),R&&(0,i.jsx)(rr,{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:m,onDecline:E,runBeforeButtonClick:S,onLoadStateChange:B,isProcessing:d=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:R=8,submitButtonStyle:D,buttonAppearance:g,themeId:V,onExpandApm:Z,expandedApmMethod:he}){let[oe,O]=(0,r.useState)(null),[ee,H]=(0,r.useState)(null),Pe=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&u?B?.("ready"):u||B?.("loading")},[s.length,u,B]);let q=(0,r.useCallback)(async te=>{if(!u||Pe.current||d)return;Pe.current=!0,H(te);let be=S?await S("card"):{proceed:!0};if(!be.proceed){Pe.current=!1,H(null);return}m?.("card");let ke=be.sessionId??e,de=be.nonce??t,ze=be.accountPatch?.email??n;try{if(N?.(null),!ke||!ze)throw new Error("Missing sessionId or email for payment.");let Be=await new dn.PaymentAPI(o).createSessionIntent(ke,de??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,paymentMethodId:null,intentKind:"payment"});if(Be.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ee=Be.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Ee,sessionId:ke,nonce:de,accountPatch:be.accountPatch,paymentMethodType:te,gateway:"stripe"}))}catch{}let{error:I,paymentIntent:ie}=await u.confirmPayment({clientSecret:Ee,confirmParams:{return_url:window.location.href,payment_method_data:{type:te,billing_details:{name:l&&l.trim().length>=3?l.trim():"FloPay Customer",...ze?{email:ze}:{}}}},redirect:"if_required"});if(I){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let Ue=I.message??"Payment failed.";N?.(Ue),E?.(wt("card",Ue,{code:I.code})),await Zr({billingApiUrl:o,sessionId:ke,nonce:de,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,providerDeclineReason:I.code??"provider_declined"}});return}let me=ie?.status;if(!Vr(me)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let Ue=me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";N?.(Ue),E?.(wt("card",Ue,{code:me??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let $e=typeof ie?.payment_method=="string"?ie.payment_method:ie?.payment_method?.id;k({id:$e??ie?.id,type:"card",threeDSecureActionResultTokenId:ie?.id,gateway:"stripe",paymentMethodType:te},{accountPatch:be.accountPatch,sessionId:ke,nonce:de})}catch(Be){N?.(Be instanceof Error?Be.message:"Payment failed. Please try again.")}finally{Pe.current=!1,H(null)}},[u,d,S,m,e,t,n,o,l,k,N,E]),[W,ce]=(0,r.useState)(null),Ne=Z?he??null:W,Se=(0,r.useCallback)(te=>{Pe.current||d||Ne&&Ne!==te||((0,w.needsStripeMethodExplicitConfirm)(te)?Z?Z(te):ce(te):q(te))},[Ne,d,q,Z]),Ce=(0,r.useMemo)(()=>W?{...c,paymentMethodTypes:[W]}:null,[W,c]);return(0,i.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(te=>{let be=he===te,ke=ee===te,de=ee!==null&&ee!==te||he!=null&&he!==te;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(ns,{method:te,themeId:V,submitting:ke,disabled:de,highlighted:be,hasNextStep:(0,w.needsStripeMethodExplicitConfirm)(te),onClick:()=>Se(te),backgroundColor:g?.backgroundColor,borderColor:g?.borderColor,textColor:g?.textColor,borderRadius:g?.borderRadius,fontFamily:g?.fontFamily}),!Z&&W===te&&Ce&&u&&(0,i.jsx)(pt.Elements,{stripe:u,options:Ce,children:(0,i.jsx)(Bo,{method:te,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:k,onErrorChange:N,onDecline:E,onCancel:()=>ce(null),runBeforeButtonClick:S,onButtonClick:m,isProcessing:d,submitButtonColor:f,submitButtonBorderRadius:R,submitButtonStyle:D})},te)]},te)})})}function rs({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:u,onDecline:c,onTokenizedBody:k,firstName:N,lastName:m,chv:E,className:S,isProcessing:B,error:d,onErrorChange:f,showPayPal:R=!0,showStripe:D=!0,enabledPaymentMethods:g,enabledPaymentMethodCountries:V,showApplePay:Z=!0,showGooglePay:he=!0,layout:oe="default",theme:O,buttonsTheme:ee,buttonsStyles:H,appearance:Pe,cardButtonContent:q,cardBackButtonContent:W,cardTitleContent:ce,showSecurityFooter:Ne,onButtonClick:Se,onBeforeButtonClick:Ce,enableAVS:te,cardFieldOrder:be,cardPreFormSlot:ke,avsLayout:de="row",country:ze,zip:Be,addressLine1:Ee,addressLine2:I,city:ie,state:me,onCountryChange:$e,onZipChange:Ue,avsCheck:Q,checkoutType:A,checkoutLayout:Y,totalAmount:ye=0,currency:Me="usd",initialCardOpen:st=!1,directPaypal:tt,isSubscription:et=!1,session:p,debug:je=!1}){let qe=ln(),Ge=qr(),Ke=(0,r.useContext)(sn),Yt=Kr(),[ht,kt]=(0,r.useState)(!1),[h,_e]=(0,r.useState)(null),[Ve,lt]=(0,r.useState)(ze??"US"),[it,nt]=(0,r.useState)(Be??""),[Je,Re]=(0,r.useState)(Ee??""),[Pt,He]=(0,r.useState)(I??""),[zt,Rt]=(0,r.useState)(ie??""),[yn,Rn]=(0,r.useState)(me??""),[In,zn]=(0,r.useState)({}),gt=(0,r.useRef)(Be??""),Ut=(0,r.useRef)(ze??"US"),Mt=(0,r.useRef)(Ee??""),Gt=(0,r.useRef)(I??""),tn=(0,r.useRef)(ie??""),fn=(0,r.useRef)(me??""),G=(0,r.useMemo)(()=>(0,w.resolveAVSConfig)(te),[te]),Fn=G!==null,gn=!!p?.vault?.html,$t=!!p?.gateways?.pcivault,M=!!(p?.gateways?.stripe?.enabledPaymentMethods??g)?.includes("card"),Xe=gn||M||$t,Te=!!(D&&Xe&&qe&&e),[Dn,We]=(0,r.useState)(()=>oe!=="buttons"||st?e??null:null),[Un,hn]=(0,r.useState)(0),Pn=oe!=="buttons"||st||!!e&&Dn===e,rt=(0,r.useMemo)(()=>!qe||!Te||!e||!Pn?null:qe.cardCapture({sessionId:e}),[qe,Te,e,Pn]),It=(0,r.useMemo)(()=>{let a=Ve,v=G?(0,w.isAVSFieldVisible)(G.postal_code,a):!1;return es(a,it,v)},[G,Ve,it]),{avsInvalid:qt,invalidAvsFields:At}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!Te||!G)return{avsInvalid:!1,invalidAvsFields:a};let v=Ve,K=(ae,Ze)=>(0,w.isAVSFieldVisible)(ae,v)&&!Ze.trim(),le={line1:K(G.address_line_1,Je),city:K(G.city,zt),state:K(G.state,yn),zip:It.empty||It.malformed};return{avsInvalid:le.line1||le.city||le.state||le.zip,invalidAvsFields:le}},[Te,G,Ve,Je,zt,yn,It]),[Jt,nn]=(0,r.useState)(!1),[En,Kt]=(0,r.useState)(!1),[Ft,Xt]=(0,r.useState)(()=>xo(p?.vault)),[we,mt]=(0,r.useState)(st&&Xe?"card":"buttons"),[ct,bn]=(0,r.useState)(null),$n=we==="expanding"||we==="card",Dt=280,Vt=(0,r.useRef)(null),bt=(0,r.useCallback)(a=>{Vt.current&&clearTimeout(Vt.current),Vt.current=setTimeout(()=>{Vt.current=null,a()},Dt)},[Dt]);(0,r.useEffect)(()=>()=>{Vt.current&&clearTimeout(Vt.current)},[]);let Xn=(0,r.useCallback)(()=>{We(e??null),hn(a=>a+1),mt("expanding"),bt(()=>mt("card"))},[bt,e]),Ht=(0,r.useCallback)(()=>{mt("collapsing"),bt(()=>mt("buttons"))},[bt]),_=(0,r.useCallback)(a=>{bn(a),mt("apm-expanding"),bt(()=>mt("apm-form"))},[bt]),j=(0,r.useCallback)(()=>{mt("apm-collapsing"),bt(()=>{mt("buttons"),bn(null)})},[bt]);(0,r.useEffect)(()=>{oe==="buttons"&&st&&Xe&&(We(e??null),mt("card"))},[oe,st,Xe,e]);let[X,re]=(0,r.useState)(null),ue=(0,r.useRef)(!1),[$,P]=(0,r.useState)(null),ne=(0,r.useRef)($);(0,r.useEffect)(()=>{ne.current=$},[$]);let z=n||Yt,pe=d??h,ve=(0,r.useMemo)(()=>(0,Nt.resolveTheme)(O),[O]),x=(0,r.useMemo)(()=>{let a=ve?.buttonsLayout??(0,w.resolveButtonsLayoutTheme)(ee);return H?{...a,...H,cardButton:{...a.cardButton,...H.cardButton},cardFormContainer:{...a.cardFormContainer,...H.cardFormContainer},backButton:{...a.backButton,...H.backButton},backButtonIcon:{...a.backButtonIcon,...H.backButtonIcon},submitButton:{...a.submitButton,...H.submitButton},title:{...a.title,...H.title}}:a},[ve,ee,H]),vt=Pe??ve?.appearance,F=(0,r.useMemo)(()=>{let a=vt?.variables,v=Ze=>typeof Ze=="string"&&Ze?Ze:void 0,K=x.submitButton,le=v(a?.colorPrimary)??v(K?.backgroundColor)??"#4A49FF",U=oe==="buttons",ae=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(ae?.color)??v(a?.colorText)??"#262833",borderColor:v(x.cardInputBorder)??(U?"#e5e7eb":"#A4A4FF"),placeholderColor:v(x.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(ae?.fontFamily)??v(a?.fontFamily)??"Poppins, sans-serif",fontSize:v(x.cardInputFontSize)??v(a?.fontSizeBase)??"16px",fontWeight:String(La(ae?.fontWeight)??400),borderRadius:v(a?.borderRadius)??"8px"}},[vt,x,oe]),y=Ke.inlineSessionPatchProcessing??!1,b=(B??ht)||y,fe=z.replace(/\/+$/,""),J=(0,r.useMemo)(()=>Io({userId:o,email:l,firstName:N,lastName:m,country:ze,zip:Be},In),[o,l,N,m,ze,Be,In]),Ye=[J.firstName,J.lastName].filter(a=>!!a?.trim()).join(" "),dt=(0,r.useMemo)(()=>qe?qe.getRawProvider():null,[qe]),Fe=(0,r.useMemo)(()=>Ge?Ge.getRawProvider():null,[Ge]),Ie=ye||100,se=(0,r.useMemo)(()=>vt?(0,dn.toStripeAppearance)(vt):null,[vt]),De=se?{appearance:se}:null,rn=(0,r.useMemo)(()=>{let a=se??{},v=a.rules??{};return{...a,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[se]),Wt=(0,r.useMemo)(()=>{let a=Ia(ye);return{...a,currency:Me.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...De}},[ye,Me,De]),Lt=(0,r.useMemo)(()=>({mode:"payment",amount:Ie,currency:Me.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...De}),[Ie,Me,De]),ge=(0,r.useCallback)(a=>{_e(a),f?.(a)},[f]);(0,r.useEffect)(()=>{!Te||!rt||rt.setCardFieldOrder?.(be??null,G==null)},[Te,rt,be,G]),(0,r.useEffect)(()=>{(we==="expanding"||we==="collapsing"||we==="apm-expanding"||we==="apm-collapsing")&&ge(null)},[we,ge]);let on=(0,r.useCallback)((a,v,K)=>{c?.(wt(a,v,K))},[c]),Zn=(0,r.useCallback)((a,v,K)=>{let le=K?.popupBlocked??Nn(v),U=Zi(a,le),ae=Yn(K?.code)??Bn(v)??"external_payment_method_failed",Ze=new Nt.FloPayError(U,"api_error",{code:"external_payment_method_failed",param:a});re(null),oe==="buttons"&&(mt("buttons"),bn(null)),ge(U),u?.(Ze),console.error("[FloPay] External payment method failed:",{method:a,code:ae,popupBlocked:le})},[oe,u,ge]);(0,r.useEffect)(()=>{if(!Te||!e){Xt(null);return}let a=xo(p?.vault);if(a){Xt(a);return}if(!Pn){Xt(null);return}Xt(null);let v=!0;return new dn.PaymentAPI(fe).getVaultCapture(e,t).then(K=>{if(!v)return;let le=xo(K);le?Xt(le):ge("Failed to load the secure card form.")}).catch(K=>{v&&ge(K instanceof Error?K.message:"Failed to load the secure card form.")}),()=>{v=!1}},[Te,Pn,Un,e,p?.vault?.html,p?.vault?.messageToken,p?.vault?.expectedOrigin,fe,t,ge]);let qn=(0,r.useRef)({onComplete:s,onError:u,updateError:ge,emitDecline:on,resolvedAccount:J,avsConfig:G,avsCheckProp:Q,sessionId:e,nonce:t,baseUrl:fe});qn.current={onComplete:s,onError:u,updateError:ge,emitDecline:on,resolvedAccount:J,avsConfig:G,avsCheckProp:Q,sessionId:e,nonce:t,baseUrl:fe};let uo=(0,r.useRef)(!1),li=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:v,avsCheckProp:K}=qn.current,le=Ut.current||a.country||"US",U=v?(0,w.isAVSFieldVisible)(v.state,le):!1,ae=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=ae&&!U&&Ze?(0,w.getStateFromPostalCode)(le,(gt.current??"").trim()):null,_t=U?fn.current:ot;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Ze&&gt.current?{zip:gt.current}:{},...Ct&&tn.current?{city:tn.current}:{},..._t?{state:_t}:{},...ae&&Mt.current?{addressLine1:Mt.current}:{},...Et&&Gt.current?{addressLine2:Gt.current}:{},country:le},...K!==void 0?{avsCheck:K}:{},...v?{avsConfig:{country:(0,w.isAVSFieldVisible)(v.country,le),postal_code:Ze,address_line_1:ae,address_line_2:Et,city:Ct,state:U}}:{}}},[]);(0,r.useEffect)(()=>{!Te||!rt||rt.setSubmitGate?.(qt)},[Te,rt,qt]),(0,r.useEffect)(()=>{if(!Te||!rt)return;uo.current=!1;let a=!1,v=rt.on("submitting",()=>{nn(!0),re("processing");let{baseUrl:ae,sessionId:Ze,nonce:Ct,updateError:Et,onError:ot}=qn.current;!Ze||!Ct||new dn.PaymentAPI(ae).patchAccountSnapshot(Ze,Ct,li(),{telemetryMode:"best_effort"}).catch(_t=>{if(!Yi(_t))return;let Oe=_t instanceof Error?_t.message:"Please check your billing address and try again.";Et(Oe),re(null),ot?.(_t instanceof Nt.FloPayError?_t:new Nt.FloPayError(Oe,"api_error"))})}),K=rt.on("complete",async ae=>{ar(ae.sessionId??qn.current.sessionId),re("success"),await new Promise(Ze=>setTimeout(Ze,Tn)),!uo.current&&(uo.current=!0,qn.current.onComplete?.({status:"succeeded",paymentIntentId:ae.intentId,checkoutMethod:"card"}))}),le=rt.on("decline",async ae=>{let{updateError:Ze,emitDecline:Ct}=qn.current,Et=ae.message??"Your payment was declined. Please try another card or contact your bank.";Ze(Et),re("error"),Ct("card",Et,ae.declineReason?{declineCode:ae.declineReason}:void 0),await new Promise(ot=>setTimeout(ot,Cn)),!a&&re(null)}),U=rt.on("error",async ae=>{let{updateError:Ze,onError:Ct}=qn.current,Et=ae.message??"There was a problem processing your payment. Please try again.";Ze(Et),re("error"),Ct?.(new Nt.FloPayError(Et,"api_error")),await new Promise(ot=>setTimeout(ot,Cn)),!a&&re(null)});return()=>{a=!0,v(),K(),le(),U()}},[Te,rt]);let vn=!!tt?.clientId,dr=Array.isArray(g),xr=dr&&g.length>0,ci=dr&&g.includes("paypal"),{expressMethods:Tr,paymentElementMethods:ur}=(0,r.useMemo)(()=>(0,w.partitionStripeMethods)(g,{excludePaypal:vn}),[g,vn]),qo=vn||!!Ge,di=(0,r.useMemo)(()=>qo?Tr.filter(a=>a!=="paypal"):Tr,[Tr,qo]),ui=(0,r.useMemo)(()=>{let a=[];return Z&&a.push("apple_pay"),he&&a.push("google_pay"),a},[Z,he]),Br=dr?di:ui,pi=D&&Br.length>0,po=Fn?Ve:ze,Mr=(0,r.useMemo)(()=>{let a=po?.trim().toUpperCase();return a?V?ur.filter(v=>{let K=V[v];return!K||K.length===0||K.includes(a)}):(0,w.filterStripeMethodsByCountry)(ur,po):ur},[ur,po,V]),mo=(0,r.useMemo)(()=>({mode:"payment",amount:Ie,currency:Me.toLowerCase(),paymentMethodCreation:"manual",appearance:rn}),[Ie,Me,rn]),[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||(dr?ci:Ar===!1)),Xo=D&&pi,pr=Jo&&vn,Zo=Go==="retrying"||Go==="exhausted",mr=Jo&&!!Fe&&(!vn||Zo),yr=Xo&&!!dt,fr=D&&xr&&Mr.length>0&&!!dt,fi=pr&&!Zo?mi:mr&&Na(jo),gi=yr&&Na(Vo),hi=fr&&Wo!=="load_error",Qo=a=>a==="loading"||a==="ready",ea=pr||mr&&Qo(jo)||yr&&Qo(Vo)||fr&&Wo!=="load_error",Fr=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!Fr.current){if(!D&&!R){Fr.current=!0;let a=new Nt.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(a),ge(a.message)}else if(!D&&R&&!vn&&!Fe){Fr.current=!0;let a=new Nt.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(a),ge(a.message)}else if(Ar!==void 0&&!Xe&&!ea){Fr.current=!0;let a=new Nt.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});u?.(a),ge(a.message)}}},[D,R,vn,Fe,Ar,Xe,ea,u,ge]);let ta=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(ta.current||!xr)return;let a=[];Z!==!0&&a.push("showApplePay"),he!==!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,Z,he]);let na=(0,r.useCallback)((a,v)=>Ke.applyInlineSessionPatch?Ke.applyInlineSessionPatch(a).then(K=>({error:null,sessionId:K.sessionId||e,nonce:K.session?.clientSecret||t})).catch(K=>{let le=Da(v,K);return ge(le.message),u?.(le),{error:le,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ke.applyInlineSessionPatch,t,u,e,ge]),an=(0,r.useCallback)(async a=>{if(!Ce)return{proceed:!0};try{let v=await Ce({method:a,sessionId:e||void 0,createSession:Ke.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&zn(le=>({...le??{},...v.account}));let K=await na(v,a);return K.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:K.sessionId,nonce:K.nonce}}return{proceed:!0}}catch(v){let K=Da(a,v);return ge(K.message),u?.(K),{proceed:!1}}},[na,Ke.inlineSessionDraft,Ce,u,e,ge]),ra=(0,r.useCallback)(async(a,v)=>{if(ue.current)return;ue.current=!0,kt(!0),re("processing"),ge(null);let K=v?.sessionId??e,le=v?.nonce??t,U=Io(J,v?.accountPatch),ae=v?.completionPaymentMethodId??Hr(a),Ze=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let Et=await new dn.PaymentAPI(fe).processPayment(U.userId??"",{sessionId:K,nonce:le,tokenizedData:Ze,accountData:{userId:U.userId??"",email:U.email??"",firstName:U.firstName??"",lastName:U.lastName??"",...G?(()=>{let Oe=Ut.current,Qt=(0,w.isAVSFieldVisible)(G.state,Oe),en=(0,w.isAVSFieldVisible)(G.address_line_1,Oe),Hn=(0,w.isAVSFieldVisible)(G.postal_code,Oe),Wn=en&&!Qt&&Hn?(0,w.getStateFromPostalCode)(Oe,(gt.current??"").trim()):null,xt=Qt?fn.current:Wn;return{country:Oe,...Hn&&gt.current?{zip:gt.current}:{},...(0,w.isAVSFieldVisible)(G.city,Oe)&&tn.current?{city:tn.current}:{},...xt?{state:xt}:{},...en&&Mt.current?{addressLine1:Mt.current}:{},...(0,w.isAVSFieldVisible)(G.address_line_2,Oe)&&Gt.current?{addressLine2:Gt.current}:{}}})():{}},chv:E,avsCheck:Q??!1,checkoutType:A,checkoutLayout:Y,avsConfig:G?{country:(0,w.isAVSFieldVisible)(G.country,Ut.current),postal_code:(0,w.isAVSFieldVisible)(G.postal_code,Ut.current),address_line_1:(0,w.isAVSFieldVisible)(G.address_line_1,Ut.current),address_line_2:(0,w.isAVSFieldVisible)(G.address_line_2,Ut.current),city:(0,w.isAVSFieldVisible)(G.city,Ut.current),state:(0,w.isAVSFieldVisible)(G.state,Ut.current)}:void 0});if(Et.ok){ar(K),re("success"),P(null),await new Promise(Oe=>setTimeout(Oe,Tn)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ae,checkoutMethod:a.isPaypal?"paypal":"card"});return}let ot=await Et.json().catch(()=>null);if(ot?.type==="paypal_redirect_required"){let Oe=ot.threeDSecureToken,Qt=ot.paymentMethodId||a.id||"";if(!qe||!Oe){re("error"),ge("PayPal authorization required but no token provided.");return}try{let en=Ge?.getRawProvider();if(!en){ge("PayPal is not available.");return}let Hn={return_url:window.location.href};Qt&&(Hn.payment_method=Qt);let{error:Wn}=await en.confirmPayment({clientSecret:Oe,confirmParams:Hn,redirect:"if_required"});if(Wn){re("error");let xt=Wn.message??"PayPal payment failed.";ge(xt),on("paypal",xt,{code:Wn.code})}}catch(en){re("error"),ge(en instanceof Error?en.message:"PayPal authorization failed.")}return}if(ot?.type==="paypal_direct_required"){let Oe=ot.orderId;if(!Oe){re("error"),ge("PayPal retry required but no order id provided.");return}let Qt=ne.current?.attempts??0;if(Qt>=2){re("error"),ge("PayPal payment could not be completed after multiple attempts."),on("paypal","paypal_direct_required retry limit exceeded");return}yo(!1),fo("loading"),P({orderId:Oe,attempts:Qt+1}),re(null);return}re("error");let _t=ot?.message??"Payment failed. Please try again.";ge(_t),on(a.isPaypal?"paypal":"card",_t,{code:ot?.code??ot?.gatewayErrorCode,declineCode:ot?.declineCode??ot?.gatewayDeclineReason}),await new Promise(Oe=>setTimeout(Oe,Cn))}catch(Ct){re("error"),ge(Ct instanceof Error?Ct.message:"An unexpected error occurred"),await new Promise(Et=>setTimeout(Et,Cn))}finally{kt(!1),re(null),ue.current=!1}},[fe,e,t,J,Ye,E,qe,Ge,s,u,ge,on]),Zt=(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"),K=a.get("payment_intent_client_secret"),le=a.get("redirect_status");if(!v||!K)return;let U=_t=>{let Oe=localStorage.getItem(_t);if(!Oe)return null;try{return JSON.parse(Oe)}catch{return localStorage.removeItem(_t),null}},ae=U(wn)??U(Aa),Ze;if(ae?.clientSecret){if(ae.clientSecret!==K)return;Ze={...ae.accountPatch?{accountPatch:ae.accountPatch}:{},...ae.sessionId?{sessionId:ae.sessionId}:{},...ae.nonce?{nonce:ae.nonce}:{}}}else if(ae?.sessionId&&ae.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=ae?.paymentMethodType??ae?.tokenType??"card",ot="card";(async()=>{let _t=qe?.getRawProvider();if(!_t){let xt="Payment is not available \u2014 please refresh and try again.";ge(xt),on(ot,xt);return}if(le==="failed"){let xt="Payment was declined. Please try again.";ge(xt),on(ot,xt);return}let{paymentIntent:Oe,error:Qt}=await _t.retrievePaymentIntent(K);if(Qt){let xt=Qt.message??"Failed to retrieve payment status.";ge(xt),on(ot,xt,{code:Qt.code});return}let en=Oe?.status,Hn=Vr(en);if(!Oe||!Hn){let xt=en==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ge(xt),on(ot,xt,{code:en??"missing_payment_intent"});return}let Wn=typeof Oe.payment_method=="string"?Oe.payment_method:Oe.payment_method?.id;Zt({id:Wn??ae?.paymentMethodId??ae?.tokenId??Oe.id,type:"card",threeDSecureActionResultTokenId:Oe.id,gateway:ae?.gateway??"stripe",paymentMethodType:Et},Ze)})()},[e,Zt,qe,ge,on]);let go=(0,r.useCallback)(a=>{a.preventDefault()},[]);if(!(qe!==null))return(0,i.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let gr=oe==="buttons",jt=vt?.variables,Pi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ho=jt?.colorBackground,bi=ho&&!Pi.has(ho)?ho:void 0,hr=x.cardInputBorder??(gr?"#e5e7eb":"#A4A4FF"),Po=jt?.colorDanger??"#dc2626",jn=a=>Jt&&a?Po:hr,Dr=(It.malformed||It.empty)&&(En||Jt),vi=Dr?Po:jn(At.zip),bo=x.cardFormContainer?.backgroundColor??bi??(gr?"white":"#EDEDFF"),Pr=x.cardInputBackground??jt?.colorBackground??"white",vo=er(W),aa=er(ce),Qn=x.nameInput,ia=x.cardInputFontSize??ts(Qn?.fontSize)??jt?.fontSizeBase??"16px",sa=typeof Qn?.fontFamily=="string"?Qn.fontFamily:jt?.fontFamily??"Poppins, sans-serif",la=La(Qn?.fontWeight)??400,Ci=x.cardInputColor??(typeof Qn?.color=="string"?Qn.color:void 0)??jt?.colorText??"#262833",Si=x.cardInputPlaceholderColor??"#9ca3af",yt=jt?.borderRadius??"8px",Kn=jt?.borderRadius??x.cardButton?.borderRadius??yt,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)},br=x.cardFormContainer??{},So=br.padding??(gr?"0":"1rem"),wo=br.borderRadius??yt,Ri=rt&&Ft?(0,i.jsx)($r,{capture:rt,html:Ft.html,messageToken:Ft.messageToken,expectedOrigin:Ft.expectedOrigin,theme:F,onReady:()=>{if(!G||typeof document>"u")return;let a=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};a();let v=0,K=window.setInterval(()=>{v+=1;let le=document.activeElement;!!le&&le.tagName==="IFRAME"&&le.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(K)):v>=50&&window.clearInterval(K)},100)},onError:a=>ge(a),onValidation:a=>{ge(a),a&&re(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,...br,padding:So,...ki,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 @@ ${Ze.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),pr&&rn&&(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:f?-2:0},children:[(0,i.jsxs)("button",{type:"button",onClick:Fn,style:{display:"inline-flex",alignItems:"center",gap:yo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:k.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...k.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",...k.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)(Xn,{content:G})]}),Xo?(0,i.jsx)("div",{style:{flex:1}}):(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:k.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...k.title},children:(0,i.jsx)(hr,{content:se})})]}),!pr&&!Xo&&(0,i.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:fo,order:f?-3:0,...k.title},children:(0,i.jsx)(hr,{content:se})}),X&&(0,i.jsx)("div",{style:{order:f?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=He,C=($=!1)=>({backgroundColor:yr,border:`1px solid ${Un($)}`,borderRadius:yt,marginTop:"0.5rem",padding:"10px"}),H=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ta}),ie=(0,R.getStateOptions)(a);return(0,i.jsxs)(i.Fragment,{children:[(0,R.isAVSFieldVisible)(X.address_line_1,a)&&(0,i.jsx)("div",{style:C(Ht.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:Ye,onChange:$=>{Mt.current=$.target.value,Ce($.target.value)},disabled:Te,required:!0,"data-testid":"flopay-address-line1",style:H()})}),(0,R.isAVSFieldVisible)(X.address_line_2,a)&&(0,i.jsx)("div",{style:C(),children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Pt,onChange:$=>{Gt.current=$.target.value,Ke($.target.value)},disabled:Te,"data-testid":"flopay-address-line2",style:H()})}),((0,R.isAVSFieldVisible)(X.city,a)||(0,R.isAVSFieldVisible)(X.state,a))&&(0,i.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,R.isAVSFieldVisible)(X.city,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:yr,borderTop:`1px solid ${Un(Ht.city)}`,borderRight:`1px solid ${Un(Ht.city)}`,borderBottom:`1px solid ${Un(Ht.city)}`,borderLeft:`1px solid ${Un(Ht.city)}`,padding:"10px",borderTopLeftRadius:yt,borderBottomLeftRadius:yt,...(0,R.isAVSFieldVisible)(X.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:yt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Nt,onChange:$=>{Qt.current=$.target.value,kt($.target.value)},disabled:Te,required:!0,"data-testid":"flopay-city",style:H()})}),(0,R.isAVSFieldVisible)(X.state,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:yr,border:`1px solid ${Un(Ht.state)}`,padding:"10px",borderTopRightRadius:yt,borderBottomRightRadius:yt,...(0,R.isAVSFieldVisible)(X.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:yt}},children:ie?(0,i.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:yn,onChange:$=>{fn.current=$.target.value,wn($.target.value)},disabled:Te,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...H(),cursor:"pointer"},children:[(0,i.jsx)("option",{value:"",children:(0,R.getStateLabel)(a)}),ie.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,R.getStateLabel)(a),autoComplete:"billing address-level1",value:yn,onChange:$=>{fn.current=$.target.value,wn($.target.value)},disabled:Te,required:!0,"data-testid":"flopay-state",style:H()})})]}),((0,R.isAVSFieldVisible)(X.country,a)||(0,R.isAVSFieldVisible)(X.postal_code,a))&&(0,i.jsxs)("div",{style:{display:"flex",flexDirection:le==="column"?"column":"row",gap:le==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,R.isAVSFieldVisible)(X.country,a)&&(0,i.jsx)("div",{style:{flex:le==="row"?1:void 0,backgroundColor:yr,borderTop:`1px solid ${mr}`,borderRight:`1px solid ${mr}`,borderBottom:`1px solid ${mr}`,borderLeft:`1px solid ${mr}`,padding:"10px",...le==="row"&&(0,R.isAVSFieldVisible)(X.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:yt,borderBottomLeftRadius:yt,borderRight:"none"}:{borderRadius:yt}},children:(0,i.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:He,onChange:$=>{Ot.current=$.target.value,st($.target.value),ze?.($.target.value),fn.current="",wn("")},disabled:Te,autoComplete:"billing country","data-testid":"flopay-country",style:{...H(),cursor:"pointer"},children:R.COUNTRY_OPTIONS.map($=>(0,i.jsxs)("option",{value:$.code,children:[$.flag," ",$.name]},$.code))})}),(0,R.isAVSFieldVisible)(X.postal_code,a)&&(0,i.jsx)("div",{style:{flex:le==="row"?1:void 0,backgroundColor:yr,border:`1px solid ${pi}`,padding:"10px",...le==="row"&&(0,R.isAVSFieldVisible)(X.country,a)?{borderRadius:"0",borderTopRightRadius:yt,borderBottomRightRadius:yt}:{borderRadius:yt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,R.getPostalCodeLabel)(He),autoComplete:"billing postal-code",value:rt,onChange:$=>{gt.current=$.target.value,Qe($.target.value),Oe?.($.target.value)},onBlur:()=>In(!0),disabled:Te,required:Vt.required,"aria-invalid":Br||void 0,"aria-describedby":Br?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:H()})})]}),Br&&(0,i.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:po,...ta,fontSize:"0.75rem"},children:Vt.empty?`${(0,R.getPostalCodeLabel)(a)} is required`:Hi(a)})]})})()}),f&&ve&&(0,i.jsx)("div",{style:{order:-2,width:"100%"},children:ve}),f&&hi,q&&(0,i.jsx)(Zn,{margin:"0.75rem 0",styleOverride:k.errorBanner,children:q})]}),Mr={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},ra=a=>je?!E||!Pn?(0,i.jsx)("pre",{"data-testid":a,style:Mr,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:Mr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${E}`,` directPaypalConfigured=${Pn}`,` inAppBrowserDetected=${String(xr)}`,` shouldRenderDirectPayPal=${lr}`,` shouldRenderStripePayPal=${cr}`,` hasPaypalStripeInstance=${!!pe}`].join(`
39
- `)}):null,oa=a=>je?!L||!B?(0,i.jsx)("pre",{"data-testid":a,style:Mr,children:"FloPay/Stripe-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:Mr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${L}`,` currency=${Ee}`,` amountInCents=${Re}`,` enabledPaymentMethods: ${JSON.stringify(P??[])}`,` enabledPaymentMethodsProvided=${ir}`,` hasEnabledMethods=${Rr}`,` expressMethods: ${JSON.stringify(Ir)}`,` walletExpressMethods: ${JSON.stringify(Er)}`,` paymentElementMethods: ${JSON.stringify(sr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(_r)}`,` hasStripeInstance=${!!B}`,` shouldRenderWallets=${dr}`,` shouldRenderPaymentElement=${ur}`].join(`
40
- `)}):null,aa=ke==="apm-expanding"||ke==="apm-form"||ke==="apm-collapsing",Ar=ke==="apm-expanding"?`flopay-card-enter ${bt}ms cubic-bezier(0, 0, 0.2, 1) both`:ke==="apm-collapsing"?`flopay-card-exit ${bt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Fr=et?{...io,paymentMethodTypes:[et]}:null;if(re==="buttons"){let a=ke==="buttons"||ke==="expanding"||ke==="apm-expanding",C=ke==="expanding"||ke==="card"||ke==="collapsing",H=V===void 0?{boxSizing:"border-box",height:Wr,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ie=ke==="expanding"||ke==="apm-expanding"?`flopay-buttons-exit ${bt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:ke==="collapsing"||ke==="apm-collapsing"?`flopay-buttons-enter ${bt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,$=ke==="expanding"?`flopay-card-enter ${bt}ms cubic-bezier(0, 0, 0.2, 1) both`:ke==="collapsing"?`flopay-card-exit ${bt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,i.jsxs)("form",{onSubmit:co,className:w,style:{position:"relative"},children:[(0,i.jsx)(wo,{}),on&&(0,i.jsx)(vn,{status:on,errorMessage:q}),(0,i.jsxs)("div",{style:{display:"grid"},children:[(0,i.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!ie?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!ie?qi:{},...ie?{animation:ie,pointerEvents:"none"}:{}},children:[ra("flopay-direct-paypal-gate-debug"),oa("flopay-stripe-gate-debug"),lr&&Ze&&(0,i.jsxs)(i.Fragment,{children:[j&&(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)(vr,{sessionId:e,nonce:t,billingApiUrl:K,email:b.email,clientId:Ze.clientId,environment:Ze.environment,currency:Ee.toUpperCase(),isSubscription:Xe,onTokenizedBody:Jt,onComplete:s,onErrorChange:T,onDecline:c,onTechnicalFailure:Rt,onButtonClick:he,runBeforeButtonClick:an,isProcessing:Te,onLoadStateChange:so,onInitializationStateChange:lo,session:y??null,existingOrderId:j?.orderId,debug:je},j?.orderId??"fresh")]}),cr&&(0,i.jsx)(dt.Elements,{stripe:pe,options:ce,children:(0,i.jsx)(Ba,{sessionId:e,nonce:t,email:b.email,billingApiUrl:K,onTokenizedBody:Jt,onErrorChange:T,isProcessing:Te,onButtonClick:he,onDecline:c,onTechnicalFailure:Rt,runBeforeButtonClick:an,onLoadStateChange:Lo,placeholderBorderRadius:$n})}),dr?(0,i.jsx)(dt.Elements,{stripe:B,options:_e,children:(0,i.jsx)(Ma,{sessionId:e,nonce:t,email:b.email,billingApiUrl:K,intentKind:ue>0?"payment":"setup",expressMethods:Er,onTokenizedBody:Jt,onErrorChange:T,onButtonClick:he,onDecline:c,onTechnicalFailure:Rt,runBeforeButtonClick:an,onLoadStateChange:Oo,placeholderBorderRadius:$n})}):jo?(0,i.jsx)("div",{style:{height:Wr,borderRadius:$n,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ur&&(0,i.jsx)(Aa,{sessionId:e,nonce:t,email:b.email,billingName:[b.firstName,b.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:K,paymentElementMethods:_r,stripeInstance:B,paymentElementBaseOptions:io,onTokenizedBody:Jt,onErrorChange:T,onButtonClick:he,onDecline:c,runBeforeButtonClick:an,onLoadStateChange:Uo,isProcessing:Te,submitButtonColor:qn,submitButtonBorderRadius:yt,submitButtonStyle:k.submitButton,onExpandApm:En,expandedApmMethod:et,themeId:z,buttonAppearance:{backgroundColor:k.cardButton?.backgroundColor,borderColor:k.cardInputBorder,textColor:k.cardButton?.color,borderRadius:$n}}),f&&(0,i.jsx)("button",{type:"button",onClick:async()=>{Te||!(await an("card")).proceed||(he?.("card"),zn())},disabled:Te,style:{width:"100%",...H,...k.cardButton,...Io({themeBundle:p,resolvedPrimaryColor:qn,resolvedBorderRadius:yt,submitButtonStyle:k.submitButton,explicitPrimaryColor:jt?.colorPrimary}),fontSize:k.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Te?"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:Te?.6:1},onMouseEnter:oe=>{!Te&&(p||jt?.colorPrimary)&&(oe.currentTarget.style.backgroundColor=fi)},onMouseLeave:oe=>{(p||jt?.colorPrimary)&&(oe.currentTarget.style.backgroundColor=qn)},onMouseDown:oe=>{oe.currentTarget.style.transform="scale(0.985)"},onMouseUp:oe=>{oe.currentTarget.style.transform="scale(1)"},children:(0,i.jsx)(Jn,{content:V})}),q&&ke==="buttons"&&(0,i.jsx)(Zn,{margin:"0.25rem 0",styleOverride:k.errorBanner,children:q})]}),f&&C&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...$?{animation:$}:{},...ke==="collapsing"?{pointerEvents:"none"}:{}},children:na}),L&&aa&&et&&Fr&&B&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...Ar?{animation:Ar}:{},...ke==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:mo,borderRadius:ho,...fr,padding:go},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,i.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:qt,style:{display:"inline-flex",alignItems:"center",gap:yo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:k.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...k.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",...k.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)(Xn,{content:G})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:k.titleFontSize??"1.05rem",color:fo,paddingRight:80,...k.title},children:`Pay with ${(0,R.getStripeMethodDisplayName)(et)}`})]}),(0,i.jsx)(dt.Elements,{stripe:B,options:Fr,children:(0,i.jsx)(ko,{method:et,sessionId:e,nonce:t,email:b.email,billingName:[b.firstName,b.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:K,onTokenizedBody:Jt,onErrorChange:T,onDecline:c,onCancel:qt,runBeforeButtonClick:an,onButtonClick:he,isProcessing:Te,submitButtonColor:qn,submitButtonBorderRadius:yt,submitButtonStyle:k.submitButton,errorText:q})},et)]})})]})]})}return aa&&et&&Fr&&B&&L?(0,i.jsxs)("form",{onSubmit:co,className:w,style:{position:"relative"},children:[(0,i.jsx)(wo,{}),on&&(0,i.jsx)(vn,{status:on,errorMessage:q}),(0,i.jsx)("div",{style:{...Ar?{animation:Ar}:{},...ke==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:mo,borderRadius:ho,...fr,padding:go},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,i.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:qt,style:{display:"inline-flex",alignItems:"center",gap:yo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:k.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...k.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",...k.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)(Xn,{content:G})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:k.titleFontSize??"1.05rem",color:fo,paddingRight:80,...k.title},children:`Pay with ${(0,R.getStripeMethodDisplayName)(et)}`})]}),(0,i.jsx)(dt.Elements,{stripe:B,options:Fr,children:(0,i.jsx)(ko,{method:et,sessionId:e,nonce:t,email:b.email,billingName:[b.firstName,b.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:K,onTokenizedBody:Jt,onErrorChange:T,onDecline:c,onCancel:qt,runBeforeButtonClick:an,onButtonClick:he,isProcessing:Te,submitButtonColor:qn,submitButtonBorderRadius:yt,submitButtonStyle:k.submitButton,errorText:q})},et)]})})]}):(0,i.jsxs)("form",{onSubmit:co,className:w,style:{position:"relative"},children:[(0,i.jsx)(wo,{}),on&&(0,i.jsx)(vn,{status:on,errorMessage:q}),(0,i.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ra("flopay-direct-paypal-gate-debug-default"),oa("flopay-stripe-gate-debug-default"),lr&&Ze&&(0,i.jsxs)(i.Fragment,{children:[j&&(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)(vr,{sessionId:e,nonce:t,billingApiUrl:K,email:b.email,clientId:Ze.clientId,environment:Ze.environment,currency:Ee.toUpperCase(),isSubscription:Xe,onTokenizedBody:Jt,onComplete:s,onErrorChange:T,onDecline:c,onTechnicalFailure:Rt,onButtonClick:he,runBeforeButtonClick:an,isProcessing:Te,onLoadStateChange:so,onInitializationStateChange:lo,session:y??null,existingOrderId:j?.orderId,debug:je},j?.orderId??"fresh")]}),cr&&(0,i.jsx)(dt.Elements,{stripe:pe,options:ce,children:(0,i.jsx)(Ba,{sessionId:e,nonce:t,email:b.email,billingApiUrl:K,onTokenizedBody:Jt,onErrorChange:T,isProcessing:Te,onButtonClick:he,onDecline:c,onTechnicalFailure:Rt,runBeforeButtonClick:an,onLoadStateChange:Lo,placeholderBorderRadius:$n})}),dr&&(0,i.jsx)(dt.Elements,{stripe:B,options:_e,children:(0,i.jsx)(Ma,{sessionId:e,nonce:t,email:b.email,billingApiUrl:K,intentKind:ue>0?"payment":"setup",expressMethods:Er,onTokenizedBody:Jt,onErrorChange:T,onButtonClick:he,onDecline:c,onTechnicalFailure:Rt,runBeforeButtonClick:an,onLoadStateChange:Oo,placeholderBorderRadius:$n})}),ur&&(0,i.jsx)(Aa,{sessionId:e,nonce:t,email:b.email,billingName:[b.firstName,b.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:K,paymentElementMethods:_r,stripeInstance:B,paymentElementBaseOptions:io,onTokenizedBody:Jt,onErrorChange:T,onButtonClick:he,onDecline:c,runBeforeButtonClick:an,onLoadStateChange:Uo,isProcessing:Te,submitButtonColor:qn,submitButtonBorderRadius:yt,submitButtonStyle:k.submitButton,themeId:z,onExpandApm:En,expandedApmMethod:et,buttonAppearance:{backgroundColor:k.cardButton?.backgroundColor,borderColor:k.cardInputBorder,textColor:k.cardButton?.color,borderRadius:$n}})]}),f&&(li||si||ci)&&(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,i.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,i.jsx)("span",{children:"or pay with card"}),(0,i.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),f&&na]})}var nr=require("@flopay/js"),Je=require("@flopay/shared");var Sr="card";async function Ji(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 Xi(e,t,n,l){if(l){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:u,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:u??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:s}=await e.confirmCardPayment(t,n);return{error:s,intent:o??null}}function Sn(e,t){return Object.assign(e,{checkoutMethod:t})}function za(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 Zi(e){return e.status==="succeeded"||e.status==="declined"}async function Ua(e){if(typeof document>"u"||typeof window>"u")throw new Je.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,l=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,s=async()=>{let m=new AbortController,x=()=>m.abort();e.signal?.aborted?m.abort():e.signal?.addEventListener("abort",x);let w=window.setTimeout(()=>m.abort(),l);try{let F=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:m.signal});if(!F.ok)return{status:"unknown"};let d=await F.json().catch(()=>null);return Qi(d)}catch{return{status:"unknown"}}finally{window.clearTimeout(w),e.signal?.removeEventListener("abort",x)}},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 I=document.createElement("iframe");I.setAttribute("title","Card authentication"),I.setAttribute("allow","payment"),I.tabIndex=0,I.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),I.src=e.nextActionRedirectUrl,c.appendChild(I),document.body.appendChild(c),I.focus();let O=null;try{O=new URL(e.billingApiUrl,window.location.href).origin}catch{O=null}try{let m=await new Promise((x,w)=>{let F=!1,d=0,g=0,E=0,L=!1,P=()=>{window.clearTimeout(d),window.clearInterval(g),window.clearTimeout(E),window.removeEventListener("message",re),I.removeEventListener("load",Z),e.signal?.removeEventListener("abort",me)},W=async()=>{if(!(F||L)){L=!0;try{let z=await s();if(F||!Zi(z))return;F=!0,P(),x(z)}finally{L=!1}}},Z=()=>{window.clearTimeout(E),E=window.setTimeout(()=>{W()},250)},me=()=>{F||(F=!0,P(),w(new Je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},re=z=>{if(z.source!==I.contentWindow||O&&z.origin!==O)return;let te=z.data;!te||typeof te!="object"||te.source!=="flopay-vault-3ds-return"||F||(F=!0,P(),x(null))};d=window.setTimeout(()=>{F||(F=!0,P(),w(new Je.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),g=window.setInterval(()=>{W()},n),I.addEventListener("load",Z),window.addEventListener("message",re),e.signal?.addEventListener("abort",me),e.signal?.aborted&&me()});return m||await s()}finally{c.parentNode?.removeChild(c),u?.isConnected&&u.focus()}}function Qi(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 Sn(new Je.FloPayError(s,"api_error",{code:e?.gatewayErrorCode}),l)}function Eo(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Jr(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function es(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 $a(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Jr(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||Jr(c)))return c;let u=o.gateways;if(u&&typeof u=="object"){let c=u.stripe;if(c&&typeof c=="object"){let I=c,O=[I.stripeClientSecret,I.clientSecret];for(let m of O)if(typeof m=="string"&&m.length>0&&(!t?.requirePaymentIntentClientSecret||Jr(m)))return m}}}}async function ts({billingApiUrl:e,sessionId:t,nonce:n,responseJson:l}){let o=$a(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 nr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Jr(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function rr({billingApiUrl:e,sessionId:t,session:n,nonce:l,tokenizedData:o,returnUrl:s,telemetry:u}){let c=e.replace(/\/+$/,""),I=t??n.id,O=l??n.clientSecret,m=n.customer?.id??n.accountData?.userId??"",x=n.customer?.email??n.accountData?.email??"",w=n.customer?.firstName??n.accountData?.firstName??"",F=n.customer?.lastName??n.accountData?.lastName??"",d=n.customer?.country??n.accountData?.country??void 0,g=n.customer?.zip??n.accountData?.zip??void 0,E=new nr.PaymentAPI(c,u===!1?{telemetry:!1}:void 0),L=await es(()=>E.processPayment(m,{sessionId:I,nonce:O,tokenizedData:o,accountData:{userId:m,email:x,firstName:w,lastName:F,country:d,zip:g},returnUrl:s??Eo(n)}));if(L.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:qr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let P=await L.json().catch(()=>null);if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let W=$a(P);if(!W)throw new Je.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:P.type,threeDSecureToken:W,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let W=await ts({billingApiUrl:c,sessionId:I,nonce:O,responseJson:P});if(W)return W;throw Sn(new Je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new Je.FloPayError(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason})}async function Xr(e,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:u,returnUrl:c,telemetry:I}){let O=t?.getRawProvider();if(!O)throw new Je.FloPayError("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!l||!e.threeDSecureToken)throw Sn(new Je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let m=(0,Je.isSetupIntentClientSecret)(e.threeDSecureToken),x=null,w=e.paymentMethodId,F=await Ji(O,e.threeDSecureToken,m);if(F){if(F.error)throw Sn(new Je.FloPayError(F.error.message??`Failed to retrieve 3DS ${m?"setup":"payment"} status.`,"api_error",{code:F.error.code}),"card");let g=F.intent;!w&&g?.payment_method&&(typeof g.payment_method=="string"?w=g.payment_method:"id"in g.payment_method&&(w=g.payment_method.id??void 0))}let d=w?await Xi(O,e.threeDSecureToken,{payment_method:w,return_url:c??Eo(u)??window.location.href},m):null;if(d){if(d.error)throw Sn(new Je.FloPayError(d.error.message??"3DS authentication failed.","api_error",{code:d.error.code}),"card");x=d.intent}else{let g=await O.handleNextAction({clientSecret:e.threeDSecureToken});if(g.error)throw Sn(new Je.FloPayError(g.error.message??"3DS authentication failed.","api_error",{code:g.error.code}),"card");x=(m?g.setupIntent:g.paymentIntent)??null}if(x&&(x.status==="requires_capture"||x.status==="succeeded"||x.status==="processing")){let g=await rr({billingApiUrl:o,sessionId:s,session:u,telemetry:I,tokenizedData:{id:x.id,type:"card",threeDSecureActionResultTokenId:x.id},returnUrl:c});return g.type==="success"?{...g.result,paymentIntentId:g.result.paymentIntentId??x.id,paymentMethodId:g.result.paymentMethodId??w}:Xr(g,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:u,returnUrl:c,telemetry:I})}throw Sn(new Je.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let m=(n??t)?.getRawProvider();if(!m)throw Sn(new Je.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:w}=await m.handleNextAction({clientSecret:e.threeDSecureToken});if(w)throw Sn(new Je.FloPayError(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:x}=await m.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Eo(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(x)throw Sn(new Je.FloPayError(x.message??"PayPal authorization failed.","api_error",{code:x.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Je.FloPayError("Unsupported payment redirect state.","api_error")}function Kn(e){if(e instanceof Je.FloPayError){let l=Dn(e.message);return l&&l!==e.message?Object.assign(new Je.FloPayError(l,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Dn(t)??t;return new Je.FloPayError(n,"api_error")}function Zr(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Je.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function Qr({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,nr.loadFloPay)(e,{billingApiUrl:n,locale:l,telemetry:o}),s?(0,nr.loadFloPay)(t,{billingApiUrl:n,locale:l,telemetry:o}).catch(I=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",I),null)):Promise.resolve(null)]);return{flopay:u,paypalFlopay:t?s?c:u:null}}var S=require("react/jsx-runtime"),or=44,Ao="flopay_checkout_saved_payment_resume",_o=new Map;function wr(e){return new Promise(t=>setTimeout(t,e))}function eo(e,t,n){let l=Lr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Be.SDK_VERSION,enabled:t!==!1});return l.beginCheckout(n),l}function to(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function xo(e,t,n,l,o){let s=eo(e,t,n);s.error({errorCode:l,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),to(s)}function ns(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 Mo(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function To(e){return!e||e.data.stripe?.publishableKey?!1:!!Mo(e)?.clientId}function ar(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function rs(){if(!ar())return null;try{let e=window.sessionStorage.getItem(Ao);return e?JSON.parse(e):null}catch{return null}}function qa(e){if(ar())try{window.sessionStorage.setItem(Ao,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Bo(){if(ar())try{window.sessionStorage.removeItem(Ao)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function os(e){if(!ar())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 as(e,t,n){if(ar())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 ja(e){if(ar())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function is(){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 Va(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 no({sessionId:e,nonce:t,createSession:n,billingApiUrl:l,telemetry:o,appearance:s,locale:u,loading:c,error:I,onComplete:O,onError:m,onDecline:x,onCountryChange:w,onZipChange:F,showPayPal:d=!0,showStripe:g=!0,showApplePay:E=!0,showGooglePay:L=!0,debug:P=!1,layout:W,theme:Z,buttonsTheme:me,buttonsStyles:re,cardButtonContent:z,cardBackButtonContent:te,cardTitleContent:Y,showSecurityFooter:ye,onButtonClick:V,onBeforeButtonClick:G,enableAVS:se,cardFieldOrder:Fe,cardPreFormSlot:he,avsLayout:ge,className:ne,initialErrorMessage:fe=null,children:ve,checkoutMode:le,confirmLabel:Ne,renderConfirmButton:Ie,onSessionCompleted:Se}){let _=(0,Be.resolveBillingApiUrl)(l),ae=(0,N.useMemo)(()=>(0,Be.resolveTheme)(Z),[Z]),de=s??ae?.appearance,ze=n?"embedded_checkout":"standard_checkout",Oe=ve?"custom_layout":W==="buttons"?"buttons_layout":"default_layout",[Q,D]=(0,N.useState)(null),[J,ue]=(0,N.useState)(null),Ee=(0,N.useRef)(null),[it,Ze]=(0,N.useState)(null),Xe=(0,N.useRef)(null),[y,je]=(0,N.useState)(null),[Ue,We]=(0,N.useState)(e??""),Ve=e??Ue,Yt=n?"":Ve,[ht,wt]=(0,N.useState)(!0),[h,we]=(0,N.useState)(null),[He,st]=(0,N.useState)("full"),[rt,Qe]=(0,N.useState)(!1),[Ye,Ce]=(0,N.useState)(fe),[Pt,Ke]=(0,N.useState)(null),[Nt,kt]=(0,N.useState)(null),[yn,wn]=(0,N.useState)(void 0),[kn,On]=(0,N.useState)(""),[gt,Ot]=(0,N.useState)(!1),[Mt,Gt]=(0,N.useState)("loading"),[Qt,fn]=(0,N.useState)(0),X=(0,N.useRef)(!1),An=(0,N.useRef)(!1),gn=(0,N.useRef)(!1),zt=(0,N.useRef)(null),ot=(0,N.useMemo)(()=>({checkoutMode:le??He,layout:ve?"unknown":W==="buttons"?"buttons":"embedded"}),[le,ve,He,W]),f=(0,N.useRef)(O);f.current=O;let ut=(0,N.useRef)(m);ut.current=m;let Tt=(0,N.useRef)(x);Tt.current=x,(0,N.useEffect)(()=>{xt(J)?.setCheckoutContext(ot),it&&it!==J&&xt(it)?.setCheckoutContext(ot)},[J,it,ot]);let Rn=(0,N.useRef)(Se);Rn.current=Se;let Pe=(0,N.useCallback)(M=>{Gt(M),!(M!=="exhausted"||gn.current)&&(gn.current=!0,ut.current?.(new Be.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Vt=(0,N.useCallback)(()=>{Gt("retrying"),fn(M=>M+1)},[]);(0,N.useEffect)(()=>{Gt("loading"),fn(0),gn.current=!1},[Ve]),(0,N.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Be.SDK_VERSION,checkout_type:ze,checkout_layout:Oe,billing_api_url:_})},[Oe,ze,_]);let en=(0,N.useMemo)(()=>n?ke(n):"",[n]),Ht=(0,N.useMemo)(()=>kn===en?yn:void 0,[yn,kn,en]),tn=(0,N.useMemo)(()=>n?bo(n,Ht):void 0,[n,Ht]),nn=le??tn?.checkoutMode??"full",Kt=(0,N.useMemo)(()=>tn?{...tn,checkoutMode:nn}:void 0,[tn,nn]);(0,N.useEffect)(()=>{wn(void 0),On(en)},[en]),(0,N.useEffect)(()=>{Ce(fe)},[fe]);let In=(0,N.useCallback)((M,j,ee)=>{ct(()=>{Tt.current?.(St(M,j,ee))})},[ct]),Ut=(0,N.useCallback)(async(M,j)=>{Ce(null),kt(null),Ke("processing");let ee=j?.sessionId??M.id,U=Ee.current??Xe.current,K=xt(U),q=U?null:eo(_,o,ot),p={log:B=>{K?K.log(B):q?.log(B)},error:B=>{K?K.error(B):q?.error(B)},terminal:B=>{K?K.terminal(B):q?.terminal(B)},performance:B=>{K?K.performance(B):q?.performance(B)},now:()=>K?.now()??q?.now()??0,elapsed:B=>K?.elapsed(B)??Math.max(0,(q?.now()??B)-B)},k=p.now(),be=!!(j?.initialAutoProcessingError||j?.initialAutoProcessingPending),at=!1,$e,Te=()=>{at||(at=!0,be=!0,$e=p.now(),p.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),p.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Bt=!1,b=()=>{Bt||(Bt=!0,p.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),p.performance({stage:"processing",durationMs:p.elapsed(k),durationMode:"machine",paymentMethodCategory:"saved"}),$e!==void 0&&p.performance({stage:"recovery",durationMs:p.elapsed($e),durationMode:"machine",paymentMethodCategory:"saved"}))};p.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),p.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),be&&Te();let v;try{let B=za(j?.initialAutoProcessingError),pe;if(B)Te(),B.type==="paypal_redirect_required"&&zt.current?.publishableKey&&qa({sessionId:ee,publishableKey:zt.current.publishableKey,paypalPublishableKey:zt.current.paypalPublishableKey}),pe=await Xr(B,{flopay:Ee.current,paypalFlopay:Xe.current,attempt3DS:j?.attempt3DS,billingApiUrl:_,sessionId:ee,session:M,telemetry:!1}),B.type==="paypal_redirect_required"&&Bo();else if(j?.initialAutoProcessingPending){let De=await new kr.PaymentAPI(_,{telemetry:!1}).waitForCheckoutSessionCompletion(j.initialAutoProcessingPending.sessionId,{initialDelayMs:j.initialAutoProcessingPending.retryAfterMs});if(De.data.session?.status!=="complete")throw new Be.FloPayError("Automatic payment failed. Please try again.","api_error",{code:De.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});pe={status:"succeeded"}}else{if(j?.initialAutoProcessingError)throw Nn(j.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:j.initialAutoProcessingError.checkoutMethod});if(j?.fromCreateSession)return j?.fallbackToFull&&(st("full"),Va("full")),!1;{let Re=await rr({billingApiUrl:_,sessionId:ee,session:M,telemetry:!1});Re.type==="success"?pe=Re.result:(Te(),Re.type==="paypal_redirect_required"&&zt.current?.publishableKey&&qa({sessionId:ee,publishableKey:zt.current.publishableKey,paypalPublishableKey:zt.current.paypalPublishableKey}),pe=await Xr(Re,{flopay:Ee.current,paypalFlopay:Xe.current,attempt3DS:j?.attempt3DS,billingApiUrl:_,sessionId:ee,session:M,telemetry:!1}),Re.type==="paypal_redirect_required"&&Bo())}}ee&&er(ee),b(),be&&(p.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),p.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),p.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Ke("success"),await wr(Tn),v=()=>f.current?.(pe)}catch(B){let pe=Kn(B),Re=pe.checkoutMethod??Sr;return Ce(pe.message),kt(pe.message),j?.fallbackToFull&&(p.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),st("full"),Va("full")),b(),!!(pe.declineCode||pe.code?.toLowerCase().includes("declin"))?p.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):pe.type==="validation_error"?p.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):p.error({errorCode:be?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:be?"recovery":"processing",paymentMethodCategory:"saved"}),ct(()=>ut.current?.(pe)),In(Re,pe,{code:pe.code,declineCode:pe.declineCode}),Ke("error"),await Promise.allSettled([wr(bn),j?.ensureProvidersReady?j.ensureProvidersReady():Promise.resolve()]),be&&(p.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),p.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{b(),q&&to(q),Ke(null),kt(null)}return ct(v),!0},[In,ct,Kn,_,o,ot]);(0,N.useEffect)(()=>{if(typeof window>"u"||An.current)return;let M=new URLSearchParams(window.location.search),j=M.get("payment_intent_client_secret");if(!j)return;let ee=rs();ee&&(An.current=!0,(async()=>{let U,K=0;Ce(null),kt(null),Ke("processing"),Qe(!0);try{if(M.get("redirect_status")==="failed")throw Object.assign(new Be.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:q,paypalFlopay:p}=await Qr({publishableKey:ee.publishableKey,paypalPublishableKey:ee.paypalPublishableKey,billingApiUrl:_,locale:u,telemetry:o});U=xt(p??q),K=U?.now()??0,U?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),U?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let k=(p??q)?.getRawProvider();if(!k)throw Object.assign(new Be.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:be,error:at}=await k.retrievePaymentIntent(j);if(at)throw Object.assign(new Be.FloPayError(at.message??"Failed to retrieve PayPal payment status.","api_error",{code:at.code}),{checkoutMethod:"paypal"});let $e=ha(be?.status);if(!be||$e==="failed")throw Object.assign(new Be.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Te=typeof be.payment_method=="string"?be.payment_method:be.payment_method?.id,Bt=$e;if(ee.sessionId){let B=(await new kr.PaymentAPI(_,{telemetry:!1}).getUnifiedCheckoutSession(ee.sessionId)).data.session;if(B&&B.status!=="complete"){let pe=await rr({billingApiUrl:_,sessionId:ee.sessionId,session:B,telemetry:!1,tokenizedData:{id:Te??be.id,type:"card",threeDSecureActionResultTokenId:be.id,isPaypal:!0}});if(pe.type!=="success")throw Object.assign(new Be.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Bt=pe.result.status}}ee.sessionId&&er(ee.sessionId),U?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),U?.performance({stage:"redirect_resume",durationMs:U.elapsed(K),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),U?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ke("success"),await wr(Tn),ct(()=>f.current?.({status:Bt,paymentIntentId:be.id,paymentMethodId:Te,checkoutMethod:"paypal"}))}catch(q){let p=Kn(q),k=p.checkoutMethod??"paypal",be=!!(p.declineCode||p.code?.toLowerCase().includes("declin"));if(U)U.performance({stage:"redirect_resume",durationMs:U.elapsed(K),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),be?U.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):U.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(be){let at=eo(_,o,ot);at.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),to(at)}else xo(_,o,ot,"REDIRECT_RESUME_FAILED","redirect_resume");Ce(p.message),kt(p.message),ct(()=>ut.current?.(p)),In(k,p,{code:p.code,declineCode:p.declineCode}),Ke("error"),await wr(bn)}finally{Bo(),is(),Ke(null),kt(null),Qe(!1)}})())},[In,ct,u,Kn,_,o]);let $t=(0,N.useRef)(null);function ke(M){let j=JSON.stringify({c:M?.clientId,cur:M?.currency??"",a:{e:M?.account?.email?.trim().toLowerCase()??"",country:M?.account?.country??""},successUrl:M?.successUrl,cancelUrl:M?.cancelUrl,p:M?.products?.map(U=>`${U.type??""}:${U.code??U.providerItemId??U.providerPlanId??""}:${U.totalAmount??""}:${U.overrideAmount??""}:${U.quantity??1}`).sort(),i:M?.items?.map(U=>`${U.code??U.providerItemId??""}:${U.totalAmount??""}:${U.overrideAmount??""}:${U.quantity??1}`).sort(),s:M?.subscriptions?.map(U=>`${U.code??U.providerPlanId??""}:${U.totalAmount??""}:${U.overrideAmount??""}:${U.quantity??1}`).sort(),couponCodes:M?.couponCodes,tagsData:M?.tagsData,utmMetadata:M?.utmMetadata,tokenizedData:M?.tokenizedData,m:M?.checkoutMode??"full"}),ee=0;for(let U=0;U<j.length;U++)ee=(ee<<5)-ee+j.charCodeAt(U)|0;return`flopay_session_${Math.abs(ee).toString(36)}`}let lt=(0,N.useMemo)(()=>Kt?ke(Kt):"",[Kt]),et=(0,N.useRef)(Kt);et.current=Kt,(0,N.useEffect)(()=>{We(e??"")},[e]),(0,N.useEffect)(()=>{X.current=!1,Ce(fe),kt(null),Ke(null)},[lt,fe,e]);async function hn(M,j){let ee=eo(_,o,ot),U=new kr.PaymentAPI(_,{telemetry:!1});try{let K=os(j);ee.log({name:K?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let q=K?.sid??null,p=null;if(q)try{if(p=await U.getUnifiedCheckoutSession(q,K?.nonce),p.data.session?.status==="complete"){if(ba(q))return{sid:q,result:p};ja(j),q=null,p=null}}catch{ee.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),ja(j),q=null}if(!q){let k=ee.now();ee.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let be={...M,avsCheck:!!se,avsConfig:typeof se=="object"?se:void 0,checkoutType:"embedded_checkout",checkoutLayout:ve?"custom_layout":W==="buttons"?"buttons_layout":"default_layout"};try{p=await U.createAndFetchSession(be),ee.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),ee.performance({stage:"session_create",durationMs:ee.now()-k,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"})}catch(at){let $e=(0,Be.classifyTelemetryFailure)(at,"CHECKOUT_SESSION_CREATE_FAILED","unknown");throw ee.performance({stage:"session_create",durationMs:ee.now()-k,durationMode:"machine",requestCategory:"session_create",statusClass:$e.statusClass}),at instanceof Be.FloPayError&&at.type==="validation_error"?ee.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):$e.statusClass==="4xx"?ee.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):ee.error({...$e,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),at}q=p.data.session?.id??"",q&&as(j,q,p.data.session?.clientSecret)}return{sid:q??"",result:p}}finally{to(ee)}}let rn=(0,N.useCallback)(async M=>{let j=et.current;if(!j)throw new Be.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ee=bo(j,M),U=ke(ee),K=_o.get(U);K||(K=hn(ee,U),_o.set(U,K));let q;try{q=await K}finally{_o.delete(U)}$t.current=U;try{M&&(On(en),wn(Bt=>fa(Bt,M)));let{sid:p,result:k}=q;D(k),k.data.session&&je(k.data.session),p&&We(p);let{publishableKey:be,paypalPublishableKey:at}=Zr(k),{flopay:$e,paypalFlopay:Te}=await Qr({publishableKey:be,paypalPublishableKey:at,billingApiUrl:_,locale:u,telemetry:o});Ee.current=$e,ue($e),Xe.current=Te,Ze(Te),wt(!1)}catch(p){throw $t.current===U&&($t.current=null),p}return q},[u,_,o,ot]),bt=(0,N.useCallback)(async M=>{if(!ss(M)||gt)return{sessionId:Ue,session:y};Ot(!0);try{let j=await rn(M);return{sessionId:j.sid,session:j.result.data.session??null}}finally{Ot(!1)}},[rn,gt,Ue,y]);(0,N.useEffect)(()=>{let M=!1;if(we(null),lt){let U=et.current;return st(nn),wt(!1),$t.current===lt?()=>{M=!0}:(je(ga(U,le)),(async()=>{let K=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),q=nn==="auto"&&!X.current&&!K;q&&(Ce(null),kt(null),Ke("processing"));try{let p=await rn(),k=p.result.data.session??null;zt.current=Zr(p.result);let be=To(p.result);if(!M&&q&&k&&!be){X.current=!0,await Ut(k,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:p.result.autoProcessingError,initialAutoProcessingPending:p.result.autoProcessingPending,autoProcessingAttempted:p.result.autoProcessingAttempted,sessionId:p.sid||k.id});return}!M&&q&&(be&&(X.current=!0),Ke(null),kt(null))}catch(p){if(M)return;let k=p instanceof Be.FloPayError||typeof p=="object"&&p!==null&&"code"in p?p.code:void 0;if(q&&k==="session_auto_completed"){X.current=!0,Ke("success"),await wr(Tn),M||(ct(()=>{f.current?.({status:"succeeded"})}),Ke(null),kt(null));return}q&&(Ke(null),kt(null));let be=p instanceof Be.FloPayError?p:new Be.FloPayError(p instanceof Error?p.message:"Failed to create session","api_error");we(be)}})(),()=>{M=!0})}wt(!0);async function j(){let U=!1;try{let q=await new kr.PaymentAPI(_,{telemetry:!1}).getUnifiedCheckoutSession(Ve,t);if(M)return;D(q);let p=q.data.session??null;if(je(p),!p)throw new Be.FloPayError("No session data returned","api_error");if(p.status==="complete"){wt(!1),ct(()=>{Rn.current?.(p.successUrl??"")});return}if(p.status==="expired")throw new Be.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});U=!0;let k=le??p.checkoutMode??"full";st(k);let be=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),at=To(q);if(k==="auto"&&!X.current&&!be&&!at){X.current=!0;let $e=ee(q);try{if(await Ut(p,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>$e,sessionId:Ve||p.id}),M)return;await $e,M||wt(!1);return}catch{if(M)return;await $e,M||wt(!1);return}}await ee(q),M||wt(!1)}catch(K){if(M)return;K instanceof Be.FloPayError?!U&&!ns(K)&&xo(_,o,ot,"NETWORK_REQUEST_FAILED","session_read"):xo(_,o,ot,"INTERNAL_SDK_ERROR","checkout_mount");let q=K instanceof Be.FloPayError?K:new Be.FloPayError(K instanceof Error?K.message:"Failed to initialize checkout","api_error");we(q),wt(!1)}}async function ee(U){let{publishableKey:K,paypalPublishableKey:q}=Zr(U);zt.current={publishableKey:K,paypalPublishableKey:q};let{flopay:p,paypalFlopay:k}=await Qr({publishableKey:K,paypalPublishableKey:q,billingApiUrl:_,locale:u,telemetry:o});Ee.current=p,ue(p),Xe.current=k,Ze(k)}return j(),()=>{M=!0}},[rn,le,lt,nn,Yt,ct,t,Ut]);let At=(0,N.useCallback)(async()=>{if(!(rt||!y)){Qe(!0),Ce(null);try{await Ut(y,{fallbackToFull:!0,sessionId:Ve||y.id})}finally{Qe(!1)}}},[Ve,rt,Ut,y]),Ft=Mo(Q),zn=To(Q),Fn=(0,N.useMemo)(()=>{if(!Q||!y||!Q.data.stripe?.publishableKey)return;let M={appearance:de,paymentMethodCreation:"manual",billingApiUrl:_};if(Q.data.stripe?.clientSecret)M.clientSecret=Q.data.stripe.clientSecret;else{let j=(0,Be.buildCheckoutDisplayData)(y).total;M.amount=Math.round(j*100)||y.amount,M.currency=y.currency?.toLowerCase()}return M},[Q,y,de,_]),En=!!(n&&!ve&&W==="buttons"&&G&&nn==="full"),qt=(0,N.useMemo)(()=>({session:y,loading:ht,error:h,checkoutMode:He,inlineSessionDraft:Kt,applyInlineSessionPatch:En?bt:void 0,inlineSessionPatchProcessing:gt}),[y,ht,h,He,Kt,En,bt,gt]),on=!!n&&W==="buttons"&&!zn&&(!J||!Fn),Me=Pt?(0,S.jsx)(vn,{status:Pt,errorMessage:Nt}):null;if(ht){if(c)return(0,S.jsxs)(S.Fragment,{children:[c,Me]});if(W==="buttons"){let M=ae?.buttonsLayout?.cardButton?.borderRadius??ae?.appearance.variables?.borderRadius??8,j=ee=>(0,S.jsx)("div",{style:{height:ee,borderRadius:M,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[d&&j(or),g&&(E||L)&&j(or),g&&j(or),(0,S.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Me]})}return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,S.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,S.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Me]})}return h?I?(0,S.jsx)(sn.Provider,{value:qt,children:I(h)}):(0,S.jsx)(sn.Provider,{value:qt,children:(0,S.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:h.message})}):on?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(sn.Provider,{value:qt,children:(0,S.jsx)(cs,{onButtonClick:V,showPayPal:d,showStripe:g,showApplePay:E,showGooglePay:L,theme:Z,buttonsTheme:me,buttonsStyles:re,cardButtonContent:z,cardBackButtonContent:te,cardTitleContent:Y})}),Me]}):zn&&y&&Ft?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(sn.Provider,{value:qt,children:(0,S.jsxs)("div",{className:ne,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ye&&(0,S.jsx)(Zn,{icon:!1,children:Ye}),Mt==="retrying"&&(0,S.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Mt==="exhausted"&&(0,S.jsxs)("div",{role:"alert",children:[(0,S.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,S.jsx)("button",{type:"button",onClick:Vt,children:"Retry PayPal"})]}),Mt!=="exhausted"&&(0,S.jsx)("div",{"aria-hidden":Mt==="retrying"?!0:void 0,style:Mt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,S.jsx)(Ra,{sessionId:Ve,nonce:y.clientSecret||void 0,billingApiUrl:_,email:y.customer?.email,clientId:Ft.clientId,environment:Ft.environment,currency:(y.currency??"usd").toUpperCase(),isSubscription:y.mode==="subscription",onComplete:O,onErrorChange:Ce,onDecline:x,onButtonClick:V,onInitializationStateChange:Pe,allowAutomaticRetry:Qt===0,session:y,telemetry:o,telemetryContext:ot,debug:P},`paypal-init-${Qt}`)})]})}),Me]}):!J||!Fn?(0,S.jsx)(S.Fragment,{children:Me}):He==="confirm"?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(sn.Provider,{value:qt,children:(0,S.jsx)(gr,{flopay:J,paypalFlopay:it,options:Fn,children:(0,S.jsxs)("div",{className:ne,children:[Ye&&(0,S.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ye}),Ie?Ie({onConfirm:At,isProcessing:rt}):(0,S.jsx)("button",{type:"button",onClick:At,disabled:rt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:rt?"not-allowed":"pointer",opacity:rt?.6:1},children:rt?"Processing...":Ne??"Confirm Purchase"})]})})}),Me]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(sn.Provider,{value:qt,children:(0,S.jsx)(gr,{flopay:J,paypalFlopay:it,options:Fn,children:ve?(0,S.jsxs)(S.Fragment,{children:[Ye&&(0,S.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ye}),(0,S.jsx)(ls,{sessionId:Ve,nonce:y?.clientSecret||void 0,billingApiUrl:_,session:y,children:ve})]}):(0,S.jsx)(Gr,{sessionId:Ve,nonce:y?.clientSecret||void 0,email:y?.customer?.email,userId:y?.customer?.id,firstName:y?.customer?.firstName,lastName:y?.customer?.lastName,totalAmount:y?Math.round((0,Be.buildCheckoutDisplayData)(y).total*100):0,currency:y?.currency?.toLowerCase()??"usd",onComplete:O,onError:m,onDecline:x,error:Ye,onErrorChange:Ce,showPayPal:d,showStripe:g,enabledPaymentMethods:Q?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Q?.data.stripe?.enabledPaymentMethodCountries,showApplePay:E,showGooglePay:L,layout:W,theme:Z,buttonsTheme:me,buttonsStyles:re,appearance:de,cardButtonContent:z,cardBackButtonContent:te,cardTitleContent:Y,onButtonClick:V,onBeforeButtonClick:G,enableAVS:se,...Fe?{cardFieldOrder:Fe}:{},...he?{cardPreFormSlot:he}:{},avsLayout:ge,country:y?.customer?.country,city:y?.customer?.city,state:y?.customer?.state,onCountryChange:w,onZipChange:F,avsCheck:!!se,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ve?"custom_layout":W==="buttons"?"buttons_layout":"default_layout",className:ne,directPaypal:Mo(Q),isSubscription:y?.mode==="subscription",session:y,debug:P})})}),Me]})}function ls({sessionId:e,nonce:t,billingApiUrl:n,session:l,children:o}){return(0,S.jsx)(S.Fragment,{children:N.default.Children.map(o,s=>{if(!N.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:N.default.cloneElement(s,c)})})}function cs({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:l,showGooglePay:o,theme:s,buttonsTheme:u,buttonsStyles:c,cardButtonContent:I,cardBackButtonContent:O,cardTitleContent:m}){let[x,w]=(0,N.useState)(!1),F=(0,N.useMemo)(()=>(0,Be.resolveTheme)(s),[s]),d=(0,N.useMemo)(()=>{let P=F?.buttonsLayout??(0,Be.resolveButtonsLayoutTheme)(u);return c?{...P,...c,cardButton:{...P.cardButton,...c.cardButton},cardFormContainer:{...P.cardFormContainer,...c.cardFormContainer},backButton:{...P.backButton,...c.backButton},backButtonIcon:{...P.backButtonIcon,...c.backButtonIcon},submitButton:{...P.submitButton,...c.submitButton},title:{...P.title,...c.title}}:P},[F,u,c]),g=F?.buttonsLayout?.cardButton?.borderRadius??F?.appearance.variables?.borderRadius??8,E=P=>(0,S.jsx)("div",{style:{height:P,borderRadius:g,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),L=I===void 0?{boxSizing:"border-box",height:or,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(x){let P=d.cardInputBorder??"#e5e7eb",W=d.cardInputBackground??"white",Z=Gn(O),me=Gn(m);return(0,S.jsxs)("div",{style:{backgroundColor:d.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...d.cardFormContainer},children:[(0,S.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,S.jsxs)("button",{type:"button",onClick:()=>w(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Z?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...d.backButton},children:[(0,S.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...d.backButtonIcon},children:(0,S.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,S.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,S.jsx)(Xn,{content:O})]}),me?(0,S.jsx)("div",{style:{flex:1}}):(0,S.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...d.title},children:(0,S.jsx)(hr,{content:m})})]}),(0,S.jsx)("div",{style:{backgroundColor:W,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,S.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,S.jsxs)("div",{style:{display:"flex"},children:[(0,S.jsx)("div",{style:{flex:1,backgroundColor:W,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,S.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,S.jsx)("div",{style:{flex:1,backgroundColor:W,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,S.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,S.jsx)("div",{style:{backgroundColor:W,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,S.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,S.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...d.submitButton,opacity:.5}}),(0,S.jsx)("style",{children:`
38
+ `}),gr&&$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)(nr,{content:W})]}),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)(Cr,{content:ce})})]}),!gr&&!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)(Cr,{content:ce})}),G&&(0,i.jsx)("div",{style:{order:Te?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=Ve,v=(U=!1)=>({backgroundColor:Pr,border:`1px solid ${jn(U)}`,borderRadius:yt,marginTop:"0.5rem",padding:"10px"}),K=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ca}),le=(0,w.getStateOptions)(a);return(0,i.jsxs)(i.Fragment,{children:[(0,w.isAVSFieldVisible)(G.address_line_1,a)&&(0,i.jsx)("div",{style:v(At.line1),children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Je,onChange:U=>{Mt.current=U.target.value,Re(U.target.value)},disabled:b,required:!0,"data-testid":"flopay-address-line1",style:K()})}),(0,w.isAVSFieldVisible)(G.address_line_2,a)&&(0,i.jsx)("div",{style:v(),children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Pt,onChange:U=>{Gt.current=U.target.value,He(U.target.value)},disabled:b,"data-testid":"flopay-address-line2",style:K()})}),((0,w.isAVSFieldVisible)(G.city,a)||(0,w.isAVSFieldVisible)(G.state,a))&&(0,i.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,w.isAVSFieldVisible)(G.city,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:Pr,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:yt,borderBottomLeftRadius:yt,...(0,w.isAVSFieldVisible)(G.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:yt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:zt,onChange:U=>{tn.current=U.target.value,Rt(U.target.value)},disabled:b,required:!0,"data-testid":"flopay-city",style:K()})}),(0,w.isAVSFieldVisible)(G.state,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:Pr,border:`1px solid ${jn(At.state)}`,padding:"10px",borderTopRightRadius:yt,borderBottomRightRadius:yt,...(0,w.isAVSFieldVisible)(G.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:yt}},children:le?(0,i.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:yn,onChange:U=>{fn.current=U.target.value,Rn(U.target.value)},disabled:b,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(U=>(0,i.jsx)("option",{value:U.code,children:U.name},U.code))]}):(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,w.getStateLabel)(a),autoComplete:"billing address-level1",value:yn,onChange:U=>{fn.current=U.target.value,Rn(U.target.value)},disabled:b,required:!0,"data-testid":"flopay-state",style:K()})})]}),((0,w.isAVSFieldVisible)(G.country,a)||(0,w.isAVSFieldVisible)(G.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)(G.country,a)&&(0,i.jsx)("div",{style:{flex:de==="row"?1:void 0,backgroundColor:Pr,borderTop:`1px solid ${hr}`,borderRight:`1px solid ${hr}`,borderBottom:`1px solid ${hr}`,borderLeft:`1px solid ${hr}`,padding:"10px",...de==="row"&&(0,w.isAVSFieldVisible)(G.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:yt,borderBottomLeftRadius:yt,borderRight:"none"}:{borderRadius:yt}},children:(0,i.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Ve,onChange:U=>{Ut.current=U.target.value,lt(U.target.value),$e?.(U.target.value),fn.current="",Rn("")},disabled:b,autoComplete:"billing country","data-testid":"flopay-country",style:{...K(),cursor:"pointer"},children:w.COUNTRY_OPTIONS.map(U=>(0,i.jsxs)("option",{value:U.code,children:[U.flag," ",U.name]},U.code))})}),(0,w.isAVSFieldVisible)(G.postal_code,a)&&(0,i.jsx)("div",{style:{flex:de==="row"?1:void 0,backgroundColor:Pr,border:`1px solid ${vi}`,padding:"10px",...de==="row"&&(0,w.isAVSFieldVisible)(G.country,a)?{borderRadius:"0",borderTopRightRadius:yt,borderBottomRightRadius:yt}:{borderRadius:yt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,w.getPostalCodeLabel)(Ve),autoComplete:"billing postal-code",value:it,onChange:U=>{gt.current=U.target.value,nt(U.target.value),Ue?.(U.target.value)},onBlur:()=>Kt(!0),disabled:b,required:It.required,"aria-invalid":Dr||void 0,"aria-describedby":Dr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:K()})})]}),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&&ke&&(0,i.jsx)("div",{style:{order:-2,width:"100%"},children:ke}),Te&&Ri,pe&&(0,i.jsx)(rr,{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=>je?!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=${pr}`,` shouldRenderStripePayPal=${mr}`,` hasPaypalStripeInstance=${!!Fe}`].join(`
39
+ `)}):null,pa=a=>je?!D||!dt?(0,i.jsx)("pre",{"data-testid":a,style:Lr,children:"FloPay/Stripe-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:Lr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${D}`,` currency=${Me}`,` amountInCents=${Ie}`,` enabledPaymentMethods: ${JSON.stringify(g??[])}`,` enabledPaymentMethodsProvided=${dr}`,` hasEnabledMethods=${xr}`,` expressMethods: ${JSON.stringify(Tr)}`,` walletExpressMethods: ${JSON.stringify(Br)}`,` paymentElementMethods: ${JSON.stringify(ur)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Mr)}`,` hasStripeInstance=${!!dt}`,` shouldRenderWallets=${yr}`,` shouldRenderPaymentElement=${fr}`].join(`
40
+ `)}):null,ma=we==="apm-expanding"||we==="apm-form"||we==="apm-collapsing",Nr=we==="apm-expanding"?`flopay-card-enter ${Dt}ms cubic-bezier(0, 0, 0.2, 1) both`:we==="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(oe==="buttons"){let a=we==="buttons"||we==="expanding"||we==="apm-expanding",v=we==="expanding"||we==="card"||we==="collapsing",K=q===void 0?{boxSizing:"border-box",height:Xr,padding:"0 1rem"}:{padding:"0.9rem 1rem"},le=we==="expanding"||we==="apm-expanding"?`flopay-buttons-exit ${Dt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:we==="collapsing"||we==="apm-collapsing"?`flopay-buttons-enter ${Dt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,U=we==="expanding"?`flopay-card-enter ${Dt}ms cubic-bezier(0, 0, 0.2, 1) both`:we==="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,{}),X&&(0,i.jsx)(Sn,{status:X,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"),pr&&tt&&(0,i.jsxs)(i.Fragment,{children:[$&&(0,i.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,i.jsx)(kr,{sessionId:e,nonce:t,billingApiUrl:z,email:J.email,clientId:tt.clientId,environment:tt.environment,currency:Me.toUpperCase(),isSubscription:et,onTokenizedBody:Zt,onComplete:s,onErrorChange:ge,onDecline:c,onTechnicalFailure:Zn,onButtonClick:Se,runBeforeButtonClick:an,isProcessing:b,onLoadStateChange:yo,onInitializationStateChange:fo,session:p??null,existingOrderId:$?.orderId,debug:je},$?.orderId??"fresh")]}),mr&&(0,i.jsx)(pt.Elements,{stripe:Fe,options:Lt,children:(0,i.jsx)(Oa,{sessionId:e,nonce:t,email:J.email,billingApiUrl:z,onTokenizedBody:Zt,onErrorChange:ge,isProcessing:b,onButtonClick:Se,onDecline:c,onTechnicalFailure:Zn,runBeforeButtonClick:an,onLoadStateChange:Ko,placeholderBorderRadius:Kn})}),yr?(0,i.jsx)(pt.Elements,{stripe:dt,options:Wt,children:(0,i.jsx)(za,{sessionId:e,nonce:t,email:J.email,billingApiUrl:z,intentKind:ye>0?"payment":"setup",expressMethods:Br,onTokenizedBody:Zt,onErrorChange:ge,onButtonClick:Se,onDecline:c,onTechnicalFailure:Zn,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,fr&&(0,i.jsx)(Ua,{sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:z,paymentElementMethods:Mr,stripeInstance:dt,paymentElementBaseOptions:mo,onTokenizedBody:Zt,onErrorChange:ge,onButtonClick:Se,onDecline:c,runBeforeButtonClick:an,onLoadStateChange:Yo,isProcessing:b,submitButtonColor:Vn,submitButtonBorderRadius:yt,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()=>{b||!(await an("card")).proceed||(Se?.("card"),Xn())},disabled:b,style:{width:"100%",...K,...x.cardButton,...Ao({themeBundle:ve,resolvedPrimaryColor:Vn,resolvedBorderRadius:yt,submitButtonStyle:x.submitButton,explicitPrimaryColor:jt?.colorPrimary}),fontSize:x.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:b?"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:b?.6:1},onMouseEnter:ae=>{!b&&(ve||jt?.colorPrimary)&&(ae.currentTarget.style.backgroundColor=wi)},onMouseLeave:ae=>{(ve||jt?.colorPrimary)&&(ae.currentTarget.style.backgroundColor=Vn)},onMouseDown:ae=>{ae.currentTarget.style.transform="scale(0.985)"},onMouseUp:ae=>{ae.currentTarget.style.transform="scale(1)"},children:(0,i.jsx)(tr,{content:q})}),pe&&we==="buttons"&&(0,i.jsx)(rr,{margin:"0.25rem 0",styleOverride:x.errorBanner,children:pe})]}),Te&&v&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...U?{animation:U}:{},...we==="collapsing"?{pointerEvents:"none"}:{}},children:da}),D&&ma&&ct&&Or&&dt&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...Nr?{animation:Nr}:{},...we==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:bo,borderRadius:wo,...br,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)(nr,{content:W})]}),(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)(pt.Elements,{stripe:dt,options:Or,children:(0,i.jsx)(Bo,{method:ct,sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:z,onTokenizedBody:Zt,onErrorChange:ge,onDecline:c,onCancel:j,runBeforeButtonClick:an,onButtonClick:Se,isProcessing:b,submitButtonColor:Vn,submitButtonBorderRadius:yt,submitButtonStyle:x.submitButton,errorText:pe})},ct)]})})]})]})}return ma&&ct&&Or&&dt&&D?(0,i.jsxs)("form",{onSubmit:go,className:S,style:{position:"relative"},children:[(0,i.jsx)(To,{}),X&&(0,i.jsx)(Sn,{status:X,errorMessage:pe}),(0,i.jsx)("div",{style:{...Nr?{animation:Nr}:{},...we==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:bo,borderRadius:wo,...br,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)(nr,{content:W})]}),(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)(pt.Elements,{stripe:dt,options:Or,children:(0,i.jsx)(Bo,{method:ct,sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:z,onTokenizedBody:Zt,onErrorChange:ge,onDecline:c,onCancel:j,runBeforeButtonClick:an,onButtonClick:Se,isProcessing:b,submitButtonColor:Vn,submitButtonBorderRadius:yt,submitButtonStyle:x.submitButton,errorText:pe})},ct)]})})]}):(0,i.jsxs)("form",{onSubmit:go,className:S,style:{position:"relative"},children:[(0,i.jsx)(To,{}),X&&(0,i.jsx)(Sn,{status:X,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"),pr&&tt&&(0,i.jsxs)(i.Fragment,{children:[$&&(0,i.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,i.jsx)(kr,{sessionId:e,nonce:t,billingApiUrl:z,email:J.email,clientId:tt.clientId,environment:tt.environment,currency:Me.toUpperCase(),isSubscription:et,onTokenizedBody:Zt,onComplete:s,onErrorChange:ge,onDecline:c,onTechnicalFailure:Zn,onButtonClick:Se,runBeforeButtonClick:an,isProcessing:b,onLoadStateChange:yo,onInitializationStateChange:fo,session:p??null,existingOrderId:$?.orderId,debug:je},$?.orderId??"fresh")]}),mr&&(0,i.jsx)(pt.Elements,{stripe:Fe,options:Lt,children:(0,i.jsx)(Oa,{sessionId:e,nonce:t,email:J.email,billingApiUrl:z,onTokenizedBody:Zt,onErrorChange:ge,isProcessing:b,onButtonClick:Se,onDecline:c,onTechnicalFailure:Zn,runBeforeButtonClick:an,onLoadStateChange:Ko,placeholderBorderRadius:Kn})}),yr&&(0,i.jsx)(pt.Elements,{stripe:dt,options:Wt,children:(0,i.jsx)(za,{sessionId:e,nonce:t,email:J.email,billingApiUrl:z,intentKind:ye>0?"payment":"setup",expressMethods:Br,onTokenizedBody:Zt,onErrorChange:ge,onButtonClick:Se,onDecline:c,onTechnicalFailure:Zn,runBeforeButtonClick:an,onLoadStateChange:Ho,placeholderBorderRadius:Kn})}),fr&&(0,i.jsx)(Ua,{sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:z,paymentElementMethods:Mr,stripeInstance:dt,paymentElementBaseOptions:mo,onTokenizedBody:Zt,onErrorChange:ge,onButtonClick:Se,onDecline:c,runBeforeButtonClick:an,onLoadStateChange:Yo,isProcessing:b,submitButtonColor:Vn,submitButtonBorderRadius:yt,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 sr=require("@flopay/js"),Qe=require("@flopay/shared");var Ir="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 m=new AbortController,E=()=>m.abort();e.signal?.aborted?m.abort():e.signal?.addEventListener("abort",E);let S=window.setTimeout(()=>m.abort(),l);try{let B=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:m.signal});if(!B.ok)return{status:"unknown"};let d=await B.json().catch(()=>null);return 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 m=await new Promise((E,S)=>{let B=!1,d=0,f=0,R=0,D=!1,g=()=>{window.clearTimeout(d),window.clearInterval(f),window.clearTimeout(R),window.removeEventListener("message",oe),k.removeEventListener("load",Z),e.signal?.removeEventListener("abort",he)},V=async()=>{if(!(B||D)){D=!0;try{let O=await s();if(B||!is(O))return;B=!0,g(),E(O)}finally{D=!1}}},Z=()=>{window.clearTimeout(R),R=window.setTimeout(()=>{V()},250)},he=()=>{B||(B=!0,g(),S(new Qe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},oe=O=>{if(O.source!==k.contentWindow||N&&O.origin!==N)return;let ee=O.data;!ee||typeof ee!="object"||ee.source!=="flopay-vault-3ds-return"||B||(B=!0,g(),E(null))};d=window.setTimeout(()=>{B||(B=!0,g(),S(new Qe.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),f=window.setInterval(()=>{V()},n),k.addEventListener("load",Z),window.addEventListener("message",oe),e.signal?.addEventListener("abort",he),e.signal?.aborted&&he()});return m||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 m of N)if(typeof m=="string"&&m.length>0&&(!t?.requirePaymentIntentClientSecret||eo(m)))return m}}}}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 sr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(eo(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function lr({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,m=n.customer?.id??n.accountData?.userId??"",E=n.customer?.email??n.accountData?.email??"",S=n.customer?.firstName??n.accountData?.firstName??"",B=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 sr.PaymentAPI(c,u===!1?{telemetry:!1}:void 0),D=await ls(()=>R.processPayment(m,{sessionId:k,nonce:N,tokenizedData:o,accountData:{userId:m,email:E,firstName:S,lastName:B,country:d,zip:f},returnUrl:s??Fo(n)}));if(D.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Hr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let g=await D.json().catch(()=>null);if(g?.type==="paypal_redirect_required"||g?.type==="3ds_required"){let V=Ya(g);if(!V)throw new Qe.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:g.type,threeDSecureToken:V,paymentMethodId:g.paymentMethodId}}if(g?.gatewayErrorCode==="authentication_required"){let V=await cs({billingApiUrl:c,sessionId:k,nonce:N,responseJson:g});if(V)return V;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 m=(0,Qe.isSetupIntentClientSecret)(e.threeDSecureToken),E=null,S=e.paymentMethodId,B=await os(N,e.threeDSecureToken,m);if(B){if(B.error)throw kn(new Qe.FloPayError(B.error.message??`Failed to retrieve 3DS ${m?"setup":"payment"} status.`,"api_error",{code:B.error.code}),"card");let f=B.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},m):null;if(d){if(d.error)throw kn(new Qe.FloPayError(d.error.message??"3DS authentication failed.","api_error",{code:d.error.code}),"card");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=(m?f.setupIntent:f.paymentIntent)??null}if(E&&(E.status==="requires_capture"||E.status==="succeeded"||E.status==="processing")){let f=await lr({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 m=(n??t)?.getRawProvider();if(!m)throw kn(new Qe.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:S}=await m.handleNextAction({clientSecret:e.threeDSecureToken});if(S)throw kn(new Qe.FloPayError(S.message??"PayPal authorization failed.","api_error",{code:S.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:E}=await m.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,sr.loadFloPay)(e,{billingApiUrl:n,locale:l,telemetry:o}),s?(0,sr.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"),cr=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 Er(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:m,onDecline:E,onCountryChange:S,onZipChange:B,showPayPal:d=!0,showStripe:f=!0,showApplePay:R=!0,showGooglePay:D=!0,debug:g=!1,layout:V,theme:Z,buttonsTheme:he,buttonsStyles:oe,cardButtonContent:O,cardBackButtonContent:ee,cardTitleContent:H,showSecurityFooter:Pe,onButtonClick:q,onBeforeButtonClick:W,enableAVS:ce,cardFieldOrder:Ne,cardPreFormSlot:Se,avsLayout:Ce,className:te,initialErrorMessage:be=null,children:ke,checkoutMode:de,confirmLabel:ze,renderConfirmButton:Be,onSessionCompleted:Ee}){let I=(0,xe.resolveBillingApiUrl)(l),ie=(0,L.useMemo)(()=>(0,xe.resolveTheme)(Z),[Z]),me=s??ie?.appearance,$e=n?"embedded_checkout":"standard_checkout",Ue=ke?"custom_layout":V==="buttons"?"buttons_layout":"default_layout",[Q,A]=(0,L.useState)(null),[Y,ye]=(0,L.useState)(null),Me=(0,L.useRef)(null),[st,tt]=(0,L.useState)(null),et=(0,L.useRef)(null),[p,je]=(0,L.useState)(null),[qe,Ge]=(0,L.useState)(e??""),Ke=e??qe,Yt=n?"":Ke,[ht,kt]=(0,L.useState)(!0),[h,_e]=(0,L.useState)(null),[Ve,lt]=(0,L.useState)("full"),[it,nt]=(0,L.useState)(!1),[Je,Re]=(0,L.useState)(be),[Pt,He]=(0,L.useState)(null),[zt,Rt]=(0,L.useState)(null),[yn,Rn]=(0,L.useState)(void 0),[In,zn]=(0,L.useState)(""),[gt,Ut]=(0,L.useState)(!1),[Mt,Gt]=(0,L.useState)("loading"),[tn,fn]=(0,L.useState)(0),G=(0,L.useRef)(!1),Fn=(0,L.useRef)(!1),gn=(0,L.useRef)(!1),$t=(0,L.useRef)(null),Bt=(0,L.useMemo)(()=>({checkoutMode:de??Ve,layout:ke?"unknown":V==="buttons"?"buttons":"embedded"}),[de,ke,Ve,V]),M=(0,L.useRef)(N);M.current=N;let Xe=(0,L.useRef)(m);Xe.current=m;let Te=(0,L.useRef)(E);Te.current=E,(0,L.useEffect)(()=>{Tt(Y)?.setCheckoutContext(Bt),st&&st!==Y&&Tt(st)?.setCheckoutContext(Bt)},[Y,st,Bt]);let Dn=(0,L.useRef)(Ee);Dn.current=Ee;let We=(0,L.useCallback)(_=>{Gt(_),!(_!=="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,L.useCallback)(()=>{Gt("retrying"),fn(_=>_+1)},[]);(0,L.useEffect)(()=>{Gt("loading"),fn(0),gn.current=!1},[Ke]),(0,L.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:xe.SDK_VERSION,checkout_type:$e,checkout_layout:Ue,billing_api_url:I})},[Ue,$e,I]);let hn=(0,L.useMemo)(()=>n?En(n,!0):"",[n]),Pn=(0,L.useMemo)(()=>In===hn?yn:void 0,[yn,In,hn]),rt=(0,L.useMemo)(()=>n?Ro(n,Pn):void 0,[n,Pn]),It=de??rt?.checkoutMode??"full",qt=(0,L.useMemo)(()=>rt?{...rt,checkoutMode:It}:void 0,[rt,It]);(0,L.useEffect)(()=>{Rn(void 0),zn(hn)},[hn]),(0,L.useEffect)(()=>{Re(be)},[be]);let At=(0,L.useCallback)((_,j,X)=>{ut(()=>{Te.current?.(wt(_,j,X))})},[ut]),Jt=(0,L.useCallback)(async(_,j)=>{Re(null),Rt(null),He("processing");let X=j?.sessionId??_.id,re=Me.current??et.current,ue=Tt(re),$=re?null:ao(I,o,Bt),P={log:b=>{ue?ue.log(b):$?.log(b)},error:b=>{ue?ue.error(b):$?.error(b)},terminal:b=>{ue?ue.terminal(b):$?.terminal(b)},performance:b=>{ue?ue.performance(b):$?.performance(b)},now:()=>ue?.now()??$?.now()??0,elapsed:b=>ue?.elapsed(b)??Math.max(0,($?.now()??b)-b)},ne=P.now(),z=!!(j?.initialAutoProcessingError||j?.initialAutoProcessingPending),pe=!1,ve,x=()=>{pe||(pe=!0,z=!0,ve=P.now(),P.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},vt=!1,F=()=>{vt||(vt=!0,P.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),P.performance({stage:"processing",durationMs:P.elapsed(ne),durationMode:"machine",paymentMethodCategory:"saved"}),ve!==void 0&&P.performance({stage:"recovery",durationMs:P.elapsed(ve),durationMode:"machine",paymentMethodCategory:"saved"}))};P.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),P.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),z&&x();let y;try{let b=Ha(j?.initialAutoProcessingError),fe;if(b)x(),b.type==="paypal_redirect_required"&&$t.current?.publishableKey&&Ja({sessionId:X,publishableKey:$t.current.publishableKey,paypalPublishableKey:$t.current.paypalPublishableKey}),fe=await to(b,{flopay:Me.current,paypalFlopay:et.current,attempt3DS:j?.attempt3DS,billingApiUrl:I,sessionId:X,session:_,telemetry:!1}),b.type==="paypal_redirect_required"&&No();else if(j?.initialAutoProcessingPending){let Ye=await new _r.PaymentAPI(I,{telemetry:!1}).waitForCheckoutSessionCompletion(j.initialAutoProcessingPending.sessionId,{initialDelayMs:j.initialAutoProcessingPending.retryAfterMs});if(Ye.data.session?.status!=="complete")throw new xe.FloPayError("Automatic payment failed. Please try again.","api_error",{code:Ye.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});fe={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 J=await lr({billingApiUrl:I,sessionId:X,session:_,telemetry:!1});J.type==="success"?fe=J.result:(x(),J.type==="paypal_redirect_required"&&$t.current?.publishableKey&&Ja({sessionId:X,publishableKey:$t.current.publishableKey,paypalPublishableKey:$t.current.paypalPublishableKey}),fe=await to(J,{flopay:Me.current,paypalFlopay:et.current,attempt3DS:j?.attempt3DS,billingApiUrl:I,sessionId:X,session:_,telemetry:!1}),J.type==="paypal_redirect_required"&&No())}}X&&ar(X),F(),z&&(P.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),P.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),He("success"),await Er(Tn),y=()=>M.current?.(fe)}catch(b){let fe=Gn(b),J=fe.checkoutMethod??Ir;return Re(fe.message),Rt(fe.message),j?.fallbackToFull&&(P.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),lt("full"),Xa("full")),F(),!!(fe.declineCode||fe.code?.toLowerCase().includes("declin"))?P.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):fe.type==="validation_error"?P.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):P.error({errorCode:z?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:z?"recovery":"processing",paymentMethodCategory:"saved"}),ut(()=>Xe.current?.(fe)),At(J,fe,{code:fe.code,declineCode:fe.declineCode}),He("error"),await Promise.allSettled([Er(Cn),j?.ensureProvidersReady?j.ensureProvidersReady():Promise.resolve()]),z&&(P.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{F(),$&&io($),He(null),Rt(null)}return ut(y),!0},[At,ut,Gn,I,o,Bt]);(0,L.useEffect)(()=>{if(typeof window>"u"||Fn.current)return;let _=new URLSearchParams(window.location.search),j=_.get("payment_intent_client_secret");if(!j)return;let X=ps();X&&(Fn.current=!0,(async()=>{let re,ue=0;Re(null),Rt(null),He("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:$,paypalFlopay:P}=await ro({publishableKey:X.publishableKey,paypalPublishableKey:X.paypalPublishableKey,billingApiUrl:I,locale:u,telemetry:o});re=Tt(P??$),ue=re?.now()??0,re?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),re?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let ne=(P??$)?.getRawProvider();if(!ne)throw Object.assign(new xe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:z,error:pe}=await ne.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 ve=Ra(z?.status);if(!z||ve==="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,vt=ve;if(X.sessionId){let b=(await new _r.PaymentAPI(I,{telemetry:!1}).getUnifiedCheckoutSession(X.sessionId)).data.session;if(b&&b.status!=="complete"){let fe=await lr({billingApiUrl:I,sessionId:X.sessionId,session:b,telemetry:!1,tokenizedData:{id:x??z.id,type:"card",threeDSecureActionResultTokenId:z.id,isPaypal:!0}});if(fe.type!=="success")throw Object.assign(new xe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});vt=fe.result.status}}X.sessionId&&ar(X.sessionId),re?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),re?.performance({stage:"redirect_resume",durationMs:re.elapsed(ue),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),re?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),He("success"),await Er(Tn),ut(()=>M.current?.({status:vt,paymentIntentId:z.id,paymentMethodId:x,checkoutMethod:"paypal"}))}catch($){let P=Gn($),ne=P.checkoutMethod??"paypal",z=!!(P.declineCode||P.code?.toLowerCase().includes("declin"));if(re)re.performance({stage:"redirect_resume",durationMs:re.elapsed(ue),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),z?re.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):re.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(z){let pe=ao(I,o,Bt);pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),io(pe)}else Do(I,o,Bt,"REDIRECT_RESUME_FAILED","redirect_resume");Re(P.message),Rt(P.message),ut(()=>Xe.current?.(P)),At(ne,P,{code:P.code,declineCode:P.declineCode}),He("error"),await Er(Cn)}finally{No(),Ps(),He(null),Rt(null),nt(!1)}})())},[At,ut,u,Gn,I,o]);let nn=(0,L.useRef)(null);function En(_,j=!1){let X=_?.account?.email?.trim().toLowerCase()??"",re={c:_?.clientId,cur:_?.currency??"",a:{e:X,u:X?"":_?.account?.userId??"",country:_?.account?.country??""},successUrl:_?.successUrl,cancelUrl:_?.cancelUrl,p:_?.products?.map(P=>Oo(`${P.type??""}:${P.code??P.providerItemId??P.providerPlanId??""}`,P)).sort(),i:_?.items?.map(P=>Oo(P.code??P.providerItemId??"",P)).sort(),s:_?.subscriptions?.map(P=>Oo(P.code??P.providerPlanId??"",P)).sort(),couponCodes:_?.couponCodes?[..._.couponCodes].sort():void 0,...j?{tagsData:_?.tagsData,utmMetadata:_?.utmMetadata,tokenizedData:_?.tokenizedData,checkoutMode:_?.checkoutMode??"full"}:{}},ue=JSON.stringify(re),$=0;for(let P=0;P<ue.length;P++)$=($<<5)-$+ue.charCodeAt(P)|0;return`flopay_session_${Math.abs($).toString(36)}`}let Kt=(0,L.useMemo)(()=>qt?En(qt):"",[qt]),Ft=(0,L.useRef)(qt);Ft.current=qt,(0,L.useEffect)(()=>{Ge(e??"")},[e]),(0,L.useEffect)(()=>{G.current=!1,Re(be),Rt(null),He(null)},[Kt,be,e]);async function Xt(_,j){let X=ao(I,o,Bt),re=new _r.PaymentAPI(I,{telemetry:!1});try{let ue=_.idempotencyKey!==void 0?(0,xe.resolveIdempotencyKey)(_.idempotencyKey):void 0,$=ue??fs(j),P,ne=!1,z=ms(j);X.log({name:z?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let pe=z?.sid??null,ve=null;if(pe)try{if(ve=await re.getUnifiedCheckoutSession(pe,z?.nonce),ve.data.session?.status==="complete"){if(Eo(pe))return{sid:pe,result:ve};hs(j),pe=null,ve=null,ne=!0}}catch{X.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Za(j),pe=null}if(!pe){!ue&&(ne||!$)&&($=(0,xe.resolveIdempotencyKey)(),P=$),$&&gs(j,$);let x=X.now();X.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let vt={..._,idempotencyKey:$,avsCheck:!!ce,avsConfig:typeof ce=="object"?ce:void 0,checkoutType:"embedded_checkout",checkoutLayout:ke?"custom_layout":V==="buttons"?"buttons_layout":"default_layout"};try{ve=await re.createAndFetchSession(vt),X.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),X.performance({stage:"session_create",durationMs:X.now()-x,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"})}catch(F){let y=(0,xe.classifyTelemetryFailure)(F,"CHECKOUT_SESSION_CREATE_FAILED","unknown");throw X.performance({stage:"session_create",durationMs:X.now()-x,durationMode:"machine",requestCategory:"session_create",statusClass:y.statusClass}),F instanceof xe.FloPayError&&F.type==="validation_error"?X.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):y.statusClass==="4xx"?X.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):X.error({...y,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),F}pe=ve.data.session?.id??"",pe&&ys(j,pe,ve.data.session?.clientSecret)}return{sid:pe??"",result:ve,sdkGeneratedIdempotencyKey:P}}finally{io(X)}}let we=(0,L.useCallback)(async(_,j)=>{let X=Ft.current;if(!X)throw new xe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let re=Ro(X,_),ue=En(re),$=so.get(ue);if(!$){let z={promise:Xt(re,ue),consumers:0,settled:!1};$=z,so.set(ue,z);let pe=()=>{z.settled=!0,Ga(ue,z)};z.promise.then(pe,pe)}$.consumers+=1;let P=!1,ne=()=>{P||(P=!0,$.consumers-=1,Ga(ue,$))};j?.(ne);try{let z=await $.promise;nn.current=ue,_&&(zn(hn),Rn(b=>wa(b,_)));let{sid:pe,result:ve}=z;A(ve),ve.data.session&&je(ve.data.session),pe&&Ge(pe);let{publishableKey:x,paypalPublishableKey:vt}=no(ve),{flopay:F,paypalFlopay:y}=await ro({publishableKey:x,paypalPublishableKey:vt,billingApiUrl:I,locale:u,telemetry:o});return Me.current=F,ye(F),et.current=y,tt(y),kt(!1),z}catch(z){throw nn.current===ue&&(nn.current=null),z}finally{j||ne()}},[u,I,o,Bt]),mt=(0,L.useCallback)(async _=>{if(!bs(_)||gt)return{sessionId:qe,session:p};Ut(!0);try{let j=await we(_);return{sessionId:j.sid,session:j.result.data.session??null}}finally{Ut(!1)}},[we,gt,qe,p]);(0,L.useEffect)(()=>{let _=!1,j;if(_e(null),Kt){let ue=Ft.current;return lt(It),kt(!1),nn.current===Kt?()=>{_=!0}:(je(ka(ue,de)),(async()=>{let $=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),P=It==="auto"&&!G.current&&!$;P&&(Re(null),Rt(null),He("processing"));try{let ne=await we(void 0,x=>{j=x}),z=ne.result.data.session??null;$t.current=no(ne.result);let pe=Lo(ne.result),ve=Eo(ne.sid||z?.id);if(!_&&P&&z&&!pe&&!ve){G.current=!0,await ds(Kt,ne.sdkGeneratedIdempotencyKey,()=>Jt(z,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:ne.result.autoProcessingError,initialAutoProcessingPending:ne.result.autoProcessingPending,autoProcessingAttempted:ne.result.autoProcessingAttempted,sessionId:ne.sid||z.id}));return}!_&&P&&((pe||ve)&&(G.current=!0),He(null),Rt(null))}catch(ne){if(_)return;let z=ne instanceof xe.FloPayError||typeof ne=="object"&&ne!==null&&"code"in ne?ne.code:void 0;if(P&&z==="session_auto_completed"){G.current=!0,He("success"),await Er(Tn),_||(ut(()=>{M.current?.({status:"succeeded"})}),He(null),Rt(null));return}P&&(He(null),Rt(null));let pe=ne instanceof xe.FloPayError?ne:new xe.FloPayError(ne instanceof Error?ne.message:"Failed to create session","api_error");_e(pe)}finally{j?.(),j=void 0}})(),()=>{_=!0,j?.()})}kt(!0);async function X(){let ue=!1;try{let P=await new _r.PaymentAPI(I,{telemetry:!1}).getUnifiedCheckoutSession(Ke,t);if(_)return;A(P);let ne=P.data.session??null;if(je(ne),!ne)throw new xe.FloPayError("No session data returned","api_error");if(ne.status==="complete"){kt(!1),ut(()=>{Dn.current?.(ne.successUrl??"")});return}if(ne.status==="expired")throw new xe.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});ue=!0;let z=de??ne.checkoutMode??"full";lt(z);let pe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ve=Lo(P);if(z==="auto"&&!G.current&&!pe&&!ve){G.current=!0;let x=re(P);try{if(await Jt(ne,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>x,sessionId:Ke||ne.id}),_)return;await x,_||kt(!1);return}catch{if(_)return;await x,_||kt(!1);return}}await re(P),_||kt(!1)}catch($){if(_)return;$ instanceof xe.FloPayError?!ue&&!us($)&&Do(I,o,Bt,"NETWORK_REQUEST_FAILED","session_read"):Do(I,o,Bt,"INTERNAL_SDK_ERROR","checkout_mount");let P=$ instanceof xe.FloPayError?$:new xe.FloPayError($ instanceof Error?$.message:"Failed to initialize checkout","api_error");_e(P),kt(!1)}}async function re(ue){let{publishableKey:$,paypalPublishableKey:P}=no(ue);$t.current={publishableKey:$,paypalPublishableKey:P};let{flopay:ne,paypalFlopay:z}=await ro({publishableKey:$,paypalPublishableKey:P,billingApiUrl:I,locale:u,telemetry:o});Me.current=ne,ye(ne),et.current=z,tt(z)}return X(),()=>{_=!0}},[we,de,Kt,It,Yt,ut,t,Jt]);let ct=(0,L.useCallback)(async()=>{if(!(it||!p)){nt(!0),Re(null);try{await Jt(p,{fallbackToFull:!0,sessionId:Ke||p.id})}finally{nt(!1)}}},[Ke,it,Jt,p]),bn=zo(Q),$n=Lo(Q),Dt=(0,L.useMemo)(()=>{if(!Q||!p||!Q.data.stripe?.publishableKey)return;let _={appearance:me,paymentMethodCreation:"manual",billingApiUrl:I};if(Q.data.stripe?.clientSecret)_.clientSecret=Q.data.stripe.clientSecret;else{let j=(0,xe.buildCheckoutDisplayData)(p).total;_.amount=Math.round(j*100)||p.amount,_.currency=p.currency?.toLowerCase()}return _},[Q,p,me,I]),Vt=!!(n&&!ke&&V==="buttons"&&W&&It==="full"),bt=(0,L.useMemo)(()=>({session:p,loading:ht,error:h,checkoutMode:Ve,inlineSessionDraft:qt,applyInlineSessionPatch:Vt?mt:void 0,inlineSessionPatchProcessing:gt}),[p,ht,h,Ve,qt,Vt,mt,gt]),Xn=!!n&&V==="buttons"&&!$n&&(!Y||!Dt),Ht=Pt?(0,C.jsx)(Sn,{status:Pt,errorMessage:zt}):null;if(ht){if(c)return(0,C.jsxs)(C.Fragment,{children:[c,Ht]});if(V==="buttons"){let _=ie?.buttonsLayout?.cardButton?.borderRadius??ie?.appearance.variables?.borderRadius??8,j=X=>(0,C.jsx)("div",{style:{height:X,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(cr),f&&(R||D)&&j(cr),f&&j(cr),(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:bt,children:k(h)}):(0,C.jsx)(sn.Provider,{value:bt,children:(0,C.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:h.message})}):Xn?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(sn.Provider,{value:bt,children:(0,C.jsx)(Cs,{onButtonClick:q,showPayPal:d,showStripe:f,showApplePay:R,showGooglePay:D,theme:Z,buttonsTheme:he,buttonsStyles:oe,cardButtonContent:O,cardBackButtonContent:ee,cardTitleContent:H})}),Ht]}):$n&&p&&bn?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(sn.Provider,{value:bt,children:(0,C.jsxs)("div",{className:te,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Je&&(0,C.jsx)(rr,{icon:!1,children:Je}),Mt==="retrying"&&(0,C.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Mt==="exhausted"&&(0,C.jsxs)("div",{role:"alert",children:[(0,C.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,C.jsx)("button",{type:"button",onClick:Un,children:"Retry PayPal"})]}),Mt!=="exhausted"&&(0,C.jsx)("div",{"aria-hidden":Mt==="retrying"?!0:void 0,style:Mt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,C.jsx)(Ma,{sessionId:Ke,nonce:p.clientSecret||void 0,billingApiUrl:I,email:p.customer?.email,clientId:bn.clientId,environment:bn.environment,currency:(p.currency??"usd").toUpperCase(),isSubscription:p.mode==="subscription",onComplete:N,onErrorChange:Re,onDecline:E,onButtonClick:q,onInitializationStateChange:We,allowAutomaticRetry:tn===0,session:p,telemetry:o,telemetryContext:Bt,debug:g},`paypal-init-${tn}`)})]})}),Ht]}):!Y||!Dt?(0,C.jsx)(C.Fragment,{children:Ht}):Ve==="confirm"?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(sn.Provider,{value:bt,children:(0,C.jsx)(vr,{flopay:Y,paypalFlopay:st,options:Dt,children:(0,C.jsxs)("div",{className:te,children:[Je&&(0,C.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Je}),Be?Be({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...":ze??"Confirm Purchase"})]})})}),Ht]}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(sn.Provider,{value:bt,children:(0,C.jsx)(vr,{flopay:Y,paypalFlopay:st,options:Dt,children:ke?(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:Ke,nonce:p?.clientSecret||void 0,billingApiUrl:I,session:p,children:ke})]}):(0,C.jsx)(Qr,{sessionId:Ke,nonce:p?.clientSecret||void 0,email:p?.customer?.email,userId:p?.customer?.id,firstName:p?.customer?.firstName,lastName:p?.customer?.lastName,totalAmount:p?Math.round((0,xe.buildCheckoutDisplayData)(p).total*100):0,currency:p?.currency?.toLowerCase()??"usd",onComplete:N,onError:m,onDecline:E,error:Je,onErrorChange:Re,showPayPal:d,showStripe:f,enabledPaymentMethods:Q?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Q?.data.stripe?.enabledPaymentMethodCountries,showApplePay:R,showGooglePay:D,layout:V,theme:Z,buttonsTheme:he,buttonsStyles:oe,appearance:me,cardButtonContent:O,cardBackButtonContent:ee,cardTitleContent:H,onButtonClick:q,onBeforeButtonClick:W,enableAVS:ce,...Ne?{cardFieldOrder:Ne}:{},...Se?{cardPreFormSlot:Se}:{},avsLayout:Ce,country:p?.customer?.country,city:p?.customer?.city,state:p?.customer?.state,onCountryChange:S,onZipChange:B,avsCheck:!!ce,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ke?"custom_layout":V==="buttons"?"buttons_layout":"default_layout",className:te,directPaypal:zo(Q),isSubscription:p?.mode==="subscription",session:p,debug:g})})}),Ht]})}function vs({sessionId:e,nonce:t,billingApiUrl:n,session:l,children:o}){return(0,C.jsx)(C.Fragment,{children:L.default.Children.map(o,s=>{if(!L.default.isValidElement(s))return s;let u=s.props,c={};return u.sessionId||(c.sessionId=e),!u.nonce&&t&&(c.nonce=t),u.billingApiUrl||(c.billingApiUrl=n),l?.customer&&(u.email||(c.email=l.customer.email),u.userId||(c.userId=l.customer.id),u.firstName||(c.firstName=l.customer.firstName),u.lastName||(c.lastName=l.customer.lastName)),Object.keys(c).length===0?s:L.default.cloneElement(s,c)})})}function Cs({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:l,showGooglePay:o,theme:s,buttonsTheme:u,buttonsStyles:c,cardButtonContent:k,cardBackButtonContent:N,cardTitleContent:m}){let[E,S]=(0,L.useState)(!1),B=(0,L.useMemo)(()=>(0,xe.resolveTheme)(s),[s]),d=(0,L.useMemo)(()=>{let g=B?.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},[B,u,c]),f=B?.buttonsLayout?.cardButton?.borderRadius??B?.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"}}),D=k===void 0?{boxSizing:"border-box",height:cr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(E){let g=d.cardInputBorder??"#e5e7eb",V=d.cardInputBackground??"white",Z=er(N),he=er(m);return(0,C.jsxs)("div",{style:{backgroundColor:d.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...d.cardFormContainer},children:[(0,C.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,C.jsxs)("button",{type:"button",onClick:()=>S(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Z?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)(nr,{content:N})]}),he?(0,C.jsx)("div",{style:{flex:1}}):(0,C.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...d.title},children:(0,C.jsx)(Cr,{content:m})})]}),(0,C.jsx)("div",{style:{backgroundColor:V,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:V,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:V,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:V,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:`
41
41
  @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
42
42
  @keyframes flopay-interim-expand {
43
43
  0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
44
44
  40% { opacity: 1; }
45
45
  100% { opacity: 1; max-height: 600px; transform: translateY(0); }
46
46
  }
47
- `})]})}return(0,S.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&E(or),n&&(l||o)&&E(or),n&&(0,S.jsx)("button",{type:"button",onClick:()=>{e?.("card"),w(!0)},style:{width:"100%",...L,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:d.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...d.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:(0,S.jsx)(Jn,{content:I})}),(0,S.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Wn=require("react");var Ya=require("react/jsx-runtime");function Ha(e,t){function n({className:l,id:o,style:s,options:u,onChange:c,onReady:I,onFocus:O,onBlur:m,onEscape:x}){let w=(0,Wn.useRef)(null),F=(0,Wn.useRef)(null),{elements:d,reportInteractive:g}=(0,Wn.useContext)(_n);return(0,Wn.useEffect)(()=>{if(!d||!w.current)return;let E=!0;return(async()=>{let L=d.getElement(e);L||(L=await d.create(e,u)),!(!E||!w.current)&&(L.mount(w.current),F.current=L,c&&L.on("change",c),L.on("ready",()=>{g?.(),I?.()}),O&&L.on("focus",O),m&&L.on("blur",m),x&&L.on("escape",x))})(),()=>{if(E=!1,F.current){try{F.current.unmount()}catch{}F.current=null}}},[d,g]),(0,Ya.jsx)("div",{ref:w,className:l,id:o,style:s})}return n.displayName=t,n}var Ka=Ha("payment","PaymentElement"),Wa=Ha("address","AddressElement");var Ga=require("@flopay/js"),Ja=require("@flopay/shared"),pn=require("react");var un=require("react/jsx-runtime");function Xa({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,firstName:s,lastName:u,chv:c,onTokenizedBody:I,onComplete:O,onErrorChange:m,isProcessing:x=!1}){let w=ln(),F=zr(),d=Ur(),[g,E]=(0,pn.useState)(!1),[L,P]=(0,pn.useState)(!1),W=(0,pn.useRef)(!1),Z=(n||d).replace(/\/+$/,""),me=(0,pn.useCallback)(async te=>{try{let ye=await new Ga.PaymentAPI(Z).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:te,accountData:{userId:o??"",email:l??"",firstName:s??"",lastName:u??""},chv:c});if(ye.ok){O?.();return}let V=await ye.json().catch(()=>null);m?.(V?.message??"Payment failed. Please try again.")}catch(Y){m?.(Y instanceof Error?Y.message:"An unexpected error occurred")}},[Z,e,t,o,l,s,u,c,O,m]),re=(0,pn.useCallback)(te=>{I?I(te):me(te)},[I,me]);(0,pn.useEffect)(()=>{if(!w||W.current)return;let te=new URLSearchParams(window.location.search),Y=te.get("payment_intent"),ye=te.get("payment_intent_client_secret"),V=te.get("redirect_status");!Y||!ye||(W.current=!0,(async()=>{try{if(P(!0),V==="failed"){m?.("PayPal payment was declined. Please try again.");return}let G=w.getRawProvider();if(!G?.retrievePaymentIntent){m?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:se,error:Fe}=await G.retrievePaymentIntent(ye);if(Fe){m?.(Fe.message??"Failed to retrieve PayPal payment status.");return}if(se&&(se.status==="requires_capture"||se.status==="succeeded")){let he=typeof se.payment_method=="string"?se.payment_method:se.payment_method?.id;re({id:he??se.id,type:"card",threeDSecureActionResultTokenId:se.id,isPaypal:!0});let ge=new URL(window.location.href);ge.searchParams.delete("payment_intent"),ge.searchParams.delete("payment_intent_client_secret"),ge.searchParams.delete("redirect_status"),window.history.replaceState({},"",ge.toString())}else m?.("PayPal payment was not completed. Please try again.")}catch(G){m?.(G instanceof Error?G.message:"Failed to complete PayPal payment.")}finally{P(!1)}})())},[w,re,m]);let z=(0,pn.useCallback)(async()=>{if(!(!w||!F))try{if(P(!0),m?.(null),!e||!l)throw new Ja.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let te=await w.confirmPayPalPayment({billingApiUrl:Z,sessionId:e,nonce:t,email:l,returnUrl:window.location.href});if(te.error){m?.(te.error.message);return}te.paymentIntentId&&(te.status==="succeeded"||te.status==="processing"||te.status==="requires_capture")&&re({id:te.paymentMethodId??te.paymentIntentId,type:"card",threeDSecureActionResultTokenId:te.paymentIntentId,isPaypal:!0})}catch(te){m?.(te instanceof Error?te.message:"PayPal payment failed. Please try again.")}finally{P(!1)}},[w,F,e,t,l,Z,re,m]);return!w||!F?(0,un.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,un.jsxs)(un.Fragment,{children:[!g&&(0,un.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,un.jsx)("div",{style:g?{}:{display:"none"},children:(0,un.jsx)("button",{type:"button",onClick:z,disabled:L||x,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:L||x?"not-allowed":"pointer",opacity:L||x?.6:1},ref:()=>E(!0),children:L?"Processing...":"PayPal"})}),(L||x)&&(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 xe=require("react"),ro=require("@flopay/js"),Lt=require("@flopay/shared");var mn=require("react/jsx-runtime"),ds=44;function Za(e){return new Promise(t=>setTimeout(t,e))}function us(e,t){return e instanceof Lt.FloPayError?e:new Lt.FloPayError(e instanceof Error?e.message:t,"api_error")}function ps(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function ms(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 Qa({sessionId:e,nonce:t,createSession:n,paymentMethodId:l,checkoutMethod:o,clientId:s,products:u,items:c,subscriptions:I,account:O,successUrl:m,cancelUrl:x,couponCodes:w,tagsData:F,utmMetadata:d,billingApiUrl:g,locale:E,theme:L,appearance:P,buttonsTheme:W,buttonsStyles:Z,onSuccess:me,onError:re,onDecline:z,children:te,disabled:Y=!1,type:ye="button",style:V,...G}){let se=(0,xe.useMemo)(()=>(0,Lt.resolveBillingApiUrl)(g),[g]),Fe=(0,xe.useMemo)(()=>ms({createSession:n,clientId:s,products:u,items:c,subscriptions:I,account:O,successUrl:m,cancelUrl:x,couponCodes:w,tagsData:F,utmMetadata:d}),[O,x,s,w,n,u,c,I,m,F,d]),[he,ge]=(0,xe.useState)(!1),[ne,fe]=(0,xe.useState)(null),[ve,le]=(0,xe.useState)(null),[Ne,Ie]=(0,xe.useState)(null),Se=(0,xe.useRef)(!0),_=(0,xe.useRef)(null),ae=(0,xe.useRef)(Ne),de=(0,xe.useRef)(me),ze=(0,xe.useRef)(re),Oe=(0,xe.useRef)(z);(0,xe.useEffect)(()=>{ae.current=Ne},[Ne]),(0,xe.useEffect)(()=>{de.current=me},[me]),(0,xe.useEffect)(()=>{ze.current=re},[re]),(0,xe.useEffect)(()=>{Oe.current=z},[z]),(0,xe.useEffect)(()=>(Se.current=!0,()=>{Se.current=!1,_.current?.abort()}),[]),(0,xe.useEffect)(()=>{if(typeof window>"u")return;let h=we=>{we.key==="Escape"&&Ie(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let Q=(0,xe.useCallback)((h,we=Sr)=>{Oe.current?.(St(we,h,{code:h.code,declineCode:h.declineCode}))},[]),D=(0,xe.useCallback)(async h=>{Se.current&&(le(null),fe("success"),await Za(Tn),Se.current&&de.current?.(h))},[]),J=(0,xe.useCallback)(async(h,we)=>{Se.current&&(ze.current?.(h),we?.emitDecline&&Q(h,we.method),le(h.message),fe("error"),await Za(bn))},[Q]),ue=(0,xe.useCallback)(async(h,we,He)=>{let st=h.data.session??null;if(!st)throw new Lt.FloPayError("No session data returned","api_error");let rt=st.clientSecret||t;if(st.status==="complete"){await D({result:{status:"succeeded"},session:st,sessionId:st.id||we,autoCompleted:!1});return}if(st.status==="expired")throw new Lt.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(h.autoProcessingPending){let Pt=(await new ro.PaymentAPI(se).waitForCheckoutSessionCompletion(h.autoProcessingPending.sessionId,{initialDelayMs:h.autoProcessingPending.retryAfterMs})).data.session;if(!Pt||Pt.status!=="complete")throw new Lt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:Pt?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await D({result:{status:"succeeded"},session:Pt,sessionId:Pt.id||we,autoCompleted:!1});return}if(h.autoProcessingError){if(h.autoProcessingError.type==="3ds_required"&&h.autoProcessingError.nextActionRedirectUrl&&we&&rt){let Ye=new AbortController;_.current=Ye;let Ce;try{Ce=await Ua({billingApiUrl:se,sessionId:we,nonce:rt,nextActionRedirectUrl:h.autoProcessingError.nextActionRedirectUrl,signal:Ye.signal})}finally{_.current===Ye&&(_.current=null)}if(Ce.status==="declined")throw Nn({type:Ce.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ce.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let Nt=(await new ro.PaymentAPI(se).waitForCheckoutSessionCompletion(we,{initialDelayMs:0,nonce:rt})).data.session;if(!Nt||Nt.status!=="complete")throw Nn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await D({result:{status:"succeeded"},session:Nt,sessionId:Nt.id||we,autoCompleted:!1});return}throw Nn(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(He?.fromCreateSession&&h.autoProcessingAttempted===!0)throw Nn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Qe=await rr({billingApiUrl:se,sessionId:we??st.id,session:st,nonce:rt});if(Qe.type!=="success")throw Nn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await D({result:Qe.result,session:st,sessionId:st.id||we,autoCompleted:!1})}catch(Qe){let Ye=Kn(Qe),Ce=st.id||we;await J(Ye,{emitDecline:!0,method:Ye.checkoutMethod??Sr}),ps(Ye,Ce)&&Ce&&Se.current&&Ie({sessionId:Ce,errorMessage:Ye.message,nonce:rt||void 0})}},[t,se,J,D]),Ee=(0,xe.useCallback)(async h=>{if(G.onClick?.(h),!(h.defaultPrevented||Y||he)){if(Ie(null),e&&Fe){let we=new Lt.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await J(we),Se.current&&(fe(null),le(null));return}if(!e&&!Fe){let we=new Lt.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await J(we),Se.current&&(fe(null),le(null));return}ge(!0),le(null),fe("processing");try{let we=new ro.PaymentAPI(se);if(e){let He=await we.getUnifiedCheckoutSession(e,t);await ue(He,e);return}try{let He=await we.createAndFetchSession({...Fe});await ue(He,He.data.session?.id??null,{fromCreateSession:!0})}catch(He){if(He instanceof Lt.FloPayError&&He.code==="session_auto_completed"){await D({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw He}}catch(we){await J(us(we,"Automatic payment failed. Please try again."))}finally{Se.current&&(fe(null),le(null),ge(!1))}}},[G,Fe,Y,he,t,ue,se,e,J,D]),it=(0,xe.useCallback)(h=>{let we=ae.current;Ie(null),de.current?.({result:h,session:null,sessionId:we?.sessionId??null,autoCompleted:!1})},[]),Ze=(0,xe.useCallback)(h=>{ze.current?.(h)},[]),Xe=(0,xe.useCallback)(h=>{Oe.current?.(h)},[]),y=(0,xe.useMemo)(()=>(0,Lt.resolveTheme)(L),[L]),je=(0,xe.useMemo)(()=>{let h=y?.buttonsLayout??(0,Lt.resolveButtonsLayoutTheme)(W);return Z?{...h,...Z,cardButton:{...h.cardButton,...Z.cardButton}}:h},[y,W,Z]),Ue=(0,xe.useMemo)(()=>{let h=y?.appearance;return P?h?{...h,...P,variables:{...h.variables,...P.variables}}:P:h},[P,y]),We=Ue?.variables,Ve=We?.colorPrimary??"#4A49FF",Yt=We?.colorPrimaryHover??Kr(Ve,.12),ht=We?.borderRadius??"8px";return(0,mn.jsxs)(mn.Fragment,{children:[(0,mn.jsx)("button",{...G,type:ye,onClick:Ee,disabled:Y||he,"aria-busy":he,style:{width:"100%",...te===void 0?{boxSizing:"border-box",height:ds,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...je.cardButton,...Io({themeBundle:y,resolvedPrimaryColor:Ve,resolvedBorderRadius:ht,submitButtonStyle:je.submitButton,explicitPrimaryColor:We?.colorPrimary}),fontSize:je.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Y||he?"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||he?.6:1,...V},onMouseEnter:h=>{G.onMouseEnter?.(h),!h.defaultPrevented&&!Y&&!he&&(y||We?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Yt)},onMouseLeave:h=>{G.onMouseLeave?.(h),!h.defaultPrevented&&(y||We?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Ve)},onMouseDown:h=>{G.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{G.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,mn.jsx)(Jn,{content:te})}),ne&&(0,mn.jsx)(vn,{status:ne,errorMessage:ve}),Ne&&(0,mn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&Ie(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,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)(no,{sessionId:Ne.sessionId,nonce:Ne.nonce,checkoutMode:"full",billingApiUrl:se,locale:E,theme:L,...Ue?{appearance:Ue}:{},buttonsTheme:W,buttonsStyles:Z,initialErrorMessage:Ne.errorMessage,cardTitleContent:null,onComplete:it,onError:Ze,onDecline:Xe})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,useCheckout,useElements,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,C.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&R(cr),n&&(l||o)&&R(cr),n&&(0,C.jsx)("button",{type:"button",onClick:()=>{e?.("card"),S(!0)},style:{width:"100%",...D,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)(tr,{content:k})}),(0,C.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Jn=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:m,onEscape:E}){let S=(0,Jn.useRef)(null),B=(0,Jn.useRef)(null),{elements:d,reportInteractive:f}=(0,Jn.useContext)(_n);return(0,Jn.useEffect)(()=>{if(!d||!S.current)return;let R=!0;return(async()=>{let D=d.getElement(e);D||(D=await d.create(e,u)),!(!R||!S.current)&&(D.mount(S.current),B.current=D,c&&D.on("change",c),D.on("ready",()=>{f?.(),k?.()}),N&&D.on("focus",N),m&&D.on("blur",m),E&&D.on("escape",E))})(),()=>{if(R=!1,B.current){try{B.current.unmount()}catch{}B.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:m,isProcessing:E=!1}){let S=ln(),B=jr(),d=Kr(),[f,R]=(0,pn.useState)(!1),[D,g]=(0,pn.useState)(!1),V=(0,pn.useRef)(!1),Z=(n||d).replace(/\/+$/,""),he=(0,pn.useCallback)(async ee=>{try{let Pe=await new ri.PaymentAPI(Z).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:ee,accountData:{userId:o??"",email:l??"",firstName:s??"",lastName:u??""},chv:c});if(Pe.ok){N?.();return}let q=await Pe.json().catch(()=>null);m?.(q?.message??"Payment failed. Please try again.")}catch(H){m?.(H instanceof Error?H.message:"An unexpected error occurred")}},[Z,e,t,o,l,s,u,c,N,m]),oe=(0,pn.useCallback)(ee=>{k?k(ee):he(ee)},[k,he]);(0,pn.useEffect)(()=>{if(!S||V.current)return;let ee=new URLSearchParams(window.location.search),H=ee.get("payment_intent"),Pe=ee.get("payment_intent_client_secret"),q=ee.get("redirect_status");!H||!Pe||(V.current=!0,(async()=>{try{if(g(!0),q==="failed"){m?.("PayPal payment was declined. Please try again.");return}let W=S.getRawProvider();if(!W?.retrievePaymentIntent){m?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ce,error:Ne}=await W.retrievePaymentIntent(Pe);if(Ne){m?.(Ne.message??"Failed to retrieve PayPal payment status.");return}if(ce&&(ce.status==="requires_capture"||ce.status==="succeeded")){let Se=typeof ce.payment_method=="string"?ce.payment_method:ce.payment_method?.id;oe({id:Se??ce.id,type:"card",threeDSecureActionResultTokenId:ce.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 m?.("PayPal payment was not completed. Please try again.")}catch(W){m?.(W instanceof Error?W.message:"Failed to complete PayPal payment.")}finally{g(!1)}})())},[S,oe,m]);let O=(0,pn.useCallback)(async()=>{if(!(!S||!B))try{if(g(!0),m?.(null),!e||!l)throw new oi.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let ee=await S.confirmPayPalPayment({billingApiUrl:Z,sessionId:e,nonce:t,email:l,returnUrl:window.location.href});if(ee.error){m?.(ee.error.message);return}ee.paymentIntentId&&(ee.status==="succeeded"||ee.status==="processing"||ee.status==="requires_capture")&&oe({id:ee.paymentMethodId??ee.paymentIntentId,type:"card",threeDSecureActionResultTokenId:ee.paymentIntentId,isPaypal:!0})}catch(ee){m?.(ee instanceof Error?ee.message:"PayPal payment failed. Please try again.")}finally{g(!1)}},[S,B,e,t,l,Z,oe,m]);return!S||!B?(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:D||E,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:D||E?"not-allowed":"pointer",opacity:D||E?.6:1},ref:()=>R(!0),children:D?"Processing...":"PayPal"})}),(D||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"),Ot=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 Ot.FloPayError?e:new Ot.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:m,cancelUrl:E,couponCodes:S,tagsData:B,utmMetadata:d,billingApiUrl:f,locale:R,theme:D,appearance:g,buttonsTheme:V,buttonsStyles:Z,onSuccess:he,onError:oe,onDecline:O,children:ee,disabled:H=!1,type:Pe="button",style:q,...W}){let ce=(0,Ae.useMemo)(()=>(0,Ot.resolveBillingApiUrl)(f),[f]),Ne=(0,Ae.useMemo)(()=>Rs({createSession:n,clientId:s,products:u,items:c,subscriptions:k,account:N,successUrl:m,cancelUrl:E,couponCodes:S,tagsData:B,utmMetadata:d}),[N,E,s,S,n,u,c,k,m,B,d]),[Se,Ce]=(0,Ae.useState)(!1),[te,be]=(0,Ae.useState)(null),[ke,de]=(0,Ae.useState)(null),[ze,Be]=(0,Ae.useState)(null),Ee=(0,Ae.useRef)(!0),I=(0,Ae.useRef)(null),ie=(0,Ae.useRef)(ze),me=(0,Ae.useRef)(he),$e=(0,Ae.useRef)(oe),Ue=(0,Ae.useRef)(O);(0,Ae.useEffect)(()=>{ie.current=ze},[ze]),(0,Ae.useEffect)(()=>{me.current=he},[he]),(0,Ae.useEffect)(()=>{$e.current=oe},[oe]),(0,Ae.useEffect)(()=>{Ue.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"&&Be(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let Q=(0,Ae.useCallback)((h,_e=Ir)=>{Ue.current?.(wt(_e,h,{code:h.code,declineCode:h.declineCode}))},[]),A=(0,Ae.useCallback)(async h=>{Ee.current&&(de(null),be("success"),await ii(Tn),Ee.current&&me.current?.(h))},[]),Y=(0,Ae.useCallback)(async(h,_e)=>{Ee.current&&($e.current?.(h),_e?.emitDecline&&Q(h,_e.method),de(h.message),be("error"),await ii(Cn))},[Q]),ye=(0,Ae.useCallback)(async(h,_e,Ve)=>{let lt=h.data.session??null;if(!lt)throw new Ot.FloPayError("No session data returned","api_error");let it=lt.clientSecret||t;if(lt.status==="complete"){await A({result:{status:"succeeded"},session:lt,sessionId:lt.id||_e,autoCompleted:!1});return}if(lt.status==="expired")throw new Ot.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(h.autoProcessingPending){let Pt=(await new co.PaymentAPI(ce).waitForCheckoutSessionCompletion(h.autoProcessingPending.sessionId,{initialDelayMs:h.autoProcessingPending.retryAfterMs})).data.session;if(!Pt||Pt.status!=="complete")throw new Ot.FloPayError("Automatic payment failed. Please try again.","api_error",{code:Pt?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await A({result:{status:"succeeded"},session:Pt,sessionId:Pt.id||_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 Re;try{Re=await Wa({billingApiUrl:ce,sessionId:_e,nonce:it,nextActionRedirectUrl:h.autoProcessingError.nextActionRedirectUrl,signal:Je.signal})}finally{I.current===Je&&(I.current=null)}if(Re.status==="declined")throw On({type:Re.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Re.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let zt=(await new co.PaymentAPI(ce).waitForCheckoutSessionCompletion(_e,{initialDelayMs:0,nonce:it})).data.session;if(!zt||zt.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:zt,sessionId:zt.id||_e,autoCompleted:!1});return}throw On(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(Ve?.fromCreateSession&&h.autoProcessingAttempted===!0)throw On({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let nt=await lr({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),Re=lt.id||_e;await Y(Je,{emitDecline:!0,method:Je.checkoutMethod??Ir}),ks(Je,Re)&&Re&&Ee.current&&Be({sessionId:Re,errorMessage:Je.message,nonce:it||void 0})}},[t,ce,Y,A]),Me=(0,Ae.useCallback)(async h=>{if(W.onClick?.(h),!(h.defaultPrevented||H||Se)){if(Be(null),e&&Ne){let _e=new Ot.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Y(_e),Ee.current&&(be(null),de(null));return}if(!e&&!Ne){let _e=new Ot.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Y(_e),Ee.current&&(be(null),de(null));return}Ce(!0),de(null),be("processing");try{let _e=new co.PaymentAPI(ce);if(e){let Ve=await _e.getUnifiedCheckoutSession(e,t);await ye(Ve,e);return}try{let Ve=await _e.createAndFetchSession({...Ne});await ye(Ve,Ve.data.session?.id??null,{fromCreateSession:!0})}catch(Ve){if(Ve instanceof Ot.FloPayError&&Ve.code==="session_auto_completed"){await A({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Ve}}catch(_e){await Y(ws(_e,"Automatic payment failed. Please try again."))}finally{Ee.current&&(be(null),de(null),Ce(!1))}}},[W,Ne,H,Se,t,ye,ce,e,Y,A]),st=(0,Ae.useCallback)(h=>{let _e=ie.current;Be(null),me.current?.({result:h,session:null,sessionId:_e?.sessionId??null,autoCompleted:!1})},[]),tt=(0,Ae.useCallback)(h=>{$e.current?.(h)},[]),et=(0,Ae.useCallback)(h=>{Ue.current?.(h)},[]),p=(0,Ae.useMemo)(()=>(0,Ot.resolveTheme)(D),[D]),je=(0,Ae.useMemo)(()=>{let h=p?.buttonsLayout??(0,Ot.resolveButtonsLayoutTheme)(V);return Z?{...h,...Z,cardButton:{...h.cardButton,...Z.cardButton}}:h},[p,V,Z]),qe=(0,Ae.useMemo)(()=>{let h=p?.appearance;return g?h?{...h,...g,variables:{...h.variables,...g.variables}}:g:h},[g,p]),Ge=qe?.variables,Ke=Ge?.colorPrimary??"#4A49FF",Yt=Ge?.colorPrimaryHover??Jr(Ke,.12),ht=Ge?.borderRadius??"8px";return(0,mn.jsxs)(mn.Fragment,{children:[(0,mn.jsx)("button",{...W,type:Pe,onClick:Me,disabled:H||Se,"aria-busy":Se,style:{width:"100%",...ee===void 0?{boxSizing:"border-box",height:Ss,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...je.cardButton,...Ao({themeBundle:p,resolvedPrimaryColor:Ke,resolvedBorderRadius:ht,submitButtonStyle:je.submitButton,explicitPrimaryColor:Ge?.colorPrimary}),fontSize:je.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:H||Se?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:H||Se?.6:1,...q},onMouseEnter:h=>{W.onMouseEnter?.(h),!h.defaultPrevented&&!H&&!Se&&(p||Ge?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Yt)},onMouseLeave:h=>{W.onMouseLeave?.(h),!h.defaultPrevented&&(p||Ge?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Ke)},onMouseDown:h=>{W.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{W.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,mn.jsx)(tr,{content:ee})}),te&&(0,mn.jsx)(Sn,{status:te,errorMessage:ke}),ze&&(0,mn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&Be(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:ze.sessionId,nonce:ze.nonce,checkoutMode:"full",billingApiUrl:ce,locale:R,theme:D,...qe?{appearance:qe}:{},buttonsTheme:V,buttonsStyles:Z,initialErrorMessage:ze.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});