@flopay/react 1.4.19 → 1.4.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,12 +1,12 @@
1
- import{useCallback as ys,useEffect as Dr,useState as zo,useMemo as fs,useRef as Uo}from"react";import{resolveBillingApiUrl as gs}from"@flopay/shared";import{createContext as Ya}from"react";var _n=Ya({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),yn=Ya({session:null,loading:!1,error:null});var ds=Symbol.for("@flopay/js.telemetry.bridge.v1"),us=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function ps(){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=ps(),n=(o,a)=>o?o.bind(e):a,i=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:i,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,i()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function oo(e){let t=globalThis[us];return ms(t?.(e)??{})}function Ft(e){if(e)return e[ds]}import{jsx as hs}from"react/jsx-runtime";function ao({flopay:e,paypalFlopay:t,options:n,children:i}){let[o,a]=zo(e instanceof Promise?null:e),[u,l]=zo(t instanceof Promise||!t?null:t),[w,B]=zo(null),P=Uo(null),R=Uo(null),S=Uo(null);Dr(()=>{if(!o)return;let I=Ft(o);return P.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),Dr(()=>{let I=!1;return e instanceof Promise?e.then(_=>{I||a(_)}):a(e),()=>{I=!0}},[e]),Dr(()=>{let I=!1;if(!t){l(null);return}return t instanceof Promise?t.then(_=>{I||l(_)}):l(t),()=>{I=!0}},[t]),Dr(()=>{if(!o){B(null);return}let I=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return B(I),()=>{I.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),Dr(()=>{if(!o||!w||R.current===w)return;R.current=w;let I=Ft(o);I?.log({name:"checkout.rendered",stage:"checkout_render"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(P.current??0),durationMode:"machine"})},[w,o]);let x=ys(()=>{if(!o||!w||S.current===w)return;S.current=w;let I=Ft(o);I?.log({name:"checkout.interactive",stage:"checkout_interactive"}),I?.performance({stage:"checkout_interactive",durationMs:I.elapsed(P.current??0),durationMode:"machine"})},[w,o]),d=gs(n?.billingApiUrl),b=fs(()=>({flopay:o,paypalFlopay:u,elements:w,billingApiUrl:d,reportInteractive:x}),[o,u,w,d,x]);return hs(_n.Provider,{value:b,children:i})}import sa,{useCallback as rr,useEffect as Bn,useMemo as fn,useRef as jt,useState as vt}from"react";import{PaymentAPI as Co,SESSION_CREATE_TELEMETRY as Pl}from"@flopay/js";import{SDK_VERSION as Ui,FloPayError as bt,classifyTelemetryFailure as Ai,isDetachedSessionEligible as bl,resolveBillingApiUrl as vl,buildCheckoutDisplayData as Fi,resolveButtonsLayoutTheme as Cl,resolveIdempotencyKey as Di,resolveTheme as $i,telemetryStatusClass as Sl}from"@flopay/shared";import"react";import{Fragment as dr,jsx as an,jsxs as Ga}from"react/jsx-runtime";function Ps(){return Ga(dr,{children:[Ga("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 bs(){return an(dr,{children:"Go back"})}function vs(){return an(dr,{children:"Secure card checkout"})}function sr(e){return e!==void 0&&(e===""||e===null||e===!1)}function lr({content:e}){return an(dr,{children:e===void 0?an(Ps,{}):e})}function cr({content:e}){return an(dr,{children:e===void 0?an(bs,{}):e})}function Lr({content:e}){return an(dr,{children:e===void 0?an(vs,{}):e})}import{ExpressCheckoutElement as Si,PaymentElement as Ls,Elements as tr,useElements as ea,useStripe as ta}from"@stripe/react-stripe-js";import{resolveButtonsLayoutTheme as Ns,getPostalCodeLabel as Qo,getStateLabel as ci,getStateOptions as Os,COUNTRY_OPTIONS as zs,resolveAVSConfig as Us,isAVSFieldVisible as De,getStateFromPostalCode as di,isPostalCodeSupported as $s,isValidPostalCode as qs,getPostalCodeExample as js,filterStripeMethodsByCountry as Vs,getStripeMethodDisplayName as hr,hasVendoredStripeMethodLogo as Ks,needsStripeMethodExplicitConfirm as ui,resolveStripeMethodBrandVariant as Hs,partitionStripeMethods as Ws,stripeExpressMethodToOptionKey as pi}from"@flopay/shared";import{PaymentAPI as $n,toStripeAppearance as Ys}from"@flopay/js";import{useEffect as Ja,useRef as Nr}from"react";import{jsx as Cs}from"react/jsx-runtime";function $o({capture:e,html:t,messageToken:n,expectedOrigin:i,theme:o,containerStyle:a,onReady:u,onError:l,onValidation:w}){let B=Nr(null),P=Nr(u),R=Nr(l),S=Nr(w);P.current=u,R.current=l,S.current=w;let x=Nr(o);return x.current=o,Ja(()=>{let d=B.current;if(!d)return;let b=!0,I=!1,_=()=>{!b||I||(I=!0,P.current?.())},f=e.on("ready",()=>{_()}),me=e.on("error",ee=>{R.current?.(ee.message??"There was a problem loading the secure card form.")}),F=e.on("validation",ee=>{S.current?.(ee.message??null)}),se={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},...x.current?{theme:x.current}:{}};return e.mount(d,se).then(()=>{_()}).catch(ee=>{b&&R.current?.(ee instanceof Error?ee.message:"Failed to load the secure card form.")}),()=>{b=!1,f(),me(),F(),e.unmount()}},[e,t,n,i]),Ja(()=>{o&&e.applyTheme?.(o)},[e,o]),Cs("div",{ref:B,"data-testid":"flopay-vault-card-fields",style:a})}import"react";import{jsx as Xa,jsxs as Ss}from"react/jsx-runtime";function ur({children:e,margin:t,icon:n=!0,styleOverride:i}){return Ss("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...i??{}},children:[n&&Xa("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Xa("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 Qa={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 Gs,{useCallback as we,useContext as Js,useEffect as Ze,useMemo as rt,useRef as Be,useState as ve}from"react";import{useContext as Or}from"react";import{resolveBillingApiUrl as ws}from"@flopay/shared";function vn(){return Or(_n).flopay}function qo(){return Or(_n).paypalFlopay??null}function jo(){return Or(_n).elements}function ks(){return Or(yn)}function io(){return Or(_n).billingApiUrl||ws()}import"react";import{jsx as sn,jsxs as pr}from"react/jsx-runtime";var xn=1200,Cn=1500;function Sn({status:e,errorMessage:t}){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:pr("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:[pr("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&pr("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:pr("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:pr("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"}})]})})]}),pr("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&"PROCESSING...",e==="success"&&"PAYMENT SUCCESSFUL",e==="error"&&"PAYMENT FAILED"]}),e==="success"&&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 Ts,useEffect as Ur,useState as Go,useMemo as Ms,useRef as Jo}from"react";import{resolveBillingApiUrl as As}from"@flopay/shared";import{createContext as ii}from"react";var xn=ii({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),pn=ii({session:null,loading:!1,error:null});var Es=Symbol.for("@flopay/js.telemetry.bridge.v1"),Is=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function _s(){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 xs(e){let t=_s(),n=(o,s)=>o?o.bind(e):s,i=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:i,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,i()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function mo(e){let t=globalThis[Is];return xs(t?.(e)??{})}function At(e){if(e)return e[Es]}import{jsx as Bs}from"react/jsx-runtime";function yo({flopay:e,paypalFlopay:t,options:n,children:i}){let[o,s]=Go(e instanceof Promise?null:e),[d,l]=Go(t instanceof Promise||!t?null:t),[v,L]=Go(null),h=Jo(null),w=Jo(null),C=Jo(null);Ur(()=>{if(!o)return;let k=At(o);return h.current=k?.beginCheckout()??k?.now()??0,k?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{k?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),Ur(()=>{let k=!1;return e instanceof Promise?e.then(E=>{k||s(E)}):s(e),()=>{k=!0}},[e]),Ur(()=>{let k=!1;if(!t){l(null);return}return t instanceof Promise?t.then(E=>{k||l(E)}):l(t),()=>{k=!0}},[t]),Ur(()=>{if(!o){L(null);return}let k=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return L(k),()=>{k.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),Ur(()=>{if(!o||!v||w.current===v)return;w.current=v;let k=At(o);k?.log({name:"checkout.rendered",stage:"checkout_render"}),k?.performance({stage:"checkout_render",durationMs:k.elapsed(h.current??0),durationMode:"machine"})},[v,o]);let R=Ts(()=>{if(!o||!v||C.current===v)return;C.current=v;let k=At(o);k?.log({name:"checkout.interactive",stage:"checkout_interactive"}),k?.performance({stage:"checkout_interactive",durationMs:k.elapsed(h.current??0),durationMode:"machine"})},[v,o]),c=As(n?.billingApiUrl),P=Ms(()=>({flopay:o,paypalFlopay:d,elements:v,billingApiUrl:c,reportInteractive:R}),[o,d,v,c,R]);return Bs(xn.Provider,{value:P,children:i})}import ha,{useCallback as ar,useEffect as Bn,useMemo as mn,useRef as Nt,useState as Ct}from"react";import{PaymentAPI as To,SESSION_CREATE_TELEMETRY as zl}from"@flopay/js";import{SDK_VERSION as ts,FloPayError as It,classifyTelemetryFailure as Yi,isDetachedSessionEligible as Ol,resolveBillingApiUrl as Nl,buildCheckoutDisplayData as Gi,resolveButtonsLayoutTheme as Ul,resolveIdempotencyKey as Ji,resolveTheme as ns,telemetryStatusClass as $l}from"@flopay/shared";import"react";import{Fragment as pr,jsx as an,jsxs as si}from"react/jsx-runtime";function Fs(){return si(pr,{children:[si("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 Ds(){return an(pr,{children:"Go back"})}function Ls(){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(Fs,{}):e})}function ur({content:e}){return an(pr,{children:e===void 0?an(Ds,{}):e})}function $r({content:e}){return an(pr,{children:e===void 0?an(Ls,{}):e})}import{ExpressCheckoutElement as Li,PaymentElement as Zs,Elements as rr,useElements as da,useStripe as ua}from"@stripe/react-stripe-js";import{isAuthorizationOnlySession as aa,normalizeCheckoutFailureOutcome as el,resolveButtonsLayoutTheme as tl,getPostalCodeLabel as la,getStateLabel as wi,getStateOptions as nl,COUNTRY_OPTIONS as rl,resolveAVSConfig as ol,isAVSFieldVisible as De,getStateFromPostalCode as ki,isPostalCodeSupported as al,isValidPostalCode as il,getPostalCodeExample as sl,filterStripeMethodsByCountry as ll,getStripeMethodDisplayName as vr,hasVendoredStripeMethodLogo as cl,needsStripeMethodExplicitConfirm as Ri,resolveStripeMethodBrandVariant as dl,partitionStripeMethods as ul,stripeExpressMethodToOptionKey as Ei}from"@flopay/shared";import{PaymentAPI as qn,toStripeAppearance as pl}from"@flopay/js";import{useEffect as li,useRef as qr}from"react";import{jsx as zs}from"react/jsx-runtime";function jr({capture:e,html:t,messageToken:n,expectedOrigin:i,theme:o,containerStyle:s,onReady:d,onError:l,onValidation:v}){let L=qr(null),h=qr(d),w=qr(l),C=qr(v);h.current=d,w.current=l,C.current=v;let R=qr(o);return R.current=o,li(()=>{let c=L.current;if(!c)return;let P=!0,k=!1,E=()=>{!P||k||(k=!0,h.current?.())},g=e.on("ready",()=>{E()}),ce=e.on("error",X=>{w.current?.(X.message??"There was a problem loading the secure card form.")}),I=e.on("validation",X=>{C.current?.(X.message??null)}),ae={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},...R.current?{theme:R.current}:{}};return e.mount(c,ae).then(()=>{E()}).catch(X=>{P&&w.current?.(X instanceof Error?X.message:"Failed to load the secure card form.")}),()=>{P=!1,g(),ce(),I(),e.unmount()}},[e,t,n,i]),li(()=>{o&&e.applyTheme?.(o)},[e,o]),zs("div",{ref:L,"data-testid":"flopay-vault-card-fields",style:s})}import"react";import{jsx as ci,jsxs as Os}from"react/jsx-runtime";function mr({children:e,margin:t,icon:n=!0,styleOverride:i}){return Os("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...i??{}},children:[n&&ci("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ci("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 di={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 ml,{useCallback as we,useContext as yl,useEffect as dt,useMemo as ct,useRef as Be,useState as Se}from"react";import{useContext as Vr}from"react";import{resolveBillingApiUrl as Ns}from"@flopay/shared";function bn(){return Vr(xn).flopay}function Xo(){return Vr(xn).paypalFlopay??null}function Qo(){return Vr(xn).elements}function Us(){return Vr(pn)}function fo(){return Vr(xn).billingApiUrl||Ns()}import"react";import{jsx as sn,jsxs as yr}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:yr("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:[yr("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&yr("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:yr("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:yr("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"}})]})})]}),yr("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:`
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 Vc,isSetupIntentClientSecret as Kc}from"@flopay/shared";function Za(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Vo(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ei(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],i=n.reduce((a,u)=>a+(u.overrideAmount??u.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(i*100),currency:o,status:"open",customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,u)=>({uuid:`synthetic-${a.type??"item"}-${u}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function Ko(e,t){return t?{...e,...t}:e}function Rt(e,t,n){let i=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:i,...o?{code:o}:{},...a?{declineCode:a}:{}}}var Rs=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function zn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:i}of Rs)if(n.test(t))return i;return e}function so(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function ti(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function ni(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function lo(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 mr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(co+e,JSON.stringify(t))}catch{}}function Ho(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 ri(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 uo,useEffect as dt,useMemo as Ur,useRef as He,useState as er}from"react";import{loadScript as Es}from"@paypal/paypal-js";import{PaymentAPI as Wo}from"@flopay/js";import{FloPayError as oi,SDK_VERSION as _s,generateIdempotencyKey as xs,normalizeGatewayEnvironment as Ts}from"@flopay/shared";function ct(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function Is(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Zn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Tn(e){if(typeof e!="object"||e===null)return;let t=e;return Zn(t.code)??Zn(t.type)??Zn(t.name)}function yr(e){if(!(typeof e!="object"||e===null))return Zn(e.decline_code)}function zr(e){return typeof e!="object"||e===null?!1:Zn(e.type)?.toLowerCase()==="card_error"||yr(e)!==void 0}function Un(e){let t=Is(e)?.toLowerCase()??"",i=`${Tn(e)?.toLowerCase()??""} ${t}`;return i.includes("popup")&&i.includes("block")}import{jsx as fr,jsxs as Yo}from"react/jsx-runtime";var po=45,Ms=1e3,Bs=11e3,As=["https://www.paypal.com","https://www.sandbox.paypal.com"],ai="We couldn't open PayPal. Try again or choose another payment method.",Fs={width:"100%",minHeight:po,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 ii(e){return e.includes("No ack for postMessage init()")&&As.some(t=>e.includes(t))&&e.includes("10000ms")}function Ds(e){return e?`${ai} Allow pop-ups for this site, then try again.`:ai}function si({sessionId:e,nonce:t,billingApiUrl:n,email:i,clientId:o,environment:a,currency:u,isSubscription:l,onTokenizedBody:w,onComplete:B,onErrorChange:P,onDecline:R,onTechnicalFailure:S,isProcessing:x=!1,onLoadStateChange:d,onInitializationStateChange:b,allowAutomaticRetry:I=!0,onButtonClick:_,runBeforeButtonClick:f,session:me,existingOrderId:F,telemetry:se,telemetryContext:ee,debug:D=!1}){let J=vn(),W=Ur(()=>{if(J)return null;let T=oo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:_s,enabled:se!==!1});return T.setCheckoutContext(ee??{}),T.beginCheckout(ee??{}),T},[n,J,se,ee?.checkoutMode,ee?.layout]),le=Ur(()=>Ft(J),[J]);dt(()=>()=>{W&&W.flush().catch(()=>{}).finally(()=>W.destroy())},[W]);let q=Ur(()=>({error:T=>{le?le.error(T):W?.error(T)},log:T=>{le?le.log(T):W?.log(T)},performance:T=>{le?le.performance(T):W?.performance(T)},terminal:T=>{le?le.terminal(T):W?.terminal(T)},startTiming:()=>le?.now()??W?.now()??0,elapsed:T=>le?.elapsed(T)??Math.max(0,(W?.now()??T)-T)}),[le,W]),K=He(null),ce=He(0),_e=He(null),Pe=He(!1),[ye,te]=er(!1),[ge,xe]=er(!1),[ne,ke]=er(0),Re=He(0),[Ce,Y]=er(!1),E=He(!1),ae=He(!1),[Ne,Oe]=er(!1),[de,k]=er(!1),Q=Ur(()=>n.replace(/\/+$/,""),[n]),Z=Ur(()=>JSON.stringify([Q,o,u,a??"",l,e,F??""]),[Q,o,u,a,F,l,e]),ze=He(Z),ut=ze.current!==Z,[je,ot]=er([]),z=T=>{D&&ot(ht=>[...ht,`${new Date().toISOString().slice(11,23)} ${T}`])},V=He(w),et=He(B),Te=He(P),at=He(R),We=He(S),Ve=He(_),ln=He(d),g=He(b),be=He(f),pt=He(me),tt=He(i),Xe=He(t),Ke=He(null),Qe=He(0),Ie=He(null),qe=He(null),Et=He(new Map),Ye=He(new Map),Fn=He(!1);dt(()=>(Fn.current=!0,()=>{Fn.current=!1}),[]),dt(()=>{V.current=w},[w]),dt(()=>{et.current=B},[B]),dt(()=>{Te.current=P},[P]),dt(()=>{at.current=R},[R]),dt(()=>{We.current=S},[S]),dt(()=>{Ve.current=_},[_]),dt(()=>{ln.current=d},[d]),dt(()=>{g.current=b},[b]),dt(()=>{be.current=f},[f]),dt(()=>{pt.current=me},[me]),dt(()=>{tt.current=i},[i]),dt(()=>{Xe.current=t},[t]),dt(()=>{Re.current=ne},[ne]),dt(()=>{Ce&&_e.current?.focus()},[Ce,ne]);let Ct=uo(()=>{window.setTimeout(()=>{_e.current?.focus()},0)},[]),Dn=uo(()=>{te(!1),ke(T=>T+1)},[]),cn=uo(()=>{Y(!1),(K.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??K.current)?.focus?.()},[]);dt(()=>{!ye||!Pe.current||(Pe.current=!1,cn())},[cn,ye,ne]);let gn=uo((T,ht)=>{let mt=We.current;if(mt){mt("paypal",T,ht);return}Te.current?.(Ds(ht?.popupBlocked??Un(T)))},[]),tn=()=>{Ie.current?.timer&&(clearTimeout(Ie.current.timer),Ie.current.timer=null)},Ln=()=>{tn();let T=Qe.current+1;return Qe.current=T,qe.current=null,Ie.current={generation:T,timer:null,yieldedControl:!1},Y(!1),T},Ut=T=>T!==void 0&&Ie.current?.generation!==T?!1:(tn(),Ie.current=null,qe.current=null,!0),_t=T=>{let ht=T?.generation??Ie.current?.generation??Qe.current;(!T?.generation||Ie.current?.generation===ht)&&(tn(),Ie.current=null),qe.current=ht,T?.showRetry&&Y(!0),T?.remount&&Dn(),T?.focus!==!1&&Ct()},Vt=T=>Ie.current?.generation===T&&qe.current!==T,Xt=T=>{typeof document<"u"&&document.visibilityState!=="visible"||(tn(),T.timer=setTimeout(()=>{Ie.current?.generation===T.generation&&(Ie.current=null,qe.current=T.generation,gn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),Y(!0),Dn(),Ct())},600))},Dt=()=>{let T=Ie.current;T?.yieldedControl&&Xt(T)},Kt=()=>{let T=Ie.current;T&&(T.yieldedControl=!0,tn())},Lt=T=>{let ht=Ke.current;return ht&&Ye.current.set(T,ht),T};dt(()=>{let T=()=>{document.visibilityState==="visible"?Dt():Kt()};return document.addEventListener("visibilitychange",T),window.addEventListener("focus",Dt),window.addEventListener("blur",Kt),()=>{document.removeEventListener("visibilitychange",T),window.removeEventListener("focus",Dt),window.removeEventListener("blur",Kt),tn()}},[]),dt(()=>{ze.current!==Z&&(ze.current=Z,E.current=!1,ae.current=!1,te(!1),xe(!1),Oe(!1),g.current?.("loading"))},[Z]),dt(()=>{ct(()=>ln.current?.(ye&&!Ne))},[ye,Ne]);let re=Ts(a);dt(()=>{let T=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",ht=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(z(`mount clientId=${T} env=${a??"(unset)"}\u2192${re??"live"} ccy=${u} sub=${l}`),z(`ua=${ht.slice(0,80)}${ht.length>80?"\u2026":""}`),!o){z("FAIL: clientId empty \u2014 gateway misconfigured"),Oe(!0),q.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!K.current){z("FAIL: containerRef not attached");return}ce.current=q.startTiming(),q.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let mt=!1,St=!1,Ee=()=>mt||St,Ue,Kn=!1,Nn=()=>{Ue=xs(),Ue||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Kn=!0},Hn=null,or=!1,Ht=null,it=!1,Nt=()=>{!Ht||it||(it=!0,Ht.close().catch(()=>{}))},Wt=null,Pt=()=>{Wt!==null&&(q.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),q.performance({stage:"overlay_return",durationMs:q.elapsed(Wt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Wt=null)},Qt=!1,Yt=K.current,dn=null,hn=null,xt=[],$t=c=>{if(!c||typeof c.getBoundingClientRect!="function")return"(no rect)";let s=c.getBoundingClientRect();return`${Math.round(s.width)}\xD7${Math.round(s.height)}`},Ae=c=>{if(!c)return"(empty)";try{let s=new URL(c,typeof window<"u"?window.location.href:"https://localhost"),M=s.pathname.toLowerCase();return M.includes("checkcaptcha")||M.includes("captcha")?`CAPTCHA(${s.host}${M})`:M.includes("risk")||M.includes("challenge")?`RISK(${s.host}${M})`:M.includes("smart/buttons")?`smart-buttons(${s.host})`:`${s.host}${M}`.slice(0,100)}catch{return c.slice(0,80)}},wt=c=>{let s=c.getAttribute("src"),M=c.getAttribute("srcdoc"),y=c.getAttribute("name"),G=c.getAttribute("sandbox"),Se=[];return s&&Se.push(`src=${Ae(s)}`),M&&Se.push(`srcdoc[${M.length}ch]`),!s&&!M&&Se.push("src=(empty) srcdoc=(empty)"),y&&Se.push(`name=${y.slice(0,40)}`),G!==null&&Se.push(`sandbox="${G.slice(0,40)}"`),Se.join(" ")},kt=c=>{if(!(c instanceof HTMLIFrameElement))return"";try{let s=c.contentDocument;if(!s)return"cd=null";let M=s.body?.children.length??0,y=s.body?.innerHTML.length??0,G=s.head?.innerHTML.length??0;return`cd=same-origin readyState=${s.readyState} body[${M}children,${y}ch] head[${G}ch]`}catch(s){return`cd=cross-origin(${s.message.slice(0,30)})`}},Pn=[],Wn=c=>{if(Ee())return;let s=c.message??String(c.error??"(no message)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(z(`window:error ${s.slice(0,140)}`),Pn.push(s))},Gt=c=>{if(Ee())return;let s=c.reason instanceof Error?c.reason.message:String(c.reason??"(no reason)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(z(`window:rejection ${s.slice(0,140)}`),Pn.push(s))};D&&typeof window<"u"&&(window.addEventListener("error",Wn),window.addEventListener("unhandledrejection",Gt));let Zt={value:0};if(D&&typeof PerformanceObserver<"u")try{hn=new PerformanceObserver(c=>{if(!Ee())for(let s of c.getEntries()){if(!s.name.toLowerCase().includes("paypal"))continue;Zt.value+=1;let M=Math.round(s.duration);z(`net ${M}ms ${s.name.slice(0,90)}`)}}),hn.observe({type:"resource",buffered:!0})}catch{}let Ot=()=>{for(dn?.disconnect(),dn=null,hn?.disconnect(),hn=null;xt.length;)clearTimeout(xt.pop());D&&typeof window<"u"&&(window.removeEventListener("error",Wn),window.removeEventListener("unhandledrejection",Gt))},In=c=>{if(!c)return!1;let s=c.toLowerCase();return s.includes("zoid destroyed")||s.includes("destroyed all components")||s.includes("window closed")||s.includes("detected container element removed")},On=c=>{if(Ee()||In(c))return;let s=zn(c)??c;ct(()=>Te.current?.(s))},un=c=>{mt||(Oe(!0),c.includes("paypal_ineligible")||q.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",c))},en=(c,s=!1)=>{if(mt)return;let M=E.current||!I;if(or)return;or=!0,St=!0,Ot(),Nt();let y=s||ii(c);if(y&&I&&!E.current){E.current=!0,te(!1),k(!1),xe(!0),g.current?.("retrying"),Hn=setTimeout(()=>{mt||ke(G=>G+1)},Ms);return}if(y||M){if(te(!1),k(!1),xe(!1),Oe(!0),g.current?.("exhausted"),!ae.current){ae.current=!0;let G=ii(c)?"paypal_init_timeout":s?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",G)}return}un(c)};Oe(!1);let Tt=async(c,s=Ke.current)=>{if(Ee())return;let M=s?.sessionId??e;if(V.current){await V.current(c,{sessionId:M,accountPatch:s?.accountPatch,nonce:s?.nonce});return}let y=q.startTiming();q.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let G=()=>{q.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),q.performance({stage:"processing",durationMs:q.elapsed(y),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Se=pt.current,nt=s?.accountPatch?.email??tt.current,he=s?.accountPatch?.userId??Se?.customer?.id??Se?.accountData?.userId??"",m=await new Wo(Q,{telemetry:!1}).processPayment(he,{sessionId:M,nonce:s?.nonce??Xe.current,tokenizedData:c,accountData:{userId:he,email:nt??Se?.customer?.email??"",firstName:s?.accountPatch?.firstName??Se?.customer?.firstName??Se?.accountData?.firstName??"",lastName:s?.accountPatch?.lastName??Se?.customer?.lastName??Se?.accountData?.lastName??"",country:s?.accountPatch?.country??Se?.customer?.country??Se?.accountData?.country??void 0,zip:s?.accountPatch?.zip??Se?.customer?.zip??Se?.accountData?.zip??void 0}});if(m.ok){if(St||mt&&Fn.current)return;G(),q.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ct(()=>et.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ee())return;let L=await m.json().catch(()=>null),N=L?.message??"PayPal payment failed.",$e=zn(N)??N;G(),m.status===400&&(typeof L?.declineCode=="string"||!Array.isArray(L?.fields))?q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):m.status===400||m.status===422?q.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):q.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:m.status>=500?"5xx":m.status>=400?"4xx":m.status>=300?"3xx":"unknown",failureCategory:m.status>=500?"server_error":void 0}),On($e),ct(()=>at.current?.(Rt("paypal",$e,{code:L?.code,declineCode:L?.declineCode})));return}catch(Se){if(Ee())return;G(),q.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let nt=Se instanceof Error?Se.message:"PayPal payment failed.",he=zn(nt)??nt;On(he),ct(()=>at.current?.(Rt("paypal",he)));return}},h=()=>new oi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),j=c=>Ee()?Promise.reject(h()):Promise.resolve(c),U=async c=>{if(Ee())throw h();Kn||Nn();let s=Ke.current,M=s?.sessionId??e,y=s?.nonce??Xe.current;q.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let G=await new Wo(Q,{telemetry:!1}).createSessionIntent(M,y??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Ue});if(Ee())throw h();if(G.provider!=="paypal")throw new Error(c);return q.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),G.providerObjectId},ue=(c,s)=>{let M=s?.nonce??Xe.current;if(!M)return;let y=s?.sessionId??e,G=yr(c)??Tn(c)??"provider_declined";new Wo(Q,{telemetry:!1}).reportSessionIntentDecline(y,M,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:G}).catch(()=>{})},H=ne;z("loadScript:scheduled (deferred 1 tick)");let ie=null,C=setTimeout(()=>{if(mt){z("loadScript:skipped (cancelled before defer ran)");return}z("loadScript:start");let c=re==="live"?"production":re;ie=Es({clientId:o,currency:u,intent:l?"subscription":"capture",vault:l?!0:void 0,...c?{environment:c}:{},...c==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),ie.then(s=>{if(z(`loadScript:resolved inactive=${Ee()} ns=${!!s} buttons=${!!s?.Buttons}`),Ee())return;if(!s?.Buttons){z("FAIL: namespace missing Buttons factory"),en("PayPal SDK did not expose the Buttons factory.");return}q.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),q.performance({stage:"provider_ready",durationMs:q.elapsed(ce.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),q.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let M=async A=>{if(Ee()||Re.current!==H)return;let m=A.subscriptionID??A.orderID??"",L=m?Ye.current.get(m):Et.current.get(H);if(!(!L||!Vt(L.generation))&&Ut(L.generation)){Ye.current.delete(m),Et.current.delete(L.surfaceKey),Pt();try{if(k(!0),ct(()=>Te.current?.(null)),!m)throw new oi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Tt({id:m,isPaypal:!0},L)}catch(N){On(N instanceof Error?N.message:"PayPal capture failed.")}finally{Ee()||k(!1)}}},y=s.Buttons({style:{layout:"horizontal",height:po,tagline:!1},onClick:async(A,m)=>{if(Ee()){await m.reject();return}Nn();let L=be.current,N={};if(L)try{let Mt=await L("paypal");if(Ee()){await m.reject();return}if(!Mt.proceed){Ke.current=null,Et.current.delete(H),await m.reject();return}N={sessionId:Mt.sessionId,accountPatch:Mt.accountPatch,nonce:Mt.nonce}}catch(Mt){z(`onClick:runBeforeButtonClick rejected msg=${(Mt instanceof Error?Mt.message:String(Mt)).slice(0,120)}`),Ke.current=null,Et.current.delete(H),await m.reject();return}ct(()=>Ve.current?.("paypal"));let yt={generation:Ln(),surfaceKey:H,...N};Ke.current=yt,Et.current.set(H,yt),await m.resolve(),q.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),q.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),q.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Wt=q.startTiming()},createOrder:l?void 0:F?()=>j(F).then(Lt):()=>U("Failed to create PayPal order.").then(Lt),createSubscription:l?F?()=>j(F).then(Lt):()=>U("Failed to create PayPal subscription.").then(Lt):void 0,onApprove:M,onCancel:()=>{if(Ee())return;let A=Et.current.get(H)??Ke.current;A&&Et.current.delete(A.surfaceKey),Ke.current=null,Pt(),q.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Pe.current=!0,_t({generation:A?.generation,remount:!0,focus:!1})},onError:A=>{if(Ee()||Re.current!==H)return;let m=A instanceof Error?A.message:"PayPal failed to render.";if(z(`onError rendered=${Qt} msg=${m.slice(0,120)}`),Qt){let L=Et.current.get(H)??Ke.current;if(L&&!Vt(L.generation)||!L&&qe.current===Qe.current)return;if(In(m)){Ut(L?.generation);return}if(Pt(),zr(A)){q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ue(A,L),ct(()=>at.current?.(Rt("paypal",m))),L&&Et.current.delete(L.surfaceKey),Ke.current=null,Ut(L?.generation);return}let N=m.toLowerCase();q.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"}),L&&Et.current.delete(L.surfaceKey),Ke.current=null,_t({generation:L?.generation,remount:!0,showRetry:!0,focus:!0}),gn(A,{code:"paypal_runtime_failed"});return}en(m)}}),G=y.isEligible();if(z(`isEligible=${G}`),q.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!G){te(!1),en("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ht=y,D&&z(`container:dims ${$t(Yt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),D&&typeof MutationObserver<"u"&&(dn=new MutationObserver(A=>{if(!Ee()){for(let m of A)if(m.type==="childList")m.addedNodes.forEach(L=>{if(!(L instanceof Element))return;let N=L.tagName.toLowerCase(),$e=(L.getAttribute("title")??"").slice(0,40),yt=N==="iframe"?` ${wt(L)}`:"";z(`child+ ${N}${$e?` title="${$e}"`:""}${yt} dims=${$t(L)}`)});else if(m.type==="attributes"&&m.target instanceof Element){let L=m.target;if(L.tagName.toLowerCase()!=="iframe")continue;let N=m.attributeName;(N==="src"||N==="srcdoc")&&z(`attr~ iframe ${N}=${N==="srcdoc"?`[${(L.getAttribute("srcdoc")??"").length}ch]`:Ae(L.getAttribute("src"))} dims=${$t(L)}`)}}}),dn.observe(Yt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let nt=A=>{if(Ee()||Qt)return;let m=Yt.querySelectorAll("iframe"),L=typeof document<"u"&&"hasStorageAccess"in document;z(`watchdog:${A} container=${$t(Yt)} children=${Yt.childElementCount} iframes=${m.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${L} paypalNetRequests=${Zt.value}`),m.forEach((N,$e)=>{let yt=(N.getAttribute("title")??"").slice(0,40);z(` iframe[${$e}] ${$t(N)}${yt?` title="${yt}"`:""} ${wt(N)}`);let Mt=kt(N);Mt&&z(` ${Mt}`)}),Pn.length===0&&z(" (no PayPal/zoid window errors captured)")};D&&(xt.push(setTimeout(()=>nt("3s"),3e3)),xt.push(setTimeout(()=>nt("8s"),8e3)),xt.push(setTimeout(()=>nt("15s"),15e3))),z("render:start");let he=q.startTiming();xt.push(setTimeout(()=>{Ee()||Qt||(z("watchdog:11s retryable render timeout"),en("PayPal Buttons render did not settle within 11000ms.",!0))},Bs)),y.render(Yt).then(()=>{if(z(`render:resolved inactive=${Ee()}`),Ot(),Ee()){Nt();return}Qt=!0,te(!0),xe(!1),g.current?.("ready"),q.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),q.performance({stage:"checkout_render",durationMs:q.elapsed(he),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(A=>{let m=A instanceof Error?A.message:"PayPal failed to render.";z(`render:rejected msg=${m.slice(0,120)}`),Ot(),en(m)})}).catch(s=>{let M=s instanceof Error?s.message:"PayPal SDK failed to load.";z(`loadScript:rejected msg=${M.slice(0,120)}`),en(M)})},0);return()=>{mt=!0,clearTimeout(C),Hn&&clearTimeout(Hn),Ot(),Nt()}},[I,Q,o,u,a,l,e,F,ne,q]);let nn=D?Yo("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ne?"#fef2f2":"#f3f4f6",border:`1px solid ${Ne?"#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=${ye} failed=${Ne})`,je.length===0?`
6
+ `})]})})}import{FloPayError as ui,isMoneySettledOutcome as $s,isSetupIntentClientSecret as fd}from"@flopay/shared";function pi(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 Zo(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 mi(e,t){let n=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],i=n.reduce((s,d)=>s+(d.overrideAmount??d.totalAmount??0),0),o=e.currency??n.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(i*100),currency:o,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,d)=>({uuid:`synthetic-${s.type??"item"}-${d}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??o,metadata:s.metadata??null}))}}function ea(e,t){return t?{...e,...t}:e}function Et(e,t,n){let i=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,s=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:i,...o?{code:o}:{},...s?{declineCode:s}:{}}}var qs=[{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:i}of qs)if(n.test(t))return i;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 fr(e){return e?.status==="authorized"||e?.status==="complete"}function yi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function go(e){let t=yi(e);return new ui(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ho(e){let t=yi(e);return new ui(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 Po(e,t){return e==="processing"||$s(e,t)}function fi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function gi(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 bo="flopay_recent_completion_";function gr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(bo+e,JSON.stringify(t))}catch{}}function ta(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(bo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(bo+e),!1):!0}catch{return!1}}function hi(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 vo,useEffect as ht,useMemo as Wr,useRef as et,useState as nr}from"react";import{loadScript as Vs}from"@paypal/paypal-js";import{PaymentAPI as na}from"@flopay/js";import{FloPayError as Pi,SDK_VERSION as Ks,generateIdempotencyKey as Hs,normalizeGatewayEnvironment as Ws}from"@flopay/shared";function He(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 hr(e){if(!(typeof e!="object"||e===null))return tr(e.decline_code)}function Hr(e){return typeof e!="object"||e===null?!1:tr(e.type)?.toLowerCase()==="card_error"||hr(e)!==void 0}function $n(e){let t=js(e)?.toLowerCase()??"",i=`${Mn(e)?.toLowerCase()??""} ${t}`;return i.includes("popup")&&i.includes("block")}import{jsx as Pr,jsxs as ra}from"react/jsx-runtime";var Co=45,Ys=1e3,Gs=11e3,Js=["https://www.paypal.com","https://www.sandbox.paypal.com"],bi="We couldn't open PayPal. Try again or choose another payment method.",Xs={width:"100%",minHeight:Co,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 vi(e){return e.includes("No ack for postMessage init()")&&Js.some(t=>e.includes(t))&&e.includes("10000ms")}function Qs(e){return e?`${bi} Allow pop-ups for this site, then try again.`:bi}function Ci({sessionId:e,nonce:t,billingApiUrl:n,email:i,clientId:o,environment:s,currency:d,isSubscription:l,onTokenizedBody:v,onComplete:L,onErrorChange:h,onDecline:w,onTechnicalFailure:C,isProcessing:R=!1,onLoadStateChange:c,onInitializationStateChange:P,allowAutomaticRetry:k=!0,onButtonClick:E,runBeforeButtonClick:g,session:ce,existingOrderId:I,telemetry:ae,telemetryContext:X,debug:z=!1}){let W=bn(),q=Wr(()=>{if(W)return null;let D=mo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ks,enabled:ae!==!1});return D.setCheckoutContext(X??{}),D.beginCheckout(X??{}),D},[n,W,ae,X?.checkoutMode,X?.layout]),te=Wr(()=>At(W),[W]);ht(()=>()=>{q&&q.flush().catch(()=>{}).finally(()=>q.destroy())},[q]);let U=Wr(()=>({error:D=>{te?te.error(D):q?.error(D)},log:D=>{te?te.log(D):q?.log(D)},performance:D=>{te?te.performance(D):q?.performance(D)},terminal:D=>{te?te.terminal(D):q?.terminal(D)},startTiming:()=>te?.now()??q?.now()??0,elapsed:D=>te?.elapsed(D)??Math.max(0,(q?.now()??D)-D)}),[te,q]),A=et(null),Q=et(0),de=et(null),se=et(!1),[le,ne]=nr(!1),[he,Te]=nr(!1),[re,Ue]=nr(0),Fe=et(0),[Re,H]=nr(!1),S=et(!1),ie=et(!1),[$e,ze]=nr(!1),[pe,T]=nr(!1),ue=Wr(()=>n.replace(/\/+$/,""),[n]),Y=Wr(()=>JSON.stringify([ue,o,d,s??"",l,e,I??""]),[ue,o,d,s,I,l,e]),Ee=et(Y),ut=Ee.current!==Y,[Je,yt]=nr([]),B=D=>{z&&yt(it=>[...it,`${new Date().toISOString().slice(11,23)} ${D}`])},G=et(v),tt=et(L),qe=et(h),ft=et(w),Oe=et(C),We=et(E),Jt=et(c),Ge=et(P),Xt=et(g),_=et(ce),Pe=et(i),Ye=et(t),Ie=et(null),St=et(0),Ve=et(null),je=et(null),nt=et(new Map),Xe=et(new Map),Rn=et(!1);ht(()=>(Rn.current=!0,()=>{Rn.current=!1}),[]),ht(()=>{G.current=v},[v]),ht(()=>{tt.current=L},[L]),ht(()=>{qe.current=h},[h]),ht(()=>{ft.current=w},[w]),ht(()=>{Oe.current=C},[C]),ht(()=>{We.current=E},[E]),ht(()=>{Jt.current=c},[c]),ht(()=>{Ge.current=P},[P]),ht(()=>{Xt.current=g},[g]),ht(()=>{_.current=ce},[ce]),ht(()=>{Pe.current=i},[i]),ht(()=>{Ye.current=t},[t]),ht(()=>{Fe.current=re},[re]),ht(()=>{Re&&de.current?.focus()},[Re,re]);let at=vo(()=>{window.setTimeout(()=>{de.current?.focus()},0)},[]),Kn=vo(()=>{ne(!1),Ue(D=>D+1)},[]),Wt=vo(()=>{H(!1),(A.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??A.current)?.focus?.()},[]);ht(()=>{!le||!se.current||(se.current=!1,Wt())},[Wt,le,re]);let yn=vo((D,it)=>{let Lt=Oe.current;if(Lt){Lt("paypal",D,it);return}qe.current?.(Qs(it?.popupBlocked??$n(D)))},[]),Qt=()=>{Ve.current?.timer&&(clearTimeout(Ve.current.timer),Ve.current.timer=null)},ir=()=>{Qt();let D=St.current+1;return St.current=D,je.current=null,Ve.current={generation:D,timer:null,yieldedControl:!1},H(!1),D},Bt=D=>D!==void 0&&Ve.current?.generation!==D?!1:(Qt(),Ve.current=null,je.current=null,!0),kt=D=>{let it=D?.generation??Ve.current?.generation??St.current;(!D?.generation||Ve.current?.generation===it)&&(Qt(),Ve.current=null),je.current=it,D?.showRetry&&H(!0),D?.remount&&Kn(),D?.focus!==!1&&at()},Zt=D=>Ve.current?.generation===D&&je.current!==D,en=D=>{typeof document<"u"&&document.visibilityState!=="visible"||(Qt(),D.timer=setTimeout(()=>{Ve.current?.generation===D.generation&&(Ve.current=null,je.current=D.generation,yn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),H(!0),Kn(),at())},600))},Ft=()=>{let D=Ve.current;D?.yieldedControl&&en(D)},Dt=()=>{let D=Ve.current;D&&(D.yieldedControl=!0,Qt())},wt=D=>{let it=Ie.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),Qt()}},[]),ht(()=>{Ee.current!==Y&&(Ee.current=Y,S.current=!1,ie.current=!1,ne(!1),Te(!1),ze(!1),Ge.current?.("loading"))},[Y]),ht(()=>{He(()=>Jt.current?.(le&&!$e))},[le,$e]);let ee=Ws(s);ht(()=>{let D=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",it=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(B(`mount clientId=${D} env=${s??"(unset)"}\u2192${ee??"live"} ccy=${d} sub=${l}`),B(`ua=${it.slice(0,80)}${it.length>80?"\u2026":""}`),!o){B("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(!A.current){B("FAIL: containerRef not attached");return}Q.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,Ke=!1,En=()=>{st=Hs(),st||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Ke=!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=A.current,tn=null,cn=null,Yt=[],Ut=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let r=m.getBoundingClientRect();return`${Math.round(r.width)}\xD7${Math.round(r.height)}`},$t=m=>{if(!m)return"(empty)";try{let r=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),f=r.pathname.toLowerCase();return f.includes("checkcaptcha")||f.includes("captcha")?`CAPTCHA(${r.host}${f})`:f.includes("risk")||f.includes("challenge")?`RISK(${r.host}${f})`:f.includes("smart/buttons")?`smart-buttons(${r.host})`:`${r.host}${f}`.slice(0,100)}catch{return m.slice(0,80)}},_e=m=>{let r=m.getAttribute("src"),f=m.getAttribute("srcdoc"),F=m.getAttribute("name"),y=m.getAttribute("sandbox"),j=[];return r&&j.push(`src=${$t(r)}`),f&&j.push(`srcdoc[${f.length}ch]`),!r&&!f&&j.push("src=(empty) srcdoc=(empty)"),F&&j.push(`name=${F.slice(0,40)}`),y!==null&&j.push(`sandbox="${y.slice(0,40)}"`),j.join(" ")},qt=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let r=m.contentDocument;if(!r)return"cd=null";let f=r.body?.children.length??0,F=r.body?.innerHTML.length??0,y=r.head?.innerHTML.length??0;return`cd=same-origin readyState=${r.readyState} body[${f}children,${F}ch] head[${y}ch]`}catch(r){return`cd=cross-origin(${r.message.slice(0,30)})`}},gt=[],fn=m=>{if(Me())return;let r=m.message??String(m.error??"(no message)");r&&(r.toLowerCase().includes("paypal")||r.toLowerCase().includes("zoid")||r.toLowerCase().includes("postrobot")||r.toLowerCase().includes("storage"))&&(B(`window:error ${r.slice(0,140)}`),gt.push(r))},Yn=m=>{if(Me())return;let r=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");r&&(r.toLowerCase().includes("paypal")||r.toLowerCase().includes("zoid")||r.toLowerCase().includes("postrobot")||r.toLowerCase().includes("storage"))&&(B(`window:rejection ${r.slice(0,140)}`),gt.push(r))};z&&typeof window<"u"&&(window.addEventListener("error",fn),window.addEventListener("unhandledrejection",Yn));let jt={value:0};if(z&&typeof PerformanceObserver<"u")try{cn=new PerformanceObserver(m=>{if(!Me())for(let r of m.getEntries()){if(!r.name.toLowerCase().includes("paypal"))continue;jt.value+=1;let f=Math.round(r.duration);B(`net ${f}ms ${r.name.slice(0,90)}`)}}),cn.observe({type:"resource",buffered:!0})}catch{}let Vt=()=>{for(tn?.disconnect(),tn=null,cn?.disconnect(),cn=null;Yt.length;)clearTimeout(Yt.pop());z&&typeof window<"u"&&(window.removeEventListener("error",fn),window.removeEventListener("unhandledrejection",Yn))},Ot=m=>{if(!m)return!1;let r=m.toLowerCase();return r.includes("zoid destroyed")||r.includes("destroyed all components")||r.includes("window closed")||r.includes("detected container element removed")},On=m=>{if(Me()||Ot(m))return;let r=Un(m)??m;He(()=>qe.current?.(r))},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,r=!1)=>{if(Lt)return;let f=S.current||!k;if(zn)return;zn=!0,Ln=!0,Vt(),rt();let F=r||vi(m);if(F&&k&&!S.current){S.current=!0,ne(!1),T(!1),Te(!0),Ge.current?.("retrying"),In=setTimeout(()=>{Lt||Ue(y=>y+1)},Ys);return}if(F||f){if(ne(!1),T(!1),Te(!1),ze(!0),Ge.current?.("exhausted"),!ie.current){ie.current=!0;let y=vi(m)?"paypal_init_timeout":r?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",y)}return}Nn(m)};ze(!1);let Gt=async(m,r=Ie.current)=>{if(Me())return;let f=r?.sessionId??e;if(G.current){await G.current(m,{sessionId:f,accountPatch:r?.accountPatch,nonce:r?.nonce});return}let F=U.startTiming();U.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let y=()=>{U.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),U.performance({stage:"processing",durationMs:U.elapsed(F),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let j=_.current,Ae=r?.accountPatch?.email??Pe.current,Qe=r?.accountPatch?.userId??j?.customer?.id??j?.accountData?.userId??"",V=await new na(ue,{telemetry:!1}).processPayment(Qe,{sessionId:f,nonce:r?.nonce??Ye.current,tokenizedData:m,accountData:{userId:Qe,email:Ae??j?.customer?.email??"",firstName:r?.accountPatch?.firstName??j?.customer?.firstName??j?.accountData?.firstName??"",lastName:r?.accountPatch?.lastName??j?.customer?.lastName??j?.accountData?.lastName??"",country:r?.accountPatch?.country??j?.customer?.country??j?.accountData?.country??void 0,zip:r?.accountPatch?.zip??j?.customer?.zip??j?.accountData?.zip??void 0}});if(V.ok){if(Ln||Lt&&Rn.current)return;y(),U.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),He(()=>tt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Me())return;let p=await V.json().catch(()=>null),N=p?.message??"PayPal payment failed.",fe=Un(N)??N;y(),V.status===400&&(typeof p?.declineCode=="string"||!Array.isArray(p?.fields))?U.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):V.status===400||V.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:V.status>=500?"5xx":V.status>=400?"4xx":V.status>=300?"3xx":"unknown",failureCategory:V.status>=500?"server_error":void 0}),On(fe),He(()=>ft.current?.(Et("paypal",fe,{code:p?.code,declineCode:p?.declineCode})));return}catch(j){if(Me())return;y(),U.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ae=j instanceof Error?j.message:"PayPal payment failed.",Qe=Un(Ae)??Ae;On(Qe),He(()=>ft.current?.(Et("paypal",Qe)));return}},rn=()=>new Pi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ne=m=>Me()?Promise.reject(rn()):Promise.resolve(m),x=async m=>{if(Me())throw rn();Ke||En();let r=Ie.current,f=r?.sessionId??e,F=r?.nonce??Ye.current;U.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let y=await new na(ue,{telemetry:!1}).createSessionIntent(f,F??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:st});if(Me())throw rn();if(y.provider!=="paypal")throw new Error(m);return U.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),y.providerObjectId},O=(m,r)=>{let f=r?.nonce??Ye.current;if(!f)return;let F=r?.sessionId??e,y=hr(m)??Mn(m)??"provider_declined";new na(ue,{telemetry:!1}).reportSessionIntentDecline(F,f,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:y}).catch(()=>{})},M=re;B("loadScript:scheduled (deferred 1 tick)");let be=null,ve=setTimeout(()=>{if(Lt){B("loadScript:skipped (cancelled before defer ran)");return}B("loadScript:start");let m=ee==="live"?"production":ee;be=Vs({clientId:o,currency:d,intent:l?"subscription":"capture",vault:l?!0:void 0,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),be.then(r=>{if(B(`loadScript:resolved inactive=${Me()} ns=${!!r} buttons=${!!r?.Buttons}`),Me())return;if(!r?.Buttons){B("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(Q.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),U.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let f=async J=>{if(Me()||Fe.current!==M)return;let V=J.subscriptionID??J.orderID??"",p=V?Xe.current.get(V):nt.current.get(M);if(!(!p||!Zt(p.generation))&&Bt(p.generation)){Xe.current.delete(V),nt.current.delete(p.surfaceKey),ln();try{if(T(!0),He(()=>qe.current?.(null)),!V)throw new Pi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Gt({id:V,isPaypal:!0},p)}catch(N){On(N instanceof Error?N.message:"PayPal capture failed.")}finally{Me()||T(!1)}}},F=r.Buttons({style:{layout:"horizontal",height:Co,tagline:!1},onClick:async(J,V)=>{if(Me()){await V.reject();return}En();let p=Xt.current,N={};if(p)try{let xe=await p("paypal");if(Me()){await V.reject();return}if(!xe.proceed){Ie.current=null,nt.current.delete(M),await V.reject();return}N={sessionId:xe.sessionId,accountPatch:xe.accountPatch,nonce:xe.nonce}}catch(xe){B(`onClick:runBeforeButtonClick rejected msg=${(xe instanceof Error?xe.message:String(xe)).slice(0,120)}`),Ie.current=null,nt.current.delete(M),await V.reject();return}He(()=>We.current?.("paypal"));let ke={generation:ir(),surfaceKey:M,...N};Ie.current=ke,nt.current.set(M,ke),await V.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:I?()=>Ne(I).then(wt):()=>x("Failed to create PayPal order.").then(wt),createSubscription:l?I?()=>Ne(I).then(wt):()=>x("Failed to create PayPal subscription.").then(wt):void 0,onApprove:f,onCancel:()=>{if(Me())return;let J=nt.current.get(M)??Ie.current;J&&nt.current.delete(J.surfaceKey),Ie.current=null,ln(),U.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),se.current=!0,kt({generation:J?.generation,remount:!0,focus:!1})},onError:J=>{if(Me()||Fe.current!==M)return;let V=J instanceof Error?J.message:"PayPal failed to render.";if(B(`onError rendered=${Pt} msg=${V.slice(0,120)}`),Pt){let p=nt.current.get(M)??Ie.current;if(p&&!Zt(p.generation)||!p&&je.current===St.current)return;if(Ot(V)){Bt(p?.generation);return}if(ln(),Hr(J)){U.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),O(J,p),He(()=>ft.current?.(Et("paypal",V))),p&&nt.current.delete(p.surfaceKey),Ie.current=null,Bt(p?.generation);return}let N=V.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),Ie.current=null,kt({generation:p?.generation,remount:!0,showRetry:!0,focus:!0}),yn(J,{code:"paypal_runtime_failed"});return}nn(V)}}),y=F.isEligible();if(B(`isEligible=${y}`),U.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!y){ne(!1),nn("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Wn=F,z&&B(`container:dims ${Ut(xt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),z&&typeof MutationObserver<"u"&&(tn=new MutationObserver(J=>{if(!Me()){for(let V of J)if(V.type==="childList")V.addedNodes.forEach(p=>{if(!(p instanceof Element))return;let N=p.tagName.toLowerCase(),fe=(p.getAttribute("title")??"").slice(0,40),ke=N==="iframe"?` ${_e(p)}`:"";B(`child+ ${N}${fe?` title="${fe}"`:""}${ke} dims=${Ut(p)}`)});else if(V.type==="attributes"&&V.target instanceof Element){let p=V.target;if(p.tagName.toLowerCase()!=="iframe")continue;let N=V.attributeName;(N==="src"||N==="srcdoc")&&B(`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=J=>{if(Me()||Pt)return;let V=xt.querySelectorAll("iframe"),p=typeof document<"u"&&"hasStorageAccess"in document;B(`watchdog:${J} container=${Ut(xt)} children=${xt.childElementCount} iframes=${V.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${p} paypalNetRequests=${jt.value}`),V.forEach((N,fe)=>{let ke=(N.getAttribute("title")??"").slice(0,40);B(` iframe[${fe}] ${Ut(N)}${ke?` title="${ke}"`:""} ${_e(N)}`);let xe=qt(N);xe&&B(` ${xe}`)}),gt.length===0&&B(" (no PayPal/zoid window errors captured)")};z&&(Yt.push(setTimeout(()=>Ae("3s"),3e3)),Yt.push(setTimeout(()=>Ae("8s"),8e3)),Yt.push(setTimeout(()=>Ae("15s"),15e3))),B("render:start");let Qe=U.startTiming();Yt.push(setTimeout(()=>{Me()||Pt||(B("watchdog:11s retryable render timeout"),nn("PayPal Buttons render did not settle within 11000ms.",!0))},Gs)),F.render(xt).then(()=>{if(B(`render:resolved inactive=${Me()}`),Vt(),Me()){rt();return}Pt=!0,ne(!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(J=>{let V=J instanceof Error?J.message:"PayPal failed to render.";B(`render:rejected msg=${V.slice(0,120)}`),Vt(),nn(V)})}).catch(r=>{let f=r instanceof Error?r.message:"PayPal SDK failed to load.";B(`loadScript:rejected msg=${f.slice(0,120)}`),nn(f)})},0);return()=>{Lt=!0,clearTimeout(ve),In&&clearTimeout(In),Vt(),rt()}},[k,ue,o,d,s,l,e,I,re,U]);let Hn=z?ra("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=${le} failed=${$e})`,Je.length===0?`
7
7
  (waiting for first lifecycle event\u2026)`:`
8
- ${je.join(`
9
- `)}`]}):null;return Ne&&!ut?D?fr("div",{children:nn}):null:Yo("div",{children:[nn,Yo("div",{"aria-hidden":ge?!0:void 0,style:ge?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:po},children:[!ye&&!ge&&fr("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"}}),fr("div",{ref:K,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:po,display:"flex",opacity:ye?1:0},"aria-busy":de||x},ne)]},ne),Ce&&fr("button",{ref:_e,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:cn,style:Fs,children:"Try PayPal again"})]})}function mo(e){return fr(si,{...e})}function li(e){return fr(si,{...e})}import{FloPayError as wn,isSetupIntentClientSecret as Xs,resolveTheme as Qs}from"@flopay/shared";import{Fragment as gr,jsx as p,jsxs as Le}from"react/jsx-runtime";var kn="flopay_stripe_resume",mi="flopay_wallet_resume",$r="flopay_paypal_resume",Zs=250,yi="Just a moment \u2014 we are finalizing your order. Please press pay again.";function na(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function go({billingApiUrl:e,sessionId:t,nonce:n,request:i}){if(!(!t||!n))try{await new $n(e,{telemetry:!1}).reportSessionIntentDecline(t,n,i)}catch{}}function el(e){return e instanceof wn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Jo(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function yo(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let i=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),a=Math.round((i>>16&255)*o),u=Math.round((i>>8&255)*o),l=Math.round((i&255)*o);return`#${(1<<24|a<<16|u<<8|l).toString(16).slice(1)}`}var tl=`
8
+ ${Je.join(`
9
+ `)}`]}):null;return $e&&!ut?z?Pr("div",{children:Hn}):null:ra("div",{children:[Hn,ra("div",{"aria-hidden":he?!0:void 0,style:he?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Co},children:[!le&&!he&&Pr("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"}}),Pr("div",{ref:A,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:Co,display:"flex",opacity:le?1:0},"aria-busy":pe||R},re)]},re),Re&&Pr("button",{ref:de,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Wt,style:Xs,children:"Try PayPal again"})]})}function So(e){return Pr(Ci,{...e})}function Si(e){return Pr(Ci,{...e})}import{FloPayError as Sn,isSetupIntentClientSecret as fl,resolveTheme as gl}from"@flopay/shared";import{Fragment as br,jsx as u,jsxs as Le}from"react/jsx-runtime";var wn="flopay_stripe_resume",Ii="flopay_wallet_resume",Yr="flopay_paypal_resume",hl=250,_i="Just a moment \u2014 we are finalizing your order. Please press pay again.";function pa(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Ro({billingApiUrl:e,sessionId:t,nonce:n,request:i}){if(!(!t||!n))try{await new qn(e,{telemetry:!1}).reportSessionIntentDecline(t,n,i)}catch{}}function Pl(e){return e instanceof Sn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ia(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function wo(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let i=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),s=Math.round((i>>16&255)*o),d=Math.round((i>>8&255)*o),l=Math.round((i&255)*o);return`#${(1<<24|s<<16|d<<8|l).toString(16).slice(1)}`}var bl=`
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
- `,fo=44;function ra(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 nl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},wi={width:"100%",minHeight:fo,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 rl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function fi(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ki(e){return e==="paypal"?"PayPal":hr(e)}function ol(e,t){let n=`We couldn't open ${ki(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ri(e){let t=Be(0),n=Be(null),i=Be(null),o=we((d=i.current)=>{let b=d;b?.timer&&(clearTimeout(b.timer),b.timer=null)},[]),a=we((d,b)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(d),d.timer=setTimeout(()=>{d.timer=null,i.current?.generation===d.generation&&(i.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"}))},b))},[o,e]),u=we(d=>{d.yieldedControl&&a(d,600)},[a]),l=we(d=>{o();let b=t.current+1;t.current=b,n.current=null;let I={generation:b,method:d,timer:null,yieldedControl:!1};return i.current=I,b},[o]),w=we(d=>{let b=i.current;return typeof d=="number"&&b?.generation!==d?!1:(o(b),i.current=null,(typeof d!="number"||n.current===d)&&(n.current=null),!0)},[o]),B=we(d=>{let b=i.current,I=d??b?.generation??t.current;(!d||b?.generation===d)&&(o(b),i.current=null),n.current=I},[o]),P=we(d=>n.current===(d??t.current),[]),R=we(d=>i.current?.generation===d&&n.current!==d,[]),S=we(()=>{let d=i.current;d&&u(d)},[u]),x=we(()=>{let d=i.current;d&&(d.yieldedControl=!0,o(d))},[o]);return Ze(()=>{let d=()=>{document.visibilityState==="visible"?S():x()},b=()=>{x()};return document.addEventListener("visibilitychange",d),window.addEventListener("blur",b),window.addEventListener("focus",S),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("blur",b),window.removeEventListener("focus",S),o()}},[o,x,S]),{startAttempt:l,finishAttempt:w,invalidateAttempt:B,isAttemptInvalidated:P,isAttemptCurrent:R}}function al(e){let t=js(e);return`Enter a valid ${Qo(e)}${t?` (e.g. ${t})`:""}`}function il(e,t,n){let i=$s(e),o=t.trim(),a=n&&i,u=a&&!o,l=a&&!!o&&!qs(e,o);return{visible:n,supported:i,required:a,empty:u,malformed:l}}function gi(e,t){return t instanceof wn?t:new wn(t instanceof Error?t.message:`${rl(e)} before-click hook failed.`,"validation_error")}function Xo(){return p("style",{children:tl})}function sl(e){return typeof e=="number"?`${e}px`:e}function hi(e){if(typeof e=="number"||typeof e=="string")return e}function Ii(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function Ei({state:e,placeholderTestId:t,borderRadius:n=8,children:i}){return e==="unavailable"||e==="load_error"?null:Le("div",{style:{position:"relative",minHeight:44},children:[p("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"}}),p("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:i})]})}function Pi(e){return e!=="unavailable"&&e!=="load_error"}function oa(e){return p(cl,{...e})}function bi({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:o,onErrorChange:a,isProcessing:u=!1,onButtonClick:l,onDecline:w,onTechnicalFailure:B,runBeforeButtonClick:P,onLoadStateChange:R,placeholderBorderRadius:S}){let x=vn(),d=ta(),b=ea(),[I,_]=ve("loading");Ze(()=>{R?.(I)},[I,R]);let[f,me]=ve(!1),F=Be(!1),se=Be(null),ee=Be(null),[D,J]=ve(0),[W,le]=ve(!1),q=Be(!1),K=Be(new Map),{startAttempt:ce,finishAttempt:_e,invalidateAttempt:Pe,isAttemptInvalidated:ye,isAttemptCurrent:te}=Ri((Y,E,ae)=>{B?.(Y,E,{...ae,popupBlocked:ae?.popupBlocked??Un(E)}),le(!0),J(Ne=>Ne+1)});Ze(()=>{W&&ee.current?.focus()},[W,D]);let ge=we(()=>{J(Y=>Y+1)},[]),xe=we((Y,E,ae)=>{Pe(ae),B?.("paypal",Y,{code:E,popupBlocked:Un(Y)}),le(!0),ge()},[Pe,B,ge]),ne=we(()=>{window.setTimeout(()=>{(se.current?.querySelector("iframe")??se.current)?.focus()},0)},[]);Ze(()=>{q.current&&(q.current=!1,ne())},[ne,D]);let ke=we(()=>{le(!1),a?.(null),ne()},[ne,a]);Ze(()=>{if(!d||F.current)return;let Y=new URLSearchParams(window.location.search),E=Y.get("payment_intent"),ae=Y.get("payment_intent_client_secret"),Ne=Y.get("redirect_status");if(!E||!ae)return;F.current=!0;let Oe;try{let k=localStorage.getItem($r);if(k){let Q=JSON.parse(k);Q.clientSecret===ae&&(Oe={...Q.accountPatch?{accountPatch:Q.accountPatch}:{},...Q.sessionId?{sessionId:Q.sessionId}:{},...Q.nonce?{nonce:Q.nonce}:{}})}}catch{}try{localStorage.removeItem($r)}catch{}let de=new URL(window.location.href);de.searchParams.delete("payment_intent"),de.searchParams.delete("payment_intent_client_secret"),de.searchParams.delete("redirect_status"),window.history.replaceState({},"",de.toString()),(async()=>{try{if(me(!0),Ne==="failed"){let Z="PayPal payment was declined. Please try again.";a?.(Z),w?.(Rt("paypal",Z));return}let{paymentIntent:k,error:Q}=await d.retrievePaymentIntent(ae);if(Q){a?.(Q.message??"Failed to retrieve PayPal payment status.");return}if(k&&(k.status==="requires_capture"||k.status==="succeeded")){let Z=typeof k.payment_method=="string"?k.payment_method:k.payment_method?.id;o({id:Z??k.id,type:"card",threeDSecureActionResultTokenId:k.id,isPaypal:!0},Oe)}else{let Z="PayPal payment was not completed. Please try again.";a?.(Z),w?.(Rt("paypal",Z))}}catch(k){a?.(k instanceof Error?k.message:"Failed to complete PayPal payment.")}finally{me(!1)}})()},[d,o,a,w]);let Re=we(async Y=>{if(u||f){Y.reject();return}let E=P?await P("paypal"):{proceed:!0};if(!E.proceed){K.current.delete(D),Y.reject();return}let ae=ce("paypal");K.current.set(D,{generation:ae,accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}),le(!1),l?.("paypal"),Y.resolve()},[K,u,l,P,ce,f,D]),Ce=we(async Y=>{if(!d||!b)return;let E=K.current.get(D);if(E&&!te(E.generation)){K.current.delete(D);return}if(!E&&ye()||E&&!_e(E.generation))return;E||_e();let ae=E??null;if(K.current.delete(D),!ae&&P){let k=await P("paypal");if(!k.proceed){Y.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ae={accountPatch:k.accountPatch,sessionId:k.sessionId,nonce:k.nonce}}let Ne=ae?.sessionId??e,Oe=ae?.nonce??t,de=ae?.accountPatch?.email??n;try{if(me(!0),a?.(null),!Ne||!de)throw new Error("Missing sessionId or email for PayPal payment");let k=d.createPaymentMethod,{error:Q,paymentMethod:Z}=await k({type:"paypal"});if(Q){xe(Q,"stripe_paypal_create_payment_method_failed",E?.generation),Y.paymentFailed({reason:"fail"});return}let ze=await new $n(i).createSessionIntent(Ne,Oe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Z?.id??null,intentKind:"payment"});if(ze.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ut=ze.clientSecret,je={return_url:window.location.href};if(Z?.id&&(je.payment_method=Z.id),typeof window<"u")try{localStorage.setItem($r,JSON.stringify({clientSecret:ut,sessionId:Ne,nonce:Oe,accountPatch:ae?.accountPatch}))}catch{}let{error:ot,paymentIntent:z}=await d.confirmPayment({clientSecret:ut,confirmParams:je,redirect:"if_required"});if(ot){if(typeof window<"u")try{localStorage.removeItem($r)}catch{}if(zr(ot)){let et=ot.message??"Your payment was declined.";a?.(et),w?.(Rt("paypal",et,{code:Tn(ot),declineCode:yr(ot)})),await go({billingApiUrl:i,sessionId:Ne,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Tn(ot)??"provider_declined"}})}else xe(ot,"stripe_paypal_confirm_failed",E?.generation);return}if(typeof window<"u")try{localStorage.removeItem($r)}catch{}let V=typeof z?.payment_method=="string"?z.payment_method:z?.payment_method?.id;o({id:V??z?.id,type:"card",threeDSecureActionResultTokenId:z?.id,isPaypal:!0},{accountPatch:ae?.accountPatch,sessionId:Ne,nonce:Oe});return}catch(k){xe(k,"stripe_paypal_failed",E?.generation)}finally{me(!1)}},[d,b,e,t,n,i,o,a,w,P,xe,_e,te,ye,D]);return Le(gr,{children:[p(Ei,{state:I,placeholderTestId:"flopay-paypal-placeholder",borderRadius:S,children:Le("div",{ref:se,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[W&&p("button",{ref:ee,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ke,style:wi,children:"Try PayPal again"}),p(Si,{onReady:Y=>_(Ii(Y,["paypal"])),onLoadError:()=>{_("load_error"),na(Ft(x),"paypal","paypal")},onClick:Re,onConfirm:Ce,onCancel:()=>{let Y=K.current.get(D);K.current.delete(D),Ft(x)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Pe(Y?.generation),le(!1),q.current=!0,ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},D)]})}),f&&p(Sn,{status:"processing"})]})}function vi({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:o,expressMethods:a,onTokenizedBody:u,onErrorChange:l,onButtonClick:w,onDecline:B,onTechnicalFailure:P,runBeforeButtonClick:R,onLoadStateChange:S,placeholderBorderRadius:x}){let d=vn(),b=ta(),I=ea(),[_,f]=ve("loading");Ze(()=>{S?.(_)},[_,S]);let[me,F]=ve(!1),se=Be(null),ee=Be(null),[D,J]=ve(0),[W,le]=ve(!1),[q,K]=ve("google_pay"),ce=Be(!1),_e=Be("google_pay"),Pe=Be("google_pay"),ye=Be(new Map),{startAttempt:te,finishAttempt:ge,invalidateAttempt:xe,isAttemptInvalidated:ne,isAttemptCurrent:ke}=Ri((de,k,Q)=>{P?.(de,k,{...Q,popupBlocked:Q?.popupBlocked??Un(k)}),K(de),le(!0),J(Z=>Z+1)});Ze(()=>{W&&ee.current?.focus()},[W,D]);let Re=we(()=>{J(de=>de+1)},[]),Ce=we((de,k,Q,Z)=>{xe(Z),P?.(de,k,{code:Q,popupBlocked:Un(k)}),K(de),le(!0),Re()},[xe,P,Re]),Y=we(()=>{window.setTimeout(()=>{(se.current?.querySelector("iframe")??se.current)?.focus()},0)},[]);Ze(()=>{ce.current&&(ce.current=!1,Y())},[Y,D]);let E=we(()=>{le(!1),l?.(null),Y()},[Y,l]),ae=we(async de=>{if(!b||!I)return;let k=ye.current.get(D);if(k&&!ke(k.generation)){ye.current.delete(D);return}if(!k&&ne()||k&&!ge(k.generation))return;k||ge();let Q=de.expressPaymentType??k?.method??_e.current,Z=k??null;ye.current.delete(D);let ze=fi(Q);if(!Z&&R){let V=await R(ze);if(!V.proceed){de.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}Z={accountPatch:V.accountPatch,sessionId:V.sessionId,nonce:V.nonce}}let ut=ze,je=Z?.sessionId??e,ot=Z?.nonce??t,z=Z?.accountPatch?.email??n;try{F(!0),l?.(null);let{error:V}=await I.submit();if(V){Ce(Q,V,"stripe_wallet_submit_failed",k?.generation);return}let{error:et,paymentMethod:Te}=await b.createPaymentMethod({elements:I});if(et||!Te){Ce(Q,et??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",k?.generation);return}if(!je||!z)throw new Error("Missing sessionId or email for wallet payment");let at=await new $n(i).createSessionIntent(je,ot??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Q??ze,paymentMethodId:Te.id,intentKind:o});if(at.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let We=at.clientSecret,{error:Ve,intentId:ln}=Xs(We)?await b.confirmCardSetup(We,{payment_method:Te.id}).then(g=>({error:g.error,intentId:g.setupIntent?.id})):await b.confirmCardPayment(We,{payment_method:Te.id}).then(g=>({error:g.error,intentId:g.paymentIntent?.id}));if(Ve){if(zr(Ve)){let g=Ve.message??"Your payment was declined.";l?.(g),B?.(Rt(ut,g,{code:Tn(Ve),declineCode:yr(Ve)})),await go({billingApiUrl:i,sessionId:je,nonce:ot,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Q??ze,providerDeclineReason:Tn(Ve)??"provider_declined"}})}else Ce(Q,Ve,"stripe_wallet_confirm_failed",k?.generation);return}u({id:Te.id,type:"card",threeDSecureActionResultTokenId:ln},{accountPatch:Z?.accountPatch,sessionId:je,nonce:ot})}catch(V){Ce(Q,V,"stripe_wallet_failed",k?.generation)}finally{F(!1)}},[b,I,e,t,n,i,o,u,l,B,R,Ce,ge,ke,ne,D]),Ne=rt(()=>{let de=["applePay","googlePay","paypal","link","amazonPay","klarna"],k=new Set(["applePay","googlePay"]),Q=new Set(a.map(pi)),Z={};for(let ze of de)Q.has(ze)?Z[ze]=k.has(ze)?"always":"auto":Z[ze]="never";return Z},[a]),Oe=rt(()=>a.map(pi),[a]);return Le(gr,{children:[p(Ei,{state:_,placeholderTestId:"flopay-wallet-placeholder",borderRadius:x,children:Le("div",{ref:se,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[W&&Le("button",{ref:ee,type:"button","data-testid":"flopay-wallet-retry-button",onClick:E,style:wi,children:["Try ",ki(q)," again"]}),p(Si,{onReady:de=>{f(Ii(de,Oe))},onLoadError:de=>{f("load_error"),na(Ft(d),"stripe","wallet")},onClick:async de=>{_e.current=de.expressPaymentType,Pe.current=fi(de.expressPaymentType);let k=R?await R(Pe.current):{proceed:!0};if(!k.proceed){ye.current.delete(D),de.reject();return}let Q=te(de.expressPaymentType);ye.current.set(D,{generation:Q,method:de.expressPaymentType,accountPatch:k.accountPatch,sessionId:k.sessionId,nonce:k.nonce}),le(!1),w?.(Pe.current),de.resolve()},onConfirm:ae,onCancel:()=>{let de=ye.current.get(D);ye.current.delete(D),Ft(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),xe(de?.generation),le(!1),ce.current=!0,Re()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ne,layout:{maxColumns:1,overflow:"never"}}},D)]})}),me&&p(Sn,{status:"processing"})]})}function ll({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:u,backgroundColor:l,borderColor:w,textColor:B,borderRadius:P,fontFamily:R}){let S=Hs(e,t),x=Qa[e],d=S?.backgroundColor??l??"#ffffff",b=S?.borderColor??w??"#d1d5db",I=S?.textColor??B??"#262833";return p("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!i&&u()},disabled:n||i,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:fo,padding:"0 1rem",backgroundColor:d,color:I,border:`1px solid ${b}`,borderRadius:P??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,cursor:n||i?"not-allowed":"pointer",opacity:i&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?p("span",{style:{margin:"0 auto"},children:`Connecting to ${hr(e)}\u2026`}):Le(gr,{children:[Le("span",{style:{display:"inline-flex",alignItems:"center",gap:Ks(e)?8:0},children:[x?p("img",{src:x,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):S?.logoSvg?p("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:S.logoSvg}}):null,p("span",{children:hr(e)})]}),a&&p("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:I,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:p("path",{d:"M9 18l6-6-6-6"})})]})})}function Zo({method:e,sessionId:t,nonce:n,email:i,billingName:o,billingApiUrl:a,onTokenizedBody:u,onErrorChange:l,onDecline:w,onCancel:B,runBeforeButtonClick:P,onButtonClick:R,isProcessing:S,submitButtonColor:x,submitButtonBorderRadius:d,submitButtonStyle:b,errorText:I}){let _=vn(),f=ta(),me=ea(),[F,se]=ve(!1),ee=Be(!1),[D,J]=ve(!1),[W,le]=ve("loading"),q=we(async()=>{if(!f||!me||S||ee.current||!D)return;ee.current=!0,se(!0);let K=P?await P("card"):{proceed:!0};if(!K.proceed){ee.current=!1,se(!1);return}R?.("card");let ce=K.sessionId??t,_e=K.nonce??n,Pe=K.accountPatch?.email??i;try{l?.(null);let ye=await me.submit();if(ye.error){l?.(ye.error.message??"Payment failed.");return}let te=await f.createPaymentMethod({elements:me});if(te.error||!te.paymentMethod){l?.(te.error?.message??"Failed to create payment method.");return}let ge=te.paymentMethod;if(!ce||!Pe)throw new Error("Missing sessionId or email for payment.");let xe=ge.type||e,ne=await new $n(a).createSessionIntent(ce,_e??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:xe,paymentMethodId:null,intentKind:"payment"});if(ne.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ke=ne.clientSecret;if(typeof window<"u")try{localStorage.setItem(kn,JSON.stringify({clientSecret:ke,sessionId:ce,nonce:_e,accountPatch:K.accountPatch,paymentMethodId:ge.id,paymentMethodType:ge.type??e,gateway:"stripe"}))}catch{}let{error:Re,paymentIntent:Ce}=await f.confirmPayment({clientSecret:ke,confirmParams:{return_url:window.location.href,payment_method:ge.id},redirect:"if_required"});if(Re){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ae=Re.message??"Payment failed.";l?.(ae),w?.(Rt("card",ae,{code:Re.code})),await go({billingApiUrl:a,sessionId:ce,nonce:_e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Re.code??"provider_declined"}});return}let Y=Ce?.status;if(!so(Y)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ae=Y==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";l?.(ae),w?.(Rt("card",ae,{code:Y??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let E=typeof Ce?.payment_method=="string"?Ce.payment_method:Ce?.payment_method?.id;u({id:E??ge.id,type:"card",threeDSecureActionResultTokenId:Ce?.id,gateway:"stripe",paymentMethodType:ge.type??e},{accountPatch:K.accountPatch,sessionId:ce,nonce:_e})}catch(ye){l?.(ye instanceof Error?ye.message:"Payment failed. Please try again.")}finally{ee.current=!1,se(!1)}},[f,me,S,D,P,R,t,n,i,a,e,u,l,w]);return Le("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[p(Ls,{onReady:()=>le("ready"),onLoadError:()=>{le("load_error"),na(Ft(_),"stripe","apm")},onChange:K=>{J(!!K.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...i?{email:i}:{}}}}}),p("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{q()},disabled:!D||F||S||W!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:x,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!D||F||S||W!=="ready"?"not-allowed":"pointer",opacity:!D||F||S||W!=="ready"?.5:1,transition:"opacity 120ms ease-out",...b??{}},children:F?"Processing\u2026":`Pay with ${hr(e)}`}),I&&p(ur,{margin:"0.75rem 0 0",children:I})]})}function Ci({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:o,paymentElementMethods:a,stripeInstance:u,paymentElementBaseOptions:l,onTokenizedBody:w,onErrorChange:B,onButtonClick:P,onDecline:R,runBeforeButtonClick:S,onLoadStateChange:x,isProcessing:d=!1,submitButtonColor:b="#4A49FF",submitButtonBorderRadius:I=8,submitButtonStyle:_,buttonAppearance:f,themeId:me,onExpandApm:F,expandedApmMethod:se}){let[ee,D]=ve(null),[J,W]=ve(null),le=Be(!1);Ze(()=>{a.length>0&&u?x?.("ready"):u||x?.("loading")},[a.length,u,x]);let q=we(async te=>{if(!u||le.current||d)return;le.current=!0,W(te);let ge=S?await S("card"):{proceed:!0};if(!ge.proceed){le.current=!1,W(null);return}P?.("card");let xe=ge.sessionId??e,ne=ge.nonce??t,ke=ge.accountPatch?.email??n;try{if(B?.(null),!xe||!ke)throw new Error("Missing sessionId or email for payment.");let Re=await new $n(o).createSessionIntent(xe,ne??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,paymentMethodId:null,intentKind:"payment"});if(Re.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ce=Re.clientSecret;if(typeof window<"u")try{localStorage.setItem(kn,JSON.stringify({clientSecret:Ce,sessionId:xe,nonce:ne,accountPatch:ge.accountPatch,paymentMethodType:te,gateway:"stripe"}))}catch{}let{error:Y,paymentIntent:E}=await u.confirmPayment({clientSecret:Ce,confirmParams:{return_url:window.location.href,payment_method_data:{type:te,billing_details:{name:i&&i.trim().length>=3?i.trim():"FloPay Customer",...ke?{email:ke}:{}}}},redirect:"if_required"});if(Y){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Oe=Y.message??"Payment failed.";B?.(Oe),R?.(Rt("card",Oe,{code:Y.code})),await go({billingApiUrl:o,sessionId:xe,nonce:ne,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,providerDeclineReason:Y.code??"provider_declined"}});return}let ae=E?.status;if(!so(ae)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Oe=ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";B?.(Oe),R?.(Rt("card",Oe,{code:ae??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Ne=typeof E?.payment_method=="string"?E.payment_method:E?.payment_method?.id;w({id:Ne??E?.id,type:"card",threeDSecureActionResultTokenId:E?.id,gateway:"stripe",paymentMethodType:te},{accountPatch:ge.accountPatch,sessionId:xe,nonce:ne})}catch(Re){B?.(Re instanceof Error?Re.message:"Payment failed. Please try again.")}finally{le.current=!1,W(null)}},[u,d,S,P,e,t,n,o,i,w,B,R]),[K,ce]=ve(null),_e=F?se??null:K,Pe=we(te=>{le.current||d||_e&&_e!==te||(ui(te)?F?F(te):ce(te):q(te))},[_e,d,q,F]),ye=rt(()=>K?{...l,paymentMethodTypes:[K]}:null,[K,l]);return p("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(te=>{let ge=se===te,xe=J===te,ne=J!==null&&J!==te||se!=null&&se!==te;return Le(Gs.Fragment,{children:[p(ll,{method:te,themeId:me,submitting:xe,disabled:ne,highlighted:ge,hasNextStep:ui(te),onClick:()=>Pe(te),backgroundColor:f?.backgroundColor,borderColor:f?.borderColor,textColor:f?.textColor,borderRadius:f?.borderRadius,fontFamily:f?.fontFamily}),!F&&K===te&&ye&&u&&p(tr,{stripe:u,options:ye,children:p(Zo,{method:te,sessionId:e,email:n,billingName:i,billingApiUrl:o,onTokenizedBody:w,onErrorChange:B,onDecline:R,onCancel:()=>ce(null),runBeforeButtonClick:S,onButtonClick:P,isProcessing:d,submitButtonColor:b,submitButtonBorderRadius:I,submitButtonStyle:_})},te)]},te)})})}function cl({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:o,onComplete:a,onError:u,onDecline:l,onTokenizedBody:w,firstName:B,lastName:P,chv:R,className:S,isProcessing:x,error:d,onErrorChange:b,showPayPal:I=!0,showStripe:_=!0,enabledPaymentMethods:f,enabledPaymentMethodCountries:me,showApplePay:F=!0,showGooglePay:se=!0,layout:ee="default",theme:D,buttonsTheme:J,buttonsStyles:W,appearance:le,cardButtonContent:q,cardBackButtonContent:K,cardTitleContent:ce,showSecurityFooter:_e,onButtonClick:Pe,onBeforeButtonClick:ye,enableAVS:te,cardFieldOrder:ge,cardPreFormSlot:xe,avsLayout:ne="row",country:ke,zip:Re,addressLine1:Ce,addressLine2:Y,city:E,state:ae,onCountryChange:Ne,onZipChange:Oe,avsCheck:de,checkoutType:k,checkoutLayout:Q,totalAmount:Z=0,currency:ze="usd",initialCardOpen:ut=!1,directPaypal:je,isSubscription:ot=!1,session:z,dataAttachmentPending:V=!1,debug:et=!1}){let Te=vn(),at=qo(),We=Js(yn),Ve=V||We.claimPending===!0,ln=io(),[g,be]=ve(!1),[pt,tt]=ve(null),[Xe,Ke]=ve(ke??"US"),[Qe,Ie]=ve(Re??""),[qe,Et]=ve(Ce??""),[Ye,Fn]=ve(Y??""),[Ct,Dn]=ve(E??""),[cn,gn]=ve(ae??""),[tn,Ln]=ve({}),Ut=Be(Re??""),_t=Be(ke??"US"),Vt=Be(Ce??""),Xt=Be(Y??""),Dt=Be(E??""),Kt=Be(ae??""),Lt=Be({});Ze(()=>{let r=(v,$,X,O,fe)=>{if(Lt.current[v])return;let Fe=$?.trim();!Fe||Fe===X.current||(X.current=Fe,O(Fe),fe?.(Fe))};r("country",ke,_t,Ke,Ne),r("zip",Re,Ut,Ie,Oe),r("addressLine1",Ce,Vt,Et),r("addressLine2",Y,Xt,Fn),r("city",E,Dt,Dn),r("state",ae,Kt,gn)},[ke,Re,Ce,Y,E,ae,Ne,Oe]);let re=rt(()=>Us(te),[te]),nn=re!==null,T=!!z?.vault?.html,ht=!!z?.gateways?.pcivault,St=!!(z?.gateways?.stripe?.enabledPaymentMethods??f)?.includes("card"),Ee=T||St||ht,Ue=!!(_&&Ee&&Te&&e),[Kn,Nn]=ve(()=>ee!=="buttons"||ut?e??null:null),[Hn,or]=ve(0),Ht=ee!=="buttons"||ut||!!e&&Kn===e,it=rt(()=>!Te||!Ue||!e||!Ht?null:Te.cardCapture({sessionId:e}),[Te,Ue,e,Ht]),Nt=rt(()=>{let r=Xe,v=re?De(re.postal_code,r):!1;return il(r,Qe,v)},[re,Xe,Qe]),{avsInvalid:Wt,invalidAvsFields:Pt}=rt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!Ue||!re)return{avsInvalid:!1,invalidAvsFields:r};let v=Xe,$=(fe,Fe)=>De(fe,v)&&!Fe.trim(),X={line1:$(re.address_line_1,qe),city:$(re.city,Ct),state:$(re.state,cn),zip:Nt.empty||Nt.malformed};return{avsInvalid:X.line1||X.city||X.state||X.zip,invalidAvsFields:X}},[Ue,re,Xe,qe,Ct,cn,Nt]),[Qt,Yt]=ve(!1),[dn,hn]=ve(!1),[xt,$t]=ve(()=>Jo(z?.vault)),[Ae,wt]=ve(ut&&Ee?"card":"buttons"),[kt,Pn]=ve(null),Wn=Ae==="expanding"||Ae==="card",Gt=280,Zt=Be(null),Ot=we(r=>{Zt.current&&clearTimeout(Zt.current),Zt.current=setTimeout(()=>{Zt.current=null,r()},Gt)},[Gt]);Ze(()=>()=>{Zt.current&&clearTimeout(Zt.current)},[]);let In=we(()=>{Nn(e??null),or(r=>r+1),wt("expanding"),Ot(()=>wt("card"))},[Ot,e]),On=we(()=>{wt("collapsing"),Ot(()=>wt("buttons"))},[Ot]),un=we(r=>{Pn(r),wt("apm-expanding"),Ot(()=>wt("apm-form"))},[Ot]),en=we(()=>{wt("apm-collapsing"),Ot(()=>{wt("buttons"),Pn(null)})},[Ot]);Ze(()=>{ee==="buttons"&&ut&&Ee&&(Nn(e??null),wt("card"))},[ee,ut,Ee,e]);let[Tt,h]=ve(null),j=Be(!1),U=Be(null),ue=Be("idle"),[H,ie]=ve(null),C=Be(H);Ze(()=>{C.current=H},[H]);let c=n||ln,s=d??pt,M=rt(()=>Qs(D),[D]),y=rt(()=>{let r=M?.buttonsLayout??Ns(J);return W?{...r,...W,cardButton:{...r.cardButton,...W.cardButton},cardFormContainer:{...r.cardFormContainer,...W.cardFormContainer},backButton:{...r.backButton,...W.backButton},backButtonIcon:{...r.backButtonIcon,...W.backButtonIcon},submitButton:{...r.submitButton,...W.submitButton},title:{...r.title,...W.title}}:r},[M,J,W]),G=le??M?.appearance,Se=rt(()=>{let r=G?.variables,v=Fe=>typeof Fe=="string"&&Fe?Fe:void 0,$=y.submitButton,X=v(r?.colorPrimary)??v($?.backgroundColor)??"#4A49FF",O=ee==="buttons",fe=y.nameInput;return{primaryColor:X,primaryHoverColor:v(r?.colorPrimaryHover)??yo(X,.12),inputBackgroundColor:v(y.cardInputBackground)??v(r?.colorBackground)??"#ffffff",textColor:v(y.cardInputColor)??v(fe?.color)??v(r?.colorText)??"#262833",borderColor:v(y.cardInputBorder)??(O?"#e5e7eb":"#A4A4FF"),placeholderColor:v(y.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(fe?.fontFamily)??v(r?.fontFamily)??"Poppins, sans-serif",fontSize:v(y.cardInputFontSize)??v(r?.fontSizeBase)??"16px",fontWeight:String(hi(fe?.fontWeight)??400),borderRadius:v(r?.borderRadius)??"8px"}},[G,y,ee]),nt=We.inlineSessionPatchProcessing??!1,he=(x??g)||nt,A=c.replace(/\/+$/,""),m=rt(()=>Ko({userId:o,email:i,firstName:B,lastName:P,country:ke,zip:Re},tn),[o,i,B,P,ke,Re,tn]),L=[m.firstName,m.lastName].filter(r=>!!r?.trim()).join(" "),N=rt(()=>Te?Te.getRawProvider():null,[Te]),$e=rt(()=>at?at.getRawProvider():null,[at]),yt=Z||100,Mt=rt(()=>G?Ys(G):null,[G]),kr=Mt?{appearance:Mt}:null,Wr=rt(()=>{let r=Mt??{},v=r.rules??{};return{...r,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[Mt]),ba=rt(()=>{let r=ni(Z);return{...r,currency:ze.toLowerCase(),paymentMethodCreation:"manual",...r.mode==="payment"?{captureMethod:"manual"}:{},...kr}},[Z,ze,kr]),va=rt(()=>({mode:"payment",amount:yt,currency:ze.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...kr}),[yt,ze,kr]),pe=we(r=>{tt(r),b?.(r)},[b]);Ze(()=>{!Ue||!it||it.setCardFieldOrder?.(ge??null,re==null)},[Ue,it,ge,re]),Ze(()=>{(Ae==="expanding"||Ae==="collapsing"||Ae==="apm-expanding"||Ae==="apm-collapsing")&&pe(null)},[Ae,pe]);let pn=we((r,v,$)=>{l?.(Rt(r,v,$))},[l]),ar=we((r,v,$)=>{let X=$?.popupBlocked??Un(v),O=ol(r,X),fe=Zn($?.code)??Tn(v)??"external_payment_method_failed",Fe=new wn(O,"api_error",{code:"external_payment_method_failed",param:r});h(null),ee==="buttons"&&(wt("buttons"),Pn(null)),pe(O),u?.(Fe),console.error("[FloPay] External payment method failed:",{method:r,code:fe,popupBlocked:X})},[ee,u,pe]);Ze(()=>{if(!Ue||!e){$t(null);return}let r=Jo(z?.vault);if(r){$t(r);return}if(!Ht){$t(null);return}$t(null);let v=!0;return new $n(A).getVaultCapture(e,t).then($=>{if(!v)return;let X=Jo($);X?$t(X):pe("Failed to load the secure card form.")}).catch($=>{v&&pe($ instanceof Error?$.message:"Failed to load the secure card form.")}),()=>{v=!1}},[Ue,Ht,Hn,e,z?.vault?.html,z?.vault?.messageToken,z?.vault?.expectedOrigin,A,t,pe]);let En=Be({onComplete:a,onError:u,updateError:pe,emitDecline:pn,resolvedAccount:m,avsConfig:re,avsCheckProp:de,sessionId:e,nonce:t,baseUrl:A});En.current={onComplete:a,onError:u,updateError:pe,emitDecline:pn,resolvedAccount:m,avsConfig:re,avsCheckProp:de,sessionId:e,nonce:t,baseUrl:A};let Io=Be(!1),Hi=we(()=>{let{resolvedAccount:r,avsConfig:v,avsCheckProp:$}=En.current,X=_t.current||r.country||"US",O=v?De(v.state,X):!1,fe=v?De(v.address_line_1,X):!1,Fe=v?De(v.postal_code,X):!1,gt=v?De(v.city,X):!1,zt=v?De(v.address_line_2,X):!1,Ge=fe&&!O&&Fe?di(X,(Ut.current??"").trim()):null,Bt=O?Kt.current:Ge;return{accountData:{userId:r.userId??"",email:r.email??"",firstName:r.firstName??"",lastName:r.lastName??"",...Fe&&Ut.current?{zip:Ut.current}:{},...gt&&Dt.current?{city:Dt.current}:{},...Bt?{state:Bt}:{},...fe&&Vt.current?{addressLine1:Vt.current}:{},...zt&&Xt.current?{addressLine2:Xt.current}:{},country:X},...$!==void 0?{avsCheck:$}:{},...v?{avsConfig:{country:De(v.country,X),postal_code:Fe,address_line_1:fe,address_line_2:zt,city:gt,state:O}}:{}}},[]),Ca=Be(Ve);Ca.current=Ve,Ze(()=>{Ve||s!==yi||En.current.updateError(null)},[Ve,s]),Ze(()=>{!Ue||!it||it.setSubmitGate?.(Wt||Ve)},[Ue,it,Wt,Ve]),Ze(()=>{if(!Ue||!it)return;Io.current=!1;let r=!1,v=it.on("submitting",()=>{Yt(!0),U.current&&clearTimeout(U.current),ue.current="validation-window",U.current=setTimeout(()=>{U.current=null,ue.current==="validation-window"&&(ue.current="processing")},Zs),h("processing");let{baseUrl:Fe,sessionId:gt,nonce:zt,updateError:Ge,onError:Bt}=En.current;!gt||!zt||new $n(Fe).patchAccountSnapshot(gt,zt,Hi(),{telemetryMode:"best_effort"}).catch(Me=>{if(!el(Me))return;let qt=Me instanceof Error?Me.message:"Please check your billing address and try again.";Ge(qt),ue.current="idle",h(null),Bt?.(Me instanceof wn?Me:new wn(qt,"api_error"))})}),$=it.on("complete",async Fe=>{mr(Fe.sessionId??En.current.sessionId),ue.current="terminal",h("success"),await new Promise(gt=>setTimeout(gt,xn)),!Io.current&&(Io.current=!0,En.current.onComplete?.({status:"succeeded",paymentIntentId:Fe.intentId,checkoutMethod:"card"}))}),X=it.on("decline",async Fe=>{let{updateError:gt,emitDecline:zt}=En.current,Ge=Fe.message??"Your payment was declined. Please try another card or contact your bank.";ue.current="terminal",gt(Ge),h("error"),zt("card",Ge,Fe.declineReason?{declineCode:Fe.declineReason}:void 0),await new Promise(Bt=>setTimeout(Bt,Cn)),!r&&(ue.current="idle",h(null))}),O=it.on("error",async Fe=>{let{updateError:gt,onError:zt}=En.current,Ge=Fe.message??"There was a problem processing your payment. Please try again.";ue.current="terminal",gt(Ge),h("error"),zt?.(new wn(Ge,"api_error")),await new Promise(Bt=>setTimeout(Bt,Cn)),!r&&(ue.current="idle",h(null))}),fe=it.on("blocked",()=>{if(!Ca.current){Yt(!0);return}En.current.updateError(yi)});return()=>{r=!0,U.current&&(clearTimeout(U.current),U.current=null),ue.current="idle",v(),$(),X(),O(),fe()}},[Ue,it]);let bn=!!je?.clientId,Rr=Array.isArray(f),Yr=Rr&&f.length>0,Wi=Rr&&f.includes("paypal"),{expressMethods:Gr,paymentElementMethods:Ir}=rt(()=>Ws(f,{excludePaypal:bn}),[f,bn]),Sa=bn||!!at,Yi=rt(()=>Sa?Gr.filter(r=>r!=="paypal"):Gr,[Gr,Sa]),Gi=rt(()=>{let r=[];return F&&r.push("apple_pay"),se&&r.push("google_pay"),r},[F,se]),Jr=Rr?Yi:Gi,Ji=_&&Jr.length>0,Eo=nn?Xe:ke,Xr=rt(()=>{let r=Eo?.trim().toUpperCase();return r?me?Ir.filter(v=>{let $=me[v];return!$||$.length===0||$.includes(r)}):Vs(Ir,Eo):Ir},[Ir,Eo,me]),_o=rt(()=>({mode:"payment",amount:yt,currency:ze.toLowerCase(),paymentMethodCreation:"manual",appearance:Wr}),[yt,ze,Wr]),[wa,ka]=ve("loading"),[Ra,Ia]=ve("loading"),[Ea,_a]=ve("loading"),[Xi,xo]=ve(!1),[xa,To]=ve("loading"),[Qr,Qi]=ve();Ze(()=>{Qi(ri())},[]);let Ta=I&&(bn||(Rr?Wi:Qr===!1)),Ma=_&&Ji,Er=!Ve&&Ta&&bn,Ba=xa==="retrying"||xa==="exhausted",_r=!Ve&&Ta&&!!$e&&(!bn||Ba),xr=!Ve&&Ma&&!!N,Tr=!Ve&&_&&Yr&&Xr.length>0&&!!N,Zi=Er&&!Ba?Xi:_r&&Pi(wa),es=xr&&Pi(Ra),ts=Tr&&Ea!=="load_error",Aa=r=>r==="loading"||r==="ready",Fa=Er||_r&&Aa(wa)||xr&&Aa(Ra)||Tr&&Ea!=="load_error",Zr=Be(!1);Ze(()=>{if(!Zr.current){if(!_&&!I){Zr.current=!0;let r=new wn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(r),pe(r.message)}else if(!_&&I&&!bn&&!$e){Zr.current=!0;let r=new wn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(r),pe(r.message)}else if(Qr!==void 0&&!Ve&&!Ee&&!Fa){Zr.current=!0;let r=new wn("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});u?.(r),pe(r.message)}}},[_,I,bn,$e,Qr,Ve,Ee,Fa,u,pe]);let Da=Be(!1);Ze(()=>{if(Da.current||!Yr)return;let r=[];F!==!0&&r.push("showApplePay"),se!==!0&&r.push("showGooglePay"),r.length!==0&&(Da.current=!0,console.warn(`[FloPay] ${r.join(" / ")} ${r.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.`))},[Yr,F,se]);let La=we((r,v)=>We.applyInlineSessionPatch?We.applyInlineSessionPatch(r).then($=>({error:null,sessionId:$.sessionId||e,nonce:$.session?.clientSecret||t})).catch($=>{let X=gi(v,$);return pe(X.message),u?.(X),{error:X,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[We.applyInlineSessionPatch,t,u,e,pe]),mn=we(async r=>{if(!ye)return{proceed:!0};try{let v=await ye({method:r,sessionId:e||void 0,createSession:We.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&Ln(X=>({...X??{},...v.account}));let $=await La(v,r);return $.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:$.sessionId,nonce:$.nonce}}return{proceed:!0}}catch(v){let $=gi(r,v);return pe($.message),u?.($),{proceed:!1}}},[La,We.inlineSessionDraft,ye,u,e,pe]),Na=we(async(r,v)=>{if(j.current)return;j.current=!0,be(!0),h("processing"),pe(null);let $=v?.sessionId??e,X=v?.nonce??t,O=Ko(m,v?.accountPatch),fe=v?.completionPaymentMethodId??lo(r),Fe=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r;try{let zt=await new $n(A).processPayment(O.userId??"",{sessionId:$,nonce:X,tokenizedData:Fe,accountData:{userId:O.userId??"",email:O.email??"",firstName:O.firstName??"",lastName:O.lastName??"",...re?(()=>{let Me=_t.current,qt=De(re.state,Me),on=De(re.address_line_1,Me),Xn=De(re.postal_code,Me),Qn=on&&!qt&&Xn?di(Me,(Ut.current??"").trim()):null,At=qt?Kt.current:Qn;return{country:Me,...Xn&&Ut.current?{zip:Ut.current}:{},...De(re.city,Me)&&Dt.current?{city:Dt.current}:{},...At?{state:At}:{},...on&&Vt.current?{addressLine1:Vt.current}:{},...De(re.address_line_2,Me)&&Xt.current?{addressLine2:Xt.current}:{}}})():{}},chv:R,avsCheck:de??!1,checkoutType:k,checkoutLayout:Q,avsConfig:re?{country:De(re.country,_t.current),postal_code:De(re.postal_code,_t.current),address_line_1:De(re.address_line_1,_t.current),address_line_2:De(re.address_line_2,_t.current),city:De(re.city,_t.current),state:De(re.state,_t.current)}:void 0});if(zt.ok){mr($),h("success"),ie(null),await new Promise(Me=>setTimeout(Me,xn)),a?.({status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:fe,checkoutMethod:r.isPaypal?"paypal":"card"});return}let Ge=await zt.json().catch(()=>null);if(Ge?.type==="paypal_redirect_required"){let Me=Ge.threeDSecureToken,qt=Ge.paymentMethodId||r.id||"";if(!Te||!Me){h("error"),pe("PayPal authorization required but no token provided.");return}try{let on=at?.getRawProvider();if(!on){pe("PayPal is not available.");return}let Xn={return_url:window.location.href};qt&&(Xn.payment_method=qt);let{error:Qn}=await on.confirmPayment({clientSecret:Me,confirmParams:Xn,redirect:"if_required"});if(Qn){h("error");let At=Qn.message??"PayPal payment failed.";pe(At),pn("paypal",At,{code:Qn.code})}}catch(on){h("error"),pe(on instanceof Error?on.message:"PayPal authorization failed.")}return}if(Ge?.type==="paypal_direct_required"){let Me=Ge.orderId;if(!Me){h("error"),pe("PayPal retry required but no order id provided.");return}let qt=C.current?.attempts??0;if(qt>=2){h("error"),pe("PayPal payment could not be completed after multiple attempts."),pn("paypal","paypal_direct_required retry limit exceeded");return}xo(!1),To("loading"),ie({orderId:Me,attempts:qt+1}),h(null);return}h("error");let Bt=Ge?.message??"Payment failed. Please try again.";pe(Bt),pn(r.isPaypal?"paypal":"card",Bt,{code:Ge?.code??Ge?.gatewayErrorCode,declineCode:Ge?.declineCode??Ge?.gatewayDeclineReason}),await new Promise(Me=>setTimeout(Me,Cn))}catch(gt){h("error"),pe(gt instanceof Error?gt.message:"An unexpected error occurred"),await new Promise(zt=>setTimeout(zt,Cn))}finally{be(!1),h(null),j.current=!1}},[A,e,t,m,L,R,Te,at,a,u,pe,pn]),rn=we((r,v)=>{w?w(r):Na(r,v)},[w,Na]),Oa=Be(!1);Ze(()=>{if(typeof window>"u"||Oa.current)return;let r=new URLSearchParams(window.location.search),v=r.get("payment_intent"),$=r.get("payment_intent_client_secret"),X=r.get("redirect_status");if(!v||!$)return;let O=Bt=>{let Me=localStorage.getItem(Bt);if(!Me)return null;try{return JSON.parse(Me)}catch{return localStorage.removeItem(Bt),null}},fe=O(kn)??O(mi),Fe;if(fe?.clientSecret){if(fe.clientSecret!==$)return;Fe={...fe.accountPatch?{accountPatch:fe.accountPatch}:{},...fe.sessionId?{sessionId:fe.sessionId}:{},...fe.nonce?{nonce:fe.nonce}:{}}}else if(fe?.sessionId&&fe.sessionId!==e)return;Oa.current=!0,localStorage.removeItem(kn),localStorage.removeItem(mi);let gt=new URL(window.location.href);gt.searchParams.delete("payment_intent"),gt.searchParams.delete("payment_intent_client_secret"),gt.searchParams.delete("redirect_status"),window.history.replaceState({},"",gt.toString());let zt=fe?.paymentMethodType??fe?.tokenType??"card",Ge="card";(async()=>{let Bt=Te?.getRawProvider();if(!Bt){let At="Payment is not available \u2014 please refresh and try again.";pe(At),pn(Ge,At);return}if(X==="failed"){let At="Payment was declined. Please try again.";pe(At),pn(Ge,At);return}let{paymentIntent:Me,error:qt}=await Bt.retrievePaymentIntent($);if(qt){let At=qt.message??"Failed to retrieve payment status.";pe(At),pn(Ge,At,{code:qt.code});return}let on=Me?.status,Xn=so(on);if(!Me||!Xn){let At=on==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";pe(At),pn(Ge,At,{code:on??"missing_payment_intent"});return}let Qn=typeof Me.payment_method=="string"?Me.payment_method:Me.payment_method?.id;rn({id:Qn??fe?.paymentMethodId??fe?.tokenId??Me.id,type:"card",threeDSecureActionResultTokenId:Me.id,gateway:fe?.gateway??"stripe",paymentMethodType:zt},Fe)})()},[e,rn,Te,pe,pn]);let Mo=we(r=>{r.preventDefault()},[]);if(!(Te!==null))return p("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Mr=ee==="buttons",Jt=G?.variables,ns=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Bo=Jt?.colorBackground,rs=Bo&&!ns.has(Bo)?Bo:void 0,Br=y.cardInputBorder??(Mr?"#e5e7eb":"#A4A4FF"),Ao=Jt?.colorDanger??"#dc2626",Yn=r=>Qt&&r?Ao:Br,eo=(Nt.malformed||Nt.empty)&&(dn||Qt),os=eo?Ao:Yn(Pt.zip),Fo=y.cardFormContainer?.backgroundColor??rs??(Mr?"white":"#EDEDFF"),Ar=y.cardInputBackground??Jt?.colorBackground??"white",Do=sr(K),za=sr(ce),ir=y.nameInput,Ua=y.cardInputFontSize??sl(ir?.fontSize)??Jt?.fontSizeBase??"16px",$a=typeof ir?.fontFamily=="string"?ir.fontFamily:Jt?.fontFamily??"Poppins, sans-serif",qa=hi(ir?.fontWeight)??400,as=y.cardInputColor??(typeof ir?.color=="string"?ir.color:void 0)??Jt?.colorText??"#262833",is=y.cardInputPlaceholderColor??"#9ca3af",ft=Jt?.borderRadius??"8px",Gn=Jt?.borderRadius??y.cardButton?.borderRadius??ft,Jn=Jt?.colorPrimary??"#4A49FF",ss=Jt?.colorPrimaryHover??yo(Jn,.12),Lo=Jt?.colorText??"#262833",ja={fontSize:Ua,fontFamily:$a,fontWeight:qa,color:as,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ls={"--flopay-input-placeholder-color":is,"--flopay-input-font-size":Ua,"--flopay-input-font-family":$a,"--flopay-input-font-weight":String(qa)},Fr=y.cardFormContainer??{},No=Fr.padding??(Mr?"0":"1rem"),Oo=Fr.borderRadius??ft,cs=it&&xt?p($o,{capture:it,html:xt.html,messageToken:xt.messageToken,expectedOrigin:xt.expectedOrigin,theme:Se,onReady:()=>{if(!re||typeof document>"u")return;let r=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};r();let v=0,$=window.setInterval(()=>{v+=1;let X=document.activeElement;!!X&&X.tagName==="IFRAME"&&X.id==="flopay_vault_form_iframe"?(r(),window.clearInterval($)):v>=50&&window.clearInterval($)},100)},onError:r=>pe(r),onValidation:r=>{let v=ue.current;(v==="idle"||v==="validation-window")&&(pe(r),r&&ue.current==="validation-window"&&(U.current&&(clearTimeout(U.current),U.current=null),ue.current="idle",h(null)))}}):p("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"}),Va=Le("div",{style:{backgroundColor:Fo,borderRadius:Oo,...Fr,padding:No,...ls,display:"flex",flexDirection:"column"},children:[p("style",{children:`
30
+ `,ko=44;function ma(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 vl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},zi={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 Cl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function xi(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Oi(e){return e==="paypal"?"PayPal":vr(e)}function Sl(e,t){let n=`We couldn't open ${Oi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ni(e){let t=Be(0),n=Be(null),i=Be(null),o=we((c=i.current)=>{let P=c;P?.timer&&(clearTimeout(P.timer),P.timer=null)},[]),s=we((c,P)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(c),c.timer=setTimeout(()=>{c.timer=null,i.current?.generation===c.generation&&(i.current=null,n.current=c.generation,e(c.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},P))},[o,e]),d=we(c=>{c.yieldedControl&&s(c,600)},[s]),l=we(c=>{o();let P=t.current+1;t.current=P,n.current=null;let k={generation:P,method:c,timer:null,yieldedControl:!1};return i.current=k,P},[o]),v=we(c=>{let P=i.current;return typeof c=="number"&&P?.generation!==c?!1:(o(P),i.current=null,(typeof c!="number"||n.current===c)&&(n.current=null),!0)},[o]),L=we(c=>{let P=i.current,k=c??P?.generation??t.current;(!c||P?.generation===c)&&(o(P),i.current=null),n.current=k},[o]),h=we(c=>n.current===(c??t.current),[]),w=we(c=>i.current?.generation===c&&n.current!==c,[]),C=we(()=>{let c=i.current;c&&d(c)},[d]),R=we(()=>{let c=i.current;c&&(c.yieldedControl=!0,o(c))},[o]);return dt(()=>{let c=()=>{document.visibilityState==="visible"?C():R()},P=()=>{R()};return document.addEventListener("visibilitychange",c),window.addEventListener("blur",P),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",c),window.removeEventListener("blur",P),window.removeEventListener("focus",C),o()}},[o,R,C]),{startAttempt:l,finishAttempt:v,invalidateAttempt:L,isAttemptInvalidated:h,isAttemptCurrent:w}}function wl(e){let t=sl(e);return`Enter a valid ${la(e)}${t?` (e.g. ${t})`:""}`}function kl(e,t,n){let i=al(e),o=t.trim(),s=n&&i,d=s&&!o,l=s&&!!o&&!il(e,o);return{visible:n,supported:i,required:s,empty:d,malformed:l}}function Ti(e,t){return t instanceof Sn?t:new Sn(t instanceof Error?t.message:`${Cl(e)} before-click hook failed.`,"validation_error")}function sa(){return u("style",{children:bl})}function Rl(e){return typeof e=="number"?`${e}px`:e}function Mi(e){if(typeof e=="number"||typeof e=="string")return e}function Ui(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function $i({state:e,placeholderTestId:t,borderRadius:n=8,children:i}){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:i})]})}function Ai(e){return e!=="unavailable"&&e!=="load_error"}function ya(e){return u(Il,{...e})}function Bi({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:o,onErrorChange:s,isProcessing:d=!1,onButtonClick:l,onDecline:v,onTechnicalFailure:L,runBeforeButtonClick:h,onLoadStateChange:w,placeholderBorderRadius:C}){let R=bn(),c=ua(),P=da(),[k,E]=Se("loading");dt(()=>{w?.(k)},[k,w]);let[g,ce]=Se(!1),I=Be(!1),ae=Be(null),X=Be(null),[z,W]=Se(0),[q,te]=Se(!1),U=Be(!1),A=Be(new Map),{startAttempt:Q,finishAttempt:de,invalidateAttempt:se,isAttemptInvalidated:le,isAttemptCurrent:ne}=Ni((H,S,ie)=>{L?.(H,S,{...ie,popupBlocked:ie?.popupBlocked??$n(S)}),te(!0),W($e=>$e+1)});dt(()=>{q&&X.current?.focus()},[q,z]);let he=we(()=>{W(H=>H+1)},[]),Te=we((H,S,ie)=>{se(ie),L?.("paypal",H,{code:S,popupBlocked:$n(H)}),te(!0),he()},[se,L,he]),re=we(()=>{window.setTimeout(()=>{(ae.current?.querySelector("iframe")??ae.current)?.focus()},0)},[]);dt(()=>{U.current&&(U.current=!1,re())},[re,z]);let Ue=we(()=>{te(!1),s?.(null),re()},[re,s]);dt(()=>{if(!c||I.current)return;let H=new URLSearchParams(window.location.search),S=H.get("payment_intent"),ie=H.get("payment_intent_client_secret"),$e=H.get("redirect_status");if(!S||!ie)return;I.current=!0;let ze;try{let T=localStorage.getItem(Yr);if(T){let ue=JSON.parse(T);ue.clientSecret===ie&&(ze={...ue.accountPatch?{accountPatch:ue.accountPatch}:{},...ue.sessionId?{sessionId:ue.sessionId}:{},...ue.nonce?{nonce:ue.nonce}:{}})}}catch{}try{localStorage.removeItem(Yr)}catch{}let pe=new URL(window.location.href);pe.searchParams.delete("payment_intent"),pe.searchParams.delete("payment_intent_client_secret"),pe.searchParams.delete("redirect_status"),window.history.replaceState({},"",pe.toString()),(async()=>{try{if(ce(!0),$e==="failed"){let Y="PayPal payment was declined. Please try again.";s?.(Y),v?.(Et("paypal",Y));return}let{paymentIntent:T,error:ue}=await c.retrievePaymentIntent(ie);if(ue){s?.(ue.message??"Failed to retrieve PayPal payment status.");return}if(T&&(T.status==="requires_capture"||T.status==="succeeded")){let Y=typeof T.payment_method=="string"?T.payment_method:T.payment_method?.id;o({id:Y??T.id,type:"card",threeDSecureActionResultTokenId:T.id,isPaypal:!0},ze)}else{let Y="PayPal payment was not completed. Please try again.";s?.(Y),v?.(Et("paypal",Y))}}catch(T){s?.(T instanceof Error?T.message:"Failed to complete PayPal payment.")}finally{ce(!1)}})()},[c,o,s,v]);let Fe=we(async H=>{if(d||g){H.reject();return}let S=h?await h("paypal"):{proceed:!0};if(!S.proceed){A.current.delete(z),H.reject();return}let ie=Q("paypal");A.current.set(z,{generation:ie,accountPatch:S.accountPatch,sessionId:S.sessionId,nonce:S.nonce}),te(!1),l?.("paypal"),H.resolve()},[A,d,l,h,Q,g,z]),Re=we(async H=>{if(!c||!P)return;let S=A.current.get(z);if(S&&!ne(S.generation)){A.current.delete(z);return}if(!S&&le()||S&&!de(S.generation))return;S||de();let ie=S??null;if(A.current.delete(z),!ie&&h){let T=await h("paypal");if(!T.proceed){H.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ie={accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}}let $e=ie?.sessionId??e,ze=ie?.nonce??t,pe=ie?.accountPatch?.email??n;try{if(ce(!0),s?.(null),!$e||!pe)throw new Error("Missing sessionId or email for PayPal payment");let T=c.createPaymentMethod,{error:ue,paymentMethod:Y}=await T({type:"paypal"});if(ue){Te(ue,"stripe_paypal_create_payment_method_failed",S?.generation),H.paymentFailed({reason:"fail"});return}let Ee=await new qn(i).createSessionIntent($e,ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Y?.id??null,intentKind:"payment"});if(Ee.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ut=Ee.clientSecret,Je={return_url:window.location.href};if(Y?.id&&(Je.payment_method=Y.id),typeof window<"u")try{localStorage.setItem(Yr,JSON.stringify({clientSecret:ut,sessionId:$e,nonce:ze,accountPatch:ie?.accountPatch}))}catch{}let{error:yt,paymentIntent:B}=await c.confirmPayment({clientSecret:ut,confirmParams:Je,redirect:"if_required"});if(yt){if(typeof window<"u")try{localStorage.removeItem(Yr)}catch{}if(Hr(yt)){let tt=yt.message??"Your payment was declined.";s?.(tt),v?.(Et("paypal",tt,{code:Mn(yt),declineCode:hr(yt)})),await Ro({billingApiUrl:i,sessionId:$e,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(yt)??"provider_declined"}})}else Te(yt,"stripe_paypal_confirm_failed",S?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Yr)}catch{}let G=typeof B?.payment_method=="string"?B.payment_method:B?.payment_method?.id;o({id:G??B?.id,type:"card",threeDSecureActionResultTokenId:B?.id,isPaypal:!0},{accountPatch:ie?.accountPatch,sessionId:$e,nonce:ze});return}catch(T){Te(T,"stripe_paypal_failed",S?.generation)}finally{ce(!1)}},[c,P,e,t,n,i,o,s,v,h,Te,de,ne,le,z]);return Le(br,{children:[u($i,{state:k,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:Le("div",{ref:ae,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[q&&u("button",{ref:X,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ue,style:zi,children:"Try PayPal again"}),u(Li,{onReady:H=>E(Ui(H,["paypal"])),onLoadError:()=>{E("load_error"),pa(At(R),"paypal","paypal")},onClick:Fe,onConfirm:Re,onCancel:()=>{let H=A.current.get(z);A.current.delete(z),At(R)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),se(H?.generation),te(!1),U.current=!0,he()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},z)]})}),g&&u(Cn,{status:"processing"})]})}function Fi({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:o,expressMethods:s,onTokenizedBody:d,onErrorChange:l,onButtonClick:v,onDecline:L,onTechnicalFailure:h,runBeforeButtonClick:w,onLoadStateChange:C,placeholderBorderRadius:R}){let c=bn(),P=ua(),k=da(),[E,g]=Se("loading");dt(()=>{C?.(E)},[E,C]);let[ce,I]=Se(!1),ae=Be(null),X=Be(null),[z,W]=Se(0),[q,te]=Se(!1),[U,A]=Se("google_pay"),Q=Be(!1),de=Be("google_pay"),se=Be("google_pay"),le=Be(new Map),{startAttempt:ne,finishAttempt:he,invalidateAttempt:Te,isAttemptInvalidated:re,isAttemptCurrent:Ue}=Ni((pe,T,ue)=>{h?.(pe,T,{...ue,popupBlocked:ue?.popupBlocked??$n(T)}),A(pe),te(!0),W(Y=>Y+1)});dt(()=>{q&&X.current?.focus()},[q,z]);let Fe=we(()=>{W(pe=>pe+1)},[]),Re=we((pe,T,ue,Y)=>{Te(Y),h?.(pe,T,{code:ue,popupBlocked:$n(T)}),A(pe),te(!0),Fe()},[Te,h,Fe]),H=we(()=>{window.setTimeout(()=>{(ae.current?.querySelector("iframe")??ae.current)?.focus()},0)},[]);dt(()=>{Q.current&&(Q.current=!1,H())},[H,z]);let S=we(()=>{te(!1),l?.(null),H()},[H,l]),ie=we(async pe=>{if(!P||!k)return;let T=le.current.get(z);if(T&&!Ue(T.generation)){le.current.delete(z);return}if(!T&&re()||T&&!he(T.generation))return;T||he();let ue=pe.expressPaymentType??T?.method??de.current,Y=T??null;le.current.delete(z);let Ee=xi(ue);if(!Y&&w){let G=await w(Ee);if(!G.proceed){pe.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}Y={accountPatch:G.accountPatch,sessionId:G.sessionId,nonce:G.nonce}}let ut=Ee,Je=Y?.sessionId??e,yt=Y?.nonce??t,B=Y?.accountPatch?.email??n;try{I(!0),l?.(null);let{error:G}=await k.submit();if(G){Re(ue,G,"stripe_wallet_submit_failed",T?.generation);return}let{error:tt,paymentMethod:qe}=await P.createPaymentMethod({elements:k});if(tt||!qe){Re(ue,tt??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",T?.generation);return}if(!Je||!B)throw new Error("Missing sessionId or email for wallet payment");let ft=await new qn(i).createSessionIntent(Je,yt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ue??Ee,paymentMethodId:qe.id,intentKind:o});if(ft.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Oe=ft.clientSecret,{error:We,intentId:Jt}=fl(Oe)?await P.confirmCardSetup(Oe,{payment_method:qe.id}).then(Ge=>({error:Ge.error,intentId:Ge.setupIntent?.id})):await P.confirmCardPayment(Oe,{payment_method:qe.id}).then(Ge=>({error:Ge.error,intentId:Ge.paymentIntent?.id}));if(We){if(Hr(We)){let Ge=We.message??"Your payment was declined.";l?.(Ge),L?.(Et(ut,Ge,{code:Mn(We),declineCode:hr(We)})),await Ro({billingApiUrl:i,sessionId:Je,nonce:yt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ue??Ee,providerDeclineReason:Mn(We)??"provider_declined"}})}else Re(ue,We,"stripe_wallet_confirm_failed",T?.generation);return}d({id:qe.id,type:"card",threeDSecureActionResultTokenId:Jt},{accountPatch:Y?.accountPatch,sessionId:Je,nonce:yt})}catch(G){Re(ue,G,"stripe_wallet_failed",T?.generation)}finally{I(!1)}},[P,k,e,t,n,i,o,d,l,L,w,Re,he,Ue,re,z]),$e=ct(()=>{let pe=["applePay","googlePay","paypal","link","amazonPay","klarna"],T=new Set(["applePay","googlePay"]),ue=new Set(s.map(Ei)),Y={};for(let Ee of pe)ue.has(Ee)?Y[Ee]=T.has(Ee)?"always":"auto":Y[Ee]="never";return Y},[s]),ze=ct(()=>s.map(Ei),[s]);return Le(br,{children:[u($i,{state:E,placeholderTestId:"flopay-wallet-placeholder",borderRadius:R,children:Le("div",{ref:ae,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[q&&Le("button",{ref:X,type:"button","data-testid":"flopay-wallet-retry-button",onClick:S,style:zi,children:["Try ",Oi(U)," again"]}),u(Li,{onReady:pe=>{g(Ui(pe,ze))},onLoadError:pe=>{g("load_error"),pa(At(c),"stripe","wallet")},onClick:async pe=>{de.current=pe.expressPaymentType,se.current=xi(pe.expressPaymentType);let T=w?await w(se.current):{proceed:!0};if(!T.proceed){le.current.delete(z),pe.reject();return}let ue=ne(pe.expressPaymentType);le.current.set(z,{generation:ue,method:pe.expressPaymentType,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),te(!1),v?.(se.current),pe.resolve()},onConfirm:ie,onCancel:()=>{let pe=le.current.get(z);le.current.delete(z),At(c)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Te(pe?.generation),te(!1),Q.current=!0,Fe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:$e,layout:{maxColumns:1,overflow:"never"}}},z)]})}),ce&&u(Cn,{status:"processing"})]})}function El({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:d,backgroundColor:l,borderColor:v,textColor:L,borderRadius:h,fontFamily:w}){let C=dl(e,t),R=di[e],c=C?.backgroundColor??l??"#ffffff",P=C?.borderColor??v??"#d1d5db",k=C?.textColor??L??"#262833";return u("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!i&&d()},disabled:n||i,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ko,padding:"0 1rem",backgroundColor:c,color:k,border:`1px solid ${P}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:w,cursor:n||i?"not-allowed":"pointer",opacity:i&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?u("span",{style:{margin:"0 auto"},children:`Connecting to ${vr(e)}\u2026`}):Le(br,{children:[Le("span",{style:{display:"inline-flex",alignItems:"center",gap:cl(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"}}):C?.logoSvg?u("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:C.logoSvg}}):null,u("span",{children:vr(e)})]}),s&&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 ca({method:e,sessionId:t,nonce:n,email:i,billingName:o,billingApiUrl:s,onTokenizedBody:d,onErrorChange:l,onDecline:v,onCancel:L,runBeforeButtonClick:h,onButtonClick:w,isProcessing:C,submitButtonColor:R,submitButtonBorderRadius:c,submitButtonStyle:P,errorText:k}){let E=bn(),g=ua(),ce=da(),[I,ae]=Se(!1),X=Be(!1),[z,W]=Se(!1),[q,te]=Se("loading"),U=we(async()=>{if(!g||!ce||C||X.current||!z)return;X.current=!0,ae(!0);let A=h?await h("card"):{proceed:!0};if(!A.proceed){X.current=!1,ae(!1);return}w?.("card");let Q=A.sessionId??t,de=A.nonce??n,se=A.accountPatch?.email??i;try{l?.(null);let le=await ce.submit();if(le.error){l?.(le.error.message??"Payment failed.");return}let ne=await g.createPaymentMethod({elements:ce});if(ne.error||!ne.paymentMethod){l?.(ne.error?.message??"Failed to create payment method.");return}let he=ne.paymentMethod;if(!Q||!se)throw new Error("Missing sessionId or email for payment.");let Te=he.type||e,re=await new qn(s).createSessionIntent(Q,de??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Te,paymentMethodId:null,intentKind:"payment"});if(re.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ue=re.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Ue,sessionId:Q,nonce:de,accountPatch:A.accountPatch,paymentMethodId:he.id,paymentMethodType:he.type??e,gateway:"stripe"}))}catch{}let{error:Fe,paymentIntent:Re}=await g.confirmPayment({clientSecret:Ue,confirmParams:{return_url:window.location.href,payment_method:he.id},redirect:"if_required"});if(Fe){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ie=Fe.message??"Payment failed.";l?.(ie),v?.(Et("card",ie,{code:Fe.code})),await Ro({billingApiUrl:s,sessionId:Q,nonce:de,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Fe.code??"provider_declined"}});return}let H=Re?.status;if(!Po(H)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ie=H==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";l?.(ie),v?.(Et("card",ie,{code:H??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let S=typeof Re?.payment_method=="string"?Re.payment_method:Re?.payment_method?.id;d({id:S??he.id,type:"card",threeDSecureActionResultTokenId:Re?.id,gateway:"stripe",paymentMethodType:he.type??e},{accountPatch:A.accountPatch,sessionId:Q,nonce:de})}catch(le){l?.(le instanceof Error?le.message:"Payment failed. Please try again.")}finally{X.current=!1,ae(!1)}},[g,ce,C,z,h,w,t,n,i,s,e,d,l,v]);return Le("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[u(Zs,{onReady:()=>te("ready"),onLoadError:()=>{te("load_error"),pa(At(E),"stripe","apm")},onChange:A=>{W(!!A.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...i?{email:i}:{}}}}}),u("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{U()},disabled:!z||I||C||q!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:R,color:"white",border:"none",borderRadius:c,fontSize:"1rem",fontWeight:600,cursor:!z||I||C||q!=="ready"?"not-allowed":"pointer",opacity:!z||I||C||q!=="ready"?.5:1,transition:"opacity 120ms ease-out",...P??{}},children:I?"Processing\u2026":`Pay with ${vr(e)}`}),k&&u(mr,{margin:"0.75rem 0 0",children:k})]})}function Di({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:o,paymentElementMethods:s,stripeInstance:d,paymentElementBaseOptions:l,onTokenizedBody:v,onErrorChange:L,onButtonClick:h,onDecline:w,runBeforeButtonClick:C,onLoadStateChange:R,isProcessing:c=!1,submitButtonColor:P="#4A49FF",submitButtonBorderRadius:k=8,submitButtonStyle:E,buttonAppearance:g,themeId:ce,onExpandApm:I,expandedApmMethod:ae}){let[X,z]=Se(null),[W,q]=Se(null),te=Be(!1);dt(()=>{s.length>0&&d?R?.("ready"):d||R?.("loading")},[s.length,d,R]);let U=we(async ne=>{if(!d||te.current||c)return;te.current=!0,q(ne);let he=C?await C("card"):{proceed:!0};if(!he.proceed){te.current=!1,q(null);return}h?.("card");let Te=he.sessionId??e,re=he.nonce??t,Ue=he.accountPatch?.email??n;try{if(L?.(null),!Te||!Ue)throw new Error("Missing sessionId or email for payment.");let Fe=await new qn(o).createSessionIntent(Te,re??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,paymentMethodId:null,intentKind:"payment"});if(Fe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Re=Fe.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Re,sessionId:Te,nonce:re,accountPatch:he.accountPatch,paymentMethodType:ne,gateway:"stripe"}))}catch{}let{error:H,paymentIntent:S}=await d.confirmPayment({clientSecret:Re,confirmParams:{return_url:window.location.href,payment_method_data:{type:ne,billing_details:{name:i&&i.trim().length>=3?i.trim():"FloPay Customer",...Ue?{email:Ue}:{}}}},redirect:"if_required"});if(H){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=H.message??"Payment failed.";L?.(ze),w?.(Et("card",ze,{code:H.code})),await Ro({billingApiUrl:o,sessionId:Te,nonce:re,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,providerDeclineReason:H.code??"provider_declined"}});return}let ie=S?.status;if(!Po(ie)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=ie==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";L?.(ze),w?.(Et("card",ze,{code:ie??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let $e=typeof S?.payment_method=="string"?S.payment_method:S?.payment_method?.id;v({id:$e??S?.id,type:"card",threeDSecureActionResultTokenId:S?.id,gateway:"stripe",paymentMethodType:ne},{accountPatch:he.accountPatch,sessionId:Te,nonce:re})}catch(Fe){L?.(Fe instanceof Error?Fe.message:"Payment failed. Please try again.")}finally{te.current=!1,q(null)}},[d,c,C,h,e,t,n,o,i,v,L,w]),[A,Q]=Se(null),de=I?ae??null:A,se=we(ne=>{te.current||c||de&&de!==ne||(Ri(ne)?I?I(ne):Q(ne):U(ne))},[de,c,U,I]),le=ct(()=>A?{...l,paymentMethodTypes:[A]}:null,[A,l]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(ne=>{let he=ae===ne,Te=W===ne,re=W!==null&&W!==ne||ae!=null&&ae!==ne;return Le(ml.Fragment,{children:[u(El,{method:ne,themeId:ce,submitting:Te,disabled:re,highlighted:he,hasNextStep:Ri(ne),onClick:()=>se(ne),backgroundColor:g?.backgroundColor,borderColor:g?.borderColor,textColor:g?.textColor,borderRadius:g?.borderRadius,fontFamily:g?.fontFamily}),!I&&A===ne&&le&&d&&u(rr,{stripe:d,options:le,children:u(ca,{method:ne,sessionId:e,email:n,billingName:i,billingApiUrl:o,onTokenizedBody:v,onErrorChange:L,onDecline:w,onCancel:()=>Q(null),runBeforeButtonClick:C,onButtonClick:h,isProcessing:c,submitButtonColor:P,submitButtonBorderRadius:k,submitButtonStyle:E})},ne)]},ne)})})}function Il({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:o,onComplete:s,onError:d,onDecline:l,onTokenizedBody:v,firstName:L,lastName:h,chv:w,className:C,isProcessing:R,error:c,onErrorChange:P,showPayPal:k=!0,showStripe:E=!0,enabledPaymentMethods:g,enabledPaymentMethodCountries:ce,showApplePay:I=!0,showGooglePay:ae=!0,layout:X="default",theme:z,buttonsTheme:W,buttonsStyles:q,appearance:te,cardButtonContent:U,cardBackButtonContent:A,cardTitleContent:Q,showSecurityFooter:de,onButtonClick:se,onBeforeButtonClick:le,enableAVS:ne,cardFieldOrder:he,cardPreFormSlot:Te,avsLayout:re="row",country:Ue,zip:Fe,addressLine1:Re,addressLine2:H,city:S,state:ie,onCountryChange:$e,onZipChange:ze,avsCheck:pe,checkoutType:T,checkoutLayout:ue,totalAmount:Y=0,currency:Ee="usd",initialCardOpen:ut=!1,directPaypal:Je,isSubscription:yt=!1,session:B,dataAttachmentPending:G=!1,debug:tt=!1}){let qe=bn(),ft=Xo(),Oe=yl(pn),We=G||Oe.claimPending===!0,Jt=fo(),[Ge,Xt]=Se(!1),[_,Pe]=Se(null),[Ye,Ie]=Se(Ue??"US"),[St,Ve]=Se(Fe??""),[je,nt]=Se(Re??""),[Xe,Rn]=Se(H??""),[at,Kn]=Se(S??""),[Wt,yn]=Se(ie??""),[Qt,ir]=Se({}),Bt=Be(Fe??""),kt=Be(Ue??"US"),Zt=Be(Re??""),en=Be(H??""),Ft=Be(S??""),Dt=Be(ie??""),wt=Be({});dt(()=>{let a=(b,K,Z,$,ye)=>{if(wt.current[b])return;let Ce=K?.trim();!Ce||Ce===Z.current||(Z.current=Ce,$(Ce),ye?.(Ce))};a("country",Ue,kt,Ie,$e),a("zip",Fe,Bt,Ve,ze),a("addressLine1",Re,Zt,nt),a("addressLine2",H,en,Rn),a("city",S,Ft,Kn),a("state",ie,Dt,yn)},[Ue,Fe,Re,H,S,ie,$e,ze]);let ee=ct(()=>ol(ne),[ne]),Hn=ee!==null,D=ct(()=>aa(B),[B]),it=!!B?.vault?.html,Lt=!!B?.gateways?.pcivault,Me=!!(B?.gateways?.stripe?.enabledPaymentMethods??g)?.includes("card"),st=it||Me||Lt,Ke=!!(E&&st&&qe&&e),[En,In]=Se(()=>X!=="buttons"||ut?e??null:null),[zn,Wn]=Se(0),_n=X!=="buttons"||ut||!!e&&En===e,rt=ct(()=>!qe||!Ke||!e||!_n?null:qe.cardCapture({sessionId:e,captureMethod:B?.captureMethod}),[qe,Ke,e,_n,B?.captureMethod]),zt=ct(()=>{let a=Ye,b=ee?De(ee.postal_code,a):!1;return kl(a,St,b)},[ee,Ye,St]),{avsInvalid:ln,invalidAvsFields:Pt}=ct(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!Ke||!ee)return{avsInvalid:!1,invalidAvsFields:a};let b=Ye,K=(ye,Ce)=>De(ye,b)&&!Ce.trim(),Z={line1:K(ee.address_line_1,je),city:K(ee.city,at),state:K(ee.state,Wt),zip:zt.empty||zt.malformed};return{avsInvalid:Z.line1||Z.city||Z.state||Z.zip,invalidAvsFields:Z}},[Ke,ee,Ye,je,at,Wt,zt]),[xt,tn]=Se(!1),[cn,Yt]=Se(!1),[Ut,$t]=Se(()=>ia(B?.vault)),[_e,qt]=Se(ut&&st?"card":"buttons"),[gt,fn]=Se(null),Yn=_e==="expanding"||_e==="card",jt=280,Vt=Be(null),Ot=we(a=>{Vt.current&&clearTimeout(Vt.current),Vt.current=setTimeout(()=>{Vt.current=null,a()},jt)},[jt]);dt(()=>()=>{Vt.current&&clearTimeout(Vt.current)},[]);let On=we(()=>{In(e??null),Wn(a=>a+1),qt("expanding"),Ot(()=>qt("card"))},[Ot,e]),Nn=we(()=>{qt("collapsing"),Ot(()=>qt("buttons"))},[Ot]),nn=we(a=>{fn(a),qt("apm-expanding"),Ot(()=>qt("apm-form"))},[Ot]),Gt=we(()=>{qt("apm-collapsing"),Ot(()=>{qt("buttons"),fn(null)})},[Ot]);dt(()=>{X==="buttons"&&ut&&st&&(In(e??null),qt("card"))},[X,ut,st,e]);let[rn,Ne]=Se(null),x=Be(!1),O=Be(null),M=Be("idle"),[be,ve]=Se(null),m=Be(be);dt(()=>{m.current=be},[be]);let r=n||Jt,f=c??_,F=ct(()=>gl(z),[z]),y=ct(()=>{let a=F?.buttonsLayout??tl(W);return q?{...a,...q,cardButton:{...a.cardButton,...q.cardButton},cardFormContainer:{...a.cardFormContainer,...q.cardFormContainer},backButton:{...a.backButton,...q.backButton},backButtonIcon:{...a.backButtonIcon,...q.backButtonIcon},submitButton:{...a.submitButton,...q.submitButton},title:{...a.title,...q.title}}:a},[F,W,q]),j=te??F?.appearance,Ae=ct(()=>{let a=j?.variables,b=Ce=>typeof Ce=="string"&&Ce?Ce:void 0,K=y.submitButton,Z=b(a?.colorPrimary)??b(K?.backgroundColor)??"#4A49FF",$=X==="buttons",ye=y.nameInput;return{primaryColor:Z,primaryHoverColor:b(a?.colorPrimaryHover)??wo(Z,.12),inputBackgroundColor:b(y.cardInputBackground)??b(a?.colorBackground)??"#ffffff",textColor:b(y.cardInputColor)??b(ye?.color)??b(a?.colorText)??"#262833",borderColor:b(y.cardInputBorder)??($?"#e5e7eb":"#A4A4FF"),placeholderColor:b(y.cardInputPlaceholderColor)??"#9ca3af",errorColor:b(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:b(ye?.fontFamily)??b(a?.fontFamily)??"Poppins, sans-serif",fontSize:b(y.cardInputFontSize)??b(a?.fontSizeBase)??"16px",fontWeight:String(Mi(ye?.fontWeight)??400),borderRadius:b(a?.borderRadius)??"8px"}},[j,y,X]),Qe=Oe.inlineSessionPatchProcessing??!1,J=(R??Ge)||Qe,V=r.replace(/\/+$/,""),p=ct(()=>ea({userId:o,email:i,firstName:L,lastName:h,country:Ue,zip:Fe},Qt),[o,i,L,h,Ue,Fe,Qt]),N=[p.firstName,p.lastName].filter(a=>!!a?.trim()).join(" "),fe=ct(()=>qe?qe.getRawProvider():null,[qe]),ke=ct(()=>ft?ft.getRawProvider():null,[ft]),xe=Y||100,gn=ct(()=>j?pl(j):null,[j]),xr=gn?{appearance:gn}:null,Do=ct(()=>{let a=gn??{},b=a.rules??{};return{...a,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[gn]),to=ct(()=>{let a=gi(Y);return{...a,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...xr}},[Y,Ee,xr]),Aa=ct(()=>({mode:"payment",amount:xe,currency:Ee.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...xr}),[xe,Ee,xr]),me=we(a=>{Pe(a),P?.(a)},[P]);dt(()=>{!Ke||!rt||rt.setCardFieldOrder?.(he??null,ee==null)},[Ke,rt,he,ee]),dt(()=>{(_e==="expanding"||_e==="collapsing"||_e==="apm-expanding"||_e==="apm-collapsing")&&me(null)},[_e,me]);let dn=we((a,b,K)=>{l?.(Et(a,b,K))},[l]),sr=we((a,b,K)=>{let Z=K?.popupBlocked??$n(b),$=Sl(a,Z),ye=tr(K?.code)??Mn(b)??"external_payment_method_failed",Ce=new Sn($,"api_error",{code:"external_payment_method_failed",param:a});Ne(null),X==="buttons"&&(qt("buttons"),fn(null)),me($),d?.(Ce),console.error("[FloPay] External payment method failed:",{method:a,code:ye,popupBlocked:Z})},[X,d,me]);dt(()=>{if(!Ke||!e){$t(null);return}let a=ia(B?.vault);if(a){$t(a);return}if(!_n){$t(null);return}$t(null);let b=!0;return new qn(V).getVaultCapture(e,t).then(K=>{if(!b)return;let Z=ia(K);Z?$t(Z):me("Failed to load the secure card form.")}).catch(K=>{b&&me(K instanceof Error?K.message:"Failed to load the secure card form.")}),()=>{b=!1}},[Ke,_n,zn,e,B?.vault?.html,B?.vault?.messageToken,B?.vault?.expectedOrigin,V,t,me]);let hn=Be({onComplete:s,onError:d,updateError:me,emitDecline:dn,resolvedAccount:p,avsConfig:ee,avsCheckProp:pe,sessionId:e,nonce:t,baseUrl:V,captureMethod:B?.captureMethod,paymentId:B?.paymentId,authorizationExpiresAt:B?.authorizationExpiresAt});hn.current={onComplete:s,onError:d,updateError:me,emitDecline:dn,resolvedAccount:p,avsConfig:ee,avsCheckProp:pe,sessionId:e,nonce:t,baseUrl:V,captureMethod:B?.captureMethod,paymentId:B?.paymentId,authorizationExpiresAt:B?.authorizationExpiresAt};let Lo=Be(!1),ls=we(()=>{let{resolvedAccount:a,avsConfig:b,avsCheckProp:K}=hn.current,Z=kt.current||a.country||"US",$=b?De(b.state,Z):!1,ye=b?De(b.address_line_1,Z):!1,Ce=b?De(b.postal_code,Z):!1,lt=b?De(b.city,Z):!1,vt=b?De(b.address_line_2,Z):!1,Ze=ye&&!$&&Ce?ki(Z,(Bt.current??"").trim()):null,Rt=$?Dt.current:Ze;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Ce&&Bt.current?{zip:Bt.current}:{},...lt&&Ft.current?{city:Ft.current}:{},...Rt?{state:Rt}:{},...ye&&Zt.current?{addressLine1:Zt.current}:{},...vt&&en.current?{addressLine2:en.current}:{},country:Z},...K!==void 0?{avsCheck:K}:{},...b?{avsConfig:{country:De(b.country,Z),postal_code:Ce,address_line_1:ye,address_line_2:vt,city:lt,state:$}}:{}}},[]),Ba=Be(We);Ba.current=We,dt(()=>{We||f!==_i||hn.current.updateError(null)},[We,f]),dt(()=>{!Ke||!rt||rt.setSubmitGate?.(ln||We)},[Ke,rt,ln,We]),dt(()=>{if(!Ke||!rt)return;Lo.current=!1;let a=!1,b=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")},hl),Ne("processing");let{baseUrl:Ce,sessionId:lt,nonce:vt,updateError:Ze,onError:Rt}=hn.current;!lt||!vt||new qn(Ce).patchAccountSnapshot(lt,vt,ls(),{telemetryMode:"best_effort"}).catch(ge=>{if(!Pl(ge))return;let Tt=ge instanceof Error?ge.message:"Please check your billing address and try again.";Ze(Tt),M.current="idle",Ne(null),Rt?.(ge instanceof Sn?ge:new Sn(Tt,"api_error"))})}),K=rt.on("complete",async Ce=>{if(gr(Ce.sessionId??hn.current.sessionId),M.current="terminal",Ne("success"),await new Promise(Ze=>setTimeout(Ze,Tn)),Lo.current)return;Lo.current=!0;let lt=hn.current,vt=aa(lt)||Ce.outcome==="authorized";hn.current.onComplete?.(vt?{status:"authorized",paymentIntentId:Ce.intentId,paymentId:Ce.paymentId??lt.paymentId,sessionId:Ce.sessionId??lt.sessionId,authorizationExpiresAt:Ce.authorizationExpiresAt??lt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ce.intentId,checkoutMethod:"card"})}),Z=rt.on("decline",async Ce=>{let{updateError:lt,emitDecline:vt}=hn.current,Ze=Ce.message??"Your payment was declined. Please try another card or contact your bank.";M.current="terminal",lt(Ze),Ne("error");let Rt=Ce.failureOutcome??el(Ce.declineReason)??"authorization_declined";vt("card",Ze,{code:Rt,declineCode:Rt}),await new Promise(ge=>setTimeout(ge,vn)),!a&&(M.current="idle",Ne(null))}),$=rt.on("error",async Ce=>{let{updateError:lt,onError:vt}=hn.current,Ze=Ce.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:Ce.failureOutcome??"capture_failed"})),await new Promise(Rt=>setTimeout(Rt,vn)),!a&&(M.current="idle",Ne(null))}),ye=rt.on("blocked",()=>{if(!Ba.current){tn(!0);return}hn.current.updateError(_i)});return()=>{a=!0,O.current&&(clearTimeout(O.current),O.current=null),M.current="idle",b(),K(),Z(),$(),ye()}},[Ke,rt]);let Pn=!!Je?.clientId,Tr=Array.isArray(g),no=Tr&&g.length>0,cs=Tr&&g.includes("paypal"),{expressMethods:ro,paymentElementMethods:Mr}=ct(()=>ul(g,{excludePaypal:Pn}),[g,Pn]),Fa=Pn||!!ft,ds=ct(()=>Fa?ro.filter(a=>a!=="paypal"):ro,[ro,Fa]),us=ct(()=>{let a=[];return I&&a.push("apple_pay"),ae&&a.push("google_pay"),a},[I,ae]),oo=Tr?ds:us,ps=E&&oo.length>0,zo=Hn?Ye:Ue,ao=ct(()=>{let a=zo?.trim().toUpperCase();return a?ce?Mr.filter(b=>{let K=ce[b];return!K||K.length===0||K.includes(a)}):ll(Mr,zo):Mr},[Mr,zo,ce]),Oo=ct(()=>({mode:"payment",amount:xe,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",appearance:Do}),[xe,Ee,Do]),[Da,La]=Se("loading"),[za,Oa]=Se("loading"),[Na,Ua]=Se("loading"),[ms,No]=Se(!1),[$a,Uo]=Se("loading"),[io,ys]=Se();dt(()=>{ys(hi())},[]);let qa=k&&(Pn||(Tr?cs:io===!1)),ja=E&&ps,Ar=!We&&qa&&Pn,Va=$a==="retrying"||$a==="exhausted",Br=!We&&qa&&!!ke&&(!Pn||Va),Fr=!We&&ja&&!!fe,Dr=!We&&E&&no&&ao.length>0&&!!fe,fs=Ar&&!Va?ms:Br&&Ai(Da),gs=Fr&&Ai(za),hs=Dr&&Na!=="load_error",Ka=a=>a==="loading"||a==="ready",Ha=Ar||Br&&Ka(Da)||Fr&&Ka(za)||Dr&&Na!=="load_error",so=Be(!1);dt(()=>{if(!so.current){if(!E&&!k){so.current=!0;let a=new Sn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(a),me(a.message)}else if(!E&&k&&!Pn&&!ke){so.current=!0;let a=new Sn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(a),me(a.message)}else if(io!==void 0&&!We&&!st&&!Ha){so.current=!0;let a=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"});d?.(a),me(a.message)}}},[E,k,Pn,ke,io,We,st,Ha,d,me]);let Wa=Be(!1);dt(()=>{if(Wa.current||!no)return;let a=[];I!==!0&&a.push("showApplePay"),ae!==!0&&a.push("showGooglePay"),a.length!==0&&(Wa.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[no,I,ae]);let Ya=we((a,b)=>Oe.applyInlineSessionPatch?Oe.applyInlineSessionPatch(a).then(K=>({error:null,sessionId:K.sessionId||e,nonce:K.session?.clientSecret||t})).catch(K=>{let Z=Ti(b,K);return me(Z.message),d?.(Z),{error:Z,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Oe.applyInlineSessionPatch,t,d,e,me]),un=we(async a=>{if(!le)return{proceed:!0};try{let b=await le({method:a,sessionId:e||void 0,createSession:Oe.inlineSessionDraft});if(b===!1)return{proceed:!1};if(b&&typeof b=="object"){b.account&&ir(Z=>({...Z??{},...b.account}));let K=await Ya(b,a);return K.error?{proceed:!1,accountPatch:b.account}:{proceed:!0,accountPatch:b.account,sessionId:K.sessionId,nonce:K.nonce}}return{proceed:!0}}catch(b){let K=Ti(a,b);return me(K.message),d?.(K),{proceed:!1}}},[Ya,Oe.inlineSessionDraft,le,d,e,me]),Ga=we(async(a,b)=>{if(x.current)return;x.current=!0,Xt(!0),Ne("processing"),me(null);let K=b?.sessionId??e,Z=b?.nonce??t,$=ea(p,b?.accountPatch),ye=b?.completionPaymentMethodId??Kr(a),Ce=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let vt=await new qn(V).processPayment($.userId??"",{sessionId:K,nonce:Z,tokenizedData:Ce,accountData:{userId:$.userId??"",email:$.email??"",firstName:$.firstName??"",lastName:$.lastName??"",...ee?(()=>{let ge=kt.current,Tt=De(ee.state,ge),Ht=De(ee.address_line_1,ge),Qn=De(ee.postal_code,ge),Zn=Ht&&!Tt&&Qn?ki(ge,(Bt.current??"").trim()):null,Mt=Tt?Dt.current:Zn;return{country:ge,...Qn&&Bt.current?{zip:Bt.current}:{},...De(ee.city,ge)&&Ft.current?{city:Ft.current}:{},...Mt?{state:Mt}:{},...Ht&&Zt.current?{addressLine1:Zt.current}:{},...De(ee.address_line_2,ge)&&en.current?{addressLine2:en.current}:{}}})():{}},chv:w,avsCheck:pe??!1,checkoutType:T,checkoutLayout:ue,avsConfig:ee?{country:De(ee.country,kt.current),postal_code:De(ee.postal_code,kt.current),address_line_1:De(ee.address_line_1,kt.current),address_line_2:De(ee.address_line_2,kt.current),city:De(ee.city,kt.current),state:De(ee.state,kt.current)}:void 0});if(vt.ok){let ge=vt.status===204?null:await vt.json().catch(()=>null),Tt=aa(B)||ge?.status==="authorized";gr(K),Ne("success"),ve(null),await new Promise(Ht=>setTimeout(Ht,Tn)),s?.(Tt?{status:"authorized",...typeof ge?.paymentId=="string"?{paymentId:ge.paymentId}:B?.paymentId?{paymentId:B.paymentId}:{},sessionId:typeof ge?.sessionId=="string"?ge.sessionId:K,...typeof ge?.authorizationExpiresAt=="string"?{authorizationExpiresAt:ge.authorizationExpiresAt}:B?.authorizationExpiresAt?{authorizationExpiresAt:B.authorizationExpiresAt}:{},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ye,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ye,checkoutMethod:a.isPaypal?"paypal":"card"});return}let Ze=await vt.json().catch(()=>null);if(Ze?.type==="paypal_redirect_required"){let ge=Ze.threeDSecureToken,Tt=Ze.paymentMethodId||a.id||"";if(!qe||!ge){Ne("error"),me("PayPal authorization required but no token provided.");return}try{let Ht=ft?.getRawProvider();if(!Ht){me("PayPal is not available.");return}let Qn={return_url:window.location.href};Tt&&(Qn.payment_method=Tt);let{error:Zn}=await Ht.confirmPayment({clientSecret:ge,confirmParams:Qn,redirect:"if_required"});if(Zn){Ne("error");let Mt=Zn.message??"PayPal payment failed.";me(Mt),dn("paypal",Mt,{code:Zn.code})}}catch(Ht){Ne("error"),me(Ht instanceof Error?Ht.message:"PayPal authorization failed.")}return}if(Ze?.type==="paypal_direct_required"){let ge=Ze.orderId;if(!ge){Ne("error"),me("PayPal retry required but no order id provided.");return}let Tt=m.current?.attempts??0;if(Tt>=2){Ne("error"),me("PayPal payment could not be completed after multiple attempts."),dn("paypal","paypal_direct_required retry limit exceeded");return}No(!1),Uo("loading"),ve({orderId:ge,attempts:Tt+1}),Ne(null);return}Ne("error");let Rt=Ze?.message??"Payment failed. Please try again.";me(Rt),dn(a.isPaypal?"paypal":"card",Rt,{code:Ze?.code??Ze?.gatewayErrorCode,declineCode:Ze?.declineCode??Ze?.gatewayDeclineReason}),await new Promise(ge=>setTimeout(ge,vn))}catch(lt){Ne("error"),me(lt instanceof Error?lt.message:"An unexpected error occurred"),await new Promise(vt=>setTimeout(vt,vn))}finally{Xt(!1),Ne(null),x.current=!1}},[V,e,t,p,N,w,qe,ft,B,s,d,me,dn]),on=we((a,b)=>{v?v(a):Ga(a,b)},[v,Ga]),Ja=Be(!1);dt(()=>{if(typeof window>"u"||Ja.current)return;let a=new URLSearchParams(window.location.search),b=a.get("payment_intent"),K=a.get("payment_intent_client_secret"),Z=a.get("redirect_status");if(!b||!K)return;let $=Rt=>{let ge=localStorage.getItem(Rt);if(!ge)return null;try{return JSON.parse(ge)}catch{return localStorage.removeItem(Rt),null}},ye=$(wn)??$(Ii),Ce;if(ye?.clientSecret){if(ye.clientSecret!==K)return;Ce={...ye.accountPatch?{accountPatch:ye.accountPatch}:{},...ye.sessionId?{sessionId:ye.sessionId}:{},...ye.nonce?{nonce:ye.nonce}:{}}}else if(ye?.sessionId&&ye.sessionId!==e)return;Ja.current=!0,localStorage.removeItem(wn),localStorage.removeItem(Ii);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=ye?.paymentMethodType??ye?.tokenType??"card",Ze="card";(async()=>{let Rt=qe?.getRawProvider();if(!Rt){let Mt="Payment is not available \u2014 please refresh and try again.";me(Mt),dn(Ze,Mt);return}if(Z==="failed"){let Mt="Payment was declined. Please try again.";me(Mt),dn(Ze,Mt);return}let{paymentIntent:ge,error:Tt}=await Rt.retrievePaymentIntent(K);if(Tt){let Mt=Tt.message??"Failed to retrieve payment status.";me(Mt),dn(Ze,Mt,{code:Tt.code});return}let Ht=ge?.status,Qn=Po(Ht);if(!ge||!Qn){let Mt=Ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";me(Mt),dn(Ze,Mt,{code:Ht??"missing_payment_intent"});return}let Zn=typeof ge.payment_method=="string"?ge.payment_method:ge.payment_method?.id;on({id:Zn??ye?.paymentMethodId??ye?.tokenId??ge.id,type:"card",threeDSecureActionResultTokenId:ge.id,gateway:ye?.gateway??"stripe",paymentMethodType:vt},Ce)})()},[e,on,qe,me,dn]);let $o=we(a=>{a.preventDefault()},[]);if(!(qe!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Lr=X==="buttons",Kt=j?.variables,Ps=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),qo=Kt?.colorBackground,bs=qo&&!Ps.has(qo)?qo:void 0,zr=y.cardInputBorder??(Lr?"#e5e7eb":"#A4A4FF"),jo=Kt?.colorDanger??"#dc2626",Gn=a=>xt&&a?jo:zr,lo=(zt.malformed||zt.empty)&&(cn||xt),vs=lo?jo:Gn(Pt.zip),Vo=y.cardFormContainer?.backgroundColor??bs??(Lr?"white":"#EDEDFF"),Or=y.cardInputBackground??Kt?.colorBackground??"white",Ko=cr(A),Xa=cr(Q),lr=y.nameInput,Qa=y.cardInputFontSize??Rl(lr?.fontSize)??Kt?.fontSizeBase??"16px",Za=typeof lr?.fontFamily=="string"?lr.fontFamily:Kt?.fontFamily??"Poppins, sans-serif",ei=Mi(lr?.fontWeight)??400,Cs=y.cardInputColor??(typeof lr?.color=="string"?lr.color:void 0)??Kt?.colorText??"#262833",Ss=y.cardInputPlaceholderColor??"#9ca3af",bt=Kt?.borderRadius??"8px",Jn=Kt?.borderRadius??y.cardButton?.borderRadius??bt,Xn=Kt?.colorPrimary??"#4A49FF",ws=Kt?.colorPrimaryHover??wo(Xn,.12),Ho=Kt?.colorText??"#262833",ti={fontSize:Qa,fontFamily:Za,fontWeight:ei,color:Cs,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ks={"--flopay-input-placeholder-color":Ss,"--flopay-input-font-size":Qa,"--flopay-input-font-family":Za,"--flopay-input-font-weight":String(ei)},Nr=y.cardFormContainer??{},Wo=Nr.padding??(Lr?"0":"1rem"),Yo=Nr.borderRadius??bt,Rs=rt&&Ut?u(jr,{capture:rt,html:Ut.html,messageToken:Ut.messageToken,expectedOrigin:Ut.expectedOrigin,theme:Ae,onReady:()=>{if(!ee||typeof document>"u")return;let a=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};a();let b=0,K=window.setInterval(()=>{b+=1;let Z=document.activeElement;!!Z&&Z.tagName==="IFRAME"&&Z.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(K)):b>=50&&window.clearInterval(K)},100)},onError:a=>me(a),onValidation:a=>{let b=M.current;(b==="idle"||b==="validation-window")&&(me(a),a&&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"}),ni=Le("div",{style:{backgroundColor:Vo,borderRadius:Yo,...Nr,padding:Wo,...ks,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
- `}),Mr&&Wn&&Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ue?-2:0},children:[Le("button",{type:"button",onClick:On,style:{display:"inline-flex",alignItems:"center",gap:Do?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:y.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...y.backButton},"aria-label":"Back to payment methods",children:[p("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...y.backButtonIcon},children:p("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:p("path",{d:"M15 18l-6-6 6-6"})})}),p(cr,{content:K})]}),za?p("div",{style:{flex:1}}):p("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...y.title},children:p(Lr,{content:ce})})]}),!Mr&&!za&&p("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Lo,order:Ue?-3:0,...y.title},children:p(Lr,{content:ce})}),re&&p("div",{style:{order:Ue?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=Xe,v=(O=!1)=>({backgroundColor:Ar,border:`1px solid ${Yn(O)}`,borderRadius:ft,marginTop:"0.5rem",padding:"10px"}),$=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ja}),X=Os(r);return Le(gr,{children:[De(re.address_line_1,r)&&p("div",{style:v(Pt.line1),children:p("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:qe,onChange:O=>{Lt.current.addressLine1=!0,Vt.current=O.target.value,Et(O.target.value)},disabled:he,required:!0,"data-testid":"flopay-address-line1",style:$()})}),De(re.address_line_2,r)&&p("div",{style:v(),children:p("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Ye,onChange:O=>{Lt.current.addressLine2=!0,Xt.current=O.target.value,Fn(O.target.value)},disabled:he,"data-testid":"flopay-address-line2",style:$()})}),(De(re.city,r)||De(re.state,r))&&Le("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[De(re.city,r)&&p("div",{style:{flex:1,backgroundColor:Ar,borderTop:`1px solid ${Yn(Pt.city)}`,borderRight:`1px solid ${Yn(Pt.city)}`,borderBottom:`1px solid ${Yn(Pt.city)}`,borderLeft:`1px solid ${Yn(Pt.city)}`,padding:"10px",borderTopLeftRadius:ft,borderBottomLeftRadius:ft,...De(re.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:ft}},children:p("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Ct,onChange:O=>{Lt.current.city=!0,Dt.current=O.target.value,Dn(O.target.value)},disabled:he,required:!0,"data-testid":"flopay-city",style:$()})}),De(re.state,r)&&p("div",{style:{flex:1,backgroundColor:Ar,border:`1px solid ${Yn(Pt.state)}`,padding:"10px",borderTopRightRadius:ft,borderBottomRightRadius:ft,...De(re.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:ft}},children:X?Le("select",{id:"flopay-billing-state",name:"billing-state",value:cn,onChange:O=>{Lt.current.state=!0,Kt.current=O.target.value,gn(O.target.value)},disabled:he,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...$(),cursor:"pointer"},children:[p("option",{value:"",children:ci(r)}),X.map(O=>p("option",{value:O.code,children:O.name},O.code))]}):p("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:ci(r),autoComplete:"billing address-level1",value:cn,onChange:O=>{Lt.current.state=!0,Kt.current=O.target.value,gn(O.target.value)},disabled:he,required:!0,"data-testid":"flopay-state",style:$()})})]}),(De(re.country,r)||De(re.postal_code,r))&&Le("div",{style:{display:"flex",flexDirection:ne==="column"?"column":"row",gap:ne==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[De(re.country,r)&&p("div",{style:{flex:ne==="row"?1:void 0,backgroundColor:Ar,borderTop:`1px solid ${Br}`,borderRight:`1px solid ${Br}`,borderBottom:`1px solid ${Br}`,borderLeft:`1px solid ${Br}`,padding:"10px",...ne==="row"&&De(re.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:ft,borderBottomLeftRadius:ft,borderRight:"none"}:{borderRadius:ft}},children:p("select",{id:"flopay-billing-country",name:"billing-country",value:Xe,onChange:O=>{Lt.current.country=!0,_t.current=O.target.value,Ke(O.target.value),Ne?.(O.target.value),Kt.current="",gn("")},disabled:he,autoComplete:"billing country","data-testid":"flopay-country",style:{...$(),cursor:"pointer"},children:zs.map(O=>Le("option",{value:O.code,children:[O.flag," ",O.name]},O.code))})}),De(re.postal_code,r)&&p("div",{style:{flex:ne==="row"?1:void 0,backgroundColor:Ar,border:`1px solid ${os}`,padding:"10px",...ne==="row"&&De(re.country,r)?{borderRadius:"0",borderTopRightRadius:ft,borderBottomRightRadius:ft}:{borderRadius:ft}},children:p("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Qo(Xe),autoComplete:"billing postal-code",value:Qe,onChange:O=>{Lt.current.zip=!0,Ut.current=O.target.value,Ie(O.target.value),Oe?.(O.target.value)},onBlur:()=>hn(!0),disabled:he,required:Nt.required,"aria-invalid":eo||void 0,"aria-describedby":eo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:$()})})]}),eo&&p("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Ao,...ja,fontSize:"0.75rem"},children:Nt.empty?`${Qo(r)} is required`:al(r)})]})})()}),Ue&&xe&&p("div",{style:{order:-2,width:"100%"},children:xe}),Ue&&cs,s&&p(ur,{margin:"0.75rem 0",styleOverride:y.errorBanner,children:s})]}),to={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"},Ka=r=>et?!I||!bn?p("pre",{"data-testid":r,style:to,children:"FloPay/DirectPayPal-debug - not enabled"}):p("pre",{"data-testid":r,style:to,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${I}`,` directPaypalConfigured=${bn}`,` inAppBrowserDetected=${String(Qr)}`,` shouldRenderDirectPayPal=${Er}`,` shouldRenderStripePayPal=${_r}`,` hasPaypalStripeInstance=${!!$e}`].join(`
39
- `)}):null,Ha=r=>et?!_||!N?p("pre",{"data-testid":r,style:to,children:"FloPay/Stripe-debug - not enabled"}):p("pre",{"data-testid":r,style:to,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${_}`,` currency=${ze}`,` amountInCents=${yt}`,` enabledPaymentMethods: ${JSON.stringify(f??[])}`,` enabledPaymentMethodsProvided=${Rr}`,` hasEnabledMethods=${Yr}`,` expressMethods: ${JSON.stringify(Gr)}`,` walletExpressMethods: ${JSON.stringify(Jr)}`,` paymentElementMethods: ${JSON.stringify(Ir)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Xr)}`,` hasStripeInstance=${!!N}`,` shouldRenderWallets=${xr}`,` shouldRenderPaymentElement=${Tr}`].join(`
40
- `)}):null,Wa=Ae==="apm-expanding"||Ae==="apm-form"||Ae==="apm-collapsing",no=Ae==="apm-expanding"?`flopay-card-enter ${Gt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ae==="apm-collapsing"?`flopay-card-exit ${Gt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,ro=kt?{..._o,paymentMethodTypes:[kt]}:null;if(ee==="buttons"){let r=Ae==="buttons"||Ae==="expanding"||Ae==="apm-expanding",v=Ae==="expanding"||Ae==="card"||Ae==="collapsing",$=q===void 0?{boxSizing:"border-box",height:fo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},X=Ae==="expanding"||Ae==="apm-expanding"?`flopay-buttons-exit ${Gt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ae==="collapsing"||Ae==="apm-collapsing"?`flopay-buttons-enter ${Gt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,O=Ae==="expanding"?`flopay-card-enter ${Gt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ae==="collapsing"?`flopay-card-exit ${Gt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Le("form",{onSubmit:Mo,className:S,style:{position:"relative"},children:[p(Xo,{}),Tt&&p(Sn,{status:Tt,errorMessage:s}),Le("div",{style:{display:"grid"},children:[Le("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!X?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!X?nl:{},...X?{animation:X,pointerEvents:"none"}:{}},children:[Ka("flopay-direct-paypal-gate-debug"),Ha("flopay-stripe-gate-debug"),Er&&je&&Le(gr,{children:[H&&p("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."}),p(mo,{sessionId:e,nonce:t,billingApiUrl:c,email:m.email,clientId:je.clientId,environment:je.environment,currency:ze.toUpperCase(),isSubscription:ot,onTokenizedBody:rn,onComplete:a,onErrorChange:pe,onDecline:l,onTechnicalFailure:ar,onButtonClick:Pe,runBeforeButtonClick:mn,isProcessing:he,onLoadStateChange:xo,onInitializationStateChange:To,session:z??null,existingOrderId:H?.orderId,debug:et},H?.orderId??"fresh")]}),_r&&p(tr,{stripe:$e,options:va,children:p(bi,{sessionId:e,nonce:t,email:m.email,billingApiUrl:c,onTokenizedBody:rn,onErrorChange:pe,isProcessing:he,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:mn,onLoadStateChange:ka,placeholderBorderRadius:Gn})}),xr?p(tr,{stripe:N,options:ba,children:p(vi,{sessionId:e,nonce:t,email:m.email,billingApiUrl:c,intentKind:Z>0?"payment":"setup",expressMethods:Jr,onTokenizedBody:rn,onErrorChange:pe,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:mn,onLoadStateChange:Ia,placeholderBorderRadius:Gn})}):Ma?p("div",{style:{height:fo,borderRadius:Gn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Tr&&p(Ci,{sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:c,paymentElementMethods:Xr,stripeInstance:N,paymentElementBaseOptions:_o,onTokenizedBody:rn,onErrorChange:pe,onButtonClick:Pe,onDecline:l,runBeforeButtonClick:mn,onLoadStateChange:_a,isProcessing:he,submitButtonColor:Jn,submitButtonBorderRadius:ft,submitButtonStyle:y.submitButton,onExpandApm:un,expandedApmMethod:kt,themeId:D,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:Gn}}),Ue&&p("button",{type:"button",onClick:async()=>{he||!(await mn("card")).proceed||(Pe?.("card"),In())},disabled:he,style:{width:"100%",...$,...y.cardButton,...ra({themeBundle:M,resolvedPrimaryColor:Jn,resolvedBorderRadius:ft,submitButtonStyle:y.submitButton,explicitPrimaryColor:Jt?.colorPrimary}),fontSize:y.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:he?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:he?.6:1},onMouseEnter:fe=>{!he&&(M||Jt?.colorPrimary)&&(fe.currentTarget.style.backgroundColor=ss)},onMouseLeave:fe=>{(M||Jt?.colorPrimary)&&(fe.currentTarget.style.backgroundColor=Jn)},onMouseDown:fe=>{fe.currentTarget.style.transform="scale(0.985)"},onMouseUp:fe=>{fe.currentTarget.style.transform="scale(1)"},children:p(lr,{content:q})}),s&&Ae==="buttons"&&p(ur,{margin:"0.25rem 0",styleOverride:y.errorBanner,children:s})]}),Ue&&v&&p("div",{style:{gridArea:"1 / 1",...O?{animation:O}:{},...Ae==="collapsing"?{pointerEvents:"none"}:{}},children:Va}),_&&Wa&&kt&&ro&&N&&p("div",{style:{gridArea:"1 / 1",...no?{animation:no}:{},...Ae==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Fo,borderRadius:Oo,...Fr,padding:No},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:en,style:{display:"inline-flex",alignItems:"center",gap:Do?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:y.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...y.backButton},"aria-label":"Back to payment methods",children:[p("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...y.backButtonIcon},children:p("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:p("path",{d:"M15 18l-6-6 6-6"})})}),p(cr,{content:K})]}),p("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:Lo,paddingRight:80,...y.title},children:`Pay with ${hr(kt)}`})]}),p(tr,{stripe:N,options:ro,children:p(Zo,{method:kt,sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:c,onTokenizedBody:rn,onErrorChange:pe,onDecline:l,onCancel:en,runBeforeButtonClick:mn,onButtonClick:Pe,isProcessing:he,submitButtonColor:Jn,submitButtonBorderRadius:ft,submitButtonStyle:y.submitButton,errorText:s})},kt)]})})]})]})}return Wa&&kt&&ro&&N&&_?Le("form",{onSubmit:Mo,className:S,style:{position:"relative"},children:[p(Xo,{}),Tt&&p(Sn,{status:Tt,errorMessage:s}),p("div",{style:{...no?{animation:no}:{},...Ae==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Fo,borderRadius:Oo,...Fr,padding:No},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:en,style:{display:"inline-flex",alignItems:"center",gap:Do?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:y.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...y.backButton},"aria-label":"Back to payment methods",children:[p("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...y.backButtonIcon},children:p("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:p("path",{d:"M15 18l-6-6 6-6"})})}),p(cr,{content:K})]}),p("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:Lo,paddingRight:80,...y.title},children:`Pay with ${hr(kt)}`})]}),p(tr,{stripe:N,options:ro,children:p(Zo,{method:kt,sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:c,onTokenizedBody:rn,onErrorChange:pe,onDecline:l,onCancel:en,runBeforeButtonClick:mn,onButtonClick:Pe,isProcessing:he,submitButtonColor:Jn,submitButtonBorderRadius:ft,submitButtonStyle:y.submitButton,errorText:s})},kt)]})})]}):Le("form",{onSubmit:Mo,className:S,style:{position:"relative"},children:[p(Xo,{}),Tt&&p(Sn,{status:Tt,errorMessage:s}),Le("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ka("flopay-direct-paypal-gate-debug-default"),Ha("flopay-stripe-gate-debug-default"),Er&&je&&Le(gr,{children:[H&&p("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."}),p(mo,{sessionId:e,nonce:t,billingApiUrl:c,email:m.email,clientId:je.clientId,environment:je.environment,currency:ze.toUpperCase(),isSubscription:ot,onTokenizedBody:rn,onComplete:a,onErrorChange:pe,onDecline:l,onTechnicalFailure:ar,onButtonClick:Pe,runBeforeButtonClick:mn,isProcessing:he,onLoadStateChange:xo,onInitializationStateChange:To,session:z??null,existingOrderId:H?.orderId,debug:et},H?.orderId??"fresh")]}),_r&&p(tr,{stripe:$e,options:va,children:p(bi,{sessionId:e,nonce:t,email:m.email,billingApiUrl:c,onTokenizedBody:rn,onErrorChange:pe,isProcessing:he,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:mn,onLoadStateChange:ka,placeholderBorderRadius:Gn})}),xr&&p(tr,{stripe:N,options:ba,children:p(vi,{sessionId:e,nonce:t,email:m.email,billingApiUrl:c,intentKind:Z>0?"payment":"setup",expressMethods:Jr,onTokenizedBody:rn,onErrorChange:pe,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:mn,onLoadStateChange:Ia,placeholderBorderRadius:Gn})}),Tr&&p(Ci,{sessionId:e,nonce:t,email:m.email,billingName:[m.firstName,m.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:c,paymentElementMethods:Xr,stripeInstance:N,paymentElementBaseOptions:_o,onTokenizedBody:rn,onErrorChange:pe,onButtonClick:Pe,onDecline:l,runBeforeButtonClick:mn,onLoadStateChange:_a,isProcessing:he,submitButtonColor:Jn,submitButtonBorderRadius:ft,submitButtonStyle:y.submitButton,themeId:D,onExpandApm:un,expandedApmMethod:kt,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:Gn}})]}),Ue&&(es||Zi||ts)&&Le("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[p("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),p("span",{children:"or pay with card"}),p("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ue&&Va]})}import{loadFloPay as _i,PaymentAPI as xi}from"@flopay/js";import{classifyPaymentRejection as dl,FloPayError as Je,isSetupIntentClientSecret as ul}from"@flopay/shared";var jr="card";async function pl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:u}=await e.retrieveSetupIntent(t);return{error:u,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:i,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:i??null}}async function ml(e,t,n,i){if(i){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:u,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:u??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function ia(e,t){return Object.assign(e,{checkoutMethod:t})}function Mn(e,t){let n=e instanceof Je?e:new Je(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 qr(e,t){try{return await e()}catch(n){throw Mn(n,t)}}function Ti(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 yl(e){return e.status==="succeeded"||e.status==="declined"}async function Mi(e){if(typeof document>"u"||typeof window>"u")throw new Je("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Je("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,i=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let P=new AbortController,R=()=>P.abort();e.signal?.aborted?P.abort():e.signal?.addEventListener("abort",R);let S=window.setTimeout(()=>P.abort(),i);try{let x=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:P.signal});if(!x.ok)return{status:"unknown"};let d=await x.json().catch(()=>null);return fl(d)}catch{return{status:"unknown"}}finally{window.clearTimeout(S),e.signal?.removeEventListener("abort",R)}},u=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 w=document.createElement("iframe");w.setAttribute("title","Card authentication"),w.setAttribute("allow","payment"),w.tabIndex=0,w.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(";"),w.src=e.nextActionRedirectUrl,l.appendChild(w),document.body.appendChild(l),w.focus();let B=null;try{B=new URL(e.billingApiUrl,window.location.href).origin}catch{B=null}try{let P=await new Promise((R,S)=>{let x=!1,d=0,b=0,I=0,_=!1,f=()=>{window.clearTimeout(d),window.clearInterval(b),window.clearTimeout(I),window.removeEventListener("message",ee),w.removeEventListener("load",F),e.signal?.removeEventListener("abort",se)},me=async()=>{if(!(x||_)){_=!0;try{let D=await a();if(x||!yl(D))return;x=!0,f(),R(D)}finally{_=!1}}},F=()=>{window.clearTimeout(I),I=window.setTimeout(()=>{me()},250)},se=()=>{x||(x=!0,f(),S(new Je("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ee=D=>{if(D.source!==w.contentWindow||B&&D.origin!==B)return;let J=D.data;!J||typeof J!="object"||J.source!=="flopay-vault-3ds-return"||x||(x=!0,f(),R(null))};d=window.setTimeout(()=>{x||(x=!0,f(),S(new Je("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),b=window.setInterval(()=>{me()},n),w.addEventListener("load",F),window.addEventListener("message",ee),e.signal?.addEventListener("abort",se),e.signal?.aborted&&se()});return P||await a()}finally{l.parentNode?.removeChild(l),u?.isConnected&&u.focus()}}function fl(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function qn(e,t="Payment failed. Please try again.",n){let i=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=zn(o)??o;return ia(new Je(a,"api_error",{code:e?.gatewayErrorCode}),i)}function aa(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ho(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function gl(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 Bi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ho(o)))return o;let i=e?.data;if(i&&typeof i=="object"){let o=i,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let l of a)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||ho(l)))return l;let u=o.gateways;if(u&&typeof u=="object"){let l=u.stripe;if(l&&typeof l=="object"){let w=l,B=[w.stripeClientSecret,w.clientSecret];for(let P of B)if(typeof P=="string"&&P.length>0&&(!t?.requirePaymentIntentClientSecret||ho(P)))return P}}}}async function hl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:i}){let o=Bi(i,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let l=(await new xi(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ho(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Pr({billingApiUrl:e,sessionId:t,session:n,nonce:i,tokenizedData:o,returnUrl:a,telemetry:u}){let l=e.replace(/\/+$/,""),w=t??n.id,B=i??n.clientSecret,P=n.customer?.id??n.accountData?.userId??"",R=n.customer?.email??n.accountData?.email??"",S=n.customer?.firstName??n.accountData?.firstName??"",x=n.customer?.lastName??n.accountData?.lastName??"",d=n.customer?.country??n.accountData?.country??void 0,b=n.customer?.zip??n.accountData?.zip??void 0,I=new xi(l,u===!1?{telemetry:!1}:void 0),_=await gl(()=>I.processPayment(P,{sessionId:w,nonce:B,tokenizedData:o,accountData:{userId:P,email:R,firstName:S,lastName:x,country:d,zip:b},returnUrl:a??aa(n)}));if(_.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:lo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let f;try{f=await _.json()}catch{throw new Je("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:_.status})}if(f?.type==="paypal_redirect_required"||f?.type==="3ds_required"){let F=Bi(f);if(!F)throw new Je("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:_.status});return{type:f.type,threeDSecureToken:F,paymentMethodId:f.paymentMethodId}}if(f?.gatewayErrorCode==="authentication_required"){let F=await hl({billingApiUrl:l,sessionId:w,nonce:B,responseJson:f});if(F)return F;throw ia(new Je("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let me=new Je(f?.message??"Payment failed. Please try again.","api_error",{code:f?.code??f?.gatewayErrorCode,declineCode:f?.declineCode??f?.gatewayDeclineReason,statusCode:_.status});throw Object.assign(me,{telemetryOutcome:dl(_.status,f)})}async function Po(e,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:o,sessionId:a,session:u,returnUrl:l,telemetry:w}){let B=t?.getRawProvider();if(!B)throw Mn(new Je("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!i||!e.threeDSecureToken)throw ia(new Je("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let P=ul(e.threeDSecureToken),R=null,S=e.paymentMethodId,x=await qr(()=>pl(B,e.threeDSecureToken,P),"card");if(x){if(x.error)throw Mn(new Je(x.error.message??`Failed to retrieve 3DS ${P?"setup":"payment"} status.`,"api_error",{code:x.error.code}),"card");let b=x.intent;!S&&b?.payment_method&&(typeof b.payment_method=="string"?S=b.payment_method:"id"in b.payment_method&&(S=b.payment_method.id??void 0))}let d=S?await qr(()=>ml(B,e.threeDSecureToken,{payment_method:S,return_url:l??aa(u)??window.location.href},P),"card"):null;if(d){if(d.error)throw Mn(new Je(d.error.message??"3DS authentication failed.","api_error",{code:d.error.code}),"card");R=d.intent}else{let b=await qr(()=>B.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(b.error)throw Mn(new Je(b.error.message??"3DS authentication failed.","api_error",{code:b.error.code}),"card");R=(P?b.setupIntent:b.paymentIntent)??null}if(R&&(R.status==="requires_capture"||R.status==="succeeded"||R.status==="processing")){let b=await Pr({billingApiUrl:o,sessionId:a,session:u,telemetry:w,tokenizedData:{id:R.id,type:"card",threeDSecureActionResultTokenId:R.id},returnUrl:l});return b.type==="success"?{...b.result,paymentIntentId:b.result.paymentIntentId??R.id,paymentMethodId:b.result.paymentMethodId??S}:Po(b,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:o,sessionId:a,session:u,returnUrl:l,telemetry:w})}throw Mn(new Je("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let P=(n??t)?.getRawProvider();if(!P)throw Mn(new Je("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:S}=await qr(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(S)throw Mn(new Je(S.message??"PayPal authorization failed.","api_error",{code:S.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:R}=await qr(()=>P.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??aa(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(R)throw Mn(new Je(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Je("Unsupported payment redirect state.","api_error")}function nr(e){if(e instanceof Je){let i=zn(e.message);return i&&i!==e.message?Object.assign(new Je(i,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=zn(t)??t;return new Je(n,"api_error")}function bo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Je("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function vo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:i,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[u,l]=await Promise.all([_i(e,{billingApiUrl:n,locale:i,telemetry:o}),a?_i(t,{billingApiUrl:n,locale:i,telemetry:o}).catch(w=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",w),null)):Promise.resolve(null)]);return{flopay:u,paypalFlopay:t?a?l:u:null}}import{Fragment as Rn,jsx as oe,jsxs as It}from"react/jsx-runtime";var br=44,ya="flopay_checkout_saved_payment_resume",ko=new Map,So=new Map;function Li(e,t){t.settled&&t.consumers===0&&ko.get(e)===t&&ko.delete(e)}function wl(e,t,n){let i=So.get(e);if(i&&(!i.sdkGeneratedIdempotencyKey||!t||i.sdkGeneratedIdempotencyKey===t))return i.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};So.set(e,a);let u=()=>{So.get(e)===a&&So.delete(e)};return o.then(u,u),o}function Vr(e){return new Promise(t=>setTimeout(t,e))}function wo(e,t,n){let i=oo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ui,enabled:t!==!1});return i.beginCheckout(n),i}function Kr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function la(e,t,n,i,o){let a=wo(e,t,n);a.error({errorCode:i,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Kr(a)}function kl(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 pa(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:!!pa(e)?.clientId}function An(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Rl(){if(!An())return null;try{let e=window.sessionStorage.getItem(ya);return e?JSON.parse(e):null}catch{return null}}function Ni(e){if(An())try{window.sessionStorage.setItem(ya,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function da(){if(An())try{window.sessionStorage.removeItem(ya)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var fa=":idempotency-key";function Il(e){if(!An())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function Oi(e,t,n){if(An())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(i){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",i)}}function ma(e){if(An())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function El(e){if(An())try{return window.sessionStorage.getItem(e+fa)??void 0}catch{return}}function _l(e,t){if(An())try{window.sessionStorage.setItem(e+fa,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function xl(e){if(ma(e),!!An())try{window.sessionStorage.removeItem(e+fa)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Tl(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let i of t)e.searchParams.has(i)&&(e.searchParams.delete(i),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function zi(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 Ml(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 ua(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function ga({sessionId:e,nonce:t,createSession:n,billingApiUrl:i,telemetry:o,appearance:a,locale:u,loading:l,error:w,onComplete:B,onError:P,onDecline:R,onCountryChange:S,onZipChange:x,showPayPal:d=!0,showStripe:b=!0,enabledPaymentMethods:I,showApplePay:_=!0,showGooglePay:f=!0,debug:me=!1,layout:F,theme:se,buttonsTheme:ee,buttonsStyles:D,cardButtonContent:J,cardBackButtonContent:W,cardTitleContent:le,showSecurityFooter:q,onButtonClick:K,onBeforeButtonClick:ce,enableAVS:_e,cardFieldOrder:Pe,cardPreFormSlot:ye,avsLayout:te,className:ge,initialErrorMessage:xe=null,children:ne,checkoutMode:ke,confirmLabel:Re,renderConfirmButton:Ce,onSessionCompleted:Y}){let E=vl(i),ae=fn(()=>$i(se),[se]),Ne=a??ae?.appearance,Oe=n?"embedded_checkout":"standard_checkout",de=ne?"custom_layout":F==="buttons"?"buttons_layout":"default_layout",[k,Q]=vt(null),[Z,ze]=vt(null),ut=jt(null),[je,ot]=vt(null),z=jt(null),[V,et]=vt(null),[Te,at]=vt(e??""),We=e??Te,Ve=n?"":We,[ln,g]=vt(!0),[be,pt]=vt(null),[tt,Xe]=vt("full"),[Ke,Qe]=vt(!1),[Ie,qe]=vt(xe),[Et,Ye]=vt(null),[Fn,Ct]=vt(null),[Dn,cn]=vt(void 0),[gn,tn]=vt(""),[Ln,Ut]=vt(!1),[_t,Vt]=vt(!1),Xt=jt(0),[Dt,Kt]=vt("loading"),[Lt,re]=vt(0),nn=jt(!1),T=jt(!1),ht=jt(!1),mt=jt(null),St=fn(()=>({checkoutMode:ke??tt,layout:ne?"unknown":F==="buttons"?"buttons":"embedded"}),[ke,ne,tt,F]),Ee=jt(B);Ee.current=B;let Ue=jt(P);Ue.current=P;let Kn=jt(R);Kn.current=R,Bn(()=>{Ft(Z)?.setCheckoutContext(St),je&&je!==Z&&Ft(je)?.setCheckoutContext(St)},[Z,je,St]);let Nn=jt(Y);Nn.current=Y;let Hn=rr(h=>{Kt(h),!(h!=="exhausted"||ht.current)&&(ht.current=!0,Ue.current?.(new bt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),or=rr(()=>{Kt("retrying"),re(h=>h+1)},[]);Bn(()=>{Kt("loading"),re(0),ht.current=!1},[We]),Bn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ui,checkout_type:Oe,checkout_layout:de,billing_api_url:E})},[de,Oe,E]);let Ht=fn(()=>n?hn(n,!0):"",[n]),it=fn(()=>gn===Ht?Dn:void 0,[Dn,gn,Ht]),Nt=fn(()=>n?Vo(n,it):void 0,[n,it]),Wt=ke??Nt?.checkoutMode??"full",Pt=fn(()=>Nt?{...Nt,checkoutMode:Wt}:void 0,[Nt,Wt]);Bn(()=>{cn(void 0),tn(Ht)},[Ht]),Bn(()=>{qe(xe)},[xe]);let Qt=rr((h,j,U)=>{ct(()=>{Kn.current?.(Rt(h,j,U))})},[ct]),Yt=rr(async(h,j)=>{qe(null),Ct(null),Ye("processing");let U=j?.sessionId??h.id,ue=ut.current??z.current,H=Ft(ue),ie=ue?null:wo(E,o,St),C={log:A=>{H?H.log(A):ie?.log(A)},error:A=>{H?H.error(A):ie?.error(A)},terminal:A=>{H?H.terminal(A):ie?.terminal(A)},performance:A=>{H?H.performance(A):ie?.performance(A)},now:()=>H?.now()??ie?.now()??0,elapsed:A=>H?.elapsed(A)??Math.max(0,(ie?.now()??A)-A)},c=C.now(),s=!!(j?.initialAutoProcessingError||j?.initialAutoProcessingPending),M=!1,y,G=()=>{M||(M=!0,s=!0,y=C.now(),C.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),C.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Se=!1,nt=()=>{Se||(Se=!0,C.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),C.performance({stage:"processing",durationMs:C.elapsed(c),durationMode:"machine",paymentMethodCategory:"saved"}),y!==void 0&&C.performance({stage:"recovery",durationMs:C.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}))};C.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),C.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),s&&G();let he;try{let A=Ti(j?.initialAutoProcessingError),m;if(A)G(),A.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Ni({sessionId:U,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey}),m=await Po(A,{flopay:ut.current,paypalFlopay:z.current,attempt3DS:j?.attempt3DS,billingApiUrl:E,sessionId:U,session:h,telemetry:!1}),A.type==="paypal_redirect_required"&&da();else if(j?.initialAutoProcessingPending){let N=await new Co(E,{telemetry:!1}).waitForCheckoutSessionCompletion(j.initialAutoProcessingPending.sessionId,{initialDelayMs:j.initialAutoProcessingPending.retryAfterMs});if(N.data.session?.status!=="complete")throw new bt("Automatic payment failed. Please try again.","api_error",{code:N.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});m={status:"succeeded"}}else{if(j?.initialAutoProcessingError)throw qn(j.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:j.initialAutoProcessingError.checkoutMethod});if(j?.fromCreateSession)return j?.fallbackToFull&&(Xe("full"),zi("full")),!1;{let L=await Pr({billingApiUrl:E,sessionId:U,session:h,telemetry:!1});L.type==="success"?m=L.result:(G(),L.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Ni({sessionId:U,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey}),m=await Po(L,{flopay:ut.current,paypalFlopay:z.current,attempt3DS:j?.attempt3DS,billingApiUrl:E,sessionId:U,session:h,telemetry:!1}),L.type==="paypal_redirect_required"&&da())}}U&&mr(U),nt(),s&&(C.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),C.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),C.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Ye("success"),await Vr(xn),he=()=>Ee.current?.(m)}catch(A){let m=nr(A),L=m.checkoutMethod??jr;qe(m.message),Ct(m.message),j?.fallbackToFull&&(C.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Xe("full"),zi("full")),nt();let N=m.statusCode!==void 0?Sl(m.statusCode,"unknown"):void 0,$e=N==="4xx"?{requestCategory:"process_payment",statusClass:N}:{},yt=N===void 0||N==="4xx";if(yt&&(m.telemetryOutcome==="payment_declined"||!!(m.declineCode||m.code?.toLowerCase().includes("declin"))))C.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...$e});else if(yt&&(m.telemetryOutcome==="validation_rejected"||m.type==="validation_error"))C.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...$e});else{let Wr=Ai(A,s?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");C.error({...Wr,...m.telemetryFailureCategory?{failureCategory:m.telemetryFailureCategory}:{},stage:s?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:m.telemetryRequestCategory??"process_payment"})}return ct(()=>Ue.current?.(m)),Qt(L,m,{code:m.code,declineCode:m.declineCode}),Ye("error"),await Promise.allSettled([Vr(Cn),j?.ensureProvidersReady?j.ensureProvidersReady():Promise.resolve()]),s&&(C.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),C.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{nt(),ie&&Kr(ie),Ye(null),Ct(null)}return ct(he),!0},[Qt,ct,nr,E,o,St]);Bn(()=>{if(typeof window>"u"||T.current)return;let h=new URLSearchParams(window.location.search),j=h.get("payment_intent_client_secret");if(!j)return;let U=Rl();U&&(T.current=!0,(async()=>{let ue,H=0;qe(null),Ct(null),Ye("processing"),Qe(!0);try{if(h.get("redirect_status")==="failed")throw Object.assign(new bt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ie,paypalFlopay:C}=await vo({publishableKey:U.publishableKey,paypalPublishableKey:U.paypalPublishableKey,billingApiUrl:E,locale:u,telemetry:o});ue=Ft(C??ie),H=ue?.now()??0,ue?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ue?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let c=(C??ie)?.getRawProvider();if(!c)throw Object.assign(new bt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:s,error:M}=await c.retrievePaymentIntent(j);if(M)throw Object.assign(new bt(M.message??"Failed to retrieve PayPal payment status.","api_error",{code:M.code}),{checkoutMethod:"paypal"});let y=ti(s?.status);if(!s||y==="failed")throw Object.assign(new bt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let G=typeof s.payment_method=="string"?s.payment_method:s.payment_method?.id,Se=y;if(U.sessionId){let A=(await new Co(E,{telemetry:!1}).getUnifiedCheckoutSession(U.sessionId)).data.session;if(A&&A.status!=="complete"){let m=await Pr({billingApiUrl:E,sessionId:U.sessionId,session:A,telemetry:!1,tokenizedData:{id:G??s.id,type:"card",threeDSecureActionResultTokenId:s.id,isPaypal:!0}});if(m.type!=="success")throw Object.assign(new bt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Se=m.result.status}}U.sessionId&&mr(U.sessionId),ue?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ue?.performance({stage:"redirect_resume",durationMs:ue.elapsed(H),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ue?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ye("success"),await Vr(xn),ct(()=>Ee.current?.({status:Se,paymentIntentId:s.id,paymentMethodId:G,checkoutMethod:"paypal"}))}catch(ie){let C=nr(ie),c=C.checkoutMethod??"paypal",s=!!(C.declineCode||C.code?.toLowerCase().includes("declin"));if(ue)ue.performance({stage:"redirect_resume",durationMs:ue.elapsed(H),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),s?ue.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ue.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(s){let M=wo(E,o,St);M.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Kr(M)}else la(E,o,St,"REDIRECT_RESUME_FAILED","redirect_resume");qe(C.message),Ct(C.message),ct(()=>Ue.current?.(C)),Qt(c,C,{code:C.code,declineCode:C.declineCode}),Ye("error"),await Vr(Cn)}finally{da(),Tl(),Ye(null),Ct(null),Qe(!1)}})())},[Qt,ct,u,nr,E,o]);let dn=jt(null);function hn(h,j=!1){let U=h?.account?.email?.trim().toLowerCase()??"",ue={c:h?.clientId,cur:h?.currency??"",a:{e:U,u:U?"":h?.account?.userId??"",country:h?.account?.country??""},successUrl:h?.successUrl,cancelUrl:h?.cancelUrl,p:h?.products?.map(C=>ua(`${C.type??""}:${C.code??C.providerItemId??C.providerPlanId??""}`,C)).sort(),i:h?.items?.map(C=>ua(C.code??C.providerItemId??"",C)).sort(),s:h?.subscriptions?.map(C=>ua(C.code??C.providerPlanId??"",C)).sort(),couponCodes:h?.couponCodes?[...h.couponCodes].sort():void 0,...j?{tagsData:h?.tagsData,utmMetadata:h?.utmMetadata,tokenizedData:h?.tokenizedData,checkoutMode:h?.checkoutMode??"full"}:{}},H=JSON.stringify(ue),ie=0;for(let C=0;C<H.length;C++)ie=(ie<<5)-ie+H.charCodeAt(C)|0;return`flopay_session_${Math.abs(ie).toString(36)}`}let xt=fn(()=>Pt?hn(Pt):"",[Pt]),$t=jt(Pt);$t.current=Pt,Bn(()=>{at(e??"")},[e]),Bn(()=>{nn.current=!1,qe(xe),Ct(null),Ye(null)},[xt,xe,e]);async function Ae(h,j){let U=wo(E,o,St),ue=new Co(E,{telemetry:!1}),H=!1;try{let ie=h.idempotencyKey!==void 0?Di(h.idempotencyKey):void 0,C=ie??El(j),c,s=!1,M=Il(j);U.log({name:M?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let y=M?.sid??null,G=null,Se;if(y)try{if(G=await ue.getUnifiedCheckoutSession(y,M?.nonce),G.data.session?.status==="complete"){if(Ho(y))return{sid:y,result:G};xl(j),y=null,G=null,s=!0}}catch{U.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),ma(j),y=null}if(!y){!ie&&(s||!C)&&(C=Di(),c=C),C&&_l(j,C);let nt=U.now(),he=0;U.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let A={...h,idempotencyKey:C,avsCheck:!!_e,avsConfig:typeof _e=="object"?_e:void 0,checkoutType:"embedded_checkout",checkoutLayout:ne?"custom_layout":F==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(A,Pl,{configurable:!1,enumerable:!1,value:{onAttempt:N=>{he=Math.max(he,N)}}});let m=()=>{U.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),U.performance({stage:"session_create",durationMs:U.now()-nt,durationMode:"machine",requestCategory:"session_create",attempt:he,statusClass:"2xx"})},L=N=>{let $e=Ai(N,"CHECKOUT_SESSION_CREATE_FAILED","unknown");U.performance({stage:"session_create",durationMs:U.now()-nt,durationMode:"machine",requestCategory:"session_create",attempt:he,statusClass:$e.statusClass}),N instanceof bt&&N.type==="validation_error"?U.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):$e.statusClass==="4xx"?U.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):U.error({...$e,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if(bl(A)){let N=await ue.createDetachedSession(A);N.claimed.catch(()=>{}),G=N.shell,y=N.sessionId,Se=N.claimed.then($e=>{let yt=$e.data.session?.id??N.sessionId;return yt&&Oi(j,yt,$e.data.session?.clientSecret??N.nonce),m(),$e},$e=>{throw ma(j),L($e),$e}).finally(()=>Kr(U)),Se.catch(()=>{}),H=!0,U.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),U.performance({stage:"session_shell",durationMs:U.now()-nt,durationMode:"machine",requestCategory:"session_create",attempt:he,statusClass:"2xx",paymentMethodCategory:"card"})}else G=await ue.createAndFetchSession(A),m()}catch(N){throw L(N),N}y=G.data.session?.id??y??"",y&&!Se&&Oi(j,y,G.data.session?.clientSecret)}return{sid:y??"",result:G,sdkGeneratedIdempotencyKey:c,...Se?{claimed:Se}:{}}}finally{H||Kr(U)}}let wt=rr(async(h,j)=>{let U=$t.current;if(!U)throw new bt("createSession is required to bootstrap checkout.","validation_error");let ue=Vo(U,h),H=hn(ue),ie=ko.get(H);if(!ie){let s={promise:Ae(ue,H),consumers:0,settled:!1};ie=s,ko.set(H,s);let M=()=>{s.settled=!0,Li(H,s)};s.promise.then(M,M)}ie.consumers+=1;let C=!1,c=()=>{C||(C=!0,ie.consumers-=1,Li(H,ie))};j?.(c);try{let s=await ie.promise;dn.current=H,h&&(tn(Ht),cn(m=>Za(m,h)));let{sid:M,result:y,claimed:G}=s;if(Q(y),y.data.session&&et(y.data.session),M&&at(M),G){let m=Xt.current+=1;Vt(!0),G.then(L=>{Xt.current===m&&(Q(L),L.data.session&&et(L.data.session),Vt(!1))},L=>{Xt.current===m&&(Vt(!1),pt(L instanceof bt?L:new bt(L instanceof Error?L.message:"Failed to create session","api_error")))})}else Xt.current+=1,Vt(!1);let{publishableKey:Se,paypalPublishableKey:nt}=bo(y),{flopay:he,paypalFlopay:A}=await vo({publishableKey:Se,paypalPublishableKey:nt,billingApiUrl:E,locale:u,telemetry:o});return ut.current=he,ze(he),z.current=A,ot(A),g(!1),s}catch(s){throw dn.current===H&&(dn.current=null),s}finally{j||c()}},[u,E,o,St]),kt=jt(Yt);kt.current=Yt;let Pn=jt(wt);Pn.current=wt;let Wn=rr(async h=>{if(!Ml(h)||Ln)return{sessionId:Te,session:V};Ut(!0);try{let j=await wt(h);return{sessionId:j.sid,session:j.result.data.session??null}}finally{Ut(!1)}},[wt,Ln,Te,V]);Bn(()=>{let h=!1,j;if(pt(null),xt){let H=$t.current;return Xe(Wt),g(!1),dn.current===xt?()=>{h=!0}:(et(ei(H,ke)),(async()=>{let ie=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),C=Wt==="auto"&&!nn.current&&!ie;C&&(qe(null),Ct(null),Ye("processing"));try{let c=await Pn.current(void 0,G=>{j=G}),s=c.result.data.session??null;mt.current=bo(c.result);let M=ca(c.result),y=Ho(c.sid||s?.id);if(!h&&C&&s&&!M&&!y){nn.current=!0,await wl(xt,c.sdkGeneratedIdempotencyKey,()=>kt.current(s,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:c.result.autoProcessingError,initialAutoProcessingPending:c.result.autoProcessingPending,autoProcessingAttempted:c.result.autoProcessingAttempted,sessionId:c.sid||s.id}));return}!h&&C&&((M||y)&&(nn.current=!0),Ye(null),Ct(null))}catch(c){if(h)return;let s=c instanceof bt||typeof c=="object"&&c!==null&&"code"in c?c.code:void 0;if(C&&s==="session_auto_completed"){nn.current=!0,Ye("success"),await Vr(xn),h||(ct(()=>{Ee.current?.({status:"succeeded"})}),Ye(null),Ct(null));return}C&&(Ye(null),Ct(null));let M=c instanceof bt?c:new bt(c instanceof Error?c.message:"Failed to create session","api_error");pt(M)}finally{j?.(),j=void 0}})(),()=>{h=!0,j?.()})}g(!0);async function U(){let H=!1;try{let C=await new Co(E,{telemetry:!1}).getUnifiedCheckoutSession(We,t);if(h)return;Q(C);let c=C.data.session??null;if(et(c),!c)throw new bt("No session data returned","api_error");if(c.status==="complete"){g(!1),ct(()=>{Nn.current?.(c.successUrl??"")});return}if(c.status==="expired")throw new bt("Checkout session has expired.","api_error",{code:"checkout_session_expired"});H=!0;let s=ke??c.checkoutMode??"full";Xe(s);let M=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),y=ca(C);if(s==="auto"&&!nn.current&&!M&&!y){nn.current=!0;let G=ue(C);try{if(await kt.current(c,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>G,sessionId:We||c.id}),h)return;await G,h||g(!1);return}catch{if(h)return;await G,h||g(!1);return}}await ue(C),h||g(!1)}catch(ie){if(h)return;ie instanceof bt?!H&&!kl(ie)&&la(E,o,St,"NETWORK_REQUEST_FAILED","session_read"):la(E,o,St,"INTERNAL_SDK_ERROR","checkout_mount");let C=ie instanceof bt?ie:new bt(ie instanceof Error?ie.message:"Failed to initialize checkout","api_error");pt(C),g(!1)}}async function ue(H){let{publishableKey:ie,paypalPublishableKey:C}=bo(H);mt.current={publishableKey:ie,paypalPublishableKey:C};let{flopay:c,paypalFlopay:s}=await vo({publishableKey:ie,paypalPublishableKey:C,billingApiUrl:E,locale:u,telemetry:o});ut.current=c,ze(c),z.current=s,ot(s)}return U(),()=>{h=!0}},[ke,xt,Wt,Ve,ct,t]);let Gt=rr(async()=>{if(!(Ke||!V)){Qe(!0),qe(null);try{await Yt(V,{attempt3DS:!0,fallbackToFull:!0,sessionId:We||V.id})}finally{Qe(!1)}}},[We,Ke,Yt,V]),Zt=pa(k),Ot=ca(k),In=fn(()=>{if(!k||!V||!k.data.stripe?.publishableKey)return;let h={appearance:Ne,paymentMethodCreation:"manual",billingApiUrl:E};if(k.data.stripe?.clientSecret)h.clientSecret=k.data.stripe.clientSecret;else{let j=Fi(V).total;h.amount=Math.round(j*100)||V.amount,h.currency=V.currency?.toLowerCase()}return h},[k,V,Ne,E]),On=!!(n&&!ne&&F==="buttons"&&ce&&Wt==="full"),un=fn(()=>({session:V,loading:ln,error:be,checkoutMode:tt,inlineSessionDraft:Pt,applyInlineSessionPatch:On?Wn:void 0,inlineSessionPatchProcessing:Ln,claimPending:_t}),[V,ln,be,tt,Pt,On,Wn,Ln,_t]),en=!!n&&F==="buttons"&&!Ot&&(!Z||!In),Tt=Et?oe(Sn,{status:Et,errorMessage:Fn}):null;if(ln){if(l)return It(Rn,{children:[l,Tt]});if(F==="buttons"){let h=ae?.buttonsLayout?.cardButton?.borderRadius??ae?.appearance.variables?.borderRadius??8,j=U=>oe("div",{style:{height:U,borderRadius:h,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return It(Rn,{children:[It("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[d&&j(br),b&&(_||f)&&j(br),b&&j(br),oe("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Tt]})}return It(Rn,{children:[It("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[oe("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),oe("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Tt]})}return be?w?oe(yn.Provider,{value:un,children:w(be)}):oe(yn.Provider,{value:un,children:oe("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:be.message})}):en?It(Rn,{children:[oe(yn.Provider,{value:un,children:oe(Al,{onButtonClick:K,showPayPal:d,showStripe:b,showApplePay:_,showGooglePay:f,theme:se,buttonsTheme:ee,buttonsStyles:D,cardButtonContent:J,cardBackButtonContent:W,cardTitleContent:le})}),Tt]}):Ot&&V&&Zt?It(Rn,{children:[oe(yn.Provider,{value:un,children:It("div",{className:ge,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ie&&oe(ur,{icon:!1,children:Ie}),Dt==="retrying"&&oe("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Dt==="exhausted"&&It("div",{role:"alert",children:[oe("div",{children:"PayPal is temporarily unavailable. Please try again."}),oe("button",{type:"button",onClick:or,children:"Retry PayPal"})]}),Dt!=="exhausted"&&oe("div",{"aria-hidden":Dt==="retrying"?!0:void 0,style:Dt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:oe(li,{sessionId:We,nonce:V.clientSecret||void 0,billingApiUrl:E,email:V.customer?.email,clientId:Zt.clientId,environment:Zt.environment,currency:(V.currency??"usd").toUpperCase(),isSubscription:V.mode==="subscription",onComplete:B,onErrorChange:qe,onDecline:R,onButtonClick:K,onInitializationStateChange:Hn,allowAutomaticRetry:Lt===0,session:V,telemetry:o,telemetryContext:St,debug:me},`paypal-init-${Lt}`)})]})}),Tt]}):!Z||!In?oe(Rn,{children:Tt}):tt==="confirm"?It(Rn,{children:[oe(yn.Provider,{value:un,children:oe(ao,{flopay:Z,paypalFlopay:je,options:In,children:It("div",{className:ge,children:[Ie&&oe("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ie}),Ce?Ce({onConfirm:Gt,isProcessing:Ke}):oe("button",{type:"button",onClick:Gt,disabled:Ke,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Ke?"not-allowed":"pointer",opacity:Ke?.6:1},children:Ke?"Processing...":Re??"Confirm Purchase"})]})})}),Tt]}):It(Rn,{children:[oe(yn.Provider,{value:un,children:oe(ao,{flopay:Z,paypalFlopay:je,options:In,children:ne?It(Rn,{children:[Ie&&oe("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ie}),oe(Bl,{sessionId:We,nonce:V?.clientSecret||void 0,billingApiUrl:E,session:V,children:ne})]}):oe(oa,{sessionId:We,nonce:V?.clientSecret||void 0,email:V?.customer?.email,userId:V?.customer?.id,firstName:V?.customer?.firstName,lastName:V?.customer?.lastName,totalAmount:V?Math.round(Fi(V).total*100):0,currency:V?.currency?.toLowerCase()??"usd",onComplete:B,onError:P,onDecline:R,error:Ie,onErrorChange:qe,showPayPal:d,showStripe:b,enabledPaymentMethods:I??k?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:k?.data.stripe?.enabledPaymentMethodCountries,showApplePay:_,showGooglePay:f,layout:F,theme:se,buttonsTheme:ee,buttonsStyles:D,appearance:Ne,cardButtonContent:J,cardBackButtonContent:W,cardTitleContent:le,onButtonClick:K,onBeforeButtonClick:ce,enableAVS:_e,...Pe?{cardFieldOrder:Pe}:{},...ye?{cardPreFormSlot:ye}:{},avsLayout:te,country:V?.customer?.country,city:V?.customer?.city,state:V?.customer?.state,onCountryChange:S,onZipChange:x,avsCheck:!!_e,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ne?"custom_layout":F==="buttons"?"buttons_layout":"default_layout",className:ge,directPaypal:pa(k),isSubscription:V?.mode==="subscription",session:V,dataAttachmentPending:_t,debug:me})})}),Tt]})}function Bl({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:o}){return oe(Rn,{children:sa.Children.map(o,a=>{if(!sa.isValidElement(a))return a;let u=a.props,l={};return u.sessionId||(l.sessionId=e),!u.nonce&&t&&(l.nonce=t),u.billingApiUrl||(l.billingApiUrl=n),i?.customer&&(u.email||(l.email=i.customer.email),u.userId||(l.userId=i.customer.id),u.firstName||(l.firstName=i.customer.firstName),u.lastName||(l.lastName=i.customer.lastName)),Object.keys(l).length===0?a:sa.cloneElement(a,l)})})}function Al({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:i,showGooglePay:o,theme:a,buttonsTheme:u,buttonsStyles:l,cardButtonContent:w,cardBackButtonContent:B,cardTitleContent:P}){let[R,S]=vt(!1),x=fn(()=>$i(a),[a]),d=fn(()=>{let f=x?.buttonsLayout??Cl(u);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},[x,u,l]),b=x?.buttonsLayout?.cardButton?.borderRadius??x?.appearance.variables?.borderRadius??8,I=f=>oe("div",{style:{height:f,borderRadius:b,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),_=w===void 0?{boxSizing:"border-box",height:br,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(R){let f=d.cardInputBorder??"#e5e7eb",me=d.cardInputBackground??"white",F=sr(B),se=sr(P);return It("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:[It("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[It("button",{type:"button",onClick:()=>S(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:F?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:[oe("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...d.backButtonIcon},children:oe("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:oe("path",{d:"M15 18l-6-6 6-6"})})}),oe(cr,{content:B})]}),se?oe("div",{style:{flex:1}}):oe("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...d.title},children:oe(Lr,{content:P})})]}),oe("div",{style:{backgroundColor:me,border:`1px solid ${f}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:oe("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),It("div",{style:{display:"flex"},children:[oe("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomLeftRadius:8,padding:12,height:45},children:oe("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),oe("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:`1px solid ${f}`,borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomRightRadius:8,padding:12,height:45},children:oe("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),oe("div",{style:{backgroundColor:me,border:`1px solid ${f}`,borderRadius:8,marginTop:8,padding:12,height:45},children:oe("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),oe("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...d.submitButton,opacity:.5}}),oe("style",{children:`
38
+ `}),Lr&&Yn&&Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ke?-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:y.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...y.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",...y.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:A})]}),Xa?u("div",{style:{flex:1}}):u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...y.title},children:u($r,{content:Q})})]}),!Lr&&!Xa&&u("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ho,order:Ke?-3:0,...y.title},children:u($r,{content:Q})}),ee&&u("div",{style:{order:Ke?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=Ye,b=($=!1)=>({backgroundColor:Or,border:`1px solid ${Gn($)}`,borderRadius:bt,marginTop:"0.5rem",padding:"10px"}),K=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ti}),Z=nl(a);return Le(br,{children:[De(ee.address_line_1,a)&&u("div",{style:b(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:je,onChange:$=>{wt.current.addressLine1=!0,Zt.current=$.target.value,nt($.target.value)},disabled:J,required:!0,"data-testid":"flopay-address-line1",style:K()})}),De(ee.address_line_2,a)&&u("div",{style:b(),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:$=>{wt.current.addressLine2=!0,en.current=$.target.value,Rn($.target.value)},disabled:J,"data-testid":"flopay-address-line2",style:K()})}),(De(ee.city,a)||De(ee.state,a))&&Le("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[De(ee.city,a)&&u("div",{style:{flex:1,backgroundColor:Or,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(ee.state,a)?{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:$=>{wt.current.city=!0,Ft.current=$.target.value,Kn($.target.value)},disabled:J,required:!0,"data-testid":"flopay-city",style:K()})}),De(ee.state,a)&&u("div",{style:{flex:1,backgroundColor:Or,border:`1px solid ${Gn(Pt.state)}`,padding:"10px",borderTopRightRadius:bt,borderBottomRightRadius:bt,...De(ee.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:bt}},children:Z?Le("select",{id:"flopay-billing-state",name:"billing-state",value:Wt,onChange:$=>{wt.current.state=!0,Dt.current=$.target.value,yn($.target.value)},disabled:J,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...K(),cursor:"pointer"},children:[u("option",{value:"",children:wi(a)}),Z.map($=>u("option",{value:$.code,children:$.name},$.code))]}):u("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:wi(a),autoComplete:"billing address-level1",value:Wt,onChange:$=>{wt.current.state=!0,Dt.current=$.target.value,yn($.target.value)},disabled:J,required:!0,"data-testid":"flopay-state",style:K()})})]}),(De(ee.country,a)||De(ee.postal_code,a))&&Le("div",{style:{display:"flex",flexDirection:re==="column"?"column":"row",gap:re==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[De(ee.country,a)&&u("div",{style:{flex:re==="row"?1:void 0,backgroundColor:Or,borderTop:`1px solid ${zr}`,borderRight:`1px solid ${zr}`,borderBottom:`1px solid ${zr}`,borderLeft:`1px solid ${zr}`,padding:"10px",...re==="row"&&De(ee.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:bt,borderBottomLeftRadius:bt,borderRight:"none"}:{borderRadius:bt}},children:u("select",{id:"flopay-billing-country",name:"billing-country",value:Ye,onChange:$=>{wt.current.country=!0,kt.current=$.target.value,Ie($.target.value),$e?.($.target.value),Dt.current="",yn("")},disabled:J,autoComplete:"billing country","data-testid":"flopay-country",style:{...K(),cursor:"pointer"},children:rl.map($=>Le("option",{value:$.code,children:[$.flag," ",$.name]},$.code))})}),De(ee.postal_code,a)&&u("div",{style:{flex:re==="row"?1:void 0,backgroundColor:Or,border:`1px solid ${vs}`,padding:"10px",...re==="row"&&De(ee.country,a)?{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:la(Ye),autoComplete:"billing postal-code",value:St,onChange:$=>{wt.current.zip=!0,Bt.current=$.target.value,Ve($.target.value),ze?.($.target.value)},onBlur:()=>Yt(!0),disabled:J,required:zt.required,"aria-invalid":lo||void 0,"aria-describedby":lo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:K()})})]}),lo&&u("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:jo,...ti,fontSize:"0.75rem"},children:zt.empty?`${la(a)} is required`:wl(a)})]})})()}),Ke&&Te&&u("div",{style:{order:-2,width:"100%"},children:Te}),Ke&&Rs,f&&u(mr,{margin:"0.75rem 0",styleOverride:y.errorBanner,children:f})]}),co={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"},ri=a=>tt?!k||!Pn?u("pre",{"data-testid":a,style:co,children:"FloPay/DirectPayPal-debug - not enabled"}):u("pre",{"data-testid":a,style:co,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${k}`,` directPaypalConfigured=${Pn}`,` inAppBrowserDetected=${String(io)}`,` shouldRenderDirectPayPal=${Ar}`,` shouldRenderStripePayPal=${Br}`,` hasPaypalStripeInstance=${!!ke}`].join(`
39
+ `)}):null,oi=a=>tt?!E||!fe?u("pre",{"data-testid":a,style:co,children:"FloPay/Stripe-debug - not enabled"}):u("pre",{"data-testid":a,style:co,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${E}`,` currency=${Ee}`,` amountInCents=${xe}`,` enabledPaymentMethods: ${JSON.stringify(g??[])}`,` enabledPaymentMethodsProvided=${Tr}`,` hasEnabledMethods=${no}`,` expressMethods: ${JSON.stringify(ro)}`,` walletExpressMethods: ${JSON.stringify(oo)}`,` paymentElementMethods: ${JSON.stringify(Mr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(ao)}`,` hasStripeInstance=${!!fe}`,` shouldRenderWallets=${Fr}`,` shouldRenderPaymentElement=${Dr}`].join(`
40
+ `)}):null,ai=_e==="apm-expanding"||_e==="apm-form"||_e==="apm-collapsing",uo=_e==="apm-expanding"?`flopay-card-enter ${jt}ms cubic-bezier(0, 0, 0.2, 1) both`:_e==="apm-collapsing"?`flopay-card-exit ${jt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,po=gt?{...Oo,paymentMethodTypes:[gt]}:null;if(X==="buttons"){let a=_e==="buttons"||_e==="expanding"||_e==="apm-expanding",b=_e==="expanding"||_e==="card"||_e==="collapsing",K=U===void 0?{boxSizing:"border-box",height:ko,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Z=_e==="expanding"||_e==="apm-expanding"?`flopay-buttons-exit ${jt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:_e==="collapsing"||_e==="apm-collapsing"?`flopay-buttons-enter ${jt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,$=_e==="expanding"?`flopay-card-enter ${jt}ms cubic-bezier(0, 0, 0.2, 1) both`:_e==="collapsing"?`flopay-card-exit ${jt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Le("form",{onSubmit:$o,className:C,style:{position:"relative"},children:[u(sa,{}),rn&&u(Cn,{status:rn,errorMessage:f,authorized:D}),Le("div",{style:{display:"grid"},children:[Le("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!Z?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!Z?vl:{},...Z?{animation:Z,pointerEvents:"none"}:{}},children:[ri("flopay-direct-paypal-gate-debug"),oi("flopay-stripe-gate-debug"),Ar&&Je&&Le(br,{children:[be&&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(So,{sessionId:e,nonce:t,billingApiUrl:r,email:p.email,clientId:Je.clientId,environment:Je.environment,currency:Ee.toUpperCase(),isSubscription:yt,onTokenizedBody:on,onComplete:s,onErrorChange:me,onDecline:l,onTechnicalFailure:sr,onButtonClick:se,runBeforeButtonClick:un,isProcessing:J,onLoadStateChange:No,onInitializationStateChange:Uo,session:B??null,existingOrderId:be?.orderId,debug:tt},be?.orderId??"fresh")]}),Br&&u(rr,{stripe:ke,options:Aa,children:u(Bi,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,onTokenizedBody:on,onErrorChange:me,isProcessing:J,onButtonClick:se,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:un,onLoadStateChange:La,placeholderBorderRadius:Jn})}),Fr?u(rr,{stripe:fe,options:to,children:u(Fi,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,intentKind:Y>0?"payment":"setup",expressMethods:oo,onTokenizedBody:on,onErrorChange:me,onButtonClick:se,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:un,onLoadStateChange:Oa,placeholderBorderRadius:Jn})}):ja?u("div",{style:{height:ko,borderRadius:Jn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Dr&&u(Di,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,paymentElementMethods:ao,stripeInstance:fe,paymentElementBaseOptions:Oo,onTokenizedBody:on,onErrorChange:me,onButtonClick:se,onDecline:l,runBeforeButtonClick:un,onLoadStateChange:Ua,isProcessing:J,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:y.submitButton,onExpandApm:nn,expandedApmMethod:gt,themeId:z,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:Jn}}),Ke&&u("button",{type:"button",onClick:async()=>{J||!(await un("card")).proceed||(se?.("card"),On())},disabled:J,style:{width:"100%",...K,...y.cardButton,...ma({themeBundle:F,resolvedPrimaryColor:Xn,resolvedBorderRadius:bt,submitButtonStyle:y.submitButton,explicitPrimaryColor:Kt?.colorPrimary}),fontSize:y.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:J?"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:J?.6:1},onMouseEnter:ye=>{!J&&(F||Kt?.colorPrimary)&&(ye.currentTarget.style.backgroundColor=ws)},onMouseLeave:ye=>{(F||Kt?.colorPrimary)&&(ye.currentTarget.style.backgroundColor=Xn)},onMouseDown:ye=>{ye.currentTarget.style.transform="scale(0.985)"},onMouseUp:ye=>{ye.currentTarget.style.transform="scale(1)"},children:u(dr,{content:U})}),f&&_e==="buttons"&&u(mr,{margin:"0.25rem 0",styleOverride:y.errorBanner,children:f})]}),Ke&&b&&u("div",{style:{gridArea:"1 / 1",...$?{animation:$}:{},..._e==="collapsing"?{pointerEvents:"none"}:{}},children:ni}),E&&ai&&gt&&po&&fe&&u("div",{style:{gridArea:"1 / 1",...uo?{animation:uo}:{},..._e==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Vo,borderRadius:Yo,...Nr,padding:Wo},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:y.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...y.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",...y.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:A})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:Ho,paddingRight:80,...y.title},children:`Pay with ${vr(gt)}`})]}),u(rr,{stripe:fe,options:po,children:u(ca,{method:gt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,onTokenizedBody:on,onErrorChange:me,onDecline:l,onCancel:Gt,runBeforeButtonClick:un,onButtonClick:se,isProcessing:J,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:y.submitButton,errorText:f})},gt)]})})]})]})}return ai&&gt&&po&&fe&&E?Le("form",{onSubmit:$o,className:C,style:{position:"relative"},children:[u(sa,{}),rn&&u(Cn,{status:rn,errorMessage:f,authorized:D}),u("div",{style:{...uo?{animation:uo}:{},..._e==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Vo,borderRadius:Yo,...Nr,padding:Wo},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:y.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...y.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",...y.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:A})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:Ho,paddingRight:80,...y.title},children:`Pay with ${vr(gt)}`})]}),u(rr,{stripe:fe,options:po,children:u(ca,{method:gt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,onTokenizedBody:on,onErrorChange:me,onDecline:l,onCancel:Gt,runBeforeButtonClick:un,onButtonClick:se,isProcessing:J,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:y.submitButton,errorText:f})},gt)]})})]}):Le("form",{onSubmit:$o,className:C,style:{position:"relative"},children:[u(sa,{}),rn&&u(Cn,{status:rn,errorMessage:f,authorized:D}),Le("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ri("flopay-direct-paypal-gate-debug-default"),oi("flopay-stripe-gate-debug-default"),Ar&&Je&&Le(br,{children:[be&&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(So,{sessionId:e,nonce:t,billingApiUrl:r,email:p.email,clientId:Je.clientId,environment:Je.environment,currency:Ee.toUpperCase(),isSubscription:yt,onTokenizedBody:on,onComplete:s,onErrorChange:me,onDecline:l,onTechnicalFailure:sr,onButtonClick:se,runBeforeButtonClick:un,isProcessing:J,onLoadStateChange:No,onInitializationStateChange:Uo,session:B??null,existingOrderId:be?.orderId,debug:tt},be?.orderId??"fresh")]}),Br&&u(rr,{stripe:ke,options:Aa,children:u(Bi,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,onTokenizedBody:on,onErrorChange:me,isProcessing:J,onButtonClick:se,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:un,onLoadStateChange:La,placeholderBorderRadius:Jn})}),Fr&&u(rr,{stripe:fe,options:to,children:u(Fi,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,intentKind:Y>0?"payment":"setup",expressMethods:oo,onTokenizedBody:on,onErrorChange:me,onButtonClick:se,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:un,onLoadStateChange:Oa,placeholderBorderRadius:Jn})}),Dr&&u(Di,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,paymentElementMethods:ao,stripeInstance:fe,paymentElementBaseOptions:Oo,onTokenizedBody:on,onErrorChange:me,onButtonClick:se,onDecline:l,runBeforeButtonClick:un,onLoadStateChange:Ua,isProcessing:J,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:y.submitButton,themeId:z,onExpandApm:nn,expandedApmMethod:gt,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:Jn}})]}),Ke&&(gs||fs||hs)&&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"}})]}),Ke&&ni]})}import{loadFloPay as qi,PaymentAPI as Vi}from"@flopay/js";import{classifyPaymentRejection as _l,FloPayError as ot,isAuthorizationOnlySession as xl,isSetupIntentClientSecret as Tl,normalizeCheckoutFailureOutcome as ji}from"@flopay/shared";var Jr="card";async function Ml(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:d}=await e.retrieveSetupIntent(t);return{error:d,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:i,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:i??null}}async function Al(e,t,n,i){if(i){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:d,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:d??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:s}=await e.confirmCardPayment(t,n);return{error:s,intent:o??null}}function ga(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 Gr(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 Bl(e){return e.status==="succeeded"||e.status==="declined"}async function Hi(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,i=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,s=async()=>{let h=new AbortController,w=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",w);let C=window.setTimeout(()=>h.abort(),i);try{let R=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!R.ok)return{status:"unknown"};let c=await R.json().catch(()=>null);return Fl(c)}catch{return{status:"unknown"}}finally{window.clearTimeout(C),e.signal?.removeEventListener("abort",w)}},d=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 v=document.createElement("iframe");v.setAttribute("title","Card authentication"),v.setAttribute("allow","payment"),v.tabIndex=0,v.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),v.src=e.nextActionRedirectUrl,l.appendChild(v),document.body.appendChild(l),v.focus();let L=null;try{L=new URL(e.billingApiUrl,window.location.href).origin}catch{L=null}try{let h=await new Promise((w,C)=>{let R=!1,c=0,P=0,k=0,E=!1,g=()=>{window.clearTimeout(c),window.clearInterval(P),window.clearTimeout(k),window.removeEventListener("message",X),v.removeEventListener("load",I),e.signal?.removeEventListener("abort",ae)},ce=async()=>{if(!(R||E)){E=!0;try{let z=await s();if(R||!Bl(z))return;R=!0,g(),w(z)}finally{E=!1}}},I=()=>{window.clearTimeout(k),k=window.setTimeout(()=>{ce()},250)},ae=()=>{R||(R=!0,g(),C(new ot("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},X=z=>{if(z.source!==v.contentWindow||L&&z.origin!==L)return;let W=z.data;!W||typeof W!="object"||W.source!=="flopay-vault-3ds-return"||R||(R=!0,g(),w(null))};c=window.setTimeout(()=>{R||(R=!0,g(),C(new ot("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),P=window.setInterval(()=>{ce()},n),v.addEventListener("load",I),window.addEventListener("message",X),e.signal?.addEventListener("abort",ae),e.signal?.aborted&&ae()});return h||await s()}finally{l.parentNode?.removeChild(l),d?.isConnected&&d.focus()}}function Fl(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 jn(e,t="Payment failed. Please try again.",n){let i=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,s=Un(o)??o;return ga(new ot(s,"api_error",{code:ji(e?.outcome)??ji(e?.type)??e?.gatewayErrorCode}),i)}function fa(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Eo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Dl(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 Wi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Eo(o)))return o;let i=e?.data;if(i&&typeof i=="object"){let o=i,s=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let l of s)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||Eo(l)))return l;let d=o.gateways;if(d&&typeof d=="object"){let l=d.stripe;if(l&&typeof l=="object"){let v=l,L=[v.stripeClientSecret,v.clientSecret];for(let h of L)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||Eo(h)))return h}}}}async function Ll({billingApiUrl:e,sessionId:t,nonce:n,responseJson:i}){let o=Wi(i,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let l=(await new Vi(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Eo(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Cr({billingApiUrl:e,sessionId:t,session:n,nonce:i,tokenizedData:o,returnUrl:s,telemetry:d}){let l=e.replace(/\/+$/,""),v=t??n.id,L=i??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",w=n.customer?.email??n.accountData?.email??"",C=n.customer?.firstName??n.accountData?.firstName??"",R=n.customer?.lastName??n.accountData?.lastName??"",c=n.customer?.country??n.accountData?.country??void 0,P=n.customer?.zip??n.accountData?.zip??void 0,k=new Vi(l,d===!1?{telemetry:!1}:void 0),E=await Dl(()=>k.processPayment(h,{sessionId:v,nonce:L,tokenizedData:o,accountData:{userId:h,email:w,firstName:C,lastName:R,country:c,zip:P},returnUrl:s??fa(n)}));if(E.ok){let I=typeof E.json=="function"?await E.json().catch(()=>null):null;return xl(n)||I?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof I?.paymentId=="string"?I.paymentId:n.paymentId,sessionId:typeof I?.sessionId=="string"?I.sessionId:v,authorizationExpiresAt:typeof I?.authorizationExpiresAt=="string"?I.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Kr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Kr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let g;try{g=await E.json()}catch{throw new ot("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:E.status})}if(g?.type==="paypal_redirect_required"||g?.type==="3ds_required"){let I=Wi(g);if(!I)throw new ot("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:E.status});return{type:g.type,threeDSecureToken:I,paymentMethodId:g.paymentMethodId}}if(g?.gatewayErrorCode==="authentication_required"){let I=await Ll({billingApiUrl:l,sessionId:v,nonce:L,responseJson:g});if(I)return I;throw ga(new ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ce=new ot(g?.message??"Payment failed. Please try again.","api_error",{code:g?.code??g?.gatewayErrorCode,declineCode:g?.declineCode??g?.gatewayDeclineReason,statusCode:E.status});throw Object.assign(ce,{telemetryOutcome:_l(E.status,g)})}async function Io(e,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:o,sessionId:s,session:d,returnUrl:l,telemetry:v}){let L=t?.getRawProvider();if(!L)throw An(new ot("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!i||!e.threeDSecureToken)throw ga(new ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=Tl(e.threeDSecureToken),w=null,C=e.paymentMethodId,R=await Gr(()=>Ml(L,e.threeDSecureToken,h),"card");if(R){if(R.error)throw An(new ot(R.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:R.error.code}),"card");let P=R.intent;!C&&P?.payment_method&&(typeof P.payment_method=="string"?C=P.payment_method:"id"in P.payment_method&&(C=P.payment_method.id??void 0))}let c=C?await Gr(()=>Al(L,e.threeDSecureToken,{payment_method:C,return_url:l??fa(d)??window.location.href},h),"card"):null;if(c){if(c.error)throw An(new ot(c.error.message??"3DS authentication failed.","api_error",{code:c.error.code}),"card");w=c.intent}else{let P=await Gr(()=>L.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(P.error)throw An(new ot(P.error.message??"3DS authentication failed.","api_error",{code:P.error.code}),"card");w=(h?P.setupIntent:P.paymentIntent)??null}if(w&&(w.status==="requires_capture"||w.status==="succeeded"||w.status==="processing")){let P=await Cr({billingApiUrl:o,sessionId:s,session:d,telemetry:v,tokenizedData:{id:w.id,type:"card",threeDSecureActionResultTokenId:w.id},returnUrl:l});return P.type==="success"?{...P.result,paymentIntentId:P.result.paymentIntentId??w.id,paymentMethodId:P.result.paymentMethodId??C}:Io(P,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:o,sessionId:s,session:d,returnUrl:l,telemetry:v})}throw An(new ot("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw An(new ot("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:C}=await Gr(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(C)throw An(new ot(C.message??"PayPal authorization failed.","api_error",{code:C.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:w}=await Gr(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??fa(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(w)throw An(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 i=Un(e.message);return i&&i!==e.message?Object.assign(new ot(i,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Un(t)??t;return new ot(n,"api_error")}function _o(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 xo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:i,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let s=!!t&&t!==e,[d,l]=await Promise.all([qi(e,{billingApiUrl:n,locale:i,telemetry:o}),s?qi(t,{billingApiUrl:n,locale:i,telemetry:o}).catch(v=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",v),null)):Promise.resolve(null)]);return{flopay:d,paypalFlopay:t?s?l:d:null}}import{Fragment as kn,jsx as oe,jsxs as _t}from"react/jsx-runtime";var Sr=44,ka="flopay_checkout_saved_payment_resume",Bo=new Map,Mo=new Map;function Xi(e,t){t.settled&&t.consumers===0&&Bo.get(e)===t&&Bo.delete(e)}function ql(e,t,n){let i=Mo.get(e);if(i&&(!i.sdkGeneratedIdempotencyKey||!t||i.sdkGeneratedIdempotencyKey===t))return i.attempt;let o=n(),s={attempt:o,sdkGeneratedIdempotencyKey:t};Mo.set(e,s);let d=()=>{Mo.get(e)===s&&Mo.delete(e)};return o.then(d,d),o}function Xr(e){return new Promise(t=>setTimeout(t,e))}function Ao(e,t,n){let i=mo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:ts,enabled:t!==!1});return i.beginCheckout(n),i}function Qr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Pa(e,t,n,i,o){let s=Ao(e,t,n);s.error({errorCode:i,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Qr(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 Sa(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function ba(e){return!e||e.data.stripe?.publishableKey?!1:!!Sa(e)?.clientId}function Fn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Vl(){if(!Fn())return null;try{let e=window.sessionStorage.getItem(ka);return e?JSON.parse(e):null}catch{return null}}function Qi(e){if(Fn())try{window.sessionStorage.setItem(ka,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function va(){if(Fn())try{window.sessionStorage.removeItem(ka)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var Ra=":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 Zi(e,t,n){if(Fn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(i){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",i)}}function wa(e){if(Fn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function Hl(e){if(Fn())try{return window.sessionStorage.getItem(e+Ra)??void 0}catch{return}}function Wl(e,t){if(Fn())try{window.sessionStorage.setItem(e+Ra,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function Yl(e){if(wa(e),!!Fn())try{window.sessionStorage.removeItem(e+Ra)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Gl(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let i of t)e.searchParams.has(i)&&(e.searchParams.delete(i),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function es(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 Jl(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 Ca(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Ea({sessionId:e,nonce:t,createSession:n,billingApiUrl:i,telemetry:o,appearance:s,locale:d,loading:l,error:v,onComplete:L,onError:h,onDecline:w,onCountryChange:C,onZipChange:R,showPayPal:c=!0,showStripe:P=!0,enabledPaymentMethods:k,showApplePay:E=!0,showGooglePay:g=!0,debug:ce=!1,layout:I,theme:ae,buttonsTheme:X,buttonsStyles:z,cardButtonContent:W,cardBackButtonContent:q,cardTitleContent:te,showSecurityFooter:U,onButtonClick:A,onBeforeButtonClick:Q,enableAVS:de,cardFieldOrder:se,cardPreFormSlot:le,avsLayout:ne,className:he,initialErrorMessage:Te=null,children:re,checkoutMode:Ue,confirmLabel:Fe,renderConfirmButton:Re,onSessionCompleted:H}){let S=Nl(i),ie=mn(()=>ns(ae),[ae]),$e=s??ie?.appearance,ze=n?"embedded_checkout":"standard_checkout",pe=re?"custom_layout":I==="buttons"?"buttons_layout":"default_layout",[T,ue]=Ct(null),[Y,Ee]=Ct(null),ut=Nt(null),[Je,yt]=Ct(null),B=Nt(null),[G,tt]=Ct(null),[qe,ft]=Ct(e??""),Oe=e??qe,We=n?"":Oe,[Jt,Ge]=Ct(!0),[Xt,_]=Ct(null),[Pe,Ye]=Ct("full"),[Ie,St]=Ct(!1),[Ve,je]=Ct(Te),[nt,Xe]=Ct(null),[Rn,at]=Ct(null),[Kn,Wt]=Ct(!1),[yn,Qt]=Ct(void 0),[ir,Bt]=Ct(""),[kt,Zt]=Ct(!1),[en,Ft]=Ct(!1),Dt=Nt(0),[wt,ee]=Ct("loading"),[Hn,D]=Ct(0),it=Nt(!1),Lt=Nt(!1),Ln=Nt(!1),Me=Nt(null),st=mn(()=>({checkoutMode:Ue??Pe,layout:re?"unknown":I==="buttons"?"buttons":"embedded"}),[Ue,re,Pe,I]),Ke=Nt(L);Ke.current=L;let En=Nt(h);En.current=h;let In=Nt(w);In.current=w,Bn(()=>{At(Y)?.setCheckoutContext(st),Je&&Je!==Y&&At(Je)?.setCheckoutContext(st)},[Y,Je,st]);let zn=Nt(H);zn.current=H;let Wn=ar(x=>{ee(x),!(x!=="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(()=>{ee("retrying"),D(x=>x+1)},[]);Bn(()=>{ee("loading"),D(0),Ln.current=!1},[Oe]),Bn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:ts,checkout_type:ze,checkout_layout:pe,billing_api_url:S})},[pe,ze,S]);let rt=mn(()=>n?Ut(n,!0):"",[n]),zt=mn(()=>ir===rt?yn:void 0,[yn,ir,rt]),ln=mn(()=>n?Zo(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(()=>{je(Te)},[Te]);let tn=ar((x,O,M)=>{He(()=>{In.current?.(Et(x,O,M))})},[He]),cn=ar(async(x,O)=>{je(null),at(null),Wt(!1),Xe("processing");let M=O?.sessionId??x.id,be=ut.current??B.current,ve=At(be),m=be?null:Ao(S,o,st),r={log:p=>{ve?ve.log(p):m?.log(p)},error:p=>{ve?ve.error(p):m?.error(p)},terminal:p=>{ve?ve.terminal(p):m?.terminal(p)},performance:p=>{ve?ve.performance(p):m?.performance(p)},now:()=>ve?.now()??m?.now()??0,elapsed:p=>ve?.elapsed(p)??Math.max(0,(m?.now()??p)-p)},f=r.now(),F=!!(O?.initialAutoProcessingError||O?.initialAutoProcessingPending),y=!1,j,Ae=()=>{y||(y=!0,F=!0,j=r.now(),r.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Qe=!1,J=()=>{Qe||(Qe=!0,r.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),r.performance({stage:"processing",durationMs:r.elapsed(f),durationMode:"machine",paymentMethodCategory:"saved"}),j!==void 0&&r.performance({stage:"recovery",durationMs:r.elapsed(j),durationMode:"machine",paymentMethodCategory:"saved"}))};r.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),r.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),F&&Ae();let V;try{let p=Ki(O?.initialAutoProcessingError),N;if(p)Ae(),p.type==="paypal_redirect_required"&&Me.current?.publishableKey&&Qi({sessionId:M,publishableKey:Me.current.publishableKey,paypalPublishableKey:Me.current.paypalPublishableKey}),N=await Io(p,{flopay:ut.current,paypalFlopay:B.current,attempt3DS:O?.attempt3DS,billingApiUrl:S,sessionId:M,session:x,telemetry:!1}),p.type==="paypal_redirect_required"&&va();else if(O?.initialAutoProcessingPending){let xe=(await new To(S,{telemetry:!1}).waitForCheckoutSessionCompletion(O.initialAutoProcessingPending.sessionId,{initialDelayMs:O.initialAutoProcessingPending.retryAfterMs})).data.session;if(!fr(xe))throw ho(xe);N=er(xe,M)}else{if(O?.initialAutoProcessingError)throw jn(O.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:O.initialAutoProcessingError.checkoutMethod});if(O?.fromCreateSession)return O?.fallbackToFull&&(Ye("full"),es("full")),!1;{let fe=await Cr({billingApiUrl:S,sessionId:M,session:x,telemetry:!1});fe.type==="success"?N=fe.result:(Ae(),fe.type==="paypal_redirect_required"&&Me.current?.publishableKey&&Qi({sessionId:M,publishableKey:Me.current.publishableKey,paypalPublishableKey:Me.current.paypalPublishableKey}),N=await Io(fe,{flopay:ut.current,paypalFlopay:B.current,attempt3DS:O?.attempt3DS,billingApiUrl:S,sessionId:M,session:x,telemetry:!1}),fe.type==="paypal_redirect_required"&&va())}}M&&gr(M),J(),F&&(r.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),r.terminal({outcome:N.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Wt(N.status==="authorized"),Xe("success"),await Xr(Tn),V=()=>Ke.current?.(N)}catch(p){let N=or(p),fe=N.checkoutMethod??Jr;je(N.message),at(N.message),Wt(!1),O?.fallbackToFull&&(r.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Ye("full"),es("full")),J();let ke=N.statusCode!==void 0?$l(N.statusCode,"unknown"):void 0,xe=ke==="4xx"?{requestCategory:"process_payment",statusClass:ke}:{},gn=ke===void 0||ke==="4xx";if(gn&&(N.telemetryOutcome==="payment_declined"||!!(N.declineCode||N.code?.toLowerCase().includes("declin"))))r.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...xe});else if(gn&&(N.telemetryOutcome==="validation_rejected"||N.type==="validation_error"))r.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...xe});else{let to=Yi(p,F?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");r.error({...to,...N.telemetryFailureCategory?{failureCategory:N.telemetryFailureCategory}:{},stage:F?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:N.telemetryRequestCategory??"process_payment"})}return He(()=>En.current?.(N)),tn(fe,N,{code:N.code,declineCode:N.declineCode}),Xe("error"),await Promise.allSettled([Xr(vn),O?.ensureProvidersReady?O.ensureProvidersReady():Promise.resolve()]),F&&(r.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{J(),m&&Qr(m),Xe(null),at(null)}return He(V),!0},[tn,He,or,S,o,st]);Bn(()=>{if(typeof window>"u"||Lt.current)return;let x=new URLSearchParams(window.location.search),O=x.get("payment_intent_client_secret");if(!O)return;let M=Vl();M&&(Lt.current=!0,(async()=>{let be,ve=0;je(null),at(null),Xe("processing"),St(!0);try{if(x.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:r}=await xo({publishableKey:M.publishableKey,paypalPublishableKey:M.paypalPublishableKey,billingApiUrl:S,locale:d,telemetry:o});be=At(r??m),ve=be?.now()??0,be?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),be?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let f=(r??m)?.getRawProvider();if(!f)throw Object.assign(new It("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:F,error:y}=await f.retrievePaymentIntent(O);if(y)throw Object.assign(new It(y.message??"Failed to retrieve PayPal payment status.","api_error",{code:y.code}),{checkoutMethod:"paypal"});let j=fi(F?.status);if(!F||j==="failed")throw Object.assign(new It("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Ae=typeof F.payment_method=="string"?F.payment_method:F.payment_method?.id,Qe=j;if(M.sessionId){let p=(await new To(S,{telemetry:!1}).getUnifiedCheckoutSession(M.sessionId)).data.session;if(p&&p.status!=="complete"){let N=await Cr({billingApiUrl:S,sessionId:M.sessionId,session:p,telemetry:!1,tokenizedData:{id:Ae??F.id,type:"card",threeDSecureActionResultTokenId:F.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&&gr(M.sessionId),be?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),be?.performance({stage:"redirect_resume",durationMs:be.elapsed(ve),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),be?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Xe("success"),await Xr(Tn),He(()=>Ke.current?.({status:Qe,paymentIntentId:F.id,paymentMethodId:Ae,checkoutMethod:"paypal"}))}catch(m){let r=or(m),f=r.checkoutMethod??"paypal",F=!!(r.declineCode||r.code?.toLowerCase().includes("declin"));if(be)be.performance({stage:"redirect_resume",durationMs:be.elapsed(ve),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),F?be.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):be.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(F){let y=Ao(S,o,st);y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Qr(y)}else Pa(S,o,st,"REDIRECT_RESUME_FAILED","redirect_resume");je(r.message),at(r.message),He(()=>En.current?.(r)),tn(f,r,{code:r.code,declineCode:r.declineCode}),Xe("error"),await Xr(vn)}finally{va(),Gl(),Xe(null),at(null),St(!1)}})())},[tn,He,d,or,S,o]);let Yt=Nt(null);function Ut(x,O=!1){let M=x?.account?.email?.trim().toLowerCase()??"",be={c:x?.clientId,cur:x?.currency??"",captureMethod:x?.captureMethod??"",a:{e:M,u:M?"":x?.account?.userId??"",country:x?.account?.country??""},successUrl:x?.successUrl,cancelUrl:x?.cancelUrl,p:x?.products?.map(r=>Ca(`${r.type??""}:${r.code??r.providerItemId??r.providerPlanId??""}`,r)).sort(),i:x?.items?.map(r=>Ca(r.code??r.providerItemId??"",r)).sort(),s:x?.subscriptions?.map(r=>Ca(r.code??r.providerPlanId??"",r)).sort(),couponCodes:x?.couponCodes?[...x.couponCodes].sort():void 0,...O?{tagsData:x?.tagsData,utmMetadata:x?.utmMetadata,tokenizedData:x?.tokenizedData,checkoutMode:x?.checkoutMode??"full"}:{}},ve=JSON.stringify(be),m=0;for(let r=0;r<ve.length;r++)m=(m<<5)-m+ve.charCodeAt(r)|0;return`flopay_session_${Math.abs(m).toString(36)}`}let $t=mn(()=>xt?Ut(xt):"",[xt]),_e=Nt(xt);_e.current=xt,Bn(()=>{ft(e??"")},[e]),Bn(()=>{it.current=!1,je(Te),at(null),Wt(!1),Xe(null)},[$t,Te,e]);async function qt(x,O){let M=Ao(S,o,st),be=new To(S,{telemetry:!1}),ve=!1;try{let m=x.idempotencyKey!==void 0?Ji(x.idempotencyKey):void 0,r=m??Hl(O),f,F=!1,y=Kl(O);M.log({name:y?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let j=y?.sid??null,Ae=null,Qe;if(j)try{if(Ae=await be.getUnifiedCheckoutSession(j,y?.nonce),Ae.data.session?.status==="complete"){if(ta(j))return{sid:j,result:Ae};Yl(O),j=null,Ae=null,F=!0}}catch{M.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),wa(O),j=null}if(!j){!m&&(F||!r)&&(r=Ji(),f=r),r&&Wl(O,r);let J=M.now(),V=0;M.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let p={...x,idempotencyKey:r,avsCheck:!!de,avsConfig:typeof de=="object"?de:void 0,checkoutType:"embedded_checkout",checkoutLayout:re?"custom_layout":I==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(p,zl,{configurable:!1,enumerable:!1,value:{onAttempt:ke=>{V=Math.max(V,ke)}}});let N=()=>{M.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),M.performance({stage:"session_create",durationMs:M.now()-J,durationMode:"machine",requestCategory:"session_create",attempt:V,statusClass:"2xx"})},fe=ke=>{let xe=Yi(ke,"CHECKOUT_SESSION_CREATE_FAILED","unknown");M.performance({stage:"session_create",durationMs:M.now()-J,durationMode:"machine",requestCategory:"session_create",attempt:V,statusClass:xe.statusClass}),ke instanceof It&&ke.type==="validation_error"?M.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):xe.statusClass==="4xx"?M.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):M.error({...xe,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if(Ol(p)){let ke=await be.createDetachedSession(p);ke.claimed.catch(()=>{}),Ae=ke.shell,j=ke.sessionId,Qe=ke.claimed.then(xe=>{let gn=xe.data.session?.id??ke.sessionId;return gn&&Zi(O,gn,xe.data.session?.clientSecret??ke.nonce),N(),xe},xe=>{throw wa(O),fe(xe),xe}).finally(()=>Qr(M)),Qe.catch(()=>{}),ve=!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()-J,durationMode:"machine",requestCategory:"session_create",attempt:V,statusClass:"2xx",paymentMethodCategory:"card"})}else Ae=await be.createAndFetchSession(p),N()}catch(ke){throw fe(ke),ke}j=Ae.data.session?.id??j??"",j&&!Qe&&Zi(O,j,Ae.data.session?.clientSecret)}return{sid:j??"",result:Ae,sdkGeneratedIdempotencyKey:f,...Qe?{claimed:Qe}:{}}}finally{ve||Qr(M)}}let gt=ar(async(x,O)=>{let M=_e.current;if(!M)throw new It("createSession is required to bootstrap checkout.","validation_error");let be=Zo(M,x),ve=Ut(be),m=Bo.get(ve);if(!m){let F={promise:qt(be,ve),consumers:0,settled:!1};m=F,Bo.set(ve,F);let y=()=>{F.settled=!0,Xi(ve,F)};F.promise.then(y,y)}m.consumers+=1;let r=!1,f=()=>{r||(r=!0,m.consumers-=1,Xi(ve,m))};O?.(f);try{let F=await m.promise;Yt.current=ve,x&&(Bt(rt),Qt(N=>pi(N,x)));let{sid:y,result:j,claimed:Ae}=F;if(ue(j),j.data.session&&tt(j.data.session),y&&ft(y),Ae){let N=Dt.current+=1;Ft(!0),Ae.then(fe=>{Dt.current===N&&(ue(fe),fe.data.session&&tt(fe.data.session),Ft(!1))},fe=>{Dt.current===N&&(Ft(!1),_(fe instanceof It?fe:new It(fe instanceof Error?fe.message:"Failed to create session","api_error")))})}else Dt.current+=1,Ft(!1);let{publishableKey:Qe,paypalPublishableKey:J}=_o(j),{flopay:V,paypalFlopay:p}=await xo({publishableKey:Qe,paypalPublishableKey:J,billingApiUrl:S,locale:d,telemetry:o});return ut.current=V,Ee(V),B.current=p,yt(p),Ge(!1),F}catch(F){throw Yt.current===ve&&(Yt.current=null),F}finally{O||f()}},[d,S,o,st]),fn=Nt(cn);fn.current=cn;let Yn=Nt(gt);Yn.current=gt;let jt=ar(async x=>{if(!Jl(x)||kt)return{sessionId:qe,session:G};Zt(!0);try{let O=await gt(x);return{sessionId:O.sid,session:O.result.data.session??null}}finally{Zt(!1)}},[gt,kt,qe,G]);Bn(()=>{let x=!1,O;if(_(null),$t){let ve=_e.current;return Ye(Pt),Ge(!1),Yt.current===$t?()=>{x=!0}:(tt(mi(ve,Ue)),(async()=>{let m=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),r=Pt==="auto"&&!it.current&&!m;r&&(je(null),at(null),Xe("processing"));try{let f=await Yn.current(void 0,Ae=>{O=Ae}),F=f.result.data.session??null;Me.current=_o(f.result);let y=ba(f.result),j=ta(f.sid||F?.id);if(!x&&r&&F&&!y&&!j){it.current=!0,await ql($t,f.sdkGeneratedIdempotencyKey,()=>fn.current(F,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:f.result.autoProcessingError,initialAutoProcessingPending:f.result.autoProcessingPending,autoProcessingAttempted:f.result.autoProcessingAttempted,sessionId:f.sid||F.id}));return}!x&&r&&((y||j)&&(it.current=!0),Xe(null),at(null))}catch(f){if(x)return;let F=f instanceof It||typeof f=="object"&&f!==null&&"code"in f?f.code:void 0;if(r&&F==="session_auto_completed"){it.current=!0,Xe("success"),await Xr(Tn),x||(He(()=>{Ke.current?.({status:"succeeded"})}),Xe(null),at(null));return}r&&(Xe(null),at(null));let y=f instanceof It?f:new It(f instanceof Error?f.message:"Failed to create session","api_error");_(y)}finally{O?.(),O=void 0}})(),()=>{x=!0,O?.()})}Ge(!0);async function M(){let ve=!1;try{let r=await new To(S,{telemetry:!1}).getUnifiedCheckoutSession(Oe,t);if(x)return;ue(r);let f=r.data.session??null;if(tt(f),!f)throw new It("No session data returned","api_error");let F=f.checkoutMode;if(F==="setup")throw new It("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(f.status==="authorized"){Ge(!1),He(()=>{Ke.current?.(er(f,Oe)),zn.current?.(f.successUrl??"")});return}if(f.status==="complete"){Ge(!1),He(()=>{zn.current?.(f.successUrl??"")});return}if(f.status==="expired")throw go(f);ve=!0;let y=Ue??F??"full";Ye(y);let j=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ae=ba(r);if(y==="auto"&&!it.current&&!j&&!Ae){it.current=!0;let Qe=be(r);try{if(await fn.current(f,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Qe,sessionId:Oe||f.id}),x)return;await Qe,x||Ge(!1);return}catch{if(x)return;await Qe,x||Ge(!1);return}}await be(r),x||Ge(!1)}catch(m){if(x)return;m instanceof It?!ve&&!jl(m)&&Pa(S,o,st,"NETWORK_REQUEST_FAILED","session_read"):Pa(S,o,st,"INTERNAL_SDK_ERROR","checkout_mount");let r=m instanceof It?m:new It(m instanceof Error?m.message:"Failed to initialize checkout","api_error");_(r),Ge(!1)}}async function be(ve){let{publishableKey:m,paypalPublishableKey:r}=_o(ve);Me.current={publishableKey:m,paypalPublishableKey:r};let{flopay:f,paypalFlopay:F}=await xo({publishableKey:m,paypalPublishableKey:r,billingApiUrl:S,locale:d,telemetry:o});ut.current=f,Ee(f),B.current=F,yt(F)}return M(),()=>{x=!0}},[Ue,$t,Pt,We,He,t]);let Vt=ar(async()=>{if(!(Ie||!G)){St(!0),je(null);try{await cn(G,{attempt3DS:!0,fallbackToFull:!0,sessionId:Oe||G.id})}finally{St(!1)}}},[Oe,Ie,cn,G]),Ot=Sa(T),On=ba(T),Nn=mn(()=>{if(!T||!G||!T.data.stripe?.publishableKey)return;let x={appearance:$e,paymentMethodCreation:"manual",billingApiUrl:S};if(T.data.stripe?.clientSecret)x.clientSecret=T.data.stripe.clientSecret;else{let O=Gi(G).total;x.amount=Math.round(O*100)||G.amount,x.currency=G.currency?.toLowerCase()}return x},[T,G,$e,S]),nn=!!(n&&!re&&I==="buttons"&&Q&&Pt==="full"),Gt=mn(()=>({session:G,loading:Jt,error:Xt,checkoutMode:Pe,inlineSessionDraft:xt,applyInlineSessionPatch:nn?jt:void 0,inlineSessionPatchProcessing:kt,claimPending:en}),[G,Jt,Xt,Pe,xt,nn,jt,kt,en]),rn=!!n&&I==="buttons"&&!On&&(!Y||!Nn),Ne=nt?oe(Cn,{status:nt,errorMessage:Rn,authorized:Kn}):null;if(Jt){if(l)return _t(kn,{children:[l,Ne]});if(I==="buttons"){let x=ie?.buttonsLayout?.cardButton?.borderRadius??ie?.appearance.variables?.borderRadius??8,O=M=>oe("div",{style:{height:M,borderRadius:x,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:[c&&O(Sr),P&&(E||g)&&O(Sr),P&&O(Sr),oe("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:[oe("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),oe("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ne]})}return Xt?v?oe(pn.Provider,{value:Gt,children:v(Xt)}):oe(pn.Provider,{value:Gt,children:oe("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Xt.message})}):rn?_t(kn,{children:[oe(pn.Provider,{value:Gt,children:oe(Ql,{onButtonClick:A,showPayPal:c,showStripe:P,showApplePay:E,showGooglePay:g,theme:ae,buttonsTheme:X,buttonsStyles:z,cardButtonContent:W,cardBackButtonContent:q,cardTitleContent:te})}),Ne]}):On&&G&&Ot?_t(kn,{children:[oe(pn.Provider,{value:Gt,children:_t("div",{className:he,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ve&&oe(mr,{icon:!1,children:Ve}),wt==="retrying"&&oe("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),wt==="exhausted"&&_t("div",{role:"alert",children:[oe("div",{children:"PayPal is temporarily unavailable. Please try again."}),oe("button",{type:"button",onClick:_n,children:"Retry PayPal"})]}),wt!=="exhausted"&&oe("div",{"aria-hidden":wt==="retrying"?!0:void 0,style:wt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:oe(Si,{sessionId:Oe,nonce:G.clientSecret||void 0,billingApiUrl:S,email:G.customer?.email,clientId:Ot.clientId,environment:Ot.environment,currency:(G.currency??"usd").toUpperCase(),isSubscription:G.mode==="subscription",onComplete:L,onErrorChange:je,onDecline:w,onButtonClick:A,onInitializationStateChange:Wn,allowAutomaticRetry:Hn===0,session:G,telemetry:o,telemetryContext:st,debug:ce},`paypal-init-${Hn}`)})]})}),Ne]}):!Y||!Nn?oe(kn,{children:Ne}):Pe==="confirm"?_t(kn,{children:[oe(pn.Provider,{value:Gt,children:oe(yo,{flopay:Y,paypalFlopay:Je,options:Nn,children:_t("div",{className:he,children:[Ve&&oe("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ve}),Re?Re({onConfirm:Vt,isProcessing:Ie}):oe("button",{type:"button",onClick:Vt,disabled:Ie,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Ie?"not-allowed":"pointer",opacity:Ie?.6:1},children:Ie?"Processing...":Fe??"Confirm Purchase"})]})})}),Ne]}):_t(kn,{children:[oe(pn.Provider,{value:Gt,children:oe(yo,{flopay:Y,paypalFlopay:Je,options:Nn,children:re?_t(kn,{children:[Ve&&oe("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ve}),oe(Xl,{sessionId:Oe,nonce:G?.clientSecret||void 0,billingApiUrl:S,session:G,children:re})]}):oe(ya,{sessionId:Oe,nonce:G?.clientSecret||void 0,email:G?.customer?.email,userId:G?.customer?.id,firstName:G?.customer?.firstName,lastName:G?.customer?.lastName,totalAmount:G?Math.round(Gi(G).total*100):0,currency:G?.currency?.toLowerCase()??"usd",onComplete:L,onError:h,onDecline:w,error:Ve,onErrorChange:je,showPayPal:c,showStripe:P,enabledPaymentMethods:k??T?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:T?.data.stripe?.enabledPaymentMethodCountries,showApplePay:E,showGooglePay:g,layout:I,theme:ae,buttonsTheme:X,buttonsStyles:z,appearance:$e,cardButtonContent:W,cardBackButtonContent:q,cardTitleContent:te,onButtonClick:A,onBeforeButtonClick:Q,enableAVS:de,...se?{cardFieldOrder:se}:{},...le?{cardPreFormSlot:le}:{},avsLayout:ne,country:G?.customer?.country,city:G?.customer?.city,state:G?.customer?.state,onCountryChange:C,onZipChange:R,avsCheck:!!de,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:re?"custom_layout":I==="buttons"?"buttons_layout":"default_layout",className:he,directPaypal:Sa(T),isSubscription:G?.mode==="subscription",session:G,dataAttachmentPending:en,debug:ce})})}),Ne]})}function Xl({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:o}){return oe(kn,{children:ha.Children.map(o,s=>{if(!ha.isValidElement(s))return s;let d=s.props,l={};return d.sessionId||(l.sessionId=e),!d.nonce&&t&&(l.nonce=t),d.billingApiUrl||(l.billingApiUrl=n),i?.customer&&(d.email||(l.email=i.customer.email),d.userId||(l.userId=i.customer.id),d.firstName||(l.firstName=i.customer.firstName),d.lastName||(l.lastName=i.customer.lastName)),Object.keys(l).length===0?s:ha.cloneElement(s,l)})})}function Ql({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:i,showGooglePay:o,theme:s,buttonsTheme:d,buttonsStyles:l,cardButtonContent:v,cardBackButtonContent:L,cardTitleContent:h}){let[w,C]=Ct(!1),R=mn(()=>ns(s),[s]),c=mn(()=>{let g=R?.buttonsLayout??Ul(d);return l?{...g,...l,cardButton:{...g.cardButton,...l.cardButton},cardFormContainer:{...g.cardFormContainer,...l.cardFormContainer},backButton:{...g.backButton,...l.backButton},backButtonIcon:{...g.backButtonIcon,...l.backButtonIcon},submitButton:{...g.submitButton,...l.submitButton},title:{...g.title,...l.title}}:g},[R,d,l]),P=R?.buttonsLayout?.cardButton?.borderRadius??R?.appearance.variables?.borderRadius??8,k=g=>oe("div",{style:{height:g,borderRadius:P,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),E=v===void 0?{boxSizing:"border-box",height:Sr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(w){let g=c.cardInputBorder??"#e5e7eb",ce=c.cardInputBackground??"white",I=cr(L),ae=cr(h);return _t("div",{style:{backgroundColor:c.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...c.cardFormContainer},children:[_t("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[_t("button",{type:"button",onClick:()=>C(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:I?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...c.backButton},children:[oe("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...c.backButtonIcon},children:oe("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:oe("path",{d:"M15 18l-6-6 6-6"})})}),oe(ur,{content:L})]}),ae?oe("div",{style:{flex:1}}):oe("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...c.title},children:oe($r,{content:h})})]}),oe("div",{style:{backgroundColor:ce,border:`1px solid ${g}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:oe("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:[oe("div",{style:{flex:1,backgroundColor:ce,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomLeftRadius:8,padding:12,height:45},children:oe("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),oe("div",{style:{flex:1,backgroundColor:ce,borderTop:"none",borderRight:`1px solid ${g}`,borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomRightRadius:8,padding:12,height:45},children:oe("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),oe("div",{style:{backgroundColor:ce,border:`1px solid ${g}`,borderRadius:8,marginTop:8,padding:12,height:45},children:oe("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),oe("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...c.submitButton,opacity:.5}}),oe("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 It("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&I(br),n&&(i||o)&&I(br),n&&oe("button",{type:"button",onClick:()=>{e?.("card"),S(!0)},style:{width:"100%",..._,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:oe(lr,{content:w})}),oe("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{dropThirdPartyOnlyError as zu}from"@flopay/shared";import{useEffect as Fl,useRef as qi,useContext as Dl}from"react";import{jsx as Ol}from"react/jsx-runtime";function ji(e,t){function n({className:i,id:o,style:a,options:u,onChange:l,onReady:w,onFocus:B,onBlur:P,onEscape:R}){let S=qi(null),x=qi(null),{elements:d,reportInteractive:b}=Dl(_n);return Fl(()=>{if(!d||!S.current)return;let I=!0;return(async()=>{let _=d.getElement(e);_||(_=await d.create(e,u)),!(!I||!S.current)&&(_.mount(S.current),x.current=_,l&&_.on("change",l),_.on("ready",()=>{b?.(),w?.()}),B&&_.on("focus",B),P&&_.on("blur",P),R&&_.on("escape",R))})(),()=>{if(I=!1,x.current){try{x.current.unmount()}catch{}x.current=null}}},[d,b]),Ol("div",{ref:S,className:i,id:o,style:a})}return n.displayName=t,n}var Ll=ji("payment","PaymentElement"),Nl=ji("address","AddressElement");import{PaymentAPI as zl}from"@flopay/js";import{FloPayError as Ul}from"@flopay/shared";import{useCallback as ha,useEffect as $l,useRef as ql,useState as Vi}from"react";import{Fragment as Vl,jsx as vr,jsxs as Kl}from"react/jsx-runtime";function jl({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:o,firstName:a,lastName:u,chv:l,onTokenizedBody:w,onComplete:B,onErrorChange:P,isProcessing:R=!1}){let S=vn(),x=jo(),d=io(),[b,I]=Vi(!1),[_,f]=Vi(!1),me=ql(!1),F=(n||d).replace(/\/+$/,""),se=ha(async J=>{try{let le=await new zl(F).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:J,accountData:{userId:o??"",email:i??"",firstName:a??"",lastName:u??""},chv:l});if(le.ok){B?.();return}let q=await le.json().catch(()=>null);P?.(q?.message??"Payment failed. Please try again.")}catch(W){P?.(W instanceof Error?W.message:"An unexpected error occurred")}},[F,e,t,o,i,a,u,l,B,P]),ee=ha(J=>{w?w(J):se(J)},[w,se]);$l(()=>{if(!S||me.current)return;let J=new URLSearchParams(window.location.search),W=J.get("payment_intent"),le=J.get("payment_intent_client_secret"),q=J.get("redirect_status");!W||!le||(me.current=!0,(async()=>{try{if(f(!0),q==="failed"){P?.("PayPal payment was declined. Please try again.");return}let K=S.getRawProvider();if(!K?.retrievePaymentIntent){P?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ce,error:_e}=await K.retrievePaymentIntent(le);if(_e){P?.(_e.message??"Failed to retrieve PayPal payment status.");return}if(ce&&(ce.status==="requires_capture"||ce.status==="succeeded")){let Pe=typeof ce.payment_method=="string"?ce.payment_method:ce.payment_method?.id;ee({id:Pe??ce.id,type:"card",threeDSecureActionResultTokenId:ce.id,isPaypal:!0});let ye=new URL(window.location.href);ye.searchParams.delete("payment_intent"),ye.searchParams.delete("payment_intent_client_secret"),ye.searchParams.delete("redirect_status"),window.history.replaceState({},"",ye.toString())}else P?.("PayPal payment was not completed. Please try again.")}catch(K){P?.(K instanceof Error?K.message:"Failed to complete PayPal payment.")}finally{f(!1)}})())},[S,ee,P]);let D=ha(async()=>{if(!(!S||!x))try{if(f(!0),P?.(null),!e||!i)throw new Ul("Missing sessionId or email for PayPal payment","validation_error");let J=await S.confirmPayPalPayment({billingApiUrl:F,sessionId:e,nonce:t,email:i,returnUrl:window.location.href});if(J.error){P?.(J.error.message);return}J.paymentIntentId&&(J.status==="succeeded"||J.status==="processing"||J.status==="requires_capture")&&ee({id:J.paymentMethodId??J.paymentIntentId,type:"card",threeDSecureActionResultTokenId:J.paymentIntentId,isPaypal:!0})}catch(J){P?.(J instanceof Error?J.message:"PayPal payment failed. Please try again.")}finally{f(!1)}},[S,x,e,t,i,F,ee,P]);return!S||!x?vr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):Kl(Vl,{children:[!b&&vr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),vr("div",{style:b?{}:{display:"none"},children:vr("button",{type:"button",onClick:D,disabled:_||R,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:_||R?"not-allowed":"pointer",opacity:_||R?.6:1},ref:()=>I(!0),children:_?"Processing...":"PayPal"})}),(_||R)&&vr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:vr("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 Cr,useMemo as Hr,useRef as Sr,useState as Ro}from"react";import{PaymentAPI as Pa}from"@flopay/js";import{FloPayError as Vn,resolveBillingApiUrl as Hl,resolveButtonsLayoutTheme as Wl,resolveTheme as Yl}from"@flopay/shared";import{Fragment as ec,jsx as wr,jsxs as tc}from"react/jsx-runtime";var Gl=44;function Ki(e){return new Promise(t=>setTimeout(t,e))}function Jl(e,t){return e instanceof Vn?e:new Vn(e instanceof Error?e.message:t,"api_error")}function Xl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Ql(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 Zl({sessionId:e,nonce:t,createSession:n,paymentMethodId:i,checkoutMethod:o,clientId:a,products:u,items:l,subscriptions:w,account:B,successUrl:P,cancelUrl:R,couponCodes:S,tagsData:x,utmMetadata:d,billingApiUrl:b,locale:I,theme:_,appearance:f,buttonsTheme:me,buttonsStyles:F,onSuccess:se,onError:ee,onDecline:D,children:J,disabled:W=!1,type:le="button",style:q,...K}){let ce=Hr(()=>Hl(b),[b]),_e=Hr(()=>Ql({createSession:n,clientId:a,products:u,items:l,subscriptions:w,account:B,successUrl:P,cancelUrl:R,couponCodes:S,tagsData:x,utmMetadata:d}),[B,R,a,S,n,u,l,w,P,x,d]),[Pe,ye]=Ro(!1),[te,ge]=Ro(null),[xe,ne]=Ro(null),[ke,Re]=Ro(null),Ce=Sr(!0),Y=Sr(null),E=Sr(ke),ae=Sr(se),Ne=Sr(ee),Oe=Sr(D);Cr(()=>{E.current=ke},[ke]),Cr(()=>{ae.current=se},[se]),Cr(()=>{Ne.current=ee},[ee]),Cr(()=>{Oe.current=D},[D]),Cr(()=>(Ce.current=!0,()=>{Ce.current=!1,Y.current?.abort()}),[]),Cr(()=>{if(typeof window>"u")return;let g=be=>{be.key==="Escape"&&Re(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let de=jn((g,be=jr)=>{Oe.current?.(Rt(be,g,{code:g.code,declineCode:g.declineCode}))},[]),k=jn(async g=>{Ce.current&&(ne(null),ge("success"),await Ki(xn),Ce.current&&ae.current?.(g))},[]),Q=jn(async(g,be)=>{Ce.current&&(Ne.current?.(g),be?.emitDecline&&de(g,be.method),ne(g.message),ge("error"),await Ki(Cn))},[de]),Z=jn(async(g,be,pt)=>{let tt=g.data.session??null;if(!tt)throw new Vn("No session data returned","api_error");let Xe=tt.clientSecret||t;if(tt.status==="complete"){await k({result:{status:"succeeded"},session:tt,sessionId:tt.id||be,autoCompleted:!1});return}if(tt.status==="expired")throw new Vn("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(g.autoProcessingPending){let qe=(await new Pa(ce).waitForCheckoutSessionCompletion(g.autoProcessingPending.sessionId,{initialDelayMs:g.autoProcessingPending.retryAfterMs})).data.session;if(!qe||qe.status!=="complete")throw new Vn("Automatic payment failed. Please try again.","api_error",{code:qe?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await k({result:{status:"succeeded"},session:qe,sessionId:qe.id||be,autoCompleted:!1});return}if(g.autoProcessingError){if(g.autoProcessingError.type==="3ds_required"&&g.autoProcessingError.nextActionRedirectUrl&&be&&Xe){let Qe=new AbortController;Y.current=Qe;let Ie;try{Ie=await Mi({billingApiUrl:ce,sessionId:be,nonce:Xe,nextActionRedirectUrl:g.autoProcessingError.nextActionRedirectUrl,signal:Qe.signal})}finally{Y.current===Qe&&(Y.current=null)}if(Ie.status==="declined")throw qn({type:Ie.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ie.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let Ye=(await new Pa(ce).waitForCheckoutSessionCompletion(be,{initialDelayMs:0,nonce:Xe})).data.session;if(!Ye||Ye.status!=="complete")throw qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await k({result:{status:"succeeded"},session:Ye,sessionId:Ye.id||be,autoCompleted:!1});return}throw qn(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(pt?.fromCreateSession&&g.autoProcessingAttempted===!0)throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ke=await Pr({billingApiUrl:ce,sessionId:be??tt.id,session:tt,nonce:Xe});if(Ke.type!=="success")throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await k({result:Ke.result,session:tt,sessionId:tt.id||be,autoCompleted:!1})}catch(Ke){let Qe=nr(Ke),Ie=tt.id||be;await Q(Qe,{emitDecline:!0,method:Qe.checkoutMethod??jr}),Xl(Qe,Ie)&&Ie&&Ce.current&&Re({sessionId:Ie,errorMessage:Qe.message,nonce:Xe||void 0})}},[t,ce,Q,k]),ze=jn(async g=>{if(K.onClick?.(g),!(g.defaultPrevented||W||Pe)){if(Re(null),e&&_e){let be=new Vn("Provide either sessionId or create-session props, not both.","validation_error");await Q(be),Ce.current&&(ge(null),ne(null));return}if(!e&&!_e){let be=new Vn("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Q(be),Ce.current&&(ge(null),ne(null));return}ye(!0),ne(null),ge("processing");try{let be=new Pa(ce);if(e){let pt=await be.getUnifiedCheckoutSession(e,t);await Z(pt,e);return}try{let pt=await be.createAndFetchSession({..._e});await Z(pt,pt.data.session?.id??null,{fromCreateSession:!0})}catch(pt){if(pt instanceof Vn&&pt.code==="session_auto_completed"){await k({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw pt}}catch(be){await Q(Jl(be,"Automatic payment failed. Please try again."))}finally{Ce.current&&(ge(null),ne(null),ye(!1))}}},[K,_e,W,Pe,t,Z,ce,e,Q,k]),ut=jn(g=>{let be=E.current;Re(null),ae.current?.({result:g,session:null,sessionId:be?.sessionId??null,autoCompleted:!1})},[]),je=jn(g=>{Ne.current?.(g)},[]),ot=jn(g=>{Oe.current?.(g)},[]),z=Hr(()=>Yl(_),[_]),V=Hr(()=>{let g=z?.buttonsLayout??Wl(me);return F?{...g,...F,cardButton:{...g.cardButton,...F.cardButton}}:g},[z,me,F]),et=Hr(()=>{let g=z?.appearance;return f?g?{...g,...f,variables:{...g.variables,...f.variables}}:f:g},[f,z]),Te=et?.variables,at=Te?.colorPrimary??"#4A49FF",We=Te?.colorPrimaryHover??yo(at,.12),Ve=Te?.borderRadius??"8px";return tc(ec,{children:[wr("button",{...K,type:le,onClick:ze,disabled:W||Pe,"aria-busy":Pe,style:{width:"100%",...J===void 0?{boxSizing:"border-box",height:Gl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...V.cardButton,...ra({themeBundle:z,resolvedPrimaryColor:at,resolvedBorderRadius:Ve,submitButtonStyle:V.submitButton,explicitPrimaryColor:Te?.colorPrimary}),fontSize:V.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:W||Pe?"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||Pe?.6:1,...q},onMouseEnter:g=>{K.onMouseEnter?.(g),!g.defaultPrevented&&!W&&!Pe&&(z||Te?.colorPrimary)&&(g.currentTarget.style.backgroundColor=We)},onMouseLeave:g=>{K.onMouseLeave?.(g),!g.defaultPrevented&&(z||Te?.colorPrimary)&&(g.currentTarget.style.backgroundColor=at)},onMouseDown:g=>{K.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{K.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:wr(lr,{content:J})}),te&&wr(Sn,{status:te,errorMessage:xe}),ke&&wr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&Re(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:wr("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:wr(ga,{sessionId:ke.sessionId,nonce:ke.nonce,checkoutMode:"full",billingApiUrl:ce,locale:I,theme:_,...et?{appearance:et}:{},buttonsTheme:me,buttonsStyles:F,initialErrorMessage:ke.errorMessage,cardTitleContent:null,onComplete:ut,onError:je,onDecline:ot})})})]})}export{Nl as AddressElement,mo as DirectPayPalButton,Zl as FloPayAutomaticPaymentButton,ga as FloPayCheckout,ao as FloPayProvider,jl as PayPalButton,Ll as PaymentElement,oa as SplitCardForm,$o as VaultCardFields,zu as dropThirdPartyOnlyError,ks as useCheckout,jo as useElements,vn as useFloPay,qo as usePayPalFloPay};
47
+ `})]})}return _t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&k(Sr),n&&(i||o)&&k(Sr),n&&oe("button",{type:"button",onClick:()=>{e?.("card"),C(!0)},style:{width:"100%",...E,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:c.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,...c.cardButton},onMouseDown:g=>{g.currentTarget.style.transform="scale(0.985)"},onMouseUp:g=>{g.currentTarget.style.transform="scale(1)"},children:oe(dr,{content:v})}),oe("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{dropThirdPartyOnlyError as Pp}from"@flopay/shared";import{useEffect as Zl,useRef as rs,useContext as ec}from"react";import{jsx as rc}from"react/jsx-runtime";function os(e,t){function n({className:i,id:o,style:s,options:d,onChange:l,onReady:v,onFocus:L,onBlur:h,onEscape:w}){let C=rs(null),R=rs(null),{elements:c,reportInteractive:P}=ec(xn);return Zl(()=>{if(!c||!C.current)return;let k=!0;return(async()=>{let E=c.getElement(e);E||(E=await c.create(e,d)),!(!k||!C.current)&&(E.mount(C.current),R.current=E,l&&E.on("change",l),E.on("ready",()=>{P?.(),v?.()}),L&&E.on("focus",L),h&&E.on("blur",h),w&&E.on("escape",w))})(),()=>{if(k=!1,R.current){try{R.current.unmount()}catch{}R.current=null}}},[c,P]),rc("div",{ref:C,className:i,id:o,style:s})}return n.displayName=t,n}var tc=os("payment","PaymentElement"),nc=os("address","AddressElement");import{useEffect as Ia,useRef as Dn,useState as _a}from"react";import{PaymentAPI as oc,PciVaultCardCapture as ac}from"@flopay/js";import{FloPayError as wr,isCardSetupCheckoutSession as ic,resolveBillingApiUrl as sc}from"@flopay/shared";import{Fragment as cc,jsx as xa}from"react/jsx-runtime";var Fo=class extends wr{constructor(t,n,i){super(t,n,i),this.name="FloPayCardSetupError",this.retryable=i.retryable}};function as(e,t={}){let n=e instanceof wr?e:void 0,i=n?.statusCode,o=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof i=="number"&&i>=500||n?.code==="vault_capture_timeout"||!n);return new Fo(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:o,...n?.param?{param:n.param}:{},...i!==void 0?{statusCode:i}:{}})}function lc({sessionId:e,nonce:t,billingApiUrl:n,telemetry:i,theme:o,containerStyle:s,loading:d=null,onReady:l,onComplete:v,onDecline:L,onCancel:h,onValidation:w,onError:C}){let[R,c]=_a(null),[P,k]=_a(null),[E,g]=_a(null),ce=Dn(l),I=Dn(C),ae=Dn(v),X=Dn(L),z=Dn(h),W=Dn(w),q=Dn(!1),te=Dn(!1),U=Dn(0);return ce.current=l,I.current=C,ae.current=v,X.current=L,z.current=h,W.current=w,Ia(()=>{let A=U.current+1;return U.current=A,()=>{queueMicrotask(()=>{U.current===A&&(q.current||te.current||(te.current=!0,He(()=>{z.current?.({status:"cancelled",sessionId:e})})))})}},[e]),Ia(()=>{let A=!0,Q=new oc(sc(n),{telemetry:i});return c(null),k(null),g(null),q.current=!1,te.current=!1,(async()=>{try{if(!e.trim())throw new wr("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new wr("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let de=await Q.getUnifiedCheckoutSession(e,t);if(!A)return;let se=de.data.session;if(!se||!ic(se))throw new wr("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let le=se.vault;if(le?.html?.trim()||(le=await Q.getVaultCapture(e,t)),!le.html?.trim())throw new wr("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!A)return;k(le),c(new ac({sessionId:e,operation:"card_setup",telemetry:i}))}catch(de){if(!A)return;let se=as(de);q.current=!0,g(se),He(()=>I.current?.(se))}})(),()=>{A=!1,Q.destroy()}},[n,t,e,i]),Ia(()=>{if(!R)return;let A=R.on("complete",de=>{q.current=!0,He(()=>{ae.current?.({status:"succeeded",sessionId:e,...de.paymentMethod?{paymentMethod:de.paymentMethod}:{}})})}),Q=R.on("decline",de=>{q.current=!0,He(()=>{X.current?.({status:"declined",sessionId:e,...de.declineReason?{reason:de.declineReason}:{},...de.message?{message:de.message}:{}})})});return()=>{A(),Q()}},[R,e]),E?xa("div",{role:"alert",children:E.message}):!R||!P?.html?xa(cc,{children:d}):xa(jr,{capture:R,html:P.html,messageToken:P.messageToken,expectedOrigin:P.expectedOrigin,theme:o,containerStyle:s,onReady:()=>{He(()=>ce.current?.())},onValidation:A=>{He(()=>W.current?.(A))},onError:A=>{if(!A)return;let Q=as(new Error(A),{code:"card_setup_widget_failed",retryable:!0});He(()=>I.current?.(Q))}})}import{PaymentAPI as dc}from"@flopay/js";import{FloPayError as uc}from"@flopay/shared";import{useCallback as Ta,useEffect as pc,useRef as mc,useState as is}from"react";import{Fragment as fc,jsx as kr,jsxs as gc}from"react/jsx-runtime";function yc({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:o,firstName:s,lastName:d,chv:l,onTokenizedBody:v,onComplete:L,onErrorChange:h,isProcessing:w=!1}){let C=bn(),R=Qo(),c=fo(),[P,k]=is(!1),[E,g]=is(!1),ce=mc(!1),I=(n||c).replace(/\/+$/,""),ae=Ta(async W=>{try{let te=await new dc(I).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:W,accountData:{userId:o??"",email:i??"",firstName:s??"",lastName:d??""},chv:l});if(te.ok){L?.();return}let U=await te.json().catch(()=>null);h?.(U?.message??"Payment failed. Please try again.")}catch(q){h?.(q instanceof Error?q.message:"An unexpected error occurred")}},[I,e,t,o,i,s,d,l,L,h]),X=Ta(W=>{v?v(W):ae(W)},[v,ae]);pc(()=>{if(!C||ce.current)return;let W=new URLSearchParams(window.location.search),q=W.get("payment_intent"),te=W.get("payment_intent_client_secret"),U=W.get("redirect_status");!q||!te||(ce.current=!0,(async()=>{try{if(g(!0),U==="failed"){h?.("PayPal payment was declined. Please try again.");return}let A=C.getRawProvider();if(!A?.retrievePaymentIntent){h?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:Q,error:de}=await A.retrievePaymentIntent(te);if(de){h?.(de.message??"Failed to retrieve PayPal payment status.");return}if(Q&&(Q.status==="requires_capture"||Q.status==="succeeded")){let se=typeof Q.payment_method=="string"?Q.payment_method:Q.payment_method?.id;X({id:se??Q.id,type:"card",threeDSecureActionResultTokenId:Q.id,isPaypal:!0});let le=new URL(window.location.href);le.searchParams.delete("payment_intent"),le.searchParams.delete("payment_intent_client_secret"),le.searchParams.delete("redirect_status"),window.history.replaceState({},"",le.toString())}else h?.("PayPal payment was not completed. Please try again.")}catch(A){h?.(A instanceof Error?A.message:"Failed to complete PayPal payment.")}finally{g(!1)}})())},[C,X,h]);let z=Ta(async()=>{if(!(!C||!R))try{if(g(!0),h?.(null),!e||!i)throw new uc("Missing sessionId or email for PayPal payment","validation_error");let W=await C.confirmPayPalPayment({billingApiUrl:I,sessionId:e,nonce:t,email:i,returnUrl:window.location.href});if(W.error){h?.(W.error.message);return}W.paymentIntentId&&(W.status==="succeeded"||W.status==="processing"||W.status==="requires_capture")&&X({id:W.paymentMethodId??W.paymentIntentId,type:"card",threeDSecureActionResultTokenId:W.paymentIntentId,isPaypal:!0})}catch(W){h?.(W instanceof Error?W.message:"PayPal payment failed. Please try again.")}finally{g(!1)}},[C,R,e,t,i,I,X,h]);return!C||!R?kr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):gc(fc,{children:[!P&&kr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),kr("div",{style:P?{}:{display:"none"},children:kr("button",{type:"button",onClick:z,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)&&kr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:kr("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 Vn,useEffect as Rr,useMemo as Zr,useRef as Er,useState as eo}from"react";import{PaymentAPI as Ma}from"@flopay/js";import{FloPayError as _r,resolveBillingApiUrl as hc,resolveButtonsLayoutTheme as Pc,resolveTheme as bc}from"@flopay/shared";import{Fragment as Rc,jsx as Ir,jsxs as Ec}from"react/jsx-runtime";var vc=44;function ss(e){return new Promise(t=>setTimeout(t,e))}function Cc(e,t){return e instanceof _r?e:new _r(e instanceof Error?e.message:t,"api_error")}function Sc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function wc(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 kc({sessionId:e,nonce:t,createSession:n,paymentMethodId:i,checkoutMethod:o,clientId:s,products:d,items:l,subscriptions:v,account:L,successUrl:h,cancelUrl:w,couponCodes:C,tagsData:R,utmMetadata:c,billingApiUrl:P,locale:k,theme:E,appearance:g,buttonsTheme:ce,buttonsStyles:I,onSuccess:ae,onError:X,onDecline:z,children:W,disabled:q=!1,type:te="button",style:U,...A}){let Q=Zr(()=>hc(P),[P]),de=Zr(()=>wc({createSession:n,clientId:s,products:d,items:l,subscriptions:v,account:L,successUrl:h,cancelUrl:w,couponCodes:C,tagsData:R,utmMetadata:c}),[L,w,s,C,n,d,l,v,h,R,c]),[se,le]=eo(!1),[ne,he]=eo(null),[Te,re]=eo(null),[Ue,Fe]=eo(!1),[Re,H]=eo(null),S=Er(!0),ie=Er(null),$e=Er(Re),ze=Er(ae),pe=Er(X),T=Er(z);Rr(()=>{$e.current=Re},[Re]),Rr(()=>{ze.current=ae},[ae]),Rr(()=>{pe.current=X},[X]),Rr(()=>{T.current=z},[z]),Rr(()=>(S.current=!0,()=>{S.current=!1,ie.current?.abort()}),[]),Rr(()=>{if(typeof window>"u")return;let _=Pe=>{Pe.key==="Escape"&&H(null)};return window.addEventListener("keydown",_),()=>{window.removeEventListener("keydown",_)}},[]);let ue=Vn((_,Pe=Jr)=>{T.current?.(Et(Pe,_,{code:_.code,declineCode:_.declineCode}))},[]),Y=Vn(async _=>{S.current&&(re(null),Fe(_.result.status==="authorized"),he("success"),await ss(Tn),S.current&&ze.current?.(_))},[]),Ee=Vn(async(_,Pe)=>{S.current&&(pe.current?.(_),Pe?.emitDecline&&ue(_,Pe.method),re(_.message),Fe(!1),he("error"),await ss(vn))},[ue]),ut=Vn(async(_,Pe,Ye)=>{let Ie=_.data.session??null;if(!Ie)throw new _r("No session data returned","api_error");let St=Ie.clientSecret||t;if(fr(Ie)){await Y({result:er(Ie,Pe),session:Ie,sessionId:Ie.id||Pe,autoCompleted:!1});return}if(Ie.status==="expired")throw go(Ie);try{if(_.autoProcessingPending){let Xe=(await new Ma(Q).waitForCheckoutSessionCompletion(_.autoProcessingPending.sessionId,{initialDelayMs:_.autoProcessingPending.retryAfterMs})).data.session;if(!fr(Xe))throw ho(Xe);await Y({result:er(Xe,Pe),session:Xe,sessionId:Xe.id||Pe,autoCompleted:!1});return}if(_.autoProcessingError){if(_.autoProcessingError.type==="3ds_required"&&_.autoProcessingError.nextActionRedirectUrl&&Pe&&St){let je=new AbortController;ie.current=je;let nt;try{nt=await Hi({billingApiUrl:Q,sessionId:Pe,nonce:St,nextActionRedirectUrl:_.autoProcessingError.nextActionRedirectUrl,signal:je.signal})}finally{ie.current===je&&(ie.current=null)}if(nt.status==="declined")throw jn({type:nt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:nt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:_.autoProcessingError.checkoutMethod});let at=(await new Ma(Q).waitForCheckoutSessionCompletion(Pe,{initialDelayMs:0,nonce:St})).data.session;if(!fr(at))throw jn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:_.autoProcessingError.checkoutMethod});await Y({result:er(at,Pe),session:at,sessionId:at.id||Pe,autoCompleted:!1});return}throw jn(_.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:_.autoProcessingError.checkoutMethod})}if(Ye?.fromCreateSession&&_.autoProcessingAttempted===!0)throw jn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ve=await Cr({billingApiUrl:Q,sessionId:Pe??Ie.id,session:Ie,nonce:St});if(Ve.type!=="success")throw jn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Y({result:Ve.result,session:Ie,sessionId:Ie.id||Pe,autoCompleted:!1})}catch(Ve){let je=or(Ve),nt=Ie.id||Pe;await Ee(je,{emitDecline:!0,method:je.checkoutMethod??Jr}),Sc(je,nt)&&nt&&S.current&&H({sessionId:nt,errorMessage:je.message,nonce:St||void 0})}},[t,Q,Ee,Y]),Je=Vn(async _=>{if(A.onClick?.(_),!(_.defaultPrevented||q||se)){if(H(null),e&&de){let Pe=new _r("Provide either sessionId or create-session props, not both.","validation_error");await Ee(Pe),S.current&&(he(null),re(null));return}if(!e&&!de){let Pe=new _r("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Ee(Pe),S.current&&(he(null),re(null));return}le(!0),re(null),Fe(!1),he("processing");try{let Pe=new Ma(Q);if(e){let Ye=await Pe.getUnifiedCheckoutSession(e,t);await ut(Ye,e);return}try{let Ye=await Pe.createAndFetchSession({...de});await ut(Ye,Ye.data.session?.id??null,{fromCreateSession:!0})}catch(Ye){if(Ye instanceof _r&&Ye.code==="session_auto_completed"){await Y({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Ye}}catch(Pe){await Ee(Cc(Pe,"Automatic payment failed. Please try again."))}finally{S.current&&(he(null),re(null),le(!1))}}},[A,de,q,se,t,ut,Q,e,Ee,Y]),yt=Vn(_=>{let Pe=$e.current;H(null),ze.current?.({result:_,session:null,sessionId:Pe?.sessionId??null,autoCompleted:!1})},[]),B=Vn(_=>{pe.current?.(_)},[]),G=Vn(_=>{T.current?.(_)},[]),tt=Zr(()=>bc(E),[E]),qe=Zr(()=>{let _=tt?.buttonsLayout??Pc(ce);return I?{..._,...I,cardButton:{..._.cardButton,...I.cardButton}}:_},[tt,ce,I]),ft=Zr(()=>{let _=tt?.appearance;return g?_?{..._,...g,variables:{..._.variables,...g.variables}}:g:_},[g,tt]),Oe=ft?.variables,We=Oe?.colorPrimary??"#4A49FF",Jt=Oe?.colorPrimaryHover??wo(We,.12),Ge=Oe?.borderRadius??"8px";return Ec(Rc,{children:[Ir("button",{...A,type:te,onClick:Je,disabled:q||se,"aria-busy":se,style:{width:"100%",...W===void 0?{boxSizing:"border-box",height:vc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...qe.cardButton,...ma({themeBundle:tt,resolvedPrimaryColor:We,resolvedBorderRadius:Ge,submitButtonStyle:qe.submitButton,explicitPrimaryColor:Oe?.colorPrimary}),fontSize:qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:q||se?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:q||se?.6:1,...U},onMouseEnter:_=>{A.onMouseEnter?.(_),!_.defaultPrevented&&!q&&!se&&(tt||Oe?.colorPrimary)&&(_.currentTarget.style.backgroundColor=Jt)},onMouseLeave:_=>{A.onMouseLeave?.(_),!_.defaultPrevented&&(tt||Oe?.colorPrimary)&&(_.currentTarget.style.backgroundColor=We)},onMouseDown:_=>{A.onMouseDown?.(_),_.defaultPrevented||(_.currentTarget.style.transform="scale(0.985)")},onMouseUp:_=>{A.onMouseUp?.(_),_.defaultPrevented||(_.currentTarget.style.transform="scale(1)")},children:Ir(dr,{content:W})}),ne&&Ir(Cn,{status:ne,errorMessage:Te,authorized:Ue}),Re&&Ir("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:_=>{_.target===_.currentTarget&&H(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:Ir("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:Ir(Ea,{sessionId:Re.sessionId,nonce:Re.nonce,checkoutMode:"full",billingApiUrl:Q,locale:k,theme:E,...ft?{appearance:ft}:{},buttonsTheme:ce,buttonsStyles:I,initialErrorMessage:Re.errorMessage,cardTitleContent:null,onComplete:yt,onError:B,onDecline:G})})})]})}export{nc as AddressElement,So as DirectPayPalButton,kc as FloPayAutomaticPaymentButton,lc as FloPayCardSetup,Fo as FloPayCardSetupError,Ea as FloPayCheckout,yo as FloPayProvider,yc as PayPalButton,tc as PaymentElement,ya as SplitCardForm,jr as VaultCardFields,Pp as dropThirdPartyOnlyError,Us as useCheckout,Qo as useElements,bn as useFloPay,Xo as usePayPalFloPay};