@flopay/react 1.4.5 → 1.4.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +9 -9
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var mi=Object.create;var Ar=Object.defineProperty;var yi=Object.getOwnPropertyDescriptor;var fi=Object.getOwnPropertyNames;var gi=Object.getPrototypeOf,hi=Object.prototype.hasOwnProperty;var Pi=(e,t)=>{for(var n in t)Ar(e,n,{get:t[n],enumerable:!0})},na=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fi(t))!hi.call(e,o)&&o!==n&&Ar(e,o,{get:()=>t[o],enumerable:!(l=yi(t,o))||l.enumerable});return e};var ra=(e,t,n)=>(n=e!=null?mi(gi(e)):{},na(t||!e||!e.__esModule?Ar(n,"default",{value:e,enumerable:!0}):n,e)),bi=e=>na(Ar({},"__esModule",{value:!0}),e);var cs={};Pi(cs,{AddressElement:()=>ja,DirectPayPalButton:()=>Pr,FloPayAutomaticPaymentButton:()=>Ga,FloPayCheckout:()=>eo,FloPayProvider:()=>yr,PayPalButton:()=>Wa,PaymentElement:()=>qa,SplitCardForm:()=>Wr,VaultCardFields:()=>Dr,useCheckout:()=>ca,useElements:()=>Nr,useFloPay:()=>on,usePayPalFloPay:()=>Lr});module.exports=bi(cs);var vi=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,Ae=vi();var wt=require("react"),oa=require("@flopay/shared");var fo=require("react"),In=(0,fo.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),rn=(0,fo.createContext)({session:null,loading:!1,error:null});var Ci=Symbol.for("@flopay/js.telemetry.bridge.v1"),Si=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function wi(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},flush:async()=>{},destroy:()=>{}}}function ki(e){let t=wi(),n=(o,s)=>o?o.bind(e):s,l=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:l,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,l()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Fr(e){let t=globalThis[Si];return ki(t?.(e)??{})}function Mt(e){if(e)return e[Ci]}var aa=require("react/jsx-runtime");function yr({flopay:e,paypalFlopay:t,options:n,children:l}){let[o,s]=(0,wt.useState)(e instanceof Promise?null:e),[u,c]=(0,wt.useState)(t instanceof Promise||!t?null:t),[R,L]=(0,wt.useState)(null),m=(0,wt.useRef)(null),_=(0,wt.useRef)(null),w=(0,wt.useRef)(null);(0,wt.useEffect)(()=>{if(!o)return;let I=Mt(o);return m.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),(0,wt.useEffect)(()=>{let I=!1;return e instanceof Promise?e.then(A=>{I||s(A)}):s(e),()=>{I=!0}},[e]),(0,wt.useEffect)(()=>{let I=!1;if(!t){c(null);return}return t instanceof Promise?t.then(A=>{I||c(A)}):c(t),()=>{I=!0}},[t]),(0,wt.useEffect)(()=>{if(!o){L(null);return}let I=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return L(I),()=>{I.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,wt.useEffect)(()=>{if(!o||!R||_.current===R)return;_.current=R;let I=Mt(o);I?.log({name:"checkout.rendered",stage:"checkout_render"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(m.current??0),durationMode:"machine"})},[R,o]);let B=(0,wt.useCallback)(()=>{if(!o||!R||w.current===R)return;w.current=R;let I=Mt(o);I?.log({name:"checkout.interactive",stage:"checkout_interactive"}),I?.performance({stage:"checkout_interactive",durationMs:I.elapsed(m.current??0),durationMode:"machine"})},[R,o]),d=(0,oa.resolveBillingApiUrl)(n?.billingApiUrl),g=(0,wt.useMemo)(()=>({flopay:o,paypalFlopay:u,elements:R,billingApiUrl:d,reportInteractive:B}),[o,u,R,d,B]);return(0,aa.jsx)(In.Provider,{value:g,children:l})}var D=ra(require("react"),1),Sr=require("@flopay/js"),Le=require("@flopay/shared");var Ss=require("react"),nt=require("react/jsx-runtime");function Ri(){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 Ii(){return(0,nt.jsx)(nt.Fragment,{children:"Go back"})}function Ei(){return(0,nt.jsx)(nt.Fragment,{children:"Secure card checkout"})}function Yn(e){return e!==void 0&&(e===""||e===null||e===!1)}function Gn({content:e}){return(0,nt.jsx)(nt.Fragment,{children:e===void 0?(0,nt.jsx)(Ri,{}):e})}function Jn({content:e}){return(0,nt.jsx)(nt.Fragment,{children:e===void 0?(0,nt.jsx)(Ii,{}):e})}function fr({content:e}){return(0,nt.jsx)(nt.Fragment,{children:e===void 0?(0,nt.jsx)(Ei,{}):e})}var ut=require("@stripe/react-stripe-js"),k=require("@flopay/shared"),Bn=require("@flopay/js");var En=require("react"),ia=require("react/jsx-runtime");function Dr({capture:e,html:t,messageToken:n,expectedOrigin:l,theme:o,containerStyle:s,onReady:u,onError:c,onValidation:R}){let L=(0,En.useRef)(null),m=(0,En.useRef)(u),_=(0,En.useRef)(c),w=(0,En.useRef)(R);m.current=u,_.current=c,w.current=R;let B=(0,En.useRef)(o);return B.current=o,(0,En.useEffect)(()=>{let d=L.current;if(!d)return;let g=!0,I=!1,A=()=>{!g||I||(I=!0,m.current?.())},P=e.on("ready",()=>{A()}),H=e.on("error",se=>{_.current?.(se.message??"There was a problem loading the secure card form.")}),Q=e.on("validation",se=>{w.current?.(se.message??null)}),me={html:t,...n?{messageToken:n}:{},...l?{expectedOrigin:l}:{},...B.current?{theme:B.current}:{}};return e.mount(d,me).then(()=>{A()}).catch(se=>{g&&_.current?.(se instanceof Error?se.message:"Failed to load the secure card form.")}),()=>{g=!1,P(),H(),Q(),e.unmount()}},[e,t,n,l]),(0,En.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,ia.jsx)("div",{ref:L,"data-testid":"flopay-vault-card-fields",style:s})}var xs=require("react"),gr=require("react/jsx-runtime");function Xn({children:e,margin:t,icon:n=!0,styleOverride:l}){return(0,gr.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,gr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,gr.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 sa={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=ra(require("react"),1);var Zn=require("react"),la=require("@flopay/shared");function on(){return(0,Zn.useContext)(In).flopay}function Lr(){return(0,Zn.useContext)(In).paypalFlopay??null}function Nr(){return(0,Zn.useContext)(In).elements}function ca(){return(0,Zn.useContext)(rn)}function Or(){return(0,Zn.useContext)(In).billingApiUrl||(0,la.resolveBillingApiUrl)()}var Os=require("react"),yt=require("react/jsx-runtime"),_n=1200,Pn=1500;function bn({status:e,errorMessage:t}){return(0,yt.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,yt.jsxs)("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,yt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,yt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,yt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,yt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,yt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,yt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,yt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,yt.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,yt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,yt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,yt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,yt.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,yt.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&"PROCESSING...",e==="success"&&"PAYMENT SUCCESSFUL",e==="error"&&"PAYMENT FAILED"]}),e==="success"&&(0,yt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:"You will be automatically redirected, do not close or navigate away from this window."}),e==="error"&&t&&(0,yt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,yt.jsx)("style",{children:`
|
|
1
|
+
"use strict";var yi=Object.create;var Fr=Object.defineProperty;var fi=Object.getOwnPropertyDescriptor;var gi=Object.getOwnPropertyNames;var hi=Object.getPrototypeOf,Pi=Object.prototype.hasOwnProperty;var bi=(e,t)=>{for(var n in t)Fr(e,n,{get:t[n],enumerable:!0})},ra=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of gi(t))!Pi.call(e,o)&&o!==n&&Fr(e,o,{get:()=>t[o],enumerable:!(l=fi(t,o))||l.enumerable});return e};var oa=(e,t,n)=>(n=e!=null?yi(hi(e)):{},ra(t||!e||!e.__esModule?Fr(n,"default",{value:e,enumerable:!0}):n,e)),vi=e=>ra(Fr({},"__esModule",{value:!0}),e);var ds={};bi(ds,{AddressElement:()=>Va,DirectPayPalButton:()=>br,FloPayAutomaticPaymentButton:()=>Ja,FloPayCheckout:()=>to,FloPayProvider:()=>fr,PayPalButton:()=>Ya,PaymentElement:()=>ja,SplitCardForm:()=>Yr,VaultCardFields:()=>Lr,useCheckout:()=>da,useElements:()=>Or,useFloPay:()=>an,usePayPalFloPay:()=>Nr});module.exports=vi(ds);var Ci=()=>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=Ci();var St=require("react"),aa=require("@flopay/shared");var go=require("react"),En=(0,go.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),on=(0,go.createContext)({session:null,loading:!1,error:null});var Si=Symbol.for("@flopay/js.telemetry.bridge.v1"),wi=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function ki(){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 Ri(e){let t=ki(),n=(o,s)=>o?o.bind(e):s,l=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:l,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,l()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Dr(e){let t=globalThis[wi];return Ri(t?.(e)??{})}function Tt(e){if(e)return e[Si]}var ia=require("react/jsx-runtime");function fr({flopay:e,paypalFlopay:t,options:n,children:l}){let[o,s]=(0,St.useState)(e instanceof Promise?null:e),[u,c]=(0,St.useState)(t instanceof Promise||!t?null:t),[R,N]=(0,St.useState)(null),m=(0,St.useRef)(null),_=(0,St.useRef)(null),w=(0,St.useRef)(null);(0,St.useEffect)(()=>{if(!o)return;let I=Tt(o);return m.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),(0,St.useEffect)(()=>{let I=!1;return e instanceof Promise?e.then(F=>{I||s(F)}):s(e),()=>{I=!0}},[e]),(0,St.useEffect)(()=>{let I=!1;if(!t){c(null);return}return t instanceof Promise?t.then(F=>{I||c(F)}):c(t),()=>{I=!0}},[t]),(0,St.useEffect)(()=>{if(!o){N(null);return}let I=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return N(I),()=>{I.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,St.useEffect)(()=>{if(!o||!R||_.current===R)return;_.current=R;let I=Tt(o);I?.log({name:"checkout.rendered",stage:"checkout_render"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(m.current??0),durationMode:"machine"})},[R,o]);let M=(0,St.useCallback)(()=>{if(!o||!R||w.current===R)return;w.current=R;let I=Tt(o);I?.log({name:"checkout.interactive",stage:"checkout_interactive"}),I?.performance({stage:"checkout_interactive",durationMs:I.elapsed(m.current??0),durationMode:"machine"})},[R,o]),d=(0,aa.resolveBillingApiUrl)(n?.billingApiUrl),g=(0,St.useMemo)(()=>({flopay:o,paypalFlopay:u,elements:R,billingApiUrl:d,reportInteractive:M}),[o,u,R,d,M]);return(0,ia.jsx)(En.Provider,{value:g,children:l})}var L=oa(require("react"),1),wr=require("@flopay/js"),Le=require("@flopay/shared");var ws=require("react"),tt=require("react/jsx-runtime");function Ii(){return(0,tt.jsxs)(tt.Fragment,{children:[(0,tt.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,tt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,tt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,tt.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,tt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Ei(){return(0,tt.jsx)(tt.Fragment,{children:"Go back"})}function _i(){return(0,tt.jsx)(tt.Fragment,{children:"Secure card checkout"})}function Yn(e){return e!==void 0&&(e===""||e===null||e===!1)}function Gn({content:e}){return(0,tt.jsx)(tt.Fragment,{children:e===void 0?(0,tt.jsx)(Ii,{}):e})}function Jn({content:e}){return(0,tt.jsx)(tt.Fragment,{children:e===void 0?(0,tt.jsx)(Ei,{}):e})}function gr({content:e}){return(0,tt.jsx)(tt.Fragment,{children:e===void 0?(0,tt.jsx)(_i,{}):e})}var dt=require("@stripe/react-stripe-js"),k=require("@flopay/shared"),ln=require("@flopay/js");var _n=require("react"),sa=require("react/jsx-runtime");function Lr({capture:e,html:t,messageToken:n,expectedOrigin:l,theme:o,containerStyle:s,onReady:u,onError:c,onValidation:R}){let N=(0,_n.useRef)(null),m=(0,_n.useRef)(u),_=(0,_n.useRef)(c),w=(0,_n.useRef)(R);m.current=u,_.current=c,w.current=R;let M=(0,_n.useRef)(o);return M.current=o,(0,_n.useEffect)(()=>{let d=N.current;if(!d)return;let g=!0,I=!1,F=()=>{!g||I||(I=!0,m.current?.())},P=e.on("ready",()=>{F()}),K=e.on("error",se=>{_.current?.(se.message??"There was a problem loading the secure card form.")}),Q=e.on("validation",se=>{w.current?.(se.message??null)}),pe={html:t,...n?{messageToken:n}:{},...l?{expectedOrigin:l}:{},...M.current?{theme:M.current}:{}};return e.mount(d,pe).then(()=>{F()}).catch(se=>{g&&_.current?.(se instanceof Error?se.message:"Failed to load the secure card form.")}),()=>{g=!1,P(),K(),Q(),e.unmount()}},[e,t,n,l]),(0,_n.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,sa.jsx)("div",{ref:N,"data-testid":"flopay-vault-card-fields",style:s})}var Ts=require("react"),hr=require("react/jsx-runtime");function Xn({children:e,margin:t,icon:n=!0,styleOverride:l}){return(0,hr.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...l??{}},children:[n&&(0,hr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,hr.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var la={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=oa(require("react"),1);var Zn=require("react"),ca=require("@flopay/shared");function an(){return(0,Zn.useContext)(En).flopay}function Nr(){return(0,Zn.useContext)(En).paypalFlopay??null}function Or(){return(0,Zn.useContext)(En).elements}function da(){return(0,Zn.useContext)(on)}function zr(){return(0,Zn.useContext)(En).billingApiUrl||(0,ca.resolveBillingApiUrl)()}var zs=require("react"),mt=require("react/jsx-runtime"),xn=1200,bn=1500;function vn({status:e,errorMessage:t}){return(0,mt.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,mt.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,mt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,mt.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,mt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,mt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,mt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,mt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,mt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,mt.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,mt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,mt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,mt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,mt.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,mt.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,mt.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,mt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,mt.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 da=require("@flopay/shared");function ua(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 go(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 pa(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 ho(e,t){return t?{...e,...t}:e}function Tt(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 Fn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:l}of _i)if(n.test(t))return l;return e}function zr(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function ma(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function ya(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Ur(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var $r="flopay_recent_completion_";function Qn(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem($r+e,JSON.stringify(t))}catch{}}function fa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem($r+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem($r+e),!1):!0}catch{return!1}}function ga(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var x=require("react"),ba=require("@paypal/paypal-js"),qr=require("@flopay/js"),Tn=require("@flopay/shared");function ft(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function xi(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Vn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function xn(e){if(typeof e!="object"||e===null)return;let t=e;return Vn(t.code)??Vn(t.type)??Vn(t.name)}function er(e){if(!(typeof e!="object"||e===null))return Vn(e.decline_code)}function hr(e){return typeof e!="object"||e===null?!1:Vn(e.type)?.toLowerCase()==="card_error"||er(e)!==void 0}function Dn(e){let t=xi(e)?.toLowerCase()??"",l=`${xn(e)?.toLowerCase()??""} ${t}`;return l.includes("popup")&&l.includes("block")}var an=require("react/jsx-runtime"),jr=45,Ti=1e3,Bi=11e3,Mi=["https://www.paypal.com","https://www.sandbox.paypal.com"],ha="We couldn't open PayPal. Try again or choose another payment method.",Ai={width:"100%",minHeight:jr,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Pa(e){return e.includes("No ack for postMessage init()")&&Mi.some(t=>e.includes(t))&&e.includes("10000ms")}function Fi(e){return e?`${ha} Allow pop-ups for this site, then try again.`:ha}function va({sessionId:e,nonce:t,billingApiUrl:n,email:l,clientId:o,environment:s,currency:u,isSubscription:c,onTokenizedBody:R,onComplete:L,onErrorChange:m,onDecline:_,onTechnicalFailure:w,isProcessing:B=!1,onLoadStateChange:d,onInitializationStateChange:g,allowAutomaticRetry:I=!0,onButtonClick:A,runBeforeButtonClick:P,session:H,existingOrderId:Q,telemetry:me,telemetryContext:se,debug:z=!1}){let te=on(),K=(0,x.useMemo)(()=>{if(te)return null;let f=Fr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Tn.SDK_VERSION,enabled:me!==!1});return f.setCheckoutContext(se??{}),f.beginCheckout(se??{}),f},[n,te,me,se?.checkoutMode,se?.layout]),ye=(0,x.useMemo)(()=>Mt(te),[te]);(0,x.useEffect)(()=>()=>{K&&K.flush().catch(()=>{}).finally(()=>K.destroy())},[K]);let W=(0,x.useMemo)(()=>({error:f=>{ye?ye.error(f):K?.error(f)},log:f=>{ye?ye.log(f):K?.log(f)},performance:f=>{ye?ye.performance(f):K?.performance(f)},terminal:f=>{ye?ye.terminal(f):K?.terminal(f)},startTiming:()=>ye?.now()??K?.now()??0,elapsed:f=>ye?.elapsed(f)??Math.max(0,(K?.now()??f)-f)}),[ye,K]),Y=(0,x.useRef)(null),le=(0,x.useRef)(0),Fe=(0,x.useRef)(null),he=(0,x.useRef)(!1),[ge,ne]=(0,x.useState)(!1),[fe,ve]=(0,x.useState)(!1),[ce,Ne]=(0,x.useState)(0),Ie=(0,x.useRef)(0),[we,E]=(0,x.useState)(!1),oe=(0,x.useRef)(!1),de=(0,x.useRef)(!1),[Ue,Oe]=(0,x.useState)(!1),[ee,M]=(0,x.useState)(!1),G=(0,x.useMemo)(()=>n.replace(/\/+$/,""),[n]),ue=(0,x.useMemo)(()=>JSON.stringify([G,o,u,s??"",c,e,Q??""]),[G,o,u,s,Q,c,e]),Ee=(0,x.useRef)(ue),gt=Ee.current!==ue,[et,Qe]=(0,x.useState)([]),y=f=>{z&&Qe(xe=>[...xe,`${new Date().toISOString().slice(11,23)} ${f}`])},je=(0,x.useRef)(R),$e=(0,x.useRef)(L),He=(0,x.useRef)(m),Ke=(0,x.useRef)(_),Wt=(0,x.useRef)(w),bt=(0,x.useRef)(A),kt=(0,x.useRef)(d),h=(0,x.useRef)(g),ke=(0,x.useRef)(P),Ve=(0,x.useRef)(H),lt=(0,x.useRef)(l),rt=(0,x.useRef)(t),ot=(0,x.useRef)(null),Ge=(0,x.useRef)(0),Ce=(0,x.useRef)(null),vt=(0,x.useRef)(null),We=(0,x.useRef)(new Map),Dt=(0,x.useRef)(new Map),Rt=(0,x.useRef)(!1);(0,x.useEffect)(()=>(Rt.current=!0,()=>{Rt.current=!1}),[]),(0,x.useEffect)(()=>{je.current=R},[R]),(0,x.useEffect)(()=>{$e.current=L},[L]),(0,x.useEffect)(()=>{He.current=m},[m]),(0,x.useEffect)(()=>{Ke.current=_},[_]),(0,x.useEffect)(()=>{Wt.current=w},[w]),(0,x.useEffect)(()=>{bt.current=A},[A]),(0,x.useEffect)(()=>{kt.current=d},[d]),(0,x.useEffect)(()=>{h.current=g},[g]),(0,x.useEffect)(()=>{ke.current=P},[P]),(0,x.useEffect)(()=>{Ve.current=H},[H]),(0,x.useEffect)(()=>{lt.current=l},[l]),(0,x.useEffect)(()=>{rt.current=t},[t]),(0,x.useEffect)(()=>{Ie.current=ce},[ce]),(0,x.useEffect)(()=>{we&&Fe.current?.focus()},[we,ce]);let dn=(0,x.useCallback)(()=>{window.setTimeout(()=>{Fe.current?.focus()},0)},[]),Sn=(0,x.useCallback)(()=>{ne(!1),Ne(f=>f+1)},[]),wn=(0,x.useCallback)(()=>{E(!1),(Y.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Y.current)?.focus?.()},[]);(0,x.useEffect)(()=>{!ge||!he.current||(he.current=!1,wn())},[wn,ge,ce]);let Nn=(0,x.useCallback)((f,xe)=>{let ct=Wt.current;if(ct){ct("paypal",f,xe);return}He.current?.(Fi(xe?.popupBlocked??Dn(f)))},[]),ht=()=>{Ce.current?.timer&&(clearTimeout(Ce.current.timer),Ce.current.timer=null)},Lt=()=>{ht();let f=Ge.current+1;return Ge.current=f,vt.current=null,Ce.current={generation:f,timer:null,yieldedControl:!1},E(!1),f},Nt=f=>f!==void 0&&Ce.current?.generation!==f?!1:(ht(),Ce.current=null,vt.current=null,!0),Yt=f=>{let xe=f?.generation??Ce.current?.generation??Ge.current;(!f?.generation||Ce.current?.generation===xe)&&(ht(),Ce.current=null),vt.current=xe,f?.showRetry&&E(!0),f?.remount&&Sn(),f?.focus!==!1&&dn()},Qt=f=>Ce.current?.generation===f&&vt.current!==f,un=f=>{typeof document<"u"&&document.visibilityState!=="visible"||(ht(),f.timer=setTimeout(()=>{Ce.current?.generation===f.generation&&(Ce.current=null,vt.current=f.generation,Nn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),E(!0),Sn(),dn())},600))},J=()=>{let f=Ce.current;f?.yieldedControl&&un(f)},Mn=()=>{let f=Ce.current;f&&(f.yieldedControl=!0,ht())},pn=f=>{let xe=ot.current;return xe&&Dt.current.set(f,xe),f};(0,x.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?J():Mn()};return document.addEventListener("visibilitychange",f),window.addEventListener("focus",J),window.addEventListener("blur",Mn),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("focus",J),window.removeEventListener("blur",Mn),ht()}},[]),(0,x.useEffect)(()=>{Ee.current!==ue&&(Ee.current=ue,oe.current=!1,de.current=!1,ne(!1),ve(!1),Oe(!1),h.current?.("loading"))},[ue]),(0,x.useEffect)(()=>{ft(()=>kt.current?.(ge&&!Ue))},[ge,Ue]);let Ot=(0,Tn.normalizeGatewayEnvironment)(s);(0,x.useEffect)(()=>{let f=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",xe=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(y(`mount clientId=${f} env=${s??"(unset)"}\u2192${Ot??"live"} ccy=${u} sub=${c}`),y(`ua=${xe.slice(0,80)}${xe.length>80?"\u2026":""}`),!o){y("FAIL: clientId empty \u2014 gateway misconfigured"),Oe(!0),W.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Y.current){y("FAIL: containerRef not attached");return}le.current=W.startTiming(),W.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ct=!1,kn=!1,Te=()=>ct||kn,An,mn=!1,On=()=>{An=(0,Tn.generateIdempotencyKey)(),An||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),mn=!0},yn=null,zt=!1,Bt=null,Re=!1,pt=()=>{!Bt||Re||(Re=!0,Bt.close().catch(()=>{}))},it=null,en=()=>{it!==null&&(W.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"overlay_return",durationMs:W.elapsed(it),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),it=null)},Gt=!1,Pt=Y.current,Vt=null,Ct=null,tn=[],fn=N=>{if(!N||typeof N.getBoundingClientRect!="function")return"(no rect)";let b=N.getBoundingClientRect();return`${Math.round(b.width)}\xD7${Math.round(b.height)}`},Rn=N=>{if(!N)return"(empty)";try{let b=new URL(N,typeof window<"u"?window.location.href:"https://localhost"),O=b.pathname.toLowerCase();return O.includes("checkcaptcha")||O.includes("captcha")?`CAPTCHA(${b.host}${O})`:O.includes("risk")||O.includes("challenge")?`RISK(${b.host}${O})`:O.includes("smart/buttons")?`smart-buttons(${b.host})`:`${b.host}${O}`.slice(0,100)}catch{return N.slice(0,80)}},gn=N=>{let b=N.getAttribute("src"),O=N.getAttribute("srcdoc"),Pe=N.getAttribute("name"),Me=N.getAttribute("sandbox"),qe=[];return b&&qe.push(`src=${Rn(b)}`),O&&qe.push(`srcdoc[${O.length}ch]`),!b&&!O&&qe.push("src=(empty) srcdoc=(empty)"),Pe&&qe.push(`name=${Pe.slice(0,40)}`),Me!==null&&qe.push(`sandbox="${Me.slice(0,40)}"`),qe.join(" ")},Ht=N=>{if(!(N instanceof HTMLIFrameElement))return"";try{let b=N.contentDocument;if(!b)return"cd=null";let O=b.body?.children.length??0,Pe=b.body?.innerHTML.length??0,Me=b.head?.innerHTML.length??0;return`cd=same-origin readyState=${b.readyState} body[${O}children,${Pe}ch] head[${Me}ch]`}catch(b){return`cd=cross-origin(${b.message.slice(0,30)})`}},Ye=[],Kt=N=>{if(Te())return;let b=N.message??String(N.error??"(no message)");b&&(b.toLowerCase().includes("paypal")||b.toLowerCase().includes("zoid")||b.toLowerCase().includes("postrobot")||b.toLowerCase().includes("storage"))&&(y(`window:error ${b.slice(0,140)}`),Ye.push(b))},Ut=N=>{if(Te())return;let b=N.reason instanceof Error?N.reason.message:String(N.reason??"(no reason)");b&&(b.toLowerCase().includes("paypal")||b.toLowerCase().includes("zoid")||b.toLowerCase().includes("postrobot")||b.toLowerCase().includes("storage"))&&(y(`window:rejection ${b.slice(0,140)}`),Ye.push(b))};z&&typeof window<"u"&&(window.addEventListener("error",Kt),window.addEventListener("unhandledrejection",Ut));let $t={value:0};if(z&&typeof PerformanceObserver<"u")try{Ct=new PerformanceObserver(N=>{if(!Te())for(let b of N.getEntries()){if(!b.name.toLowerCase().includes("paypal"))continue;$t.value+=1;let O=Math.round(b.duration);y(`net ${O}ms ${b.name.slice(0,90)}`)}}),Ct.observe({type:"resource",buffered:!0})}catch{}let T=()=>{for(Vt?.disconnect(),Vt=null,Ct?.disconnect(),Ct=null;tn.length;)clearTimeout(tn.pop());z&&typeof window<"u"&&(window.removeEventListener("error",Kt),window.removeEventListener("unhandledrejection",Ut))},U=N=>{if(!N)return!1;let b=N.toLowerCase();return b.includes("zoid destroyed")||b.includes("destroyed all components")||b.includes("window closed")||b.includes("detected container element removed")},q=N=>{if(Te()||U(N))return;let b=Fn(N)??N;ft(()=>He.current?.(b))},F=N=>{ct||(Oe(!0),N.includes("paypal_ineligible")||W.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal load/render failure:",N))},p=(N,b=!1)=>{if(ct)return;let O=oe.current||!I;if(zt)return;zt=!0,kn=!0,T(),pt();let Pe=b||Pa(N);if(Pe&&I&&!oe.current){oe.current=!0,ne(!1),M(!1),ve(!0),h.current?.("retrying"),yn=setTimeout(()=>{ct||Ne(Me=>Me+1)},Ti);return}if(Pe||O){if(ne(!1),M(!1),ve(!1),Oe(!0),h.current?.("exhausted"),!de.current){de.current=!0;let Me=Pa(N)?"paypal_init_timeout":b?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",Me)}return}F(N)};Oe(!1);let j=async(N,b=ot.current)=>{if(Te())return;let O=b?.sessionId??e;if(je.current){await je.current(N,{sessionId:O,accountPatch:b?.accountPatch,nonce:b?.nonce});return}let Pe=W.startTiming();W.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Me=()=>{W.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"processing",durationMs:W.elapsed(Pe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let qe=Ve.current,Z=b?.accountPatch?.email??lt.current,be=b?.accountPatch?.userId??qe?.customer?.id??qe?.accountData?.userId??"",pe=await new qr.PaymentAPI(G,{telemetry:!1}).processPayment(be,{sessionId:O,nonce:b?.nonce??rt.current,tokenizedData:N,accountData:{userId:be,email:Z??qe?.customer?.email??"",firstName:b?.accountPatch?.firstName??qe?.customer?.firstName??qe?.accountData?.firstName??"",lastName:b?.accountPatch?.lastName??qe?.customer?.lastName??qe?.accountData?.lastName??"",country:b?.accountPatch?.country??qe?.customer?.country??qe?.accountData?.country??void 0,zip:b?.accountPatch?.zip??qe?.customer?.zip??qe?.accountData?.zip??void 0}});if(pe.ok){if(kn||ct&&Rt.current)return;Me(),W.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ft(()=>$e.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Te())return;let ze=await pe.json().catch(()=>null),hn=ze?.message??"PayPal payment failed.",dt=Fn(hn)??hn;Me(),typeof ze?.declineCode=="string"?W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):W.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:pe.status>=500?"5xx":pe.status>=400?"4xx":pe.status>=300?"3xx":"unknown"}),q(dt),ft(()=>Ke.current?.(Tt("paypal",dt,{code:ze?.code,declineCode:ze?.declineCode})));return}catch(qe){if(Te())return;Me(),W.error({errorCode:"NETWORK_REQUEST_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Z=qe instanceof Error?qe.message:"PayPal payment failed.",be=Fn(Z)??Z;q(be),ft(()=>Ke.current?.(Tt("paypal",be)));return}},v=()=>new Tn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Be=N=>Te()?Promise.reject(v()):Promise.resolve(N),X=async N=>{if(Te())throw v();mn||On();let b=ot.current,O=b?.sessionId??e,Pe=b?.nonce??rt.current;W.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Me=await new qr.PaymentAPI(G,{telemetry:!1}).createSessionIntent(O,Pe??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:An});if(Te())throw v();if(Me.provider!=="paypal")throw new Error(N);return W.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Me.providerObjectId},Je=(N,b)=>{let O=b?.nonce??rt.current;if(!O)return;let Pe=b?.sessionId??e,Me=er(N)??xn(N)??"provider_declined";new qr.PaymentAPI(G,{telemetry:!1}).reportSessionIntentDecline(Pe,O,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Me}).catch(()=>{})},ae=ce;y("loadScript:scheduled (deferred 1 tick)");let qt=null,st=setTimeout(()=>{if(ct){y("loadScript:skipped (cancelled before defer ran)");return}y("loadScript:start");let N=Ot==="live"?"production":Ot;qt=(0,ba.loadScript)({clientId:o,currency:u,intent:c?"subscription":"capture",vault:c?!0:void 0,...N?{environment:N}:{},...N==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),qt.then(b=>{if(y(`loadScript:resolved inactive=${Te()} ns=${!!b} buttons=${!!b?.Buttons}`),Te())return;if(!b?.Buttons){y("FAIL: namespace missing Buttons factory"),p("PayPal SDK did not expose the Buttons factory.");return}W.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let O=async be=>{if(Te()||Ie.current!==ae)return;let Se=be.subscriptionID??be.orderID??"",pe=Se?Dt.current.get(Se):We.current.get(ae);if(!(!pe||!Qt(pe.generation))&&Nt(pe.generation)){Dt.current.delete(Se),We.current.delete(pe.surfaceKey),en();try{if(M(!0),ft(()=>He.current?.(null)),!Se)throw new Tn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await j({id:Se,isPaypal:!0},pe)}catch(ze){q(ze instanceof Error?ze.message:"PayPal capture failed.")}finally{Te()||M(!1)}}},Pe=b.Buttons({style:{layout:"horizontal",height:jr,tagline:!1},onClick:async(be,Se)=>{if(Te()){await Se.reject();return}On();let pe=ke.current,ze={};if(pe)try{let It=await pe("paypal");if(Te()){await Se.reject();return}if(!It.proceed){ot.current=null,We.current.delete(ae),await Se.reject();return}ze={sessionId:It.sessionId,accountPatch:It.accountPatch,nonce:It.nonce}}catch(It){y(`onClick:runBeforeButtonClick rejected msg=${(It instanceof Error?It.message:String(It)).slice(0,120)}`),ot.current=null,We.current.delete(ae),await Se.reject();return}ft(()=>bt.current?.("paypal"));let dt={generation:Lt(),surfaceKey:ae,...ze};ot.current=dt,We.current.set(ae,dt),await Se.resolve(),W.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),W.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),it=W.startTiming()},createOrder:c?void 0:Q?()=>Be(Q).then(pn):()=>X("Failed to create PayPal order.").then(pn),createSubscription:c?Q?()=>Be(Q).then(pn):()=>X("Failed to create PayPal subscription.").then(pn):void 0,onApprove:O,onCancel:()=>{if(Te())return;let be=We.current.get(ae)??ot.current;be&&We.current.delete(be.surfaceKey),ot.current=null,en(),W.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),he.current=!0,Yt({generation:be?.generation,remount:!0,focus:!1})},onError:be=>{if(Te()||Ie.current!==ae)return;let Se=be instanceof Error?be.message:"PayPal failed to render.";if(y(`onError rendered=${Gt} msg=${Se.slice(0,120)}`),Gt){let pe=We.current.get(ae)??ot.current;if(pe&&!Qt(pe.generation)||!pe&&vt.current===Ge.current)return;if(U(Se)){Nt(pe?.generation);return}en();let ze=Se.toLowerCase();W.error({errorCode:ze.includes("popup")&&ze.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),hr(be)&&Je(be,pe),pe&&We.current.delete(pe.surfaceKey),ot.current=null,Yt({generation:pe?.generation,remount:!0,showRetry:!0,focus:!0}),Nn(be,{code:"paypal_runtime_failed"});return}p(Se)}}),Me=Pe.isEligible();if(y(`isEligible=${Me}`),W.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Me){ne(!1),p("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Bt=Pe,z&&y(`container:dims ${fn(Pt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),z&&typeof MutationObserver<"u"&&(Vt=new MutationObserver(be=>{if(!Te()){for(let Se of be)if(Se.type==="childList")Se.addedNodes.forEach(pe=>{if(!(pe instanceof Element))return;let ze=pe.tagName.toLowerCase(),hn=(pe.getAttribute("title")??"").slice(0,40),dt=ze==="iframe"?` ${gn(pe)}`:"";y(`child+ ${ze}${hn?` title="${hn}"`:""}${dt} dims=${fn(pe)}`)});else if(Se.type==="attributes"&&Se.target instanceof Element){let pe=Se.target;if(pe.tagName.toLowerCase()!=="iframe")continue;let ze=Se.attributeName;(ze==="src"||ze==="srcdoc")&&y(`attr~ iframe ${ze}=${ze==="srcdoc"?`[${(pe.getAttribute("srcdoc")??"").length}ch]`:Rn(pe.getAttribute("src"))} dims=${fn(pe)}`)}}}),Vt.observe(Pt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Z=be=>{if(Te()||Gt)return;let Se=Pt.querySelectorAll("iframe"),pe=typeof document<"u"&&"hasStorageAccess"in document;y(`watchdog:${be} container=${fn(Pt)} children=${Pt.childElementCount} iframes=${Se.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${pe} paypalNetRequests=${$t.value}`),Se.forEach((ze,hn)=>{let dt=(ze.getAttribute("title")??"").slice(0,40);y(` iframe[${hn}] ${fn(ze)}${dt?` title="${dt}"`:""} ${gn(ze)}`);let It=Ht(ze);It&&y(` ${It}`)}),Ye.length===0&&y(" (no PayPal/zoid window errors captured)")};z&&(tn.push(setTimeout(()=>Z("3s"),3e3)),tn.push(setTimeout(()=>Z("8s"),8e3)),tn.push(setTimeout(()=>Z("15s"),15e3))),y("render:start"),tn.push(setTimeout(()=>{Te()||Gt||(y("watchdog:11s retryable render timeout"),p("PayPal Buttons render did not settle within 11000ms.",!0))},Bi)),Pe.render(Pt).then(()=>{if(y(`render:resolved inactive=${Te()}`),T(),Te()){pt();return}Gt=!0,ne(!0),ve(!1),h.current?.("ready"),W.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"provider_ready",durationMs:W.elapsed(le.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(be=>{let Se=be instanceof Error?be.message:"PayPal failed to render.";y(`render:rejected msg=${Se.slice(0,120)}`),T(),p(Se)})}).catch(b=>{let O=b instanceof Error?b.message:"PayPal SDK failed to load.";y(`loadScript:rejected msg=${O.slice(0,120)}`),p(O)})},0);return()=>{ct=!0,clearTimeout(st),yn&&clearTimeout(yn),T(),pt()}},[I,G,o,u,s,c,e,Q,ce,W]);let at=z?(0,an.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ue?"#fef2f2":"#f3f4f6",border:`1px solid ${Ue?"#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=${Ue})`,et.length===0?`
|
|
6
|
+
`})]})})}var ua=require("@flopay/shared");function pa(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function ho(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ma(e,t){let n=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],l=n.reduce((s,u)=>s+(u.overrideAmount??u.totalAmount??0),0),o=e.currency??n.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(l*100),currency:o,status:"open",customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((s,u)=>({uuid:`synthetic-${s.type??"item"}-${u}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??o,metadata:s.metadata??null}))}}function Po(e,t){return t?{...e,...t}:e}function _t(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 xi=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Fn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:l}of xi)if(n.test(t))return l;return e}function Ur(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function ya(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function fa(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function $r(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var qr="flopay_recent_completion_";function Qn(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(qr+e,JSON.stringify(t))}catch{}}function ga(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(qr+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(qr+e),!1):!0}catch{return!1}}function ha(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"),va=require("@paypal/paypal-js"),jr=require("@flopay/js"),Bn=require("@flopay/shared");function yt(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 Ti(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Vn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Tn(e){if(typeof e!="object"||e===null)return;let t=e;return Vn(t.code)??Vn(t.type)??Vn(t.name)}function er(e){if(!(typeof e!="object"||e===null))return Vn(e.decline_code)}function Pr(e){return typeof e!="object"||e===null?!1:Vn(e.type)?.toLowerCase()==="card_error"||er(e)!==void 0}function Dn(e){let t=Ti(e)?.toLowerCase()??"",l=`${Tn(e)?.toLowerCase()??""} ${t}`;return l.includes("popup")&&l.includes("block")}var sn=require("react/jsx-runtime"),Vr=45,Bi=1e3,Mi=11e3,Ai=["https://www.paypal.com","https://www.sandbox.paypal.com"],Pa="We couldn't open PayPal. Try again or choose another payment method.",Fi={width:"100%",minHeight:Vr,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function ba(e){return e.includes("No ack for postMessage init()")&&Ai.some(t=>e.includes(t))&&e.includes("10000ms")}function Di(e){return e?`${Pa} Allow pop-ups for this site, then try again.`:Pa}function Ca({sessionId:e,nonce:t,billingApiUrl:n,email:l,clientId:o,environment:s,currency:u,isSubscription:c,onTokenizedBody:R,onComplete:N,onErrorChange:m,onDecline:_,onTechnicalFailure:w,isProcessing:M=!1,onLoadStateChange:d,onInitializationStateChange:g,allowAutomaticRetry:I=!0,onButtonClick:F,runBeforeButtonClick:P,session:K,existingOrderId:Q,telemetry:pe,telemetryContext:se,debug:U=!1}){let te=an(),W=(0,T.useMemo)(()=>{if(te)return null;let f=Dr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Bn.SDK_VERSION,enabled:pe!==!1});return f.setCheckoutContext(se??{}),f.beginCheckout(se??{}),f},[n,te,pe,se?.checkoutMode,se?.layout]),me=(0,T.useMemo)(()=>Tt(te),[te]);(0,T.useEffect)(()=>()=>{W&&W.flush().catch(()=>{}).finally(()=>W.destroy())},[W]);let Y=(0,T.useMemo)(()=>({error:f=>{me?me.error(f):W?.error(f)},log:f=>{me?me.log(f):W?.log(f)},performance:f=>{me?me.performance(f):W?.performance(f)},terminal:f=>{me?me.terminal(f):W?.terminal(f)},startTiming:()=>me?.now()??W?.now()??0,elapsed:f=>me?.elapsed(f)??Math.max(0,(W?.now()??f)-f)}),[me,W]),G=(0,T.useRef)(null),le=(0,T.useRef)(0),Fe=(0,T.useRef)(null),be=(0,T.useRef)(!1),[he,ne]=(0,T.useState)(!1),[ye,ve]=(0,T.useState)(!1),[ce,Ne]=(0,T.useState)(0),Re=(0,T.useRef)(0),[Se,E]=(0,T.useState)(!1),oe=(0,T.useRef)(!1),de=(0,T.useRef)(!1),[ze,Oe]=(0,T.useState)(!1),[ee,A]=(0,T.useState)(!1),J=(0,T.useMemo)(()=>n.replace(/\/+$/,""),[n]),ue=(0,T.useMemo)(()=>JSON.stringify([J,o,u,s??"",c,e,Q??""]),[J,o,u,s,Q,c,e]),Ie=(0,T.useRef)(ue),ft=Ie.current!==ue,[Qe,Ze]=(0,T.useState)([]),y=f=>{U&&Ze(xe=>[...xe,`${new Date().toISOString().slice(11,23)} ${f}`])},qe=(0,T.useRef)(R),Ue=(0,T.useRef)(N),Ve=(0,T.useRef)(m),He=(0,T.useRef)(_),Ht=(0,T.useRef)(w),Pt=(0,T.useRef)(F),wt=(0,T.useRef)(d),h=(0,T.useRef)(g),we=(0,T.useRef)(P),je=(0,T.useRef)(K),lt=(0,T.useRef)(l),nt=(0,T.useRef)(t),rt=(0,T.useRef)(null),Ye=(0,T.useRef)(0),Ce=(0,T.useRef)(null),bt=(0,T.useRef)(null),Ke=(0,T.useRef)(new Map),At=(0,T.useRef)(new Map),kt=(0,T.useRef)(!1);(0,T.useEffect)(()=>(kt.current=!0,()=>{kt.current=!1}),[]),(0,T.useEffect)(()=>{qe.current=R},[R]),(0,T.useEffect)(()=>{Ue.current=N},[N]),(0,T.useEffect)(()=>{Ve.current=m},[m]),(0,T.useEffect)(()=>{He.current=_},[_]),(0,T.useEffect)(()=>{Ht.current=w},[w]),(0,T.useEffect)(()=>{Pt.current=F},[F]),(0,T.useEffect)(()=>{wt.current=d},[d]),(0,T.useEffect)(()=>{h.current=g},[g]),(0,T.useEffect)(()=>{we.current=P},[P]),(0,T.useEffect)(()=>{je.current=K},[K]),(0,T.useEffect)(()=>{lt.current=l},[l]),(0,T.useEffect)(()=>{nt.current=t},[t]),(0,T.useEffect)(()=>{Re.current=ce},[ce]),(0,T.useEffect)(()=>{Se&&Fe.current?.focus()},[Se,ce]);let pn=(0,T.useCallback)(()=>{window.setTimeout(()=>{Fe.current?.focus()},0)},[]),wn=(0,T.useCallback)(()=>{ne(!1),Ne(f=>f+1)},[]),kn=(0,T.useCallback)(()=>{E(!1),(G.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??G.current)?.focus?.()},[]);(0,T.useEffect)(()=>{!he||!be.current||(be.current=!1,kn())},[kn,he,ce]);let Nn=(0,T.useCallback)((f,xe)=>{let ct=Ht.current;if(ct){ct("paypal",f,xe);return}Ve.current?.(Di(xe?.popupBlocked??Dn(f)))},[]),gt=()=>{Ce.current?.timer&&(clearTimeout(Ce.current.timer),Ce.current.timer=null)},Ft=()=>{gt();let f=Ye.current+1;return Ye.current=f,bt.current=null,Ce.current={generation:f,timer:null,yieldedControl:!1},E(!1),f},Dt=f=>f!==void 0&&Ce.current?.generation!==f?!1:(gt(),Ce.current=null,bt.current=null,!0),Kt=f=>{let xe=f?.generation??Ce.current?.generation??Ye.current;(!f?.generation||Ce.current?.generation===xe)&&(gt(),Ce.current=null),bt.current=xe,f?.showRetry&&E(!0),f?.remount&&wn(),f?.focus!==!1&&pn()},Qt=f=>Ce.current?.generation===f&&bt.current!==f,mn=f=>{typeof document<"u"&&document.visibilityState!=="visible"||(gt(),f.timer=setTimeout(()=>{Ce.current?.generation===f.generation&&(Ce.current=null,bt.current=f.generation,Nn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),E(!0),wn(),pn())},600))},X=()=>{let f=Ce.current;f?.yieldedControl&&mn(f)},Mn=()=>{let f=Ce.current;f&&(f.yieldedControl=!0,gt())},yn=f=>{let xe=rt.current;return xe&&At.current.set(f,xe),f};(0,T.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?X():Mn()};return document.addEventListener("visibilitychange",f),window.addEventListener("focus",X),window.addEventListener("blur",Mn),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("focus",X),window.removeEventListener("blur",Mn),gt()}},[]),(0,T.useEffect)(()=>{Ie.current!==ue&&(Ie.current=ue,oe.current=!1,de.current=!1,ne(!1),ve(!1),Oe(!1),h.current?.("loading"))},[ue]),(0,T.useEffect)(()=>{yt(()=>wt.current?.(he&&!ze))},[he,ze]);let Lt=(0,Bn.normalizeGatewayEnvironment)(s);(0,T.useEffect)(()=>{let f=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",xe=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(y(`mount clientId=${f} env=${s??"(unset)"}\u2192${Lt??"live"} ccy=${u} sub=${c}`),y(`ua=${xe.slice(0,80)}${xe.length>80?"\u2026":""}`),!o){y("FAIL: clientId empty \u2014 gateway misconfigured"),Oe(!0),Y.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!G.current){y("FAIL: containerRef not attached");return}le.current=Y.startTiming(),Y.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ct=!1,Rn=!1,Te=()=>ct||Rn,An,fn=!1,On=()=>{An=(0,Bn.generateIdempotencyKey)(),An||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),fn=!0},gn=null,Nt=!1,xt=null,ke=!1,ut=()=>{!xt||ke||(ke=!0,xt.close().catch(()=>{}))},at=null,en=()=>{at!==null&&(Y.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),Y.performance({stage:"overlay_return",durationMs:Y.elapsed(at),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),at=null)},Wt=!1,ht=G.current,qt=null,vt=null,tn=[],hn=O=>{if(!O||typeof O.getBoundingClientRect!="function")return"(no rect)";let b=O.getBoundingClientRect();return`${Math.round(b.width)}\xD7${Math.round(b.height)}`},In=O=>{if(!O)return"(empty)";try{let b=new URL(O,typeof window<"u"?window.location.href:"https://localhost"),z=b.pathname.toLowerCase();return z.includes("checkcaptcha")||z.includes("captcha")?`CAPTCHA(${b.host}${z})`:z.includes("risk")||z.includes("challenge")?`RISK(${b.host}${z})`:z.includes("smart/buttons")?`smart-buttons(${b.host})`:`${b.host}${z}`.slice(0,100)}catch{return O.slice(0,80)}},Pn=O=>{let b=O.getAttribute("src"),z=O.getAttribute("srcdoc"),Pe=O.getAttribute("name"),Me=O.getAttribute("sandbox"),$e=[];return b&&$e.push(`src=${In(b)}`),z&&$e.push(`srcdoc[${z.length}ch]`),!b&&!z&&$e.push("src=(empty) srcdoc=(empty)"),Pe&&$e.push(`name=${Pe.slice(0,40)}`),Me!==null&&$e.push(`sandbox="${Me.slice(0,40)}"`),$e.join(" ")},jt=O=>{if(!(O instanceof HTMLIFrameElement))return"";try{let b=O.contentDocument;if(!b)return"cd=null";let z=b.body?.children.length??0,Pe=b.body?.innerHTML.length??0,Me=b.head?.innerHTML.length??0;return`cd=same-origin readyState=${b.readyState} body[${z}children,${Pe}ch] head[${Me}ch]`}catch(b){return`cd=cross-origin(${b.message.slice(0,30)})`}},We=[],Vt=O=>{if(Te())return;let b=O.message??String(O.error??"(no message)");b&&(b.toLowerCase().includes("paypal")||b.toLowerCase().includes("zoid")||b.toLowerCase().includes("postrobot")||b.toLowerCase().includes("storage"))&&(y(`window:error ${b.slice(0,140)}`),We.push(b))},Ot=O=>{if(Te())return;let b=O.reason instanceof Error?O.reason.message:String(O.reason??"(no reason)");b&&(b.toLowerCase().includes("paypal")||b.toLowerCase().includes("zoid")||b.toLowerCase().includes("postrobot")||b.toLowerCase().includes("storage"))&&(y(`window:rejection ${b.slice(0,140)}`),We.push(b))};U&&typeof window<"u"&&(window.addEventListener("error",Vt),window.addEventListener("unhandledrejection",Ot));let zt={value:0};if(U&&typeof PerformanceObserver<"u")try{vt=new PerformanceObserver(O=>{if(!Te())for(let b of O.getEntries()){if(!b.name.toLowerCase().includes("paypal"))continue;zt.value+=1;let z=Math.round(b.duration);y(`net ${z}ms ${b.name.slice(0,90)}`)}}),vt.observe({type:"resource",buffered:!0})}catch{}let B=()=>{for(qt?.disconnect(),qt=null,vt?.disconnect(),vt=null;tn.length;)clearTimeout(tn.pop());U&&typeof window<"u"&&(window.removeEventListener("error",Vt),window.removeEventListener("unhandledrejection",Ot))},$=O=>{if(!O)return!1;let b=O.toLowerCase();return b.includes("zoid destroyed")||b.includes("destroyed all components")||b.includes("window closed")||b.includes("detected container element removed")},j=O=>{if(Te()||$(O))return;let b=Fn(O)??O;yt(()=>Ve.current?.(b))},D=O=>{ct||(Oe(!0),O.includes("paypal_ineligible")||Y.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal load/render failure:",O))},p=(O,b=!1)=>{if(ct)return;let z=oe.current||!I;if(Nt)return;Nt=!0,Rn=!0,B(),ut();let Pe=b||ba(O);if(Pe&&I&&!oe.current){oe.current=!0,ne(!1),A(!1),ve(!0),h.current?.("retrying"),gn=setTimeout(()=>{ct||Ne(Me=>Me+1)},Bi);return}if(Pe||z){if(ne(!1),A(!1),ve(!1),Oe(!0),h.current?.("exhausted"),!de.current){de.current=!0;let Me=ba(O)?"paypal_init_timeout":b?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",Me)}return}D(O)};Oe(!1);let H=async(O,b=rt.current)=>{if(Te())return;let z=b?.sessionId??e;if(qe.current){await qe.current(O,{sessionId:z,accountPatch:b?.accountPatch,nonce:b?.nonce});return}let Pe=Y.startTiming();Y.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Me=()=>{Y.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Y.performance({stage:"processing",durationMs:Y.elapsed(Pe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let $e=je.current,nn=b?.accountPatch?.email??lt.current,x=b?.accountPatch?.userId??$e?.customer?.id??$e?.accountData?.userId??"",fe=await new jr.PaymentAPI(J,{telemetry:!1}).processPayment(x,{sessionId:z,nonce:b?.nonce??nt.current,tokenizedData:O,accountData:{userId:x,email:nn??$e?.customer?.email??"",firstName:b?.accountPatch?.firstName??$e?.customer?.firstName??$e?.accountData?.firstName??"",lastName:b?.accountPatch?.lastName??$e?.customer?.lastName??$e?.accountData?.lastName??"",country:b?.accountPatch?.country??$e?.customer?.country??$e?.accountData?.country??void 0,zip:b?.accountPatch?.zip??$e?.customer?.zip??$e?.accountData?.zip??void 0}});if(fe.ok){if(Rn||ct&&kt.current)return;Me(),Y.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),yt(()=>Ue.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Te())return;let Ee=await fe.json().catch(()=>null),Yt=Ee?.message??"PayPal payment failed.",Gt=Fn(Yt)??Yt;Me(),typeof Ee?.declineCode=="string"?Y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Y.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:fe.status>=500?"5xx":fe.status>=400?"4xx":fe.status>=300?"3xx":"unknown"}),j(Gt),yt(()=>He.current?.(_t("paypal",Gt,{code:Ee?.code,declineCode:Ee?.declineCode})));return}catch($e){if(Te())return;Me(),Y.error({errorCode:"NETWORK_REQUEST_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let nn=$e instanceof Error?$e.message:"PayPal payment failed.",x=Fn(nn)??nn;j(x),yt(()=>He.current?.(_t("paypal",x)));return}},v=()=>new Bn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Be=O=>Te()?Promise.reject(v()):Promise.resolve(O),Z=async O=>{if(Te())throw v();fn||On();let b=rt.current,z=b?.sessionId??e,Pe=b?.nonce??nt.current;Y.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Me=await new jr.PaymentAPI(J,{telemetry:!1}).createSessionIntent(z,Pe??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:An});if(Te())throw v();if(Me.provider!=="paypal")throw new Error(O);return Y.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Me.providerObjectId},Ge=(O,b)=>{let z=b?.nonce??nt.current;if(!z)return;let Pe=b?.sessionId??e,Me=er(O)??Tn(O)??"provider_declined";new jr.PaymentAPI(J,{telemetry:!1}).reportSessionIntentDecline(Pe,z,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Me}).catch(()=>{})},ae=ce;y("loadScript:scheduled (deferred 1 tick)");let Ut=null,it=setTimeout(()=>{if(ct){y("loadScript:skipped (cancelled before defer ran)");return}y("loadScript:start");let O=Lt==="live"?"production":Lt;Ut=(0,va.loadScript)({clientId:o,currency:u,intent:c?"subscription":"capture",vault:c?!0:void 0,...O?{environment:O}:{},...O==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Ut.then(b=>{if(y(`loadScript:resolved inactive=${Te()} ns=${!!b} buttons=${!!b?.Buttons}`),Te())return;if(!b?.Buttons){y("FAIL: namespace missing Buttons factory"),p("PayPal SDK did not expose the Buttons factory.");return}Y.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let z=async x=>{if(Te()||Re.current!==ae)return;let ge=x.subscriptionID??x.orderID??"",fe=ge?At.current.get(ge):Ke.current.get(ae);if(!(!fe||!Qt(fe.generation))&&Dt(fe.generation)){At.current.delete(ge),Ke.current.delete(fe.surfaceKey),en();try{if(A(!0),yt(()=>Ve.current?.(null)),!ge)throw new Bn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await H({id:ge,isPaypal:!0},fe)}catch(Ee){j(Ee instanceof Error?Ee.message:"PayPal capture failed.")}finally{Te()||A(!1)}}},Pe=b.Buttons({style:{layout:"horizontal",height:Vr,tagline:!1},onClick:async(x,ge)=>{if(Te()){await ge.reject();return}On();let fe=we.current,Ee={};if(fe)try{let st=await fe("paypal");if(Te()){await ge.reject();return}if(!st.proceed){rt.current=null,Ke.current.delete(ae),await ge.reject();return}Ee={sessionId:st.sessionId,accountPatch:st.accountPatch,nonce:st.nonce}}catch(st){y(`onClick:runBeforeButtonClick rejected msg=${(st instanceof Error?st.message:String(st)).slice(0,120)}`),rt.current=null,Ke.current.delete(ae),await ge.reject();return}yt(()=>Pt.current?.("paypal"));let Gt={generation:Ft(),surfaceKey:ae,...Ee};rt.current=Gt,Ke.current.set(ae,Gt),await ge.resolve(),Y.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Y.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Y.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),at=Y.startTiming()},createOrder:c?void 0:Q?()=>Be(Q).then(yn):()=>Z("Failed to create PayPal order.").then(yn),createSubscription:c?Q?()=>Be(Q).then(yn):()=>Z("Failed to create PayPal subscription.").then(yn):void 0,onApprove:z,onCancel:()=>{if(Te())return;let x=Ke.current.get(ae)??rt.current;x&&Ke.current.delete(x.surfaceKey),rt.current=null,en(),Y.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be.current=!0,Kt({generation:x?.generation,remount:!0,focus:!1})},onError:x=>{if(Te()||Re.current!==ae)return;let ge=x instanceof Error?x.message:"PayPal failed to render.";if(y(`onError rendered=${Wt} msg=${ge.slice(0,120)}`),Wt){let fe=Ke.current.get(ae)??rt.current;if(fe&&!Qt(fe.generation)||!fe&&bt.current===Ye.current)return;if($(ge)){Dt(fe?.generation);return}en();let Ee=ge.toLowerCase();Y.error({errorCode:Ee.includes("popup")&&Ee.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),Pr(x)&&Ge(x,fe),fe&&Ke.current.delete(fe.surfaceKey),rt.current=null,Kt({generation:fe?.generation,remount:!0,showRetry:!0,focus:!0}),Nn(x,{code:"paypal_runtime_failed"});return}p(ge)}}),Me=Pe.isEligible();if(y(`isEligible=${Me}`),Y.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Me){ne(!1),p("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}xt=Pe,U&&y(`container:dims ${hn(ht)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),U&&typeof MutationObserver<"u"&&(qt=new MutationObserver(x=>{if(!Te()){for(let ge of x)if(ge.type==="childList")ge.addedNodes.forEach(fe=>{if(!(fe instanceof Element))return;let Ee=fe.tagName.toLowerCase(),Yt=(fe.getAttribute("title")??"").slice(0,40),Gt=Ee==="iframe"?` ${Pn(fe)}`:"";y(`child+ ${Ee}${Yt?` title="${Yt}"`:""}${Gt} dims=${hn(fe)}`)});else if(ge.type==="attributes"&&ge.target instanceof Element){let fe=ge.target;if(fe.tagName.toLowerCase()!=="iframe")continue;let Ee=ge.attributeName;(Ee==="src"||Ee==="srcdoc")&&y(`attr~ iframe ${Ee}=${Ee==="srcdoc"?`[${(fe.getAttribute("srcdoc")??"").length}ch]`:In(fe.getAttribute("src"))} dims=${hn(fe)}`)}}}),qt.observe(ht,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let nn=x=>{if(Te()||Wt)return;let ge=ht.querySelectorAll("iframe"),fe=typeof document<"u"&&"hasStorageAccess"in document;y(`watchdog:${x} container=${hn(ht)} children=${ht.childElementCount} iframes=${ge.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${fe} paypalNetRequests=${zt.value}`),ge.forEach((Ee,Yt)=>{let Gt=(Ee.getAttribute("title")??"").slice(0,40);y(` iframe[${Yt}] ${hn(Ee)}${Gt?` title="${Gt}"`:""} ${Pn(Ee)}`);let st=jt(Ee);st&&y(` ${st}`)}),We.length===0&&y(" (no PayPal/zoid window errors captured)")};U&&(tn.push(setTimeout(()=>nn("3s"),3e3)),tn.push(setTimeout(()=>nn("8s"),8e3)),tn.push(setTimeout(()=>nn("15s"),15e3))),y("render:start"),tn.push(setTimeout(()=>{Te()||Wt||(y("watchdog:11s retryable render timeout"),p("PayPal Buttons render did not settle within 11000ms.",!0))},Mi)),Pe.render(ht).then(()=>{if(y(`render:resolved inactive=${Te()}`),B(),Te()){ut();return}Wt=!0,ne(!0),ve(!1),h.current?.("ready"),Y.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),Y.performance({stage:"provider_ready",durationMs:Y.elapsed(le.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(x=>{let ge=x instanceof Error?x.message:"PayPal failed to render.";y(`render:rejected msg=${ge.slice(0,120)}`),B(),p(ge)})}).catch(b=>{let z=b instanceof Error?b.message:"PayPal SDK failed to load.";y(`loadScript:rejected msg=${z.slice(0,120)}`),p(z)})},0);return()=>{ct=!0,clearTimeout(it),gn&&clearTimeout(gn),B(),ut()}},[I,J,o,u,s,c,e,Q,ce,Y]);let ot=U?(0,sn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ze?"#fef2f2":"#f3f4f6",border:`1px solid ${ze?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${he} failed=${ze})`,Qe.length===0?`
|
|
7
7
|
(waiting for first lifecycle event\u2026)`:`
|
|
8
|
-
${
|
|
9
|
-
`)}`]}):null;return
|
|
8
|
+
${Qe.join(`
|
|
9
|
+
`)}`]}):null;return ze&&!ft?U?(0,sn.jsx)("div",{children:ot}):null:(0,sn.jsxs)("div",{children:[ot,(0,sn.jsxs)("div",{"aria-hidden":ye?!0:void 0,style:ye?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Vr},children:[!he&&!ye&&(0,sn.jsx)("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),(0,sn.jsx)("div",{ref:G,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:Vr,display:"flex",opacity:he?1:0},"aria-busy":ee||M},ce)]},ce),Se&&(0,sn.jsx)("button",{ref:Fe,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:kn,style:Fi,children:"Try PayPal again"})]})}function br(e){return(0,sn.jsx)(Ca,{...e})}function Sa(e){return(0,sn.jsx)(Ca,{...e})}var Bt=require("@flopay/shared"),i=require("react/jsx-runtime"),Cn="flopay_stripe_resume",wa="flopay_wallet_resume",vr="flopay_paypal_resume";async function Wr({billingApiUrl:e,sessionId:t,nonce:n,request:l}){if(!(!t||!n))try{await new ln.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,l)}catch{}}function Li(e){return e instanceof Bt.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function vo(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Hr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let l=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),s=Math.round((l>>16&255)*o),u=Math.round((l>>8&255)*o),c=Math.round((l&255)*o);return`#${(1<<24|s<<16|u<<8|c).toString(16).slice(1)}`}var Ni=`
|
|
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 @@ ${et.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
|
-
`,Hr=44;function So(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 Ni={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Ta={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 Oi(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function wa(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ba(e){return e==="paypal"?"PayPal":(0,k.getStripeMethodDisplayName)(e)}function zi(e,t){let n=`We couldn't open ${Ba(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ma(e){let t=(0,r.useRef)(0),n=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useCallback)((d=l.current)=>{let g=d;g?.timer&&(clearTimeout(g.timer),g.timer=null)},[]),s=(0,r.useCallback)((d,g)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(d),d.timer=setTimeout(()=>{d.timer=null,l.current?.generation===d.generation&&(l.current=null,n.current=d.generation,e(d.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},g))},[o,e]),u=(0,r.useCallback)(d=>{d.yieldedControl&&s(d,600)},[s]),c=(0,r.useCallback)(d=>{o();let g=t.current+1;t.current=g,n.current=null;let I={generation:g,method:d,timer:null,yieldedControl:!1};return l.current=I,g},[o]),R=(0,r.useCallback)(d=>{let g=l.current;return typeof d=="number"&&g?.generation!==d?!1:(o(g),l.current=null,(typeof d!="number"||n.current===d)&&(n.current=null),!0)},[o]),L=(0,r.useCallback)(d=>{let g=l.current,I=d??g?.generation??t.current;(!d||g?.generation===d)&&(o(g),l.current=null),n.current=I},[o]),m=(0,r.useCallback)(d=>n.current===(d??t.current),[]),_=(0,r.useCallback)(d=>l.current?.generation===d&&n.current!==d,[]),w=(0,r.useCallback)(()=>{let d=l.current;d&&u(d)},[u]),B=(0,r.useCallback)(()=>{let d=l.current;d&&(d.yieldedControl=!0,o(d))},[o]);return(0,r.useEffect)(()=>{let d=()=>{document.visibilityState==="visible"?w():B()},g=()=>{B()};return document.addEventListener("visibilitychange",d),window.addEventListener("blur",g),window.addEventListener("focus",w),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("blur",g),window.removeEventListener("focus",w),o()}},[o,B,w]),{startAttempt:c,finishAttempt:R,invalidateAttempt:L,isAttemptInvalidated:m,isAttemptCurrent:_}}function Ui(e){let t=(0,k.getPostalCodeExample)(e);return`Enter a valid ${(0,k.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function $i(e,t,n){let l=(0,k.isPostalCodeSupported)(e),o=t.trim(),s=n&&l,u=s&&!o,c=s&&!!o&&!(0,k.isValidPostalCode)(e,o);return{visible:n,supported:l,required:s,empty:u,malformed:c}}function ka(e,t){return t instanceof At.FloPayError?t:new At.FloPayError(t instanceof Error?t.message:`${Oi(e)} before-click hook failed.`,"validation_error")}function vo(){return(0,i.jsx)("style",{children:Li})}function qi(e){return typeof e=="number"?`${e}px`:e}function Ra(e){if(typeof e=="number"||typeof e=="string")return e}function Aa(e,t){let n=e.availablePaymentMethods;return n&&t.some(l=>n[l])?"ready":"unavailable"}function Fa({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 Ia(e){return e!=="unavailable"&&e!=="load_error"}function Wr(e){return(0,i.jsx)(Vi,{...e})}function Ea({sessionId:e,nonce:t,email:n,billingApiUrl:l,onTokenizedBody:o,onErrorChange:s,isProcessing:u=!1,onButtonClick:c,onDecline:R,onTechnicalFailure:L,runBeforeButtonClick:m,onLoadStateChange:_,placeholderBorderRadius:w}){let B=on(),d=(0,ut.useStripe)(),g=(0,ut.useElements)(),[I,A]=(0,r.useState)("loading");(0,r.useEffect)(()=>{_?.(I)},[I,_]);let[P,H]=(0,r.useState)(!1),Q=(0,r.useRef)(!1),me=(0,r.useRef)(null),se=(0,r.useRef)(null),[z,te]=(0,r.useState)(0),[K,ye]=(0,r.useState)(!1),W=(0,r.useRef)(!1),Y=(0,r.useRef)(new Map),{startAttempt:le,finishAttempt:Fe,invalidateAttempt:he,isAttemptInvalidated:ge,isAttemptCurrent:ne}=Ma((E,oe,de)=>{L?.(E,oe,{...de,popupBlocked:de?.popupBlocked??Dn(oe)}),ye(!0),te(Ue=>Ue+1)});(0,r.useEffect)(()=>{K&&se.current?.focus()},[K,z]);let fe=(0,r.useCallback)(()=>{te(E=>E+1)},[]),ve=(0,r.useCallback)((E,oe,de)=>{he(de),L?.("paypal",E,{code:oe,popupBlocked:Dn(E)}),ye(!0),fe()},[he,L,fe]),ce=(0,r.useCallback)(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{W.current&&(W.current=!1,ce())},[ce,z]);let Ne=(0,r.useCallback)(()=>{ye(!1),s?.(null),ce()},[ce,s]);(0,r.useEffect)(()=>{if(!d||Q.current)return;let E=new URLSearchParams(window.location.search),oe=E.get("payment_intent"),de=E.get("payment_intent_client_secret"),Ue=E.get("redirect_status");if(!oe||!de)return;Q.current=!0;let Oe;try{let M=localStorage.getItem(br);if(M){let G=JSON.parse(M);G.clientSecret===de&&(Oe={...G.accountPatch?{accountPatch:G.accountPatch}:{},...G.sessionId?{sessionId:G.sessionId}:{},...G.nonce?{nonce:G.nonce}:{}})}}catch{}try{localStorage.removeItem(br)}catch{}let ee=new URL(window.location.href);ee.searchParams.delete("payment_intent"),ee.searchParams.delete("payment_intent_client_secret"),ee.searchParams.delete("redirect_status"),window.history.replaceState({},"",ee.toString()),(async()=>{try{if(H(!0),Ue==="failed"){let ue="PayPal payment was declined. Please try again.";s?.(ue),R?.(Tt("paypal",ue));return}let{paymentIntent:M,error:G}=await d.retrievePaymentIntent(de);if(G){s?.(G.message??"Failed to retrieve PayPal payment status.");return}if(M&&(M.status==="requires_capture"||M.status==="succeeded")){let ue=typeof M.payment_method=="string"?M.payment_method:M.payment_method?.id;o({id:ue??M.id,type:"card",threeDSecureActionResultTokenId:M.id,isPaypal:!0},Oe)}else{let ue="PayPal payment was not completed. Please try again.";s?.(ue),R?.(Tt("paypal",ue))}}catch(M){s?.(M instanceof Error?M.message:"Failed to complete PayPal payment.")}finally{H(!1)}})()},[d,o,s,R]);let Ie=(0,r.useCallback)(async E=>{if(u||P){E.reject();return}let oe=m?await m("paypal"):{proceed:!0};if(!oe.proceed){Y.current.delete(z),E.reject();return}let de=le("paypal");Y.current.set(z,{generation:de,accountPatch:oe.accountPatch,sessionId:oe.sessionId,nonce:oe.nonce}),ye(!1),c?.("paypal"),E.resolve()},[Y,u,c,m,le,P,z]),we=(0,r.useCallback)(async E=>{if(!d||!g)return;let oe=Y.current.get(z);if(oe&&!ne(oe.generation)){Y.current.delete(z);return}if(!oe&&ge()||oe&&!Fe(oe.generation))return;oe||Fe();let de=oe??null;if(Y.current.delete(z),!de&&m){let M=await m("paypal");if(!M.proceed){E.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}de={accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}}let Ue=de?.sessionId??e,Oe=de?.nonce??t,ee=de?.accountPatch?.email??n;try{if(H(!0),s?.(null),!Ue||!ee)throw new Error("Missing sessionId or email for PayPal payment");let M=d.createPaymentMethod,{error:G,paymentMethod:ue}=await M({type:"paypal"});if(G){ve(G,"stripe_paypal_create_payment_method_failed",oe?.generation),E.paymentFailed({reason:"fail"});return}let Ee=await new Bn.PaymentAPI(l).createSessionIntent(Ue,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 gt=Ee.clientSecret,et={return_url:window.location.href};if(ue?.id&&(et.payment_method=ue.id),typeof window<"u")try{localStorage.setItem(br,JSON.stringify({clientSecret:gt,sessionId:Ue,nonce:Oe,accountPatch:de?.accountPatch}))}catch{}let{error:Qe,paymentIntent:y}=await d.confirmPayment({clientSecret:gt,confirmParams:et,redirect:"if_required"});if(Qe){if(typeof window<"u")try{localStorage.removeItem(br)}catch{}if(hr(Qe)){let $e=Qe.message??"Your payment was declined.";s?.($e),R?.(Tt("paypal",$e,{code:xn(Qe),declineCode:er(Qe)})),await Kr({billingApiUrl:l,sessionId:Ue,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:xn(Qe)??"provider_declined"}})}else ve(Qe,"stripe_paypal_confirm_failed",oe?.generation);return}if(typeof window<"u")try{localStorage.removeItem(br)}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:Ue,nonce:Oe});return}catch(M){ve(M,"stripe_paypal_failed",oe?.generation)}finally{H(!1)}},[d,g,e,t,n,l,o,s,R,m,ve,Fe,ne,ge,z]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Fa,{state:I,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:(0,i.jsxs)("div",{ref:me,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[K&&(0,i.jsx)("button",{ref:se,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ne,style:Ta,children:"Try PayPal again"}),(0,i.jsx)(ut.ExpressCheckoutElement,{onReady:E=>A(Aa(E,["paypal"])),onLoadError:()=>A("load_error"),onClick:Ie,onConfirm:we,onCancel:()=>{let E=Y.current.get(z);Y.current.delete(z),Mt(B)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),he(E?.generation),ye(!1),W.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)(bn,{status:"processing"})]})}function _a({sessionId:e,nonce:t,email:n,billingApiUrl:l,intentKind:o,expressMethods:s,onTokenizedBody:u,onErrorChange:c,onButtonClick:R,onDecline:L,onTechnicalFailure:m,runBeforeButtonClick:_,onLoadStateChange:w,placeholderBorderRadius:B}){let d=on(),g=(0,ut.useStripe)(),I=(0,ut.useElements)(),[A,P]=(0,r.useState)("loading");(0,r.useEffect)(()=>{w?.(A)},[A,w]);let[H,Q]=(0,r.useState)(!1),me=(0,r.useRef)(null),se=(0,r.useRef)(null),[z,te]=(0,r.useState)(0),[K,ye]=(0,r.useState)(!1),[W,Y]=(0,r.useState)("google_pay"),le=(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:ce,isAttemptCurrent:Ne}=Ma((ee,M,G)=>{m?.(ee,M,{...G,popupBlocked:G?.popupBlocked??Dn(M)}),Y(ee),ye(!0),te(ue=>ue+1)});(0,r.useEffect)(()=>{K&&se.current?.focus()},[K,z]);let Ie=(0,r.useCallback)(()=>{te(ee=>ee+1)},[]),we=(0,r.useCallback)((ee,M,G,ue)=>{ve(ue),m?.(ee,M,{code:G,popupBlocked:Dn(M)}),Y(ee),ye(!0),Ie()},[ve,m,Ie]),E=(0,r.useCallback)(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{le.current&&(le.current=!1,E())},[E,z]);let oe=(0,r.useCallback)(()=>{ye(!1),c?.(null),E()},[E,c]),de=(0,r.useCallback)(async ee=>{if(!g||!I)return;let M=ge.current.get(z);if(M&&!Ne(M.generation)){ge.current.delete(z);return}if(!M&&ce()||M&&!fe(M.generation))return;M||fe();let G=ee.expressPaymentType??M?.method??Fe.current,ue=M??null;ge.current.delete(z);let Ee=wa(G);if(!ue&&_){let je=await _(Ee);if(!je.proceed){ee.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}ue={accountPatch:je.accountPatch,sessionId:je.sessionId,nonce:je.nonce}}let gt=Ee,et=ue?.sessionId??e,Qe=ue?.nonce??t,y=ue?.accountPatch?.email??n;try{Q(!0),c?.(null);let{error:je}=await I.submit();if(je){we(G,je,"stripe_wallet_submit_failed",M?.generation);return}let{error:$e,paymentMethod:He}=await g.createPaymentMethod({elements:I});if($e||!He){we(G,$e??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",M?.generation);return}if(!et||!y)throw new Error("Missing sessionId or email for wallet payment");let Ke=await new Bn.PaymentAPI(l).createSessionIntent(et,Qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:G??Ee,paymentMethodId:He.id,intentKind:o});if(Ke.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Wt=Ke.clientSecret,{error:bt,intentId:kt}=(0,At.isSetupIntentClientSecret)(Wt)?await g.confirmCardSetup(Wt,{payment_method:He.id}).then(h=>({error:h.error,intentId:h.setupIntent?.id})):await g.confirmCardPayment(Wt,{payment_method:He.id}).then(h=>({error:h.error,intentId:h.paymentIntent?.id}));if(bt){if(hr(bt)){let h=bt.message??"Your payment was declined.";c?.(h),L?.(Tt(gt,h,{code:xn(bt),declineCode:er(bt)})),await Kr({billingApiUrl:l,sessionId:et,nonce:Qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:G??Ee,providerDeclineReason:xn(bt)??"provider_declined"}})}else we(G,bt,"stripe_wallet_confirm_failed",M?.generation);return}u({id:He.id,type:"card",threeDSecureActionResultTokenId:kt},{accountPatch:ue?.accountPatch,sessionId:et,nonce:Qe})}catch(je){we(G,je,"stripe_wallet_failed",M?.generation)}finally{Q(!1)}},[g,I,e,t,n,l,o,u,c,L,_,we,fe,Ne,ce,z]),Ue=(0,r.useMemo)(()=>{let ee=["applePay","googlePay","paypal","link","amazonPay","klarna"],M=new Set(["applePay","googlePay"]),G=new Set(s.map(k.stripeExpressMethodToOptionKey)),ue={};for(let Ee of ee)G.has(Ee)?ue[Ee]=M.has(Ee)?"always":"auto":ue[Ee]="never";return ue},[s]),Oe=(0,r.useMemo)(()=>s.map(k.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Fa,{state:A,placeholderTestId:"flopay-wallet-placeholder",borderRadius:B,children:(0,i.jsxs)("div",{ref:me,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[K&&(0,i.jsxs)("button",{ref:se,type:"button","data-testid":"flopay-wallet-retry-button",onClick:oe,style:Ta,children:["Try ",Ba(W)," again"]}),(0,i.jsx)(ut.ExpressCheckoutElement,{onReady:ee=>{P(Aa(ee,Oe))},onLoadError:ee=>{P("load_error"),Mt(d)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk"})},onClick:async ee=>{Fe.current=ee.expressPaymentType,he.current=wa(ee.expressPaymentType);let M=_?await _(he.current):{proceed:!0};if(!M.proceed){ge.current.delete(z),ee.reject();return}let G=ne(ee.expressPaymentType);ge.current.set(z,{generation:G,method:ee.expressPaymentType,accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}),ye(!1),R?.(he.current),ee.resolve()},onConfirm:de,onCancel:()=>{let ee=ge.current.get(z);ge.current.delete(z),Mt(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),ve(ee?.generation),ye(!1),le.current=!0,Ie()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ue,layout:{maxColumns:1,overflow:"never"}}},z)]})}),H&&(0,i.jsx)(bn,{status:"processing"})]})}function ji({method:e,themeId:t,submitting:n=!1,disabled:l=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:u,backgroundColor:c,borderColor:R,textColor:L,borderRadius:m,fontFamily:_}){let w=(0,k.resolveStripeMethodBrandVariant)(e,t),B=sa[e],d=w?.backgroundColor??c??"#ffffff",g=w?.borderColor??R??"#d1d5db",I=w?.textColor??L??"#262833";return(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!l&&u()},disabled:n||l,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Hr,padding:"0 1rem",backgroundColor:d,color:I,border:`1px solid ${g}`,borderRadius:m??8,fontSize:"0.95rem",fontWeight:600,fontFamily:_,cursor:n||l?"not-allowed":"pointer",opacity:l&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,i.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,k.getStripeMethodDisplayName)(e)}\u2026`}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,k.hasVendoredStripeMethodLogo)(e)?8:0},children:[B?(0,i.jsx)("img",{src:B,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):w?.logoSvg?(0,i.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:w.logoSvg}}):null,(0,i.jsx)("span",{children:(0,k.getStripeMethodDisplayName)(e)})]}),s&&(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:I,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,i.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Co({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:u,onErrorChange:c,onDecline:R,onCancel:L,runBeforeButtonClick:m,onButtonClick:_,isProcessing:w,submitButtonColor:B,submitButtonBorderRadius:d,submitButtonStyle:g,errorText:I}){let A=on(),P=(0,ut.useStripe)(),H=(0,ut.useElements)(),[Q,me]=(0,r.useState)(!1),se=(0,r.useRef)(!1),[z,te]=(0,r.useState)(!1),[K,ye]=(0,r.useState)("loading"),W=(0,r.useCallback)(async()=>{if(!P||!H||w||se.current||!z)return;se.current=!0,me(!0);let Y=m?await m("card"):{proceed:!0};if(!Y.proceed){se.current=!1,me(!1);return}_?.("card");let le=Y.sessionId??t,Fe=Y.nonce??n,he=Y.accountPatch?.email??l;try{c?.(null);let ge=await H.submit();if(ge.error){c?.(ge.error.message??"Payment failed.");return}let ne=await P.createPaymentMethod({elements:H});if(ne.error||!ne.paymentMethod){c?.(ne.error?.message??"Failed to create payment method.");return}let fe=ne.paymentMethod;if(!le||!he)throw new Error("Missing sessionId or email for payment.");let ve=fe.type||e,ce=await new Bn.PaymentAPI(s).createSessionIntent(le,Fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ve,paymentMethodId:null,intentKind:"payment"});if(ce.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ne=ce.clientSecret;if(typeof window<"u")try{localStorage.setItem(vn,JSON.stringify({clientSecret:Ne,sessionId:le,nonce:Fe,accountPatch:Y.accountPatch,paymentMethodId:fe.id,paymentMethodType:fe.type??e,gateway:"stripe"}))}catch{}let{error:Ie,paymentIntent:we}=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(vn)}catch{}let de=Ie.message??"Payment failed.";c?.(de),R?.(Tt("card",de,{code:Ie.code})),await Kr({billingApiUrl:s,sessionId:le,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ie.code??"provider_declined"}});return}let E=we?.status;if(!zr(E)){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let de=E==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";c?.(de),R?.(Tt("card",de,{code:E??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let oe=typeof we?.payment_method=="string"?we.payment_method:we?.payment_method?.id;u({id:oe??fe.id,type:"card",threeDSecureActionResultTokenId:we?.id,gateway:"stripe",paymentMethodType:fe.type??e},{accountPatch:Y.accountPatch,sessionId:le,nonce:Fe})}catch(ge){c?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{se.current=!1,me(!1)}},[P,H,w,z,m,_,t,n,l,s,e,u,c,R]);return(0,i.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,i.jsx)(ut.PaymentElement,{onReady:()=>ye("ready"),onLoadError:()=>{ye("load_error"),Mt(A)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"apm",requestCategory:"provider_sdk"})},onChange:Y=>{te(!!Y.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...l?{email:l}:{}}}}}),(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{W()},disabled:!z||Q||w||K!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:B,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!z||Q||w||K!=="ready"?"not-allowed":"pointer",opacity:!z||Q||w||K!=="ready"?.5:1,transition:"opacity 120ms ease-out",...g??{}},children:Q?"Processing\u2026":`Pay with ${(0,k.getStripeMethodDisplayName)(e)}`}),I&&(0,i.jsx)(Xn,{margin:"0.75rem 0 0",children:I})]})}function xa({sessionId:e,nonce:t,email:n,billingName:l,billingApiUrl:o,paymentElementMethods:s,stripeInstance:u,paymentElementBaseOptions:c,onTokenizedBody:R,onErrorChange:L,onButtonClick:m,onDecline:_,runBeforeButtonClick:w,onLoadStateChange:B,isProcessing:d=!1,submitButtonColor:g="#4A49FF",submitButtonBorderRadius:I=8,submitButtonStyle:A,buttonAppearance:P,themeId:H,onExpandApm:Q,expandedApmMethod:me}){let[se,z]=(0,r.useState)(null),[te,K]=(0,r.useState)(null),ye=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&u?B?.("ready"):u||B?.("loading")},[s.length,u,B]);let W=(0,r.useCallback)(async ne=>{if(!u||ye.current||d)return;ye.current=!0,K(ne);let fe=w?await w("card"):{proceed:!0};if(!fe.proceed){ye.current=!1,K(null);return}m?.("card");let ve=fe.sessionId??e,ce=fe.nonce??t,Ne=fe.accountPatch?.email??n;try{if(L?.(null),!ve||!Ne)throw new Error("Missing sessionId or email for payment.");let Ie=await new Bn.PaymentAPI(o).createSessionIntent(ve,ce??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,paymentMethodId:null,intentKind:"payment"});if(Ie.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let we=Ie.clientSecret;if(typeof window<"u")try{localStorage.setItem(vn,JSON.stringify({clientSecret:we,sessionId:ve,nonce:ce,accountPatch:fe.accountPatch,paymentMethodType:ne,gateway:"stripe"}))}catch{}let{error:E,paymentIntent:oe}=await u.confirmPayment({clientSecret:we,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(E){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let Oe=E.message??"Payment failed.";L?.(Oe),_?.(Tt("card",Oe,{code:E.code})),await Kr({billingApiUrl:o,sessionId:ve,nonce:ce,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,providerDeclineReason:E.code??"provider_declined"}});return}let de=oe?.status;if(!zr(de)){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let Oe=de==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";L?.(Oe),_?.(Tt("card",Oe,{code:de??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let Ue=typeof oe?.payment_method=="string"?oe.payment_method:oe?.payment_method?.id;R({id:Ue??oe?.id,type:"card",threeDSecureActionResultTokenId:oe?.id,gateway:"stripe",paymentMethodType:ne},{accountPatch:fe.accountPatch,sessionId:ve,nonce:ce})}catch(Ie){L?.(Ie instanceof Error?Ie.message:"Payment failed. Please try again.")}finally{ye.current=!1,K(null)}},[u,d,w,m,e,t,n,o,l,R,L,_]),[Y,le]=(0,r.useState)(null),Fe=Q?me??null:Y,he=(0,r.useCallback)(ne=>{ye.current||d||Fe&&Fe!==ne||((0,k.needsStripeMethodExplicitConfirm)(ne)?Q?Q(ne):le(ne):W(ne))},[Fe,d,W,Q]),ge=(0,r.useMemo)(()=>Y?{...c,paymentMethodTypes:[Y]}:null,[Y,c]);return(0,i.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(ne=>{let fe=me===ne,ve=te===ne,ce=te!==null&&te!==ne||me!=null&&me!==ne;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(ji,{method:ne,themeId:H,submitting:ve,disabled:ce,highlighted:fe,hasNextStep:(0,k.needsStripeMethodExplicitConfirm)(ne),onClick:()=>he(ne),backgroundColor:P?.backgroundColor,borderColor:P?.borderColor,textColor:P?.textColor,borderRadius:P?.borderRadius,fontFamily:P?.fontFamily}),!Q&&Y===ne&&ge&&u&&(0,i.jsx)(ut.Elements,{stripe:u,options:ge,children:(0,i.jsx)(Co,{method:ne,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:R,onErrorChange:L,onDecline:_,onCancel:()=>le(null),runBeforeButtonClick:w,onButtonClick:m,isProcessing:d,submitButtonColor:g,submitButtonBorderRadius:I,submitButtonStyle:A})},ne)]},ne)})})}function Vi({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:u,onDecline:c,onTokenizedBody:R,firstName:L,lastName:m,chv:_,className:w,isProcessing:B,error:d,onErrorChange:g,showPayPal:I=!0,showStripe:A=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:H,showApplePay:Q=!0,showGooglePay:me=!0,layout:se="default",theme:z,buttonsTheme:te,buttonsStyles:K,appearance:ye,cardButtonContent:W,cardBackButtonContent:Y,cardTitleContent:le,showSecurityFooter:Fe,onButtonClick:he,onBeforeButtonClick:ge,enableAVS:ne,cardFieldOrder:fe,cardPreFormSlot:ve,avsLayout:ce="row",country:Ne,zip:Ie,addressLine1:we,addressLine2:E,city:oe,state:de,onCountryChange:Ue,onZipChange:Oe,avsCheck:ee,checkoutType:M,checkoutLayout:G,totalAmount:ue=0,currency:Ee="usd",initialCardOpen:gt=!1,directPaypal:et,isSubscription:Qe=!1,session:y,debug:je=!1}){let $e=on(),He=Lr(),Ke=(0,r.useContext)(rn),Wt=Or(),[bt,kt]=(0,r.useState)(!1),[h,ke]=(0,r.useState)(null),[Ve,lt]=(0,r.useState)(Ne??"US"),[rt,ot]=(0,r.useState)(Ie??""),[Ge,Ce]=(0,r.useState)(we??""),[vt,We]=(0,r.useState)(E??""),[Dt,Rt]=(0,r.useState)(oe??""),[dn,Sn]=(0,r.useState)(de??""),[wn,Nn]=(0,r.useState)({}),ht=(0,r.useRef)(Ie??""),Lt=(0,r.useRef)(Ne??"US"),Nt=(0,r.useRef)(we??""),Yt=(0,r.useRef)(E??""),Qt=(0,r.useRef)(oe??""),un=(0,r.useRef)(de??""),J=(0,r.useMemo)(()=>(0,k.resolveAVSConfig)(ne),[ne]),Mn=J!==null,pn=!!y?.vault?.html,Ot=!!y?.gateways?.pcivault,at=pn||Ot,f=!!(A&&at&&$e&&e),xe=(0,r.useMemo)(()=>!$e||!f||!e?null:$e.cardCapture({sessionId:e}),[$e,f,e]),ct=(0,r.useMemo)(()=>{let a=Ve,C=J?(0,k.isAVSFieldVisible)(J.postal_code,a):!1;return $i(a,rt,C)},[J,Ve,rt]),{avsInvalid:kn,invalidAvsFields:Te}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!f||!J)return{avsInvalid:!1,invalidAvsFields:a};let C=Ve,V=(re,Xe)=>(0,k.isAVSFieldVisible)(re,C)&&!Xe.trim(),ie={line1:V(J.address_line_1,Ge),city:V(J.city,Dt),state:V(J.state,dn),zip:ct.empty||ct.malformed};return{avsInvalid:ie.line1||ie.city||ie.state||ie.zip,invalidAvsFields:ie}},[f,J,Ve,Ge,Dt,dn,ct]),[An,mn]=(0,r.useState)(!1),[On,yn]=(0,r.useState)(!1),[zt,Bt]=(0,r.useState)(()=>bo(y?.vault)),[Re,pt]=(0,r.useState)(gt&&at?"card":"buttons"),[it,en]=(0,r.useState)(null),Gt=Re==="expanding"||Re==="card",Pt=280,Vt=(0,r.useRef)(null),Ct=(0,r.useCallback)(a=>{Vt.current&&clearTimeout(Vt.current),Vt.current=setTimeout(()=>{Vt.current=null,a()},Pt)},[Pt]);(0,r.useEffect)(()=>()=>{Vt.current&&clearTimeout(Vt.current)},[]);let tn=(0,r.useCallback)(()=>{pt("expanding"),Ct(()=>pt("card"))},[Ct]),fn=(0,r.useCallback)(()=>{pt("collapsing"),Ct(()=>pt("buttons"))},[Ct]),Rn=(0,r.useCallback)(a=>{en(a),pt("apm-expanding"),Ct(()=>pt("apm-form"))},[Ct]),gn=(0,r.useCallback)(()=>{pt("apm-collapsing"),Ct(()=>{pt("buttons"),en(null)})},[Ct]);(0,r.useEffect)(()=>{se==="buttons"&>&&at&&pt("card")},[se,gt,at]);let[Ht,Ye]=(0,r.useState)(null),Kt=(0,r.useRef)(!1),[Ut,$t]=(0,r.useState)(null),T=(0,r.useRef)(Ut);(0,r.useEffect)(()=>{T.current=Ut},[Ut]);let U=n||Wt,q=d??h,F=(0,r.useMemo)(()=>(0,At.resolveTheme)(z),[z]),p=(0,r.useMemo)(()=>{let a=F?.buttonsLayout??(0,k.resolveButtonsLayoutTheme)(te);return K?{...a,...K,cardButton:{...a.cardButton,...K.cardButton},cardFormContainer:{...a.cardFormContainer,...K.cardFormContainer},backButton:{...a.backButton,...K.backButton},backButtonIcon:{...a.backButtonIcon,...K.backButtonIcon},submitButton:{...a.submitButton,...K.submitButton},title:{...a.title,...K.title}}:a},[F,te,K]),j=ye??F?.appearance,v=(0,r.useMemo)(()=>{let a=j?.variables,C=Xe=>typeof Xe=="string"&&Xe?Xe:void 0,V=p.submitButton,ie=C(a?.colorPrimary)??C(V?.backgroundColor)??"#4A49FF",$=se==="buttons",re=p.nameInput;return{primaryColor:ie,primaryHoverColor:C(a?.colorPrimaryHover)??Vr(ie,.12),inputBackgroundColor:C(p.cardInputBackground)??C(a?.colorBackground)??"#ffffff",textColor:C(p.cardInputColor)??C(re?.color)??C(a?.colorText)??"#262833",borderColor:C(p.cardInputBorder)??($?"#e5e7eb":"#A4A4FF"),placeholderColor:C(p.cardInputPlaceholderColor)??"#9ca3af",errorColor:C(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:C(re?.fontFamily)??C(a?.fontFamily)??"Poppins, sans-serif",fontSize:C(p.cardInputFontSize)??C(a?.fontSizeBase)??"16px",fontWeight:String(Ra(re?.fontWeight)??400),borderRadius:C(a?.borderRadius)??"8px"}},[j,p,se]),Be=Ke.inlineSessionPatchProcessing??!1,X=(B??bt)||Be,Je=U.replace(/\/+$/,""),ae=(0,r.useMemo)(()=>ho({userId:o,email:l,firstName:L,lastName:m,country:Ne,zip:Ie},wn),[o,l,L,m,Ne,Ie,wn]),qt=[ae.firstName,ae.lastName].filter(a=>!!a?.trim()).join(" "),st=(0,r.useMemo)(()=>$e?$e.getRawProvider():null,[$e]),N=(0,r.useMemo)(()=>He?He.getRawProvider():null,[He]),b=ue||100,O=j?{appearance:j}:null,Pe=(0,r.useMemo)(()=>{let a=j??{},C=a.rules??{};return{...a,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[j]),Me=(0,r.useMemo)(()=>{let a=ya(ue);return{...a,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...O}},[ue,Ee,O]),qe=(0,r.useMemo)(()=>({mode:"payment",amount:b,currency:Ee.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...O}),[b,Ee,O]),Z=(0,r.useCallback)(a=>{ke(a),g?.(a)},[g]);(0,r.useEffect)(()=>{!f||!xe||xe.setCardFieldOrder?.(fe??null,J==null)},[f,xe,fe,J]),(0,r.useEffect)(()=>{(Re==="expanding"||Re==="collapsing"||Re==="apm-expanding"||Re==="apm-collapsing")&&Z(null)},[Re,Z]);let be=(0,r.useCallback)((a,C,V)=>{c?.(Tt(a,C,V))},[c]),Se=(0,r.useCallback)((a,C,V)=>{let ie=V?.popupBlocked??Dn(C),$=zi(a,ie),re=Vn(V?.code)??xn(C)??"external_payment_method_failed",Xe=new At.FloPayError($,"api_error",{code:"external_payment_method_failed",param:a});Ye(null),se==="buttons"&&(pt("buttons"),en(null)),Z($),u?.(Xe),console.error("[FloPay] External payment method failed:",{method:a,code:re,popupBlocked:ie})},[se,u,Z]);(0,r.useEffect)(()=>{if(!f||!e){Bt(null);return}let a=bo(y?.vault);if(a){Bt(a);return}Bt(null);let C=!0;return new Bn.PaymentAPI(Je).getVaultCapture(e,t).then(V=>{if(!C)return;let ie=bo(V);ie?Bt(ie):Z("Failed to load the secure card form.")}).catch(V=>{C&&Z(V instanceof Error?V.message:"Failed to load the secure card form.")}),()=>{C=!1}},[f,e,y?.vault?.html,y?.vault?.messageToken,y?.vault?.expectedOrigin,Je,t,Z]);let pe=(0,r.useRef)({onComplete:s,onError:u,updateError:Z,emitDecline:be,resolvedAccount:ae,avsConfig:J,avsCheckProp:ee,sessionId:e,nonce:t,baseUrl:Je});pe.current={onComplete:s,onError:u,updateError:Z,emitDecline:be,resolvedAccount:ae,avsConfig:J,avsCheckProp:ee,sessionId:e,nonce:t,baseUrl:Je};let ze=(0,r.useRef)(!1),hn=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:C,avsCheckProp:V}=pe.current,ie=Lt.current||a.country||"US",$=C?(0,k.isAVSFieldVisible)(C.state,ie):!1,re=C?(0,k.isAVSFieldVisible)(C.address_line_1,ie):!1,Xe=C?(0,k.isAVSFieldVisible)(C.postal_code,ie):!1,St=C?(0,k.isAVSFieldVisible)(C.city,ie):!1,Et=C?(0,k.isAVSFieldVisible)(C.address_line_2,ie):!1,tt=re&&!$&&Xe?(0,k.getStateFromPostalCode)(ie,(ht.current??"").trim()):null,_t=$?un.current:tt;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Xe&&ht.current?{zip:ht.current}:{},...St&&Qt.current?{city:Qt.current}:{},..._t?{state:_t}:{},...re&&Nt.current?{addressLine1:Nt.current}:{},...Et&&Yt.current?{addressLine2:Yt.current}:{},country:ie},...V!==void 0?{avsCheck:V}:{},...C?{avsConfig:{country:(0,k.isAVSFieldVisible)(C.country,ie),postal_code:Xe,address_line_1:re,address_line_2:Et,city:St,state:$}}:{}}},[]);(0,r.useEffect)(()=>{!f||!xe||xe.setSubmitGate?.(kn)},[f,xe,kn]),(0,r.useEffect)(()=>{if(!f||!xe)return;ze.current=!1;let a=!1,C=xe.on("submitting",()=>{mn(!0),Ye("processing");let{baseUrl:re,sessionId:Xe,nonce:St,updateError:Et,onError:tt}=pe.current;!Xe||!St||new Bn.PaymentAPI(re).patchAccountSnapshot(Xe,St,hn(),{telemetryMode:"best_effort"}).catch(_t=>{if(!Di(_t))return;let De=_t instanceof Error?_t.message:"Please check your billing address and try again.";Et(De),Ye(null),tt?.(_t instanceof At.FloPayError?_t:new At.FloPayError(De,"api_error"))})}),V=xe.on("complete",async re=>{Qn(re.sessionId??pe.current.sessionId),Ye("success"),await new Promise(Xe=>setTimeout(Xe,_n)),!ze.current&&(ze.current=!0,pe.current.onComplete?.({status:"succeeded",paymentIntentId:re.intentId,checkoutMethod:"card"}))}),ie=xe.on("decline",async re=>{let{updateError:Xe,emitDecline:St}=pe.current,Et=re.message??"Your payment was declined. Please try another card or contact your bank.";Xe(Et),Ye("error"),St("card",Et,re.declineReason?{declineCode:re.declineReason}:void 0),await new Promise(tt=>setTimeout(tt,Pn)),!a&&Ye(null)}),$=xe.on("error",async re=>{let{updateError:Xe,onError:St}=pe.current,Et=re.message??"There was a problem processing your payment. Please try again.";Xe(Et),Ye("error"),St?.(new At.FloPayError(Et,"api_error")),await new Promise(tt=>setTimeout(tt,Pn)),!a&&Ye(null)});return()=>{a=!0,C(),V(),ie(),$()}},[f,xe]);let dt=!!et?.clientId,It=Array.isArray(P),wr=It&&P.length>0,Ja=It&&P.includes("paypal"),{expressMethods:kr,paymentElementMethods:ar}=(0,r.useMemo)(()=>(0,k.partitionStripeMethods)(P,{excludePaypal:dt}),[P,dt]),To=dt||!!He,Xa=(0,r.useMemo)(()=>To?kr.filter(a=>a!=="paypal"):kr,[kr,To]),Za=(0,r.useMemo)(()=>{let a=[];return Q&&a.push("apple_pay"),me&&a.push("google_pay"),a},[Q,me]),Rr=It?Xa:Za,Qa=A&&Rr.length>0,no=Mn?Ve:Ne,Ir=(0,r.useMemo)(()=>{let a=no?.trim().toUpperCase();return a?H?ar.filter(C=>{let V=H[C];return!V||V.length===0||V.includes(a)}):(0,k.filterStripeMethodsByCountry)(ar,no):ar},[ar,no,H]),ro=(0,r.useMemo)(()=>({mode:"payment",amount:b,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",appearance:Pe}),[b,Ee,Pe]),[Bo,Mo]=(0,r.useState)("loading"),[Ao,Fo]=(0,r.useState)("loading"),[Do,Lo]=(0,r.useState)("loading"),[ei,oo]=(0,r.useState)(!1),[No,ao]=(0,r.useState)("loading"),[Er,ti]=(0,r.useState)();(0,r.useEffect)(()=>{ti(ga())},[]);let Oo=I&&(dt||(It?Ja:Er===!1)),zo=A&&Qa,ir=Oo&&dt,Uo=No==="retrying"||No==="exhausted",sr=Oo&&!!N&&(!dt||Uo),lr=zo&&!!st,cr=A&&wr&&Ir.length>0&&!!st,ni=ir&&!Uo?ei:sr&&Ia(Bo),ri=lr&&Ia(Ao),oi=cr&&Do!=="load_error",$o=a=>a==="loading"||a==="ready",qo=ir||sr&&$o(Bo)||lr&&$o(Ao)||cr&&Do!=="load_error",_r=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!_r.current){if(!A&&!I){_r.current=!0;let a=new At.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(a),Z(a.message)}else if(!A&&I&&!dt&&!N){_r.current=!0;let a=new At.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(a),Z(a.message)}else if(Er!==void 0&&!at&&!qo){_r.current=!0;let a=new At.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});u?.(a),Z(a.message)}}},[A,I,dt,N,Er,at,qo,u,Z]);let jo=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(jo.current||!wr)return;let a=[];Q!==!0&&a.push("showApplePay"),me!==!0&&a.push("showGooglePay"),a.length!==0&&(jo.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.`))},[wr,Q,me]);let Vo=(0,r.useCallback)((a,C)=>Ke.applyInlineSessionPatch?Ke.applyInlineSessionPatch(a).then(V=>({error:null,sessionId:V.sessionId||e,nonce:V.session?.clientSecret||t})).catch(V=>{let ie=ka(C,V);return Z(ie.message),u?.(ie),{error:ie,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ke.applyInlineSessionPatch,t,u,e,Z]),nn=(0,r.useCallback)(async a=>{if(!ge)return{proceed:!0};try{let C=await ge({method:a,sessionId:e||void 0,createSession:Ke.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&Nn(ie=>({...ie??{},...C.account}));let V=await Vo(C,a);return V.error?{proceed:!1,accountPatch:C.account}:{proceed:!0,accountPatch:C.account,sessionId:V.sessionId,nonce:V.nonce}}return{proceed:!0}}catch(C){let V=ka(a,C);return Z(V.message),u?.(V),{proceed:!1}}},[Vo,Ke.inlineSessionDraft,ge,u,e,Z]),Ho=(0,r.useCallback)(async(a,C)=>{if(Kt.current)return;Kt.current=!0,kt(!0),Ye("processing"),Z(null);let V=C?.sessionId??e,ie=C?.nonce??t,$=ho(ae,C?.accountPatch),re=C?.completionPaymentMethodId??Ur(a),Xe=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let Et=await new Bn.PaymentAPI(Je).processPayment($.userId??"",{sessionId:V,nonce:ie,tokenizedData:Xe,accountData:{userId:$.userId??"",email:$.email??"",firstName:$.firstName??"",lastName:$.lastName??"",...J?(()=>{let De=Lt.current,Xt=(0,k.isAVSFieldVisible)(J.state,De),Zt=(0,k.isAVSFieldVisible)(J.address_line_1,De),qn=(0,k.isAVSFieldVisible)(J.postal_code,De),jn=Zt&&!Xt&&qn?(0,k.getStateFromPostalCode)(De,(ht.current??"").trim()):null,xt=Xt?un.current:jn;return{country:De,...qn&&ht.current?{zip:ht.current}:{},...(0,k.isAVSFieldVisible)(J.city,De)&&Qt.current?{city:Qt.current}:{},...xt?{state:xt}:{},...Zt&&Nt.current?{addressLine1:Nt.current}:{},...(0,k.isAVSFieldVisible)(J.address_line_2,De)&&Yt.current?{addressLine2:Yt.current}:{}}})():{}},chv:_,avsCheck:ee??!1,checkoutType:M,checkoutLayout:G,avsConfig:J?{country:(0,k.isAVSFieldVisible)(J.country,Lt.current),postal_code:(0,k.isAVSFieldVisible)(J.postal_code,Lt.current),address_line_1:(0,k.isAVSFieldVisible)(J.address_line_1,Lt.current),address_line_2:(0,k.isAVSFieldVisible)(J.address_line_2,Lt.current),city:(0,k.isAVSFieldVisible)(J.city,Lt.current),state:(0,k.isAVSFieldVisible)(J.state,Lt.current)}:void 0});if(Et.ok){Qn(V),Ye("success"),$t(null),await new Promise(De=>setTimeout(De,_n)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:re,checkoutMethod:a.isPaypal?"paypal":"card"});return}let tt=await Et.json().catch(()=>null);if(tt?.type==="paypal_redirect_required"){let De=tt.threeDSecureToken,Xt=tt.paymentMethodId||a.id||"";if(!$e||!De){Ye("error"),Z("PayPal authorization required but no token provided.");return}try{let Zt=He?.getRawProvider();if(!Zt){Z("PayPal is not available.");return}let qn={return_url:window.location.href};Xt&&(qn.payment_method=Xt);let{error:jn}=await Zt.confirmPayment({clientSecret:De,confirmParams:qn,redirect:"if_required"});if(jn){Ye("error");let xt=jn.message??"PayPal payment failed.";Z(xt),be("paypal",xt,{code:jn.code})}}catch(Zt){Ye("error"),Z(Zt instanceof Error?Zt.message:"PayPal authorization failed.")}return}if(tt?.type==="paypal_direct_required"){let De=tt.orderId;if(!De){Ye("error"),Z("PayPal retry required but no order id provided.");return}let Xt=T.current?.attempts??0;if(Xt>=2){Ye("error"),Z("PayPal payment could not be completed after multiple attempts."),be("paypal","paypal_direct_required retry limit exceeded");return}oo(!1),ao("loading"),$t({orderId:De,attempts:Xt+1}),Ye(null);return}Ye("error");let _t=tt?.message??"Payment failed. Please try again.";Z(_t),be(a.isPaypal?"paypal":"card",_t,{code:tt?.code??tt?.gatewayErrorCode,declineCode:tt?.declineCode??tt?.gatewayDeclineReason}),await new Promise(De=>setTimeout(De,Pn))}catch(St){Ye("error"),Z(St instanceof Error?St.message:"An unexpected error occurred"),await new Promise(Et=>setTimeout(Et,Pn))}finally{kt(!1),Ye(null),Kt.current=!1}},[Je,e,t,ae,qt,_,$e,He,s,u,Z,be]),Jt=(0,r.useCallback)((a,C)=>{R?R(a):Ho(a,C)},[R,Ho]),Ko=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(typeof window>"u"||Ko.current)return;let a=new URLSearchParams(window.location.search),C=a.get("payment_intent"),V=a.get("payment_intent_client_secret"),ie=a.get("redirect_status");if(!C||!V)return;let $=_t=>{let De=localStorage.getItem(_t);if(!De)return null;try{return JSON.parse(De)}catch{return localStorage.removeItem(_t),null}},re=$(vn)??$(Sa),Xe;if(re?.clientSecret){if(re.clientSecret!==V)return;Xe={...re.accountPatch?{accountPatch:re.accountPatch}:{},...re.sessionId?{sessionId:re.sessionId}:{},...re.nonce?{nonce:re.nonce}:{}}}else if(re?.sessionId&&re.sessionId!==e)return;Ko.current=!0,localStorage.removeItem(vn),localStorage.removeItem(Sa);let St=new URL(window.location.href);St.searchParams.delete("payment_intent"),St.searchParams.delete("payment_intent_client_secret"),St.searchParams.delete("redirect_status"),window.history.replaceState({},"",St.toString());let Et=re?.paymentMethodType??re?.tokenType??"card",tt="card";(async()=>{let _t=$e?.getRawProvider();if(!_t){let xt="Payment is not available \u2014 please refresh and try again.";Z(xt),be(tt,xt);return}if(ie==="failed"){let xt="Payment was declined. Please try again.";Z(xt),be(tt,xt);return}let{paymentIntent:De,error:Xt}=await _t.retrievePaymentIntent(V);if(Xt){let xt=Xt.message??"Failed to retrieve payment status.";Z(xt),be(tt,xt,{code:Xt.code});return}let Zt=De?.status,qn=zr(Zt);if(!De||!qn){let xt=Zt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Z(xt),be(tt,xt,{code:Zt??"missing_payment_intent"});return}let jn=typeof De.payment_method=="string"?De.payment_method:De.payment_method?.id;Jt({id:jn??re?.paymentMethodId??re?.tokenId??De.id,type:"card",threeDSecureActionResultTokenId:De.id,gateway:re?.gateway??"stripe",paymentMethodType:Et},Xe)})()},[e,Jt,$e,Z,be]);let io=(0,r.useCallback)(a=>{a.preventDefault()},[]);if(!($e!==null))return(0,i.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let dr=se==="buttons",jt=j?.variables,ai=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),so=jt?.colorBackground,ii=so&&!ai.has(so)?so:void 0,ur=p.cardInputBorder??(dr?"#e5e7eb":"#A4A4FF"),lo=jt?.colorDanger??"#dc2626",zn=a=>An&&a?lo:ur,xr=(ct.malformed||ct.empty)&&(On||An),si=xr?lo:zn(Te.zip),co=p.cardFormContainer?.backgroundColor??ii??(dr?"white":"#EDEDFF"),pr=p.cardInputBackground??jt?.colorBackground??"white",uo=Yn(Y),Wo=Yn(le),Wn=p.nameInput,Yo=p.cardInputFontSize??qi(Wn?.fontSize)??jt?.fontSizeBase??"16px",Go=typeof Wn?.fontFamily=="string"?Wn.fontFamily:jt?.fontFamily??"Poppins, sans-serif",Jo=Ra(Wn?.fontWeight)??400,li=p.cardInputColor??(typeof Wn?.color=="string"?Wn.color:void 0)??jt?.colorText??"#262833",ci=p.cardInputPlaceholderColor??"#9ca3af",mt=jt?.borderRadius??"8px",Un=jt?.borderRadius??p.cardButton?.borderRadius??mt,$n=jt?.colorPrimary??"#4A49FF",di=jt?.colorPrimaryHover??Vr($n,.12),po=jt?.colorText??"#262833",Xo={fontSize:Yo,fontFamily:Go,fontWeight:Jo,color:li,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ui={"--flopay-input-placeholder-color":ci,"--flopay-input-font-size":Yo,"--flopay-input-font-family":Go,"--flopay-input-font-weight":String(Jo)},mr=p.cardFormContainer??{},mo=mr.padding??(dr?"0":"1rem"),yo=mr.borderRadius??mt,pi=xe&&zt?(0,i.jsx)(Dr,{capture:xe,html:zt.html,messageToken:zt.messageToken,expectedOrigin:zt.expectedOrigin,theme:v,onReady:()=>{if(!J||typeof document>"u")return;let a=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};a();let C=0,V=window.setInterval(()=>{C+=1;let ie=document.activeElement;!!ie&&ie.tagName==="IFRAME"&&ie.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(V)):C>=50&&window.clearInterval(V)},100)},onError:a=>Z(a),onValidation:a=>{Z(a),a&&Ye(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"}),Zo=(0,i.jsxs)("div",{style:{backgroundColor:co,borderRadius:yo,...mr,padding:mo,...ui,display:"flex",flexDirection:"column"},children:[(0,i.jsx)("style",{children:`
|
|
30
|
+
`,Kr=44;function wo(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 Oi={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Ba={width:"100%",minHeight:Kr,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function zi(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ka(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ma(e){return e==="paypal"?"PayPal":(0,k.getStripeMethodDisplayName)(e)}function Ui(e,t){let n=`We couldn't open ${Ma(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Aa(e){let t=(0,r.useRef)(0),n=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useCallback)((d=l.current)=>{let g=d;g?.timer&&(clearTimeout(g.timer),g.timer=null)},[]),s=(0,r.useCallback)((d,g)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(d),d.timer=setTimeout(()=>{d.timer=null,l.current?.generation===d.generation&&(l.current=null,n.current=d.generation,e(d.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},g))},[o,e]),u=(0,r.useCallback)(d=>{d.yieldedControl&&s(d,600)},[s]),c=(0,r.useCallback)(d=>{o();let g=t.current+1;t.current=g,n.current=null;let I={generation:g,method:d,timer:null,yieldedControl:!1};return l.current=I,g},[o]),R=(0,r.useCallback)(d=>{let g=l.current;return typeof d=="number"&&g?.generation!==d?!1:(o(g),l.current=null,(typeof d!="number"||n.current===d)&&(n.current=null),!0)},[o]),N=(0,r.useCallback)(d=>{let g=l.current,I=d??g?.generation??t.current;(!d||g?.generation===d)&&(o(g),l.current=null),n.current=I},[o]),m=(0,r.useCallback)(d=>n.current===(d??t.current),[]),_=(0,r.useCallback)(d=>l.current?.generation===d&&n.current!==d,[]),w=(0,r.useCallback)(()=>{let d=l.current;d&&u(d)},[u]),M=(0,r.useCallback)(()=>{let d=l.current;d&&(d.yieldedControl=!0,o(d))},[o]);return(0,r.useEffect)(()=>{let d=()=>{document.visibilityState==="visible"?w():M()},g=()=>{M()};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,M,w]),{startAttempt:c,finishAttempt:R,invalidateAttempt:N,isAttemptInvalidated:m,isAttemptCurrent:_}}function $i(e){let t=(0,k.getPostalCodeExample)(e);return`Enter a valid ${(0,k.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function qi(e,t,n){let l=(0,k.isPostalCodeSupported)(e),o=t.trim(),s=n&&l,u=s&&!o,c=s&&!!o&&!(0,k.isValidPostalCode)(e,o);return{visible:n,supported:l,required:s,empty:u,malformed:c}}function Ra(e,t){return t instanceof Bt.FloPayError?t:new Bt.FloPayError(t instanceof Error?t.message:`${zi(e)} before-click hook failed.`,"validation_error")}function Co(){return(0,i.jsx)("style",{children:Ni})}function ji(e){return typeof e=="number"?`${e}px`:e}function Ia(e){if(typeof e=="number"||typeof e=="string")return e}function Fa(e,t){let n=e.availablePaymentMethods;return n&&t.some(l=>n[l])?"ready":"unavailable"}function Da({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 Ea(e){return e!=="unavailable"&&e!=="load_error"}function Yr(e){return(0,i.jsx)(Hi,{...e})}function _a({sessionId:e,nonce:t,email:n,billingApiUrl:l,onTokenizedBody:o,onErrorChange:s,isProcessing:u=!1,onButtonClick:c,onDecline:R,onTechnicalFailure:N,runBeforeButtonClick:m,onLoadStateChange:_,placeholderBorderRadius:w}){let M=an(),d=(0,dt.useStripe)(),g=(0,dt.useElements)(),[I,F]=(0,r.useState)("loading");(0,r.useEffect)(()=>{_?.(I)},[I,_]);let[P,K]=(0,r.useState)(!1),Q=(0,r.useRef)(!1),pe=(0,r.useRef)(null),se=(0,r.useRef)(null),[U,te]=(0,r.useState)(0),[W,me]=(0,r.useState)(!1),Y=(0,r.useRef)(!1),G=(0,r.useRef)(new Map),{startAttempt:le,finishAttempt:Fe,invalidateAttempt:be,isAttemptInvalidated:he,isAttemptCurrent:ne}=Aa((E,oe,de)=>{N?.(E,oe,{...de,popupBlocked:de?.popupBlocked??Dn(oe)}),me(!0),te(ze=>ze+1)});(0,r.useEffect)(()=>{W&&se.current?.focus()},[W,U]);let ye=(0,r.useCallback)(()=>{te(E=>E+1)},[]),ve=(0,r.useCallback)((E,oe,de)=>{be(de),N?.("paypal",E,{code:oe,popupBlocked:Dn(E)}),me(!0),ye()},[be,N,ye]),ce=(0,r.useCallback)(()=>{window.setTimeout(()=>{(pe.current?.querySelector("iframe")??pe.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{Y.current&&(Y.current=!1,ce())},[ce,U]);let Ne=(0,r.useCallback)(()=>{me(!1),s?.(null),ce()},[ce,s]);(0,r.useEffect)(()=>{if(!d||Q.current)return;let E=new URLSearchParams(window.location.search),oe=E.get("payment_intent"),de=E.get("payment_intent_client_secret"),ze=E.get("redirect_status");if(!oe||!de)return;Q.current=!0;let Oe;try{let A=localStorage.getItem(vr);if(A){let J=JSON.parse(A);J.clientSecret===de&&(Oe={...J.accountPatch?{accountPatch:J.accountPatch}:{},...J.sessionId?{sessionId:J.sessionId}:{},...J.nonce?{nonce:J.nonce}:{}})}}catch{}try{localStorage.removeItem(vr)}catch{}let ee=new URL(window.location.href);ee.searchParams.delete("payment_intent"),ee.searchParams.delete("payment_intent_client_secret"),ee.searchParams.delete("redirect_status"),window.history.replaceState({},"",ee.toString()),(async()=>{try{if(K(!0),ze==="failed"){let ue="PayPal payment was declined. Please try again.";s?.(ue),R?.(_t("paypal",ue));return}let{paymentIntent:A,error:J}=await d.retrievePaymentIntent(de);if(J){s?.(J.message??"Failed to retrieve PayPal payment status.");return}if(A&&(A.status==="requires_capture"||A.status==="succeeded")){let ue=typeof A.payment_method=="string"?A.payment_method:A.payment_method?.id;o({id:ue??A.id,type:"card",threeDSecureActionResultTokenId:A.id,isPaypal:!0},Oe)}else{let ue="PayPal payment was not completed. Please try again.";s?.(ue),R?.(_t("paypal",ue))}}catch(A){s?.(A instanceof Error?A.message:"Failed to complete PayPal payment.")}finally{K(!1)}})()},[d,o,s,R]);let Re=(0,r.useCallback)(async E=>{if(u||P){E.reject();return}let oe=m?await m("paypal"):{proceed:!0};if(!oe.proceed){G.current.delete(U),E.reject();return}let de=le("paypal");G.current.set(U,{generation:de,accountPatch:oe.accountPatch,sessionId:oe.sessionId,nonce:oe.nonce}),me(!1),c?.("paypal"),E.resolve()},[G,u,c,m,le,P,U]),Se=(0,r.useCallback)(async E=>{if(!d||!g)return;let oe=G.current.get(U);if(oe&&!ne(oe.generation)){G.current.delete(U);return}if(!oe&&he()||oe&&!Fe(oe.generation))return;oe||Fe();let de=oe??null;if(G.current.delete(U),!de&&m){let A=await m("paypal");if(!A.proceed){E.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}de={accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}}let ze=de?.sessionId??e,Oe=de?.nonce??t,ee=de?.accountPatch?.email??n;try{if(K(!0),s?.(null),!ze||!ee)throw new Error("Missing sessionId or email for PayPal payment");let A=d.createPaymentMethod,{error:J,paymentMethod:ue}=await A({type:"paypal"});if(J){ve(J,"stripe_paypal_create_payment_method_failed",oe?.generation),E.paymentFailed({reason:"fail"});return}let Ie=await new ln.PaymentAPI(l).createSessionIntent(ze,Oe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ue?.id??null,intentKind:"payment"});if(Ie.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ft=Ie.clientSecret,Qe={return_url:window.location.href};if(ue?.id&&(Qe.payment_method=ue.id),typeof window<"u")try{localStorage.setItem(vr,JSON.stringify({clientSecret:ft,sessionId:ze,nonce:Oe,accountPatch:de?.accountPatch}))}catch{}let{error:Ze,paymentIntent:y}=await d.confirmPayment({clientSecret:ft,confirmParams:Qe,redirect:"if_required"});if(Ze){if(typeof window<"u")try{localStorage.removeItem(vr)}catch{}if(Pr(Ze)){let Ue=Ze.message??"Your payment was declined.";s?.(Ue),R?.(_t("paypal",Ue,{code:Tn(Ze),declineCode:er(Ze)})),await Wr({billingApiUrl:l,sessionId:ze,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Tn(Ze)??"provider_declined"}})}else ve(Ze,"stripe_paypal_confirm_failed",oe?.generation);return}if(typeof window<"u")try{localStorage.removeItem(vr)}catch{}let qe=typeof y?.payment_method=="string"?y.payment_method:y?.payment_method?.id;o({id:qe??y?.id,type:"card",threeDSecureActionResultTokenId:y?.id,isPaypal:!0},{accountPatch:de?.accountPatch,sessionId:ze,nonce:Oe});return}catch(A){ve(A,"stripe_paypal_failed",oe?.generation)}finally{K(!1)}},[d,g,e,t,n,l,o,s,R,m,ve,Fe,ne,he,U]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Da,{state:I,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:(0,i.jsxs)("div",{ref:pe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[W&&(0,i.jsx)("button",{ref:se,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ne,style:Ba,children:"Try PayPal again"}),(0,i.jsx)(dt.ExpressCheckoutElement,{onReady:E=>F(Fa(E,["paypal"])),onLoadError:()=>F("load_error"),onClick:Re,onConfirm:Se,onCancel:()=>{let E=G.current.get(U);G.current.delete(U),Tt(M)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be(E?.generation),me(!1),Y.current=!0,ye()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},U)]})}),P&&(0,i.jsx)(vn,{status:"processing"})]})}function xa({sessionId:e,nonce:t,email:n,billingApiUrl:l,intentKind:o,expressMethods:s,onTokenizedBody:u,onErrorChange:c,onButtonClick:R,onDecline:N,onTechnicalFailure:m,runBeforeButtonClick:_,onLoadStateChange:w,placeholderBorderRadius:M}){let d=an(),g=(0,dt.useStripe)(),I=(0,dt.useElements)(),[F,P]=(0,r.useState)("loading");(0,r.useEffect)(()=>{w?.(F)},[F,w]);let[K,Q]=(0,r.useState)(!1),pe=(0,r.useRef)(null),se=(0,r.useRef)(null),[U,te]=(0,r.useState)(0),[W,me]=(0,r.useState)(!1),[Y,G]=(0,r.useState)("google_pay"),le=(0,r.useRef)(!1),Fe=(0,r.useRef)("google_pay"),be=(0,r.useRef)("google_pay"),he=(0,r.useRef)(new Map),{startAttempt:ne,finishAttempt:ye,invalidateAttempt:ve,isAttemptInvalidated:ce,isAttemptCurrent:Ne}=Aa((ee,A,J)=>{m?.(ee,A,{...J,popupBlocked:J?.popupBlocked??Dn(A)}),G(ee),me(!0),te(ue=>ue+1)});(0,r.useEffect)(()=>{W&&se.current?.focus()},[W,U]);let Re=(0,r.useCallback)(()=>{te(ee=>ee+1)},[]),Se=(0,r.useCallback)((ee,A,J,ue)=>{ve(ue),m?.(ee,A,{code:J,popupBlocked:Dn(A)}),G(ee),me(!0),Re()},[ve,m,Re]),E=(0,r.useCallback)(()=>{window.setTimeout(()=>{(pe.current?.querySelector("iframe")??pe.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{le.current&&(le.current=!1,E())},[E,U]);let oe=(0,r.useCallback)(()=>{me(!1),c?.(null),E()},[E,c]),de=(0,r.useCallback)(async ee=>{if(!g||!I)return;let A=he.current.get(U);if(A&&!Ne(A.generation)){he.current.delete(U);return}if(!A&&ce()||A&&!ye(A.generation))return;A||ye();let J=ee.expressPaymentType??A?.method??Fe.current,ue=A??null;he.current.delete(U);let Ie=ka(J);if(!ue&&_){let qe=await _(Ie);if(!qe.proceed){ee.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}ue={accountPatch:qe.accountPatch,sessionId:qe.sessionId,nonce:qe.nonce}}let ft=Ie,Qe=ue?.sessionId??e,Ze=ue?.nonce??t,y=ue?.accountPatch?.email??n;try{Q(!0),c?.(null);let{error:qe}=await I.submit();if(qe){Se(J,qe,"stripe_wallet_submit_failed",A?.generation);return}let{error:Ue,paymentMethod:Ve}=await g.createPaymentMethod({elements:I});if(Ue||!Ve){Se(J,Ue??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",A?.generation);return}if(!Qe||!y)throw new Error("Missing sessionId or email for wallet payment");let He=await new ln.PaymentAPI(l).createSessionIntent(Qe,Ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:J??Ie,paymentMethodId:Ve.id,intentKind:o});if(He.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Ht=He.clientSecret,{error:Pt,intentId:wt}=(0,Bt.isSetupIntentClientSecret)(Ht)?await g.confirmCardSetup(Ht,{payment_method:Ve.id}).then(h=>({error:h.error,intentId:h.setupIntent?.id})):await g.confirmCardPayment(Ht,{payment_method:Ve.id}).then(h=>({error:h.error,intentId:h.paymentIntent?.id}));if(Pt){if(Pr(Pt)){let h=Pt.message??"Your payment was declined.";c?.(h),N?.(_t(ft,h,{code:Tn(Pt),declineCode:er(Pt)})),await Wr({billingApiUrl:l,sessionId:Qe,nonce:Ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:J??Ie,providerDeclineReason:Tn(Pt)??"provider_declined"}})}else Se(J,Pt,"stripe_wallet_confirm_failed",A?.generation);return}u({id:Ve.id,type:"card",threeDSecureActionResultTokenId:wt},{accountPatch:ue?.accountPatch,sessionId:Qe,nonce:Ze})}catch(qe){Se(J,qe,"stripe_wallet_failed",A?.generation)}finally{Q(!1)}},[g,I,e,t,n,l,o,u,c,N,_,Se,ye,Ne,ce,U]),ze=(0,r.useMemo)(()=>{let ee=["applePay","googlePay","paypal","link","amazonPay","klarna"],A=new Set(["applePay","googlePay"]),J=new Set(s.map(k.stripeExpressMethodToOptionKey)),ue={};for(let Ie of ee)J.has(Ie)?ue[Ie]=A.has(Ie)?"always":"auto":ue[Ie]="never";return ue},[s]),Oe=(0,r.useMemo)(()=>s.map(k.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Da,{state:F,placeholderTestId:"flopay-wallet-placeholder",borderRadius:M,children:(0,i.jsxs)("div",{ref:pe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[W&&(0,i.jsxs)("button",{ref:se,type:"button","data-testid":"flopay-wallet-retry-button",onClick:oe,style:Ba,children:["Try ",Ma(Y)," again"]}),(0,i.jsx)(dt.ExpressCheckoutElement,{onReady:ee=>{P(Fa(ee,Oe))},onLoadError:ee=>{P("load_error"),Tt(d)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk"})},onClick:async ee=>{Fe.current=ee.expressPaymentType,be.current=ka(ee.expressPaymentType);let A=_?await _(be.current):{proceed:!0};if(!A.proceed){he.current.delete(U),ee.reject();return}let J=ne(ee.expressPaymentType);he.current.set(U,{generation:J,method:ee.expressPaymentType,accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}),me(!1),R?.(be.current),ee.resolve()},onConfirm:de,onCancel:()=>{let ee=he.current.get(U);he.current.delete(U),Tt(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),ve(ee?.generation),me(!1),le.current=!0,Re()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ze,layout:{maxColumns:1,overflow:"never"}}},U)]})}),K&&(0,i.jsx)(vn,{status:"processing"})]})}function Vi({method:e,themeId:t,submitting:n=!1,disabled:l=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:u,backgroundColor:c,borderColor:R,textColor:N,borderRadius:m,fontFamily:_}){let w=(0,k.resolveStripeMethodBrandVariant)(e,t),M=la[e],d=w?.backgroundColor??c??"#ffffff",g=w?.borderColor??R??"#d1d5db",I=w?.textColor??N??"#262833";return(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!l&&u()},disabled:n||l,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Kr,padding:"0 1rem",backgroundColor:d,color:I,border:`1px solid ${g}`,borderRadius:m??8,fontSize:"0.95rem",fontWeight:600,fontFamily:_,cursor:n||l?"not-allowed":"pointer",opacity:l&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,i.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,k.getStripeMethodDisplayName)(e)}\u2026`}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,k.hasVendoredStripeMethodLogo)(e)?8:0},children:[M?(0,i.jsx)("img",{src:M,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):w?.logoSvg?(0,i.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:w.logoSvg}}):null,(0,i.jsx)("span",{children:(0,k.getStripeMethodDisplayName)(e)})]}),s&&(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:I,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,i.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function So({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:u,onErrorChange:c,onDecline:R,onCancel:N,runBeforeButtonClick:m,onButtonClick:_,isProcessing:w,submitButtonColor:M,submitButtonBorderRadius:d,submitButtonStyle:g,errorText:I}){let F=an(),P=(0,dt.useStripe)(),K=(0,dt.useElements)(),[Q,pe]=(0,r.useState)(!1),se=(0,r.useRef)(!1),[U,te]=(0,r.useState)(!1),[W,me]=(0,r.useState)("loading"),Y=(0,r.useCallback)(async()=>{if(!P||!K||w||se.current||!U)return;se.current=!0,pe(!0);let G=m?await m("card"):{proceed:!0};if(!G.proceed){se.current=!1,pe(!1);return}_?.("card");let le=G.sessionId??t,Fe=G.nonce??n,be=G.accountPatch?.email??l;try{c?.(null);let he=await K.submit();if(he.error){c?.(he.error.message??"Payment failed.");return}let ne=await P.createPaymentMethod({elements:K});if(ne.error||!ne.paymentMethod){c?.(ne.error?.message??"Failed to create payment method.");return}let ye=ne.paymentMethod;if(!le||!be)throw new Error("Missing sessionId or email for payment.");let ve=ye.type||e,ce=await new ln.PaymentAPI(s).createSessionIntent(le,Fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ve,paymentMethodId:null,intentKind:"payment"});if(ce.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ne=ce.clientSecret;if(typeof window<"u")try{localStorage.setItem(Cn,JSON.stringify({clientSecret:Ne,sessionId:le,nonce:Fe,accountPatch:G.accountPatch,paymentMethodId:ye.id,paymentMethodType:ye.type??e,gateway:"stripe"}))}catch{}let{error:Re,paymentIntent:Se}=await P.confirmPayment({clientSecret:Ne,confirmParams:{return_url:window.location.href,payment_method:ye.id},redirect:"if_required"});if(Re){if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let de=Re.message??"Payment failed.";c?.(de),R?.(_t("card",de,{code:Re.code})),await Wr({billingApiUrl:s,sessionId:le,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Re.code??"provider_declined"}});return}let E=Se?.status;if(!Ur(E)){if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let de=E==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";c?.(de),R?.(_t("card",de,{code:E??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let oe=typeof Se?.payment_method=="string"?Se.payment_method:Se?.payment_method?.id;u({id:oe??ye.id,type:"card",threeDSecureActionResultTokenId:Se?.id,gateway:"stripe",paymentMethodType:ye.type??e},{accountPatch:G.accountPatch,sessionId:le,nonce:Fe})}catch(he){c?.(he instanceof Error?he.message:"Payment failed. Please try again.")}finally{se.current=!1,pe(!1)}},[P,K,w,U,m,_,t,n,l,s,e,u,c,R]);return(0,i.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,i.jsx)(dt.PaymentElement,{onReady:()=>me("ready"),onLoadError:()=>{me("load_error"),Tt(F)?.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"stripe",paymentMethodCategory:"apm",requestCategory:"provider_sdk"})},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:()=>{Y()},disabled:!U||Q||w||W!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:M,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!U||Q||w||W!=="ready"?"not-allowed":"pointer",opacity:!U||Q||w||W!=="ready"?.5:1,transition:"opacity 120ms ease-out",...g??{}},children:Q?"Processing\u2026":`Pay with ${(0,k.getStripeMethodDisplayName)(e)}`}),I&&(0,i.jsx)(Xn,{margin:"0.75rem 0 0",children:I})]})}function Ta({sessionId:e,nonce:t,email:n,billingName:l,billingApiUrl:o,paymentElementMethods:s,stripeInstance:u,paymentElementBaseOptions:c,onTokenizedBody:R,onErrorChange:N,onButtonClick:m,onDecline:_,runBeforeButtonClick:w,onLoadStateChange:M,isProcessing:d=!1,submitButtonColor:g="#4A49FF",submitButtonBorderRadius:I=8,submitButtonStyle:F,buttonAppearance:P,themeId:K,onExpandApm:Q,expandedApmMethod:pe}){let[se,U]=(0,r.useState)(null),[te,W]=(0,r.useState)(null),me=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&u?M?.("ready"):u||M?.("loading")},[s.length,u,M]);let Y=(0,r.useCallback)(async ne=>{if(!u||me.current||d)return;me.current=!0,W(ne);let ye=w?await w("card"):{proceed:!0};if(!ye.proceed){me.current=!1,W(null);return}m?.("card");let ve=ye.sessionId??e,ce=ye.nonce??t,Ne=ye.accountPatch?.email??n;try{if(N?.(null),!ve||!Ne)throw new Error("Missing sessionId or email for payment.");let Re=await new ln.PaymentAPI(o).createSessionIntent(ve,ce??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,paymentMethodId:null,intentKind:"payment"});if(Re.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Se=Re.clientSecret;if(typeof window<"u")try{localStorage.setItem(Cn,JSON.stringify({clientSecret:Se,sessionId:ve,nonce:ce,accountPatch:ye.accountPatch,paymentMethodType:ne,gateway:"stripe"}))}catch{}let{error:E,paymentIntent:oe}=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(E){if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let Oe=E.message??"Payment failed.";N?.(Oe),_?.(_t("card",Oe,{code:E.code})),await Wr({billingApiUrl:o,sessionId:ve,nonce:ce,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,providerDeclineReason:E.code??"provider_declined"}});return}let de=oe?.status;if(!Ur(de)){if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let Oe=de==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";N?.(Oe),_?.(_t("card",Oe,{code:de??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Cn)}catch{}let ze=typeof oe?.payment_method=="string"?oe.payment_method:oe?.payment_method?.id;R({id:ze??oe?.id,type:"card",threeDSecureActionResultTokenId:oe?.id,gateway:"stripe",paymentMethodType:ne},{accountPatch:ye.accountPatch,sessionId:ve,nonce:ce})}catch(Re){N?.(Re instanceof Error?Re.message:"Payment failed. Please try again.")}finally{me.current=!1,W(null)}},[u,d,w,m,e,t,n,o,l,R,N,_]),[G,le]=(0,r.useState)(null),Fe=Q?pe??null:G,be=(0,r.useCallback)(ne=>{me.current||d||Fe&&Fe!==ne||((0,k.needsStripeMethodExplicitConfirm)(ne)?Q?Q(ne):le(ne):Y(ne))},[Fe,d,Y,Q]),he=(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 ye=pe===ne,ve=te===ne,ce=te!==null&&te!==ne||pe!=null&&pe!==ne;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(Vi,{method:ne,themeId:K,submitting:ve,disabled:ce,highlighted:ye,hasNextStep:(0,k.needsStripeMethodExplicitConfirm)(ne),onClick:()=>be(ne),backgroundColor:P?.backgroundColor,borderColor:P?.borderColor,textColor:P?.textColor,borderRadius:P?.borderRadius,fontFamily:P?.fontFamily}),!Q&&G===ne&&he&&u&&(0,i.jsx)(dt.Elements,{stripe:u,options:he,children:(0,i.jsx)(So,{method:ne,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:R,onErrorChange:N,onDecline:_,onCancel:()=>le(null),runBeforeButtonClick:w,onButtonClick:m,isProcessing:d,submitButtonColor:g,submitButtonBorderRadius:I,submitButtonStyle:F})},ne)]},ne)})})}function Hi({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:u,onDecline:c,onTokenizedBody:R,firstName:N,lastName:m,chv:_,className:w,isProcessing:M,error:d,onErrorChange:g,showPayPal:I=!0,showStripe:F=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:K,showApplePay:Q=!0,showGooglePay:pe=!0,layout:se="default",theme:U,buttonsTheme:te,buttonsStyles:W,appearance:me,cardButtonContent:Y,cardBackButtonContent:G,cardTitleContent:le,showSecurityFooter:Fe,onButtonClick:be,onBeforeButtonClick:he,enableAVS:ne,cardFieldOrder:ye,cardPreFormSlot:ve,avsLayout:ce="row",country:Ne,zip:Re,addressLine1:Se,addressLine2:E,city:oe,state:de,onCountryChange:ze,onZipChange:Oe,avsCheck:ee,checkoutType:A,checkoutLayout:J,totalAmount:ue=0,currency:Ie="usd",initialCardOpen:ft=!1,directPaypal:Qe,isSubscription:Ze=!1,session:y,debug:qe=!1}){let Ue=an(),Ve=Nr(),He=(0,r.useContext)(on),Ht=zr(),[Pt,wt]=(0,r.useState)(!1),[h,we]=(0,r.useState)(null),[je,lt]=(0,r.useState)(Ne??"US"),[nt,rt]=(0,r.useState)(Re??""),[Ye,Ce]=(0,r.useState)(Se??""),[bt,Ke]=(0,r.useState)(E??""),[At,kt]=(0,r.useState)(oe??""),[pn,wn]=(0,r.useState)(de??""),[kn,Nn]=(0,r.useState)({}),gt=(0,r.useRef)(Re??""),Ft=(0,r.useRef)(Ne??"US"),Dt=(0,r.useRef)(Se??""),Kt=(0,r.useRef)(E??""),Qt=(0,r.useRef)(oe??""),mn=(0,r.useRef)(de??""),X=(0,r.useMemo)(()=>(0,k.resolveAVSConfig)(ne),[ne]),Mn=X!==null,yn=!!y?.vault?.html,Lt=!!y?.gateways?.pcivault,ot=yn||Lt,f=!!(F&&ot&&Ue&&e),xe=(0,r.useMemo)(()=>!Ue||!f||!e?null:Ue.cardCapture({sessionId:e}),[Ue,f,e]),ct=(0,r.useMemo)(()=>{let a=je,C=X?(0,k.isAVSFieldVisible)(X.postal_code,a):!1;return qi(a,nt,C)},[X,je,nt]),{avsInvalid:Rn,invalidAvsFields:Te}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!f||!X)return{avsInvalid:!1,invalidAvsFields:a};let C=je,V=(re,Je)=>(0,k.isAVSFieldVisible)(re,C)&&!Je.trim(),ie={line1:V(X.address_line_1,Ye),city:V(X.city,At),state:V(X.state,pn),zip:ct.empty||ct.malformed};return{avsInvalid:ie.line1||ie.city||ie.state||ie.zip,invalidAvsFields:ie}},[f,X,je,Ye,At,pn,ct]),[An,fn]=(0,r.useState)(!1),[On,gn]=(0,r.useState)(!1),[Nt,xt]=(0,r.useState)(()=>vo(y?.vault)),[ke,ut]=(0,r.useState)(ft&&ot?"card":"buttons"),[at,en]=(0,r.useState)(null),Wt=ke==="expanding"||ke==="card",ht=280,qt=(0,r.useRef)(null),vt=(0,r.useCallback)(a=>{qt.current&&clearTimeout(qt.current),qt.current=setTimeout(()=>{qt.current=null,a()},ht)},[ht]);(0,r.useEffect)(()=>()=>{qt.current&&clearTimeout(qt.current)},[]);let tn=(0,r.useCallback)(()=>{ut("expanding"),vt(()=>ut("card"))},[vt]),hn=(0,r.useCallback)(()=>{ut("collapsing"),vt(()=>ut("buttons"))},[vt]),In=(0,r.useCallback)(a=>{en(a),ut("apm-expanding"),vt(()=>ut("apm-form"))},[vt]),Pn=(0,r.useCallback)(()=>{ut("apm-collapsing"),vt(()=>{ut("buttons"),en(null)})},[vt]);(0,r.useEffect)(()=>{se==="buttons"&&ft&&ot&&ut("card")},[se,ft,ot]);let[jt,We]=(0,r.useState)(null),Vt=(0,r.useRef)(!1),[Ot,zt]=(0,r.useState)(null),B=(0,r.useRef)(Ot);(0,r.useEffect)(()=>{B.current=Ot},[Ot]);let $=n||Ht,j=d??h,D=(0,r.useMemo)(()=>(0,Bt.resolveTheme)(U),[U]),p=(0,r.useMemo)(()=>{let a=D?.buttonsLayout??(0,k.resolveButtonsLayoutTheme)(te);return W?{...a,...W,cardButton:{...a.cardButton,...W.cardButton},cardFormContainer:{...a.cardFormContainer,...W.cardFormContainer},backButton:{...a.backButton,...W.backButton},backButtonIcon:{...a.backButtonIcon,...W.backButtonIcon},submitButton:{...a.submitButton,...W.submitButton},title:{...a.title,...W.title}}:a},[D,te,W]),H=me??D?.appearance,v=(0,r.useMemo)(()=>{let a=H?.variables,C=Je=>typeof Je=="string"&&Je?Je:void 0,V=p.submitButton,ie=C(a?.colorPrimary)??C(V?.backgroundColor)??"#4A49FF",q=se==="buttons",re=p.nameInput;return{primaryColor:ie,primaryHoverColor:C(a?.colorPrimaryHover)??Hr(ie,.12),inputBackgroundColor:C(p.cardInputBackground)??C(a?.colorBackground)??"#ffffff",textColor:C(p.cardInputColor)??C(re?.color)??C(a?.colorText)??"#262833",borderColor:C(p.cardInputBorder)??(q?"#e5e7eb":"#A4A4FF"),placeholderColor:C(p.cardInputPlaceholderColor)??"#9ca3af",errorColor:C(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:C(re?.fontFamily)??C(a?.fontFamily)??"Poppins, sans-serif",fontSize:C(p.cardInputFontSize)??C(a?.fontSizeBase)??"16px",fontWeight:String(Ia(re?.fontWeight)??400),borderRadius:C(a?.borderRadius)??"8px"}},[H,p,se]),Be=He.inlineSessionPatchProcessing??!1,Z=(M??Pt)||Be,Ge=$.replace(/\/+$/,""),ae=(0,r.useMemo)(()=>Po({userId:o,email:l,firstName:N,lastName:m,country:Ne,zip:Re},kn),[o,l,N,m,Ne,Re,kn]),Ut=[ae.firstName,ae.lastName].filter(a=>!!a?.trim()).join(" "),it=(0,r.useMemo)(()=>Ue?Ue.getRawProvider():null,[Ue]),O=(0,r.useMemo)(()=>Ve?Ve.getRawProvider():null,[Ve]),b=ue||100,z=(0,r.useMemo)(()=>H?(0,ln.toStripeAppearance)(H):null,[H]),Pe=z?{appearance:z}:null,Me=(0,r.useMemo)(()=>{let a=z??{},C=a.rules??{};return{...a,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[z]),$e=(0,r.useMemo)(()=>{let a=fa(ue);return{...a,currency:Ie.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...Pe}},[ue,Ie,Pe]),nn=(0,r.useMemo)(()=>({mode:"payment",amount:b,currency:Ie.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Pe}),[b,Ie,Pe]),x=(0,r.useCallback)(a=>{we(a),g?.(a)},[g]);(0,r.useEffect)(()=>{!f||!xe||xe.setCardFieldOrder?.(ye??null,X==null)},[f,xe,ye,X]),(0,r.useEffect)(()=>{(ke==="expanding"||ke==="collapsing"||ke==="apm-expanding"||ke==="apm-collapsing")&&x(null)},[ke,x]);let ge=(0,r.useCallback)((a,C,V)=>{c?.(_t(a,C,V))},[c]),fe=(0,r.useCallback)((a,C,V)=>{let ie=V?.popupBlocked??Dn(C),q=Ui(a,ie),re=Vn(V?.code)??Tn(C)??"external_payment_method_failed",Je=new Bt.FloPayError(q,"api_error",{code:"external_payment_method_failed",param:a});We(null),se==="buttons"&&(ut("buttons"),en(null)),x(q),u?.(Je),console.error("[FloPay] External payment method failed:",{method:a,code:re,popupBlocked:ie})},[se,u,x]);(0,r.useEffect)(()=>{if(!f||!e){xt(null);return}let a=vo(y?.vault);if(a){xt(a);return}xt(null);let C=!0;return new ln.PaymentAPI(Ge).getVaultCapture(e,t).then(V=>{if(!C)return;let ie=vo(V);ie?xt(ie):x("Failed to load the secure card form.")}).catch(V=>{C&&x(V instanceof Error?V.message:"Failed to load the secure card form.")}),()=>{C=!1}},[f,e,y?.vault?.html,y?.vault?.messageToken,y?.vault?.expectedOrigin,Ge,t,x]);let Ee=(0,r.useRef)({onComplete:s,onError:u,updateError:x,emitDecline:ge,resolvedAccount:ae,avsConfig:X,avsCheckProp:ee,sessionId:e,nonce:t,baseUrl:Ge});Ee.current={onComplete:s,onError:u,updateError:x,emitDecline:ge,resolvedAccount:ae,avsConfig:X,avsCheckProp:ee,sessionId:e,nonce:t,baseUrl:Ge};let Yt=(0,r.useRef)(!1),Gt=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:C,avsCheckProp:V}=Ee.current,ie=Ft.current||a.country||"US",q=C?(0,k.isAVSFieldVisible)(C.state,ie):!1,re=C?(0,k.isAVSFieldVisible)(C.address_line_1,ie):!1,Je=C?(0,k.isAVSFieldVisible)(C.postal_code,ie):!1,Ct=C?(0,k.isAVSFieldVisible)(C.city,ie):!1,Rt=C?(0,k.isAVSFieldVisible)(C.address_line_2,ie):!1,et=re&&!q&&Je?(0,k.getStateFromPostalCode)(ie,(gt.current??"").trim()):null,It=q?mn.current:et;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Je&>.current?{zip:gt.current}:{},...Ct&&Qt.current?{city:Qt.current}:{},...It?{state:It}:{},...re&&Dt.current?{addressLine1:Dt.current}:{},...Rt&&Kt.current?{addressLine2:Kt.current}:{},country:ie},...V!==void 0?{avsCheck:V}:{},...C?{avsConfig:{country:(0,k.isAVSFieldVisible)(C.country,ie),postal_code:Je,address_line_1:re,address_line_2:Rt,city:Ct,state:q}}:{}}},[]);(0,r.useEffect)(()=>{!f||!xe||xe.setSubmitGate?.(Rn)},[f,xe,Rn]),(0,r.useEffect)(()=>{if(!f||!xe)return;Yt.current=!1;let a=!1,C=xe.on("submitting",()=>{fn(!0),We("processing");let{baseUrl:re,sessionId:Je,nonce:Ct,updateError:Rt,onError:et}=Ee.current;!Je||!Ct||new ln.PaymentAPI(re).patchAccountSnapshot(Je,Ct,Gt(),{telemetryMode:"best_effort"}).catch(It=>{if(!Li(It))return;let De=It instanceof Error?It.message:"Please check your billing address and try again.";Rt(De),We(null),et?.(It instanceof Bt.FloPayError?It:new Bt.FloPayError(De,"api_error"))})}),V=xe.on("complete",async re=>{Qn(re.sessionId??Ee.current.sessionId),We("success"),await new Promise(Je=>setTimeout(Je,xn)),!Yt.current&&(Yt.current=!0,Ee.current.onComplete?.({status:"succeeded",paymentIntentId:re.intentId,checkoutMethod:"card"}))}),ie=xe.on("decline",async re=>{let{updateError:Je,emitDecline:Ct}=Ee.current,Rt=re.message??"Your payment was declined. Please try another card or contact your bank.";Je(Rt),We("error"),Ct("card",Rt,re.declineReason?{declineCode:re.declineReason}:void 0),await new Promise(et=>setTimeout(et,bn)),!a&&We(null)}),q=xe.on("error",async re=>{let{updateError:Je,onError:Ct}=Ee.current,Rt=re.message??"There was a problem processing your payment. Please try again.";Je(Rt),We("error"),Ct?.(new Bt.FloPayError(Rt,"api_error")),await new Promise(et=>setTimeout(et,bn)),!a&&We(null)});return()=>{a=!0,C(),V(),ie(),q()}},[f,xe]);let st=!!Qe?.clientId,ar=Array.isArray(P),kr=ar&&P.length>0,Xa=ar&&P.includes("paypal"),{expressMethods:Rr,paymentElementMethods:ir}=(0,r.useMemo)(()=>(0,k.partitionStripeMethods)(P,{excludePaypal:st}),[P,st]),Bo=st||!!Ve,Za=(0,r.useMemo)(()=>Bo?Rr.filter(a=>a!=="paypal"):Rr,[Rr,Bo]),Qa=(0,r.useMemo)(()=>{let a=[];return Q&&a.push("apple_pay"),pe&&a.push("google_pay"),a},[Q,pe]),Ir=ar?Za:Qa,ei=F&&Ir.length>0,ro=Mn?je:Ne,Er=(0,r.useMemo)(()=>{let a=ro?.trim().toUpperCase();return a?K?ir.filter(C=>{let V=K[C];return!V||V.length===0||V.includes(a)}):(0,k.filterStripeMethodsByCountry)(ir,ro):ir},[ir,ro,K]),oo=(0,r.useMemo)(()=>({mode:"payment",amount:b,currency:Ie.toLowerCase(),paymentMethodCreation:"manual",appearance:Me}),[b,Ie,Me]),[Mo,Ao]=(0,r.useState)("loading"),[Fo,Do]=(0,r.useState)("loading"),[Lo,No]=(0,r.useState)("loading"),[ti,ao]=(0,r.useState)(!1),[Oo,io]=(0,r.useState)("loading"),[_r,ni]=(0,r.useState)();(0,r.useEffect)(()=>{ni(ha())},[]);let zo=I&&(st||(ar?Xa:_r===!1)),Uo=F&&ei,sr=zo&&st,$o=Oo==="retrying"||Oo==="exhausted",lr=zo&&!!O&&(!st||$o),cr=Uo&&!!it,dr=F&&kr&&Er.length>0&&!!it,ri=sr&&!$o?ti:lr&&Ea(Mo),oi=cr&&Ea(Fo),ai=dr&&Lo!=="load_error",qo=a=>a==="loading"||a==="ready",jo=sr||lr&&qo(Mo)||cr&&qo(Fo)||dr&&Lo!=="load_error",xr=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!xr.current){if(!F&&!I){xr.current=!0;let a=new Bt.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(a),x(a.message)}else if(!F&&I&&!st&&!O){xr.current=!0;let a=new Bt.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(a),x(a.message)}else if(_r!==void 0&&!ot&&!jo){xr.current=!0;let a=new Bt.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});u?.(a),x(a.message)}}},[F,I,st,O,_r,ot,jo,u,x]);let Vo=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(Vo.current||!kr)return;let a=[];Q!==!0&&a.push("showApplePay"),pe!==!0&&a.push("showGooglePay"),a.length!==0&&(Vo.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[kr,Q,pe]);let Ho=(0,r.useCallback)((a,C)=>He.applyInlineSessionPatch?He.applyInlineSessionPatch(a).then(V=>({error:null,sessionId:V.sessionId||e,nonce:V.session?.clientSecret||t})).catch(V=>{let ie=Ra(C,V);return x(ie.message),u?.(ie),{error:ie,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[He.applyInlineSessionPatch,t,u,e,x]),rn=(0,r.useCallback)(async a=>{if(!he)return{proceed:!0};try{let C=await he({method:a,sessionId:e||void 0,createSession:He.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&Nn(ie=>({...ie??{},...C.account}));let V=await Ho(C,a);return V.error?{proceed:!1,accountPatch:C.account}:{proceed:!0,accountPatch:C.account,sessionId:V.sessionId,nonce:V.nonce}}return{proceed:!0}}catch(C){let V=Ra(a,C);return x(V.message),u?.(V),{proceed:!1}}},[Ho,He.inlineSessionDraft,he,u,e,x]),Ko=(0,r.useCallback)(async(a,C)=>{if(Vt.current)return;Vt.current=!0,wt(!0),We("processing"),x(null);let V=C?.sessionId??e,ie=C?.nonce??t,q=Po(ae,C?.accountPatch),re=C?.completionPaymentMethodId??$r(a),Je=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let Rt=await new ln.PaymentAPI(Ge).processPayment(q.userId??"",{sessionId:V,nonce:ie,tokenizedData:Je,accountData:{userId:q.userId??"",email:q.email??"",firstName:q.firstName??"",lastName:q.lastName??"",...X?(()=>{let De=Ft.current,Xt=(0,k.isAVSFieldVisible)(X.state,De),Zt=(0,k.isAVSFieldVisible)(X.address_line_1,De),qn=(0,k.isAVSFieldVisible)(X.postal_code,De),jn=Zt&&!Xt&&qn?(0,k.getStateFromPostalCode)(De,(gt.current??"").trim()):null,Et=Xt?mn.current:jn;return{country:De,...qn&>.current?{zip:gt.current}:{},...(0,k.isAVSFieldVisible)(X.city,De)&&Qt.current?{city:Qt.current}:{},...Et?{state:Et}:{},...Zt&&Dt.current?{addressLine1:Dt.current}:{},...(0,k.isAVSFieldVisible)(X.address_line_2,De)&&Kt.current?{addressLine2:Kt.current}:{}}})():{}},chv:_,avsCheck:ee??!1,checkoutType:A,checkoutLayout:J,avsConfig:X?{country:(0,k.isAVSFieldVisible)(X.country,Ft.current),postal_code:(0,k.isAVSFieldVisible)(X.postal_code,Ft.current),address_line_1:(0,k.isAVSFieldVisible)(X.address_line_1,Ft.current),address_line_2:(0,k.isAVSFieldVisible)(X.address_line_2,Ft.current),city:(0,k.isAVSFieldVisible)(X.city,Ft.current),state:(0,k.isAVSFieldVisible)(X.state,Ft.current)}:void 0});if(Rt.ok){Qn(V),We("success"),zt(null),await new Promise(De=>setTimeout(De,xn)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:re,checkoutMethod:a.isPaypal?"paypal":"card"});return}let et=await Rt.json().catch(()=>null);if(et?.type==="paypal_redirect_required"){let De=et.threeDSecureToken,Xt=et.paymentMethodId||a.id||"";if(!Ue||!De){We("error"),x("PayPal authorization required but no token provided.");return}try{let Zt=Ve?.getRawProvider();if(!Zt){x("PayPal is not available.");return}let qn={return_url:window.location.href};Xt&&(qn.payment_method=Xt);let{error:jn}=await Zt.confirmPayment({clientSecret:De,confirmParams:qn,redirect:"if_required"});if(jn){We("error");let Et=jn.message??"PayPal payment failed.";x(Et),ge("paypal",Et,{code:jn.code})}}catch(Zt){We("error"),x(Zt instanceof Error?Zt.message:"PayPal authorization failed.")}return}if(et?.type==="paypal_direct_required"){let De=et.orderId;if(!De){We("error"),x("PayPal retry required but no order id provided.");return}let Xt=B.current?.attempts??0;if(Xt>=2){We("error"),x("PayPal payment could not be completed after multiple attempts."),ge("paypal","paypal_direct_required retry limit exceeded");return}ao(!1),io("loading"),zt({orderId:De,attempts:Xt+1}),We(null);return}We("error");let It=et?.message??"Payment failed. Please try again.";x(It),ge(a.isPaypal?"paypal":"card",It,{code:et?.code??et?.gatewayErrorCode,declineCode:et?.declineCode??et?.gatewayDeclineReason}),await new Promise(De=>setTimeout(De,bn))}catch(Ct){We("error"),x(Ct instanceof Error?Ct.message:"An unexpected error occurred"),await new Promise(Rt=>setTimeout(Rt,bn))}finally{wt(!1),We(null),Vt.current=!1}},[Ge,e,t,ae,Ut,_,Ue,Ve,s,u,x,ge]),Jt=(0,r.useCallback)((a,C)=>{R?R(a):Ko(a,C)},[R,Ko]),Wo=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(typeof window>"u"||Wo.current)return;let a=new URLSearchParams(window.location.search),C=a.get("payment_intent"),V=a.get("payment_intent_client_secret"),ie=a.get("redirect_status");if(!C||!V)return;let q=It=>{let De=localStorage.getItem(It);if(!De)return null;try{return JSON.parse(De)}catch{return localStorage.removeItem(It),null}},re=q(Cn)??q(wa),Je;if(re?.clientSecret){if(re.clientSecret!==V)return;Je={...re.accountPatch?{accountPatch:re.accountPatch}:{},...re.sessionId?{sessionId:re.sessionId}:{},...re.nonce?{nonce:re.nonce}:{}}}else if(re?.sessionId&&re.sessionId!==e)return;Wo.current=!0,localStorage.removeItem(Cn),localStorage.removeItem(wa);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 Rt=re?.paymentMethodType??re?.tokenType??"card",et="card";(async()=>{let It=Ue?.getRawProvider();if(!It){let Et="Payment is not available \u2014 please refresh and try again.";x(Et),ge(et,Et);return}if(ie==="failed"){let Et="Payment was declined. Please try again.";x(Et),ge(et,Et);return}let{paymentIntent:De,error:Xt}=await It.retrievePaymentIntent(V);if(Xt){let Et=Xt.message??"Failed to retrieve payment status.";x(Et),ge(et,Et,{code:Xt.code});return}let Zt=De?.status,qn=Ur(Zt);if(!De||!qn){let Et=Zt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";x(Et),ge(et,Et,{code:Zt??"missing_payment_intent"});return}let jn=typeof De.payment_method=="string"?De.payment_method:De.payment_method?.id;Jt({id:jn??re?.paymentMethodId??re?.tokenId??De.id,type:"card",threeDSecureActionResultTokenId:De.id,gateway:re?.gateway??"stripe",paymentMethodType:Rt},Je)})()},[e,Jt,Ue,x,ge]);let so=(0,r.useCallback)(a=>{a.preventDefault()},[]);if(!(Ue!==null))return(0,i.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ur=se==="buttons",$t=H?.variables,ii=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),lo=$t?.colorBackground,si=lo&&!ii.has(lo)?lo:void 0,pr=p.cardInputBorder??(ur?"#e5e7eb":"#A4A4FF"),co=$t?.colorDanger??"#dc2626",zn=a=>An&&a?co:pr,Tr=(ct.malformed||ct.empty)&&(On||An),li=Tr?co:zn(Te.zip),uo=p.cardFormContainer?.backgroundColor??si??(ur?"white":"#EDEDFF"),mr=p.cardInputBackground??$t?.colorBackground??"white",po=Yn(G),Yo=Yn(le),Wn=p.nameInput,Go=p.cardInputFontSize??ji(Wn?.fontSize)??$t?.fontSizeBase??"16px",Jo=typeof Wn?.fontFamily=="string"?Wn.fontFamily:$t?.fontFamily??"Poppins, sans-serif",Xo=Ia(Wn?.fontWeight)??400,ci=p.cardInputColor??(typeof Wn?.color=="string"?Wn.color:void 0)??$t?.colorText??"#262833",di=p.cardInputPlaceholderColor??"#9ca3af",pt=$t?.borderRadius??"8px",Un=$t?.borderRadius??p.cardButton?.borderRadius??pt,$n=$t?.colorPrimary??"#4A49FF",ui=$t?.colorPrimaryHover??Hr($n,.12),mo=$t?.colorText??"#262833",Zo={fontSize:Go,fontFamily:Jo,fontWeight:Xo,color:ci,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},pi={"--flopay-input-placeholder-color":di,"--flopay-input-font-size":Go,"--flopay-input-font-family":Jo,"--flopay-input-font-weight":String(Xo)},yr=p.cardFormContainer??{},yo=yr.padding??(ur?"0":"1rem"),fo=yr.borderRadius??pt,mi=xe&&Nt?(0,i.jsx)(Lr,{capture:xe,html:Nt.html,messageToken:Nt.messageToken,expectedOrigin:Nt.expectedOrigin,theme:v,onReady:()=>{if(!X||typeof document>"u")return;let a=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};a();let C=0,V=window.setInterval(()=>{C+=1;let ie=document.activeElement;!!ie&&ie.tagName==="IFRAME"&&ie.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(V)):C>=50&&window.clearInterval(V)},100)},onError:a=>x(a),onValidation:a=>{x(a),a&&We(null)}}):(0,i.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Qo=(0,i.jsxs)("div",{style:{backgroundColor:uo,borderRadius:fo,...yr,padding:yo,...pi,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 @@ ${et.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),
|
|
39
|
-
`)}):null,
|
|
40
|
-
`)}):null,ta=Re==="apm-expanding"||Re==="apm-form"||Re==="apm-collapsing",Br=Re==="apm-expanding"?`flopay-card-enter ${Pt}ms cubic-bezier(0, 0, 0.2, 1) both`:Re==="apm-collapsing"?`flopay-card-exit ${Pt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Mr=it?{...ro,paymentMethodTypes:[it]}:null;if(se==="buttons"){let a=Re==="buttons"||Re==="expanding"||Re==="apm-expanding",C=Re==="expanding"||Re==="card"||Re==="collapsing",V=W===void 0?{boxSizing:"border-box",height:Hr,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ie=Re==="expanding"||Re==="apm-expanding"?`flopay-buttons-exit ${Pt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Re==="collapsing"||Re==="apm-collapsing"?`flopay-buttons-enter ${Pt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,$=Re==="expanding"?`flopay-card-enter ${Pt}ms cubic-bezier(0, 0, 0.2, 1) both`:Re==="collapsing"?`flopay-card-exit ${Pt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,i.jsxs)("form",{onSubmit:io,className:w,style:{position:"relative"},children:[(0,i.jsx)(vo,{}),Ht&&(0,i.jsx)(bn,{status:Ht,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?Ni:{},...ie?{animation:ie,pointerEvents:"none"}:{}},children:[Qo("flopay-direct-paypal-gate-debug"),ea("flopay-stripe-gate-debug"),ir&&et&&(0,i.jsxs)(i.Fragment,{children:[Ut&&(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)(Pr,{sessionId:e,nonce:t,billingApiUrl:U,email:ae.email,clientId:et.clientId,environment:et.environment,currency:Ee.toUpperCase(),isSubscription:Qe,onTokenizedBody:Jt,onComplete:s,onErrorChange:Z,onDecline:c,onTechnicalFailure:Se,onButtonClick:he,runBeforeButtonClick:nn,isProcessing:X,onLoadStateChange:oo,onInitializationStateChange:ao,session:y??null,existingOrderId:Ut?.orderId,debug:je},Ut?.orderId??"fresh")]}),sr&&(0,i.jsx)(ut.Elements,{stripe:N,options:qe,children:(0,i.jsx)(Ea,{sessionId:e,nonce:t,email:ae.email,billingApiUrl:U,onTokenizedBody:Jt,onErrorChange:Z,isProcessing:X,onButtonClick:he,onDecline:c,onTechnicalFailure:Se,runBeforeButtonClick:nn,onLoadStateChange:Mo,placeholderBorderRadius:Un})}),lr?(0,i.jsx)(ut.Elements,{stripe:st,options:Me,children:(0,i.jsx)(_a,{sessionId:e,nonce:t,email:ae.email,billingApiUrl:U,intentKind:ue>0?"payment":"setup",expressMethods:Rr,onTokenizedBody:Jt,onErrorChange:Z,onButtonClick:he,onDecline:c,onTechnicalFailure:Se,runBeforeButtonClick:nn,onLoadStateChange:Fo,placeholderBorderRadius:Un})}):zo?(0,i.jsx)("div",{style:{height:Hr,borderRadius:Un,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,cr&&(0,i.jsx)(xa,{sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:U,paymentElementMethods:Ir,stripeInstance:st,paymentElementBaseOptions:ro,onTokenizedBody:Jt,onErrorChange:Z,onButtonClick:he,onDecline:c,runBeforeButtonClick:nn,onLoadStateChange:Lo,isProcessing:X,submitButtonColor:$n,submitButtonBorderRadius:mt,submitButtonStyle:p.submitButton,onExpandApm:Rn,expandedApmMethod:it,themeId:z,buttonAppearance:{backgroundColor:p.cardButton?.backgroundColor,borderColor:p.cardInputBorder,textColor:p.cardButton?.color,borderRadius:Un}}),f&&(0,i.jsx)("button",{type:"button",onClick:async()=>{X||!(await nn("card")).proceed||(he?.("card"),tn())},disabled:X,style:{width:"100%",...V,...p.cardButton,...So({themeBundle:F,resolvedPrimaryColor:$n,resolvedBorderRadius:mt,submitButtonStyle:p.submitButton,explicitPrimaryColor:jt?.colorPrimary}),fontSize:p.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:X?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:X?.6:1},onMouseEnter:re=>{!X&&(F||jt?.colorPrimary)&&(re.currentTarget.style.backgroundColor=di)},onMouseLeave:re=>{(F||jt?.colorPrimary)&&(re.currentTarget.style.backgroundColor=$n)},onMouseDown:re=>{re.currentTarget.style.transform="scale(0.985)"},onMouseUp:re=>{re.currentTarget.style.transform="scale(1)"},children:(0,i.jsx)(Gn,{content:W})}),q&&Re==="buttons"&&(0,i.jsx)(Xn,{margin:"0.25rem 0",styleOverride:p.errorBanner,children:q})]}),f&&C&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...$?{animation:$}:{},...Re==="collapsing"?{pointerEvents:"none"}:{}},children:Zo}),A&&ta&&it&&Mr&&st&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...Br?{animation:Br}:{},...Re==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:co,borderRadius:yo,...mr,padding:mo},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:gn,style:{display:"inline-flex",alignItems:"center",gap:uo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(Jn,{content:Y})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:po,paddingRight:80,...p.title},children:`Pay with ${(0,k.getStripeMethodDisplayName)(it)}`})]}),(0,i.jsx)(ut.Elements,{stripe:st,options:Mr,children:(0,i.jsx)(Co,{method:it,sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:U,onTokenizedBody:Jt,onErrorChange:Z,onDecline:c,onCancel:gn,runBeforeButtonClick:nn,onButtonClick:he,isProcessing:X,submitButtonColor:$n,submitButtonBorderRadius:mt,submitButtonStyle:p.submitButton,errorText:q})},it)]})})]})]})}return ta&&it&&Mr&&st&&A?(0,i.jsxs)("form",{onSubmit:io,className:w,style:{position:"relative"},children:[(0,i.jsx)(vo,{}),Ht&&(0,i.jsx)(bn,{status:Ht,errorMessage:q}),(0,i.jsx)("div",{style:{...Br?{animation:Br}:{},...Re==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:co,borderRadius:yo,...mr,padding:mo},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:gn,style:{display:"inline-flex",alignItems:"center",gap:uo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(Jn,{content:Y})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:po,paddingRight:80,...p.title},children:`Pay with ${(0,k.getStripeMethodDisplayName)(it)}`})]}),(0,i.jsx)(ut.Elements,{stripe:st,options:Mr,children:(0,i.jsx)(Co,{method:it,sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:U,onTokenizedBody:Jt,onErrorChange:Z,onDecline:c,onCancel:gn,runBeforeButtonClick:nn,onButtonClick:he,isProcessing:X,submitButtonColor:$n,submitButtonBorderRadius:mt,submitButtonStyle:p.submitButton,errorText:q})},it)]})})]}):(0,i.jsxs)("form",{onSubmit:io,className:w,style:{position:"relative"},children:[(0,i.jsx)(vo,{}),Ht&&(0,i.jsx)(bn,{status:Ht,errorMessage:q}),(0,i.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Qo("flopay-direct-paypal-gate-debug-default"),ea("flopay-stripe-gate-debug-default"),ir&&et&&(0,i.jsxs)(i.Fragment,{children:[Ut&&(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)(Pr,{sessionId:e,nonce:t,billingApiUrl:U,email:ae.email,clientId:et.clientId,environment:et.environment,currency:Ee.toUpperCase(),isSubscription:Qe,onTokenizedBody:Jt,onComplete:s,onErrorChange:Z,onDecline:c,onTechnicalFailure:Se,onButtonClick:he,runBeforeButtonClick:nn,isProcessing:X,onLoadStateChange:oo,onInitializationStateChange:ao,session:y??null,existingOrderId:Ut?.orderId,debug:je},Ut?.orderId??"fresh")]}),sr&&(0,i.jsx)(ut.Elements,{stripe:N,options:qe,children:(0,i.jsx)(Ea,{sessionId:e,nonce:t,email:ae.email,billingApiUrl:U,onTokenizedBody:Jt,onErrorChange:Z,isProcessing:X,onButtonClick:he,onDecline:c,onTechnicalFailure:Se,runBeforeButtonClick:nn,onLoadStateChange:Mo,placeholderBorderRadius:Un})}),lr&&(0,i.jsx)(ut.Elements,{stripe:st,options:Me,children:(0,i.jsx)(_a,{sessionId:e,nonce:t,email:ae.email,billingApiUrl:U,intentKind:ue>0?"payment":"setup",expressMethods:Rr,onTokenizedBody:Jt,onErrorChange:Z,onButtonClick:he,onDecline:c,onTechnicalFailure:Se,runBeforeButtonClick:nn,onLoadStateChange:Fo,placeholderBorderRadius:Un})}),cr&&(0,i.jsx)(xa,{sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:U,paymentElementMethods:Ir,stripeInstance:st,paymentElementBaseOptions:ro,onTokenizedBody:Jt,onErrorChange:Z,onButtonClick:he,onDecline:c,runBeforeButtonClick:nn,onLoadStateChange:Lo,isProcessing:X,submitButtonColor:$n,submitButtonBorderRadius:mt,submitButtonStyle:p.submitButton,themeId:z,onExpandApm:Rn,expandedApmMethod:it,buttonAppearance:{backgroundColor:p.cardButton?.backgroundColor,borderColor:p.cardInputBorder,textColor:p.cardButton?.color,borderRadius:Un}})]}),f&&(ri||ni||oi)&&(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&&Zo]})}var tr=require("@flopay/js"),Ze=require("@flopay/shared");var vr="card";async function Hi(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 Ki(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 Cn(e,t){return Object.assign(e,{checkoutMethod:t})}function Da(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 Wi(e){return e.status==="succeeded"||e.status==="declined"}async function La(e){if(typeof document>"u"||typeof window>"u")throw new Ze.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ze.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,l=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,s=async()=>{let m=new AbortController,_=()=>m.abort();e.signal?.aborted?m.abort():e.signal?.addEventListener("abort",_);let w=window.setTimeout(()=>m.abort(),l);try{let B=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:m.signal});if(!B.ok)return{status:"unknown"};let d=await B.json().catch(()=>null);return Yi(d)}catch{return{status:"unknown"}}finally{window.clearTimeout(w),e.signal?.removeEventListener("abort",_)}},u=document.activeElement instanceof HTMLElement?document.activeElement:null,c=document.createElement("div");c.setAttribute("data-flopay-auto-3ds-overlay","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let R=document.createElement("iframe");R.setAttribute("title","Card authentication"),R.setAttribute("allow","payment"),R.tabIndex=0,R.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),R.src=e.nextActionRedirectUrl,c.appendChild(R),document.body.appendChild(c),R.focus();let L=null;try{L=new URL(e.billingApiUrl,window.location.href).origin}catch{L=null}try{let m=await new Promise((_,w)=>{let B=!1,d=0,g=0,I=0,A=!1,P=()=>{window.clearTimeout(d),window.clearInterval(g),window.clearTimeout(I),window.removeEventListener("message",se),R.removeEventListener("load",Q),e.signal?.removeEventListener("abort",me)},H=async()=>{if(!(B||A)){A=!0;try{let z=await s();if(B||!Wi(z))return;B=!0,P(),_(z)}finally{A=!1}}},Q=()=>{window.clearTimeout(I),I=window.setTimeout(()=>{H()},250)},me=()=>{B||(B=!0,P(),w(new Ze.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},se=z=>{if(z.source!==R.contentWindow||L&&z.origin!==L)return;let te=z.data;!te||typeof te!="object"||te.source!=="flopay-vault-3ds-return"||B||(B=!0,P(),_(null))};d=window.setTimeout(()=>{B||(B=!0,P(),w(new Ze.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),g=window.setInterval(()=>{H()},n),R.addEventListener("load",Q),window.addEventListener("message",se),e.signal?.addEventListener("abort",me),e.signal?.aborted&&me()});return m||await s()}finally{c.parentNode?.removeChild(c),u?.isConnected&&u.focus()}}function Yi(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Ln(e,t="Payment failed. Please try again.",n){let l=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,s=Fn(o)??o;return Cn(new Ze.FloPayError(s,"api_error",{code:e?.gatewayErrorCode}),l)}function wo(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Yr(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Gi(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 Na(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Yr(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||Yr(c)))return c;let u=o.gateways;if(u&&typeof u=="object"){let c=u.stripe;if(c&&typeof c=="object"){let R=c,L=[R.stripeClientSecret,R.clientSecret];for(let m of L)if(typeof m=="string"&&m.length>0&&(!t?.requirePaymentIntentClientSecret||Yr(m)))return m}}}}async function Ji({billingApiUrl:e,sessionId:t,nonce:n,responseJson:l}){let o=Na(l,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let c=(await new tr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Yr(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function nr({billingApiUrl:e,sessionId:t,session:n,nonce:l,tokenizedData:o,returnUrl:s,telemetry:u}){let c=e.replace(/\/+$/,""),R=t??n.id,L=l??n.clientSecret,m=n.customer?.id??n.accountData?.userId??"",_=n.customer?.email??n.accountData?.email??"",w=n.customer?.firstName??n.accountData?.firstName??"",B=n.customer?.lastName??n.accountData?.lastName??"",d=n.customer?.country??n.accountData?.country??void 0,g=n.customer?.zip??n.accountData?.zip??void 0,I=new tr.PaymentAPI(c,u===!1?{telemetry:!1}:void 0),A=await Gi(()=>I.processPayment(m,{sessionId:R,nonce:L,tokenizedData:o,accountData:{userId:m,email:_,firstName:w,lastName:B,country:d,zip:g},returnUrl:s??wo(n)}));if(A.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Ur(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let P=await A.json().catch(()=>null);if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let H=Na(P);if(!H)throw new Ze.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:P.type,threeDSecureToken:H,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let H=await Ji({billingApiUrl:c,sessionId:R,nonce:L,responseJson:P});if(H)return H;throw Cn(new Ze.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new Ze.FloPayError(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason})}async function Gr(e,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:u,returnUrl:c,telemetry:R}){let L=t?.getRawProvider();if(!L)throw new Ze.FloPayError("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!l||!e.threeDSecureToken)throw Cn(new Ze.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let m=(0,Ze.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,w=e.paymentMethodId,B=await Hi(L,e.threeDSecureToken,m);if(B){if(B.error)throw Cn(new Ze.FloPayError(B.error.message??`Failed to retrieve 3DS ${m?"setup":"payment"} status.`,"api_error",{code:B.error.code}),"card");let g=B.intent;!w&&g?.payment_method&&(typeof g.payment_method=="string"?w=g.payment_method:"id"in g.payment_method&&(w=g.payment_method.id??void 0))}let d=w?await Ki(L,e.threeDSecureToken,{payment_method:w,return_url:c??wo(u)??window.location.href},m):null;if(d){if(d.error)throw Cn(new Ze.FloPayError(d.error.message??"3DS authentication failed.","api_error",{code:d.error.code}),"card");_=d.intent}else{let g=await L.handleNextAction({clientSecret:e.threeDSecureToken});if(g.error)throw Cn(new Ze.FloPayError(g.error.message??"3DS authentication failed.","api_error",{code:g.error.code}),"card");_=(m?g.setupIntent:g.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let g=await nr({billingApiUrl:o,sessionId:s,session:u,telemetry:R,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:c});return g.type==="success"?{...g.result,paymentIntentId:g.result.paymentIntentId??_.id,paymentMethodId:g.result.paymentMethodId??w}:Gr(g,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:u,returnUrl:c,telemetry:R})}throw Cn(new Ze.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let m=(n??t)?.getRawProvider();if(!m)throw Cn(new Ze.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:w}=await m.handleNextAction({clientSecret:e.threeDSecureToken});if(w)throw Cn(new Ze.FloPayError(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await m.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??wo(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(_)throw Cn(new Ze.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ze.FloPayError("Unsupported payment redirect state.","api_error")}function Hn(e){if(e instanceof Ze.FloPayError){let l=Fn(e.message);return l&&l!==e.message?Object.assign(new Ze.FloPayError(l,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Fn(t)??t;return new Ze.FloPayError(n,"api_error")}function Jr(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ze.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 Xr({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:l,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let s=!!t&&t!==e,[u,c]=await Promise.all([(0,tr.loadFloPay)(e,{billingApiUrl:n,locale:l,telemetry:o}),s?(0,tr.loadFloPay)(t,{billingApiUrl:n,locale:l,telemetry:o}).catch(R=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",R),null)):Promise.resolve(null)]);return{flopay:u,paypalFlopay:t?s?c:u:null}}var S=require("react/jsx-runtime"),rr=44,xo="flopay_checkout_saved_payment_resume",ko=new Map;function Cr(e){return new Promise(t=>setTimeout(t,e))}function Zr(e,t,n){let l=Fr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Le.SDK_VERSION,enabled:t!==!1});return l.beginCheckout(n),l}function Qr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ro(e,t,n,l,o){let s=Zr(e,t,n);s.error({errorCode:l,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Qr(s)}function Xi(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 _o(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function Io(e){return!e||e.data.stripe?.publishableKey?!1:!!_o(e)?.clientId}function or(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Zi(){if(!or())return null;try{let e=window.sessionStorage.getItem(xo);return e?JSON.parse(e):null}catch{return null}}function Oa(e){if(or())try{window.sessionStorage.setItem(xo,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Eo(){if(or())try{window.sessionStorage.removeItem(xo)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Qi(e){if(!or())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function es(e,t,n){if(or())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(l){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",l)}}function za(e){if(or())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function ts(){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 Ua(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 ns(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 eo({sessionId:e,nonce:t,createSession:n,billingApiUrl:l,telemetry:o,appearance:s,locale:u,loading:c,error:R,onComplete:L,onError:m,onDecline:_,onCountryChange:w,onZipChange:B,showPayPal:d=!0,showStripe:g=!0,showApplePay:I=!0,showGooglePay:A=!0,debug:P=!1,layout:H,theme:Q,buttonsTheme:me,buttonsStyles:se,cardButtonContent:z,cardBackButtonContent:te,cardTitleContent:K,showSecurityFooter:ye,onButtonClick:W,onBeforeButtonClick:Y,enableAVS:le,cardFieldOrder:Fe,cardPreFormSlot:he,avsLayout:ge,className:ne,initialErrorMessage:fe=null,children:ve,checkoutMode:ce,confirmLabel:Ne,renderConfirmButton:Ie,onSessionCompleted:we}){let E=(0,Le.resolveBillingApiUrl)(l),oe=(0,D.useMemo)(()=>(0,Le.resolveTheme)(Q),[Q]),de=s??oe?.appearance,Ue=n?"embedded_checkout":"standard_checkout",Oe=ve?"custom_layout":H==="buttons"?"buttons_layout":"default_layout",[ee,M]=(0,D.useState)(null),[G,ue]=(0,D.useState)(null),Ee=(0,D.useRef)(null),[gt,et]=(0,D.useState)(null),Qe=(0,D.useRef)(null),[y,je]=(0,D.useState)(null),[$e,He]=(0,D.useState)(e??""),Ke=e??$e,Wt=n?"":Ke,[bt,kt]=(0,D.useState)(!0),[h,ke]=(0,D.useState)(null),[Ve,lt]=(0,D.useState)("full"),[rt,ot]=(0,D.useState)(!1),[Ge,Ce]=(0,D.useState)(fe),[vt,We]=(0,D.useState)(null),[Dt,Rt]=(0,D.useState)(null),[dn,Sn]=(0,D.useState)(void 0),[wn,Nn]=(0,D.useState)(""),[ht,Lt]=(0,D.useState)(!1),[Nt,Yt]=(0,D.useState)("loading"),[Qt,un]=(0,D.useState)(0),J=(0,D.useRef)(!1),Mn=(0,D.useRef)(!1),pn=(0,D.useRef)(!1),Ot=(0,D.useRef)(null),at=(0,D.useMemo)(()=>({checkoutMode:ce??Ve,layout:ve?"unknown":H==="buttons"?"buttons":"embedded"}),[ce,ve,Ve,H]),f=(0,D.useRef)(L);f.current=L;let xe=(0,D.useRef)(m);xe.current=m;let ct=(0,D.useRef)(_);ct.current=_,(0,D.useEffect)(()=>{Mt(G)?.setCheckoutContext(at),gt&>!==G&&Mt(gt)?.setCheckoutContext(at)},[G,gt,at]);let kn=(0,D.useRef)(we);kn.current=we;let Te=(0,D.useCallback)(T=>{Yt(T),!(T!=="exhausted"||pn.current)&&(pn.current=!0,xe.current?.(new Le.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),An=(0,D.useCallback)(()=>{Yt("retrying"),un(T=>T+1)},[]);(0,D.useEffect)(()=>{Yt("loading"),un(0),pn.current=!1},[Ke]),(0,D.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Le.SDK_VERSION,checkout_type:Ue,checkout_layout:Oe,billing_api_url:E})},[Oe,Ue,E]);let mn=(0,D.useMemo)(()=>n?en(n):"",[n]),On=(0,D.useMemo)(()=>wn===mn?dn:void 0,[dn,wn,mn]),yn=(0,D.useMemo)(()=>n?go(n,On):void 0,[n,On]),zt=ce??yn?.checkoutMode??"full",Bt=(0,D.useMemo)(()=>yn?{...yn,checkoutMode:zt}:void 0,[yn,zt]);(0,D.useEffect)(()=>{Sn(void 0),Nn(mn)},[mn]),(0,D.useEffect)(()=>{Ce(fe)},[fe]);let Re=(0,D.useCallback)((T,U,q)=>{ft(()=>{ct.current?.(Tt(T,U,q))})},[ft]),pt=(0,D.useCallback)(async(T,U)=>{Ce(null),Rt(null),We("processing");let q=U?.sessionId??T.id,F=Ee.current??Qe.current,p=Mt(F),j=F?null:Zr(E,o,at),v={log:O=>{p?p.log(O):j?.log(O)},error:O=>{p?p.error(O):j?.error(O)},terminal:O=>{p?p.terminal(O):j?.terminal(O)},performance:O=>{p?p.performance(O):j?.performance(O)},now:()=>p?.now()??j?.now()??0,elapsed:O=>p?.elapsed(O)??Math.max(0,(j?.now()??O)-O)},Be=v.now(),X=!!(U?.initialAutoProcessingError||U?.initialAutoProcessingPending),Je=!1,ae,qt=()=>{Je||(Je=!0,X=!0,ae=v.now(),v.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),v.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},st=!1,N=()=>{st||(st=!0,v.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),v.performance({stage:"processing",durationMs:v.elapsed(Be),durationMode:"machine",paymentMethodCategory:"saved"}),ae!==void 0&&v.performance({stage:"recovery",durationMs:v.elapsed(ae),durationMode:"machine",paymentMethodCategory:"saved"}))};v.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),v.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),X&&qt();let b;try{let O=Da(U?.initialAutoProcessingError),Pe;if(O)qt(),O.type==="paypal_redirect_required"&&Ot.current?.publishableKey&&Oa({sessionId:q,publishableKey:Ot.current.publishableKey,paypalPublishableKey:Ot.current.paypalPublishableKey}),Pe=await Gr(O,{flopay:Ee.current,paypalFlopay:Qe.current,attempt3DS:U?.attempt3DS,billingApiUrl:E,sessionId:q,session:T,telemetry:!1}),O.type==="paypal_redirect_required"&&Eo();else if(U?.initialAutoProcessingPending){let qe=await new Sr.PaymentAPI(E,{telemetry:!1}).waitForCheckoutSessionCompletion(U.initialAutoProcessingPending.sessionId,{initialDelayMs:U.initialAutoProcessingPending.retryAfterMs});if(qe.data.session?.status!=="complete")throw new Le.FloPayError("Automatic payment failed. Please try again.","api_error",{code:qe.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});Pe={status:"succeeded"}}else{if(U?.initialAutoProcessingError)throw Ln(U.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:U.initialAutoProcessingError.checkoutMethod});if(U?.fromCreateSession)return U?.fallbackToFull&&(lt("full"),Ua("full")),!1;{let Me=await nr({billingApiUrl:E,sessionId:q,session:T,telemetry:!1});Me.type==="success"?Pe=Me.result:(qt(),Me.type==="paypal_redirect_required"&&Ot.current?.publishableKey&&Oa({sessionId:q,publishableKey:Ot.current.publishableKey,paypalPublishableKey:Ot.current.paypalPublishableKey}),Pe=await Gr(Me,{flopay:Ee.current,paypalFlopay:Qe.current,attempt3DS:U?.attempt3DS,billingApiUrl:E,sessionId:q,session:T,telemetry:!1}),Me.type==="paypal_redirect_required"&&Eo())}}q&&Qn(q),N(),X&&(v.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),v.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),v.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),We("success"),await Cr(_n),b=()=>f.current?.(Pe)}catch(O){let Pe=Hn(O),Me=Pe.checkoutMethod??vr;return Ce(Pe.message),Rt(Pe.message),U?.fallbackToFull&&(v.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),lt("full"),Ua("full")),N(),!!(Pe.declineCode||Pe.code?.toLowerCase().includes("declin"))?v.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):v.error({errorCode:X?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:X?"recovery":"processing",paymentMethodCategory:"saved"}),ft(()=>xe.current?.(Pe)),Re(Me,Pe,{code:Pe.code,declineCode:Pe.declineCode}),We("error"),await Promise.allSettled([Cr(Pn),U?.ensureProvidersReady?U.ensureProvidersReady():Promise.resolve()]),X&&(v.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),v.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{N(),j&&Qr(j),We(null),Rt(null)}return ft(b),!0},[Re,ft,Hn,E,o,at]);(0,D.useEffect)(()=>{if(typeof window>"u"||Mn.current)return;let T=new URLSearchParams(window.location.search),U=T.get("payment_intent_client_secret");if(!U)return;let q=Zi();q&&(Mn.current=!0,(async()=>{let F,p=0;Ce(null),Rt(null),We("processing"),ot(!0);try{if(T.get("redirect_status")==="failed")throw Object.assign(new Le.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:j,paypalFlopay:v}=await Xr({publishableKey:q.publishableKey,paypalPublishableKey:q.paypalPublishableKey,billingApiUrl:E,locale:u,telemetry:o});F=Mt(v??j),p=F?.now()??0,F?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),F?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Be=(v??j)?.getRawProvider();if(!Be)throw Object.assign(new Le.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:X,error:Je}=await Be.retrievePaymentIntent(U);if(Je)throw Object.assign(new Le.FloPayError(Je.message??"Failed to retrieve PayPal payment status.","api_error",{code:Je.code}),{checkoutMethod:"paypal"});let ae=ma(X?.status);if(!X||ae==="failed")throw Object.assign(new Le.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let qt=typeof X.payment_method=="string"?X.payment_method:X.payment_method?.id,st=ae;if(q.sessionId){let O=(await new Sr.PaymentAPI(E,{telemetry:!1}).getUnifiedCheckoutSession(q.sessionId)).data.session;if(O&&O.status!=="complete"){let Pe=await nr({billingApiUrl:E,sessionId:q.sessionId,session:O,telemetry:!1,tokenizedData:{id:qt??X.id,type:"card",threeDSecureActionResultTokenId:X.id,isPaypal:!0}});if(Pe.type!=="success")throw Object.assign(new Le.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});st=Pe.result.status}}q.sessionId&&Qn(q.sessionId),F?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),F?.performance({stage:"redirect_resume",durationMs:F.elapsed(p),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),F?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),We("success"),await Cr(_n),ft(()=>f.current?.({status:st,paymentIntentId:X.id,paymentMethodId:qt,checkoutMethod:"paypal"}))}catch(j){let v=Hn(j),Be=v.checkoutMethod??"paypal",X=!!(v.declineCode||v.code?.toLowerCase().includes("declin"));if(F)F.performance({stage:"redirect_resume",durationMs:F.elapsed(p),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),X?F.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):F.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(X){let Je=Zr(E,o,at);Je.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Qr(Je)}else Ro(E,o,at,"REDIRECT_RESUME_FAILED","redirect_resume");Ce(v.message),Rt(v.message),ft(()=>xe.current?.(v)),Re(Be,v,{code:v.code,declineCode:v.declineCode}),We("error"),await Cr(Pn)}finally{Eo(),ts(),We(null),Rt(null),ot(!1)}})())},[Re,ft,u,Hn,E,o]);let it=(0,D.useRef)(null);function en(T){let U=JSON.stringify({c:T?.clientId,cur:T?.currency??"",a:{e:T?.account?.email?.trim().toLowerCase()??"",country:T?.account?.country??""},successUrl:T?.successUrl,cancelUrl:T?.cancelUrl,p:T?.products?.map(F=>`${F.type??""}:${F.code??F.providerItemId??F.providerPlanId??""}:${F.totalAmount??""}:${F.overrideAmount??""}:${F.quantity??1}`).sort(),i:T?.items?.map(F=>`${F.code??F.providerItemId??""}:${F.totalAmount??""}:${F.overrideAmount??""}:${F.quantity??1}`).sort(),s:T?.subscriptions?.map(F=>`${F.code??F.providerPlanId??""}:${F.totalAmount??""}:${F.overrideAmount??""}:${F.quantity??1}`).sort(),couponCodes:T?.couponCodes,tagsData:T?.tagsData,utmMetadata:T?.utmMetadata,tokenizedData:T?.tokenizedData,m:T?.checkoutMode??"full"}),q=0;for(let F=0;F<U.length;F++)q=(q<<5)-q+U.charCodeAt(F)|0;return`flopay_session_${Math.abs(q).toString(36)}`}let Gt=(0,D.useMemo)(()=>Bt?en(Bt):"",[Bt]),Pt=(0,D.useRef)(Bt);Pt.current=Bt,(0,D.useEffect)(()=>{He(e??"")},[e]),(0,D.useEffect)(()=>{J.current=!1,Ce(fe),Rt(null),We(null)},[Gt,fe,e]);async function Vt(T,U){let q=Zr(E,o,at),F=new Sr.PaymentAPI(E,{telemetry:!1});try{let p=Qi(U);q.log({name:p?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let j=p?.sid??null,v=null;if(j)try{if(v=await F.getUnifiedCheckoutSession(j,p?.nonce),v.data.session?.status==="complete"){if(fa(j))return{sid:j,result:v};za(U),j=null,v=null}}catch{q.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),za(U),j=null}if(!j){let Be=q.now();q.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let X={...T,avsCheck:!!le,avsConfig:typeof le=="object"?le:void 0,checkoutType:"embedded_checkout",checkoutLayout:ve?"custom_layout":H==="buttons"?"buttons_layout":"default_layout"};try{v=await F.createAndFetchSession(X),q.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),q.performance({stage:"session_create",durationMs:q.now()-Be,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"})}catch(Je){throw q.performance({stage:"session_create",durationMs:q.now()-Be,durationMode:"machine",requestCategory:"session_create",statusClass:"network_error"}),Je instanceof Le.FloPayError&&Je.type==="validation_error"?q.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):q.error({errorCode:"CHECKOUT_SESSION_CREATE_FAILED",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Je}j=v.data.session?.id??"",j&&es(U,j,v.data.session?.clientSecret)}return{sid:j??"",result:v}}finally{Qr(q)}}let Ct=(0,D.useCallback)(async T=>{let U=Pt.current;if(!U)throw new Le.FloPayError("createSession is required to bootstrap checkout.","validation_error");let q=go(U,T),F=en(q),p=ko.get(F);p||(p=Vt(q,F),ko.set(F,p));let j;try{j=await p}finally{ko.delete(F)}it.current=F;try{T&&(Nn(mn),Sn(st=>ua(st,T)));let{sid:v,result:Be}=j;M(Be),Be.data.session&&je(Be.data.session),v&&He(v);let{publishableKey:X,paypalPublishableKey:Je}=Jr(Be),{flopay:ae,paypalFlopay:qt}=await Xr({publishableKey:X,paypalPublishableKey:Je,billingApiUrl:E,locale:u,telemetry:o});Ee.current=ae,ue(ae),Qe.current=qt,et(qt),kt(!1)}catch(v){throw it.current===F&&(it.current=null),v}return j},[u,E,o,at]),tn=(0,D.useCallback)(async T=>{if(!ns(T)||ht)return{sessionId:$e,session:y};Lt(!0);try{let U=await Ct(T);return{sessionId:U.sid,session:U.result.data.session??null}}finally{Lt(!1)}},[Ct,ht,$e,y]);(0,D.useEffect)(()=>{let T=!1;if(ke(null),Gt){let F=Pt.current;return lt(zt),kt(!1),it.current===Gt?()=>{T=!0}:(je(pa(F,ce)),(async()=>{let p=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),j=zt==="auto"&&!J.current&&!p;j&&(Ce(null),Rt(null),We("processing"));try{let v=await Ct(),Be=v.result.data.session??null;Ot.current=Jr(v.result);let X=Io(v.result);if(!T&&j&&Be&&!X){J.current=!0,await pt(Be,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:v.result.autoProcessingError,initialAutoProcessingPending:v.result.autoProcessingPending,autoProcessingAttempted:v.result.autoProcessingAttempted,sessionId:v.sid||Be.id});return}!T&&j&&(X&&(J.current=!0),We(null),Rt(null))}catch(v){if(T)return;let Be=v instanceof Le.FloPayError||typeof v=="object"&&v!==null&&"code"in v?v.code:void 0;if(j&&Be==="session_auto_completed"){J.current=!0,We("success"),await Cr(_n),T||(ft(()=>{f.current?.({status:"succeeded"})}),We(null),Rt(null));return}j&&(We(null),Rt(null));let X=v instanceof Le.FloPayError?v:new Le.FloPayError(v instanceof Error?v.message:"Failed to create session","api_error");ke(X)}})(),()=>{T=!0})}kt(!0);async function U(){let F=!1;try{let j=await new Sr.PaymentAPI(E,{telemetry:!1}).getUnifiedCheckoutSession(Ke,t);if(T)return;M(j);let v=j.data.session??null;if(je(v),!v)throw new Le.FloPayError("No session data returned","api_error");if(v.status==="complete"){kt(!1),ft(()=>{kn.current?.(v.successUrl??"")});return}if(v.status==="expired")throw new Le.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});F=!0;let Be=ce??v.checkoutMode??"full";lt(Be);let X=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Je=Io(j);if(Be==="auto"&&!J.current&&!X&&!Je){J.current=!0;let ae=q(j);try{if(await pt(v,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ae,sessionId:Ke||v.id}),T)return;await ae,T||kt(!1);return}catch{if(T)return;await ae,T||kt(!1);return}}await q(j),T||kt(!1)}catch(p){if(T)return;p instanceof Le.FloPayError?!F&&!Xi(p)&&Ro(E,o,at,"NETWORK_REQUEST_FAILED","session_read"):Ro(E,o,at,"INTERNAL_SDK_ERROR","checkout_mount");let j=p instanceof Le.FloPayError?p:new Le.FloPayError(p instanceof Error?p.message:"Failed to initialize checkout","api_error");ke(j),kt(!1)}}async function q(F){let{publishableKey:p,paypalPublishableKey:j}=Jr(F);Ot.current={publishableKey:p,paypalPublishableKey:j};let{flopay:v,paypalFlopay:Be}=await Xr({publishableKey:p,paypalPublishableKey:j,billingApiUrl:E,locale:u,telemetry:o});Ee.current=v,ue(v),Qe.current=Be,et(Be)}return U(),()=>{T=!0}},[Ct,ce,Gt,zt,Wt,ft,t,pt]);let fn=(0,D.useCallback)(async()=>{if(!(rt||!y)){ot(!0),Ce(null);try{await pt(y,{fallbackToFull:!0,sessionId:Ke||y.id})}finally{ot(!1)}}},[Ke,rt,pt,y]),Rn=_o(ee),gn=Io(ee),Ht=(0,D.useMemo)(()=>{if(!ee||!y||!ee.data.stripe?.publishableKey)return;let T={appearance:de,paymentMethodCreation:"manual",billingApiUrl:E};if(ee.data.stripe?.clientSecret)T.clientSecret=ee.data.stripe.clientSecret;else{let U=(0,Le.buildCheckoutDisplayData)(y).total;T.amount=Math.round(U*100)||y.amount,T.currency=y.currency?.toLowerCase()}return T},[ee,y,de,E]),Ye=!!(n&&!ve&&H==="buttons"&&Y&&zt==="full"),Kt=(0,D.useMemo)(()=>({session:y,loading:bt,error:h,checkoutMode:Ve,inlineSessionDraft:Bt,applyInlineSessionPatch:Ye?tn:void 0,inlineSessionPatchProcessing:ht}),[y,bt,h,Ve,Bt,Ye,tn,ht]),Ut=!!n&&H==="buttons"&&!gn&&(!G||!Ht),$t=vt?(0,S.jsx)(bn,{status:vt,errorMessage:Dt}):null;if(bt){if(c)return(0,S.jsxs)(S.Fragment,{children:[c,$t]});if(H==="buttons"){let T=oe?.buttonsLayout?.cardButton?.borderRadius??oe?.appearance.variables?.borderRadius??8,U=q=>(0,S.jsx)("div",{style:{height:q,borderRadius:T,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&&U(rr),g&&(I||A)&&U(rr),g&&U(rr),(0,S.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),$t]})}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); } }"})]}),$t]})}return h?R?(0,S.jsx)(rn.Provider,{value:Kt,children:R(h)}):(0,S.jsx)(rn.Provider,{value:Kt,children:(0,S.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:h.message})}):Ut?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(rn.Provider,{value:Kt,children:(0,S.jsx)(os,{onButtonClick:W,showPayPal:d,showStripe:g,showApplePay:I,showGooglePay:A,theme:Q,buttonsTheme:me,buttonsStyles:se,cardButtonContent:z,cardBackButtonContent:te,cardTitleContent:K})}),$t]}):gn&&y&&Rn?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(rn.Provider,{value:Kt,children:(0,S.jsxs)("div",{className:ne,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ge&&(0,S.jsx)(Xn,{icon:!1,children:Ge}),Nt==="retrying"&&(0,S.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Nt==="exhausted"&&(0,S.jsxs)("div",{role:"alert",children:[(0,S.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,S.jsx)("button",{type:"button",onClick:An,children:"Retry PayPal"})]}),Nt!=="exhausted"&&(0,S.jsx)("div",{"aria-hidden":Nt==="retrying"?!0:void 0,style:Nt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,S.jsx)(Ca,{sessionId:Ke,nonce:y.clientSecret||void 0,billingApiUrl:E,email:y.customer?.email,clientId:Rn.clientId,environment:Rn.environment,currency:(y.currency??"usd").toUpperCase(),isSubscription:y.mode==="subscription",onComplete:L,onErrorChange:Ce,onDecline:_,onButtonClick:W,onInitializationStateChange:Te,allowAutomaticRetry:Qt===0,session:y,telemetry:o,telemetryContext:at,debug:P},`paypal-init-${Qt}`)})]})}),$t]}):!G||!Ht?(0,S.jsx)(S.Fragment,{children:$t}):Ve==="confirm"?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(rn.Provider,{value:Kt,children:(0,S.jsx)(yr,{flopay:G,paypalFlopay:gt,options:Ht,children:(0,S.jsxs)("div",{className:ne,children:[Ge&&(0,S.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ge}),Ie?Ie({onConfirm:fn,isProcessing:rt}):(0,S.jsx)("button",{type:"button",onClick:fn,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"})]})})}),$t]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(rn.Provider,{value:Kt,children:(0,S.jsx)(yr,{flopay:G,paypalFlopay:gt,options:Ht,children:ve?(0,S.jsxs)(S.Fragment,{children:[Ge&&(0,S.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ge}),(0,S.jsx)(rs,{sessionId:Ke,nonce:y?.clientSecret||void 0,billingApiUrl:E,session:y,children:ve})]}):(0,S.jsx)(Wr,{sessionId:Ke,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,Le.buildCheckoutDisplayData)(y).total*100):0,currency:y?.currency?.toLowerCase()??"usd",onComplete:L,onError:m,onDecline:_,error:Ge,onErrorChange:Ce,showPayPal:d,showStripe:g,enabledPaymentMethods:ee?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ee?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:A,layout:H,theme:Q,buttonsTheme:me,buttonsStyles:se,appearance:de,cardButtonContent:z,cardBackButtonContent:te,cardTitleContent:K,onButtonClick:W,onBeforeButtonClick:Y,enableAVS:le,...Fe?{cardFieldOrder:Fe}:{},...he?{cardPreFormSlot:he}:{},avsLayout:ge,country:y?.customer?.country,city:y?.customer?.city,state:y?.customer?.state,onCountryChange:w,onZipChange:B,avsCheck:!!le,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ve?"custom_layout":H==="buttons"?"buttons_layout":"default_layout",className:ne,directPaypal:_o(ee),isSubscription:y?.mode==="subscription",session:y,debug:P})})}),$t]})}function rs({sessionId:e,nonce:t,billingApiUrl:n,session:l,children:o}){return(0,S.jsx)(S.Fragment,{children:D.default.Children.map(o,s=>{if(!D.default.isValidElement(s))return s;let u=s.props,c={};return u.sessionId||(c.sessionId=e),!u.nonce&&t&&(c.nonce=t),u.billingApiUrl||(c.billingApiUrl=n),l?.customer&&(u.email||(c.email=l.customer.email),u.userId||(c.userId=l.customer.id),u.firstName||(c.firstName=l.customer.firstName),u.lastName||(c.lastName=l.customer.lastName)),Object.keys(c).length===0?s:D.default.cloneElement(s,c)})})}function os({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:l,showGooglePay:o,theme:s,buttonsTheme:u,buttonsStyles:c,cardButtonContent:R,cardBackButtonContent:L,cardTitleContent:m}){let[_,w]=(0,D.useState)(!1),B=(0,D.useMemo)(()=>(0,Le.resolveTheme)(s),[s]),d=(0,D.useMemo)(()=>{let P=B?.buttonsLayout??(0,Le.resolveButtonsLayoutTheme)(u);return c?{...P,...c,cardButton:{...P.cardButton,...c.cardButton},cardFormContainer:{...P.cardFormContainer,...c.cardFormContainer},backButton:{...P.backButton,...c.backButton},backButtonIcon:{...P.backButtonIcon,...c.backButtonIcon},submitButton:{...P.submitButton,...c.submitButton},title:{...P.title,...c.title}}:P},[B,u,c]),g=B?.buttonsLayout?.cardButton?.borderRadius??B?.appearance.variables?.borderRadius??8,I=P=>(0,S.jsx)("div",{style:{height:P,borderRadius:g,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),A=R===void 0?{boxSizing:"border-box",height:rr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let P=d.cardInputBorder??"#e5e7eb",H=d.cardInputBackground??"white",Q=Yn(L),me=Yn(m);return(0,S.jsxs)("div",{style:{backgroundColor:d.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...d.cardFormContainer},children:[(0,S.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,S.jsxs)("button",{type:"button",onClick:()=>w(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...d.backButton},children:[(0,S.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...d.backButtonIcon},children:(0,S.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,S.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,S.jsx)(Jn,{content:L})]}),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)(fr,{content:m})})]}),(0,S.jsx)("div",{style:{backgroundColor:H,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:H,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:H,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:H,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
|
+
`}),ur&&Wt&&(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:f?-2:0},children:[(0,i.jsxs)("button",{type:"button",onClick:hn,style:{display:"inline-flex",alignItems:"center",gap:po?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(Jn,{content:G})]}),Yo?(0,i.jsx)("div",{style:{flex:1}}):(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...p.title},children:(0,i.jsx)(gr,{content:le})})]}),!ur&&!Yo&&(0,i.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:mo,order:f?-3:0,...p.title},children:(0,i.jsx)(gr,{content:le})}),X&&(0,i.jsx)("div",{style:{order:f?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=je,C=(q=!1)=>({backgroundColor:mr,border:`1px solid ${zn(q)}`,borderRadius:pt,marginTop:"0.5rem",padding:"10px"}),V=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Zo}),ie=(0,k.getStateOptions)(a);return(0,i.jsxs)(i.Fragment,{children:[(0,k.isAVSFieldVisible)(X.address_line_1,a)&&(0,i.jsx)("div",{style:C(Te.line1),children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Ye,onChange:q=>{Dt.current=q.target.value,Ce(q.target.value)},disabled:Z,required:!0,"data-testid":"flopay-address-line1",style:V()})}),(0,k.isAVSFieldVisible)(X.address_line_2,a)&&(0,i.jsx)("div",{style:C(),children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:bt,onChange:q=>{Kt.current=q.target.value,Ke(q.target.value)},disabled:Z,"data-testid":"flopay-address-line2",style:V()})}),((0,k.isAVSFieldVisible)(X.city,a)||(0,k.isAVSFieldVisible)(X.state,a))&&(0,i.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,k.isAVSFieldVisible)(X.city,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:mr,borderTop:`1px solid ${zn(Te.city)}`,borderRight:`1px solid ${zn(Te.city)}`,borderBottom:`1px solid ${zn(Te.city)}`,borderLeft:`1px solid ${zn(Te.city)}`,padding:"10px",borderTopLeftRadius:pt,borderBottomLeftRadius:pt,...(0,k.isAVSFieldVisible)(X.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:pt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:At,onChange:q=>{Qt.current=q.target.value,kt(q.target.value)},disabled:Z,required:!0,"data-testid":"flopay-city",style:V()})}),(0,k.isAVSFieldVisible)(X.state,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:mr,border:`1px solid ${zn(Te.state)}`,padding:"10px",borderTopRightRadius:pt,borderBottomRightRadius:pt,...(0,k.isAVSFieldVisible)(X.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:pt}},children:ie?(0,i.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:pn,onChange:q=>{mn.current=q.target.value,wn(q.target.value)},disabled:Z,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...V(),cursor:"pointer"},children:[(0,i.jsx)("option",{value:"",children:(0,k.getStateLabel)(a)}),ie.map(q=>(0,i.jsx)("option",{value:q.code,children:q.name},q.code))]}):(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,k.getStateLabel)(a),autoComplete:"billing address-level1",value:pn,onChange:q=>{mn.current=q.target.value,wn(q.target.value)},disabled:Z,required:!0,"data-testid":"flopay-state",style:V()})})]}),((0,k.isAVSFieldVisible)(X.country,a)||(0,k.isAVSFieldVisible)(X.postal_code,a))&&(0,i.jsxs)("div",{style:{display:"flex",flexDirection:ce==="column"?"column":"row",gap:ce==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,k.isAVSFieldVisible)(X.country,a)&&(0,i.jsx)("div",{style:{flex:ce==="row"?1:void 0,backgroundColor:mr,borderTop:`1px solid ${pr}`,borderRight:`1px solid ${pr}`,borderBottom:`1px solid ${pr}`,borderLeft:`1px solid ${pr}`,padding:"10px",...ce==="row"&&(0,k.isAVSFieldVisible)(X.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:pt,borderBottomLeftRadius:pt,borderRight:"none"}:{borderRadius:pt}},children:(0,i.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:je,onChange:q=>{Ft.current=q.target.value,lt(q.target.value),ze?.(q.target.value),mn.current="",wn("")},disabled:Z,autoComplete:"billing country","data-testid":"flopay-country",style:{...V(),cursor:"pointer"},children:k.COUNTRY_OPTIONS.map(q=>(0,i.jsxs)("option",{value:q.code,children:[q.flag," ",q.name]},q.code))})}),(0,k.isAVSFieldVisible)(X.postal_code,a)&&(0,i.jsx)("div",{style:{flex:ce==="row"?1:void 0,backgroundColor:mr,border:`1px solid ${li}`,padding:"10px",...ce==="row"&&(0,k.isAVSFieldVisible)(X.country,a)?{borderRadius:"0",borderTopRightRadius:pt,borderBottomRightRadius:pt}:{borderRadius:pt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,k.getPostalCodeLabel)(je),autoComplete:"billing postal-code",value:nt,onChange:q=>{gt.current=q.target.value,rt(q.target.value),Oe?.(q.target.value)},onBlur:()=>gn(!0),disabled:Z,required:ct.required,"aria-invalid":Tr||void 0,"aria-describedby":Tr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:V()})})]}),Tr&&(0,i.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:co,...Zo,fontSize:"0.75rem"},children:ct.empty?`${(0,k.getPostalCodeLabel)(a)} is required`:$i(a)})]})})()}),f&&ve&&(0,i.jsx)("div",{style:{order:-2,width:"100%"},children:ve}),f&&mi,j&&(0,i.jsx)(Xn,{margin:"0.75rem 0",styleOverride:p.errorBanner,children:j})]}),Br={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},ea=a=>qe?!I||!st?(0,i.jsx)("pre",{"data-testid":a,style:Br,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:Br,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${I}`,` directPaypalConfigured=${st}`,` inAppBrowserDetected=${String(_r)}`,` shouldRenderDirectPayPal=${sr}`,` shouldRenderStripePayPal=${lr}`,` hasPaypalStripeInstance=${!!O}`].join(`
|
|
39
|
+
`)}):null,ta=a=>qe?!F||!it?(0,i.jsx)("pre",{"data-testid":a,style:Br,children:"FloPay/Stripe-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:Br,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${F}`,` currency=${Ie}`,` amountInCents=${b}`,` enabledPaymentMethods: ${JSON.stringify(P??[])}`,` enabledPaymentMethodsProvided=${ar}`,` hasEnabledMethods=${kr}`,` expressMethods: ${JSON.stringify(Rr)}`,` walletExpressMethods: ${JSON.stringify(Ir)}`,` paymentElementMethods: ${JSON.stringify(ir)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Er)}`,` hasStripeInstance=${!!it}`,` shouldRenderWallets=${cr}`,` shouldRenderPaymentElement=${dr}`].join(`
|
|
40
|
+
`)}):null,na=ke==="apm-expanding"||ke==="apm-form"||ke==="apm-collapsing",Mr=ke==="apm-expanding"?`flopay-card-enter ${ht}ms cubic-bezier(0, 0, 0.2, 1) both`:ke==="apm-collapsing"?`flopay-card-exit ${ht}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Ar=at?{...oo,paymentMethodTypes:[at]}:null;if(se==="buttons"){let a=ke==="buttons"||ke==="expanding"||ke==="apm-expanding",C=ke==="expanding"||ke==="card"||ke==="collapsing",V=Y===void 0?{boxSizing:"border-box",height:Kr,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ie=ke==="expanding"||ke==="apm-expanding"?`flopay-buttons-exit ${ht}ms cubic-bezier(0.4, 0, 0.2, 1) both`:ke==="collapsing"||ke==="apm-collapsing"?`flopay-buttons-enter ${ht}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,q=ke==="expanding"?`flopay-card-enter ${ht}ms cubic-bezier(0, 0, 0.2, 1) both`:ke==="collapsing"?`flopay-card-exit ${ht}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,i.jsxs)("form",{onSubmit:so,className:w,style:{position:"relative"},children:[(0,i.jsx)(Co,{}),jt&&(0,i.jsx)(vn,{status:jt,errorMessage:j}),(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?Oi:{},...ie?{animation:ie,pointerEvents:"none"}:{}},children:[ea("flopay-direct-paypal-gate-debug"),ta("flopay-stripe-gate-debug"),sr&&Qe&&(0,i.jsxs)(i.Fragment,{children:[Ot&&(0,i.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,i.jsx)(br,{sessionId:e,nonce:t,billingApiUrl:$,email:ae.email,clientId:Qe.clientId,environment:Qe.environment,currency:Ie.toUpperCase(),isSubscription:Ze,onTokenizedBody:Jt,onComplete:s,onErrorChange:x,onDecline:c,onTechnicalFailure:fe,onButtonClick:be,runBeforeButtonClick:rn,isProcessing:Z,onLoadStateChange:ao,onInitializationStateChange:io,session:y??null,existingOrderId:Ot?.orderId,debug:qe},Ot?.orderId??"fresh")]}),lr&&(0,i.jsx)(dt.Elements,{stripe:O,options:nn,children:(0,i.jsx)(_a,{sessionId:e,nonce:t,email:ae.email,billingApiUrl:$,onTokenizedBody:Jt,onErrorChange:x,isProcessing:Z,onButtonClick:be,onDecline:c,onTechnicalFailure:fe,runBeforeButtonClick:rn,onLoadStateChange:Ao,placeholderBorderRadius:Un})}),cr?(0,i.jsx)(dt.Elements,{stripe:it,options:$e,children:(0,i.jsx)(xa,{sessionId:e,nonce:t,email:ae.email,billingApiUrl:$,intentKind:ue>0?"payment":"setup",expressMethods:Ir,onTokenizedBody:Jt,onErrorChange:x,onButtonClick:be,onDecline:c,onTechnicalFailure:fe,runBeforeButtonClick:rn,onLoadStateChange:Do,placeholderBorderRadius:Un})}):Uo?(0,i.jsx)("div",{style:{height:Kr,borderRadius:Un,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,dr&&(0,i.jsx)(Ta,{sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:$,paymentElementMethods:Er,stripeInstance:it,paymentElementBaseOptions:oo,onTokenizedBody:Jt,onErrorChange:x,onButtonClick:be,onDecline:c,runBeforeButtonClick:rn,onLoadStateChange:No,isProcessing:Z,submitButtonColor:$n,submitButtonBorderRadius:pt,submitButtonStyle:p.submitButton,onExpandApm:In,expandedApmMethod:at,themeId:U,buttonAppearance:{backgroundColor:p.cardButton?.backgroundColor,borderColor:p.cardInputBorder,textColor:p.cardButton?.color,borderRadius:Un}}),f&&(0,i.jsx)("button",{type:"button",onClick:async()=>{Z||!(await rn("card")).proceed||(be?.("card"),tn())},disabled:Z,style:{width:"100%",...V,...p.cardButton,...wo({themeBundle:D,resolvedPrimaryColor:$n,resolvedBorderRadius:pt,submitButtonStyle:p.submitButton,explicitPrimaryColor:$t?.colorPrimary}),fontSize:p.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Z?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Z?.6:1},onMouseEnter:re=>{!Z&&(D||$t?.colorPrimary)&&(re.currentTarget.style.backgroundColor=ui)},onMouseLeave:re=>{(D||$t?.colorPrimary)&&(re.currentTarget.style.backgroundColor=$n)},onMouseDown:re=>{re.currentTarget.style.transform="scale(0.985)"},onMouseUp:re=>{re.currentTarget.style.transform="scale(1)"},children:(0,i.jsx)(Gn,{content:Y})}),j&&ke==="buttons"&&(0,i.jsx)(Xn,{margin:"0.25rem 0",styleOverride:p.errorBanner,children:j})]}),f&&C&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...q?{animation:q}:{},...ke==="collapsing"?{pointerEvents:"none"}:{}},children:Qo}),F&&na&&at&&Ar&&it&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...Mr?{animation:Mr}:{},...ke==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:uo,borderRadius:fo,...yr,padding:yo},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,i.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Pn,style:{display:"inline-flex",alignItems:"center",gap:po?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(Jn,{content:G})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:mo,paddingRight:80,...p.title},children:`Pay with ${(0,k.getStripeMethodDisplayName)(at)}`})]}),(0,i.jsx)(dt.Elements,{stripe:it,options:Ar,children:(0,i.jsx)(So,{method:at,sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:$,onTokenizedBody:Jt,onErrorChange:x,onDecline:c,onCancel:Pn,runBeforeButtonClick:rn,onButtonClick:be,isProcessing:Z,submitButtonColor:$n,submitButtonBorderRadius:pt,submitButtonStyle:p.submitButton,errorText:j})},at)]})})]})]})}return na&&at&&Ar&&it&&F?(0,i.jsxs)("form",{onSubmit:so,className:w,style:{position:"relative"},children:[(0,i.jsx)(Co,{}),jt&&(0,i.jsx)(vn,{status:jt,errorMessage:j}),(0,i.jsx)("div",{style:{...Mr?{animation:Mr}:{},...ke==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:uo,borderRadius:fo,...yr,padding:yo},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,i.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Pn,style:{display:"inline-flex",alignItems:"center",gap:po?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(Jn,{content:G})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:mo,paddingRight:80,...p.title},children:`Pay with ${(0,k.getStripeMethodDisplayName)(at)}`})]}),(0,i.jsx)(dt.Elements,{stripe:it,options:Ar,children:(0,i.jsx)(So,{method:at,sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:$,onTokenizedBody:Jt,onErrorChange:x,onDecline:c,onCancel:Pn,runBeforeButtonClick:rn,onButtonClick:be,isProcessing:Z,submitButtonColor:$n,submitButtonBorderRadius:pt,submitButtonStyle:p.submitButton,errorText:j})},at)]})})]}):(0,i.jsxs)("form",{onSubmit:so,className:w,style:{position:"relative"},children:[(0,i.jsx)(Co,{}),jt&&(0,i.jsx)(vn,{status:jt,errorMessage:j}),(0,i.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ea("flopay-direct-paypal-gate-debug-default"),ta("flopay-stripe-gate-debug-default"),sr&&Qe&&(0,i.jsxs)(i.Fragment,{children:[Ot&&(0,i.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,i.jsx)(br,{sessionId:e,nonce:t,billingApiUrl:$,email:ae.email,clientId:Qe.clientId,environment:Qe.environment,currency:Ie.toUpperCase(),isSubscription:Ze,onTokenizedBody:Jt,onComplete:s,onErrorChange:x,onDecline:c,onTechnicalFailure:fe,onButtonClick:be,runBeforeButtonClick:rn,isProcessing:Z,onLoadStateChange:ao,onInitializationStateChange:io,session:y??null,existingOrderId:Ot?.orderId,debug:qe},Ot?.orderId??"fresh")]}),lr&&(0,i.jsx)(dt.Elements,{stripe:O,options:nn,children:(0,i.jsx)(_a,{sessionId:e,nonce:t,email:ae.email,billingApiUrl:$,onTokenizedBody:Jt,onErrorChange:x,isProcessing:Z,onButtonClick:be,onDecline:c,onTechnicalFailure:fe,runBeforeButtonClick:rn,onLoadStateChange:Ao,placeholderBorderRadius:Un})}),cr&&(0,i.jsx)(dt.Elements,{stripe:it,options:$e,children:(0,i.jsx)(xa,{sessionId:e,nonce:t,email:ae.email,billingApiUrl:$,intentKind:ue>0?"payment":"setup",expressMethods:Ir,onTokenizedBody:Jt,onErrorChange:x,onButtonClick:be,onDecline:c,onTechnicalFailure:fe,runBeforeButtonClick:rn,onLoadStateChange:Do,placeholderBorderRadius:Un})}),dr&&(0,i.jsx)(Ta,{sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:$,paymentElementMethods:Er,stripeInstance:it,paymentElementBaseOptions:oo,onTokenizedBody:Jt,onErrorChange:x,onButtonClick:be,onDecline:c,runBeforeButtonClick:rn,onLoadStateChange:No,isProcessing:Z,submitButtonColor:$n,submitButtonBorderRadius:pt,submitButtonStyle:p.submitButton,themeId:U,onExpandApm:In,expandedApmMethod:at,buttonAppearance:{backgroundColor:p.cardButton?.backgroundColor,borderColor:p.cardInputBorder,textColor:p.cardButton?.color,borderRadius:Un}})]}),f&&(oi||ri||ai)&&(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&&Qo]})}var tr=require("@flopay/js"),Xe=require("@flopay/shared");var Cr="card";async function Ki(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 Wi(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 La(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 Yi(e){return e.status==="succeeded"||e.status==="declined"}async function Na(e){if(typeof document>"u"||typeof window>"u")throw new Xe.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Xe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,l=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,s=async()=>{let m=new AbortController,_=()=>m.abort();e.signal?.aborted?m.abort():e.signal?.addEventListener("abort",_);let w=window.setTimeout(()=>m.abort(),l);try{let M=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:m.signal});if(!M.ok)return{status:"unknown"};let d=await M.json().catch(()=>null);return Gi(d)}catch{return{status:"unknown"}}finally{window.clearTimeout(w),e.signal?.removeEventListener("abort",_)}},u=document.activeElement instanceof HTMLElement?document.activeElement:null,c=document.createElement("div");c.setAttribute("data-flopay-auto-3ds-overlay","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let R=document.createElement("iframe");R.setAttribute("title","Card authentication"),R.setAttribute("allow","payment"),R.tabIndex=0,R.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),R.src=e.nextActionRedirectUrl,c.appendChild(R),document.body.appendChild(c),R.focus();let N=null;try{N=new URL(e.billingApiUrl,window.location.href).origin}catch{N=null}try{let m=await new Promise((_,w)=>{let M=!1,d=0,g=0,I=0,F=!1,P=()=>{window.clearTimeout(d),window.clearInterval(g),window.clearTimeout(I),window.removeEventListener("message",se),R.removeEventListener("load",Q),e.signal?.removeEventListener("abort",pe)},K=async()=>{if(!(M||F)){F=!0;try{let U=await s();if(M||!Yi(U))return;M=!0,P(),_(U)}finally{F=!1}}},Q=()=>{window.clearTimeout(I),I=window.setTimeout(()=>{K()},250)},pe=()=>{M||(M=!0,P(),w(new Xe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},se=U=>{if(U.source!==R.contentWindow||N&&U.origin!==N)return;let te=U.data;!te||typeof te!="object"||te.source!=="flopay-vault-3ds-return"||M||(M=!0,P(),_(null))};d=window.setTimeout(()=>{M||(M=!0,P(),w(new Xe.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),g=window.setInterval(()=>{K()},n),R.addEventListener("load",Q),window.addEventListener("message",se),e.signal?.addEventListener("abort",pe),e.signal?.aborted&&pe()});return m||await s()}finally{c.parentNode?.removeChild(c),u?.isConnected&&u.focus()}}function Gi(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Ln(e,t="Payment failed. Please try again.",n){let l=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,s=Fn(o)??o;return Sn(new Xe.FloPayError(s,"api_error",{code:e?.gatewayErrorCode}),l)}function ko(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Gr(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Ji(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 Oa(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Gr(o)))return o;let l=e?.data;if(l&&typeof l=="object"){let o=l,s=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let c of s)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||Gr(c)))return c;let u=o.gateways;if(u&&typeof u=="object"){let c=u.stripe;if(c&&typeof c=="object"){let R=c,N=[R.stripeClientSecret,R.clientSecret];for(let m of N)if(typeof m=="string"&&m.length>0&&(!t?.requirePaymentIntentClientSecret||Gr(m)))return m}}}}async function Xi({billingApiUrl:e,sessionId:t,nonce:n,responseJson:l}){let o=Oa(l,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let c=(await new tr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Gr(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function nr({billingApiUrl:e,sessionId:t,session:n,nonce:l,tokenizedData:o,returnUrl:s,telemetry:u}){let c=e.replace(/\/+$/,""),R=t??n.id,N=l??n.clientSecret,m=n.customer?.id??n.accountData?.userId??"",_=n.customer?.email??n.accountData?.email??"",w=n.customer?.firstName??n.accountData?.firstName??"",M=n.customer?.lastName??n.accountData?.lastName??"",d=n.customer?.country??n.accountData?.country??void 0,g=n.customer?.zip??n.accountData?.zip??void 0,I=new tr.PaymentAPI(c,u===!1?{telemetry:!1}:void 0),F=await Ji(()=>I.processPayment(m,{sessionId:R,nonce:N,tokenizedData:o,accountData:{userId:m,email:_,firstName:w,lastName:M,country:d,zip:g},returnUrl:s??ko(n)}));if(F.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:$r(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let P=await F.json().catch(()=>null);if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let K=Oa(P);if(!K)throw new Xe.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:P.type,threeDSecureToken:K,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let K=await Xi({billingApiUrl:c,sessionId:R,nonce:N,responseJson:P});if(K)return K;throw Sn(new Xe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new Xe.FloPayError(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason})}async function Jr(e,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:u,returnUrl:c,telemetry:R}){let N=t?.getRawProvider();if(!N)throw new Xe.FloPayError("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!l||!e.threeDSecureToken)throw Sn(new Xe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let m=(0,Xe.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,w=e.paymentMethodId,M=await Ki(N,e.threeDSecureToken,m);if(M){if(M.error)throw Sn(new Xe.FloPayError(M.error.message??`Failed to retrieve 3DS ${m?"setup":"payment"} status.`,"api_error",{code:M.error.code}),"card");let g=M.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 Wi(N,e.threeDSecureToken,{payment_method:w,return_url:c??ko(u)??window.location.href},m):null;if(d){if(d.error)throw Sn(new Xe.FloPayError(d.error.message??"3DS authentication failed.","api_error",{code:d.error.code}),"card");_=d.intent}else{let g=await N.handleNextAction({clientSecret:e.threeDSecureToken});if(g.error)throw Sn(new Xe.FloPayError(g.error.message??"3DS authentication failed.","api_error",{code:g.error.code}),"card");_=(m?g.setupIntent:g.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let g=await nr({billingApiUrl:o,sessionId:s,session:u,telemetry:R,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:c});return g.type==="success"?{...g.result,paymentIntentId:g.result.paymentIntentId??_.id,paymentMethodId:g.result.paymentMethodId??w}:Jr(g,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:u,returnUrl:c,telemetry:R})}throw Sn(new Xe.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let m=(n??t)?.getRawProvider();if(!m)throw Sn(new Xe.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:w}=await m.handleNextAction({clientSecret:e.threeDSecureToken});if(w)throw Sn(new Xe.FloPayError(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await m.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??ko(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(_)throw Sn(new Xe.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Xe.FloPayError("Unsupported payment redirect state.","api_error")}function Hn(e){if(e instanceof Xe.FloPayError){let l=Fn(e.message);return l&&l!==e.message?Object.assign(new Xe.FloPayError(l,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Fn(t)??t;return new Xe.FloPayError(n,"api_error")}function Xr(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Xe.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function Zr({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:l,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let s=!!t&&t!==e,[u,c]=await Promise.all([(0,tr.loadFloPay)(e,{billingApiUrl:n,locale:l,telemetry:o}),s?(0,tr.loadFloPay)(t,{billingApiUrl:n,locale:l,telemetry:o}).catch(R=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",R),null)):Promise.resolve(null)]);return{flopay:u,paypalFlopay:t?s?c:u:null}}var S=require("react/jsx-runtime"),rr=44,To="flopay_checkout_saved_payment_resume",Ro=new Map;function Sr(e){return new Promise(t=>setTimeout(t,e))}function Qr(e,t,n){let l=Dr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Le.SDK_VERSION,enabled:t!==!1});return l.beginCheckout(n),l}function eo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Io(e,t,n,l,o){let s=Qr(e,t,n);s.error({errorCode:l,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),eo(s)}function Zi(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function xo(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function Eo(e){return!e||e.data.stripe?.publishableKey?!1:!!xo(e)?.clientId}function or(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Qi(){if(!or())return null;try{let e=window.sessionStorage.getItem(To);return e?JSON.parse(e):null}catch{return null}}function za(e){if(or())try{window.sessionStorage.setItem(To,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function _o(){if(or())try{window.sessionStorage.removeItem(To)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function es(e){if(!or())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function ts(e,t,n){if(or())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(l){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",l)}}function Ua(e){if(or())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function ns(){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 $a(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 rs(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function to({sessionId:e,nonce:t,createSession:n,billingApiUrl:l,telemetry:o,appearance:s,locale:u,loading:c,error:R,onComplete:N,onError:m,onDecline:_,onCountryChange:w,onZipChange:M,showPayPal:d=!0,showStripe:g=!0,showApplePay:I=!0,showGooglePay:F=!0,debug:P=!1,layout:K,theme:Q,buttonsTheme:pe,buttonsStyles:se,cardButtonContent:U,cardBackButtonContent:te,cardTitleContent:W,showSecurityFooter:me,onButtonClick:Y,onBeforeButtonClick:G,enableAVS:le,cardFieldOrder:Fe,cardPreFormSlot:be,avsLayout:he,className:ne,initialErrorMessage:ye=null,children:ve,checkoutMode:ce,confirmLabel:Ne,renderConfirmButton:Re,onSessionCompleted:Se}){let E=(0,Le.resolveBillingApiUrl)(l),oe=(0,L.useMemo)(()=>(0,Le.resolveTheme)(Q),[Q]),de=s??oe?.appearance,ze=n?"embedded_checkout":"standard_checkout",Oe=ve?"custom_layout":K==="buttons"?"buttons_layout":"default_layout",[ee,A]=(0,L.useState)(null),[J,ue]=(0,L.useState)(null),Ie=(0,L.useRef)(null),[ft,Qe]=(0,L.useState)(null),Ze=(0,L.useRef)(null),[y,qe]=(0,L.useState)(null),[Ue,Ve]=(0,L.useState)(e??""),He=e??Ue,Ht=n?"":He,[Pt,wt]=(0,L.useState)(!0),[h,we]=(0,L.useState)(null),[je,lt]=(0,L.useState)("full"),[nt,rt]=(0,L.useState)(!1),[Ye,Ce]=(0,L.useState)(ye),[bt,Ke]=(0,L.useState)(null),[At,kt]=(0,L.useState)(null),[pn,wn]=(0,L.useState)(void 0),[kn,Nn]=(0,L.useState)(""),[gt,Ft]=(0,L.useState)(!1),[Dt,Kt]=(0,L.useState)("loading"),[Qt,mn]=(0,L.useState)(0),X=(0,L.useRef)(!1),Mn=(0,L.useRef)(!1),yn=(0,L.useRef)(!1),Lt=(0,L.useRef)(null),ot=(0,L.useMemo)(()=>({checkoutMode:ce??je,layout:ve?"unknown":K==="buttons"?"buttons":"embedded"}),[ce,ve,je,K]),f=(0,L.useRef)(N);f.current=N;let xe=(0,L.useRef)(m);xe.current=m;let ct=(0,L.useRef)(_);ct.current=_,(0,L.useEffect)(()=>{Tt(J)?.setCheckoutContext(ot),ft&&ft!==J&&Tt(ft)?.setCheckoutContext(ot)},[J,ft,ot]);let Rn=(0,L.useRef)(Se);Rn.current=Se;let Te=(0,L.useCallback)(B=>{Kt(B),!(B!=="exhausted"||yn.current)&&(yn.current=!0,xe.current?.(new Le.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),An=(0,L.useCallback)(()=>{Kt("retrying"),mn(B=>B+1)},[]);(0,L.useEffect)(()=>{Kt("loading"),mn(0),yn.current=!1},[He]),(0,L.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Le.SDK_VERSION,checkout_type:ze,checkout_layout:Oe,billing_api_url:E})},[Oe,ze,E]);let fn=(0,L.useMemo)(()=>n?en(n):"",[n]),On=(0,L.useMemo)(()=>kn===fn?pn:void 0,[pn,kn,fn]),gn=(0,L.useMemo)(()=>n?ho(n,On):void 0,[n,On]),Nt=ce??gn?.checkoutMode??"full",xt=(0,L.useMemo)(()=>gn?{...gn,checkoutMode:Nt}:void 0,[gn,Nt]);(0,L.useEffect)(()=>{wn(void 0),Nn(fn)},[fn]),(0,L.useEffect)(()=>{Ce(ye)},[ye]);let ke=(0,L.useCallback)((B,$,j)=>{yt(()=>{ct.current?.(_t(B,$,j))})},[yt]),ut=(0,L.useCallback)(async(B,$)=>{Ce(null),kt(null),Ke("processing");let j=$?.sessionId??B.id,D=Ie.current??Ze.current,p=Tt(D),H=D?null:Qr(E,o,ot),v={log:z=>{p?p.log(z):H?.log(z)},error:z=>{p?p.error(z):H?.error(z)},terminal:z=>{p?p.terminal(z):H?.terminal(z)},performance:z=>{p?p.performance(z):H?.performance(z)},now:()=>p?.now()??H?.now()??0,elapsed:z=>p?.elapsed(z)??Math.max(0,(H?.now()??z)-z)},Be=v.now(),Z=!!($?.initialAutoProcessingError||$?.initialAutoProcessingPending),Ge=!1,ae,Ut=()=>{Ge||(Ge=!0,Z=!0,ae=v.now(),v.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),v.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},it=!1,O=()=>{it||(it=!0,v.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),v.performance({stage:"processing",durationMs:v.elapsed(Be),durationMode:"machine",paymentMethodCategory:"saved"}),ae!==void 0&&v.performance({stage:"recovery",durationMs:v.elapsed(ae),durationMode:"machine",paymentMethodCategory:"saved"}))};v.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),v.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),Z&&Ut();let b;try{let z=La($?.initialAutoProcessingError),Pe;if(z)Ut(),z.type==="paypal_redirect_required"&&Lt.current?.publishableKey&&za({sessionId:j,publishableKey:Lt.current.publishableKey,paypalPublishableKey:Lt.current.paypalPublishableKey}),Pe=await Jr(z,{flopay:Ie.current,paypalFlopay:Ze.current,attempt3DS:$?.attempt3DS,billingApiUrl:E,sessionId:j,session:B,telemetry:!1}),z.type==="paypal_redirect_required"&&_o();else if($?.initialAutoProcessingPending){let $e=await new wr.PaymentAPI(E,{telemetry:!1}).waitForCheckoutSessionCompletion($.initialAutoProcessingPending.sessionId,{initialDelayMs:$.initialAutoProcessingPending.retryAfterMs});if($e.data.session?.status!=="complete")throw new Le.FloPayError("Automatic payment failed. Please try again.","api_error",{code:$e.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});Pe={status:"succeeded"}}else{if($?.initialAutoProcessingError)throw Ln($.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:$.initialAutoProcessingError.checkoutMethod});if($?.fromCreateSession)return $?.fallbackToFull&&(lt("full"),$a("full")),!1;{let Me=await nr({billingApiUrl:E,sessionId:j,session:B,telemetry:!1});Me.type==="success"?Pe=Me.result:(Ut(),Me.type==="paypal_redirect_required"&&Lt.current?.publishableKey&&za({sessionId:j,publishableKey:Lt.current.publishableKey,paypalPublishableKey:Lt.current.paypalPublishableKey}),Pe=await Jr(Me,{flopay:Ie.current,paypalFlopay:Ze.current,attempt3DS:$?.attempt3DS,billingApiUrl:E,sessionId:j,session:B,telemetry:!1}),Me.type==="paypal_redirect_required"&&_o())}}j&&Qn(j),O(),Z&&(v.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),v.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),v.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Ke("success"),await Sr(xn),b=()=>f.current?.(Pe)}catch(z){let Pe=Hn(z),Me=Pe.checkoutMethod??Cr;return Ce(Pe.message),kt(Pe.message),$?.fallbackToFull&&(v.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),lt("full"),$a("full")),O(),!!(Pe.declineCode||Pe.code?.toLowerCase().includes("declin"))?v.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):v.error({errorCode:Z?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:Z?"recovery":"processing",paymentMethodCategory:"saved"}),yt(()=>xe.current?.(Pe)),ke(Me,Pe,{code:Pe.code,declineCode:Pe.declineCode}),Ke("error"),await Promise.allSettled([Sr(bn),$?.ensureProvidersReady?$.ensureProvidersReady():Promise.resolve()]),Z&&(v.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),v.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{O(),H&&eo(H),Ke(null),kt(null)}return yt(b),!0},[ke,yt,Hn,E,o,ot]);(0,L.useEffect)(()=>{if(typeof window>"u"||Mn.current)return;let B=new URLSearchParams(window.location.search),$=B.get("payment_intent_client_secret");if(!$)return;let j=Qi();j&&(Mn.current=!0,(async()=>{let D,p=0;Ce(null),kt(null),Ke("processing"),rt(!0);try{if(B.get("redirect_status")==="failed")throw Object.assign(new Le.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:H,paypalFlopay:v}=await Zr({publishableKey:j.publishableKey,paypalPublishableKey:j.paypalPublishableKey,billingApiUrl:E,locale:u,telemetry:o});D=Tt(v??H),p=D?.now()??0,D?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),D?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Be=(v??H)?.getRawProvider();if(!Be)throw Object.assign(new Le.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:Z,error:Ge}=await Be.retrievePaymentIntent($);if(Ge)throw Object.assign(new Le.FloPayError(Ge.message??"Failed to retrieve PayPal payment status.","api_error",{code:Ge.code}),{checkoutMethod:"paypal"});let ae=ya(Z?.status);if(!Z||ae==="failed")throw Object.assign(new Le.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Ut=typeof Z.payment_method=="string"?Z.payment_method:Z.payment_method?.id,it=ae;if(j.sessionId){let z=(await new wr.PaymentAPI(E,{telemetry:!1}).getUnifiedCheckoutSession(j.sessionId)).data.session;if(z&&z.status!=="complete"){let Pe=await nr({billingApiUrl:E,sessionId:j.sessionId,session:z,telemetry:!1,tokenizedData:{id:Ut??Z.id,type:"card",threeDSecureActionResultTokenId:Z.id,isPaypal:!0}});if(Pe.type!=="success")throw Object.assign(new Le.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});it=Pe.result.status}}j.sessionId&&Qn(j.sessionId),D?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),D?.performance({stage:"redirect_resume",durationMs:D.elapsed(p),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),D?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ke("success"),await Sr(xn),yt(()=>f.current?.({status:it,paymentIntentId:Z.id,paymentMethodId:Ut,checkoutMethod:"paypal"}))}catch(H){let v=Hn(H),Be=v.checkoutMethod??"paypal",Z=!!(v.declineCode||v.code?.toLowerCase().includes("declin"));if(D)D.performance({stage:"redirect_resume",durationMs:D.elapsed(p),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Z?D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):D.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(Z){let Ge=Qr(E,o,ot);Ge.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),eo(Ge)}else Io(E,o,ot,"REDIRECT_RESUME_FAILED","redirect_resume");Ce(v.message),kt(v.message),yt(()=>xe.current?.(v)),ke(Be,v,{code:v.code,declineCode:v.declineCode}),Ke("error"),await Sr(bn)}finally{_o(),ns(),Ke(null),kt(null),rt(!1)}})())},[ke,yt,u,Hn,E,o]);let at=(0,L.useRef)(null);function en(B){let $=JSON.stringify({c:B?.clientId,cur:B?.currency??"",a:{e:B?.account?.email?.trim().toLowerCase()??"",country:B?.account?.country??""},successUrl:B?.successUrl,cancelUrl:B?.cancelUrl,p:B?.products?.map(D=>`${D.type??""}:${D.code??D.providerItemId??D.providerPlanId??""}:${D.totalAmount??""}:${D.overrideAmount??""}:${D.quantity??1}`).sort(),i:B?.items?.map(D=>`${D.code??D.providerItemId??""}:${D.totalAmount??""}:${D.overrideAmount??""}:${D.quantity??1}`).sort(),s:B?.subscriptions?.map(D=>`${D.code??D.providerPlanId??""}:${D.totalAmount??""}:${D.overrideAmount??""}:${D.quantity??1}`).sort(),couponCodes:B?.couponCodes,tagsData:B?.tagsData,utmMetadata:B?.utmMetadata,tokenizedData:B?.tokenizedData,m:B?.checkoutMode??"full"}),j=0;for(let D=0;D<$.length;D++)j=(j<<5)-j+$.charCodeAt(D)|0;return`flopay_session_${Math.abs(j).toString(36)}`}let Wt=(0,L.useMemo)(()=>xt?en(xt):"",[xt]),ht=(0,L.useRef)(xt);ht.current=xt,(0,L.useEffect)(()=>{Ve(e??"")},[e]),(0,L.useEffect)(()=>{X.current=!1,Ce(ye),kt(null),Ke(null)},[Wt,ye,e]);async function qt(B,$){let j=Qr(E,o,ot),D=new wr.PaymentAPI(E,{telemetry:!1});try{let p=es($);j.log({name:p?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let H=p?.sid??null,v=null;if(H)try{if(v=await D.getUnifiedCheckoutSession(H,p?.nonce),v.data.session?.status==="complete"){if(ga(H))return{sid:H,result:v};Ua($),H=null,v=null}}catch{j.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ua($),H=null}if(!H){let Be=j.now();j.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Z={...B,avsCheck:!!le,avsConfig:typeof le=="object"?le:void 0,checkoutType:"embedded_checkout",checkoutLayout:ve?"custom_layout":K==="buttons"?"buttons_layout":"default_layout"};try{v=await D.createAndFetchSession(Z),j.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),j.performance({stage:"session_create",durationMs:j.now()-Be,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"})}catch(Ge){throw j.performance({stage:"session_create",durationMs:j.now()-Be,durationMode:"machine",requestCategory:"session_create",statusClass:"network_error"}),Ge instanceof Le.FloPayError&&Ge.type==="validation_error"?j.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):j.error({errorCode:"CHECKOUT_SESSION_CREATE_FAILED",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Ge}H=v.data.session?.id??"",H&&ts($,H,v.data.session?.clientSecret)}return{sid:H??"",result:v}}finally{eo(j)}}let vt=(0,L.useCallback)(async B=>{let $=ht.current;if(!$)throw new Le.FloPayError("createSession is required to bootstrap checkout.","validation_error");let j=ho($,B),D=en(j),p=Ro.get(D);p||(p=qt(j,D),Ro.set(D,p));let H;try{H=await p}finally{Ro.delete(D)}at.current=D;try{B&&(Nn(fn),wn(it=>pa(it,B)));let{sid:v,result:Be}=H;A(Be),Be.data.session&&qe(Be.data.session),v&&Ve(v);let{publishableKey:Z,paypalPublishableKey:Ge}=Xr(Be),{flopay:ae,paypalFlopay:Ut}=await Zr({publishableKey:Z,paypalPublishableKey:Ge,billingApiUrl:E,locale:u,telemetry:o});Ie.current=ae,ue(ae),Ze.current=Ut,Qe(Ut),wt(!1)}catch(v){throw at.current===D&&(at.current=null),v}return H},[u,E,o,ot]),tn=(0,L.useCallback)(async B=>{if(!rs(B)||gt)return{sessionId:Ue,session:y};Ft(!0);try{let $=await vt(B);return{sessionId:$.sid,session:$.result.data.session??null}}finally{Ft(!1)}},[vt,gt,Ue,y]);(0,L.useEffect)(()=>{let B=!1;if(we(null),Wt){let D=ht.current;return lt(Nt),wt(!1),at.current===Wt?()=>{B=!0}:(qe(ma(D,ce)),(async()=>{let p=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),H=Nt==="auto"&&!X.current&&!p;H&&(Ce(null),kt(null),Ke("processing"));try{let v=await vt(),Be=v.result.data.session??null;Lt.current=Xr(v.result);let Z=Eo(v.result);if(!B&&H&&Be&&!Z){X.current=!0,await ut(Be,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:v.result.autoProcessingError,initialAutoProcessingPending:v.result.autoProcessingPending,autoProcessingAttempted:v.result.autoProcessingAttempted,sessionId:v.sid||Be.id});return}!B&&H&&(Z&&(X.current=!0),Ke(null),kt(null))}catch(v){if(B)return;let Be=v instanceof Le.FloPayError||typeof v=="object"&&v!==null&&"code"in v?v.code:void 0;if(H&&Be==="session_auto_completed"){X.current=!0,Ke("success"),await Sr(xn),B||(yt(()=>{f.current?.({status:"succeeded"})}),Ke(null),kt(null));return}H&&(Ke(null),kt(null));let Z=v instanceof Le.FloPayError?v:new Le.FloPayError(v instanceof Error?v.message:"Failed to create session","api_error");we(Z)}})(),()=>{B=!0})}wt(!0);async function $(){let D=!1;try{let H=await new wr.PaymentAPI(E,{telemetry:!1}).getUnifiedCheckoutSession(He,t);if(B)return;A(H);let v=H.data.session??null;if(qe(v),!v)throw new Le.FloPayError("No session data returned","api_error");if(v.status==="complete"){wt(!1),yt(()=>{Rn.current?.(v.successUrl??"")});return}if(v.status==="expired")throw new Le.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});D=!0;let Be=ce??v.checkoutMode??"full";lt(Be);let Z=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ge=Eo(H);if(Be==="auto"&&!X.current&&!Z&&!Ge){X.current=!0;let ae=j(H);try{if(await ut(v,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ae,sessionId:He||v.id}),B)return;await ae,B||wt(!1);return}catch{if(B)return;await ae,B||wt(!1);return}}await j(H),B||wt(!1)}catch(p){if(B)return;p instanceof Le.FloPayError?!D&&!Zi(p)&&Io(E,o,ot,"NETWORK_REQUEST_FAILED","session_read"):Io(E,o,ot,"INTERNAL_SDK_ERROR","checkout_mount");let H=p instanceof Le.FloPayError?p:new Le.FloPayError(p instanceof Error?p.message:"Failed to initialize checkout","api_error");we(H),wt(!1)}}async function j(D){let{publishableKey:p,paypalPublishableKey:H}=Xr(D);Lt.current={publishableKey:p,paypalPublishableKey:H};let{flopay:v,paypalFlopay:Be}=await Zr({publishableKey:p,paypalPublishableKey:H,billingApiUrl:E,locale:u,telemetry:o});Ie.current=v,ue(v),Ze.current=Be,Qe(Be)}return $(),()=>{B=!0}},[vt,ce,Wt,Nt,Ht,yt,t,ut]);let hn=(0,L.useCallback)(async()=>{if(!(nt||!y)){rt(!0),Ce(null);try{await ut(y,{fallbackToFull:!0,sessionId:He||y.id})}finally{rt(!1)}}},[He,nt,ut,y]),In=xo(ee),Pn=Eo(ee),jt=(0,L.useMemo)(()=>{if(!ee||!y||!ee.data.stripe?.publishableKey)return;let B={appearance:de,paymentMethodCreation:"manual",billingApiUrl:E};if(ee.data.stripe?.clientSecret)B.clientSecret=ee.data.stripe.clientSecret;else{let $=(0,Le.buildCheckoutDisplayData)(y).total;B.amount=Math.round($*100)||y.amount,B.currency=y.currency?.toLowerCase()}return B},[ee,y,de,E]),We=!!(n&&!ve&&K==="buttons"&&G&&Nt==="full"),Vt=(0,L.useMemo)(()=>({session:y,loading:Pt,error:h,checkoutMode:je,inlineSessionDraft:xt,applyInlineSessionPatch:We?tn:void 0,inlineSessionPatchProcessing:gt}),[y,Pt,h,je,xt,We,tn,gt]),Ot=!!n&&K==="buttons"&&!Pn&&(!J||!jt),zt=bt?(0,S.jsx)(vn,{status:bt,errorMessage:At}):null;if(Pt){if(c)return(0,S.jsxs)(S.Fragment,{children:[c,zt]});if(K==="buttons"){let B=oe?.buttonsLayout?.cardButton?.borderRadius??oe?.appearance.variables?.borderRadius??8,$=j=>(0,S.jsx)("div",{style:{height:j,borderRadius:B,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[d&&$(rr),g&&(I||F)&&$(rr),g&&$(rr),(0,S.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),zt]})}return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,S.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,S.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),zt]})}return h?R?(0,S.jsx)(on.Provider,{value:Vt,children:R(h)}):(0,S.jsx)(on.Provider,{value:Vt,children:(0,S.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:h.message})}):Ot?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(on.Provider,{value:Vt,children:(0,S.jsx)(as,{onButtonClick:Y,showPayPal:d,showStripe:g,showApplePay:I,showGooglePay:F,theme:Q,buttonsTheme:pe,buttonsStyles:se,cardButtonContent:U,cardBackButtonContent:te,cardTitleContent:W})}),zt]}):Pn&&y&&In?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(on.Provider,{value:Vt,children:(0,S.jsxs)("div",{className:ne,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ye&&(0,S.jsx)(Xn,{icon:!1,children:Ye}),Dt==="retrying"&&(0,S.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Dt==="exhausted"&&(0,S.jsxs)("div",{role:"alert",children:[(0,S.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,S.jsx)("button",{type:"button",onClick:An,children:"Retry PayPal"})]}),Dt!=="exhausted"&&(0,S.jsx)("div",{"aria-hidden":Dt==="retrying"?!0:void 0,style:Dt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,S.jsx)(Sa,{sessionId:He,nonce:y.clientSecret||void 0,billingApiUrl:E,email:y.customer?.email,clientId:In.clientId,environment:In.environment,currency:(y.currency??"usd").toUpperCase(),isSubscription:y.mode==="subscription",onComplete:N,onErrorChange:Ce,onDecline:_,onButtonClick:Y,onInitializationStateChange:Te,allowAutomaticRetry:Qt===0,session:y,telemetry:o,telemetryContext:ot,debug:P},`paypal-init-${Qt}`)})]})}),zt]}):!J||!jt?(0,S.jsx)(S.Fragment,{children:zt}):je==="confirm"?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(on.Provider,{value:Vt,children:(0,S.jsx)(fr,{flopay:J,paypalFlopay:ft,options:jt,children:(0,S.jsxs)("div",{className:ne,children:[Ye&&(0,S.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ye}),Re?Re({onConfirm:hn,isProcessing:nt}):(0,S.jsx)("button",{type:"button",onClick:hn,disabled:nt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:nt?"not-allowed":"pointer",opacity:nt?.6:1},children:nt?"Processing...":Ne??"Confirm Purchase"})]})})}),zt]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(on.Provider,{value:Vt,children:(0,S.jsx)(fr,{flopay:J,paypalFlopay:ft,options:jt,children:ve?(0,S.jsxs)(S.Fragment,{children:[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)(os,{sessionId:He,nonce:y?.clientSecret||void 0,billingApiUrl:E,session:y,children:ve})]}):(0,S.jsx)(Yr,{sessionId:He,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,Le.buildCheckoutDisplayData)(y).total*100):0,currency:y?.currency?.toLowerCase()??"usd",onComplete:N,onError:m,onDecline:_,error:Ye,onErrorChange:Ce,showPayPal:d,showStripe:g,enabledPaymentMethods:ee?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ee?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:F,layout:K,theme:Q,buttonsTheme:pe,buttonsStyles:se,appearance:de,cardButtonContent:U,cardBackButtonContent:te,cardTitleContent:W,onButtonClick:Y,onBeforeButtonClick:G,enableAVS:le,...Fe?{cardFieldOrder:Fe}:{},...be?{cardPreFormSlot:be}:{},avsLayout:he,country:y?.customer?.country,city:y?.customer?.city,state:y?.customer?.state,onCountryChange:w,onZipChange:M,avsCheck:!!le,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ve?"custom_layout":K==="buttons"?"buttons_layout":"default_layout",className:ne,directPaypal:xo(ee),isSubscription:y?.mode==="subscription",session:y,debug:P})})}),zt]})}function os({sessionId:e,nonce:t,billingApiUrl:n,session:l,children:o}){return(0,S.jsx)(S.Fragment,{children:L.default.Children.map(o,s=>{if(!L.default.isValidElement(s))return s;let u=s.props,c={};return u.sessionId||(c.sessionId=e),!u.nonce&&t&&(c.nonce=t),u.billingApiUrl||(c.billingApiUrl=n),l?.customer&&(u.email||(c.email=l.customer.email),u.userId||(c.userId=l.customer.id),u.firstName||(c.firstName=l.customer.firstName),u.lastName||(c.lastName=l.customer.lastName)),Object.keys(c).length===0?s:L.default.cloneElement(s,c)})})}function as({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:l,showGooglePay:o,theme:s,buttonsTheme:u,buttonsStyles:c,cardButtonContent:R,cardBackButtonContent:N,cardTitleContent:m}){let[_,w]=(0,L.useState)(!1),M=(0,L.useMemo)(()=>(0,Le.resolveTheme)(s),[s]),d=(0,L.useMemo)(()=>{let P=M?.buttonsLayout??(0,Le.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},[M,u,c]),g=M?.buttonsLayout?.cardButton?.borderRadius??M?.appearance.variables?.borderRadius??8,I=P=>(0,S.jsx)("div",{style:{height:P,borderRadius:g,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),F=R===void 0?{boxSizing:"border-box",height:rr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let P=d.cardInputBorder??"#e5e7eb",K=d.cardInputBackground??"white",Q=Yn(N),pe=Yn(m);return(0,S.jsxs)("div",{style:{backgroundColor:d.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...d.cardFormContainer},children:[(0,S.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,S.jsxs)("button",{type:"button",onClick:()=>w(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...d.backButton},children:[(0,S.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...d.backButtonIcon},children:(0,S.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,S.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,S.jsx)(Jn,{content:N})]}),pe?(0,S.jsx)("div",{style:{flex:1}}):(0,S.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...d.title},children:(0,S.jsx)(gr,{content:m})})]}),(0,S.jsx)("div",{style:{backgroundColor:K,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:K,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:K,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:K,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:`
|
|
41
41
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
42
42
|
@keyframes flopay-interim-expand {
|
|
43
43
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
44
44
|
40% { opacity: 1; }
|
|
45
45
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
46
46
|
}
|
|
47
|
-
`})]})}return(0,S.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&I(rr),n&&(l||o)&&I(rr),n&&(0,S.jsx)("button",{type:"button",onClick:()=>{e?.("card"),w(!0)},style:{width:"100%",...A,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:d.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...d.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:(0,S.jsx)(Gn,{content:R})}),(0,S.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Kn=require("react");var Va=require("react/jsx-runtime");function $a(e,t){function n({className:l,id:o,style:s,options:u,onChange:c,onReady:R,onFocus:L,onBlur:m,onEscape:_}){let w=(0,Kn.useRef)(null),B=(0,Kn.useRef)(null),{elements:d,reportInteractive:g}=(0,Kn.useContext)(In);return(0,Kn.useEffect)(()=>{if(!d||!w.current)return;let I=!0;return(async()=>{let A=d.getElement(e);A||(A=await d.create(e,u)),!(!I||!w.current)&&(A.mount(w.current),B.current=A,c&&A.on("change",c),A.on("ready",()=>{g?.(),R?.()}),L&&A.on("focus",L),m&&A.on("blur",m),_&&A.on("escape",_))})(),()=>{if(I=!1,B.current){try{B.current.unmount()}catch{}B.current=null}}},[d,g]),(0,Va.jsx)("div",{ref:w,className:l,id:o,style:s})}return n.displayName=t,n}var qa=$a("payment","PaymentElement"),ja=$a("address","AddressElement");var Ha=require("@flopay/js"),Ka=require("@flopay/shared"),ln=require("react");var sn=require("react/jsx-runtime");function Wa({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,firstName:s,lastName:u,chv:c,onTokenizedBody:R,onComplete:L,onErrorChange:m,isProcessing:_=!1}){let w=on(),B=Nr(),d=Or(),[g,I]=(0,ln.useState)(!1),[A,P]=(0,ln.useState)(!1),H=(0,ln.useRef)(!1),Q=(n||d).replace(/\/+$/,""),me=(0,ln.useCallback)(async te=>{try{let ye=await new Ha.PaymentAPI(Q).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:te,accountData:{userId:o??"",email:l??"",firstName:s??"",lastName:u??""},chv:c});if(ye.ok){L?.();return}let W=await ye.json().catch(()=>null);m?.(W?.message??"Payment failed. Please try again.")}catch(K){m?.(K instanceof Error?K.message:"An unexpected error occurred")}},[Q,e,t,o,l,s,u,c,L,m]),se=(0,ln.useCallback)(te=>{R?R(te):me(te)},[R,me]);(0,ln.useEffect)(()=>{if(!w||H.current)return;let te=new URLSearchParams(window.location.search),K=te.get("payment_intent"),ye=te.get("payment_intent_client_secret"),W=te.get("redirect_status");!K||!ye||(H.current=!0,(async()=>{try{if(P(!0),W==="failed"){m?.("PayPal payment was declined. Please try again.");return}let Y=w.getRawProvider();if(!Y?.retrievePaymentIntent){m?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:le,error:Fe}=await Y.retrievePaymentIntent(ye);if(Fe){m?.(Fe.message??"Failed to retrieve PayPal payment status.");return}if(le&&(le.status==="requires_capture"||le.status==="succeeded")){let he=typeof le.payment_method=="string"?le.payment_method:le.payment_method?.id;se({id:he??le.id,type:"card",threeDSecureActionResultTokenId:le.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(Y){m?.(Y instanceof Error?Y.message:"Failed to complete PayPal payment.")}finally{P(!1)}})())},[w,se,m]);let z=(0,ln.useCallback)(async()=>{if(!(!w||!B))try{if(P(!0),m?.(null),!e||!l)throw new Ka.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let te=await w.confirmPayPalPayment({billingApiUrl:Q,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")&&se({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,B,e,t,l,Q,se,m]);return!w||!B?(0,sn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,sn.jsxs)(sn.Fragment,{children:[!g&&(0,sn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,sn.jsx)("div",{style:g?{}:{display:"none"},children:(0,sn.jsx)("button",{type:"button",onClick:z,disabled:A||_,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:A||_?"not-allowed":"pointer",opacity:A||_?.6:1},ref:()=>I(!0),children:A?"Processing...":"PayPal"})}),(A||_)&&(0,sn.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,sn.jsx)("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}var _e=require("react"),to=require("@flopay/js"),Ft=require("@flopay/shared");var cn=require("react/jsx-runtime"),as=44;function Ya(e){return new Promise(t=>setTimeout(t,e))}function is(e,t){return e instanceof Ft.FloPayError?e:new Ft.FloPayError(e instanceof Error?e.message:t,"api_error")}function ss(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function ls(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function Ga({sessionId:e,nonce:t,createSession:n,paymentMethodId:l,checkoutMethod:o,clientId:s,products:u,items:c,subscriptions:R,account:L,successUrl:m,cancelUrl:_,couponCodes:w,tagsData:B,utmMetadata:d,billingApiUrl:g,locale:I,theme:A,appearance:P,buttonsTheme:H,buttonsStyles:Q,onSuccess:me,onError:se,onDecline:z,children:te,disabled:K=!1,type:ye="button",style:W,...Y}){let le=(0,_e.useMemo)(()=>(0,Ft.resolveBillingApiUrl)(g),[g]),Fe=(0,_e.useMemo)(()=>ls({createSession:n,clientId:s,products:u,items:c,subscriptions:R,account:L,successUrl:m,cancelUrl:_,couponCodes:w,tagsData:B,utmMetadata:d}),[L,_,s,w,n,u,c,R,m,B,d]),[he,ge]=(0,_e.useState)(!1),[ne,fe]=(0,_e.useState)(null),[ve,ce]=(0,_e.useState)(null),[Ne,Ie]=(0,_e.useState)(null),we=(0,_e.useRef)(!0),E=(0,_e.useRef)(null),oe=(0,_e.useRef)(Ne),de=(0,_e.useRef)(me),Ue=(0,_e.useRef)(se),Oe=(0,_e.useRef)(z);(0,_e.useEffect)(()=>{oe.current=Ne},[Ne]),(0,_e.useEffect)(()=>{de.current=me},[me]),(0,_e.useEffect)(()=>{Ue.current=se},[se]),(0,_e.useEffect)(()=>{Oe.current=z},[z]),(0,_e.useEffect)(()=>(we.current=!0,()=>{we.current=!1,E.current?.abort()}),[]),(0,_e.useEffect)(()=>{if(typeof window>"u")return;let h=ke=>{ke.key==="Escape"&&Ie(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let ee=(0,_e.useCallback)((h,ke=vr)=>{Oe.current?.(Tt(ke,h,{code:h.code,declineCode:h.declineCode}))},[]),M=(0,_e.useCallback)(async h=>{we.current&&(ce(null),fe("success"),await Ya(_n),we.current&&de.current?.(h))},[]),G=(0,_e.useCallback)(async(h,ke)=>{we.current&&(Ue.current?.(h),ke?.emitDecline&&ee(h,ke.method),ce(h.message),fe("error"),await Ya(Pn))},[ee]),ue=(0,_e.useCallback)(async(h,ke,Ve)=>{let lt=h.data.session??null;if(!lt)throw new Ft.FloPayError("No session data returned","api_error");let rt=lt.clientSecret||t;if(lt.status==="complete"){await M({result:{status:"succeeded"},session:lt,sessionId:lt.id||ke,autoCompleted:!1});return}if(lt.status==="expired")throw new Ft.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(h.autoProcessingPending){let vt=(await new to.PaymentAPI(le).waitForCheckoutSessionCompletion(h.autoProcessingPending.sessionId,{initialDelayMs:h.autoProcessingPending.retryAfterMs})).data.session;if(!vt||vt.status!=="complete")throw new Ft.FloPayError("Automatic payment failed. Please try again.","api_error",{code:vt?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await M({result:{status:"succeeded"},session:vt,sessionId:vt.id||ke,autoCompleted:!1});return}if(h.autoProcessingError){if(h.autoProcessingError.type==="3ds_required"&&h.autoProcessingError.nextActionRedirectUrl&&ke&&rt){let Ge=new AbortController;E.current=Ge;let Ce;try{Ce=await La({billingApiUrl:le,sessionId:ke,nonce:rt,nextActionRedirectUrl:h.autoProcessingError.nextActionRedirectUrl,signal:Ge.signal})}finally{E.current===Ge&&(E.current=null)}if(Ce.status==="declined")throw Ln({type:Ce.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ce.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let Dt=(await new to.PaymentAPI(le).waitForCheckoutSessionCompletion(ke,{initialDelayMs:0,nonce:rt})).data.session;if(!Dt||Dt.status!=="complete")throw Ln({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await M({result:{status:"succeeded"},session:Dt,sessionId:Dt.id||ke,autoCompleted:!1});return}throw Ln(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(Ve?.fromCreateSession&&h.autoProcessingAttempted===!0)throw Ln({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ot=await nr({billingApiUrl:le,sessionId:ke??lt.id,session:lt,nonce:rt});if(ot.type!=="success")throw Ln({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await M({result:ot.result,session:lt,sessionId:lt.id||ke,autoCompleted:!1})}catch(ot){let Ge=Hn(ot),Ce=lt.id||ke;await G(Ge,{emitDecline:!0,method:Ge.checkoutMethod??vr}),ss(Ge,Ce)&&Ce&&we.current&&Ie({sessionId:Ce,errorMessage:Ge.message,nonce:rt||void 0})}},[t,le,G,M]),Ee=(0,_e.useCallback)(async h=>{if(Y.onClick?.(h),!(h.defaultPrevented||K||he)){if(Ie(null),e&&Fe){let ke=new Ft.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await G(ke),we.current&&(fe(null),ce(null));return}if(!e&&!Fe){let ke=new Ft.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await G(ke),we.current&&(fe(null),ce(null));return}ge(!0),ce(null),fe("processing");try{let ke=new to.PaymentAPI(le);if(e){let Ve=await ke.getUnifiedCheckoutSession(e,t);await ue(Ve,e);return}try{let Ve=await ke.createAndFetchSession({...Fe});await ue(Ve,Ve.data.session?.id??null,{fromCreateSession:!0})}catch(Ve){if(Ve instanceof Ft.FloPayError&&Ve.code==="session_auto_completed"){await M({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Ve}}catch(ke){await G(is(ke,"Automatic payment failed. Please try again."))}finally{we.current&&(fe(null),ce(null),ge(!1))}}},[Y,Fe,K,he,t,ue,le,e,G,M]),gt=(0,_e.useCallback)(h=>{let ke=oe.current;Ie(null),de.current?.({result:h,session:null,sessionId:ke?.sessionId??null,autoCompleted:!1})},[]),et=(0,_e.useCallback)(h=>{Ue.current?.(h)},[]),Qe=(0,_e.useCallback)(h=>{Oe.current?.(h)},[]),y=(0,_e.useMemo)(()=>(0,Ft.resolveTheme)(A),[A]),je=(0,_e.useMemo)(()=>{let h=y?.buttonsLayout??(0,Ft.resolveButtonsLayoutTheme)(H);return Q?{...h,...Q,cardButton:{...h.cardButton,...Q.cardButton}}:h},[y,H,Q]),$e=(0,_e.useMemo)(()=>{let h=y?.appearance;return P?h?{...h,...P,variables:{...h.variables,...P.variables}}:P:h},[P,y]),He=$e?.variables,Ke=He?.colorPrimary??"#4A49FF",Wt=He?.colorPrimaryHover??Vr(Ke,.12),bt=He?.borderRadius??"8px";return(0,cn.jsxs)(cn.Fragment,{children:[(0,cn.jsx)("button",{...Y,type:ye,onClick:Ee,disabled:K||he,"aria-busy":he,style:{width:"100%",...te===void 0?{boxSizing:"border-box",height:as,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...je.cardButton,...So({themeBundle:y,resolvedPrimaryColor:Ke,resolvedBorderRadius:bt,submitButtonStyle:je.submitButton,explicitPrimaryColor:He?.colorPrimary}),fontSize:je.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:K||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:K||he?.6:1,...W},onMouseEnter:h=>{Y.onMouseEnter?.(h),!h.defaultPrevented&&!K&&!he&&(y||He?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Wt)},onMouseLeave:h=>{Y.onMouseLeave?.(h),!h.defaultPrevented&&(y||He?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Ke)},onMouseDown:h=>{Y.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{Y.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,cn.jsx)(Gn,{content:te})}),ne&&(0,cn.jsx)(bn,{status:ne,errorMessage:ve}),Ne&&(0,cn.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,cn.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,cn.jsx)(eo,{sessionId:Ne.sessionId,nonce:Ne.nonce,checkoutMode:"full",billingApiUrl:le,locale:I,theme:A,...$e?{appearance:$e}:{},buttonsTheme:H,buttonsStyles:Q,initialErrorMessage:Ne.errorMessage,cardTitleContent:null,onComplete:gt,onError:et,onDecline:Qe})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,useCheckout,useElements,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}return(0,S.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&I(rr),n&&(l||o)&&I(rr),n&&(0,S.jsx)("button",{type:"button",onClick:()=>{e?.("card"),w(!0)},style:{width:"100%",...F,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:d.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...d.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:(0,S.jsx)(Gn,{content:R})}),(0,S.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Kn=require("react");var Ha=require("react/jsx-runtime");function qa(e,t){function n({className:l,id:o,style:s,options:u,onChange:c,onReady:R,onFocus:N,onBlur:m,onEscape:_}){let w=(0,Kn.useRef)(null),M=(0,Kn.useRef)(null),{elements:d,reportInteractive:g}=(0,Kn.useContext)(En);return(0,Kn.useEffect)(()=>{if(!d||!w.current)return;let I=!0;return(async()=>{let F=d.getElement(e);F||(F=await d.create(e,u)),!(!I||!w.current)&&(F.mount(w.current),M.current=F,c&&F.on("change",c),F.on("ready",()=>{g?.(),R?.()}),N&&F.on("focus",N),m&&F.on("blur",m),_&&F.on("escape",_))})(),()=>{if(I=!1,M.current){try{M.current.unmount()}catch{}M.current=null}}},[d,g]),(0,Ha.jsx)("div",{ref:w,className:l,id:o,style:s})}return n.displayName=t,n}var ja=qa("payment","PaymentElement"),Va=qa("address","AddressElement");var Ka=require("@flopay/js"),Wa=require("@flopay/shared"),dn=require("react");var cn=require("react/jsx-runtime");function Ya({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,firstName:s,lastName:u,chv:c,onTokenizedBody:R,onComplete:N,onErrorChange:m,isProcessing:_=!1}){let w=an(),M=Or(),d=zr(),[g,I]=(0,dn.useState)(!1),[F,P]=(0,dn.useState)(!1),K=(0,dn.useRef)(!1),Q=(n||d).replace(/\/+$/,""),pe=(0,dn.useCallback)(async te=>{try{let me=await new Ka.PaymentAPI(Q).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:te,accountData:{userId:o??"",email:l??"",firstName:s??"",lastName:u??""},chv:c});if(me.ok){N?.();return}let Y=await me.json().catch(()=>null);m?.(Y?.message??"Payment failed. Please try again.")}catch(W){m?.(W instanceof Error?W.message:"An unexpected error occurred")}},[Q,e,t,o,l,s,u,c,N,m]),se=(0,dn.useCallback)(te=>{R?R(te):pe(te)},[R,pe]);(0,dn.useEffect)(()=>{if(!w||K.current)return;let te=new URLSearchParams(window.location.search),W=te.get("payment_intent"),me=te.get("payment_intent_client_secret"),Y=te.get("redirect_status");!W||!me||(K.current=!0,(async()=>{try{if(P(!0),Y==="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:le,error:Fe}=await G.retrievePaymentIntent(me);if(Fe){m?.(Fe.message??"Failed to retrieve PayPal payment status.");return}if(le&&(le.status==="requires_capture"||le.status==="succeeded")){let be=typeof le.payment_method=="string"?le.payment_method:le.payment_method?.id;se({id:be??le.id,type:"card",threeDSecureActionResultTokenId:le.id,isPaypal:!0});let he=new URL(window.location.href);he.searchParams.delete("payment_intent"),he.searchParams.delete("payment_intent_client_secret"),he.searchParams.delete("redirect_status"),window.history.replaceState({},"",he.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,se,m]);let U=(0,dn.useCallback)(async()=>{if(!(!w||!M))try{if(P(!0),m?.(null),!e||!l)throw new Wa.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let te=await w.confirmPayPalPayment({billingApiUrl:Q,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")&&se({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,M,e,t,l,Q,se,m]);return!w||!M?(0,cn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,cn.jsxs)(cn.Fragment,{children:[!g&&(0,cn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,cn.jsx)("div",{style:g?{}:{display:"none"},children:(0,cn.jsx)("button",{type:"button",onClick:U,disabled:F||_,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:F||_?"not-allowed":"pointer",opacity:F||_?.6:1},ref:()=>I(!0),children:F?"Processing...":"PayPal"})}),(F||_)&&(0,cn.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,cn.jsx)("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}var _e=require("react"),no=require("@flopay/js"),Mt=require("@flopay/shared");var un=require("react/jsx-runtime"),is=44;function Ga(e){return new Promise(t=>setTimeout(t,e))}function ss(e,t){return e instanceof Mt.FloPayError?e:new Mt.FloPayError(e instanceof Error?e.message:t,"api_error")}function ls(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function cs(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 Ja({sessionId:e,nonce:t,createSession:n,paymentMethodId:l,checkoutMethod:o,clientId:s,products:u,items:c,subscriptions:R,account:N,successUrl:m,cancelUrl:_,couponCodes:w,tagsData:M,utmMetadata:d,billingApiUrl:g,locale:I,theme:F,appearance:P,buttonsTheme:K,buttonsStyles:Q,onSuccess:pe,onError:se,onDecline:U,children:te,disabled:W=!1,type:me="button",style:Y,...G}){let le=(0,_e.useMemo)(()=>(0,Mt.resolveBillingApiUrl)(g),[g]),Fe=(0,_e.useMemo)(()=>cs({createSession:n,clientId:s,products:u,items:c,subscriptions:R,account:N,successUrl:m,cancelUrl:_,couponCodes:w,tagsData:M,utmMetadata:d}),[N,_,s,w,n,u,c,R,m,M,d]),[be,he]=(0,_e.useState)(!1),[ne,ye]=(0,_e.useState)(null),[ve,ce]=(0,_e.useState)(null),[Ne,Re]=(0,_e.useState)(null),Se=(0,_e.useRef)(!0),E=(0,_e.useRef)(null),oe=(0,_e.useRef)(Ne),de=(0,_e.useRef)(pe),ze=(0,_e.useRef)(se),Oe=(0,_e.useRef)(U);(0,_e.useEffect)(()=>{oe.current=Ne},[Ne]),(0,_e.useEffect)(()=>{de.current=pe},[pe]),(0,_e.useEffect)(()=>{ze.current=se},[se]),(0,_e.useEffect)(()=>{Oe.current=U},[U]),(0,_e.useEffect)(()=>(Se.current=!0,()=>{Se.current=!1,E.current?.abort()}),[]),(0,_e.useEffect)(()=>{if(typeof window>"u")return;let h=we=>{we.key==="Escape"&&Re(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let ee=(0,_e.useCallback)((h,we=Cr)=>{Oe.current?.(_t(we,h,{code:h.code,declineCode:h.declineCode}))},[]),A=(0,_e.useCallback)(async h=>{Se.current&&(ce(null),ye("success"),await Ga(xn),Se.current&&de.current?.(h))},[]),J=(0,_e.useCallback)(async(h,we)=>{Se.current&&(ze.current?.(h),we?.emitDecline&&ee(h,we.method),ce(h.message),ye("error"),await Ga(bn))},[ee]),ue=(0,_e.useCallback)(async(h,we,je)=>{let lt=h.data.session??null;if(!lt)throw new Mt.FloPayError("No session data returned","api_error");let nt=lt.clientSecret||t;if(lt.status==="complete"){await A({result:{status:"succeeded"},session:lt,sessionId:lt.id||we,autoCompleted:!1});return}if(lt.status==="expired")throw new Mt.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(h.autoProcessingPending){let bt=(await new no.PaymentAPI(le).waitForCheckoutSessionCompletion(h.autoProcessingPending.sessionId,{initialDelayMs:h.autoProcessingPending.retryAfterMs})).data.session;if(!bt||bt.status!=="complete")throw new Mt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:bt?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await A({result:{status:"succeeded"},session:bt,sessionId:bt.id||we,autoCompleted:!1});return}if(h.autoProcessingError){if(h.autoProcessingError.type==="3ds_required"&&h.autoProcessingError.nextActionRedirectUrl&&we&&nt){let Ye=new AbortController;E.current=Ye;let Ce;try{Ce=await Na({billingApiUrl:le,sessionId:we,nonce:nt,nextActionRedirectUrl:h.autoProcessingError.nextActionRedirectUrl,signal:Ye.signal})}finally{E.current===Ye&&(E.current=null)}if(Ce.status==="declined")throw Ln({type:Ce.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ce.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let At=(await new no.PaymentAPI(le).waitForCheckoutSessionCompletion(we,{initialDelayMs:0,nonce:nt})).data.session;if(!At||At.status!=="complete")throw Ln({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await A({result:{status:"succeeded"},session:At,sessionId:At.id||we,autoCompleted:!1});return}throw Ln(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(je?.fromCreateSession&&h.autoProcessingAttempted===!0)throw Ln({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let rt=await nr({billingApiUrl:le,sessionId:we??lt.id,session:lt,nonce:nt});if(rt.type!=="success")throw Ln({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await A({result:rt.result,session:lt,sessionId:lt.id||we,autoCompleted:!1})}catch(rt){let Ye=Hn(rt),Ce=lt.id||we;await J(Ye,{emitDecline:!0,method:Ye.checkoutMethod??Cr}),ls(Ye,Ce)&&Ce&&Se.current&&Re({sessionId:Ce,errorMessage:Ye.message,nonce:nt||void 0})}},[t,le,J,A]),Ie=(0,_e.useCallback)(async h=>{if(G.onClick?.(h),!(h.defaultPrevented||W||be)){if(Re(null),e&&Fe){let we=new Mt.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await J(we),Se.current&&(ye(null),ce(null));return}if(!e&&!Fe){let we=new Mt.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await J(we),Se.current&&(ye(null),ce(null));return}he(!0),ce(null),ye("processing");try{let we=new no.PaymentAPI(le);if(e){let je=await we.getUnifiedCheckoutSession(e,t);await ue(je,e);return}try{let je=await we.createAndFetchSession({...Fe});await ue(je,je.data.session?.id??null,{fromCreateSession:!0})}catch(je){if(je instanceof Mt.FloPayError&&je.code==="session_auto_completed"){await A({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw je}}catch(we){await J(ss(we,"Automatic payment failed. Please try again."))}finally{Se.current&&(ye(null),ce(null),he(!1))}}},[G,Fe,W,be,t,ue,le,e,J,A]),ft=(0,_e.useCallback)(h=>{let we=oe.current;Re(null),de.current?.({result:h,session:null,sessionId:we?.sessionId??null,autoCompleted:!1})},[]),Qe=(0,_e.useCallback)(h=>{ze.current?.(h)},[]),Ze=(0,_e.useCallback)(h=>{Oe.current?.(h)},[]),y=(0,_e.useMemo)(()=>(0,Mt.resolveTheme)(F),[F]),qe=(0,_e.useMemo)(()=>{let h=y?.buttonsLayout??(0,Mt.resolveButtonsLayoutTheme)(K);return Q?{...h,...Q,cardButton:{...h.cardButton,...Q.cardButton}}:h},[y,K,Q]),Ue=(0,_e.useMemo)(()=>{let h=y?.appearance;return P?h?{...h,...P,variables:{...h.variables,...P.variables}}:P:h},[P,y]),Ve=Ue?.variables,He=Ve?.colorPrimary??"#4A49FF",Ht=Ve?.colorPrimaryHover??Hr(He,.12),Pt=Ve?.borderRadius??"8px";return(0,un.jsxs)(un.Fragment,{children:[(0,un.jsx)("button",{...G,type:me,onClick:Ie,disabled:W||be,"aria-busy":be,style:{width:"100%",...te===void 0?{boxSizing:"border-box",height:is,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...qe.cardButton,...wo({themeBundle:y,resolvedPrimaryColor:He,resolvedBorderRadius:Pt,submitButtonStyle:qe.submitButton,explicitPrimaryColor:Ve?.colorPrimary}),fontSize:qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:W||be?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:W||be?.6:1,...Y},onMouseEnter:h=>{G.onMouseEnter?.(h),!h.defaultPrevented&&!W&&!be&&(y||Ve?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Ht)},onMouseLeave:h=>{G.onMouseLeave?.(h),!h.defaultPrevented&&(y||Ve?.colorPrimary)&&(h.currentTarget.style.backgroundColor=He)},onMouseDown:h=>{G.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{G.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,un.jsx)(Gn,{content:te})}),ne&&(0,un.jsx)(vn,{status:ne,errorMessage:ve}),Ne&&(0,un.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&Re(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,un.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,un.jsx)(to,{sessionId:Ne.sessionId,nonce:Ne.nonce,checkoutMode:"full",billingApiUrl:le,locale:I,theme:F,...Ue?{appearance:Ue}:{},buttonsTheme:K,buttonsStyles:Q,initialErrorMessage:Ne.errorMessage,cardTitleContent:null,onComplete:ft,onError:Qe,onDecline:Ze})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,useCheckout,useElements,useFloPay,usePayPalFloPay});
|