@flopay/react 1.4.19 → 1.4.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +105 -0
- package/dist/index.cjs +9 -9
- package/dist/index.d.cts +67 -2
- package/dist/index.d.ts +67 -2
- package/dist/index.mjs +9 -9
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var Ni=Object.create;var Vr=Object.defineProperty;var Oi=Object.getOwnPropertyDescriptor;var zi=Object.getOwnPropertyNames;var Ui=Object.getPrototypeOf,$i=Object.prototype.hasOwnProperty;var qi=(e,t)=>{for(var n in t)Vr(e,n,{get:t[n],enumerable:!0})},wa=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of zi(t))!$i.call(e,o)&&o!==n&&Vr(e,o,{get:()=>t[o],enumerable:!(l=Oi(t,o))||l.enumerable});return e};var ka=(e,t,n)=>(n=e!=null?Ni(Ui(e)):{},wa(t||!e||!e.__esModule?Vr(n,"default",{value:e,enumerable:!0}):n,e)),ji=e=>wa(Vr({},"__esModule",{value:!0}),e);var Ns={};qi(Ns,{AddressElement:()=>ui,DirectPayPalButton:()=>Er,FloPayAutomaticPaymentButton:()=>hi,FloPayCheckout:()=>mo,FloPayProvider:()=>wr,PayPalButton:()=>fi,PaymentElement:()=>di,SplitCardForm:()=>oo,VaultCardFields:()=>Hr,dropThirdPartyOnlyError:()=>Pi.dropThirdPartyOnlyError,useCheckout:()=>Ta,useElements:()=>Yr,useFloPay:()=>un,usePayPalFloPay:()=>Wr});module.exports=ji(Ns);var Vi=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,Ue=Vi();var St=require("react"),Ra=require("@flopay/shared");var _o=require("react"),In=(0,_o.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),dn=(0,_o.createContext)({session:null,loading:!1,error:null});var Ki=Symbol.for("@flopay/js.telemetry.bridge.v1"),Hi=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Wi(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},flush:async()=>{},destroy:()=>{}}}function Yi(e){let t=Wi(),n=(o,s)=>o?o.bind(e):s,l=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:l,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,l()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Kr(e){let t=globalThis[Hi];return Yi(t?.(e)??{})}function Mt(e){if(e)return e[Ki]}var Ia=require("react/jsx-runtime");function wr({flopay:e,paypalFlopay:t,options:n,children:l}){let[o,s]=(0,St.useState)(e instanceof Promise?null:e),[m,d]=(0,St.useState)(t instanceof Promise||!t?null:t),[I,N]=(0,St.useState)(null),b=(0,St.useRef)(null),_=(0,St.useRef)(null),k=(0,St.useRef)(null);(0,St.useEffect)(()=>{if(!o)return;let x=Mt(o);return b.current=x?.beginCheckout()??x?.now()??0,x?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{x?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),(0,St.useEffect)(()=>{let x=!1;return e instanceof Promise?e.then(M=>{x||s(M)}):s(e),()=>{x=!0}},[e]),(0,St.useEffect)(()=>{let x=!1;if(!t){d(null);return}return t instanceof Promise?t.then(M=>{x||d(M)}):d(t),()=>{x=!0}},[t]),(0,St.useEffect)(()=>{if(!o){N(null);return}let x=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return N(x),()=>{x.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,St.useEffect)(()=>{if(!o||!I||_.current===I)return;_.current=I;let x=Mt(o);x?.log({name:"checkout.rendered",stage:"checkout_render"}),x?.performance({stage:"checkout_render",durationMs:x.elapsed(b.current??0),durationMode:"machine"})},[I,o]);let F=(0,St.useCallback)(()=>{if(!o||!I||k.current===I)return;k.current=I;let x=Mt(o);x?.log({name:"checkout.interactive",stage:"checkout_interactive"}),x?.performance({stage:"checkout_interactive",durationMs:x.elapsed(b.current??0),durationMode:"machine"})},[I,o]),p=(0,Ra.resolveBillingApiUrl)(n?.billingApiUrl),v=(0,St.useMemo)(()=>({flopay:o,paypalFlopay:m,elements:I,billingApiUrl:p,reportInteractive:F}),[o,m,I,p,F]);return(0,Ia.jsx)(In.Provider,{value:v,children:l})}var B=ka(require("react"),1),Xn=require("@flopay/js"),Pe=require("@flopay/shared");var Js=require("react"),et=require("react/jsx-runtime");function Gi(){return(0,et.jsxs)(et.Fragment,{children:[(0,et.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,et.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,et.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,et.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,et.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Ji(){return(0,et.jsx)(et.Fragment,{children:"Go back"})}function Xi(){return(0,et.jsx)(et.Fragment,{children:"Secure card checkout"})}function nr(e){return e!==void 0&&(e===""||e===null||e===!1)}function rr({content:e}){return(0,et.jsx)(et.Fragment,{children:e===void 0?(0,et.jsx)(Gi,{}):e})}function or({content:e}){return(0,et.jsx)(et.Fragment,{children:e===void 0?(0,et.jsx)(Ji,{}):e})}function kr({content:e}){return(0,et.jsx)(et.Fragment,{children:e===void 0?(0,et.jsx)(Xi,{}):e})}var lt=require("@stripe/react-stripe-js"),R=require("@flopay/shared"),mn=require("@flopay/js");var En=require("react"),Ea=require("react/jsx-runtime");function Hr({capture:e,html:t,messageToken:n,expectedOrigin:l,theme:o,containerStyle:s,onReady:m,onError:d,onValidation:I}){let N=(0,En.useRef)(null),b=(0,En.useRef)(m),_=(0,En.useRef)(d),k=(0,En.useRef)(I);b.current=m,_.current=d,k.current=I;let F=(0,En.useRef)(o);return F.current=o,(0,En.useEffect)(()=>{let p=N.current;if(!p)return;let v=!0,x=!1,M=()=>{!v||x||(x=!0,b.current?.())},g=e.on("ready",()=>{M()}),he=e.on("error",ae=>{_.current?.(ae.message??"There was a problem loading the secure card form.")}),z=e.on("validation",ae=>{k.current?.(ae.message??null)}),ue={html:t,...n?{messageToken:n}:{},...l?{expectedOrigin:l}:{},...F.current?{theme:F.current}:{}};return e.mount(p,ue).then(()=>{M()}).catch(ae=>{v&&_.current?.(ae instanceof Error?ae.message:"Failed to load the secure card form.")}),()=>{v=!1,g(),he(),z(),e.unmount()}},[e,t,n,l]),(0,En.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,Ea.jsx)("div",{ref:N,"data-testid":"flopay-vault-card-fields",style:s})}var rl=require("react"),Rr=require("react/jsx-runtime");function ar({children:e,margin:t,icon:n=!0,styleOverride:l}){return(0,Rr.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...l??{}},children:[n&&(0,Rr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Rr.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var _a={alipay:new URL("./payment-logos/alipay.svg",Ue).href,bancontact:new URL("./payment-logos/bancontact.svg",Ue).href,blik:new URL("./payment-logos/blik.svg",Ue).href,eps:new URL("./payment-logos/eps.svg",Ue).href,giropay:new URL("./payment-logos/giropay.svg",Ue).href,ideal:new URL("./payment-logos/ideal.svg",Ue).href,klarna:new URL("./payment-logos/klarna.svg",Ue).href,p24:new URL("./payment-logos/p24.svg",Ue).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",Ue).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",Ue).href};var r=ka(require("react"),1);var ir=require("react"),xa=require("@flopay/shared");function un(){return(0,ir.useContext)(In).flopay}function Wr(){return(0,ir.useContext)(In).paypalFlopay??null}function Yr(){return(0,ir.useContext)(In).elements}function Ta(){return(0,ir.useContext)(dn)}function Gr(){return(0,ir.useContext)(In).billingApiUrl||(0,xa.resolveBillingApiUrl)()}var pl=require("react"),ft=require("react/jsx-runtime"),_n=1200,Cn=1500;function Sn({status:e,errorMessage:t}){return(0,ft.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,ft.jsxs)("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,ft.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,ft.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,ft.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,ft.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,ft.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,ft.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,ft.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,ft.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,ft.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,ft.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,ft.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,ft.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,ft.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&"PROCESSING...",e==="success"&&"PAYMENT SUCCESSFUL",e==="error"&&"PAYMENT FAILED"]}),e==="success"&&(0,ft.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:"You will be automatically redirected, do not close or navigate away from this window."}),e==="error"&&t&&(0,ft.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,ft.jsx)("style",{children:`
|
|
1
|
+
"use strict";var Ji=Object.create;var eo=Object.defineProperty;var Xi=Object.getOwnPropertyDescriptor;var Qi=Object.getOwnPropertyNames;var Zi=Object.getPrototypeOf,es=Object.prototype.hasOwnProperty;var ts=(e,t)=>{for(var n in t)eo(e,n,{get:t[n],enumerable:!0})},Fa=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Qi(t))!es.call(e,a)&&a!==n&&eo(e,a,{get:()=>t[a],enumerable:!(s=Xi(t,a))||s.enumerable});return e};var Da=(e,t,n)=>(n=e!=null?Ji(Zi(e)):{},Fa(t||!e||!e.__esModule?eo(n,"default",{value:e,enumerable:!0}):n,e)),ns=e=>Fa(eo({},"__esModule",{value:!0}),e);var Js={};ts(Js,{AddressElement:()=>Si,DirectPayPalButton:()=>Lr,FloPayAutomaticPaymentButton:()=>Ti,FloPayCardSetup:()=>Ri,FloPayCardSetupError:()=>qr,FloPayCheckout:()=>wo,FloPayProvider:()=>Mr,PayPalButton:()=>_i,PaymentElement:()=>Ci,SplitCardForm:()=>fo,VaultCardFields:()=>cr,dropThirdPartyOnlyError:()=>Mi.dropThirdPartyOnlyError,useCheckout:()=>$a,useElements:()=>ro,useFloPay:()=>dn,usePayPalFloPay:()=>no});module.exports=ns(Js);var rs=()=>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,Ne=rs();var kt=require("react"),La=require("@flopay/shared");var Uo=require("react"),xn=(0,Uo.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),cn=(0,Uo.createContext)({session:null,loading:!1,error:null});var os=Symbol.for("@flopay/js.telemetry.bridge.v1"),as=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function is(){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 ss(e){let t=is(),n=(a,c)=>a?a.bind(e):c,s=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:s,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,s()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function to(e){let t=globalThis[as];return ss(t?.(e)??{})}function Tt(e){if(e)return e[os]}var za=require("react/jsx-runtime");function Mr({flopay:e,paypalFlopay:t,options:n,children:s}){let[a,c]=(0,kt.useState)(e instanceof Promise?null:e),[p,d]=(0,kt.useState)(t instanceof Promise||!t?null:t),[S,$]=(0,kt.useState)(null),P=(0,kt.useRef)(null),E=(0,kt.useRef)(null),w=(0,kt.useRef)(null);(0,kt.useEffect)(()=>{if(!a)return;let I=Tt(a);return P.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,kt.useEffect)(()=>{let I=!1;return e instanceof Promise?e.then(x=>{I||c(x)}):c(e),()=>{I=!0}},[e]),(0,kt.useEffect)(()=>{let I=!1;if(!t){d(null);return}return t instanceof Promise?t.then(x=>{I||d(x)}):d(t),()=>{I=!0}},[t]),(0,kt.useEffect)(()=>{if(!a){$(null);return}let I=a.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return $(I),()=>{I.destroy()}},[a,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,kt.useEffect)(()=>{if(!a||!S||E.current===S)return;E.current=S;let I=Tt(a);I?.log({name:"checkout.rendered",stage:"checkout_render"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(P.current??0),durationMode:"machine"})},[S,a]);let _=(0,kt.useCallback)(()=>{if(!a||!S||w.current===S)return;w.current=S;let I=Tt(a);I?.log({name:"checkout.interactive",stage:"checkout_interactive"}),I?.performance({stage:"checkout_interactive",durationMs:I.elapsed(P.current??0),durationMode:"machine"})},[S,a]),u=(0,La.resolveBillingApiUrl)(n?.billingApiUrl),b=(0,kt.useMemo)(()=>({flopay:a,paypalFlopay:p,elements:S,billingApiUrl:u,reportInteractive:_}),[a,p,S,u,_]);return(0,za.jsx)(xn.Provider,{value:b,children:s})}var D=Da(require("react"),1),tr=require("@flopay/js"),Ce=require("@flopay/shared");var cl=require("react"),dt=require("react/jsx-runtime");function ls(){return(0,dt.jsxs)(dt.Fragment,{children:[(0,dt.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,dt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,dt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,dt.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,dt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function cs(){return(0,dt.jsx)(dt.Fragment,{children:"Go back"})}function ds(){return(0,dt.jsx)(dt.Fragment,{children:"Secure card checkout"})}function ir(e){return e!==void 0&&(e===""||e===null||e===!1)}function sr({content:e}){return(0,dt.jsx)(dt.Fragment,{children:e===void 0?(0,dt.jsx)(ls,{}):e})}function lr({content:e}){return(0,dt.jsx)(dt.Fragment,{children:e===void 0?(0,dt.jsx)(cs,{}):e})}function Ar({content:e}){return(0,dt.jsx)(dt.Fragment,{children:e===void 0?(0,dt.jsx)(ds,{}):e})}var ft=require("@stripe/react-stripe-js"),C=require("@flopay/shared"),pn=require("@flopay/js");var Tn=require("react"),Oa=require("react/jsx-runtime");function cr({capture:e,html:t,messageToken:n,expectedOrigin:s,theme:a,containerStyle:c,onReady:p,onError:d,onValidation:S}){let $=(0,Tn.useRef)(null),P=(0,Tn.useRef)(p),E=(0,Tn.useRef)(d),w=(0,Tn.useRef)(S);P.current=p,E.current=d,w.current=S;let _=(0,Tn.useRef)(a);return _.current=a,(0,Tn.useEffect)(()=>{let u=$.current;if(!u)return;let b=!0,I=!1,x=()=>{!b||I||(I=!0,P.current?.())},h=e.on("ready",()=>{x()}),me=e.on("error",ne=>{E.current?.(ne.message??"There was a problem loading the secure card form.")}),T=e.on("validation",ne=>{w.current?.(ne.message??null)}),ce={html:t,...n?{messageToken:n}:{},...s?{expectedOrigin:s}:{},..._.current?{theme:_.current}:{}};return e.mount(u,ce).then(()=>{x()}).catch(ne=>{b&&E.current?.(ne instanceof Error?ne.message:"Failed to load the secure card form.")}),()=>{b=!1,h(),me(),T(),e.unmount()}},[e,t,n,s]),(0,Tn.useEffect)(()=>{a&&e.applyTheme?.(a)},[e,a]),(0,Oa.jsx)("div",{ref:$,"data-testid":"flopay-vault-card-fields",style:c})}var gl=require("react"),Br=require("react/jsx-runtime");function dr({children:e,margin:t,icon:n=!0,styleOverride:s}){return(0,Br.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"}:{},...s??{}},children:[n&&(0,Br.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Br.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 Na={alipay:new URL("./payment-logos/alipay.svg",Ne).href,bancontact:new URL("./payment-logos/bancontact.svg",Ne).href,blik:new URL("./payment-logos/blik.svg",Ne).href,eps:new URL("./payment-logos/eps.svg",Ne).href,giropay:new URL("./payment-logos/giropay.svg",Ne).href,ideal:new URL("./payment-logos/ideal.svg",Ne).href,klarna:new URL("./payment-logos/klarna.svg",Ne).href,p24:new URL("./payment-logos/p24.svg",Ne).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",Ne).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",Ne).href};var o=Da(require("react"),1);var ur=require("react"),Ua=require("@flopay/shared");function dn(){return(0,ur.useContext)(xn).flopay}function no(){return(0,ur.useContext)(xn).paypalFlopay??null}function ro(){return(0,ur.useContext)(xn).elements}function $a(){return(0,ur.useContext)(cn)}function oo(){return(0,ur.useContext)(xn).billingApiUrl||(0,Ua.resolveBillingApiUrl)()}var Rl=require("react"),bt=require("react/jsx-runtime"),Mn=1200,Sn=1500;function wn({status:e,errorMessage:t,authorized:n=!1}){return(0,bt.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,bt.jsxs)("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,bt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,bt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,bt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,bt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,bt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,bt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,bt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,bt.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,bt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,bt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,bt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,bt.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,bt.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&"PROCESSING...",e==="success"&&(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL"),e==="error"&&"PAYMENT FAILED"]}),e==="success"&&(0,bt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:"You will be automatically redirected, do not close or navigate away from this window."}),e==="error"&&t&&(0,bt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,bt.jsx)("style",{children:`
|
|
2
2
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
3
3
|
@keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
|
|
4
4
|
@keyframes flopay-draw { to { stroke-dashoffset: 0; } }
|
|
5
5
|
@keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
|
|
6
|
-
`})]})})}var Ma=require("@flopay/shared");function Ba(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function xo(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Aa(e,t){let n=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],l=n.reduce((s,m)=>s+(m.overrideAmount??m.totalAmount??0),0),o=e.currency??n.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(l*100),currency:o,status:"open",customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((s,m)=>({uuid:`synthetic-${s.type??"item"}-${m}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??o,metadata:s.metadata??null}))}}function To(e,t){return t?{...e,...t}:e}function wt(e,t,n){let l=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,s=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:l,...o?{code:o}:{},...s?{declineCode:s}:{}}}var Qi=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function On(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:l}of Qi)if(n.test(t))return l;return e}function Jr(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Fa(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Da(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Xr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Qr="flopay_recent_completion_";function sr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Qr+e,JSON.stringify(t))}catch{}}function Mo(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Qr+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Qr+e),!1):!0}catch{return!1}}function La(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var A=require("react"),za=require("@paypal/paypal-js"),Zr=require("@flopay/js"),Tn=require("@flopay/shared");function st(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function Zi(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Gn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function xn(e){if(typeof e!="object"||e===null)return;let t=e;return Gn(t.code)??Gn(t.type)??Gn(t.name)}function lr(e){if(!(typeof e!="object"||e===null))return Gn(e.decline_code)}function Ir(e){return typeof e!="object"||e===null?!1:Gn(e.type)?.toLowerCase()==="card_error"||lr(e)!==void 0}function zn(e){let t=Zi(e)?.toLowerCase()??"",l=`${xn(e)?.toLowerCase()??""} ${t}`;return l.includes("popup")&&l.includes("block")}var pn=require("react/jsx-runtime"),eo=45,es=1e3,ts=11e3,ns=["https://www.paypal.com","https://www.sandbox.paypal.com"],Na="We couldn't open PayPal. Try again or choose another payment method.",rs={width:"100%",minHeight:eo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Oa(e){return e.includes("No ack for postMessage init()")&&ns.some(t=>e.includes(t))&&e.includes("10000ms")}function os(e){return e?`${Na} Allow pop-ups for this site, then try again.`:Na}function Ua({sessionId:e,nonce:t,billingApiUrl:n,email:l,clientId:o,environment:s,currency:m,isSubscription:d,onTokenizedBody:I,onComplete:N,onErrorChange:b,onDecline:_,onTechnicalFailure:k,isProcessing:F=!1,onLoadStateChange:p,onInitializationStateChange:v,allowAutomaticRetry:x=!0,onButtonClick:M,runBeforeButtonClick:g,session:he,existingOrderId:z,telemetry:ue,telemetryContext:ae,debug:U=!1}){let te=un(),Q=(0,A.useMemo)(()=>{if(te)return null;let D=Kr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Tn.SDK_VERSION,enabled:ue!==!1});return D.setCheckoutContext(ae??{}),D.beginCheckout(ae??{}),D},[n,te,ue,ae?.checkoutMode,ae?.layout]),pe=(0,A.useMemo)(()=>Mt(te),[te]);(0,A.useEffect)(()=>()=>{Q&&Q.flush().catch(()=>{}).finally(()=>Q.destroy())},[Q]);let W=(0,A.useMemo)(()=>({error:D=>{pe?pe.error(D):Q?.error(D)},log:D=>{pe?pe.log(D):Q?.log(D)},performance:D=>{pe?pe.performance(D):Q?.performance(D)},terminal:D=>{pe?pe.terminal(D):Q?.terminal(D)},startTiming:()=>pe?.now()??Q?.now()??0,elapsed:D=>pe?.elapsed(D)??Math.max(0,(Q?.now()??D)-D)}),[pe,Q]),J=(0,A.useRef)(null),me=(0,A.useRef)(0),Me=(0,A.useRef)(null),we=(0,A.useRef)(!1),[be,ie]=(0,A.useState)(!1),[Ce,Be]=(0,A.useState)(!1),[se,Ee]=(0,A.useState)(0),_e=(0,A.useRef)(0),[Re,Z]=(0,A.useState)(!1),T=(0,A.useRef)(!1),ce=(0,A.useRef)(!1),[Oe,ze]=(0,A.useState)(!1),[ye,E]=(0,A.useState)(!1),re=(0,A.useMemo)(()=>n.replace(/\/+$/,""),[n]),oe=(0,A.useMemo)(()=>JSON.stringify([re,o,m,s??"",d,e,z??""]),[re,o,m,s,z,d,e]),$e=(0,A.useRef)(oe),ct=$e.current!==oe,[He,ot]=(0,A.useState)([]),V=D=>{U&&ot(gt=>[...gt,`${new Date().toISOString().slice(11,23)} ${D}`])},G=(0,A.useRef)(I),tt=(0,A.useRef)(N),Ae=(0,A.useRef)(b),at=(0,A.useRef)(_),Ge=(0,A.useRef)(k),We=(0,A.useRef)(M),rn=(0,A.useRef)(p),h=(0,A.useRef)(v),ke=(0,A.useRef)(g),dt=(0,A.useRef)(he),nt=(0,A.useRef)(l),Qe=(0,A.useRef)(t),Ye=(0,A.useRef)(null),Ze=(0,A.useRef)(0),xe=(0,A.useRef)(null),Ke=(0,A.useRef)(null),kt=(0,A.useRef)(new Map),Je=(0,A.useRef)(new Map),An=(0,A.useRef)(!1);(0,A.useEffect)(()=>(An.current=!0,()=>{An.current=!1}),[]),(0,A.useEffect)(()=>{G.current=I},[I]),(0,A.useEffect)(()=>{tt.current=N},[N]),(0,A.useEffect)(()=>{Ae.current=b},[b]),(0,A.useEffect)(()=>{at.current=_},[_]),(0,A.useEffect)(()=>{Ge.current=k},[k]),(0,A.useEffect)(()=>{We.current=M},[M]),(0,A.useEffect)(()=>{rn.current=p},[p]),(0,A.useEffect)(()=>{h.current=v},[v]),(0,A.useEffect)(()=>{ke.current=g},[g]),(0,A.useEffect)(()=>{dt.current=he},[he]),(0,A.useEffect)(()=>{nt.current=l},[l]),(0,A.useEffect)(()=>{Qe.current=t},[t]),(0,A.useEffect)(()=>{_e.current=se},[se]),(0,A.useEffect)(()=>{Re&&Me.current?.focus()},[Re,se]);let Pt=(0,A.useCallback)(()=>{window.setTimeout(()=>{Me.current?.focus()},0)},[]),Fn=(0,A.useCallback)(()=>{ie(!1),Ee(D=>D+1)},[]),on=(0,A.useCallback)(()=>{Z(!1),(J.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??J.current)?.focus?.()},[]);(0,A.useEffect)(()=>{!be||!we.current||(we.current=!1,on())},[on,be,se]);let hn=(0,A.useCallback)((D,gt)=>{let ut=Ge.current;if(ut){ut("paypal",D,gt);return}Ae.current?.(os(gt?.popupBlocked??zn(D)))},[]),Zt=()=>{xe.current?.timer&&(clearTimeout(xe.current.timer),xe.current.timer=null)},Dn=()=>{Zt();let D=Ze.current+1;return Ze.current=D,Ke.current=null,xe.current={generation:D,timer:null,yieldedControl:!1},Z(!1),D},Nt=D=>D!==void 0&&xe.current?.generation!==D?!1:(Zt(),xe.current=null,Ke.current=null,!0),Rt=D=>{let gt=D?.generation??xe.current?.generation??Ze.current;(!D?.generation||xe.current?.generation===gt)&&(Zt(),xe.current=null),Ke.current=gt,D?.showRetry&&Z(!0),D?.remount&&Fn(),D?.focus!==!1&&Pt()},qt=D=>xe.current?.generation===D&&Ke.current!==D,Gt=D=>{typeof document<"u"&&document.visibilityState!=="visible"||(Zt(),D.timer=setTimeout(()=>{xe.current?.generation===D.generation&&(xe.current=null,Ke.current=D.generation,hn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),Z(!0),Fn(),Pt())},600))},Bt=()=>{let D=xe.current;D?.yieldedControl&&Gt(D)},jt=()=>{let D=xe.current;D&&(D.yieldedControl=!0,Zt())},At=D=>{let gt=Ye.current;return gt&&Je.current.set(D,gt),D};(0,A.useEffect)(()=>{let D=()=>{document.visibilityState==="visible"?Bt():jt()};return document.addEventListener("visibilitychange",D),window.addEventListener("focus",Bt),window.addEventListener("blur",jt),()=>{document.removeEventListener("visibilitychange",D),window.removeEventListener("focus",Bt),window.removeEventListener("blur",jt),Zt()}},[]),(0,A.useEffect)(()=>{$e.current!==oe&&($e.current=oe,T.current=!1,ce.current=!1,ie(!1),Be(!1),ze(!1),h.current?.("loading"))},[oe]),(0,A.useEffect)(()=>{st(()=>rn.current?.(be&&!Oe))},[be,Oe]);let le=(0,Tn.normalizeGatewayEnvironment)(s);(0,A.useEffect)(()=>{let D=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",gt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(V(`mount clientId=${D} env=${s??"(unset)"}\u2192${le??"live"} ccy=${m} sub=${d}`),V(`ua=${gt.slice(0,80)}${gt.length>80?"\u2026":""}`),!o){V("FAIL: clientId empty \u2014 gateway misconfigured"),ze(!0),W.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!J.current){V("FAIL: containerRef not attached");return}me.current=W.startTiming(),W.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ut=!1,bt=!1,Te=()=>ut||bt,qe,$n=!1,Ln=()=>{qe=(0,Tn.generateIdempotencyKey)(),qe||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),$n=!0},qn=null,Zn=!1,Vt=null,it=!1,Ft=()=>{!Vt||it||(it=!0,Vt.close().catch(()=>{}))},Kt=null,ht=()=>{Kt!==null&&(W.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"overlay_return",durationMs:W.elapsed(Kt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Kt=null)},Jt=!1,Ht=J.current,an=null,Pn=null,It=[],Ot=u=>{if(!u||typeof u.getBoundingClientRect!="function")return"(no rect)";let c=u.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},Le=u=>{if(!u)return"(empty)";try{let c=new URL(u,typeof window<"u"?window.location.href:"https://localhost"),L=c.pathname.toLowerCase();return L.includes("checkcaptcha")||L.includes("captcha")?`CAPTCHA(${c.host}${L})`:L.includes("risk")||L.includes("challenge")?`RISK(${c.host}${L})`:L.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${L}`.slice(0,100)}catch{return u.slice(0,80)}},vt=u=>{let c=u.getAttribute("src"),L=u.getAttribute("srcdoc"),f=u.getAttribute("name"),ee=u.getAttribute("sandbox"),Ie=[];return c&&Ie.push(`src=${Le(c)}`),L&&Ie.push(`srcdoc[${L.length}ch]`),!c&&!L&&Ie.push("src=(empty) srcdoc=(empty)"),f&&Ie.push(`name=${f.slice(0,40)}`),ee!==null&&Ie.push(`sandbox="${ee.slice(0,40)}"`),Ie.join(" ")},Ct=u=>{if(!(u instanceof HTMLIFrameElement))return"";try{let c=u.contentDocument;if(!c)return"cd=null";let L=c.body?.children.length??0,f=c.body?.innerHTML.length??0,ee=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${L}children,${f}ch] head[${ee}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},bn=[],jn=u=>{if(Te())return;let c=u.message??String(u.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(V(`window:error ${c.slice(0,140)}`),bn.push(c))},Wt=u=>{if(Te())return;let c=u.reason instanceof Error?u.reason.message:String(u.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(V(`window:rejection ${c.slice(0,140)}`),bn.push(c))};U&&typeof window<"u"&&(window.addEventListener("error",jn),window.addEventListener("unhandledrejection",Wt));let Xt={value:0};if(U&&typeof PerformanceObserver<"u")try{Pn=new PerformanceObserver(u=>{if(!Te())for(let c of u.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;Xt.value+=1;let L=Math.round(c.duration);V(`net ${L}ms ${c.name.slice(0,90)}`)}}),Pn.observe({type:"resource",buffered:!0})}catch{}let Dt=()=>{for(an?.disconnect(),an=null,Pn?.disconnect(),Pn=null;It.length;)clearTimeout(It.pop());U&&typeof window<"u"&&(window.removeEventListener("error",jn),window.removeEventListener("unhandledrejection",Wt))},kn=u=>{if(!u)return!1;let c=u.toLowerCase();return c.includes("zoid destroyed")||c.includes("destroyed all components")||c.includes("window closed")||c.includes("detected container element removed")},Nn=u=>{if(Te()||kn(u))return;let c=On(u)??u;st(()=>Ae.current?.(c))},sn=u=>{ut||(ze(!0),u.includes("paypal_ineligible")||W.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",u))},Qt=(u,c=!1)=>{if(ut)return;let L=T.current||!x;if(Zn)return;Zn=!0,bt=!0,Dt(),Ft();let f=c||Oa(u);if(f&&x&&!T.current){T.current=!0,ie(!1),E(!1),Be(!0),h.current?.("retrying"),qn=setTimeout(()=>{ut||Ee(ee=>ee+1)},es);return}if(f||L){if(ie(!1),E(!1),Be(!1),ze(!0),h.current?.("exhausted"),!ce.current){ce.current=!0;let ee=Oa(u)?"paypal_init_timeout":c?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",ee)}return}sn(u)};ze(!1);let Et=async(u,c=Ye.current)=>{if(Te())return;let L=c?.sessionId??e;if(G.current){await G.current(u,{sessionId:L,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let f=W.startTiming();W.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ee=()=>{W.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"processing",durationMs:W.elapsed(f),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Ie=dt.current,rt=c?.accountPatch?.email??nt.current,Se=c?.accountPatch?.userId??Ie?.customer?.id??Ie?.accountData?.userId??"",y=await new Zr.PaymentAPI(re,{telemetry:!1}).processPayment(Se,{sessionId:L,nonce:c?.nonce??Qe.current,tokenizedData:u,accountData:{userId:Se,email:rt??Ie?.customer?.email??"",firstName:c?.accountPatch?.firstName??Ie?.customer?.firstName??Ie?.accountData?.firstName??"",lastName:c?.accountPatch?.lastName??Ie?.customer?.lastName??Ie?.accountData?.lastName??"",country:c?.accountPatch?.country??Ie?.customer?.country??Ie?.accountData?.country??void 0,zip:c?.accountPatch?.zip??Ie?.customer?.zip??Ie?.accountData?.zip??void 0}});if(y.ok){if(bt||ut&&An.current)return;ee(),W.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),st(()=>tt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Te())return;let $=await y.json().catch(()=>null),q=$?.message??"PayPal payment failed.",Ve=On(q)??q;ee(),y.status===400&&(typeof $?.declineCode=="string"||!Array.isArray($?.fields))?W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):y.status===400||y.status===422?W.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):W.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:y.status>=500?"5xx":y.status>=400?"4xx":y.status>=300?"3xx":"unknown",failureCategory:y.status>=500?"server_error":void 0}),Nn(Ve),st(()=>at.current?.(wt("paypal",Ve,{code:$?.code,declineCode:$?.declineCode})));return}catch(Ie){if(Te())return;ee(),W.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let rt=Ie instanceof Error?Ie.message:"PayPal payment failed.",Se=On(rt)??rt;Nn(Se),st(()=>at.current?.(wt("paypal",Se)));return}},P=()=>new Tn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Y=u=>Te()?Promise.reject(P()):Promise.resolve(u),K=async u=>{if(Te())throw P();$n||Ln();let c=Ye.current,L=c?.sessionId??e,f=c?.nonce??Qe.current;W.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ee=await new Zr.PaymentAPI(re,{telemetry:!1}).createSessionIntent(L,f??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:qe});if(Te())throw P();if(ee.provider!=="paypal")throw new Error(u);return W.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ee.providerObjectId},fe=(u,c)=>{let L=c?.nonce??Qe.current;if(!L)return;let f=c?.sessionId??e,ee=lr(u)??xn(u)??"provider_declined";new Zr.PaymentAPI(re,{telemetry:!1}).reportSessionIntentDecline(f,L,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ee}).catch(()=>{})},X=se;V("loadScript:scheduled (deferred 1 tick)");let de=null,S=setTimeout(()=>{if(ut){V("loadScript:skipped (cancelled before defer ran)");return}V("loadScript:start");let u=le==="live"?"production":le;de=(0,za.loadScript)({clientId:o,currency:m,intent:d?"subscription":"capture",vault:d?!0:void 0,...u?{environment:u}:{},...u==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),de.then(c=>{if(V(`loadScript:resolved inactive=${Te()} ns=${!!c} buttons=${!!c?.Buttons}`),Te())return;if(!c?.Buttons){V("FAIL: namespace missing Buttons factory"),Qt("PayPal SDK did not expose the Buttons factory.");return}W.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"provider_ready",durationMs:W.elapsed(me.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),W.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let L=async O=>{if(Te()||_e.current!==X)return;let y=O.subscriptionID??O.orderID??"",$=y?Je.current.get(y):kt.current.get(X);if(!(!$||!qt($.generation))&&Nt($.generation)){Je.current.delete(y),kt.current.delete($.surfaceKey),ht();try{if(E(!0),st(()=>Ae.current?.(null)),!y)throw new Tn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Et({id:y,isPaypal:!0},$)}catch(q){Nn(q instanceof Error?q.message:"PayPal capture failed.")}finally{Te()||E(!1)}}},f=c.Buttons({style:{layout:"horizontal",height:eo,tagline:!1},onClick:async(O,y)=>{if(Te()){await y.reject();return}Ln();let $=ke.current,q={};if($)try{let _t=await $("paypal");if(Te()){await y.reject();return}if(!_t.proceed){Ye.current=null,kt.current.delete(X),await y.reject();return}q={sessionId:_t.sessionId,accountPatch:_t.accountPatch,nonce:_t.nonce}}catch(_t){V(`onClick:runBeforeButtonClick rejected msg=${(_t instanceof Error?_t.message:String(_t)).slice(0,120)}`),Ye.current=null,kt.current.delete(X),await y.reject();return}st(()=>We.current?.("paypal"));let pt={generation:Dn(),surfaceKey:X,...q};Ye.current=pt,kt.current.set(X,pt),await y.resolve(),W.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),W.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Kt=W.startTiming()},createOrder:d?void 0:z?()=>Y(z).then(At):()=>K("Failed to create PayPal order.").then(At),createSubscription:d?z?()=>Y(z).then(At):()=>K("Failed to create PayPal subscription.").then(At):void 0,onApprove:L,onCancel:()=>{if(Te())return;let O=kt.current.get(X)??Ye.current;O&&kt.current.delete(O.surfaceKey),Ye.current=null,ht(),W.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we.current=!0,Rt({generation:O?.generation,remount:!0,focus:!1})},onError:O=>{if(Te()||_e.current!==X)return;let y=O instanceof Error?O.message:"PayPal failed to render.";if(V(`onError rendered=${Jt} msg=${y.slice(0,120)}`),Jt){let $=kt.current.get(X)??Ye.current;if($&&!qt($.generation)||!$&&Ke.current===Ze.current)return;if(kn(y)){Nt($?.generation);return}if(ht(),Ir(O)){W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),fe(O,$),st(()=>at.current?.(wt("paypal",y))),$&&kt.current.delete($.surfaceKey),Ye.current=null,Nt($?.generation);return}let q=y.toLowerCase();W.error({errorCode:q.includes("popup")&&q.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),$&&kt.current.delete($.surfaceKey),Ye.current=null,Rt({generation:$?.generation,remount:!0,showRetry:!0,focus:!0}),hn(O,{code:"paypal_runtime_failed"});return}Qt(y)}}),ee=f.isEligible();if(V(`isEligible=${ee}`),W.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ee){ie(!1),Qt("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Vt=f,U&&V(`container:dims ${Ot(Ht)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),U&&typeof MutationObserver<"u"&&(an=new MutationObserver(O=>{if(!Te()){for(let y of O)if(y.type==="childList")y.addedNodes.forEach($=>{if(!($ instanceof Element))return;let q=$.tagName.toLowerCase(),Ve=($.getAttribute("title")??"").slice(0,40),pt=q==="iframe"?` ${vt($)}`:"";V(`child+ ${q}${Ve?` title="${Ve}"`:""}${pt} dims=${Ot($)}`)});else if(y.type==="attributes"&&y.target instanceof Element){let $=y.target;if($.tagName.toLowerCase()!=="iframe")continue;let q=y.attributeName;(q==="src"||q==="srcdoc")&&V(`attr~ iframe ${q}=${q==="srcdoc"?`[${($.getAttribute("srcdoc")??"").length}ch]`:Le($.getAttribute("src"))} dims=${Ot($)}`)}}}),an.observe(Ht,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let rt=O=>{if(Te()||Jt)return;let y=Ht.querySelectorAll("iframe"),$=typeof document<"u"&&"hasStorageAccess"in document;V(`watchdog:${O} container=${Ot(Ht)} children=${Ht.childElementCount} iframes=${y.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${$} paypalNetRequests=${Xt.value}`),y.forEach((q,Ve)=>{let pt=(q.getAttribute("title")??"").slice(0,40);V(` iframe[${Ve}] ${Ot(q)}${pt?` title="${pt}"`:""} ${vt(q)}`);let _t=Ct(q);_t&&V(` ${_t}`)}),bn.length===0&&V(" (no PayPal/zoid window errors captured)")};U&&(It.push(setTimeout(()=>rt("3s"),3e3)),It.push(setTimeout(()=>rt("8s"),8e3)),It.push(setTimeout(()=>rt("15s"),15e3))),V("render:start");let Se=W.startTiming();It.push(setTimeout(()=>{Te()||Jt||(V("watchdog:11s retryable render timeout"),Qt("PayPal Buttons render did not settle within 11000ms.",!0))},ts)),f.render(Ht).then(()=>{if(V(`render:resolved inactive=${Te()}`),Dt(),Te()){Ft();return}Jt=!0,ie(!0),Be(!1),h.current?.("ready"),W.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"checkout_render",durationMs:W.elapsed(Se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(O=>{let y=O instanceof Error?O.message:"PayPal failed to render.";V(`render:rejected msg=${y.slice(0,120)}`),Dt(),Qt(y)})}).catch(c=>{let L=c instanceof Error?c.message:"PayPal SDK failed to load.";V(`loadScript:rejected msg=${L.slice(0,120)}`),Qt(L)})},0);return()=>{ut=!0,clearTimeout(S),qn&&clearTimeout(qn),Dt(),Ft()}},[x,re,o,m,s,d,e,z,se,W]);let en=U?(0,pn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Oe?"#fef2f2":"#f3f4f6",border:`1px solid ${Oe?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${be} failed=${Oe})`,He.length===0?`
|
|
6
|
+
`})]})})}var pr=require("@flopay/shared");function qa(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 $o(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 ja(e,t){let n=e.products??[...(e.subscriptions??[]).map(c=>({type:"subscription",code:c.code??c.providerPlanId,name:c.subscriptionName??c.providerPlanName??c.code??c.providerPlanId??null,quantity:c.quantity??1,totalAmount:c.totalAmount,overrideAmount:c.overrideAmount,currency:c.currency,metadata:c.metadata})),...(e.items??[]).map(c=>({type:"item",code:c.code??c.providerItemId,name:c.itemName??c.providerItemName??c.code??c.providerItemId??null,quantity:c.quantity??1,totalAmount:c.totalAmount,overrideAmount:c.overrideAmount,currency:c.currency,metadata:c.metadata}))],s=n.reduce((c,p)=>c+(p.overrideAmount??p.totalAmount??0),0),a=e.currency??n.find(c=>c.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(c=>c.type==="subscription")?"subscription":"payment",amount:Math.round(s*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((c,p)=>({uuid:`synthetic-${c.type??"item"}-${p}`,checkoutSessionId:"",type:c.type??"item",code:c.code,name:c.name??null,quantity:c.quantity??1,totalAmount:c.totalAmount,overrideAmount:c.overrideAmount??null,currency:c.currency??a,metadata:c.metadata??null}))}}function qo(e,t){return t?{...e,...t}:e}function Rt(e,t,n){let s=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,c=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:s,...a?{code:a}:{},...c?{declineCode:c}:{}}}var us=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Un(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:s}of us)if(n.test(t))return s;return e}function Qn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function mr(e){return e?.status==="authorized"||e?.status==="complete"}function Va(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ao(e){let t=Va(e);return new pr.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function io(e){let t=Va(e);return new pr.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function so(e,t){return e==="processing"||(0,pr.isMoneySettledOutcome)(e,t)}function Ka(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Ha(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Fr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var lo="flopay_recent_completion_";function yr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(lo+e,JSON.stringify(t))}catch{}}function jo(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(lo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(lo+e),!1):!0}catch{return!1}}function Wa(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 N=require("react"),Ja=require("@paypal/paypal-js"),co=require("@flopay/js"),Bn=require("@flopay/shared");function Ge(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 ps(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 Zn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function An(e){if(typeof e!="object"||e===null)return;let t=e;return Zn(t.code)??Zn(t.type)??Zn(t.name)}function fr(e){if(!(typeof e!="object"||e===null))return Zn(e.decline_code)}function Dr(e){return typeof e!="object"||e===null?!1:Zn(e.type)?.toLowerCase()==="card_error"||fr(e)!==void 0}function $n(e){let t=ps(e)?.toLowerCase()??"",s=`${An(e)?.toLowerCase()??""} ${t}`;return s.includes("popup")&&s.includes("block")}var un=require("react/jsx-runtime"),uo=45,ms=1e3,ys=11e3,fs=["https://www.paypal.com","https://www.sandbox.paypal.com"],Ya="We couldn't open PayPal. Try again or choose another payment method.",gs={width:"100%",minHeight:uo,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 Ga(e){return e.includes("No ack for postMessage init()")&&fs.some(t=>e.includes(t))&&e.includes("10000ms")}function hs(e){return e?`${Ya} Allow pop-ups for this site, then try again.`:Ya}function Xa({sessionId:e,nonce:t,billingApiUrl:n,email:s,clientId:a,environment:c,currency:p,isSubscription:d,onTokenizedBody:S,onComplete:$,onErrorChange:P,onDecline:E,onTechnicalFailure:w,isProcessing:_=!1,onLoadStateChange:u,onInitializationStateChange:b,allowAutomaticRetry:I=!0,onButtonClick:x,runBeforeButtonClick:h,session:me,existingOrderId:T,telemetry:ce,telemetryContext:ne,debug:q=!1}){let Q=dn(),W=(0,N.useMemo)(()=>{if(Q)return null;let U=to({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Bn.SDK_VERSION,enabled:ce!==!1});return U.setCheckoutContext(ne??{}),U.beginCheckout(ne??{}),U},[n,Q,ce,ne?.checkoutMode,ne?.layout]),ie=(0,N.useMemo)(()=>Tt(Q),[Q]);(0,N.useEffect)(()=>()=>{W&&W.flush().catch(()=>{}).finally(()=>W.destroy())},[W]);let K=(0,N.useMemo)(()=>({error:U=>{ie?ie.error(U):W?.error(U)},log:U=>{ie?ie.log(U):W?.log(U)},performance:U=>{ie?ie.performance(U):W?.performance(U)},terminal:U=>{ie?ie.terminal(U):W?.terminal(U)},startTiming:()=>ie?.now()??W?.now()??0,elapsed:U=>ie?.elapsed(U)??Math.max(0,(W?.now()??U)-U)}),[ie,W]),L=(0,N.useRef)(null),re=(0,N.useRef)(0),ye=(0,N.useRef)(null),ue=(0,N.useRef)(!1),[pe,se]=(0,N.useState)(!1),[Se,De]=(0,N.useState)(!1),[le,je]=(0,N.useState)(0),Oe=(0,N.useRef)(0),[_e,X]=(0,N.useState)(!1),k=(0,N.useRef)(!1),de=(0,N.useRef)(!1),[Ve,Ue]=(0,N.useState)(!1),[ge,B]=(0,N.useState)(!1),fe=(0,N.useMemo)(()=>n.replace(/\/+$/,""),[n]),Z=(0,N.useMemo)(()=>JSON.stringify([fe,a,p,c??"",d,e,T??""]),[fe,a,p,c,T,d,e]),xe=(0,N.useRef)(Z),ut=xe.current!==Z,[Ze,pt]=(0,N.useState)([]),z=U=>{q&&pt(st=>[...st,`${new Date().toISOString().slice(11,23)} ${U}`])},ee=(0,N.useRef)(S),rt=(0,N.useRef)($),Ke=(0,N.useRef)(P),mt=(0,N.useRef)(E),$e=(0,N.useRef)(w),Je=(0,N.useRef)(x),Gt=(0,N.useRef)(u),Qe=(0,N.useRef)(b),Jt=(0,N.useRef)(h),M=(0,N.useRef)(me),we=(0,N.useRef)(s),Xe=(0,N.useRef)(t),Te=(0,N.useRef)(null),vt=(0,N.useRef)(0),We=(0,N.useRef)(null),He=(0,N.useRef)(null),ot=(0,N.useRef)(new Map),et=(0,N.useRef)(new Map),Rn=(0,N.useRef)(!1);(0,N.useEffect)(()=>(Rn.current=!0,()=>{Rn.current=!1}),[]),(0,N.useEffect)(()=>{ee.current=S},[S]),(0,N.useEffect)(()=>{rt.current=$},[$]),(0,N.useEffect)(()=>{Ke.current=P},[P]),(0,N.useEffect)(()=>{mt.current=E},[E]),(0,N.useEffect)(()=>{$e.current=w},[w]),(0,N.useEffect)(()=>{Je.current=x},[x]),(0,N.useEffect)(()=>{Gt.current=u},[u]),(0,N.useEffect)(()=>{Qe.current=b},[b]),(0,N.useEffect)(()=>{Jt.current=h},[h]),(0,N.useEffect)(()=>{M.current=me},[me]),(0,N.useEffect)(()=>{we.current=s},[s]),(0,N.useEffect)(()=>{Xe.current=t},[t]),(0,N.useEffect)(()=>{Oe.current=le},[le]),(0,N.useEffect)(()=>{_e&&ye.current?.focus()},[_e,le]);let it=(0,N.useCallback)(()=>{window.setTimeout(()=>{ye.current?.focus()},0)},[]),jn=(0,N.useCallback)(()=>{se(!1),je(U=>U+1)},[]),Kt=(0,N.useCallback)(()=>{X(!1),(L.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??L.current)?.focus?.()},[]);(0,N.useEffect)(()=>{!pe||!ue.current||(ue.current=!1,Kt())},[Kt,pe,le]);let hn=(0,N.useCallback)((U,st)=>{let Ft=$e.current;if(Ft){Ft("paypal",U,st);return}Ke.current?.(hs(st?.popupBlocked??$n(U)))},[]),Xt=()=>{We.current?.timer&&(clearTimeout(We.current.timer),We.current.timer=null)},rr=()=>{Xt();let U=vt.current+1;return vt.current=U,He.current=null,We.current={generation:U,timer:null,yieldedControl:!1},X(!1),U},Mt=U=>U!==void 0&&We.current?.generation!==U?!1:(Xt(),We.current=null,He.current=null,!0),St=U=>{let st=U?.generation??We.current?.generation??vt.current;(!U?.generation||We.current?.generation===st)&&(Xt(),We.current=null),He.current=st,U?.showRetry&&X(!0),U?.remount&&jn(),U?.focus!==!1&&it()},Qt=U=>We.current?.generation===U&&He.current!==U,Zt=U=>{typeof document<"u"&&document.visibilityState!=="visible"||(Xt(),U.timer=setTimeout(()=>{We.current?.generation===U.generation&&(We.current=null,He.current=U.generation,hn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),X(!0),jn(),it())},600))},At=()=>{let U=We.current;U?.yieldedControl&&Zt(U)},Bt=()=>{let U=We.current;U&&(U.yieldedControl=!0,Xt())},Ct=U=>{let st=Te.current;return st&&et.current.set(U,st),U};(0,N.useEffect)(()=>{let U=()=>{document.visibilityState==="visible"?At():Bt()};return document.addEventListener("visibilitychange",U),window.addEventListener("focus",At),window.addEventListener("blur",Bt),()=>{document.removeEventListener("visibilitychange",U),window.removeEventListener("focus",At),window.removeEventListener("blur",Bt),Xt()}},[]),(0,N.useEffect)(()=>{xe.current!==Z&&(xe.current=Z,k.current=!1,de.current=!1,se(!1),De(!1),Ue(!1),Qe.current?.("loading"))},[Z]),(0,N.useEffect)(()=>{Ge(()=>Gt.current?.(pe&&!Ve))},[pe,Ve]);let ae=(0,Bn.normalizeGatewayEnvironment)(c);(0,N.useEffect)(()=>{let U=a?`${a.slice(0,6)}\u2026(len ${a.length})`:"(empty)",st=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(z(`mount clientId=${U} env=${c??"(unset)"}\u2192${ae??"live"} ccy=${p} sub=${d}`),z(`ua=${st.slice(0,80)}${st.length>80?"\u2026":""}`),!a){z("FAIL: clientId empty \u2014 gateway misconfigured"),Ue(!0),K.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(!L.current){z("FAIL: containerRef not attached");return}re.current=K.startTiming(),K.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ft=!1,Ln=!1,Le=()=>Ft||Ln,lt,Ye=!1,En=()=>{lt=(0,Bn.generateIdempotencyKey)(),lt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Ye=!0},In=null,zn=!1,Kn=null,_n=!1,at=()=>{!Kn||_n||(_n=!0,Kn.close().catch(()=>{}))},Dt=null,on=()=>{Dt!==null&&(K.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),K.performance({stage:"overlay_return",durationMs:K.elapsed(Dt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Dt=null)},gt=!1,It=L.current,en=null,an=null,Ht=[],Ot=y=>{if(!y||typeof y.getBoundingClientRect!="function")return"(no rect)";let r=y.getBoundingClientRect();return`${Math.round(r.width)}\xD7${Math.round(r.height)}`},Nt=y=>{if(!y)return"(empty)";try{let r=new URL(y,typeof window<"u"?window.location.href:"https://localhost"),g=r.pathname.toLowerCase();return g.includes("checkcaptcha")||g.includes("captcha")?`CAPTCHA(${r.host}${g})`:g.includes("risk")||g.includes("challenge")?`RISK(${r.host}${g})`:g.includes("smart/buttons")?`smart-buttons(${r.host})`:`${r.host}${g}`.slice(0,100)}catch{return y.slice(0,80)}},Me=y=>{let r=y.getAttribute("src"),g=y.getAttribute("srcdoc"),O=y.getAttribute("name"),f=y.getAttribute("sandbox"),Y=[];return r&&Y.push(`src=${Nt(r)}`),g&&Y.push(`srcdoc[${g.length}ch]`),!r&&!g&&Y.push("src=(empty) srcdoc=(empty)"),O&&Y.push(`name=${O.slice(0,40)}`),f!==null&&Y.push(`sandbox="${f.slice(0,40)}"`),Y.join(" ")},Ut=y=>{if(!(y instanceof HTMLIFrameElement))return"";try{let r=y.contentDocument;if(!r)return"cd=null";let g=r.body?.children.length??0,O=r.body?.innerHTML.length??0,f=r.head?.innerHTML.length??0;return`cd=same-origin readyState=${r.readyState} body[${g}children,${O}ch] head[${f}ch]`}catch(r){return`cd=cross-origin(${r.message.slice(0,30)})`}},yt=[],Pn=y=>{if(Le())return;let r=y.message??String(y.error??"(no message)");r&&(r.toLowerCase().includes("paypal")||r.toLowerCase().includes("zoid")||r.toLowerCase().includes("postrobot")||r.toLowerCase().includes("storage"))&&(z(`window:error ${r.slice(0,140)}`),yt.push(r))},Hn=y=>{if(Le())return;let r=y.reason instanceof Error?y.reason.message:String(y.reason??"(no reason)");r&&(r.toLowerCase().includes("paypal")||r.toLowerCase().includes("zoid")||r.toLowerCase().includes("postrobot")||r.toLowerCase().includes("storage"))&&(z(`window:rejection ${r.slice(0,140)}`),yt.push(r))};q&&typeof window<"u"&&(window.addEventListener("error",Pn),window.addEventListener("unhandledrejection",Hn));let $t={value:0};if(q&&typeof PerformanceObserver<"u")try{an=new PerformanceObserver(y=>{if(!Le())for(let r of y.getEntries()){if(!r.name.toLowerCase().includes("paypal"))continue;$t.value+=1;let g=Math.round(r.duration);z(`net ${g}ms ${r.name.slice(0,90)}`)}}),an.observe({type:"resource",buffered:!0})}catch{}let qt=()=>{for(en?.disconnect(),en=null,an?.disconnect(),an=null;Ht.length;)clearTimeout(Ht.pop());q&&typeof window<"u"&&(window.removeEventListener("error",Pn),window.removeEventListener("unhandledrejection",Hn))},Lt=y=>{if(!y)return!1;let r=y.toLowerCase();return r.includes("zoid destroyed")||r.includes("destroyed all components")||r.includes("window closed")||r.includes("detected container element removed")},On=y=>{if(Le()||Lt(y))return;let r=Un(y)??y;Ge(()=>Ke.current?.(r))},Nn=y=>{Ft||(Ue(!0),y.includes("paypal_ineligible")||K.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",y))},tn=(y,r=!1)=>{if(Ft)return;let g=k.current||!I;if(zn)return;zn=!0,Ln=!0,qt(),at();let O=r||Ga(y);if(O&&I&&!k.current){k.current=!0,se(!1),B(!1),De(!0),Qe.current?.("retrying"),In=setTimeout(()=>{Ft||je(f=>f+1)},ms);return}if(O||g){if(se(!1),B(!1),De(!1),Ue(!0),Qe.current?.("exhausted"),!de.current){de.current=!0;let f=Ga(y)?"paypal_init_timeout":r?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",f)}return}Nn(y)};Ue(!1);let Wt=async(y,r=Te.current)=>{if(Le())return;let g=r?.sessionId??e;if(ee.current){await ee.current(y,{sessionId:g,accountPatch:r?.accountPatch,nonce:r?.nonce});return}let O=K.startTiming();K.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let f=()=>{K.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),K.performance({stage:"processing",durationMs:K.elapsed(O),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Y=M.current,ze=r?.accountPatch?.email??we.current,tt=r?.accountPatch?.userId??Y?.customer?.id??Y?.accountData?.userId??"",G=await new co.PaymentAPI(fe,{telemetry:!1}).processPayment(tt,{sessionId:g,nonce:r?.nonce??Xe.current,tokenizedData:y,accountData:{userId:tt,email:ze??Y?.customer?.email??"",firstName:r?.accountPatch?.firstName??Y?.customer?.firstName??Y?.accountData?.firstName??"",lastName:r?.accountPatch?.lastName??Y?.customer?.lastName??Y?.accountData?.lastName??"",country:r?.accountPatch?.country??Y?.customer?.country??Y?.accountData?.country??void 0,zip:r?.accountPatch?.zip??Y?.customer?.zip??Y?.accountData?.zip??void 0}});if(G.ok){if(Ln||Ft&&Rn.current)return;f(),K.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ge(()=>rt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Le())return;let m=await G.json().catch(()=>null),V=m?.message??"PayPal payment failed.",be=Un(V)??V;f(),G.status===400&&(typeof m?.declineCode=="string"||!Array.isArray(m?.fields))?K.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):G.status===400||G.status===422?K.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):K.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:G.status>=500?"5xx":G.status>=400?"4xx":G.status>=300?"3xx":"unknown",failureCategory:G.status>=500?"server_error":void 0}),On(be),Ge(()=>mt.current?.(Rt("paypal",be,{code:m?.code,declineCode:m?.declineCode})));return}catch(Y){if(Le())return;f(),K.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let ze=Y instanceof Error?Y.message:"PayPal payment failed.",tt=Un(ze)??ze;On(tt),Ge(()=>mt.current?.(Rt("paypal",tt)));return}},nn=()=>new Bn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),qe=y=>Le()?Promise.reject(nn()):Promise.resolve(y),A=async y=>{if(Le())throw nn();Ye||En();let r=Te.current,g=r?.sessionId??e,O=r?.nonce??Xe.current;K.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let f=await new co.PaymentAPI(fe,{telemetry:!1}).createSessionIntent(g,O??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:lt});if(Le())throw nn();if(f.provider!=="paypal")throw new Error(y);return K.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),f.providerObjectId},j=(y,r)=>{let g=r?.nonce??Xe.current;if(!g)return;let O=r?.sessionId??e,f=fr(y)??An(y)??"provider_declined";new co.PaymentAPI(fe,{telemetry:!1}).reportSessionIntentDecline(O,g,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:f}).catch(()=>{})},F=le;z("loadScript:scheduled (deferred 1 tick)");let ke=null,Re=setTimeout(()=>{if(Ft){z("loadScript:skipped (cancelled before defer ran)");return}z("loadScript:start");let y=ae==="live"?"production":ae;ke=(0,Ja.loadScript)({clientId:a,currency:p,intent:d?"subscription":"capture",vault:d?!0:void 0,...y?{environment:y}:{},...y==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),ke.then(r=>{if(z(`loadScript:resolved inactive=${Le()} ns=${!!r} buttons=${!!r?.Buttons}`),Le())return;if(!r?.Buttons){z("FAIL: namespace missing Buttons factory"),tn("PayPal SDK did not expose the Buttons factory.");return}K.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),K.performance({stage:"provider_ready",durationMs:K.elapsed(re.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),K.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let g=async te=>{if(Le()||Oe.current!==F)return;let G=te.subscriptionID??te.orderID??"",m=G?et.current.get(G):ot.current.get(F);if(!(!m||!Qt(m.generation))&&Mt(m.generation)){et.current.delete(G),ot.current.delete(m.surfaceKey),on();try{if(B(!0),Ge(()=>Ke.current?.(null)),!G)throw new Bn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Wt({id:G,isPaypal:!0},m)}catch(V){On(V instanceof Error?V.message:"PayPal capture failed.")}finally{Le()||B(!1)}}},O=r.Buttons({style:{layout:"horizontal",height:uo,tagline:!1},onClick:async(te,G)=>{if(Le()){await G.reject();return}En();let m=Jt.current,V={};if(m)try{let Ae=await m("paypal");if(Le()){await G.reject();return}if(!Ae.proceed){Te.current=null,ot.current.delete(F),await G.reject();return}V={sessionId:Ae.sessionId,accountPatch:Ae.accountPatch,nonce:Ae.nonce}}catch(Ae){z(`onClick:runBeforeButtonClick rejected msg=${(Ae instanceof Error?Ae.message:String(Ae)).slice(0,120)}`),Te.current=null,ot.current.delete(F),await G.reject();return}Ge(()=>Je.current?.("paypal"));let Ie={generation:rr(),surfaceKey:F,...V};Te.current=Ie,ot.current.set(F,Ie),await G.resolve(),K.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),K.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),K.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Dt=K.startTiming()},createOrder:d?void 0:T?()=>qe(T).then(Ct):()=>A("Failed to create PayPal order.").then(Ct),createSubscription:d?T?()=>qe(T).then(Ct):()=>A("Failed to create PayPal subscription.").then(Ct):void 0,onApprove:g,onCancel:()=>{if(Le())return;let te=ot.current.get(F)??Te.current;te&&ot.current.delete(te.surfaceKey),Te.current=null,on(),K.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ue.current=!0,St({generation:te?.generation,remount:!0,focus:!1})},onError:te=>{if(Le()||Oe.current!==F)return;let G=te instanceof Error?te.message:"PayPal failed to render.";if(z(`onError rendered=${gt} msg=${G.slice(0,120)}`),gt){let m=ot.current.get(F)??Te.current;if(m&&!Qt(m.generation)||!m&&He.current===vt.current)return;if(Lt(G)){Mt(m?.generation);return}if(on(),Dr(te)){K.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),j(te,m),Ge(()=>mt.current?.(Rt("paypal",G))),m&&ot.current.delete(m.surfaceKey),Te.current=null,Mt(m?.generation);return}let V=G.toLowerCase();K.error({errorCode:V.includes("popup")&&V.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),m&&ot.current.delete(m.surfaceKey),Te.current=null,St({generation:m?.generation,remount:!0,showRetry:!0,focus:!0}),hn(te,{code:"paypal_runtime_failed"});return}tn(G)}}),f=O.isEligible();if(z(`isEligible=${f}`),K.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!f){se(!1),tn("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Kn=O,q&&z(`container:dims ${Ot(It)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),q&&typeof MutationObserver<"u"&&(en=new MutationObserver(te=>{if(!Le()){for(let G of te)if(G.type==="childList")G.addedNodes.forEach(m=>{if(!(m instanceof Element))return;let V=m.tagName.toLowerCase(),be=(m.getAttribute("title")??"").slice(0,40),Ie=V==="iframe"?` ${Me(m)}`:"";z(`child+ ${V}${be?` title="${be}"`:""}${Ie} dims=${Ot(m)}`)});else if(G.type==="attributes"&&G.target instanceof Element){let m=G.target;if(m.tagName.toLowerCase()!=="iframe")continue;let V=G.attributeName;(V==="src"||V==="srcdoc")&&z(`attr~ iframe ${V}=${V==="srcdoc"?`[${(m.getAttribute("srcdoc")??"").length}ch]`:Nt(m.getAttribute("src"))} dims=${Ot(m)}`)}}}),en.observe(It,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ze=te=>{if(Le()||gt)return;let G=It.querySelectorAll("iframe"),m=typeof document<"u"&&"hasStorageAccess"in document;z(`watchdog:${te} container=${Ot(It)} children=${It.childElementCount} iframes=${G.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${m} paypalNetRequests=${$t.value}`),G.forEach((V,be)=>{let Ie=(V.getAttribute("title")??"").slice(0,40);z(` iframe[${be}] ${Ot(V)}${Ie?` title="${Ie}"`:""} ${Me(V)}`);let Ae=Ut(V);Ae&&z(` ${Ae}`)}),yt.length===0&&z(" (no PayPal/zoid window errors captured)")};q&&(Ht.push(setTimeout(()=>ze("3s"),3e3)),Ht.push(setTimeout(()=>ze("8s"),8e3)),Ht.push(setTimeout(()=>ze("15s"),15e3))),z("render:start");let tt=K.startTiming();Ht.push(setTimeout(()=>{Le()||gt||(z("watchdog:11s retryable render timeout"),tn("PayPal Buttons render did not settle within 11000ms.",!0))},ys)),O.render(It).then(()=>{if(z(`render:resolved inactive=${Le()}`),qt(),Le()){at();return}gt=!0,se(!0),De(!1),Qe.current?.("ready"),K.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),K.performance({stage:"checkout_render",durationMs:K.elapsed(tt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(te=>{let G=te instanceof Error?te.message:"PayPal failed to render.";z(`render:rejected msg=${G.slice(0,120)}`),qt(),tn(G)})}).catch(r=>{let g=r instanceof Error?r.message:"PayPal SDK failed to load.";z(`loadScript:rejected msg=${g.slice(0,120)}`),tn(g)})},0);return()=>{Ft=!0,clearTimeout(Re),In&&clearTimeout(In),qt(),at()}},[I,fe,a,p,c,d,e,T,le,K]);let Vn=q?(0,un.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ve?"#fef2f2":"#f3f4f6",border:`1px solid ${Ve?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${pe} failed=${Ve})`,Ze.length===0?`
|
|
7
7
|
(waiting for first lifecycle event\u2026)`:`
|
|
8
|
-
${
|
|
9
|
-
`)}`]}):null;return
|
|
8
|
+
${Ze.join(`
|
|
9
|
+
`)}`]}):null;return Ve&&!ut?q?(0,un.jsx)("div",{children:Vn}):null:(0,un.jsxs)("div",{children:[Vn,(0,un.jsxs)("div",{"aria-hidden":Se?!0:void 0,style:Se?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:uo},children:[!pe&&!Se&&(0,un.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,un.jsx)("div",{ref:L,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:uo,display:"flex",opacity:pe?1:0},"aria-busy":ge||_},le)]},le),_e&&(0,un.jsx)("button",{ref:ye,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Kt,style:gs,children:"Try PayPal again"})]})}function Lr(e){return(0,un.jsx)(Xa,{...e})}function Qa(e){return(0,un.jsx)(Xa,{...e})}var zt=require("@flopay/shared"),l=require("react/jsx-runtime"),kn="flopay_stripe_resume",Za="flopay_wallet_resume",zr="flopay_paypal_resume",Ps=250,ei="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Yo(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function yo({billingApiUrl:e,sessionId:t,nonce:n,request:s}){if(!(!t||!n))try{await new pn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,s)}catch{}}function bs(e){return e instanceof zt.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ko(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function po(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let s=parseInt(n[1],16),a=Math.max(0,Math.min(1,1-t)),c=Math.round((s>>16&255)*a),p=Math.round((s>>8&255)*a),d=Math.round((s&255)*a);return`#${(1<<24|c<<16|p<<8|d).toString(16).slice(1)}`}var vs=`
|
|
10
10
|
.paypal-buttons { margin: 0 !important; vertical-align: top !important; }
|
|
11
11
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
12
12
|
@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
@@ -27,7 +27,7 @@ ${He.join(`
|
|
|
27
27
|
0% { opacity: 1; transform: translateX(0) scale(1); }
|
|
28
28
|
100% { opacity: 0; transform: translateX(16px) scale(0.97); }
|
|
29
29
|
}
|
|
30
|
-
`,no=44;function No(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var ls={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Xa={width:"100%",minHeight:no,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function cs(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Va(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Qa(e){return e==="paypal"?"PayPal":(0,R.getStripeMethodDisplayName)(e)}function ds(e,t){let n=`We couldn't open ${Qa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Za(e){let t=(0,r.useRef)(0),n=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useCallback)((p=l.current)=>{let v=p;v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),s=(0,r.useCallback)((p,v)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(p),p.timer=setTimeout(()=>{p.timer=null,l.current?.generation===p.generation&&(l.current=null,n.current=p.generation,e(p.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},v))},[o,e]),m=(0,r.useCallback)(p=>{p.yieldedControl&&s(p,600)},[s]),d=(0,r.useCallback)(p=>{o();let v=t.current+1;t.current=v,n.current=null;let x={generation:v,method:p,timer:null,yieldedControl:!1};return l.current=x,v},[o]),I=(0,r.useCallback)(p=>{let v=l.current;return typeof p=="number"&&v?.generation!==p?!1:(o(v),l.current=null,(typeof p!="number"||n.current===p)&&(n.current=null),!0)},[o]),N=(0,r.useCallback)(p=>{let v=l.current,x=p??v?.generation??t.current;(!p||v?.generation===p)&&(o(v),l.current=null),n.current=x},[o]),b=(0,r.useCallback)(p=>n.current===(p??t.current),[]),_=(0,r.useCallback)(p=>l.current?.generation===p&&n.current!==p,[]),k=(0,r.useCallback)(()=>{let p=l.current;p&&m(p)},[m]),F=(0,r.useCallback)(()=>{let p=l.current;p&&(p.yieldedControl=!0,o(p))},[o]);return(0,r.useEffect)(()=>{let p=()=>{document.visibilityState==="visible"?k():F()},v=()=>{F()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",v),window.addEventListener("focus",k),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",v),window.removeEventListener("focus",k),o()}},[o,F,k]),{startAttempt:d,finishAttempt:I,invalidateAttempt:N,isAttemptInvalidated:b,isAttemptCurrent:_}}function us(e){let t=(0,R.getPostalCodeExample)(e);return`Enter a valid ${(0,R.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function ps(e,t,n){let l=(0,R.isPostalCodeSupported)(e),o=t.trim(),s=n&&l,m=s&&!o,d=s&&!!o&&!(0,R.isValidPostalCode)(e,o);return{visible:n,supported:l,required:s,empty:m,malformed:d}}function Ka(e,t){return t instanceof Ut.FloPayError?t:new Ut.FloPayError(t instanceof Error?t.message:`${cs(e)} before-click hook failed.`,"validation_error")}function Fo(){return(0,i.jsx)("style",{children:ss})}function ms(e){return typeof e=="number"?`${e}px`:e}function Ha(e){if(typeof e=="number"||typeof e=="string")return e}function ei(e,t){let n=e.availablePaymentMethods;return n&&t.some(l=>n[l])?"ready":"unavailable"}function ti({state:e,placeholderTestId:t,borderRadius:n=8,children:l}){return e==="unavailable"||e==="load_error"?null:(0,i.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,i.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,i.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:l})]})}function Wa(e){return e!=="unavailable"&&e!=="load_error"}function oo(e){return(0,i.jsx)(fs,{...e})}function Ya({sessionId:e,nonce:t,email:n,billingApiUrl:l,onTokenizedBody:o,onErrorChange:s,isProcessing:m=!1,onButtonClick:d,onDecline:I,onTechnicalFailure:N,runBeforeButtonClick:b,onLoadStateChange:_,placeholderBorderRadius:k}){let F=un(),p=(0,lt.useStripe)(),v=(0,lt.useElements)(),[x,M]=(0,r.useState)("loading");(0,r.useEffect)(()=>{_?.(x)},[x,_]);let[g,he]=(0,r.useState)(!1),z=(0,r.useRef)(!1),ue=(0,r.useRef)(null),ae=(0,r.useRef)(null),[U,te]=(0,r.useState)(0),[Q,pe]=(0,r.useState)(!1),W=(0,r.useRef)(!1),J=(0,r.useRef)(new Map),{startAttempt:me,finishAttempt:Me,invalidateAttempt:we,isAttemptInvalidated:be,isAttemptCurrent:ie}=Za((Z,T,ce)=>{N?.(Z,T,{...ce,popupBlocked:ce?.popupBlocked??zn(T)}),pe(!0),te(Oe=>Oe+1)});(0,r.useEffect)(()=>{Q&&ae.current?.focus()},[Q,U]);let Ce=(0,r.useCallback)(()=>{te(Z=>Z+1)},[]),Be=(0,r.useCallback)((Z,T,ce)=>{we(ce),N?.("paypal",Z,{code:T,popupBlocked:zn(Z)}),pe(!0),Ce()},[we,N,Ce]),se=(0,r.useCallback)(()=>{window.setTimeout(()=>{(ue.current?.querySelector("iframe")??ue.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{W.current&&(W.current=!1,se())},[se,U]);let Ee=(0,r.useCallback)(()=>{pe(!1),s?.(null),se()},[se,s]);(0,r.useEffect)(()=>{if(!p||z.current)return;let Z=new URLSearchParams(window.location.search),T=Z.get("payment_intent"),ce=Z.get("payment_intent_client_secret"),Oe=Z.get("redirect_status");if(!T||!ce)return;z.current=!0;let ze;try{let E=localStorage.getItem(_r);if(E){let re=JSON.parse(E);re.clientSecret===ce&&(ze={...re.accountPatch?{accountPatch:re.accountPatch}:{},...re.sessionId?{sessionId:re.sessionId}:{},...re.nonce?{nonce:re.nonce}:{}})}}catch{}try{localStorage.removeItem(_r)}catch{}let ye=new URL(window.location.href);ye.searchParams.delete("payment_intent"),ye.searchParams.delete("payment_intent_client_secret"),ye.searchParams.delete("redirect_status"),window.history.replaceState({},"",ye.toString()),(async()=>{try{if(he(!0),Oe==="failed"){let oe="PayPal payment was declined. Please try again.";s?.(oe),I?.(wt("paypal",oe));return}let{paymentIntent:E,error:re}=await p.retrievePaymentIntent(ce);if(re){s?.(re.message??"Failed to retrieve PayPal payment status.");return}if(E&&(E.status==="requires_capture"||E.status==="succeeded")){let oe=typeof E.payment_method=="string"?E.payment_method:E.payment_method?.id;o({id:oe??E.id,type:"card",threeDSecureActionResultTokenId:E.id,isPaypal:!0},ze)}else{let oe="PayPal payment was not completed. Please try again.";s?.(oe),I?.(wt("paypal",oe))}}catch(E){s?.(E instanceof Error?E.message:"Failed to complete PayPal payment.")}finally{he(!1)}})()},[p,o,s,I]);let _e=(0,r.useCallback)(async Z=>{if(m||g){Z.reject();return}let T=b?await b("paypal"):{proceed:!0};if(!T.proceed){J.current.delete(U),Z.reject();return}let ce=me("paypal");J.current.set(U,{generation:ce,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),pe(!1),d?.("paypal"),Z.resolve()},[J,m,d,b,me,g,U]),Re=(0,r.useCallback)(async Z=>{if(!p||!v)return;let T=J.current.get(U);if(T&&!ie(T.generation)){J.current.delete(U);return}if(!T&&be()||T&&!Me(T.generation))return;T||Me();let ce=T??null;if(J.current.delete(U),!ce&&b){let E=await b("paypal");if(!E.proceed){Z.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ce={accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}}let Oe=ce?.sessionId??e,ze=ce?.nonce??t,ye=ce?.accountPatch?.email??n;try{if(he(!0),s?.(null),!Oe||!ye)throw new Error("Missing sessionId or email for PayPal payment");let E=p.createPaymentMethod,{error:re,paymentMethod:oe}=await E({type:"paypal"});if(re){Be(re,"stripe_paypal_create_payment_method_failed",T?.generation),Z.paymentFailed({reason:"fail"});return}let $e=await new mn.PaymentAPI(l).createSessionIntent(Oe,ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:oe?.id??null,intentKind:"payment"});if($e.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ct=$e.clientSecret,He={return_url:window.location.href};if(oe?.id&&(He.payment_method=oe.id),typeof window<"u")try{localStorage.setItem(_r,JSON.stringify({clientSecret:ct,sessionId:Oe,nonce:ze,accountPatch:ce?.accountPatch}))}catch{}let{error:ot,paymentIntent:V}=await p.confirmPayment({clientSecret:ct,confirmParams:He,redirect:"if_required"});if(ot){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}if(Ir(ot)){let tt=ot.message??"Your payment was declined.";s?.(tt),I?.(wt("paypal",tt,{code:xn(ot),declineCode:lr(ot)})),await ro({billingApiUrl:l,sessionId:Oe,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:xn(ot)??"provider_declined"}})}else Be(ot,"stripe_paypal_confirm_failed",T?.generation);return}if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let G=typeof V?.payment_method=="string"?V.payment_method:V?.payment_method?.id;o({id:G??V?.id,type:"card",threeDSecureActionResultTokenId:V?.id,isPaypal:!0},{accountPatch:ce?.accountPatch,sessionId:Oe,nonce:ze});return}catch(E){Be(E,"stripe_paypal_failed",T?.generation)}finally{he(!1)}},[p,v,e,t,n,l,o,s,I,b,Be,Me,ie,be,U]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(ti,{state:x,placeholderTestId:"flopay-paypal-placeholder",borderRadius:k,children:(0,i.jsxs)("div",{ref:ue,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Q&&(0,i.jsx)("button",{ref:ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ee,style:Xa,children:"Try PayPal again"}),(0,i.jsx)(lt.ExpressCheckoutElement,{onReady:Z=>M(ei(Z,["paypal"])),onLoadError:()=>{M("load_error"),Lo(Mt(F),"paypal","paypal")},onClick:_e,onConfirm:Re,onCancel:()=>{let Z=J.current.get(U);J.current.delete(U),Mt(F)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we(Z?.generation),pe(!1),W.current=!0,Ce()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},U)]})}),g&&(0,i.jsx)(Sn,{status:"processing"})]})}function Ga({sessionId:e,nonce:t,email:n,billingApiUrl:l,intentKind:o,expressMethods:s,onTokenizedBody:m,onErrorChange:d,onButtonClick:I,onDecline:N,onTechnicalFailure:b,runBeforeButtonClick:_,onLoadStateChange:k,placeholderBorderRadius:F}){let p=un(),v=(0,lt.useStripe)(),x=(0,lt.useElements)(),[M,g]=(0,r.useState)("loading");(0,r.useEffect)(()=>{k?.(M)},[M,k]);let[he,z]=(0,r.useState)(!1),ue=(0,r.useRef)(null),ae=(0,r.useRef)(null),[U,te]=(0,r.useState)(0),[Q,pe]=(0,r.useState)(!1),[W,J]=(0,r.useState)("google_pay"),me=(0,r.useRef)(!1),Me=(0,r.useRef)("google_pay"),we=(0,r.useRef)("google_pay"),be=(0,r.useRef)(new Map),{startAttempt:ie,finishAttempt:Ce,invalidateAttempt:Be,isAttemptInvalidated:se,isAttemptCurrent:Ee}=Za((ye,E,re)=>{b?.(ye,E,{...re,popupBlocked:re?.popupBlocked??zn(E)}),J(ye),pe(!0),te(oe=>oe+1)});(0,r.useEffect)(()=>{Q&&ae.current?.focus()},[Q,U]);let _e=(0,r.useCallback)(()=>{te(ye=>ye+1)},[]),Re=(0,r.useCallback)((ye,E,re,oe)=>{Be(oe),b?.(ye,E,{code:re,popupBlocked:zn(E)}),J(ye),pe(!0),_e()},[Be,b,_e]),Z=(0,r.useCallback)(()=>{window.setTimeout(()=>{(ue.current?.querySelector("iframe")??ue.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{me.current&&(me.current=!1,Z())},[Z,U]);let T=(0,r.useCallback)(()=>{pe(!1),d?.(null),Z()},[Z,d]),ce=(0,r.useCallback)(async ye=>{if(!v||!x)return;let E=be.current.get(U);if(E&&!Ee(E.generation)){be.current.delete(U);return}if(!E&&se()||E&&!Ce(E.generation))return;E||Ce();let re=ye.expressPaymentType??E?.method??Me.current,oe=E??null;be.current.delete(U);let $e=Va(re);if(!oe&&_){let G=await _($e);if(!G.proceed){ye.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}oe={accountPatch:G.accountPatch,sessionId:G.sessionId,nonce:G.nonce}}let ct=$e,He=oe?.sessionId??e,ot=oe?.nonce??t,V=oe?.accountPatch?.email??n;try{z(!0),d?.(null);let{error:G}=await x.submit();if(G){Re(re,G,"stripe_wallet_submit_failed",E?.generation);return}let{error:tt,paymentMethod:Ae}=await v.createPaymentMethod({elements:x});if(tt||!Ae){Re(re,tt??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",E?.generation);return}if(!He||!V)throw new Error("Missing sessionId or email for wallet payment");let at=await new mn.PaymentAPI(l).createSessionIntent(He,ot??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:re??$e,paymentMethodId:Ae.id,intentKind:o});if(at.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Ge=at.clientSecret,{error:We,intentId:rn}=(0,Ut.isSetupIntentClientSecret)(Ge)?await v.confirmCardSetup(Ge,{payment_method:Ae.id}).then(h=>({error:h.error,intentId:h.setupIntent?.id})):await v.confirmCardPayment(Ge,{payment_method:Ae.id}).then(h=>({error:h.error,intentId:h.paymentIntent?.id}));if(We){if(Ir(We)){let h=We.message??"Your payment was declined.";d?.(h),N?.(wt(ct,h,{code:xn(We),declineCode:lr(We)})),await ro({billingApiUrl:l,sessionId:He,nonce:ot,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:re??$e,providerDeclineReason:xn(We)??"provider_declined"}})}else Re(re,We,"stripe_wallet_confirm_failed",E?.generation);return}m({id:Ae.id,type:"card",threeDSecureActionResultTokenId:rn},{accountPatch:oe?.accountPatch,sessionId:He,nonce:ot})}catch(G){Re(re,G,"stripe_wallet_failed",E?.generation)}finally{z(!1)}},[v,x,e,t,n,l,o,m,d,N,_,Re,Ce,Ee,se,U]),Oe=(0,r.useMemo)(()=>{let ye=["applePay","googlePay","paypal","link","amazonPay","klarna"],E=new Set(["applePay","googlePay"]),re=new Set(s.map(R.stripeExpressMethodToOptionKey)),oe={};for(let $e of ye)re.has($e)?oe[$e]=E.has($e)?"always":"auto":oe[$e]="never";return oe},[s]),ze=(0,r.useMemo)(()=>s.map(R.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(ti,{state:M,placeholderTestId:"flopay-wallet-placeholder",borderRadius:F,children:(0,i.jsxs)("div",{ref:ue,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Q&&(0,i.jsxs)("button",{ref:ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:T,style:Xa,children:["Try ",Qa(W)," again"]}),(0,i.jsx)(lt.ExpressCheckoutElement,{onReady:ye=>{g(ei(ye,ze))},onLoadError:ye=>{g("load_error"),Lo(Mt(p),"stripe","wallet")},onClick:async ye=>{Me.current=ye.expressPaymentType,we.current=Va(ye.expressPaymentType);let E=_?await _(we.current):{proceed:!0};if(!E.proceed){be.current.delete(U),ye.reject();return}let re=ie(ye.expressPaymentType);be.current.set(U,{generation:re,method:ye.expressPaymentType,accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}),pe(!1),I?.(we.current),ye.resolve()},onConfirm:ce,onCancel:()=>{let ye=be.current.get(U);be.current.delete(U),Mt(p)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Be(ye?.generation),pe(!1),me.current=!0,_e()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Oe,layout:{maxColumns:1,overflow:"never"}}},U)]})}),he&&(0,i.jsx)(Sn,{status:"processing"})]})}function ys({method:e,themeId:t,submitting:n=!1,disabled:l=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:m,backgroundColor:d,borderColor:I,textColor:N,borderRadius:b,fontFamily:_}){let k=(0,R.resolveStripeMethodBrandVariant)(e,t),F=_a[e],p=k?.backgroundColor??d??"#ffffff",v=k?.borderColor??I??"#d1d5db",x=k?.textColor??N??"#262833";return(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!l&&m()},disabled:n||l,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:no,padding:"0 1rem",backgroundColor:p,color:x,border:`1px solid ${v}`,borderRadius:b??8,fontSize:"0.95rem",fontWeight:600,fontFamily:_,cursor:n||l?"not-allowed":"pointer",opacity:l&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,i.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,R.getStripeMethodDisplayName)(e)}\u2026`}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,R.hasVendoredStripeMethodLogo)(e)?8:0},children:[F?(0,i.jsx)("img",{src:F,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):k?.logoSvg?(0,i.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:k.logoSvg}}):null,(0,i.jsx)("span",{children:(0,R.getStripeMethodDisplayName)(e)})]}),s&&(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:x,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,i.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Do({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:m,onErrorChange:d,onDecline:I,onCancel:N,runBeforeButtonClick:b,onButtonClick:_,isProcessing:k,submitButtonColor:F,submitButtonBorderRadius:p,submitButtonStyle:v,errorText:x}){let M=un(),g=(0,lt.useStripe)(),he=(0,lt.useElements)(),[z,ue]=(0,r.useState)(!1),ae=(0,r.useRef)(!1),[U,te]=(0,r.useState)(!1),[Q,pe]=(0,r.useState)("loading"),W=(0,r.useCallback)(async()=>{if(!g||!he||k||ae.current||!U)return;ae.current=!0,ue(!0);let J=b?await b("card"):{proceed:!0};if(!J.proceed){ae.current=!1,ue(!1);return}_?.("card");let me=J.sessionId??t,Me=J.nonce??n,we=J.accountPatch?.email??l;try{d?.(null);let be=await he.submit();if(be.error){d?.(be.error.message??"Payment failed.");return}let ie=await g.createPaymentMethod({elements:he});if(ie.error||!ie.paymentMethod){d?.(ie.error?.message??"Failed to create payment method.");return}let Ce=ie.paymentMethod;if(!me||!we)throw new Error("Missing sessionId or email for payment.");let Be=Ce.type||e,se=await new mn.PaymentAPI(s).createSessionIntent(me,Me??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Be,paymentMethodId:null,intentKind:"payment"});if(se.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ee=se.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Ee,sessionId:me,nonce:Me,accountPatch:J.accountPatch,paymentMethodId:Ce.id,paymentMethodType:Ce.type??e,gateway:"stripe"}))}catch{}let{error:_e,paymentIntent:Re}=await g.confirmPayment({clientSecret:Ee,confirmParams:{return_url:window.location.href,payment_method:Ce.id},redirect:"if_required"});if(_e){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ce=_e.message??"Payment failed.";d?.(ce),I?.(wt("card",ce,{code:_e.code})),await ro({billingApiUrl:s,sessionId:me,nonce:Me,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:_e.code??"provider_declined"}});return}let Z=Re?.status;if(!Jr(Z)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ce=Z==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(ce),I?.(wt("card",ce,{code:Z??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let T=typeof Re?.payment_method=="string"?Re.payment_method:Re?.payment_method?.id;m({id:T??Ce.id,type:"card",threeDSecureActionResultTokenId:Re?.id,gateway:"stripe",paymentMethodType:Ce.type??e},{accountPatch:J.accountPatch,sessionId:me,nonce:Me})}catch(be){d?.(be instanceof Error?be.message:"Payment failed. Please try again.")}finally{ae.current=!1,ue(!1)}},[g,he,k,U,b,_,t,n,l,s,e,m,d,I]);return(0,i.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,i.jsx)(lt.PaymentElement,{onReady:()=>pe("ready"),onLoadError:()=>{pe("load_error"),Lo(Mt(M),"stripe","apm")},onChange:J=>{te(!!J.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...l?{email:l}:{}}}}}),(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{W()},disabled:!U||z||k||Q!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:F,color:"white",border:"none",borderRadius:p,fontSize:"1rem",fontWeight:600,cursor:!U||z||k||Q!=="ready"?"not-allowed":"pointer",opacity:!U||z||k||Q!=="ready"?.5:1,transition:"opacity 120ms ease-out",...v??{}},children:z?"Processing\u2026":`Pay with ${(0,R.getStripeMethodDisplayName)(e)}`}),x&&(0,i.jsx)(ar,{margin:"0.75rem 0 0",children:x})]})}function Ja({sessionId:e,nonce:t,email:n,billingName:l,billingApiUrl:o,paymentElementMethods:s,stripeInstance:m,paymentElementBaseOptions:d,onTokenizedBody:I,onErrorChange:N,onButtonClick:b,onDecline:_,runBeforeButtonClick:k,onLoadStateChange:F,isProcessing:p=!1,submitButtonColor:v="#4A49FF",submitButtonBorderRadius:x=8,submitButtonStyle:M,buttonAppearance:g,themeId:he,onExpandApm:z,expandedApmMethod:ue}){let[ae,U]=(0,r.useState)(null),[te,Q]=(0,r.useState)(null),pe=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&m?F?.("ready"):m||F?.("loading")},[s.length,m,F]);let W=(0,r.useCallback)(async ie=>{if(!m||pe.current||p)return;pe.current=!0,Q(ie);let Ce=k?await k("card"):{proceed:!0};if(!Ce.proceed){pe.current=!1,Q(null);return}b?.("card");let Be=Ce.sessionId??e,se=Ce.nonce??t,Ee=Ce.accountPatch?.email??n;try{if(N?.(null),!Be||!Ee)throw new Error("Missing sessionId or email for payment.");let _e=await new mn.PaymentAPI(o).createSessionIntent(Be,se??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ie,paymentMethodId:null,intentKind:"payment"});if(_e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Re=_e.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Re,sessionId:Be,nonce:se,accountPatch:Ce.accountPatch,paymentMethodType:ie,gateway:"stripe"}))}catch{}let{error:Z,paymentIntent:T}=await m.confirmPayment({clientSecret:Re,confirmParams:{return_url:window.location.href,payment_method_data:{type:ie,billing_details:{name:l&&l.trim().length>=3?l.trim():"FloPay Customer",...Ee?{email:Ee}:{}}}},redirect:"if_required"});if(Z){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=Z.message??"Payment failed.";N?.(ze),_?.(wt("card",ze,{code:Z.code})),await ro({billingApiUrl:o,sessionId:Be,nonce:se,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ie,providerDeclineReason:Z.code??"provider_declined"}});return}let ce=T?.status;if(!Jr(ce)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=ce==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";N?.(ze),_?.(wt("card",ze,{code:ce??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let Oe=typeof T?.payment_method=="string"?T.payment_method:T?.payment_method?.id;I({id:Oe??T?.id,type:"card",threeDSecureActionResultTokenId:T?.id,gateway:"stripe",paymentMethodType:ie},{accountPatch:Ce.accountPatch,sessionId:Be,nonce:se})}catch(_e){N?.(_e instanceof Error?_e.message:"Payment failed. Please try again.")}finally{pe.current=!1,Q(null)}},[m,p,k,b,e,t,n,o,l,I,N,_]),[J,me]=(0,r.useState)(null),Me=z?ue??null:J,we=(0,r.useCallback)(ie=>{pe.current||p||Me&&Me!==ie||((0,R.needsStripeMethodExplicitConfirm)(ie)?z?z(ie):me(ie):W(ie))},[Me,p,W,z]),be=(0,r.useMemo)(()=>J?{...d,paymentMethodTypes:[J]}:null,[J,d]);return(0,i.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(ie=>{let Ce=ue===ie,Be=te===ie,se=te!==null&&te!==ie||ue!=null&&ue!==ie;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(ys,{method:ie,themeId:he,submitting:Be,disabled:se,highlighted:Ce,hasNextStep:(0,R.needsStripeMethodExplicitConfirm)(ie),onClick:()=>we(ie),backgroundColor:g?.backgroundColor,borderColor:g?.borderColor,textColor:g?.textColor,borderRadius:g?.borderRadius,fontFamily:g?.fontFamily}),!z&&J===ie&&be&&m&&(0,i.jsx)(lt.Elements,{stripe:m,options:be,children:(0,i.jsx)(Do,{method:ie,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:I,onErrorChange:N,onDecline:_,onCancel:()=>me(null),runBeforeButtonClick:k,onButtonClick:b,isProcessing:p,submitButtonColor:v,submitButtonBorderRadius:x,submitButtonStyle:M})},ie)]},ie)})})}function fs({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:m,onDecline:d,onTokenizedBody:I,firstName:N,lastName:b,chv:_,className:k,isProcessing:F,error:p,onErrorChange:v,showPayPal:x=!0,showStripe:M=!0,enabledPaymentMethods:g,enabledPaymentMethodCountries:he,showApplePay:z=!0,showGooglePay:ue=!0,layout:ae="default",theme:U,buttonsTheme:te,buttonsStyles:Q,appearance:pe,cardButtonContent:W,cardBackButtonContent:J,cardTitleContent:me,showSecurityFooter:Me,onButtonClick:we,onBeforeButtonClick:be,enableAVS:ie,cardFieldOrder:Ce,cardPreFormSlot:Be,avsLayout:se="row",country:Ee,zip:_e,addressLine1:Re,addressLine2:Z,city:T,state:ce,onCountryChange:Oe,onZipChange:ze,avsCheck:ye,checkoutType:E,checkoutLayout:re,totalAmount:oe=0,currency:$e="usd",initialCardOpen:ct=!1,directPaypal:He,isSubscription:ot=!1,session:V,dataAttachmentPending:G=!1,debug:tt=!1}){let Ae=un(),at=Wr(),Ge=(0,r.useContext)(dn),We=G||Ge.claimPending===!0,rn=Gr(),[h,ke]=(0,r.useState)(!1),[dt,nt]=(0,r.useState)(null),[Qe,Ye]=(0,r.useState)(Ee??"US"),[Ze,xe]=(0,r.useState)(_e??""),[Ke,kt]=(0,r.useState)(Re??""),[Je,An]=(0,r.useState)(Z??""),[Pt,Fn]=(0,r.useState)(T??""),[on,hn]=(0,r.useState)(ce??""),[Zt,Dn]=(0,r.useState)({}),Nt=(0,r.useRef)(_e??""),Rt=(0,r.useRef)(Ee??"US"),qt=(0,r.useRef)(Re??""),Gt=(0,r.useRef)(Z??""),Bt=(0,r.useRef)(T??""),jt=(0,r.useRef)(ce??""),At=(0,r.useRef)({});(0,r.useEffect)(()=>{let a=(C,H,ne,j,ve)=>{if(At.current[C])return;let Ne=H?.trim();!Ne||Ne===ne.current||(ne.current=Ne,j(Ne),ve?.(Ne))};a("country",Ee,Rt,Ye,Oe),a("zip",_e,Nt,xe,ze),a("addressLine1",Re,qt,kt),a("addressLine2",Z,Gt,An),a("city",T,Bt,Fn),a("state",ce,jt,hn)},[Ee,_e,Re,Z,T,ce,Oe,ze]);let le=(0,r.useMemo)(()=>(0,R.resolveAVSConfig)(ie),[ie]),en=le!==null,D=!!V?.vault?.html,gt=!!V?.gateways?.pcivault,bt=!!(V?.gateways?.stripe?.enabledPaymentMethods??g)?.includes("card"),Te=D||bt||gt,qe=!!(M&&Te&&Ae&&e),[$n,Ln]=(0,r.useState)(()=>ae!=="buttons"||ct?e??null:null),[qn,Zn]=(0,r.useState)(0),Vt=ae!=="buttons"||ct||!!e&&$n===e,it=(0,r.useMemo)(()=>!Ae||!qe||!e||!Vt?null:Ae.cardCapture({sessionId:e}),[Ae,qe,e,Vt]),Ft=(0,r.useMemo)(()=>{let a=Qe,C=le?(0,R.isAVSFieldVisible)(le.postal_code,a):!1;return ps(a,Ze,C)},[le,Qe,Ze]),{avsInvalid:Kt,invalidAvsFields:ht}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!qe||!le)return{avsInvalid:!1,invalidAvsFields:a};let C=Qe,H=(ve,Ne)=>(0,R.isAVSFieldVisible)(ve,C)&&!Ne.trim(),ne={line1:H(le.address_line_1,Ke),city:H(le.city,Pt),state:H(le.state,on),zip:Ft.empty||Ft.malformed};return{avsInvalid:ne.line1||ne.city||ne.state||ne.zip,invalidAvsFields:ne}},[qe,le,Qe,Ke,Pt,on,Ft]),[Jt,Ht]=(0,r.useState)(!1),[an,Pn]=(0,r.useState)(!1),[It,Ot]=(0,r.useState)(()=>Ao(V?.vault)),[Le,vt]=(0,r.useState)(ct&&Te?"card":"buttons"),[Ct,bn]=(0,r.useState)(null),jn=Le==="expanding"||Le==="card",Wt=280,Xt=(0,r.useRef)(null),Dt=(0,r.useCallback)(a=>{Xt.current&&clearTimeout(Xt.current),Xt.current=setTimeout(()=>{Xt.current=null,a()},Wt)},[Wt]);(0,r.useEffect)(()=>()=>{Xt.current&&clearTimeout(Xt.current)},[]);let kn=(0,r.useCallback)(()=>{Ln(e??null),Zn(a=>a+1),vt("expanding"),Dt(()=>vt("card"))},[Dt,e]),Nn=(0,r.useCallback)(()=>{vt("collapsing"),Dt(()=>vt("buttons"))},[Dt]),sn=(0,r.useCallback)(a=>{bn(a),vt("apm-expanding"),Dt(()=>vt("apm-form"))},[Dt]),Qt=(0,r.useCallback)(()=>{vt("apm-collapsing"),Dt(()=>{vt("buttons"),bn(null)})},[Dt]);(0,r.useEffect)(()=>{ae==="buttons"&&ct&&Te&&(Ln(e??null),vt("card"))},[ae,ct,Te,e]);let[Et,P]=(0,r.useState)(null),Y=(0,r.useRef)(!1),K=(0,r.useRef)(null),fe=(0,r.useRef)("idle"),[X,de]=(0,r.useState)(null),S=(0,r.useRef)(X);(0,r.useEffect)(()=>{S.current=X},[X]);let u=n||rn,c=p??dt,L=(0,r.useMemo)(()=>(0,Ut.resolveTheme)(U),[U]),f=(0,r.useMemo)(()=>{let a=L?.buttonsLayout??(0,R.resolveButtonsLayoutTheme)(te);return Q?{...a,...Q,cardButton:{...a.cardButton,...Q.cardButton},cardFormContainer:{...a.cardFormContainer,...Q.cardFormContainer},backButton:{...a.backButton,...Q.backButton},backButtonIcon:{...a.backButtonIcon,...Q.backButtonIcon},submitButton:{...a.submitButton,...Q.submitButton},title:{...a.title,...Q.title}}:a},[L,te,Q]),ee=pe??L?.appearance,Ie=(0,r.useMemo)(()=>{let a=ee?.variables,C=Ne=>typeof Ne=="string"&&Ne?Ne:void 0,H=f.submitButton,ne=C(a?.colorPrimary)??C(H?.backgroundColor)??"#4A49FF",j=ae==="buttons",ve=f.nameInput;return{primaryColor:ne,primaryHoverColor:C(a?.colorPrimaryHover)??to(ne,.12),inputBackgroundColor:C(f.cardInputBackground)??C(a?.colorBackground)??"#ffffff",textColor:C(f.cardInputColor)??C(ve?.color)??C(a?.colorText)??"#262833",borderColor:C(f.cardInputBorder)??(j?"#e5e7eb":"#A4A4FF"),placeholderColor:C(f.cardInputPlaceholderColor)??"#9ca3af",errorColor:C(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:C(ve?.fontFamily)??C(a?.fontFamily)??"Poppins, sans-serif",fontSize:C(f.cardInputFontSize)??C(a?.fontSizeBase)??"16px",fontWeight:String(Ha(ve?.fontWeight)??400),borderRadius:C(a?.borderRadius)??"8px"}},[ee,f,ae]),rt=Ge.inlineSessionPatchProcessing??!1,Se=(F??h)||rt,O=u.replace(/\/+$/,""),y=(0,r.useMemo)(()=>To({userId:o,email:l,firstName:N,lastName:b,country:Ee,zip:_e},Zt),[o,l,N,b,Ee,_e,Zt]),$=[y.firstName,y.lastName].filter(a=>!!a?.trim()).join(" "),q=(0,r.useMemo)(()=>Ae?Ae.getRawProvider():null,[Ae]),Ve=(0,r.useMemo)(()=>at?at.getRawProvider():null,[at]),pt=oe||100,_t=(0,r.useMemo)(()=>ee?(0,mn.toStripeAppearance)(ee):null,[ee]),pr=_t?{appearance:_t}:null,Ar=(0,r.useMemo)(()=>{let a=_t??{},C=a.rules??{};return{...a,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[_t]),Yo=(0,r.useMemo)(()=>{let a=Da(oe);return{...a,currency:$e.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...pr}},[oe,$e,pr]),Go=(0,r.useMemo)(()=>({mode:"payment",amount:pt,currency:$e.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...pr}),[pt,$e,pr]),ge=(0,r.useCallback)(a=>{nt(a),v?.(a)},[v]);(0,r.useEffect)(()=>{!qe||!it||it.setCardFieldOrder?.(Ce??null,le==null)},[qe,it,Ce,le]),(0,r.useEffect)(()=>{(Le==="expanding"||Le==="collapsing"||Le==="apm-expanding"||Le==="apm-collapsing")&&ge(null)},[Le,ge]);let ln=(0,r.useCallback)((a,C,H)=>{d?.(wt(a,C,H))},[d]),er=(0,r.useCallback)((a,C,H)=>{let ne=H?.popupBlocked??zn(C),j=ds(a,ne),ve=Gn(H?.code)??xn(C)??"external_payment_method_failed",Ne=new Ut.FloPayError(j,"api_error",{code:"external_payment_method_failed",param:a});P(null),ae==="buttons"&&(vt("buttons"),bn(null)),ge(j),m?.(Ne),console.error("[FloPay] External payment method failed:",{method:a,code:ve,popupBlocked:ne})},[ae,m,ge]);(0,r.useEffect)(()=>{if(!qe||!e){Ot(null);return}let a=Ao(V?.vault);if(a){Ot(a);return}if(!Vt){Ot(null);return}Ot(null);let C=!0;return new mn.PaymentAPI(O).getVaultCapture(e,t).then(H=>{if(!C)return;let ne=Ao(H);ne?Ot(ne):ge("Failed to load the secure card form.")}).catch(H=>{C&&ge(H instanceof Error?H.message:"Failed to load the secure card form.")}),()=>{C=!1}},[qe,Vt,qn,e,V?.vault?.html,V?.vault?.messageToken,V?.vault?.expectedOrigin,O,t,ge]);let Rn=(0,r.useRef)({onComplete:s,onError:m,updateError:ge,emitDecline:ln,resolvedAccount:y,avsConfig:le,avsCheckProp:ye,sessionId:e,nonce:t,baseUrl:O});Rn.current={onComplete:s,onError:m,updateError:ge,emitDecline:ln,resolvedAccount:y,avsConfig:le,avsCheckProp:ye,sessionId:e,nonce:t,baseUrl:O};let fo=(0,r.useRef)(!1),bi=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:C,avsCheckProp:H}=Rn.current,ne=Rt.current||a.country||"US",j=C?(0,R.isAVSFieldVisible)(C.state,ne):!1,ve=C?(0,R.isAVSFieldVisible)(C.address_line_1,ne):!1,Ne=C?(0,R.isAVSFieldVisible)(C.postal_code,ne):!1,yt=C?(0,R.isAVSFieldVisible)(C.city,ne):!1,Lt=C?(0,R.isAVSFieldVisible)(C.address_line_2,ne):!1,Xe=ve&&!j&&Ne?(0,R.getStateFromPostalCode)(ne,(Nt.current??"").trim()):null,xt=j?jt.current:Xe;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Ne&&Nt.current?{zip:Nt.current}:{},...yt&&Bt.current?{city:Bt.current}:{},...xt?{state:xt}:{},...ve&&qt.current?{addressLine1:qt.current}:{},...Lt&&Gt.current?{addressLine2:Gt.current}:{},country:ne},...H!==void 0?{avsCheck:H}:{},...C?{avsConfig:{country:(0,R.isAVSFieldVisible)(C.country,ne),postal_code:Ne,address_line_1:ve,address_line_2:Lt,city:yt,state:j}}:{}}},[]),Jo=(0,r.useRef)(We);Jo.current=We,(0,r.useEffect)(()=>{We||c!==ja||Rn.current.updateError(null)},[We,c]),(0,r.useEffect)(()=>{!qe||!it||it.setSubmitGate?.(Kt||We)},[qe,it,Kt,We]),(0,r.useEffect)(()=>{if(!qe||!it)return;fo.current=!1;let a=!1,C=it.on("submitting",()=>{Ht(!0),K.current&&clearTimeout(K.current),fe.current="validation-window",K.current=setTimeout(()=>{K.current=null,fe.current==="validation-window"&&(fe.current="processing")},as),P("processing");let{baseUrl:Ne,sessionId:yt,nonce:Lt,updateError:Xe,onError:xt}=Rn.current;!yt||!Lt||new mn.PaymentAPI(Ne).patchAccountSnapshot(yt,Lt,bi(),{telemetryMode:"best_effort"}).catch(Fe=>{if(!is(Fe))return;let zt=Fe instanceof Error?Fe.message:"Please check your billing address and try again.";Xe(zt),fe.current="idle",P(null),xt?.(Fe instanceof Ut.FloPayError?Fe:new Ut.FloPayError(zt,"api_error"))})}),H=it.on("complete",async Ne=>{sr(Ne.sessionId??Rn.current.sessionId),fe.current="terminal",P("success"),await new Promise(yt=>setTimeout(yt,_n)),!fo.current&&(fo.current=!0,Rn.current.onComplete?.({status:"succeeded",paymentIntentId:Ne.intentId,checkoutMethod:"card"}))}),ne=it.on("decline",async Ne=>{let{updateError:yt,emitDecline:Lt}=Rn.current,Xe=Ne.message??"Your payment was declined. Please try another card or contact your bank.";fe.current="terminal",yt(Xe),P("error"),Lt("card",Xe,Ne.declineReason?{declineCode:Ne.declineReason}:void 0),await new Promise(xt=>setTimeout(xt,Cn)),!a&&(fe.current="idle",P(null))}),j=it.on("error",async Ne=>{let{updateError:yt,onError:Lt}=Rn.current,Xe=Ne.message??"There was a problem processing your payment. Please try again.";fe.current="terminal",yt(Xe),P("error"),Lt?.(new Ut.FloPayError(Xe,"api_error")),await new Promise(xt=>setTimeout(xt,Cn)),!a&&(fe.current="idle",P(null))}),ve=it.on("blocked",()=>{if(!Jo.current){Ht(!0);return}Rn.current.updateError(ja)});return()=>{a=!0,K.current&&(clearTimeout(K.current),K.current=null),fe.current="idle",C(),H(),ne(),j(),ve()}},[qe,it]);let vn=!!He?.clientId,mr=Array.isArray(g),Fr=mr&&g.length>0,vi=mr&&g.includes("paypal"),{expressMethods:Dr,paymentElementMethods:yr}=(0,r.useMemo)(()=>(0,R.partitionStripeMethods)(g,{excludePaypal:vn}),[g,vn]),Xo=vn||!!at,Ci=(0,r.useMemo)(()=>Xo?Dr.filter(a=>a!=="paypal"):Dr,[Dr,Xo]),Si=(0,r.useMemo)(()=>{let a=[];return z&&a.push("apple_pay"),ue&&a.push("google_pay"),a},[z,ue]),Lr=mr?Ci:Si,wi=M&&Lr.length>0,go=en?Qe:Ee,Nr=(0,r.useMemo)(()=>{let a=go?.trim().toUpperCase();return a?he?yr.filter(C=>{let H=he[C];return!H||H.length===0||H.includes(a)}):(0,R.filterStripeMethodsByCountry)(yr,go):yr},[yr,go,he]),ho=(0,r.useMemo)(()=>({mode:"payment",amount:pt,currency:$e.toLowerCase(),paymentMethodCreation:"manual",appearance:Ar}),[pt,$e,Ar]),[Qo,Zo]=(0,r.useState)("loading"),[ea,ta]=(0,r.useState)("loading"),[na,ra]=(0,r.useState)("loading"),[ki,Po]=(0,r.useState)(!1),[oa,bo]=(0,r.useState)("loading"),[Or,Ri]=(0,r.useState)();(0,r.useEffect)(()=>{Ri(La())},[]);let aa=x&&(vn||(mr?vi:Or===!1)),ia=M&&wi,fr=!We&&aa&&vn,sa=oa==="retrying"||oa==="exhausted",gr=!We&&aa&&!!Ve&&(!vn||sa),hr=!We&&ia&&!!q,Pr=!We&&M&&Fr&&Nr.length>0&&!!q,Ii=fr&&!sa?ki:gr&&Wa(Qo),Ei=hr&&Wa(ea),_i=Pr&&na!=="load_error",la=a=>a==="loading"||a==="ready",ca=fr||gr&&la(Qo)||hr&&la(ea)||Pr&&na!=="load_error",zr=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!zr.current){if(!M&&!x){zr.current=!0;let a=new Ut.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");m?.(a),ge(a.message)}else if(!M&&x&&!vn&&!Ve){zr.current=!0;let a=new Ut.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");m?.(a),ge(a.message)}else if(Or!==void 0&&!We&&!Te&&!ca){zr.current=!0;let a=new Ut.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});m?.(a),ge(a.message)}}},[M,x,vn,Ve,Or,We,Te,ca,m,ge]);let da=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(da.current||!Fr)return;let a=[];z!==!0&&a.push("showApplePay"),ue!==!0&&a.push("showGooglePay"),a.length!==0&&(da.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Fr,z,ue]);let ua=(0,r.useCallback)((a,C)=>Ge.applyInlineSessionPatch?Ge.applyInlineSessionPatch(a).then(H=>({error:null,sessionId:H.sessionId||e,nonce:H.session?.clientSecret||t})).catch(H=>{let ne=Ka(C,H);return ge(ne.message),m?.(ne),{error:ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ge.applyInlineSessionPatch,t,m,e,ge]),cn=(0,r.useCallback)(async a=>{if(!be)return{proceed:!0};try{let C=await be({method:a,sessionId:e||void 0,createSession:Ge.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&Dn(ne=>({...ne??{},...C.account}));let H=await ua(C,a);return H.error?{proceed:!1,accountPatch:C.account}:{proceed:!0,accountPatch:C.account,sessionId:H.sessionId,nonce:H.nonce}}return{proceed:!0}}catch(C){let H=Ka(a,C);return ge(H.message),m?.(H),{proceed:!1}}},[ua,Ge.inlineSessionDraft,be,m,e,ge]),pa=(0,r.useCallback)(async(a,C)=>{if(Y.current)return;Y.current=!0,ke(!0),P("processing"),ge(null);let H=C?.sessionId??e,ne=C?.nonce??t,j=To(y,C?.accountPatch),ve=C?.completionPaymentMethodId??Xr(a),Ne=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let Lt=await new mn.PaymentAPI(O).processPayment(j.userId??"",{sessionId:H,nonce:ne,tokenizedData:Ne,accountData:{userId:j.userId??"",email:j.email??"",firstName:j.firstName??"",lastName:j.lastName??"",...le?(()=>{let Fe=Rt.current,zt=(0,R.isAVSFieldVisible)(le.state,Fe),nn=(0,R.isAVSFieldVisible)(le.address_line_1,Fe),Wn=(0,R.isAVSFieldVisible)(le.postal_code,Fe),Yn=nn&&!zt&&Wn?(0,R.getStateFromPostalCode)(Fe,(Nt.current??"").trim()):null,Tt=zt?jt.current:Yn;return{country:Fe,...Wn&&Nt.current?{zip:Nt.current}:{},...(0,R.isAVSFieldVisible)(le.city,Fe)&&Bt.current?{city:Bt.current}:{},...Tt?{state:Tt}:{},...nn&&qt.current?{addressLine1:qt.current}:{},...(0,R.isAVSFieldVisible)(le.address_line_2,Fe)&&Gt.current?{addressLine2:Gt.current}:{}}})():{}},chv:_,avsCheck:ye??!1,checkoutType:E,checkoutLayout:re,avsConfig:le?{country:(0,R.isAVSFieldVisible)(le.country,Rt.current),postal_code:(0,R.isAVSFieldVisible)(le.postal_code,Rt.current),address_line_1:(0,R.isAVSFieldVisible)(le.address_line_1,Rt.current),address_line_2:(0,R.isAVSFieldVisible)(le.address_line_2,Rt.current),city:(0,R.isAVSFieldVisible)(le.city,Rt.current),state:(0,R.isAVSFieldVisible)(le.state,Rt.current)}:void 0});if(Lt.ok){sr(H),P("success"),de(null),await new Promise(Fe=>setTimeout(Fe,_n)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ve,checkoutMethod:a.isPaypal?"paypal":"card"});return}let Xe=await Lt.json().catch(()=>null);if(Xe?.type==="paypal_redirect_required"){let Fe=Xe.threeDSecureToken,zt=Xe.paymentMethodId||a.id||"";if(!Ae||!Fe){P("error"),ge("PayPal authorization required but no token provided.");return}try{let nn=at?.getRawProvider();if(!nn){ge("PayPal is not available.");return}let Wn={return_url:window.location.href};zt&&(Wn.payment_method=zt);let{error:Yn}=await nn.confirmPayment({clientSecret:Fe,confirmParams:Wn,redirect:"if_required"});if(Yn){P("error");let Tt=Yn.message??"PayPal payment failed.";ge(Tt),ln("paypal",Tt,{code:Yn.code})}}catch(nn){P("error"),ge(nn instanceof Error?nn.message:"PayPal authorization failed.")}return}if(Xe?.type==="paypal_direct_required"){let Fe=Xe.orderId;if(!Fe){P("error"),ge("PayPal retry required but no order id provided.");return}let zt=S.current?.attempts??0;if(zt>=2){P("error"),ge("PayPal payment could not be completed after multiple attempts."),ln("paypal","paypal_direct_required retry limit exceeded");return}Po(!1),bo("loading"),de({orderId:Fe,attempts:zt+1}),P(null);return}P("error");let xt=Xe?.message??"Payment failed. Please try again.";ge(xt),ln(a.isPaypal?"paypal":"card",xt,{code:Xe?.code??Xe?.gatewayErrorCode,declineCode:Xe?.declineCode??Xe?.gatewayDeclineReason}),await new Promise(Fe=>setTimeout(Fe,Cn))}catch(yt){P("error"),ge(yt instanceof Error?yt.message:"An unexpected error occurred"),await new Promise(Lt=>setTimeout(Lt,Cn))}finally{ke(!1),P(null),Y.current=!1}},[O,e,t,y,$,_,Ae,at,s,m,ge,ln]),tn=(0,r.useCallback)((a,C)=>{I?I(a):pa(a,C)},[I,pa]),ma=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(typeof window>"u"||ma.current)return;let a=new URLSearchParams(window.location.search),C=a.get("payment_intent"),H=a.get("payment_intent_client_secret"),ne=a.get("redirect_status");if(!C||!H)return;let j=xt=>{let Fe=localStorage.getItem(xt);if(!Fe)return null;try{return JSON.parse(Fe)}catch{return localStorage.removeItem(xt),null}},ve=j(wn)??j(qa),Ne;if(ve?.clientSecret){if(ve.clientSecret!==H)return;Ne={...ve.accountPatch?{accountPatch:ve.accountPatch}:{},...ve.sessionId?{sessionId:ve.sessionId}:{},...ve.nonce?{nonce:ve.nonce}:{}}}else if(ve?.sessionId&&ve.sessionId!==e)return;ma.current=!0,localStorage.removeItem(wn),localStorage.removeItem(qa);let yt=new URL(window.location.href);yt.searchParams.delete("payment_intent"),yt.searchParams.delete("payment_intent_client_secret"),yt.searchParams.delete("redirect_status"),window.history.replaceState({},"",yt.toString());let Lt=ve?.paymentMethodType??ve?.tokenType??"card",Xe="card";(async()=>{let xt=Ae?.getRawProvider();if(!xt){let Tt="Payment is not available \u2014 please refresh and try again.";ge(Tt),ln(Xe,Tt);return}if(ne==="failed"){let Tt="Payment was declined. Please try again.";ge(Tt),ln(Xe,Tt);return}let{paymentIntent:Fe,error:zt}=await xt.retrievePaymentIntent(H);if(zt){let Tt=zt.message??"Failed to retrieve payment status.";ge(Tt),ln(Xe,Tt,{code:zt.code});return}let nn=Fe?.status,Wn=Jr(nn);if(!Fe||!Wn){let Tt=nn==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ge(Tt),ln(Xe,Tt,{code:nn??"missing_payment_intent"});return}let Yn=typeof Fe.payment_method=="string"?Fe.payment_method:Fe.payment_method?.id;tn({id:Yn??ve?.paymentMethodId??ve?.tokenId??Fe.id,type:"card",threeDSecureActionResultTokenId:Fe.id,gateway:ve?.gateway??"stripe",paymentMethodType:Lt},Ne)})()},[e,tn,Ae,ge,ln]);let vo=(0,r.useCallback)(a=>{a.preventDefault()},[]);if(!(Ae!==null))return(0,i.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let br=ae==="buttons",Yt=ee?.variables,xi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Co=Yt?.colorBackground,Ti=Co&&!xi.has(Co)?Co:void 0,vr=f.cardInputBorder??(br?"#e5e7eb":"#A4A4FF"),So=Yt?.colorDanger??"#dc2626",Vn=a=>Jt&&a?So:vr,Ur=(Ft.malformed||Ft.empty)&&(an||Jt),Mi=Ur?So:Vn(ht.zip),wo=f.cardFormContainer?.backgroundColor??Ti??(br?"white":"#EDEDFF"),Cr=f.cardInputBackground??Yt?.colorBackground??"white",ko=nr(J),ya=nr(me),tr=f.nameInput,fa=f.cardInputFontSize??ms(tr?.fontSize)??Yt?.fontSizeBase??"16px",ga=typeof tr?.fontFamily=="string"?tr.fontFamily:Yt?.fontFamily??"Poppins, sans-serif",ha=Ha(tr?.fontWeight)??400,Bi=f.cardInputColor??(typeof tr?.color=="string"?tr.color:void 0)??Yt?.colorText??"#262833",Ai=f.cardInputPlaceholderColor??"#9ca3af",mt=Yt?.borderRadius??"8px",Kn=Yt?.borderRadius??f.cardButton?.borderRadius??mt,Hn=Yt?.colorPrimary??"#4A49FF",Fi=Yt?.colorPrimaryHover??to(Hn,.12),Ro=Yt?.colorText??"#262833",Pa={fontSize:fa,fontFamily:ga,fontWeight:ha,color:Bi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Di={"--flopay-input-placeholder-color":Ai,"--flopay-input-font-size":fa,"--flopay-input-font-family":ga,"--flopay-input-font-weight":String(ha)},Sr=f.cardFormContainer??{},Io=Sr.padding??(br?"0":"1rem"),Eo=Sr.borderRadius??mt,Li=it&&It?(0,i.jsx)(Hr,{capture:it,html:It.html,messageToken:It.messageToken,expectedOrigin:It.expectedOrigin,theme:Ie,onReady:()=>{if(!le||typeof document>"u")return;let a=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};a();let C=0,H=window.setInterval(()=>{C+=1;let ne=document.activeElement;!!ne&&ne.tagName==="IFRAME"&&ne.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(H)):C>=50&&window.clearInterval(H)},100)},onError:a=>ge(a),onValidation:a=>{let C=fe.current;(C==="idle"||C==="validation-window")&&(ge(a),a&&fe.current==="validation-window"&&(K.current&&(clearTimeout(K.current),K.current=null),fe.current="idle",P(null)))}}):(0,i.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),ba=(0,i.jsxs)("div",{style:{backgroundColor:wo,borderRadius:Eo,...Sr,padding:Io,...Di,display:"flex",flexDirection:"column"},children:[(0,i.jsx)("style",{children:`
|
|
30
|
+
`,mo=44;function Go(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 Cs={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},li={width:"100%",minHeight:mo,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 Ss(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ti(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ci(e){return e==="paypal"?"PayPal":(0,C.getStripeMethodDisplayName)(e)}function ws(e,t){let n=`We couldn't open ${ci(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function di(e){let t=(0,o.useRef)(0),n=(0,o.useRef)(null),s=(0,o.useRef)(null),a=(0,o.useCallback)((u=s.current)=>{let b=u;b?.timer&&(clearTimeout(b.timer),b.timer=null)},[]),c=(0,o.useCallback)((u,b)=>{typeof document<"u"&&document.visibilityState!=="visible"||(a(u),u.timer=setTimeout(()=>{u.timer=null,s.current?.generation===u.generation&&(s.current=null,n.current=u.generation,e(u.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},b))},[a,e]),p=(0,o.useCallback)(u=>{u.yieldedControl&&c(u,600)},[c]),d=(0,o.useCallback)(u=>{a();let b=t.current+1;t.current=b,n.current=null;let I={generation:b,method:u,timer:null,yieldedControl:!1};return s.current=I,b},[a]),S=(0,o.useCallback)(u=>{let b=s.current;return typeof u=="number"&&b?.generation!==u?!1:(a(b),s.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[a]),$=(0,o.useCallback)(u=>{let b=s.current,I=u??b?.generation??t.current;(!u||b?.generation===u)&&(a(b),s.current=null),n.current=I},[a]),P=(0,o.useCallback)(u=>n.current===(u??t.current),[]),E=(0,o.useCallback)(u=>s.current?.generation===u&&n.current!==u,[]),w=(0,o.useCallback)(()=>{let u=s.current;u&&p(u)},[p]),_=(0,o.useCallback)(()=>{let u=s.current;u&&(u.yieldedControl=!0,a(u))},[a]);return(0,o.useEffect)(()=>{let u=()=>{document.visibilityState==="visible"?w():_()},b=()=>{_()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",b),window.addEventListener("focus",w),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",b),window.removeEventListener("focus",w),a()}},[a,_,w]),{startAttempt:d,finishAttempt:S,invalidateAttempt:$,isAttemptInvalidated:P,isAttemptCurrent:E}}function ks(e){let t=(0,C.getPostalCodeExample)(e);return`Enter a valid ${(0,C.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Rs(e,t,n){let s=(0,C.isPostalCodeSupported)(e),a=t.trim(),c=n&&s,p=c&&!a,d=c&&!!a&&!(0,C.isValidPostalCode)(e,a);return{visible:n,supported:s,required:c,empty:p,malformed:d}}function ni(e,t){return t instanceof zt.FloPayError?t:new zt.FloPayError(t instanceof Error?t.message:`${Ss(e)} before-click hook failed.`,"validation_error")}function Ho(){return(0,l.jsx)("style",{children:vs})}function Es(e){return typeof e=="number"?`${e}px`:e}function ri(e){if(typeof e=="number"||typeof e=="string")return e}function ui(e,t){let n=e.availablePaymentMethods;return n&&t.some(s=>n[s])?"ready":"unavailable"}function pi({state:e,placeholderTestId:t,borderRadius:n=8,children:s}){return e==="unavailable"||e==="load_error"?null:(0,l.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,l.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,l.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:s})]})}function oi(e){return e!=="unavailable"&&e!=="load_error"}function fo(e){return(0,l.jsx)(_s,{...e})}function ai({sessionId:e,nonce:t,email:n,billingApiUrl:s,onTokenizedBody:a,onErrorChange:c,isProcessing:p=!1,onButtonClick:d,onDecline:S,onTechnicalFailure:$,runBeforeButtonClick:P,onLoadStateChange:E,placeholderBorderRadius:w}){let _=dn(),u=(0,ft.useStripe)(),b=(0,ft.useElements)(),[I,x]=(0,o.useState)("loading");(0,o.useEffect)(()=>{E?.(I)},[I,E]);let[h,me]=(0,o.useState)(!1),T=(0,o.useRef)(!1),ce=(0,o.useRef)(null),ne=(0,o.useRef)(null),[q,Q]=(0,o.useState)(0),[W,ie]=(0,o.useState)(!1),K=(0,o.useRef)(!1),L=(0,o.useRef)(new Map),{startAttempt:re,finishAttempt:ye,invalidateAttempt:ue,isAttemptInvalidated:pe,isAttemptCurrent:se}=di((X,k,de)=>{$?.(X,k,{...de,popupBlocked:de?.popupBlocked??$n(k)}),ie(!0),Q(Ve=>Ve+1)});(0,o.useEffect)(()=>{W&&ne.current?.focus()},[W,q]);let Se=(0,o.useCallback)(()=>{Q(X=>X+1)},[]),De=(0,o.useCallback)((X,k,de)=>{ue(de),$?.("paypal",X,{code:k,popupBlocked:$n(X)}),ie(!0),Se()},[ue,$,Se]),le=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{K.current&&(K.current=!1,le())},[le,q]);let je=(0,o.useCallback)(()=>{ie(!1),c?.(null),le()},[le,c]);(0,o.useEffect)(()=>{if(!u||T.current)return;let X=new URLSearchParams(window.location.search),k=X.get("payment_intent"),de=X.get("payment_intent_client_secret"),Ve=X.get("redirect_status");if(!k||!de)return;T.current=!0;let Ue;try{let B=localStorage.getItem(zr);if(B){let fe=JSON.parse(B);fe.clientSecret===de&&(Ue={...fe.accountPatch?{accountPatch:fe.accountPatch}:{},...fe.sessionId?{sessionId:fe.sessionId}:{},...fe.nonce?{nonce:fe.nonce}:{}})}}catch{}try{localStorage.removeItem(zr)}catch{}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()),(async()=>{try{if(me(!0),Ve==="failed"){let Z="PayPal payment was declined. Please try again.";c?.(Z),S?.(Rt("paypal",Z));return}let{paymentIntent:B,error:fe}=await u.retrievePaymentIntent(de);if(fe){c?.(fe.message??"Failed to retrieve PayPal payment status.");return}if(B&&(B.status==="requires_capture"||B.status==="succeeded")){let Z=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id;a({id:Z??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0},Ue)}else{let Z="PayPal payment was not completed. Please try again.";c?.(Z),S?.(Rt("paypal",Z))}}catch(B){c?.(B instanceof Error?B.message:"Failed to complete PayPal payment.")}finally{me(!1)}})()},[u,a,c,S]);let Oe=(0,o.useCallback)(async X=>{if(p||h){X.reject();return}let k=P?await P("paypal"):{proceed:!0};if(!k.proceed){L.current.delete(q),X.reject();return}let de=re("paypal");L.current.set(q,{generation:de,accountPatch:k.accountPatch,sessionId:k.sessionId,nonce:k.nonce}),ie(!1),d?.("paypal"),X.resolve()},[L,p,d,P,re,h,q]),_e=(0,o.useCallback)(async X=>{if(!u||!b)return;let k=L.current.get(q);if(k&&!se(k.generation)){L.current.delete(q);return}if(!k&&pe()||k&&!ye(k.generation))return;k||ye();let de=k??null;if(L.current.delete(q),!de&&P){let B=await P("paypal");if(!B.proceed){X.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}de={accountPatch:B.accountPatch,sessionId:B.sessionId,nonce:B.nonce}}let Ve=de?.sessionId??e,Ue=de?.nonce??t,ge=de?.accountPatch?.email??n;try{if(me(!0),c?.(null),!Ve||!ge)throw new Error("Missing sessionId or email for PayPal payment");let B=u.createPaymentMethod,{error:fe,paymentMethod:Z}=await B({type:"paypal"});if(fe){De(fe,"stripe_paypal_create_payment_method_failed",k?.generation),X.paymentFailed({reason:"fail"});return}let xe=await new pn.PaymentAPI(s).createSessionIntent(Ve,Ue??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Z?.id??null,intentKind:"payment"});if(xe.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ut=xe.clientSecret,Ze={return_url:window.location.href};if(Z?.id&&(Ze.payment_method=Z.id),typeof window<"u")try{localStorage.setItem(zr,JSON.stringify({clientSecret:ut,sessionId:Ve,nonce:Ue,accountPatch:de?.accountPatch}))}catch{}let{error:pt,paymentIntent:z}=await u.confirmPayment({clientSecret:ut,confirmParams:Ze,redirect:"if_required"});if(pt){if(typeof window<"u")try{localStorage.removeItem(zr)}catch{}if(Dr(pt)){let rt=pt.message??"Your payment was declined.";c?.(rt),S?.(Rt("paypal",rt,{code:An(pt),declineCode:fr(pt)})),await yo({billingApiUrl:s,sessionId:Ve,nonce:Ue,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:An(pt)??"provider_declined"}})}else De(pt,"stripe_paypal_confirm_failed",k?.generation);return}if(typeof window<"u")try{localStorage.removeItem(zr)}catch{}let ee=typeof z?.payment_method=="string"?z.payment_method:z?.payment_method?.id;a({id:ee??z?.id,type:"card",threeDSecureActionResultTokenId:z?.id,isPaypal:!0},{accountPatch:de?.accountPatch,sessionId:Ve,nonce:Ue});return}catch(B){De(B,"stripe_paypal_failed",k?.generation)}finally{me(!1)}},[u,b,e,t,n,s,a,c,S,P,De,ye,se,pe,q]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(pi,{state:I,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:(0,l.jsxs)("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[W&&(0,l.jsx)("button",{ref:ne,type:"button","data-testid":"flopay-paypal-retry-button",onClick:je,style:li,children:"Try PayPal again"}),(0,l.jsx)(ft.ExpressCheckoutElement,{onReady:X=>x(ui(X,["paypal"])),onLoadError:()=>{x("load_error"),Yo(Tt(_),"paypal","paypal")},onClick:Oe,onConfirm:_e,onCancel:()=>{let X=L.current.get(q);L.current.delete(q),Tt(_)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ue(X?.generation),ie(!1),K.current=!0,Se()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},q)]})}),h&&(0,l.jsx)(wn,{status:"processing"})]})}function ii({sessionId:e,nonce:t,email:n,billingApiUrl:s,intentKind:a,expressMethods:c,onTokenizedBody:p,onErrorChange:d,onButtonClick:S,onDecline:$,onTechnicalFailure:P,runBeforeButtonClick:E,onLoadStateChange:w,placeholderBorderRadius:_}){let u=dn(),b=(0,ft.useStripe)(),I=(0,ft.useElements)(),[x,h]=(0,o.useState)("loading");(0,o.useEffect)(()=>{w?.(x)},[x,w]);let[me,T]=(0,o.useState)(!1),ce=(0,o.useRef)(null),ne=(0,o.useRef)(null),[q,Q]=(0,o.useState)(0),[W,ie]=(0,o.useState)(!1),[K,L]=(0,o.useState)("google_pay"),re=(0,o.useRef)(!1),ye=(0,o.useRef)("google_pay"),ue=(0,o.useRef)("google_pay"),pe=(0,o.useRef)(new Map),{startAttempt:se,finishAttempt:Se,invalidateAttempt:De,isAttemptInvalidated:le,isAttemptCurrent:je}=di((ge,B,fe)=>{P?.(ge,B,{...fe,popupBlocked:fe?.popupBlocked??$n(B)}),L(ge),ie(!0),Q(Z=>Z+1)});(0,o.useEffect)(()=>{W&&ne.current?.focus()},[W,q]);let Oe=(0,o.useCallback)(()=>{Q(ge=>ge+1)},[]),_e=(0,o.useCallback)((ge,B,fe,Z)=>{De(Z),P?.(ge,B,{code:fe,popupBlocked:$n(B)}),L(ge),ie(!0),Oe()},[De,P,Oe]),X=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{re.current&&(re.current=!1,X())},[X,q]);let k=(0,o.useCallback)(()=>{ie(!1),d?.(null),X()},[X,d]),de=(0,o.useCallback)(async ge=>{if(!b||!I)return;let B=pe.current.get(q);if(B&&!je(B.generation)){pe.current.delete(q);return}if(!B&&le()||B&&!Se(B.generation))return;B||Se();let fe=ge.expressPaymentType??B?.method??ye.current,Z=B??null;pe.current.delete(q);let xe=ti(fe);if(!Z&&E){let ee=await E(xe);if(!ee.proceed){ge.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}Z={accountPatch:ee.accountPatch,sessionId:ee.sessionId,nonce:ee.nonce}}let ut=xe,Ze=Z?.sessionId??e,pt=Z?.nonce??t,z=Z?.accountPatch?.email??n;try{T(!0),d?.(null);let{error:ee}=await I.submit();if(ee){_e(fe,ee,"stripe_wallet_submit_failed",B?.generation);return}let{error:rt,paymentMethod:Ke}=await b.createPaymentMethod({elements:I});if(rt||!Ke){_e(fe,rt??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",B?.generation);return}if(!Ze||!z)throw new Error("Missing sessionId or email for wallet payment");let mt=await new pn.PaymentAPI(s).createSessionIntent(Ze,pt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:fe??xe,paymentMethodId:Ke.id,intentKind:a});if(mt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let $e=mt.clientSecret,{error:Je,intentId:Gt}=(0,zt.isSetupIntentClientSecret)($e)?await b.confirmCardSetup($e,{payment_method:Ke.id}).then(Qe=>({error:Qe.error,intentId:Qe.setupIntent?.id})):await b.confirmCardPayment($e,{payment_method:Ke.id}).then(Qe=>({error:Qe.error,intentId:Qe.paymentIntent?.id}));if(Je){if(Dr(Je)){let Qe=Je.message??"Your payment was declined.";d?.(Qe),$?.(Rt(ut,Qe,{code:An(Je),declineCode:fr(Je)})),await yo({billingApiUrl:s,sessionId:Ze,nonce:pt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:fe??xe,providerDeclineReason:An(Je)??"provider_declined"}})}else _e(fe,Je,"stripe_wallet_confirm_failed",B?.generation);return}p({id:Ke.id,type:"card",threeDSecureActionResultTokenId:Gt},{accountPatch:Z?.accountPatch,sessionId:Ze,nonce:pt})}catch(ee){_e(fe,ee,"stripe_wallet_failed",B?.generation)}finally{T(!1)}},[b,I,e,t,n,s,a,p,d,$,E,_e,Se,je,le,q]),Ve=(0,o.useMemo)(()=>{let ge=["applePay","googlePay","paypal","link","amazonPay","klarna"],B=new Set(["applePay","googlePay"]),fe=new Set(c.map(C.stripeExpressMethodToOptionKey)),Z={};for(let xe of ge)fe.has(xe)?Z[xe]=B.has(xe)?"always":"auto":Z[xe]="never";return Z},[c]),Ue=(0,o.useMemo)(()=>c.map(C.stripeExpressMethodToOptionKey),[c]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(pi,{state:x,placeholderTestId:"flopay-wallet-placeholder",borderRadius:_,children:(0,l.jsxs)("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[W&&(0,l.jsxs)("button",{ref:ne,type:"button","data-testid":"flopay-wallet-retry-button",onClick:k,style:li,children:["Try ",ci(K)," again"]}),(0,l.jsx)(ft.ExpressCheckoutElement,{onReady:ge=>{h(ui(ge,Ue))},onLoadError:ge=>{h("load_error"),Yo(Tt(u),"stripe","wallet")},onClick:async ge=>{ye.current=ge.expressPaymentType,ue.current=ti(ge.expressPaymentType);let B=E?await E(ue.current):{proceed:!0};if(!B.proceed){pe.current.delete(q),ge.reject();return}let fe=se(ge.expressPaymentType);pe.current.set(q,{generation:fe,method:ge.expressPaymentType,accountPatch:B.accountPatch,sessionId:B.sessionId,nonce:B.nonce}),ie(!1),S?.(ue.current),ge.resolve()},onConfirm:de,onCancel:()=>{let ge=pe.current.get(q);pe.current.delete(q),Tt(u)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),De(ge?.generation),ie(!1),re.current=!0,Oe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ve,layout:{maxColumns:1,overflow:"never"}}},q)]})}),me&&(0,l.jsx)(wn,{status:"processing"})]})}function Is({method:e,themeId:t,submitting:n=!1,disabled:s=!1,highlighted:a=!1,hasNextStep:c=!1,onClick:p,backgroundColor:d,borderColor:S,textColor:$,borderRadius:P,fontFamily:E}){let w=(0,C.resolveStripeMethodBrandVariant)(e,t),_=Na[e],u=w?.backgroundColor??d??"#ffffff",b=w?.borderColor??S??"#d1d5db",I=w?.textColor??$??"#262833";return(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!s&&p()},disabled:n||s,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:mo,padding:"0 1rem",backgroundColor:u,color:I,border:`1px solid ${b}`,borderRadius:P??8,fontSize:"0.95rem",fontWeight:600,fontFamily:E,cursor:n||s?"not-allowed":"pointer",opacity:s&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,l.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,C.getStripeMethodDisplayName)(e)}\u2026`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,C.hasVendoredStripeMethodLogo)(e)?8:0},children:[_?(0,l.jsx)("img",{src:_,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,l.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,l.jsx)("span",{children:(0,C.getStripeMethodDisplayName)(e)})]}),c&&(0,l.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,l.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Wo({method:e,sessionId:t,nonce:n,email:s,billingName:a,billingApiUrl:c,onTokenizedBody:p,onErrorChange:d,onDecline:S,onCancel:$,runBeforeButtonClick:P,onButtonClick:E,isProcessing:w,submitButtonColor:_,submitButtonBorderRadius:u,submitButtonStyle:b,errorText:I}){let x=dn(),h=(0,ft.useStripe)(),me=(0,ft.useElements)(),[T,ce]=(0,o.useState)(!1),ne=(0,o.useRef)(!1),[q,Q]=(0,o.useState)(!1),[W,ie]=(0,o.useState)("loading"),K=(0,o.useCallback)(async()=>{if(!h||!me||w||ne.current||!q)return;ne.current=!0,ce(!0);let L=P?await P("card"):{proceed:!0};if(!L.proceed){ne.current=!1,ce(!1);return}E?.("card");let re=L.sessionId??t,ye=L.nonce??n,ue=L.accountPatch?.email??s;try{d?.(null);let pe=await me.submit();if(pe.error){d?.(pe.error.message??"Payment failed.");return}let se=await h.createPaymentMethod({elements:me});if(se.error||!se.paymentMethod){d?.(se.error?.message??"Failed to create payment method.");return}let Se=se.paymentMethod;if(!re||!ue)throw new Error("Missing sessionId or email for payment.");let De=Se.type||e,le=await new pn.PaymentAPI(c).createSessionIntent(re,ye??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:De,paymentMethodId:null,intentKind:"payment"});if(le.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let je=le.clientSecret;if(typeof window<"u")try{localStorage.setItem(kn,JSON.stringify({clientSecret:je,sessionId:re,nonce:ye,accountPatch:L.accountPatch,paymentMethodId:Se.id,paymentMethodType:Se.type??e,gateway:"stripe"}))}catch{}let{error:Oe,paymentIntent:_e}=await h.confirmPayment({clientSecret:je,confirmParams:{return_url:window.location.href,payment_method:Se.id},redirect:"if_required"});if(Oe){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let de=Oe.message??"Payment failed.";d?.(de),S?.(Rt("card",de,{code:Oe.code})),await yo({billingApiUrl:c,sessionId:re,nonce:ye,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Oe.code??"provider_declined"}});return}let X=_e?.status;if(!so(X)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let de=X==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(de),S?.(Rt("card",de,{code:X??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let k=typeof _e?.payment_method=="string"?_e.payment_method:_e?.payment_method?.id;p({id:k??Se.id,type:"card",threeDSecureActionResultTokenId:_e?.id,gateway:"stripe",paymentMethodType:Se.type??e},{accountPatch:L.accountPatch,sessionId:re,nonce:ye})}catch(pe){d?.(pe instanceof Error?pe.message:"Payment failed. Please try again.")}finally{ne.current=!1,ce(!1)}},[h,me,w,q,P,E,t,n,s,c,e,p,d,S]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,l.jsx)(ft.PaymentElement,{onReady:()=>ie("ready"),onLoadError:()=>{ie("load_error"),Yo(Tt(x),"stripe","apm")},onChange:L=>{Q(!!L.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:a&&a.trim().length>=3?a.trim():"FloPay Customer",...s?{email:s}:{}}}}}),(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{K()},disabled:!q||T||w||W!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:_,color:"white",border:"none",borderRadius:u,fontSize:"1rem",fontWeight:600,cursor:!q||T||w||W!=="ready"?"not-allowed":"pointer",opacity:!q||T||w||W!=="ready"?.5:1,transition:"opacity 120ms ease-out",...b??{}},children:T?"Processing\u2026":`Pay with ${(0,C.getStripeMethodDisplayName)(e)}`}),I&&(0,l.jsx)(dr,{margin:"0.75rem 0 0",children:I})]})}function si({sessionId:e,nonce:t,email:n,billingName:s,billingApiUrl:a,paymentElementMethods:c,stripeInstance:p,paymentElementBaseOptions:d,onTokenizedBody:S,onErrorChange:$,onButtonClick:P,onDecline:E,runBeforeButtonClick:w,onLoadStateChange:_,isProcessing:u=!1,submitButtonColor:b="#4A49FF",submitButtonBorderRadius:I=8,submitButtonStyle:x,buttonAppearance:h,themeId:me,onExpandApm:T,expandedApmMethod:ce}){let[ne,q]=(0,o.useState)(null),[Q,W]=(0,o.useState)(null),ie=(0,o.useRef)(!1);(0,o.useEffect)(()=>{c.length>0&&p?_?.("ready"):p||_?.("loading")},[c.length,p,_]);let K=(0,o.useCallback)(async se=>{if(!p||ie.current||u)return;ie.current=!0,W(se);let Se=w?await w("card"):{proceed:!0};if(!Se.proceed){ie.current=!1,W(null);return}P?.("card");let De=Se.sessionId??e,le=Se.nonce??t,je=Se.accountPatch?.email??n;try{if($?.(null),!De||!je)throw new Error("Missing sessionId or email for payment.");let Oe=await new pn.PaymentAPI(a).createSessionIntent(De,le??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:se,paymentMethodId:null,intentKind:"payment"});if(Oe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let _e=Oe.clientSecret;if(typeof window<"u")try{localStorage.setItem(kn,JSON.stringify({clientSecret:_e,sessionId:De,nonce:le,accountPatch:Se.accountPatch,paymentMethodType:se,gateway:"stripe"}))}catch{}let{error:X,paymentIntent:k}=await p.confirmPayment({clientSecret:_e,confirmParams:{return_url:window.location.href,payment_method_data:{type:se,billing_details:{name:s&&s.trim().length>=3?s.trim():"FloPay Customer",...je?{email:je}:{}}}},redirect:"if_required"});if(X){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Ue=X.message??"Payment failed.";$?.(Ue),E?.(Rt("card",Ue,{code:X.code})),await yo({billingApiUrl:a,sessionId:De,nonce:le,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:se,providerDeclineReason:X.code??"provider_declined"}});return}let de=k?.status;if(!so(de)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Ue=de==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";$?.(Ue),E?.(Rt("card",Ue,{code:de??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Ve=typeof k?.payment_method=="string"?k.payment_method:k?.payment_method?.id;S({id:Ve??k?.id,type:"card",threeDSecureActionResultTokenId:k?.id,gateway:"stripe",paymentMethodType:se},{accountPatch:Se.accountPatch,sessionId:De,nonce:le})}catch(Oe){$?.(Oe instanceof Error?Oe.message:"Payment failed. Please try again.")}finally{ie.current=!1,W(null)}},[p,u,w,P,e,t,n,a,s,S,$,E]),[L,re]=(0,o.useState)(null),ye=T?ce??null:L,ue=(0,o.useCallback)(se=>{ie.current||u||ye&&ye!==se||((0,C.needsStripeMethodExplicitConfirm)(se)?T?T(se):re(se):K(se))},[ye,u,K,T]),pe=(0,o.useMemo)(()=>L?{...d,paymentMethodTypes:[L]}:null,[L,d]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:c.map(se=>{let Se=ce===se,De=Q===se,le=Q!==null&&Q!==se||ce!=null&&ce!==se;return(0,l.jsxs)(o.default.Fragment,{children:[(0,l.jsx)(Is,{method:se,themeId:me,submitting:De,disabled:le,highlighted:Se,hasNextStep:(0,C.needsStripeMethodExplicitConfirm)(se),onClick:()=>ue(se),backgroundColor:h?.backgroundColor,borderColor:h?.borderColor,textColor:h?.textColor,borderRadius:h?.borderRadius,fontFamily:h?.fontFamily}),!T&&L===se&&pe&&p&&(0,l.jsx)(ft.Elements,{stripe:p,options:pe,children:(0,l.jsx)(Wo,{method:se,sessionId:e,email:n,billingName:s,billingApiUrl:a,onTokenizedBody:S,onErrorChange:$,onDecline:E,onCancel:()=>re(null),runBeforeButtonClick:w,onButtonClick:P,isProcessing:u,submitButtonColor:b,submitButtonBorderRadius:I,submitButtonStyle:x})},se)]},se)})})}function _s({sessionId:e,nonce:t,billingApiUrl:n,email:s,userId:a,onComplete:c,onError:p,onDecline:d,onTokenizedBody:S,firstName:$,lastName:P,chv:E,className:w,isProcessing:_,error:u,onErrorChange:b,showPayPal:I=!0,showStripe:x=!0,enabledPaymentMethods:h,enabledPaymentMethodCountries:me,showApplePay:T=!0,showGooglePay:ce=!0,layout:ne="default",theme:q,buttonsTheme:Q,buttonsStyles:W,appearance:ie,cardButtonContent:K,cardBackButtonContent:L,cardTitleContent:re,showSecurityFooter:ye,onButtonClick:ue,onBeforeButtonClick:pe,enableAVS:se,cardFieldOrder:Se,cardPreFormSlot:De,avsLayout:le="row",country:je,zip:Oe,addressLine1:_e,addressLine2:X,city:k,state:de,onCountryChange:Ve,onZipChange:Ue,avsCheck:ge,checkoutType:B,checkoutLayout:fe,totalAmount:Z=0,currency:xe="usd",initialCardOpen:ut=!1,directPaypal:Ze,isSubscription:pt=!1,session:z,dataAttachmentPending:ee=!1,debug:rt=!1}){let Ke=dn(),mt=no(),$e=(0,o.useContext)(cn),Je=ee||$e.claimPending===!0,Gt=oo(),[Qe,Jt]=(0,o.useState)(!1),[M,we]=(0,o.useState)(null),[Xe,Te]=(0,o.useState)(je??"US"),[vt,We]=(0,o.useState)(Oe??""),[He,ot]=(0,o.useState)(_e??""),[et,Rn]=(0,o.useState)(X??""),[it,jn]=(0,o.useState)(k??""),[Kt,hn]=(0,o.useState)(de??""),[Xt,rr]=(0,o.useState)({}),Mt=(0,o.useRef)(Oe??""),St=(0,o.useRef)(je??"US"),Qt=(0,o.useRef)(_e??""),Zt=(0,o.useRef)(X??""),At=(0,o.useRef)(k??""),Bt=(0,o.useRef)(de??""),Ct=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(v,J,oe,H,Pe)=>{if(Ct.current[v])return;let Ee=J?.trim();!Ee||Ee===oe.current||(oe.current=Ee,H(Ee),Pe?.(Ee))};i("country",je,St,Te,Ve),i("zip",Oe,Mt,We,Ue),i("addressLine1",_e,Qt,ot),i("addressLine2",X,Zt,Rn),i("city",k,At,jn),i("state",de,Bt,hn)},[je,Oe,_e,X,k,de,Ve,Ue]);let ae=(0,o.useMemo)(()=>(0,C.resolveAVSConfig)(se),[se]),Vn=ae!==null,U=(0,o.useMemo)(()=>(0,C.isAuthorizationOnlySession)(z),[z]),st=!!z?.vault?.html,Ft=!!z?.gateways?.pcivault,Le=!!(z?.gateways?.stripe?.enabledPaymentMethods??h)?.includes("card"),lt=st||Le||Ft,Ye=!!(x&<&&Ke&&e),[En,In]=(0,o.useState)(()=>ne!=="buttons"||ut?e??null:null),[zn,Kn]=(0,o.useState)(0),_n=ne!=="buttons"||ut||!!e&&En===e,at=(0,o.useMemo)(()=>!Ke||!Ye||!e||!_n?null:Ke.cardCapture({sessionId:e,captureMethod:z?.captureMethod}),[Ke,Ye,e,_n,z?.captureMethod]),Dt=(0,o.useMemo)(()=>{let i=Xe,v=ae?(0,C.isAVSFieldVisible)(ae.postal_code,i):!1;return Rs(i,vt,v)},[ae,Xe,vt]),{avsInvalid:on,invalidAvsFields:gt}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Ye||!ae)return{avsInvalid:!1,invalidAvsFields:i};let v=Xe,J=(Pe,Ee)=>(0,C.isAVSFieldVisible)(Pe,v)&&!Ee.trim(),oe={line1:J(ae.address_line_1,He),city:J(ae.city,it),state:J(ae.state,Kt),zip:Dt.empty||Dt.malformed};return{avsInvalid:oe.line1||oe.city||oe.state||oe.zip,invalidAvsFields:oe}},[Ye,ae,Xe,He,it,Kt,Dt]),[It,en]=(0,o.useState)(!1),[an,Ht]=(0,o.useState)(!1),[Ot,Nt]=(0,o.useState)(()=>Ko(z?.vault)),[Me,Ut]=(0,o.useState)(ut&<?"card":"buttons"),[yt,Pn]=(0,o.useState)(null),Hn=Me==="expanding"||Me==="card",$t=280,qt=(0,o.useRef)(null),Lt=(0,o.useCallback)(i=>{qt.current&&clearTimeout(qt.current),qt.current=setTimeout(()=>{qt.current=null,i()},$t)},[$t]);(0,o.useEffect)(()=>()=>{qt.current&&clearTimeout(qt.current)},[]);let On=(0,o.useCallback)(()=>{In(e??null),Kn(i=>i+1),Ut("expanding"),Lt(()=>Ut("card"))},[Lt,e]),Nn=(0,o.useCallback)(()=>{Ut("collapsing"),Lt(()=>Ut("buttons"))},[Lt]),tn=(0,o.useCallback)(i=>{Pn(i),Ut("apm-expanding"),Lt(()=>Ut("apm-form"))},[Lt]),Wt=(0,o.useCallback)(()=>{Ut("apm-collapsing"),Lt(()=>{Ut("buttons"),Pn(null)})},[Lt]);(0,o.useEffect)(()=>{ne==="buttons"&&ut&<&&(In(e??null),Ut("card"))},[ne,ut,lt,e]);let[nn,qe]=(0,o.useState)(null),A=(0,o.useRef)(!1),j=(0,o.useRef)(null),F=(0,o.useRef)("idle"),[ke,Re]=(0,o.useState)(null),y=(0,o.useRef)(ke);(0,o.useEffect)(()=>{y.current=ke},[ke]);let r=n||Gt,g=u??M,O=(0,o.useMemo)(()=>(0,zt.resolveTheme)(q),[q]),f=(0,o.useMemo)(()=>{let i=O?.buttonsLayout??(0,C.resolveButtonsLayoutTheme)(Q);return W?{...i,...W,cardButton:{...i.cardButton,...W.cardButton},cardFormContainer:{...i.cardFormContainer,...W.cardFormContainer},backButton:{...i.backButton,...W.backButton},backButtonIcon:{...i.backButtonIcon,...W.backButtonIcon},submitButton:{...i.submitButton,...W.submitButton},title:{...i.title,...W.title}}:i},[O,Q,W]),Y=ie??O?.appearance,ze=(0,o.useMemo)(()=>{let i=Y?.variables,v=Ee=>typeof Ee=="string"&&Ee?Ee:void 0,J=f.submitButton,oe=v(i?.colorPrimary)??v(J?.backgroundColor)??"#4A49FF",H=ne==="buttons",Pe=f.nameInput;return{primaryColor:oe,primaryHoverColor:v(i?.colorPrimaryHover)??po(oe,.12),inputBackgroundColor:v(f.cardInputBackground)??v(i?.colorBackground)??"#ffffff",textColor:v(f.cardInputColor)??v(Pe?.color)??v(i?.colorText)??"#262833",borderColor:v(f.cardInputBorder)??(H?"#e5e7eb":"#A4A4FF"),placeholderColor:v(f.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(i?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(Pe?.fontFamily)??v(i?.fontFamily)??"Poppins, sans-serif",fontSize:v(f.cardInputFontSize)??v(i?.fontSizeBase)??"16px",fontWeight:String(ri(Pe?.fontWeight)??400),borderRadius:v(i?.borderRadius)??"8px"}},[Y,f,ne]),tt=$e.inlineSessionPatchProcessing??!1,te=(_??Qe)||tt,G=r.replace(/\/+$/,""),m=(0,o.useMemo)(()=>qo({userId:a,email:s,firstName:$,lastName:P,country:je,zip:Oe},Xt),[a,s,$,P,je,Oe,Xt]),V=[m.firstName,m.lastName].filter(i=>!!i?.trim()).join(" "),be=(0,o.useMemo)(()=>Ke?Ke.getRawProvider():null,[Ke]),Ie=(0,o.useMemo)(()=>mt?mt.getRawProvider():null,[mt]),Ae=Z||100,bn=(0,o.useMemo)(()=>Y?(0,pn.toStripeAppearance)(Y):null,[Y]),vr=bn?{appearance:bn}:null,Eo=(0,o.useMemo)(()=>{let i=bn??{},v=i.rules??{};return{...i,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[bn]),jr=(0,o.useMemo)(()=>{let i=Ha(Z);return{...i,currency:xe.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...vr}},[Z,xe,vr]),ia=(0,o.useMemo)(()=>({mode:"payment",amount:Ae,currency:xe.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...vr}),[Ae,xe,vr]),he=(0,o.useCallback)(i=>{we(i),b?.(i)},[b]);(0,o.useEffect)(()=>{!Ye||!at||at.setCardFieldOrder?.(Se??null,ae==null)},[Ye,at,Se,ae]),(0,o.useEffect)(()=>{(Me==="expanding"||Me==="collapsing"||Me==="apm-expanding"||Me==="apm-collapsing")&&he(null)},[Me,he]);let sn=(0,o.useCallback)((i,v,J)=>{d?.(Rt(i,v,J))},[d]),or=(0,o.useCallback)((i,v,J)=>{let oe=J?.popupBlocked??$n(v),H=ws(i,oe),Pe=Zn(J?.code)??An(v)??"external_payment_method_failed",Ee=new zt.FloPayError(H,"api_error",{code:"external_payment_method_failed",param:i});qe(null),ne==="buttons"&&(Ut("buttons"),Pn(null)),he(H),p?.(Ee),console.error("[FloPay] External payment method failed:",{method:i,code:Pe,popupBlocked:oe})},[ne,p,he]);(0,o.useEffect)(()=>{if(!Ye||!e){Nt(null);return}let i=Ko(z?.vault);if(i){Nt(i);return}if(!_n){Nt(null);return}Nt(null);let v=!0;return new pn.PaymentAPI(G).getVaultCapture(e,t).then(J=>{if(!v)return;let oe=Ko(J);oe?Nt(oe):he("Failed to load the secure card form.")}).catch(J=>{v&&he(J instanceof Error?J.message:"Failed to load the secure card form.")}),()=>{v=!1}},[Ye,_n,zn,e,z?.vault?.html,z?.vault?.messageToken,z?.vault?.expectedOrigin,G,t,he]);let vn=(0,o.useRef)({onComplete:c,onError:p,updateError:he,emitDecline:sn,resolvedAccount:m,avsConfig:ae,avsCheckProp:ge,sessionId:e,nonce:t,baseUrl:G,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt});vn.current={onComplete:c,onError:p,updateError:he,emitDecline:sn,resolvedAccount:m,avsConfig:ae,avsCheckProp:ge,sessionId:e,nonce:t,baseUrl:G,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt};let Io=(0,o.useRef)(!1),Ai=(0,o.useCallback)(()=>{let{resolvedAccount:i,avsConfig:v,avsCheckProp:J}=vn.current,oe=St.current||i.country||"US",H=v?(0,C.isAVSFieldVisible)(v.state,oe):!1,Pe=v?(0,C.isAVSFieldVisible)(v.address_line_1,oe):!1,Ee=v?(0,C.isAVSFieldVisible)(v.postal_code,oe):!1,ct=v?(0,C.isAVSFieldVisible)(v.city,oe):!1,Pt=v?(0,C.isAVSFieldVisible)(v.address_line_2,oe):!1,nt=Pe&&!H&&Ee?(0,C.getStateFromPostalCode)(oe,(Mt.current??"").trim()):null,wt=H?Bt.current:nt;return{accountData:{userId:i.userId??"",email:i.email??"",firstName:i.firstName??"",lastName:i.lastName??"",...Ee&&Mt.current?{zip:Mt.current}:{},...ct&&At.current?{city:At.current}:{},...wt?{state:wt}:{},...Pe&&Qt.current?{addressLine1:Qt.current}:{},...Pt&&Zt.current?{addressLine2:Zt.current}:{},country:oe},...J!==void 0?{avsCheck:J}:{},...v?{avsConfig:{country:(0,C.isAVSFieldVisible)(v.country,oe),postal_code:Ee,address_line_1:Pe,address_line_2:Pt,city:ct,state:H}}:{}}},[]),sa=(0,o.useRef)(Je);sa.current=Je,(0,o.useEffect)(()=>{Je||g!==ei||vn.current.updateError(null)},[Je,g]),(0,o.useEffect)(()=>{!Ye||!at||at.setSubmitGate?.(on||Je)},[Ye,at,on,Je]),(0,o.useEffect)(()=>{if(!Ye||!at)return;Io.current=!1;let i=!1,v=at.on("submitting",()=>{en(!0),j.current&&clearTimeout(j.current),F.current="validation-window",j.current=setTimeout(()=>{j.current=null,F.current==="validation-window"&&(F.current="processing")},Ps),qe("processing");let{baseUrl:Ee,sessionId:ct,nonce:Pt,updateError:nt,onError:wt}=vn.current;!ct||!Pt||new pn.PaymentAPI(Ee).patchAccountSnapshot(ct,Pt,Ai(),{telemetryMode:"best_effort"}).catch(ve=>{if(!bs(ve))return;let _t=ve instanceof Error?ve.message:"Please check your billing address and try again.";nt(_t),F.current="idle",qe(null),wt?.(ve instanceof zt.FloPayError?ve:new zt.FloPayError(_t,"api_error"))})}),J=at.on("complete",async Ee=>{if(yr(Ee.sessionId??vn.current.sessionId),F.current="terminal",qe("success"),await new Promise(nt=>setTimeout(nt,Mn)),Io.current)return;Io.current=!0;let ct=vn.current,Pt=(0,C.isAuthorizationOnlySession)(ct)||Ee.outcome==="authorized";vn.current.onComplete?.(Pt?{status:"authorized",paymentIntentId:Ee.intentId,paymentId:Ee.paymentId??ct.paymentId,sessionId:Ee.sessionId??ct.sessionId,authorizationExpiresAt:Ee.authorizationExpiresAt??ct.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ee.intentId,checkoutMethod:"card"})}),oe=at.on("decline",async Ee=>{let{updateError:ct,emitDecline:Pt}=vn.current,nt=Ee.message??"Your payment was declined. Please try another card or contact your bank.";F.current="terminal",ct(nt),qe("error");let wt=Ee.failureOutcome??(0,C.normalizeCheckoutFailureOutcome)(Ee.declineReason)??"authorization_declined";Pt("card",nt,{code:wt,declineCode:wt}),await new Promise(ve=>setTimeout(ve,Sn)),!i&&(F.current="idle",qe(null))}),H=at.on("error",async Ee=>{let{updateError:ct,onError:Pt}=vn.current,nt=Ee.message??"There was a problem processing your payment. Please try again.";F.current="terminal",ct(nt),qe("error"),Pt?.(new zt.FloPayError(nt,"api_error",{code:Ee.failureOutcome??"capture_failed"})),await new Promise(wt=>setTimeout(wt,Sn)),!i&&(F.current="idle",qe(null))}),Pe=at.on("blocked",()=>{if(!sa.current){en(!0);return}vn.current.updateError(ei)});return()=>{i=!0,j.current&&(clearTimeout(j.current),j.current=null),F.current="idle",v(),J(),oe(),H(),Pe()}},[Ye,at]);let Cn=!!Ze?.clientId,Cr=Array.isArray(h),Vr=Cr&&h.length>0,Bi=Cr&&h.includes("paypal"),{expressMethods:Kr,paymentElementMethods:Sr}=(0,o.useMemo)(()=>(0,C.partitionStripeMethods)(h,{excludePaypal:Cn}),[h,Cn]),la=Cn||!!mt,Fi=(0,o.useMemo)(()=>la?Kr.filter(i=>i!=="paypal"):Kr,[Kr,la]),Di=(0,o.useMemo)(()=>{let i=[];return T&&i.push("apple_pay"),ce&&i.push("google_pay"),i},[T,ce]),Hr=Cr?Fi:Di,Li=x&&Hr.length>0,_o=Vn?Xe:je,Wr=(0,o.useMemo)(()=>{let i=_o?.trim().toUpperCase();return i?me?Sr.filter(v=>{let J=me[v];return!J||J.length===0||J.includes(i)}):(0,C.filterStripeMethodsByCountry)(Sr,_o):Sr},[Sr,_o,me]),xo=(0,o.useMemo)(()=>({mode:"payment",amount:Ae,currency:xe.toLowerCase(),paymentMethodCreation:"manual",appearance:Eo}),[Ae,xe,Eo]),[ca,da]=(0,o.useState)("loading"),[ua,pa]=(0,o.useState)("loading"),[ma,ya]=(0,o.useState)("loading"),[zi,To]=(0,o.useState)(!1),[fa,Mo]=(0,o.useState)("loading"),[Yr,Oi]=(0,o.useState)();(0,o.useEffect)(()=>{Oi(Wa())},[]);let ga=I&&(Cn||(Cr?Bi:Yr===!1)),ha=x&&Li,wr=!Je&&ga&&Cn,Pa=fa==="retrying"||fa==="exhausted",kr=!Je&&ga&&!!Ie&&(!Cn||Pa),Rr=!Je&&ha&&!!be,Er=!Je&&x&&Vr&&Wr.length>0&&!!be,Ni=wr&&!Pa?zi:kr&&oi(ca),Ui=Rr&&oi(ua),$i=Er&&ma!=="load_error",ba=i=>i==="loading"||i==="ready",va=wr||kr&&ba(ca)||Rr&&ba(ua)||Er&&ma!=="load_error",Gr=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Gr.current){if(!x&&!I){Gr.current=!0;let i=new zt.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(i),he(i.message)}else if(!x&&I&&!Cn&&!Ie){Gr.current=!0;let i=new zt.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(i),he(i.message)}else if(Yr!==void 0&&!Je&&!lt&&!va){Gr.current=!0;let i=new zt.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});p?.(i),he(i.message)}}},[x,I,Cn,Ie,Yr,Je,lt,va,p,he]);let Ca=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(Ca.current||!Vr)return;let i=[];T!==!0&&i.push("showApplePay"),ce!==!0&&i.push("showGooglePay"),i.length!==0&&(Ca.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Vr,T,ce]);let Sa=(0,o.useCallback)((i,v)=>$e.applyInlineSessionPatch?$e.applyInlineSessionPatch(i).then(J=>({error:null,sessionId:J.sessionId||e,nonce:J.session?.clientSecret||t})).catch(J=>{let oe=ni(v,J);return he(oe.message),p?.(oe),{error:oe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[$e.applyInlineSessionPatch,t,p,e,he]),ln=(0,o.useCallback)(async i=>{if(!pe)return{proceed:!0};try{let v=await pe({method:i,sessionId:e||void 0,createSession:$e.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&rr(oe=>({...oe??{},...v.account}));let J=await Sa(v,i);return J.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:J.sessionId,nonce:J.nonce}}return{proceed:!0}}catch(v){let J=ni(i,v);return he(J.message),p?.(J),{proceed:!1}}},[Sa,$e.inlineSessionDraft,pe,p,e,he]),wa=(0,o.useCallback)(async(i,v)=>{if(A.current)return;A.current=!0,Jt(!0),qe("processing"),he(null);let J=v?.sessionId??e,oe=v?.nonce??t,H=qo(m,v?.accountPatch),Pe=v?.completionPaymentMethodId??Fr(i),Ee=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i;try{let Pt=await new pn.PaymentAPI(G).processPayment(H.userId??"",{sessionId:J,nonce:oe,tokenizedData:Ee,accountData:{userId:H.userId??"",email:H.email??"",firstName:H.firstName??"",lastName:H.lastName??"",...ae?(()=>{let ve=St.current,_t=(0,C.isAVSFieldVisible)(ae.state,ve),Vt=(0,C.isAVSFieldVisible)(ae.address_line_1,ve),Jn=(0,C.isAVSFieldVisible)(ae.postal_code,ve),Xn=Vt&&!_t&&Jn?(0,C.getStateFromPostalCode)(ve,(Mt.current??"").trim()):null,xt=_t?Bt.current:Xn;return{country:ve,...Jn&&Mt.current?{zip:Mt.current}:{},...(0,C.isAVSFieldVisible)(ae.city,ve)&&At.current?{city:At.current}:{},...xt?{state:xt}:{},...Vt&&Qt.current?{addressLine1:Qt.current}:{},...(0,C.isAVSFieldVisible)(ae.address_line_2,ve)&&Zt.current?{addressLine2:Zt.current}:{}}})():{}},chv:E,avsCheck:ge??!1,checkoutType:B,checkoutLayout:fe,avsConfig:ae?{country:(0,C.isAVSFieldVisible)(ae.country,St.current),postal_code:(0,C.isAVSFieldVisible)(ae.postal_code,St.current),address_line_1:(0,C.isAVSFieldVisible)(ae.address_line_1,St.current),address_line_2:(0,C.isAVSFieldVisible)(ae.address_line_2,St.current),city:(0,C.isAVSFieldVisible)(ae.city,St.current),state:(0,C.isAVSFieldVisible)(ae.state,St.current)}:void 0});if(Pt.ok){let ve=Pt.status===204?null:await Pt.json().catch(()=>null),_t=(0,C.isAuthorizationOnlySession)(z)||ve?.status==="authorized";yr(J),qe("success"),Re(null),await new Promise(Vt=>setTimeout(Vt,Mn)),c?.(_t?{status:"authorized",...typeof ve?.paymentId=="string"?{paymentId:ve.paymentId}:z?.paymentId?{paymentId:z.paymentId}:{},sessionId:typeof ve?.sessionId=="string"?ve.sessionId:J,...typeof ve?.authorizationExpiresAt=="string"?{authorizationExpiresAt:ve.authorizationExpiresAt}:z?.authorizationExpiresAt?{authorizationExpiresAt:z.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Pe,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Pe,checkoutMethod:i.isPaypal?"paypal":"card"});return}let nt=await Pt.json().catch(()=>null);if(nt?.type==="paypal_redirect_required"){let ve=nt.threeDSecureToken,_t=nt.paymentMethodId||i.id||"";if(!Ke||!ve){qe("error"),he("PayPal authorization required but no token provided.");return}try{let Vt=mt?.getRawProvider();if(!Vt){he("PayPal is not available.");return}let Jn={return_url:window.location.href};_t&&(Jn.payment_method=_t);let{error:Xn}=await Vt.confirmPayment({clientSecret:ve,confirmParams:Jn,redirect:"if_required"});if(Xn){qe("error");let xt=Xn.message??"PayPal payment failed.";he(xt),sn("paypal",xt,{code:Xn.code})}}catch(Vt){qe("error"),he(Vt instanceof Error?Vt.message:"PayPal authorization failed.")}return}if(nt?.type==="paypal_direct_required"){let ve=nt.orderId;if(!ve){qe("error"),he("PayPal retry required but no order id provided.");return}let _t=y.current?.attempts??0;if(_t>=2){qe("error"),he("PayPal payment could not be completed after multiple attempts."),sn("paypal","paypal_direct_required retry limit exceeded");return}To(!1),Mo("loading"),Re({orderId:ve,attempts:_t+1}),qe(null);return}qe("error");let wt=nt?.message??"Payment failed. Please try again.";he(wt),sn(i.isPaypal?"paypal":"card",wt,{code:nt?.code??nt?.gatewayErrorCode,declineCode:nt?.declineCode??nt?.gatewayDeclineReason}),await new Promise(ve=>setTimeout(ve,Sn))}catch(ct){qe("error"),he(ct instanceof Error?ct.message:"An unexpected error occurred"),await new Promise(Pt=>setTimeout(Pt,Sn))}finally{Jt(!1),qe(null),A.current=!1}},[G,e,t,m,V,E,Ke,mt,z,c,p,he,sn]),rn=(0,o.useCallback)((i,v)=>{S?S(i):wa(i,v)},[S,wa]),ka=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||ka.current)return;let i=new URLSearchParams(window.location.search),v=i.get("payment_intent"),J=i.get("payment_intent_client_secret"),oe=i.get("redirect_status");if(!v||!J)return;let H=wt=>{let ve=localStorage.getItem(wt);if(!ve)return null;try{return JSON.parse(ve)}catch{return localStorage.removeItem(wt),null}},Pe=H(kn)??H(Za),Ee;if(Pe?.clientSecret){if(Pe.clientSecret!==J)return;Ee={...Pe.accountPatch?{accountPatch:Pe.accountPatch}:{},...Pe.sessionId?{sessionId:Pe.sessionId}:{},...Pe.nonce?{nonce:Pe.nonce}:{}}}else if(Pe?.sessionId&&Pe.sessionId!==e)return;ka.current=!0,localStorage.removeItem(kn),localStorage.removeItem(Za);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 Pt=Pe?.paymentMethodType??Pe?.tokenType??"card",nt="card";(async()=>{let wt=Ke?.getRawProvider();if(!wt){let xt="Payment is not available \u2014 please refresh and try again.";he(xt),sn(nt,xt);return}if(oe==="failed"){let xt="Payment was declined. Please try again.";he(xt),sn(nt,xt);return}let{paymentIntent:ve,error:_t}=await wt.retrievePaymentIntent(J);if(_t){let xt=_t.message??"Failed to retrieve payment status.";he(xt),sn(nt,xt,{code:_t.code});return}let Vt=ve?.status,Jn=so(Vt);if(!ve||!Jn){let xt=Vt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";he(xt),sn(nt,xt,{code:Vt??"missing_payment_intent"});return}let Xn=typeof ve.payment_method=="string"?ve.payment_method:ve.payment_method?.id;rn({id:Xn??Pe?.paymentMethodId??Pe?.tokenId??ve.id,type:"card",threeDSecureActionResultTokenId:ve.id,gateway:Pe?.gateway??"stripe",paymentMethodType:Pt},Ee)})()},[e,rn,Ke,he,sn]);let Ao=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(Ke!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Ir=ne==="buttons",jt=Y?.variables,qi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Bo=jt?.colorBackground,ji=Bo&&!qi.has(Bo)?Bo:void 0,_r=f.cardInputBorder??(Ir?"#e5e7eb":"#A4A4FF"),Fo=jt?.colorDanger??"#dc2626",Wn=i=>It&&i?Fo:_r,Jr=(Dt.malformed||Dt.empty)&&(an||It),Vi=Jr?Fo:Wn(gt.zip),Do=f.cardFormContainer?.backgroundColor??ji??(Ir?"white":"#EDEDFF"),xr=f.cardInputBackground??jt?.colorBackground??"white",Lo=ir(L),Ra=ir(re),ar=f.nameInput,Ea=f.cardInputFontSize??Es(ar?.fontSize)??jt?.fontSizeBase??"16px",Ia=typeof ar?.fontFamily=="string"?ar.fontFamily:jt?.fontFamily??"Poppins, sans-serif",_a=ri(ar?.fontWeight)??400,Ki=f.cardInputColor??(typeof ar?.color=="string"?ar.color:void 0)??jt?.colorText??"#262833",Hi=f.cardInputPlaceholderColor??"#9ca3af",ht=jt?.borderRadius??"8px",Yn=jt?.borderRadius??f.cardButton?.borderRadius??ht,Gn=jt?.colorPrimary??"#4A49FF",Wi=jt?.colorPrimaryHover??po(Gn,.12),zo=jt?.colorText??"#262833",xa={fontSize:Ea,fontFamily:Ia,fontWeight:_a,color:Ki,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Yi={"--flopay-input-placeholder-color":Hi,"--flopay-input-font-size":Ea,"--flopay-input-font-family":Ia,"--flopay-input-font-weight":String(_a)},Tr=f.cardFormContainer??{},Oo=Tr.padding??(Ir?"0":"1rem"),No=Tr.borderRadius??ht,Gi=at&&Ot?(0,l.jsx)(cr,{capture:at,html:Ot.html,messageToken:Ot.messageToken,expectedOrigin:Ot.expectedOrigin,theme:ze,onReady:()=>{if(!ae||typeof document>"u")return;let i=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};i();let v=0,J=window.setInterval(()=>{v+=1;let oe=document.activeElement;!!oe&&oe.tagName==="IFRAME"&&oe.id==="flopay_vault_form_iframe"?(i(),window.clearInterval(J)):v>=50&&window.clearInterval(J)},100)},onError:i=>he(i),onValidation:i=>{let v=F.current;(v==="idle"||v==="validation-window")&&(he(i),i&&F.current==="validation-window"&&(j.current&&(clearTimeout(j.current),j.current=null),F.current="idle",qe(null)))}}):(0,l.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"}),Ta=(0,l.jsxs)("div",{style:{backgroundColor:Do,borderRadius:No,...Tr,padding:Oo,...Yi,display:"flex",flexDirection:"column"},children:[(0,l.jsx)("style",{children:`
|
|
31
31
|
.flopay-shared-input::placeholder {
|
|
32
32
|
color: var(--flopay-input-placeholder-color);
|
|
33
33
|
opacity: 1;
|
|
@@ -35,13 +35,13 @@ ${He.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),
|
|
39
|
-
`)}):null,
|
|
40
|
-
`)}):null,Sa=Le==="apm-expanding"||Le==="apm-form"||Le==="apm-collapsing",qr=Le==="apm-expanding"?`flopay-card-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:Le==="apm-collapsing"?`flopay-card-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,jr=Ct?{...ho,paymentMethodTypes:[Ct]}:null;if(ae==="buttons"){let a=Le==="buttons"||Le==="expanding"||Le==="apm-expanding",C=Le==="expanding"||Le==="card"||Le==="collapsing",H=W===void 0?{boxSizing:"border-box",height:no,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ne=Le==="expanding"||Le==="apm-expanding"?`flopay-buttons-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Le==="collapsing"||Le==="apm-collapsing"?`flopay-buttons-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,j=Le==="expanding"?`flopay-card-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:Le==="collapsing"?`flopay-card-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,i.jsxs)("form",{onSubmit:vo,className:k,style:{position:"relative"},children:[(0,i.jsx)(Fo,{}),Et&&(0,i.jsx)(Sn,{status:Et,errorMessage:c}),(0,i.jsxs)("div",{style:{display:"grid"},children:[(0,i.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!ne?ls:{},...ne?{animation:ne,pointerEvents:"none"}:{}},children:[va("flopay-direct-paypal-gate-debug"),Ca("flopay-stripe-gate-debug"),fr&&He&&(0,i.jsxs)(i.Fragment,{children:[X&&(0,i.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,i.jsx)(Er,{sessionId:e,nonce:t,billingApiUrl:u,email:y.email,clientId:He.clientId,environment:He.environment,currency:$e.toUpperCase(),isSubscription:ot,onTokenizedBody:tn,onComplete:s,onErrorChange:ge,onDecline:d,onTechnicalFailure:er,onButtonClick:we,runBeforeButtonClick:cn,isProcessing:Se,onLoadStateChange:Po,onInitializationStateChange:bo,session:V??null,existingOrderId:X?.orderId,debug:tt},X?.orderId??"fresh")]}),gr&&(0,i.jsx)(lt.Elements,{stripe:Ve,options:Go,children:(0,i.jsx)(Ya,{sessionId:e,nonce:t,email:y.email,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:ge,isProcessing:Se,onButtonClick:we,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:Zo,placeholderBorderRadius:Kn})}),hr?(0,i.jsx)(lt.Elements,{stripe:q,options:Yo,children:(0,i.jsx)(Ga,{sessionId:e,nonce:t,email:y.email,billingApiUrl:u,intentKind:oe>0?"payment":"setup",expressMethods:Lr,onTokenizedBody:tn,onErrorChange:ge,onButtonClick:we,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:ta,placeholderBorderRadius:Kn})}):ia?(0,i.jsx)("div",{style:{height:no,borderRadius:Kn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Pr&&(0,i.jsx)(Ja,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,paymentElementMethods:Nr,stripeInstance:q,paymentElementBaseOptions:ho,onTokenizedBody:tn,onErrorChange:ge,onButtonClick:we,onDecline:d,runBeforeButtonClick:cn,onLoadStateChange:ra,isProcessing:Se,submitButtonColor:Hn,submitButtonBorderRadius:mt,submitButtonStyle:f.submitButton,onExpandApm:sn,expandedApmMethod:Ct,themeId:U,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Kn}}),qe&&(0,i.jsx)("button",{type:"button",onClick:async()=>{Se||!(await cn("card")).proceed||(we?.("card"),kn())},disabled:Se,style:{width:"100%",...H,...f.cardButton,...No({themeBundle:L,resolvedPrimaryColor:Hn,resolvedBorderRadius:mt,submitButtonStyle:f.submitButton,explicitPrimaryColor:Yt?.colorPrimary}),fontSize:f.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Se?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Se?.6:1},onMouseEnter:ve=>{!Se&&(L||Yt?.colorPrimary)&&(ve.currentTarget.style.backgroundColor=Fi)},onMouseLeave:ve=>{(L||Yt?.colorPrimary)&&(ve.currentTarget.style.backgroundColor=Hn)},onMouseDown:ve=>{ve.currentTarget.style.transform="scale(0.985)"},onMouseUp:ve=>{ve.currentTarget.style.transform="scale(1)"},children:(0,i.jsx)(rr,{content:W})}),c&&Le==="buttons"&&(0,i.jsx)(ar,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:c})]}),qe&&C&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...j?{animation:j}:{},...Le==="collapsing"?{pointerEvents:"none"}:{}},children:ba}),M&&Sa&&Ct&&jr&&q&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...qr?{animation:qr}:{},...Le==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:wo,borderRadius:Eo,...Sr,padding:Io},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,i.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Qt,style:{display:"inline-flex",alignItems:"center",gap:ko?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(or,{content:J})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Ro,paddingRight:80,...f.title},children:`Pay with ${(0,R.getStripeMethodDisplayName)(Ct)}`})]}),(0,i.jsx)(lt.Elements,{stripe:q,options:jr,children:(0,i.jsx)(Do,{method:Ct,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:ge,onDecline:d,onCancel:Qt,runBeforeButtonClick:cn,onButtonClick:we,isProcessing:Se,submitButtonColor:Hn,submitButtonBorderRadius:mt,submitButtonStyle:f.submitButton,errorText:c})},Ct)]})})]})]})}return Sa&&Ct&&jr&&q&&M?(0,i.jsxs)("form",{onSubmit:vo,className:k,style:{position:"relative"},children:[(0,i.jsx)(Fo,{}),Et&&(0,i.jsx)(Sn,{status:Et,errorMessage:c}),(0,i.jsx)("div",{style:{...qr?{animation:qr}:{},...Le==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:wo,borderRadius:Eo,...Sr,padding:Io},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,i.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Qt,style:{display:"inline-flex",alignItems:"center",gap:ko?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(or,{content:J})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Ro,paddingRight:80,...f.title},children:`Pay with ${(0,R.getStripeMethodDisplayName)(Ct)}`})]}),(0,i.jsx)(lt.Elements,{stripe:q,options:jr,children:(0,i.jsx)(Do,{method:Ct,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:ge,onDecline:d,onCancel:Qt,runBeforeButtonClick:cn,onButtonClick:we,isProcessing:Se,submitButtonColor:Hn,submitButtonBorderRadius:mt,submitButtonStyle:f.submitButton,errorText:c})},Ct)]})})]}):(0,i.jsxs)("form",{onSubmit:vo,className:k,style:{position:"relative"},children:[(0,i.jsx)(Fo,{}),Et&&(0,i.jsx)(Sn,{status:Et,errorMessage:c}),(0,i.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[va("flopay-direct-paypal-gate-debug-default"),Ca("flopay-stripe-gate-debug-default"),fr&&He&&(0,i.jsxs)(i.Fragment,{children:[X&&(0,i.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,i.jsx)(Er,{sessionId:e,nonce:t,billingApiUrl:u,email:y.email,clientId:He.clientId,environment:He.environment,currency:$e.toUpperCase(),isSubscription:ot,onTokenizedBody:tn,onComplete:s,onErrorChange:ge,onDecline:d,onTechnicalFailure:er,onButtonClick:we,runBeforeButtonClick:cn,isProcessing:Se,onLoadStateChange:Po,onInitializationStateChange:bo,session:V??null,existingOrderId:X?.orderId,debug:tt},X?.orderId??"fresh")]}),gr&&(0,i.jsx)(lt.Elements,{stripe:Ve,options:Go,children:(0,i.jsx)(Ya,{sessionId:e,nonce:t,email:y.email,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:ge,isProcessing:Se,onButtonClick:we,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:Zo,placeholderBorderRadius:Kn})}),hr&&(0,i.jsx)(lt.Elements,{stripe:q,options:Yo,children:(0,i.jsx)(Ga,{sessionId:e,nonce:t,email:y.email,billingApiUrl:u,intentKind:oe>0?"payment":"setup",expressMethods:Lr,onTokenizedBody:tn,onErrorChange:ge,onButtonClick:we,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:ta,placeholderBorderRadius:Kn})}),Pr&&(0,i.jsx)(Ja,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,paymentElementMethods:Nr,stripeInstance:q,paymentElementBaseOptions:ho,onTokenizedBody:tn,onErrorChange:ge,onButtonClick:we,onDecline:d,runBeforeButtonClick:cn,onLoadStateChange:ra,isProcessing:Se,submitButtonColor:Hn,submitButtonBorderRadius:mt,submitButtonStyle:f.submitButton,themeId:U,onExpandApm:sn,expandedApmMethod:Ct,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Kn}})]}),qe&&(Ei||Ii||_i)&&(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,i.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,i.jsx)("span",{children:"or pay with card"}),(0,i.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),qe&&ba]})}var cr=require("@flopay/js"),je=require("@flopay/shared");var Tr="card";async function gs(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:m}=await e.retrieveSetupIntent(t);return{error:m,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:l,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:l??null}}async function hs(e,t,n,l){if(l){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:m,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:m??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:s}=await e.confirmCardPayment(t,n);return{error:s,intent:o??null}}function zo(e,t){return Object.assign(e,{checkoutMethod:t})}function Mn(e,t){let n=e instanceof je.FloPayError?e:new je.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function xr(e,t){try{return await e()}catch(n){throw Mn(n,t)}}function ni(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Ps(e){return e.status==="succeeded"||e.status==="declined"}async function ri(e){if(typeof document>"u"||typeof window>"u")throw new je.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,l=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,s=async()=>{let b=new AbortController,_=()=>b.abort();e.signal?.aborted?b.abort():e.signal?.addEventListener("abort",_);let k=window.setTimeout(()=>b.abort(),l);try{let F=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:b.signal});if(!F.ok)return{status:"unknown"};let p=await F.json().catch(()=>null);return bs(p)}catch{return{status:"unknown"}}finally{window.clearTimeout(k),e.signal?.removeEventListener("abort",_)}},m=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let I=document.createElement("iframe");I.setAttribute("title","Card authentication"),I.setAttribute("allow","payment"),I.tabIndex=0,I.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),I.src=e.nextActionRedirectUrl,d.appendChild(I),document.body.appendChild(d),I.focus();let N=null;try{N=new URL(e.billingApiUrl,window.location.href).origin}catch{N=null}try{let b=await new Promise((_,k)=>{let F=!1,p=0,v=0,x=0,M=!1,g=()=>{window.clearTimeout(p),window.clearInterval(v),window.clearTimeout(x),window.removeEventListener("message",ae),I.removeEventListener("load",z),e.signal?.removeEventListener("abort",ue)},he=async()=>{if(!(F||M)){M=!0;try{let U=await s();if(F||!Ps(U))return;F=!0,g(),_(U)}finally{M=!1}}},z=()=>{window.clearTimeout(x),x=window.setTimeout(()=>{he()},250)},ue=()=>{F||(F=!0,g(),k(new je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ae=U=>{if(U.source!==I.contentWindow||N&&U.origin!==N)return;let te=U.data;!te||typeof te!="object"||te.source!=="flopay-vault-3ds-return"||F||(F=!0,g(),_(null))};p=window.setTimeout(()=>{F||(F=!0,g(),k(new je.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),v=window.setInterval(()=>{he()},n),I.addEventListener("load",z),window.addEventListener("message",ae),e.signal?.addEventListener("abort",ue),e.signal?.aborted&&ue()});return b||await s()}finally{d.parentNode?.removeChild(d),m?.isConnected&&m.focus()}}function bs(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Un(e,t="Payment failed. Please try again.",n){let l=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,s=On(o)??o;return zo(new je.FloPayError(s,"api_error",{code:e?.gatewayErrorCode}),l)}function Oo(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ao(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function vs(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function oi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ao(o)))return o;let l=e?.data;if(l&&typeof l=="object"){let o=l,s=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let d of s)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||ao(d)))return d;let m=o.gateways;if(m&&typeof m=="object"){let d=m.stripe;if(d&&typeof d=="object"){let I=d,N=[I.stripeClientSecret,I.clientSecret];for(let b of N)if(typeof b=="string"&&b.length>0&&(!t?.requirePaymentIntentClientSecret||ao(b)))return b}}}}async function Cs({billingApiUrl:e,sessionId:t,nonce:n,responseJson:l}){let o=oi(l,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new cr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ao(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function dr({billingApiUrl:e,sessionId:t,session:n,nonce:l,tokenizedData:o,returnUrl:s,telemetry:m}){let d=e.replace(/\/+$/,""),I=t??n.id,N=l??n.clientSecret,b=n.customer?.id??n.accountData?.userId??"",_=n.customer?.email??n.accountData?.email??"",k=n.customer?.firstName??n.accountData?.firstName??"",F=n.customer?.lastName??n.accountData?.lastName??"",p=n.customer?.country??n.accountData?.country??void 0,v=n.customer?.zip??n.accountData?.zip??void 0,x=new cr.PaymentAPI(d,m===!1?{telemetry:!1}:void 0),M=await vs(()=>x.processPayment(b,{sessionId:I,nonce:N,tokenizedData:o,accountData:{userId:b,email:_,firstName:k,lastName:F,country:p,zip:v},returnUrl:s??Oo(n)}));if(M.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Xr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let g;try{g=await M.json()}catch{throw new je.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:M.status})}if(g?.type==="paypal_redirect_required"||g?.type==="3ds_required"){let z=oi(g);if(!z)throw new je.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:M.status});return{type:g.type,threeDSecureToken:z,paymentMethodId:g.paymentMethodId}}if(g?.gatewayErrorCode==="authentication_required"){let z=await Cs({billingApiUrl:d,sessionId:I,nonce:N,responseJson:g});if(z)return z;throw zo(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let he=new je.FloPayError(g?.message??"Payment failed. Please try again.","api_error",{code:g?.code??g?.gatewayErrorCode,declineCode:g?.declineCode??g?.gatewayDeclineReason,statusCode:M.status});throw Object.assign(he,{telemetryOutcome:(0,je.classifyPaymentRejection)(M.status,g)})}async function io(e,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:m,returnUrl:d,telemetry:I}){let N=t?.getRawProvider();if(!N)throw Mn(new je.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!l||!e.threeDSecureToken)throw zo(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let b=(0,je.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,k=e.paymentMethodId,F=await xr(()=>gs(N,e.threeDSecureToken,b),"card");if(F){if(F.error)throw Mn(new je.FloPayError(F.error.message??`Failed to retrieve 3DS ${b?"setup":"payment"} status.`,"api_error",{code:F.error.code}),"card");let v=F.intent;!k&&v?.payment_method&&(typeof v.payment_method=="string"?k=v.payment_method:"id"in v.payment_method&&(k=v.payment_method.id??void 0))}let p=k?await xr(()=>hs(N,e.threeDSecureToken,{payment_method:k,return_url:d??Oo(m)??window.location.href},b),"card"):null;if(p){if(p.error)throw Mn(new je.FloPayError(p.error.message??"3DS authentication failed.","api_error",{code:p.error.code}),"card");_=p.intent}else{let v=await xr(()=>N.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(v.error)throw Mn(new je.FloPayError(v.error.message??"3DS authentication failed.","api_error",{code:v.error.code}),"card");_=(b?v.setupIntent:v.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let v=await dr({billingApiUrl:o,sessionId:s,session:m,telemetry:I,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:d});return v.type==="success"?{...v.result,paymentIntentId:v.result.paymentIntentId??_.id,paymentMethodId:v.result.paymentMethodId??k}:io(v,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:m,returnUrl:d,telemetry:I})}throw Mn(new je.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let b=(n??t)?.getRawProvider();if(!b)throw Mn(new je.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:k}=await xr(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(k)throw Mn(new je.FloPayError(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await xr(()=>b.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Oo(m)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(_)throw Mn(new je.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new je.FloPayError("Unsupported payment redirect state.","api_error")}function Jn(e){if(e instanceof je.FloPayError){let l=On(e.message);return l&&l!==e.message?Object.assign(new je.FloPayError(l,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=On(t)??t;return new je.FloPayError(n,"api_error")}function so(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new je.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function lo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:l,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let s=!!t&&t!==e,[m,d]=await Promise.all([(0,cr.loadFloPay)(e,{billingApiUrl:n,locale:l,telemetry:o}),s?(0,cr.loadFloPay)(t,{billingApiUrl:n,locale:l,telemetry:o}).catch(I=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",I),null)):Promise.resolve(null)]);return{flopay:m,paypalFlopay:t?s?d:m:null}}var w=require("react/jsx-runtime"),ur=44,Ho="flopay_checkout_saved_payment_resume",po=new Map,co=new Map;function ai(e,t){t.settled&&t.consumers===0&&po.get(e)===t&&po.delete(e)}function Ss(e,t,n){let l=co.get(e);if(l&&(!l.sdkGeneratedIdempotencyKey||!t||l.sdkGeneratedIdempotencyKey===t))return l.attempt;let o=n(),s={attempt:o,sdkGeneratedIdempotencyKey:t};co.set(e,s);let m=()=>{co.get(e)===s&&co.delete(e)};return o.then(m,m),o}function Mr(e){return new Promise(t=>setTimeout(t,e))}function uo(e,t,n){let l=Kr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Pe.SDK_VERSION,enabled:t!==!1});return l.beginCheckout(n),l}function Br(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Uo(e,t,n,l,o){let s=uo(e,t,n);s.error({errorCode:l,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Br(s)}function ws(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function Vo(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function $o(e){return!e||e.data.stripe?.publishableKey?!1:!!Vo(e)?.clientId}function Bn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ks(){if(!Bn())return null;try{let e=window.sessionStorage.getItem(Ho);return e?JSON.parse(e):null}catch{return null}}function ii(e){if(Bn())try{window.sessionStorage.setItem(Ho,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function qo(){if(Bn())try{window.sessionStorage.removeItem(Ho)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var Wo=":idempotency-key";function Rs(e){if(!Bn())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function si(e,t,n){if(Bn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(l){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",l)}}function Ko(e){if(Bn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function Is(e){if(Bn())try{return window.sessionStorage.getItem(e+Wo)??void 0}catch{return}}function Es(e,t){if(Bn())try{window.sessionStorage.setItem(e+Wo,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function _s(e){if(Ko(e),!!Bn())try{window.sessionStorage.removeItem(e+Wo)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function xs(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let l of t)e.searchParams.has(l)&&(e.searchParams.delete(l),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function li(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function Ts(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function jo(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function mo({sessionId:e,nonce:t,createSession:n,billingApiUrl:l,telemetry:o,appearance:s,locale:m,loading:d,error:I,onComplete:N,onError:b,onDecline:_,onCountryChange:k,onZipChange:F,showPayPal:p=!0,showStripe:v=!0,enabledPaymentMethods:x,showApplePay:M=!0,showGooglePay:g=!0,debug:he=!1,layout:z,theme:ue,buttonsTheme:ae,buttonsStyles:U,cardButtonContent:te,cardBackButtonContent:Q,cardTitleContent:pe,showSecurityFooter:W,onButtonClick:J,onBeforeButtonClick:me,enableAVS:Me,cardFieldOrder:we,cardPreFormSlot:be,avsLayout:ie,className:Ce,initialErrorMessage:Be=null,children:se,checkoutMode:Ee,confirmLabel:_e,renderConfirmButton:Re,onSessionCompleted:Z}){let T=(0,Pe.resolveBillingApiUrl)(l),ce=(0,B.useMemo)(()=>(0,Pe.resolveTheme)(ue),[ue]),Oe=s??ce?.appearance,ze=n?"embedded_checkout":"standard_checkout",ye=se?"custom_layout":z==="buttons"?"buttons_layout":"default_layout",[E,re]=(0,B.useState)(null),[oe,$e]=(0,B.useState)(null),ct=(0,B.useRef)(null),[He,ot]=(0,B.useState)(null),V=(0,B.useRef)(null),[G,tt]=(0,B.useState)(null),[Ae,at]=(0,B.useState)(e??""),Ge=e??Ae,We=n?"":Ge,[rn,h]=(0,B.useState)(!0),[ke,dt]=(0,B.useState)(null),[nt,Qe]=(0,B.useState)("full"),[Ye,Ze]=(0,B.useState)(!1),[xe,Ke]=(0,B.useState)(Be),[kt,Je]=(0,B.useState)(null),[An,Pt]=(0,B.useState)(null),[Fn,on]=(0,B.useState)(void 0),[hn,Zt]=(0,B.useState)(""),[Dn,Nt]=(0,B.useState)(!1),[Rt,qt]=(0,B.useState)(!1),Gt=(0,B.useRef)(0),[Bt,jt]=(0,B.useState)("loading"),[At,le]=(0,B.useState)(0),en=(0,B.useRef)(!1),D=(0,B.useRef)(!1),gt=(0,B.useRef)(!1),ut=(0,B.useRef)(null),bt=(0,B.useMemo)(()=>({checkoutMode:Ee??nt,layout:se?"unknown":z==="buttons"?"buttons":"embedded"}),[Ee,se,nt,z]),Te=(0,B.useRef)(N);Te.current=N;let qe=(0,B.useRef)(b);qe.current=b;let $n=(0,B.useRef)(_);$n.current=_,(0,B.useEffect)(()=>{Mt(oe)?.setCheckoutContext(bt),He&&He!==oe&&Mt(He)?.setCheckoutContext(bt)},[oe,He,bt]);let Ln=(0,B.useRef)(Z);Ln.current=Z;let qn=(0,B.useCallback)(P=>{jt(P),!(P!=="exhausted"||gt.current)&&(gt.current=!0,qe.current?.(new Pe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Zn=(0,B.useCallback)(()=>{jt("retrying"),le(P=>P+1)},[]);(0,B.useEffect)(()=>{jt("loading"),le(0),gt.current=!1},[Ge]),(0,B.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Pe.SDK_VERSION,checkout_type:ze,checkout_layout:ye,billing_api_url:T})},[ye,ze,T]);let Vt=(0,B.useMemo)(()=>n?Pn(n,!0):"",[n]),it=(0,B.useMemo)(()=>hn===Vt?Fn:void 0,[Fn,hn,Vt]),Ft=(0,B.useMemo)(()=>n?xo(n,it):void 0,[n,it]),Kt=Ee??Ft?.checkoutMode??"full",ht=(0,B.useMemo)(()=>Ft?{...Ft,checkoutMode:Kt}:void 0,[Ft,Kt]);(0,B.useEffect)(()=>{on(void 0),Zt(Vt)},[Vt]),(0,B.useEffect)(()=>{Ke(Be)},[Be]);let Jt=(0,B.useCallback)((P,Y,K)=>{st(()=>{$n.current?.(wt(P,Y,K))})},[st]),Ht=(0,B.useCallback)(async(P,Y)=>{Ke(null),Pt(null),Je("processing");let K=Y?.sessionId??P.id,fe=ct.current??V.current,X=Mt(fe),de=fe?null:uo(T,o,bt),S={log:O=>{X?X.log(O):de?.log(O)},error:O=>{X?X.error(O):de?.error(O)},terminal:O=>{X?X.terminal(O):de?.terminal(O)},performance:O=>{X?X.performance(O):de?.performance(O)},now:()=>X?.now()??de?.now()??0,elapsed:O=>X?.elapsed(O)??Math.max(0,(de?.now()??O)-O)},u=S.now(),c=!!(Y?.initialAutoProcessingError||Y?.initialAutoProcessingPending),L=!1,f,ee=()=>{L||(L=!0,c=!0,f=S.now(),S.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ie=!1,rt=()=>{Ie||(Ie=!0,S.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),S.performance({stage:"processing",durationMs:S.elapsed(u),durationMode:"machine",paymentMethodCategory:"saved"}),f!==void 0&&S.performance({stage:"recovery",durationMs:S.elapsed(f),durationMode:"machine",paymentMethodCategory:"saved"}))};S.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),S.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),c&&ee();let Se;try{let O=ni(Y?.initialAutoProcessingError),y;if(O)ee(),O.type==="paypal_redirect_required"&&ut.current?.publishableKey&&ii({sessionId:K,publishableKey:ut.current.publishableKey,paypalPublishableKey:ut.current.paypalPublishableKey}),y=await io(O,{flopay:ct.current,paypalFlopay:V.current,attempt3DS:Y?.attempt3DS,billingApiUrl:T,sessionId:K,session:P,telemetry:!1}),O.type==="paypal_redirect_required"&&qo();else if(Y?.initialAutoProcessingPending){let q=await new Xn.PaymentAPI(T,{telemetry:!1}).waitForCheckoutSessionCompletion(Y.initialAutoProcessingPending.sessionId,{initialDelayMs:Y.initialAutoProcessingPending.retryAfterMs});if(q.data.session?.status!=="complete")throw new Pe.FloPayError("Automatic payment failed. Please try again.","api_error",{code:q.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});y={status:"succeeded"}}else{if(Y?.initialAutoProcessingError)throw Un(Y.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Y.initialAutoProcessingError.checkoutMethod});if(Y?.fromCreateSession)return Y?.fallbackToFull&&(Qe("full"),li("full")),!1;{let $=await dr({billingApiUrl:T,sessionId:K,session:P,telemetry:!1});$.type==="success"?y=$.result:(ee(),$.type==="paypal_redirect_required"&&ut.current?.publishableKey&&ii({sessionId:K,publishableKey:ut.current.publishableKey,paypalPublishableKey:ut.current.paypalPublishableKey}),y=await io($,{flopay:ct.current,paypalFlopay:V.current,attempt3DS:Y?.attempt3DS,billingApiUrl:T,sessionId:K,session:P,telemetry:!1}),$.type==="paypal_redirect_required"&&qo())}}K&&sr(K),rt(),c&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),S.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Je("success"),await Mr(_n),Se=()=>Te.current?.(y)}catch(O){let y=Jn(O),$=y.checkoutMethod??Tr;Ke(y.message),Pt(y.message),Y?.fallbackToFull&&(S.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Qe("full"),li("full")),rt();let q=y.statusCode!==void 0?(0,Pe.telemetryStatusClass)(y.statusCode,"unknown"):void 0,Ve=q==="4xx"?{requestCategory:"process_payment",statusClass:q}:{},pt=q===void 0||q==="4xx";if(pt&&(y.telemetryOutcome==="payment_declined"||!!(y.declineCode||y.code?.toLowerCase().includes("declin"))))S.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ve});else if(pt&&(y.telemetryOutcome==="validation_rejected"||y.type==="validation_error"))S.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ve});else{let Ar=(0,Pe.classifyTelemetryFailure)(O,c?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");S.error({...Ar,...y.telemetryFailureCategory?{failureCategory:y.telemetryFailureCategory}:{},stage:c?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:y.telemetryRequestCategory??"process_payment"})}return st(()=>qe.current?.(y)),Jt($,y,{code:y.code,declineCode:y.declineCode}),Je("error"),await Promise.allSettled([Mr(Cn),Y?.ensureProvidersReady?Y.ensureProvidersReady():Promise.resolve()]),c&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{rt(),de&&Br(de),Je(null),Pt(null)}return st(Se),!0},[Jt,st,Jn,T,o,bt]);(0,B.useEffect)(()=>{if(typeof window>"u"||D.current)return;let P=new URLSearchParams(window.location.search),Y=P.get("payment_intent_client_secret");if(!Y)return;let K=ks();K&&(D.current=!0,(async()=>{let fe,X=0;Ke(null),Pt(null),Je("processing"),Ze(!0);try{if(P.get("redirect_status")==="failed")throw Object.assign(new Pe.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:de,paypalFlopay:S}=await lo({publishableKey:K.publishableKey,paypalPublishableKey:K.paypalPublishableKey,billingApiUrl:T,locale:m,telemetry:o});fe=Mt(S??de),X=fe?.now()??0,fe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let u=(S??de)?.getRawProvider();if(!u)throw Object.assign(new Pe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:c,error:L}=await u.retrievePaymentIntent(Y);if(L)throw Object.assign(new Pe.FloPayError(L.message??"Failed to retrieve PayPal payment status.","api_error",{code:L.code}),{checkoutMethod:"paypal"});let f=Fa(c?.status);if(!c||f==="failed")throw Object.assign(new Pe.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let ee=typeof c.payment_method=="string"?c.payment_method:c.payment_method?.id,Ie=f;if(K.sessionId){let O=(await new Xn.PaymentAPI(T,{telemetry:!1}).getUnifiedCheckoutSession(K.sessionId)).data.session;if(O&&O.status!=="complete"){let y=await dr({billingApiUrl:T,sessionId:K.sessionId,session:O,telemetry:!1,tokenizedData:{id:ee??c.id,type:"card",threeDSecureActionResultTokenId:c.id,isPaypal:!0}});if(y.type!=="success")throw Object.assign(new Pe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Ie=y.result.status}}K.sessionId&&sr(K.sessionId),fe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.performance({stage:"redirect_resume",durationMs:fe.elapsed(X),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Je("success"),await Mr(_n),st(()=>Te.current?.({status:Ie,paymentIntentId:c.id,paymentMethodId:ee,checkoutMethod:"paypal"}))}catch(de){let S=Jn(de),u=S.checkoutMethod??"paypal",c=!!(S.declineCode||S.code?.toLowerCase().includes("declin"));if(fe)fe.performance({stage:"redirect_resume",durationMs:fe.elapsed(X),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),c?fe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):fe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(c){let L=uo(T,o,bt);L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Br(L)}else Uo(T,o,bt,"REDIRECT_RESUME_FAILED","redirect_resume");Ke(S.message),Pt(S.message),st(()=>qe.current?.(S)),Jt(u,S,{code:S.code,declineCode:S.declineCode}),Je("error"),await Mr(Cn)}finally{qo(),xs(),Je(null),Pt(null),Ze(!1)}})())},[Jt,st,m,Jn,T,o]);let an=(0,B.useRef)(null);function Pn(P,Y=!1){let K=P?.account?.email?.trim().toLowerCase()??"",fe={c:P?.clientId,cur:P?.currency??"",a:{e:K,u:K?"":P?.account?.userId??"",country:P?.account?.country??""},successUrl:P?.successUrl,cancelUrl:P?.cancelUrl,p:P?.products?.map(S=>jo(`${S.type??""}:${S.code??S.providerItemId??S.providerPlanId??""}`,S)).sort(),i:P?.items?.map(S=>jo(S.code??S.providerItemId??"",S)).sort(),s:P?.subscriptions?.map(S=>jo(S.code??S.providerPlanId??"",S)).sort(),couponCodes:P?.couponCodes?[...P.couponCodes].sort():void 0,...Y?{tagsData:P?.tagsData,utmMetadata:P?.utmMetadata,tokenizedData:P?.tokenizedData,checkoutMode:P?.checkoutMode??"full"}:{}},X=JSON.stringify(fe),de=0;for(let S=0;S<X.length;S++)de=(de<<5)-de+X.charCodeAt(S)|0;return`flopay_session_${Math.abs(de).toString(36)}`}let It=(0,B.useMemo)(()=>ht?Pn(ht):"",[ht]),Ot=(0,B.useRef)(ht);Ot.current=ht,(0,B.useEffect)(()=>{at(e??"")},[e]),(0,B.useEffect)(()=>{en.current=!1,Ke(Be),Pt(null),Je(null)},[It,Be,e]);async function Le(P,Y){let K=uo(T,o,bt),fe=new Xn.PaymentAPI(T,{telemetry:!1}),X=!1;try{let de=P.idempotencyKey!==void 0?(0,Pe.resolveIdempotencyKey)(P.idempotencyKey):void 0,S=de??Is(Y),u,c=!1,L=Rs(Y);K.log({name:L?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let f=L?.sid??null,ee=null,Ie;if(f)try{if(ee=await fe.getUnifiedCheckoutSession(f,L?.nonce),ee.data.session?.status==="complete"){if(Mo(f))return{sid:f,result:ee};_s(Y),f=null,ee=null,c=!0}}catch{K.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ko(Y),f=null}if(!f){!de&&(c||!S)&&(S=(0,Pe.resolveIdempotencyKey)(),u=S),S&&Es(Y,S);let rt=K.now(),Se=0;K.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let O={...P,idempotencyKey:S,avsCheck:!!Me,avsConfig:typeof Me=="object"?Me:void 0,checkoutType:"embedded_checkout",checkoutLayout:se?"custom_layout":z==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(O,Xn.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:q=>{Se=Math.max(Se,q)}}});let y=()=>{K.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),K.performance({stage:"session_create",durationMs:K.now()-rt,durationMode:"machine",requestCategory:"session_create",attempt:Se,statusClass:"2xx"})},$=q=>{let Ve=(0,Pe.classifyTelemetryFailure)(q,"CHECKOUT_SESSION_CREATE_FAILED","unknown");K.performance({stage:"session_create",durationMs:K.now()-rt,durationMode:"machine",requestCategory:"session_create",attempt:Se,statusClass:Ve.statusClass}),q instanceof Pe.FloPayError&&q.type==="validation_error"?K.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):Ve.statusClass==="4xx"?K.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):K.error({...Ve,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if((0,Pe.isDetachedSessionEligible)(O)){let q=await fe.createDetachedSession(O);q.claimed.catch(()=>{}),ee=q.shell,f=q.sessionId,Ie=q.claimed.then(Ve=>{let pt=Ve.data.session?.id??q.sessionId;return pt&&si(Y,pt,Ve.data.session?.clientSecret??q.nonce),y(),Ve},Ve=>{throw Ko(Y),$(Ve),Ve}).finally(()=>Br(K)),Ie.catch(()=>{}),X=!0,K.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),K.performance({stage:"session_shell",durationMs:K.now()-rt,durationMode:"machine",requestCategory:"session_create",attempt:Se,statusClass:"2xx",paymentMethodCategory:"card"})}else ee=await fe.createAndFetchSession(O),y()}catch(q){throw $(q),q}f=ee.data.session?.id??f??"",f&&!Ie&&si(Y,f,ee.data.session?.clientSecret)}return{sid:f??"",result:ee,sdkGeneratedIdempotencyKey:u,...Ie?{claimed:Ie}:{}}}finally{X||Br(K)}}let vt=(0,B.useCallback)(async(P,Y)=>{let K=Ot.current;if(!K)throw new Pe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let fe=xo(K,P),X=Pn(fe),de=po.get(X);if(!de){let c={promise:Le(fe,X),consumers:0,settled:!1};de=c,po.set(X,c);let L=()=>{c.settled=!0,ai(X,c)};c.promise.then(L,L)}de.consumers+=1;let S=!1,u=()=>{S||(S=!0,de.consumers-=1,ai(X,de))};Y?.(u);try{let c=await de.promise;an.current=X,P&&(Zt(Vt),on(y=>Ba(y,P)));let{sid:L,result:f,claimed:ee}=c;if(re(f),f.data.session&&tt(f.data.session),L&&at(L),ee){let y=Gt.current+=1;qt(!0),ee.then($=>{Gt.current===y&&(re($),$.data.session&&tt($.data.session),qt(!1))},$=>{Gt.current===y&&(qt(!1),dt($ instanceof Pe.FloPayError?$:new Pe.FloPayError($ instanceof Error?$.message:"Failed to create session","api_error")))})}else Gt.current+=1,qt(!1);let{publishableKey:Ie,paypalPublishableKey:rt}=so(f),{flopay:Se,paypalFlopay:O}=await lo({publishableKey:Ie,paypalPublishableKey:rt,billingApiUrl:T,locale:m,telemetry:o});return ct.current=Se,$e(Se),V.current=O,ot(O),h(!1),c}catch(c){throw an.current===X&&(an.current=null),c}finally{Y||u()}},[m,T,o,bt]),Ct=(0,B.useRef)(Ht);Ct.current=Ht;let bn=(0,B.useRef)(vt);bn.current=vt;let jn=(0,B.useCallback)(async P=>{if(!Ts(P)||Dn)return{sessionId:Ae,session:G};Nt(!0);try{let Y=await vt(P);return{sessionId:Y.sid,session:Y.result.data.session??null}}finally{Nt(!1)}},[vt,Dn,Ae,G]);(0,B.useEffect)(()=>{let P=!1,Y;if(dt(null),It){let X=Ot.current;return Qe(Kt),h(!1),an.current===It?()=>{P=!0}:(tt(Aa(X,Ee)),(async()=>{let de=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),S=Kt==="auto"&&!en.current&&!de;S&&(Ke(null),Pt(null),Je("processing"));try{let u=await bn.current(void 0,ee=>{Y=ee}),c=u.result.data.session??null;ut.current=so(u.result);let L=$o(u.result),f=Mo(u.sid||c?.id);if(!P&&S&&c&&!L&&!f){en.current=!0,await Ss(It,u.sdkGeneratedIdempotencyKey,()=>Ct.current(c,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:u.result.autoProcessingError,initialAutoProcessingPending:u.result.autoProcessingPending,autoProcessingAttempted:u.result.autoProcessingAttempted,sessionId:u.sid||c.id}));return}!P&&S&&((L||f)&&(en.current=!0),Je(null),Pt(null))}catch(u){if(P)return;let c=u instanceof Pe.FloPayError||typeof u=="object"&&u!==null&&"code"in u?u.code:void 0;if(S&&c==="session_auto_completed"){en.current=!0,Je("success"),await Mr(_n),P||(st(()=>{Te.current?.({status:"succeeded"})}),Je(null),Pt(null));return}S&&(Je(null),Pt(null));let L=u instanceof Pe.FloPayError?u:new Pe.FloPayError(u instanceof Error?u.message:"Failed to create session","api_error");dt(L)}finally{Y?.(),Y=void 0}})(),()=>{P=!0,Y?.()})}h(!0);async function K(){let X=!1;try{let S=await new Xn.PaymentAPI(T,{telemetry:!1}).getUnifiedCheckoutSession(Ge,t);if(P)return;re(S);let u=S.data.session??null;if(tt(u),!u)throw new Pe.FloPayError("No session data returned","api_error");if(u.status==="complete"){h(!1),st(()=>{Ln.current?.(u.successUrl??"")});return}if(u.status==="expired")throw new Pe.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});X=!0;let c=Ee??u.checkoutMode??"full";Qe(c);let L=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),f=$o(S);if(c==="auto"&&!en.current&&!L&&!f){en.current=!0;let ee=fe(S);try{if(await Ct.current(u,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ee,sessionId:Ge||u.id}),P)return;await ee,P||h(!1);return}catch{if(P)return;await ee,P||h(!1);return}}await fe(S),P||h(!1)}catch(de){if(P)return;de instanceof Pe.FloPayError?!X&&!ws(de)&&Uo(T,o,bt,"NETWORK_REQUEST_FAILED","session_read"):Uo(T,o,bt,"INTERNAL_SDK_ERROR","checkout_mount");let S=de instanceof Pe.FloPayError?de:new Pe.FloPayError(de instanceof Error?de.message:"Failed to initialize checkout","api_error");dt(S),h(!1)}}async function fe(X){let{publishableKey:de,paypalPublishableKey:S}=so(X);ut.current={publishableKey:de,paypalPublishableKey:S};let{flopay:u,paypalFlopay:c}=await lo({publishableKey:de,paypalPublishableKey:S,billingApiUrl:T,locale:m,telemetry:o});ct.current=u,$e(u),V.current=c,ot(c)}return K(),()=>{P=!0}},[Ee,It,Kt,We,st,t]);let Wt=(0,B.useCallback)(async()=>{if(!(Ye||!G)){Ze(!0),Ke(null);try{await Ht(G,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ge||G.id})}finally{Ze(!1)}}},[Ge,Ye,Ht,G]),Xt=Vo(E),Dt=$o(E),kn=(0,B.useMemo)(()=>{if(!E||!G||!E.data.stripe?.publishableKey)return;let P={appearance:Oe,paymentMethodCreation:"manual",billingApiUrl:T};if(E.data.stripe?.clientSecret)P.clientSecret=E.data.stripe.clientSecret;else{let Y=(0,Pe.buildCheckoutDisplayData)(G).total;P.amount=Math.round(Y*100)||G.amount,P.currency=G.currency?.toLowerCase()}return P},[E,G,Oe,T]),Nn=!!(n&&!se&&z==="buttons"&&me&&Kt==="full"),sn=(0,B.useMemo)(()=>({session:G,loading:rn,error:ke,checkoutMode:nt,inlineSessionDraft:ht,applyInlineSessionPatch:Nn?jn:void 0,inlineSessionPatchProcessing:Dn,claimPending:Rt}),[G,rn,ke,nt,ht,Nn,jn,Dn,Rt]),Qt=!!n&&z==="buttons"&&!Dt&&(!oe||!kn),Et=kt?(0,w.jsx)(Sn,{status:kt,errorMessage:An}):null;if(rn){if(d)return(0,w.jsxs)(w.Fragment,{children:[d,Et]});if(z==="buttons"){let P=ce?.buttonsLayout?.cardButton?.borderRadius??ce?.appearance.variables?.borderRadius??8,Y=K=>(0,w.jsx)("div",{style:{height:K,borderRadius:P,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[p&&Y(ur),v&&(M||g)&&Y(ur),v&&Y(ur),(0,w.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Et]})}return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,w.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,w.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Et]})}return ke?I?(0,w.jsx)(dn.Provider,{value:sn,children:I(ke)}):(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:ke.message})}):Qt?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)(Bs,{onButtonClick:J,showPayPal:p,showStripe:v,showApplePay:M,showGooglePay:g,theme:ue,buttonsTheme:ae,buttonsStyles:U,cardButtonContent:te,cardBackButtonContent:Q,cardTitleContent:pe})}),Et]}):Dt&&G&&Xt?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsxs)("div",{className:Ce,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[xe&&(0,w.jsx)(ar,{icon:!1,children:xe}),Bt==="retrying"&&(0,w.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Bt==="exhausted"&&(0,w.jsxs)("div",{role:"alert",children:[(0,w.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,w.jsx)("button",{type:"button",onClick:Zn,children:"Retry PayPal"})]}),Bt!=="exhausted"&&(0,w.jsx)("div",{"aria-hidden":Bt==="retrying"?!0:void 0,style:Bt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,w.jsx)($a,{sessionId:Ge,nonce:G.clientSecret||void 0,billingApiUrl:T,email:G.customer?.email,clientId:Xt.clientId,environment:Xt.environment,currency:(G.currency??"usd").toUpperCase(),isSubscription:G.mode==="subscription",onComplete:N,onErrorChange:Ke,onDecline:_,onButtonClick:J,onInitializationStateChange:qn,allowAutomaticRetry:At===0,session:G,telemetry:o,telemetryContext:bt,debug:he},`paypal-init-${At}`)})]})}),Et]}):!oe||!kn?(0,w.jsx)(w.Fragment,{children:Et}):nt==="confirm"?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)(wr,{flopay:oe,paypalFlopay:He,options:kn,children:(0,w.jsxs)("div",{className:Ce,children:[xe&&(0,w.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:xe}),Re?Re({onConfirm:Wt,isProcessing:Ye}):(0,w.jsx)("button",{type:"button",onClick:Wt,disabled:Ye,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Ye?"not-allowed":"pointer",opacity:Ye?.6:1},children:Ye?"Processing...":_e??"Confirm Purchase"})]})})}),Et]}):(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)(wr,{flopay:oe,paypalFlopay:He,options:kn,children:se?(0,w.jsxs)(w.Fragment,{children:[xe&&(0,w.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:xe}),(0,w.jsx)(Ms,{sessionId:Ge,nonce:G?.clientSecret||void 0,billingApiUrl:T,session:G,children:se})]}):(0,w.jsx)(oo,{sessionId:Ge,nonce:G?.clientSecret||void 0,email:G?.customer?.email,userId:G?.customer?.id,firstName:G?.customer?.firstName,lastName:G?.customer?.lastName,totalAmount:G?Math.round((0,Pe.buildCheckoutDisplayData)(G).total*100):0,currency:G?.currency?.toLowerCase()??"usd",onComplete:N,onError:b,onDecline:_,error:xe,onErrorChange:Ke,showPayPal:p,showStripe:v,enabledPaymentMethods:x??E?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:E?.data.stripe?.enabledPaymentMethodCountries,showApplePay:M,showGooglePay:g,layout:z,theme:ue,buttonsTheme:ae,buttonsStyles:U,appearance:Oe,cardButtonContent:te,cardBackButtonContent:Q,cardTitleContent:pe,onButtonClick:J,onBeforeButtonClick:me,enableAVS:Me,...we?{cardFieldOrder:we}:{},...be?{cardPreFormSlot:be}:{},avsLayout:ie,country:G?.customer?.country,city:G?.customer?.city,state:G?.customer?.state,onCountryChange:k,onZipChange:F,avsCheck:!!Me,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:se?"custom_layout":z==="buttons"?"buttons_layout":"default_layout",className:Ce,directPaypal:Vo(E),isSubscription:G?.mode==="subscription",session:G,dataAttachmentPending:Rt,debug:he})})}),Et]})}function Ms({sessionId:e,nonce:t,billingApiUrl:n,session:l,children:o}){return(0,w.jsx)(w.Fragment,{children:B.default.Children.map(o,s=>{if(!B.default.isValidElement(s))return s;let m=s.props,d={};return m.sessionId||(d.sessionId=e),!m.nonce&&t&&(d.nonce=t),m.billingApiUrl||(d.billingApiUrl=n),l?.customer&&(m.email||(d.email=l.customer.email),m.userId||(d.userId=l.customer.id),m.firstName||(d.firstName=l.customer.firstName),m.lastName||(d.lastName=l.customer.lastName)),Object.keys(d).length===0?s:B.default.cloneElement(s,d)})})}function Bs({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:l,showGooglePay:o,theme:s,buttonsTheme:m,buttonsStyles:d,cardButtonContent:I,cardBackButtonContent:N,cardTitleContent:b}){let[_,k]=(0,B.useState)(!1),F=(0,B.useMemo)(()=>(0,Pe.resolveTheme)(s),[s]),p=(0,B.useMemo)(()=>{let g=F?.buttonsLayout??(0,Pe.resolveButtonsLayoutTheme)(m);return d?{...g,...d,cardButton:{...g.cardButton,...d.cardButton},cardFormContainer:{...g.cardFormContainer,...d.cardFormContainer},backButton:{...g.backButton,...d.backButton},backButtonIcon:{...g.backButtonIcon,...d.backButtonIcon},submitButton:{...g.submitButton,...d.submitButton},title:{...g.title,...d.title}}:g},[F,m,d]),v=F?.buttonsLayout?.cardButton?.borderRadius??F?.appearance.variables?.borderRadius??8,x=g=>(0,w.jsx)("div",{style:{height:g,borderRadius:v,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),M=I===void 0?{boxSizing:"border-box",height:ur,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let g=p.cardInputBorder??"#e5e7eb",he=p.cardInputBackground??"white",z=nr(N),ue=nr(b);return(0,w.jsxs)("div",{style:{backgroundColor:p.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...p.cardFormContainer},children:[(0,w.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,w.jsxs)("button",{type:"button",onClick:()=>k(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:z?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...p.backButton},children:[(0,w.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...p.backButtonIcon},children:(0,w.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,w.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,w.jsx)(or,{content:N})]}),ue?(0,w.jsx)("div",{style:{flex:1}}):(0,w.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...p.title},children:(0,w.jsx)(kr,{content:b})})]}),(0,w.jsx)("div",{style:{backgroundColor:he,border:`1px solid ${g}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsxs)("div",{style:{display:"flex"},children:[(0,w.jsx)("div",{style:{flex:1,backgroundColor:he,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsx)("div",{style:{flex:1,backgroundColor:he,borderTop:"none",borderRight:`1px solid ${g}`,borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,w.jsx)("div",{style:{backgroundColor:he,border:`1px solid ${g}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...p.submitButton,opacity:.5}}),(0,w.jsx)("style",{children:`
|
|
38
|
+
`}),Ir&&Hn&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ye?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:Nn,style:{display:"inline-flex",alignItems:"center",gap:Lo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(lr,{content:L})]}),Ra?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...f.title},children:(0,l.jsx)(Ar,{content:re})})]}),!Ir&&!Ra&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:zo,order:Ye?-3:0,...f.title},children:(0,l.jsx)(Ar,{content:re})}),ae&&(0,l.jsx)("div",{style:{order:Ye?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Xe,v=(H=!1)=>({backgroundColor:xr,border:`1px solid ${Wn(H)}`,borderRadius:ht,marginTop:"0.5rem",padding:"10px"}),J=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...xa}),oe=(0,C.getStateOptions)(i);return(0,l.jsxs)(l.Fragment,{children:[(0,C.isAVSFieldVisible)(ae.address_line_1,i)&&(0,l.jsx)("div",{style:v(gt.line1),children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:He,onChange:H=>{Ct.current.addressLine1=!0,Qt.current=H.target.value,ot(H.target.value)},disabled:te,required:!0,"data-testid":"flopay-address-line1",style:J()})}),(0,C.isAVSFieldVisible)(ae.address_line_2,i)&&(0,l.jsx)("div",{style:v(),children:(0,l.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:et,onChange:H=>{Ct.current.addressLine2=!0,Zt.current=H.target.value,Rn(H.target.value)},disabled:te,"data-testid":"flopay-address-line2",style:J()})}),((0,C.isAVSFieldVisible)(ae.city,i)||(0,C.isAVSFieldVisible)(ae.state,i))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,C.isAVSFieldVisible)(ae.city,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:xr,borderTop:`1px solid ${Wn(gt.city)}`,borderRight:`1px solid ${Wn(gt.city)}`,borderBottom:`1px solid ${Wn(gt.city)}`,borderLeft:`1px solid ${Wn(gt.city)}`,padding:"10px",borderTopLeftRadius:ht,borderBottomLeftRadius:ht,...(0,C.isAVSFieldVisible)(ae.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:ht}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:it,onChange:H=>{Ct.current.city=!0,At.current=H.target.value,jn(H.target.value)},disabled:te,required:!0,"data-testid":"flopay-city",style:J()})}),(0,C.isAVSFieldVisible)(ae.state,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:xr,border:`1px solid ${Wn(gt.state)}`,padding:"10px",borderTopRightRadius:ht,borderBottomRightRadius:ht,...(0,C.isAVSFieldVisible)(ae.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:ht}},children:oe?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Kt,onChange:H=>{Ct.current.state=!0,Bt.current=H.target.value,hn(H.target.value)},disabled:te,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...J(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,C.getStateLabel)(i)}),oe.map(H=>(0,l.jsx)("option",{value:H.code,children:H.name},H.code))]}):(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,C.getStateLabel)(i),autoComplete:"billing address-level1",value:Kt,onChange:H=>{Ct.current.state=!0,Bt.current=H.target.value,hn(H.target.value)},disabled:te,required:!0,"data-testid":"flopay-state",style:J()})})]}),((0,C.isAVSFieldVisible)(ae.country,i)||(0,C.isAVSFieldVisible)(ae.postal_code,i))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:le==="column"?"column":"row",gap:le==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,C.isAVSFieldVisible)(ae.country,i)&&(0,l.jsx)("div",{style:{flex:le==="row"?1:void 0,backgroundColor:xr,borderTop:`1px solid ${_r}`,borderRight:`1px solid ${_r}`,borderBottom:`1px solid ${_r}`,borderLeft:`1px solid ${_r}`,padding:"10px",...le==="row"&&(0,C.isAVSFieldVisible)(ae.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:ht,borderBottomLeftRadius:ht,borderRight:"none"}:{borderRadius:ht}},children:(0,l.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Xe,onChange:H=>{Ct.current.country=!0,St.current=H.target.value,Te(H.target.value),Ve?.(H.target.value),Bt.current="",hn("")},disabled:te,autoComplete:"billing country","data-testid":"flopay-country",style:{...J(),cursor:"pointer"},children:C.COUNTRY_OPTIONS.map(H=>(0,l.jsxs)("option",{value:H.code,children:[H.flag," ",H.name]},H.code))})}),(0,C.isAVSFieldVisible)(ae.postal_code,i)&&(0,l.jsx)("div",{style:{flex:le==="row"?1:void 0,backgroundColor:xr,border:`1px solid ${Vi}`,padding:"10px",...le==="row"&&(0,C.isAVSFieldVisible)(ae.country,i)?{borderRadius:"0",borderTopRightRadius:ht,borderBottomRightRadius:ht}:{borderRadius:ht}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,C.getPostalCodeLabel)(Xe),autoComplete:"billing postal-code",value:vt,onChange:H=>{Ct.current.zip=!0,Mt.current=H.target.value,We(H.target.value),Ue?.(H.target.value)},onBlur:()=>Ht(!0),disabled:te,required:Dt.required,"aria-invalid":Jr||void 0,"aria-describedby":Jr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:J()})})]}),Jr&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Fo,...xa,fontSize:"0.75rem"},children:Dt.empty?`${(0,C.getPostalCodeLabel)(i)} is required`:ks(i)})]})})()}),Ye&&De&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:De}),Ye&&Gi,g&&(0,l.jsx)(dr,{margin:"0.75rem 0",styleOverride:f.errorBanner,children:g})]}),Xr={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},Ma=i=>rt?!I||!Cn?(0,l.jsx)("pre",{"data-testid":i,style:Xr,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:Xr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${I}`,` directPaypalConfigured=${Cn}`,` inAppBrowserDetected=${String(Yr)}`,` shouldRenderDirectPayPal=${wr}`,` shouldRenderStripePayPal=${kr}`,` hasPaypalStripeInstance=${!!Ie}`].join(`
|
|
39
|
+
`)}):null,Aa=i=>rt?!x||!be?(0,l.jsx)("pre",{"data-testid":i,style:Xr,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:Xr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${x}`,` currency=${xe}`,` amountInCents=${Ae}`,` enabledPaymentMethods: ${JSON.stringify(h??[])}`,` enabledPaymentMethodsProvided=${Cr}`,` hasEnabledMethods=${Vr}`,` expressMethods: ${JSON.stringify(Kr)}`,` walletExpressMethods: ${JSON.stringify(Hr)}`,` paymentElementMethods: ${JSON.stringify(Sr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Wr)}`,` hasStripeInstance=${!!be}`,` shouldRenderWallets=${Rr}`,` shouldRenderPaymentElement=${Er}`].join(`
|
|
40
|
+
`)}):null,Ba=Me==="apm-expanding"||Me==="apm-form"||Me==="apm-collapsing",Qr=Me==="apm-expanding"?`flopay-card-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:Me==="apm-collapsing"?`flopay-card-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Zr=yt?{...xo,paymentMethodTypes:[yt]}:null;if(ne==="buttons"){let i=Me==="buttons"||Me==="expanding"||Me==="apm-expanding",v=Me==="expanding"||Me==="card"||Me==="collapsing",J=K===void 0?{boxSizing:"border-box",height:mo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},oe=Me==="expanding"||Me==="apm-expanding"?`flopay-buttons-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Me==="collapsing"||Me==="apm-collapsing"?`flopay-buttons-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,H=Me==="expanding"?`flopay-card-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:Me==="collapsing"?`flopay-card-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,l.jsxs)("form",{onSubmit:Ao,className:w,style:{position:"relative"},children:[(0,l.jsx)(Ho,{}),nn&&(0,l.jsx)(wn,{status:nn,errorMessage:g,authorized:U}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!oe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!oe?Cs:{},...oe?{animation:oe,pointerEvents:"none"}:{}},children:[Ma("flopay-direct-paypal-gate-debug"),Aa("flopay-stripe-gate-debug"),wr&&Ze&&(0,l.jsxs)(l.Fragment,{children:[ke&&(0,l.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,l.jsx)(Lr,{sessionId:e,nonce:t,billingApiUrl:r,email:m.email,clientId:Ze.clientId,environment:Ze.environment,currency:xe.toUpperCase(),isSubscription:pt,onTokenizedBody:rn,onComplete:c,onErrorChange:he,onDecline:d,onTechnicalFailure:or,onButtonClick:ue,runBeforeButtonClick:ln,isProcessing:te,onLoadStateChange:To,onInitializationStateChange:Mo,session:z??null,existingOrderId:ke?.orderId,debug:rt},ke?.orderId??"fresh")]}),kr&&(0,l.jsx)(ft.Elements,{stripe:Ie,options:ia,children:(0,l.jsx)(ai,{sessionId:e,nonce:t,email:m.email,billingApiUrl:r,onTokenizedBody:rn,onErrorChange:he,isProcessing:te,onButtonClick:ue,onDecline:d,onTechnicalFailure:or,runBeforeButtonClick:ln,onLoadStateChange:da,placeholderBorderRadius:Yn})}),Rr?(0,l.jsx)(ft.Elements,{stripe:be,options:jr,children:(0,l.jsx)(ii,{sessionId:e,nonce:t,email:m.email,billingApiUrl:r,intentKind:Z>0?"payment":"setup",expressMethods:Hr,onTokenizedBody:rn,onErrorChange:he,onButtonClick:ue,onDecline:d,onTechnicalFailure:or,runBeforeButtonClick:ln,onLoadStateChange:pa,placeholderBorderRadius:Yn})}):ha?(0,l.jsx)("div",{style:{height:mo,borderRadius:Yn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Er&&(0,l.jsx)(si,{sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,paymentElementMethods:Wr,stripeInstance:be,paymentElementBaseOptions:xo,onTokenizedBody:rn,onErrorChange:he,onButtonClick:ue,onDecline:d,runBeforeButtonClick:ln,onLoadStateChange:ya,isProcessing:te,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,onExpandApm:tn,expandedApmMethod:yt,themeId:q,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Yn}}),Ye&&(0,l.jsx)("button",{type:"button",onClick:async()=>{te||!(await ln("card")).proceed||(ue?.("card"),On())},disabled:te,style:{width:"100%",...J,...f.cardButton,...Go({themeBundle:O,resolvedPrimaryColor:Gn,resolvedBorderRadius:ht,submitButtonStyle:f.submitButton,explicitPrimaryColor:jt?.colorPrimary}),fontSize:f.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:te?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:te?.6:1},onMouseEnter:Pe=>{!te&&(O||jt?.colorPrimary)&&(Pe.currentTarget.style.backgroundColor=Wi)},onMouseLeave:Pe=>{(O||jt?.colorPrimary)&&(Pe.currentTarget.style.backgroundColor=Gn)},onMouseDown:Pe=>{Pe.currentTarget.style.transform="scale(0.985)"},onMouseUp:Pe=>{Pe.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(sr,{content:K})}),g&&Me==="buttons"&&(0,l.jsx)(dr,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:g})]}),Ye&&v&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...H?{animation:H}:{},...Me==="collapsing"?{pointerEvents:"none"}:{}},children:Ta}),x&&Ba&&yt&&Zr&&be&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Qr?{animation:Qr}:{},...Me==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Do,borderRadius:No,...Tr,padding:Oo},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:Lo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(lr,{content:L})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:zo,paddingRight:80,...f.title},children:`Pay with ${(0,C.getStripeMethodDisplayName)(yt)}`})]}),(0,l.jsx)(ft.Elements,{stripe:be,options:Zr,children:(0,l.jsx)(Wo,{method:yt,sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,onTokenizedBody:rn,onErrorChange:he,onDecline:d,onCancel:Wt,runBeforeButtonClick:ln,onButtonClick:ue,isProcessing:te,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,errorText:g})},yt)]})})]})]})}return Ba&&yt&&Zr&&be&&x?(0,l.jsxs)("form",{onSubmit:Ao,className:w,style:{position:"relative"},children:[(0,l.jsx)(Ho,{}),nn&&(0,l.jsx)(wn,{status:nn,errorMessage:g,authorized:U}),(0,l.jsx)("div",{style:{...Qr?{animation:Qr}:{},...Me==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Do,borderRadius:No,...Tr,padding:Oo},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:Lo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(lr,{content:L})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:zo,paddingRight:80,...f.title},children:`Pay with ${(0,C.getStripeMethodDisplayName)(yt)}`})]}),(0,l.jsx)(ft.Elements,{stripe:be,options:Zr,children:(0,l.jsx)(Wo,{method:yt,sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,onTokenizedBody:rn,onErrorChange:he,onDecline:d,onCancel:Wt,runBeforeButtonClick:ln,onButtonClick:ue,isProcessing:te,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,errorText:g})},yt)]})})]}):(0,l.jsxs)("form",{onSubmit:Ao,className:w,style:{position:"relative"},children:[(0,l.jsx)(Ho,{}),nn&&(0,l.jsx)(wn,{status:nn,errorMessage:g,authorized:U}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ma("flopay-direct-paypal-gate-debug-default"),Aa("flopay-stripe-gate-debug-default"),wr&&Ze&&(0,l.jsxs)(l.Fragment,{children:[ke&&(0,l.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,l.jsx)(Lr,{sessionId:e,nonce:t,billingApiUrl:r,email:m.email,clientId:Ze.clientId,environment:Ze.environment,currency:xe.toUpperCase(),isSubscription:pt,onTokenizedBody:rn,onComplete:c,onErrorChange:he,onDecline:d,onTechnicalFailure:or,onButtonClick:ue,runBeforeButtonClick:ln,isProcessing:te,onLoadStateChange:To,onInitializationStateChange:Mo,session:z??null,existingOrderId:ke?.orderId,debug:rt},ke?.orderId??"fresh")]}),kr&&(0,l.jsx)(ft.Elements,{stripe:Ie,options:ia,children:(0,l.jsx)(ai,{sessionId:e,nonce:t,email:m.email,billingApiUrl:r,onTokenizedBody:rn,onErrorChange:he,isProcessing:te,onButtonClick:ue,onDecline:d,onTechnicalFailure:or,runBeforeButtonClick:ln,onLoadStateChange:da,placeholderBorderRadius:Yn})}),Rr&&(0,l.jsx)(ft.Elements,{stripe:be,options:jr,children:(0,l.jsx)(ii,{sessionId:e,nonce:t,email:m.email,billingApiUrl:r,intentKind:Z>0?"payment":"setup",expressMethods:Hr,onTokenizedBody:rn,onErrorChange:he,onButtonClick:ue,onDecline:d,onTechnicalFailure:or,runBeforeButtonClick:ln,onLoadStateChange:pa,placeholderBorderRadius:Yn})}),Er&&(0,l.jsx)(si,{sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,paymentElementMethods:Wr,stripeInstance:be,paymentElementBaseOptions:xo,onTokenizedBody:rn,onErrorChange:he,onButtonClick:ue,onDecline:d,runBeforeButtonClick:ln,onLoadStateChange:ya,isProcessing:te,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,themeId:q,onExpandApm:tn,expandedApmMethod:yt,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Yn}})]}),Ye&&(Ui||Ni||$i)&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,l.jsx)("span",{children:"or pay with card"}),(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ye&&Ta]})}var gr=require("@flopay/js"),Be=require("@flopay/shared");var Nr="card";async function xs(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:c,error:p}=await e.retrieveSetupIntent(t);return{error:p,intent:c??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:s,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:s??null}}async function Ts(e,t,n,s){if(s){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:p,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:p??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:c}=await e.confirmCardPayment(t,n);return{error:c,intent:a??null}}function Xo(e,t){return Object.assign(e,{checkoutMethod:t})}function Fn(e,t){let n=e instanceof Be.FloPayError?e:new Be.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Or(e,t){try{return await e()}catch(n){throw Fn(n,t)}}function mi(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 Ms(e){return e.status==="succeeded"||e.status==="declined"}async function yi(e){if(typeof document>"u"||typeof window>"u")throw new Be.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Be.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,s=15e3,a=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,c=async()=>{let P=new AbortController,E=()=>P.abort();e.signal?.aborted?P.abort():e.signal?.addEventListener("abort",E);let w=window.setTimeout(()=>P.abort(),s);try{let _=await fetch(a,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:P.signal});if(!_.ok)return{status:"unknown"};let u=await _.json().catch(()=>null);return As(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(w),e.signal?.removeEventListener("abort",E)}},p=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let S=document.createElement("iframe");S.setAttribute("title","Card authentication"),S.setAttribute("allow","payment"),S.tabIndex=0,S.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(";"),S.src=e.nextActionRedirectUrl,d.appendChild(S),document.body.appendChild(d),S.focus();let $=null;try{$=new URL(e.billingApiUrl,window.location.href).origin}catch{$=null}try{let P=await new Promise((E,w)=>{let _=!1,u=0,b=0,I=0,x=!1,h=()=>{window.clearTimeout(u),window.clearInterval(b),window.clearTimeout(I),window.removeEventListener("message",ne),S.removeEventListener("load",T),e.signal?.removeEventListener("abort",ce)},me=async()=>{if(!(_||x)){x=!0;try{let q=await c();if(_||!Ms(q))return;_=!0,h(),E(q)}finally{x=!1}}},T=()=>{window.clearTimeout(I),I=window.setTimeout(()=>{me()},250)},ce=()=>{_||(_=!0,h(),w(new Be.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ne=q=>{if(q.source!==S.contentWindow||$&&q.origin!==$)return;let Q=q.data;!Q||typeof Q!="object"||Q.source!=="flopay-vault-3ds-return"||_||(_=!0,h(),E(null))};u=window.setTimeout(()=>{_||(_=!0,h(),w(new Be.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),b=window.setInterval(()=>{me()},n),S.addEventListener("load",T),window.addEventListener("message",ne),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return P||await c()}finally{d.parentNode?.removeChild(d),p?.isConnected&&p.focus()}}function As(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 qn(e,t="Payment failed. Please try again.",n){let s=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,c=Un(a)??a;return Xo(new Be.FloPayError(c,"api_error",{code:(0,Be.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Be.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),s)}function Jo(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function go(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Bs(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 fi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||go(a)))return a;let s=e?.data;if(s&&typeof s=="object"){let a=s,c=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let d of c)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||go(d)))return d;let p=a.gateways;if(p&&typeof p=="object"){let d=p.stripe;if(d&&typeof d=="object"){let S=d,$=[S.stripeClientSecret,S.clientSecret];for(let P of $)if(typeof P=="string"&&P.length>0&&(!t?.requirePaymentIntentClientSecret||go(P)))return P}}}}async function Fs({billingApiUrl:e,sessionId:t,nonce:n,responseJson:s}){let a=fi(s,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let d=(await new gr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(go(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function hr({billingApiUrl:e,sessionId:t,session:n,nonce:s,tokenizedData:a,returnUrl:c,telemetry:p}){let d=e.replace(/\/+$/,""),S=t??n.id,$=s??n.clientSecret,P=n.customer?.id??n.accountData?.userId??"",E=n.customer?.email??n.accountData?.email??"",w=n.customer?.firstName??n.accountData?.firstName??"",_=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,b=n.customer?.zip??n.accountData?.zip??void 0,I=new gr.PaymentAPI(d,p===!1?{telemetry:!1}:void 0),x=await Bs(()=>I.processPayment(P,{sessionId:S,nonce:$,tokenizedData:a,accountData:{userId:P,email:E,firstName:w,lastName:_,country:u,zip:b},returnUrl:c??Jo(n)}));if(x.ok){let T=typeof x.json=="function"?await x.json().catch(()=>null):null;return(0,Be.isAuthorizationOnlySession)(n)||T?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof T?.paymentId=="string"?T.paymentId:n.paymentId,sessionId:typeof T?.sessionId=="string"?T.sessionId:S,authorizationExpiresAt:typeof T?.authorizationExpiresAt=="string"?T.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Fr(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:a?.threeDSecureActionResultTokenId,paymentMethodId:Fr(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}}let h;try{h=await x.json()}catch{throw new Be.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:x.status})}if(h?.type==="paypal_redirect_required"||h?.type==="3ds_required"){let T=fi(h);if(!T)throw new Be.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:x.status});return{type:h.type,threeDSecureToken:T,paymentMethodId:h.paymentMethodId}}if(h?.gatewayErrorCode==="authentication_required"){let T=await Fs({billingApiUrl:d,sessionId:S,nonce:$,responseJson:h});if(T)return T;throw Xo(new Be.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let me=new Be.FloPayError(h?.message??"Payment failed. Please try again.","api_error",{code:h?.code??h?.gatewayErrorCode,declineCode:h?.declineCode??h?.gatewayDeclineReason,statusCode:x.status});throw Object.assign(me,{telemetryOutcome:(0,Be.classifyPaymentRejection)(x.status,h)})}async function ho(e,{flopay:t,paypalFlopay:n,attempt3DS:s,billingApiUrl:a,sessionId:c,session:p,returnUrl:d,telemetry:S}){let $=t?.getRawProvider();if(!$)throw Fn(new Be.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!s||!e.threeDSecureToken)throw Xo(new Be.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let P=(0,Be.isSetupIntentClientSecret)(e.threeDSecureToken),E=null,w=e.paymentMethodId,_=await Or(()=>xs($,e.threeDSecureToken,P),"card");if(_){if(_.error)throw Fn(new Be.FloPayError(_.error.message??`Failed to retrieve 3DS ${P?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let b=_.intent;!w&&b?.payment_method&&(typeof b.payment_method=="string"?w=b.payment_method:"id"in b.payment_method&&(w=b.payment_method.id??void 0))}let u=w?await Or(()=>Ts($,e.threeDSecureToken,{payment_method:w,return_url:d??Jo(p)??window.location.href},P),"card"):null;if(u){if(u.error)throw Fn(new Be.FloPayError(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");E=u.intent}else{let b=await Or(()=>$.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(b.error)throw Fn(new Be.FloPayError(b.error.message??"3DS authentication failed.","api_error",{code:b.error.code}),"card");E=(P?b.setupIntent:b.paymentIntent)??null}if(E&&(E.status==="requires_capture"||E.status==="succeeded"||E.status==="processing")){let b=await hr({billingApiUrl:a,sessionId:c,session:p,telemetry:S,tokenizedData:{id:E.id,type:"card",threeDSecureActionResultTokenId:E.id},returnUrl:d});return b.type==="success"?{...b.result,paymentIntentId:b.result.paymentIntentId??E.id,paymentMethodId:b.result.paymentMethodId??w}:ho(b,{flopay:t,paypalFlopay:n,attempt3DS:s,billingApiUrl:a,sessionId:c,session:p,returnUrl:d,telemetry:S})}throw Fn(new Be.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let P=(n??t)?.getRawProvider();if(!P)throw Fn(new Be.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:w}=await Or(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(w)throw Fn(new Be.FloPayError(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:E}=await Or(()=>P.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Jo(p)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(E)throw Fn(new Be.FloPayError(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Be.FloPayError("Unsupported payment redirect state.","api_error")}function er(e){if(e instanceof Be.FloPayError){let s=Un(e.message);return s&&s!==e.message?Object.assign(new Be.FloPayError(s,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Un(t)??t;return new Be.FloPayError(n,"api_error")}function Po(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Be.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function bo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:s,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let c=!!t&&t!==e,[p,d]=await Promise.all([(0,gr.loadFloPay)(e,{billingApiUrl:n,locale:s,telemetry:a}),c?(0,gr.loadFloPay)(t,{billingApiUrl:n,locale:s,telemetry:a}).catch(S=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",S),null)):Promise.resolve(null)]);return{flopay:p,paypalFlopay:t?c?d:p:null}}var R=require("react/jsx-runtime"),Pr=44,oa="flopay_checkout_saved_payment_resume",So=new Map,vo=new Map;function gi(e,t){t.settled&&t.consumers===0&&So.get(e)===t&&So.delete(e)}function Ds(e,t,n){let s=vo.get(e);if(s&&(!s.sdkGeneratedIdempotencyKey||!t||s.sdkGeneratedIdempotencyKey===t))return s.attempt;let a=n(),c={attempt:a,sdkGeneratedIdempotencyKey:t};vo.set(e,c);let p=()=>{vo.get(e)===c&&vo.delete(e)};return a.then(p,p),a}function Ur(e){return new Promise(t=>setTimeout(t,e))}function Co(e,t,n){let s=to({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ce.SDK_VERSION,enabled:t!==!1});return s.beginCheckout(n),s}function $r(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Qo(e,t,n,s,a){let c=Co(e,t,n);c.error({errorCode:s,stage:a,paymentMethodCategory:"unknown",...a==="session_read"?{requestCategory:"session_read"}:{}}),$r(c)}function Ls(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 na(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function Zo(e){return!e||e.data.stripe?.publishableKey?!1:!!na(e)?.clientId}function Dn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function zs(){if(!Dn())return null;try{let e=window.sessionStorage.getItem(oa);return e?JSON.parse(e):null}catch{return null}}function hi(e){if(Dn())try{window.sessionStorage.setItem(oa,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ea(){if(Dn())try{window.sessionStorage.removeItem(oa)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var aa=":idempotency-key";function Os(e){if(!Dn())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 Pi(e,t,n){if(Dn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(s){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",s)}}function ra(e){if(Dn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function Ns(e){if(Dn())try{return window.sessionStorage.getItem(e+aa)??void 0}catch{return}}function Us(e,t){if(Dn())try{window.sessionStorage.setItem(e+aa,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function $s(e){if(ra(e),!!Dn())try{window.sessionStorage.removeItem(e+aa)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function qs(){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 s of t)e.searchParams.has(s)&&(e.searchParams.delete(s),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function bi(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 js(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 ta(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function wo({sessionId:e,nonce:t,createSession:n,billingApiUrl:s,telemetry:a,appearance:c,locale:p,loading:d,error:S,onComplete:$,onError:P,onDecline:E,onCountryChange:w,onZipChange:_,showPayPal:u=!0,showStripe:b=!0,enabledPaymentMethods:I,showApplePay:x=!0,showGooglePay:h=!0,debug:me=!1,layout:T,theme:ce,buttonsTheme:ne,buttonsStyles:q,cardButtonContent:Q,cardBackButtonContent:W,cardTitleContent:ie,showSecurityFooter:K,onButtonClick:L,onBeforeButtonClick:re,enableAVS:ye,cardFieldOrder:ue,cardPreFormSlot:pe,avsLayout:se,className:Se,initialErrorMessage:De=null,children:le,checkoutMode:je,confirmLabel:Oe,renderConfirmButton:_e,onSessionCompleted:X}){let k=(0,Ce.resolveBillingApiUrl)(s),de=(0,D.useMemo)(()=>(0,Ce.resolveTheme)(ce),[ce]),Ve=c??de?.appearance,Ue=n?"embedded_checkout":"standard_checkout",ge=le?"custom_layout":T==="buttons"?"buttons_layout":"default_layout",[B,fe]=(0,D.useState)(null),[Z,xe]=(0,D.useState)(null),ut=(0,D.useRef)(null),[Ze,pt]=(0,D.useState)(null),z=(0,D.useRef)(null),[ee,rt]=(0,D.useState)(null),[Ke,mt]=(0,D.useState)(e??""),$e=e??Ke,Je=n?"":$e,[Gt,Qe]=(0,D.useState)(!0),[Jt,M]=(0,D.useState)(null),[we,Xe]=(0,D.useState)("full"),[Te,vt]=(0,D.useState)(!1),[We,He]=(0,D.useState)(De),[ot,et]=(0,D.useState)(null),[Rn,it]=(0,D.useState)(null),[jn,Kt]=(0,D.useState)(!1),[hn,Xt]=(0,D.useState)(void 0),[rr,Mt]=(0,D.useState)(""),[St,Qt]=(0,D.useState)(!1),[Zt,At]=(0,D.useState)(!1),Bt=(0,D.useRef)(0),[Ct,ae]=(0,D.useState)("loading"),[Vn,U]=(0,D.useState)(0),st=(0,D.useRef)(!1),Ft=(0,D.useRef)(!1),Ln=(0,D.useRef)(!1),Le=(0,D.useRef)(null),lt=(0,D.useMemo)(()=>({checkoutMode:je??we,layout:le?"unknown":T==="buttons"?"buttons":"embedded"}),[je,le,we,T]),Ye=(0,D.useRef)($);Ye.current=$;let En=(0,D.useRef)(P);En.current=P;let In=(0,D.useRef)(E);In.current=E,(0,D.useEffect)(()=>{Tt(Z)?.setCheckoutContext(lt),Ze&&Ze!==Z&&Tt(Ze)?.setCheckoutContext(lt)},[Z,Ze,lt]);let zn=(0,D.useRef)(X);zn.current=X;let Kn=(0,D.useCallback)(A=>{ae(A),!(A!=="exhausted"||Ln.current)&&(Ln.current=!0,En.current?.(new Ce.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),_n=(0,D.useCallback)(()=>{ae("retrying"),U(A=>A+1)},[]);(0,D.useEffect)(()=>{ae("loading"),U(0),Ln.current=!1},[$e]),(0,D.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ce.SDK_VERSION,checkout_type:Ue,checkout_layout:ge,billing_api_url:k})},[ge,Ue,k]);let at=(0,D.useMemo)(()=>n?Ot(n,!0):"",[n]),Dt=(0,D.useMemo)(()=>rr===at?hn:void 0,[hn,rr,at]),on=(0,D.useMemo)(()=>n?$o(n,Dt):void 0,[n,Dt]),gt=je??on?.checkoutMode??"full",It=(0,D.useMemo)(()=>on?{...on,checkoutMode:gt}:void 0,[on,gt]);(0,D.useEffect)(()=>{Xt(void 0),Mt(at)},[at]),(0,D.useEffect)(()=>{He(De)},[De]);let en=(0,D.useCallback)((A,j,F)=>{Ge(()=>{In.current?.(Rt(A,j,F))})},[Ge]),an=(0,D.useCallback)(async(A,j)=>{He(null),it(null),Kt(!1),et("processing");let F=j?.sessionId??A.id,ke=ut.current??z.current,Re=Tt(ke),y=ke?null:Co(k,a,lt),r={log:m=>{Re?Re.log(m):y?.log(m)},error:m=>{Re?Re.error(m):y?.error(m)},terminal:m=>{Re?Re.terminal(m):y?.terminal(m)},performance:m=>{Re?Re.performance(m):y?.performance(m)},now:()=>Re?.now()??y?.now()??0,elapsed:m=>Re?.elapsed(m)??Math.max(0,(y?.now()??m)-m)},g=r.now(),O=!!(j?.initialAutoProcessingError||j?.initialAutoProcessingPending),f=!1,Y,ze=()=>{f||(f=!0,O=!0,Y=r.now(),r.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},tt=!1,te=()=>{tt||(tt=!0,r.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),r.performance({stage:"processing",durationMs:r.elapsed(g),durationMode:"machine",paymentMethodCategory:"saved"}),Y!==void 0&&r.performance({stage:"recovery",durationMs:r.elapsed(Y),durationMode:"machine",paymentMethodCategory:"saved"}))};r.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),r.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),O&&ze();let G;try{let m=mi(j?.initialAutoProcessingError),V;if(m)ze(),m.type==="paypal_redirect_required"&&Le.current?.publishableKey&&hi({sessionId:F,publishableKey:Le.current.publishableKey,paypalPublishableKey:Le.current.paypalPublishableKey}),V=await ho(m,{flopay:ut.current,paypalFlopay:z.current,attempt3DS:j?.attempt3DS,billingApiUrl:k,sessionId:F,session:A,telemetry:!1}),m.type==="paypal_redirect_required"&&ea();else if(j?.initialAutoProcessingPending){let Ae=(await new tr.PaymentAPI(k,{telemetry:!1}).waitForCheckoutSessionCompletion(j.initialAutoProcessingPending.sessionId,{initialDelayMs:j.initialAutoProcessingPending.retryAfterMs})).data.session;if(!mr(Ae))throw io(Ae);V=Qn(Ae,F)}else{if(j?.initialAutoProcessingError)throw qn(j.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:j.initialAutoProcessingError.checkoutMethod});if(j?.fromCreateSession)return j?.fallbackToFull&&(Xe("full"),bi("full")),!1;{let be=await hr({billingApiUrl:k,sessionId:F,session:A,telemetry:!1});be.type==="success"?V=be.result:(ze(),be.type==="paypal_redirect_required"&&Le.current?.publishableKey&&hi({sessionId:F,publishableKey:Le.current.publishableKey,paypalPublishableKey:Le.current.paypalPublishableKey}),V=await ho(be,{flopay:ut.current,paypalFlopay:z.current,attempt3DS:j?.attempt3DS,billingApiUrl:k,sessionId:F,session:A,telemetry:!1}),be.type==="paypal_redirect_required"&&ea())}}F&&yr(F),te(),O&&(r.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),r.terminal({outcome:V.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Kt(V.status==="authorized"),et("success"),await Ur(Mn),G=()=>Ye.current?.(V)}catch(m){let V=er(m),be=V.checkoutMethod??Nr;He(V.message),it(V.message),Kt(!1),j?.fallbackToFull&&(r.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Xe("full"),bi("full")),te();let Ie=V.statusCode!==void 0?(0,Ce.telemetryStatusClass)(V.statusCode,"unknown"):void 0,Ae=Ie==="4xx"?{requestCategory:"process_payment",statusClass:Ie}:{},bn=Ie===void 0||Ie==="4xx";if(bn&&(V.telemetryOutcome==="payment_declined"||!!(V.declineCode||V.code?.toLowerCase().includes("declin"))))r.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ae});else if(bn&&(V.telemetryOutcome==="validation_rejected"||V.type==="validation_error"))r.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ae});else{let jr=(0,Ce.classifyTelemetryFailure)(m,O?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");r.error({...jr,...V.telemetryFailureCategory?{failureCategory:V.telemetryFailureCategory}:{},stage:O?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:V.telemetryRequestCategory??"process_payment"})}return Ge(()=>En.current?.(V)),en(be,V,{code:V.code,declineCode:V.declineCode}),et("error"),await Promise.allSettled([Ur(Sn),j?.ensureProvidersReady?j.ensureProvidersReady():Promise.resolve()]),O&&(r.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{te(),y&&$r(y),et(null),it(null)}return Ge(G),!0},[en,Ge,er,k,a,lt]);(0,D.useEffect)(()=>{if(typeof window>"u"||Ft.current)return;let A=new URLSearchParams(window.location.search),j=A.get("payment_intent_client_secret");if(!j)return;let F=zs();F&&(Ft.current=!0,(async()=>{let ke,Re=0;He(null),it(null),et("processing"),vt(!0);try{if(A.get("redirect_status")==="failed")throw Object.assign(new Ce.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:y,paypalFlopay:r}=await bo({publishableKey:F.publishableKey,paypalPublishableKey:F.paypalPublishableKey,billingApiUrl:k,locale:p,telemetry:a});ke=Tt(r??y),Re=ke?.now()??0,ke?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ke?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let g=(r??y)?.getRawProvider();if(!g)throw Object.assign(new Ce.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:O,error:f}=await g.retrievePaymentIntent(j);if(f)throw Object.assign(new Ce.FloPayError(f.message??"Failed to retrieve PayPal payment status.","api_error",{code:f.code}),{checkoutMethod:"paypal"});let Y=Ka(O?.status);if(!O||Y==="failed")throw Object.assign(new Ce.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let ze=typeof O.payment_method=="string"?O.payment_method:O.payment_method?.id,tt=Y;if(F.sessionId){let m=(await new tr.PaymentAPI(k,{telemetry:!1}).getUnifiedCheckoutSession(F.sessionId)).data.session;if(m&&m.status!=="complete"){let V=await hr({billingApiUrl:k,sessionId:F.sessionId,session:m,telemetry:!1,tokenizedData:{id:ze??O.id,type:"card",threeDSecureActionResultTokenId:O.id,isPaypal:!0}});if(V.type!=="success")throw Object.assign(new Ce.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});tt=V.result.status}}F.sessionId&&yr(F.sessionId),ke?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ke?.performance({stage:"redirect_resume",durationMs:ke.elapsed(Re),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ke?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),et("success"),await Ur(Mn),Ge(()=>Ye.current?.({status:tt,paymentIntentId:O.id,paymentMethodId:ze,checkoutMethod:"paypal"}))}catch(y){let r=er(y),g=r.checkoutMethod??"paypal",O=!!(r.declineCode||r.code?.toLowerCase().includes("declin"));if(ke)ke.performance({stage:"redirect_resume",durationMs:ke.elapsed(Re),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),O?ke.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ke.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(O){let f=Co(k,a,lt);f.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),$r(f)}else Qo(k,a,lt,"REDIRECT_RESUME_FAILED","redirect_resume");He(r.message),it(r.message),Ge(()=>En.current?.(r)),en(g,r,{code:r.code,declineCode:r.declineCode}),et("error"),await Ur(Sn)}finally{ea(),qs(),et(null),it(null),vt(!1)}})())},[en,Ge,p,er,k,a]);let Ht=(0,D.useRef)(null);function Ot(A,j=!1){let F=A?.account?.email?.trim().toLowerCase()??"",ke={c:A?.clientId,cur:A?.currency??"",captureMethod:A?.captureMethod??"",a:{e:F,u:F?"":A?.account?.userId??"",country:A?.account?.country??""},successUrl:A?.successUrl,cancelUrl:A?.cancelUrl,p:A?.products?.map(r=>ta(`${r.type??""}:${r.code??r.providerItemId??r.providerPlanId??""}`,r)).sort(),i:A?.items?.map(r=>ta(r.code??r.providerItemId??"",r)).sort(),s:A?.subscriptions?.map(r=>ta(r.code??r.providerPlanId??"",r)).sort(),couponCodes:A?.couponCodes?[...A.couponCodes].sort():void 0,...j?{tagsData:A?.tagsData,utmMetadata:A?.utmMetadata,tokenizedData:A?.tokenizedData,checkoutMode:A?.checkoutMode??"full"}:{}},Re=JSON.stringify(ke),y=0;for(let r=0;r<Re.length;r++)y=(y<<5)-y+Re.charCodeAt(r)|0;return`flopay_session_${Math.abs(y).toString(36)}`}let Nt=(0,D.useMemo)(()=>It?Ot(It):"",[It]),Me=(0,D.useRef)(It);Me.current=It,(0,D.useEffect)(()=>{mt(e??"")},[e]),(0,D.useEffect)(()=>{st.current=!1,He(De),it(null),Kt(!1),et(null)},[Nt,De,e]);async function Ut(A,j){let F=Co(k,a,lt),ke=new tr.PaymentAPI(k,{telemetry:!1}),Re=!1;try{let y=A.idempotencyKey!==void 0?(0,Ce.resolveIdempotencyKey)(A.idempotencyKey):void 0,r=y??Ns(j),g,O=!1,f=Os(j);F.log({name:f?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let Y=f?.sid??null,ze=null,tt;if(Y)try{if(ze=await ke.getUnifiedCheckoutSession(Y,f?.nonce),ze.data.session?.status==="complete"){if(jo(Y))return{sid:Y,result:ze};$s(j),Y=null,ze=null,O=!0}}catch{F.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),ra(j),Y=null}if(!Y){!y&&(O||!r)&&(r=(0,Ce.resolveIdempotencyKey)(),g=r),r&&Us(j,r);let te=F.now(),G=0;F.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let m={...A,idempotencyKey:r,avsCheck:!!ye,avsConfig:typeof ye=="object"?ye:void 0,checkoutType:"embedded_checkout",checkoutLayout:le?"custom_layout":T==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(m,tr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Ie=>{G=Math.max(G,Ie)}}});let V=()=>{F.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),F.performance({stage:"session_create",durationMs:F.now()-te,durationMode:"machine",requestCategory:"session_create",attempt:G,statusClass:"2xx"})},be=Ie=>{let Ae=(0,Ce.classifyTelemetryFailure)(Ie,"CHECKOUT_SESSION_CREATE_FAILED","unknown");F.performance({stage:"session_create",durationMs:F.now()-te,durationMode:"machine",requestCategory:"session_create",attempt:G,statusClass:Ae.statusClass}),Ie instanceof Ce.FloPayError&&Ie.type==="validation_error"?F.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):Ae.statusClass==="4xx"?F.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):F.error({...Ae,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if((0,Ce.isDetachedSessionEligible)(m)){let Ie=await ke.createDetachedSession(m);Ie.claimed.catch(()=>{}),ze=Ie.shell,Y=Ie.sessionId,tt=Ie.claimed.then(Ae=>{let bn=Ae.data.session?.id??Ie.sessionId;return bn&&Pi(j,bn,Ae.data.session?.clientSecret??Ie.nonce),V(),Ae},Ae=>{throw ra(j),be(Ae),Ae}).finally(()=>$r(F)),tt.catch(()=>{}),Re=!0,F.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),F.performance({stage:"session_shell",durationMs:F.now()-te,durationMode:"machine",requestCategory:"session_create",attempt:G,statusClass:"2xx",paymentMethodCategory:"card"})}else ze=await ke.createAndFetchSession(m),V()}catch(Ie){throw be(Ie),Ie}Y=ze.data.session?.id??Y??"",Y&&!tt&&Pi(j,Y,ze.data.session?.clientSecret)}return{sid:Y??"",result:ze,sdkGeneratedIdempotencyKey:g,...tt?{claimed:tt}:{}}}finally{Re||$r(F)}}let yt=(0,D.useCallback)(async(A,j)=>{let F=Me.current;if(!F)throw new Ce.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ke=$o(F,A),Re=Ot(ke),y=So.get(Re);if(!y){let O={promise:Ut(ke,Re),consumers:0,settled:!1};y=O,So.set(Re,O);let f=()=>{O.settled=!0,gi(Re,O)};O.promise.then(f,f)}y.consumers+=1;let r=!1,g=()=>{r||(r=!0,y.consumers-=1,gi(Re,y))};j?.(g);try{let O=await y.promise;Ht.current=Re,A&&(Mt(at),Xt(V=>qa(V,A)));let{sid:f,result:Y,claimed:ze}=O;if(fe(Y),Y.data.session&&rt(Y.data.session),f&&mt(f),ze){let V=Bt.current+=1;At(!0),ze.then(be=>{Bt.current===V&&(fe(be),be.data.session&&rt(be.data.session),At(!1))},be=>{Bt.current===V&&(At(!1),M(be instanceof Ce.FloPayError?be:new Ce.FloPayError(be instanceof Error?be.message:"Failed to create session","api_error")))})}else Bt.current+=1,At(!1);let{publishableKey:tt,paypalPublishableKey:te}=Po(Y),{flopay:G,paypalFlopay:m}=await bo({publishableKey:tt,paypalPublishableKey:te,billingApiUrl:k,locale:p,telemetry:a});return ut.current=G,xe(G),z.current=m,pt(m),Qe(!1),O}catch(O){throw Ht.current===Re&&(Ht.current=null),O}finally{j||g()}},[p,k,a,lt]),Pn=(0,D.useRef)(an);Pn.current=an;let Hn=(0,D.useRef)(yt);Hn.current=yt;let $t=(0,D.useCallback)(async A=>{if(!js(A)||St)return{sessionId:Ke,session:ee};Qt(!0);try{let j=await yt(A);return{sessionId:j.sid,session:j.result.data.session??null}}finally{Qt(!1)}},[yt,St,Ke,ee]);(0,D.useEffect)(()=>{let A=!1,j;if(M(null),Nt){let Re=Me.current;return Xe(gt),Qe(!1),Ht.current===Nt?()=>{A=!0}:(rt(ja(Re,je)),(async()=>{let y=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),r=gt==="auto"&&!st.current&&!y;r&&(He(null),it(null),et("processing"));try{let g=await Hn.current(void 0,ze=>{j=ze}),O=g.result.data.session??null;Le.current=Po(g.result);let f=Zo(g.result),Y=jo(g.sid||O?.id);if(!A&&r&&O&&!f&&!Y){st.current=!0,await Ds(Nt,g.sdkGeneratedIdempotencyKey,()=>Pn.current(O,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:g.result.autoProcessingError,initialAutoProcessingPending:g.result.autoProcessingPending,autoProcessingAttempted:g.result.autoProcessingAttempted,sessionId:g.sid||O.id}));return}!A&&r&&((f||Y)&&(st.current=!0),et(null),it(null))}catch(g){if(A)return;let O=g instanceof Ce.FloPayError||typeof g=="object"&&g!==null&&"code"in g?g.code:void 0;if(r&&O==="session_auto_completed"){st.current=!0,et("success"),await Ur(Mn),A||(Ge(()=>{Ye.current?.({status:"succeeded"})}),et(null),it(null));return}r&&(et(null),it(null));let f=g instanceof Ce.FloPayError?g:new Ce.FloPayError(g instanceof Error?g.message:"Failed to create session","api_error");M(f)}finally{j?.(),j=void 0}})(),()=>{A=!0,j?.()})}Qe(!0);async function F(){let Re=!1;try{let r=await new tr.PaymentAPI(k,{telemetry:!1}).getUnifiedCheckoutSession($e,t);if(A)return;fe(r);let g=r.data.session??null;if(rt(g),!g)throw new Ce.FloPayError("No session data returned","api_error");let O=g.checkoutMode;if(O==="setup")throw new Ce.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(g.status==="authorized"){Qe(!1),Ge(()=>{Ye.current?.(Qn(g,$e)),zn.current?.(g.successUrl??"")});return}if(g.status==="complete"){Qe(!1),Ge(()=>{zn.current?.(g.successUrl??"")});return}if(g.status==="expired")throw ao(g);Re=!0;let f=je??O??"full";Xe(f);let Y=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ze=Zo(r);if(f==="auto"&&!st.current&&!Y&&!ze){st.current=!0;let tt=ke(r);try{if(await Pn.current(g,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>tt,sessionId:$e||g.id}),A)return;await tt,A||Qe(!1);return}catch{if(A)return;await tt,A||Qe(!1);return}}await ke(r),A||Qe(!1)}catch(y){if(A)return;y instanceof Ce.FloPayError?!Re&&!Ls(y)&&Qo(k,a,lt,"NETWORK_REQUEST_FAILED","session_read"):Qo(k,a,lt,"INTERNAL_SDK_ERROR","checkout_mount");let r=y instanceof Ce.FloPayError?y:new Ce.FloPayError(y instanceof Error?y.message:"Failed to initialize checkout","api_error");M(r),Qe(!1)}}async function ke(Re){let{publishableKey:y,paypalPublishableKey:r}=Po(Re);Le.current={publishableKey:y,paypalPublishableKey:r};let{flopay:g,paypalFlopay:O}=await bo({publishableKey:y,paypalPublishableKey:r,billingApiUrl:k,locale:p,telemetry:a});ut.current=g,xe(g),z.current=O,pt(O)}return F(),()=>{A=!0}},[je,Nt,gt,Je,Ge,t]);let qt=(0,D.useCallback)(async()=>{if(!(Te||!ee)){vt(!0),He(null);try{await an(ee,{attempt3DS:!0,fallbackToFull:!0,sessionId:$e||ee.id})}finally{vt(!1)}}},[$e,Te,an,ee]),Lt=na(B),On=Zo(B),Nn=(0,D.useMemo)(()=>{if(!B||!ee||!B.data.stripe?.publishableKey)return;let A={appearance:Ve,paymentMethodCreation:"manual",billingApiUrl:k};if(B.data.stripe?.clientSecret)A.clientSecret=B.data.stripe.clientSecret;else{let j=(0,Ce.buildCheckoutDisplayData)(ee).total;A.amount=Math.round(j*100)||ee.amount,A.currency=ee.currency?.toLowerCase()}return A},[B,ee,Ve,k]),tn=!!(n&&!le&&T==="buttons"&&re&>==="full"),Wt=(0,D.useMemo)(()=>({session:ee,loading:Gt,error:Jt,checkoutMode:we,inlineSessionDraft:It,applyInlineSessionPatch:tn?$t:void 0,inlineSessionPatchProcessing:St,claimPending:Zt}),[ee,Gt,Jt,we,It,tn,$t,St,Zt]),nn=!!n&&T==="buttons"&&!On&&(!Z||!Nn),qe=ot?(0,R.jsx)(wn,{status:ot,errorMessage:Rn,authorized:jn}):null;if(Gt){if(d)return(0,R.jsxs)(R.Fragment,{children:[d,qe]});if(T==="buttons"){let A=de?.buttonsLayout?.cardButton?.borderRadius??de?.appearance.variables?.borderRadius??8,j=F=>(0,R.jsx)("div",{style:{height:F,borderRadius:A,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[u&&j(Pr),b&&(x||h)&&j(Pr),b&&j(Pr),(0,R.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),qe]})}return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,R.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,R.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),qe]})}return Jt?S?(0,R.jsx)(cn.Provider,{value:Wt,children:S(Jt)}):(0,R.jsx)(cn.Provider,{value:Wt,children:(0,R.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Jt.message})}):nn?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(cn.Provider,{value:Wt,children:(0,R.jsx)(Ks,{onButtonClick:L,showPayPal:u,showStripe:b,showApplePay:x,showGooglePay:h,theme:ce,buttonsTheme:ne,buttonsStyles:q,cardButtonContent:Q,cardBackButtonContent:W,cardTitleContent:ie})}),qe]}):On&&ee&&Lt?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(cn.Provider,{value:Wt,children:(0,R.jsxs)("div",{className:Se,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[We&&(0,R.jsx)(dr,{icon:!1,children:We}),Ct==="retrying"&&(0,R.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ct==="exhausted"&&(0,R.jsxs)("div",{role:"alert",children:[(0,R.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,R.jsx)("button",{type:"button",onClick:_n,children:"Retry PayPal"})]}),Ct!=="exhausted"&&(0,R.jsx)("div",{"aria-hidden":Ct==="retrying"?!0:void 0,style:Ct==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,R.jsx)(Qa,{sessionId:$e,nonce:ee.clientSecret||void 0,billingApiUrl:k,email:ee.customer?.email,clientId:Lt.clientId,environment:Lt.environment,currency:(ee.currency??"usd").toUpperCase(),isSubscription:ee.mode==="subscription",onComplete:$,onErrorChange:He,onDecline:E,onButtonClick:L,onInitializationStateChange:Kn,allowAutomaticRetry:Vn===0,session:ee,telemetry:a,telemetryContext:lt,debug:me},`paypal-init-${Vn}`)})]})}),qe]}):!Z||!Nn?(0,R.jsx)(R.Fragment,{children:qe}):we==="confirm"?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(cn.Provider,{value:Wt,children:(0,R.jsx)(Mr,{flopay:Z,paypalFlopay:Ze,options:Nn,children:(0,R.jsxs)("div",{className:Se,children:[We&&(0,R.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:We}),_e?_e({onConfirm:qt,isProcessing:Te}):(0,R.jsx)("button",{type:"button",onClick:qt,disabled:Te,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Te?"not-allowed":"pointer",opacity:Te?.6:1},children:Te?"Processing...":Oe??"Confirm Purchase"})]})})}),qe]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(cn.Provider,{value:Wt,children:(0,R.jsx)(Mr,{flopay:Z,paypalFlopay:Ze,options:Nn,children:le?(0,R.jsxs)(R.Fragment,{children:[We&&(0,R.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:We}),(0,R.jsx)(Vs,{sessionId:$e,nonce:ee?.clientSecret||void 0,billingApiUrl:k,session:ee,children:le})]}):(0,R.jsx)(fo,{sessionId:$e,nonce:ee?.clientSecret||void 0,email:ee?.customer?.email,userId:ee?.customer?.id,firstName:ee?.customer?.firstName,lastName:ee?.customer?.lastName,totalAmount:ee?Math.round((0,Ce.buildCheckoutDisplayData)(ee).total*100):0,currency:ee?.currency?.toLowerCase()??"usd",onComplete:$,onError:P,onDecline:E,error:We,onErrorChange:He,showPayPal:u,showStripe:b,enabledPaymentMethods:I??B?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:B?.data.stripe?.enabledPaymentMethodCountries,showApplePay:x,showGooglePay:h,layout:T,theme:ce,buttonsTheme:ne,buttonsStyles:q,appearance:Ve,cardButtonContent:Q,cardBackButtonContent:W,cardTitleContent:ie,onButtonClick:L,onBeforeButtonClick:re,enableAVS:ye,...ue?{cardFieldOrder:ue}:{},...pe?{cardPreFormSlot:pe}:{},avsLayout:se,country:ee?.customer?.country,city:ee?.customer?.city,state:ee?.customer?.state,onCountryChange:w,onZipChange:_,avsCheck:!!ye,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:le?"custom_layout":T==="buttons"?"buttons_layout":"default_layout",className:Se,directPaypal:na(B),isSubscription:ee?.mode==="subscription",session:ee,dataAttachmentPending:Zt,debug:me})})}),qe]})}function Vs({sessionId:e,nonce:t,billingApiUrl:n,session:s,children:a}){return(0,R.jsx)(R.Fragment,{children:D.default.Children.map(a,c=>{if(!D.default.isValidElement(c))return c;let p=c.props,d={};return p.sessionId||(d.sessionId=e),!p.nonce&&t&&(d.nonce=t),p.billingApiUrl||(d.billingApiUrl=n),s?.customer&&(p.email||(d.email=s.customer.email),p.userId||(d.userId=s.customer.id),p.firstName||(d.firstName=s.customer.firstName),p.lastName||(d.lastName=s.customer.lastName)),Object.keys(d).length===0?c:D.default.cloneElement(c,d)})})}function Ks({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:s,showGooglePay:a,theme:c,buttonsTheme:p,buttonsStyles:d,cardButtonContent:S,cardBackButtonContent:$,cardTitleContent:P}){let[E,w]=(0,D.useState)(!1),_=(0,D.useMemo)(()=>(0,Ce.resolveTheme)(c),[c]),u=(0,D.useMemo)(()=>{let h=_?.buttonsLayout??(0,Ce.resolveButtonsLayoutTheme)(p);return d?{...h,...d,cardButton:{...h.cardButton,...d.cardButton},cardFormContainer:{...h.cardFormContainer,...d.cardFormContainer},backButton:{...h.backButton,...d.backButton},backButtonIcon:{...h.backButtonIcon,...d.backButtonIcon},submitButton:{...h.submitButton,...d.submitButton},title:{...h.title,...d.title}}:h},[_,p,d]),b=_?.buttonsLayout?.cardButton?.borderRadius??_?.appearance.variables?.borderRadius??8,I=h=>(0,R.jsx)("div",{style:{height:h,borderRadius:b,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),x=S===void 0?{boxSizing:"border-box",height:Pr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(E){let h=u.cardInputBorder??"#e5e7eb",me=u.cardInputBackground??"white",T=ir($),ce=ir(P);return(0,R.jsxs)("div",{style:{backgroundColor:u.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...u.cardFormContainer},children:[(0,R.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,R.jsxs)("button",{type:"button",onClick:()=>w(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:T?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...u.backButton},children:[(0,R.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:(0,R.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,R.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,R.jsx)(lr,{content:$})]}),ce?(0,R.jsx)("div",{style:{flex:1}}):(0,R.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:(0,R.jsx)(Ar,{content:P})})]}),(0,R.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${h}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsxs)("div",{style:{display:"flex"},children:[(0,R.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:`1px solid ${h}`,borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,R.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${h}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...u.submitButton,opacity:.5}}),(0,R.jsx)("style",{children:`
|
|
41
41
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
42
42
|
@keyframes flopay-interim-expand {
|
|
43
43
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
44
44
|
40% { opacity: 1; }
|
|
45
45
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
46
46
|
}
|
|
47
|
-
`})]})}return(0,w.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&x(ur),n&&(l||o)&&x(ur),n&&(0,w.jsx)("button",{type:"button",onClick:()=>{e?.("card"),k(!0)},style:{width:"100%",...M,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:p.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...p.cardButton},onMouseDown:g=>{g.currentTarget.style.transform="scale(0.985)"},onMouseUp:g=>{g.currentTarget.style.transform="scale(1)"},children:(0,w.jsx)(rr,{content:I})}),(0,w.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Pi=require("@flopay/shared");var Qn=require("react");var pi=require("react/jsx-runtime");function ci(e,t){function n({className:l,id:o,style:s,options:m,onChange:d,onReady:I,onFocus:N,onBlur:b,onEscape:_}){let k=(0,Qn.useRef)(null),F=(0,Qn.useRef)(null),{elements:p,reportInteractive:v}=(0,Qn.useContext)(In);return(0,Qn.useEffect)(()=>{if(!p||!k.current)return;let x=!0;return(async()=>{let M=p.getElement(e);M||(M=await p.create(e,m)),!(!x||!k.current)&&(M.mount(k.current),F.current=M,d&&M.on("change",d),M.on("ready",()=>{v?.(),I?.()}),N&&M.on("focus",N),b&&M.on("blur",b),_&&M.on("escape",_))})(),()=>{if(x=!1,F.current){try{F.current.unmount()}catch{}F.current=null}}},[p,v]),(0,pi.jsx)("div",{ref:k,className:l,id:o,style:s})}return n.displayName=t,n}var di=ci("payment","PaymentElement"),ui=ci("address","AddressElement");var mi=require("@flopay/js"),yi=require("@flopay/shared"),fn=require("react");var yn=require("react/jsx-runtime");function fi({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,firstName:s,lastName:m,chv:d,onTokenizedBody:I,onComplete:N,onErrorChange:b,isProcessing:_=!1}){let k=un(),F=Yr(),p=Gr(),[v,x]=(0,fn.useState)(!1),[M,g]=(0,fn.useState)(!1),he=(0,fn.useRef)(!1),z=(n||p).replace(/\/+$/,""),ue=(0,fn.useCallback)(async te=>{try{let pe=await new mi.PaymentAPI(z).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:te,accountData:{userId:o??"",email:l??"",firstName:s??"",lastName:m??""},chv:d});if(pe.ok){N?.();return}let W=await pe.json().catch(()=>null);b?.(W?.message??"Payment failed. Please try again.")}catch(Q){b?.(Q instanceof Error?Q.message:"An unexpected error occurred")}},[z,e,t,o,l,s,m,d,N,b]),ae=(0,fn.useCallback)(te=>{I?I(te):ue(te)},[I,ue]);(0,fn.useEffect)(()=>{if(!k||he.current)return;let te=new URLSearchParams(window.location.search),Q=te.get("payment_intent"),pe=te.get("payment_intent_client_secret"),W=te.get("redirect_status");!Q||!pe||(he.current=!0,(async()=>{try{if(g(!0),W==="failed"){b?.("PayPal payment was declined. Please try again.");return}let J=k.getRawProvider();if(!J?.retrievePaymentIntent){b?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:me,error:Me}=await J.retrievePaymentIntent(pe);if(Me){b?.(Me.message??"Failed to retrieve PayPal payment status.");return}if(me&&(me.status==="requires_capture"||me.status==="succeeded")){let we=typeof me.payment_method=="string"?me.payment_method:me.payment_method?.id;ae({id:we??me.id,type:"card",threeDSecureActionResultTokenId:me.id,isPaypal:!0});let be=new URL(window.location.href);be.searchParams.delete("payment_intent"),be.searchParams.delete("payment_intent_client_secret"),be.searchParams.delete("redirect_status"),window.history.replaceState({},"",be.toString())}else b?.("PayPal payment was not completed. Please try again.")}catch(J){b?.(J instanceof Error?J.message:"Failed to complete PayPal payment.")}finally{g(!1)}})())},[k,ae,b]);let U=(0,fn.useCallback)(async()=>{if(!(!k||!F))try{if(g(!0),b?.(null),!e||!l)throw new yi.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let te=await k.confirmPayPalPayment({billingApiUrl:z,sessionId:e,nonce:t,email:l,returnUrl:window.location.href});if(te.error){b?.(te.error.message);return}te.paymentIntentId&&(te.status==="succeeded"||te.status==="processing"||te.status==="requires_capture")&&ae({id:te.paymentMethodId??te.paymentIntentId,type:"card",threeDSecureActionResultTokenId:te.paymentIntentId,isPaypal:!0})}catch(te){b?.(te instanceof Error?te.message:"PayPal payment failed. Please try again.")}finally{g(!1)}},[k,F,e,t,l,z,ae,b]);return!k||!F?(0,yn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,yn.jsxs)(yn.Fragment,{children:[!v&&(0,yn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,yn.jsx)("div",{style:v?{}:{display:"none"},children:(0,yn.jsx)("button",{type:"button",onClick:U,disabled:M||_,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:M||_?"not-allowed":"pointer",opacity:M||_?.6:1},ref:()=>x(!0),children:M?"Processing...":"PayPal"})}),(M||_)&&(0,yn.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,yn.jsx)("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}var De=require("react"),yo=require("@flopay/js"),$t=require("@flopay/shared");var gn=require("react/jsx-runtime"),As=44;function gi(e){return new Promise(t=>setTimeout(t,e))}function Fs(e,t){return e instanceof $t.FloPayError?e:new $t.FloPayError(e instanceof Error?e.message:t,"api_error")}function Ds(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Ls(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function hi({sessionId:e,nonce:t,createSession:n,paymentMethodId:l,checkoutMethod:o,clientId:s,products:m,items:d,subscriptions:I,account:N,successUrl:b,cancelUrl:_,couponCodes:k,tagsData:F,utmMetadata:p,billingApiUrl:v,locale:x,theme:M,appearance:g,buttonsTheme:he,buttonsStyles:z,onSuccess:ue,onError:ae,onDecline:U,children:te,disabled:Q=!1,type:pe="button",style:W,...J}){let me=(0,De.useMemo)(()=>(0,$t.resolveBillingApiUrl)(v),[v]),Me=(0,De.useMemo)(()=>Ls({createSession:n,clientId:s,products:m,items:d,subscriptions:I,account:N,successUrl:b,cancelUrl:_,couponCodes:k,tagsData:F,utmMetadata:p}),[N,_,s,k,n,m,d,I,b,F,p]),[we,be]=(0,De.useState)(!1),[ie,Ce]=(0,De.useState)(null),[Be,se]=(0,De.useState)(null),[Ee,_e]=(0,De.useState)(null),Re=(0,De.useRef)(!0),Z=(0,De.useRef)(null),T=(0,De.useRef)(Ee),ce=(0,De.useRef)(ue),Oe=(0,De.useRef)(ae),ze=(0,De.useRef)(U);(0,De.useEffect)(()=>{T.current=Ee},[Ee]),(0,De.useEffect)(()=>{ce.current=ue},[ue]),(0,De.useEffect)(()=>{Oe.current=ae},[ae]),(0,De.useEffect)(()=>{ze.current=U},[U]),(0,De.useEffect)(()=>(Re.current=!0,()=>{Re.current=!1,Z.current?.abort()}),[]),(0,De.useEffect)(()=>{if(typeof window>"u")return;let h=ke=>{ke.key==="Escape"&&_e(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let ye=(0,De.useCallback)((h,ke=Tr)=>{ze.current?.(wt(ke,h,{code:h.code,declineCode:h.declineCode}))},[]),E=(0,De.useCallback)(async h=>{Re.current&&(se(null),Ce("success"),await gi(_n),Re.current&&ce.current?.(h))},[]),re=(0,De.useCallback)(async(h,ke)=>{Re.current&&(Oe.current?.(h),ke?.emitDecline&&ye(h,ke.method),se(h.message),Ce("error"),await gi(Cn))},[ye]),oe=(0,De.useCallback)(async(h,ke,dt)=>{let nt=h.data.session??null;if(!nt)throw new $t.FloPayError("No session data returned","api_error");let Qe=nt.clientSecret||t;if(nt.status==="complete"){await E({result:{status:"succeeded"},session:nt,sessionId:nt.id||ke,autoCompleted:!1});return}if(nt.status==="expired")throw new $t.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(h.autoProcessingPending){let Ke=(await new yo.PaymentAPI(me).waitForCheckoutSessionCompletion(h.autoProcessingPending.sessionId,{initialDelayMs:h.autoProcessingPending.retryAfterMs})).data.session;if(!Ke||Ke.status!=="complete")throw new $t.FloPayError("Automatic payment failed. Please try again.","api_error",{code:Ke?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await E({result:{status:"succeeded"},session:Ke,sessionId:Ke.id||ke,autoCompleted:!1});return}if(h.autoProcessingError){if(h.autoProcessingError.type==="3ds_required"&&h.autoProcessingError.nextActionRedirectUrl&&ke&&Qe){let Ze=new AbortController;Z.current=Ze;let xe;try{xe=await ri({billingApiUrl:me,sessionId:ke,nonce:Qe,nextActionRedirectUrl:h.autoProcessingError.nextActionRedirectUrl,signal:Ze.signal})}finally{Z.current===Ze&&(Z.current=null)}if(xe.status==="declined")throw Un({type:xe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:xe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let Je=(await new yo.PaymentAPI(me).waitForCheckoutSessionCompletion(ke,{initialDelayMs:0,nonce:Qe})).data.session;if(!Je||Je.status!=="complete")throw Un({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await E({result:{status:"succeeded"},session:Je,sessionId:Je.id||ke,autoCompleted:!1});return}throw Un(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(dt?.fromCreateSession&&h.autoProcessingAttempted===!0)throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ye=await dr({billingApiUrl:me,sessionId:ke??nt.id,session:nt,nonce:Qe});if(Ye.type!=="success")throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await E({result:Ye.result,session:nt,sessionId:nt.id||ke,autoCompleted:!1})}catch(Ye){let Ze=Jn(Ye),xe=nt.id||ke;await re(Ze,{emitDecline:!0,method:Ze.checkoutMethod??Tr}),Ds(Ze,xe)&&xe&&Re.current&&_e({sessionId:xe,errorMessage:Ze.message,nonce:Qe||void 0})}},[t,me,re,E]),$e=(0,De.useCallback)(async h=>{if(J.onClick?.(h),!(h.defaultPrevented||Q||we)){if(_e(null),e&&Me){let ke=new $t.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await re(ke),Re.current&&(Ce(null),se(null));return}if(!e&&!Me){let ke=new $t.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await re(ke),Re.current&&(Ce(null),se(null));return}be(!0),se(null),Ce("processing");try{let ke=new yo.PaymentAPI(me);if(e){let dt=await ke.getUnifiedCheckoutSession(e,t);await oe(dt,e);return}try{let dt=await ke.createAndFetchSession({...Me});await oe(dt,dt.data.session?.id??null,{fromCreateSession:!0})}catch(dt){if(dt instanceof $t.FloPayError&&dt.code==="session_auto_completed"){await E({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw dt}}catch(ke){await re(Fs(ke,"Automatic payment failed. Please try again."))}finally{Re.current&&(Ce(null),se(null),be(!1))}}},[J,Me,Q,we,t,oe,me,e,re,E]),ct=(0,De.useCallback)(h=>{let ke=T.current;_e(null),ce.current?.({result:h,session:null,sessionId:ke?.sessionId??null,autoCompleted:!1})},[]),He=(0,De.useCallback)(h=>{Oe.current?.(h)},[]),ot=(0,De.useCallback)(h=>{ze.current?.(h)},[]),V=(0,De.useMemo)(()=>(0,$t.resolveTheme)(M),[M]),G=(0,De.useMemo)(()=>{let h=V?.buttonsLayout??(0,$t.resolveButtonsLayoutTheme)(he);return z?{...h,...z,cardButton:{...h.cardButton,...z.cardButton}}:h},[V,he,z]),tt=(0,De.useMemo)(()=>{let h=V?.appearance;return g?h?{...h,...g,variables:{...h.variables,...g.variables}}:g:h},[g,V]),Ae=tt?.variables,at=Ae?.colorPrimary??"#4A49FF",Ge=Ae?.colorPrimaryHover??to(at,.12),We=Ae?.borderRadius??"8px";return(0,gn.jsxs)(gn.Fragment,{children:[(0,gn.jsx)("button",{...J,type:pe,onClick:$e,disabled:Q||we,"aria-busy":we,style:{width:"100%",...te===void 0?{boxSizing:"border-box",height:As,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...G.cardButton,...No({themeBundle:V,resolvedPrimaryColor:at,resolvedBorderRadius:We,submitButtonStyle:G.submitButton,explicitPrimaryColor:Ae?.colorPrimary}),fontSize:G.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Q||we?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Q||we?.6:1,...W},onMouseEnter:h=>{J.onMouseEnter?.(h),!h.defaultPrevented&&!Q&&!we&&(V||Ae?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Ge)},onMouseLeave:h=>{J.onMouseLeave?.(h),!h.defaultPrevented&&(V||Ae?.colorPrimary)&&(h.currentTarget.style.backgroundColor=at)},onMouseDown:h=>{J.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{J.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,gn.jsx)(rr,{content:te})}),ie&&(0,gn.jsx)(Sn,{status:ie,errorMessage:Be}),Ee&&(0,gn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&_e(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,gn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,gn.jsx)(mo,{sessionId:Ee.sessionId,nonce:Ee.nonce,checkoutMode:"full",billingApiUrl:me,locale:x,theme:M,...tt?{appearance:tt}:{},buttonsTheme:he,buttonsStyles:z,initialErrorMessage:Ee.errorMessage,cardTitleContent:null,onComplete:ct,onError:He,onDecline:ot})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useElements,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}return(0,R.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&I(Pr),n&&(s||a)&&I(Pr),n&&(0,R.jsx)("button",{type:"button",onClick:()=>{e?.("card"),w(!0)},style:{width:"100%",...x,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:u.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...u.cardButton},onMouseDown:h=>{h.currentTarget.style.transform="scale(0.985)"},onMouseUp:h=>{h.currentTarget.style.transform="scale(1)"},children:(0,R.jsx)(sr,{content:S})}),(0,R.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Mi=require("@flopay/shared");var nr=require("react");var wi=require("react/jsx-runtime");function vi(e,t){function n({className:s,id:a,style:c,options:p,onChange:d,onReady:S,onFocus:$,onBlur:P,onEscape:E}){let w=(0,nr.useRef)(null),_=(0,nr.useRef)(null),{elements:u,reportInteractive:b}=(0,nr.useContext)(xn);return(0,nr.useEffect)(()=>{if(!u||!w.current)return;let I=!0;return(async()=>{let x=u.getElement(e);x||(x=await u.create(e,p)),!(!I||!w.current)&&(x.mount(w.current),_.current=x,d&&x.on("change",d),x.on("ready",()=>{b?.(),S?.()}),$&&x.on("focus",$),P&&x.on("blur",P),E&&x.on("escape",E))})(),()=>{if(I=!1,_.current){try{_.current.unmount()}catch{}_.current=null}}},[u,b]),(0,wi.jsx)("div",{ref:w,className:s,id:a,style:c})}return n.displayName=t,n}var Ci=vi("payment","PaymentElement"),Si=vi("address","AddressElement");var Et=require("react"),ko=require("@flopay/js"),mn=require("@flopay/shared");var br=require("react/jsx-runtime"),qr=class extends mn.FloPayError{constructor(t,n,s){super(t,n,s),this.name="FloPayCardSetupError",this.retryable=s.retryable}};function ki(e,t={}){let n=e instanceof mn.FloPayError?e:void 0,s=n?.statusCode,a=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof s=="number"&&s>=500||n?.code==="vault_capture_timeout"||!n);return new qr(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:a,...n?.param?{param:n.param}:{},...s!==void 0?{statusCode:s}:{}})}function Ri({sessionId:e,nonce:t,billingApiUrl:n,telemetry:s,theme:a,containerStyle:c,loading:p=null,onReady:d,onComplete:S,onDecline:$,onCancel:P,onValidation:E,onError:w}){let[_,u]=(0,Et.useState)(null),[b,I]=(0,Et.useState)(null),[x,h]=(0,Et.useState)(null),me=(0,Et.useRef)(d),T=(0,Et.useRef)(w),ce=(0,Et.useRef)(S),ne=(0,Et.useRef)($),q=(0,Et.useRef)(P),Q=(0,Et.useRef)(E),W=(0,Et.useRef)(!1),ie=(0,Et.useRef)(!1),K=(0,Et.useRef)(0);return me.current=d,T.current=w,ce.current=S,ne.current=$,q.current=P,Q.current=E,(0,Et.useEffect)(()=>{let L=K.current+1;return K.current=L,()=>{queueMicrotask(()=>{K.current===L&&(W.current||ie.current||(ie.current=!0,Ge(()=>{q.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Et.useEffect)(()=>{let L=!0,re=new ko.PaymentAPI((0,mn.resolveBillingApiUrl)(n),{telemetry:s});return u(null),I(null),h(null),W.current=!1,ie.current=!1,(async()=>{try{if(!e.trim())throw new mn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new mn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ye=await re.getUnifiedCheckoutSession(e,t);if(!L)return;let ue=ye.data.session;if(!ue||!(0,mn.isCardSetupCheckoutSession)(ue))throw new mn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let pe=ue.vault;if(pe?.html?.trim()||(pe=await re.getVaultCapture(e,t)),!pe.html?.trim())throw new mn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!L)return;I(pe),u(new ko.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:s}))}catch(ye){if(!L)return;let ue=ki(ye);W.current=!0,h(ue),Ge(()=>T.current?.(ue))}})(),()=>{L=!1,re.destroy()}},[n,t,e,s]),(0,Et.useEffect)(()=>{if(!_)return;let L=_.on("complete",ye=>{W.current=!0,Ge(()=>{ce.current?.({status:"succeeded",sessionId:e,...ye.paymentMethod?{paymentMethod:ye.paymentMethod}:{}})})}),re=_.on("decline",ye=>{W.current=!0,Ge(()=>{ne.current?.({status:"declined",sessionId:e,...ye.declineReason?{reason:ye.declineReason}:{},...ye.message?{message:ye.message}:{}})})});return()=>{L(),re()}},[_,e]),x?(0,br.jsx)("div",{role:"alert",children:x.message}):!_||!b?.html?(0,br.jsx)(br.Fragment,{children:p}):(0,br.jsx)(cr,{capture:_,html:b.html,messageToken:b.messageToken,expectedOrigin:b.expectedOrigin,theme:a,containerStyle:c,onReady:()=>{Ge(()=>me.current?.())},onValidation:L=>{Ge(()=>Q.current?.(L))},onError:L=>{if(!L)return;let re=ki(new Error(L),{code:"card_setup_widget_failed",retryable:!0});Ge(()=>T.current?.(re))}})}var Ei=require("@flopay/js"),Ii=require("@flopay/shared"),fn=require("react");var yn=require("react/jsx-runtime");function _i({sessionId:e,nonce:t,billingApiUrl:n,email:s,userId:a,firstName:c,lastName:p,chv:d,onTokenizedBody:S,onComplete:$,onErrorChange:P,isProcessing:E=!1}){let w=dn(),_=ro(),u=oo(),[b,I]=(0,fn.useState)(!1),[x,h]=(0,fn.useState)(!1),me=(0,fn.useRef)(!1),T=(n||u).replace(/\/+$/,""),ce=(0,fn.useCallback)(async Q=>{try{let ie=await new Ei.PaymentAPI(T).processPayment(a??"",{sessionId:e,nonce:t,tokenizedData:Q,accountData:{userId:a??"",email:s??"",firstName:c??"",lastName:p??""},chv:d});if(ie.ok){$?.();return}let K=await ie.json().catch(()=>null);P?.(K?.message??"Payment failed. Please try again.")}catch(W){P?.(W instanceof Error?W.message:"An unexpected error occurred")}},[T,e,t,a,s,c,p,d,$,P]),ne=(0,fn.useCallback)(Q=>{S?S(Q):ce(Q)},[S,ce]);(0,fn.useEffect)(()=>{if(!w||me.current)return;let Q=new URLSearchParams(window.location.search),W=Q.get("payment_intent"),ie=Q.get("payment_intent_client_secret"),K=Q.get("redirect_status");!W||!ie||(me.current=!0,(async()=>{try{if(h(!0),K==="failed"){P?.("PayPal payment was declined. Please try again.");return}let L=w.getRawProvider();if(!L?.retrievePaymentIntent){P?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:re,error:ye}=await L.retrievePaymentIntent(ie);if(ye){P?.(ye.message??"Failed to retrieve PayPal payment status.");return}if(re&&(re.status==="requires_capture"||re.status==="succeeded")){let ue=typeof re.payment_method=="string"?re.payment_method:re.payment_method?.id;ne({id:ue??re.id,type:"card",threeDSecureActionResultTokenId:re.id,isPaypal:!0});let pe=new URL(window.location.href);pe.searchParams.delete("payment_intent"),pe.searchParams.delete("payment_intent_client_secret"),pe.searchParams.delete("redirect_status"),window.history.replaceState({},"",pe.toString())}else P?.("PayPal payment was not completed. Please try again.")}catch(L){P?.(L instanceof Error?L.message:"Failed to complete PayPal payment.")}finally{h(!1)}})())},[w,ne,P]);let q=(0,fn.useCallback)(async()=>{if(!(!w||!_))try{if(h(!0),P?.(null),!e||!s)throw new Ii.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let Q=await w.confirmPayPalPayment({billingApiUrl:T,sessionId:e,nonce:t,email:s,returnUrl:window.location.href});if(Q.error){P?.(Q.error.message);return}Q.paymentIntentId&&(Q.status==="succeeded"||Q.status==="processing"||Q.status==="requires_capture")&&ne({id:Q.paymentMethodId??Q.paymentIntentId,type:"card",threeDSecureActionResultTokenId:Q.paymentIntentId,isPaypal:!0})}catch(Q){P?.(Q instanceof Error?Q.message:"PayPal payment failed. Please try again.")}finally{h(!1)}},[w,_,e,t,s,T,ne,P]);return!w||!_?(0,yn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,yn.jsxs)(yn.Fragment,{children:[!b&&(0,yn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,yn.jsx)("div",{style:b?{}:{display:"none"},children:(0,yn.jsx)("button",{type:"button",onClick:q,disabled:x||E,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:x||E?"not-allowed":"pointer",opacity:x||E?.6:1},ref:()=>I(!0),children:x?"Processing...":"PayPal"})}),(x||E)&&(0,yn.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,yn.jsx)("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}var Fe=require("react"),Ro=require("@flopay/js"),Yt=require("@flopay/shared");var gn=require("react/jsx-runtime"),Hs=44;function xi(e){return new Promise(t=>setTimeout(t,e))}function Ws(e,t){return e instanceof Yt.FloPayError?e:new Yt.FloPayError(e instanceof Error?e.message:t,"api_error")}function Ys(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Gs(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 Ti({sessionId:e,nonce:t,createSession:n,paymentMethodId:s,checkoutMethod:a,clientId:c,products:p,items:d,subscriptions:S,account:$,successUrl:P,cancelUrl:E,couponCodes:w,tagsData:_,utmMetadata:u,billingApiUrl:b,locale:I,theme:x,appearance:h,buttonsTheme:me,buttonsStyles:T,onSuccess:ce,onError:ne,onDecline:q,children:Q,disabled:W=!1,type:ie="button",style:K,...L}){let re=(0,Fe.useMemo)(()=>(0,Yt.resolveBillingApiUrl)(b),[b]),ye=(0,Fe.useMemo)(()=>Gs({createSession:n,clientId:c,products:p,items:d,subscriptions:S,account:$,successUrl:P,cancelUrl:E,couponCodes:w,tagsData:_,utmMetadata:u}),[$,E,c,w,n,p,d,S,P,_,u]),[ue,pe]=(0,Fe.useState)(!1),[se,Se]=(0,Fe.useState)(null),[De,le]=(0,Fe.useState)(null),[je,Oe]=(0,Fe.useState)(!1),[_e,X]=(0,Fe.useState)(null),k=(0,Fe.useRef)(!0),de=(0,Fe.useRef)(null),Ve=(0,Fe.useRef)(_e),Ue=(0,Fe.useRef)(ce),ge=(0,Fe.useRef)(ne),B=(0,Fe.useRef)(q);(0,Fe.useEffect)(()=>{Ve.current=_e},[_e]),(0,Fe.useEffect)(()=>{Ue.current=ce},[ce]),(0,Fe.useEffect)(()=>{ge.current=ne},[ne]),(0,Fe.useEffect)(()=>{B.current=q},[q]),(0,Fe.useEffect)(()=>(k.current=!0,()=>{k.current=!1,de.current?.abort()}),[]),(0,Fe.useEffect)(()=>{if(typeof window>"u")return;let M=we=>{we.key==="Escape"&&X(null)};return window.addEventListener("keydown",M),()=>{window.removeEventListener("keydown",M)}},[]);let fe=(0,Fe.useCallback)((M,we=Nr)=>{B.current?.(Rt(we,M,{code:M.code,declineCode:M.declineCode}))},[]),Z=(0,Fe.useCallback)(async M=>{k.current&&(le(null),Oe(M.result.status==="authorized"),Se("success"),await xi(Mn),k.current&&Ue.current?.(M))},[]),xe=(0,Fe.useCallback)(async(M,we)=>{k.current&&(ge.current?.(M),we?.emitDecline&&fe(M,we.method),le(M.message),Oe(!1),Se("error"),await xi(Sn))},[fe]),ut=(0,Fe.useCallback)(async(M,we,Xe)=>{let Te=M.data.session??null;if(!Te)throw new Yt.FloPayError("No session data returned","api_error");let vt=Te.clientSecret||t;if(mr(Te)){await Z({result:Qn(Te,we),session:Te,sessionId:Te.id||we,autoCompleted:!1});return}if(Te.status==="expired")throw ao(Te);try{if(M.autoProcessingPending){let et=(await new Ro.PaymentAPI(re).waitForCheckoutSessionCompletion(M.autoProcessingPending.sessionId,{initialDelayMs:M.autoProcessingPending.retryAfterMs})).data.session;if(!mr(et))throw io(et);await Z({result:Qn(et,we),session:et,sessionId:et.id||we,autoCompleted:!1});return}if(M.autoProcessingError){if(M.autoProcessingError.type==="3ds_required"&&M.autoProcessingError.nextActionRedirectUrl&&we&&vt){let He=new AbortController;de.current=He;let ot;try{ot=await yi({billingApiUrl:re,sessionId:we,nonce:vt,nextActionRedirectUrl:M.autoProcessingError.nextActionRedirectUrl,signal:He.signal})}finally{de.current===He&&(de.current=null)}if(ot.status==="declined")throw qn({type:ot.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:ot.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:M.autoProcessingError.checkoutMethod});let it=(await new Ro.PaymentAPI(re).waitForCheckoutSessionCompletion(we,{initialDelayMs:0,nonce:vt})).data.session;if(!mr(it))throw qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:M.autoProcessingError.checkoutMethod});await Z({result:Qn(it,we),session:it,sessionId:it.id||we,autoCompleted:!1});return}throw qn(M.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:M.autoProcessingError.checkoutMethod})}if(Xe?.fromCreateSession&&M.autoProcessingAttempted===!0)throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let We=await hr({billingApiUrl:re,sessionId:we??Te.id,session:Te,nonce:vt});if(We.type!=="success")throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Z({result:We.result,session:Te,sessionId:Te.id||we,autoCompleted:!1})}catch(We){let He=er(We),ot=Te.id||we;await xe(He,{emitDecline:!0,method:He.checkoutMethod??Nr}),Ys(He,ot)&&ot&&k.current&&X({sessionId:ot,errorMessage:He.message,nonce:vt||void 0})}},[t,re,xe,Z]),Ze=(0,Fe.useCallback)(async M=>{if(L.onClick?.(M),!(M.defaultPrevented||W||ue)){if(X(null),e&&ye){let we=new Yt.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await xe(we),k.current&&(Se(null),le(null));return}if(!e&&!ye){let we=new Yt.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await xe(we),k.current&&(Se(null),le(null));return}pe(!0),le(null),Oe(!1),Se("processing");try{let we=new Ro.PaymentAPI(re);if(e){let Xe=await we.getUnifiedCheckoutSession(e,t);await ut(Xe,e);return}try{let Xe=await we.createAndFetchSession({...ye});await ut(Xe,Xe.data.session?.id??null,{fromCreateSession:!0})}catch(Xe){if(Xe instanceof Yt.FloPayError&&Xe.code==="session_auto_completed"){await Z({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Xe}}catch(we){await xe(Ws(we,"Automatic payment failed. Please try again."))}finally{k.current&&(Se(null),le(null),pe(!1))}}},[L,ye,W,ue,t,ut,re,e,xe,Z]),pt=(0,Fe.useCallback)(M=>{let we=Ve.current;X(null),Ue.current?.({result:M,session:null,sessionId:we?.sessionId??null,autoCompleted:!1})},[]),z=(0,Fe.useCallback)(M=>{ge.current?.(M)},[]),ee=(0,Fe.useCallback)(M=>{B.current?.(M)},[]),rt=(0,Fe.useMemo)(()=>(0,Yt.resolveTheme)(x),[x]),Ke=(0,Fe.useMemo)(()=>{let M=rt?.buttonsLayout??(0,Yt.resolveButtonsLayoutTheme)(me);return T?{...M,...T,cardButton:{...M.cardButton,...T.cardButton}}:M},[rt,me,T]),mt=(0,Fe.useMemo)(()=>{let M=rt?.appearance;return h?M?{...M,...h,variables:{...M.variables,...h.variables}}:h:M},[h,rt]),$e=mt?.variables,Je=$e?.colorPrimary??"#4A49FF",Gt=$e?.colorPrimaryHover??po(Je,.12),Qe=$e?.borderRadius??"8px";return(0,gn.jsxs)(gn.Fragment,{children:[(0,gn.jsx)("button",{...L,type:ie,onClick:Ze,disabled:W||ue,"aria-busy":ue,style:{width:"100%",...Q===void 0?{boxSizing:"border-box",height:Hs,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Ke.cardButton,...Go({themeBundle:rt,resolvedPrimaryColor:Je,resolvedBorderRadius:Qe,submitButtonStyle:Ke.submitButton,explicitPrimaryColor:$e?.colorPrimary}),fontSize:Ke.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:W||ue?"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||ue?.6:1,...K},onMouseEnter:M=>{L.onMouseEnter?.(M),!M.defaultPrevented&&!W&&!ue&&(rt||$e?.colorPrimary)&&(M.currentTarget.style.backgroundColor=Gt)},onMouseLeave:M=>{L.onMouseLeave?.(M),!M.defaultPrevented&&(rt||$e?.colorPrimary)&&(M.currentTarget.style.backgroundColor=Je)},onMouseDown:M=>{L.onMouseDown?.(M),M.defaultPrevented||(M.currentTarget.style.transform="scale(0.985)")},onMouseUp:M=>{L.onMouseUp?.(M),M.defaultPrevented||(M.currentTarget.style.transform="scale(1)")},children:(0,gn.jsx)(sr,{content:Q})}),se&&(0,gn.jsx)(wn,{status:se,errorMessage:De,authorized:je}),_e&&(0,gn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:M=>{M.target===M.currentTarget&&X(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,gn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,gn.jsx)(wo,{sessionId:_e.sessionId,nonce:_e.nonce,checkoutMode:"full",billingApiUrl:re,locale:I,theme:x,...mt?{appearance:mt}:{},buttonsTheme:me,buttonsStyles:T,initialErrorMessage:_e.errorMessage,cardTitleContent:null,onComplete:pt,onError:z,onDecline:ee})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useElements,useFloPay,usePayPalFloPay});
|