@flopay/react 1.4.22 → 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/dist/index.mjs CHANGED
@@ -1,12 +1,12 @@
1
- import{useCallback as Ms,useEffect as $r,useState as Jo,useMemo as As,useRef as Xo}from"react";import{resolveBillingApiUrl as Bs}from"@flopay/shared";import{createContext as li}from"react";var xn=li({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),pn=li({session:null,loading:!1,error:null});var Is=Symbol.for("@flopay/js.telemetry.bridge.v1"),_s=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function xs(){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 Ts(e){let t=xs(),n=(r,s)=>r?r.bind(e):s,a=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:a,elapsed:e.elapsed?e.elapsed.bind(e):r=>Math.max(0,a()-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 yo(e){let t=globalThis[_s];return Ts(t?.(e)??{})}function At(e){if(e)return e[Is]}import{jsx as Fs}from"react/jsx-runtime";function fo({flopay:e,paypalFlopay:t,options:n,children:a}){let[r,s]=Jo(e instanceof Promise?null:e),[c,l]=Jo(t instanceof Promise||!t?null:t),[b,x]=Jo(null),g=Xo(null),S=Xo(null),v=Xo(null);$r(()=>{if(!r)return;let w=At(r);return g.current=w?.beginCheckout()??w?.now()??0,w?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{w?.log({name:"checkout.unmount",stage:"unmount"})}},[r]),$r(()=>{let w=!1;return e instanceof Promise?e.then(R=>{w||s(R)}):s(e),()=>{w=!0}},[e]),$r(()=>{let w=!1;if(!t){l(null);return}return t instanceof Promise?t.then(R=>{w||l(R)}):l(t),()=>{w=!0}},[t]),$r(()=>{if(!r){x(null);return}let w=r.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return x(w),()=>{w.destroy()}},[r,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),$r(()=>{if(!r||!b||S.current===b)return;S.current=b;let w=At(r);w?.log({name:"checkout.rendered",stage:"checkout_render"}),w?.performance({stage:"checkout_render",durationMs:w.elapsed(g.current??0),durationMode:"machine"})},[b,r]);let k=Ms(()=>{if(!r||!b||v.current===b)return;v.current=b;let w=At(r);w?.log({name:"checkout.interactive",stage:"checkout_interactive"}),w?.performance({stage:"checkout_interactive",durationMs:w.elapsed(g.current??0),durationMode:"machine"})},[b,r]),d=Bs(n?.billingApiUrl),h=As(()=>({flopay:r,paypalFlopay:c,elements:b,billingApiUrl:d,reportInteractive:k}),[r,c,b,d,k]);return Fs(xn.Provider,{value:h,children:a})}import ba,{useCallback as ar,useEffect as Bn,useMemo as mn,useRef as Nt,useState as Ct}from"react";import{PaymentAPI as Mo,SESSION_CREATE_TELEMETRY as Ol}from"@flopay/js";import{SDK_VERSION as ns,FloPayError as It,classifyTelemetryFailure as Gi,isDetachedSessionEligible as Nl,resolveBillingApiUrl as Ul,buildCheckoutDisplayData as Ji,resolveButtonsLayoutTheme as $l,resolveIdempotencyKey as Xi,resolveTheme as rs,telemetryStatusClass as ql}from"@flopay/shared";import"react";import{Fragment as pr,jsx as an,jsxs as ci}from"react/jsx-runtime";function Ds(){return ci(pr,{children:[ci("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:[an("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),an("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",an("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:an("path",{d:"M9 18l6-6-6-6"})})]})}function Ls(){return an(pr,{children:"Go back"})}function zs(){return an(pr,{children:"Secure card checkout"})}function cr(e){return e!==void 0&&(e===""||e===null||e===!1)}function dr({content:e}){return an(pr,{children:e===void 0?an(Ds,{}):e})}function ur({content:e}){return an(pr,{children:e===void 0?an(Ls,{}):e})}function qr({content:e}){return an(pr,{children:e===void 0?an(zs,{}):e})}import{ExpressCheckoutElement as zi,PaymentElement as el,Elements as rr,useElements as pa,useStripe as ma}from"@stripe/react-stripe-js";import{isAuthorizationOnlySession as sa,normalizeCheckoutFailureOutcome as tl,resolveButtonsLayoutTheme as nl,getPostalCodeLabel as da,getStateLabel as Ri,getStateOptions as rl,COUNTRY_OPTIONS as ol,resolveAVSConfig as al,isAVSFieldVisible as De,getStateFromPostalCode as Ei,isPostalCodeSupported as il,isValidPostalCode as sl,getPostalCodeExample as ll,filterStripeMethodsByCountry as cl,getStripeMethodDisplayName as Cr,hasVendoredStripeMethodLogo as dl,needsStripeMethodExplicitConfirm as Ii,resolveStripeMethodBrandVariant as ul,partitionStripeMethods as pl,stripeExpressMethodToOptionKey as _i}from"@flopay/shared";function mr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let a=parseInt(n[1],16),r=Math.max(0,Math.min(1,1-t)),s=Math.round((a>>16&255)*r),c=Math.round((a>>8&255)*r),l=Math.round((a&255)*r);return`#${(1<<24|s<<16|c<<8|l).toString(16).slice(1)}`}function Qo(e){if(typeof e=="number"||typeof e=="string")return e}function go({appearance:e,buttonsStyles:t,layout:n="default"}){let a=e?.variables,r=x=>typeof x=="string"&&x?x:void 0,s=t.submitButton,c=r(a?.colorPrimary)??r(s?.backgroundColor)??"#4A49FF",l=n==="buttons",b=t.nameInput;return{primaryColor:c,primaryHoverColor:r(a?.colorPrimaryHover)??mr(c,.12),inputBackgroundColor:r(t.cardInputBackground)??r(a?.colorBackground)??"#ffffff",textColor:r(t.cardInputColor)??r(b?.color)??r(a?.colorText)??"#262833",borderColor:r(t.cardInputBorder)??(l?"#e5e7eb":"#A4A4FF"),placeholderColor:r(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:r(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:r(b?.fontFamily)??r(a?.fontFamily)??"Poppins, sans-serif",fontSize:r(t.cardInputFontSize)??r(a?.fontSizeBase)??"16px",fontWeight:String(Qo(b?.fontWeight)??400),borderRadius:r(a?.borderRadius)??"8px"}}import{PaymentAPI as qn,toStripeAppearance as ml}from"@flopay/js";import{useEffect as di,useRef as Vr}from"react";import{jsx as Os}from"react/jsx-runtime";function jr({capture:e,html:t,messageToken:n,expectedOrigin:a,theme:r,containerStyle:s,onReady:c,onError:l,onValidation:b}){let x=Vr(null),g=Vr(c),S=Vr(l),v=Vr(b);g.current=c,S.current=l,v.current=b;let k=Vr(r);return k.current=r,di(()=>{let d=x.current;if(!d)return;let h=!0,w=!1,R=()=>{!h||w||(w=!0,g.current?.())},f=e.on("ready",()=>{R()}),de=e.on("error",Z=>{S.current?.(Z.message??"There was a problem loading the secure card form.")}),E=e.on("validation",Z=>{v.current?.(Z.message??null)}),re={html:t,...n?{messageToken:n}:{},...a?{expectedOrigin:a}:{},...k.current?{theme:k.current}:{}};return e.mount(d,re).then(()=>{R()}).catch(Z=>{h&&S.current?.(Z instanceof Error?Z.message:"Failed to load the secure card form.")}),()=>{h=!1,f(),de(),E(),e.unmount()}},[e,t,n,a]),di(()=>{r&&e.applyTheme?.(r)},[e,r]),Os("div",{ref:x,"data-testid":"flopay-vault-card-fields",style:s})}import"react";import{jsx as ui,jsxs as Ns}from"react/jsx-runtime";function yr({children:e,margin:t,icon:n=!0,styleOverride:a}){return Ns("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"}:{},...a??{}},children:[n&&ui("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ui("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 pi={alipay:new URL("./payment-logos/alipay.svg",import.meta.url).href,bancontact:new URL("./payment-logos/bancontact.svg",import.meta.url).href,blik:new URL("./payment-logos/blik.svg",import.meta.url).href,eps:new URL("./payment-logos/eps.svg",import.meta.url).href,giropay:new URL("./payment-logos/giropay.svg",import.meta.url).href,ideal:new URL("./payment-logos/ideal.svg",import.meta.url).href,klarna:new URL("./payment-logos/klarna.svg",import.meta.url).href,p24:new URL("./payment-logos/p24.svg",import.meta.url).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",import.meta.url).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",import.meta.url).href};import yl,{useCallback as Se,useContext as fl,useEffect as pt,useMemo as ut,useRef as Be,useState as Ce}from"react";import{useContext as Hr}from"react";import{resolveBillingApiUrl as Us}from"@flopay/shared";function bn(){return Hr(xn).flopay}function Zo(){return Hr(xn).paypalFlopay??null}function ea(){return Hr(xn).elements}function $s(){return Hr(pn)}function ho(){return Hr(xn).billingApiUrl||Us()}import"react";import{jsx as sn,jsxs as fr}from"react/jsx-runtime";var Tn=1200,vn=1500;function Cn({status:e,errorMessage:t,authorized:n=!1}){return sn("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:fr("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:[fr("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&fr("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:[sn("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),sn("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&sn("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:fr("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[sn("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),sn("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"&&sn("div",{style:{animation:"flopay-shake 0.4s ease"},children:fr("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[sn("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),sn("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"}})]})})]}),fr("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"&&sn("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&&sn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),sn("style",{children:`
1
+ import{useCallback as As,useEffect as $r,useState as Qo,useMemo as Bs,useRef as Zo}from"react";import{resolveBillingApiUrl as Fs}from"@flopay/shared";import{createContext as li}from"react";var Mn=li({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),yn=li({session:null,loading:!1,error:null});var _s=Symbol.for("@flopay/js.telemetry.bridge.v1"),xs=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ts(){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 Ms(e){let t=Ts(),n=(r,i)=>r?r.bind(e):i,a=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:a,elapsed:e.elapsed?e.elapsed.bind(e):r=>Math.max(0,a()-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 fo(e){let t=globalThis[xs];return Ms(t?.(e)??{})}function At(e){if(e)return e[_s]}import{jsx as Ds}from"react/jsx-runtime";function go({flopay:e,paypalFlopay:t,options:n,children:a}){let[r,i]=Qo(e instanceof Promise?null:e),[c,l]=Qo(t instanceof Promise||!t?null:t),[b,x]=Qo(null),g=Zo(null),w=Zo(null),v=Zo(null);$r(()=>{if(!r)return;let k=At(r);return g.current=k?.beginCheckout()??k?.now()??0,k?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{k?.log({name:"checkout.unmount",stage:"unmount"})}},[r]),$r(()=>{let k=!1;return e instanceof Promise?e.then(E=>{k||i(E)}):i(e),()=>{k=!0}},[e]),$r(()=>{let k=!1;if(!t){l(null);return}return t instanceof Promise?t.then(E=>{k||l(E)}):l(t),()=>{k=!0}},[t]),$r(()=>{if(!r){x(null);return}let k=r.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return x(k),()=>{k.destroy()}},[r,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),$r(()=>{if(!r||!b||w.current===b)return;w.current=b;let k=At(r);k?.log({name:"checkout.rendered",stage:"checkout_render"}),k?.performance({stage:"checkout_render",durationMs:k.elapsed(g.current??0),durationMode:"machine"})},[b,r]);let R=As(()=>{if(!r||!b||v.current===b)return;v.current=b;let k=At(r);k?.log({name:"checkout.interactive",stage:"checkout_interactive"}),k?.performance({stage:"checkout_interactive",durationMs:k.elapsed(g.current??0),durationMode:"machine"})},[b,r]),d=Fs(n?.billingApiUrl),h=Bs(()=>({flopay:r,paypalFlopay:c,elements:b,billingApiUrl:d,reportInteractive:R}),[r,c,b,d,R]);return Ds(Mn.Provider,{value:h,children:a})}import Ca,{useCallback as ar,useEffect as Fn,useMemo as gn,useRef as Nt,useState as Ct}from"react";import{PaymentAPI as Ao,SESSION_CREATE_TELEMETRY as Nl}from"@flopay/js";import{SDK_VERSION as ns,FloPayError as It,classifyTelemetryFailure as Gi,isDetachedSessionEligible as Ul,resolveBillingApiUrl as $l,buildCheckoutDisplayData as Ji,resolveButtonsLayoutTheme as ql,resolveIdempotencyKey as Xi,resolveTheme as rs,telemetryStatusClass as Vl}from"@flopay/shared";import"react";import{Fragment as pr,jsx as sn,jsxs as ci}from"react/jsx-runtime";function Ls(){return ci(pr,{children:[ci("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:[sn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),sn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",sn("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:sn("path",{d:"M9 18l6-6-6-6"})})]})}function zs(){return sn(pr,{children:"Go back"})}function Os(){return sn(pr,{children:"Secure card checkout"})}function cr(e){return e!==void 0&&(e===""||e===null||e===!1)}function dr({content:e}){return sn(pr,{children:e===void 0?sn(Ls,{}):e})}function ur({content:e}){return sn(pr,{children:e===void 0?sn(zs,{}):e})}function qr({content:e}){return sn(pr,{children:e===void 0?sn(Os,{}):e})}import{ExpressCheckoutElement as zi,PaymentElement as tl,Elements as rr,useElements as ya,useStripe as fa}from"@stripe/react-stripe-js";import{isAuthorizationOnlySession as ca,normalizeCheckoutFailureOutcome as nl,resolveButtonsLayoutTheme as rl,getPostalCodeLabel as pa,getStateLabel as Ri,getStateOptions as ol,COUNTRY_OPTIONS as al,resolveAVSConfig as il,isAVSFieldVisible as Le,getStateFromPostalCode as Ei,isPostalCodeSupported as sl,isValidPostalCode as ll,getPostalCodeExample as cl,filterStripeMethodsByCountry as dl,getStripeMethodDisplayName as Cr,hasVendoredStripeMethodLogo as ul,needsStripeMethodExplicitConfirm as Ii,resolveStripeMethodBrandVariant as pl,partitionStripeMethods as ml,stripeExpressMethodToOptionKey as _i}from"@flopay/shared";function mr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let a=parseInt(n[1],16),r=Math.max(0,Math.min(1,1-t)),i=Math.round((a>>16&255)*r),c=Math.round((a>>8&255)*r),l=Math.round((a&255)*r);return`#${(1<<24|i<<16|c<<8|l).toString(16).slice(1)}`}function ea(e){if(typeof e=="number"||typeof e=="string")return e}function ho({appearance:e,buttonsStyles:t,layout:n="default"}){let a=e?.variables,r=x=>typeof x=="string"&&x?x:void 0,i=t.submitButton,c=r(a?.colorPrimary)??r(i?.backgroundColor)??"#4A49FF",l=n==="buttons",b=t.nameInput;return{primaryColor:c,primaryHoverColor:r(a?.colorPrimaryHover)??mr(c,.12),inputBackgroundColor:r(t.cardInputBackground)??r(a?.colorBackground)??"#ffffff",textColor:r(t.cardInputColor)??r(b?.color)??r(a?.colorText)??"#262833",borderColor:r(t.cardInputBorder)??(l?"#e5e7eb":"#A4A4FF"),placeholderColor:r(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:r(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:r(b?.fontFamily)??r(a?.fontFamily)??"Poppins, sans-serif",fontSize:r(t.cardInputFontSize)??r(a?.fontSizeBase)??"16px",fontWeight:String(ea(b?.fontWeight)??400),borderRadius:r(a?.borderRadius)??"8px"}}import{PaymentAPI as qn,toStripeAppearance as yl}from"@flopay/js";import{useEffect as di,useRef as Vr}from"react";import{jsx as Ns}from"react/jsx-runtime";function jr({capture:e,html:t,messageToken:n,expectedOrigin:a,theme:r,containerStyle:i,onReady:c,onError:l,onValidation:b}){let x=Vr(null),g=Vr(c),w=Vr(l),v=Vr(b);g.current=c,w.current=l,v.current=b;let R=Vr(r);return R.current=r,di(()=>{let d=x.current;if(!d)return;let h=!0,k=!1,E=()=>{!h||k||(k=!0,g.current?.())},f=e.on("ready",()=>{E()}),de=e.on("error",Z=>{w.current?.(Z.message??"There was a problem loading the secure card form.")}),S=e.on("validation",Z=>{v.current?.(Z.message??null)}),le={html:t,...n?{messageToken:n}:{},...a?{expectedOrigin:a}:{},...R.current?{theme:R.current}:{}};return e.mount(d,le).then(()=>{E()}).catch(Z=>{h&&w.current?.(Z instanceof Error?Z.message:"Failed to load the secure card form.")}),()=>{h=!1,f(),de(),S(),e.unmount()}},[e,t,n,a]),di(()=>{r&&e.applyTheme?.(r)},[e,r]),Ns("div",{ref:x,"data-testid":"flopay-vault-card-fields",style:i})}import"react";import{jsx as ui,jsxs as Us}from"react/jsx-runtime";function yr({children:e,margin:t,icon:n=!0,styleOverride:a}){return Us("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"}:{},...a??{}},children:[n&&ui("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ui("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 pi={alipay:new URL("./payment-logos/alipay.svg",import.meta.url).href,bancontact:new URL("./payment-logos/bancontact.svg",import.meta.url).href,blik:new URL("./payment-logos/blik.svg",import.meta.url).href,eps:new URL("./payment-logos/eps.svg",import.meta.url).href,giropay:new URL("./payment-logos/giropay.svg",import.meta.url).href,ideal:new URL("./payment-logos/ideal.svg",import.meta.url).href,klarna:new URL("./payment-logos/klarna.svg",import.meta.url).href,p24:new URL("./payment-logos/p24.svg",import.meta.url).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",import.meta.url).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",import.meta.url).href};import fl,{useCallback as ke,useContext as gl,useEffect as pt,useMemo as ut,useRef as De,useState as we}from"react";import{useContext as Hr}from"react";import{resolveBillingApiUrl as $s}from"@flopay/shared";function wn(){return Hr(Mn).flopay}function ta(){return Hr(Mn).paypalFlopay??null}function na(){return Hr(Mn).elements}function qs(){return Hr(yn)}function Po(){return Hr(Mn).billingApiUrl||$s()}import"react";import{jsx as ln,jsxs as fr}from"react/jsx-runtime";var fn=1200,Jt=1500;function cn({status:e,errorMessage:t,authorized:n=!1,processingLabel:a="PROCESSING...",successLabel:r,errorLabel:i="PAYMENT FAILED",successNote:c="You will be automatically redirected, do not close or navigate away from this window."}){return ln("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:fr("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:[fr("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&fr("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:[ln("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),ln("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&ln("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:fr("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[ln("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),ln("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"&&ln("div",{style:{animation:"flopay-shake 0.4s ease"},children:fr("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[ln("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),ln("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"}})]})})]}),fr("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&a,e==="success"&&(r??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&c!==null&&ln("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:c}),e==="error"&&t&&ln("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),ln("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
- `})]})})}import{FloPayError as mi,isMoneySettledOutcome as qs,isSetupIntentClientSecret as vd}from"@flopay/shared";function yi(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 ta(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 fi(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}))],a=n.reduce((s,c)=>s+(c.overrideAmount??c.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(a*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,c)=>({uuid:`synthetic-${s.type??"item"}-${c}`,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 na(e,t){return t?{...e,...t}:e}function Et(e,t,n){let a=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:a,...r?{code:r}:{},...s?{declineCode:s}:{}}}var Vs=[{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:a}of Vs)if(n.test(t))return a;return e}function er(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function gr(e){return e?.status==="authorized"||e?.status==="complete"}function gi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Po(e){let t=gi(e);return new mi(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function bo(e){let t=gi(e);return new mi(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 vo(e,t){return e==="processing"||qs(e,t)}function hi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Pi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Kr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Co="flopay_recent_completion_";function hr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Co+e,JSON.stringify(t))}catch{}}function ra(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Co+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Co+e),!1):!0}catch{return!1}}function bi(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}import{useCallback as So,useEffect as ht,useMemo as Yr,useRef as et,useState as nr}from"react";import{loadScript as Hs}from"@paypal/paypal-js";import{PaymentAPI as oa}from"@flopay/js";import{FloPayError as vi,SDK_VERSION as Ks,generateIdempotencyKey as Ws,normalizeGatewayEnvironment as Ys}from"@flopay/shared";function Ke(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 js(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 tr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Mn(e){if(typeof e!="object"||e===null)return;let t=e;return tr(t.code)??tr(t.type)??tr(t.name)}function Pr(e){if(!(typeof e!="object"||e===null))return tr(e.decline_code)}function Wr(e){return typeof e!="object"||e===null?!1:tr(e.type)?.toLowerCase()==="card_error"||Pr(e)!==void 0}function $n(e){let t=js(e)?.toLowerCase()??"",a=`${Mn(e)?.toLowerCase()??""} ${t}`;return a.includes("popup")&&a.includes("block")}import{jsx as br,jsxs as aa}from"react/jsx-runtime";var wo=45,Gs=1e3,Js=11e3,Xs=["https://www.paypal.com","https://www.sandbox.paypal.com"],Ci="We couldn't open PayPal. Try again or choose another payment method.",Qs={width:"100%",minHeight:wo,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 Si(e){return e.includes("No ack for postMessage init()")&&Xs.some(t=>e.includes(t))&&e.includes("10000ms")}function Zs(e){return e?`${Ci} Allow pop-ups for this site, then try again.`:Ci}function wi({sessionId:e,nonce:t,billingApiUrl:n,email:a,clientId:r,environment:s,currency:c,isSubscription:l,onTokenizedBody:b,onComplete:x,onErrorChange:g,onDecline:S,onTechnicalFailure:v,isProcessing:k=!1,onLoadStateChange:d,onInitializationStateChange:h,allowAutomaticRetry:w=!0,onButtonClick:R,runBeforeButtonClick:f,session:de,existingOrderId:E,telemetry:re,telemetryContext:Z,debug:L=!1}){let Y=bn(),K=Yr(()=>{if(Y)return null;let F=yo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ks,enabled:re!==!1});return F.setCheckoutContext(Z??{}),F.beginCheckout(Z??{}),F},[n,Y,re,Z?.checkoutMode,Z?.layout]),te=Yr(()=>At(Y),[Y]);ht(()=>()=>{K&&K.flush().catch(()=>{}).finally(()=>K.destroy())},[K]);let U=Yr(()=>({error:F=>{te?te.error(F):K?.error(F)},log:F=>{te?te.log(F):K?.log(F)},performance:F=>{te?te.performance(F):K?.performance(F)},terminal:F=>{te?te.terminal(F):K?.terminal(F)},startTiming:()=>te?.now()??K?.now()??0,elapsed:F=>te?.elapsed(F)??Math.max(0,(K?.now()??F)-F)}),[te,K]),V=et(null),z=et(0),me=et(null),ee=et(!1),[oe,G]=nr(!1),[ge,Te]=nr(!1),[ae,Ue]=nr(0),Fe=et(0),[ke,W]=nr(!1),C=et(!1),se=et(!1),[$e,ze]=nr(!1),[ue,T]=nr(!1),ce=Yr(()=>n.replace(/\/+$/,""),[n]),J=Yr(()=>JSON.stringify([ce,r,c,s??"",l,e,E??""]),[ce,r,c,s,E,l,e]),Re=et(J),mt=Re.current!==J,[Je,yt]=nr([]),A=F=>{L&&yt(it=>[...it,`${new Date().toISOString().slice(11,23)} ${F}`])},X=et(b),tt=et(x),qe=et(g),ft=et(S),Oe=et(v),We=et(R),Jt=et(d),Ge=et(h),Xt=et(f),I=et(de),he=et(a),Ye=et(t),Ee=et(null),St=et(0),je=et(null),Ve=et(null),nt=et(new Map),Xe=et(new Map),Rn=et(!1);ht(()=>(Rn.current=!0,()=>{Rn.current=!1}),[]),ht(()=>{X.current=b},[b]),ht(()=>{tt.current=x},[x]),ht(()=>{qe.current=g},[g]),ht(()=>{ft.current=S},[S]),ht(()=>{Oe.current=v},[v]),ht(()=>{We.current=R},[R]),ht(()=>{Jt.current=d},[d]),ht(()=>{Ge.current=h},[h]),ht(()=>{Xt.current=f},[f]),ht(()=>{I.current=de},[de]),ht(()=>{he.current=a},[a]),ht(()=>{Ye.current=t},[t]),ht(()=>{Fe.current=ae},[ae]),ht(()=>{ke&&me.current?.focus()},[ke,ae]);let at=So(()=>{window.setTimeout(()=>{me.current?.focus()},0)},[]),Hn=So(()=>{G(!1),Ue(F=>F+1)},[]),Wt=So(()=>{W(!1),(V.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??V.current)?.focus?.()},[]);ht(()=>{!oe||!ee.current||(ee.current=!1,Wt())},[Wt,oe,ae]);let yn=So((F,it)=>{let Lt=Oe.current;if(Lt){Lt("paypal",F,it);return}qe.current?.(Zs(it?.popupBlocked??$n(F)))},[]),Qt=()=>{je.current?.timer&&(clearTimeout(je.current.timer),je.current.timer=null)},ir=()=>{Qt();let F=St.current+1;return St.current=F,Ve.current=null,je.current={generation:F,timer:null,yieldedControl:!1},W(!1),F},Bt=F=>F!==void 0&&je.current?.generation!==F?!1:(Qt(),je.current=null,Ve.current=null,!0),kt=F=>{let it=F?.generation??je.current?.generation??St.current;(!F?.generation||je.current?.generation===it)&&(Qt(),je.current=null),Ve.current=it,F?.showRetry&&W(!0),F?.remount&&Hn(),F?.focus!==!1&&at()},Zt=F=>je.current?.generation===F&&Ve.current!==F,en=F=>{typeof document<"u"&&document.visibilityState!=="visible"||(Qt(),F.timer=setTimeout(()=>{je.current?.generation===F.generation&&(je.current=null,Ve.current=F.generation,yn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),W(!0),Hn(),at())},600))},Ft=()=>{let F=je.current;F?.yieldedControl&&en(F)},Dt=()=>{let F=je.current;F&&(F.yieldedControl=!0,Qt())},wt=F=>{let it=Ee.current;return it&&Xe.current.set(F,it),F};ht(()=>{let F=()=>{document.visibilityState==="visible"?Ft():Dt()};return document.addEventListener("visibilitychange",F),window.addEventListener("focus",Ft),window.addEventListener("blur",Dt),()=>{document.removeEventListener("visibilitychange",F),window.removeEventListener("focus",Ft),window.removeEventListener("blur",Dt),Qt()}},[]),ht(()=>{Re.current!==J&&(Re.current=J,C.current=!1,se.current=!1,G(!1),Te(!1),ze(!1),Ge.current?.("loading"))},[J]),ht(()=>{Ke(()=>Jt.current?.(oe&&!$e))},[oe,$e]);let ne=Ys(s);ht(()=>{let F=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",it=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(A(`mount clientId=${F} env=${s??"(unset)"}\u2192${ne??"live"} ccy=${c} sub=${l}`),A(`ua=${it.slice(0,80)}${it.length>80?"\u2026":""}`),!r){A("FAIL: clientId empty \u2014 gateway misconfigured"),ze(!0),U.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!V.current){A("FAIL: containerRef not attached");return}z.current=U.startTiming(),U.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Lt=!1,Ln=!1,Me=()=>Lt||Ln,st,He=!1,En=()=>{st=Ws(),st||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),He=!0},In=null,zn=!1,Wn=null,_n=!1,rt=()=>{!Wn||_n||(_n=!0,Wn.close().catch(()=>{}))},zt=null,ln=()=>{zt!==null&&(U.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),U.performance({stage:"overlay_return",durationMs:U.elapsed(zt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),zt=null)},Pt=!1,xt=V.current,tn=null,cn=null,Yt=[],Ut=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let o=m.getBoundingClientRect();return`${Math.round(o.width)}\xD7${Math.round(o.height)}`},$t=m=>{if(!m)return"(empty)";try{let o=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),y=o.pathname.toLowerCase();return y.includes("checkcaptcha")||y.includes("captcha")?`CAPTCHA(${o.host}${y})`:y.includes("risk")||y.includes("challenge")?`RISK(${o.host}${y})`:y.includes("smart/buttons")?`smart-buttons(${o.host})`:`${o.host}${y}`.slice(0,100)}catch{return m.slice(0,80)}},Ie=m=>{let o=m.getAttribute("src"),y=m.getAttribute("srcdoc"),B=m.getAttribute("name"),P=m.getAttribute("sandbox"),$=[];return o&&$.push(`src=${$t(o)}`),y&&$.push(`srcdoc[${y.length}ch]`),!o&&!y&&$.push("src=(empty) srcdoc=(empty)"),B&&$.push(`name=${B.slice(0,40)}`),P!==null&&$.push(`sandbox="${P.slice(0,40)}"`),$.join(" ")},qt=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let o=m.contentDocument;if(!o)return"cd=null";let y=o.body?.children.length??0,B=o.body?.innerHTML.length??0,P=o.head?.innerHTML.length??0;return`cd=same-origin readyState=${o.readyState} body[${y}children,${B}ch] head[${P}ch]`}catch(o){return`cd=cross-origin(${o.message.slice(0,30)})`}},gt=[],fn=m=>{if(Me())return;let o=m.message??String(m.error??"(no message)");o&&(o.toLowerCase().includes("paypal")||o.toLowerCase().includes("zoid")||o.toLowerCase().includes("postrobot")||o.toLowerCase().includes("storage"))&&(A(`window:error ${o.slice(0,140)}`),gt.push(o))},Yn=m=>{if(Me())return;let o=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");o&&(o.toLowerCase().includes("paypal")||o.toLowerCase().includes("zoid")||o.toLowerCase().includes("postrobot")||o.toLowerCase().includes("storage"))&&(A(`window:rejection ${o.slice(0,140)}`),gt.push(o))};L&&typeof window<"u"&&(window.addEventListener("error",fn),window.addEventListener("unhandledrejection",Yn));let Vt={value:0};if(L&&typeof PerformanceObserver<"u")try{cn=new PerformanceObserver(m=>{if(!Me())for(let o of m.getEntries()){if(!o.name.toLowerCase().includes("paypal"))continue;Vt.value+=1;let y=Math.round(o.duration);A(`net ${y}ms ${o.name.slice(0,90)}`)}}),cn.observe({type:"resource",buffered:!0})}catch{}let jt=()=>{for(tn?.disconnect(),tn=null,cn?.disconnect(),cn=null;Yt.length;)clearTimeout(Yt.pop());L&&typeof window<"u"&&(window.removeEventListener("error",fn),window.removeEventListener("unhandledrejection",Yn))},Ot=m=>{if(!m)return!1;let o=m.toLowerCase();return o.includes("zoid destroyed")||o.includes("destroyed all components")||o.includes("window closed")||o.includes("detected container element removed")},On=m=>{if(Me()||Ot(m))return;let o=Un(m)??m;Ke(()=>qe.current?.(o))},Nn=m=>{Lt||(ze(!0),m.includes("paypal_ineligible")||U.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",m))},nn=(m,o=!1)=>{if(Lt)return;let y=C.current||!w;if(zn)return;zn=!0,Ln=!0,jt(),rt();let B=o||Si(m);if(B&&w&&!C.current){C.current=!0,G(!1),T(!1),Te(!0),Ge.current?.("retrying"),In=setTimeout(()=>{Lt||Ue(P=>P+1)},Gs);return}if(B||y){if(G(!1),T(!1),Te(!1),ze(!0),Ge.current?.("exhausted"),!se.current){se.current=!0;let P=Si(m)?"paypal_init_timeout":o?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",P)}return}Nn(m)};ze(!1);let Gt=async(m,o=Ee.current)=>{if(Me())return;let y=o?.sessionId??e;if(X.current){await X.current(m,{sessionId:y,accountPatch:o?.accountPatch,nonce:o?.nonce});return}let B=U.startTiming();U.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let P=()=>{U.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),U.performance({stage:"processing",durationMs:U.elapsed(B),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let $=I.current,Ae=o?.accountPatch?.email??he.current,Qe=o?.accountPatch?.userId??$?.customer?.id??$?.accountData?.userId??"",q=await new oa(ce,{telemetry:!1}).processPayment(Qe,{sessionId:y,nonce:o?.nonce??Ye.current,tokenizedData:m,accountData:{userId:Qe,email:Ae??$?.customer?.email??"",firstName:o?.accountPatch?.firstName??$?.customer?.firstName??$?.accountData?.firstName??"",lastName:o?.accountPatch?.lastName??$?.customer?.lastName??$?.accountData?.lastName??"",country:o?.accountPatch?.country??$?.customer?.country??$?.accountData?.country??void 0,zip:o?.accountPatch?.zip??$?.customer?.zip??$?.accountData?.zip??void 0}});if(q.ok){if(Ln||Lt&&Rn.current)return;P(),U.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ke(()=>tt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Me())return;let p=await q.json().catch(()=>null),N=p?.message??"PayPal payment failed.",ye=Un(N)??N;P(),q.status===400&&(typeof p?.declineCode=="string"||!Array.isArray(p?.fields))?U.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):q.status===400||q.status===422?U.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):U.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:q.status>=500?"5xx":q.status>=400?"4xx":q.status>=300?"3xx":"unknown",failureCategory:q.status>=500?"server_error":void 0}),On(ye),Ke(()=>ft.current?.(Et("paypal",ye,{code:p?.code,declineCode:p?.declineCode})));return}catch($){if(Me())return;P(),U.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ae=$ instanceof Error?$.message:"PayPal payment failed.",Qe=Un(Ae)??Ae;On(Qe),Ke(()=>ft.current?.(Et("paypal",Qe)));return}},rn=()=>new vi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ne=m=>Me()?Promise.reject(rn()):Promise.resolve(m),_=async m=>{if(Me())throw rn();He||En();let o=Ee.current,y=o?.sessionId??e,B=o?.nonce??Ye.current;U.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let P=await new oa(ce,{telemetry:!1}).createSessionIntent(y,B??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:st});if(Me())throw rn();if(P.provider!=="paypal")throw new Error(m);return U.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),P.providerObjectId},O=(m,o)=>{let y=o?.nonce??Ye.current;if(!y)return;let B=o?.sessionId??e,P=Pr(m)??Mn(m)??"provider_declined";new oa(ce,{telemetry:!1}).reportSessionIntentDecline(B,y,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:P}).catch(()=>{})},M=ae;A("loadScript:scheduled (deferred 1 tick)");let Pe=null,be=setTimeout(()=>{if(Lt){A("loadScript:skipped (cancelled before defer ran)");return}A("loadScript:start");let m=ne==="live"?"production":ne;Pe=Hs({clientId:r,currency:c,intent:l?"subscription":"capture",vault:l?!0:void 0,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Pe.then(o=>{if(A(`loadScript:resolved inactive=${Me()} ns=${!!o} buttons=${!!o?.Buttons}`),Me())return;if(!o?.Buttons){A("FAIL: namespace missing Buttons factory"),nn("PayPal SDK did not expose the Buttons factory.");return}U.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),U.performance({stage:"provider_ready",durationMs:U.elapsed(z.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),U.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let y=async Q=>{if(Me()||Fe.current!==M)return;let q=Q.subscriptionID??Q.orderID??"",p=q?Xe.current.get(q):nt.current.get(M);if(!(!p||!Zt(p.generation))&&Bt(p.generation)){Xe.current.delete(q),nt.current.delete(p.surfaceKey),ln();try{if(T(!0),Ke(()=>qe.current?.(null)),!q)throw new vi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Gt({id:q,isPaypal:!0},p)}catch(N){On(N instanceof Error?N.message:"PayPal capture failed.")}finally{Me()||T(!1)}}},B=o.Buttons({style:{layout:"horizontal",height:wo,tagline:!1},onClick:async(Q,q)=>{if(Me()){await q.reject();return}En();let p=Xt.current,N={};if(p)try{let _e=await p("paypal");if(Me()){await q.reject();return}if(!_e.proceed){Ee.current=null,nt.current.delete(M),await q.reject();return}N={sessionId:_e.sessionId,accountPatch:_e.accountPatch,nonce:_e.nonce}}catch(_e){A(`onClick:runBeforeButtonClick rejected msg=${(_e instanceof Error?_e.message:String(_e)).slice(0,120)}`),Ee.current=null,nt.current.delete(M),await q.reject();return}Ke(()=>We.current?.("paypal"));let we={generation:ir(),surfaceKey:M,...N};Ee.current=we,nt.current.set(M,we),await q.resolve(),U.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),U.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),U.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),zt=U.startTiming()},createOrder:l?void 0:E?()=>Ne(E).then(wt):()=>_("Failed to create PayPal order.").then(wt),createSubscription:l?E?()=>Ne(E).then(wt):()=>_("Failed to create PayPal subscription.").then(wt):void 0,onApprove:y,onCancel:()=>{if(Me())return;let Q=nt.current.get(M)??Ee.current;Q&&nt.current.delete(Q.surfaceKey),Ee.current=null,ln(),U.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ee.current=!0,kt({generation:Q?.generation,remount:!0,focus:!1})},onError:Q=>{if(Me()||Fe.current!==M)return;let q=Q instanceof Error?Q.message:"PayPal failed to render.";if(A(`onError rendered=${Pt} msg=${q.slice(0,120)}`),Pt){let p=nt.current.get(M)??Ee.current;if(p&&!Zt(p.generation)||!p&&Ve.current===St.current)return;if(Ot(q)){Bt(p?.generation);return}if(ln(),Wr(Q)){U.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),O(Q,p),Ke(()=>ft.current?.(Et("paypal",q))),p&&nt.current.delete(p.surfaceKey),Ee.current=null,Bt(p?.generation);return}let N=q.toLowerCase();U.error({errorCode:N.includes("popup")&&N.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),p&&nt.current.delete(p.surfaceKey),Ee.current=null,kt({generation:p?.generation,remount:!0,showRetry:!0,focus:!0}),yn(Q,{code:"paypal_runtime_failed"});return}nn(q)}}),P=B.isEligible();if(A(`isEligible=${P}`),U.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!P){G(!1),nn("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Wn=B,L&&A(`container:dims ${Ut(xt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),L&&typeof MutationObserver<"u"&&(tn=new MutationObserver(Q=>{if(!Me()){for(let q of Q)if(q.type==="childList")q.addedNodes.forEach(p=>{if(!(p instanceof Element))return;let N=p.tagName.toLowerCase(),ye=(p.getAttribute("title")??"").slice(0,40),we=N==="iframe"?` ${Ie(p)}`:"";A(`child+ ${N}${ye?` title="${ye}"`:""}${we} dims=${Ut(p)}`)});else if(q.type==="attributes"&&q.target instanceof Element){let p=q.target;if(p.tagName.toLowerCase()!=="iframe")continue;let N=q.attributeName;(N==="src"||N==="srcdoc")&&A(`attr~ iframe ${N}=${N==="srcdoc"?`[${(p.getAttribute("srcdoc")??"").length}ch]`:$t(p.getAttribute("src"))} dims=${Ut(p)}`)}}}),tn.observe(xt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ae=Q=>{if(Me()||Pt)return;let q=xt.querySelectorAll("iframe"),p=typeof document<"u"&&"hasStorageAccess"in document;A(`watchdog:${Q} container=${Ut(xt)} children=${xt.childElementCount} iframes=${q.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${p} paypalNetRequests=${Vt.value}`),q.forEach((N,ye)=>{let we=(N.getAttribute("title")??"").slice(0,40);A(` iframe[${ye}] ${Ut(N)}${we?` title="${we}"`:""} ${Ie(N)}`);let _e=qt(N);_e&&A(` ${_e}`)}),gt.length===0&&A(" (no PayPal/zoid window errors captured)")};L&&(Yt.push(setTimeout(()=>Ae("3s"),3e3)),Yt.push(setTimeout(()=>Ae("8s"),8e3)),Yt.push(setTimeout(()=>Ae("15s"),15e3))),A("render:start");let Qe=U.startTiming();Yt.push(setTimeout(()=>{Me()||Pt||(A("watchdog:11s retryable render timeout"),nn("PayPal Buttons render did not settle within 11000ms.",!0))},Js)),B.render(xt).then(()=>{if(A(`render:resolved inactive=${Me()}`),jt(),Me()){rt();return}Pt=!0,G(!0),Te(!1),Ge.current?.("ready"),U.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),U.performance({stage:"checkout_render",durationMs:U.elapsed(Qe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(Q=>{let q=Q instanceof Error?Q.message:"PayPal failed to render.";A(`render:rejected msg=${q.slice(0,120)}`),jt(),nn(q)})}).catch(o=>{let y=o instanceof Error?o.message:"PayPal SDK failed to load.";A(`loadScript:rejected msg=${y.slice(0,120)}`),nn(y)})},0);return()=>{Lt=!0,clearTimeout(be),In&&clearTimeout(In),jt(),rt()}},[w,ce,r,c,s,l,e,E,ae,U]);let Kn=L?aa("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:$e?"#fef2f2":"#f3f4f6",border:`1px solid ${$e?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${oe} failed=${$e})`,Je.length===0?`
6
+ `})]})})}import{FloPayError as mi,isMoneySettledOutcome as Vs,isSetupIntentClientSecret as Cd}from"@flopay/shared";function yi(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 ra(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function fi(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],a=n.reduce((i,c)=>i+(c.overrideAmount??c.totalAmount??0),0),r=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(a*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((i,c)=>({uuid:`synthetic-${i.type??"item"}-${c}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??r,metadata:i.metadata??null}))}}function oa(e,t){return t?{...e,...t}:e}function Et(e,t,n){let a=typeof t=="string"?t:t.message,r=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:a,...r?{code:r}:{},...i?{declineCode:i}:{}}}var js=[{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:a}of js)if(n.test(t))return a;return e}function er(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function gr(e){return e?.status==="authorized"||e?.status==="complete"}function gi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function bo(e){let t=gi(e);return new mi(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function vo(e){let t=gi(e);return new mi(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"||Vs(e,t)}function hi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Pi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Kr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var So="flopay_recent_completion_";function hr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(So+e,JSON.stringify(t))}catch{}}function aa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(So+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(So+e),!1):!0}catch{return!1}}function bi(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}import{useCallback as wo,useEffect as ht,useMemo as Yr,useRef as et,useState as nr}from"react";import{loadScript as Ks}from"@paypal/paypal-js";import{PaymentAPI as ia}from"@flopay/js";import{FloPayError as vi,SDK_VERSION as Ws,generateIdempotencyKey as Ys,normalizeGatewayEnvironment as Gs}from"@flopay/shared";function Ke(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 Hs(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 tr(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 tr(t.code)??tr(t.type)??tr(t.name)}function Pr(e){if(!(typeof e!="object"||e===null))return tr(e.decline_code)}function Wr(e){return typeof e!="object"||e===null?!1:tr(e.type)?.toLowerCase()==="card_error"||Pr(e)!==void 0}function $n(e){let t=Hs(e)?.toLowerCase()??"",a=`${An(e)?.toLowerCase()??""} ${t}`;return a.includes("popup")&&a.includes("block")}import{jsx as br,jsxs as sa}from"react/jsx-runtime";var ko=45,Js=1e3,Xs=11e3,Qs=["https://www.paypal.com","https://www.sandbox.paypal.com"],Ci="We couldn't open PayPal. Try again or choose another payment method.",Zs={width:"100%",minHeight:ko,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 Si(e){return e.includes("No ack for postMessage init()")&&Qs.some(t=>e.includes(t))&&e.includes("10000ms")}function el(e){return e?`${Ci} Allow pop-ups for this site, then try again.`:Ci}function wi({sessionId:e,nonce:t,billingApiUrl:n,email:a,clientId:r,environment:i,currency:c,isSubscription:l,onTokenizedBody:b,onComplete:x,onErrorChange:g,onDecline:w,onTechnicalFailure:v,isProcessing:R=!1,onLoadStateChange:d,onInitializationStateChange:h,allowAutomaticRetry:k=!0,onButtonClick:E,runBeforeButtonClick:f,session:de,existingOrderId:S,telemetry:le,telemetryContext:Z,debug:F=!1}){let G=wn(),W=Yr(()=>{if(G)return null;let D=fo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ws,enabled:le!==!1});return D.setCheckoutContext(Z??{}),D.beginCheckout(Z??{}),D},[n,G,le,Z?.checkoutMode,Z?.layout]),oe=Yr(()=>At(G),[G]);ht(()=>()=>{W&&W.flush().catch(()=>{}).finally(()=>W.destroy())},[W]);let N=Yr(()=>({error:D=>{oe?oe.error(D):W?.error(D)},log:D=>{oe?oe.log(D):W?.log(D)},performance:D=>{oe?oe.performance(D):W?.performance(D)},terminal:D=>{oe?oe.terminal(D):W?.terminal(D)},startTiming:()=>oe?.now()??W?.now()??0,elapsed:D=>oe?.elapsed(D)??Math.max(0,(W?.now()??D)-D)}),[oe,W]),j=et(null),ce=et(0),Re=et(null),fe=et(!1),[ae,ee]=nr(!1),[pe,Y]=nr(!1),[K,Ee]=nr(0),ge=et(0),[te,q]=nr(!1),C=et(!1),ie=et(!1),[$e,Oe]=nr(!1),[me,T]=nr(!1),ue=Yr(()=>n.replace(/\/+$/,""),[n]),J=Yr(()=>JSON.stringify([ue,r,c,i??"",l,e,S??""]),[ue,r,c,i,S,l,e]),_e=et(J),mt=_e.current!==J,[Je,yt]=nr([]),A=D=>{F&&yt(it=>[...it,`${new Date().toISOString().slice(11,23)} ${D}`])},X=et(b),tt=et(x),qe=et(g),ft=et(w),Ne=et(v),We=et(E),Xt=et(d),Ge=et(h),Qt=et(f),I=et(de),be=et(a),Ye=et(t),xe=et(null),St=et(0),je=et(null),Ve=et(null),nt=et(new Map),Xe=et(new Map),In=et(!1);ht(()=>(In.current=!0,()=>{In.current=!1}),[]),ht(()=>{X.current=b},[b]),ht(()=>{tt.current=x},[x]),ht(()=>{qe.current=g},[g]),ht(()=>{ft.current=w},[w]),ht(()=>{Ne.current=v},[v]),ht(()=>{We.current=E},[E]),ht(()=>{Xt.current=d},[d]),ht(()=>{Ge.current=h},[h]),ht(()=>{Qt.current=f},[f]),ht(()=>{I.current=de},[de]),ht(()=>{be.current=a},[a]),ht(()=>{Ye.current=t},[t]),ht(()=>{ge.current=K},[K]),ht(()=>{te&&Re.current?.focus()},[te,K]);let at=wo(()=>{window.setTimeout(()=>{Re.current?.focus()},0)},[]),Hn=wo(()=>{ee(!1),Ee(D=>D+1)},[]),Wt=wo(()=>{q(!1),(j.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??j.current)?.focus?.()},[]);ht(()=>{!ae||!fe.current||(fe.current=!1,Wt())},[Wt,ae,K]);let Pn=wo((D,it)=>{let Lt=Ne.current;if(Lt){Lt("paypal",D,it);return}qe.current?.(el(it?.popupBlocked??$n(D)))},[]),Zt=()=>{je.current?.timer&&(clearTimeout(je.current.timer),je.current.timer=null)},ir=()=>{Zt();let D=St.current+1;return St.current=D,Ve.current=null,je.current={generation:D,timer:null,yieldedControl:!1},q(!1),D},Bt=D=>D!==void 0&&je.current?.generation!==D?!1:(Zt(),je.current=null,Ve.current=null,!0),kt=D=>{let it=D?.generation??je.current?.generation??St.current;(!D?.generation||je.current?.generation===it)&&(Zt(),je.current=null),Ve.current=it,D?.showRetry&&q(!0),D?.remount&&Hn(),D?.focus!==!1&&at()},en=D=>je.current?.generation===D&&Ve.current!==D,tn=D=>{typeof document<"u"&&document.visibilityState!=="visible"||(Zt(),D.timer=setTimeout(()=>{je.current?.generation===D.generation&&(je.current=null,Ve.current=D.generation,Pn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),q(!0),Hn(),at())},600))},Ft=()=>{let D=je.current;D?.yieldedControl&&tn(D)},Dt=()=>{let D=je.current;D&&(D.yieldedControl=!0,Zt())},wt=D=>{let it=xe.current;return it&&Xe.current.set(D,it),D};ht(()=>{let D=()=>{document.visibilityState==="visible"?Ft():Dt()};return document.addEventListener("visibilitychange",D),window.addEventListener("focus",Ft),window.addEventListener("blur",Dt),()=>{document.removeEventListener("visibilitychange",D),window.removeEventListener("focus",Ft),window.removeEventListener("blur",Dt),Zt()}},[]),ht(()=>{_e.current!==J&&(_e.current=J,C.current=!1,ie.current=!1,ee(!1),Y(!1),Oe(!1),Ge.current?.("loading"))},[J]),ht(()=>{Ke(()=>Xt.current?.(ae&&!$e))},[ae,$e]);let ne=Gs(i);ht(()=>{let D=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",it=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(A(`mount clientId=${D} env=${i??"(unset)"}\u2192${ne??"live"} ccy=${c} sub=${l}`),A(`ua=${it.slice(0,80)}${it.length>80?"\u2026":""}`),!r){A("FAIL: clientId empty \u2014 gateway misconfigured"),Oe(!0),N.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!j.current){A("FAIL: containerRef not attached");return}ce.current=N.startTiming(),N.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Lt=!1,Ln=!1,Be=()=>Lt||Ln,st,He=!1,_n=()=>{st=Ys(),st||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),He=!0},xn=null,zn=!1,Wn=null,Tn=!1,rt=()=>{!Wn||Tn||(Tn=!0,Wn.close().catch(()=>{}))},zt=null,dn=()=>{zt!==null&&(N.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"overlay_return",durationMs:N.elapsed(zt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),zt=null)},Pt=!1,xt=j.current,nn=null,un=null,Yt=[],Ut=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let o=m.getBoundingClientRect();return`${Math.round(o.width)}\xD7${Math.round(o.height)}`},$t=m=>{if(!m)return"(empty)";try{let o=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),y=o.pathname.toLowerCase();return y.includes("checkcaptcha")||y.includes("captcha")?`CAPTCHA(${o.host}${y})`:y.includes("risk")||y.includes("challenge")?`RISK(${o.host}${y})`:y.includes("smart/buttons")?`smart-buttons(${o.host})`:`${o.host}${y}`.slice(0,100)}catch{return m.slice(0,80)}},Te=m=>{let o=m.getAttribute("src"),y=m.getAttribute("srcdoc"),B=m.getAttribute("name"),P=m.getAttribute("sandbox"),U=[];return o&&U.push(`src=${$t(o)}`),y&&U.push(`srcdoc[${y.length}ch]`),!o&&!y&&U.push("src=(empty) srcdoc=(empty)"),B&&U.push(`name=${B.slice(0,40)}`),P!==null&&U.push(`sandbox="${P.slice(0,40)}"`),U.join(" ")},qt=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let o=m.contentDocument;if(!o)return"cd=null";let y=o.body?.children.length??0,B=o.body?.innerHTML.length??0,P=o.head?.innerHTML.length??0;return`cd=same-origin readyState=${o.readyState} body[${y}children,${B}ch] head[${P}ch]`}catch(o){return`cd=cross-origin(${o.message.slice(0,30)})`}},gt=[],bn=m=>{if(Be())return;let o=m.message??String(m.error??"(no message)");o&&(o.toLowerCase().includes("paypal")||o.toLowerCase().includes("zoid")||o.toLowerCase().includes("postrobot")||o.toLowerCase().includes("storage"))&&(A(`window:error ${o.slice(0,140)}`),gt.push(o))},Yn=m=>{if(Be())return;let o=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");o&&(o.toLowerCase().includes("paypal")||o.toLowerCase().includes("zoid")||o.toLowerCase().includes("postrobot")||o.toLowerCase().includes("storage"))&&(A(`window:rejection ${o.slice(0,140)}`),gt.push(o))};F&&typeof window<"u"&&(window.addEventListener("error",bn),window.addEventListener("unhandledrejection",Yn));let Vt={value:0};if(F&&typeof PerformanceObserver<"u")try{un=new PerformanceObserver(m=>{if(!Be())for(let o of m.getEntries()){if(!o.name.toLowerCase().includes("paypal"))continue;Vt.value+=1;let y=Math.round(o.duration);A(`net ${y}ms ${o.name.slice(0,90)}`)}}),un.observe({type:"resource",buffered:!0})}catch{}let jt=()=>{for(nn?.disconnect(),nn=null,un?.disconnect(),un=null;Yt.length;)clearTimeout(Yt.pop());F&&typeof window<"u"&&(window.removeEventListener("error",bn),window.removeEventListener("unhandledrejection",Yn))},Ot=m=>{if(!m)return!1;let o=m.toLowerCase();return o.includes("zoid destroyed")||o.includes("destroyed all components")||o.includes("window closed")||o.includes("detected container element removed")},On=m=>{if(Be()||Ot(m))return;let o=Un(m)??m;Ke(()=>qe.current?.(o))},Nn=m=>{Lt||(Oe(!0),m.includes("paypal_ineligible")||N.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:",m))},rn=(m,o=!1)=>{if(Lt)return;let y=C.current||!k;if(zn)return;zn=!0,Ln=!0,jt(),rt();let B=o||Si(m);if(B&&k&&!C.current){C.current=!0,ee(!1),T(!1),Y(!0),Ge.current?.("retrying"),xn=setTimeout(()=>{Lt||Ee(P=>P+1)},Js);return}if(B||y){if(ee(!1),T(!1),Y(!1),Oe(!0),Ge.current?.("exhausted"),!ie.current){ie.current=!0;let P=Si(m)?"paypal_init_timeout":o?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",P)}return}Nn(m)};Oe(!1);let Gt=async(m,o=xe.current)=>{if(Be())return;let y=o?.sessionId??e;if(X.current){await X.current(m,{sessionId:y,accountPatch:o?.accountPatch,nonce:o?.nonce});return}let B=N.startTiming();N.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let P=()=>{N.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"processing",durationMs:N.elapsed(B),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let U=I.current,Fe=o?.accountPatch?.email??be.current,Qe=o?.accountPatch?.userId??U?.customer?.id??U?.accountData?.userId??"",$=await new ia(ue,{telemetry:!1}).processPayment(Qe,{sessionId:y,nonce:o?.nonce??Ye.current,tokenizedData:m,accountData:{userId:Qe,email:Fe??U?.customer?.email??"",firstName:o?.accountPatch?.firstName??U?.customer?.firstName??U?.accountData?.firstName??"",lastName:o?.accountPatch?.lastName??U?.customer?.lastName??U?.accountData?.lastName??"",country:o?.accountPatch?.country??U?.customer?.country??U?.accountData?.country??void 0,zip:o?.accountPatch?.zip??U?.customer?.zip??U?.accountData?.zip??void 0}});if($.ok){if(Ln||Lt&&In.current)return;P(),N.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ke(()=>tt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Be())return;let p=await $.json().catch(()=>null),O=p?.message??"PayPal payment failed.",he=Un(O)??O;P(),$.status===400&&(typeof p?.declineCode=="string"||!Array.isArray(p?.fields))?N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):$.status===400||$.status===422?N.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):N.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:$.status>=500?"5xx":$.status>=400?"4xx":$.status>=300?"3xx":"unknown",failureCategory:$.status>=500?"server_error":void 0}),On(he),Ke(()=>ft.current?.(Et("paypal",he,{code:p?.code,declineCode:p?.declineCode})));return}catch(U){if(Be())return;P(),N.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Fe=U instanceof Error?U.message:"PayPal payment failed.",Qe=Un(Fe)??Fe;On(Qe),Ke(()=>ft.current?.(Et("paypal",Qe)));return}},on=()=>new vi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ue=m=>Be()?Promise.reject(on()):Promise.resolve(m),_=async m=>{if(Be())throw on();He||_n();let o=xe.current,y=o?.sessionId??e,B=o?.nonce??Ye.current;N.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let P=await new ia(ue,{telemetry:!1}).createSessionIntent(y,B??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:st});if(Be())throw on();if(P.provider!=="paypal")throw new Error(m);return N.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),P.providerObjectId},z=(m,o)=>{let y=o?.nonce??Ye.current;if(!y)return;let B=o?.sessionId??e,P=Pr(m)??An(m)??"provider_declined";new ia(ue,{telemetry:!1}).reportSessionIntentDecline(B,y,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:P}).catch(()=>{})},M=K;A("loadScript:scheduled (deferred 1 tick)");let ve=null,Ce=setTimeout(()=>{if(Lt){A("loadScript:skipped (cancelled before defer ran)");return}A("loadScript:start");let m=ne==="live"?"production":ne;ve=Ks({clientId:r,currency:c,intent:l?"subscription":"capture",vault:l?!0:void 0,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),ve.then(o=>{if(A(`loadScript:resolved inactive=${Be()} ns=${!!o} buttons=${!!o?.Buttons}`),Be())return;if(!o?.Buttons){A("FAIL: namespace missing Buttons factory"),rn("PayPal SDK did not expose the Buttons factory.");return}N.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"provider_ready",durationMs:N.elapsed(ce.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let y=async Q=>{if(Be()||ge.current!==M)return;let $=Q.subscriptionID??Q.orderID??"",p=$?Xe.current.get($):nt.current.get(M);if(!(!p||!en(p.generation))&&Bt(p.generation)){Xe.current.delete($),nt.current.delete(p.surfaceKey),dn();try{if(T(!0),Ke(()=>qe.current?.(null)),!$)throw new vi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Gt({id:$,isPaypal:!0},p)}catch(O){On(O instanceof Error?O.message:"PayPal capture failed.")}finally{Be()||T(!1)}}},B=o.Buttons({style:{layout:"horizontal",height:ko,tagline:!1},onClick:async(Q,$)=>{if(Be()){await $.reject();return}_n();let p=Qt.current,O={};if(p)try{let Me=await p("paypal");if(Be()){await $.reject();return}if(!Me.proceed){xe.current=null,nt.current.delete(M),await $.reject();return}O={sessionId:Me.sessionId,accountPatch:Me.accountPatch,nonce:Me.nonce}}catch(Me){A(`onClick:runBeforeButtonClick rejected msg=${(Me instanceof Error?Me.message:String(Me)).slice(0,120)}`),xe.current=null,nt.current.delete(M),await $.reject();return}Ke(()=>We.current?.("paypal"));let Ie={generation:ir(),surfaceKey:M,...O};xe.current=Ie,nt.current.set(M,Ie),await $.resolve(),N.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),zt=N.startTiming()},createOrder:l?void 0:S?()=>Ue(S).then(wt):()=>_("Failed to create PayPal order.").then(wt),createSubscription:l?S?()=>Ue(S).then(wt):()=>_("Failed to create PayPal subscription.").then(wt):void 0,onApprove:y,onCancel:()=>{if(Be())return;let Q=nt.current.get(M)??xe.current;Q&&nt.current.delete(Q.surfaceKey),xe.current=null,dn(),N.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),fe.current=!0,kt({generation:Q?.generation,remount:!0,focus:!1})},onError:Q=>{if(Be()||ge.current!==M)return;let $=Q instanceof Error?Q.message:"PayPal failed to render.";if(A(`onError rendered=${Pt} msg=${$.slice(0,120)}`),Pt){let p=nt.current.get(M)??xe.current;if(p&&!en(p.generation)||!p&&Ve.current===St.current)return;if(Ot($)){Bt(p?.generation);return}if(dn(),Wr(Q)){N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),z(Q,p),Ke(()=>ft.current?.(Et("paypal",$))),p&&nt.current.delete(p.surfaceKey),xe.current=null,Bt(p?.generation);return}let O=$.toLowerCase();N.error({errorCode:O.includes("popup")&&O.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),p&&nt.current.delete(p.surfaceKey),xe.current=null,kt({generation:p?.generation,remount:!0,showRetry:!0,focus:!0}),Pn(Q,{code:"paypal_runtime_failed"});return}rn($)}}),P=B.isEligible();if(A(`isEligible=${P}`),N.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!P){ee(!1),rn("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Wn=B,F&&A(`container:dims ${Ut(xt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),F&&typeof MutationObserver<"u"&&(nn=new MutationObserver(Q=>{if(!Be()){for(let $ of Q)if($.type==="childList")$.addedNodes.forEach(p=>{if(!(p instanceof Element))return;let O=p.tagName.toLowerCase(),he=(p.getAttribute("title")??"").slice(0,40),Ie=O==="iframe"?` ${Te(p)}`:"";A(`child+ ${O}${he?` title="${he}"`:""}${Ie} dims=${Ut(p)}`)});else if($.type==="attributes"&&$.target instanceof Element){let p=$.target;if(p.tagName.toLowerCase()!=="iframe")continue;let O=$.attributeName;(O==="src"||O==="srcdoc")&&A(`attr~ iframe ${O}=${O==="srcdoc"?`[${(p.getAttribute("srcdoc")??"").length}ch]`:$t(p.getAttribute("src"))} dims=${Ut(p)}`)}}}),nn.observe(xt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Fe=Q=>{if(Be()||Pt)return;let $=xt.querySelectorAll("iframe"),p=typeof document<"u"&&"hasStorageAccess"in document;A(`watchdog:${Q} container=${Ut(xt)} children=${xt.childElementCount} iframes=${$.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${p} paypalNetRequests=${Vt.value}`),$.forEach((O,he)=>{let Ie=(O.getAttribute("title")??"").slice(0,40);A(` iframe[${he}] ${Ut(O)}${Ie?` title="${Ie}"`:""} ${Te(O)}`);let Me=qt(O);Me&&A(` ${Me}`)}),gt.length===0&&A(" (no PayPal/zoid window errors captured)")};F&&(Yt.push(setTimeout(()=>Fe("3s"),3e3)),Yt.push(setTimeout(()=>Fe("8s"),8e3)),Yt.push(setTimeout(()=>Fe("15s"),15e3))),A("render:start");let Qe=N.startTiming();Yt.push(setTimeout(()=>{Be()||Pt||(A("watchdog:11s retryable render timeout"),rn("PayPal Buttons render did not settle within 11000ms.",!0))},Xs)),B.render(xt).then(()=>{if(A(`render:resolved inactive=${Be()}`),jt(),Be()){rt();return}Pt=!0,ee(!0),Y(!1),Ge.current?.("ready"),N.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"checkout_render",durationMs:N.elapsed(Qe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(Q=>{let $=Q instanceof Error?Q.message:"PayPal failed to render.";A(`render:rejected msg=${$.slice(0,120)}`),jt(),rn($)})}).catch(o=>{let y=o instanceof Error?o.message:"PayPal SDK failed to load.";A(`loadScript:rejected msg=${y.slice(0,120)}`),rn(y)})},0);return()=>{Lt=!0,clearTimeout(Ce),xn&&clearTimeout(xn),jt(),rt()}},[k,ue,r,c,i,l,e,S,K,N]);let Kn=F?sa("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:$e?"#fef2f2":"#f3f4f6",border:`1px solid ${$e?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${ae} failed=${$e})`,Je.length===0?`
7
7
  (waiting for first lifecycle event\u2026)`:`
8
8
  ${Je.join(`
9
- `)}`]}):null;return $e&&!mt?L?br("div",{children:Kn}):null:aa("div",{children:[Kn,aa("div",{"aria-hidden":ge?!0:void 0,style:ge?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:wo},children:[!oe&&!ge&&br("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"}}),br("div",{ref:V,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:wo,display:"flex",opacity:oe?1:0},"aria-busy":ue||k},ae)]},ae),ke&&br("button",{ref:me,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Wt,style:Qs,children:"Try PayPal again"})]})}function ko(e){return br(wi,{...e})}function ki(e){return br(wi,{...e})}import{FloPayError as Sn,isSetupIntentClientSecret as gl,resolveTheme as hl}from"@flopay/shared";import{Fragment as vr,jsx as u,jsxs as Le}from"react/jsx-runtime";var wn="flopay_stripe_resume",xi="flopay_wallet_resume",Gr="flopay_paypal_resume",Pl=250,Ti="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ya(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Eo({billingApiUrl:e,sessionId:t,nonce:n,request:a}){if(!(!t||!n))try{await new qn(e,{telemetry:!1}).reportSessionIntentDecline(t,n,a)}catch{}}function bl(e){return e instanceof Sn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function la(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var vl=`
9
+ `)}`]}):null;return $e&&!mt?F?br("div",{children:Kn}):null:sa("div",{children:[Kn,sa("div",{"aria-hidden":pe?!0:void 0,style:pe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ko},children:[!ae&&!pe&&br("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"}}),br("div",{ref:j,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:ko,display:"flex",opacity:ae?1:0},"aria-busy":me||R},K)]},K),te&&br("button",{ref:Re,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Wt,style:Zs,children:"Try PayPal again"})]})}function Ro(e){return br(wi,{...e})}function ki(e){return br(wi,{...e})}import{FloPayError as kn,isSetupIntentClientSecret as hl,resolveTheme as Pl}from"@flopay/shared";import{Fragment as vr,jsx as u,jsxs as ze}from"react/jsx-runtime";var Rn="flopay_stripe_resume",xi="flopay_wallet_resume",Gr="flopay_paypal_resume",bl=250,Ti="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ga(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Io({billingApiUrl:e,sessionId:t,nonce:n,request:a}){if(!(!t||!n))try{await new qn(e,{telemetry:!1}).reportSessionIntentDecline(t,n,a)}catch{}}function vl(e){return e instanceof kn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function da(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var Cl=`
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 @@ ${Je.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
- `,Ro=44;function fa(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 Cl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Oi={width:"100%",minHeight:Ro,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 Sl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Mi(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ni(e){return e==="paypal"?"PayPal":Cr(e)}function wl(e,t){let n=`We couldn't open ${Ni(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=Be(0),n=Be(null),a=Be(null),r=Se((d=a.current)=>{let h=d;h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),s=Se((d,h)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(d),d.timer=setTimeout(()=>{d.timer=null,a.current?.generation===d.generation&&(a.current=null,n.current=d.generation,e(d.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},h))},[r,e]),c=Se(d=>{d.yieldedControl&&s(d,600)},[s]),l=Se(d=>{r();let h=t.current+1;t.current=h,n.current=null;let w={generation:h,method:d,timer:null,yieldedControl:!1};return a.current=w,h},[r]),b=Se(d=>{let h=a.current;return typeof d=="number"&&h?.generation!==d?!1:(r(h),a.current=null,(typeof d!="number"||n.current===d)&&(n.current=null),!0)},[r]),x=Se(d=>{let h=a.current,w=d??h?.generation??t.current;(!d||h?.generation===d)&&(r(h),a.current=null),n.current=w},[r]),g=Se(d=>n.current===(d??t.current),[]),S=Se(d=>a.current?.generation===d&&n.current!==d,[]),v=Se(()=>{let d=a.current;d&&c(d)},[c]),k=Se(()=>{let d=a.current;d&&(d.yieldedControl=!0,r(d))},[r]);return pt(()=>{let d=()=>{document.visibilityState==="visible"?v():k()},h=()=>{k()};return document.addEventListener("visibilitychange",d),window.addEventListener("blur",h),window.addEventListener("focus",v),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("blur",h),window.removeEventListener("focus",v),r()}},[r,k,v]),{startAttempt:l,finishAttempt:b,invalidateAttempt:x,isAttemptInvalidated:g,isAttemptCurrent:S}}function kl(e){let t=ll(e);return`Enter a valid ${da(e)}${t?` (e.g. ${t})`:""}`}function Rl(e,t,n){let a=il(e),r=t.trim(),s=n&&a,c=s&&!r,l=s&&!!r&&!sl(e,r);return{visible:n,supported:a,required:s,empty:c,malformed:l}}function Ai(e,t){return t instanceof Sn?t:new Sn(t instanceof Error?t.message:`${Sl(e)} before-click hook failed.`,"validation_error")}function ca(){return u("style",{children:vl})}function El(e){return typeof e=="number"?`${e}px`:e}function $i(e,t){let n=e.availablePaymentMethods;return n&&t.some(a=>n[a])?"ready":"unavailable"}function qi({state:e,placeholderTestId:t,borderRadius:n=8,children:a}){return e==="unavailable"||e==="load_error"?null:Le("div",{style:{position:"relative",minHeight:44},children:[u("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"}}),u("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:a})]})}function Bi(e){return e!=="unavailable"&&e!=="load_error"}function ga(e){return u(_l,{...e})}function Fi({sessionId:e,nonce:t,email:n,billingApiUrl:a,onTokenizedBody:r,onErrorChange:s,isProcessing:c=!1,onButtonClick:l,onDecline:b,onTechnicalFailure:x,runBeforeButtonClick:g,onLoadStateChange:S,placeholderBorderRadius:v}){let k=bn(),d=ma(),h=pa(),[w,R]=Ce("loading");pt(()=>{S?.(w)},[w,S]);let[f,de]=Ce(!1),E=Be(!1),re=Be(null),Z=Be(null),[L,Y]=Ce(0),[K,te]=Ce(!1),U=Be(!1),V=Be(new Map),{startAttempt:z,finishAttempt:me,invalidateAttempt:ee,isAttemptInvalidated:oe,isAttemptCurrent:G}=Ui((W,C,se)=>{x?.(W,C,{...se,popupBlocked:se?.popupBlocked??$n(C)}),te(!0),Y($e=>$e+1)});pt(()=>{K&&Z.current?.focus()},[K,L]);let ge=Se(()=>{Y(W=>W+1)},[]),Te=Se((W,C,se)=>{ee(se),x?.("paypal",W,{code:C,popupBlocked:$n(W)}),te(!0),ge()},[ee,x,ge]),ae=Se(()=>{window.setTimeout(()=>{(re.current?.querySelector("iframe")??re.current)?.focus()},0)},[]);pt(()=>{U.current&&(U.current=!1,ae())},[ae,L]);let Ue=Se(()=>{te(!1),s?.(null),ae()},[ae,s]);pt(()=>{if(!d||E.current)return;let W=new URLSearchParams(window.location.search),C=W.get("payment_intent"),se=W.get("payment_intent_client_secret"),$e=W.get("redirect_status");if(!C||!se)return;E.current=!0;let ze;try{let T=localStorage.getItem(Gr);if(T){let ce=JSON.parse(T);ce.clientSecret===se&&(ze={...ce.accountPatch?{accountPatch:ce.accountPatch}:{},...ce.sessionId?{sessionId:ce.sessionId}:{},...ce.nonce?{nonce:ce.nonce}:{}})}}catch{}try{localStorage.removeItem(Gr)}catch{}let ue=new URL(window.location.href);ue.searchParams.delete("payment_intent"),ue.searchParams.delete("payment_intent_client_secret"),ue.searchParams.delete("redirect_status"),window.history.replaceState({},"",ue.toString()),(async()=>{try{if(de(!0),$e==="failed"){let J="PayPal payment was declined. Please try again.";s?.(J),b?.(Et("paypal",J));return}let{paymentIntent:T,error:ce}=await d.retrievePaymentIntent(se);if(ce){s?.(ce.message??"Failed to retrieve PayPal payment status.");return}if(T&&(T.status==="requires_capture"||T.status==="succeeded")){let J=typeof T.payment_method=="string"?T.payment_method:T.payment_method?.id;r({id:J??T.id,type:"card",threeDSecureActionResultTokenId:T.id,isPaypal:!0},ze)}else{let J="PayPal payment was not completed. Please try again.";s?.(J),b?.(Et("paypal",J))}}catch(T){s?.(T instanceof Error?T.message:"Failed to complete PayPal payment.")}finally{de(!1)}})()},[d,r,s,b]);let Fe=Se(async W=>{if(c||f){W.reject();return}let C=g?await g("paypal"):{proceed:!0};if(!C.proceed){V.current.delete(L),W.reject();return}let se=z("paypal");V.current.set(L,{generation:se,accountPatch:C.accountPatch,sessionId:C.sessionId,nonce:C.nonce}),te(!1),l?.("paypal"),W.resolve()},[V,c,l,g,z,f,L]),ke=Se(async W=>{if(!d||!h)return;let C=V.current.get(L);if(C&&!G(C.generation)){V.current.delete(L);return}if(!C&&oe()||C&&!me(C.generation))return;C||me();let se=C??null;if(V.current.delete(L),!se&&g){let T=await g("paypal");if(!T.proceed){W.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}se={accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}}let $e=se?.sessionId??e,ze=se?.nonce??t,ue=se?.accountPatch?.email??n;try{if(de(!0),s?.(null),!$e||!ue)throw new Error("Missing sessionId or email for PayPal payment");let T=d.createPaymentMethod,{error:ce,paymentMethod:J}=await T({type:"paypal"});if(ce){Te(ce,"stripe_paypal_create_payment_method_failed",C?.generation),W.paymentFailed({reason:"fail"});return}let Re=await new qn(a).createSessionIntent($e,ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:J?.id??null,intentKind:"payment"});if(Re.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let mt=Re.clientSecret,Je={return_url:window.location.href};if(J?.id&&(Je.payment_method=J.id),typeof window<"u")try{localStorage.setItem(Gr,JSON.stringify({clientSecret:mt,sessionId:$e,nonce:ze,accountPatch:se?.accountPatch}))}catch{}let{error:yt,paymentIntent:A}=await d.confirmPayment({clientSecret:mt,confirmParams:Je,redirect:"if_required"});if(yt){if(typeof window<"u")try{localStorage.removeItem(Gr)}catch{}if(Wr(yt)){let tt=yt.message??"Your payment was declined.";s?.(tt),b?.(Et("paypal",tt,{code:Mn(yt),declineCode:Pr(yt)})),await Eo({billingApiUrl:a,sessionId:$e,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(yt)??"provider_declined"}})}else Te(yt,"stripe_paypal_confirm_failed",C?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Gr)}catch{}let X=typeof A?.payment_method=="string"?A.payment_method:A?.payment_method?.id;r({id:X??A?.id,type:"card",threeDSecureActionResultTokenId:A?.id,isPaypal:!0},{accountPatch:se?.accountPatch,sessionId:$e,nonce:ze});return}catch(T){Te(T,"stripe_paypal_failed",C?.generation)}finally{de(!1)}},[d,h,e,t,n,a,r,s,b,g,Te,me,G,oe,L]);return Le(vr,{children:[u(qi,{state:w,placeholderTestId:"flopay-paypal-placeholder",borderRadius:v,children:Le("div",{ref:re,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[K&&u("button",{ref:Z,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ue,style:Oi,children:"Try PayPal again"}),u(zi,{onReady:W=>R($i(W,["paypal"])),onLoadError:()=>{R("load_error"),ya(At(k),"paypal","paypal")},onClick:Fe,onConfirm:ke,onCancel:()=>{let W=V.current.get(L);V.current.delete(L),At(k)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ee(W?.generation),te(!1),U.current=!0,ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},L)]})}),f&&u(Cn,{status:"processing"})]})}function Di({sessionId:e,nonce:t,email:n,billingApiUrl:a,intentKind:r,expressMethods:s,onTokenizedBody:c,onErrorChange:l,onButtonClick:b,onDecline:x,onTechnicalFailure:g,runBeforeButtonClick:S,onLoadStateChange:v,placeholderBorderRadius:k}){let d=bn(),h=ma(),w=pa(),[R,f]=Ce("loading");pt(()=>{v?.(R)},[R,v]);let[de,E]=Ce(!1),re=Be(null),Z=Be(null),[L,Y]=Ce(0),[K,te]=Ce(!1),[U,V]=Ce("google_pay"),z=Be(!1),me=Be("google_pay"),ee=Be("google_pay"),oe=Be(new Map),{startAttempt:G,finishAttempt:ge,invalidateAttempt:Te,isAttemptInvalidated:ae,isAttemptCurrent:Ue}=Ui((ue,T,ce)=>{g?.(ue,T,{...ce,popupBlocked:ce?.popupBlocked??$n(T)}),V(ue),te(!0),Y(J=>J+1)});pt(()=>{K&&Z.current?.focus()},[K,L]);let Fe=Se(()=>{Y(ue=>ue+1)},[]),ke=Se((ue,T,ce,J)=>{Te(J),g?.(ue,T,{code:ce,popupBlocked:$n(T)}),V(ue),te(!0),Fe()},[Te,g,Fe]),W=Se(()=>{window.setTimeout(()=>{(re.current?.querySelector("iframe")??re.current)?.focus()},0)},[]);pt(()=>{z.current&&(z.current=!1,W())},[W,L]);let C=Se(()=>{te(!1),l?.(null),W()},[W,l]),se=Se(async ue=>{if(!h||!w)return;let T=oe.current.get(L);if(T&&!Ue(T.generation)){oe.current.delete(L);return}if(!T&&ae()||T&&!ge(T.generation))return;T||ge();let ce=ue.expressPaymentType??T?.method??me.current,J=T??null;oe.current.delete(L);let Re=Mi(ce);if(!J&&S){let X=await S(Re);if(!X.proceed){ue.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}J={accountPatch:X.accountPatch,sessionId:X.sessionId,nonce:X.nonce}}let mt=Re,Je=J?.sessionId??e,yt=J?.nonce??t,A=J?.accountPatch?.email??n;try{E(!0),l?.(null);let{error:X}=await w.submit();if(X){ke(ce,X,"stripe_wallet_submit_failed",T?.generation);return}let{error:tt,paymentMethod:qe}=await h.createPaymentMethod({elements:w});if(tt||!qe){ke(ce,tt??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",T?.generation);return}if(!Je||!A)throw new Error("Missing sessionId or email for wallet payment");let ft=await new qn(a).createSessionIntent(Je,yt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ce??Re,paymentMethodId:qe.id,intentKind:r});if(ft.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Oe=ft.clientSecret,{error:We,intentId:Jt}=gl(Oe)?await h.confirmCardSetup(Oe,{payment_method:qe.id}).then(Ge=>({error:Ge.error,intentId:Ge.setupIntent?.id})):await h.confirmCardPayment(Oe,{payment_method:qe.id}).then(Ge=>({error:Ge.error,intentId:Ge.paymentIntent?.id}));if(We){if(Wr(We)){let Ge=We.message??"Your payment was declined.";l?.(Ge),x?.(Et(mt,Ge,{code:Mn(We),declineCode:Pr(We)})),await Eo({billingApiUrl:a,sessionId:Je,nonce:yt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ce??Re,providerDeclineReason:Mn(We)??"provider_declined"}})}else ke(ce,We,"stripe_wallet_confirm_failed",T?.generation);return}c({id:qe.id,type:"card",threeDSecureActionResultTokenId:Jt},{accountPatch:J?.accountPatch,sessionId:Je,nonce:yt})}catch(X){ke(ce,X,"stripe_wallet_failed",T?.generation)}finally{E(!1)}},[h,w,e,t,n,a,r,c,l,x,S,ke,ge,Ue,ae,L]),$e=ut(()=>{let ue=["applePay","googlePay","paypal","link","amazonPay","klarna"],T=new Set(["applePay","googlePay"]),ce=new Set(s.map(_i)),J={};for(let Re of ue)ce.has(Re)?J[Re]=T.has(Re)?"always":"auto":J[Re]="never";return J},[s]),ze=ut(()=>s.map(_i),[s]);return Le(vr,{children:[u(qi,{state:R,placeholderTestId:"flopay-wallet-placeholder",borderRadius:k,children:Le("div",{ref:re,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[K&&Le("button",{ref:Z,type:"button","data-testid":"flopay-wallet-retry-button",onClick:C,style:Oi,children:["Try ",Ni(U)," again"]}),u(zi,{onReady:ue=>{f($i(ue,ze))},onLoadError:ue=>{f("load_error"),ya(At(d),"stripe","wallet")},onClick:async ue=>{me.current=ue.expressPaymentType,ee.current=Mi(ue.expressPaymentType);let T=S?await S(ee.current):{proceed:!0};if(!T.proceed){oe.current.delete(L),ue.reject();return}let ce=G(ue.expressPaymentType);oe.current.set(L,{generation:ce,method:ue.expressPaymentType,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),te(!1),b?.(ee.current),ue.resolve()},onConfirm:se,onCancel:()=>{let ue=oe.current.get(L);oe.current.delete(L),At(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Te(ue?.generation),te(!1),z.current=!0,Fe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:$e,layout:{maxColumns:1,overflow:"never"}}},L)]})}),de&&u(Cn,{status:"processing"})]})}function Il({method:e,themeId:t,submitting:n=!1,disabled:a=!1,highlighted:r=!1,hasNextStep:s=!1,onClick:c,backgroundColor:l,borderColor:b,textColor:x,borderRadius:g,fontFamily:S}){let v=ul(e,t),k=pi[e],d=v?.backgroundColor??l??"#ffffff",h=v?.borderColor??b??"#d1d5db",w=v?.textColor??x??"#262833";return u("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!a&&c()},disabled:n||a,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Ro,padding:"0 1rem",backgroundColor:d,color:w,border:`1px solid ${h}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:S,cursor:n||a?"not-allowed":"pointer",opacity:a&&!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?u("span",{style:{margin:"0 auto"},children:`Connecting to ${Cr(e)}\u2026`}):Le(vr,{children:[Le("span",{style:{display:"inline-flex",alignItems:"center",gap:dl(e)?8:0},children:[k?u("img",{src:k,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"}}):v?.logoSvg?u("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:v.logoSvg}}):null,u("span",{children:Cr(e)})]}),s&&u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:w,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:u("path",{d:"M9 18l6-6-6-6"})})]})})}function ua({method:e,sessionId:t,nonce:n,email:a,billingName:r,billingApiUrl:s,onTokenizedBody:c,onErrorChange:l,onDecline:b,onCancel:x,runBeforeButtonClick:g,onButtonClick:S,isProcessing:v,submitButtonColor:k,submitButtonBorderRadius:d,submitButtonStyle:h,errorText:w}){let R=bn(),f=ma(),de=pa(),[E,re]=Ce(!1),Z=Be(!1),[L,Y]=Ce(!1),[K,te]=Ce("loading"),U=Se(async()=>{if(!f||!de||v||Z.current||!L)return;Z.current=!0,re(!0);let V=g?await g("card"):{proceed:!0};if(!V.proceed){Z.current=!1,re(!1);return}S?.("card");let z=V.sessionId??t,me=V.nonce??n,ee=V.accountPatch?.email??a;try{l?.(null);let oe=await de.submit();if(oe.error){l?.(oe.error.message??"Payment failed.");return}let G=await f.createPaymentMethod({elements:de});if(G.error||!G.paymentMethod){l?.(G.error?.message??"Failed to create payment method.");return}let ge=G.paymentMethod;if(!z||!ee)throw new Error("Missing sessionId or email for payment.");let Te=ge.type||e,ae=await new qn(s).createSessionIntent(z,me??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Te,paymentMethodId:null,intentKind:"payment"});if(ae.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ue=ae.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Ue,sessionId:z,nonce:me,accountPatch:V.accountPatch,paymentMethodId:ge.id,paymentMethodType:ge.type??e,gateway:"stripe"}))}catch{}let{error:Fe,paymentIntent:ke}=await f.confirmPayment({clientSecret:Ue,confirmParams:{return_url:window.location.href,payment_method:ge.id},redirect:"if_required"});if(Fe){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let se=Fe.message??"Payment failed.";l?.(se),b?.(Et("card",se,{code:Fe.code})),await Eo({billingApiUrl:s,sessionId:z,nonce:me,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Fe.code??"provider_declined"}});return}let W=ke?.status;if(!vo(W)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let se=W==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";l?.(se),b?.(Et("card",se,{code:W??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let C=typeof ke?.payment_method=="string"?ke.payment_method:ke?.payment_method?.id;c({id:C??ge.id,type:"card",threeDSecureActionResultTokenId:ke?.id,gateway:"stripe",paymentMethodType:ge.type??e},{accountPatch:V.accountPatch,sessionId:z,nonce:me})}catch(oe){l?.(oe instanceof Error?oe.message:"Payment failed. Please try again.")}finally{Z.current=!1,re(!1)}},[f,de,v,L,g,S,t,n,a,s,e,c,l,b]);return Le("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[u(el,{onReady:()=>te("ready"),onLoadError:()=>{te("load_error"),ya(At(R),"stripe","apm")},onChange:V=>{Y(!!V.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...a?{email:a}:{}}}}}),u("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{U()},disabled:!L||E||v||K!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:k,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!L||E||v||K!=="ready"?"not-allowed":"pointer",opacity:!L||E||v||K!=="ready"?.5:1,transition:"opacity 120ms ease-out",...h??{}},children:E?"Processing\u2026":`Pay with ${Cr(e)}`}),w&&u(yr,{margin:"0.75rem 0 0",children:w})]})}function Li({sessionId:e,nonce:t,email:n,billingName:a,billingApiUrl:r,paymentElementMethods:s,stripeInstance:c,paymentElementBaseOptions:l,onTokenizedBody:b,onErrorChange:x,onButtonClick:g,onDecline:S,runBeforeButtonClick:v,onLoadStateChange:k,isProcessing:d=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:w=8,submitButtonStyle:R,buttonAppearance:f,themeId:de,onExpandApm:E,expandedApmMethod:re}){let[Z,L]=Ce(null),[Y,K]=Ce(null),te=Be(!1);pt(()=>{s.length>0&&c?k?.("ready"):c||k?.("loading")},[s.length,c,k]);let U=Se(async G=>{if(!c||te.current||d)return;te.current=!0,K(G);let ge=v?await v("card"):{proceed:!0};if(!ge.proceed){te.current=!1,K(null);return}g?.("card");let Te=ge.sessionId??e,ae=ge.nonce??t,Ue=ge.accountPatch?.email??n;try{if(x?.(null),!Te||!Ue)throw new Error("Missing sessionId or email for payment.");let Fe=await new qn(r).createSessionIntent(Te,ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:G,paymentMethodId:null,intentKind:"payment"});if(Fe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ke=Fe.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:ke,sessionId:Te,nonce:ae,accountPatch:ge.accountPatch,paymentMethodType:G,gateway:"stripe"}))}catch{}let{error:W,paymentIntent:C}=await c.confirmPayment({clientSecret:ke,confirmParams:{return_url:window.location.href,payment_method_data:{type:G,billing_details:{name:a&&a.trim().length>=3?a.trim():"FloPay Customer",...Ue?{email:Ue}:{}}}},redirect:"if_required"});if(W){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=W.message??"Payment failed.";x?.(ze),S?.(Et("card",ze,{code:W.code})),await Eo({billingApiUrl:r,sessionId:Te,nonce:ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:G,providerDeclineReason:W.code??"provider_declined"}});return}let se=C?.status;if(!vo(se)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=se==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";x?.(ze),S?.(Et("card",ze,{code:se??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let $e=typeof C?.payment_method=="string"?C.payment_method:C?.payment_method?.id;b({id:$e??C?.id,type:"card",threeDSecureActionResultTokenId:C?.id,gateway:"stripe",paymentMethodType:G},{accountPatch:ge.accountPatch,sessionId:Te,nonce:ae})}catch(Fe){x?.(Fe instanceof Error?Fe.message:"Payment failed. Please try again.")}finally{te.current=!1,K(null)}},[c,d,v,g,e,t,n,r,a,b,x,S]),[V,z]=Ce(null),me=E?re??null:V,ee=Se(G=>{te.current||d||me&&me!==G||(Ii(G)?E?E(G):z(G):U(G))},[me,d,U,E]),oe=ut(()=>V?{...l,paymentMethodTypes:[V]}:null,[V,l]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(G=>{let ge=re===G,Te=Y===G,ae=Y!==null&&Y!==G||re!=null&&re!==G;return Le(yl.Fragment,{children:[u(Il,{method:G,themeId:de,submitting:Te,disabled:ae,highlighted:ge,hasNextStep:Ii(G),onClick:()=>ee(G),backgroundColor:f?.backgroundColor,borderColor:f?.borderColor,textColor:f?.textColor,borderRadius:f?.borderRadius,fontFamily:f?.fontFamily}),!E&&V===G&&oe&&c&&u(rr,{stripe:c,options:oe,children:u(ua,{method:G,sessionId:e,email:n,billingName:a,billingApiUrl:r,onTokenizedBody:b,onErrorChange:x,onDecline:S,onCancel:()=>z(null),runBeforeButtonClick:v,onButtonClick:g,isProcessing:d,submitButtonColor:h,submitButtonBorderRadius:w,submitButtonStyle:R})},G)]},G)})})}function _l({sessionId:e,nonce:t,billingApiUrl:n,email:a,userId:r,onComplete:s,onError:c,onDecline:l,onTokenizedBody:b,firstName:x,lastName:g,chv:S,className:v,isProcessing:k,error:d,onErrorChange:h,showPayPal:w=!0,showStripe:R=!0,enabledPaymentMethods:f,enabledPaymentMethodCountries:de,showApplePay:E=!0,showGooglePay:re=!0,layout:Z="default",theme:L,buttonsTheme:Y,buttonsStyles:K,appearance:te,cardButtonContent:U,cardBackButtonContent:V,cardTitleContent:z,showSecurityFooter:me,onButtonClick:ee,onBeforeButtonClick:oe,enableAVS:G,cardFieldOrder:ge,cardPreFormSlot:Te,avsLayout:ae="row",country:Ue,zip:Fe,addressLine1:ke,addressLine2:W,city:C,state:se,onCountryChange:$e,onZipChange:ze,avsCheck:ue,checkoutType:T,checkoutLayout:ce,totalAmount:J=0,currency:Re="usd",initialCardOpen:mt=!1,directPaypal:Je,isSubscription:yt=!1,session:A,dataAttachmentPending:X=!1,debug:tt=!1}){let qe=bn(),ft=Zo(),Oe=fl(pn),We=X||Oe.claimPending===!0,Jt=ho(),[Ge,Xt]=Ce(!1),[I,he]=Ce(null),[Ye,Ee]=Ce(Ue??"US"),[St,je]=Ce(Fe??""),[Ve,nt]=Ce(ke??""),[Xe,Rn]=Ce(W??""),[at,Hn]=Ce(C??""),[Wt,yn]=Ce(se??""),[Qt,ir]=Ce({}),Bt=Be(Fe??""),kt=Be(Ue??"US"),Zt=Be(ke??""),en=Be(W??""),Ft=Be(C??""),Dt=Be(se??""),wt=Be({});pt(()=>{let i=(D,H,le,j,ve)=>{if(wt.current[D])return;let xe=H?.trim();!xe||xe===le.current||(le.current=xe,j(xe),ve?.(xe))};i("country",Ue,kt,Ee,$e),i("zip",Fe,Bt,je,ze),i("addressLine1",ke,Zt,nt),i("addressLine2",W,en,Rn),i("city",C,Ft,Hn),i("state",se,Dt,yn)},[Ue,Fe,ke,W,C,se,$e,ze]);let ne=ut(()=>al(G),[G]),Kn=ne!==null,F=ut(()=>sa(A),[A]),it=!!A?.vault?.html,Lt=!!A?.gateways?.pcivault,Me=!!(A?.gateways?.stripe?.enabledPaymentMethods??f)?.includes("card"),st=it||Me||Lt,He=!!(R&&st&&qe&&e),[En,In]=Ce(()=>Z!=="buttons"||mt?e??null:null),[zn,Wn]=Ce(0),_n=Z!=="buttons"||mt||!!e&&En===e,rt=ut(()=>!qe||!He||!e||!_n?null:qe.cardCapture({sessionId:e,captureMethod:A?.captureMethod}),[qe,He,e,_n,A?.captureMethod]),zt=ut(()=>{let i=Ye,D=ne?De(ne.postal_code,i):!1;return Rl(i,St,D)},[ne,Ye,St]),{avsInvalid:ln,invalidAvsFields:Pt}=ut(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!He||!ne)return{avsInvalid:!1,invalidAvsFields:i};let D=Ye,H=(ve,xe)=>De(ve,D)&&!xe.trim(),le={line1:H(ne.address_line_1,Ve),city:H(ne.city,at),state:H(ne.state,Wt),zip:zt.empty||zt.malformed};return{avsInvalid:le.line1||le.city||le.state||le.zip,invalidAvsFields:le}},[He,ne,Ye,Ve,at,Wt,zt]),[xt,tn]=Ce(!1),[cn,Yt]=Ce(!1),[Ut,$t]=Ce(()=>la(A?.vault)),[Ie,qt]=Ce(mt&&st?"card":"buttons"),[gt,fn]=Ce(null),Yn=Ie==="expanding"||Ie==="card",Vt=280,jt=Be(null),Ot=Se(i=>{jt.current&&clearTimeout(jt.current),jt.current=setTimeout(()=>{jt.current=null,i()},Vt)},[Vt]);pt(()=>()=>{jt.current&&clearTimeout(jt.current)},[]);let On=Se(()=>{In(e??null),Wn(i=>i+1),qt("expanding"),Ot(()=>qt("card"))},[Ot,e]),Nn=Se(()=>{qt("collapsing"),Ot(()=>qt("buttons"))},[Ot]),nn=Se(i=>{fn(i),qt("apm-expanding"),Ot(()=>qt("apm-form"))},[Ot]),Gt=Se(()=>{qt("apm-collapsing"),Ot(()=>{qt("buttons"),fn(null)})},[Ot]);pt(()=>{Z==="buttons"&&mt&&st&&(In(e??null),qt("card"))},[Z,mt,st,e]);let[rn,Ne]=Ce(null),_=Be(!1),O=Be(null),M=Be("idle"),[Pe,be]=Ce(null),m=Be(Pe);pt(()=>{m.current=Pe},[Pe]);let o=n||Jt,y=d??I,B=ut(()=>hl(L),[L]),P=ut(()=>{let i=B?.buttonsLayout??nl(Y);return K?{...i,...K,cardButton:{...i.cardButton,...K.cardButton},cardFormContainer:{...i.cardFormContainer,...K.cardFormContainer},backButton:{...i.backButton,...K.backButton},backButtonIcon:{...i.backButtonIcon,...K.backButtonIcon},submitButton:{...i.submitButton,...K.submitButton},title:{...i.title,...K.title}}:i},[B,Y,K]),$=te??B?.appearance,Ae=ut(()=>go({appearance:$,buttonsStyles:P,layout:Z}),[$,P,Z]),Qe=Oe.inlineSessionPatchProcessing??!1,Q=(k??Ge)||Qe,q=o.replace(/\/+$/,""),p=ut(()=>na({userId:r,email:a,firstName:x,lastName:g,country:Ue,zip:Fe},Qt),[r,a,x,g,Ue,Fe,Qt]),N=[p.firstName,p.lastName].filter(i=>!!i?.trim()).join(" "),ye=ut(()=>qe?qe.getRawProvider():null,[qe]),we=ut(()=>ft?ft.getRawProvider():null,[ft]),_e=J||100,gn=ut(()=>$?ml($):null,[$]),Tr=gn?{appearance:gn}:null,Lo=ut(()=>{let i=gn??{},D=i.rules??{};return{...i,rules:{...D,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...D[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...D[".AccordionItemContents"]??{}}}}},[gn]),no=ut(()=>{let i=Pi(J);return{...i,currency:Re.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...Tr}},[J,Re,Tr]),Fa=ut(()=>({mode:"payment",amount:_e,currency:Re.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Tr}),[_e,Re,Tr]),pe=Se(i=>{he(i),h?.(i)},[h]);pt(()=>{!He||!rt||rt.setCardFieldOrder?.(ge??null,ne==null)},[He,rt,ge,ne]),pt(()=>{(Ie==="expanding"||Ie==="collapsing"||Ie==="apm-expanding"||Ie==="apm-collapsing")&&pe(null)},[Ie,pe]);let dn=Se((i,D,H)=>{l?.(Et(i,D,H))},[l]),sr=Se((i,D,H)=>{let le=H?.popupBlocked??$n(D),j=wl(i,le),ve=tr(H?.code)??Mn(D)??"external_payment_method_failed",xe=new Sn(j,"api_error",{code:"external_payment_method_failed",param:i});Ne(null),Z==="buttons"&&(qt("buttons"),fn(null)),pe(j),c?.(xe),console.error("[FloPay] External payment method failed:",{method:i,code:ve,popupBlocked:le})},[Z,c,pe]);pt(()=>{if(!He||!e){$t(null);return}let i=la(A?.vault);if(i){$t(i);return}if(!_n){$t(null);return}$t(null);let D=!0;return new qn(q).getVaultCapture(e,t).then(H=>{if(!D)return;let le=la(H);le?$t(le):pe("Failed to load the secure card form.")}).catch(H=>{D&&pe(H instanceof Error?H.message:"Failed to load the secure card form.")}),()=>{D=!1}},[He,_n,zn,e,A?.vault?.html,A?.vault?.messageToken,A?.vault?.expectedOrigin,q,t,pe]);let hn=Be({onComplete:s,onError:c,updateError:pe,emitDecline:dn,resolvedAccount:p,avsConfig:ne,avsCheckProp:ue,sessionId:e,nonce:t,baseUrl:q,captureMethod:A?.captureMethod,paymentId:A?.paymentId,authorizationExpiresAt:A?.authorizationExpiresAt});hn.current={onComplete:s,onError:c,updateError:pe,emitDecline:dn,resolvedAccount:p,avsConfig:ne,avsCheckProp:ue,sessionId:e,nonce:t,baseUrl:q,captureMethod:A?.captureMethod,paymentId:A?.paymentId,authorizationExpiresAt:A?.authorizationExpiresAt};let zo=Be(!1),cs=Se(()=>{let{resolvedAccount:i,avsConfig:D,avsCheckProp:H}=hn.current,le=kt.current||i.country||"US",j=D?De(D.state,le):!1,ve=D?De(D.address_line_1,le):!1,xe=D?De(D.postal_code,le):!1,lt=D?De(D.city,le):!1,vt=D?De(D.address_line_2,le):!1,Ze=ve&&!j&&xe?Ei(le,(Bt.current??"").trim()):null,Rt=j?Dt.current:Ze;return{accountData:{userId:i.userId??"",email:i.email??"",firstName:i.firstName??"",lastName:i.lastName??"",...xe&&Bt.current?{zip:Bt.current}:{},...lt&&Ft.current?{city:Ft.current}:{},...Rt?{state:Rt}:{},...ve&&Zt.current?{addressLine1:Zt.current}:{},...vt&&en.current?{addressLine2:en.current}:{},country:le},...H!==void 0?{avsCheck:H}:{},...D?{avsConfig:{country:De(D.country,le),postal_code:xe,address_line_1:ve,address_line_2:vt,city:lt,state:j}}:{}}},[]),Da=Be(We);Da.current=We,pt(()=>{We||y!==Ti||hn.current.updateError(null)},[We,y]),pt(()=>{!He||!rt||rt.setSubmitGate?.(ln||We)},[He,rt,ln,We]),pt(()=>{if(!He||!rt)return;zo.current=!1;let i=!1,D=rt.on("submitting",()=>{tn(!0),O.current&&clearTimeout(O.current),M.current="validation-window",O.current=setTimeout(()=>{O.current=null,M.current==="validation-window"&&(M.current="processing")},Pl),Ne("processing");let{baseUrl:xe,sessionId:lt,nonce:vt,updateError:Ze,onError:Rt}=hn.current;!lt||!vt||new qn(xe).patchAccountSnapshot(lt,vt,cs(),{telemetryMode:"best_effort"}).catch(fe=>{if(!bl(fe))return;let Tt=fe instanceof Error?fe.message:"Please check your billing address and try again.";Ze(Tt),M.current="idle",Ne(null),Rt?.(fe instanceof Sn?fe:new Sn(Tt,"api_error"))})}),H=rt.on("complete",async xe=>{if(hr(xe.sessionId??hn.current.sessionId),M.current="terminal",Ne("success"),await new Promise(Ze=>setTimeout(Ze,Tn)),zo.current)return;zo.current=!0;let lt=hn.current,vt=sa(lt)||xe.outcome==="authorized";hn.current.onComplete?.(vt?{status:"authorized",paymentIntentId:xe.intentId,paymentId:xe.paymentId??lt.paymentId,sessionId:xe.sessionId??lt.sessionId,authorizationExpiresAt:xe.authorizationExpiresAt??lt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:xe.intentId,checkoutMethod:"card"})}),le=rt.on("decline",async xe=>{let{updateError:lt,emitDecline:vt}=hn.current,Ze=xe.message??"Your payment was declined. Please try another card or contact your bank.";M.current="terminal",lt(Ze),Ne("error");let Rt=xe.failureOutcome??tl(xe.declineReason)??"authorization_declined";vt("card",Ze,{code:Rt,declineCode:Rt}),await new Promise(fe=>setTimeout(fe,vn)),!i&&(M.current="idle",Ne(null))}),j=rt.on("error",async xe=>{let{updateError:lt,onError:vt}=hn.current,Ze=xe.message??"There was a problem processing your payment. Please try again.";M.current="terminal",lt(Ze),Ne("error"),vt?.(new Sn(Ze,"api_error",{code:xe.failureOutcome??"capture_failed"})),await new Promise(Rt=>setTimeout(Rt,vn)),!i&&(M.current="idle",Ne(null))}),ve=rt.on("blocked",()=>{if(!Da.current){tn(!0);return}hn.current.updateError(Ti)});return()=>{i=!0,O.current&&(clearTimeout(O.current),O.current=null),M.current="idle",D(),H(),le(),j(),ve()}},[He,rt]);let Pn=!!Je?.clientId,Mr=Array.isArray(f),ro=Mr&&f.length>0,ds=Mr&&f.includes("paypal"),{expressMethods:oo,paymentElementMethods:Ar}=ut(()=>pl(f,{excludePaypal:Pn}),[f,Pn]),La=Pn||!!ft,us=ut(()=>La?oo.filter(i=>i!=="paypal"):oo,[oo,La]),ps=ut(()=>{let i=[];return E&&i.push("apple_pay"),re&&i.push("google_pay"),i},[E,re]),ao=Mr?us:ps,ms=R&&ao.length>0,Oo=Kn?Ye:Ue,io=ut(()=>{let i=Oo?.trim().toUpperCase();return i?de?Ar.filter(D=>{let H=de[D];return!H||H.length===0||H.includes(i)}):cl(Ar,Oo):Ar},[Ar,Oo,de]),No=ut(()=>({mode:"payment",amount:_e,currency:Re.toLowerCase(),paymentMethodCreation:"manual",appearance:Lo}),[_e,Re,Lo]),[za,Oa]=Ce("loading"),[Na,Ua]=Ce("loading"),[$a,qa]=Ce("loading"),[ys,Uo]=Ce(!1),[Va,$o]=Ce("loading"),[so,fs]=Ce();pt(()=>{fs(bi())},[]);let ja=w&&(Pn||(Mr?ds:so===!1)),Ha=R&&ms,Br=!We&&ja&&Pn,Ka=Va==="retrying"||Va==="exhausted",Fr=!We&&ja&&!!we&&(!Pn||Ka),Dr=!We&&Ha&&!!ye,Lr=!We&&R&&ro&&io.length>0&&!!ye,gs=Br&&!Ka?ys:Fr&&Bi(za),hs=Dr&&Bi(Na),Ps=Lr&&$a!=="load_error",Wa=i=>i==="loading"||i==="ready",Ya=Br||Fr&&Wa(za)||Dr&&Wa(Na)||Lr&&$a!=="load_error",lo=Be(!1);pt(()=>{if(!lo.current){if(!R&&!w){lo.current=!0;let i=new Sn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(i),pe(i.message)}else if(!R&&w&&!Pn&&!we){lo.current=!0;let i=new Sn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(i),pe(i.message)}else if(so!==void 0&&!We&&!st&&!Ya){lo.current=!0;let i=new Sn("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"});c?.(i),pe(i.message)}}},[R,w,Pn,we,so,We,st,Ya,c,pe]);let Ga=Be(!1);pt(()=>{if(Ga.current||!ro)return;let i=[];E!==!0&&i.push("showApplePay"),re!==!0&&i.push("showGooglePay"),i.length!==0&&(Ga.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.`))},[ro,E,re]);let Ja=Se((i,D)=>Oe.applyInlineSessionPatch?Oe.applyInlineSessionPatch(i).then(H=>({error:null,sessionId:H.sessionId||e,nonce:H.session?.clientSecret||t})).catch(H=>{let le=Ai(D,H);return pe(le.message),c?.(le),{error:le,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Oe.applyInlineSessionPatch,t,c,e,pe]),un=Se(async i=>{if(!oe)return{proceed:!0};try{let D=await oe({method:i,sessionId:e||void 0,createSession:Oe.inlineSessionDraft});if(D===!1)return{proceed:!1};if(D&&typeof D=="object"){D.account&&ir(le=>({...le??{},...D.account}));let H=await Ja(D,i);return H.error?{proceed:!1,accountPatch:D.account}:{proceed:!0,accountPatch:D.account,sessionId:H.sessionId,nonce:H.nonce}}return{proceed:!0}}catch(D){let H=Ai(i,D);return pe(H.message),c?.(H),{proceed:!1}}},[Ja,Oe.inlineSessionDraft,oe,c,e,pe]),Xa=Se(async(i,D)=>{if(_.current)return;_.current=!0,Xt(!0),Ne("processing"),pe(null);let H=D?.sessionId??e,le=D?.nonce??t,j=na(p,D?.accountPatch),ve=D?.completionPaymentMethodId??Kr(i),xe=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i;try{let vt=await new qn(q).processPayment(j.userId??"",{sessionId:H,nonce:le,tokenizedData:xe,accountData:{userId:j.userId??"",email:j.email??"",firstName:j.firstName??"",lastName:j.lastName??"",...ne?(()=>{let fe=kt.current,Tt=De(ne.state,fe),Kt=De(ne.address_line_1,fe),Qn=De(ne.postal_code,fe),Zn=Kt&&!Tt&&Qn?Ei(fe,(Bt.current??"").trim()):null,Mt=Tt?Dt.current:Zn;return{country:fe,...Qn&&Bt.current?{zip:Bt.current}:{},...De(ne.city,fe)&&Ft.current?{city:Ft.current}:{},...Mt?{state:Mt}:{},...Kt&&Zt.current?{addressLine1:Zt.current}:{},...De(ne.address_line_2,fe)&&en.current?{addressLine2:en.current}:{}}})():{}},chv:S,avsCheck:ue??!1,checkoutType:T,checkoutLayout:ce,avsConfig:ne?{country:De(ne.country,kt.current),postal_code:De(ne.postal_code,kt.current),address_line_1:De(ne.address_line_1,kt.current),address_line_2:De(ne.address_line_2,kt.current),city:De(ne.city,kt.current),state:De(ne.state,kt.current)}:void 0});if(vt.ok){let fe=vt.status===204?null:await vt.json().catch(()=>null),Tt=sa(A)||fe?.status==="authorized";hr(H),Ne("success"),be(null),await new Promise(Kt=>setTimeout(Kt,Tn)),s?.(Tt?{status:"authorized",...typeof fe?.paymentId=="string"?{paymentId:fe.paymentId}:A?.paymentId?{paymentId:A.paymentId}:{},sessionId:typeof fe?.sessionId=="string"?fe.sessionId:H,...typeof fe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:fe.authorizationExpiresAt}:A?.authorizationExpiresAt?{authorizationExpiresAt:A.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:ve,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:ve,checkoutMethod:i.isPaypal?"paypal":"card"});return}let Ze=await vt.json().catch(()=>null);if(Ze?.type==="paypal_redirect_required"){let fe=Ze.threeDSecureToken,Tt=Ze.paymentMethodId||i.id||"";if(!qe||!fe){Ne("error"),pe("PayPal authorization required but no token provided.");return}try{let Kt=ft?.getRawProvider();if(!Kt){pe("PayPal is not available.");return}let Qn={return_url:window.location.href};Tt&&(Qn.payment_method=Tt);let{error:Zn}=await Kt.confirmPayment({clientSecret:fe,confirmParams:Qn,redirect:"if_required"});if(Zn){Ne("error");let Mt=Zn.message??"PayPal payment failed.";pe(Mt),dn("paypal",Mt,{code:Zn.code})}}catch(Kt){Ne("error"),pe(Kt instanceof Error?Kt.message:"PayPal authorization failed.")}return}if(Ze?.type==="paypal_direct_required"){let fe=Ze.orderId;if(!fe){Ne("error"),pe("PayPal retry required but no order id provided.");return}let Tt=m.current?.attempts??0;if(Tt>=2){Ne("error"),pe("PayPal payment could not be completed after multiple attempts."),dn("paypal","paypal_direct_required retry limit exceeded");return}Uo(!1),$o("loading"),be({orderId:fe,attempts:Tt+1}),Ne(null);return}Ne("error");let Rt=Ze?.message??"Payment failed. Please try again.";pe(Rt),dn(i.isPaypal?"paypal":"card",Rt,{code:Ze?.code??Ze?.gatewayErrorCode,declineCode:Ze?.declineCode??Ze?.gatewayDeclineReason}),await new Promise(fe=>setTimeout(fe,vn))}catch(lt){Ne("error"),pe(lt instanceof Error?lt.message:"An unexpected error occurred"),await new Promise(vt=>setTimeout(vt,vn))}finally{Xt(!1),Ne(null),_.current=!1}},[q,e,t,p,N,S,qe,ft,A,s,c,pe,dn]),on=Se((i,D)=>{b?b(i):Xa(i,D)},[b,Xa]),Qa=Be(!1);pt(()=>{if(typeof window>"u"||Qa.current)return;let i=new URLSearchParams(window.location.search),D=i.get("payment_intent"),H=i.get("payment_intent_client_secret"),le=i.get("redirect_status");if(!D||!H)return;let j=Rt=>{let fe=localStorage.getItem(Rt);if(!fe)return null;try{return JSON.parse(fe)}catch{return localStorage.removeItem(Rt),null}},ve=j(wn)??j(xi),xe;if(ve?.clientSecret){if(ve.clientSecret!==H)return;xe={...ve.accountPatch?{accountPatch:ve.accountPatch}:{},...ve.sessionId?{sessionId:ve.sessionId}:{},...ve.nonce?{nonce:ve.nonce}:{}}}else if(ve?.sessionId&&ve.sessionId!==e)return;Qa.current=!0,localStorage.removeItem(wn),localStorage.removeItem(xi);let lt=new URL(window.location.href);lt.searchParams.delete("payment_intent"),lt.searchParams.delete("payment_intent_client_secret"),lt.searchParams.delete("redirect_status"),window.history.replaceState({},"",lt.toString());let vt=ve?.paymentMethodType??ve?.tokenType??"card",Ze="card";(async()=>{let Rt=qe?.getRawProvider();if(!Rt){let Mt="Payment is not available \u2014 please refresh and try again.";pe(Mt),dn(Ze,Mt);return}if(le==="failed"){let Mt="Payment was declined. Please try again.";pe(Mt),dn(Ze,Mt);return}let{paymentIntent:fe,error:Tt}=await Rt.retrievePaymentIntent(H);if(Tt){let Mt=Tt.message??"Failed to retrieve payment status.";pe(Mt),dn(Ze,Mt,{code:Tt.code});return}let Kt=fe?.status,Qn=vo(Kt);if(!fe||!Qn){let Mt=Kt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";pe(Mt),dn(Ze,Mt,{code:Kt??"missing_payment_intent"});return}let Zn=typeof fe.payment_method=="string"?fe.payment_method:fe.payment_method?.id;on({id:Zn??ve?.paymentMethodId??ve?.tokenId??fe.id,type:"card",threeDSecureActionResultTokenId:fe.id,gateway:ve?.gateway??"stripe",paymentMethodType:vt},xe)})()},[e,on,qe,pe,dn]);let qo=Se(i=>{i.preventDefault()},[]);if(!(qe!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let zr=Z==="buttons",Ht=$?.variables,bs=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Vo=Ht?.colorBackground,vs=Vo&&!bs.has(Vo)?Vo:void 0,Or=P.cardInputBorder??(zr?"#e5e7eb":"#A4A4FF"),jo=Ht?.colorDanger??"#dc2626",Gn=i=>xt&&i?jo:Or,co=(zt.malformed||zt.empty)&&(cn||xt),Cs=co?jo:Gn(Pt.zip),Ho=P.cardFormContainer?.backgroundColor??vs??(zr?"white":"#EDEDFF"),Nr=P.cardInputBackground??Ht?.colorBackground??"white",Ko=cr(V),Za=cr(z),lr=P.nameInput,ei=P.cardInputFontSize??El(lr?.fontSize)??Ht?.fontSizeBase??"16px",ti=typeof lr?.fontFamily=="string"?lr.fontFamily:Ht?.fontFamily??"Poppins, sans-serif",ni=Qo(lr?.fontWeight)??400,Ss=P.cardInputColor??(typeof lr?.color=="string"?lr.color:void 0)??Ht?.colorText??"#262833",ws=P.cardInputPlaceholderColor??"#9ca3af",bt=Ht?.borderRadius??"8px",Jn=Ht?.borderRadius??P.cardButton?.borderRadius??bt,Xn=Ht?.colorPrimary??"#4A49FF",ks=Ht?.colorPrimaryHover??mr(Xn,.12),Wo=Ht?.colorText??"#262833",ri={fontSize:ei,fontFamily:ti,fontWeight:ni,color:Ss,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Rs={"--flopay-input-placeholder-color":ws,"--flopay-input-font-size":ei,"--flopay-input-font-family":ti,"--flopay-input-font-weight":String(ni)},Ur=P.cardFormContainer??{},Yo=Ur.padding??(zr?"0":"1rem"),Go=Ur.borderRadius??bt,Es=rt&&Ut?u(jr,{capture:rt,html:Ut.html,messageToken:Ut.messageToken,expectedOrigin:Ut.expectedOrigin,theme:Ae,onReady:()=>{if(!ne||typeof document>"u")return;let i=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};i();let D=0,H=window.setInterval(()=>{D+=1;let le=document.activeElement;!!le&&le.tagName==="IFRAME"&&le.id==="flopay_vault_form_iframe"?(i(),window.clearInterval(H)):D>=50&&window.clearInterval(H)},100)},onError:i=>pe(i),onValidation:i=>{let D=M.current;(D==="idle"||D==="validation-window")&&(pe(i),i&&M.current==="validation-window"&&(O.current&&(clearTimeout(O.current),O.current=null),M.current="idle",Ne(null)))}}):u("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"}),oi=Le("div",{style:{backgroundColor:Ho,borderRadius:Go,...Ur,padding:Yo,...Rs,display:"flex",flexDirection:"column"},children:[u("style",{children:`
30
+ `,Eo=44;function ha(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 Sl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Oi={width:"100%",minHeight:Eo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function wl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Mi(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ni(e){return e==="paypal"?"PayPal":Cr(e)}function kl(e,t){let n=`We couldn't open ${Ni(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=De(0),n=De(null),a=De(null),r=ke((d=a.current)=>{let h=d;h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),i=ke((d,h)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(d),d.timer=setTimeout(()=>{d.timer=null,a.current?.generation===d.generation&&(a.current=null,n.current=d.generation,e(d.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},h))},[r,e]),c=ke(d=>{d.yieldedControl&&i(d,600)},[i]),l=ke(d=>{r();let h=t.current+1;t.current=h,n.current=null;let k={generation:h,method:d,timer:null,yieldedControl:!1};return a.current=k,h},[r]),b=ke(d=>{let h=a.current;return typeof d=="number"&&h?.generation!==d?!1:(r(h),a.current=null,(typeof d!="number"||n.current===d)&&(n.current=null),!0)},[r]),x=ke(d=>{let h=a.current,k=d??h?.generation??t.current;(!d||h?.generation===d)&&(r(h),a.current=null),n.current=k},[r]),g=ke(d=>n.current===(d??t.current),[]),w=ke(d=>a.current?.generation===d&&n.current!==d,[]),v=ke(()=>{let d=a.current;d&&c(d)},[c]),R=ke(()=>{let d=a.current;d&&(d.yieldedControl=!0,r(d))},[r]);return pt(()=>{let d=()=>{document.visibilityState==="visible"?v():R()},h=()=>{R()};return document.addEventListener("visibilitychange",d),window.addEventListener("blur",h),window.addEventListener("focus",v),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("blur",h),window.removeEventListener("focus",v),r()}},[r,R,v]),{startAttempt:l,finishAttempt:b,invalidateAttempt:x,isAttemptInvalidated:g,isAttemptCurrent:w}}function Rl(e){let t=cl(e);return`Enter a valid ${pa(e)}${t?` (e.g. ${t})`:""}`}function El(e,t,n){let a=sl(e),r=t.trim(),i=n&&a,c=i&&!r,l=i&&!!r&&!ll(e,r);return{visible:n,supported:a,required:i,empty:c,malformed:l}}function Ai(e,t){return t instanceof kn?t:new kn(t instanceof Error?t.message:`${wl(e)} before-click hook failed.`,"validation_error")}function ua(){return u("style",{children:Cl})}function Il(e){return typeof e=="number"?`${e}px`:e}function $i(e,t){let n=e.availablePaymentMethods;return n&&t.some(a=>n[a])?"ready":"unavailable"}function qi({state:e,placeholderTestId:t,borderRadius:n=8,children:a}){return e==="unavailable"||e==="load_error"?null:ze("div",{style:{position:"relative",minHeight:44},children:[u("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"}}),u("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:a})]})}function Bi(e){return e!=="unavailable"&&e!=="load_error"}function Pa(e){return u(xl,{...e})}function Fi({sessionId:e,nonce:t,email:n,billingApiUrl:a,onTokenizedBody:r,onErrorChange:i,isProcessing:c=!1,onButtonClick:l,onDecline:b,onTechnicalFailure:x,runBeforeButtonClick:g,onLoadStateChange:w,placeholderBorderRadius:v}){let R=wn(),d=fa(),h=ya(),[k,E]=we("loading");pt(()=>{w?.(k)},[k,w]);let[f,de]=we(!1),S=De(!1),le=De(null),Z=De(null),[F,G]=we(0),[W,oe]=we(!1),N=De(!1),j=De(new Map),{startAttempt:ce,finishAttempt:Re,invalidateAttempt:fe,isAttemptInvalidated:ae,isAttemptCurrent:ee}=Ui((q,C,ie)=>{x?.(q,C,{...ie,popupBlocked:ie?.popupBlocked??$n(C)}),oe(!0),G($e=>$e+1)});pt(()=>{W&&Z.current?.focus()},[W,F]);let pe=ke(()=>{G(q=>q+1)},[]),Y=ke((q,C,ie)=>{fe(ie),x?.("paypal",q,{code:C,popupBlocked:$n(q)}),oe(!0),pe()},[fe,x,pe]),K=ke(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);pt(()=>{N.current&&(N.current=!1,K())},[K,F]);let Ee=ke(()=>{oe(!1),i?.(null),K()},[K,i]);pt(()=>{if(!d||S.current)return;let q=new URLSearchParams(window.location.search),C=q.get("payment_intent"),ie=q.get("payment_intent_client_secret"),$e=q.get("redirect_status");if(!C||!ie)return;S.current=!0;let Oe;try{let T=localStorage.getItem(Gr);if(T){let ue=JSON.parse(T);ue.clientSecret===ie&&(Oe={...ue.accountPatch?{accountPatch:ue.accountPatch}:{},...ue.sessionId?{sessionId:ue.sessionId}:{},...ue.nonce?{nonce:ue.nonce}:{}})}}catch{}try{localStorage.removeItem(Gr)}catch{}let me=new URL(window.location.href);me.searchParams.delete("payment_intent"),me.searchParams.delete("payment_intent_client_secret"),me.searchParams.delete("redirect_status"),window.history.replaceState({},"",me.toString()),(async()=>{try{if(de(!0),$e==="failed"){let J="PayPal payment was declined. Please try again.";i?.(J),b?.(Et("paypal",J));return}let{paymentIntent:T,error:ue}=await d.retrievePaymentIntent(ie);if(ue){i?.(ue.message??"Failed to retrieve PayPal payment status.");return}if(T&&(T.status==="requires_capture"||T.status==="succeeded")){let J=typeof T.payment_method=="string"?T.payment_method:T.payment_method?.id;r({id:J??T.id,type:"card",threeDSecureActionResultTokenId:T.id,isPaypal:!0},Oe)}else{let J="PayPal payment was not completed. Please try again.";i?.(J),b?.(Et("paypal",J))}}catch(T){i?.(T instanceof Error?T.message:"Failed to complete PayPal payment.")}finally{de(!1)}})()},[d,r,i,b]);let ge=ke(async q=>{if(c||f){q.reject();return}let C=g?await g("paypal"):{proceed:!0};if(!C.proceed){j.current.delete(F),q.reject();return}let ie=ce("paypal");j.current.set(F,{generation:ie,accountPatch:C.accountPatch,sessionId:C.sessionId,nonce:C.nonce}),oe(!1),l?.("paypal"),q.resolve()},[j,c,l,g,ce,f,F]),te=ke(async q=>{if(!d||!h)return;let C=j.current.get(F);if(C&&!ee(C.generation)){j.current.delete(F);return}if(!C&&ae()||C&&!Re(C.generation))return;C||Re();let ie=C??null;if(j.current.delete(F),!ie&&g){let T=await g("paypal");if(!T.proceed){q.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ie={accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}}let $e=ie?.sessionId??e,Oe=ie?.nonce??t,me=ie?.accountPatch?.email??n;try{if(de(!0),i?.(null),!$e||!me)throw new Error("Missing sessionId or email for PayPal payment");let T=d.createPaymentMethod,{error:ue,paymentMethod:J}=await T({type:"paypal"});if(ue){Y(ue,"stripe_paypal_create_payment_method_failed",C?.generation),q.paymentFailed({reason:"fail"});return}let _e=await new qn(a).createSessionIntent($e,Oe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:J?.id??null,intentKind:"payment"});if(_e.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let mt=_e.clientSecret,Je={return_url:window.location.href};if(J?.id&&(Je.payment_method=J.id),typeof window<"u")try{localStorage.setItem(Gr,JSON.stringify({clientSecret:mt,sessionId:$e,nonce:Oe,accountPatch:ie?.accountPatch}))}catch{}let{error:yt,paymentIntent:A}=await d.confirmPayment({clientSecret:mt,confirmParams:Je,redirect:"if_required"});if(yt){if(typeof window<"u")try{localStorage.removeItem(Gr)}catch{}if(Wr(yt)){let tt=yt.message??"Your payment was declined.";i?.(tt),b?.(Et("paypal",tt,{code:An(yt),declineCode:Pr(yt)})),await Io({billingApiUrl:a,sessionId:$e,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:An(yt)??"provider_declined"}})}else Y(yt,"stripe_paypal_confirm_failed",C?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Gr)}catch{}let X=typeof A?.payment_method=="string"?A.payment_method:A?.payment_method?.id;r({id:X??A?.id,type:"card",threeDSecureActionResultTokenId:A?.id,isPaypal:!0},{accountPatch:ie?.accountPatch,sessionId:$e,nonce:Oe});return}catch(T){Y(T,"stripe_paypal_failed",C?.generation)}finally{de(!1)}},[d,h,e,t,n,a,r,i,b,g,Y,Re,ee,ae,F]);return ze(vr,{children:[u(qi,{state:k,placeholderTestId:"flopay-paypal-placeholder",borderRadius:v,children:ze("div",{ref:le,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[W&&u("button",{ref:Z,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ee,style:Oi,children:"Try PayPal again"}),u(zi,{onReady:q=>E($i(q,["paypal"])),onLoadError:()=>{E("load_error"),ga(At(R),"paypal","paypal")},onClick:ge,onConfirm:te,onCancel:()=>{let q=j.current.get(F);j.current.delete(F),At(R)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),fe(q?.generation),oe(!1),N.current=!0,pe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},F)]})}),f&&u(cn,{status:"processing"})]})}function Di({sessionId:e,nonce:t,email:n,billingApiUrl:a,intentKind:r,expressMethods:i,onTokenizedBody:c,onErrorChange:l,onButtonClick:b,onDecline:x,onTechnicalFailure:g,runBeforeButtonClick:w,onLoadStateChange:v,placeholderBorderRadius:R}){let d=wn(),h=fa(),k=ya(),[E,f]=we("loading");pt(()=>{v?.(E)},[E,v]);let[de,S]=we(!1),le=De(null),Z=De(null),[F,G]=we(0),[W,oe]=we(!1),[N,j]=we("google_pay"),ce=De(!1),Re=De("google_pay"),fe=De("google_pay"),ae=De(new Map),{startAttempt:ee,finishAttempt:pe,invalidateAttempt:Y,isAttemptInvalidated:K,isAttemptCurrent:Ee}=Ui((me,T,ue)=>{g?.(me,T,{...ue,popupBlocked:ue?.popupBlocked??$n(T)}),j(me),oe(!0),G(J=>J+1)});pt(()=>{W&&Z.current?.focus()},[W,F]);let ge=ke(()=>{G(me=>me+1)},[]),te=ke((me,T,ue,J)=>{Y(J),g?.(me,T,{code:ue,popupBlocked:$n(T)}),j(me),oe(!0),ge()},[Y,g,ge]),q=ke(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);pt(()=>{ce.current&&(ce.current=!1,q())},[q,F]);let C=ke(()=>{oe(!1),l?.(null),q()},[q,l]),ie=ke(async me=>{if(!h||!k)return;let T=ae.current.get(F);if(T&&!Ee(T.generation)){ae.current.delete(F);return}if(!T&&K()||T&&!pe(T.generation))return;T||pe();let ue=me.expressPaymentType??T?.method??Re.current,J=T??null;ae.current.delete(F);let _e=Mi(ue);if(!J&&w){let X=await w(_e);if(!X.proceed){me.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}J={accountPatch:X.accountPatch,sessionId:X.sessionId,nonce:X.nonce}}let mt=_e,Je=J?.sessionId??e,yt=J?.nonce??t,A=J?.accountPatch?.email??n;try{S(!0),l?.(null);let{error:X}=await k.submit();if(X){te(ue,X,"stripe_wallet_submit_failed",T?.generation);return}let{error:tt,paymentMethod:qe}=await h.createPaymentMethod({elements:k});if(tt||!qe){te(ue,tt??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",T?.generation);return}if(!Je||!A)throw new Error("Missing sessionId or email for wallet payment");let ft=await new qn(a).createSessionIntent(Je,yt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ue??_e,paymentMethodId:qe.id,intentKind:r});if(ft.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Ne=ft.clientSecret,{error:We,intentId:Xt}=hl(Ne)?await h.confirmCardSetup(Ne,{payment_method:qe.id}).then(Ge=>({error:Ge.error,intentId:Ge.setupIntent?.id})):await h.confirmCardPayment(Ne,{payment_method:qe.id}).then(Ge=>({error:Ge.error,intentId:Ge.paymentIntent?.id}));if(We){if(Wr(We)){let Ge=We.message??"Your payment was declined.";l?.(Ge),x?.(Et(mt,Ge,{code:An(We),declineCode:Pr(We)})),await Io({billingApiUrl:a,sessionId:Je,nonce:yt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ue??_e,providerDeclineReason:An(We)??"provider_declined"}})}else te(ue,We,"stripe_wallet_confirm_failed",T?.generation);return}c({id:qe.id,type:"card",threeDSecureActionResultTokenId:Xt},{accountPatch:J?.accountPatch,sessionId:Je,nonce:yt})}catch(X){te(ue,X,"stripe_wallet_failed",T?.generation)}finally{S(!1)}},[h,k,e,t,n,a,r,c,l,x,w,te,pe,Ee,K,F]),$e=ut(()=>{let me=["applePay","googlePay","paypal","link","amazonPay","klarna"],T=new Set(["applePay","googlePay"]),ue=new Set(i.map(_i)),J={};for(let _e of me)ue.has(_e)?J[_e]=T.has(_e)?"always":"auto":J[_e]="never";return J},[i]),Oe=ut(()=>i.map(_i),[i]);return ze(vr,{children:[u(qi,{state:E,placeholderTestId:"flopay-wallet-placeholder",borderRadius:R,children:ze("div",{ref:le,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[W&&ze("button",{ref:Z,type:"button","data-testid":"flopay-wallet-retry-button",onClick:C,style:Oi,children:["Try ",Ni(N)," again"]}),u(zi,{onReady:me=>{f($i(me,Oe))},onLoadError:me=>{f("load_error"),ga(At(d),"stripe","wallet")},onClick:async me=>{Re.current=me.expressPaymentType,fe.current=Mi(me.expressPaymentType);let T=w?await w(fe.current):{proceed:!0};if(!T.proceed){ae.current.delete(F),me.reject();return}let ue=ee(me.expressPaymentType);ae.current.set(F,{generation:ue,method:me.expressPaymentType,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),oe(!1),b?.(fe.current),me.resolve()},onConfirm:ie,onCancel:()=>{let me=ae.current.get(F);ae.current.delete(F),At(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Y(me?.generation),oe(!1),ce.current=!0,ge()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:$e,layout:{maxColumns:1,overflow:"never"}}},F)]})}),de&&u(cn,{status:"processing"})]})}function _l({method:e,themeId:t,submitting:n=!1,disabled:a=!1,highlighted:r=!1,hasNextStep:i=!1,onClick:c,backgroundColor:l,borderColor:b,textColor:x,borderRadius:g,fontFamily:w}){let v=pl(e,t),R=pi[e],d=v?.backgroundColor??l??"#ffffff",h=v?.borderColor??b??"#d1d5db",k=v?.textColor??x??"#262833";return u("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!a&&c()},disabled:n||a,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Eo,padding:"0 1rem",backgroundColor:d,color:k,border:`1px solid ${h}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:w,cursor:n||a?"not-allowed":"pointer",opacity:a&&!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?u("span",{style:{margin:"0 auto"},children:`Connecting to ${Cr(e)}\u2026`}):ze(vr,{children:[ze("span",{style:{display:"inline-flex",alignItems:"center",gap:ul(e)?8:0},children:[R?u("img",{src:R,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"}}):v?.logoSvg?u("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:v.logoSvg}}):null,u("span",{children:Cr(e)})]}),i&&u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:k,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:u("path",{d:"M9 18l6-6-6-6"})})]})})}function ma({method:e,sessionId:t,nonce:n,email:a,billingName:r,billingApiUrl:i,onTokenizedBody:c,onErrorChange:l,onDecline:b,onCancel:x,runBeforeButtonClick:g,onButtonClick:w,isProcessing:v,submitButtonColor:R,submitButtonBorderRadius:d,submitButtonStyle:h,errorText:k}){let E=wn(),f=fa(),de=ya(),[S,le]=we(!1),Z=De(!1),[F,G]=we(!1),[W,oe]=we("loading"),N=ke(async()=>{if(!f||!de||v||Z.current||!F)return;Z.current=!0,le(!0);let j=g?await g("card"):{proceed:!0};if(!j.proceed){Z.current=!1,le(!1);return}w?.("card");let ce=j.sessionId??t,Re=j.nonce??n,fe=j.accountPatch?.email??a;try{l?.(null);let ae=await de.submit();if(ae.error){l?.(ae.error.message??"Payment failed.");return}let ee=await f.createPaymentMethod({elements:de});if(ee.error||!ee.paymentMethod){l?.(ee.error?.message??"Failed to create payment method.");return}let pe=ee.paymentMethod;if(!ce||!fe)throw new Error("Missing sessionId or email for payment.");let Y=pe.type||e,K=await new qn(i).createSessionIntent(ce,Re??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Y,paymentMethodId:null,intentKind:"payment"});if(K.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ee=K.clientSecret;if(typeof window<"u")try{localStorage.setItem(Rn,JSON.stringify({clientSecret:Ee,sessionId:ce,nonce:Re,accountPatch:j.accountPatch,paymentMethodId:pe.id,paymentMethodType:pe.type??e,gateway:"stripe"}))}catch{}let{error:ge,paymentIntent:te}=await f.confirmPayment({clientSecret:Ee,confirmParams:{return_url:window.location.href,payment_method:pe.id},redirect:"if_required"});if(ge){if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let ie=ge.message??"Payment failed.";l?.(ie),b?.(Et("card",ie,{code:ge.code})),await Io({billingApiUrl:i,sessionId:ce,nonce:Re,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ge.code??"provider_declined"}});return}let q=te?.status;if(!Co(q)){if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let ie=q==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";l?.(ie),b?.(Et("card",ie,{code:q??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let C=typeof te?.payment_method=="string"?te.payment_method:te?.payment_method?.id;c({id:C??pe.id,type:"card",threeDSecureActionResultTokenId:te?.id,gateway:"stripe",paymentMethodType:pe.type??e},{accountPatch:j.accountPatch,sessionId:ce,nonce:Re})}catch(ae){l?.(ae instanceof Error?ae.message:"Payment failed. Please try again.")}finally{Z.current=!1,le(!1)}},[f,de,v,F,g,w,t,n,a,i,e,c,l,b]);return ze("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[u(tl,{onReady:()=>oe("ready"),onLoadError:()=>{oe("load_error"),ga(At(E),"stripe","apm")},onChange:j=>{G(!!j.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...a?{email:a}:{}}}}}),u("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{N()},disabled:!F||S||v||W!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:R,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!F||S||v||W!=="ready"?"not-allowed":"pointer",opacity:!F||S||v||W!=="ready"?.5:1,transition:"opacity 120ms ease-out",...h??{}},children:S?"Processing\u2026":`Pay with ${Cr(e)}`}),k&&u(yr,{margin:"0.75rem 0 0",children:k})]})}function Li({sessionId:e,nonce:t,email:n,billingName:a,billingApiUrl:r,paymentElementMethods:i,stripeInstance:c,paymentElementBaseOptions:l,onTokenizedBody:b,onErrorChange:x,onButtonClick:g,onDecline:w,runBeforeButtonClick:v,onLoadStateChange:R,isProcessing:d=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:k=8,submitButtonStyle:E,buttonAppearance:f,themeId:de,onExpandApm:S,expandedApmMethod:le}){let[Z,F]=we(null),[G,W]=we(null),oe=De(!1);pt(()=>{i.length>0&&c?R?.("ready"):c||R?.("loading")},[i.length,c,R]);let N=ke(async ee=>{if(!c||oe.current||d)return;oe.current=!0,W(ee);let pe=v?await v("card"):{proceed:!0};if(!pe.proceed){oe.current=!1,W(null);return}g?.("card");let Y=pe.sessionId??e,K=pe.nonce??t,Ee=pe.accountPatch?.email??n;try{if(x?.(null),!Y||!Ee)throw new Error("Missing sessionId or email for payment.");let ge=await new qn(r).createSessionIntent(Y,K??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,paymentMethodId:null,intentKind:"payment"});if(ge.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let te=ge.clientSecret;if(typeof window<"u")try{localStorage.setItem(Rn,JSON.stringify({clientSecret:te,sessionId:Y,nonce:K,accountPatch:pe.accountPatch,paymentMethodType:ee,gateway:"stripe"}))}catch{}let{error:q,paymentIntent:C}=await c.confirmPayment({clientSecret:te,confirmParams:{return_url:window.location.href,payment_method_data:{type:ee,billing_details:{name:a&&a.trim().length>=3?a.trim():"FloPay Customer",...Ee?{email:Ee}:{}}}},redirect:"if_required"});if(q){if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let Oe=q.message??"Payment failed.";x?.(Oe),w?.(Et("card",Oe,{code:q.code})),await Io({billingApiUrl:r,sessionId:Y,nonce:K,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,providerDeclineReason:q.code??"provider_declined"}});return}let ie=C?.status;if(!Co(ie)){if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let Oe=ie==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";x?.(Oe),w?.(Et("card",Oe,{code:ie??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let $e=typeof C?.payment_method=="string"?C.payment_method:C?.payment_method?.id;b({id:$e??C?.id,type:"card",threeDSecureActionResultTokenId:C?.id,gateway:"stripe",paymentMethodType:ee},{accountPatch:pe.accountPatch,sessionId:Y,nonce:K})}catch(ge){x?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{oe.current=!1,W(null)}},[c,d,v,g,e,t,n,r,a,b,x,w]),[j,ce]=we(null),Re=S?le??null:j,fe=ke(ee=>{oe.current||d||Re&&Re!==ee||(Ii(ee)?S?S(ee):ce(ee):N(ee))},[Re,d,N,S]),ae=ut(()=>j?{...l,paymentMethodTypes:[j]}:null,[j,l]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:i.map(ee=>{let pe=le===ee,Y=G===ee,K=G!==null&&G!==ee||le!=null&&le!==ee;return ze(fl.Fragment,{children:[u(_l,{method:ee,themeId:de,submitting:Y,disabled:K,highlighted:pe,hasNextStep:Ii(ee),onClick:()=>fe(ee),backgroundColor:f?.backgroundColor,borderColor:f?.borderColor,textColor:f?.textColor,borderRadius:f?.borderRadius,fontFamily:f?.fontFamily}),!S&&j===ee&&ae&&c&&u(rr,{stripe:c,options:ae,children:u(ma,{method:ee,sessionId:e,email:n,billingName:a,billingApiUrl:r,onTokenizedBody:b,onErrorChange:x,onDecline:w,onCancel:()=>ce(null),runBeforeButtonClick:v,onButtonClick:g,isProcessing:d,submitButtonColor:h,submitButtonBorderRadius:k,submitButtonStyle:E})},ee)]},ee)})})}function xl({sessionId:e,nonce:t,billingApiUrl:n,email:a,userId:r,onComplete:i,onError:c,onDecline:l,onTokenizedBody:b,firstName:x,lastName:g,chv:w,className:v,isProcessing:R,error:d,onErrorChange:h,showPayPal:k=!0,showStripe:E=!0,enabledPaymentMethods:f,enabledPaymentMethodCountries:de,showApplePay:S=!0,showGooglePay:le=!0,layout:Z="default",theme:F,buttonsTheme:G,buttonsStyles:W,appearance:oe,cardButtonContent:N,cardBackButtonContent:j,cardTitleContent:ce,showSecurityFooter:Re,onButtonClick:fe,onBeforeButtonClick:ae,enableAVS:ee,cardFieldOrder:pe,cardPreFormSlot:Y,avsLayout:K="row",country:Ee,zip:ge,addressLine1:te,addressLine2:q,city:C,state:ie,onCountryChange:$e,onZipChange:Oe,avsCheck:me,checkoutType:T,checkoutLayout:ue,totalAmount:J=0,currency:_e="usd",initialCardOpen:mt=!1,directPaypal:Je,isSubscription:yt=!1,session:A,dataAttachmentPending:X=!1,debug:tt=!1}){let qe=wn(),ft=ta(),Ne=gl(yn),We=X||Ne.claimPending===!0,Xt=Po(),[Ge,Qt]=we(!1),[I,be]=we(null),[Ye,xe]=we(Ee??"US"),[St,je]=we(ge??""),[Ve,nt]=we(te??""),[Xe,In]=we(q??""),[at,Hn]=we(C??""),[Wt,Pn]=we(ie??""),[Zt,ir]=we({}),Bt=De(ge??""),kt=De(Ee??"US"),en=De(te??""),tn=De(q??""),Ft=De(C??""),Dt=De(ie??""),wt=De({});pt(()=>{let s=(L,H,se,V,Se)=>{if(wt.current[L])return;let Ae=H?.trim();!Ae||Ae===se.current||(se.current=Ae,V(Ae),Se?.(Ae))};s("country",Ee,kt,xe,$e),s("zip",ge,Bt,je,Oe),s("addressLine1",te,en,nt),s("addressLine2",q,tn,In),s("city",C,Ft,Hn),s("state",ie,Dt,Pn)},[Ee,ge,te,q,C,ie,$e,Oe]);let ne=ut(()=>il(ee),[ee]),Kn=ne!==null,D=ut(()=>ca(A),[A]),it=!!A?.vault?.html,Lt=!!A?.gateways?.pcivault,Be=!!(A?.gateways?.stripe?.enabledPaymentMethods??f)?.includes("card"),st=it||Be||Lt,He=!!(E&&st&&qe&&e),[_n,xn]=we(()=>Z!=="buttons"||mt?e??null:null),[zn,Wn]=we(0),Tn=Z!=="buttons"||mt||!!e&&_n===e,rt=ut(()=>!qe||!He||!e||!Tn?null:qe.cardCapture({sessionId:e,captureMethod:A?.captureMethod}),[qe,He,e,Tn,A?.captureMethod]),zt=ut(()=>{let s=Ye,L=ne?Le(ne.postal_code,s):!1;return El(s,St,L)},[ne,Ye,St]),{avsInvalid:dn,invalidAvsFields:Pt}=ut(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!He||!ne)return{avsInvalid:!1,invalidAvsFields:s};let L=Ye,H=(Se,Ae)=>Le(Se,L)&&!Ae.trim(),se={line1:H(ne.address_line_1,Ve),city:H(ne.city,at),state:H(ne.state,Wt),zip:zt.empty||zt.malformed};return{avsInvalid:se.line1||se.city||se.state||se.zip,invalidAvsFields:se}},[He,ne,Ye,Ve,at,Wt,zt]),[xt,nn]=we(!1),[un,Yt]=we(!1),[Ut,$t]=we(()=>da(A?.vault)),[Te,qt]=we(mt&&st?"card":"buttons"),[gt,bn]=we(null),Yn=Te==="expanding"||Te==="card",Vt=280,jt=De(null),Ot=ke(s=>{jt.current&&clearTimeout(jt.current),jt.current=setTimeout(()=>{jt.current=null,s()},Vt)},[Vt]);pt(()=>()=>{jt.current&&clearTimeout(jt.current)},[]);let On=ke(()=>{xn(e??null),Wn(s=>s+1),qt("expanding"),Ot(()=>qt("card"))},[Ot,e]),Nn=ke(()=>{qt("collapsing"),Ot(()=>qt("buttons"))},[Ot]),rn=ke(s=>{bn(s),qt("apm-expanding"),Ot(()=>qt("apm-form"))},[Ot]),Gt=ke(()=>{qt("apm-collapsing"),Ot(()=>{qt("buttons"),bn(null)})},[Ot]);pt(()=>{Z==="buttons"&&mt&&st&&(xn(e??null),qt("card"))},[Z,mt,st,e]);let[on,Ue]=we(null),_=De(!1),z=De(null),M=De("idle"),[ve,Ce]=we(null),m=De(ve);pt(()=>{m.current=ve},[ve]);let o=n||Xt,y=d??I,B=ut(()=>Pl(F),[F]),P=ut(()=>{let s=B?.buttonsLayout??rl(G);return W?{...s,...W,cardButton:{...s.cardButton,...W.cardButton},cardFormContainer:{...s.cardFormContainer,...W.cardFormContainer},backButton:{...s.backButton,...W.backButton},backButtonIcon:{...s.backButtonIcon,...W.backButtonIcon},submitButton:{...s.submitButton,...W.submitButton},title:{...s.title,...W.title}}:s},[B,G,W]),U=oe??B?.appearance,Fe=ut(()=>ho({appearance:U,buttonsStyles:P,layout:Z}),[U,P,Z]),Qe=Ne.inlineSessionPatchProcessing??!1,Q=(R??Ge)||Qe,$=o.replace(/\/+$/,""),p=ut(()=>oa({userId:r,email:a,firstName:x,lastName:g,country:Ee,zip:ge},Zt),[r,a,x,g,Ee,ge,Zt]),O=[p.firstName,p.lastName].filter(s=>!!s?.trim()).join(" "),he=ut(()=>qe?qe.getRawProvider():null,[qe]),Ie=ut(()=>ft?ft.getRawProvider():null,[ft]),Me=J||100,vn=ut(()=>U?yl(U):null,[U]),Tr=vn?{appearance:vn}:null,Oo=ut(()=>{let s=vn??{},L=s.rules??{};return{...s,rules:{...L,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...L[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...L[".AccordionItemContents"]??{}}}}},[vn]),ro=ut(()=>{let s=Pi(J);return{...s,currency:_e.toLowerCase(),paymentMethodCreation:"manual",...s.mode==="payment"?{captureMethod:"manual"}:{},...Tr}},[J,_e,Tr]),Fa=ut(()=>({mode:"payment",amount:Me,currency:_e.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Tr}),[Me,_e,Tr]),ye=ke(s=>{be(s),h?.(s)},[h]);pt(()=>{!He||!rt||rt.setCardFieldOrder?.(pe??null,ne==null)},[He,rt,pe,ne]),pt(()=>{(Te==="expanding"||Te==="collapsing"||Te==="apm-expanding"||Te==="apm-collapsing")&&ye(null)},[Te,ye]);let pn=ke((s,L,H)=>{l?.(Et(s,L,H))},[l]),sr=ke((s,L,H)=>{let se=H?.popupBlocked??$n(L),V=kl(s,se),Se=tr(H?.code)??An(L)??"external_payment_method_failed",Ae=new kn(V,"api_error",{code:"external_payment_method_failed",param:s});Ue(null),Z==="buttons"&&(qt("buttons"),bn(null)),ye(V),c?.(Ae),console.error("[FloPay] External payment method failed:",{method:s,code:Se,popupBlocked:se})},[Z,c,ye]);pt(()=>{if(!He||!e){$t(null);return}let s=da(A?.vault);if(s){$t(s);return}if(!Tn){$t(null);return}$t(null);let L=!0;return new qn($).getVaultCapture(e,t).then(H=>{if(!L)return;let se=da(H);se?$t(se):ye("Failed to load the secure card form.")}).catch(H=>{L&&ye(H instanceof Error?H.message:"Failed to load the secure card form.")}),()=>{L=!1}},[He,Tn,zn,e,A?.vault?.html,A?.vault?.messageToken,A?.vault?.expectedOrigin,$,t,ye]);let Cn=De({onComplete:i,onError:c,updateError:ye,emitDecline:pn,resolvedAccount:p,avsConfig:ne,avsCheckProp:me,sessionId:e,nonce:t,baseUrl:$,captureMethod:A?.captureMethod,paymentId:A?.paymentId,authorizationExpiresAt:A?.authorizationExpiresAt});Cn.current={onComplete:i,onError:c,updateError:ye,emitDecline:pn,resolvedAccount:p,avsConfig:ne,avsCheckProp:me,sessionId:e,nonce:t,baseUrl:$,captureMethod:A?.captureMethod,paymentId:A?.paymentId,authorizationExpiresAt:A?.authorizationExpiresAt};let No=De(!1),ds=ke(()=>{let{resolvedAccount:s,avsConfig:L,avsCheckProp:H}=Cn.current,se=kt.current||s.country||"US",V=L?Le(L.state,se):!1,Se=L?Le(L.address_line_1,se):!1,Ae=L?Le(L.postal_code,se):!1,lt=L?Le(L.city,se):!1,vt=L?Le(L.address_line_2,se):!1,Ze=Se&&!V&&Ae?Ei(se,(Bt.current??"").trim()):null,Rt=V?Dt.current:Ze;return{accountData:{userId:s.userId??"",email:s.email??"",firstName:s.firstName??"",lastName:s.lastName??"",...Ae&&Bt.current?{zip:Bt.current}:{},...lt&&Ft.current?{city:Ft.current}:{},...Rt?{state:Rt}:{},...Se&&en.current?{addressLine1:en.current}:{},...vt&&tn.current?{addressLine2:tn.current}:{},country:se},...H!==void 0?{avsCheck:H}:{},...L?{avsConfig:{country:Le(L.country,se),postal_code:Ae,address_line_1:Se,address_line_2:vt,city:lt,state:V}}:{}}},[]),Da=De(We);Da.current=We,pt(()=>{We||y!==Ti||Cn.current.updateError(null)},[We,y]),pt(()=>{!He||!rt||rt.setSubmitGate?.(dn||We)},[He,rt,dn,We]),pt(()=>{if(!He||!rt)return;No.current=!1;let s=!1,L=rt.on("submitting",()=>{nn(!0),z.current&&clearTimeout(z.current),M.current="validation-window",z.current=setTimeout(()=>{z.current=null,M.current==="validation-window"&&(M.current="processing")},bl),Ue("processing");let{baseUrl:Ae,sessionId:lt,nonce:vt,updateError:Ze,onError:Rt}=Cn.current;!lt||!vt||new qn(Ae).patchAccountSnapshot(lt,vt,ds(),{telemetryMode:"best_effort"}).catch(Pe=>{if(!vl(Pe))return;let Tt=Pe instanceof Error?Pe.message:"Please check your billing address and try again.";Ze(Tt),M.current="idle",Ue(null),Rt?.(Pe instanceof kn?Pe:new kn(Tt,"api_error"))})}),H=rt.on("complete",async Ae=>{if(hr(Ae.sessionId??Cn.current.sessionId),M.current="terminal",Ue("success"),await new Promise(Ze=>setTimeout(Ze,fn)),No.current)return;No.current=!0;let lt=Cn.current,vt=ca(lt)||Ae.outcome==="authorized";Cn.current.onComplete?.(vt?{status:"authorized",paymentIntentId:Ae.intentId,paymentId:Ae.paymentId??lt.paymentId,sessionId:Ae.sessionId??lt.sessionId,authorizationExpiresAt:Ae.authorizationExpiresAt??lt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ae.intentId,checkoutMethod:"card"})}),se=rt.on("decline",async Ae=>{let{updateError:lt,emitDecline:vt}=Cn.current,Ze=Ae.message??"Your payment was declined. Please try another card or contact your bank.";M.current="terminal",lt(Ze),Ue("error");let Rt=Ae.failureOutcome??nl(Ae.declineReason)??"authorization_declined";vt("card",Ze,{code:Rt,declineCode:Rt}),await new Promise(Pe=>setTimeout(Pe,Jt)),!s&&(M.current="idle",Ue(null))}),V=rt.on("error",async Ae=>{let{updateError:lt,onError:vt}=Cn.current,Ze=Ae.message??"There was a problem processing your payment. Please try again.";M.current="terminal",lt(Ze),Ue("error"),vt?.(new kn(Ze,"api_error",{code:Ae.failureOutcome??"capture_failed"})),await new Promise(Rt=>setTimeout(Rt,Jt)),!s&&(M.current="idle",Ue(null))}),Se=rt.on("blocked",()=>{if(!Da.current){nn(!0);return}Cn.current.updateError(Ti)});return()=>{s=!0,z.current&&(clearTimeout(z.current),z.current=null),M.current="idle",L(),H(),se(),V(),Se()}},[He,rt]);let Sn=!!Je?.clientId,Mr=Array.isArray(f),oo=Mr&&f.length>0,us=Mr&&f.includes("paypal"),{expressMethods:ao,paymentElementMethods:Ar}=ut(()=>ml(f,{excludePaypal:Sn}),[f,Sn]),La=Sn||!!ft,ps=ut(()=>La?ao.filter(s=>s!=="paypal"):ao,[ao,La]),ms=ut(()=>{let s=[];return S&&s.push("apple_pay"),le&&s.push("google_pay"),s},[S,le]),io=Mr?ps:ms,ys=E&&io.length>0,Uo=Kn?Ye:Ee,so=ut(()=>{let s=Uo?.trim().toUpperCase();return s?de?Ar.filter(L=>{let H=de[L];return!H||H.length===0||H.includes(s)}):dl(Ar,Uo):Ar},[Ar,Uo,de]),$o=ut(()=>({mode:"payment",amount:Me,currency:_e.toLowerCase(),paymentMethodCreation:"manual",appearance:Oo}),[Me,_e,Oo]),[za,Oa]=we("loading"),[Na,Ua]=we("loading"),[$a,qa]=we("loading"),[fs,qo]=we(!1),[Va,Vo]=we("loading"),[lo,gs]=we();pt(()=>{gs(bi())},[]);let ja=k&&(Sn||(Mr?us:lo===!1)),Ha=E&&ys,Br=!We&&ja&&Sn,Ka=Va==="retrying"||Va==="exhausted",Fr=!We&&ja&&!!Ie&&(!Sn||Ka),Dr=!We&&Ha&&!!he,Lr=!We&&E&&oo&&so.length>0&&!!he,hs=Br&&!Ka?fs:Fr&&Bi(za),Ps=Dr&&Bi(Na),bs=Lr&&$a!=="load_error",Wa=s=>s==="loading"||s==="ready",Ya=Br||Fr&&Wa(za)||Dr&&Wa(Na)||Lr&&$a!=="load_error",co=De(!1);pt(()=>{if(!co.current){if(!E&&!k){co.current=!0;let s=new kn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(s),ye(s.message)}else if(!E&&k&&!Sn&&!Ie){co.current=!0;let s=new kn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(s),ye(s.message)}else if(lo!==void 0&&!We&&!st&&!Ya){co.current=!0;let s=new kn("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"});c?.(s),ye(s.message)}}},[E,k,Sn,Ie,lo,We,st,Ya,c,ye]);let Ga=De(!1);pt(()=>{if(Ga.current||!oo)return;let s=[];S!==!0&&s.push("showApplePay"),le!==!0&&s.push("showGooglePay"),s.length!==0&&(Ga.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.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.`))},[oo,S,le]);let Ja=ke((s,L)=>Ne.applyInlineSessionPatch?Ne.applyInlineSessionPatch(s).then(H=>({error:null,sessionId:H.sessionId||e,nonce:H.session?.clientSecret||t})).catch(H=>{let se=Ai(L,H);return ye(se.message),c?.(se),{error:se,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ne.applyInlineSessionPatch,t,c,e,ye]),mn=ke(async s=>{if(!ae)return{proceed:!0};try{let L=await ae({method:s,sessionId:e||void 0,createSession:Ne.inlineSessionDraft});if(L===!1)return{proceed:!1};if(L&&typeof L=="object"){L.account&&ir(se=>({...se??{},...L.account}));let H=await Ja(L,s);return H.error?{proceed:!1,accountPatch:L.account}:{proceed:!0,accountPatch:L.account,sessionId:H.sessionId,nonce:H.nonce}}return{proceed:!0}}catch(L){let H=Ai(s,L);return ye(H.message),c?.(H),{proceed:!1}}},[Ja,Ne.inlineSessionDraft,ae,c,e,ye]),Xa=ke(async(s,L)=>{if(_.current)return;_.current=!0,Qt(!0),Ue("processing"),ye(null);let H=L?.sessionId??e,se=L?.nonce??t,V=oa(p,L?.accountPatch),Se=L?.completionPaymentMethodId??Kr(s),Ae=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s;try{let vt=await new qn($).processPayment(V.userId??"",{sessionId:H,nonce:se,tokenizedData:Ae,accountData:{userId:V.userId??"",email:V.email??"",firstName:V.firstName??"",lastName:V.lastName??"",...ne?(()=>{let Pe=kt.current,Tt=Le(ne.state,Pe),Kt=Le(ne.address_line_1,Pe),Qn=Le(ne.postal_code,Pe),Zn=Kt&&!Tt&&Qn?Ei(Pe,(Bt.current??"").trim()):null,Mt=Tt?Dt.current:Zn;return{country:Pe,...Qn&&Bt.current?{zip:Bt.current}:{},...Le(ne.city,Pe)&&Ft.current?{city:Ft.current}:{},...Mt?{state:Mt}:{},...Kt&&en.current?{addressLine1:en.current}:{},...Le(ne.address_line_2,Pe)&&tn.current?{addressLine2:tn.current}:{}}})():{}},chv:w,avsCheck:me??!1,checkoutType:T,checkoutLayout:ue,avsConfig:ne?{country:Le(ne.country,kt.current),postal_code:Le(ne.postal_code,kt.current),address_line_1:Le(ne.address_line_1,kt.current),address_line_2:Le(ne.address_line_2,kt.current),city:Le(ne.city,kt.current),state:Le(ne.state,kt.current)}:void 0});if(vt.ok){let Pe=vt.status===204?null:await vt.json().catch(()=>null),Tt=ca(A)||Pe?.status==="authorized";hr(H),Ue("success"),Ce(null),await new Promise(Kt=>setTimeout(Kt,fn)),i?.(Tt?{status:"authorized",...typeof Pe?.paymentId=="string"?{paymentId:Pe.paymentId}:A?.paymentId?{paymentId:A.paymentId}:{},sessionId:typeof Pe?.sessionId=="string"?Pe.sessionId:H,...typeof Pe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Pe.authorizationExpiresAt}:A?.authorizationExpiresAt?{authorizationExpiresAt:A.authorizationExpiresAt}:{},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Se,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Se,checkoutMethod:s.isPaypal?"paypal":"card"});return}let Ze=await vt.json().catch(()=>null);if(Ze?.type==="paypal_redirect_required"){let Pe=Ze.threeDSecureToken,Tt=Ze.paymentMethodId||s.id||"";if(!qe||!Pe){Ue("error"),ye("PayPal authorization required but no token provided.");return}try{let Kt=ft?.getRawProvider();if(!Kt){ye("PayPal is not available.");return}let Qn={return_url:window.location.href};Tt&&(Qn.payment_method=Tt);let{error:Zn}=await Kt.confirmPayment({clientSecret:Pe,confirmParams:Qn,redirect:"if_required"});if(Zn){Ue("error");let Mt=Zn.message??"PayPal payment failed.";ye(Mt),pn("paypal",Mt,{code:Zn.code})}}catch(Kt){Ue("error"),ye(Kt instanceof Error?Kt.message:"PayPal authorization failed.")}return}if(Ze?.type==="paypal_direct_required"){let Pe=Ze.orderId;if(!Pe){Ue("error"),ye("PayPal retry required but no order id provided.");return}let Tt=m.current?.attempts??0;if(Tt>=2){Ue("error"),ye("PayPal payment could not be completed after multiple attempts."),pn("paypal","paypal_direct_required retry limit exceeded");return}qo(!1),Vo("loading"),Ce({orderId:Pe,attempts:Tt+1}),Ue(null);return}Ue("error");let Rt=Ze?.message??"Payment failed. Please try again.";ye(Rt),pn(s.isPaypal?"paypal":"card",Rt,{code:Ze?.code??Ze?.gatewayErrorCode,declineCode:Ze?.declineCode??Ze?.gatewayDeclineReason}),await new Promise(Pe=>setTimeout(Pe,Jt))}catch(lt){Ue("error"),ye(lt instanceof Error?lt.message:"An unexpected error occurred"),await new Promise(vt=>setTimeout(vt,Jt))}finally{Qt(!1),Ue(null),_.current=!1}},[$,e,t,p,O,w,qe,ft,A,i,c,ye,pn]),an=ke((s,L)=>{b?b(s):Xa(s,L)},[b,Xa]),Qa=De(!1);pt(()=>{if(typeof window>"u"||Qa.current)return;let s=new URLSearchParams(window.location.search),L=s.get("payment_intent"),H=s.get("payment_intent_client_secret"),se=s.get("redirect_status");if(!L||!H)return;let V=Rt=>{let Pe=localStorage.getItem(Rt);if(!Pe)return null;try{return JSON.parse(Pe)}catch{return localStorage.removeItem(Rt),null}},Se=V(Rn)??V(xi),Ae;if(Se?.clientSecret){if(Se.clientSecret!==H)return;Ae={...Se.accountPatch?{accountPatch:Se.accountPatch}:{},...Se.sessionId?{sessionId:Se.sessionId}:{},...Se.nonce?{nonce:Se.nonce}:{}}}else if(Se?.sessionId&&Se.sessionId!==e)return;Qa.current=!0,localStorage.removeItem(Rn),localStorage.removeItem(xi);let lt=new URL(window.location.href);lt.searchParams.delete("payment_intent"),lt.searchParams.delete("payment_intent_client_secret"),lt.searchParams.delete("redirect_status"),window.history.replaceState({},"",lt.toString());let vt=Se?.paymentMethodType??Se?.tokenType??"card",Ze="card";(async()=>{let Rt=qe?.getRawProvider();if(!Rt){let Mt="Payment is not available \u2014 please refresh and try again.";ye(Mt),pn(Ze,Mt);return}if(se==="failed"){let Mt="Payment was declined. Please try again.";ye(Mt),pn(Ze,Mt);return}let{paymentIntent:Pe,error:Tt}=await Rt.retrievePaymentIntent(H);if(Tt){let Mt=Tt.message??"Failed to retrieve payment status.";ye(Mt),pn(Ze,Mt,{code:Tt.code});return}let Kt=Pe?.status,Qn=Co(Kt);if(!Pe||!Qn){let Mt=Kt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ye(Mt),pn(Ze,Mt,{code:Kt??"missing_payment_intent"});return}let Zn=typeof Pe.payment_method=="string"?Pe.payment_method:Pe.payment_method?.id;an({id:Zn??Se?.paymentMethodId??Se?.tokenId??Pe.id,type:"card",threeDSecureActionResultTokenId:Pe.id,gateway:Se?.gateway??"stripe",paymentMethodType:vt},Ae)})()},[e,an,qe,ye,pn]);let jo=ke(s=>{s.preventDefault()},[]);if(!(qe!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let zr=Z==="buttons",Ht=U?.variables,vs=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ho=Ht?.colorBackground,Cs=Ho&&!vs.has(Ho)?Ho:void 0,Or=P.cardInputBorder??(zr?"#e5e7eb":"#A4A4FF"),Ko=Ht?.colorDanger??"#dc2626",Gn=s=>xt&&s?Ko:Or,uo=(zt.malformed||zt.empty)&&(un||xt),Ss=uo?Ko:Gn(Pt.zip),Wo=P.cardFormContainer?.backgroundColor??Cs??(zr?"white":"#EDEDFF"),Nr=P.cardInputBackground??Ht?.colorBackground??"white",Yo=cr(j),Za=cr(ce),lr=P.nameInput,ei=P.cardInputFontSize??Il(lr?.fontSize)??Ht?.fontSizeBase??"16px",ti=typeof lr?.fontFamily=="string"?lr.fontFamily:Ht?.fontFamily??"Poppins, sans-serif",ni=ea(lr?.fontWeight)??400,ws=P.cardInputColor??(typeof lr?.color=="string"?lr.color:void 0)??Ht?.colorText??"#262833",ks=P.cardInputPlaceholderColor??"#9ca3af",bt=Ht?.borderRadius??"8px",Jn=Ht?.borderRadius??P.cardButton?.borderRadius??bt,Xn=Ht?.colorPrimary??"#4A49FF",Rs=Ht?.colorPrimaryHover??mr(Xn,.12),Go=Ht?.colorText??"#262833",ri={fontSize:ei,fontFamily:ti,fontWeight:ni,color:ws,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Es={"--flopay-input-placeholder-color":ks,"--flopay-input-font-size":ei,"--flopay-input-font-family":ti,"--flopay-input-font-weight":String(ni)},Ur=P.cardFormContainer??{},Jo=Ur.padding??(zr?"0":"1rem"),Xo=Ur.borderRadius??bt,Is=rt&&Ut?u(jr,{capture:rt,html:Ut.html,messageToken:Ut.messageToken,expectedOrigin:Ut.expectedOrigin,theme:Fe,onReady:()=>{if(!ne||typeof document>"u")return;let s=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};s();let L=0,H=window.setInterval(()=>{L+=1;let se=document.activeElement;!!se&&se.tagName==="IFRAME"&&se.id==="flopay_vault_form_iframe"?(s(),window.clearInterval(H)):L>=50&&window.clearInterval(H)},100)},onError:s=>ye(s),onValidation:s=>{let L=M.current;(L==="idle"||L==="validation-window")&&(ye(s),s&&M.current==="validation-window"&&(z.current&&(clearTimeout(z.current),z.current=null),M.current="idle",Ue(null)))}}):u("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"}),oi=ze("div",{style:{backgroundColor:Wo,borderRadius:Xo,...Ur,padding:Jo,...Es,display:"flex",flexDirection:"column"},children:[u("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${Je.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),zr&&Yn&&Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:He?-2:0},children:[Le("button",{type:"button",onClick:Nn,style:{display:"inline-flex",alignItems:"center",gap:Ko?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:P.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...P.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...P.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(ur,{content:V})]}),Za?u("div",{style:{flex:1}}):u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...P.title},children:u(qr,{content:z})})]}),!zr&&!Za&&u("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Wo,order:He?-3:0,...P.title},children:u(qr,{content:z})}),ne&&u("div",{style:{order:He?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Ye,D=(j=!1)=>({backgroundColor:Nr,border:`1px solid ${Gn(j)}`,borderRadius:bt,marginTop:"0.5rem",padding:"10px"}),H=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ri}),le=rl(i);return Le(vr,{children:[De(ne.address_line_1,i)&&u("div",{style:D(Pt.line1),children:u("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:Ve,onChange:j=>{wt.current.addressLine1=!0,Zt.current=j.target.value,nt(j.target.value)},disabled:Q,required:!0,"data-testid":"flopay-address-line1",style:H()})}),De(ne.address_line_2,i)&&u("div",{style:D(),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Xe,onChange:j=>{wt.current.addressLine2=!0,en.current=j.target.value,Rn(j.target.value)},disabled:Q,"data-testid":"flopay-address-line2",style:H()})}),(De(ne.city,i)||De(ne.state,i))&&Le("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[De(ne.city,i)&&u("div",{style:{flex:1,backgroundColor:Nr,borderTop:`1px solid ${Gn(Pt.city)}`,borderRight:`1px solid ${Gn(Pt.city)}`,borderBottom:`1px solid ${Gn(Pt.city)}`,borderLeft:`1px solid ${Gn(Pt.city)}`,padding:"10px",borderTopLeftRadius:bt,borderBottomLeftRadius:bt,...De(ne.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:bt}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:at,onChange:j=>{wt.current.city=!0,Ft.current=j.target.value,Hn(j.target.value)},disabled:Q,required:!0,"data-testid":"flopay-city",style:H()})}),De(ne.state,i)&&u("div",{style:{flex:1,backgroundColor:Nr,border:`1px solid ${Gn(Pt.state)}`,padding:"10px",borderTopRightRadius:bt,borderBottomRightRadius:bt,...De(ne.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:bt}},children:le?Le("select",{id:"flopay-billing-state",name:"billing-state",value:Wt,onChange:j=>{wt.current.state=!0,Dt.current=j.target.value,yn(j.target.value)},disabled:Q,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...H(),cursor:"pointer"},children:[u("option",{value:"",children:Ri(i)}),le.map(j=>u("option",{value:j.code,children:j.name},j.code))]}):u("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Ri(i),autoComplete:"billing address-level1",value:Wt,onChange:j=>{wt.current.state=!0,Dt.current=j.target.value,yn(j.target.value)},disabled:Q,required:!0,"data-testid":"flopay-state",style:H()})})]}),(De(ne.country,i)||De(ne.postal_code,i))&&Le("div",{style:{display:"flex",flexDirection:ae==="column"?"column":"row",gap:ae==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[De(ne.country,i)&&u("div",{style:{flex:ae==="row"?1:void 0,backgroundColor:Nr,borderTop:`1px solid ${Or}`,borderRight:`1px solid ${Or}`,borderBottom:`1px solid ${Or}`,borderLeft:`1px solid ${Or}`,padding:"10px",...ae==="row"&&De(ne.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:bt,borderBottomLeftRadius:bt,borderRight:"none"}:{borderRadius:bt}},children:u("select",{id:"flopay-billing-country",name:"billing-country",value:Ye,onChange:j=>{wt.current.country=!0,kt.current=j.target.value,Ee(j.target.value),$e?.(j.target.value),Dt.current="",yn("")},disabled:Q,autoComplete:"billing country","data-testid":"flopay-country",style:{...H(),cursor:"pointer"},children:ol.map(j=>Le("option",{value:j.code,children:[j.flag," ",j.name]},j.code))})}),De(ne.postal_code,i)&&u("div",{style:{flex:ae==="row"?1:void 0,backgroundColor:Nr,border:`1px solid ${Cs}`,padding:"10px",...ae==="row"&&De(ne.country,i)?{borderRadius:"0",borderTopRightRadius:bt,borderBottomRightRadius:bt}:{borderRadius:bt}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:da(Ye),autoComplete:"billing postal-code",value:St,onChange:j=>{wt.current.zip=!0,Bt.current=j.target.value,je(j.target.value),ze?.(j.target.value)},onBlur:()=>Yt(!0),disabled:Q,required:zt.required,"aria-invalid":co||void 0,"aria-describedby":co?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:H()})})]}),co&&u("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:jo,...ri,fontSize:"0.75rem"},children:zt.empty?`${da(i)} is required`:kl(i)})]})})()}),He&&Te&&u("div",{style:{order:-2,width:"100%"},children:Te}),He&&Es,y&&u(yr,{margin:"0.75rem 0",styleOverride:P.errorBanner,children:y})]}),uo={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"},ai=i=>tt?!w||!Pn?u("pre",{"data-testid":i,style:uo,children:"FloPay/DirectPayPal-debug - not enabled"}):u("pre",{"data-testid":i,style:uo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${w}`,` directPaypalConfigured=${Pn}`,` inAppBrowserDetected=${String(so)}`,` shouldRenderDirectPayPal=${Br}`,` shouldRenderStripePayPal=${Fr}`,` hasPaypalStripeInstance=${!!we}`].join(`
39
- `)}):null,ii=i=>tt?!R||!ye?u("pre",{"data-testid":i,style:uo,children:"FloPay/Stripe-debug - not enabled"}):u("pre",{"data-testid":i,style:uo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${R}`,` currency=${Re}`,` amountInCents=${_e}`,` enabledPaymentMethods: ${JSON.stringify(f??[])}`,` enabledPaymentMethodsProvided=${Mr}`,` hasEnabledMethods=${ro}`,` expressMethods: ${JSON.stringify(oo)}`,` walletExpressMethods: ${JSON.stringify(ao)}`,` paymentElementMethods: ${JSON.stringify(Ar)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(io)}`,` hasStripeInstance=${!!ye}`,` shouldRenderWallets=${Dr}`,` shouldRenderPaymentElement=${Lr}`].join(`
40
- `)}):null,si=Ie==="apm-expanding"||Ie==="apm-form"||Ie==="apm-collapsing",po=Ie==="apm-expanding"?`flopay-card-enter ${Vt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ie==="apm-collapsing"?`flopay-card-exit ${Vt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,mo=gt?{...No,paymentMethodTypes:[gt]}:null;if(Z==="buttons"){let i=Ie==="buttons"||Ie==="expanding"||Ie==="apm-expanding",D=Ie==="expanding"||Ie==="card"||Ie==="collapsing",H=U===void 0?{boxSizing:"border-box",height:Ro,padding:"0 1rem"}:{padding:"0.9rem 1rem"},le=Ie==="expanding"||Ie==="apm-expanding"?`flopay-buttons-exit ${Vt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ie==="collapsing"||Ie==="apm-collapsing"?`flopay-buttons-enter ${Vt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,j=Ie==="expanding"?`flopay-card-enter ${Vt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ie==="collapsing"?`flopay-card-exit ${Vt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Le("form",{onSubmit:qo,className:v,style:{position:"relative"},children:[u(ca,{}),rn&&u(Cn,{status:rn,errorMessage:y,authorized:F}),Le("div",{style:{display:"grid"},children:[Le("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!le?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!le?Cl:{},...le?{animation:le,pointerEvents:"none"}:{}},children:[ai("flopay-direct-paypal-gate-debug"),ii("flopay-stripe-gate-debug"),Br&&Je&&Le(vr,{children:[Pe&&u("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."}),u(ko,{sessionId:e,nonce:t,billingApiUrl:o,email:p.email,clientId:Je.clientId,environment:Je.environment,currency:Re.toUpperCase(),isSubscription:yt,onTokenizedBody:on,onComplete:s,onErrorChange:pe,onDecline:l,onTechnicalFailure:sr,onButtonClick:ee,runBeforeButtonClick:un,isProcessing:Q,onLoadStateChange:Uo,onInitializationStateChange:$o,session:A??null,existingOrderId:Pe?.orderId,debug:tt},Pe?.orderId??"fresh")]}),Fr&&u(rr,{stripe:we,options:Fa,children:u(Fi,{sessionId:e,nonce:t,email:p.email,billingApiUrl:o,onTokenizedBody:on,onErrorChange:pe,isProcessing:Q,onButtonClick:ee,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:un,onLoadStateChange:Oa,placeholderBorderRadius:Jn})}),Dr?u(rr,{stripe:ye,options:no,children:u(Di,{sessionId:e,nonce:t,email:p.email,billingApiUrl:o,intentKind:J>0?"payment":"setup",expressMethods:ao,onTokenizedBody:on,onErrorChange:pe,onButtonClick:ee,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:un,onLoadStateChange:Ua,placeholderBorderRadius:Jn})}):Ha?u("div",{style:{height:Ro,borderRadius:Jn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Lr&&u(Li,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,paymentElementMethods:io,stripeInstance:ye,paymentElementBaseOptions:No,onTokenizedBody:on,onErrorChange:pe,onButtonClick:ee,onDecline:l,runBeforeButtonClick:un,onLoadStateChange:qa,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:P.submitButton,onExpandApm:nn,expandedApmMethod:gt,themeId:L,buttonAppearance:{backgroundColor:P.cardButton?.backgroundColor,borderColor:P.cardInputBorder,textColor:P.cardButton?.color,borderRadius:Jn}}),He&&u("button",{type:"button",onClick:async()=>{Q||!(await un("card")).proceed||(ee?.("card"),On())},disabled:Q,style:{width:"100%",...H,...P.cardButton,...fa({themeBundle:B,resolvedPrimaryColor:Xn,resolvedBorderRadius:bt,submitButtonStyle:P.submitButton,explicitPrimaryColor:Ht?.colorPrimary}),fontSize:P.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Q?"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?.6:1},onMouseEnter:ve=>{!Q&&(B||Ht?.colorPrimary)&&(ve.currentTarget.style.backgroundColor=ks)},onMouseLeave:ve=>{(B||Ht?.colorPrimary)&&(ve.currentTarget.style.backgroundColor=Xn)},onMouseDown:ve=>{ve.currentTarget.style.transform="scale(0.985)"},onMouseUp:ve=>{ve.currentTarget.style.transform="scale(1)"},children:u(dr,{content:U})}),y&&Ie==="buttons"&&u(yr,{margin:"0.25rem 0",styleOverride:P.errorBanner,children:y})]}),He&&D&&u("div",{style:{gridArea:"1 / 1",...j?{animation:j}:{},...Ie==="collapsing"?{pointerEvents:"none"}:{}},children:oi}),R&&si&&gt&&mo&&ye&&u("div",{style:{gridArea:"1 / 1",...po?{animation:po}:{},...Ie==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Ho,borderRadius:Go,...Ur,padding:Yo},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:Ko?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:P.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...P.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...P.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(ur,{content:V})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:Wo,paddingRight:80,...P.title},children:`Pay with ${Cr(gt)}`})]}),u(rr,{stripe:ye,options:mo,children:u(ua,{method:gt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,onTokenizedBody:on,onErrorChange:pe,onDecline:l,onCancel:Gt,runBeforeButtonClick:un,onButtonClick:ee,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:P.submitButton,errorText:y})},gt)]})})]})]})}return si&&gt&&mo&&ye&&R?Le("form",{onSubmit:qo,className:v,style:{position:"relative"},children:[u(ca,{}),rn&&u(Cn,{status:rn,errorMessage:y,authorized:F}),u("div",{style:{...po?{animation:po}:{},...Ie==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Ho,borderRadius:Go,...Ur,padding:Yo},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:Ko?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:P.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...P.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...P.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(ur,{content:V})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:Wo,paddingRight:80,...P.title},children:`Pay with ${Cr(gt)}`})]}),u(rr,{stripe:ye,options:mo,children:u(ua,{method:gt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,onTokenizedBody:on,onErrorChange:pe,onDecline:l,onCancel:Gt,runBeforeButtonClick:un,onButtonClick:ee,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:P.submitButton,errorText:y})},gt)]})})]}):Le("form",{onSubmit:qo,className:v,style:{position:"relative"},children:[u(ca,{}),rn&&u(Cn,{status:rn,errorMessage:y,authorized:F}),Le("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ai("flopay-direct-paypal-gate-debug-default"),ii("flopay-stripe-gate-debug-default"),Br&&Je&&Le(vr,{children:[Pe&&u("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."}),u(ko,{sessionId:e,nonce:t,billingApiUrl:o,email:p.email,clientId:Je.clientId,environment:Je.environment,currency:Re.toUpperCase(),isSubscription:yt,onTokenizedBody:on,onComplete:s,onErrorChange:pe,onDecline:l,onTechnicalFailure:sr,onButtonClick:ee,runBeforeButtonClick:un,isProcessing:Q,onLoadStateChange:Uo,onInitializationStateChange:$o,session:A??null,existingOrderId:Pe?.orderId,debug:tt},Pe?.orderId??"fresh")]}),Fr&&u(rr,{stripe:we,options:Fa,children:u(Fi,{sessionId:e,nonce:t,email:p.email,billingApiUrl:o,onTokenizedBody:on,onErrorChange:pe,isProcessing:Q,onButtonClick:ee,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:un,onLoadStateChange:Oa,placeholderBorderRadius:Jn})}),Dr&&u(rr,{stripe:ye,options:no,children:u(Di,{sessionId:e,nonce:t,email:p.email,billingApiUrl:o,intentKind:J>0?"payment":"setup",expressMethods:ao,onTokenizedBody:on,onErrorChange:pe,onButtonClick:ee,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:un,onLoadStateChange:Ua,placeholderBorderRadius:Jn})}),Lr&&u(Li,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,paymentElementMethods:io,stripeInstance:ye,paymentElementBaseOptions:No,onTokenizedBody:on,onErrorChange:pe,onButtonClick:ee,onDecline:l,runBeforeButtonClick:un,onLoadStateChange:qa,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:P.submitButton,themeId:L,onExpandApm:nn,expandedApmMethod:gt,buttonAppearance:{backgroundColor:P.cardButton?.backgroundColor,borderColor:P.cardInputBorder,textColor:P.cardButton?.color,borderRadius:Jn}})]}),He&&(hs||gs||Ps)&&Le("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),u("span",{children:"or pay with card"}),u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),He&&oi]})}import{loadFloPay as Vi,PaymentAPI as Hi}from"@flopay/js";import{classifyPaymentRejection as xl,FloPayError as ot,isAuthorizationOnlySession as Tl,isSetupIntentClientSecret as Ml,normalizeCheckoutFailureOutcome as ji}from"@flopay/shared";var Xr="card";async function Al(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:a,error:r}=await e.retrievePaymentIntent(t);return{error:r,intent:a??null}}async function Bl(e,t,n,a){if(a){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:c??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 Pa(e,t){return Object.assign(e,{checkoutMethod:t})}function An(e,t){let n=e instanceof ot?e:new ot(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 Jr(e,t){try{return await e()}catch(n){throw An(n,t)}}function Ki(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 Fl(e){return e.status==="succeeded"||e.status==="declined"}async function Wi(e){if(typeof document>"u"||typeof window>"u")throw new ot("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new ot("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,a=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,s=async()=>{let g=new AbortController,S=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",S);let v=window.setTimeout(()=>g.abort(),a);try{let k=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!k.ok)return{status:"unknown"};let d=await k.json().catch(()=>null);return Dl(d)}catch{return{status:"unknown"}}finally{window.clearTimeout(v),e.signal?.removeEventListener("abort",S)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.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 b=document.createElement("iframe");b.setAttribute("title","Card authentication"),b.setAttribute("allow","payment"),b.tabIndex=0,b.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(";"),b.src=e.nextActionRedirectUrl,l.appendChild(b),document.body.appendChild(l),b.focus();let x=null;try{x=new URL(e.billingApiUrl,window.location.href).origin}catch{x=null}try{let g=await new Promise((S,v)=>{let k=!1,d=0,h=0,w=0,R=!1,f=()=>{window.clearTimeout(d),window.clearInterval(h),window.clearTimeout(w),window.removeEventListener("message",Z),b.removeEventListener("load",E),e.signal?.removeEventListener("abort",re)},de=async()=>{if(!(k||R)){R=!0;try{let L=await s();if(k||!Fl(L))return;k=!0,f(),S(L)}finally{R=!1}}},E=()=>{window.clearTimeout(w),w=window.setTimeout(()=>{de()},250)},re=()=>{k||(k=!0,f(),v(new ot("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Z=L=>{if(L.source!==b.contentWindow||x&&L.origin!==x)return;let Y=L.data;!Y||typeof Y!="object"||Y.source!=="flopay-vault-3ds-return"||k||(k=!0,f(),S(null))};d=window.setTimeout(()=>{k||(k=!0,f(),v(new ot("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),h=window.setInterval(()=>{de()},n),b.addEventListener("load",E),window.addEventListener("message",Z),e.signal?.addEventListener("abort",re),e.signal?.aborted&&re()});return g||await s()}finally{l.parentNode?.removeChild(l),c?.isConnected&&c.focus()}}function Dl(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 a=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),r=e?.message??t,s=Un(r)??r;return Pa(new ot(s,"api_error",{code:ji(e?.outcome)??ji(e?.type)??e?.gatewayErrorCode}),a)}function ha(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Io(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Ll(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 Yi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||Io(r)))return r;let a=e?.data;if(a&&typeof a=="object"){let r=a,s=[r.threeDSecureToken,r.clientSecret,r.stripeClientSecret,r.id];for(let l of s)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||Io(l)))return l;let c=r.gateways;if(c&&typeof c=="object"){let l=c.stripe;if(l&&typeof l=="object"){let b=l,x=[b.stripeClientSecret,b.clientSecret];for(let g of x)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||Io(g)))return g}}}}async function zl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:a}){let r=Yi(a,{requirePaymentIntentClientSecret:!0});if(typeof r=="string"&&r.length>0)return{type:"3ds_required",threeDSecureToken:r};if(!t)return null;try{let l=(await new Hi(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Io(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Sr({billingApiUrl:e,sessionId:t,session:n,nonce:a,tokenizedData:r,returnUrl:s,telemetry:c}){let l=e.replace(/\/+$/,""),b=t??n.id,x=a??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",S=n.customer?.email??n.accountData?.email??"",v=n.customer?.firstName??n.accountData?.firstName??"",k=n.customer?.lastName??n.accountData?.lastName??"",d=n.customer?.country??n.accountData?.country??void 0,h=n.customer?.zip??n.accountData?.zip??void 0,w=new Hi(l,c===!1?{telemetry:!1}:void 0),R=await Ll(()=>w.processPayment(g,{sessionId:b,nonce:x,tokenizedData:r,accountData:{userId:g,email:S,firstName:v,lastName:k,country:d,zip:h},returnUrl:s??ha(n)}));if(R.ok){let E=typeof R.json=="function"?await R.json().catch(()=>null):null;return Tl(n)||E?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof E?.paymentId=="string"?E.paymentId:n.paymentId,sessionId:typeof E?.sessionId=="string"?E.sessionId:b,authorizationExpiresAt:typeof E?.authorizationExpiresAt=="string"?E.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Kr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:Kr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}}let f;try{f=await R.json()}catch{throw new ot("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:R.status})}if(f?.type==="paypal_redirect_required"||f?.type==="3ds_required"){let E=Yi(f);if(!E)throw new ot("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:R.status});return{type:f.type,threeDSecureToken:E,paymentMethodId:f.paymentMethodId}}if(f?.gatewayErrorCode==="authentication_required"){let E=await zl({billingApiUrl:l,sessionId:b,nonce:x,responseJson:f});if(E)return E;throw Pa(new ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let de=new ot(f?.message??"Payment failed. Please try again.","api_error",{code:f?.code??f?.gatewayErrorCode,declineCode:f?.declineCode??f?.gatewayDeclineReason,statusCode:R.status});throw Object.assign(de,{telemetryOutcome:xl(R.status,f)})}async function _o(e,{flopay:t,paypalFlopay:n,attempt3DS:a,billingApiUrl:r,sessionId:s,session:c,returnUrl:l,telemetry:b}){let x=t?.getRawProvider();if(!x)throw An(new ot("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!a||!e.threeDSecureToken)throw Pa(new ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Ml(e.threeDSecureToken),S=null,v=e.paymentMethodId,k=await Jr(()=>Al(x,e.threeDSecureToken,g),"card");if(k){if(k.error)throw An(new ot(k.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:k.error.code}),"card");let h=k.intent;!v&&h?.payment_method&&(typeof h.payment_method=="string"?v=h.payment_method:"id"in h.payment_method&&(v=h.payment_method.id??void 0))}let d=v?await Jr(()=>Bl(x,e.threeDSecureToken,{payment_method:v,return_url:l??ha(c)??window.location.href},g),"card"):null;if(d){if(d.error)throw An(new ot(d.error.message??"3DS authentication failed.","api_error",{code:d.error.code}),"card");S=d.intent}else{let h=await Jr(()=>x.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(h.error)throw An(new ot(h.error.message??"3DS authentication failed.","api_error",{code:h.error.code}),"card");S=(g?h.setupIntent:h.paymentIntent)??null}if(S&&(S.status==="requires_capture"||S.status==="succeeded"||S.status==="processing")){let h=await Sr({billingApiUrl:r,sessionId:s,session:c,telemetry:b,tokenizedData:{id:S.id,type:"card",threeDSecureActionResultTokenId:S.id},returnUrl:l});return h.type==="success"?{...h.result,paymentIntentId:h.result.paymentIntentId??S.id,paymentMethodId:h.result.paymentMethodId??v}:_o(h,{flopay:t,paypalFlopay:n,attempt3DS:a,billingApiUrl:r,sessionId:s,session:c,returnUrl:l,telemetry:b})}throw An(new ot("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw An(new ot("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:v}=await Jr(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(v)throw An(new ot(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:S}=await Jr(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??ha(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(S)throw An(new ot(S.message??"PayPal authorization failed.","api_error",{code:S.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new ot("Unsupported payment redirect state.","api_error")}function or(e){if(e instanceof ot){let a=Un(e.message);return a&&a!==e.message?Object.assign(new ot(a,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 ot(n,"api_error")}function xo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new ot("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 To({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:a,telemetry:r}){if(!e)return{flopay:null,paypalFlopay:null};let s=!!t&&t!==e,[c,l]=await Promise.all([Vi(e,{billingApiUrl:n,locale:a,telemetry:r}),s?Vi(t,{billingApiUrl:n,locale:a,telemetry:r}).catch(b=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",b),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?s?l:c:null}}import{Fragment as kn,jsx as ie,jsxs as _t}from"react/jsx-runtime";var wr=44,Ea="flopay_checkout_saved_payment_resume",Fo=new Map,Ao=new Map;function Qi(e,t){t.settled&&t.consumers===0&&Fo.get(e)===t&&Fo.delete(e)}function Vl(e,t,n){let a=Ao.get(e);if(a&&(!a.sdkGeneratedIdempotencyKey||!t||a.sdkGeneratedIdempotencyKey===t))return a.attempt;let r=n(),s={attempt:r,sdkGeneratedIdempotencyKey:t};Ao.set(e,s);let c=()=>{Ao.get(e)===s&&Ao.delete(e)};return r.then(c,c),r}function Qr(e){return new Promise(t=>setTimeout(t,e))}function Bo(e,t,n){let a=yo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:ns,enabled:t!==!1});return a.beginCheckout(n),a}function Zr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function va(e,t,n,a,r){let s=Bo(e,t,n);s.error({errorCode:a,stage:r,paymentMethodCategory:"unknown",...r==="session_read"?{requestCategory:"session_read"}:{}}),Zr(s)}function jl(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 ka(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function Ca(e){return!e||e.data.stripe?.publishableKey?!1:!!ka(e)?.clientId}function Fn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Hl(){if(!Fn())return null;try{let e=window.sessionStorage.getItem(Ea);return e?JSON.parse(e):null}catch{return null}}function Zi(e){if(Fn())try{window.sessionStorage.setItem(Ea,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Sa(){if(Fn())try{window.sessionStorage.removeItem(Ea)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var Ia=":idempotency-key";function Kl(e){if(!Fn())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function es(e,t,n){if(Fn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(a){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",a)}}function Ra(e){if(Fn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function Wl(e){if(Fn())try{return window.sessionStorage.getItem(e+Ia)??void 0}catch{return}}function Yl(e,t){if(Fn())try{window.sessionStorage.setItem(e+Ia,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function Gl(e){if(Ra(e),!!Fn())try{window.sessionStorage.removeItem(e+Ia)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Jl(){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 a of t)e.searchParams.has(a)&&(e.searchParams.delete(a),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function ts(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 Xl(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 wa(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function _a({sessionId:e,nonce:t,createSession:n,billingApiUrl:a,telemetry:r,appearance:s,locale:c,loading:l,error:b,onComplete:x,onError:g,onDecline:S,onCountryChange:v,onZipChange:k,showPayPal:d=!0,showStripe:h=!0,enabledPaymentMethods:w,showApplePay:R=!0,showGooglePay:f=!0,debug:de=!1,layout:E,theme:re,buttonsTheme:Z,buttonsStyles:L,cardButtonContent:Y,cardBackButtonContent:K,cardTitleContent:te,showSecurityFooter:U,onButtonClick:V,onBeforeButtonClick:z,enableAVS:me,cardFieldOrder:ee,cardPreFormSlot:oe,avsLayout:G,className:ge,initialErrorMessage:Te=null,children:ae,checkoutMode:Ue,confirmLabel:Fe,renderConfirmButton:ke,onSessionCompleted:W}){let C=Ul(a),se=mn(()=>rs(re),[re]),$e=s??se?.appearance,ze=n?"embedded_checkout":"standard_checkout",ue=ae?"custom_layout":E==="buttons"?"buttons_layout":"default_layout",[T,ce]=Ct(null),[J,Re]=Ct(null),mt=Nt(null),[Je,yt]=Ct(null),A=Nt(null),[X,tt]=Ct(null),[qe,ft]=Ct(e??""),Oe=e??qe,We=n?"":Oe,[Jt,Ge]=Ct(!0),[Xt,I]=Ct(null),[he,Ye]=Ct("full"),[Ee,St]=Ct(!1),[je,Ve]=Ct(Te),[nt,Xe]=Ct(null),[Rn,at]=Ct(null),[Hn,Wt]=Ct(!1),[yn,Qt]=Ct(void 0),[ir,Bt]=Ct(""),[kt,Zt]=Ct(!1),[en,Ft]=Ct(!1),Dt=Nt(0),[wt,ne]=Ct("loading"),[Kn,F]=Ct(0),it=Nt(!1),Lt=Nt(!1),Ln=Nt(!1),Me=Nt(null),st=mn(()=>({checkoutMode:Ue??he,layout:ae?"unknown":E==="buttons"?"buttons":"embedded"}),[Ue,ae,he,E]),He=Nt(x);He.current=x;let En=Nt(g);En.current=g;let In=Nt(S);In.current=S,Bn(()=>{At(J)?.setCheckoutContext(st),Je&&Je!==J&&At(Je)?.setCheckoutContext(st)},[J,Je,st]);let zn=Nt(W);zn.current=W;let Wn=ar(_=>{ne(_),!(_!=="exhausted"||Ln.current)&&(Ln.current=!0,En.current?.(new It("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),_n=ar(()=>{ne("retrying"),F(_=>_+1)},[]);Bn(()=>{ne("loading"),F(0),Ln.current=!1},[Oe]),Bn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:ns,checkout_type:ze,checkout_layout:ue,billing_api_url:C})},[ue,ze,C]);let rt=mn(()=>n?Ut(n,!0):"",[n]),zt=mn(()=>ir===rt?yn:void 0,[yn,ir,rt]),ln=mn(()=>n?ta(n,zt):void 0,[n,zt]),Pt=Ue??ln?.checkoutMode??"full",xt=mn(()=>ln?{...ln,checkoutMode:Pt}:void 0,[ln,Pt]);Bn(()=>{Qt(void 0),Bt(rt)},[rt]),Bn(()=>{Ve(Te)},[Te]);let tn=ar((_,O,M)=>{Ke(()=>{In.current?.(Et(_,O,M))})},[Ke]),cn=ar(async(_,O)=>{Ve(null),at(null),Wt(!1),Xe("processing");let M=O?.sessionId??_.id,Pe=mt.current??A.current,be=At(Pe),m=Pe?null:Bo(C,r,st),o={log:p=>{be?be.log(p):m?.log(p)},error:p=>{be?be.error(p):m?.error(p)},terminal:p=>{be?be.terminal(p):m?.terminal(p)},performance:p=>{be?be.performance(p):m?.performance(p)},now:()=>be?.now()??m?.now()??0,elapsed:p=>be?.elapsed(p)??Math.max(0,(m?.now()??p)-p)},y=o.now(),B=!!(O?.initialAutoProcessingError||O?.initialAutoProcessingPending),P=!1,$,Ae=()=>{P||(P=!0,B=!0,$=o.now(),o.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),o.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Qe=!1,Q=()=>{Qe||(Qe=!0,o.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),o.performance({stage:"processing",durationMs:o.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}),$!==void 0&&o.performance({stage:"recovery",durationMs:o.elapsed($),durationMode:"machine",paymentMethodCategory:"saved"}))};o.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),o.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),B&&Ae();let q;try{let p=Ki(O?.initialAutoProcessingError),N;if(p)Ae(),p.type==="paypal_redirect_required"&&Me.current?.publishableKey&&Zi({sessionId:M,publishableKey:Me.current.publishableKey,paypalPublishableKey:Me.current.paypalPublishableKey}),N=await _o(p,{flopay:mt.current,paypalFlopay:A.current,attempt3DS:O?.attempt3DS,billingApiUrl:C,sessionId:M,session:_,telemetry:!1}),p.type==="paypal_redirect_required"&&Sa();else if(O?.initialAutoProcessingPending){let _e=(await new Mo(C,{telemetry:!1}).waitForCheckoutSessionCompletion(O.initialAutoProcessingPending.sessionId,{initialDelayMs:O.initialAutoProcessingPending.retryAfterMs})).data.session;if(!gr(_e))throw bo(_e);N=er(_e,M)}else{if(O?.initialAutoProcessingError)throw Vn(O.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:O.initialAutoProcessingError.checkoutMethod});if(O?.fromCreateSession)return O?.fallbackToFull&&(Ye("full"),ts("full")),!1;{let ye=await Sr({billingApiUrl:C,sessionId:M,session:_,telemetry:!1});ye.type==="success"?N=ye.result:(Ae(),ye.type==="paypal_redirect_required"&&Me.current?.publishableKey&&Zi({sessionId:M,publishableKey:Me.current.publishableKey,paypalPublishableKey:Me.current.paypalPublishableKey}),N=await _o(ye,{flopay:mt.current,paypalFlopay:A.current,attempt3DS:O?.attempt3DS,billingApiUrl:C,sessionId:M,session:_,telemetry:!1}),ye.type==="paypal_redirect_required"&&Sa())}}M&&hr(M),Q(),B&&(o.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),o.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),o.terminal({outcome:N.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Wt(N.status==="authorized"),Xe("success"),await Qr(Tn),q=()=>He.current?.(N)}catch(p){let N=or(p),ye=N.checkoutMethod??Xr;Ve(N.message),at(N.message),Wt(!1),O?.fallbackToFull&&(o.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Ye("full"),ts("full")),Q();let we=N.statusCode!==void 0?ql(N.statusCode,"unknown"):void 0,_e=we==="4xx"?{requestCategory:"process_payment",statusClass:we}:{},gn=we===void 0||we==="4xx";if(gn&&(N.telemetryOutcome==="payment_declined"||!!(N.declineCode||N.code?.toLowerCase().includes("declin"))))o.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",..._e});else if(gn&&(N.telemetryOutcome==="validation_rejected"||N.type==="validation_error"))o.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",..._e});else{let no=Gi(p,B?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");o.error({...no,...N.telemetryFailureCategory?{failureCategory:N.telemetryFailureCategory}:{},stage:B?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:N.telemetryRequestCategory??"process_payment"})}return Ke(()=>En.current?.(N)),tn(ye,N,{code:N.code,declineCode:N.declineCode}),Xe("error"),await Promise.allSettled([Qr(vn),O?.ensureProvidersReady?O.ensureProvidersReady():Promise.resolve()]),B&&(o.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),o.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Q(),m&&Zr(m),Xe(null),at(null)}return Ke(q),!0},[tn,Ke,or,C,r,st]);Bn(()=>{if(typeof window>"u"||Lt.current)return;let _=new URLSearchParams(window.location.search),O=_.get("payment_intent_client_secret");if(!O)return;let M=Hl();M&&(Lt.current=!0,(async()=>{let Pe,be=0;Ve(null),at(null),Xe("processing"),St(!0);try{if(_.get("redirect_status")==="failed")throw Object.assign(new It("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:m,paypalFlopay:o}=await To({publishableKey:M.publishableKey,paypalPublishableKey:M.paypalPublishableKey,billingApiUrl:C,locale:c,telemetry:r});Pe=At(o??m),be=Pe?.now()??0,Pe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let y=(o??m)?.getRawProvider();if(!y)throw Object.assign(new It("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:P}=await y.retrievePaymentIntent(O);if(P)throw Object.assign(new It(P.message??"Failed to retrieve PayPal payment status.","api_error",{code:P.code}),{checkoutMethod:"paypal"});let $=hi(B?.status);if(!B||$==="failed")throw Object.assign(new It("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Ae=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id,Qe=$;if(M.sessionId){let p=(await new Mo(C,{telemetry:!1}).getUnifiedCheckoutSession(M.sessionId)).data.session;if(p&&p.status!=="complete"){let N=await Sr({billingApiUrl:C,sessionId:M.sessionId,session:p,telemetry:!1,tokenizedData:{id:Ae??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0}});if(N.type!=="success")throw Object.assign(new It("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Qe=N.result.status}}M.sessionId&&hr(M.sessionId),Pe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.performance({stage:"redirect_resume",durationMs:Pe.elapsed(be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Xe("success"),await Qr(Tn),Ke(()=>He.current?.({status:Qe,paymentIntentId:B.id,paymentMethodId:Ae,checkoutMethod:"paypal"}))}catch(m){let o=or(m),y=o.checkoutMethod??"paypal",B=!!(o.declineCode||o.code?.toLowerCase().includes("declin"));if(Pe)Pe.performance({stage:"redirect_resume",durationMs:Pe.elapsed(be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?Pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Pe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let P=Bo(C,r,st);P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Zr(P)}else va(C,r,st,"REDIRECT_RESUME_FAILED","redirect_resume");Ve(o.message),at(o.message),Ke(()=>En.current?.(o)),tn(y,o,{code:o.code,declineCode:o.declineCode}),Xe("error"),await Qr(vn)}finally{Sa(),Jl(),Xe(null),at(null),St(!1)}})())},[tn,Ke,c,or,C,r]);let Yt=Nt(null);function Ut(_,O=!1){let M=_?.account?.email?.trim().toLowerCase()??"",Pe={c:_?.clientId,cur:_?.currency??"",captureMethod:_?.captureMethod??"",a:{e:M,u:M?"":_?.account?.userId??"",country:_?.account?.country??""},successUrl:_?.successUrl,cancelUrl:_?.cancelUrl,p:_?.products?.map(o=>wa(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:_?.items?.map(o=>wa(o.code??o.providerItemId??"",o)).sort(),s:_?.subscriptions?.map(o=>wa(o.code??o.providerPlanId??"",o)).sort(),couponCodes:_?.couponCodes?[..._.couponCodes].sort():void 0,...O?{tagsData:_?.tagsData,utmMetadata:_?.utmMetadata,tokenizedData:_?.tokenizedData,checkoutMode:_?.checkoutMode??"full"}:{}},be=JSON.stringify(Pe),m=0;for(let o=0;o<be.length;o++)m=(m<<5)-m+be.charCodeAt(o)|0;return`flopay_session_${Math.abs(m).toString(36)}`}let $t=mn(()=>xt?Ut(xt):"",[xt]),Ie=Nt(xt);Ie.current=xt,Bn(()=>{ft(e??"")},[e]),Bn(()=>{it.current=!1,Ve(Te),at(null),Wt(!1),Xe(null)},[$t,Te,e]);async function qt(_,O){let M=Bo(C,r,st),Pe=new Mo(C,{telemetry:!1}),be=!1;try{let m=_.idempotencyKey!==void 0?Xi(_.idempotencyKey):void 0,o=m??Wl(O),y,B=!1,P=Kl(O);M.log({name:P?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let $=P?.sid??null,Ae=null,Qe;if($)try{if(Ae=await Pe.getUnifiedCheckoutSession($,P?.nonce),Ae.data.session?.status==="complete"){if(ra($))return{sid:$,result:Ae};Gl(O),$=null,Ae=null,B=!0}}catch{M.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ra(O),$=null}if(!$){!m&&(B||!o)&&(o=Xi(),y=o),o&&Yl(O,o);let Q=M.now(),q=0;M.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let p={..._,idempotencyKey:o,avsCheck:!!me,avsConfig:typeof me=="object"?me:void 0,checkoutType:"embedded_checkout",checkoutLayout:ae?"custom_layout":E==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(p,Ol,{configurable:!1,enumerable:!1,value:{onAttempt:we=>{q=Math.max(q,we)}}});let N=()=>{M.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),M.performance({stage:"session_create",durationMs:M.now()-Q,durationMode:"machine",requestCategory:"session_create",attempt:q,statusClass:"2xx"})},ye=we=>{let _e=Gi(we,"CHECKOUT_SESSION_CREATE_FAILED","unknown");M.performance({stage:"session_create",durationMs:M.now()-Q,durationMode:"machine",requestCategory:"session_create",attempt:q,statusClass:_e.statusClass}),we instanceof It&&we.type==="validation_error"?M.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):_e.statusClass==="4xx"?M.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):M.error({..._e,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if(Nl(p)){let we=await Pe.createDetachedSession(p);we.claimed.catch(()=>{}),Ae=we.shell,$=we.sessionId,Qe=we.claimed.then(_e=>{let gn=_e.data.session?.id??we.sessionId;return gn&&es(O,gn,_e.data.session?.clientSecret??we.nonce),N(),_e},_e=>{throw Ra(O),ye(_e),_e}).finally(()=>Zr(M)),Qe.catch(()=>{}),be=!0,M.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),M.performance({stage:"session_shell",durationMs:M.now()-Q,durationMode:"machine",requestCategory:"session_create",attempt:q,statusClass:"2xx",paymentMethodCategory:"card"})}else Ae=await Pe.createAndFetchSession(p),N()}catch(we){throw ye(we),we}$=Ae.data.session?.id??$??"",$&&!Qe&&es(O,$,Ae.data.session?.clientSecret)}return{sid:$??"",result:Ae,sdkGeneratedIdempotencyKey:y,...Qe?{claimed:Qe}:{}}}finally{be||Zr(M)}}let gt=ar(async(_,O)=>{let M=Ie.current;if(!M)throw new It("createSession is required to bootstrap checkout.","validation_error");let Pe=ta(M,_),be=Ut(Pe),m=Fo.get(be);if(!m){let B={promise:qt(Pe,be),consumers:0,settled:!1};m=B,Fo.set(be,B);let P=()=>{B.settled=!0,Qi(be,B)};B.promise.then(P,P)}m.consumers+=1;let o=!1,y=()=>{o||(o=!0,m.consumers-=1,Qi(be,m))};O?.(y);try{let B=await m.promise;Yt.current=be,_&&(Bt(rt),Qt(N=>yi(N,_)));let{sid:P,result:$,claimed:Ae}=B;if(ce($),$.data.session&&tt($.data.session),P&&ft(P),Ae){let N=Dt.current+=1;Ft(!0),Ae.then(ye=>{Dt.current===N&&(ce(ye),ye.data.session&&tt(ye.data.session),Ft(!1))},ye=>{Dt.current===N&&(Ft(!1),I(ye instanceof It?ye:new It(ye instanceof Error?ye.message:"Failed to create session","api_error")))})}else Dt.current+=1,Ft(!1);let{publishableKey:Qe,paypalPublishableKey:Q}=xo($),{flopay:q,paypalFlopay:p}=await To({publishableKey:Qe,paypalPublishableKey:Q,billingApiUrl:C,locale:c,telemetry:r});return mt.current=q,Re(q),A.current=p,yt(p),Ge(!1),B}catch(B){throw Yt.current===be&&(Yt.current=null),B}finally{O||y()}},[c,C,r,st]),fn=Nt(cn);fn.current=cn;let Yn=Nt(gt);Yn.current=gt;let Vt=ar(async _=>{if(!Xl(_)||kt)return{sessionId:qe,session:X};Zt(!0);try{let O=await gt(_);return{sessionId:O.sid,session:O.result.data.session??null}}finally{Zt(!1)}},[gt,kt,qe,X]);Bn(()=>{let _=!1,O;if(I(null),$t){let be=Ie.current;return Ye(Pt),Ge(!1),Yt.current===$t?()=>{_=!0}:(tt(fi(be,Ue)),(async()=>{let m=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),o=Pt==="auto"&&!it.current&&!m;o&&(Ve(null),at(null),Xe("processing"));try{let y=await Yn.current(void 0,Ae=>{O=Ae}),B=y.result.data.session??null;Me.current=xo(y.result);let P=Ca(y.result),$=ra(y.sid||B?.id);if(!_&&o&&B&&!P&&!$){it.current=!0,await Vl($t,y.sdkGeneratedIdempotencyKey,()=>fn.current(B,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:y.result.autoProcessingError,initialAutoProcessingPending:y.result.autoProcessingPending,autoProcessingAttempted:y.result.autoProcessingAttempted,sessionId:y.sid||B.id}));return}!_&&o&&((P||$)&&(it.current=!0),Xe(null),at(null))}catch(y){if(_)return;let B=y instanceof It||typeof y=="object"&&y!==null&&"code"in y?y.code:void 0;if(o&&B==="session_auto_completed"){it.current=!0,Xe("success"),await Qr(Tn),_||(Ke(()=>{He.current?.({status:"succeeded"})}),Xe(null),at(null));return}o&&(Xe(null),at(null));let P=y instanceof It?y:new It(y instanceof Error?y.message:"Failed to create session","api_error");I(P)}finally{O?.(),O=void 0}})(),()=>{_=!0,O?.()})}Ge(!0);async function M(){let be=!1;try{let o=await new Mo(C,{telemetry:!1}).getUnifiedCheckoutSession(Oe,t);if(_)return;ce(o);let y=o.data.session??null;if(tt(y),!y)throw new It("No session data returned","api_error");let B=y.checkoutMode;if(B==="setup")throw new It("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(y.status==="authorized"){Ge(!1),Ke(()=>{He.current?.(er(y,Oe)),zn.current?.(y.successUrl??"")});return}if(y.status==="complete"){Ge(!1),Ke(()=>{zn.current?.(y.successUrl??"")});return}if(y.status==="expired")throw Po(y);be=!0;let P=Ue??B??"full";Ye(P);let $=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ae=Ca(o);if(P==="auto"&&!it.current&&!$&&!Ae){it.current=!0;let Qe=Pe(o);try{if(await fn.current(y,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Qe,sessionId:Oe||y.id}),_)return;await Qe,_||Ge(!1);return}catch{if(_)return;await Qe,_||Ge(!1);return}}await Pe(o),_||Ge(!1)}catch(m){if(_)return;m instanceof It?!be&&!jl(m)&&va(C,r,st,"NETWORK_REQUEST_FAILED","session_read"):va(C,r,st,"INTERNAL_SDK_ERROR","checkout_mount");let o=m instanceof It?m:new It(m instanceof Error?m.message:"Failed to initialize checkout","api_error");I(o),Ge(!1)}}async function Pe(be){let{publishableKey:m,paypalPublishableKey:o}=xo(be);Me.current={publishableKey:m,paypalPublishableKey:o};let{flopay:y,paypalFlopay:B}=await To({publishableKey:m,paypalPublishableKey:o,billingApiUrl:C,locale:c,telemetry:r});mt.current=y,Re(y),A.current=B,yt(B)}return M(),()=>{_=!0}},[Ue,$t,Pt,We,Ke,t]);let jt=ar(async()=>{if(!(Ee||!X)){St(!0),Ve(null);try{await cn(X,{attempt3DS:!0,fallbackToFull:!0,sessionId:Oe||X.id})}finally{St(!1)}}},[Oe,Ee,cn,X]),Ot=ka(T),On=Ca(T),Nn=mn(()=>{if(!T||!X||!T.data.stripe?.publishableKey)return;let _={appearance:$e,paymentMethodCreation:"manual",billingApiUrl:C};if(T.data.stripe?.clientSecret)_.clientSecret=T.data.stripe.clientSecret;else{let O=Ji(X).total;_.amount=Math.round(O*100)||X.amount,_.currency=X.currency?.toLowerCase()}return _},[T,X,$e,C]),nn=!!(n&&!ae&&E==="buttons"&&z&&Pt==="full"),Gt=mn(()=>({session:X,loading:Jt,error:Xt,checkoutMode:he,inlineSessionDraft:xt,applyInlineSessionPatch:nn?Vt:void 0,inlineSessionPatchProcessing:kt,claimPending:en}),[X,Jt,Xt,he,xt,nn,Vt,kt,en]),rn=!!n&&E==="buttons"&&!On&&(!J||!Nn),Ne=nt?ie(Cn,{status:nt,errorMessage:Rn,authorized:Hn}):null;if(Jt){if(l)return _t(kn,{children:[l,Ne]});if(E==="buttons"){let _=se?.buttonsLayout?.cardButton?.borderRadius??se?.appearance.variables?.borderRadius??8,O=M=>ie("div",{style:{height:M,borderRadius:_,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return _t(kn,{children:[_t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[d&&O(wr),h&&(R||f)&&O(wr),h&&O(wr),ie("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ne]})}return _t(kn,{children:[_t("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ie("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ie("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ne]})}return Xt?b?ie(pn.Provider,{value:Gt,children:b(Xt)}):ie(pn.Provider,{value:Gt,children:ie("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Xt.message})}):rn?_t(kn,{children:[ie(pn.Provider,{value:Gt,children:ie(Zl,{onButtonClick:V,showPayPal:d,showStripe:h,showApplePay:R,showGooglePay:f,theme:re,buttonsTheme:Z,buttonsStyles:L,cardButtonContent:Y,cardBackButtonContent:K,cardTitleContent:te})}),Ne]}):On&&X&&Ot?_t(kn,{children:[ie(pn.Provider,{value:Gt,children:_t("div",{className:ge,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[je&&ie(yr,{icon:!1,children:je}),wt==="retrying"&&ie("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),wt==="exhausted"&&_t("div",{role:"alert",children:[ie("div",{children:"PayPal is temporarily unavailable. Please try again."}),ie("button",{type:"button",onClick:_n,children:"Retry PayPal"})]}),wt!=="exhausted"&&ie("div",{"aria-hidden":wt==="retrying"?!0:void 0,style:wt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ie(ki,{sessionId:Oe,nonce:X.clientSecret||void 0,billingApiUrl:C,email:X.customer?.email,clientId:Ot.clientId,environment:Ot.environment,currency:(X.currency??"usd").toUpperCase(),isSubscription:X.mode==="subscription",onComplete:x,onErrorChange:Ve,onDecline:S,onButtonClick:V,onInitializationStateChange:Wn,allowAutomaticRetry:Kn===0,session:X,telemetry:r,telemetryContext:st,debug:de},`paypal-init-${Kn}`)})]})}),Ne]}):!J||!Nn?ie(kn,{children:Ne}):he==="confirm"?_t(kn,{children:[ie(pn.Provider,{value:Gt,children:ie(fo,{flopay:J,paypalFlopay:Je,options:Nn,children:_t("div",{className:ge,children:[je&&ie("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:je}),ke?ke({onConfirm:jt,isProcessing:Ee}):ie("button",{type:"button",onClick:jt,disabled:Ee,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Ee?"not-allowed":"pointer",opacity:Ee?.6:1},children:Ee?"Processing...":Fe??"Confirm Purchase"})]})})}),Ne]}):_t(kn,{children:[ie(pn.Provider,{value:Gt,children:ie(fo,{flopay:J,paypalFlopay:Je,options:Nn,children:ae?_t(kn,{children:[je&&ie("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:je}),ie(Ql,{sessionId:Oe,nonce:X?.clientSecret||void 0,billingApiUrl:C,session:X,children:ae})]}):ie(ga,{sessionId:Oe,nonce:X?.clientSecret||void 0,email:X?.customer?.email,userId:X?.customer?.id,firstName:X?.customer?.firstName,lastName:X?.customer?.lastName,totalAmount:X?Math.round(Ji(X).total*100):0,currency:X?.currency?.toLowerCase()??"usd",onComplete:x,onError:g,onDecline:S,error:je,onErrorChange:Ve,showPayPal:d,showStripe:h,enabledPaymentMethods:w??T?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:T?.data.stripe?.enabledPaymentMethodCountries,showApplePay:R,showGooglePay:f,layout:E,theme:re,buttonsTheme:Z,buttonsStyles:L,appearance:$e,cardButtonContent:Y,cardBackButtonContent:K,cardTitleContent:te,onButtonClick:V,onBeforeButtonClick:z,enableAVS:me,...ee?{cardFieldOrder:ee}:{},...oe?{cardPreFormSlot:oe}:{},avsLayout:G,country:X?.customer?.country,city:X?.customer?.city,state:X?.customer?.state,onCountryChange:v,onZipChange:k,avsCheck:!!me,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ae?"custom_layout":E==="buttons"?"buttons_layout":"default_layout",className:ge,directPaypal:ka(T),isSubscription:X?.mode==="subscription",session:X,dataAttachmentPending:en,debug:de})})}),Ne]})}function Ql({sessionId:e,nonce:t,billingApiUrl:n,session:a,children:r}){return ie(kn,{children:ba.Children.map(r,s=>{if(!ba.isValidElement(s))return s;let c=s.props,l={};return c.sessionId||(l.sessionId=e),!c.nonce&&t&&(l.nonce=t),c.billingApiUrl||(l.billingApiUrl=n),a?.customer&&(c.email||(l.email=a.customer.email),c.userId||(l.userId=a.customer.id),c.firstName||(l.firstName=a.customer.firstName),c.lastName||(l.lastName=a.customer.lastName)),Object.keys(l).length===0?s:ba.cloneElement(s,l)})})}function Zl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:a,showGooglePay:r,theme:s,buttonsTheme:c,buttonsStyles:l,cardButtonContent:b,cardBackButtonContent:x,cardTitleContent:g}){let[S,v]=Ct(!1),k=mn(()=>rs(s),[s]),d=mn(()=>{let f=k?.buttonsLayout??$l(c);return l?{...f,...l,cardButton:{...f.cardButton,...l.cardButton},cardFormContainer:{...f.cardFormContainer,...l.cardFormContainer},backButton:{...f.backButton,...l.backButton},backButtonIcon:{...f.backButtonIcon,...l.backButtonIcon},submitButton:{...f.submitButton,...l.submitButton},title:{...f.title,...l.title}}:f},[k,c,l]),h=k?.buttonsLayout?.cardButton?.borderRadius??k?.appearance.variables?.borderRadius??8,w=f=>ie("div",{style:{height:f,borderRadius:h,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),R=b===void 0?{boxSizing:"border-box",height:wr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(S){let f=d.cardInputBorder??"#e5e7eb",de=d.cardInputBackground??"white",E=cr(x),re=cr(g);return _t("div",{style:{backgroundColor:d.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...d.cardFormContainer},children:[_t("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[_t("button",{type:"button",onClick:()=>v(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:E?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...d.backButton},children:[ie("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...d.backButtonIcon},children:ie("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:ie("path",{d:"M15 18l-6-6 6-6"})})}),ie(ur,{content:x})]}),re?ie("div",{style:{flex:1}}):ie("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...d.title},children:ie(qr,{content:g})})]}),ie("div",{style:{backgroundColor:de,border:`1px solid ${f}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ie("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),_t("div",{style:{display:"flex"},children:[ie("div",{style:{flex:1,backgroundColor:de,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomLeftRadius:8,padding:12,height:45},children:ie("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ie("div",{style:{flex:1,backgroundColor:de,borderTop:"none",borderRight:`1px solid ${f}`,borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomRightRadius:8,padding:12,height:45},children:ie("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ie("div",{style:{backgroundColor:de,border:`1px solid ${f}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ie("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ie("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...d.submitButton,opacity:.5}}),ie("style",{children:`
38
+ `}),zr&&Yn&&ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:He?-2:0},children:[ze("button",{type:"button",onClick:Nn,style:{display:"inline-flex",alignItems:"center",gap:Yo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:P.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...P.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...P.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(ur,{content:j})]}),Za?u("div",{style:{flex:1}}):u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...P.title},children:u(qr,{content:ce})})]}),!zr&&!Za&&u("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Go,order:He?-3:0,...P.title},children:u(qr,{content:ce})}),ne&&u("div",{style:{order:He?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Ye,L=(V=!1)=>({backgroundColor:Nr,border:`1px solid ${Gn(V)}`,borderRadius:bt,marginTop:"0.5rem",padding:"10px"}),H=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ri}),se=ol(s);return ze(vr,{children:[Le(ne.address_line_1,s)&&u("div",{style:L(Pt.line1),children:u("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:Ve,onChange:V=>{wt.current.addressLine1=!0,en.current=V.target.value,nt(V.target.value)},disabled:Q,required:!0,"data-testid":"flopay-address-line1",style:H()})}),Le(ne.address_line_2,s)&&u("div",{style:L(),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Xe,onChange:V=>{wt.current.addressLine2=!0,tn.current=V.target.value,In(V.target.value)},disabled:Q,"data-testid":"flopay-address-line2",style:H()})}),(Le(ne.city,s)||Le(ne.state,s))&&ze("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Le(ne.city,s)&&u("div",{style:{flex:1,backgroundColor:Nr,borderTop:`1px solid ${Gn(Pt.city)}`,borderRight:`1px solid ${Gn(Pt.city)}`,borderBottom:`1px solid ${Gn(Pt.city)}`,borderLeft:`1px solid ${Gn(Pt.city)}`,padding:"10px",borderTopLeftRadius:bt,borderBottomLeftRadius:bt,...Le(ne.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:bt}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:at,onChange:V=>{wt.current.city=!0,Ft.current=V.target.value,Hn(V.target.value)},disabled:Q,required:!0,"data-testid":"flopay-city",style:H()})}),Le(ne.state,s)&&u("div",{style:{flex:1,backgroundColor:Nr,border:`1px solid ${Gn(Pt.state)}`,padding:"10px",borderTopRightRadius:bt,borderBottomRightRadius:bt,...Le(ne.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:bt}},children:se?ze("select",{id:"flopay-billing-state",name:"billing-state",value:Wt,onChange:V=>{wt.current.state=!0,Dt.current=V.target.value,Pn(V.target.value)},disabled:Q,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...H(),cursor:"pointer"},children:[u("option",{value:"",children:Ri(s)}),se.map(V=>u("option",{value:V.code,children:V.name},V.code))]}):u("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Ri(s),autoComplete:"billing address-level1",value:Wt,onChange:V=>{wt.current.state=!0,Dt.current=V.target.value,Pn(V.target.value)},disabled:Q,required:!0,"data-testid":"flopay-state",style:H()})})]}),(Le(ne.country,s)||Le(ne.postal_code,s))&&ze("div",{style:{display:"flex",flexDirection:K==="column"?"column":"row",gap:K==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Le(ne.country,s)&&u("div",{style:{flex:K==="row"?1:void 0,backgroundColor:Nr,borderTop:`1px solid ${Or}`,borderRight:`1px solid ${Or}`,borderBottom:`1px solid ${Or}`,borderLeft:`1px solid ${Or}`,padding:"10px",...K==="row"&&Le(ne.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:bt,borderBottomLeftRadius:bt,borderRight:"none"}:{borderRadius:bt}},children:u("select",{id:"flopay-billing-country",name:"billing-country",value:Ye,onChange:V=>{wt.current.country=!0,kt.current=V.target.value,xe(V.target.value),$e?.(V.target.value),Dt.current="",Pn("")},disabled:Q,autoComplete:"billing country","data-testid":"flopay-country",style:{...H(),cursor:"pointer"},children:al.map(V=>ze("option",{value:V.code,children:[V.flag," ",V.name]},V.code))})}),Le(ne.postal_code,s)&&u("div",{style:{flex:K==="row"?1:void 0,backgroundColor:Nr,border:`1px solid ${Ss}`,padding:"10px",...K==="row"&&Le(ne.country,s)?{borderRadius:"0",borderTopRightRadius:bt,borderBottomRightRadius:bt}:{borderRadius:bt}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:pa(Ye),autoComplete:"billing postal-code",value:St,onChange:V=>{wt.current.zip=!0,Bt.current=V.target.value,je(V.target.value),Oe?.(V.target.value)},onBlur:()=>Yt(!0),disabled:Q,required:zt.required,"aria-invalid":uo||void 0,"aria-describedby":uo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:H()})})]}),uo&&u("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Ko,...ri,fontSize:"0.75rem"},children:zt.empty?`${pa(s)} is required`:Rl(s)})]})})()}),He&&Y&&u("div",{style:{order:-2,width:"100%"},children:Y}),He&&Is,y&&u(yr,{margin:"0.75rem 0",styleOverride:P.errorBanner,children:y})]}),po={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"},ai=s=>tt?!k||!Sn?u("pre",{"data-testid":s,style:po,children:"FloPay/DirectPayPal-debug - not enabled"}):u("pre",{"data-testid":s,style:po,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${k}`,` directPaypalConfigured=${Sn}`,` inAppBrowserDetected=${String(lo)}`,` shouldRenderDirectPayPal=${Br}`,` shouldRenderStripePayPal=${Fr}`,` hasPaypalStripeInstance=${!!Ie}`].join(`
39
+ `)}):null,ii=s=>tt?!E||!he?u("pre",{"data-testid":s,style:po,children:"FloPay/Stripe-debug - not enabled"}):u("pre",{"data-testid":s,style:po,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${E}`,` currency=${_e}`,` amountInCents=${Me}`,` enabledPaymentMethods: ${JSON.stringify(f??[])}`,` enabledPaymentMethodsProvided=${Mr}`,` hasEnabledMethods=${oo}`,` expressMethods: ${JSON.stringify(ao)}`,` walletExpressMethods: ${JSON.stringify(io)}`,` paymentElementMethods: ${JSON.stringify(Ar)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(so)}`,` hasStripeInstance=${!!he}`,` shouldRenderWallets=${Dr}`,` shouldRenderPaymentElement=${Lr}`].join(`
40
+ `)}):null,si=Te==="apm-expanding"||Te==="apm-form"||Te==="apm-collapsing",mo=Te==="apm-expanding"?`flopay-card-enter ${Vt}ms cubic-bezier(0, 0, 0.2, 1) both`:Te==="apm-collapsing"?`flopay-card-exit ${Vt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,yo=gt?{...$o,paymentMethodTypes:[gt]}:null;if(Z==="buttons"){let s=Te==="buttons"||Te==="expanding"||Te==="apm-expanding",L=Te==="expanding"||Te==="card"||Te==="collapsing",H=N===void 0?{boxSizing:"border-box",height:Eo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},se=Te==="expanding"||Te==="apm-expanding"?`flopay-buttons-exit ${Vt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Te==="collapsing"||Te==="apm-collapsing"?`flopay-buttons-enter ${Vt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,V=Te==="expanding"?`flopay-card-enter ${Vt}ms cubic-bezier(0, 0, 0.2, 1) both`:Te==="collapsing"?`flopay-card-exit ${Vt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return ze("form",{onSubmit:jo,className:v,style:{position:"relative"},children:[u(ua,{}),on&&u(cn,{status:on,errorMessage:y,authorized:D}),ze("div",{style:{display:"grid"},children:[ze("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!se?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!se?Sl:{},...se?{animation:se,pointerEvents:"none"}:{}},children:[ai("flopay-direct-paypal-gate-debug"),ii("flopay-stripe-gate-debug"),Br&&Je&&ze(vr,{children:[ve&&u("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."}),u(Ro,{sessionId:e,nonce:t,billingApiUrl:o,email:p.email,clientId:Je.clientId,environment:Je.environment,currency:_e.toUpperCase(),isSubscription:yt,onTokenizedBody:an,onComplete:i,onErrorChange:ye,onDecline:l,onTechnicalFailure:sr,onButtonClick:fe,runBeforeButtonClick:mn,isProcessing:Q,onLoadStateChange:qo,onInitializationStateChange:Vo,session:A??null,existingOrderId:ve?.orderId,debug:tt},ve?.orderId??"fresh")]}),Fr&&u(rr,{stripe:Ie,options:Fa,children:u(Fi,{sessionId:e,nonce:t,email:p.email,billingApiUrl:o,onTokenizedBody:an,onErrorChange:ye,isProcessing:Q,onButtonClick:fe,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:mn,onLoadStateChange:Oa,placeholderBorderRadius:Jn})}),Dr?u(rr,{stripe:he,options:ro,children:u(Di,{sessionId:e,nonce:t,email:p.email,billingApiUrl:o,intentKind:J>0?"payment":"setup",expressMethods:io,onTokenizedBody:an,onErrorChange:ye,onButtonClick:fe,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:mn,onLoadStateChange:Ua,placeholderBorderRadius:Jn})}):Ha?u("div",{style:{height:Eo,borderRadius:Jn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Lr&&u(Li,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,paymentElementMethods:so,stripeInstance:he,paymentElementBaseOptions:$o,onTokenizedBody:an,onErrorChange:ye,onButtonClick:fe,onDecline:l,runBeforeButtonClick:mn,onLoadStateChange:qa,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:P.submitButton,onExpandApm:rn,expandedApmMethod:gt,themeId:F,buttonAppearance:{backgroundColor:P.cardButton?.backgroundColor,borderColor:P.cardInputBorder,textColor:P.cardButton?.color,borderRadius:Jn}}),He&&u("button",{type:"button",onClick:async()=>{Q||!(await mn("card")).proceed||(fe?.("card"),On())},disabled:Q,style:{width:"100%",...H,...P.cardButton,...ha({themeBundle:B,resolvedPrimaryColor:Xn,resolvedBorderRadius:bt,submitButtonStyle:P.submitButton,explicitPrimaryColor:Ht?.colorPrimary}),fontSize:P.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Q?"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?.6:1},onMouseEnter:Se=>{!Q&&(B||Ht?.colorPrimary)&&(Se.currentTarget.style.backgroundColor=Rs)},onMouseLeave:Se=>{(B||Ht?.colorPrimary)&&(Se.currentTarget.style.backgroundColor=Xn)},onMouseDown:Se=>{Se.currentTarget.style.transform="scale(0.985)"},onMouseUp:Se=>{Se.currentTarget.style.transform="scale(1)"},children:u(dr,{content:N})}),y&&Te==="buttons"&&u(yr,{margin:"0.25rem 0",styleOverride:P.errorBanner,children:y})]}),He&&L&&u("div",{style:{gridArea:"1 / 1",...V?{animation:V}:{},...Te==="collapsing"?{pointerEvents:"none"}:{}},children:oi}),E&&si&&gt&&yo&&he&&u("div",{style:{gridArea:"1 / 1",...mo?{animation:mo}:{},...Te==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:Wo,borderRadius:Xo,...Ur,padding:Jo},children:[ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ze("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:Yo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:P.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...P.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...P.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(ur,{content:j})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:Go,paddingRight:80,...P.title},children:`Pay with ${Cr(gt)}`})]}),u(rr,{stripe:he,options:yo,children:u(ma,{method:gt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,onTokenizedBody:an,onErrorChange:ye,onDecline:l,onCancel:Gt,runBeforeButtonClick:mn,onButtonClick:fe,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:P.submitButton,errorText:y})},gt)]})})]})]})}return si&&gt&&yo&&he&&E?ze("form",{onSubmit:jo,className:v,style:{position:"relative"},children:[u(ua,{}),on&&u(cn,{status:on,errorMessage:y,authorized:D}),u("div",{style:{...mo?{animation:mo}:{},...Te==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:Wo,borderRadius:Xo,...Ur,padding:Jo},children:[ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ze("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:Yo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:P.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...P.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...P.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(ur,{content:j})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:Go,paddingRight:80,...P.title},children:`Pay with ${Cr(gt)}`})]}),u(rr,{stripe:he,options:yo,children:u(ma,{method:gt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,onTokenizedBody:an,onErrorChange:ye,onDecline:l,onCancel:Gt,runBeforeButtonClick:mn,onButtonClick:fe,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:P.submitButton,errorText:y})},gt)]})})]}):ze("form",{onSubmit:jo,className:v,style:{position:"relative"},children:[u(ua,{}),on&&u(cn,{status:on,errorMessage:y,authorized:D}),ze("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ai("flopay-direct-paypal-gate-debug-default"),ii("flopay-stripe-gate-debug-default"),Br&&Je&&ze(vr,{children:[ve&&u("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."}),u(Ro,{sessionId:e,nonce:t,billingApiUrl:o,email:p.email,clientId:Je.clientId,environment:Je.environment,currency:_e.toUpperCase(),isSubscription:yt,onTokenizedBody:an,onComplete:i,onErrorChange:ye,onDecline:l,onTechnicalFailure:sr,onButtonClick:fe,runBeforeButtonClick:mn,isProcessing:Q,onLoadStateChange:qo,onInitializationStateChange:Vo,session:A??null,existingOrderId:ve?.orderId,debug:tt},ve?.orderId??"fresh")]}),Fr&&u(rr,{stripe:Ie,options:Fa,children:u(Fi,{sessionId:e,nonce:t,email:p.email,billingApiUrl:o,onTokenizedBody:an,onErrorChange:ye,isProcessing:Q,onButtonClick:fe,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:mn,onLoadStateChange:Oa,placeholderBorderRadius:Jn})}),Dr&&u(rr,{stripe:he,options:ro,children:u(Di,{sessionId:e,nonce:t,email:p.email,billingApiUrl:o,intentKind:J>0?"payment":"setup",expressMethods:io,onTokenizedBody:an,onErrorChange:ye,onButtonClick:fe,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:mn,onLoadStateChange:Ua,placeholderBorderRadius:Jn})}),Lr&&u(Li,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,paymentElementMethods:so,stripeInstance:he,paymentElementBaseOptions:$o,onTokenizedBody:an,onErrorChange:ye,onButtonClick:fe,onDecline:l,runBeforeButtonClick:mn,onLoadStateChange:qa,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:P.submitButton,themeId:F,onExpandApm:rn,expandedApmMethod:gt,buttonAppearance:{backgroundColor:P.cardButton?.backgroundColor,borderColor:P.cardInputBorder,textColor:P.cardButton?.color,borderRadius:Jn}})]}),He&&(Ps||hs||bs)&&ze("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),u("span",{children:"or pay with card"}),u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),He&&oi]})}import{loadFloPay as Vi,PaymentAPI as Hi}from"@flopay/js";import{classifyPaymentRejection as Tl,FloPayError as ot,isAuthorizationOnlySession as Ml,isSetupIntentClientSecret as Al,normalizeCheckoutFailureOutcome as ji}from"@flopay/shared";var Xr="card";async function Bl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:a,error:r}=await e.retrievePaymentIntent(t);return{error:r,intent:a??null}}async function Fl(e,t,n,a){if(a){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:c??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:r,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:r??null}}function va(e,t){return Object.assign(e,{checkoutMethod:t})}function Bn(e,t){let n=e instanceof ot?e:new ot(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 Jr(e,t){try{return await e()}catch(n){throw Bn(n,t)}}function Ki(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 Dl(e){return e.status==="succeeded"||e.status==="declined"}async function Wi(e){if(typeof document>"u"||typeof window>"u")throw new ot("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new ot("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,a=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let g=new AbortController,w=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",w);let v=window.setTimeout(()=>g.abort(),a);try{let R=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!R.ok)return{status:"unknown"};let d=await R.json().catch(()=>null);return Ll(d)}catch{return{status:"unknown"}}finally{window.clearTimeout(v),e.signal?.removeEventListener("abort",w)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.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 b=document.createElement("iframe");b.setAttribute("title","Card authentication"),b.setAttribute("allow","payment"),b.tabIndex=0,b.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(";"),b.src=e.nextActionRedirectUrl,l.appendChild(b),document.body.appendChild(l),b.focus();let x=null;try{x=new URL(e.billingApiUrl,window.location.href).origin}catch{x=null}try{let g=await new Promise((w,v)=>{let R=!1,d=0,h=0,k=0,E=!1,f=()=>{window.clearTimeout(d),window.clearInterval(h),window.clearTimeout(k),window.removeEventListener("message",Z),b.removeEventListener("load",S),e.signal?.removeEventListener("abort",le)},de=async()=>{if(!(R||E)){E=!0;try{let F=await i();if(R||!Dl(F))return;R=!0,f(),w(F)}finally{E=!1}}},S=()=>{window.clearTimeout(k),k=window.setTimeout(()=>{de()},250)},le=()=>{R||(R=!0,f(),v(new ot("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Z=F=>{if(F.source!==b.contentWindow||x&&F.origin!==x)return;let G=F.data;!G||typeof G!="object"||G.source!=="flopay-vault-3ds-return"||R||(R=!0,f(),w(null))};d=window.setTimeout(()=>{R||(R=!0,f(),v(new ot("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),h=window.setInterval(()=>{de()},n),b.addEventListener("load",S),window.addEventListener("message",Z),e.signal?.addEventListener("abort",le),e.signal?.aborted&&le()});return g||await i()}finally{l.parentNode?.removeChild(l),c?.isConnected&&c.focus()}}function Ll(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 a=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),r=e?.message??t,i=Un(r)??r;return va(new ot(i,"api_error",{code:ji(e?.outcome)??ji(e?.type)??e?.gatewayErrorCode}),a)}function ba(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function _o(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function zl(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 Yi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||_o(r)))return r;let a=e?.data;if(a&&typeof a=="object"){let r=a,i=[r.threeDSecureToken,r.clientSecret,r.stripeClientSecret,r.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||_o(l)))return l;let c=r.gateways;if(c&&typeof c=="object"){let l=c.stripe;if(l&&typeof l=="object"){let b=l,x=[b.stripeClientSecret,b.clientSecret];for(let g of x)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||_o(g)))return g}}}}async function Ol({billingApiUrl:e,sessionId:t,nonce:n,responseJson:a}){let r=Yi(a,{requirePaymentIntentClientSecret:!0});if(typeof r=="string"&&r.length>0)return{type:"3ds_required",threeDSecureToken:r};if(!t)return null;try{let l=(await new Hi(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(_o(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Sr({billingApiUrl:e,sessionId:t,session:n,nonce:a,tokenizedData:r,returnUrl:i,telemetry:c}){let l=e.replace(/\/+$/,""),b=t??n.id,x=a??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",w=n.customer?.email??n.accountData?.email??"",v=n.customer?.firstName??n.accountData?.firstName??"",R=n.customer?.lastName??n.accountData?.lastName??"",d=n.customer?.country??n.accountData?.country??void 0,h=n.customer?.zip??n.accountData?.zip??void 0,k=new Hi(l,c===!1?{telemetry:!1}:void 0),E=await zl(()=>k.processPayment(g,{sessionId:b,nonce:x,tokenizedData:r,accountData:{userId:g,email:w,firstName:v,lastName:R,country:d,zip:h},returnUrl:i??ba(n)}));if(E.ok){let S=typeof E.json=="function"?await E.json().catch(()=>null):null;return Ml(n)||S?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof S?.paymentId=="string"?S.paymentId:n.paymentId,sessionId:typeof S?.sessionId=="string"?S.sessionId:b,authorizationExpiresAt:typeof S?.authorizationExpiresAt=="string"?S.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Kr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:Kr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}}let f;try{f=await E.json()}catch{throw new ot("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:E.status})}if(f?.type==="paypal_redirect_required"||f?.type==="3ds_required"){let S=Yi(f);if(!S)throw new ot("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:E.status});return{type:f.type,threeDSecureToken:S,paymentMethodId:f.paymentMethodId}}if(f?.gatewayErrorCode==="authentication_required"){let S=await Ol({billingApiUrl:l,sessionId:b,nonce:x,responseJson:f});if(S)return S;throw va(new ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let de=new ot(f?.message??"Payment failed. Please try again.","api_error",{code:f?.code??f?.gatewayErrorCode,declineCode:f?.declineCode??f?.gatewayDeclineReason,statusCode:E.status});throw Object.assign(de,{telemetryOutcome:Tl(E.status,f)})}async function xo(e,{flopay:t,paypalFlopay:n,attempt3DS:a,billingApiUrl:r,sessionId:i,session:c,returnUrl:l,telemetry:b}){let x=t?.getRawProvider();if(!x)throw Bn(new ot("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!a||!e.threeDSecureToken)throw va(new ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Al(e.threeDSecureToken),w=null,v=e.paymentMethodId,R=await Jr(()=>Bl(x,e.threeDSecureToken,g),"card");if(R){if(R.error)throw Bn(new ot(R.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:R.error.code}),"card");let h=R.intent;!v&&h?.payment_method&&(typeof h.payment_method=="string"?v=h.payment_method:"id"in h.payment_method&&(v=h.payment_method.id??void 0))}let d=v?await Jr(()=>Fl(x,e.threeDSecureToken,{payment_method:v,return_url:l??ba(c)??window.location.href},g),"card"):null;if(d){if(d.error)throw Bn(new ot(d.error.message??"3DS authentication failed.","api_error",{code:d.error.code}),"card");w=d.intent}else{let h=await Jr(()=>x.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(h.error)throw Bn(new ot(h.error.message??"3DS authentication failed.","api_error",{code:h.error.code}),"card");w=(g?h.setupIntent:h.paymentIntent)??null}if(w&&(w.status==="requires_capture"||w.status==="succeeded"||w.status==="processing")){let h=await Sr({billingApiUrl:r,sessionId:i,session:c,telemetry:b,tokenizedData:{id:w.id,type:"card",threeDSecureActionResultTokenId:w.id},returnUrl:l});return h.type==="success"?{...h.result,paymentIntentId:h.result.paymentIntentId??w.id,paymentMethodId:h.result.paymentMethodId??v}:xo(h,{flopay:t,paypalFlopay:n,attempt3DS:a,billingApiUrl:r,sessionId:i,session:c,returnUrl:l,telemetry:b})}throw Bn(new ot("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw Bn(new ot("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:v}=await Jr(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(v)throw Bn(new ot(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:w}=await Jr(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??ba(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(w)throw Bn(new ot(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new ot("Unsupported payment redirect state.","api_error")}function or(e){if(e instanceof ot){let a=Un(e.message);return a&&a!==e.message?Object.assign(new ot(a,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 ot(n,"api_error")}function To(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new ot("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 Mo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:a,telemetry:r}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[c,l]=await Promise.all([Vi(e,{billingApiUrl:n,locale:a,telemetry:r}),i?Vi(t,{billingApiUrl:n,locale:a,telemetry:r}).catch(b=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",b),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?i?l:c:null}}import{Fragment as En,jsx as re,jsxs as _t}from"react/jsx-runtime";var wr=44,_a="flopay_checkout_saved_payment_resume",Do=new Map,Bo=new Map;function Qi(e,t){t.settled&&t.consumers===0&&Do.get(e)===t&&Do.delete(e)}function jl(e,t,n){let a=Bo.get(e);if(a&&(!a.sdkGeneratedIdempotencyKey||!t||a.sdkGeneratedIdempotencyKey===t))return a.attempt;let r=n(),i={attempt:r,sdkGeneratedIdempotencyKey:t};Bo.set(e,i);let c=()=>{Bo.get(e)===i&&Bo.delete(e)};return r.then(c,c),r}function Qr(e){return new Promise(t=>setTimeout(t,e))}function Fo(e,t,n){let a=fo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:ns,enabled:t!==!1});return a.beginCheckout(n),a}function Zr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Sa(e,t,n,a,r){let i=Fo(e,t,n);i.error({errorCode:a,stage:r,paymentMethodCategory:"unknown",...r==="session_read"?{requestCategory:"session_read"}:{}}),Zr(i)}function Hl(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 Ea(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function wa(e){return!e||e.data.stripe?.publishableKey?!1:!!Ea(e)?.clientId}function Dn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Kl(){if(!Dn())return null;try{let e=window.sessionStorage.getItem(_a);return e?JSON.parse(e):null}catch{return null}}function Zi(e){if(Dn())try{window.sessionStorage.setItem(_a,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ka(){if(Dn())try{window.sessionStorage.removeItem(_a)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var xa=":idempotency-key";function Wl(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 es(e,t,n){if(Dn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(a){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",a)}}function Ia(e){if(Dn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function Yl(e){if(Dn())try{return window.sessionStorage.getItem(e+xa)??void 0}catch{return}}function Gl(e,t){if(Dn())try{window.sessionStorage.setItem(e+xa,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function Jl(e){if(Ia(e),!!Dn())try{window.sessionStorage.removeItem(e+xa)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Xl(){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 a of t)e.searchParams.has(a)&&(e.searchParams.delete(a),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function ts(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 Ql(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 Ta({sessionId:e,nonce:t,createSession:n,billingApiUrl:a,telemetry:r,appearance:i,locale:c,loading:l,error:b,onComplete:x,onError:g,onDecline:w,onCountryChange:v,onZipChange:R,showPayPal:d=!0,showStripe:h=!0,enabledPaymentMethods:k,showApplePay:E=!0,showGooglePay:f=!0,debug:de=!1,layout:S,theme:le,buttonsTheme:Z,buttonsStyles:F,cardButtonContent:G,cardBackButtonContent:W,cardTitleContent:oe,showSecurityFooter:N,onButtonClick:j,onBeforeButtonClick:ce,enableAVS:Re,cardFieldOrder:fe,cardPreFormSlot:ae,avsLayout:ee,className:pe,initialErrorMessage:Y=null,children:K,checkoutMode:Ee,confirmLabel:ge,renderConfirmButton:te,onSessionCompleted:q}){let C=$l(a),ie=gn(()=>rs(le),[le]),$e=i??ie?.appearance,Oe=n?"embedded_checkout":"standard_checkout",me=K?"custom_layout":S==="buttons"?"buttons_layout":"default_layout",[T,ue]=Ct(null),[J,_e]=Ct(null),mt=Nt(null),[Je,yt]=Ct(null),A=Nt(null),[X,tt]=Ct(null),[qe,ft]=Ct(e??""),Ne=e??qe,We=n?"":Ne,[Xt,Ge]=Ct(!0),[Qt,I]=Ct(null),[be,Ye]=Ct("full"),[xe,St]=Ct(!1),[je,Ve]=Ct(Y),[nt,Xe]=Ct(null),[In,at]=Ct(null),[Hn,Wt]=Ct(!1),[Pn,Zt]=Ct(void 0),[ir,Bt]=Ct(""),[kt,en]=Ct(!1),[tn,Ft]=Ct(!1),Dt=Nt(0),[wt,ne]=Ct("loading"),[Kn,D]=Ct(0),it=Nt(!1),Lt=Nt(!1),Ln=Nt(!1),Be=Nt(null),st=gn(()=>({checkoutMode:Ee??be,layout:K?"unknown":S==="buttons"?"buttons":"embedded"}),[Ee,K,be,S]),He=Nt(x);He.current=x;let _n=Nt(g);_n.current=g;let xn=Nt(w);xn.current=w,Fn(()=>{At(J)?.setCheckoutContext(st),Je&&Je!==J&&At(Je)?.setCheckoutContext(st)},[J,Je,st]);let zn=Nt(q);zn.current=q;let Wn=ar(_=>{ne(_),!(_!=="exhausted"||Ln.current)&&(Ln.current=!0,_n.current?.(new It("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Tn=ar(()=>{ne("retrying"),D(_=>_+1)},[]);Fn(()=>{ne("loading"),D(0),Ln.current=!1},[Ne]),Fn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:ns,checkout_type:Oe,checkout_layout:me,billing_api_url:C})},[me,Oe,C]);let rt=gn(()=>n?Ut(n,!0):"",[n]),zt=gn(()=>ir===rt?Pn:void 0,[Pn,ir,rt]),dn=gn(()=>n?ra(n,zt):void 0,[n,zt]),Pt=Ee??dn?.checkoutMode??"full",xt=gn(()=>dn?{...dn,checkoutMode:Pt}:void 0,[dn,Pt]);Fn(()=>{Zt(void 0),Bt(rt)},[rt]),Fn(()=>{Ve(Y)},[Y]);let nn=ar((_,z,M)=>{Ke(()=>{xn.current?.(Et(_,z,M))})},[Ke]),un=ar(async(_,z)=>{Ve(null),at(null),Wt(!1),Xe("processing");let M=z?.sessionId??_.id,ve=mt.current??A.current,Ce=At(ve),m=ve?null:Fo(C,r,st),o={log:p=>{Ce?Ce.log(p):m?.log(p)},error:p=>{Ce?Ce.error(p):m?.error(p)},terminal:p=>{Ce?Ce.terminal(p):m?.terminal(p)},performance:p=>{Ce?Ce.performance(p):m?.performance(p)},now:()=>Ce?.now()??m?.now()??0,elapsed:p=>Ce?.elapsed(p)??Math.max(0,(m?.now()??p)-p)},y=o.now(),B=!!(z?.initialAutoProcessingError||z?.initialAutoProcessingPending),P=!1,U,Fe=()=>{P||(P=!0,B=!0,U=o.now(),o.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),o.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Qe=!1,Q=()=>{Qe||(Qe=!0,o.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),o.performance({stage:"processing",durationMs:o.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}),U!==void 0&&o.performance({stage:"recovery",durationMs:o.elapsed(U),durationMode:"machine",paymentMethodCategory:"saved"}))};o.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),o.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),B&&Fe();let $;try{let p=Ki(z?.initialAutoProcessingError),O;if(p)Fe(),p.type==="paypal_redirect_required"&&Be.current?.publishableKey&&Zi({sessionId:M,publishableKey:Be.current.publishableKey,paypalPublishableKey:Be.current.paypalPublishableKey}),O=await xo(p,{flopay:mt.current,paypalFlopay:A.current,attempt3DS:z?.attempt3DS,billingApiUrl:C,sessionId:M,session:_,telemetry:!1}),p.type==="paypal_redirect_required"&&ka();else if(z?.initialAutoProcessingPending){let Me=(await new Ao(C,{telemetry:!1}).waitForCheckoutSessionCompletion(z.initialAutoProcessingPending.sessionId,{initialDelayMs:z.initialAutoProcessingPending.retryAfterMs})).data.session;if(!gr(Me))throw vo(Me);O=er(Me,M)}else{if(z?.initialAutoProcessingError)throw Vn(z.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:z.initialAutoProcessingError.checkoutMethod});if(z?.fromCreateSession)return z?.fallbackToFull&&(Ye("full"),ts("full")),!1;{let he=await Sr({billingApiUrl:C,sessionId:M,session:_,telemetry:!1});he.type==="success"?O=he.result:(Fe(),he.type==="paypal_redirect_required"&&Be.current?.publishableKey&&Zi({sessionId:M,publishableKey:Be.current.publishableKey,paypalPublishableKey:Be.current.paypalPublishableKey}),O=await xo(he,{flopay:mt.current,paypalFlopay:A.current,attempt3DS:z?.attempt3DS,billingApiUrl:C,sessionId:M,session:_,telemetry:!1}),he.type==="paypal_redirect_required"&&ka())}}M&&hr(M),Q(),B&&(o.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),o.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),o.terminal({outcome:O.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Wt(O.status==="authorized"),Xe("success"),await Qr(fn),$=()=>He.current?.(O)}catch(p){let O=or(p),he=O.checkoutMethod??Xr;Ve(O.message),at(O.message),Wt(!1),z?.fallbackToFull&&(o.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Ye("full"),ts("full")),Q();let Ie=O.statusCode!==void 0?Vl(O.statusCode,"unknown"):void 0,Me=Ie==="4xx"?{requestCategory:"process_payment",statusClass:Ie}:{},vn=Ie===void 0||Ie==="4xx";if(vn&&(O.telemetryOutcome==="payment_declined"||!!(O.declineCode||O.code?.toLowerCase().includes("declin"))))o.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Me});else if(vn&&(O.telemetryOutcome==="validation_rejected"||O.type==="validation_error"))o.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Me});else{let ro=Gi(p,B?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");o.error({...ro,...O.telemetryFailureCategory?{failureCategory:O.telemetryFailureCategory}:{},stage:B?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:O.telemetryRequestCategory??"process_payment"})}return Ke(()=>_n.current?.(O)),nn(he,O,{code:O.code,declineCode:O.declineCode}),Xe("error"),await Promise.allSettled([Qr(Jt),z?.ensureProvidersReady?z.ensureProvidersReady():Promise.resolve()]),B&&(o.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),o.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Q(),m&&Zr(m),Xe(null),at(null)}return Ke($),!0},[nn,Ke,or,C,r,st]);Fn(()=>{if(typeof window>"u"||Lt.current)return;let _=new URLSearchParams(window.location.search),z=_.get("payment_intent_client_secret");if(!z)return;let M=Kl();M&&(Lt.current=!0,(async()=>{let ve,Ce=0;Ve(null),at(null),Xe("processing"),St(!0);try{if(_.get("redirect_status")==="failed")throw Object.assign(new It("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:m,paypalFlopay:o}=await Mo({publishableKey:M.publishableKey,paypalPublishableKey:M.paypalPublishableKey,billingApiUrl:C,locale:c,telemetry:r});ve=At(o??m),Ce=ve?.now()??0,ve?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ve?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let y=(o??m)?.getRawProvider();if(!y)throw Object.assign(new It("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:P}=await y.retrievePaymentIntent(z);if(P)throw Object.assign(new It(P.message??"Failed to retrieve PayPal payment status.","api_error",{code:P.code}),{checkoutMethod:"paypal"});let U=hi(B?.status);if(!B||U==="failed")throw Object.assign(new It("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Fe=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id,Qe=U;if(M.sessionId){let p=(await new Ao(C,{telemetry:!1}).getUnifiedCheckoutSession(M.sessionId)).data.session;if(p&&p.status!=="complete"){let O=await Sr({billingApiUrl:C,sessionId:M.sessionId,session:p,telemetry:!1,tokenizedData:{id:Fe??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0}});if(O.type!=="success")throw Object.assign(new It("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Qe=O.result.status}}M.sessionId&&hr(M.sessionId),ve?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ve?.performance({stage:"redirect_resume",durationMs:ve.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ve?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Xe("success"),await Qr(fn),Ke(()=>He.current?.({status:Qe,paymentIntentId:B.id,paymentMethodId:Fe,checkoutMethod:"paypal"}))}catch(m){let o=or(m),y=o.checkoutMethod??"paypal",B=!!(o.declineCode||o.code?.toLowerCase().includes("declin"));if(ve)ve.performance({stage:"redirect_resume",durationMs:ve.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?ve.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ve.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let P=Fo(C,r,st);P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Zr(P)}else Sa(C,r,st,"REDIRECT_RESUME_FAILED","redirect_resume");Ve(o.message),at(o.message),Ke(()=>_n.current?.(o)),nn(y,o,{code:o.code,declineCode:o.declineCode}),Xe("error"),await Qr(Jt)}finally{ka(),Xl(),Xe(null),at(null),St(!1)}})())},[nn,Ke,c,or,C,r]);let Yt=Nt(null);function Ut(_,z=!1){let M=_?.account?.email?.trim().toLowerCase()??"",ve={c:_?.clientId,cur:_?.currency??"",captureMethod:_?.captureMethod??"",a:{e:M,u:M?"":_?.account?.userId??"",country:_?.account?.country??""},successUrl:_?.successUrl,cancelUrl:_?.cancelUrl,p:_?.products?.map(o=>Ra(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:_?.items?.map(o=>Ra(o.code??o.providerItemId??"",o)).sort(),s:_?.subscriptions?.map(o=>Ra(o.code??o.providerPlanId??"",o)).sort(),couponCodes:_?.couponCodes?[..._.couponCodes].sort():void 0,...z?{tagsData:_?.tagsData,utmMetadata:_?.utmMetadata,tokenizedData:_?.tokenizedData,checkoutMode:_?.checkoutMode??"full"}:{}},Ce=JSON.stringify(ve),m=0;for(let o=0;o<Ce.length;o++)m=(m<<5)-m+Ce.charCodeAt(o)|0;return`flopay_session_${Math.abs(m).toString(36)}`}let $t=gn(()=>xt?Ut(xt):"",[xt]),Te=Nt(xt);Te.current=xt,Fn(()=>{ft(e??"")},[e]),Fn(()=>{it.current=!1,Ve(Y),at(null),Wt(!1),Xe(null)},[$t,Y,e]);async function qt(_,z){let M=Fo(C,r,st),ve=new Ao(C,{telemetry:!1}),Ce=!1;try{let m=_.idempotencyKey!==void 0?Xi(_.idempotencyKey):void 0,o=m??Yl(z),y,B=!1,P=Wl(z);M.log({name:P?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let U=P?.sid??null,Fe=null,Qe;if(U)try{if(Fe=await ve.getUnifiedCheckoutSession(U,P?.nonce),Fe.data.session?.status==="complete"){if(aa(U))return{sid:U,result:Fe};Jl(z),U=null,Fe=null,B=!0}}catch{M.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ia(z),U=null}if(!U){!m&&(B||!o)&&(o=Xi(),y=o),o&&Gl(z,o);let Q=M.now(),$=0;M.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let p={..._,idempotencyKey:o,avsCheck:!!Re,avsConfig:typeof Re=="object"?Re:void 0,checkoutType:"embedded_checkout",checkoutLayout:K?"custom_layout":S==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(p,Nl,{configurable:!1,enumerable:!1,value:{onAttempt:Ie=>{$=Math.max($,Ie)}}});let O=()=>{M.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),M.performance({stage:"session_create",durationMs:M.now()-Q,durationMode:"machine",requestCategory:"session_create",attempt:$,statusClass:"2xx"})},he=Ie=>{let Me=Gi(Ie,"CHECKOUT_SESSION_CREATE_FAILED","unknown");M.performance({stage:"session_create",durationMs:M.now()-Q,durationMode:"machine",requestCategory:"session_create",attempt:$,statusClass:Me.statusClass}),Ie instanceof It&&Ie.type==="validation_error"?M.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):Me.statusClass==="4xx"?M.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):M.error({...Me,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if(Ul(p)){let Ie=await ve.createDetachedSession(p);Ie.claimed.catch(()=>{}),Fe=Ie.shell,U=Ie.sessionId,Qe=Ie.claimed.then(Me=>{let vn=Me.data.session?.id??Ie.sessionId;return vn&&es(z,vn,Me.data.session?.clientSecret??Ie.nonce),O(),Me},Me=>{throw Ia(z),he(Me),Me}).finally(()=>Zr(M)),Qe.catch(()=>{}),Ce=!0,M.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),M.performance({stage:"session_shell",durationMs:M.now()-Q,durationMode:"machine",requestCategory:"session_create",attempt:$,statusClass:"2xx",paymentMethodCategory:"card"})}else Fe=await ve.createAndFetchSession(p),O()}catch(Ie){throw he(Ie),Ie}U=Fe.data.session?.id??U??"",U&&!Qe&&es(z,U,Fe.data.session?.clientSecret)}return{sid:U??"",result:Fe,sdkGeneratedIdempotencyKey:y,...Qe?{claimed:Qe}:{}}}finally{Ce||Zr(M)}}let gt=ar(async(_,z)=>{let M=Te.current;if(!M)throw new It("createSession is required to bootstrap checkout.","validation_error");let ve=ra(M,_),Ce=Ut(ve),m=Do.get(Ce);if(!m){let B={promise:qt(ve,Ce),consumers:0,settled:!1};m=B,Do.set(Ce,B);let P=()=>{B.settled=!0,Qi(Ce,B)};B.promise.then(P,P)}m.consumers+=1;let o=!1,y=()=>{o||(o=!0,m.consumers-=1,Qi(Ce,m))};z?.(y);try{let B=await m.promise;Yt.current=Ce,_&&(Bt(rt),Zt(O=>yi(O,_)));let{sid:P,result:U,claimed:Fe}=B;if(ue(U),U.data.session&&tt(U.data.session),P&&ft(P),Fe){let O=Dt.current+=1;Ft(!0),Fe.then(he=>{Dt.current===O&&(ue(he),he.data.session&&tt(he.data.session),Ft(!1))},he=>{Dt.current===O&&(Ft(!1),I(he instanceof It?he:new It(he instanceof Error?he.message:"Failed to create session","api_error")))})}else Dt.current+=1,Ft(!1);let{publishableKey:Qe,paypalPublishableKey:Q}=To(U),{flopay:$,paypalFlopay:p}=await Mo({publishableKey:Qe,paypalPublishableKey:Q,billingApiUrl:C,locale:c,telemetry:r});return mt.current=$,_e($),A.current=p,yt(p),Ge(!1),B}catch(B){throw Yt.current===Ce&&(Yt.current=null),B}finally{z||y()}},[c,C,r,st]),bn=Nt(un);bn.current=un;let Yn=Nt(gt);Yn.current=gt;let Vt=ar(async _=>{if(!Ql(_)||kt)return{sessionId:qe,session:X};en(!0);try{let z=await gt(_);return{sessionId:z.sid,session:z.result.data.session??null}}finally{en(!1)}},[gt,kt,qe,X]);Fn(()=>{let _=!1,z;if(I(null),$t){let Ce=Te.current;return Ye(Pt),Ge(!1),Yt.current===$t?()=>{_=!0}:(tt(fi(Ce,Ee)),(async()=>{let m=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),o=Pt==="auto"&&!it.current&&!m;o&&(Ve(null),at(null),Xe("processing"));try{let y=await Yn.current(void 0,Fe=>{z=Fe}),B=y.result.data.session??null;Be.current=To(y.result);let P=wa(y.result),U=aa(y.sid||B?.id);if(!_&&o&&B&&!P&&!U){it.current=!0,await jl($t,y.sdkGeneratedIdempotencyKey,()=>bn.current(B,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:y.result.autoProcessingError,initialAutoProcessingPending:y.result.autoProcessingPending,autoProcessingAttempted:y.result.autoProcessingAttempted,sessionId:y.sid||B.id}));return}!_&&o&&((P||U)&&(it.current=!0),Xe(null),at(null))}catch(y){if(_)return;let B=y instanceof It||typeof y=="object"&&y!==null&&"code"in y?y.code:void 0;if(o&&B==="session_auto_completed"){it.current=!0,Xe("success"),await Qr(fn),_||(Ke(()=>{He.current?.({status:"succeeded"})}),Xe(null),at(null));return}o&&(Xe(null),at(null));let P=y instanceof It?y:new It(y instanceof Error?y.message:"Failed to create session","api_error");I(P)}finally{z?.(),z=void 0}})(),()=>{_=!0,z?.()})}Ge(!0);async function M(){let Ce=!1;try{let o=await new Ao(C,{telemetry:!1}).getUnifiedCheckoutSession(Ne,t);if(_)return;ue(o);let y=o.data.session??null;if(tt(y),!y)throw new It("No session data returned","api_error");let B=y.checkoutMode;if(B==="setup")throw new It("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(y.status==="authorized"){Ge(!1),Ke(()=>{He.current?.(er(y,Ne)),zn.current?.(y.successUrl??"")});return}if(y.status==="complete"){Ge(!1),Ke(()=>{zn.current?.(y.successUrl??"")});return}if(y.status==="expired")throw bo(y);Ce=!0;let P=Ee??B??"full";Ye(P);let U=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Fe=wa(o);if(P==="auto"&&!it.current&&!U&&!Fe){it.current=!0;let Qe=ve(o);try{if(await bn.current(y,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Qe,sessionId:Ne||y.id}),_)return;await Qe,_||Ge(!1);return}catch{if(_)return;await Qe,_||Ge(!1);return}}await ve(o),_||Ge(!1)}catch(m){if(_)return;m instanceof It?!Ce&&!Hl(m)&&Sa(C,r,st,"NETWORK_REQUEST_FAILED","session_read"):Sa(C,r,st,"INTERNAL_SDK_ERROR","checkout_mount");let o=m instanceof It?m:new It(m instanceof Error?m.message:"Failed to initialize checkout","api_error");I(o),Ge(!1)}}async function ve(Ce){let{publishableKey:m,paypalPublishableKey:o}=To(Ce);Be.current={publishableKey:m,paypalPublishableKey:o};let{flopay:y,paypalFlopay:B}=await Mo({publishableKey:m,paypalPublishableKey:o,billingApiUrl:C,locale:c,telemetry:r});mt.current=y,_e(y),A.current=B,yt(B)}return M(),()=>{_=!0}},[Ee,$t,Pt,We,Ke,t]);let jt=ar(async()=>{if(!(xe||!X)){St(!0),Ve(null);try{await un(X,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ne||X.id})}finally{St(!1)}}},[Ne,xe,un,X]),Ot=Ea(T),On=wa(T),Nn=gn(()=>{if(!T||!X||!T.data.stripe?.publishableKey)return;let _={appearance:$e,paymentMethodCreation:"manual",billingApiUrl:C};if(T.data.stripe?.clientSecret)_.clientSecret=T.data.stripe.clientSecret;else{let z=Ji(X).total;_.amount=Math.round(z*100)||X.amount,_.currency=X.currency?.toLowerCase()}return _},[T,X,$e,C]),rn=!!(n&&!K&&S==="buttons"&&ce&&Pt==="full"),Gt=gn(()=>({session:X,loading:Xt,error:Qt,checkoutMode:be,inlineSessionDraft:xt,applyInlineSessionPatch:rn?Vt:void 0,inlineSessionPatchProcessing:kt,claimPending:tn}),[X,Xt,Qt,be,xt,rn,Vt,kt,tn]),on=!!n&&S==="buttons"&&!On&&(!J||!Nn),Ue=nt?re(cn,{status:nt,errorMessage:In,authorized:Hn}):null;if(Xt){if(l)return _t(En,{children:[l,Ue]});if(S==="buttons"){let _=ie?.buttonsLayout?.cardButton?.borderRadius??ie?.appearance.variables?.borderRadius??8,z=M=>re("div",{style:{height:M,borderRadius:_,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return _t(En,{children:[_t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[d&&z(wr),h&&(E||f)&&z(wr),h&&z(wr),re("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ue]})}return _t(En,{children:[_t("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[re("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),re("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ue]})}return Qt?b?re(yn.Provider,{value:Gt,children:b(Qt)}):re(yn.Provider,{value:Gt,children:re("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Qt.message})}):on?_t(En,{children:[re(yn.Provider,{value:Gt,children:re(ec,{onButtonClick:j,showPayPal:d,showStripe:h,showApplePay:E,showGooglePay:f,theme:le,buttonsTheme:Z,buttonsStyles:F,cardButtonContent:G,cardBackButtonContent:W,cardTitleContent:oe})}),Ue]}):On&&X&&Ot?_t(En,{children:[re(yn.Provider,{value:Gt,children:_t("div",{className:pe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[je&&re(yr,{icon:!1,children:je}),wt==="retrying"&&re("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),wt==="exhausted"&&_t("div",{role:"alert",children:[re("div",{children:"PayPal is temporarily unavailable. Please try again."}),re("button",{type:"button",onClick:Tn,children:"Retry PayPal"})]}),wt!=="exhausted"&&re("div",{"aria-hidden":wt==="retrying"?!0:void 0,style:wt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:re(ki,{sessionId:Ne,nonce:X.clientSecret||void 0,billingApiUrl:C,email:X.customer?.email,clientId:Ot.clientId,environment:Ot.environment,currency:(X.currency??"usd").toUpperCase(),isSubscription:X.mode==="subscription",onComplete:x,onErrorChange:Ve,onDecline:w,onButtonClick:j,onInitializationStateChange:Wn,allowAutomaticRetry:Kn===0,session:X,telemetry:r,telemetryContext:st,debug:de},`paypal-init-${Kn}`)})]})}),Ue]}):!J||!Nn?re(En,{children:Ue}):be==="confirm"?_t(En,{children:[re(yn.Provider,{value:Gt,children:re(go,{flopay:J,paypalFlopay:Je,options:Nn,children:_t("div",{className:pe,children:[je&&re("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:je}),te?te({onConfirm:jt,isProcessing:xe}):re("button",{type:"button",onClick:jt,disabled:xe,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:xe?"not-allowed":"pointer",opacity:xe?.6:1},children:xe?"Processing...":ge??"Confirm Purchase"})]})})}),Ue]}):_t(En,{children:[re(yn.Provider,{value:Gt,children:re(go,{flopay:J,paypalFlopay:Je,options:Nn,children:K?_t(En,{children:[je&&re("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:je}),re(Zl,{sessionId:Ne,nonce:X?.clientSecret||void 0,billingApiUrl:C,session:X,children:K})]}):re(Pa,{sessionId:Ne,nonce:X?.clientSecret||void 0,email:X?.customer?.email,userId:X?.customer?.id,firstName:X?.customer?.firstName,lastName:X?.customer?.lastName,totalAmount:X?Math.round(Ji(X).total*100):0,currency:X?.currency?.toLowerCase()??"usd",onComplete:x,onError:g,onDecline:w,error:je,onErrorChange:Ve,showPayPal:d,showStripe:h,enabledPaymentMethods:k??T?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:T?.data.stripe?.enabledPaymentMethodCountries,showApplePay:E,showGooglePay:f,layout:S,theme:le,buttonsTheme:Z,buttonsStyles:F,appearance:$e,cardButtonContent:G,cardBackButtonContent:W,cardTitleContent:oe,onButtonClick:j,onBeforeButtonClick:ce,enableAVS:Re,...fe?{cardFieldOrder:fe}:{},...ae?{cardPreFormSlot:ae}:{},avsLayout:ee,country:X?.customer?.country,city:X?.customer?.city,state:X?.customer?.state,onCountryChange:v,onZipChange:R,avsCheck:!!Re,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:K?"custom_layout":S==="buttons"?"buttons_layout":"default_layout",className:pe,directPaypal:Ea(T),isSubscription:X?.mode==="subscription",session:X,dataAttachmentPending:tn,debug:de})})}),Ue]})}function Zl({sessionId:e,nonce:t,billingApiUrl:n,session:a,children:r}){return re(En,{children:Ca.Children.map(r,i=>{if(!Ca.isValidElement(i))return i;let c=i.props,l={};return c.sessionId||(l.sessionId=e),!c.nonce&&t&&(l.nonce=t),c.billingApiUrl||(l.billingApiUrl=n),a?.customer&&(c.email||(l.email=a.customer.email),c.userId||(l.userId=a.customer.id),c.firstName||(l.firstName=a.customer.firstName),c.lastName||(l.lastName=a.customer.lastName)),Object.keys(l).length===0?i:Ca.cloneElement(i,l)})})}function ec({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:a,showGooglePay:r,theme:i,buttonsTheme:c,buttonsStyles:l,cardButtonContent:b,cardBackButtonContent:x,cardTitleContent:g}){let[w,v]=Ct(!1),R=gn(()=>rs(i),[i]),d=gn(()=>{let f=R?.buttonsLayout??ql(c);return l?{...f,...l,cardButton:{...f.cardButton,...l.cardButton},cardFormContainer:{...f.cardFormContainer,...l.cardFormContainer},backButton:{...f.backButton,...l.backButton},backButtonIcon:{...f.backButtonIcon,...l.backButtonIcon},submitButton:{...f.submitButton,...l.submitButton},title:{...f.title,...l.title}}:f},[R,c,l]),h=R?.buttonsLayout?.cardButton?.borderRadius??R?.appearance.variables?.borderRadius??8,k=f=>re("div",{style:{height:f,borderRadius:h,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),E=b===void 0?{boxSizing:"border-box",height:wr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(w){let f=d.cardInputBorder??"#e5e7eb",de=d.cardInputBackground??"white",S=cr(x),le=cr(g);return _t("div",{style:{backgroundColor:d.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...d.cardFormContainer},children:[_t("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[_t("button",{type:"button",onClick:()=>v(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:S?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...d.backButton},children:[re("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...d.backButtonIcon},children:re("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:re("path",{d:"M15 18l-6-6 6-6"})})}),re(ur,{content:x})]}),le?re("div",{style:{flex:1}}):re("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...d.title},children:re(qr,{content:g})})]}),re("div",{style:{backgroundColor:de,border:`1px solid ${f}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:re("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),_t("div",{style:{display:"flex"},children:[re("div",{style:{flex:1,backgroundColor:de,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomLeftRadius:8,padding:12,height:45},children:re("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{flex:1,backgroundColor:de,borderTop:"none",borderRight:`1px solid ${f}`,borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomRightRadius:8,padding:12,height:45},children:re("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),re("div",{style:{backgroundColor:de,border:`1px solid ${f}`,borderRadius:8,marginTop:8,padding:12,height:45},children:re("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...d.submitButton,opacity:.5}}),re("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 _t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&w(wr),n&&(a||r)&&w(wr),n&&ie("button",{type:"button",onClick:()=>{e?.("card"),v(!0)},style:{width:"100%",...R,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:d.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...d.cardButton},onMouseDown:f=>{f.currentTarget.style.transform="scale(0.985)"},onMouseUp:f=>{f.currentTarget.style.transform="scale(1)"},children:ie(dr,{content:b})}),ie("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{dropThirdPartyOnlyError as Ep}from"@flopay/shared";import{useEffect as ec,useRef as os,useContext as tc}from"react";import{jsx as oc}from"react/jsx-runtime";function as(e,t){function n({className:a,id:r,style:s,options:c,onChange:l,onReady:b,onFocus:x,onBlur:g,onEscape:S}){let v=os(null),k=os(null),{elements:d,reportInteractive:h}=tc(xn);return ec(()=>{if(!d||!v.current)return;let w=!0;return(async()=>{let R=d.getElement(e);R||(R=await d.create(e,c)),!(!w||!v.current)&&(R.mount(v.current),k.current=R,l&&R.on("change",l),R.on("ready",()=>{h?.(),b?.()}),x&&R.on("focus",x),g&&R.on("blur",g),S&&R.on("escape",S))})(),()=>{if(w=!1,k.current){try{k.current.unmount()}catch{}k.current=null}}},[d,h]),oc("div",{ref:v,className:a,id:r,style:s})}return n.displayName=t,n}var nc=as("payment","PaymentElement"),rc=as("address","AddressElement");import{useEffect as xa,useMemo as ac,useRef as Dn,useState as Ta}from"react";import{PaymentAPI as ic,PciVaultCardCapture as sc}from"@flopay/js";import{FloPayError as kr,isCardSetupCheckoutSession as lc,resolveBillingApiUrl as cc,resolveTheme as dc}from"@flopay/shared";import{Fragment as pc,jsx as Ma}from"react/jsx-runtime";var Do=class extends kr{constructor(t,n,a){super(t,n,a),this.name="FloPayCardSetupError",this.retryable=a.retryable}};function is(e,t={}){let n=e instanceof kr?e:void 0,a=n?.statusCode,r=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof a=="number"&&a>=500||n?.code==="vault_capture_timeout"||!n);return new Do(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}:{},...a!==void 0?{statusCode:a}:{}})}function uc({sessionId:e,nonce:t,billingApiUrl:n,telemetry:a,theme:r="modern-light",containerStyle:s,loading:c=null,onReady:l,onComplete:b,onDecline:x,onCancel:g,onValidation:S,onError:v}){let[k,d]=Ta(null),[h,w]=Ta(null),[R,f]=Ta(null),de=ac(()=>{if(typeof r=="object")return r;let z=dc(r);if(z)return go({appearance:z.appearance,buttonsStyles:z.buttonsLayout,layout:"default"})},[r]),E=Dn(l),re=Dn(v),Z=Dn(b),L=Dn(x),Y=Dn(g),K=Dn(S),te=Dn(!1),U=Dn(!1),V=Dn(0);return E.current=l,re.current=v,Z.current=b,L.current=x,Y.current=g,K.current=S,xa(()=>{let z=V.current+1;return V.current=z,()=>{queueMicrotask(()=>{V.current===z&&(te.current||U.current||(U.current=!0,Ke(()=>{Y.current?.({status:"cancelled",sessionId:e})})))})}},[e]),xa(()=>{let z=!0,me=new ic(cc(n),{telemetry:a});return d(null),w(null),f(null),te.current=!1,U.current=!1,(async()=>{try{if(!e.trim())throw new kr("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new kr("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ee=await me.getUnifiedCheckoutSession(e,t);if(!z)return;let oe=ee.data.session;if(!oe||!lc(oe))throw new kr("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let G=oe.vault;if(G?.html?.trim()||(G=await me.getVaultCapture(e,t)),!G.html?.trim())throw new kr("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!z)return;w(G),d(new sc({sessionId:e,operation:"card_setup",telemetry:a}))}catch(ee){if(!z)return;let oe=is(ee);te.current=!0,f(oe),Ke(()=>re.current?.(oe))}})(),()=>{z=!1,me.destroy()}},[n,t,e,a]),xa(()=>{if(!k)return;let z=k.on("complete",ee=>{te.current=!0,Ke(()=>{Z.current?.({status:"succeeded",sessionId:e,...ee.paymentMethod?{paymentMethod:ee.paymentMethod}:{}})})}),me=k.on("decline",ee=>{te.current=!0,Ke(()=>{L.current?.({status:"declined",sessionId:e,...ee.declineReason?{reason:ee.declineReason}:{},...ee.message?{message:ee.message}:{}})})});return()=>{z(),me()}},[k,e]),R?Ma("div",{role:"alert",children:R.message}):!k||!h?.html?Ma(pc,{children:c}):Ma(jr,{capture:k,html:h.html,messageToken:h.messageToken,expectedOrigin:h.expectedOrigin,theme:de,containerStyle:s,onReady:()=>{Ke(()=>E.current?.())},onValidation:z=>{Ke(()=>K.current?.(z))},onError:z=>{if(!z)return;let me=is(new Error(z),{code:"card_setup_widget_failed",retryable:!0});Ke(()=>re.current?.(me))}})}import{PaymentAPI as mc}from"@flopay/js";import{FloPayError as yc}from"@flopay/shared";import{useCallback as Aa,useEffect as fc,useRef as gc,useState as ss}from"react";import{Fragment as Pc,jsx as Rr,jsxs as bc}from"react/jsx-runtime";function hc({sessionId:e,nonce:t,billingApiUrl:n,email:a,userId:r,firstName:s,lastName:c,chv:l,onTokenizedBody:b,onComplete:x,onErrorChange:g,isProcessing:S=!1}){let v=bn(),k=ea(),d=ho(),[h,w]=ss(!1),[R,f]=ss(!1),de=gc(!1),E=(n||d).replace(/\/+$/,""),re=Aa(async Y=>{try{let te=await new mc(E).processPayment(r??"",{sessionId:e,nonce:t,tokenizedData:Y,accountData:{userId:r??"",email:a??"",firstName:s??"",lastName:c??""},chv:l});if(te.ok){x?.();return}let U=await te.json().catch(()=>null);g?.(U?.message??"Payment failed. Please try again.")}catch(K){g?.(K instanceof Error?K.message:"An unexpected error occurred")}},[E,e,t,r,a,s,c,l,x,g]),Z=Aa(Y=>{b?b(Y):re(Y)},[b,re]);fc(()=>{if(!v||de.current)return;let Y=new URLSearchParams(window.location.search),K=Y.get("payment_intent"),te=Y.get("payment_intent_client_secret"),U=Y.get("redirect_status");!K||!te||(de.current=!0,(async()=>{try{if(f(!0),U==="failed"){g?.("PayPal payment was declined. Please try again.");return}let V=v.getRawProvider();if(!V?.retrievePaymentIntent){g?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:z,error:me}=await V.retrievePaymentIntent(te);if(me){g?.(me.message??"Failed to retrieve PayPal payment status.");return}if(z&&(z.status==="requires_capture"||z.status==="succeeded")){let ee=typeof z.payment_method=="string"?z.payment_method:z.payment_method?.id;Z({id:ee??z.id,type:"card",threeDSecureActionResultTokenId:z.id,isPaypal:!0});let oe=new URL(window.location.href);oe.searchParams.delete("payment_intent"),oe.searchParams.delete("payment_intent_client_secret"),oe.searchParams.delete("redirect_status"),window.history.replaceState({},"",oe.toString())}else g?.("PayPal payment was not completed. Please try again.")}catch(V){g?.(V instanceof Error?V.message:"Failed to complete PayPal payment.")}finally{f(!1)}})())},[v,Z,g]);let L=Aa(async()=>{if(!(!v||!k))try{if(f(!0),g?.(null),!e||!a)throw new yc("Missing sessionId or email for PayPal payment","validation_error");let Y=await v.confirmPayPalPayment({billingApiUrl:E,sessionId:e,nonce:t,email:a,returnUrl:window.location.href});if(Y.error){g?.(Y.error.message);return}Y.paymentIntentId&&(Y.status==="succeeded"||Y.status==="processing"||Y.status==="requires_capture")&&Z({id:Y.paymentMethodId??Y.paymentIntentId,type:"card",threeDSecureActionResultTokenId:Y.paymentIntentId,isPaypal:!0})}catch(Y){g?.(Y instanceof Error?Y.message:"PayPal payment failed. Please try again.")}finally{f(!1)}},[v,k,e,t,a,E,Z,g]);return!v||!k?Rr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):bc(Pc,{children:[!h&&Rr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),Rr("div",{style:h?{}:{display:"none"},children:Rr("button",{type:"button",onClick:L,disabled:R||S,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:R||S?"not-allowed":"pointer",opacity:R||S?.6:1},ref:()=>w(!0),children:R?"Processing...":"PayPal"})}),(R||S)&&Rr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:Rr("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..."})})]})}import{useCallback as jn,useEffect as Er,useMemo as eo,useRef as Ir,useState as to}from"react";import{PaymentAPI as Ba}from"@flopay/js";import{FloPayError as xr,resolveBillingApiUrl as vc,resolveButtonsLayoutTheme as Cc,resolveTheme as Sc}from"@flopay/shared";import{Fragment as _c,jsx as _r,jsxs as xc}from"react/jsx-runtime";var wc=44;function ls(e){return new Promise(t=>setTimeout(t,e))}function kc(e,t){return e instanceof xr?e:new xr(e instanceof Error?e.message:t,"api_error")}function Rc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Ec(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 Ic({sessionId:e,nonce:t,createSession:n,paymentMethodId:a,checkoutMethod:r,clientId:s,products:c,items:l,subscriptions:b,account:x,successUrl:g,cancelUrl:S,couponCodes:v,tagsData:k,utmMetadata:d,billingApiUrl:h,locale:w,theme:R,appearance:f,buttonsTheme:de,buttonsStyles:E,onSuccess:re,onError:Z,onDecline:L,children:Y,disabled:K=!1,type:te="button",style:U,...V}){let z=eo(()=>vc(h),[h]),me=eo(()=>Ec({createSession:n,clientId:s,products:c,items:l,subscriptions:b,account:x,successUrl:g,cancelUrl:S,couponCodes:v,tagsData:k,utmMetadata:d}),[x,S,s,v,n,c,l,b,g,k,d]),[ee,oe]=to(!1),[G,ge]=to(null),[Te,ae]=to(null),[Ue,Fe]=to(!1),[ke,W]=to(null),C=Ir(!0),se=Ir(null),$e=Ir(ke),ze=Ir(re),ue=Ir(Z),T=Ir(L);Er(()=>{$e.current=ke},[ke]),Er(()=>{ze.current=re},[re]),Er(()=>{ue.current=Z},[Z]),Er(()=>{T.current=L},[L]),Er(()=>(C.current=!0,()=>{C.current=!1,se.current?.abort()}),[]),Er(()=>{if(typeof window>"u")return;let I=he=>{he.key==="Escape"&&W(null)};return window.addEventListener("keydown",I),()=>{window.removeEventListener("keydown",I)}},[]);let ce=jn((I,he=Xr)=>{T.current?.(Et(he,I,{code:I.code,declineCode:I.declineCode}))},[]),J=jn(async I=>{C.current&&(ae(null),Fe(I.result.status==="authorized"),ge("success"),await ls(Tn),C.current&&ze.current?.(I))},[]),Re=jn(async(I,he)=>{C.current&&(ue.current?.(I),he?.emitDecline&&ce(I,he.method),ae(I.message),Fe(!1),ge("error"),await ls(vn))},[ce]),mt=jn(async(I,he,Ye)=>{let Ee=I.data.session??null;if(!Ee)throw new xr("No session data returned","api_error");let St=Ee.clientSecret||t;if(gr(Ee)){await J({result:er(Ee,he),session:Ee,sessionId:Ee.id||he,autoCompleted:!1});return}if(Ee.status==="expired")throw Po(Ee);try{if(I.autoProcessingPending){let Xe=(await new Ba(z).waitForCheckoutSessionCompletion(I.autoProcessingPending.sessionId,{initialDelayMs:I.autoProcessingPending.retryAfterMs})).data.session;if(!gr(Xe))throw bo(Xe);await J({result:er(Xe,he),session:Xe,sessionId:Xe.id||he,autoCompleted:!1});return}if(I.autoProcessingError){if(I.autoProcessingError.type==="3ds_required"&&I.autoProcessingError.nextActionRedirectUrl&&he&&St){let Ve=new AbortController;se.current=Ve;let nt;try{nt=await Wi({billingApiUrl:z,sessionId:he,nonce:St,nextActionRedirectUrl:I.autoProcessingError.nextActionRedirectUrl,signal:Ve.signal})}finally{se.current===Ve&&(se.current=null)}if(nt.status==="declined")throw Vn({type:nt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:nt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:I.autoProcessingError.checkoutMethod});let at=(await new Ba(z).waitForCheckoutSessionCompletion(he,{initialDelayMs:0,nonce:St})).data.session;if(!gr(at))throw Vn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:I.autoProcessingError.checkoutMethod});await J({result:er(at,he),session:at,sessionId:at.id||he,autoCompleted:!1});return}throw Vn(I.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:I.autoProcessingError.checkoutMethod})}if(Ye?.fromCreateSession&&I.autoProcessingAttempted===!0)throw Vn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let je=await Sr({billingApiUrl:z,sessionId:he??Ee.id,session:Ee,nonce:St});if(je.type!=="success")throw Vn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await J({result:je.result,session:Ee,sessionId:Ee.id||he,autoCompleted:!1})}catch(je){let Ve=or(je),nt=Ee.id||he;await Re(Ve,{emitDecline:!0,method:Ve.checkoutMethod??Xr}),Rc(Ve,nt)&&nt&&C.current&&W({sessionId:nt,errorMessage:Ve.message,nonce:St||void 0})}},[t,z,Re,J]),Je=jn(async I=>{if(V.onClick?.(I),!(I.defaultPrevented||K||ee)){if(W(null),e&&me){let he=new xr("Provide either sessionId or create-session props, not both.","validation_error");await Re(he),C.current&&(ge(null),ae(null));return}if(!e&&!me){let he=new xr("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Re(he),C.current&&(ge(null),ae(null));return}oe(!0),ae(null),Fe(!1),ge("processing");try{let he=new Ba(z);if(e){let Ye=await he.getUnifiedCheckoutSession(e,t);await mt(Ye,e);return}try{let Ye=await he.createAndFetchSession({...me});await mt(Ye,Ye.data.session?.id??null,{fromCreateSession:!0})}catch(Ye){if(Ye instanceof xr&&Ye.code==="session_auto_completed"){await J({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Ye}}catch(he){await Re(kc(he,"Automatic payment failed. Please try again."))}finally{C.current&&(ge(null),ae(null),oe(!1))}}},[V,me,K,ee,t,mt,z,e,Re,J]),yt=jn(I=>{let he=$e.current;W(null),ze.current?.({result:I,session:null,sessionId:he?.sessionId??null,autoCompleted:!1})},[]),A=jn(I=>{ue.current?.(I)},[]),X=jn(I=>{T.current?.(I)},[]),tt=eo(()=>Sc(R),[R]),qe=eo(()=>{let I=tt?.buttonsLayout??Cc(de);return E?{...I,...E,cardButton:{...I.cardButton,...E.cardButton}}:I},[tt,de,E]),ft=eo(()=>{let I=tt?.appearance;return f?I?{...I,...f,variables:{...I.variables,...f.variables}}:f:I},[f,tt]),Oe=ft?.variables,We=Oe?.colorPrimary??"#4A49FF",Jt=Oe?.colorPrimaryHover??mr(We,.12),Ge=Oe?.borderRadius??"8px";return xc(_c,{children:[_r("button",{...V,type:te,onClick:Je,disabled:K||ee,"aria-busy":ee,style:{width:"100%",...Y===void 0?{boxSizing:"border-box",height:wc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...qe.cardButton,...fa({themeBundle:tt,resolvedPrimaryColor:We,resolvedBorderRadius:Ge,submitButtonStyle:qe.submitButton,explicitPrimaryColor:Oe?.colorPrimary}),fontSize:qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:K||ee?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:K||ee?.6:1,...U},onMouseEnter:I=>{V.onMouseEnter?.(I),!I.defaultPrevented&&!K&&!ee&&(tt||Oe?.colorPrimary)&&(I.currentTarget.style.backgroundColor=Jt)},onMouseLeave:I=>{V.onMouseLeave?.(I),!I.defaultPrevented&&(tt||Oe?.colorPrimary)&&(I.currentTarget.style.backgroundColor=We)},onMouseDown:I=>{V.onMouseDown?.(I),I.defaultPrevented||(I.currentTarget.style.transform="scale(0.985)")},onMouseUp:I=>{V.onMouseUp?.(I),I.defaultPrevented||(I.currentTarget.style.transform="scale(1)")},children:_r(dr,{content:Y})}),G&&_r(Cn,{status:G,errorMessage:Te,authorized:Ue}),ke&&_r("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:I=>{I.target===I.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:_r("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:_r(_a,{sessionId:ke.sessionId,nonce:ke.nonce,checkoutMode:"full",billingApiUrl:z,locale:w,theme:R,...ft?{appearance:ft}:{},buttonsTheme:de,buttonsStyles:E,initialErrorMessage:ke.errorMessage,cardTitleContent:null,onComplete:yt,onError:A,onDecline:X})})})]})}export{rc as AddressElement,ko as DirectPayPalButton,Ic as FloPayAutomaticPaymentButton,uc as FloPayCardSetup,Do as FloPayCardSetupError,_a as FloPayCheckout,fo as FloPayProvider,hc as PayPalButton,nc as PaymentElement,ga as SplitCardForm,jr as VaultCardFields,Ep as dropThirdPartyOnlyError,$s as useCheckout,ea as useElements,bn as useFloPay,Zo as usePayPalFloPay};
47
+ `})]})}return _t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&k(wr),n&&(a||r)&&k(wr),n&&re("button",{type:"button",onClick:()=>{e?.("card"),v(!0)},style:{width:"100%",...E,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:d.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...d.cardButton},onMouseDown:f=>{f.currentTarget.style.transform="scale(0.985)"},onMouseUp:f=>{f.currentTarget.style.transform="scale(1)"},children:re(dr,{content:b})}),re("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{dropThirdPartyOnlyError as _p}from"@flopay/shared";import{useEffect as tc,useRef as os,useContext as nc}from"react";import{jsx as ac}from"react/jsx-runtime";function as(e,t){function n({className:a,id:r,style:i,options:c,onChange:l,onReady:b,onFocus:x,onBlur:g,onEscape:w}){let v=os(null),R=os(null),{elements:d,reportInteractive:h}=nc(Mn);return tc(()=>{if(!d||!v.current)return;let k=!0;return(async()=>{let E=d.getElement(e);E||(E=await d.create(e,c)),!(!k||!v.current)&&(E.mount(v.current),R.current=E,l&&E.on("change",l),E.on("ready",()=>{h?.(),b?.()}),x&&E.on("focus",x),g&&E.on("blur",g),w&&E.on("escape",w))})(),()=>{if(k=!1,R.current){try{R.current.unmount()}catch{}R.current=null}}},[d,h]),ac("div",{ref:v,className:a,id:r,style:i})}return n.displayName=t,n}var rc=as("payment","PaymentElement"),oc=as("address","AddressElement");import{useEffect as Ma,useMemo as ic,useRef as hn,useState as eo}from"react";import{PaymentAPI as sc,PciVaultCardCapture as lc}from"@flopay/js";import{FloPayError as kr,isCardSetupCheckoutSession as cc,resolveBillingApiUrl as dc,resolveTheme as uc}from"@flopay/shared";import{Fragment as ss,jsx as Lo,jsxs as mc}from"react/jsx-runtime";var zo=class extends kr{constructor(t,n,a){super(t,n,a),this.name="FloPayCardSetupError",this.retryable=a.retryable}};function is(e,t={}){let n=e instanceof kr?e:void 0,a=n?.statusCode,r=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof a=="number"&&a>=500||n?.code==="vault_capture_timeout"||!n);return new zo(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}:{},...a!==void 0?{statusCode:a}:{}})}function pc({sessionId:e,nonce:t,billingApiUrl:n,telemetry:a,theme:r="modern-light",containerStyle:i,loading:c=null,onReady:l,onComplete:b,onDecline:x,onCancel:g,onValidation:w,onError:v}){let[R,d]=eo(null),[h,k]=eo(null),[E,f]=eo(null),[de,S]=eo(null),[le,Z]=eo(null),F=hn(!1),G=hn(!1),W=ic(()=>{if(typeof r=="object")return r;let Y=uc(r);if(Y)return ho({appearance:Y.appearance,buttonsStyles:Y.buttonsLayout,layout:"default"})},[r]),oe=hn(l),N=hn(v),j=hn(b),ce=hn(x),Re=hn(g),fe=hn(w),ae=hn(!1),ee=hn(!1),pe=hn(0);return oe.current=l,N.current=v,j.current=b,ce.current=x,Re.current=g,fe.current=w,Ma(()=>{let Y=pe.current+1;return pe.current=Y,()=>{queueMicrotask(()=>{pe.current===Y&&(ae.current||ee.current||(ee.current=!0,Ke(()=>{Re.current?.({status:"cancelled",sessionId:e})})))})}},[e]),Ma(()=>{let Y=!0,K=new sc(dc(n),{telemetry:a});return d(null),k(null),f(null),ae.current=!1,ee.current=!1,(async()=>{try{if(!e.trim())throw new kr("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new kr("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Ee=await K.getUnifiedCheckoutSession(e,t);if(!Y)return;let ge=Ee.data.session;if(!ge||!cc(ge))throw new kr("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let te=ge.vault;if(te?.html?.trim()||(te=await K.getVaultCapture(e,t)),!te.html?.trim())throw new kr("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!Y)return;k(te),d(new lc({sessionId:e,operation:"card_setup",telemetry:a}))}catch(Ee){if(!Y)return;let ge=is(Ee);ae.current=!0,f(ge),Ke(()=>N.current?.(ge))}})(),()=>{Y=!1,K.destroy()}},[n,t,e,a]),Ma(()=>{if(!R)return;let Y=!1;G.current=!1,F.current=!1;let K=R.on("submitting",()=>{F.current=!0,Z(null),S("processing")}),Ee=R.on("complete",te=>{ae.current=!0,F.current=!1,S("success"),(async()=>(await new Promise(q=>setTimeout(q,fn)),!G.current&&(G.current=!0,Ke(()=>{j.current?.({status:"succeeded",sessionId:e,...te.paymentMethod?{paymentMethod:te.paymentMethod}:{}})}),Y||S(null))))()}),ge=R.on("decline",te=>{ae.current=!0,F.current=!1,Z(te.message??null),S("error"),Ke(()=>{ce.current?.({status:"declined",sessionId:e,...te.declineReason?{reason:te.declineReason}:{},...te.message?{message:te.message}:{}})}),(async()=>(await new Promise(q=>setTimeout(q,Jt)),Y||S(null)))()});return()=>{Y=!0,K(),Ee(),ge()}},[R,e]),E?Lo("div",{role:"alert",children:E.message}):!R||!h?.html?Lo(ss,{children:c}):mc(ss,{children:[de&&Lo(cn,{status:de,errorMessage:le,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),Lo(jr,{capture:R,html:h.html,messageToken:h.messageToken,expectedOrigin:h.expectedOrigin,theme:W,containerStyle:i,onReady:()=>{Ke(()=>oe.current?.())},onValidation:Y=>{Ke(()=>fe.current?.(Y))},onError:Y=>{if(!Y)return;F.current&&(F.current=!1,Z(Y),S("error"),setTimeout(()=>S(null),Jt));let K=is(new Error(Y),{code:"card_setup_widget_failed",retryable:!0});Ke(()=>N.current?.(K))}})]})}import{PaymentAPI as yc}from"@flopay/js";import{FloPayError as fc}from"@flopay/shared";import{useCallback as Aa,useEffect as gc,useRef as hc,useState as ls}from"react";import{Fragment as bc,jsx as Rr,jsxs as vc}from"react/jsx-runtime";function Pc({sessionId:e,nonce:t,billingApiUrl:n,email:a,userId:r,firstName:i,lastName:c,chv:l,onTokenizedBody:b,onComplete:x,onErrorChange:g,isProcessing:w=!1}){let v=wn(),R=na(),d=Po(),[h,k]=ls(!1),[E,f]=ls(!1),de=hc(!1),S=(n||d).replace(/\/+$/,""),le=Aa(async G=>{try{let oe=await new yc(S).processPayment(r??"",{sessionId:e,nonce:t,tokenizedData:G,accountData:{userId:r??"",email:a??"",firstName:i??"",lastName:c??""},chv:l});if(oe.ok){x?.();return}let N=await oe.json().catch(()=>null);g?.(N?.message??"Payment failed. Please try again.")}catch(W){g?.(W instanceof Error?W.message:"An unexpected error occurred")}},[S,e,t,r,a,i,c,l,x,g]),Z=Aa(G=>{b?b(G):le(G)},[b,le]);gc(()=>{if(!v||de.current)return;let G=new URLSearchParams(window.location.search),W=G.get("payment_intent"),oe=G.get("payment_intent_client_secret"),N=G.get("redirect_status");!W||!oe||(de.current=!0,(async()=>{try{if(f(!0),N==="failed"){g?.("PayPal payment was declined. Please try again.");return}let j=v.getRawProvider();if(!j?.retrievePaymentIntent){g?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ce,error:Re}=await j.retrievePaymentIntent(oe);if(Re){g?.(Re.message??"Failed to retrieve PayPal payment status.");return}if(ce&&(ce.status==="requires_capture"||ce.status==="succeeded")){let fe=typeof ce.payment_method=="string"?ce.payment_method:ce.payment_method?.id;Z({id:fe??ce.id,type:"card",threeDSecureActionResultTokenId:ce.id,isPaypal:!0});let ae=new URL(window.location.href);ae.searchParams.delete("payment_intent"),ae.searchParams.delete("payment_intent_client_secret"),ae.searchParams.delete("redirect_status"),window.history.replaceState({},"",ae.toString())}else g?.("PayPal payment was not completed. Please try again.")}catch(j){g?.(j instanceof Error?j.message:"Failed to complete PayPal payment.")}finally{f(!1)}})())},[v,Z,g]);let F=Aa(async()=>{if(!(!v||!R))try{if(f(!0),g?.(null),!e||!a)throw new fc("Missing sessionId or email for PayPal payment","validation_error");let G=await v.confirmPayPalPayment({billingApiUrl:S,sessionId:e,nonce:t,email:a,returnUrl:window.location.href});if(G.error){g?.(G.error.message);return}G.paymentIntentId&&(G.status==="succeeded"||G.status==="processing"||G.status==="requires_capture")&&Z({id:G.paymentMethodId??G.paymentIntentId,type:"card",threeDSecureActionResultTokenId:G.paymentIntentId,isPaypal:!0})}catch(G){g?.(G instanceof Error?G.message:"PayPal payment failed. Please try again.")}finally{f(!1)}},[v,R,e,t,a,S,Z,g]);return!v||!R?Rr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):vc(bc,{children:[!h&&Rr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),Rr("div",{style:h?{}:{display:"none"},children:Rr("button",{type:"button",onClick:F,disabled:E||w,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:E||w?"not-allowed":"pointer",opacity:E||w?.6:1},ref:()=>k(!0),children:E?"Processing...":"PayPal"})}),(E||w)&&Rr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:Rr("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..."})})]})}import{useCallback as jn,useEffect as Er,useMemo as to,useRef as Ir,useState as no}from"react";import{PaymentAPI as Ba}from"@flopay/js";import{FloPayError as xr,resolveBillingApiUrl as Cc,resolveButtonsLayoutTheme as Sc,resolveTheme as wc}from"@flopay/shared";import{Fragment as xc,jsx as _r,jsxs as Tc}from"react/jsx-runtime";var kc=44;function cs(e){return new Promise(t=>setTimeout(t,e))}function Rc(e,t){return e instanceof xr?e:new xr(e instanceof Error?e.message:t,"api_error")}function Ec(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Ic(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 _c({sessionId:e,nonce:t,createSession:n,paymentMethodId:a,checkoutMethod:r,clientId:i,products:c,items:l,subscriptions:b,account:x,successUrl:g,cancelUrl:w,couponCodes:v,tagsData:R,utmMetadata:d,billingApiUrl:h,locale:k,theme:E,appearance:f,buttonsTheme:de,buttonsStyles:S,onSuccess:le,onError:Z,onDecline:F,children:G,disabled:W=!1,type:oe="button",style:N,...j}){let ce=to(()=>Cc(h),[h]),Re=to(()=>Ic({createSession:n,clientId:i,products:c,items:l,subscriptions:b,account:x,successUrl:g,cancelUrl:w,couponCodes:v,tagsData:R,utmMetadata:d}),[x,w,i,v,n,c,l,b,g,R,d]),[fe,ae]=no(!1),[ee,pe]=no(null),[Y,K]=no(null),[Ee,ge]=no(!1),[te,q]=no(null),C=Ir(!0),ie=Ir(null),$e=Ir(te),Oe=Ir(le),me=Ir(Z),T=Ir(F);Er(()=>{$e.current=te},[te]),Er(()=>{Oe.current=le},[le]),Er(()=>{me.current=Z},[Z]),Er(()=>{T.current=F},[F]),Er(()=>(C.current=!0,()=>{C.current=!1,ie.current?.abort()}),[]),Er(()=>{if(typeof window>"u")return;let I=be=>{be.key==="Escape"&&q(null)};return window.addEventListener("keydown",I),()=>{window.removeEventListener("keydown",I)}},[]);let ue=jn((I,be=Xr)=>{T.current?.(Et(be,I,{code:I.code,declineCode:I.declineCode}))},[]),J=jn(async I=>{C.current&&(K(null),ge(I.result.status==="authorized"),pe("success"),await cs(fn),C.current&&Oe.current?.(I))},[]),_e=jn(async(I,be)=>{C.current&&(me.current?.(I),be?.emitDecline&&ue(I,be.method),K(I.message),ge(!1),pe("error"),await cs(Jt))},[ue]),mt=jn(async(I,be,Ye)=>{let xe=I.data.session??null;if(!xe)throw new xr("No session data returned","api_error");let St=xe.clientSecret||t;if(gr(xe)){await J({result:er(xe,be),session:xe,sessionId:xe.id||be,autoCompleted:!1});return}if(xe.status==="expired")throw bo(xe);try{if(I.autoProcessingPending){let Xe=(await new Ba(ce).waitForCheckoutSessionCompletion(I.autoProcessingPending.sessionId,{initialDelayMs:I.autoProcessingPending.retryAfterMs})).data.session;if(!gr(Xe))throw vo(Xe);await J({result:er(Xe,be),session:Xe,sessionId:Xe.id||be,autoCompleted:!1});return}if(I.autoProcessingError){if(I.autoProcessingError.type==="3ds_required"&&I.autoProcessingError.nextActionRedirectUrl&&be&&St){let Ve=new AbortController;ie.current=Ve;let nt;try{nt=await Wi({billingApiUrl:ce,sessionId:be,nonce:St,nextActionRedirectUrl:I.autoProcessingError.nextActionRedirectUrl,signal:Ve.signal})}finally{ie.current===Ve&&(ie.current=null)}if(nt.status==="declined")throw Vn({type:nt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:nt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:I.autoProcessingError.checkoutMethod});let at=(await new Ba(ce).waitForCheckoutSessionCompletion(be,{initialDelayMs:0,nonce:St})).data.session;if(!gr(at))throw Vn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:I.autoProcessingError.checkoutMethod});await J({result:er(at,be),session:at,sessionId:at.id||be,autoCompleted:!1});return}throw Vn(I.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:I.autoProcessingError.checkoutMethod})}if(Ye?.fromCreateSession&&I.autoProcessingAttempted===!0)throw Vn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let je=await Sr({billingApiUrl:ce,sessionId:be??xe.id,session:xe,nonce:St});if(je.type!=="success")throw Vn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await J({result:je.result,session:xe,sessionId:xe.id||be,autoCompleted:!1})}catch(je){let Ve=or(je),nt=xe.id||be;await _e(Ve,{emitDecline:!0,method:Ve.checkoutMethod??Xr}),Ec(Ve,nt)&&nt&&C.current&&q({sessionId:nt,errorMessage:Ve.message,nonce:St||void 0})}},[t,ce,_e,J]),Je=jn(async I=>{if(j.onClick?.(I),!(I.defaultPrevented||W||fe)){if(q(null),e&&Re){let be=new xr("Provide either sessionId or create-session props, not both.","validation_error");await _e(be),C.current&&(pe(null),K(null));return}if(!e&&!Re){let be=new xr("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await _e(be),C.current&&(pe(null),K(null));return}ae(!0),K(null),ge(!1),pe("processing");try{let be=new Ba(ce);if(e){let Ye=await be.getUnifiedCheckoutSession(e,t);await mt(Ye,e);return}try{let Ye=await be.createAndFetchSession({...Re});await mt(Ye,Ye.data.session?.id??null,{fromCreateSession:!0})}catch(Ye){if(Ye instanceof xr&&Ye.code==="session_auto_completed"){await J({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Ye}}catch(be){await _e(Rc(be,"Automatic payment failed. Please try again."))}finally{C.current&&(pe(null),K(null),ae(!1))}}},[j,Re,W,fe,t,mt,ce,e,_e,J]),yt=jn(I=>{let be=$e.current;q(null),Oe.current?.({result:I,session:null,sessionId:be?.sessionId??null,autoCompleted:!1})},[]),A=jn(I=>{me.current?.(I)},[]),X=jn(I=>{T.current?.(I)},[]),tt=to(()=>wc(E),[E]),qe=to(()=>{let I=tt?.buttonsLayout??Sc(de);return S?{...I,...S,cardButton:{...I.cardButton,...S.cardButton}}:I},[tt,de,S]),ft=to(()=>{let I=tt?.appearance;return f?I?{...I,...f,variables:{...I.variables,...f.variables}}:f:I},[f,tt]),Ne=ft?.variables,We=Ne?.colorPrimary??"#4A49FF",Xt=Ne?.colorPrimaryHover??mr(We,.12),Ge=Ne?.borderRadius??"8px";return Tc(xc,{children:[_r("button",{...j,type:oe,onClick:Je,disabled:W||fe,"aria-busy":fe,style:{width:"100%",...G===void 0?{boxSizing:"border-box",height:kc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...qe.cardButton,...ha({themeBundle:tt,resolvedPrimaryColor:We,resolvedBorderRadius:Ge,submitButtonStyle:qe.submitButton,explicitPrimaryColor:Ne?.colorPrimary}),fontSize:qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:W||fe?"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||fe?.6:1,...N},onMouseEnter:I=>{j.onMouseEnter?.(I),!I.defaultPrevented&&!W&&!fe&&(tt||Ne?.colorPrimary)&&(I.currentTarget.style.backgroundColor=Xt)},onMouseLeave:I=>{j.onMouseLeave?.(I),!I.defaultPrevented&&(tt||Ne?.colorPrimary)&&(I.currentTarget.style.backgroundColor=We)},onMouseDown:I=>{j.onMouseDown?.(I),I.defaultPrevented||(I.currentTarget.style.transform="scale(0.985)")},onMouseUp:I=>{j.onMouseUp?.(I),I.defaultPrevented||(I.currentTarget.style.transform="scale(1)")},children:_r(dr,{content:G})}),ee&&_r(cn,{status:ee,errorMessage:Y,authorized:Ee}),te&&_r("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:I=>{I.target===I.currentTarget&&q(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:_r("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:_r(Ta,{sessionId:te.sessionId,nonce:te.nonce,checkoutMode:"full",billingApiUrl:ce,locale:k,theme:E,...ft?{appearance:ft}:{},buttonsTheme:de,buttonsStyles:S,initialErrorMessage:te.errorMessage,cardTitleContent:null,onComplete:yt,onError:A,onDecline:X})})})]})}export{oc as AddressElement,Ro as DirectPayPalButton,_c as FloPayAutomaticPaymentButton,pc as FloPayCardSetup,zo as FloPayCardSetupError,Ta as FloPayCheckout,go as FloPayProvider,Pc as PayPalButton,rc as PaymentElement,Pa as SplitCardForm,jr as VaultCardFields,_p as dropThirdPartyOnlyError,qs as useCheckout,na as useElements,wn as useFloPay,ta as usePayPalFloPay};