@flopay/react 1.4.21 → 1.4.23
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 +7 -2
- package/dist/index.cjs +8 -8
- package/dist/index.d.cts +10 -3
- package/dist/index.d.ts +10 -3
- package/dist/index.mjs +8 -8
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
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:`
|
|
1
|
+
"use strict";var Xi=Object.create;var to=Object.defineProperty;var Qi=Object.getOwnPropertyDescriptor;var Zi=Object.getOwnPropertyNames;var es=Object.getPrototypeOf,ts=Object.prototype.hasOwnProperty;var ns=(e,t)=>{for(var n in t)to(e,n,{get:t[n],enumerable:!0})},La=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Zi(t))!ts.call(e,r)&&r!==n&&to(e,r,{get:()=>t[r],enumerable:!(i=Qi(t,r))||i.enumerable});return e};var za=(e,t,n)=>(n=e!=null?Xi(es(e)):{},La(t||!e||!e.__esModule?to(n,"default",{value:e,enumerable:!0}):n,e)),rs=e=>La(to({},"__esModule",{value:!0}),e);var Xs={};ns(Xs,{AddressElement:()=>wi,DirectPayPalButton:()=>zr,FloPayAutomaticPaymentButton:()=>Mi,FloPayCardSetup:()=>Ei,FloPayCardSetupError:()=>Vr,FloPayCheckout:()=>ko,FloPayProvider:()=>Ar,PayPalButton:()=>xi,PaymentElement:()=>Si,SplitCardForm:()=>go,VaultCardFields:()=>ur,dropThirdPartyOnlyError:()=>Ai.dropThirdPartyOnlyError,useCheckout:()=>Va,useElements:()=>ao,useFloPay:()=>mn,usePayPalFloPay:()=>oo});module.exports=rs(Xs);var os=()=>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=os();var Rt=require("react"),Oa=require("@flopay/shared");var $o=require("react"),Mn=(0,$o.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),pn=(0,$o.createContext)({session:null,loading:!1,error:null});var as=Symbol.for("@flopay/js.telemetry.bridge.v1"),is=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function ss(){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 ls(e){let t=ss(),n=(r,s)=>r?r.bind(e):s,i=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:i,elapsed:e.elapsed?e.elapsed.bind(e):r=>Math.max(0,i()-r),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 no(e){let t=globalThis[is];return ls(t?.(e)??{})}function Tt(e){if(e)return e[as]}var Na=require("react/jsx-runtime");function Ar({flopay:e,paypalFlopay:t,options:n,children:i}){let[r,s]=(0,Rt.useState)(e instanceof Promise?null:e),[u,d]=(0,Rt.useState)(t instanceof Promise||!t?null:t),[v,A]=(0,Rt.useState)(null),h=(0,Rt.useRef)(null),E=(0,Rt.useRef)(null),S=(0,Rt.useRef)(null);(0,Rt.useEffect)(()=>{if(!r)return;let I=Tt(r);return h.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[r]),(0,Rt.useEffect)(()=>{let I=!1;return e instanceof Promise?e.then(x=>{I||s(x)}):s(e),()=>{I=!0}},[e]),(0,Rt.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,Rt.useEffect)(()=>{if(!r){A(null);return}let I=r.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return A(I),()=>{I.destroy()}},[r,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,Rt.useEffect)(()=>{if(!r||!v||E.current===v)return;E.current=v;let I=Tt(r);I?.log({name:"checkout.rendered",stage:"checkout_render"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(h.current??0),durationMode:"machine"})},[v,r]);let _=(0,Rt.useCallback)(()=>{if(!r||!v||S.current===v)return;S.current=v;let I=Tt(r);I?.log({name:"checkout.interactive",stage:"checkout_interactive"}),I?.performance({stage:"checkout_interactive",durationMs:I.elapsed(h.current??0),durationMode:"machine"})},[v,r]),p=(0,Oa.resolveBillingApiUrl)(n?.billingApiUrl),P=(0,Rt.useMemo)(()=>({flopay:r,paypalFlopay:u,elements:v,billingApiUrl:p,reportInteractive:_}),[r,u,v,p,_]);return(0,Na.jsx)(Mn.Provider,{value:P,children:i})}var D=za(require("react"),1),nr=require("@flopay/js"),we=require("@flopay/shared");var dl=require("react"),ut=require("react/jsx-runtime");function cs(){return(0,ut.jsxs)(ut.Fragment,{children:[(0,ut.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,ut.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,ut.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,ut.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,ut.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function ds(){return(0,ut.jsx)(ut.Fragment,{children:"Go back"})}function us(){return(0,ut.jsx)(ut.Fragment,{children:"Secure card checkout"})}function sr(e){return e!==void 0&&(e===""||e===null||e===!1)}function lr({content:e}){return(0,ut.jsx)(ut.Fragment,{children:e===void 0?(0,ut.jsx)(cs,{}):e})}function cr({content:e}){return(0,ut.jsx)(ut.Fragment,{children:e===void 0?(0,ut.jsx)(ds,{}):e})}function Br({content:e}){return(0,ut.jsx)(ut.Fragment,{children:e===void 0?(0,ut.jsx)(us,{}):e})}var gt=require("@stripe/react-stripe-js"),C=require("@flopay/shared");function dr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let i=parseInt(n[1],16),r=Math.max(0,Math.min(1,1-t)),s=Math.round((i>>16&255)*r),u=Math.round((i>>8&255)*r),d=Math.round((i&255)*r);return`#${(1<<24|s<<16|u<<8|d).toString(16).slice(1)}`}function qo(e){if(typeof e=="number"||typeof e=="string")return e}function ro({appearance:e,buttonsStyles:t,layout:n="default"}){let i=e?.variables,r=A=>typeof A=="string"&&A?A:void 0,s=t.submitButton,u=r(i?.colorPrimary)??r(s?.backgroundColor)??"#4A49FF",d=n==="buttons",v=t.nameInput;return{primaryColor:u,primaryHoverColor:r(i?.colorPrimaryHover)??dr(u,.12),inputBackgroundColor:r(t.cardInputBackground)??r(i?.colorBackground)??"#ffffff",textColor:r(t.cardInputColor)??r(v?.color)??r(i?.colorText)??"#262833",borderColor:r(t.cardInputBorder)??(d?"#e5e7eb":"#A4A4FF"),placeholderColor:r(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:r(i?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:r(v?.fontFamily)??r(i?.fontFamily)??"Poppins, sans-serif",fontSize:r(t.cardInputFontSize)??r(i?.fontSizeBase)??"16px",fontWeight:String(qo(v?.fontWeight)??400),borderRadius:r(i?.borderRadius)??"8px"}}var gn=require("@flopay/js");var An=require("react"),Ua=require("react/jsx-runtime");function ur({capture:e,html:t,messageToken:n,expectedOrigin:i,theme:r,containerStyle:s,onReady:u,onError:d,onValidation:v}){let A=(0,An.useRef)(null),h=(0,An.useRef)(u),E=(0,An.useRef)(d),S=(0,An.useRef)(v);h.current=u,E.current=d,S.current=v;let _=(0,An.useRef)(r);return _.current=r,(0,An.useEffect)(()=>{let p=A.current;if(!p)return;let P=!0,I=!1,x=()=>{!P||I||(I=!0,h.current?.())},g=e.on("ready",()=>{x()}),ye=e.on("error",oe=>{E.current?.(oe.message??"There was a problem loading the secure card form.")}),R=e.on("validation",oe=>{S.current?.(oe.message??null)}),pe={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},..._.current?{theme:_.current}:{}};return e.mount(p,pe).then(()=>{x()}).catch(oe=>{P&&E.current?.(oe instanceof Error?oe.message:"Failed to load the secure card form.")}),()=>{P=!1,g(),ye(),R(),e.unmount()}},[e,t,n,i]),(0,An.useEffect)(()=>{r&&e.applyTheme?.(r)},[e,r]),(0,Ua.jsx)("div",{ref:A,"data-testid":"flopay-vault-card-fields",style:s})}var bl=require("react"),Fr=require("react/jsx-runtime");function pr({children:e,margin:t,icon:n=!0,styleOverride:i}){return(0,Fr.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"}:{},...i??{}},children:[n&&(0,Fr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Fr.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 a=za(require("react"),1);var mr=require("react"),qa=require("@flopay/shared");function mn(){return(0,mr.useContext)(Mn).flopay}function oo(){return(0,mr.useContext)(Mn).paypalFlopay??null}function ao(){return(0,mr.useContext)(Mn).elements}function Va(){return(0,mr.useContext)(pn)}function io(){return(0,mr.useContext)(Mn).billingApiUrl||(0,qa.resolveBillingApiUrl)()}var _l=require("react"),vt=require("react/jsx-runtime"),yn=1200,Yt=1500;function sn({status:e,errorMessage:t,authorized:n=!1,processingLabel:i="PROCESSING...",successLabel:r,errorLabel:s="PAYMENT FAILED",successNote:u="You will be automatically redirected, do not close or navigate away from this window."}){return(0,vt.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,vt.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,vt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,vt.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,vt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,vt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,vt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,vt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,vt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,vt.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,vt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,vt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,vt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,vt.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,vt.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&i,e==="success"&&(r??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&s]}),e==="success"&&u!==null&&(0,vt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:u}),e==="error"&&t&&(0,vt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,vt.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 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?`
|
|
6
|
+
`})]})})}var yr=require("@flopay/shared");function ja(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 Vo(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 Ha(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}))],i=n.reduce((s,u)=>s+(u.overrideAmount??u.totalAmount??0),0),r=e.currency??n.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(i*100),currency:r,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((s,u)=>({uuid:`synthetic-${s.type??"item"}-${u}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??r,metadata:s.metadata??null}))}}function jo(e,t){return t?{...e,...t}:e}function Et(e,t,n){let i=typeof t=="string"?t:t.message,r=typeof t=="string"?n?.code:n?.code??t.code,s=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:i,...r?{code:r}:{},...s?{declineCode:s}:{}}}var ps=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function $n(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:i}of ps)if(n.test(t))return i;return e}function Zn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function fr(e){return e?.status==="authorized"||e?.status==="complete"}function Ka(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function so(e){let t=Ka(e);return new yr.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function lo(e){let t=Ka(e);return new yr.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 co(e,t){return e==="processing"||(0,yr.isMoneySettledOutcome)(e,t)}function Wa(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Ya(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Dr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var uo="flopay_recent_completion_";function gr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(uo+e,JSON.stringify(t))}catch{}}function Ho(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(uo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(uo+e),!1):!0}catch{return!1}}function Ga(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var N=require("react"),Qa=require("@paypal/paypal-js"),po=require("@flopay/js"),Fn=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 ms(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 er(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Bn(e){if(typeof e!="object"||e===null)return;let t=e;return er(t.code)??er(t.type)??er(t.name)}function hr(e){if(!(typeof e!="object"||e===null))return er(e.decline_code)}function Lr(e){return typeof e!="object"||e===null?!1:er(e.type)?.toLowerCase()==="card_error"||hr(e)!==void 0}function qn(e){let t=ms(e)?.toLowerCase()??"",i=`${Bn(e)?.toLowerCase()??""} ${t}`;return i.includes("popup")&&i.includes("block")}var fn=require("react/jsx-runtime"),mo=45,ys=1e3,fs=11e3,gs=["https://www.paypal.com","https://www.sandbox.paypal.com"],Ja="We couldn't open PayPal. Try again or choose another payment method.",hs={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 Xa(e){return e.includes("No ack for postMessage init()")&&gs.some(t=>e.includes(t))&&e.includes("10000ms")}function Ps(e){return e?`${Ja} Allow pop-ups for this site, then try again.`:Ja}function Za({sessionId:e,nonce:t,billingApiUrl:n,email:i,clientId:r,environment:s,currency:u,isSubscription:d,onTokenizedBody:v,onComplete:A,onErrorChange:h,onDecline:E,onTechnicalFailure:S,isProcessing:_=!1,onLoadStateChange:p,onInitializationStateChange:P,allowAutomaticRetry:I=!0,onButtonClick:x,runBeforeButtonClick:g,session:ye,existingOrderId:R,telemetry:pe,telemetryContext:oe,debug:O=!1}){let ee=mn(),Q=(0,N.useMemo)(()=>{if(ee)return null;let U=no({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Fn.SDK_VERSION,enabled:pe!==!1});return U.setCheckoutContext(oe??{}),U.beginCheckout(oe??{}),U},[n,ee,pe,oe?.checkoutMode,oe?.layout]),le=(0,N.useMemo)(()=>Tt(ee),[ee]);(0,N.useEffect)(()=>()=>{Q&&Q.flush().catch(()=>{}).finally(()=>Q.destroy())},[Q]);let j=(0,N.useMemo)(()=>({error:U=>{le?le.error(U):Q?.error(U)},log:U=>{le?le.log(U):Q?.log(U)},performance:U=>{le?le.performance(U):Q?.performance(U)},terminal:U=>{le?le.terminal(U):Q?.terminal(U)},startTiming:()=>le?.now()??Q?.now()??0,elapsed:U=>le?.elapsed(U)??Math.max(0,(Q?.now()??U)-U)}),[le,Q]),G=(0,N.useRef)(null),me=(0,N.useRef)(0),_e=(0,N.useRef)(null),be=(0,N.useRef)(!1),[ce,ae]=(0,N.useState)(!1),[ge,Z]=(0,N.useState)(!1),[X,xe]=(0,N.useState)(0),ve=(0,N.useRef)(0),[ie,W]=(0,N.useState)(!1),w=(0,N.useRef)(!1),de=(0,N.useRef)(!1),[je,$e]=(0,N.useState)(!1),[he,B]=(0,N.useState)(!1),fe=(0,N.useMemo)(()=>n.replace(/\/+$/,""),[n]),te=(0,N.useMemo)(()=>JSON.stringify([fe,r,u,s??"",d,e,R??""]),[fe,r,u,s,R,d,e]),Me=(0,N.useRef)(te),pt=Me.current!==te,[Ze,mt]=(0,N.useState)([]),L=U=>{O&&mt(lt=>[...lt,`${new Date().toISOString().slice(11,23)} ${U}`])},ne=(0,N.useRef)(v),rt=(0,N.useRef)(A),He=(0,N.useRef)(h),yt=(0,N.useRef)(E),qe=(0,N.useRef)(S),Je=(0,N.useRef)(x),Xt=(0,N.useRef)(p),Qe=(0,N.useRef)(P),Qt=(0,N.useRef)(g),T=(0,N.useRef)(ye),ke=(0,N.useRef)(i),Xe=(0,N.useRef)(t),Ae=(0,N.useRef)(null),Ct=(0,N.useRef)(0),We=(0,N.useRef)(null),Ke=(0,N.useRef)(null),ot=(0,N.useRef)(new Map),et=(0,N.useRef)(new Map),In=(0,N.useRef)(!1);(0,N.useEffect)(()=>(In.current=!0,()=>{In.current=!1}),[]),(0,N.useEffect)(()=>{ne.current=v},[v]),(0,N.useEffect)(()=>{rt.current=A},[A]),(0,N.useEffect)(()=>{He.current=h},[h]),(0,N.useEffect)(()=>{yt.current=E},[E]),(0,N.useEffect)(()=>{qe.current=S},[S]),(0,N.useEffect)(()=>{Je.current=x},[x]),(0,N.useEffect)(()=>{Xt.current=p},[p]),(0,N.useEffect)(()=>{Qe.current=P},[P]),(0,N.useEffect)(()=>{Qt.current=g},[g]),(0,N.useEffect)(()=>{T.current=ye},[ye]),(0,N.useEffect)(()=>{ke.current=i},[i]),(0,N.useEffect)(()=>{Xe.current=t},[t]),(0,N.useEffect)(()=>{ve.current=X},[X]),(0,N.useEffect)(()=>{ie&&_e.current?.focus()},[ie,X]);let st=(0,N.useCallback)(()=>{window.setTimeout(()=>{_e.current?.focus()},0)},[]),jn=(0,N.useCallback)(()=>{ae(!1),xe(U=>U+1)},[]),Ht=(0,N.useCallback)(()=>{W(!1),(G.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??G.current)?.focus?.()},[]);(0,N.useEffect)(()=>{!ce||!be.current||(be.current=!1,Ht())},[Ht,ce,X]);let vn=(0,N.useCallback)((U,lt)=>{let Ft=qe.current;if(Ft){Ft("paypal",U,lt);return}He.current?.(Ps(lt?.popupBlocked??qn(U)))},[]),Zt=()=>{We.current?.timer&&(clearTimeout(We.current.timer),We.current.timer=null)},or=()=>{Zt();let U=Ct.current+1;return Ct.current=U,Ke.current=null,We.current={generation:U,timer:null,yieldedControl:!1},W(!1),U},Mt=U=>U!==void 0&&We.current?.generation!==U?!1:(Zt(),We.current=null,Ke.current=null,!0),wt=U=>{let lt=U?.generation??We.current?.generation??Ct.current;(!U?.generation||We.current?.generation===lt)&&(Zt(),We.current=null),Ke.current=lt,U?.showRetry&&W(!0),U?.remount&&jn(),U?.focus!==!1&&st()},en=U=>We.current?.generation===U&&Ke.current!==U,tn=U=>{typeof document<"u"&&document.visibilityState!=="visible"||(Zt(),U.timer=setTimeout(()=>{We.current?.generation===U.generation&&(We.current=null,Ke.current=U.generation,vn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),W(!0),jn(),st())},600))},At=()=>{let U=We.current;U?.yieldedControl&&tn(U)},Bt=()=>{let U=We.current;U&&(U.yieldedControl=!0,Zt())},St=U=>{let lt=Ae.current;return lt&&et.current.set(U,lt),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),Zt()}},[]),(0,N.useEffect)(()=>{Me.current!==te&&(Me.current=te,w.current=!1,de.current=!1,ae(!1),Z(!1),$e(!1),Qe.current?.("loading"))},[te]),(0,N.useEffect)(()=>{Ge(()=>Xt.current?.(ce&&!je))},[ce,je]);let se=(0,Fn.normalizeGatewayEnvironment)(s);(0,N.useEffect)(()=>{let U=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",lt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(L(`mount clientId=${U} env=${s??"(unset)"}\u2192${se??"live"} ccy=${u} sub=${d}`),L(`ua=${lt.slice(0,80)}${lt.length>80?"\u2026":""}`),!r){L("FAIL: clientId empty \u2014 gateway misconfigured"),$e(!0),j.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!G.current){L("FAIL: containerRef not attached");return}me.current=j.startTiming(),j.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ft=!1,zn=!1,Oe=()=>Ft||zn,ct,Ye=!1,_n=()=>{ct=(0,Fn.generateIdempotencyKey)(),ct||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Ye=!0},xn=null,On=!1,Kn=null,Tn=!1,at=()=>{!Kn||Tn||(Tn=!0,Kn.close().catch(()=>{}))},Dt=null,ln=()=>{Dt!==null&&(j.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"overlay_return",durationMs:j.elapsed(Dt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Dt=null)},ht=!1,It=G.current,nn=null,cn=null,Kt=[],Ot=y=>{if(!y||typeof y.getBoundingClientRect!="function")return"(no rect)";let o=y.getBoundingClientRect();return`${Math.round(o.width)}\xD7${Math.round(o.height)}`},Nt=y=>{if(!y)return"(empty)";try{let o=new URL(y,typeof window<"u"?window.location.href:"https://localhost"),f=o.pathname.toLowerCase();return f.includes("checkcaptcha")||f.includes("captcha")?`CAPTCHA(${o.host}${f})`:f.includes("risk")||f.includes("challenge")?`RISK(${o.host}${f})`:f.includes("smart/buttons")?`smart-buttons(${o.host})`:`${o.host}${f}`.slice(0,100)}catch{return y.slice(0,80)}},Be=y=>{let o=y.getAttribute("src"),f=y.getAttribute("srcdoc"),z=y.getAttribute("name"),b=y.getAttribute("sandbox"),H=[];return o&&H.push(`src=${Nt(o)}`),f&&H.push(`srcdoc[${f.length}ch]`),!o&&!f&&H.push("src=(empty) srcdoc=(empty)"),z&&H.push(`name=${z.slice(0,40)}`),b!==null&&H.push(`sandbox="${b.slice(0,40)}"`),H.join(" ")},Ut=y=>{if(!(y instanceof HTMLIFrameElement))return"";try{let o=y.contentDocument;if(!o)return"cd=null";let f=o.body?.children.length??0,z=o.body?.innerHTML.length??0,b=o.head?.innerHTML.length??0;return`cd=same-origin readyState=${o.readyState} body[${f}children,${z}ch] head[${b}ch]`}catch(o){return`cd=cross-origin(${o.message.slice(0,30)})`}},ft=[],Cn=y=>{if(Oe())return;let o=y.message??String(y.error??"(no message)");o&&(o.toLowerCase().includes("paypal")||o.toLowerCase().includes("zoid")||o.toLowerCase().includes("postrobot")||o.toLowerCase().includes("storage"))&&(L(`window:error ${o.slice(0,140)}`),ft.push(o))},Wn=y=>{if(Oe())return;let o=y.reason instanceof Error?y.reason.message:String(y.reason??"(no reason)");o&&(o.toLowerCase().includes("paypal")||o.toLowerCase().includes("zoid")||o.toLowerCase().includes("postrobot")||o.toLowerCase().includes("storage"))&&(L(`window:rejection ${o.slice(0,140)}`),ft.push(o))};O&&typeof window<"u"&&(window.addEventListener("error",Cn),window.addEventListener("unhandledrejection",Wn));let $t={value:0};if(O&&typeof PerformanceObserver<"u")try{cn=new PerformanceObserver(y=>{if(!Oe())for(let o of y.getEntries()){if(!o.name.toLowerCase().includes("paypal"))continue;$t.value+=1;let f=Math.round(o.duration);L(`net ${f}ms ${o.name.slice(0,90)}`)}}),cn.observe({type:"resource",buffered:!0})}catch{}let qt=()=>{for(nn?.disconnect(),nn=null,cn?.disconnect(),cn=null;Kt.length;)clearTimeout(Kt.pop());O&&typeof window<"u"&&(window.removeEventListener("error",Cn),window.removeEventListener("unhandledrejection",Wn))},Lt=y=>{if(!y)return!1;let o=y.toLowerCase();return o.includes("zoid destroyed")||o.includes("destroyed all components")||o.includes("window closed")||o.includes("detected container element removed")},Nn=y=>{if(Oe()||Lt(y))return;let o=$n(y)??y;Ge(()=>He.current?.(o))},Un=y=>{Ft||($e(!0),y.includes("paypal_ineligible")||j.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))},rn=(y,o=!1)=>{if(Ft)return;let f=w.current||!I;if(On)return;On=!0,zn=!0,qt(),at();let z=o||Xa(y);if(z&&I&&!w.current){w.current=!0,ae(!1),B(!1),Z(!0),Qe.current?.("retrying"),xn=setTimeout(()=>{Ft||xe(b=>b+1)},ys);return}if(z||f){if(ae(!1),B(!1),Z(!1),$e(!0),Qe.current?.("exhausted"),!de.current){de.current=!0;let b=Xa(y)?"paypal_init_timeout":o?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",b)}return}Un(y)};$e(!1);let Wt=async(y,o=Ae.current)=>{if(Oe())return;let f=o?.sessionId??e;if(ne.current){await ne.current(y,{sessionId:f,accountPatch:o?.accountPatch,nonce:o?.nonce});return}let z=j.startTiming();j.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let b=()=>{j.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"processing",durationMs:j.elapsed(z),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let H=T.current,Ne=o?.accountPatch?.email??ke.current,tt=o?.accountPatch?.userId??H?.customer?.id??H?.accountData?.userId??"",K=await new po.PaymentAPI(fe,{telemetry:!1}).processPayment(tt,{sessionId:f,nonce:o?.nonce??Xe.current,tokenizedData:y,accountData:{userId:tt,email:Ne??H?.customer?.email??"",firstName:o?.accountPatch?.firstName??H?.customer?.firstName??H?.accountData?.firstName??"",lastName:o?.accountPatch?.lastName??H?.customer?.lastName??H?.accountData?.lastName??"",country:o?.accountPatch?.country??H?.customer?.country??H?.accountData?.country??void 0,zip:o?.accountPatch?.zip??H?.customer?.zip??H?.accountData?.zip??void 0}});if(K.ok){if(zn||Ft&&In.current)return;b(),j.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ge(()=>rt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Oe())return;let m=await K.json().catch(()=>null),V=m?.message??"PayPal payment failed.",Ce=$n(V)??V;b(),K.status===400&&(typeof m?.declineCode=="string"||!Array.isArray(m?.fields))?j.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):K.status===400||K.status===422?j.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):j.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:K.status>=500?"5xx":K.status>=400?"4xx":K.status>=300?"3xx":"unknown",failureCategory:K.status>=500?"server_error":void 0}),Nn(Ce),Ge(()=>yt.current?.(Et("paypal",Ce,{code:m?.code,declineCode:m?.declineCode})));return}catch(H){if(Oe())return;b(),j.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ne=H instanceof Error?H.message:"PayPal payment failed.",tt=$n(Ne)??Ne;Nn(tt),Ge(()=>yt.current?.(Et("paypal",tt)));return}},on=()=>new Fn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ve=y=>Oe()?Promise.reject(on()):Promise.resolve(y),M=async y=>{if(Oe())throw on();Ye||_n();let o=Ae.current,f=o?.sessionId??e,z=o?.nonce??Xe.current;j.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let b=await new po.PaymentAPI(fe,{telemetry:!1}).createSessionIntent(f,z??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:ct});if(Oe())throw on();if(b.provider!=="paypal")throw new Error(y);return j.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),b.providerObjectId},q=(y,o)=>{let f=o?.nonce??Xe.current;if(!f)return;let z=o?.sessionId??e,b=hr(y)??Bn(y)??"provider_declined";new po.PaymentAPI(fe,{telemetry:!1}).reportSessionIntentDecline(z,f,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:b}).catch(()=>{})},F=X;L("loadScript:scheduled (deferred 1 tick)");let Re=null,Ee=setTimeout(()=>{if(Ft){L("loadScript:skipped (cancelled before defer ran)");return}L("loadScript:start");let y=se==="live"?"production":se;Re=(0,Qa.loadScript)({clientId:r,currency:u,intent:d?"subscription":"capture",vault:d?!0:void 0,...y?{environment:y}:{},...y==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Re.then(o=>{if(L(`loadScript:resolved inactive=${Oe()} ns=${!!o} buttons=${!!o?.Buttons}`),Oe())return;if(!o?.Buttons){L("FAIL: namespace missing Buttons factory"),rn("PayPal SDK did not expose the Buttons factory.");return}j.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"provider_ready",durationMs:j.elapsed(me.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let f=async re=>{if(Oe()||ve.current!==F)return;let K=re.subscriptionID??re.orderID??"",m=K?et.current.get(K):ot.current.get(F);if(!(!m||!en(m.generation))&&Mt(m.generation)){et.current.delete(K),ot.current.delete(m.surfaceKey),ln();try{if(B(!0),Ge(()=>He.current?.(null)),!K)throw new Fn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Wt({id:K,isPaypal:!0},m)}catch(V){Nn(V instanceof Error?V.message:"PayPal capture failed.")}finally{Oe()||B(!1)}}},z=o.Buttons({style:{layout:"horizontal",height:mo,tagline:!1},onClick:async(re,K)=>{if(Oe()){await K.reject();return}_n();let m=Qt.current,V={};if(m)try{let Fe=await m("paypal");if(Oe()){await K.reject();return}if(!Fe.proceed){Ae.current=null,ot.current.delete(F),await K.reject();return}V={sessionId:Fe.sessionId,accountPatch:Fe.accountPatch,nonce:Fe.nonce}}catch(Fe){L(`onClick:runBeforeButtonClick rejected msg=${(Fe instanceof Error?Fe.message:String(Fe)).slice(0,120)}`),Ae.current=null,ot.current.delete(F),await K.reject();return}Ge(()=>Je.current?.("paypal"));let Te={generation:or(),surfaceKey:F,...V};Ae.current=Te,ot.current.set(F,Te),await K.resolve(),j.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Dt=j.startTiming()},createOrder:d?void 0:R?()=>Ve(R).then(St):()=>M("Failed to create PayPal order.").then(St),createSubscription:d?R?()=>Ve(R).then(St):()=>M("Failed to create PayPal subscription.").then(St):void 0,onApprove:f,onCancel:()=>{if(Oe())return;let re=ot.current.get(F)??Ae.current;re&&ot.current.delete(re.surfaceKey),Ae.current=null,ln(),j.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be.current=!0,wt({generation:re?.generation,remount:!0,focus:!1})},onError:re=>{if(Oe()||ve.current!==F)return;let K=re instanceof Error?re.message:"PayPal failed to render.";if(L(`onError rendered=${ht} msg=${K.slice(0,120)}`),ht){let m=ot.current.get(F)??Ae.current;if(m&&!en(m.generation)||!m&&Ke.current===Ct.current)return;if(Lt(K)){Mt(m?.generation);return}if(ln(),Lr(re)){j.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),q(re,m),Ge(()=>yt.current?.(Et("paypal",K))),m&&ot.current.delete(m.surfaceKey),Ae.current=null,Mt(m?.generation);return}let V=K.toLowerCase();j.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),Ae.current=null,wt({generation:m?.generation,remount:!0,showRetry:!0,focus:!0}),vn(re,{code:"paypal_runtime_failed"});return}rn(K)}}),b=z.isEligible();if(L(`isEligible=${b}`),j.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!b){ae(!1),rn("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Kn=z,O&&L(`container:dims ${Ot(It)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),O&&typeof MutationObserver<"u"&&(nn=new MutationObserver(re=>{if(!Oe()){for(let K of re)if(K.type==="childList")K.addedNodes.forEach(m=>{if(!(m instanceof Element))return;let V=m.tagName.toLowerCase(),Ce=(m.getAttribute("title")??"").slice(0,40),Te=V==="iframe"?` ${Be(m)}`:"";L(`child+ ${V}${Ce?` title="${Ce}"`:""}${Te} dims=${Ot(m)}`)});else if(K.type==="attributes"&&K.target instanceof Element){let m=K.target;if(m.tagName.toLowerCase()!=="iframe")continue;let V=K.attributeName;(V==="src"||V==="srcdoc")&&L(`attr~ iframe ${V}=${V==="srcdoc"?`[${(m.getAttribute("srcdoc")??"").length}ch]`:Nt(m.getAttribute("src"))} dims=${Ot(m)}`)}}}),nn.observe(It,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ne=re=>{if(Oe()||ht)return;let K=It.querySelectorAll("iframe"),m=typeof document<"u"&&"hasStorageAccess"in document;L(`watchdog:${re} container=${Ot(It)} children=${It.childElementCount} iframes=${K.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${m} paypalNetRequests=${$t.value}`),K.forEach((V,Ce)=>{let Te=(V.getAttribute("title")??"").slice(0,40);L(` iframe[${Ce}] ${Ot(V)}${Te?` title="${Te}"`:""} ${Be(V)}`);let Fe=Ut(V);Fe&&L(` ${Fe}`)}),ft.length===0&&L(" (no PayPal/zoid window errors captured)")};O&&(Kt.push(setTimeout(()=>Ne("3s"),3e3)),Kt.push(setTimeout(()=>Ne("8s"),8e3)),Kt.push(setTimeout(()=>Ne("15s"),15e3))),L("render:start");let tt=j.startTiming();Kt.push(setTimeout(()=>{Oe()||ht||(L("watchdog:11s retryable render timeout"),rn("PayPal Buttons render did not settle within 11000ms.",!0))},fs)),z.render(It).then(()=>{if(L(`render:resolved inactive=${Oe()}`),qt(),Oe()){at();return}ht=!0,ae(!0),Z(!1),Qe.current?.("ready"),j.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"checkout_render",durationMs:j.elapsed(tt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(re=>{let K=re instanceof Error?re.message:"PayPal failed to render.";L(`render:rejected msg=${K.slice(0,120)}`),qt(),rn(K)})}).catch(o=>{let f=o instanceof Error?o.message:"PayPal SDK failed to load.";L(`loadScript:rejected msg=${f.slice(0,120)}`),rn(f)})},0);return()=>{Ft=!0,clearTimeout(Ee),xn&&clearTimeout(xn),qt(),at()}},[I,fe,r,u,s,d,e,R,X,j]);let Hn=O?(0,fn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:je?"#fef2f2":"#f3f4f6",border:`1px solid ${je?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${ce} failed=${je})`,Ze.length===0?`
|
|
7
7
|
(waiting for first lifecycle event\u2026)`:`
|
|
8
8
|
${Ze.join(`
|
|
9
|
-
`)}`]}):null;return
|
|
9
|
+
`)}`]}):null;return je&&!pt?O?(0,fn.jsx)("div",{children:Hn}):null:(0,fn.jsxs)("div",{children:[Hn,(0,fn.jsxs)("div",{"aria-hidden":ge?!0:void 0,style:ge?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:mo},children:[!ce&&!ge&&(0,fn.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,fn.jsx)("div",{ref:G,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:mo,display:"flex",opacity:ce?1:0},"aria-busy":he||_},X)]},X),ie&&(0,fn.jsx)("button",{ref:_e,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Ht,style:hs,children:"Try PayPal again"})]})}function zr(e){return(0,fn.jsx)(Za,{...e})}function ei(e){return(0,fn.jsx)(Za,{...e})}var zt=require("@flopay/shared"),c=require("react/jsx-runtime"),Rn="flopay_stripe_resume",ti="flopay_wallet_resume",Or="flopay_paypal_resume",bs=250,ni="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Jo(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function fo({billingApiUrl:e,sessionId:t,nonce:n,request:i}){if(!(!t||!n))try{await new gn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,i)}catch{}}function vs(e){return e instanceof zt.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Wo(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var Cs=`
|
|
10
10
|
.paypal-buttons { margin: 0 !important; vertical-align: top !important; }
|
|
11
11
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
12
12
|
@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
@@ -27,7 +27,7 @@ ${Ze.join(`
|
|
|
27
27
|
0% { opacity: 1; transform: translateX(0) scale(1); }
|
|
28
28
|
100% { opacity: 0; transform: translateX(16px) scale(0.97); }
|
|
29
29
|
}
|
|
30
|
-
`,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:`
|
|
30
|
+
`,yo=44;function Xo(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 Ss={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ci={width:"100%",minHeight:yo,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 ws(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ri(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function di(e){return e==="paypal"?"PayPal":(0,C.getStripeMethodDisplayName)(e)}function ks(e,t){let n=`We couldn't open ${di(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function ui(e){let t=(0,a.useRef)(0),n=(0,a.useRef)(null),i=(0,a.useRef)(null),r=(0,a.useCallback)((p=i.current)=>{let P=p;P?.timer&&(clearTimeout(P.timer),P.timer=null)},[]),s=(0,a.useCallback)((p,P)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(p),p.timer=setTimeout(()=>{p.timer=null,i.current?.generation===p.generation&&(i.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"}))},P))},[r,e]),u=(0,a.useCallback)(p=>{p.yieldedControl&&s(p,600)},[s]),d=(0,a.useCallback)(p=>{r();let P=t.current+1;t.current=P,n.current=null;let I={generation:P,method:p,timer:null,yieldedControl:!1};return i.current=I,P},[r]),v=(0,a.useCallback)(p=>{let P=i.current;return typeof p=="number"&&P?.generation!==p?!1:(r(P),i.current=null,(typeof p!="number"||n.current===p)&&(n.current=null),!0)},[r]),A=(0,a.useCallback)(p=>{let P=i.current,I=p??P?.generation??t.current;(!p||P?.generation===p)&&(r(P),i.current=null),n.current=I},[r]),h=(0,a.useCallback)(p=>n.current===(p??t.current),[]),E=(0,a.useCallback)(p=>i.current?.generation===p&&n.current!==p,[]),S=(0,a.useCallback)(()=>{let p=i.current;p&&u(p)},[u]),_=(0,a.useCallback)(()=>{let p=i.current;p&&(p.yieldedControl=!0,r(p))},[r]);return(0,a.useEffect)(()=>{let p=()=>{document.visibilityState==="visible"?S():_()},P=()=>{_()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",P),window.addEventListener("focus",S),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",P),window.removeEventListener("focus",S),r()}},[r,_,S]),{startAttempt:d,finishAttempt:v,invalidateAttempt:A,isAttemptInvalidated:h,isAttemptCurrent:E}}function Rs(e){let t=(0,C.getPostalCodeExample)(e);return`Enter a valid ${(0,C.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Es(e,t,n){let i=(0,C.isPostalCodeSupported)(e),r=t.trim(),s=n&&i,u=s&&!r,d=s&&!!r&&!(0,C.isValidPostalCode)(e,r);return{visible:n,supported:i,required:s,empty:u,malformed:d}}function oi(e,t){return t instanceof zt.FloPayError?t:new zt.FloPayError(t instanceof Error?t.message:`${ws(e)} before-click hook failed.`,"validation_error")}function Yo(){return(0,c.jsx)("style",{children:Cs})}function Is(e){return typeof e=="number"?`${e}px`:e}function pi(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function mi({state:e,placeholderTestId:t,borderRadius:n=8,children:i}){return e==="unavailable"||e==="load_error"?null:(0,c.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,c.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,c.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:i})]})}function ai(e){return e!=="unavailable"&&e!=="load_error"}function go(e){return(0,c.jsx)(xs,{...e})}function ii({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:r,onErrorChange:s,isProcessing:u=!1,onButtonClick:d,onDecline:v,onTechnicalFailure:A,runBeforeButtonClick:h,onLoadStateChange:E,placeholderBorderRadius:S}){let _=mn(),p=(0,gt.useStripe)(),P=(0,gt.useElements)(),[I,x]=(0,a.useState)("loading");(0,a.useEffect)(()=>{E?.(I)},[I,E]);let[g,ye]=(0,a.useState)(!1),R=(0,a.useRef)(!1),pe=(0,a.useRef)(null),oe=(0,a.useRef)(null),[O,ee]=(0,a.useState)(0),[Q,le]=(0,a.useState)(!1),j=(0,a.useRef)(!1),G=(0,a.useRef)(new Map),{startAttempt:me,finishAttempt:_e,invalidateAttempt:be,isAttemptInvalidated:ce,isAttemptCurrent:ae}=ui((W,w,de)=>{A?.(W,w,{...de,popupBlocked:de?.popupBlocked??qn(w)}),le(!0),ee(je=>je+1)});(0,a.useEffect)(()=>{Q&&oe.current?.focus()},[Q,O]);let ge=(0,a.useCallback)(()=>{ee(W=>W+1)},[]),Z=(0,a.useCallback)((W,w,de)=>{be(de),A?.("paypal",W,{code:w,popupBlocked:qn(W)}),le(!0),ge()},[be,A,ge]),X=(0,a.useCallback)(()=>{window.setTimeout(()=>{(pe.current?.querySelector("iframe")??pe.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{j.current&&(j.current=!1,X())},[X,O]);let xe=(0,a.useCallback)(()=>{le(!1),s?.(null),X()},[X,s]);(0,a.useEffect)(()=>{if(!p||R.current)return;let W=new URLSearchParams(window.location.search),w=W.get("payment_intent"),de=W.get("payment_intent_client_secret"),je=W.get("redirect_status");if(!w||!de)return;R.current=!0;let $e;try{let B=localStorage.getItem(Or);if(B){let fe=JSON.parse(B);fe.clientSecret===de&&($e={...fe.accountPatch?{accountPatch:fe.accountPatch}:{},...fe.sessionId?{sessionId:fe.sessionId}:{},...fe.nonce?{nonce:fe.nonce}:{}})}}catch{}try{localStorage.removeItem(Or)}catch{}let he=new URL(window.location.href);he.searchParams.delete("payment_intent"),he.searchParams.delete("payment_intent_client_secret"),he.searchParams.delete("redirect_status"),window.history.replaceState({},"",he.toString()),(async()=>{try{if(ye(!0),je==="failed"){let te="PayPal payment was declined. Please try again.";s?.(te),v?.(Et("paypal",te));return}let{paymentIntent:B,error:fe}=await p.retrievePaymentIntent(de);if(fe){s?.(fe.message??"Failed to retrieve PayPal payment status.");return}if(B&&(B.status==="requires_capture"||B.status==="succeeded")){let te=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id;r({id:te??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0},$e)}else{let te="PayPal payment was not completed. Please try again.";s?.(te),v?.(Et("paypal",te))}}catch(B){s?.(B instanceof Error?B.message:"Failed to complete PayPal payment.")}finally{ye(!1)}})()},[p,r,s,v]);let ve=(0,a.useCallback)(async W=>{if(u||g){W.reject();return}let w=h?await h("paypal"):{proceed:!0};if(!w.proceed){G.current.delete(O),W.reject();return}let de=me("paypal");G.current.set(O,{generation:de,accountPatch:w.accountPatch,sessionId:w.sessionId,nonce:w.nonce}),le(!1),d?.("paypal"),W.resolve()},[G,u,d,h,me,g,O]),ie=(0,a.useCallback)(async W=>{if(!p||!P)return;let w=G.current.get(O);if(w&&!ae(w.generation)){G.current.delete(O);return}if(!w&&ce()||w&&!_e(w.generation))return;w||_e();let de=w??null;if(G.current.delete(O),!de&&h){let B=await h("paypal");if(!B.proceed){W.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}de={accountPatch:B.accountPatch,sessionId:B.sessionId,nonce:B.nonce}}let je=de?.sessionId??e,$e=de?.nonce??t,he=de?.accountPatch?.email??n;try{if(ye(!0),s?.(null),!je||!he)throw new Error("Missing sessionId or email for PayPal payment");let B=p.createPaymentMethod,{error:fe,paymentMethod:te}=await B({type:"paypal"});if(fe){Z(fe,"stripe_paypal_create_payment_method_failed",w?.generation),W.paymentFailed({reason:"fail"});return}let Me=await new gn.PaymentAPI(i).createSessionIntent(je,$e??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:te?.id??null,intentKind:"payment"});if(Me.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let pt=Me.clientSecret,Ze={return_url:window.location.href};if(te?.id&&(Ze.payment_method=te.id),typeof window<"u")try{localStorage.setItem(Or,JSON.stringify({clientSecret:pt,sessionId:je,nonce:$e,accountPatch:de?.accountPatch}))}catch{}let{error:mt,paymentIntent:L}=await p.confirmPayment({clientSecret:pt,confirmParams:Ze,redirect:"if_required"});if(mt){if(typeof window<"u")try{localStorage.removeItem(Or)}catch{}if(Lr(mt)){let rt=mt.message??"Your payment was declined.";s?.(rt),v?.(Et("paypal",rt,{code:Bn(mt),declineCode:hr(mt)})),await fo({billingApiUrl:i,sessionId:je,nonce:$e,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Bn(mt)??"provider_declined"}})}else Z(mt,"stripe_paypal_confirm_failed",w?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Or)}catch{}let ne=typeof L?.payment_method=="string"?L.payment_method:L?.payment_method?.id;r({id:ne??L?.id,type:"card",threeDSecureActionResultTokenId:L?.id,isPaypal:!0},{accountPatch:de?.accountPatch,sessionId:je,nonce:$e});return}catch(B){Z(B,"stripe_paypal_failed",w?.generation)}finally{ye(!1)}},[p,P,e,t,n,i,r,s,v,h,Z,_e,ae,ce,O]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(mi,{state:I,placeholderTestId:"flopay-paypal-placeholder",borderRadius:S,children:(0,c.jsxs)("div",{ref:pe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Q&&(0,c.jsx)("button",{ref:oe,type:"button","data-testid":"flopay-paypal-retry-button",onClick:xe,style:ci,children:"Try PayPal again"}),(0,c.jsx)(gt.ExpressCheckoutElement,{onReady:W=>x(pi(W,["paypal"])),onLoadError:()=>{x("load_error"),Jo(Tt(_),"paypal","paypal")},onClick:ve,onConfirm:ie,onCancel:()=>{let W=G.current.get(O);G.current.delete(O),Tt(_)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be(W?.generation),le(!1),j.current=!0,ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},O)]})}),g&&(0,c.jsx)(sn,{status:"processing"})]})}function si({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:r,expressMethods:s,onTokenizedBody:u,onErrorChange:d,onButtonClick:v,onDecline:A,onTechnicalFailure:h,runBeforeButtonClick:E,onLoadStateChange:S,placeholderBorderRadius:_}){let p=mn(),P=(0,gt.useStripe)(),I=(0,gt.useElements)(),[x,g]=(0,a.useState)("loading");(0,a.useEffect)(()=>{S?.(x)},[x,S]);let[ye,R]=(0,a.useState)(!1),pe=(0,a.useRef)(null),oe=(0,a.useRef)(null),[O,ee]=(0,a.useState)(0),[Q,le]=(0,a.useState)(!1),[j,G]=(0,a.useState)("google_pay"),me=(0,a.useRef)(!1),_e=(0,a.useRef)("google_pay"),be=(0,a.useRef)("google_pay"),ce=(0,a.useRef)(new Map),{startAttempt:ae,finishAttempt:ge,invalidateAttempt:Z,isAttemptInvalidated:X,isAttemptCurrent:xe}=ui((he,B,fe)=>{h?.(he,B,{...fe,popupBlocked:fe?.popupBlocked??qn(B)}),G(he),le(!0),ee(te=>te+1)});(0,a.useEffect)(()=>{Q&&oe.current?.focus()},[Q,O]);let ve=(0,a.useCallback)(()=>{ee(he=>he+1)},[]),ie=(0,a.useCallback)((he,B,fe,te)=>{Z(te),h?.(he,B,{code:fe,popupBlocked:qn(B)}),G(he),le(!0),ve()},[Z,h,ve]),W=(0,a.useCallback)(()=>{window.setTimeout(()=>{(pe.current?.querySelector("iframe")??pe.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{me.current&&(me.current=!1,W())},[W,O]);let w=(0,a.useCallback)(()=>{le(!1),d?.(null),W()},[W,d]),de=(0,a.useCallback)(async he=>{if(!P||!I)return;let B=ce.current.get(O);if(B&&!xe(B.generation)){ce.current.delete(O);return}if(!B&&X()||B&&!ge(B.generation))return;B||ge();let fe=he.expressPaymentType??B?.method??_e.current,te=B??null;ce.current.delete(O);let Me=ri(fe);if(!te&&E){let ne=await E(Me);if(!ne.proceed){he.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}te={accountPatch:ne.accountPatch,sessionId:ne.sessionId,nonce:ne.nonce}}let pt=Me,Ze=te?.sessionId??e,mt=te?.nonce??t,L=te?.accountPatch?.email??n;try{R(!0),d?.(null);let{error:ne}=await I.submit();if(ne){ie(fe,ne,"stripe_wallet_submit_failed",B?.generation);return}let{error:rt,paymentMethod:He}=await P.createPaymentMethod({elements:I});if(rt||!He){ie(fe,rt??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",B?.generation);return}if(!Ze||!L)throw new Error("Missing sessionId or email for wallet payment");let yt=await new gn.PaymentAPI(i).createSessionIntent(Ze,mt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:fe??Me,paymentMethodId:He.id,intentKind:r});if(yt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let qe=yt.clientSecret,{error:Je,intentId:Xt}=(0,zt.isSetupIntentClientSecret)(qe)?await P.confirmCardSetup(qe,{payment_method:He.id}).then(Qe=>({error:Qe.error,intentId:Qe.setupIntent?.id})):await P.confirmCardPayment(qe,{payment_method:He.id}).then(Qe=>({error:Qe.error,intentId:Qe.paymentIntent?.id}));if(Je){if(Lr(Je)){let Qe=Je.message??"Your payment was declined.";d?.(Qe),A?.(Et(pt,Qe,{code:Bn(Je),declineCode:hr(Je)})),await fo({billingApiUrl:i,sessionId:Ze,nonce:mt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:fe??Me,providerDeclineReason:Bn(Je)??"provider_declined"}})}else ie(fe,Je,"stripe_wallet_confirm_failed",B?.generation);return}u({id:He.id,type:"card",threeDSecureActionResultTokenId:Xt},{accountPatch:te?.accountPatch,sessionId:Ze,nonce:mt})}catch(ne){ie(fe,ne,"stripe_wallet_failed",B?.generation)}finally{R(!1)}},[P,I,e,t,n,i,r,u,d,A,E,ie,ge,xe,X,O]),je=(0,a.useMemo)(()=>{let he=["applePay","googlePay","paypal","link","amazonPay","klarna"],B=new Set(["applePay","googlePay"]),fe=new Set(s.map(C.stripeExpressMethodToOptionKey)),te={};for(let Me of he)fe.has(Me)?te[Me]=B.has(Me)?"always":"auto":te[Me]="never";return te},[s]),$e=(0,a.useMemo)(()=>s.map(C.stripeExpressMethodToOptionKey),[s]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(mi,{state:x,placeholderTestId:"flopay-wallet-placeholder",borderRadius:_,children:(0,c.jsxs)("div",{ref:pe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Q&&(0,c.jsxs)("button",{ref:oe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:w,style:ci,children:["Try ",di(j)," again"]}),(0,c.jsx)(gt.ExpressCheckoutElement,{onReady:he=>{g(pi(he,$e))},onLoadError:he=>{g("load_error"),Jo(Tt(p),"stripe","wallet")},onClick:async he=>{_e.current=he.expressPaymentType,be.current=ri(he.expressPaymentType);let B=E?await E(be.current):{proceed:!0};if(!B.proceed){ce.current.delete(O),he.reject();return}let fe=ae(he.expressPaymentType);ce.current.set(O,{generation:fe,method:he.expressPaymentType,accountPatch:B.accountPatch,sessionId:B.sessionId,nonce:B.nonce}),le(!1),v?.(be.current),he.resolve()},onConfirm:de,onCancel:()=>{let he=ce.current.get(O);ce.current.delete(O),Tt(p)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Z(he?.generation),le(!1),me.current=!0,ve()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:je,layout:{maxColumns:1,overflow:"never"}}},O)]})}),ye&&(0,c.jsx)(sn,{status:"processing"})]})}function _s({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:r=!1,hasNextStep:s=!1,onClick:u,backgroundColor:d,borderColor:v,textColor:A,borderRadius:h,fontFamily:E}){let S=(0,C.resolveStripeMethodBrandVariant)(e,t),_=$a[e],p=S?.backgroundColor??d??"#ffffff",P=S?.borderColor??v??"#d1d5db",I=S?.textColor??A??"#262833";return(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!i&&u()},disabled:n||i,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:yo,padding:"0 1rem",backgroundColor:p,color:I,border:`1px solid ${P}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:E,cursor:n||i?"not-allowed":"pointer",opacity:i&&!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:r?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,c.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,C.getStripeMethodDisplayName)(e)}\u2026`}):(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,C.hasVendoredStripeMethodLogo)(e)?8:0},children:[_?(0,c.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"}}):S?.logoSvg?(0,c.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:S.logoSvg}}):null,(0,c.jsx)("span",{children:(0,C.getStripeMethodDisplayName)(e)})]}),s&&(0,c.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,c.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Go({method:e,sessionId:t,nonce:n,email:i,billingName:r,billingApiUrl:s,onTokenizedBody:u,onErrorChange:d,onDecline:v,onCancel:A,runBeforeButtonClick:h,onButtonClick:E,isProcessing:S,submitButtonColor:_,submitButtonBorderRadius:p,submitButtonStyle:P,errorText:I}){let x=mn(),g=(0,gt.useStripe)(),ye=(0,gt.useElements)(),[R,pe]=(0,a.useState)(!1),oe=(0,a.useRef)(!1),[O,ee]=(0,a.useState)(!1),[Q,le]=(0,a.useState)("loading"),j=(0,a.useCallback)(async()=>{if(!g||!ye||S||oe.current||!O)return;oe.current=!0,pe(!0);let G=h?await h("card"):{proceed:!0};if(!G.proceed){oe.current=!1,pe(!1);return}E?.("card");let me=G.sessionId??t,_e=G.nonce??n,be=G.accountPatch?.email??i;try{d?.(null);let ce=await ye.submit();if(ce.error){d?.(ce.error.message??"Payment failed.");return}let ae=await g.createPaymentMethod({elements:ye});if(ae.error||!ae.paymentMethod){d?.(ae.error?.message??"Failed to create payment method.");return}let ge=ae.paymentMethod;if(!me||!be)throw new Error("Missing sessionId or email for payment.");let Z=ge.type||e,X=await new gn.PaymentAPI(s).createSessionIntent(me,_e??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,paymentMethodId:null,intentKind:"payment"});if(X.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let xe=X.clientSecret;if(typeof window<"u")try{localStorage.setItem(Rn,JSON.stringify({clientSecret:xe,sessionId:me,nonce:_e,accountPatch:G.accountPatch,paymentMethodId:ge.id,paymentMethodType:ge.type??e,gateway:"stripe"}))}catch{}let{error:ve,paymentIntent:ie}=await g.confirmPayment({clientSecret:xe,confirmParams:{return_url:window.location.href,payment_method:ge.id},redirect:"if_required"});if(ve){if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let de=ve.message??"Payment failed.";d?.(de),v?.(Et("card",de,{code:ve.code})),await fo({billingApiUrl:s,sessionId:me,nonce:_e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ve.code??"provider_declined"}});return}let W=ie?.status;if(!co(W)){if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let de=W==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(de),v?.(Et("card",de,{code:W??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let w=typeof ie?.payment_method=="string"?ie.payment_method:ie?.payment_method?.id;u({id:w??ge.id,type:"card",threeDSecureActionResultTokenId:ie?.id,gateway:"stripe",paymentMethodType:ge.type??e},{accountPatch:G.accountPatch,sessionId:me,nonce:_e})}catch(ce){d?.(ce instanceof Error?ce.message:"Payment failed. Please try again.")}finally{oe.current=!1,pe(!1)}},[g,ye,S,O,h,E,t,n,i,s,e,u,d,v]);return(0,c.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,c.jsx)(gt.PaymentElement,{onReady:()=>le("ready"),onLoadError:()=>{le("load_error"),Jo(Tt(x),"stripe","apm")},onChange:G=>{ee(!!G.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...i?{email:i}:{}}}}}),(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{j()},disabled:!O||R||S||Q!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:_,color:"white",border:"none",borderRadius:p,fontSize:"1rem",fontWeight:600,cursor:!O||R||S||Q!=="ready"?"not-allowed":"pointer",opacity:!O||R||S||Q!=="ready"?.5:1,transition:"opacity 120ms ease-out",...P??{}},children:R?"Processing\u2026":`Pay with ${(0,C.getStripeMethodDisplayName)(e)}`}),I&&(0,c.jsx)(pr,{margin:"0.75rem 0 0",children:I})]})}function li({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:r,paymentElementMethods:s,stripeInstance:u,paymentElementBaseOptions:d,onTokenizedBody:v,onErrorChange:A,onButtonClick:h,onDecline:E,runBeforeButtonClick:S,onLoadStateChange:_,isProcessing:p=!1,submitButtonColor:P="#4A49FF",submitButtonBorderRadius:I=8,submitButtonStyle:x,buttonAppearance:g,themeId:ye,onExpandApm:R,expandedApmMethod:pe}){let[oe,O]=(0,a.useState)(null),[ee,Q]=(0,a.useState)(null),le=(0,a.useRef)(!1);(0,a.useEffect)(()=>{s.length>0&&u?_?.("ready"):u||_?.("loading")},[s.length,u,_]);let j=(0,a.useCallback)(async ae=>{if(!u||le.current||p)return;le.current=!0,Q(ae);let ge=S?await S("card"):{proceed:!0};if(!ge.proceed){le.current=!1,Q(null);return}h?.("card");let Z=ge.sessionId??e,X=ge.nonce??t,xe=ge.accountPatch?.email??n;try{if(A?.(null),!Z||!xe)throw new Error("Missing sessionId or email for payment.");let ve=await new gn.PaymentAPI(r).createSessionIntent(Z,X??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ae,paymentMethodId:null,intentKind:"payment"});if(ve.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ie=ve.clientSecret;if(typeof window<"u")try{localStorage.setItem(Rn,JSON.stringify({clientSecret:ie,sessionId:Z,nonce:X,accountPatch:ge.accountPatch,paymentMethodType:ae,gateway:"stripe"}))}catch{}let{error:W,paymentIntent:w}=await u.confirmPayment({clientSecret:ie,confirmParams:{return_url:window.location.href,payment_method_data:{type:ae,billing_details:{name:i&&i.trim().length>=3?i.trim():"FloPay Customer",...xe?{email:xe}:{}}}},redirect:"if_required"});if(W){if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let $e=W.message??"Payment failed.";A?.($e),E?.(Et("card",$e,{code:W.code})),await fo({billingApiUrl:r,sessionId:Z,nonce:X,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ae,providerDeclineReason:W.code??"provider_declined"}});return}let de=w?.status;if(!co(de)){if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let $e=de==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";A?.($e),E?.(Et("card",$e,{code:de??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let je=typeof w?.payment_method=="string"?w.payment_method:w?.payment_method?.id;v({id:je??w?.id,type:"card",threeDSecureActionResultTokenId:w?.id,gateway:"stripe",paymentMethodType:ae},{accountPatch:ge.accountPatch,sessionId:Z,nonce:X})}catch(ve){A?.(ve instanceof Error?ve.message:"Payment failed. Please try again.")}finally{le.current=!1,Q(null)}},[u,p,S,h,e,t,n,r,i,v,A,E]),[G,me]=(0,a.useState)(null),_e=R?pe??null:G,be=(0,a.useCallback)(ae=>{le.current||p||_e&&_e!==ae||((0,C.needsStripeMethodExplicitConfirm)(ae)?R?R(ae):me(ae):j(ae))},[_e,p,j,R]),ce=(0,a.useMemo)(()=>G?{...d,paymentMethodTypes:[G]}:null,[G,d]);return(0,c.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(ae=>{let ge=pe===ae,Z=ee===ae,X=ee!==null&&ee!==ae||pe!=null&&pe!==ae;return(0,c.jsxs)(a.default.Fragment,{children:[(0,c.jsx)(_s,{method:ae,themeId:ye,submitting:Z,disabled:X,highlighted:ge,hasNextStep:(0,C.needsStripeMethodExplicitConfirm)(ae),onClick:()=>be(ae),backgroundColor:g?.backgroundColor,borderColor:g?.borderColor,textColor:g?.textColor,borderRadius:g?.borderRadius,fontFamily:g?.fontFamily}),!R&&G===ae&&ce&&u&&(0,c.jsx)(gt.Elements,{stripe:u,options:ce,children:(0,c.jsx)(Go,{method:ae,sessionId:e,email:n,billingName:i,billingApiUrl:r,onTokenizedBody:v,onErrorChange:A,onDecline:E,onCancel:()=>me(null),runBeforeButtonClick:S,onButtonClick:h,isProcessing:p,submitButtonColor:P,submitButtonBorderRadius:I,submitButtonStyle:x})},ae)]},ae)})})}function xs({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,onComplete:s,onError:u,onDecline:d,onTokenizedBody:v,firstName:A,lastName:h,chv:E,className:S,isProcessing:_,error:p,onErrorChange:P,showPayPal:I=!0,showStripe:x=!0,enabledPaymentMethods:g,enabledPaymentMethodCountries:ye,showApplePay:R=!0,showGooglePay:pe=!0,layout:oe="default",theme:O,buttonsTheme:ee,buttonsStyles:Q,appearance:le,cardButtonContent:j,cardBackButtonContent:G,cardTitleContent:me,showSecurityFooter:_e,onButtonClick:be,onBeforeButtonClick:ce,enableAVS:ae,cardFieldOrder:ge,cardPreFormSlot:Z,avsLayout:X="row",country:xe,zip:ve,addressLine1:ie,addressLine2:W,city:w,state:de,onCountryChange:je,onZipChange:$e,avsCheck:he,checkoutType:B,checkoutLayout:fe,totalAmount:te=0,currency:Me="usd",initialCardOpen:pt=!1,directPaypal:Ze,isSubscription:mt=!1,session:L,dataAttachmentPending:ne=!1,debug:rt=!1}){let He=mn(),yt=oo(),qe=(0,a.useContext)(pn),Je=ne||qe.claimPending===!0,Xt=io(),[Qe,Qt]=(0,a.useState)(!1),[T,ke]=(0,a.useState)(null),[Xe,Ae]=(0,a.useState)(xe??"US"),[Ct,We]=(0,a.useState)(ve??""),[Ke,ot]=(0,a.useState)(ie??""),[et,In]=(0,a.useState)(W??""),[st,jn]=(0,a.useState)(w??""),[Ht,vn]=(0,a.useState)(de??""),[Zt,or]=(0,a.useState)({}),Mt=(0,a.useRef)(ve??""),wt=(0,a.useRef)(xe??"US"),en=(0,a.useRef)(ie??""),tn=(0,a.useRef)(W??""),At=(0,a.useRef)(w??""),Bt=(0,a.useRef)(de??""),St=(0,a.useRef)({});(0,a.useEffect)(()=>{let l=($,J,ue,Y,Ie)=>{if(St.current[$])return;let De=J?.trim();!De||De===ue.current||(ue.current=De,Y(De),Ie?.(De))};l("country",xe,wt,Ae,je),l("zip",ve,Mt,We,$e),l("addressLine1",ie,en,ot),l("addressLine2",W,tn,In),l("city",w,At,jn),l("state",de,Bt,vn)},[xe,ve,ie,W,w,de,je,$e]);let se=(0,a.useMemo)(()=>(0,C.resolveAVSConfig)(ae),[ae]),Hn=se!==null,U=(0,a.useMemo)(()=>(0,C.isAuthorizationOnlySession)(L),[L]),lt=!!L?.vault?.html,Ft=!!L?.gateways?.pcivault,Oe=!!(L?.gateways?.stripe?.enabledPaymentMethods??g)?.includes("card"),ct=lt||Oe||Ft,Ye=!!(x&&ct&&He&&e),[_n,xn]=(0,a.useState)(()=>oe!=="buttons"||pt?e??null:null),[On,Kn]=(0,a.useState)(0),Tn=oe!=="buttons"||pt||!!e&&_n===e,at=(0,a.useMemo)(()=>!He||!Ye||!e||!Tn?null:He.cardCapture({sessionId:e,captureMethod:L?.captureMethod}),[He,Ye,e,Tn,L?.captureMethod]),Dt=(0,a.useMemo)(()=>{let l=Xe,$=se?(0,C.isAVSFieldVisible)(se.postal_code,l):!1;return Es(l,Ct,$)},[se,Xe,Ct]),{avsInvalid:ln,invalidAvsFields:ht}=(0,a.useMemo)(()=>{let l={line1:!1,city:!1,state:!1,zip:!1};if(!Ye||!se)return{avsInvalid:!1,invalidAvsFields:l};let $=Xe,J=(Ie,De)=>(0,C.isAVSFieldVisible)(Ie,$)&&!De.trim(),ue={line1:J(se.address_line_1,Ke),city:J(se.city,st),state:J(se.state,Ht),zip:Dt.empty||Dt.malformed};return{avsInvalid:ue.line1||ue.city||ue.state||ue.zip,invalidAvsFields:ue}},[Ye,se,Xe,Ke,st,Ht,Dt]),[It,nn]=(0,a.useState)(!1),[cn,Kt]=(0,a.useState)(!1),[Ot,Nt]=(0,a.useState)(()=>Wo(L?.vault)),[Be,Ut]=(0,a.useState)(pt&&ct?"card":"buttons"),[ft,Cn]=(0,a.useState)(null),Wn=Be==="expanding"||Be==="card",$t=280,qt=(0,a.useRef)(null),Lt=(0,a.useCallback)(l=>{qt.current&&clearTimeout(qt.current),qt.current=setTimeout(()=>{qt.current=null,l()},$t)},[$t]);(0,a.useEffect)(()=>()=>{qt.current&&clearTimeout(qt.current)},[]);let Nn=(0,a.useCallback)(()=>{xn(e??null),Kn(l=>l+1),Ut("expanding"),Lt(()=>Ut("card"))},[Lt,e]),Un=(0,a.useCallback)(()=>{Ut("collapsing"),Lt(()=>Ut("buttons"))},[Lt]),rn=(0,a.useCallback)(l=>{Cn(l),Ut("apm-expanding"),Lt(()=>Ut("apm-form"))},[Lt]),Wt=(0,a.useCallback)(()=>{Ut("apm-collapsing"),Lt(()=>{Ut("buttons"),Cn(null)})},[Lt]);(0,a.useEffect)(()=>{oe==="buttons"&&pt&&ct&&(xn(e??null),Ut("card"))},[oe,pt,ct,e]);let[on,Ve]=(0,a.useState)(null),M=(0,a.useRef)(!1),q=(0,a.useRef)(null),F=(0,a.useRef)("idle"),[Re,Ee]=(0,a.useState)(null),y=(0,a.useRef)(Re);(0,a.useEffect)(()=>{y.current=Re},[Re]);let o=n||Xt,f=p??T,z=(0,a.useMemo)(()=>(0,zt.resolveTheme)(O),[O]),b=(0,a.useMemo)(()=>{let l=z?.buttonsLayout??(0,C.resolveButtonsLayoutTheme)(ee);return Q?{...l,...Q,cardButton:{...l.cardButton,...Q.cardButton},cardFormContainer:{...l.cardFormContainer,...Q.cardFormContainer},backButton:{...l.backButton,...Q.backButton},backButtonIcon:{...l.backButtonIcon,...Q.backButtonIcon},submitButton:{...l.submitButton,...Q.submitButton},title:{...l.title,...Q.title}}:l},[z,ee,Q]),H=le??z?.appearance,Ne=(0,a.useMemo)(()=>ro({appearance:H,buttonsStyles:b,layout:oe}),[H,b,oe]),tt=qe.inlineSessionPatchProcessing??!1,re=(_??Qe)||tt,K=o.replace(/\/+$/,""),m=(0,a.useMemo)(()=>jo({userId:r,email:i,firstName:A,lastName:h,country:xe,zip:ve},Zt),[r,i,A,h,xe,ve,Zt]),V=[m.firstName,m.lastName].filter(l=>!!l?.trim()).join(" "),Ce=(0,a.useMemo)(()=>He?He.getRawProvider():null,[He]),Te=(0,a.useMemo)(()=>yt?yt.getRawProvider():null,[yt]),Fe=te||100,Sn=(0,a.useMemo)(()=>H?(0,gn.toStripeAppearance)(H):null,[H]),Cr=Sn?{appearance:Sn}:null,Io=(0,a.useMemo)(()=>{let l=Sn??{},$=l.rules??{};return{...l,rules:{...$,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...$[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...$[".AccordionItemContents"]??{}}}}},[Sn]),jr=(0,a.useMemo)(()=>{let l=Ya(te);return{...l,currency:Me.toLowerCase(),paymentMethodCreation:"manual",...l.mode==="payment"?{captureMethod:"manual"}:{},...Cr}},[te,Me,Cr]),la=(0,a.useMemo)(()=>({mode:"payment",amount:Fe,currency:Me.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Cr}),[Fe,Me,Cr]),Pe=(0,a.useCallback)(l=>{ke(l),P?.(l)},[P]);(0,a.useEffect)(()=>{!Ye||!at||at.setCardFieldOrder?.(ge??null,se==null)},[Ye,at,ge,se]),(0,a.useEffect)(()=>{(Be==="expanding"||Be==="collapsing"||Be==="apm-expanding"||Be==="apm-collapsing")&&Pe(null)},[Be,Pe]);let dn=(0,a.useCallback)((l,$,J)=>{d?.(Et(l,$,J))},[d]),ar=(0,a.useCallback)((l,$,J)=>{let ue=J?.popupBlocked??qn($),Y=ks(l,ue),Ie=er(J?.code)??Bn($)??"external_payment_method_failed",De=new zt.FloPayError(Y,"api_error",{code:"external_payment_method_failed",param:l});Ve(null),oe==="buttons"&&(Ut("buttons"),Cn(null)),Pe(Y),u?.(De),console.error("[FloPay] External payment method failed:",{method:l,code:Ie,popupBlocked:ue})},[oe,u,Pe]);(0,a.useEffect)(()=>{if(!Ye||!e){Nt(null);return}let l=Wo(L?.vault);if(l){Nt(l);return}if(!Tn){Nt(null);return}Nt(null);let $=!0;return new gn.PaymentAPI(K).getVaultCapture(e,t).then(J=>{if(!$)return;let ue=Wo(J);ue?Nt(ue):Pe("Failed to load the secure card form.")}).catch(J=>{$&&Pe(J instanceof Error?J.message:"Failed to load the secure card form.")}),()=>{$=!1}},[Ye,Tn,On,e,L?.vault?.html,L?.vault?.messageToken,L?.vault?.expectedOrigin,K,t,Pe]);let wn=(0,a.useRef)({onComplete:s,onError:u,updateError:Pe,emitDecline:dn,resolvedAccount:m,avsConfig:se,avsCheckProp:he,sessionId:e,nonce:t,baseUrl:K,captureMethod:L?.captureMethod,paymentId:L?.paymentId,authorizationExpiresAt:L?.authorizationExpiresAt});wn.current={onComplete:s,onError:u,updateError:Pe,emitDecline:dn,resolvedAccount:m,avsConfig:se,avsCheckProp:he,sessionId:e,nonce:t,baseUrl:K,captureMethod:L?.captureMethod,paymentId:L?.paymentId,authorizationExpiresAt:L?.authorizationExpiresAt};let _o=(0,a.useRef)(!1),Bi=(0,a.useCallback)(()=>{let{resolvedAccount:l,avsConfig:$,avsCheckProp:J}=wn.current,ue=wt.current||l.country||"US",Y=$?(0,C.isAVSFieldVisible)($.state,ue):!1,Ie=$?(0,C.isAVSFieldVisible)($.address_line_1,ue):!1,De=$?(0,C.isAVSFieldVisible)($.postal_code,ue):!1,dt=$?(0,C.isAVSFieldVisible)($.city,ue):!1,bt=$?(0,C.isAVSFieldVisible)($.address_line_2,ue):!1,nt=Ie&&!Y&&De?(0,C.getStateFromPostalCode)(ue,(Mt.current??"").trim()):null,kt=Y?Bt.current:nt;return{accountData:{userId:l.userId??"",email:l.email??"",firstName:l.firstName??"",lastName:l.lastName??"",...De&&Mt.current?{zip:Mt.current}:{},...dt&&At.current?{city:At.current}:{},...kt?{state:kt}:{},...Ie&&en.current?{addressLine1:en.current}:{},...bt&&tn.current?{addressLine2:tn.current}:{},country:ue},...J!==void 0?{avsCheck:J}:{},...$?{avsConfig:{country:(0,C.isAVSFieldVisible)($.country,ue),postal_code:De,address_line_1:Ie,address_line_2:bt,city:dt,state:Y}}:{}}},[]),ca=(0,a.useRef)(Je);ca.current=Je,(0,a.useEffect)(()=>{Je||f!==ni||wn.current.updateError(null)},[Je,f]),(0,a.useEffect)(()=>{!Ye||!at||at.setSubmitGate?.(ln||Je)},[Ye,at,ln,Je]),(0,a.useEffect)(()=>{if(!Ye||!at)return;_o.current=!1;let l=!1,$=at.on("submitting",()=>{nn(!0),q.current&&clearTimeout(q.current),F.current="validation-window",q.current=setTimeout(()=>{q.current=null,F.current==="validation-window"&&(F.current="processing")},bs),Ve("processing");let{baseUrl:De,sessionId:dt,nonce:bt,updateError:nt,onError:kt}=wn.current;!dt||!bt||new gn.PaymentAPI(De).patchAccountSnapshot(dt,bt,Bi(),{telemetryMode:"best_effort"}).catch(Se=>{if(!vs(Se))return;let _t=Se instanceof Error?Se.message:"Please check your billing address and try again.";nt(_t),F.current="idle",Ve(null),kt?.(Se instanceof zt.FloPayError?Se:new zt.FloPayError(_t,"api_error"))})}),J=at.on("complete",async De=>{if(gr(De.sessionId??wn.current.sessionId),F.current="terminal",Ve("success"),await new Promise(nt=>setTimeout(nt,yn)),_o.current)return;_o.current=!0;let dt=wn.current,bt=(0,C.isAuthorizationOnlySession)(dt)||De.outcome==="authorized";wn.current.onComplete?.(bt?{status:"authorized",paymentIntentId:De.intentId,paymentId:De.paymentId??dt.paymentId,sessionId:De.sessionId??dt.sessionId,authorizationExpiresAt:De.authorizationExpiresAt??dt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:De.intentId,checkoutMethod:"card"})}),ue=at.on("decline",async De=>{let{updateError:dt,emitDecline:bt}=wn.current,nt=De.message??"Your payment was declined. Please try another card or contact your bank.";F.current="terminal",dt(nt),Ve("error");let kt=De.failureOutcome??(0,C.normalizeCheckoutFailureOutcome)(De.declineReason)??"authorization_declined";bt("card",nt,{code:kt,declineCode:kt}),await new Promise(Se=>setTimeout(Se,Yt)),!l&&(F.current="idle",Ve(null))}),Y=at.on("error",async De=>{let{updateError:dt,onError:bt}=wn.current,nt=De.message??"There was a problem processing your payment. Please try again.";F.current="terminal",dt(nt),Ve("error"),bt?.(new zt.FloPayError(nt,"api_error",{code:De.failureOutcome??"capture_failed"})),await new Promise(kt=>setTimeout(kt,Yt)),!l&&(F.current="idle",Ve(null))}),Ie=at.on("blocked",()=>{if(!ca.current){nn(!0);return}wn.current.updateError(ni)});return()=>{l=!0,q.current&&(clearTimeout(q.current),q.current=null),F.current="idle",$(),J(),ue(),Y(),Ie()}},[Ye,at]);let kn=!!Ze?.clientId,Sr=Array.isArray(g),Hr=Sr&&g.length>0,Fi=Sr&&g.includes("paypal"),{expressMethods:Kr,paymentElementMethods:wr}=(0,a.useMemo)(()=>(0,C.partitionStripeMethods)(g,{excludePaypal:kn}),[g,kn]),da=kn||!!yt,Di=(0,a.useMemo)(()=>da?Kr.filter(l=>l!=="paypal"):Kr,[Kr,da]),Li=(0,a.useMemo)(()=>{let l=[];return R&&l.push("apple_pay"),pe&&l.push("google_pay"),l},[R,pe]),Wr=Sr?Di:Li,zi=x&&Wr.length>0,xo=Hn?Xe:xe,Yr=(0,a.useMemo)(()=>{let l=xo?.trim().toUpperCase();return l?ye?wr.filter($=>{let J=ye[$];return!J||J.length===0||J.includes(l)}):(0,C.filterStripeMethodsByCountry)(wr,xo):wr},[wr,xo,ye]),To=(0,a.useMemo)(()=>({mode:"payment",amount:Fe,currency:Me.toLowerCase(),paymentMethodCreation:"manual",appearance:Io}),[Fe,Me,Io]),[ua,pa]=(0,a.useState)("loading"),[ma,ya]=(0,a.useState)("loading"),[fa,ga]=(0,a.useState)("loading"),[Oi,Mo]=(0,a.useState)(!1),[ha,Ao]=(0,a.useState)("loading"),[Gr,Ni]=(0,a.useState)();(0,a.useEffect)(()=>{Ni(Ga())},[]);let Pa=I&&(kn||(Sr?Fi:Gr===!1)),ba=x&&zi,kr=!Je&&Pa&&kn,va=ha==="retrying"||ha==="exhausted",Rr=!Je&&Pa&&!!Te&&(!kn||va),Er=!Je&&ba&&!!Ce,Ir=!Je&&x&&Hr&&Yr.length>0&&!!Ce,Ui=kr&&!va?Oi:Rr&&ai(ua),$i=Er&&ai(ma),qi=Ir&&fa!=="load_error",Ca=l=>l==="loading"||l==="ready",Sa=kr||Rr&&Ca(ua)||Er&&Ca(ma)||Ir&&fa!=="load_error",Jr=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(!Jr.current){if(!x&&!I){Jr.current=!0;let l=new zt.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(l),Pe(l.message)}else if(!x&&I&&!kn&&!Te){Jr.current=!0;let l=new zt.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(l),Pe(l.message)}else if(Gr!==void 0&&!Je&&!ct&&!Sa){Jr.current=!0;let l=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"});u?.(l),Pe(l.message)}}},[x,I,kn,Te,Gr,Je,ct,Sa,u,Pe]);let wa=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(wa.current||!Hr)return;let l=[];R!==!0&&l.push("showApplePay"),pe!==!0&&l.push("showGooglePay"),l.length!==0&&(wa.current=!0,console.warn(`[FloPay] ${l.join(" / ")} ${l.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.`))},[Hr,R,pe]);let ka=(0,a.useCallback)((l,$)=>qe.applyInlineSessionPatch?qe.applyInlineSessionPatch(l).then(J=>({error:null,sessionId:J.sessionId||e,nonce:J.session?.clientSecret||t})).catch(J=>{let ue=oi($,J);return Pe(ue.message),u?.(ue),{error:ue,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[qe.applyInlineSessionPatch,t,u,e,Pe]),un=(0,a.useCallback)(async l=>{if(!ce)return{proceed:!0};try{let $=await ce({method:l,sessionId:e||void 0,createSession:qe.inlineSessionDraft});if($===!1)return{proceed:!1};if($&&typeof $=="object"){$.account&&or(ue=>({...ue??{},...$.account}));let J=await ka($,l);return J.error?{proceed:!1,accountPatch:$.account}:{proceed:!0,accountPatch:$.account,sessionId:J.sessionId,nonce:J.nonce}}return{proceed:!0}}catch($){let J=oi(l,$);return Pe(J.message),u?.(J),{proceed:!1}}},[ka,qe.inlineSessionDraft,ce,u,e,Pe]),Ra=(0,a.useCallback)(async(l,$)=>{if(M.current)return;M.current=!0,Qt(!0),Ve("processing"),Pe(null);let J=$?.sessionId??e,ue=$?.nonce??t,Y=jo(m,$?.accountPatch),Ie=$?.completionPaymentMethodId??Dr(l),De=l.originalPaymentMethodId?{...l,originalPaymentMethodId:void 0}:l;try{let bt=await new gn.PaymentAPI(K).processPayment(Y.userId??"",{sessionId:J,nonce:ue,tokenizedData:De,accountData:{userId:Y.userId??"",email:Y.email??"",firstName:Y.firstName??"",lastName:Y.lastName??"",...se?(()=>{let Se=wt.current,_t=(0,C.isAVSFieldVisible)(se.state,Se),jt=(0,C.isAVSFieldVisible)(se.address_line_1,Se),Xn=(0,C.isAVSFieldVisible)(se.postal_code,Se),Qn=jt&&!_t&&Xn?(0,C.getStateFromPostalCode)(Se,(Mt.current??"").trim()):null,xt=_t?Bt.current:Qn;return{country:Se,...Xn&&Mt.current?{zip:Mt.current}:{},...(0,C.isAVSFieldVisible)(se.city,Se)&&At.current?{city:At.current}:{},...xt?{state:xt}:{},...jt&&en.current?{addressLine1:en.current}:{},...(0,C.isAVSFieldVisible)(se.address_line_2,Se)&&tn.current?{addressLine2:tn.current}:{}}})():{}},chv:E,avsCheck:he??!1,checkoutType:B,checkoutLayout:fe,avsConfig:se?{country:(0,C.isAVSFieldVisible)(se.country,wt.current),postal_code:(0,C.isAVSFieldVisible)(se.postal_code,wt.current),address_line_1:(0,C.isAVSFieldVisible)(se.address_line_1,wt.current),address_line_2:(0,C.isAVSFieldVisible)(se.address_line_2,wt.current),city:(0,C.isAVSFieldVisible)(se.city,wt.current),state:(0,C.isAVSFieldVisible)(se.state,wt.current)}:void 0});if(bt.ok){let Se=bt.status===204?null:await bt.json().catch(()=>null),_t=(0,C.isAuthorizationOnlySession)(L)||Se?.status==="authorized";gr(J),Ve("success"),Ee(null),await new Promise(jt=>setTimeout(jt,yn)),s?.(_t?{status:"authorized",...typeof Se?.paymentId=="string"?{paymentId:Se.paymentId}:L?.paymentId?{paymentId:L.paymentId}:{},sessionId:typeof Se?.sessionId=="string"?Se.sessionId:J,...typeof Se?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Se.authorizationExpiresAt}:L?.authorizationExpiresAt?{authorizationExpiresAt:L.authorizationExpiresAt}:{},paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Ie,checkoutMethod:l.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Ie,checkoutMethod:l.isPaypal?"paypal":"card"});return}let nt=await bt.json().catch(()=>null);if(nt?.type==="paypal_redirect_required"){let Se=nt.threeDSecureToken,_t=nt.paymentMethodId||l.id||"";if(!He||!Se){Ve("error"),Pe("PayPal authorization required but no token provided.");return}try{let jt=yt?.getRawProvider();if(!jt){Pe("PayPal is not available.");return}let Xn={return_url:window.location.href};_t&&(Xn.payment_method=_t);let{error:Qn}=await jt.confirmPayment({clientSecret:Se,confirmParams:Xn,redirect:"if_required"});if(Qn){Ve("error");let xt=Qn.message??"PayPal payment failed.";Pe(xt),dn("paypal",xt,{code:Qn.code})}}catch(jt){Ve("error"),Pe(jt instanceof Error?jt.message:"PayPal authorization failed.")}return}if(nt?.type==="paypal_direct_required"){let Se=nt.orderId;if(!Se){Ve("error"),Pe("PayPal retry required but no order id provided.");return}let _t=y.current?.attempts??0;if(_t>=2){Ve("error"),Pe("PayPal payment could not be completed after multiple attempts."),dn("paypal","paypal_direct_required retry limit exceeded");return}Mo(!1),Ao("loading"),Ee({orderId:Se,attempts:_t+1}),Ve(null);return}Ve("error");let kt=nt?.message??"Payment failed. Please try again.";Pe(kt),dn(l.isPaypal?"paypal":"card",kt,{code:nt?.code??nt?.gatewayErrorCode,declineCode:nt?.declineCode??nt?.gatewayDeclineReason}),await new Promise(Se=>setTimeout(Se,Yt))}catch(dt){Ve("error"),Pe(dt instanceof Error?dt.message:"An unexpected error occurred"),await new Promise(bt=>setTimeout(bt,Yt))}finally{Qt(!1),Ve(null),M.current=!1}},[K,e,t,m,V,E,He,yt,L,s,u,Pe,dn]),an=(0,a.useCallback)((l,$)=>{v?v(l):Ra(l,$)},[v,Ra]),Ea=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||Ea.current)return;let l=new URLSearchParams(window.location.search),$=l.get("payment_intent"),J=l.get("payment_intent_client_secret"),ue=l.get("redirect_status");if(!$||!J)return;let Y=kt=>{let Se=localStorage.getItem(kt);if(!Se)return null;try{return JSON.parse(Se)}catch{return localStorage.removeItem(kt),null}},Ie=Y(Rn)??Y(ti),De;if(Ie?.clientSecret){if(Ie.clientSecret!==J)return;De={...Ie.accountPatch?{accountPatch:Ie.accountPatch}:{},...Ie.sessionId?{sessionId:Ie.sessionId}:{},...Ie.nonce?{nonce:Ie.nonce}:{}}}else if(Ie?.sessionId&&Ie.sessionId!==e)return;Ea.current=!0,localStorage.removeItem(Rn),localStorage.removeItem(ti);let dt=new URL(window.location.href);dt.searchParams.delete("payment_intent"),dt.searchParams.delete("payment_intent_client_secret"),dt.searchParams.delete("redirect_status"),window.history.replaceState({},"",dt.toString());let bt=Ie?.paymentMethodType??Ie?.tokenType??"card",nt="card";(async()=>{let kt=He?.getRawProvider();if(!kt){let xt="Payment is not available \u2014 please refresh and try again.";Pe(xt),dn(nt,xt);return}if(ue==="failed"){let xt="Payment was declined. Please try again.";Pe(xt),dn(nt,xt);return}let{paymentIntent:Se,error:_t}=await kt.retrievePaymentIntent(J);if(_t){let xt=_t.message??"Failed to retrieve payment status.";Pe(xt),dn(nt,xt,{code:_t.code});return}let jt=Se?.status,Xn=co(jt);if(!Se||!Xn){let xt=jt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Pe(xt),dn(nt,xt,{code:jt??"missing_payment_intent"});return}let Qn=typeof Se.payment_method=="string"?Se.payment_method:Se.payment_method?.id;an({id:Qn??Ie?.paymentMethodId??Ie?.tokenId??Se.id,type:"card",threeDSecureActionResultTokenId:Se.id,gateway:Ie?.gateway??"stripe",paymentMethodType:bt},De)})()},[e,an,He,Pe,dn]);let Bo=(0,a.useCallback)(l=>{l.preventDefault()},[]);if(!(He!==null))return(0,c.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let _r=oe==="buttons",Vt=H?.variables,Vi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Fo=Vt?.colorBackground,ji=Fo&&!Vi.has(Fo)?Fo:void 0,xr=b.cardInputBorder??(_r?"#e5e7eb":"#A4A4FF"),Do=Vt?.colorDanger??"#dc2626",Yn=l=>It&&l?Do:xr,Xr=(Dt.malformed||Dt.empty)&&(cn||It),Hi=Xr?Do:Yn(ht.zip),Lo=b.cardFormContainer?.backgroundColor??ji??(_r?"white":"#EDEDFF"),Tr=b.cardInputBackground??Vt?.colorBackground??"white",zo=sr(G),Ia=sr(me),ir=b.nameInput,_a=b.cardInputFontSize??Is(ir?.fontSize)??Vt?.fontSizeBase??"16px",xa=typeof ir?.fontFamily=="string"?ir.fontFamily:Vt?.fontFamily??"Poppins, sans-serif",Ta=qo(ir?.fontWeight)??400,Ki=b.cardInputColor??(typeof ir?.color=="string"?ir.color:void 0)??Vt?.colorText??"#262833",Wi=b.cardInputPlaceholderColor??"#9ca3af",Pt=Vt?.borderRadius??"8px",Gn=Vt?.borderRadius??b.cardButton?.borderRadius??Pt,Jn=Vt?.colorPrimary??"#4A49FF",Yi=Vt?.colorPrimaryHover??dr(Jn,.12),Oo=Vt?.colorText??"#262833",Ma={fontSize:_a,fontFamily:xa,fontWeight:Ta,color:Ki,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Gi={"--flopay-input-placeholder-color":Wi,"--flopay-input-font-size":_a,"--flopay-input-font-family":xa,"--flopay-input-font-weight":String(Ta)},Mr=b.cardFormContainer??{},No=Mr.padding??(_r?"0":"1rem"),Uo=Mr.borderRadius??Pt,Ji=at&&Ot?(0,c.jsx)(ur,{capture:at,html:Ot.html,messageToken:Ot.messageToken,expectedOrigin:Ot.expectedOrigin,theme:Ne,onReady:()=>{if(!se||typeof document>"u")return;let l=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};l();let $=0,J=window.setInterval(()=>{$+=1;let ue=document.activeElement;!!ue&&ue.tagName==="IFRAME"&&ue.id==="flopay_vault_form_iframe"?(l(),window.clearInterval(J)):$>=50&&window.clearInterval(J)},100)},onError:l=>Pe(l),onValidation:l=>{let $=F.current;($==="idle"||$==="validation-window")&&(Pe(l),l&&F.current==="validation-window"&&(q.current&&(clearTimeout(q.current),q.current=null),F.current="idle",Ve(null)))}}):(0,c.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"}),Aa=(0,c.jsxs)("div",{style:{backgroundColor:Lo,borderRadius:Uo,...Mr,padding:No,...Gi,display:"flex",flexDirection:"column"},children:[(0,c.jsx)("style",{children:`
|
|
31
31
|
.flopay-shared-input::placeholder {
|
|
32
32
|
color: var(--flopay-input-placeholder-color);
|
|
33
33
|
opacity: 1;
|
|
@@ -35,13 +35,13 @@ ${Ze.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),
|
|
39
|
-
`)}):null,
|
|
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:`
|
|
38
|
+
`}),_r&&Wn&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ye?-2:0},children:[(0,c.jsxs)("button",{type:"button",onClick:Un,style:{display:"inline-flex",alignItems:"center",gap:zo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:(0,c.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(cr,{content:G})]}),Ia?(0,c.jsx)("div",{style:{flex:1}}):(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...b.title},children:(0,c.jsx)(Br,{content:me})})]}),!_r&&!Ia&&(0,c.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Oo,order:Ye?-3:0,...b.title},children:(0,c.jsx)(Br,{content:me})}),se&&(0,c.jsx)("div",{style:{order:Ye?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let l=Xe,$=(Y=!1)=>({backgroundColor:Tr,border:`1px solid ${Yn(Y)}`,borderRadius:Pt,marginTop:"0.5rem",padding:"10px"}),J=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ma}),ue=(0,C.getStateOptions)(l);return(0,c.jsxs)(c.Fragment,{children:[(0,C.isAVSFieldVisible)(se.address_line_1,l)&&(0,c.jsx)("div",{style:$(ht.line1),children:(0,c.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:Ke,onChange:Y=>{St.current.addressLine1=!0,en.current=Y.target.value,ot(Y.target.value)},disabled:re,required:!0,"data-testid":"flopay-address-line1",style:J()})}),(0,C.isAVSFieldVisible)(se.address_line_2,l)&&(0,c.jsx)("div",{style:$(),children:(0,c.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:Y=>{St.current.addressLine2=!0,tn.current=Y.target.value,In(Y.target.value)},disabled:re,"data-testid":"flopay-address-line2",style:J()})}),((0,C.isAVSFieldVisible)(se.city,l)||(0,C.isAVSFieldVisible)(se.state,l))&&(0,c.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,C.isAVSFieldVisible)(se.city,l)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Tr,borderTop:`1px solid ${Yn(ht.city)}`,borderRight:`1px solid ${Yn(ht.city)}`,borderBottom:`1px solid ${Yn(ht.city)}`,borderLeft:`1px solid ${Yn(ht.city)}`,padding:"10px",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,...(0,C.isAVSFieldVisible)(se.state,l)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Pt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:st,onChange:Y=>{St.current.city=!0,At.current=Y.target.value,jn(Y.target.value)},disabled:re,required:!0,"data-testid":"flopay-city",style:J()})}),(0,C.isAVSFieldVisible)(se.state,l)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Tr,border:`1px solid ${Yn(ht.state)}`,padding:"10px",borderTopRightRadius:Pt,borderBottomRightRadius:Pt,...(0,C.isAVSFieldVisible)(se.city,l)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:Pt}},children:ue?(0,c.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Ht,onChange:Y=>{St.current.state=!0,Bt.current=Y.target.value,vn(Y.target.value)},disabled:re,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...J(),cursor:"pointer"},children:[(0,c.jsx)("option",{value:"",children:(0,C.getStateLabel)(l)}),ue.map(Y=>(0,c.jsx)("option",{value:Y.code,children:Y.name},Y.code))]}):(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,C.getStateLabel)(l),autoComplete:"billing address-level1",value:Ht,onChange:Y=>{St.current.state=!0,Bt.current=Y.target.value,vn(Y.target.value)},disabled:re,required:!0,"data-testid":"flopay-state",style:J()})})]}),((0,C.isAVSFieldVisible)(se.country,l)||(0,C.isAVSFieldVisible)(se.postal_code,l))&&(0,c.jsxs)("div",{style:{display:"flex",flexDirection:X==="column"?"column":"row",gap:X==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,C.isAVSFieldVisible)(se.country,l)&&(0,c.jsx)("div",{style:{flex:X==="row"?1:void 0,backgroundColor:Tr,borderTop:`1px solid ${xr}`,borderRight:`1px solid ${xr}`,borderBottom:`1px solid ${xr}`,borderLeft:`1px solid ${xr}`,padding:"10px",...X==="row"&&(0,C.isAVSFieldVisible)(se.postal_code,l)?{borderRadius:"0",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,borderRight:"none"}:{borderRadius:Pt}},children:(0,c.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Xe,onChange:Y=>{St.current.country=!0,wt.current=Y.target.value,Ae(Y.target.value),je?.(Y.target.value),Bt.current="",vn("")},disabled:re,autoComplete:"billing country","data-testid":"flopay-country",style:{...J(),cursor:"pointer"},children:C.COUNTRY_OPTIONS.map(Y=>(0,c.jsxs)("option",{value:Y.code,children:[Y.flag," ",Y.name]},Y.code))})}),(0,C.isAVSFieldVisible)(se.postal_code,l)&&(0,c.jsx)("div",{style:{flex:X==="row"?1:void 0,backgroundColor:Tr,border:`1px solid ${Hi}`,padding:"10px",...X==="row"&&(0,C.isAVSFieldVisible)(se.country,l)?{borderRadius:"0",borderTopRightRadius:Pt,borderBottomRightRadius:Pt}:{borderRadius:Pt}},children:(0,c.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:Ct,onChange:Y=>{St.current.zip=!0,Mt.current=Y.target.value,We(Y.target.value),$e?.(Y.target.value)},onBlur:()=>Kt(!0),disabled:re,required:Dt.required,"aria-invalid":Xr||void 0,"aria-describedby":Xr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:J()})})]}),Xr&&(0,c.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Do,...Ma,fontSize:"0.75rem"},children:Dt.empty?`${(0,C.getPostalCodeLabel)(l)} is required`:Rs(l)})]})})()}),Ye&&Z&&(0,c.jsx)("div",{style:{order:-2,width:"100%"},children:Z}),Ye&&Ji,f&&(0,c.jsx)(pr,{margin:"0.75rem 0",styleOverride:b.errorBanner,children:f})]}),Qr={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"},Ba=l=>rt?!I||!kn?(0,c.jsx)("pre",{"data-testid":l,style:Qr,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":l,style:Qr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${I}`,` directPaypalConfigured=${kn}`,` inAppBrowserDetected=${String(Gr)}`,` shouldRenderDirectPayPal=${kr}`,` shouldRenderStripePayPal=${Rr}`,` hasPaypalStripeInstance=${!!Te}`].join(`
|
|
39
|
+
`)}):null,Fa=l=>rt?!x||!Ce?(0,c.jsx)("pre",{"data-testid":l,style:Qr,children:"FloPay/Stripe-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":l,style:Qr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${x}`,` currency=${Me}`,` amountInCents=${Fe}`,` enabledPaymentMethods: ${JSON.stringify(g??[])}`,` enabledPaymentMethodsProvided=${Sr}`,` hasEnabledMethods=${Hr}`,` expressMethods: ${JSON.stringify(Kr)}`,` walletExpressMethods: ${JSON.stringify(Wr)}`,` paymentElementMethods: ${JSON.stringify(wr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Yr)}`,` hasStripeInstance=${!!Ce}`,` shouldRenderWallets=${Er}`,` shouldRenderPaymentElement=${Ir}`].join(`
|
|
40
|
+
`)}):null,Da=Be==="apm-expanding"||Be==="apm-form"||Be==="apm-collapsing",Zr=Be==="apm-expanding"?`flopay-card-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:Be==="apm-collapsing"?`flopay-card-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,eo=ft?{...To,paymentMethodTypes:[ft]}:null;if(oe==="buttons"){let l=Be==="buttons"||Be==="expanding"||Be==="apm-expanding",$=Be==="expanding"||Be==="card"||Be==="collapsing",J=j===void 0?{boxSizing:"border-box",height:yo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ue=Be==="expanding"||Be==="apm-expanding"?`flopay-buttons-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Be==="collapsing"||Be==="apm-collapsing"?`flopay-buttons-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,Y=Be==="expanding"?`flopay-card-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:Be==="collapsing"?`flopay-card-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,c.jsxs)("form",{onSubmit:Bo,className:S,style:{position:"relative"},children:[(0,c.jsx)(Yo,{}),on&&(0,c.jsx)(sn,{status:on,errorMessage:f,authorized:U}),(0,c.jsxs)("div",{style:{display:"grid"},children:[(0,c.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!l&&!ue?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!l&&!ue?Ss:{},...ue?{animation:ue,pointerEvents:"none"}:{}},children:[Ba("flopay-direct-paypal-gate-debug"),Fa("flopay-stripe-gate-debug"),kr&&Ze&&(0,c.jsxs)(c.Fragment,{children:[Re&&(0,c.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,c.jsx)(zr,{sessionId:e,nonce:t,billingApiUrl:o,email:m.email,clientId:Ze.clientId,environment:Ze.environment,currency:Me.toUpperCase(),isSubscription:mt,onTokenizedBody:an,onComplete:s,onErrorChange:Pe,onDecline:d,onTechnicalFailure:ar,onButtonClick:be,runBeforeButtonClick:un,isProcessing:re,onLoadStateChange:Mo,onInitializationStateChange:Ao,session:L??null,existingOrderId:Re?.orderId,debug:rt},Re?.orderId??"fresh")]}),Rr&&(0,c.jsx)(gt.Elements,{stripe:Te,options:la,children:(0,c.jsx)(ii,{sessionId:e,nonce:t,email:m.email,billingApiUrl:o,onTokenizedBody:an,onErrorChange:Pe,isProcessing:re,onButtonClick:be,onDecline:d,onTechnicalFailure:ar,runBeforeButtonClick:un,onLoadStateChange:pa,placeholderBorderRadius:Gn})}),Er?(0,c.jsx)(gt.Elements,{stripe:Ce,options:jr,children:(0,c.jsx)(si,{sessionId:e,nonce:t,email:m.email,billingApiUrl:o,intentKind:te>0?"payment":"setup",expressMethods:Wr,onTokenizedBody:an,onErrorChange:Pe,onButtonClick:be,onDecline:d,onTechnicalFailure:ar,runBeforeButtonClick:un,onLoadStateChange:ya,placeholderBorderRadius:Gn})}):ba?(0,c.jsx)("div",{style:{height:yo,borderRadius:Gn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Ir&&(0,c.jsx)(li,{sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,paymentElementMethods:Yr,stripeInstance:Ce,paymentElementBaseOptions:To,onTokenizedBody:an,onErrorChange:Pe,onButtonClick:be,onDecline:d,runBeforeButtonClick:un,onLoadStateChange:ga,isProcessing:re,submitButtonColor:Jn,submitButtonBorderRadius:Pt,submitButtonStyle:b.submitButton,onExpandApm:rn,expandedApmMethod:ft,themeId:O,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:Gn}}),Ye&&(0,c.jsx)("button",{type:"button",onClick:async()=>{re||!(await un("card")).proceed||(be?.("card"),Nn())},disabled:re,style:{width:"100%",...J,...b.cardButton,...Xo({themeBundle:z,resolvedPrimaryColor:Jn,resolvedBorderRadius:Pt,submitButtonStyle:b.submitButton,explicitPrimaryColor:Vt?.colorPrimary}),fontSize:b.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:re?"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:re?.6:1},onMouseEnter:Ie=>{!re&&(z||Vt?.colorPrimary)&&(Ie.currentTarget.style.backgroundColor=Yi)},onMouseLeave:Ie=>{(z||Vt?.colorPrimary)&&(Ie.currentTarget.style.backgroundColor=Jn)},onMouseDown:Ie=>{Ie.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ie=>{Ie.currentTarget.style.transform="scale(1)"},children:(0,c.jsx)(lr,{content:j})}),f&&Be==="buttons"&&(0,c.jsx)(pr,{margin:"0.25rem 0",styleOverride:b.errorBanner,children:f})]}),Ye&&$&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...Y?{animation:Y}:{},...Be==="collapsing"?{pointerEvents:"none"}:{}},children:Aa}),x&&Da&&ft&&eo&&Ce&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...Zr?{animation:Zr}:{},...Be==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Lo,borderRadius:Uo,...Mr,padding:No},children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,c.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:zo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:(0,c.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(cr,{content:G})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:Oo,paddingRight:80,...b.title},children:`Pay with ${(0,C.getStripeMethodDisplayName)(ft)}`})]}),(0,c.jsx)(gt.Elements,{stripe:Ce,options:eo,children:(0,c.jsx)(Go,{method:ft,sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,onTokenizedBody:an,onErrorChange:Pe,onDecline:d,onCancel:Wt,runBeforeButtonClick:un,onButtonClick:be,isProcessing:re,submitButtonColor:Jn,submitButtonBorderRadius:Pt,submitButtonStyle:b.submitButton,errorText:f})},ft)]})})]})]})}return Da&&ft&&eo&&Ce&&x?(0,c.jsxs)("form",{onSubmit:Bo,className:S,style:{position:"relative"},children:[(0,c.jsx)(Yo,{}),on&&(0,c.jsx)(sn,{status:on,errorMessage:f,authorized:U}),(0,c.jsx)("div",{style:{...Zr?{animation:Zr}:{},...Be==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Lo,borderRadius:Uo,...Mr,padding:No},children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,c.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:zo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:(0,c.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(cr,{content:G})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:Oo,paddingRight:80,...b.title},children:`Pay with ${(0,C.getStripeMethodDisplayName)(ft)}`})]}),(0,c.jsx)(gt.Elements,{stripe:Ce,options:eo,children:(0,c.jsx)(Go,{method:ft,sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,onTokenizedBody:an,onErrorChange:Pe,onDecline:d,onCancel:Wt,runBeforeButtonClick:un,onButtonClick:be,isProcessing:re,submitButtonColor:Jn,submitButtonBorderRadius:Pt,submitButtonStyle:b.submitButton,errorText:f})},ft)]})})]}):(0,c.jsxs)("form",{onSubmit:Bo,className:S,style:{position:"relative"},children:[(0,c.jsx)(Yo,{}),on&&(0,c.jsx)(sn,{status:on,errorMessage:f,authorized:U}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ba("flopay-direct-paypal-gate-debug-default"),Fa("flopay-stripe-gate-debug-default"),kr&&Ze&&(0,c.jsxs)(c.Fragment,{children:[Re&&(0,c.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,c.jsx)(zr,{sessionId:e,nonce:t,billingApiUrl:o,email:m.email,clientId:Ze.clientId,environment:Ze.environment,currency:Me.toUpperCase(),isSubscription:mt,onTokenizedBody:an,onComplete:s,onErrorChange:Pe,onDecline:d,onTechnicalFailure:ar,onButtonClick:be,runBeforeButtonClick:un,isProcessing:re,onLoadStateChange:Mo,onInitializationStateChange:Ao,session:L??null,existingOrderId:Re?.orderId,debug:rt},Re?.orderId??"fresh")]}),Rr&&(0,c.jsx)(gt.Elements,{stripe:Te,options:la,children:(0,c.jsx)(ii,{sessionId:e,nonce:t,email:m.email,billingApiUrl:o,onTokenizedBody:an,onErrorChange:Pe,isProcessing:re,onButtonClick:be,onDecline:d,onTechnicalFailure:ar,runBeforeButtonClick:un,onLoadStateChange:pa,placeholderBorderRadius:Gn})}),Er&&(0,c.jsx)(gt.Elements,{stripe:Ce,options:jr,children:(0,c.jsx)(si,{sessionId:e,nonce:t,email:m.email,billingApiUrl:o,intentKind:te>0?"payment":"setup",expressMethods:Wr,onTokenizedBody:an,onErrorChange:Pe,onButtonClick:be,onDecline:d,onTechnicalFailure:ar,runBeforeButtonClick:un,onLoadStateChange:ya,placeholderBorderRadius:Gn})}),Ir&&(0,c.jsx)(li,{sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,paymentElementMethods:Yr,stripeInstance:Ce,paymentElementBaseOptions:To,onTokenizedBody:an,onErrorChange:Pe,onButtonClick:be,onDecline:d,runBeforeButtonClick:un,onLoadStateChange:ga,isProcessing:re,submitButtonColor:Jn,submitButtonBorderRadius:Pt,submitButtonStyle:b.submitButton,themeId:O,onExpandApm:rn,expandedApmMethod:ft,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:Gn}})]}),Ye&&($i||Ui||qi)&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,c.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,c.jsx)("span",{children:"or pay with card"}),(0,c.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ye&&Aa]})}var Pr=require("@flopay/js"),Le=require("@flopay/shared");var Ur="card";async function Ts(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:u}=await e.retrieveSetupIntent(t);return{error:u,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:i,error:r}=await e.retrievePaymentIntent(t);return{error:r,intent:i??null}}async function Ms(e,t,n,i){if(i){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:u,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:u??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:r,error:s}=await e.confirmCardPayment(t,n);return{error:s,intent:r??null}}function Zo(e,t){return Object.assign(e,{checkoutMethod:t})}function Dn(e,t){let n=e instanceof Le.FloPayError?e:new Le.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 Nr(e,t){try{return await e()}catch(n){throw Dn(n,t)}}function yi(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 As(e){return e.status==="succeeded"||e.status==="declined"}async function fi(e){if(typeof document>"u"||typeof window>"u")throw new Le.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Le.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,i=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,s=async()=>{let h=new AbortController,E=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",E);let S=window.setTimeout(()=>h.abort(),i);try{let _=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!_.ok)return{status:"unknown"};let p=await _.json().catch(()=>null);return Bs(p)}catch{return{status:"unknown"}}finally{window.clearTimeout(S),e.signal?.removeEventListener("abort",E)}},u=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 v=document.createElement("iframe");v.setAttribute("title","Card authentication"),v.setAttribute("allow","payment"),v.tabIndex=0,v.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(";"),v.src=e.nextActionRedirectUrl,d.appendChild(v),document.body.appendChild(d),v.focus();let A=null;try{A=new URL(e.billingApiUrl,window.location.href).origin}catch{A=null}try{let h=await new Promise((E,S)=>{let _=!1,p=0,P=0,I=0,x=!1,g=()=>{window.clearTimeout(p),window.clearInterval(P),window.clearTimeout(I),window.removeEventListener("message",oe),v.removeEventListener("load",R),e.signal?.removeEventListener("abort",pe)},ye=async()=>{if(!(_||x)){x=!0;try{let O=await s();if(_||!As(O))return;_=!0,g(),E(O)}finally{x=!1}}},R=()=>{window.clearTimeout(I),I=window.setTimeout(()=>{ye()},250)},pe=()=>{_||(_=!0,g(),S(new Le.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},oe=O=>{if(O.source!==v.contentWindow||A&&O.origin!==A)return;let ee=O.data;!ee||typeof ee!="object"||ee.source!=="flopay-vault-3ds-return"||_||(_=!0,g(),E(null))};p=window.setTimeout(()=>{_||(_=!0,g(),S(new Le.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),P=window.setInterval(()=>{ye()},n),v.addEventListener("load",R),window.addEventListener("message",oe),e.signal?.addEventListener("abort",pe),e.signal?.aborted&&pe()});return h||await s()}finally{d.parentNode?.removeChild(d),u?.isConnected&&u.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 Vn(e,t="Payment failed. Please try again.",n){let i=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),r=e?.message??t,s=$n(r)??r;return Zo(new Le.FloPayError(s,"api_error",{code:(0,Le.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Le.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),i)}function Qo(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ho(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Fs(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 gi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||ho(r)))return r;let i=e?.data;if(i&&typeof i=="object"){let r=i,s=[r.threeDSecureToken,r.clientSecret,r.stripeClientSecret,r.id];for(let d of s)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||ho(d)))return d;let u=r.gateways;if(u&&typeof u=="object"){let d=u.stripe;if(d&&typeof d=="object"){let v=d,A=[v.stripeClientSecret,v.clientSecret];for(let h of A)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||ho(h)))return h}}}}async function Ds({billingApiUrl:e,sessionId:t,nonce:n,responseJson:i}){let r=gi(i,{requirePaymentIntentClientSecret:!0});if(typeof r=="string"&&r.length>0)return{type:"3ds_required",threeDSecureToken:r};if(!t)return null;try{let d=(await new Pr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ho(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function br({billingApiUrl:e,sessionId:t,session:n,nonce:i,tokenizedData:r,returnUrl:s,telemetry:u}){let d=e.replace(/\/+$/,""),v=t??n.id,A=i??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",E=n.customer?.email??n.accountData?.email??"",S=n.customer?.firstName??n.accountData?.firstName??"",_=n.customer?.lastName??n.accountData?.lastName??"",p=n.customer?.country??n.accountData?.country??void 0,P=n.customer?.zip??n.accountData?.zip??void 0,I=new Pr.PaymentAPI(d,u===!1?{telemetry:!1}:void 0),x=await Fs(()=>I.processPayment(h,{sessionId:v,nonce:A,tokenizedData:r,accountData:{userId:h,email:E,firstName:S,lastName:_,country:p,zip:P},returnUrl:s??Qo(n)}));if(x.ok){let R=typeof x.json=="function"?await x.json().catch(()=>null):null;return(0,Le.isAuthorizationOnlySession)(n)||R?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof R?.paymentId=="string"?R.paymentId:n.paymentId,sessionId:typeof R?.sessionId=="string"?R.sessionId:v,authorizationExpiresAt:typeof R?.authorizationExpiresAt=="string"?R.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Dr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:Dr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}}let g;try{g=await x.json()}catch{throw new Le.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:x.status})}if(g?.type==="paypal_redirect_required"||g?.type==="3ds_required"){let R=gi(g);if(!R)throw new Le.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:x.status});return{type:g.type,threeDSecureToken:R,paymentMethodId:g.paymentMethodId}}if(g?.gatewayErrorCode==="authentication_required"){let R=await Ds({billingApiUrl:d,sessionId:v,nonce:A,responseJson:g});if(R)return R;throw Zo(new Le.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ye=new Le.FloPayError(g?.message??"Payment failed. Please try again.","api_error",{code:g?.code??g?.gatewayErrorCode,declineCode:g?.declineCode??g?.gatewayDeclineReason,statusCode:x.status});throw Object.assign(ye,{telemetryOutcome:(0,Le.classifyPaymentRejection)(x.status,g)})}async function Po(e,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:s,session:u,returnUrl:d,telemetry:v}){let A=t?.getRawProvider();if(!A)throw Dn(new Le.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!i||!e.threeDSecureToken)throw Zo(new Le.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=(0,Le.isSetupIntentClientSecret)(e.threeDSecureToken),E=null,S=e.paymentMethodId,_=await Nr(()=>Ts(A,e.threeDSecureToken,h),"card");if(_){if(_.error)throw Dn(new Le.FloPayError(_.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let P=_.intent;!S&&P?.payment_method&&(typeof P.payment_method=="string"?S=P.payment_method:"id"in P.payment_method&&(S=P.payment_method.id??void 0))}let p=S?await Nr(()=>Ms(A,e.threeDSecureToken,{payment_method:S,return_url:d??Qo(u)??window.location.href},h),"card"):null;if(p){if(p.error)throw Dn(new Le.FloPayError(p.error.message??"3DS authentication failed.","api_error",{code:p.error.code}),"card");E=p.intent}else{let P=await Nr(()=>A.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(P.error)throw Dn(new Le.FloPayError(P.error.message??"3DS authentication failed.","api_error",{code:P.error.code}),"card");E=(h?P.setupIntent:P.paymentIntent)??null}if(E&&(E.status==="requires_capture"||E.status==="succeeded"||E.status==="processing")){let P=await br({billingApiUrl:r,sessionId:s,session:u,telemetry:v,tokenizedData:{id:E.id,type:"card",threeDSecureActionResultTokenId:E.id},returnUrl:d});return P.type==="success"?{...P.result,paymentIntentId:P.result.paymentIntentId??E.id,paymentMethodId:P.result.paymentMethodId??S}:Po(P,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:s,session:u,returnUrl:d,telemetry:v})}throw Dn(new Le.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw Dn(new Le.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:S}=await Nr(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(S)throw Dn(new Le.FloPayError(S.message??"PayPal authorization failed.","api_error",{code:S.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:E}=await Nr(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Qo(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(E)throw Dn(new Le.FloPayError(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Le.FloPayError("Unsupported payment redirect state.","api_error")}function tr(e){if(e instanceof Le.FloPayError){let i=$n(e.message);return i&&i!==e.message?Object.assign(new Le.FloPayError(i,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=$n(t)??t;return new Le.FloPayError(n,"api_error")}function bo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Le.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 vo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:i,telemetry:r}){if(!e)return{flopay:null,paypalFlopay:null};let s=!!t&&t!==e,[u,d]=await Promise.all([(0,Pr.loadFloPay)(e,{billingApiUrl:n,locale:i,telemetry:r}),s?(0,Pr.loadFloPay)(t,{billingApiUrl:n,locale:i,telemetry:r}).catch(v=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",v),null)):Promise.resolve(null)]);return{flopay:u,paypalFlopay:t?s?d:u:null}}var k=require("react/jsx-runtime"),vr=44,ia="flopay_checkout_saved_payment_resume",wo=new Map,Co=new Map;function hi(e,t){t.settled&&t.consumers===0&&wo.get(e)===t&&wo.delete(e)}function Ls(e,t,n){let i=Co.get(e);if(i&&(!i.sdkGeneratedIdempotencyKey||!t||i.sdkGeneratedIdempotencyKey===t))return i.attempt;let r=n(),s={attempt:r,sdkGeneratedIdempotencyKey:t};Co.set(e,s);let u=()=>{Co.get(e)===s&&Co.delete(e)};return r.then(u,u),r}function $r(e){return new Promise(t=>setTimeout(t,e))}function So(e,t,n){let i=no({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:we.SDK_VERSION,enabled:t!==!1});return i.beginCheckout(n),i}function qr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ea(e,t,n,i,r){let s=So(e,t,n);s.error({errorCode:i,stage:r,paymentMethodCategory:"unknown",...r==="session_read"?{requestCategory:"session_read"}:{}}),qr(s)}function zs(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 oa(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function ta(e){return!e||e.data.stripe?.publishableKey?!1:!!oa(e)?.clientId}function Ln(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Os(){if(!Ln())return null;try{let e=window.sessionStorage.getItem(ia);return e?JSON.parse(e):null}catch{return null}}function Pi(e){if(Ln())try{window.sessionStorage.setItem(ia,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function na(){if(Ln())try{window.sessionStorage.removeItem(ia)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var sa=":idempotency-key";function Ns(e){if(!Ln())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 bi(e,t,n){if(Ln())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(i){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",i)}}function aa(e){if(Ln())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function Us(e){if(Ln())try{return window.sessionStorage.getItem(e+sa)??void 0}catch{return}}function $s(e,t){if(Ln())try{window.sessionStorage.setItem(e+sa,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function qs(e){if(aa(e),!!Ln())try{window.sessionStorage.removeItem(e+sa)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Vs(){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 i of t)e.searchParams.has(i)&&(e.searchParams.delete(i),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function vi(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 ra(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function ko({sessionId:e,nonce:t,createSession:n,billingApiUrl:i,telemetry:r,appearance:s,locale:u,loading:d,error:v,onComplete:A,onError:h,onDecline:E,onCountryChange:S,onZipChange:_,showPayPal:p=!0,showStripe:P=!0,enabledPaymentMethods:I,showApplePay:x=!0,showGooglePay:g=!0,debug:ye=!1,layout:R,theme:pe,buttonsTheme:oe,buttonsStyles:O,cardButtonContent:ee,cardBackButtonContent:Q,cardTitleContent:le,showSecurityFooter:j,onButtonClick:G,onBeforeButtonClick:me,enableAVS:_e,cardFieldOrder:be,cardPreFormSlot:ce,avsLayout:ae,className:ge,initialErrorMessage:Z=null,children:X,checkoutMode:xe,confirmLabel:ve,renderConfirmButton:ie,onSessionCompleted:W}){let w=(0,we.resolveBillingApiUrl)(i),de=(0,D.useMemo)(()=>(0,we.resolveTheme)(pe),[pe]),je=s??de?.appearance,$e=n?"embedded_checkout":"standard_checkout",he=X?"custom_layout":R==="buttons"?"buttons_layout":"default_layout",[B,fe]=(0,D.useState)(null),[te,Me]=(0,D.useState)(null),pt=(0,D.useRef)(null),[Ze,mt]=(0,D.useState)(null),L=(0,D.useRef)(null),[ne,rt]=(0,D.useState)(null),[He,yt]=(0,D.useState)(e??""),qe=e??He,Je=n?"":qe,[Xt,Qe]=(0,D.useState)(!0),[Qt,T]=(0,D.useState)(null),[ke,Xe]=(0,D.useState)("full"),[Ae,Ct]=(0,D.useState)(!1),[We,Ke]=(0,D.useState)(Z),[ot,et]=(0,D.useState)(null),[In,st]=(0,D.useState)(null),[jn,Ht]=(0,D.useState)(!1),[vn,Zt]=(0,D.useState)(void 0),[or,Mt]=(0,D.useState)(""),[wt,en]=(0,D.useState)(!1),[tn,At]=(0,D.useState)(!1),Bt=(0,D.useRef)(0),[St,se]=(0,D.useState)("loading"),[Hn,U]=(0,D.useState)(0),lt=(0,D.useRef)(!1),Ft=(0,D.useRef)(!1),zn=(0,D.useRef)(!1),Oe=(0,D.useRef)(null),ct=(0,D.useMemo)(()=>({checkoutMode:xe??ke,layout:X?"unknown":R==="buttons"?"buttons":"embedded"}),[xe,X,ke,R]),Ye=(0,D.useRef)(A);Ye.current=A;let _n=(0,D.useRef)(h);_n.current=h;let xn=(0,D.useRef)(E);xn.current=E,(0,D.useEffect)(()=>{Tt(te)?.setCheckoutContext(ct),Ze&&Ze!==te&&Tt(Ze)?.setCheckoutContext(ct)},[te,Ze,ct]);let On=(0,D.useRef)(W);On.current=W;let Kn=(0,D.useCallback)(M=>{se(M),!(M!=="exhausted"||zn.current)&&(zn.current=!0,_n.current?.(new we.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Tn=(0,D.useCallback)(()=>{se("retrying"),U(M=>M+1)},[]);(0,D.useEffect)(()=>{se("loading"),U(0),zn.current=!1},[qe]),(0,D.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:we.SDK_VERSION,checkout_type:$e,checkout_layout:he,billing_api_url:w})},[he,$e,w]);let at=(0,D.useMemo)(()=>n?Ot(n,!0):"",[n]),Dt=(0,D.useMemo)(()=>or===at?vn:void 0,[vn,or,at]),ln=(0,D.useMemo)(()=>n?Vo(n,Dt):void 0,[n,Dt]),ht=xe??ln?.checkoutMode??"full",It=(0,D.useMemo)(()=>ln?{...ln,checkoutMode:ht}:void 0,[ln,ht]);(0,D.useEffect)(()=>{Zt(void 0),Mt(at)},[at]),(0,D.useEffect)(()=>{Ke(Z)},[Z]);let nn=(0,D.useCallback)((M,q,F)=>{Ge(()=>{xn.current?.(Et(M,q,F))})},[Ge]),cn=(0,D.useCallback)(async(M,q)=>{Ke(null),st(null),Ht(!1),et("processing");let F=q?.sessionId??M.id,Re=pt.current??L.current,Ee=Tt(Re),y=Re?null:So(w,r,ct),o={log:m=>{Ee?Ee.log(m):y?.log(m)},error:m=>{Ee?Ee.error(m):y?.error(m)},terminal:m=>{Ee?Ee.terminal(m):y?.terminal(m)},performance:m=>{Ee?Ee.performance(m):y?.performance(m)},now:()=>Ee?.now()??y?.now()??0,elapsed:m=>Ee?.elapsed(m)??Math.max(0,(y?.now()??m)-m)},f=o.now(),z=!!(q?.initialAutoProcessingError||q?.initialAutoProcessingPending),b=!1,H,Ne=()=>{b||(b=!0,z=!0,H=o.now(),o.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),o.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},tt=!1,re=()=>{tt||(tt=!0,o.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),o.performance({stage:"processing",durationMs:o.elapsed(f),durationMode:"machine",paymentMethodCategory:"saved"}),H!==void 0&&o.performance({stage:"recovery",durationMs:o.elapsed(H),durationMode:"machine",paymentMethodCategory:"saved"}))};o.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),o.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),z&&Ne();let K;try{let m=yi(q?.initialAutoProcessingError),V;if(m)Ne(),m.type==="paypal_redirect_required"&&Oe.current?.publishableKey&&Pi({sessionId:F,publishableKey:Oe.current.publishableKey,paypalPublishableKey:Oe.current.paypalPublishableKey}),V=await Po(m,{flopay:pt.current,paypalFlopay:L.current,attempt3DS:q?.attempt3DS,billingApiUrl:w,sessionId:F,session:M,telemetry:!1}),m.type==="paypal_redirect_required"&&na();else if(q?.initialAutoProcessingPending){let Fe=(await new nr.PaymentAPI(w,{telemetry:!1}).waitForCheckoutSessionCompletion(q.initialAutoProcessingPending.sessionId,{initialDelayMs:q.initialAutoProcessingPending.retryAfterMs})).data.session;if(!fr(Fe))throw lo(Fe);V=Zn(Fe,F)}else{if(q?.initialAutoProcessingError)throw Vn(q.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:q.initialAutoProcessingError.checkoutMethod});if(q?.fromCreateSession)return q?.fallbackToFull&&(Xe("full"),vi("full")),!1;{let Ce=await br({billingApiUrl:w,sessionId:F,session:M,telemetry:!1});Ce.type==="success"?V=Ce.result:(Ne(),Ce.type==="paypal_redirect_required"&&Oe.current?.publishableKey&&Pi({sessionId:F,publishableKey:Oe.current.publishableKey,paypalPublishableKey:Oe.current.paypalPublishableKey}),V=await Po(Ce,{flopay:pt.current,paypalFlopay:L.current,attempt3DS:q?.attempt3DS,billingApiUrl:w,sessionId:F,session:M,telemetry:!1}),Ce.type==="paypal_redirect_required"&&na())}}F&&gr(F),re(),z&&(o.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),o.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),o.terminal({outcome:V.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Ht(V.status==="authorized"),et("success"),await $r(yn),K=()=>Ye.current?.(V)}catch(m){let V=tr(m),Ce=V.checkoutMethod??Ur;Ke(V.message),st(V.message),Ht(!1),q?.fallbackToFull&&(o.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Xe("full"),vi("full")),re();let Te=V.statusCode!==void 0?(0,we.telemetryStatusClass)(V.statusCode,"unknown"):void 0,Fe=Te==="4xx"?{requestCategory:"process_payment",statusClass:Te}:{},Sn=Te===void 0||Te==="4xx";if(Sn&&(V.telemetryOutcome==="payment_declined"||!!(V.declineCode||V.code?.toLowerCase().includes("declin"))))o.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Fe});else if(Sn&&(V.telemetryOutcome==="validation_rejected"||V.type==="validation_error"))o.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Fe});else{let jr=(0,we.classifyTelemetryFailure)(m,z?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");o.error({...jr,...V.telemetryFailureCategory?{failureCategory:V.telemetryFailureCategory}:{},stage:z?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:V.telemetryRequestCategory??"process_payment"})}return Ge(()=>_n.current?.(V)),nn(Ce,V,{code:V.code,declineCode:V.declineCode}),et("error"),await Promise.allSettled([$r(Yt),q?.ensureProvidersReady?q.ensureProvidersReady():Promise.resolve()]),z&&(o.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),o.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{re(),y&&qr(y),et(null),st(null)}return Ge(K),!0},[nn,Ge,tr,w,r,ct]);(0,D.useEffect)(()=>{if(typeof window>"u"||Ft.current)return;let M=new URLSearchParams(window.location.search),q=M.get("payment_intent_client_secret");if(!q)return;let F=Os();F&&(Ft.current=!0,(async()=>{let Re,Ee=0;Ke(null),st(null),et("processing"),Ct(!0);try{if(M.get("redirect_status")==="failed")throw Object.assign(new we.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:y,paypalFlopay:o}=await vo({publishableKey:F.publishableKey,paypalPublishableKey:F.paypalPublishableKey,billingApiUrl:w,locale:u,telemetry:r});Re=Tt(o??y),Ee=Re?.now()??0,Re?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Re?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let f=(o??y)?.getRawProvider();if(!f)throw Object.assign(new we.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:z,error:b}=await f.retrievePaymentIntent(q);if(b)throw Object.assign(new we.FloPayError(b.message??"Failed to retrieve PayPal payment status.","api_error",{code:b.code}),{checkoutMethod:"paypal"});let H=Wa(z?.status);if(!z||H==="failed")throw Object.assign(new we.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Ne=typeof z.payment_method=="string"?z.payment_method:z.payment_method?.id,tt=H;if(F.sessionId){let m=(await new nr.PaymentAPI(w,{telemetry:!1}).getUnifiedCheckoutSession(F.sessionId)).data.session;if(m&&m.status!=="complete"){let V=await br({billingApiUrl:w,sessionId:F.sessionId,session:m,telemetry:!1,tokenizedData:{id:Ne??z.id,type:"card",threeDSecureActionResultTokenId:z.id,isPaypal:!0}});if(V.type!=="success")throw Object.assign(new we.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});tt=V.result.status}}F.sessionId&&gr(F.sessionId),Re?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Re?.performance({stage:"redirect_resume",durationMs:Re.elapsed(Ee),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Re?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),et("success"),await $r(yn),Ge(()=>Ye.current?.({status:tt,paymentIntentId:z.id,paymentMethodId:Ne,checkoutMethod:"paypal"}))}catch(y){let o=tr(y),f=o.checkoutMethod??"paypal",z=!!(o.declineCode||o.code?.toLowerCase().includes("declin"));if(Re)Re.performance({stage:"redirect_resume",durationMs:Re.elapsed(Ee),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),z?Re.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Re.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(z){let b=So(w,r,ct);b.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),qr(b)}else ea(w,r,ct,"REDIRECT_RESUME_FAILED","redirect_resume");Ke(o.message),st(o.message),Ge(()=>_n.current?.(o)),nn(f,o,{code:o.code,declineCode:o.declineCode}),et("error"),await $r(Yt)}finally{na(),Vs(),et(null),st(null),Ct(!1)}})())},[nn,Ge,u,tr,w,r]);let Kt=(0,D.useRef)(null);function Ot(M,q=!1){let F=M?.account?.email?.trim().toLowerCase()??"",Re={c:M?.clientId,cur:M?.currency??"",captureMethod:M?.captureMethod??"",a:{e:F,u:F?"":M?.account?.userId??"",country:M?.account?.country??""},successUrl:M?.successUrl,cancelUrl:M?.cancelUrl,p:M?.products?.map(o=>ra(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:M?.items?.map(o=>ra(o.code??o.providerItemId??"",o)).sort(),s:M?.subscriptions?.map(o=>ra(o.code??o.providerPlanId??"",o)).sort(),couponCodes:M?.couponCodes?[...M.couponCodes].sort():void 0,...q?{tagsData:M?.tagsData,utmMetadata:M?.utmMetadata,tokenizedData:M?.tokenizedData,checkoutMode:M?.checkoutMode??"full"}:{}},Ee=JSON.stringify(Re),y=0;for(let o=0;o<Ee.length;o++)y=(y<<5)-y+Ee.charCodeAt(o)|0;return`flopay_session_${Math.abs(y).toString(36)}`}let Nt=(0,D.useMemo)(()=>It?Ot(It):"",[It]),Be=(0,D.useRef)(It);Be.current=It,(0,D.useEffect)(()=>{yt(e??"")},[e]),(0,D.useEffect)(()=>{lt.current=!1,Ke(Z),st(null),Ht(!1),et(null)},[Nt,Z,e]);async function Ut(M,q){let F=So(w,r,ct),Re=new nr.PaymentAPI(w,{telemetry:!1}),Ee=!1;try{let y=M.idempotencyKey!==void 0?(0,we.resolveIdempotencyKey)(M.idempotencyKey):void 0,o=y??Us(q),f,z=!1,b=Ns(q);F.log({name:b?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let H=b?.sid??null,Ne=null,tt;if(H)try{if(Ne=await Re.getUnifiedCheckoutSession(H,b?.nonce),Ne.data.session?.status==="complete"){if(Ho(H))return{sid:H,result:Ne};qs(q),H=null,Ne=null,z=!0}}catch{F.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),aa(q),H=null}if(!H){!y&&(z||!o)&&(o=(0,we.resolveIdempotencyKey)(),f=o),o&&$s(q,o);let re=F.now(),K=0;F.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let m={...M,idempotencyKey:o,avsCheck:!!_e,avsConfig:typeof _e=="object"?_e:void 0,checkoutType:"embedded_checkout",checkoutLayout:X?"custom_layout":R==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(m,nr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Te=>{K=Math.max(K,Te)}}});let V=()=>{F.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),F.performance({stage:"session_create",durationMs:F.now()-re,durationMode:"machine",requestCategory:"session_create",attempt:K,statusClass:"2xx"})},Ce=Te=>{let Fe=(0,we.classifyTelemetryFailure)(Te,"CHECKOUT_SESSION_CREATE_FAILED","unknown");F.performance({stage:"session_create",durationMs:F.now()-re,durationMode:"machine",requestCategory:"session_create",attempt:K,statusClass:Fe.statusClass}),Te instanceof we.FloPayError&&Te.type==="validation_error"?F.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):Fe.statusClass==="4xx"?F.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):F.error({...Fe,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if((0,we.isDetachedSessionEligible)(m)){let Te=await Re.createDetachedSession(m);Te.claimed.catch(()=>{}),Ne=Te.shell,H=Te.sessionId,tt=Te.claimed.then(Fe=>{let Sn=Fe.data.session?.id??Te.sessionId;return Sn&&bi(q,Sn,Fe.data.session?.clientSecret??Te.nonce),V(),Fe},Fe=>{throw aa(q),Ce(Fe),Fe}).finally(()=>qr(F)),tt.catch(()=>{}),Ee=!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()-re,durationMode:"machine",requestCategory:"session_create",attempt:K,statusClass:"2xx",paymentMethodCategory:"card"})}else Ne=await Re.createAndFetchSession(m),V()}catch(Te){throw Ce(Te),Te}H=Ne.data.session?.id??H??"",H&&!tt&&bi(q,H,Ne.data.session?.clientSecret)}return{sid:H??"",result:Ne,sdkGeneratedIdempotencyKey:f,...tt?{claimed:tt}:{}}}finally{Ee||qr(F)}}let ft=(0,D.useCallback)(async(M,q)=>{let F=Be.current;if(!F)throw new we.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Re=Vo(F,M),Ee=Ot(Re),y=wo.get(Ee);if(!y){let z={promise:Ut(Re,Ee),consumers:0,settled:!1};y=z,wo.set(Ee,z);let b=()=>{z.settled=!0,hi(Ee,z)};z.promise.then(b,b)}y.consumers+=1;let o=!1,f=()=>{o||(o=!0,y.consumers-=1,hi(Ee,y))};q?.(f);try{let z=await y.promise;Kt.current=Ee,M&&(Mt(at),Zt(V=>ja(V,M)));let{sid:b,result:H,claimed:Ne}=z;if(fe(H),H.data.session&&rt(H.data.session),b&&yt(b),Ne){let V=Bt.current+=1;At(!0),Ne.then(Ce=>{Bt.current===V&&(fe(Ce),Ce.data.session&&rt(Ce.data.session),At(!1))},Ce=>{Bt.current===V&&(At(!1),T(Ce instanceof we.FloPayError?Ce:new we.FloPayError(Ce instanceof Error?Ce.message:"Failed to create session","api_error")))})}else Bt.current+=1,At(!1);let{publishableKey:tt,paypalPublishableKey:re}=bo(H),{flopay:K,paypalFlopay:m}=await vo({publishableKey:tt,paypalPublishableKey:re,billingApiUrl:w,locale:u,telemetry:r});return pt.current=K,Me(K),L.current=m,mt(m),Qe(!1),z}catch(z){throw Kt.current===Ee&&(Kt.current=null),z}finally{q||f()}},[u,w,r,ct]),Cn=(0,D.useRef)(cn);Cn.current=cn;let Wn=(0,D.useRef)(ft);Wn.current=ft;let $t=(0,D.useCallback)(async M=>{if(!js(M)||wt)return{sessionId:He,session:ne};en(!0);try{let q=await ft(M);return{sessionId:q.sid,session:q.result.data.session??null}}finally{en(!1)}},[ft,wt,He,ne]);(0,D.useEffect)(()=>{let M=!1,q;if(T(null),Nt){let Ee=Be.current;return Xe(ht),Qe(!1),Kt.current===Nt?()=>{M=!0}:(rt(Ha(Ee,xe)),(async()=>{let y=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),o=ht==="auto"&&!lt.current&&!y;o&&(Ke(null),st(null),et("processing"));try{let f=await Wn.current(void 0,Ne=>{q=Ne}),z=f.result.data.session??null;Oe.current=bo(f.result);let b=ta(f.result),H=Ho(f.sid||z?.id);if(!M&&o&&z&&!b&&!H){lt.current=!0,await Ls(Nt,f.sdkGeneratedIdempotencyKey,()=>Cn.current(z,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:f.result.autoProcessingError,initialAutoProcessingPending:f.result.autoProcessingPending,autoProcessingAttempted:f.result.autoProcessingAttempted,sessionId:f.sid||z.id}));return}!M&&o&&((b||H)&&(lt.current=!0),et(null),st(null))}catch(f){if(M)return;let z=f instanceof we.FloPayError||typeof f=="object"&&f!==null&&"code"in f?f.code:void 0;if(o&&z==="session_auto_completed"){lt.current=!0,et("success"),await $r(yn),M||(Ge(()=>{Ye.current?.({status:"succeeded"})}),et(null),st(null));return}o&&(et(null),st(null));let b=f instanceof we.FloPayError?f:new we.FloPayError(f instanceof Error?f.message:"Failed to create session","api_error");T(b)}finally{q?.(),q=void 0}})(),()=>{M=!0,q?.()})}Qe(!0);async function F(){let Ee=!1;try{let o=await new nr.PaymentAPI(w,{telemetry:!1}).getUnifiedCheckoutSession(qe,t);if(M)return;fe(o);let f=o.data.session??null;if(rt(f),!f)throw new we.FloPayError("No session data returned","api_error");let z=f.checkoutMode;if(z==="setup")throw new we.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(f.status==="authorized"){Qe(!1),Ge(()=>{Ye.current?.(Zn(f,qe)),On.current?.(f.successUrl??"")});return}if(f.status==="complete"){Qe(!1),Ge(()=>{On.current?.(f.successUrl??"")});return}if(f.status==="expired")throw so(f);Ee=!0;let b=xe??z??"full";Xe(b);let H=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ne=ta(o);if(b==="auto"&&!lt.current&&!H&&!Ne){lt.current=!0;let tt=Re(o);try{if(await Cn.current(f,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>tt,sessionId:qe||f.id}),M)return;await tt,M||Qe(!1);return}catch{if(M)return;await tt,M||Qe(!1);return}}await Re(o),M||Qe(!1)}catch(y){if(M)return;y instanceof we.FloPayError?!Ee&&!zs(y)&&ea(w,r,ct,"NETWORK_REQUEST_FAILED","session_read"):ea(w,r,ct,"INTERNAL_SDK_ERROR","checkout_mount");let o=y instanceof we.FloPayError?y:new we.FloPayError(y instanceof Error?y.message:"Failed to initialize checkout","api_error");T(o),Qe(!1)}}async function Re(Ee){let{publishableKey:y,paypalPublishableKey:o}=bo(Ee);Oe.current={publishableKey:y,paypalPublishableKey:o};let{flopay:f,paypalFlopay:z}=await vo({publishableKey:y,paypalPublishableKey:o,billingApiUrl:w,locale:u,telemetry:r});pt.current=f,Me(f),L.current=z,mt(z)}return F(),()=>{M=!0}},[xe,Nt,ht,Je,Ge,t]);let qt=(0,D.useCallback)(async()=>{if(!(Ae||!ne)){Ct(!0),Ke(null);try{await cn(ne,{attempt3DS:!0,fallbackToFull:!0,sessionId:qe||ne.id})}finally{Ct(!1)}}},[qe,Ae,cn,ne]),Lt=oa(B),Nn=ta(B),Un=(0,D.useMemo)(()=>{if(!B||!ne||!B.data.stripe?.publishableKey)return;let M={appearance:je,paymentMethodCreation:"manual",billingApiUrl:w};if(B.data.stripe?.clientSecret)M.clientSecret=B.data.stripe.clientSecret;else{let q=(0,we.buildCheckoutDisplayData)(ne).total;M.amount=Math.round(q*100)||ne.amount,M.currency=ne.currency?.toLowerCase()}return M},[B,ne,je,w]),rn=!!(n&&!X&&R==="buttons"&&me&&ht==="full"),Wt=(0,D.useMemo)(()=>({session:ne,loading:Xt,error:Qt,checkoutMode:ke,inlineSessionDraft:It,applyInlineSessionPatch:rn?$t:void 0,inlineSessionPatchProcessing:wt,claimPending:tn}),[ne,Xt,Qt,ke,It,rn,$t,wt,tn]),on=!!n&&R==="buttons"&&!Nn&&(!te||!Un),Ve=ot?(0,k.jsx)(sn,{status:ot,errorMessage:In,authorized:jn}):null;if(Xt){if(d)return(0,k.jsxs)(k.Fragment,{children:[d,Ve]});if(R==="buttons"){let M=de?.buttonsLayout?.cardButton?.borderRadius??de?.appearance.variables?.borderRadius??8,q=F=>(0,k.jsx)("div",{style:{height:F,borderRadius:M,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,k.jsxs)(k.Fragment,{children:[(0,k.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[p&&q(vr),P&&(x||g)&&q(vr),P&&q(vr),(0,k.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ve]})}return(0,k.jsxs)(k.Fragment,{children:[(0,k.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,k.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,k.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ve]})}return Qt?v?(0,k.jsx)(pn.Provider,{value:Wt,children:v(Qt)}):(0,k.jsx)(pn.Provider,{value:Wt,children:(0,k.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Qt.message})}):on?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(pn.Provider,{value:Wt,children:(0,k.jsx)(Ks,{onButtonClick:G,showPayPal:p,showStripe:P,showApplePay:x,showGooglePay:g,theme:pe,buttonsTheme:oe,buttonsStyles:O,cardButtonContent:ee,cardBackButtonContent:Q,cardTitleContent:le})}),Ve]}):Nn&&ne&&Lt?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(pn.Provider,{value:Wt,children:(0,k.jsxs)("div",{className:ge,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[We&&(0,k.jsx)(pr,{icon:!1,children:We}),St==="retrying"&&(0,k.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),St==="exhausted"&&(0,k.jsxs)("div",{role:"alert",children:[(0,k.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,k.jsx)("button",{type:"button",onClick:Tn,children:"Retry PayPal"})]}),St!=="exhausted"&&(0,k.jsx)("div",{"aria-hidden":St==="retrying"?!0:void 0,style:St==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,k.jsx)(ei,{sessionId:qe,nonce:ne.clientSecret||void 0,billingApiUrl:w,email:ne.customer?.email,clientId:Lt.clientId,environment:Lt.environment,currency:(ne.currency??"usd").toUpperCase(),isSubscription:ne.mode==="subscription",onComplete:A,onErrorChange:Ke,onDecline:E,onButtonClick:G,onInitializationStateChange:Kn,allowAutomaticRetry:Hn===0,session:ne,telemetry:r,telemetryContext:ct,debug:ye},`paypal-init-${Hn}`)})]})}),Ve]}):!te||!Un?(0,k.jsx)(k.Fragment,{children:Ve}):ke==="confirm"?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(pn.Provider,{value:Wt,children:(0,k.jsx)(Ar,{flopay:te,paypalFlopay:Ze,options:Un,children:(0,k.jsxs)("div",{className:ge,children:[We&&(0,k.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:We}),ie?ie({onConfirm:qt,isProcessing:Ae}):(0,k.jsx)("button",{type:"button",onClick:qt,disabled:Ae,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Ae?"not-allowed":"pointer",opacity:Ae?.6:1},children:Ae?"Processing...":ve??"Confirm Purchase"})]})})}),Ve]}):(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(pn.Provider,{value:Wt,children:(0,k.jsx)(Ar,{flopay:te,paypalFlopay:Ze,options:Un,children:X?(0,k.jsxs)(k.Fragment,{children:[We&&(0,k.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,k.jsx)(Hs,{sessionId:qe,nonce:ne?.clientSecret||void 0,billingApiUrl:w,session:ne,children:X})]}):(0,k.jsx)(go,{sessionId:qe,nonce:ne?.clientSecret||void 0,email:ne?.customer?.email,userId:ne?.customer?.id,firstName:ne?.customer?.firstName,lastName:ne?.customer?.lastName,totalAmount:ne?Math.round((0,we.buildCheckoutDisplayData)(ne).total*100):0,currency:ne?.currency?.toLowerCase()??"usd",onComplete:A,onError:h,onDecline:E,error:We,onErrorChange:Ke,showPayPal:p,showStripe:P,enabledPaymentMethods:I??B?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:B?.data.stripe?.enabledPaymentMethodCountries,showApplePay:x,showGooglePay:g,layout:R,theme:pe,buttonsTheme:oe,buttonsStyles:O,appearance:je,cardButtonContent:ee,cardBackButtonContent:Q,cardTitleContent:le,onButtonClick:G,onBeforeButtonClick:me,enableAVS:_e,...be?{cardFieldOrder:be}:{},...ce?{cardPreFormSlot:ce}:{},avsLayout:ae,country:ne?.customer?.country,city:ne?.customer?.city,state:ne?.customer?.state,onCountryChange:S,onZipChange:_,avsCheck:!!_e,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:X?"custom_layout":R==="buttons"?"buttons_layout":"default_layout",className:ge,directPaypal:oa(B),isSubscription:ne?.mode==="subscription",session:ne,dataAttachmentPending:tn,debug:ye})})}),Ve]})}function Hs({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:r}){return(0,k.jsx)(k.Fragment,{children:D.default.Children.map(r,s=>{if(!D.default.isValidElement(s))return s;let u=s.props,d={};return u.sessionId||(d.sessionId=e),!u.nonce&&t&&(d.nonce=t),u.billingApiUrl||(d.billingApiUrl=n),i?.customer&&(u.email||(d.email=i.customer.email),u.userId||(d.userId=i.customer.id),u.firstName||(d.firstName=i.customer.firstName),u.lastName||(d.lastName=i.customer.lastName)),Object.keys(d).length===0?s:D.default.cloneElement(s,d)})})}function Ks({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:i,showGooglePay:r,theme:s,buttonsTheme:u,buttonsStyles:d,cardButtonContent:v,cardBackButtonContent:A,cardTitleContent:h}){let[E,S]=(0,D.useState)(!1),_=(0,D.useMemo)(()=>(0,we.resolveTheme)(s),[s]),p=(0,D.useMemo)(()=>{let g=_?.buttonsLayout??(0,we.resolveButtonsLayoutTheme)(u);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},[_,u,d]),P=_?.buttonsLayout?.cardButton?.borderRadius??_?.appearance.variables?.borderRadius??8,I=g=>(0,k.jsx)("div",{style:{height:g,borderRadius:P,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),x=v===void 0?{boxSizing:"border-box",height:vr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(E){let g=p.cardInputBorder??"#e5e7eb",ye=p.cardInputBackground??"white",R=sr(A),pe=sr(h);return(0,k.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,k.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,k.jsxs)("button",{type:"button",onClick:()=>S(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:R?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,k.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...p.backButtonIcon},children:(0,k.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,k.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,k.jsx)(cr,{content:A})]}),pe?(0,k.jsx)("div",{style:{flex:1}}):(0,k.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...p.title},children:(0,k.jsx)(Br,{content:h})})]}),(0,k.jsx)("div",{style:{backgroundColor:ye,border:`1px solid ${g}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,k.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,k.jsxs)("div",{style:{display:"flex"},children:[(0,k.jsx)("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,k.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,k.jsx)("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:`1px solid ${g}`,borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,k.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,k.jsx)("div",{style:{backgroundColor:ye,border:`1px solid ${g}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,k.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,k.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,k.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,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});
|
|
47
|
+
`})]})}return(0,k.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&I(vr),n&&(i||r)&&I(vr),n&&(0,k.jsx)("button",{type:"button",onClick:()=>{e?.("card"),S(!0)},style:{width:"100%",...x,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,k.jsx)(lr,{content:v})}),(0,k.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Ai=require("@flopay/shared");var rr=require("react");var ki=require("react/jsx-runtime");function Ci(e,t){function n({className:i,id:r,style:s,options:u,onChange:d,onReady:v,onFocus:A,onBlur:h,onEscape:E}){let S=(0,rr.useRef)(null),_=(0,rr.useRef)(null),{elements:p,reportInteractive:P}=(0,rr.useContext)(Mn);return(0,rr.useEffect)(()=>{if(!p||!S.current)return;let I=!0;return(async()=>{let x=p.getElement(e);x||(x=await p.create(e,u)),!(!I||!S.current)&&(x.mount(S.current),_.current=x,d&&x.on("change",d),x.on("ready",()=>{P?.(),v?.()}),A&&x.on("focus",A),h&&x.on("blur",h),E&&x.on("escape",E))})(),()=>{if(I=!1,_.current){try{_.current.unmount()}catch{}_.current=null}}},[p,P]),(0,ki.jsx)("div",{ref:S,className:i,id:r,style:s})}return n.displayName=t,n}var Si=Ci("payment","PaymentElement"),wi=Ci("address","AddressElement");var it=require("react"),Ro=require("@flopay/js"),Gt=require("@flopay/shared");var En=require("react/jsx-runtime"),Vr=class extends Gt.FloPayError{constructor(t,n,i){super(t,n,i),this.name="FloPayCardSetupError",this.retryable=i.retryable}};function Ri(e,t={}){let n=e instanceof Gt.FloPayError?e:void 0,i=n?.statusCode,r=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof i=="number"&&i>=500||n?.code==="vault_capture_timeout"||!n);return new Vr(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:r,...n?.param?{param:n.param}:{},...i!==void 0?{statusCode:i}:{}})}function Ei({sessionId:e,nonce:t,billingApiUrl:n,telemetry:i,theme:r="modern-light",containerStyle:s,loading:u=null,onReady:d,onComplete:v,onDecline:A,onCancel:h,onValidation:E,onError:S}){let[_,p]=(0,it.useState)(null),[P,I]=(0,it.useState)(null),[x,g]=(0,it.useState)(null),[ye,R]=(0,it.useState)(null),[pe,oe]=(0,it.useState)(null),O=(0,it.useRef)(!1),ee=(0,it.useRef)(!1),Q=(0,it.useMemo)(()=>{if(typeof r=="object")return r;let Z=(0,Gt.resolveTheme)(r);if(Z)return ro({appearance:Z.appearance,buttonsStyles:Z.buttonsLayout,layout:"default"})},[r]),le=(0,it.useRef)(d),j=(0,it.useRef)(S),G=(0,it.useRef)(v),me=(0,it.useRef)(A),_e=(0,it.useRef)(h),be=(0,it.useRef)(E),ce=(0,it.useRef)(!1),ae=(0,it.useRef)(!1),ge=(0,it.useRef)(0);return le.current=d,j.current=S,G.current=v,me.current=A,_e.current=h,be.current=E,(0,it.useEffect)(()=>{let Z=ge.current+1;return ge.current=Z,()=>{queueMicrotask(()=>{ge.current===Z&&(ce.current||ae.current||(ae.current=!0,Ge(()=>{_e.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,it.useEffect)(()=>{let Z=!0,X=new Ro.PaymentAPI((0,Gt.resolveBillingApiUrl)(n),{telemetry:i});return p(null),I(null),g(null),ce.current=!1,ae.current=!1,(async()=>{try{if(!e.trim())throw new Gt.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Gt.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let xe=await X.getUnifiedCheckoutSession(e,t);if(!Z)return;let ve=xe.data.session;if(!ve||!(0,Gt.isCardSetupCheckoutSession)(ve))throw new Gt.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let ie=ve.vault;if(ie?.html?.trim()||(ie=await X.getVaultCapture(e,t)),!ie.html?.trim())throw new Gt.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!Z)return;I(ie),p(new Ro.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:i}))}catch(xe){if(!Z)return;let ve=Ri(xe);ce.current=!0,g(ve),Ge(()=>j.current?.(ve))}})(),()=>{Z=!1,X.destroy()}},[n,t,e,i]),(0,it.useEffect)(()=>{if(!_)return;let Z=!1;ee.current=!1,O.current=!1;let X=_.on("submitting",()=>{O.current=!0,oe(null),R("processing")}),xe=_.on("complete",ie=>{ce.current=!0,O.current=!1,R("success"),(async()=>(await new Promise(W=>setTimeout(W,yn)),!ee.current&&(ee.current=!0,Ge(()=>{G.current?.({status:"succeeded",sessionId:e,...ie.paymentMethod?{paymentMethod:ie.paymentMethod}:{}})}),Z||R(null))))()}),ve=_.on("decline",ie=>{ce.current=!0,O.current=!1,oe(ie.message??null),R("error"),Ge(()=>{me.current?.({status:"declined",sessionId:e,...ie.declineReason?{reason:ie.declineReason}:{},...ie.message?{message:ie.message}:{}})}),(async()=>(await new Promise(W=>setTimeout(W,Yt)),Z||R(null)))()});return()=>{Z=!0,X(),xe(),ve()}},[_,e]),x?(0,En.jsx)("div",{role:"alert",children:x.message}):!_||!P?.html?(0,En.jsx)(En.Fragment,{children:u}):(0,En.jsxs)(En.Fragment,{children:[ye&&(0,En.jsx)(sn,{status:ye,errorMessage:pe,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,En.jsx)(ur,{capture:_,html:P.html,messageToken:P.messageToken,expectedOrigin:P.expectedOrigin,theme:Q,containerStyle:s,onReady:()=>{Ge(()=>le.current?.())},onValidation:Z=>{Ge(()=>be.current?.(Z))},onError:Z=>{if(!Z)return;O.current&&(O.current=!1,oe(Z),R("error"),setTimeout(()=>R(null),Yt));let X=Ri(new Error(Z),{code:"card_setup_widget_failed",retryable:!0});Ge(()=>j.current?.(X))}})]})}var Ii=require("@flopay/js"),_i=require("@flopay/shared"),Pn=require("react");var hn=require("react/jsx-runtime");function xi({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,firstName:s,lastName:u,chv:d,onTokenizedBody:v,onComplete:A,onErrorChange:h,isProcessing:E=!1}){let S=mn(),_=ao(),p=io(),[P,I]=(0,Pn.useState)(!1),[x,g]=(0,Pn.useState)(!1),ye=(0,Pn.useRef)(!1),R=(n||p).replace(/\/+$/,""),pe=(0,Pn.useCallback)(async ee=>{try{let le=await new Ii.PaymentAPI(R).processPayment(r??"",{sessionId:e,nonce:t,tokenizedData:ee,accountData:{userId:r??"",email:i??"",firstName:s??"",lastName:u??""},chv:d});if(le.ok){A?.();return}let j=await le.json().catch(()=>null);h?.(j?.message??"Payment failed. Please try again.")}catch(Q){h?.(Q instanceof Error?Q.message:"An unexpected error occurred")}},[R,e,t,r,i,s,u,d,A,h]),oe=(0,Pn.useCallback)(ee=>{v?v(ee):pe(ee)},[v,pe]);(0,Pn.useEffect)(()=>{if(!S||ye.current)return;let ee=new URLSearchParams(window.location.search),Q=ee.get("payment_intent"),le=ee.get("payment_intent_client_secret"),j=ee.get("redirect_status");!Q||!le||(ye.current=!0,(async()=>{try{if(g(!0),j==="failed"){h?.("PayPal payment was declined. Please try again.");return}let G=S.getRawProvider();if(!G?.retrievePaymentIntent){h?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:me,error:_e}=await G.retrievePaymentIntent(le);if(_e){h?.(_e.message??"Failed to retrieve PayPal payment status.");return}if(me&&(me.status==="requires_capture"||me.status==="succeeded")){let be=typeof me.payment_method=="string"?me.payment_method:me.payment_method?.id;oe({id:be??me.id,type:"card",threeDSecureActionResultTokenId:me.id,isPaypal:!0});let ce=new URL(window.location.href);ce.searchParams.delete("payment_intent"),ce.searchParams.delete("payment_intent_client_secret"),ce.searchParams.delete("redirect_status"),window.history.replaceState({},"",ce.toString())}else h?.("PayPal payment was not completed. Please try again.")}catch(G){h?.(G instanceof Error?G.message:"Failed to complete PayPal payment.")}finally{g(!1)}})())},[S,oe,h]);let O=(0,Pn.useCallback)(async()=>{if(!(!S||!_))try{if(g(!0),h?.(null),!e||!i)throw new _i.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let ee=await S.confirmPayPalPayment({billingApiUrl:R,sessionId:e,nonce:t,email:i,returnUrl:window.location.href});if(ee.error){h?.(ee.error.message);return}ee.paymentIntentId&&(ee.status==="succeeded"||ee.status==="processing"||ee.status==="requires_capture")&&oe({id:ee.paymentMethodId??ee.paymentIntentId,type:"card",threeDSecureActionResultTokenId:ee.paymentIntentId,isPaypal:!0})}catch(ee){h?.(ee instanceof Error?ee.message:"PayPal payment failed. Please try again.")}finally{g(!1)}},[S,_,e,t,i,R,oe,h]);return!S||!_?(0,hn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,hn.jsxs)(hn.Fragment,{children:[!P&&(0,hn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,hn.jsx)("div",{style:P?{}:{display:"none"},children:(0,hn.jsx)("button",{type:"button",onClick:O,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,hn.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,hn.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 ze=require("react"),Eo=require("@flopay/js"),Jt=require("@flopay/shared");var bn=require("react/jsx-runtime"),Ws=44;function Ti(e){return new Promise(t=>setTimeout(t,e))}function Ys(e,t){return e instanceof Jt.FloPayError?e:new Jt.FloPayError(e instanceof Error?e.message:t,"api_error")}function Gs(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Js(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 Mi({sessionId:e,nonce:t,createSession:n,paymentMethodId:i,checkoutMethod:r,clientId:s,products:u,items:d,subscriptions:v,account:A,successUrl:h,cancelUrl:E,couponCodes:S,tagsData:_,utmMetadata:p,billingApiUrl:P,locale:I,theme:x,appearance:g,buttonsTheme:ye,buttonsStyles:R,onSuccess:pe,onError:oe,onDecline:O,children:ee,disabled:Q=!1,type:le="button",style:j,...G}){let me=(0,ze.useMemo)(()=>(0,Jt.resolveBillingApiUrl)(P),[P]),_e=(0,ze.useMemo)(()=>Js({createSession:n,clientId:s,products:u,items:d,subscriptions:v,account:A,successUrl:h,cancelUrl:E,couponCodes:S,tagsData:_,utmMetadata:p}),[A,E,s,S,n,u,d,v,h,_,p]),[be,ce]=(0,ze.useState)(!1),[ae,ge]=(0,ze.useState)(null),[Z,X]=(0,ze.useState)(null),[xe,ve]=(0,ze.useState)(!1),[ie,W]=(0,ze.useState)(null),w=(0,ze.useRef)(!0),de=(0,ze.useRef)(null),je=(0,ze.useRef)(ie),$e=(0,ze.useRef)(pe),he=(0,ze.useRef)(oe),B=(0,ze.useRef)(O);(0,ze.useEffect)(()=>{je.current=ie},[ie]),(0,ze.useEffect)(()=>{$e.current=pe},[pe]),(0,ze.useEffect)(()=>{he.current=oe},[oe]),(0,ze.useEffect)(()=>{B.current=O},[O]),(0,ze.useEffect)(()=>(w.current=!0,()=>{w.current=!1,de.current?.abort()}),[]),(0,ze.useEffect)(()=>{if(typeof window>"u")return;let T=ke=>{ke.key==="Escape"&&W(null)};return window.addEventListener("keydown",T),()=>{window.removeEventListener("keydown",T)}},[]);let fe=(0,ze.useCallback)((T,ke=Ur)=>{B.current?.(Et(ke,T,{code:T.code,declineCode:T.declineCode}))},[]),te=(0,ze.useCallback)(async T=>{w.current&&(X(null),ve(T.result.status==="authorized"),ge("success"),await Ti(yn),w.current&&$e.current?.(T))},[]),Me=(0,ze.useCallback)(async(T,ke)=>{w.current&&(he.current?.(T),ke?.emitDecline&&fe(T,ke.method),X(T.message),ve(!1),ge("error"),await Ti(Yt))},[fe]),pt=(0,ze.useCallback)(async(T,ke,Xe)=>{let Ae=T.data.session??null;if(!Ae)throw new Jt.FloPayError("No session data returned","api_error");let Ct=Ae.clientSecret||t;if(fr(Ae)){await te({result:Zn(Ae,ke),session:Ae,sessionId:Ae.id||ke,autoCompleted:!1});return}if(Ae.status==="expired")throw so(Ae);try{if(T.autoProcessingPending){let et=(await new Eo.PaymentAPI(me).waitForCheckoutSessionCompletion(T.autoProcessingPending.sessionId,{initialDelayMs:T.autoProcessingPending.retryAfterMs})).data.session;if(!fr(et))throw lo(et);await te({result:Zn(et,ke),session:et,sessionId:et.id||ke,autoCompleted:!1});return}if(T.autoProcessingError){if(T.autoProcessingError.type==="3ds_required"&&T.autoProcessingError.nextActionRedirectUrl&&ke&&Ct){let Ke=new AbortController;de.current=Ke;let ot;try{ot=await fi({billingApiUrl:me,sessionId:ke,nonce:Ct,nextActionRedirectUrl:T.autoProcessingError.nextActionRedirectUrl,signal:Ke.signal})}finally{de.current===Ke&&(de.current=null)}if(ot.status==="declined")throw Vn({type:ot.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:ot.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:T.autoProcessingError.checkoutMethod});let st=(await new Eo.PaymentAPI(me).waitForCheckoutSessionCompletion(ke,{initialDelayMs:0,nonce:Ct})).data.session;if(!fr(st))throw Vn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:T.autoProcessingError.checkoutMethod});await te({result:Zn(st,ke),session:st,sessionId:st.id||ke,autoCompleted:!1});return}throw Vn(T.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:T.autoProcessingError.checkoutMethod})}if(Xe?.fromCreateSession&&T.autoProcessingAttempted===!0)throw Vn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let We=await br({billingApiUrl:me,sessionId:ke??Ae.id,session:Ae,nonce:Ct});if(We.type!=="success")throw Vn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await te({result:We.result,session:Ae,sessionId:Ae.id||ke,autoCompleted:!1})}catch(We){let Ke=tr(We),ot=Ae.id||ke;await Me(Ke,{emitDecline:!0,method:Ke.checkoutMethod??Ur}),Gs(Ke,ot)&&ot&&w.current&&W({sessionId:ot,errorMessage:Ke.message,nonce:Ct||void 0})}},[t,me,Me,te]),Ze=(0,ze.useCallback)(async T=>{if(G.onClick?.(T),!(T.defaultPrevented||Q||be)){if(W(null),e&&_e){let ke=new Jt.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Me(ke),w.current&&(ge(null),X(null));return}if(!e&&!_e){let ke=new Jt.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Me(ke),w.current&&(ge(null),X(null));return}ce(!0),X(null),ve(!1),ge("processing");try{let ke=new Eo.PaymentAPI(me);if(e){let Xe=await ke.getUnifiedCheckoutSession(e,t);await pt(Xe,e);return}try{let Xe=await ke.createAndFetchSession({..._e});await pt(Xe,Xe.data.session?.id??null,{fromCreateSession:!0})}catch(Xe){if(Xe instanceof Jt.FloPayError&&Xe.code==="session_auto_completed"){await te({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Xe}}catch(ke){await Me(Ys(ke,"Automatic payment failed. Please try again."))}finally{w.current&&(ge(null),X(null),ce(!1))}}},[G,_e,Q,be,t,pt,me,e,Me,te]),mt=(0,ze.useCallback)(T=>{let ke=je.current;W(null),$e.current?.({result:T,session:null,sessionId:ke?.sessionId??null,autoCompleted:!1})},[]),L=(0,ze.useCallback)(T=>{he.current?.(T)},[]),ne=(0,ze.useCallback)(T=>{B.current?.(T)},[]),rt=(0,ze.useMemo)(()=>(0,Jt.resolveTheme)(x),[x]),He=(0,ze.useMemo)(()=>{let T=rt?.buttonsLayout??(0,Jt.resolveButtonsLayoutTheme)(ye);return R?{...T,...R,cardButton:{...T.cardButton,...R.cardButton}}:T},[rt,ye,R]),yt=(0,ze.useMemo)(()=>{let T=rt?.appearance;return g?T?{...T,...g,variables:{...T.variables,...g.variables}}:g:T},[g,rt]),qe=yt?.variables,Je=qe?.colorPrimary??"#4A49FF",Xt=qe?.colorPrimaryHover??dr(Je,.12),Qe=qe?.borderRadius??"8px";return(0,bn.jsxs)(bn.Fragment,{children:[(0,bn.jsx)("button",{...G,type:le,onClick:Ze,disabled:Q||be,"aria-busy":be,style:{width:"100%",...ee===void 0?{boxSizing:"border-box",height:Ws,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...He.cardButton,...Xo({themeBundle:rt,resolvedPrimaryColor:Je,resolvedBorderRadius:Qe,submitButtonStyle:He.submitButton,explicitPrimaryColor:qe?.colorPrimary}),fontSize:He.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Q||be?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Q||be?.6:1,...j},onMouseEnter:T=>{G.onMouseEnter?.(T),!T.defaultPrevented&&!Q&&!be&&(rt||qe?.colorPrimary)&&(T.currentTarget.style.backgroundColor=Xt)},onMouseLeave:T=>{G.onMouseLeave?.(T),!T.defaultPrevented&&(rt||qe?.colorPrimary)&&(T.currentTarget.style.backgroundColor=Je)},onMouseDown:T=>{G.onMouseDown?.(T),T.defaultPrevented||(T.currentTarget.style.transform="scale(0.985)")},onMouseUp:T=>{G.onMouseUp?.(T),T.defaultPrevented||(T.currentTarget.style.transform="scale(1)")},children:(0,bn.jsx)(lr,{content:ee})}),ae&&(0,bn.jsx)(sn,{status:ae,errorMessage:Z,authorized:xe}),ie&&(0,bn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:T=>{T.target===T.currentTarget&&W(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,bn.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,bn.jsx)(ko,{sessionId:ie.sessionId,nonce:ie.nonce,checkoutMode:"full",billingApiUrl:me,locale:I,theme:x,...yt?{appearance:yt}:{},buttonsTheme:ye,buttonsStyles:R,initialErrorMessage:ie.errorMessage,cardTitleContent:null,onComplete:mt,onError:L,onDecline:ne})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useElements,useFloPay,usePayPalFloPay});
|