@flopay/react 1.4.18 → 1.4.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -0
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +9 -9
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{useCallback as us,useEffect as Fr,useState as No,useMemo as ps,useRef as Oo}from"react";import{resolveBillingApiUrl as ms}from"@flopay/shared";import{createContext as Ha}from"react";var xn=Ha({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),yn=Ha({session:null,loading:!1,error:null});var ss=Symbol.for("@flopay/js.telemetry.bridge.v1"),ls=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function cs(){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 ds(e){let t=cs(),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 no(e){let t=globalThis[ls];return ds(t?.(e)??{})}function At(e){if(e)return e[ss]}import{jsx as ys}from"react/jsx-runtime";function ro({flopay:e,paypalFlopay:t,options:n,children:i}){let[o,a]=No(e instanceof Promise?null:e),[u,l]=No(t instanceof Promise||!t?null:t),[w,B]=No(null),h=Oo(null),R=Oo(null),S=Oo(null);Fr(()=>{if(!o)return;let I=At(o);return h.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),Fr(()=>{let I=!1;return e instanceof Promise?e.then(x=>{I||a(x)}):a(e),()=>{I=!0}},[e]),Fr(()=>{let I=!1;if(!t){l(null);return}return t instanceof Promise?t.then(x=>{I||l(x)}):l(t),()=>{I=!0}},[t]),Fr(()=>{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]),Fr(()=>{if(!o||!w||R.current===w)return;R.current=w;let I=At(o);I?.log({name:"checkout.rendered",stage:"checkout_render"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(h.current??0),durationMode:"machine"})},[w,o]);let _=us(()=>{if(!o||!w||S.current===w)return;S.current=w;let I=At(o);I?.log({name:"checkout.interactive",stage:"checkout_interactive"}),I?.performance({stage:"checkout_interactive",durationMs:I.elapsed(h.current??0),durationMode:"machine"})},[w,o]),d=ms(n?.billingApiUrl),b=ps(()=>({flopay:o,paypalFlopay:u,elements:w,billingApiUrl:d,reportInteractive:_}),[o,u,w,d,_]);return ys(xn.Provider,{value:b,children:i})}import oa,{useCallback as rr,useEffect as Bn,useMemo as fn,useRef as jt,useState as bt}from"react";import{PaymentAPI as bo,SESSION_CREATE_TELEMETRY as yl}from"@flopay/js";import{SDK_VERSION as Ni,FloPayError as Pt,classifyTelemetryFailure as fl,isDetachedSessionEligible as gl,resolveBillingApiUrl as hl,buildCheckoutDisplayData as Mi,resolveButtonsLayoutTheme as Pl,resolveIdempotencyKey as Bi,resolveTheme as Oi}from"@flopay/shared";import"react";import{Fragment as dr,jsx as an,jsxs as Wa}from"react/jsx-runtime";function fs(){return Wa(dr,{children:[Wa("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 gs(){return an(dr,{children:"Go back"})}function hs(){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(fs,{}):e})}function cr({content:e}){return an(dr,{children:e===void 0?an(gs,{}):e})}function Dr({content:e}){return an(dr,{children:e===void 0?an(hs,{}):e})}import{ExpressCheckoutElement as vi,PaymentElement as As,Elements as tr,useElements as Qo,useStripe as Zo}from"@stripe/react-stripe-js";import{resolveButtonsLayoutTheme as Fs,getPostalCodeLabel as Jo,getStateLabel as si,getStateOptions as Ds,COUNTRY_OPTIONS as Ls,resolveAVSConfig as Ns,isAVSFieldVisible as De,getStateFromPostalCode as li,isPostalCodeSupported as Os,isValidPostalCode as zs,getPostalCodeExample as Us,filterStripeMethodsByCountry as $s,getStripeMethodDisplayName as hr,hasVendoredStripeMethodLogo as qs,needsStripeMethodExplicitConfirm as ci,resolveStripeMethodBrandVariant as js,partitionStripeMethods as Vs,stripeExpressMethodToOptionKey as di}from"@flopay/shared";import{PaymentAPI as $n,toStripeAppearance as Ks}from"@flopay/js";import{useEffect as Ya,useRef as Lr}from"react";import{jsx as Ps}from"react/jsx-runtime";function zo({capture:e,html:t,messageToken:n,expectedOrigin:i,theme:o,containerStyle:a,onReady:u,onError:l,onValidation:w}){let B=Lr(null),h=Lr(u),R=Lr(l),S=Lr(w);h.current=u,R.current=l,S.current=w;let _=Lr(o);return _.current=o,Ya(()=>{let d=B.current;if(!d)return;let b=!0,I=!1,x=()=>{!b||I||(I=!0,h.current?.())},P=e.on("ready",()=>{x()}),ae=e.on("error",ee=>{R.current?.(ee.message??"There was a problem loading the secure card form.")}),U=e.on("validation",ee=>{S.current?.(ee.message??null)}),le={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},..._.current?{theme:_.current}:{}};return e.mount(d,le).then(()=>{x()}).catch(ee=>{b&&R.current?.(ee instanceof Error?ee.message:"Failed to load the secure card form.")}),()=>{b=!1,P(),ae(),U(),e.unmount()}},[e,t,n,i]),Ya(()=>{o&&e.applyTheme?.(o)},[e,o]),Ps("div",{ref:B,"data-testid":"flopay-vault-card-fields",style:a})}import"react";import{jsx as Ga,jsxs as bs}from"react/jsx-runtime";function ur({children:e,margin:t,icon:n=!0,styleOverride:i}){return bs("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&&Ga("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Ga("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 Ja={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 Hs,{useCallback as we,useContext as Ws,useEffect as Qe,useMemo as nt,useRef as Be,useState as ve}from"react";import{useContext as Nr}from"react";import{resolveBillingApiUrl as vs}from"@flopay/shared";function vn(){return Nr(xn).flopay}function Uo(){return Nr(xn).paypalFlopay??null}function $o(){return Nr(xn).elements}function Cs(){return Nr(yn)}function oo(){return Nr(xn).billingApiUrl||vs()}import"react";import{jsx as sn,jsxs as pr}from"react/jsx-runtime";var Tn=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 ws,useEffect as Or,useState as Ko,useMemo as ks,useRef as Ho}from"react";import{resolveBillingApiUrl as Rs}from"@flopay/shared";import{createContext as ei}from"react";var xn=ei({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),pn=ei({session:null,loading:!1,error:null});var bs=Symbol.for("@flopay/js.telemetry.bridge.v1"),vs=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Cs(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},flush:async()=>{},destroy:()=>{}}}function Ss(e){let t=Cs(),n=(a,i)=>a?a.bind(e):i,s=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:s,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,s()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function co(e){let t=globalThis[vs];return Ss(t?.(e)??{})}function Mt(e){if(e)return e[bs]}import{jsx as Is}from"react/jsx-runtime";function uo({flopay:e,paypalFlopay:t,options:n,children:s}){let[a,i]=Ko(e instanceof Promise?null:e),[d,l]=Ko(t instanceof Promise||!t?null:t),[C,D]=Ko(null),h=Ho(null),w=Ho(null),S=Ho(null);Or(()=>{if(!a)return;let k=Mt(a);return h.current=k?.beginCheckout()??k?.now()??0,k?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{k?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),Or(()=>{let k=!1;return e instanceof Promise?e.then(I=>{k||i(I)}):i(e),()=>{k=!0}},[e]),Or(()=>{let k=!1;if(!t){l(null);return}return t instanceof Promise?t.then(I=>{k||l(I)}):l(t),()=>{k=!0}},[t]),Or(()=>{if(!a){D(null);return}let k=a.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return D(k),()=>{k.destroy()}},[a,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),Or(()=>{if(!a||!C||w.current===C)return;w.current=C;let k=Mt(a);k?.log({name:"checkout.rendered",stage:"checkout_render"}),k?.performance({stage:"checkout_render",durationMs:k.elapsed(h.current??0),durationMode:"machine"})},[C,a]);let B=ws(()=>{if(!a||!C||S.current===C)return;S.current=C;let k=Mt(a);k?.log({name:"checkout.interactive",stage:"checkout_interactive"}),k?.performance({stage:"checkout_interactive",durationMs:k.elapsed(h.current??0),durationMode:"machine"})},[C,a]),c=Rs(n?.billingApiUrl),P=ks(()=>({flopay:a,paypalFlopay:d,elements:C,billingApiUrl:c,reportInteractive:B}),[a,d,C,c,B]);return Is(xn.Provider,{value:P,children:s})}import ya,{useCallback as or,useEffect as Bn,useMemo as mn,useRef as Nt,useState as Ct}from"react";import{PaymentAPI as Eo,SESSION_CREATE_TELEMETRY as Tl}from"@flopay/js";import{SDK_VERSION as Gi,FloPayError as At,classifyTelemetryFailure as qi,isDetachedSessionEligible as Ml,resolveBillingApiUrl as Al,buildCheckoutDisplayData as ji,resolveButtonsLayoutTheme as Bl,resolveIdempotencyKey as Vi,resolveTheme as Ji,telemetryStatusClass as Fl}from"@flopay/shared";import"react";import{Fragment as ur,jsx as an,jsxs as ti}from"react/jsx-runtime";function Es(){return ti(ur,{children:[ti("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 _s(){return an(ur,{children:"Go back"})}function xs(){return an(ur,{children:"Secure card checkout"})}function lr(e){return e!==void 0&&(e===""||e===null||e===!1)}function cr({content:e}){return an(ur,{children:e===void 0?an(Es,{}):e})}function dr({content:e}){return an(ur,{children:e===void 0?an(_s,{}):e})}function Nr({content:e}){return an(ur,{children:e===void 0?an(xs,{}):e})}import{ExpressCheckoutElement as Ti,PaymentElement as Hs,Elements as nr,useElements as sa,useStripe as la}from"@stripe/react-stripe-js";import{isAuthorizationOnlySession as na,normalizeCheckoutFailureOutcome as Ws,resolveButtonsLayoutTheme as Ys,getPostalCodeLabel as aa,getStateLabel as hi,getStateOptions as Gs,COUNTRY_OPTIONS as Js,resolveAVSConfig as Xs,isAVSFieldVisible as De,getStateFromPostalCode as Pi,isPostalCodeSupported as Qs,isValidPostalCode as Zs,getPostalCodeExample as el,filterStripeMethodsByCountry as tl,getStripeMethodDisplayName as br,hasVendoredStripeMethodLogo as nl,needsStripeMethodExplicitConfirm as bi,resolveStripeMethodBrandVariant as rl,partitionStripeMethods as ol,stripeExpressMethodToOptionKey as vi}from"@flopay/shared";import{PaymentAPI as $n,toStripeAppearance as al}from"@flopay/js";import{useEffect as ni,useRef as Ur}from"react";import{jsx as Ts}from"react/jsx-runtime";function Wo({capture:e,html:t,messageToken:n,expectedOrigin:s,theme:a,containerStyle:i,onReady:d,onError:l,onValidation:C}){let D=Ur(null),h=Ur(d),w=Ur(l),S=Ur(C);h.current=d,w.current=l,S.current=C;let B=Ur(a);return B.current=a,ni(()=>{let c=D.current;if(!c)return;let P=!0,k=!1,I=()=>{!P||k||(k=!0,h.current?.())},g=e.on("ready",()=>{I()}),de=e.on("error",Z=>{w.current?.(Z.message??"There was a problem loading the secure card form.")}),_=e.on("validation",Z=>{S.current?.(Z.message??null)}),ae={html:t,...n?{messageToken:n}:{},...s?{expectedOrigin:s}:{},...B.current?{theme:B.current}:{}};return e.mount(c,ae).then(()=>{I()}).catch(Z=>{P&&w.current?.(Z instanceof Error?Z.message:"Failed to load the secure card form.")}),()=>{P=!1,g(),de(),_(),e.unmount()}},[e,t,n,s]),ni(()=>{a&&e.applyTheme?.(a)},[e,a]),Ts("div",{ref:D,"data-testid":"flopay-vault-card-fields",style:i})}import"react";import{jsx as ri,jsxs as Ms}from"react/jsx-runtime";function pr({children:e,margin:t,icon:n=!0,styleOverride:s}){return Ms("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...s??{}},children:[n&&ri("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ri("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 oi={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 il,{useCallback as Se,useContext as sl,useEffect as ct,useMemo as lt,useRef as Be,useState as Ce}from"react";import{useContext as $r}from"react";import{resolveBillingApiUrl as As}from"@flopay/shared";function bn(){return $r(xn).flopay}function Yo(){return $r(xn).paypalFlopay??null}function Go(){return $r(xn).elements}function Bs(){return $r(pn)}function po(){return $r(xn).billingApiUrl||As()}import"react";import{jsx as sn,jsxs as mr}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:mr("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:[mr("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&mr("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:mr("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:mr("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"}})]})})]}),mr("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 Uc,isSetupIntentClientSecret as $c}from"@flopay/shared";function Xa(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 qo(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 Qa(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 jo(e,t){return t?{...e,...t}:e}function kt(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 Ss=[{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 Ss)if(n.test(t))return i;return e}function ao(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Za(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function ei(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function io(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var so="flopay_recent_completion_";function mr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(so+e,JSON.stringify(t))}catch{}}function Vo(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(so+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(so+e),!1):!0}catch{return!1}}function ti(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 lo,useEffect as dt,useMemo as zr,useRef as Ke,useState as er}from"react";import{loadScript as ks}from"@paypal/paypal-js";import{PaymentAPI as Ko}from"@flopay/js";import{FloPayError as ni,SDK_VERSION as Rs,generateIdempotencyKey as Is,normalizeGatewayEnvironment as Es}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 ws(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 Mn(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 Or(e){return typeof e!="object"||e===null?!1:Zn(e.type)?.toLowerCase()==="card_error"||yr(e)!==void 0}function Un(e){let t=ws(e)?.toLowerCase()??"",i=`${Mn(e)?.toLowerCase()??""} ${t}`;return i.includes("popup")&&i.includes("block")}import{jsx as fr,jsxs as Ho}from"react/jsx-runtime";var co=45,_s=1e3,xs=11e3,Ts=["https://www.paypal.com","https://www.sandbox.paypal.com"],ri="We couldn't open PayPal. Try again or choose another payment method.",Ms={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 oi(e){return e.includes("No ack for postMessage init()")&&Ts.some(t=>e.includes(t))&&e.includes("10000ms")}function Bs(e){return e?`${ri} Allow pop-ups for this site, then try again.`:ri}function ai({sessionId:e,nonce:t,billingApiUrl:n,email:i,clientId:o,environment:a,currency:u,isSubscription:l,onTokenizedBody:w,onComplete:B,onErrorChange:h,onDecline:R,onTechnicalFailure:S,isProcessing:_=!1,onLoadStateChange:d,onInitializationStateChange:b,allowAutomaticRetry:I=!0,onButtonClick:x,runBeforeButtonClick:P,session:ae,existingOrderId:U,telemetry:le,telemetryContext:ee,debug:F=!1}){let J=vn(),W=zr(()=>{if(J)return null;let T=no({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Rs,enabled:le!==!1});return T.setCheckoutContext(ee??{}),T.beginCheckout(ee??{}),T},[n,J,le,ee?.checkoutMode,ee?.layout]),ce=zr(()=>At(J),[J]);dt(()=>()=>{W&&W.flush().catch(()=>{}).finally(()=>W.destroy())},[W]);let $=zr(()=>({error:T=>{ce?ce.error(T):W?.error(T)},log:T=>{ce?ce.log(T):W?.log(T)},performance:T=>{ce?ce.performance(T):W?.performance(T)},terminal:T=>{ce?ce.terminal(T):W?.terminal(T)},startTiming:()=>ce?.now()??W?.now()??0,elapsed:T=>ce?.elapsed(T)??Math.max(0,(W?.now()??T)-T)}),[ce,W]),K=Ke(null),de=Ke(0),_e=Ke(null),Pe=Ke(!1),[ye,te]=er(!1),[ge,xe]=er(!1),[ne,ke]=er(0),Re=Ke(0),[Ce,Y]=er(!1),E=Ke(!1),ie=Ke(!1),[Ne,Oe]=er(!1),[ue,k]=er(!1),Q=zr(()=>n.replace(/\/+$/,""),[n]),Z=zr(()=>JSON.stringify([Q,o,u,a??"",l,e,U??""]),[Q,o,u,a,U,l,e]),ze=Ke(Z),ut=ze.current!==Z,[qe,ot]=er([]),N=T=>{F&&ot(gt=>[...gt,`${new Date().toISOString().slice(11,23)} ${T}`])},V=Ke(w),Ze=Ke(B),Te=Ke(h),at=Ke(R),He=Ke(S),je=Ke(x),ln=Ke(d),f=Ke(b),be=Ke(P),pt=Ke(ae),et=Ke(i),Je=Ke(t),Ve=Ke(null),Xe=Ke(0),Ie=Ke(null),$e=Ke(null),It=Ke(new Map),Ye=Ke(new Map),Fn=Ke(!1);dt(()=>(Fn.current=!0,()=>{Fn.current=!1}),[]),dt(()=>{V.current=w},[w]),dt(()=>{Ze.current=B},[B]),dt(()=>{Te.current=h},[h]),dt(()=>{at.current=R},[R]),dt(()=>{He.current=S},[S]),dt(()=>{je.current=x},[x]),dt(()=>{ln.current=d},[d]),dt(()=>{f.current=b},[b]),dt(()=>{be.current=P},[P]),dt(()=>{pt.current=ae},[ae]),dt(()=>{et.current=i},[i]),dt(()=>{Je.current=t},[t]),dt(()=>{Re.current=ne},[ne]),dt(()=>{Ce&&_e.current?.focus()},[Ce,ne]);let vt=lo(()=>{window.setTimeout(()=>{_e.current?.focus()},0)},[]),Dn=lo(()=>{te(!1),ke(T=>T+1)},[]),cn=lo(()=>{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=lo((T,gt)=>{let mt=He.current;if(mt){mt("paypal",T,gt);return}Te.current?.(Bs(gt?.popupBlocked??Un(T)))},[]),tn=()=>{Ie.current?.timer&&(clearTimeout(Ie.current.timer),Ie.current.timer=null)},Ln=()=>{tn();let T=Xe.current+1;return Xe.current=T,$e.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,$e.current=null,!0),Et=T=>{let gt=T?.generation??Ie.current?.generation??Xe.current;(!T?.generation||Ie.current?.generation===gt)&&(tn(),Ie.current=null),$e.current=gt,T?.showRetry&&Y(!0),T?.remount&&Dn(),T?.focus!==!1&&vt()},Vt=T=>Ie.current?.generation===T&&$e.current!==T,Xt=T=>{typeof document<"u"&&document.visibilityState!=="visible"||(tn(),T.timer=setTimeout(()=>{Ie.current?.generation===T.generation&&(Ie.current=null,$e.current=T.generation,gn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),Y(!0),Dn(),vt())},600))},Ft=()=>{let T=Ie.current;T?.yieldedControl&&Xt(T)},Kt=()=>{let T=Ie.current;T&&(T.yieldedControl=!0,tn())},Dt=T=>{let gt=Ve.current;return gt&&Ye.current.set(T,gt),T};dt(()=>{let T=()=>{document.visibilityState==="visible"?Ft():Kt()};return document.addEventListener("visibilitychange",T),window.addEventListener("focus",Ft),window.addEventListener("blur",Kt),()=>{document.removeEventListener("visibilitychange",T),window.removeEventListener("focus",Ft),window.removeEventListener("blur",Kt),tn()}},[]),dt(()=>{ze.current!==Z&&(ze.current=Z,E.current=!1,ie.current=!1,te(!1),xe(!1),Oe(!1),f.current?.("loading"))},[Z]),dt(()=>{ct(()=>ln.current?.(ye&&!Ne))},[ye,Ne]);let re=Es(a);dt(()=>{let T=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",gt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(N(`mount clientId=${T} env=${a??"(unset)"}\u2192${re??"live"} ccy=${u} sub=${l}`),N(`ua=${gt.slice(0,80)}${gt.length>80?"\u2026":""}`),!o){N("FAIL: clientId empty \u2014 gateway misconfigured"),Oe(!0),$.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){N("FAIL: containerRef not attached");return}de.current=$.startTiming(),$.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let mt=!1,Ct=!1,Ee=()=>mt||Ct,Ue,Kn=!1,Nn=()=>{Ue=Is(),Ue||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Kn=!0},Hn=null,or=!1,Ht=null,it=!1,Lt=()=>{!Ht||it||(it=!0,Ht.close().catch(()=>{}))},Wt=null,ht=()=>{Wt!==null&&($.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"overlay_return",durationMs:$.elapsed(Wt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Wt=null)},Qt=!1,Yt=K.current,dn=null,hn=null,_t=[],$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)}},St=c=>{let s=c.getAttribute("src"),M=c.getAttribute("srcdoc"),m=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)"),m&&Se.push(`name=${m.slice(0,40)}`),G!==null&&Se.push(`sandbox="${G.slice(0,40)}"`),Se.join(" ")},wt=c=>{if(!(c instanceof HTMLIFrameElement))return"";try{let s=c.contentDocument;if(!s)return"cd=null";let M=s.body?.children.length??0,m=s.body?.innerHTML.length??0,G=s.head?.innerHTML.length??0;return`cd=same-origin readyState=${s.readyState} body[${M}children,${m}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"))&&(N(`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"))&&(N(`window:rejection ${s.slice(0,140)}`),Pn.push(s))};F&&typeof window<"u"&&(window.addEventListener("error",Wn),window.addEventListener("unhandledrejection",Gt));let Zt={value:0};if(F&&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);N(`net ${M}ms ${s.name.slice(0,90)}`)}}),hn.observe({type:"resource",buffered:!0})}catch{}let Nt=()=>{for(dn?.disconnect(),dn=null,hn?.disconnect(),hn=null;_t.length;)clearTimeout(_t.pop());F&&typeof window<"u"&&(window.removeEventListener("error",Wn),window.removeEventListener("unhandledrejection",Gt))},En=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()||En(c))return;let s=zn(c)??c;ct(()=>Te.current?.(s))},un=c=>{mt||(Oe(!0),c.includes("paypal_ineligible")||$.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,Ct=!0,Nt(),Lt();let m=s||oi(c);if(m&&I&&!E.current){E.current=!0,te(!1),k(!1),xe(!0),f.current?.("retrying"),Hn=setTimeout(()=>{mt||ke(G=>G+1)},_s);return}if(m||M){if(te(!1),k(!1),xe(!1),Oe(!0),f.current?.("exhausted"),!ie.current){ie.current=!0;let G=oi(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 xt=async(c,s=Ve.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 m=$.startTiming();$.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let G=()=>{$.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"processing",durationMs:$.elapsed(m),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Se=pt.current,tt=s?.accountPatch?.email??et.current,he=s?.accountPatch?.userId??Se?.customer?.id??Se?.accountData?.userId??"",y=await new Ko(Q,{telemetry:!1}).processPayment(he,{sessionId:M,nonce:s?.nonce??Je.current,tokenizedData:c,accountData:{userId:he,email:tt??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(y.ok){if(Ct||mt&&Fn.current)return;G(),$.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ct(()=>Ze.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ee())return;let D=await y.json().catch(()=>null),j=D?.message??"PayPal payment failed.",We=zn(j)??j;G(),y.status===400&&(typeof D?.declineCode=="string"||!Array.isArray(D?.fields))?$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):y.status===400||y.status===422?$.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):$.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:y.status>=500?"5xx":y.status>=400?"4xx":y.status>=300?"3xx":"unknown",failureCategory:y.status>=500?"server_error":void 0}),On(We),ct(()=>at.current?.(kt("paypal",We,{code:D?.code,declineCode:D?.declineCode})));return}catch(Se){if(Ee())return;G(),$.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let tt=Se instanceof Error?Se.message:"PayPal payment failed.",he=zn(tt)??tt;On(he),ct(()=>at.current?.(kt("paypal",he)));return}},g=()=>new ni("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),q=c=>Ee()?Promise.reject(g()):Promise.resolve(c),O=async c=>{if(Ee())throw g();Kn||Nn();let s=Ve.current,M=s?.sessionId??e,m=s?.nonce??Je.current;$.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let G=await new Ko(Q,{telemetry:!1}).createSessionIntent(M,m??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Ue});if(Ee())throw g();if(G.provider!=="paypal")throw new Error(c);return $.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),G.providerObjectId},pe=(c,s)=>{let M=s?.nonce??Je.current;if(!M)return;let m=s?.sessionId??e,G=yr(c)??Mn(c)??"provider_declined";new Ko(Q,{telemetry:!1}).reportSessionIntentDecline(m,M,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:G}).catch(()=>{})},H=ne;N("loadScript:scheduled (deferred 1 tick)");let se=null,C=setTimeout(()=>{if(mt){N("loadScript:skipped (cancelled before defer ran)");return}N("loadScript:start");let c=re==="live"?"production":re;se=ks({clientId:o,currency:u,intent:l?"subscription":"capture",vault:l?!0:void 0,...c?{environment:c}:{},...c==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),se.then(s=>{if(N(`loadScript:resolved inactive=${Ee()} ns=${!!s} buttons=${!!s?.Buttons}`),Ee())return;if(!s?.Buttons){N("FAIL: namespace missing Buttons factory"),en("PayPal SDK did not expose the Buttons factory.");return}$.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"provider_ready",durationMs:$.elapsed(de.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),$.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let M=async A=>{if(Ee()||Re.current!==H)return;let y=A.subscriptionID??A.orderID??"",D=y?Ye.current.get(y):It.current.get(H);if(!(!D||!Vt(D.generation))&&Ut(D.generation)){Ye.current.delete(y),It.current.delete(D.surfaceKey),ht();try{if(k(!0),ct(()=>Te.current?.(null)),!y)throw new ni("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await xt({id:y,isPaypal:!0},D)}catch(j){On(j instanceof Error?j.message:"PayPal capture failed.")}finally{Ee()||k(!1)}}},m=s.Buttons({style:{layout:"horizontal",height:co,tagline:!1},onClick:async(A,y)=>{if(Ee()){await y.reject();return}Nn();let D=be.current,j={};if(D)try{let Ot=await D("paypal");if(Ee()){await y.reject();return}if(!Ot.proceed){Ve.current=null,It.current.delete(H),await y.reject();return}j={sessionId:Ot.sessionId,accountPatch:Ot.accountPatch,nonce:Ot.nonce}}catch(Ot){N(`onClick:runBeforeButtonClick rejected msg=${(Ot instanceof Error?Ot.message:String(Ot)).slice(0,120)}`),Ve.current=null,It.current.delete(H),await y.reject();return}ct(()=>je.current?.("paypal"));let Tt={generation:Ln(),surfaceKey:H,...j};Ve.current=Tt,It.current.set(H,Tt),await y.resolve(),$.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),$.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),$.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Wt=$.startTiming()},createOrder:l?void 0:U?()=>q(U).then(Dt):()=>O("Failed to create PayPal order.").then(Dt),createSubscription:l?U?()=>q(U).then(Dt):()=>O("Failed to create PayPal subscription.").then(Dt):void 0,onApprove:M,onCancel:()=>{if(Ee())return;let A=It.current.get(H)??Ve.current;A&&It.current.delete(A.surfaceKey),Ve.current=null,ht(),$.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Pe.current=!0,Et({generation:A?.generation,remount:!0,focus:!1})},onError:A=>{if(Ee()||Re.current!==H)return;let y=A instanceof Error?A.message:"PayPal failed to render.";if(N(`onError rendered=${Qt} msg=${y.slice(0,120)}`),Qt){let D=It.current.get(H)??Ve.current;if(D&&!Vt(D.generation)||!D&&$e.current===Xe.current)return;if(En(y)){Ut(D?.generation);return}if(ht(),Or(A)){$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),pe(A,D),ct(()=>at.current?.(kt("paypal",y))),D&&It.current.delete(D.surfaceKey),Ve.current=null,Ut(D?.generation);return}let j=y.toLowerCase();$.error({errorCode:j.includes("popup")&&j.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),D&&It.current.delete(D.surfaceKey),Ve.current=null,Et({generation:D?.generation,remount:!0,showRetry:!0,focus:!0}),gn(A,{code:"paypal_runtime_failed"});return}en(y)}}),G=m.isEligible();if(N(`isEligible=${G}`),$.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=m,F&&N(`container:dims ${$t(Yt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),F&&typeof MutationObserver<"u"&&(dn=new MutationObserver(A=>{if(!Ee()){for(let y of A)if(y.type==="childList")y.addedNodes.forEach(D=>{if(!(D instanceof Element))return;let j=D.tagName.toLowerCase(),We=(D.getAttribute("title")??"").slice(0,40),Tt=j==="iframe"?` ${St(D)}`:"";N(`child+ ${j}${We?` title="${We}"`:""}${Tt} dims=${$t(D)}`)});else if(y.type==="attributes"&&y.target instanceof Element){let D=y.target;if(D.tagName.toLowerCase()!=="iframe")continue;let j=y.attributeName;(j==="src"||j==="srcdoc")&&N(`attr~ iframe ${j}=${j==="srcdoc"?`[${(D.getAttribute("srcdoc")??"").length}ch]`:Ae(D.getAttribute("src"))} dims=${$t(D)}`)}}}),dn.observe(Yt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let tt=A=>{if(Ee()||Qt)return;let y=Yt.querySelectorAll("iframe"),D=typeof document<"u"&&"hasStorageAccess"in document;N(`watchdog:${A} container=${$t(Yt)} children=${Yt.childElementCount} iframes=${y.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${D} paypalNetRequests=${Zt.value}`),y.forEach((j,We)=>{let Tt=(j.getAttribute("title")??"").slice(0,40);N(` iframe[${We}] ${$t(j)}${Tt?` title="${Tt}"`:""} ${St(j)}`);let Ot=wt(j);Ot&&N(` ${Ot}`)}),Pn.length===0&&N(" (no PayPal/zoid window errors captured)")};F&&(_t.push(setTimeout(()=>tt("3s"),3e3)),_t.push(setTimeout(()=>tt("8s"),8e3)),_t.push(setTimeout(()=>tt("15s"),15e3))),N("render:start");let he=$.startTiming();_t.push(setTimeout(()=>{Ee()||Qt||(N("watchdog:11s retryable render timeout"),en("PayPal Buttons render did not settle within 11000ms.",!0))},xs)),m.render(Yt).then(()=>{if(N(`render:resolved inactive=${Ee()}`),Nt(),Ee()){Lt();return}Qt=!0,te(!0),xe(!1),f.current?.("ready"),$.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"checkout_render",durationMs:$.elapsed(he),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(A=>{let y=A instanceof Error?A.message:"PayPal failed to render.";N(`render:rejected msg=${y.slice(0,120)}`),Nt(),en(y)})}).catch(s=>{let M=s instanceof Error?s.message:"PayPal SDK failed to load.";N(`loadScript:rejected msg=${M.slice(0,120)}`),en(M)})},0);return()=>{mt=!0,clearTimeout(C),Hn&&clearTimeout(Hn),Nt(),Lt()}},[I,Q,o,u,a,l,e,U,ne,$]);let nn=F?Ho("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})`,qe.length===0?`
|
|
6
|
+
`})]})})}import{FloPayError as ai,isMoneySettledOutcome as Fs,isSetupIntentClientSecret as nd}from"@flopay/shared";function ii(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 Jo(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 si(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],s=n.reduce((i,d)=>i+(d.overrideAmount??d.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(s*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,d)=>({uuid:`synthetic-${i.type??"item"}-${d}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Xo(e,t){return t?{...e,...t}:e}function It(e,t,n){let s=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:s,...a?{code:a}:{},...i?{declineCode:i}:{}}}var Ds=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Nn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:s}of Ds)if(n.test(t))return s;return e}function Zn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function yr(e){return e?.status==="authorized"||e?.status==="complete"}function li(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function mo(e){let t=li(e);return new ai(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function yo(e){let t=li(e);return new ai(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 fo(e,t){return e==="processing"||Fs(e,t)}function ci(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function di(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function qr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var go="flopay_recent_completion_";function fr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(go+e,JSON.stringify(t))}catch{}}function Qo(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(go+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(go+e),!1):!0}catch{return!1}}function ui(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 ho,useEffect as ht,useMemo as Vr,useRef as Qe,useState as tr}from"react";import{loadScript as zs}from"@paypal/paypal-js";import{PaymentAPI as Zo}from"@flopay/js";import{FloPayError as pi,SDK_VERSION as Os,generateIdempotencyKey as Ns,normalizeGatewayEnvironment as Us}from"@flopay/shared";function ut(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 Ls(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function er(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Mn(e){if(typeof e!="object"||e===null)return;let t=e;return er(t.code)??er(t.type)??er(t.name)}function gr(e){if(!(typeof e!="object"||e===null))return er(e.decline_code)}function jr(e){return typeof e!="object"||e===null?!1:er(e.type)?.toLowerCase()==="card_error"||gr(e)!==void 0}function Un(e){let t=Ls(e)?.toLowerCase()??"",s=`${Mn(e)?.toLowerCase()??""} ${t}`;return s.includes("popup")&&s.includes("block")}import{jsx as hr,jsxs as ea}from"react/jsx-runtime";var Po=45,$s=1e3,qs=11e3,js=["https://www.paypal.com","https://www.sandbox.paypal.com"],mi="We couldn't open PayPal. Try again or choose another payment method.",Vs={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 yi(e){return e.includes("No ack for postMessage init()")&&js.some(t=>e.includes(t))&&e.includes("10000ms")}function Ks(e){return e?`${mi} Allow pop-ups for this site, then try again.`:mi}function fi({sessionId:e,nonce:t,billingApiUrl:n,email:s,clientId:a,environment:i,currency:d,isSubscription:l,onTokenizedBody:C,onComplete:D,onErrorChange:h,onDecline:w,onTechnicalFailure:S,isProcessing:B=!1,onLoadStateChange:c,onInitializationStateChange:P,allowAutomaticRetry:k=!0,onButtonClick:I,runBeforeButtonClick:g,session:de,existingOrderId:_,telemetry:ae,telemetryContext:Z,debug:O=!1}){let J=bn(),H=Vr(()=>{if(J)return null;let F=co({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Os,enabled:ae!==!1});return F.setCheckoutContext(Z??{}),F.beginCheckout(Z??{}),F},[n,J,ae,Z?.checkoutMode,Z?.layout]),ie=Vr(()=>Mt(J),[J]);ht(()=>()=>{H&&H.flush().catch(()=>{}).finally(()=>H.destroy())},[H]);let j=Vr(()=>({error:F=>{ie?ie.error(F):H?.error(F)},log:F=>{ie?ie.log(F):H?.log(F)},performance:F=>{ie?ie.performance(F):H?.performance(F)},terminal:F=>{ie?ie.terminal(F):H?.terminal(F)},startTiming:()=>ie?.now()??H?.now()??0,elapsed:F=>ie?.elapsed(F)??Math.max(0,(H?.now()??F)-F)}),[ie,H]),V=Qe(null),le=Qe(0),Te=Qe(null),Pe=Qe(!1),[pe,ee]=tr(!1),[fe,Me]=tr(!1),[te,Ue]=tr(0),Fe=Qe(0),[ke,K]=tr(!1),v=Qe(!1),re=Qe(!1),[$e,ze]=tr(!1),[se,x]=tr(!1),oe=Vr(()=>n.replace(/\/+$/,""),[n]),W=Vr(()=>JSON.stringify([oe,a,d,i??"",l,e,_??""]),[oe,a,d,i,_,l,e]),Re=Qe(W),dt=Re.current!==W,[Ge,pt]=tr([]),M=F=>{O&&pt(ot=>[...ot,`${new Date().toISOString().slice(11,23)} ${F}`])},Y=Qe(C),Ze=Qe(D),qe=Qe(h),mt=Qe(w),Oe=Qe(S),He=Qe(I),Jt=Qe(c),Ye=Qe(P),Xt=Qe(g),R=Qe(de),ge=Qe(s),We=Qe(t),Ie=Qe(null),St=Qe(0),Ve=Qe(null),je=Qe(null),et=Qe(new Map),Je=Qe(new Map),Rn=Qe(!1);ht(()=>(Rn.current=!0,()=>{Rn.current=!1}),[]),ht(()=>{Y.current=C},[C]),ht(()=>{Ze.current=D},[D]),ht(()=>{qe.current=h},[h]),ht(()=>{mt.current=w},[w]),ht(()=>{Oe.current=S},[S]),ht(()=>{He.current=I},[I]),ht(()=>{Jt.current=c},[c]),ht(()=>{Ye.current=P},[P]),ht(()=>{Xt.current=g},[g]),ht(()=>{R.current=de},[de]),ht(()=>{ge.current=s},[s]),ht(()=>{We.current=t},[t]),ht(()=>{Fe.current=te},[te]),ht(()=>{ke&&Te.current?.focus()},[ke,te]);let rt=ho(()=>{window.setTimeout(()=>{Te.current?.focus()},0)},[]),Vn=ho(()=>{ee(!1),Ue(F=>F+1)},[]),Wt=ho(()=>{K(!1),(V.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??V.current)?.focus?.()},[]);ht(()=>{!pe||!Pe.current||(Pe.current=!1,Wt())},[Wt,pe,te]);let yn=ho((F,ot)=>{let Lt=Oe.current;if(Lt){Lt("paypal",F,ot);return}qe.current?.(Ks(ot?.popupBlocked??Un(F)))},[]),Qt=()=>{Ve.current?.timer&&(clearTimeout(Ve.current.timer),Ve.current.timer=null)},ar=()=>{Qt();let F=St.current+1;return St.current=F,je.current=null,Ve.current={generation:F,timer:null,yieldedControl:!1},K(!1),F},Bt=F=>F!==void 0&&Ve.current?.generation!==F?!1:(Qt(),Ve.current=null,je.current=null,!0),kt=F=>{let ot=F?.generation??Ve.current?.generation??St.current;(!F?.generation||Ve.current?.generation===ot)&&(Qt(),Ve.current=null),je.current=ot,F?.showRetry&&K(!0),F?.remount&&Vn(),F?.focus!==!1&&rt()},Zt=F=>Ve.current?.generation===F&&je.current!==F,en=F=>{typeof document<"u"&&document.visibilityState!=="visible"||(Qt(),F.timer=setTimeout(()=>{Ve.current?.generation===F.generation&&(Ve.current=null,je.current=F.generation,yn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),K(!0),Vn(),rt())},600))},Ft=()=>{let F=Ve.current;F?.yieldedControl&&en(F)},Dt=()=>{let F=Ve.current;F&&(F.yieldedControl=!0,Qt())},wt=F=>{let ot=Ie.current;return ot&&Je.current.set(F,ot),F};ht(()=>{let F=()=>{document.visibilityState==="visible"?Ft():Dt()};return document.addEventListener("visibilitychange",F),window.addEventListener("focus",Ft),window.addEventListener("blur",Dt),()=>{document.removeEventListener("visibilitychange",F),window.removeEventListener("focus",Ft),window.removeEventListener("blur",Dt),Qt()}},[]),ht(()=>{Re.current!==W&&(Re.current=W,v.current=!1,re.current=!1,ee(!1),Me(!1),ze(!1),Ye.current?.("loading"))},[W]),ht(()=>{ut(()=>Jt.current?.(pe&&!$e))},[pe,$e]);let Q=Us(i);ht(()=>{let F=a?`${a.slice(0,6)}\u2026(len ${a.length})`:"(empty)",ot=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(M(`mount clientId=${F} env=${i??"(unset)"}\u2192${Q??"live"} ccy=${d} sub=${l}`),M(`ua=${ot.slice(0,80)}${ot.length>80?"\u2026":""}`),!a){M("FAIL: clientId empty \u2014 gateway misconfigured"),ze(!0),j.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!V.current){M("FAIL: containerRef not attached");return}le.current=j.startTiming(),j.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Lt=!1,Dn=!1,Ae=()=>Lt||Dn,at,Ke=!1,In=()=>{at=Ns(),at||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Ke=!0},En=null,Ln=!1,Hn=null,_n=!1,tt=()=>{!Hn||_n||(_n=!0,Hn.close().catch(()=>{}))},zt=null,ln=()=>{zt!==null&&(j.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"overlay_return",durationMs:j.elapsed(zt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),zt=null)},Pt=!1,_t=V.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"),A=m.getAttribute("name"),y=m.getAttribute("sandbox"),U=[];return r&&U.push(`src=${$t(r)}`),f&&U.push(`srcdoc[${f.length}ch]`),!r&&!f&&U.push("src=(empty) srcdoc=(empty)"),A&&U.push(`name=${A.slice(0,40)}`),y!==null&&U.push(`sandbox="${y.slice(0,40)}"`),U.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,A=r.body?.innerHTML.length??0,y=r.head?.innerHTML.length??0;return`cd=same-origin readyState=${r.readyState} body[${f}children,${A}ch] head[${y}ch]`}catch(r){return`cd=cross-origin(${r.message.slice(0,30)})`}},yt=[],fn=m=>{if(Ae())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"))&&(M(`window:error ${r.slice(0,140)}`),yt.push(r))},Wn=m=>{if(Ae())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"))&&(M(`window:rejection ${r.slice(0,140)}`),yt.push(r))};O&&typeof window<"u"&&(window.addEventListener("error",fn),window.addEventListener("unhandledrejection",Wn));let jt={value:0};if(O&&typeof PerformanceObserver<"u")try{cn=new PerformanceObserver(m=>{if(!Ae())for(let r of m.getEntries()){if(!r.name.toLowerCase().includes("paypal"))continue;jt.value+=1;let f=Math.round(r.duration);M(`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());O&&typeof window<"u"&&(window.removeEventListener("error",fn),window.removeEventListener("unhandledrejection",Wn))},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")},zn=m=>{if(Ae()||Ot(m))return;let r=Nn(m)??m;ut(()=>qe.current?.(r))},On=m=>{Lt||(ze(!0),m.includes("paypal_ineligible")||j.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",m))},nn=(m,r=!1)=>{if(Lt)return;let f=v.current||!k;if(Ln)return;Ln=!0,Dn=!0,Vt(),tt();let A=r||yi(m);if(A&&k&&!v.current){v.current=!0,ee(!1),x(!1),Me(!0),Ye.current?.("retrying"),En=setTimeout(()=>{Lt||Ue(y=>y+1)},$s);return}if(A||f){if(ee(!1),x(!1),Me(!1),ze(!0),Ye.current?.("exhausted"),!re.current){re.current=!0;let y=yi(m)?"paypal_init_timeout":r?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",y)}return}On(m)};ze(!1);let Gt=async(m,r=Ie.current)=>{if(Ae())return;let f=r?.sessionId??e;if(Y.current){await Y.current(m,{sessionId:f,accountPatch:r?.accountPatch,nonce:r?.nonce});return}let A=j.startTiming();j.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let y=()=>{j.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"processing",durationMs:j.elapsed(A),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let U=R.current,Ee=r?.accountPatch?.email??ge.current,it=r?.accountPatch?.userId??U?.customer?.id??U?.accountData?.userId??"",$=await new Zo(oe,{telemetry:!1}).processPayment(it,{sessionId:f,nonce:r?.nonce??We.current,tokenizedData:m,accountData:{userId:it,email:Ee??U?.customer?.email??"",firstName:r?.accountPatch?.firstName??U?.customer?.firstName??U?.accountData?.firstName??"",lastName:r?.accountPatch?.lastName??U?.customer?.lastName??U?.accountData?.lastName??"",country:r?.accountPatch?.country??U?.customer?.country??U?.accountData?.country??void 0,zip:r?.accountPatch?.zip??U?.customer?.zip??U?.accountData?.zip??void 0}});if($.ok){if(Dn||Lt&&Rn.current)return;y(),j.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ut(()=>Ze.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ae())return;let p=await $.json().catch(()=>null),z=p?.message??"PayPal payment failed.",me=Nn(z)??z;y(),$.status===400&&(typeof p?.declineCode=="string"||!Array.isArray(p?.fields))?j.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):$.status===400||$.status===422?j.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):j.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:$.status>=500?"5xx":$.status>=400?"4xx":$.status>=300?"3xx":"unknown",failureCategory:$.status>=500?"server_error":void 0}),zn(me),ut(()=>mt.current?.(It("paypal",me,{code:p?.code,declineCode:p?.declineCode})));return}catch(U){if(Ae())return;y(),j.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ee=U instanceof Error?U.message:"PayPal payment failed.",it=Nn(Ee)??Ee;zn(it),ut(()=>mt.current?.(It("paypal",it)));return}},rn=()=>new pi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ne=m=>Ae()?Promise.reject(rn()):Promise.resolve(m),E=async m=>{if(Ae())throw rn();Ke||In();let r=Ie.current,f=r?.sessionId??e,A=r?.nonce??We.current;j.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let y=await new Zo(oe,{telemetry:!1}).createSessionIntent(f,A??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:at});if(Ae())throw rn();if(y.provider!=="paypal")throw new Error(m);return j.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),y.providerObjectId},L=(m,r)=>{let f=r?.nonce??We.current;if(!f)return;let A=r?.sessionId??e,y=gr(m)??Mn(m)??"provider_declined";new Zo(oe,{telemetry:!1}).reportSessionIntentDecline(A,f,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:y}).catch(()=>{})},T=te;M("loadScript:scheduled (deferred 1 tick)");let he=null,be=setTimeout(()=>{if(Lt){M("loadScript:skipped (cancelled before defer ran)");return}M("loadScript:start");let m=Q==="live"?"production":Q;he=zs({clientId:a,currency:d,intent:l?"subscription":"capture",vault:l?!0:void 0,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),he.then(r=>{if(M(`loadScript:resolved inactive=${Ae()} ns=${!!r} buttons=${!!r?.Buttons}`),Ae())return;if(!r?.Buttons){M("FAIL: namespace missing Buttons factory"),nn("PayPal SDK did not expose the Buttons factory.");return}j.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"provider_ready",durationMs:j.elapsed(le.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let f=async G=>{if(Ae()||Fe.current!==T)return;let $=G.subscriptionID??G.orderID??"",p=$?Je.current.get($):et.current.get(T);if(!(!p||!Zt(p.generation))&&Bt(p.generation)){Je.current.delete($),et.current.delete(p.surfaceKey),ln();try{if(x(!0),ut(()=>qe.current?.(null)),!$)throw new pi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Gt({id:$,isPaypal:!0},p)}catch(z){zn(z instanceof Error?z.message:"PayPal capture failed.")}finally{Ae()||x(!1)}}},A=r.Buttons({style:{layout:"horizontal",height:Po,tagline:!1},onClick:async(G,$)=>{if(Ae()){await $.reject();return}In();let p=Xt.current,z={};if(p)try{let xe=await p("paypal");if(Ae()){await $.reject();return}if(!xe.proceed){Ie.current=null,et.current.delete(T),await $.reject();return}z={sessionId:xe.sessionId,accountPatch:xe.accountPatch,nonce:xe.nonce}}catch(xe){M(`onClick:runBeforeButtonClick rejected msg=${(xe instanceof Error?xe.message:String(xe)).slice(0,120)}`),Ie.current=null,et.current.delete(T),await $.reject();return}ut(()=>He.current?.("paypal"));let we={generation:ar(),surfaceKey:T,...z};Ie.current=we,et.current.set(T,we),await $.resolve(),j.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),zt=j.startTiming()},createOrder:l?void 0:_?()=>Ne(_).then(wt):()=>E("Failed to create PayPal order.").then(wt),createSubscription:l?_?()=>Ne(_).then(wt):()=>E("Failed to create PayPal subscription.").then(wt):void 0,onApprove:f,onCancel:()=>{if(Ae())return;let G=et.current.get(T)??Ie.current;G&&et.current.delete(G.surfaceKey),Ie.current=null,ln(),j.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Pe.current=!0,kt({generation:G?.generation,remount:!0,focus:!1})},onError:G=>{if(Ae()||Fe.current!==T)return;let $=G instanceof Error?G.message:"PayPal failed to render.";if(M(`onError rendered=${Pt} msg=${$.slice(0,120)}`),Pt){let p=et.current.get(T)??Ie.current;if(p&&!Zt(p.generation)||!p&&je.current===St.current)return;if(Ot($)){Bt(p?.generation);return}if(ln(),jr(G)){j.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),L(G,p),ut(()=>mt.current?.(It("paypal",$))),p&&et.current.delete(p.surfaceKey),Ie.current=null,Bt(p?.generation);return}let z=$.toLowerCase();j.error({errorCode:z.includes("popup")&&z.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),p&&et.current.delete(p.surfaceKey),Ie.current=null,kt({generation:p?.generation,remount:!0,showRetry:!0,focus:!0}),yn(G,{code:"paypal_runtime_failed"});return}nn($)}}),y=A.isEligible();if(M(`isEligible=${y}`),j.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!y){ee(!1),nn("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Hn=A,O&&M(`container:dims ${Ut(_t)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),O&&typeof MutationObserver<"u"&&(tn=new MutationObserver(G=>{if(!Ae()){for(let $ of G)if($.type==="childList")$.addedNodes.forEach(p=>{if(!(p instanceof Element))return;let z=p.tagName.toLowerCase(),me=(p.getAttribute("title")??"").slice(0,40),we=z==="iframe"?` ${_e(p)}`:"";M(`child+ ${z}${me?` title="${me}"`:""}${we} dims=${Ut(p)}`)});else if($.type==="attributes"&&$.target instanceof Element){let p=$.target;if(p.tagName.toLowerCase()!=="iframe")continue;let z=$.attributeName;(z==="src"||z==="srcdoc")&&M(`attr~ iframe ${z}=${z==="srcdoc"?`[${(p.getAttribute("srcdoc")??"").length}ch]`:$t(p.getAttribute("src"))} dims=${Ut(p)}`)}}}),tn.observe(_t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ee=G=>{if(Ae()||Pt)return;let $=_t.querySelectorAll("iframe"),p=typeof document<"u"&&"hasStorageAccess"in document;M(`watchdog:${G} container=${Ut(_t)} children=${_t.childElementCount} iframes=${$.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${p} paypalNetRequests=${jt.value}`),$.forEach((z,me)=>{let we=(z.getAttribute("title")??"").slice(0,40);M(` iframe[${me}] ${Ut(z)}${we?` title="${we}"`:""} ${_e(z)}`);let xe=qt(z);xe&&M(` ${xe}`)}),yt.length===0&&M(" (no PayPal/zoid window errors captured)")};O&&(Yt.push(setTimeout(()=>Ee("3s"),3e3)),Yt.push(setTimeout(()=>Ee("8s"),8e3)),Yt.push(setTimeout(()=>Ee("15s"),15e3))),M("render:start");let it=j.startTiming();Yt.push(setTimeout(()=>{Ae()||Pt||(M("watchdog:11s retryable render timeout"),nn("PayPal Buttons render did not settle within 11000ms.",!0))},qs)),A.render(_t).then(()=>{if(M(`render:resolved inactive=${Ae()}`),Vt(),Ae()){tt();return}Pt=!0,ee(!0),Me(!1),Ye.current?.("ready"),j.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"checkout_render",durationMs:j.elapsed(it),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(G=>{let $=G instanceof Error?G.message:"PayPal failed to render.";M(`render:rejected msg=${$.slice(0,120)}`),Vt(),nn($)})}).catch(r=>{let f=r instanceof Error?r.message:"PayPal SDK failed to load.";M(`loadScript:rejected msg=${f.slice(0,120)}`),nn(f)})},0);return()=>{Lt=!0,clearTimeout(be),En&&clearTimeout(En),Vt(),tt()}},[k,oe,a,d,i,l,e,_,te,j]);let Kn=O?ea("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=${pe} failed=${$e})`,Ge.length===0?`
|
|
7
7
|
(waiting for first lifecycle event\u2026)`:`
|
|
8
|
-
${
|
|
9
|
-
`)}`]}):null;return
|
|
8
|
+
${Ge.join(`
|
|
9
|
+
`)}`]}):null;return $e&&!dt?O?hr("div",{children:Kn}):null:ea("div",{children:[Kn,ea("div",{"aria-hidden":fe?!0:void 0,style:fe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Po},children:[!pe&&!fe&&hr("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"}}),hr("div",{ref:V,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:Po,display:"flex",opacity:pe?1:0},"aria-busy":se||B},te)]},te),ke&&hr("button",{ref:Te,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Wt,style:Vs,children:"Try PayPal again"})]})}function bo(e){return hr(fi,{...e})}function gi(e){return hr(fi,{...e})}import{FloPayError as Sn,isSetupIntentClientSecret as ll,resolveTheme as cl}from"@flopay/shared";import{Fragment as Pr,jsx as u,jsxs as Le}from"react/jsx-runtime";var wn="flopay_stripe_resume",Ci="flopay_wallet_resume",Kr="flopay_paypal_resume",dl=250,Si="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ca(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function So({billingApiUrl:e,sessionId:t,nonce:n,request:s}){if(!(!t||!n))try{await new $n(e,{telemetry:!1}).reportSessionIntentDecline(t,n,s)}catch{}}function ul(e){return e instanceof Sn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ra(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function vo(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let s=parseInt(n[1],16),a=Math.max(0,Math.min(1,1-t)),i=Math.round((s>>16&255)*a),d=Math.round((s>>8&255)*a),l=Math.round((s&255)*a);return`#${(1<<24|i<<16|d<<8|l).toString(16).slice(1)}`}var pl=`
|
|
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 @@ ${qe.join(`
|
|
|
27
27
|
0% { opacity: 1; transform: translateX(0) scale(1); }
|
|
28
28
|
100% { opacity: 0; transform: translateX(16px) scale(0.97); }
|
|
29
29
|
}
|
|
30
|
-
`,mo=44;function ta(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 Zs={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Ci={width:"100%",minHeight:mo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function el(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function mi(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Si(e){return e==="paypal"?"PayPal":hr(e)}function tl(e,t){let n=`We couldn't open ${Si(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function wi(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]),h=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]),_=we(()=>{let d=i.current;d&&(d.yieldedControl=!0,o(d))},[o]);return Qe(()=>{let d=()=>{document.visibilityState==="visible"?S():_()},b=()=>{_()};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,_,S]),{startAttempt:l,finishAttempt:w,invalidateAttempt:B,isAttemptInvalidated:h,isAttemptCurrent:R}}function nl(e){let t=Us(e);return`Enter a valid ${Jo(e)}${t?` (e.g. ${t})`:""}`}function rl(e,t,n){let i=Os(e),o=t.trim(),a=n&&i,u=a&&!o,l=a&&!!o&&!zs(e,o);return{visible:n,supported:i,required:a,empty:u,malformed:l}}function yi(e,t){return t instanceof wn?t:new wn(t instanceof Error?t.message:`${el(e)} before-click hook failed.`,"validation_error")}function Go(){return p("style",{children:Qs})}function ol(e){return typeof e=="number"?`${e}px`:e}function fi(e){if(typeof e=="number"||typeof e=="string")return e}function ki(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function Ri({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 gi(e){return e!=="unavailable"&&e!=="load_error"}function na(e){return p(il,{...e})}function hi({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:o,onErrorChange:a,isProcessing:u=!1,onButtonClick:l,onDecline:w,onTechnicalFailure:B,runBeforeButtonClick:h,onLoadStateChange:R,placeholderBorderRadius:S}){let _=vn(),d=Zo(),b=Qo(),[I,x]=ve("loading");Qe(()=>{R?.(I)},[I,R]);let[P,ae]=ve(!1),U=Be(!1),le=Be(null),ee=Be(null),[F,J]=ve(0),[W,ce]=ve(!1),$=Be(!1),K=Be(new Map),{startAttempt:de,finishAttempt:_e,invalidateAttempt:Pe,isAttemptInvalidated:ye,isAttemptCurrent:te}=wi((Y,E,ie)=>{B?.(Y,E,{...ie,popupBlocked:ie?.popupBlocked??Un(E)}),ce(!0),J(Ne=>Ne+1)});Qe(()=>{W&&ee.current?.focus()},[W,F]);let ge=we(()=>{J(Y=>Y+1)},[]),xe=we((Y,E,ie)=>{Pe(ie),B?.("paypal",Y,{code:E,popupBlocked:Un(Y)}),ce(!0),ge()},[Pe,B,ge]),ne=we(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);Qe(()=>{$.current&&($.current=!1,ne())},[ne,F]);let ke=we(()=>{ce(!1),a?.(null),ne()},[ne,a]);Qe(()=>{if(!d||U.current)return;let Y=new URLSearchParams(window.location.search),E=Y.get("payment_intent"),ie=Y.get("payment_intent_client_secret"),Ne=Y.get("redirect_status");if(!E||!ie)return;U.current=!0;let Oe;try{let k=localStorage.getItem(Ur);if(k){let Q=JSON.parse(k);Q.clientSecret===ie&&(Oe={...Q.accountPatch?{accountPatch:Q.accountPatch}:{},...Q.sessionId?{sessionId:Q.sessionId}:{},...Q.nonce?{nonce:Q.nonce}:{}})}}catch{}try{localStorage.removeItem(Ur)}catch{}let ue=new URL(window.location.href);ue.searchParams.delete("payment_intent"),ue.searchParams.delete("payment_intent_client_secret"),ue.searchParams.delete("redirect_status"),window.history.replaceState({},"",ue.toString()),(async()=>{try{if(ae(!0),Ne==="failed"){let Z="PayPal payment was declined. Please try again.";a?.(Z),w?.(kt("paypal",Z));return}let{paymentIntent:k,error:Q}=await d.retrievePaymentIntent(ie);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?.(kt("paypal",Z))}}catch(k){a?.(k instanceof Error?k.message:"Failed to complete PayPal payment.")}finally{ae(!1)}})()},[d,o,a,w]);let Re=we(async Y=>{if(u||P){Y.reject();return}let E=h?await h("paypal"):{proceed:!0};if(!E.proceed){K.current.delete(F),Y.reject();return}let ie=de("paypal");K.current.set(F,{generation:ie,accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}),ce(!1),l?.("paypal"),Y.resolve()},[K,u,l,h,de,P,F]),Ce=we(async Y=>{if(!d||!b)return;let E=K.current.get(F);if(E&&!te(E.generation)){K.current.delete(F);return}if(!E&&ye()||E&&!_e(E.generation))return;E||_e();let ie=E??null;if(K.current.delete(F),!ie&&h){let k=await h("paypal");if(!k.proceed){Y.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ie={accountPatch:k.accountPatch,sessionId:k.sessionId,nonce:k.nonce}}let Ne=ie?.sessionId??e,Oe=ie?.nonce??t,ue=ie?.accountPatch?.email??n;try{if(ae(!0),a?.(null),!Ne||!ue)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,qe={return_url:window.location.href};if(Z?.id&&(qe.payment_method=Z.id),typeof window<"u")try{localStorage.setItem(Ur,JSON.stringify({clientSecret:ut,sessionId:Ne,nonce:Oe,accountPatch:ie?.accountPatch}))}catch{}let{error:ot,paymentIntent:N}=await d.confirmPayment({clientSecret:ut,confirmParams:qe,redirect:"if_required"});if(ot){if(typeof window<"u")try{localStorage.removeItem(Ur)}catch{}if(Or(ot)){let Ze=ot.message??"Your payment was declined.";a?.(Ze),w?.(kt("paypal",Ze,{code:Mn(ot),declineCode:yr(ot)})),await yo({billingApiUrl:i,sessionId:Ne,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(ot)??"provider_declined"}})}else xe(ot,"stripe_paypal_confirm_failed",E?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Ur)}catch{}let V=typeof N?.payment_method=="string"?N.payment_method:N?.payment_method?.id;o({id:V??N?.id,type:"card",threeDSecureActionResultTokenId:N?.id,isPaypal:!0},{accountPatch:ie?.accountPatch,sessionId:Ne,nonce:Oe});return}catch(k){xe(k,"stripe_paypal_failed",E?.generation)}finally{ae(!1)}},[d,b,e,t,n,i,o,a,w,h,xe,_e,te,ye,F]);return Le(gr,{children:[p(Ri,{state:I,placeholderTestId:"flopay-paypal-placeholder",borderRadius:S,children:Le("div",{ref:le,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:Ci,children:"Try PayPal again"}),p(vi,{onReady:Y=>x(ki(Y,["paypal"])),onLoadError:()=>{x("load_error"),ea(At(_),"paypal","paypal")},onClick:Re,onConfirm:Ce,onCancel:()=>{let Y=K.current.get(F);K.current.delete(F),At(_)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Pe(Y?.generation),ce(!1),$.current=!0,ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},F)]})}),P&&p(Sn,{status:"processing"})]})}function Pi({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:o,expressMethods:a,onTokenizedBody:u,onErrorChange:l,onButtonClick:w,onDecline:B,onTechnicalFailure:h,runBeforeButtonClick:R,onLoadStateChange:S,placeholderBorderRadius:_}){let d=vn(),b=Zo(),I=Qo(),[x,P]=ve("loading");Qe(()=>{S?.(x)},[x,S]);let[ae,U]=ve(!1),le=Be(null),ee=Be(null),[F,J]=ve(0),[W,ce]=ve(!1),[$,K]=ve("google_pay"),de=Be(!1),_e=Be("google_pay"),Pe=Be("google_pay"),ye=Be(new Map),{startAttempt:te,finishAttempt:ge,invalidateAttempt:xe,isAttemptInvalidated:ne,isAttemptCurrent:ke}=wi((ue,k,Q)=>{h?.(ue,k,{...Q,popupBlocked:Q?.popupBlocked??Un(k)}),K(ue),ce(!0),J(Z=>Z+1)});Qe(()=>{W&&ee.current?.focus()},[W,F]);let Re=we(()=>{J(ue=>ue+1)},[]),Ce=we((ue,k,Q,Z)=>{xe(Z),h?.(ue,k,{code:Q,popupBlocked:Un(k)}),K(ue),ce(!0),Re()},[xe,h,Re]),Y=we(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);Qe(()=>{de.current&&(de.current=!1,Y())},[Y,F]);let E=we(()=>{ce(!1),l?.(null),Y()},[Y,l]),ie=we(async ue=>{if(!b||!I)return;let k=ye.current.get(F);if(k&&!ke(k.generation)){ye.current.delete(F);return}if(!k&&ne()||k&&!ge(k.generation))return;k||ge();let Q=ue.expressPaymentType??k?.method??_e.current,Z=k??null;ye.current.delete(F);let ze=mi(Q);if(!Z&&R){let V=await R(ze);if(!V.proceed){ue.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}Z={accountPatch:V.accountPatch,sessionId:V.sessionId,nonce:V.nonce}}let ut=ze,qe=Z?.sessionId??e,ot=Z?.nonce??t,N=Z?.accountPatch?.email??n;try{U(!0),l?.(null);let{error:V}=await I.submit();if(V){Ce(Q,V,"stripe_wallet_submit_failed",k?.generation);return}let{error:Ze,paymentMethod:Te}=await b.createPaymentMethod({elements:I});if(Ze||!Te){Ce(Q,Ze??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",k?.generation);return}if(!qe||!N)throw new Error("Missing sessionId or email for wallet payment");let at=await new $n(i).createSessionIntent(qe,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 He=at.clientSecret,{error:je,intentId:ln}=Ys(He)?await b.confirmCardSetup(He,{payment_method:Te.id}).then(f=>({error:f.error,intentId:f.setupIntent?.id})):await b.confirmCardPayment(He,{payment_method:Te.id}).then(f=>({error:f.error,intentId:f.paymentIntent?.id}));if(je){if(Or(je)){let f=je.message??"Your payment was declined.";l?.(f),B?.(kt(ut,f,{code:Mn(je),declineCode:yr(je)})),await yo({billingApiUrl:i,sessionId:qe,nonce:ot,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Q??ze,providerDeclineReason:Mn(je)??"provider_declined"}})}else Ce(Q,je,"stripe_wallet_confirm_failed",k?.generation);return}u({id:Te.id,type:"card",threeDSecureActionResultTokenId:ln},{accountPatch:Z?.accountPatch,sessionId:qe,nonce:ot})}catch(V){Ce(Q,V,"stripe_wallet_failed",k?.generation)}finally{U(!1)}},[b,I,e,t,n,i,o,u,l,B,R,Ce,ge,ke,ne,F]),Ne=nt(()=>{let ue=["applePay","googlePay","paypal","link","amazonPay","klarna"],k=new Set(["applePay","googlePay"]),Q=new Set(a.map(di)),Z={};for(let ze of ue)Q.has(ze)?Z[ze]=k.has(ze)?"always":"auto":Z[ze]="never";return Z},[a]),Oe=nt(()=>a.map(di),[a]);return Le(gr,{children:[p(Ri,{state:x,placeholderTestId:"flopay-wallet-placeholder",borderRadius:_,children:Le("div",{ref:le,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:Ci,children:["Try ",Si($)," again"]}),p(vi,{onReady:ue=>{P(ki(ue,Oe))},onLoadError:ue=>{P("load_error"),ea(At(d),"stripe","wallet")},onClick:async ue=>{_e.current=ue.expressPaymentType,Pe.current=mi(ue.expressPaymentType);let k=R?await R(Pe.current):{proceed:!0};if(!k.proceed){ye.current.delete(F),ue.reject();return}let Q=te(ue.expressPaymentType);ye.current.set(F,{generation:Q,method:ue.expressPaymentType,accountPatch:k.accountPatch,sessionId:k.sessionId,nonce:k.nonce}),ce(!1),w?.(Pe.current),ue.resolve()},onConfirm:ie,onCancel:()=>{let ue=ye.current.get(F);ye.current.delete(F),At(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),xe(ue?.generation),ce(!1),de.current=!0,Re()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ne,layout:{maxColumns:1,overflow:"never"}}},F)]})}),ae&&p(Sn,{status:"processing"})]})}function al({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:h,fontFamily:R}){let S=js(e,t),_=Ja[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:mo,padding:"0 1rem",backgroundColor:d,color:I,border:`1px solid ${b}`,borderRadius:h??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:qs(e)?8:0},children:[_?p("img",{src:_,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):S?.logoSvg?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 Xo({method:e,sessionId:t,nonce:n,email:i,billingName:o,billingApiUrl:a,onTokenizedBody:u,onErrorChange:l,onDecline:w,onCancel:B,runBeforeButtonClick:h,onButtonClick:R,isProcessing:S,submitButtonColor:_,submitButtonBorderRadius:d,submitButtonStyle:b,errorText:I}){let x=vn(),P=Zo(),ae=Qo(),[U,le]=ve(!1),ee=Be(!1),[F,J]=ve(!1),[W,ce]=ve("loading"),$=we(async()=>{if(!P||!ae||S||ee.current||!F)return;ee.current=!0,le(!0);let K=h?await h("card"):{proceed:!0};if(!K.proceed){ee.current=!1,le(!1);return}R?.("card");let de=K.sessionId??t,_e=K.nonce??n,Pe=K.accountPatch?.email??i;try{l?.(null);let ye=await ae.submit();if(ye.error){l?.(ye.error.message??"Payment failed.");return}let te=await P.createPaymentMethod({elements:ae});if(te.error||!te.paymentMethod){l?.(te.error?.message??"Failed to create payment method.");return}let ge=te.paymentMethod;if(!de||!Pe)throw new Error("Missing sessionId or email for payment.");let xe=ge.type||e,ne=await new $n(a).createSessionIntent(de,_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:de,nonce:_e,accountPatch:K.accountPatch,paymentMethodId:ge.id,paymentMethodType:ge.type??e,gateway:"stripe"}))}catch{}let{error:Re,paymentIntent:Ce}=await P.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 ie=Re.message??"Payment failed.";l?.(ie),w?.(kt("card",ie,{code:Re.code})),await yo({billingApiUrl:a,sessionId:de,nonce:_e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Re.code??"provider_declined"}});return}let Y=Ce?.status;if(!ao(Y)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ie=Y==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";l?.(ie),w?.(kt("card",ie,{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:de,nonce:_e})}catch(ye){l?.(ye instanceof Error?ye.message:"Payment failed. Please try again.")}finally{ee.current=!1,le(!1)}},[P,ae,S,F,h,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(As,{onReady:()=>ce("ready"),onLoadError:()=>{ce("load_error"),ea(At(x),"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:()=>{$()},disabled:!F||U||S||W!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:_,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!F||U||S||W!=="ready"?"not-allowed":"pointer",opacity:!F||U||S||W!=="ready"?.5:1,transition:"opacity 120ms ease-out",...b??{}},children:U?"Processing\u2026":`Pay with ${hr(e)}`}),I&&p(ur,{margin:"0.75rem 0 0",children:I})]})}function bi({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:o,paymentElementMethods:a,stripeInstance:u,paymentElementBaseOptions:l,onTokenizedBody:w,onErrorChange:B,onButtonClick:h,onDecline:R,runBeforeButtonClick:S,onLoadStateChange:_,isProcessing:d=!1,submitButtonColor:b="#4A49FF",submitButtonBorderRadius:I=8,submitButtonStyle:x,buttonAppearance:P,themeId:ae,onExpandApm:U,expandedApmMethod:le}){let[ee,F]=ve(null),[J,W]=ve(null),ce=Be(!1);Qe(()=>{a.length>0&&u?_?.("ready"):u||_?.("loading")},[a.length,u,_]);let $=we(async te=>{if(!u||ce.current||d)return;ce.current=!0,W(te);let ge=S?await S("card"):{proceed:!0};if(!ge.proceed){ce.current=!1,W(null);return}h?.("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?.(kt("card",Oe,{code:Y.code})),await yo({billingApiUrl:o,sessionId:xe,nonce:ne,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,providerDeclineReason:Y.code??"provider_declined"}});return}let ie=E?.status;if(!ao(ie)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Oe=ie==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";B?.(Oe),R?.(kt("card",Oe,{code:ie??"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{ce.current=!1,W(null)}},[u,d,S,h,e,t,n,o,i,w,B,R]),[K,de]=ve(null),_e=U?le??null:K,Pe=we(te=>{ce.current||d||_e&&_e!==te||(ci(te)?U?U(te):de(te):$(te))},[_e,d,$,U]),ye=nt(()=>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=le===te,xe=J===te,ne=J!==null&&J!==te||le!=null&&le!==te;return Le(Hs.Fragment,{children:[p(al,{method:te,themeId:ae,submitting:xe,disabled:ne,highlighted:ge,hasNextStep:ci(te),onClick:()=>Pe(te),backgroundColor:P?.backgroundColor,borderColor:P?.borderColor,textColor:P?.textColor,borderRadius:P?.borderRadius,fontFamily:P?.fontFamily}),!U&&K===te&&ye&&u&&p(tr,{stripe:u,options:ye,children:p(Xo,{method:te,sessionId:e,email:n,billingName:i,billingApiUrl:o,onTokenizedBody:w,onErrorChange:B,onDecline:R,onCancel:()=>de(null),runBeforeButtonClick:S,onButtonClick:h,isProcessing:d,submitButtonColor:b,submitButtonBorderRadius:I,submitButtonStyle:x})},te)]},te)})})}function il({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:o,onComplete:a,onError:u,onDecline:l,onTokenizedBody:w,firstName:B,lastName:h,chv:R,className:S,isProcessing:_,error:d,onErrorChange:b,showPayPal:I=!0,showStripe:x=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:ae,showApplePay:U=!0,showGooglePay:le=!0,layout:ee="default",theme:F,buttonsTheme:J,buttonsStyles:W,appearance:ce,cardButtonContent:$,cardBackButtonContent:K,cardTitleContent:de,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:ie,onCountryChange:Ne,onZipChange:Oe,avsCheck:ue,checkoutType:k,checkoutLayout:Q,totalAmount:Z=0,currency:ze="usd",initialCardOpen:ut=!1,directPaypal:qe,isSubscription:ot=!1,session:N,dataAttachmentPending:V=!1,debug:Ze=!1}){let Te=vn(),at=Uo(),He=Ws(yn),je=V||He.claimPending===!0,ln=oo(),[f,be]=ve(!1),[pt,et]=ve(null),[Je,Ve]=ve(ke??"US"),[Xe,Ie]=ve(Re??""),[$e,It]=ve(Ce??""),[Ye,Fn]=ve(Y??""),[vt,Dn]=ve(E??""),[cn,gn]=ve(ie??""),[tn,Ln]=ve({}),Ut=Be(Re??""),Et=Be(ke??"US"),Vt=Be(Ce??""),Xt=Be(Y??""),Ft=Be(E??""),Kt=Be(ie??""),Dt=Be({});Qe(()=>{let r=(v,z,X,L,fe)=>{if(Dt.current[v])return;let Fe=z?.trim();!Fe||Fe===X.current||(X.current=Fe,L(Fe),fe?.(Fe))};r("country",ke,Et,Ve,Ne),r("zip",Re,Ut,Ie,Oe),r("addressLine1",Ce,Vt,It),r("addressLine2",Y,Xt,Fn),r("city",E,Ft,Dn),r("state",ie,Kt,gn)},[ke,Re,Ce,Y,E,ie,Ne,Oe]);let re=nt(()=>Ns(te),[te]),nn=re!==null,T=!!N?.vault?.html,gt=!!N?.gateways?.pcivault,Ct=!!(N?.gateways?.stripe?.enabledPaymentMethods??P)?.includes("card"),Ee=T||Ct||gt,Ue=!!(x&&Ee&&Te&&e),[Kn,Nn]=ve(()=>ee!=="buttons"||ut?e??null:null),[Hn,or]=ve(0),Ht=ee!=="buttons"||ut||!!e&&Kn===e,it=nt(()=>!Te||!Ue||!e||!Ht?null:Te.cardCapture({sessionId:e}),[Te,Ue,e,Ht]),Lt=nt(()=>{let r=Je,v=re?De(re.postal_code,r):!1;return rl(r,Xe,v)},[re,Je,Xe]),{avsInvalid:Wt,invalidAvsFields:ht}=nt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!Ue||!re)return{avsInvalid:!1,invalidAvsFields:r};let v=Je,z=(fe,Fe)=>De(fe,v)&&!Fe.trim(),X={line1:z(re.address_line_1,$e),city:z(re.city,vt),state:z(re.state,cn),zip:Lt.empty||Lt.malformed};return{avsInvalid:X.line1||X.city||X.state||X.zip,invalidAvsFields:X}},[Ue,re,Je,$e,vt,cn,Lt]),[Qt,Yt]=ve(!1),[dn,hn]=ve(!1),[_t,$t]=ve(()=>Yo(N?.vault)),[Ae,St]=ve(ut&&Ee?"card":"buttons"),[wt,Pn]=ve(null),Wn=Ae==="expanding"||Ae==="card",Gt=280,Zt=Be(null),Nt=we(r=>{Zt.current&&clearTimeout(Zt.current),Zt.current=setTimeout(()=>{Zt.current=null,r()},Gt)},[Gt]);Qe(()=>()=>{Zt.current&&clearTimeout(Zt.current)},[]);let En=we(()=>{Nn(e??null),or(r=>r+1),St("expanding"),Nt(()=>St("card"))},[Nt,e]),On=we(()=>{St("collapsing"),Nt(()=>St("buttons"))},[Nt]),un=we(r=>{Pn(r),St("apm-expanding"),Nt(()=>St("apm-form"))},[Nt]),en=we(()=>{St("apm-collapsing"),Nt(()=>{St("buttons"),Pn(null)})},[Nt]);Qe(()=>{ee==="buttons"&&ut&&Ee&&(Nn(e??null),St("card"))},[ee,ut,Ee,e]);let[xt,g]=ve(null),q=Be(!1),O=Be(null),pe=Be("idle"),[H,se]=ve(null),C=Be(H);Qe(()=>{C.current=H},[H]);let c=n||ln,s=d??pt,M=nt(()=>Gs(F),[F]),m=nt(()=>{let r=M?.buttonsLayout??Fs(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=ce??M?.appearance,Se=nt(()=>{let r=G?.variables,v=Fe=>typeof Fe=="string"&&Fe?Fe:void 0,z=m.submitButton,X=v(r?.colorPrimary)??v(z?.backgroundColor)??"#4A49FF",L=ee==="buttons",fe=m.nameInput;return{primaryColor:X,primaryHoverColor:v(r?.colorPrimaryHover)??po(X,.12),inputBackgroundColor:v(m.cardInputBackground)??v(r?.colorBackground)??"#ffffff",textColor:v(m.cardInputColor)??v(fe?.color)??v(r?.colorText)??"#262833",borderColor:v(m.cardInputBorder)??(L?"#e5e7eb":"#A4A4FF"),placeholderColor:v(m.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(fe?.fontFamily)??v(r?.fontFamily)??"Poppins, sans-serif",fontSize:v(m.cardInputFontSize)??v(r?.fontSizeBase)??"16px",fontWeight:String(fi(fe?.fontWeight)??400),borderRadius:v(r?.borderRadius)??"8px"}},[G,m,ee]),tt=He.inlineSessionPatchProcessing??!1,he=(_??f)||tt,A=c.replace(/\/+$/,""),y=nt(()=>jo({userId:o,email:i,firstName:B,lastName:h,country:ke,zip:Re},tn),[o,i,B,h,ke,Re,tn]),D=[y.firstName,y.lastName].filter(r=>!!r?.trim()).join(" "),j=nt(()=>Te?Te.getRawProvider():null,[Te]),We=nt(()=>at?at.getRawProvider():null,[at]),Tt=Z||100,Ot=nt(()=>G?Ks(G):null,[G]),Kr=Ot?{appearance:Ot}:null,ga=nt(()=>{let r=Ot??{},v=r.rules??{};return{...r,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[Ot]),ha=nt(()=>{let r=ei(Z);return{...r,currency:ze.toLowerCase(),paymentMethodCreation:"manual",...r.mode==="payment"?{captureMethod:"manual"}:{},...Kr}},[Z,ze,Kr]),Pa=nt(()=>({mode:"payment",amount:Tt,currency:ze.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Kr}),[Tt,ze,Kr]),me=we(r=>{et(r),b?.(r)},[b]);Qe(()=>{!Ue||!it||it.setCardFieldOrder?.(ge??null,re==null)},[Ue,it,ge,re]),Qe(()=>{(Ae==="expanding"||Ae==="collapsing"||Ae==="apm-expanding"||Ae==="apm-collapsing")&&me(null)},[Ae,me]);let pn=we((r,v,z)=>{l?.(kt(r,v,z))},[l]),ar=we((r,v,z)=>{let X=z?.popupBlocked??Un(v),L=tl(r,X),fe=Zn(z?.code)??Mn(v)??"external_payment_method_failed",Fe=new wn(L,"api_error",{code:"external_payment_method_failed",param:r});g(null),ee==="buttons"&&(St("buttons"),Pn(null)),me(L),u?.(Fe),console.error("[FloPay] External payment method failed:",{method:r,code:fe,popupBlocked:X})},[ee,u,me]);Qe(()=>{if(!Ue||!e){$t(null);return}let r=Yo(N?.vault);if(r){$t(r);return}if(!Ht){$t(null);return}$t(null);let v=!0;return new $n(A).getVaultCapture(e,t).then(z=>{if(!v)return;let X=Yo(z);X?$t(X):me("Failed to load the secure card form.")}).catch(z=>{v&&me(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{v=!1}},[Ue,Ht,Hn,e,N?.vault?.html,N?.vault?.messageToken,N?.vault?.expectedOrigin,A,t,me]);let _n=Be({onComplete:a,onError:u,updateError:me,emitDecline:pn,resolvedAccount:y,avsConfig:re,avsCheckProp:ue,sessionId:e,nonce:t,baseUrl:A});_n.current={onComplete:a,onError:u,updateError:me,emitDecline:pn,resolvedAccount:y,avsConfig:re,avsCheckProp:ue,sessionId:e,nonce:t,baseUrl:A};let ko=Be(!1),ji=we(()=>{let{resolvedAccount:r,avsConfig:v,avsCheckProp:z}=_n.current,X=Et.current||r.country||"US",L=v?De(v.state,X):!1,fe=v?De(v.address_line_1,X):!1,Fe=v?De(v.postal_code,X):!1,ft=v?De(v.city,X):!1,zt=v?De(v.address_line_2,X):!1,Ge=fe&&!L&&Fe?li(X,(Ut.current??"").trim()):null,Mt=L?Kt.current:Ge;return{accountData:{userId:r.userId??"",email:r.email??"",firstName:r.firstName??"",lastName:r.lastName??"",...Fe&&Ut.current?{zip:Ut.current}:{},...ft&&Ft.current?{city:Ft.current}:{},...Mt?{state:Mt}:{},...fe&&Vt.current?{addressLine1:Vt.current}:{},...zt&&Xt.current?{addressLine2:Xt.current}:{},country:X},...z!==void 0?{avsCheck:z}:{},...v?{avsConfig:{country:De(v.country,X),postal_code:Fe,address_line_1:fe,address_line_2:zt,city:ft,state:L}}:{}}},[]),ba=Be(je);ba.current=je,Qe(()=>{je||s!==pi||_n.current.updateError(null)},[je,s]),Qe(()=>{!Ue||!it||it.setSubmitGate?.(Wt||je)},[Ue,it,Wt,je]),Qe(()=>{if(!Ue||!it)return;ko.current=!1;let r=!1,v=it.on("submitting",()=>{Yt(!0),O.current&&clearTimeout(O.current),pe.current="validation-window",O.current=setTimeout(()=>{O.current=null,pe.current==="validation-window"&&(pe.current="processing")},Js),g("processing");let{baseUrl:Fe,sessionId:ft,nonce:zt,updateError:Ge,onError:Mt}=_n.current;!ft||!zt||new $n(Fe).patchAccountSnapshot(ft,zt,ji(),{telemetryMode:"best_effort"}).catch(Me=>{if(!Xs(Me))return;let qt=Me instanceof Error?Me.message:"Please check your billing address and try again.";Ge(qt),pe.current="idle",g(null),Mt?.(Me instanceof wn?Me:new wn(qt,"api_error"))})}),z=it.on("complete",async Fe=>{mr(Fe.sessionId??_n.current.sessionId),pe.current="terminal",g("success"),await new Promise(ft=>setTimeout(ft,Tn)),!ko.current&&(ko.current=!0,_n.current.onComplete?.({status:"succeeded",paymentIntentId:Fe.intentId,checkoutMethod:"card"}))}),X=it.on("decline",async Fe=>{let{updateError:ft,emitDecline:zt}=_n.current,Ge=Fe.message??"Your payment was declined. Please try another card or contact your bank.";pe.current="terminal",ft(Ge),g("error"),zt("card",Ge,Fe.declineReason?{declineCode:Fe.declineReason}:void 0),await new Promise(Mt=>setTimeout(Mt,Cn)),!r&&(pe.current="idle",g(null))}),L=it.on("error",async Fe=>{let{updateError:ft,onError:zt}=_n.current,Ge=Fe.message??"There was a problem processing your payment. Please try again.";pe.current="terminal",ft(Ge),g("error"),zt?.(new wn(Ge,"api_error")),await new Promise(Mt=>setTimeout(Mt,Cn)),!r&&(pe.current="idle",g(null))}),fe=it.on("blocked",()=>{if(!ba.current){Yt(!0);return}_n.current.updateError(pi)});return()=>{r=!0,O.current&&(clearTimeout(O.current),O.current=null),pe.current="idle",v(),z(),X(),L(),fe()}},[Ue,it]);let bn=!!qe?.clientId,kr=Array.isArray(P),Hr=kr&&P.length>0,Vi=kr&&P.includes("paypal"),{expressMethods:Wr,paymentElementMethods:Rr}=nt(()=>Vs(P,{excludePaypal:bn}),[P,bn]),va=bn||!!at,Ki=nt(()=>va?Wr.filter(r=>r!=="paypal"):Wr,[Wr,va]),Hi=nt(()=>{let r=[];return U&&r.push("apple_pay"),le&&r.push("google_pay"),r},[U,le]),Yr=kr?Ki:Hi,Wi=x&&Yr.length>0,Ro=nn?Je:ke,Gr=nt(()=>{let r=Ro?.trim().toUpperCase();return r?ae?Rr.filter(v=>{let z=ae[v];return!z||z.length===0||z.includes(r)}):$s(Rr,Ro):Rr},[Rr,Ro,ae]),Io=nt(()=>({mode:"payment",amount:Tt,currency:ze.toLowerCase(),paymentMethodCreation:"manual",appearance:ga}),[Tt,ze,ga]),[Ca,Sa]=ve("loading"),[wa,ka]=ve("loading"),[Ra,Ia]=ve("loading"),[Yi,Eo]=ve(!1),[Ea,_o]=ve("loading"),[Jr,Gi]=ve();Qe(()=>{Gi(ti())},[]);let _a=I&&(bn||(kr?Vi:Jr===!1)),xa=x&&Wi,Ir=!je&&_a&&bn,Ta=Ea==="retrying"||Ea==="exhausted",Er=!je&&_a&&!!We&&(!bn||Ta),_r=!je&&xa&&!!j,xr=!je&&x&&Hr&&Gr.length>0&&!!j,Ji=Ir&&!Ta?Yi:Er&&gi(Ca),Xi=_r&&gi(wa),Qi=xr&&Ra!=="load_error",Ma=r=>r==="loading"||r==="ready",Ba=Ir||Er&&Ma(Ca)||_r&&Ma(wa)||xr&&Ra!=="load_error",Xr=Be(!1);Qe(()=>{if(!Xr.current){if(!x&&!I){Xr.current=!0;let r=new wn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(r),me(r.message)}else if(!x&&I&&!bn&&!We){Xr.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),me(r.message)}else if(Jr!==void 0&&!je&&!Ee&&!Ba){Xr.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),me(r.message)}}},[x,I,bn,We,Jr,je,Ee,Ba,u,me]);let Aa=Be(!1);Qe(()=>{if(Aa.current||!Hr)return;let r=[];U!==!0&&r.push("showApplePay"),le!==!0&&r.push("showGooglePay"),r.length!==0&&(Aa.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.`))},[Hr,U,le]);let Fa=we((r,v)=>He.applyInlineSessionPatch?He.applyInlineSessionPatch(r).then(z=>({error:null,sessionId:z.sessionId||e,nonce:z.session?.clientSecret||t})).catch(z=>{let X=yi(v,z);return me(X.message),u?.(X),{error:X,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[He.applyInlineSessionPatch,t,u,e,me]),mn=we(async r=>{if(!ye)return{proceed:!0};try{let v=await ye({method:r,sessionId:e||void 0,createSession:He.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&Ln(X=>({...X??{},...v.account}));let z=await Fa(v,r);return z.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:z.sessionId,nonce:z.nonce}}return{proceed:!0}}catch(v){let z=yi(r,v);return me(z.message),u?.(z),{proceed:!1}}},[Fa,He.inlineSessionDraft,ye,u,e,me]),Da=we(async(r,v)=>{if(q.current)return;q.current=!0,be(!0),g("processing"),me(null);let z=v?.sessionId??e,X=v?.nonce??t,L=jo(y,v?.accountPatch),fe=v?.completionPaymentMethodId??io(r),Fe=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r;try{let zt=await new $n(A).processPayment(L.userId??"",{sessionId:z,nonce:X,tokenizedData:Fe,accountData:{userId:L.userId??"",email:L.email??"",firstName:L.firstName??"",lastName:L.lastName??"",...re?(()=>{let Me=Et.current,qt=De(re.state,Me),on=De(re.address_line_1,Me),Xn=De(re.postal_code,Me),Qn=on&&!qt&&Xn?li(Me,(Ut.current??"").trim()):null,Bt=qt?Kt.current:Qn;return{country:Me,...Xn&&Ut.current?{zip:Ut.current}:{},...De(re.city,Me)&&Ft.current?{city:Ft.current}:{},...Bt?{state:Bt}:{},...on&&Vt.current?{addressLine1:Vt.current}:{},...De(re.address_line_2,Me)&&Xt.current?{addressLine2:Xt.current}:{}}})():{}},chv:R,avsCheck:ue??!1,checkoutType:k,checkoutLayout:Q,avsConfig:re?{country:De(re.country,Et.current),postal_code:De(re.postal_code,Et.current),address_line_1:De(re.address_line_1,Et.current),address_line_2:De(re.address_line_2,Et.current),city:De(re.city,Et.current),state:De(re.state,Et.current)}:void 0});if(zt.ok){mr(z),g("success"),se(null),await new Promise(Me=>setTimeout(Me,Tn)),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){g("error"),me("PayPal authorization required but no token provided.");return}try{let on=at?.getRawProvider();if(!on){me("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){g("error");let Bt=Qn.message??"PayPal payment failed.";me(Bt),pn("paypal",Bt,{code:Qn.code})}}catch(on){g("error"),me(on instanceof Error?on.message:"PayPal authorization failed.")}return}if(Ge?.type==="paypal_direct_required"){let Me=Ge.orderId;if(!Me){g("error"),me("PayPal retry required but no order id provided.");return}let qt=C.current?.attempts??0;if(qt>=2){g("error"),me("PayPal payment could not be completed after multiple attempts."),pn("paypal","paypal_direct_required retry limit exceeded");return}Eo(!1),_o("loading"),se({orderId:Me,attempts:qt+1}),g(null);return}g("error");let Mt=Ge?.message??"Payment failed. Please try again.";me(Mt),pn(r.isPaypal?"paypal":"card",Mt,{code:Ge?.code??Ge?.gatewayErrorCode,declineCode:Ge?.declineCode??Ge?.gatewayDeclineReason}),await new Promise(Me=>setTimeout(Me,Cn))}catch(ft){g("error"),me(ft instanceof Error?ft.message:"An unexpected error occurred"),await new Promise(zt=>setTimeout(zt,Cn))}finally{be(!1),g(null),q.current=!1}},[A,e,t,y,D,R,Te,at,a,u,me,pn]),rn=we((r,v)=>{w?w(r):Da(r,v)},[w,Da]),La=Be(!1);Qe(()=>{if(typeof window>"u"||La.current)return;let r=new URLSearchParams(window.location.search),v=r.get("payment_intent"),z=r.get("payment_intent_client_secret"),X=r.get("redirect_status");if(!v||!z)return;let L=Mt=>{let Me=localStorage.getItem(Mt);if(!Me)return null;try{return JSON.parse(Me)}catch{return localStorage.removeItem(Mt),null}},fe=L(kn)??L(ui),Fe;if(fe?.clientSecret){if(fe.clientSecret!==z)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;La.current=!0,localStorage.removeItem(kn),localStorage.removeItem(ui);let ft=new URL(window.location.href);ft.searchParams.delete("payment_intent"),ft.searchParams.delete("payment_intent_client_secret"),ft.searchParams.delete("redirect_status"),window.history.replaceState({},"",ft.toString());let zt=fe?.paymentMethodType??fe?.tokenType??"card",Ge="card";(async()=>{let Mt=Te?.getRawProvider();if(!Mt){let Bt="Payment is not available \u2014 please refresh and try again.";me(Bt),pn(Ge,Bt);return}if(X==="failed"){let Bt="Payment was declined. Please try again.";me(Bt),pn(Ge,Bt);return}let{paymentIntent:Me,error:qt}=await Mt.retrievePaymentIntent(z);if(qt){let Bt=qt.message??"Failed to retrieve payment status.";me(Bt),pn(Ge,Bt,{code:qt.code});return}let on=Me?.status,Xn=ao(on);if(!Me||!Xn){let Bt=on==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";me(Bt),pn(Ge,Bt,{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,me,pn]);let xo=we(r=>{r.preventDefault()},[]);if(!(Te!==null))return p("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Tr=ee==="buttons",Jt=G?.variables,Zi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),To=Jt?.colorBackground,es=To&&!Zi.has(To)?To:void 0,Mr=m.cardInputBorder??(Tr?"#e5e7eb":"#A4A4FF"),Mo=Jt?.colorDanger??"#dc2626",Yn=r=>Qt&&r?Mo:Mr,Qr=(Lt.malformed||Lt.empty)&&(dn||Qt),ts=Qr?Mo:Yn(ht.zip),Bo=m.cardFormContainer?.backgroundColor??es??(Tr?"white":"#EDEDFF"),Br=m.cardInputBackground??Jt?.colorBackground??"white",Ao=sr(K),Na=sr(de),ir=m.nameInput,Oa=m.cardInputFontSize??ol(ir?.fontSize)??Jt?.fontSizeBase??"16px",za=typeof ir?.fontFamily=="string"?ir.fontFamily:Jt?.fontFamily??"Poppins, sans-serif",Ua=fi(ir?.fontWeight)??400,ns=m.cardInputColor??(typeof ir?.color=="string"?ir.color:void 0)??Jt?.colorText??"#262833",rs=m.cardInputPlaceholderColor??"#9ca3af",yt=Jt?.borderRadius??"8px",Gn=Jt?.borderRadius??m.cardButton?.borderRadius??yt,Jn=Jt?.colorPrimary??"#4A49FF",os=Jt?.colorPrimaryHover??po(Jn,.12),Fo=Jt?.colorText??"#262833",$a={fontSize:Oa,fontFamily:za,fontWeight:Ua,color:ns,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},as={"--flopay-input-placeholder-color":rs,"--flopay-input-font-size":Oa,"--flopay-input-font-family":za,"--flopay-input-font-weight":String(Ua)},Ar=m.cardFormContainer??{},Do=Ar.padding??(Tr?"0":"1rem"),Lo=Ar.borderRadius??yt,is=it&&_t?p(zo,{capture:it,html:_t.html,messageToken:_t.messageToken,expectedOrigin:_t.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,z=window.setInterval(()=>{v+=1;let X=document.activeElement;!!X&&X.tagName==="IFRAME"&&X.id==="flopay_vault_form_iframe"?(r(),window.clearInterval(z)):v>=50&&window.clearInterval(z)},100)},onError:r=>me(r),onValidation:r=>{let v=pe.current;(v==="idle"||v==="validation-window")&&(me(r),r&&pe.current==="validation-window"&&(O.current&&(clearTimeout(O.current),O.current=null),pe.current="idle",g(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"}),qa=Le("div",{style:{backgroundColor:Bo,borderRadius:Lo,...Ar,padding:Do,...as,display:"flex",flexDirection:"column"},children:[p("style",{children:`
|
|
30
|
+
`,Co=44;function da(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 ml={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Mi={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 yl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function wi(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ai(e){return e==="paypal"?"PayPal":br(e)}function fl(e,t){let n=`We couldn't open ${Ai(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Bi(e){let t=Be(0),n=Be(null),s=Be(null),a=Se((c=s.current)=>{let P=c;P?.timer&&(clearTimeout(P.timer),P.timer=null)},[]),i=Se((c,P)=>{typeof document<"u"&&document.visibilityState!=="visible"||(a(c),c.timer=setTimeout(()=>{c.timer=null,s.current?.generation===c.generation&&(s.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))},[a,e]),d=Se(c=>{c.yieldedControl&&i(c,600)},[i]),l=Se(c=>{a();let P=t.current+1;t.current=P,n.current=null;let k={generation:P,method:c,timer:null,yieldedControl:!1};return s.current=k,P},[a]),C=Se(c=>{let P=s.current;return typeof c=="number"&&P?.generation!==c?!1:(a(P),s.current=null,(typeof c!="number"||n.current===c)&&(n.current=null),!0)},[a]),D=Se(c=>{let P=s.current,k=c??P?.generation??t.current;(!c||P?.generation===c)&&(a(P),s.current=null),n.current=k},[a]),h=Se(c=>n.current===(c??t.current),[]),w=Se(c=>s.current?.generation===c&&n.current!==c,[]),S=Se(()=>{let c=s.current;c&&d(c)},[d]),B=Se(()=>{let c=s.current;c&&(c.yieldedControl=!0,a(c))},[a]);return ct(()=>{let c=()=>{document.visibilityState==="visible"?S():B()},P=()=>{B()};return document.addEventListener("visibilitychange",c),window.addEventListener("blur",P),window.addEventListener("focus",S),()=>{document.removeEventListener("visibilitychange",c),window.removeEventListener("blur",P),window.removeEventListener("focus",S),a()}},[a,B,S]),{startAttempt:l,finishAttempt:C,invalidateAttempt:D,isAttemptInvalidated:h,isAttemptCurrent:w}}function gl(e){let t=el(e);return`Enter a valid ${aa(e)}${t?` (e.g. ${t})`:""}`}function hl(e,t,n){let s=Qs(e),a=t.trim(),i=n&&s,d=i&&!a,l=i&&!!a&&!Zs(e,a);return{visible:n,supported:s,required:i,empty:d,malformed:l}}function ki(e,t){return t instanceof Sn?t:new Sn(t instanceof Error?t.message:`${yl(e)} before-click hook failed.`,"validation_error")}function oa(){return u("style",{children:pl})}function Pl(e){return typeof e=="number"?`${e}px`:e}function Ri(e){if(typeof e=="number"||typeof e=="string")return e}function Fi(e,t){let n=e.availablePaymentMethods;return n&&t.some(s=>n[s])?"ready":"unavailable"}function Di({state:e,placeholderTestId:t,borderRadius:n=8,children:s}){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:s})]})}function Ii(e){return e!=="unavailable"&&e!=="load_error"}function ua(e){return u(vl,{...e})}function Ei({sessionId:e,nonce:t,email:n,billingApiUrl:s,onTokenizedBody:a,onErrorChange:i,isProcessing:d=!1,onButtonClick:l,onDecline:C,onTechnicalFailure:D,runBeforeButtonClick:h,onLoadStateChange:w,placeholderBorderRadius:S}){let B=bn(),c=la(),P=sa(),[k,I]=Ce("loading");ct(()=>{w?.(k)},[k,w]);let[g,de]=Ce(!1),_=Be(!1),ae=Be(null),Z=Be(null),[O,J]=Ce(0),[H,ie]=Ce(!1),j=Be(!1),V=Be(new Map),{startAttempt:le,finishAttempt:Te,invalidateAttempt:Pe,isAttemptInvalidated:pe,isAttemptCurrent:ee}=Bi((K,v,re)=>{D?.(K,v,{...re,popupBlocked:re?.popupBlocked??Un(v)}),ie(!0),J($e=>$e+1)});ct(()=>{H&&Z.current?.focus()},[H,O]);let fe=Se(()=>{J(K=>K+1)},[]),Me=Se((K,v,re)=>{Pe(re),D?.("paypal",K,{code:v,popupBlocked:Un(K)}),ie(!0),fe()},[Pe,D,fe]),te=Se(()=>{window.setTimeout(()=>{(ae.current?.querySelector("iframe")??ae.current)?.focus()},0)},[]);ct(()=>{j.current&&(j.current=!1,te())},[te,O]);let Ue=Se(()=>{ie(!1),i?.(null),te()},[te,i]);ct(()=>{if(!c||_.current)return;let K=new URLSearchParams(window.location.search),v=K.get("payment_intent"),re=K.get("payment_intent_client_secret"),$e=K.get("redirect_status");if(!v||!re)return;_.current=!0;let ze;try{let x=localStorage.getItem(Kr);if(x){let oe=JSON.parse(x);oe.clientSecret===re&&(ze={...oe.accountPatch?{accountPatch:oe.accountPatch}:{},...oe.sessionId?{sessionId:oe.sessionId}:{},...oe.nonce?{nonce:oe.nonce}:{}})}}catch{}try{localStorage.removeItem(Kr)}catch{}let se=new URL(window.location.href);se.searchParams.delete("payment_intent"),se.searchParams.delete("payment_intent_client_secret"),se.searchParams.delete("redirect_status"),window.history.replaceState({},"",se.toString()),(async()=>{try{if(de(!0),$e==="failed"){let W="PayPal payment was declined. Please try again.";i?.(W),C?.(It("paypal",W));return}let{paymentIntent:x,error:oe}=await c.retrievePaymentIntent(re);if(oe){i?.(oe.message??"Failed to retrieve PayPal payment status.");return}if(x&&(x.status==="requires_capture"||x.status==="succeeded")){let W=typeof x.payment_method=="string"?x.payment_method:x.payment_method?.id;a({id:W??x.id,type:"card",threeDSecureActionResultTokenId:x.id,isPaypal:!0},ze)}else{let W="PayPal payment was not completed. Please try again.";i?.(W),C?.(It("paypal",W))}}catch(x){i?.(x instanceof Error?x.message:"Failed to complete PayPal payment.")}finally{de(!1)}})()},[c,a,i,C]);let Fe=Se(async K=>{if(d||g){K.reject();return}let v=h?await h("paypal"):{proceed:!0};if(!v.proceed){V.current.delete(O),K.reject();return}let re=le("paypal");V.current.set(O,{generation:re,accountPatch:v.accountPatch,sessionId:v.sessionId,nonce:v.nonce}),ie(!1),l?.("paypal"),K.resolve()},[V,d,l,h,le,g,O]),ke=Se(async K=>{if(!c||!P)return;let v=V.current.get(O);if(v&&!ee(v.generation)){V.current.delete(O);return}if(!v&&pe()||v&&!Te(v.generation))return;v||Te();let re=v??null;if(V.current.delete(O),!re&&h){let x=await h("paypal");if(!x.proceed){K.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}re={accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}}let $e=re?.sessionId??e,ze=re?.nonce??t,se=re?.accountPatch?.email??n;try{if(de(!0),i?.(null),!$e||!se)throw new Error("Missing sessionId or email for PayPal payment");let x=c.createPaymentMethod,{error:oe,paymentMethod:W}=await x({type:"paypal"});if(oe){Me(oe,"stripe_paypal_create_payment_method_failed",v?.generation),K.paymentFailed({reason:"fail"});return}let Re=await new $n(s).createSessionIntent($e,ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:W?.id??null,intentKind:"payment"});if(Re.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let dt=Re.clientSecret,Ge={return_url:window.location.href};if(W?.id&&(Ge.payment_method=W.id),typeof window<"u")try{localStorage.setItem(Kr,JSON.stringify({clientSecret:dt,sessionId:$e,nonce:ze,accountPatch:re?.accountPatch}))}catch{}let{error:pt,paymentIntent:M}=await c.confirmPayment({clientSecret:dt,confirmParams:Ge,redirect:"if_required"});if(pt){if(typeof window<"u")try{localStorage.removeItem(Kr)}catch{}if(jr(pt)){let Ze=pt.message??"Your payment was declined.";i?.(Ze),C?.(It("paypal",Ze,{code:Mn(pt),declineCode:gr(pt)})),await So({billingApiUrl:s,sessionId:$e,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(pt)??"provider_declined"}})}else Me(pt,"stripe_paypal_confirm_failed",v?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Kr)}catch{}let Y=typeof M?.payment_method=="string"?M.payment_method:M?.payment_method?.id;a({id:Y??M?.id,type:"card",threeDSecureActionResultTokenId:M?.id,isPaypal:!0},{accountPatch:re?.accountPatch,sessionId:$e,nonce:ze});return}catch(x){Me(x,"stripe_paypal_failed",v?.generation)}finally{de(!1)}},[c,P,e,t,n,s,a,i,C,h,Me,Te,ee,pe,O]);return Le(Pr,{children:[u(Di,{state:k,placeholderTestId:"flopay-paypal-placeholder",borderRadius:S,children:Le("div",{ref:ae,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[H&&u("button",{ref:Z,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ue,style:Mi,children:"Try PayPal again"}),u(Ti,{onReady:K=>I(Fi(K,["paypal"])),onLoadError:()=>{I("load_error"),ca(Mt(B),"paypal","paypal")},onClick:Fe,onConfirm:ke,onCancel:()=>{let K=V.current.get(O);V.current.delete(O),Mt(B)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Pe(K?.generation),ie(!1),j.current=!0,fe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},O)]})}),g&&u(Cn,{status:"processing"})]})}function _i({sessionId:e,nonce:t,email:n,billingApiUrl:s,intentKind:a,expressMethods:i,onTokenizedBody:d,onErrorChange:l,onButtonClick:C,onDecline:D,onTechnicalFailure:h,runBeforeButtonClick:w,onLoadStateChange:S,placeholderBorderRadius:B}){let c=bn(),P=la(),k=sa(),[I,g]=Ce("loading");ct(()=>{S?.(I)},[I,S]);let[de,_]=Ce(!1),ae=Be(null),Z=Be(null),[O,J]=Ce(0),[H,ie]=Ce(!1),[j,V]=Ce("google_pay"),le=Be(!1),Te=Be("google_pay"),Pe=Be("google_pay"),pe=Be(new Map),{startAttempt:ee,finishAttempt:fe,invalidateAttempt:Me,isAttemptInvalidated:te,isAttemptCurrent:Ue}=Bi((se,x,oe)=>{h?.(se,x,{...oe,popupBlocked:oe?.popupBlocked??Un(x)}),V(se),ie(!0),J(W=>W+1)});ct(()=>{H&&Z.current?.focus()},[H,O]);let Fe=Se(()=>{J(se=>se+1)},[]),ke=Se((se,x,oe,W)=>{Me(W),h?.(se,x,{code:oe,popupBlocked:Un(x)}),V(se),ie(!0),Fe()},[Me,h,Fe]),K=Se(()=>{window.setTimeout(()=>{(ae.current?.querySelector("iframe")??ae.current)?.focus()},0)},[]);ct(()=>{le.current&&(le.current=!1,K())},[K,O]);let v=Se(()=>{ie(!1),l?.(null),K()},[K,l]),re=Se(async se=>{if(!P||!k)return;let x=pe.current.get(O);if(x&&!Ue(x.generation)){pe.current.delete(O);return}if(!x&&te()||x&&!fe(x.generation))return;x||fe();let oe=se.expressPaymentType??x?.method??Te.current,W=x??null;pe.current.delete(O);let Re=wi(oe);if(!W&&w){let Y=await w(Re);if(!Y.proceed){se.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}W={accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}}let dt=Re,Ge=W?.sessionId??e,pt=W?.nonce??t,M=W?.accountPatch?.email??n;try{_(!0),l?.(null);let{error:Y}=await k.submit();if(Y){ke(oe,Y,"stripe_wallet_submit_failed",x?.generation);return}let{error:Ze,paymentMethod:qe}=await P.createPaymentMethod({elements:k});if(Ze||!qe){ke(oe,Ze??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",x?.generation);return}if(!Ge||!M)throw new Error("Missing sessionId or email for wallet payment");let mt=await new $n(s).createSessionIntent(Ge,pt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:oe??Re,paymentMethodId:qe.id,intentKind:a});if(mt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Oe=mt.clientSecret,{error:He,intentId:Jt}=ll(Oe)?await P.confirmCardSetup(Oe,{payment_method:qe.id}).then(Ye=>({error:Ye.error,intentId:Ye.setupIntent?.id})):await P.confirmCardPayment(Oe,{payment_method:qe.id}).then(Ye=>({error:Ye.error,intentId:Ye.paymentIntent?.id}));if(He){if(jr(He)){let Ye=He.message??"Your payment was declined.";l?.(Ye),D?.(It(dt,Ye,{code:Mn(He),declineCode:gr(He)})),await So({billingApiUrl:s,sessionId:Ge,nonce:pt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:oe??Re,providerDeclineReason:Mn(He)??"provider_declined"}})}else ke(oe,He,"stripe_wallet_confirm_failed",x?.generation);return}d({id:qe.id,type:"card",threeDSecureActionResultTokenId:Jt},{accountPatch:W?.accountPatch,sessionId:Ge,nonce:pt})}catch(Y){ke(oe,Y,"stripe_wallet_failed",x?.generation)}finally{_(!1)}},[P,k,e,t,n,s,a,d,l,D,w,ke,fe,Ue,te,O]),$e=lt(()=>{let se=["applePay","googlePay","paypal","link","amazonPay","klarna"],x=new Set(["applePay","googlePay"]),oe=new Set(i.map(vi)),W={};for(let Re of se)oe.has(Re)?W[Re]=x.has(Re)?"always":"auto":W[Re]="never";return W},[i]),ze=lt(()=>i.map(vi),[i]);return Le(Pr,{children:[u(Di,{state:I,placeholderTestId:"flopay-wallet-placeholder",borderRadius:B,children:Le("div",{ref:ae,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[H&&Le("button",{ref:Z,type:"button","data-testid":"flopay-wallet-retry-button",onClick:v,style:Mi,children:["Try ",Ai(j)," again"]}),u(Ti,{onReady:se=>{g(Fi(se,ze))},onLoadError:se=>{g("load_error"),ca(Mt(c),"stripe","wallet")},onClick:async se=>{Te.current=se.expressPaymentType,Pe.current=wi(se.expressPaymentType);let x=w?await w(Pe.current):{proceed:!0};if(!x.proceed){pe.current.delete(O),se.reject();return}let oe=ee(se.expressPaymentType);pe.current.set(O,{generation:oe,method:se.expressPaymentType,accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}),ie(!1),C?.(Pe.current),se.resolve()},onConfirm:re,onCancel:()=>{let se=pe.current.get(O);pe.current.delete(O),Mt(c)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Me(se?.generation),ie(!1),le.current=!0,Fe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:$e,layout:{maxColumns:1,overflow:"never"}}},O)]})}),de&&u(Cn,{status:"processing"})]})}function bl({method:e,themeId:t,submitting:n=!1,disabled:s=!1,highlighted:a=!1,hasNextStep:i=!1,onClick:d,backgroundColor:l,borderColor:C,textColor:D,borderRadius:h,fontFamily:w}){let S=rl(e,t),B=oi[e],c=S?.backgroundColor??l??"#ffffff",P=S?.borderColor??C??"#d1d5db",k=S?.textColor??D??"#262833";return u("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!s&&d()},disabled:n||s,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Co,padding:"0 1rem",backgroundColor:c,color:k,border:`1px solid ${P}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:w,cursor:n||s?"not-allowed":"pointer",opacity:s&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?u("span",{style:{margin:"0 auto"},children:`Connecting to ${br(e)}\u2026`}):Le(Pr,{children:[Le("span",{style:{display:"inline-flex",alignItems:"center",gap:nl(e)?8:0},children:[B?u("img",{src:B,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):S?.logoSvg?u("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:S.logoSvg}}):null,u("span",{children:br(e)})]}),i&&u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:k,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:u("path",{d:"M9 18l6-6-6-6"})})]})})}function ia({method:e,sessionId:t,nonce:n,email:s,billingName:a,billingApiUrl:i,onTokenizedBody:d,onErrorChange:l,onDecline:C,onCancel:D,runBeforeButtonClick:h,onButtonClick:w,isProcessing:S,submitButtonColor:B,submitButtonBorderRadius:c,submitButtonStyle:P,errorText:k}){let I=bn(),g=la(),de=sa(),[_,ae]=Ce(!1),Z=Be(!1),[O,J]=Ce(!1),[H,ie]=Ce("loading"),j=Se(async()=>{if(!g||!de||S||Z.current||!O)return;Z.current=!0,ae(!0);let V=h?await h("card"):{proceed:!0};if(!V.proceed){Z.current=!1,ae(!1);return}w?.("card");let le=V.sessionId??t,Te=V.nonce??n,Pe=V.accountPatch?.email??s;try{l?.(null);let pe=await de.submit();if(pe.error){l?.(pe.error.message??"Payment failed.");return}let ee=await g.createPaymentMethod({elements:de});if(ee.error||!ee.paymentMethod){l?.(ee.error?.message??"Failed to create payment method.");return}let fe=ee.paymentMethod;if(!le||!Pe)throw new Error("Missing sessionId or email for payment.");let Me=fe.type||e,te=await new $n(i).createSessionIntent(le,Te??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Me,paymentMethodId:null,intentKind:"payment"});if(te.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ue=te.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Ue,sessionId:le,nonce:Te,accountPatch:V.accountPatch,paymentMethodId:fe.id,paymentMethodType:fe.type??e,gateway:"stripe"}))}catch{}let{error:Fe,paymentIntent:ke}=await g.confirmPayment({clientSecret:Ue,confirmParams:{return_url:window.location.href,payment_method:fe.id},redirect:"if_required"});if(Fe){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let re=Fe.message??"Payment failed.";l?.(re),C?.(It("card",re,{code:Fe.code})),await So({billingApiUrl:i,sessionId:le,nonce:Te,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Fe.code??"provider_declined"}});return}let K=ke?.status;if(!fo(K)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let re=K==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";l?.(re),C?.(It("card",re,{code:K??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let v=typeof ke?.payment_method=="string"?ke.payment_method:ke?.payment_method?.id;d({id:v??fe.id,type:"card",threeDSecureActionResultTokenId:ke?.id,gateway:"stripe",paymentMethodType:fe.type??e},{accountPatch:V.accountPatch,sessionId:le,nonce:Te})}catch(pe){l?.(pe instanceof Error?pe.message:"Payment failed. Please try again.")}finally{Z.current=!1,ae(!1)}},[g,de,S,O,h,w,t,n,s,i,e,d,l,C]);return Le("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[u(Hs,{onReady:()=>ie("ready"),onLoadError:()=>{ie("load_error"),ca(Mt(I),"stripe","apm")},onChange:V=>{J(!!V.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:a&&a.trim().length>=3?a.trim():"FloPay Customer",...s?{email:s}:{}}}}}),u("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{j()},disabled:!O||_||S||H!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:B,color:"white",border:"none",borderRadius:c,fontSize:"1rem",fontWeight:600,cursor:!O||_||S||H!=="ready"?"not-allowed":"pointer",opacity:!O||_||S||H!=="ready"?.5:1,transition:"opacity 120ms ease-out",...P??{}},children:_?"Processing\u2026":`Pay with ${br(e)}`}),k&&u(pr,{margin:"0.75rem 0 0",children:k})]})}function xi({sessionId:e,nonce:t,email:n,billingName:s,billingApiUrl:a,paymentElementMethods:i,stripeInstance:d,paymentElementBaseOptions:l,onTokenizedBody:C,onErrorChange:D,onButtonClick:h,onDecline:w,runBeforeButtonClick:S,onLoadStateChange:B,isProcessing:c=!1,submitButtonColor:P="#4A49FF",submitButtonBorderRadius:k=8,submitButtonStyle:I,buttonAppearance:g,themeId:de,onExpandApm:_,expandedApmMethod:ae}){let[Z,O]=Ce(null),[J,H]=Ce(null),ie=Be(!1);ct(()=>{i.length>0&&d?B?.("ready"):d||B?.("loading")},[i.length,d,B]);let j=Se(async ee=>{if(!d||ie.current||c)return;ie.current=!0,H(ee);let fe=S?await S("card"):{proceed:!0};if(!fe.proceed){ie.current=!1,H(null);return}h?.("card");let Me=fe.sessionId??e,te=fe.nonce??t,Ue=fe.accountPatch?.email??n;try{if(D?.(null),!Me||!Ue)throw new Error("Missing sessionId or email for payment.");let Fe=await new $n(a).createSessionIntent(Me,te??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,paymentMethodId:null,intentKind:"payment"});if(Fe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ke=Fe.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:ke,sessionId:Me,nonce:te,accountPatch:fe.accountPatch,paymentMethodType:ee,gateway:"stripe"}))}catch{}let{error:K,paymentIntent:v}=await d.confirmPayment({clientSecret:ke,confirmParams:{return_url:window.location.href,payment_method_data:{type:ee,billing_details:{name:s&&s.trim().length>=3?s.trim():"FloPay Customer",...Ue?{email:Ue}:{}}}},redirect:"if_required"});if(K){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=K.message??"Payment failed.";D?.(ze),w?.(It("card",ze,{code:K.code})),await So({billingApiUrl:a,sessionId:Me,nonce:te,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,providerDeclineReason:K.code??"provider_declined"}});return}let re=v?.status;if(!fo(re)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=re==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";D?.(ze),w?.(It("card",ze,{code:re??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let $e=typeof v?.payment_method=="string"?v.payment_method:v?.payment_method?.id;C({id:$e??v?.id,type:"card",threeDSecureActionResultTokenId:v?.id,gateway:"stripe",paymentMethodType:ee},{accountPatch:fe.accountPatch,sessionId:Me,nonce:te})}catch(Fe){D?.(Fe instanceof Error?Fe.message:"Payment failed. Please try again.")}finally{ie.current=!1,H(null)}},[d,c,S,h,e,t,n,a,s,C,D,w]),[V,le]=Ce(null),Te=_?ae??null:V,Pe=Se(ee=>{ie.current||c||Te&&Te!==ee||(bi(ee)?_?_(ee):le(ee):j(ee))},[Te,c,j,_]),pe=lt(()=>V?{...l,paymentMethodTypes:[V]}:null,[V,l]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:i.map(ee=>{let fe=ae===ee,Me=J===ee,te=J!==null&&J!==ee||ae!=null&&ae!==ee;return Le(il.Fragment,{children:[u(bl,{method:ee,themeId:de,submitting:Me,disabled:te,highlighted:fe,hasNextStep:bi(ee),onClick:()=>Pe(ee),backgroundColor:g?.backgroundColor,borderColor:g?.borderColor,textColor:g?.textColor,borderRadius:g?.borderRadius,fontFamily:g?.fontFamily}),!_&&V===ee&&pe&&d&&u(nr,{stripe:d,options:pe,children:u(ia,{method:ee,sessionId:e,email:n,billingName:s,billingApiUrl:a,onTokenizedBody:C,onErrorChange:D,onDecline:w,onCancel:()=>le(null),runBeforeButtonClick:S,onButtonClick:h,isProcessing:c,submitButtonColor:P,submitButtonBorderRadius:k,submitButtonStyle:I})},ee)]},ee)})})}function vl({sessionId:e,nonce:t,billingApiUrl:n,email:s,userId:a,onComplete:i,onError:d,onDecline:l,onTokenizedBody:C,firstName:D,lastName:h,chv:w,className:S,isProcessing:B,error:c,onErrorChange:P,showPayPal:k=!0,showStripe:I=!0,enabledPaymentMethods:g,enabledPaymentMethodCountries:de,showApplePay:_=!0,showGooglePay:ae=!0,layout:Z="default",theme:O,buttonsTheme:J,buttonsStyles:H,appearance:ie,cardButtonContent:j,cardBackButtonContent:V,cardTitleContent:le,showSecurityFooter:Te,onButtonClick:Pe,onBeforeButtonClick:pe,enableAVS:ee,cardFieldOrder:fe,cardPreFormSlot:Me,avsLayout:te="row",country:Ue,zip:Fe,addressLine1:ke,addressLine2:K,city:v,state:re,onCountryChange:$e,onZipChange:ze,avsCheck:se,checkoutType:x,checkoutLayout:oe,totalAmount:W=0,currency:Re="usd",initialCardOpen:dt=!1,directPaypal:Ge,isSubscription:pt=!1,session:M,dataAttachmentPending:Y=!1,debug:Ze=!1}){let qe=bn(),mt=Yo(),Oe=sl(pn),He=Y||Oe.claimPending===!0,Jt=po(),[Ye,Xt]=Ce(!1),[R,ge]=Ce(null),[We,Ie]=Ce(Ue??"US"),[St,Ve]=Ce(Fe??""),[je,et]=Ce(ke??""),[Je,Rn]=Ce(K??""),[rt,Vn]=Ce(v??""),[Wt,yn]=Ce(re??""),[Qt,ar]=Ce({}),Bt=Be(Fe??""),kt=Be(Ue??"US"),Zt=Be(ke??""),en=Be(K??""),Ft=Be(v??""),Dt=Be(re??""),wt=Be({});ct(()=>{let o=(b,q,X,N,ue)=>{if(wt.current[b])return;let ve=q?.trim();!ve||ve===X.current||(X.current=ve,N(ve),ue?.(ve))};o("country",Ue,kt,Ie,$e),o("zip",Fe,Bt,Ve,ze),o("addressLine1",ke,Zt,et),o("addressLine2",K,en,Rn),o("city",v,Ft,Vn),o("state",re,Dt,yn)},[Ue,Fe,ke,K,v,re,$e,ze]);let Q=lt(()=>Xs(ee),[ee]),Kn=Q!==null,F=lt(()=>na(M),[M]),ot=!!M?.vault?.html,Lt=!!M?.gateways?.pcivault,Ae=!!(M?.gateways?.stripe?.enabledPaymentMethods??g)?.includes("card"),at=ot||Ae||Lt,Ke=!!(I&&at&&qe&&e),[In,En]=Ce(()=>Z!=="buttons"||dt?e??null:null),[Ln,Hn]=Ce(0),_n=Z!=="buttons"||dt||!!e&&In===e,tt=lt(()=>!qe||!Ke||!e||!_n?null:qe.cardCapture({sessionId:e,captureMethod:M?.captureMethod}),[qe,Ke,e,_n,M?.captureMethod]),zt=lt(()=>{let o=We,b=Q?De(Q.postal_code,o):!1;return hl(o,St,b)},[Q,We,St]),{avsInvalid:ln,invalidAvsFields:Pt}=lt(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!Ke||!Q)return{avsInvalid:!1,invalidAvsFields:o};let b=We,q=(ue,ve)=>De(ue,b)&&!ve.trim(),X={line1:q(Q.address_line_1,je),city:q(Q.city,rt),state:q(Q.state,Wt),zip:zt.empty||zt.malformed};return{avsInvalid:X.line1||X.city||X.state||X.zip,invalidAvsFields:X}},[Ke,Q,We,je,rt,Wt,zt]),[_t,tn]=Ce(!1),[cn,Yt]=Ce(!1),[Ut,$t]=Ce(()=>ra(M?.vault)),[_e,qt]=Ce(dt&&at?"card":"buttons"),[yt,fn]=Ce(null),Wn=_e==="expanding"||_e==="card",jt=280,Vt=Be(null),Ot=Se(o=>{Vt.current&&clearTimeout(Vt.current),Vt.current=setTimeout(()=>{Vt.current=null,o()},jt)},[jt]);ct(()=>()=>{Vt.current&&clearTimeout(Vt.current)},[]);let zn=Se(()=>{En(e??null),Hn(o=>o+1),qt("expanding"),Ot(()=>qt("card"))},[Ot,e]),On=Se(()=>{qt("collapsing"),Ot(()=>qt("buttons"))},[Ot]),nn=Se(o=>{fn(o),qt("apm-expanding"),Ot(()=>qt("apm-form"))},[Ot]),Gt=Se(()=>{qt("apm-collapsing"),Ot(()=>{qt("buttons"),fn(null)})},[Ot]);ct(()=>{Z==="buttons"&&dt&&at&&(En(e??null),qt("card"))},[Z,dt,at,e]);let[rn,Ne]=Ce(null),E=Be(!1),L=Be(null),T=Be("idle"),[he,be]=Ce(null),m=Be(he);ct(()=>{m.current=he},[he]);let r=n||Jt,f=c??R,A=lt(()=>cl(O),[O]),y=lt(()=>{let o=A?.buttonsLayout??Ys(J);return H?{...o,...H,cardButton:{...o.cardButton,...H.cardButton},cardFormContainer:{...o.cardFormContainer,...H.cardFormContainer},backButton:{...o.backButton,...H.backButton},backButtonIcon:{...o.backButtonIcon,...H.backButtonIcon},submitButton:{...o.submitButton,...H.submitButton},title:{...o.title,...H.title}}:o},[A,J,H]),U=ie??A?.appearance,Ee=lt(()=>{let o=U?.variables,b=ve=>typeof ve=="string"&&ve?ve:void 0,q=y.submitButton,X=b(o?.colorPrimary)??b(q?.backgroundColor)??"#4A49FF",N=Z==="buttons",ue=y.nameInput;return{primaryColor:X,primaryHoverColor:b(o?.colorPrimaryHover)??vo(X,.12),inputBackgroundColor:b(y.cardInputBackground)??b(o?.colorBackground)??"#ffffff",textColor:b(y.cardInputColor)??b(ue?.color)??b(o?.colorText)??"#262833",borderColor:b(y.cardInputBorder)??(N?"#e5e7eb":"#A4A4FF"),placeholderColor:b(y.cardInputPlaceholderColor)??"#9ca3af",errorColor:b(o?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:b(ue?.fontFamily)??b(o?.fontFamily)??"Poppins, sans-serif",fontSize:b(y.cardInputFontSize)??b(o?.fontSizeBase)??"16px",fontWeight:String(Ri(ue?.fontWeight)??400),borderRadius:b(o?.borderRadius)??"8px"}},[U,y,Z]),it=Oe.inlineSessionPatchProcessing??!1,G=(B??Ye)||it,$=r.replace(/\/+$/,""),p=lt(()=>Xo({userId:a,email:s,firstName:D,lastName:h,country:Ue,zip:Fe},Qt),[a,s,D,h,Ue,Fe,Qt]),z=[p.firstName,p.lastName].filter(o=>!!o?.trim()).join(" "),me=lt(()=>qe?qe.getRawProvider():null,[qe]),we=lt(()=>mt?mt.getRawProvider():null,[mt]),xe=W||100,gn=lt(()=>U?al(U):null,[U]),Er=gn?{appearance:gn}:null,Mo=lt(()=>{let o=gn??{},b=o.rules??{};return{...o,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[gn]),Qr=lt(()=>{let o=di(W);return{...o,currency:Re.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...Er}},[W,Re,Er]),Ia=lt(()=>({mode:"payment",amount:xe,currency:Re.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Er}),[xe,Re,Er]),ce=Se(o=>{ge(o),P?.(o)},[P]);ct(()=>{!Ke||!tt||tt.setCardFieldOrder?.(fe??null,Q==null)},[Ke,tt,fe,Q]),ct(()=>{(_e==="expanding"||_e==="collapsing"||_e==="apm-expanding"||_e==="apm-collapsing")&&ce(null)},[_e,ce]);let dn=Se((o,b,q)=>{l?.(It(o,b,q))},[l]),ir=Se((o,b,q)=>{let X=q?.popupBlocked??Un(b),N=fl(o,X),ue=er(q?.code)??Mn(b)??"external_payment_method_failed",ve=new Sn(N,"api_error",{code:"external_payment_method_failed",param:o});Ne(null),Z==="buttons"&&(qt("buttons"),fn(null)),ce(N),d?.(ve),console.error("[FloPay] External payment method failed:",{method:o,code:ue,popupBlocked:X})},[Z,d,ce]);ct(()=>{if(!Ke||!e){$t(null);return}let o=ra(M?.vault);if(o){$t(o);return}if(!_n){$t(null);return}$t(null);let b=!0;return new $n($).getVaultCapture(e,t).then(q=>{if(!b)return;let X=ra(q);X?$t(X):ce("Failed to load the secure card form.")}).catch(q=>{b&&ce(q instanceof Error?q.message:"Failed to load the secure card form.")}),()=>{b=!1}},[Ke,_n,Ln,e,M?.vault?.html,M?.vault?.messageToken,M?.vault?.expectedOrigin,$,t,ce]);let hn=Be({onComplete:i,onError:d,updateError:ce,emitDecline:dn,resolvedAccount:p,avsConfig:Q,avsCheckProp:se,sessionId:e,nonce:t,baseUrl:$,captureMethod:M?.captureMethod,paymentId:M?.paymentId,authorizationExpiresAt:M?.authorizationExpiresAt});hn.current={onComplete:i,onError:d,updateError:ce,emitDecline:dn,resolvedAccount:p,avsConfig:Q,avsCheckProp:se,sessionId:e,nonce:t,baseUrl:$,captureMethod:M?.captureMethod,paymentId:M?.paymentId,authorizationExpiresAt:M?.authorizationExpiresAt};let Ao=Be(!1),ts=Se(()=>{let{resolvedAccount:o,avsConfig:b,avsCheckProp:q}=hn.current,X=kt.current||o.country||"US",N=b?De(b.state,X):!1,ue=b?De(b.address_line_1,X):!1,ve=b?De(b.postal_code,X):!1,st=b?De(b.city,X):!1,vt=b?De(b.address_line_2,X):!1,Xe=ue&&!N&&ve?Pi(X,(Bt.current??"").trim()):null,Rt=N?Dt.current:Xe;return{accountData:{userId:o.userId??"",email:o.email??"",firstName:o.firstName??"",lastName:o.lastName??"",...ve&&Bt.current?{zip:Bt.current}:{},...st&&Ft.current?{city:Ft.current}:{},...Rt?{state:Rt}:{},...ue&&Zt.current?{addressLine1:Zt.current}:{},...vt&&en.current?{addressLine2:en.current}:{},country:X},...q!==void 0?{avsCheck:q}:{},...b?{avsConfig:{country:De(b.country,X),postal_code:ve,address_line_1:ue,address_line_2:vt,city:st,state:N}}:{}}},[]),Ea=Be(He);Ea.current=He,ct(()=>{He||f!==Si||hn.current.updateError(null)},[He,f]),ct(()=>{!Ke||!tt||tt.setSubmitGate?.(ln||He)},[Ke,tt,ln,He]),ct(()=>{if(!Ke||!tt)return;Ao.current=!1;let o=!1,b=tt.on("submitting",()=>{tn(!0),L.current&&clearTimeout(L.current),T.current="validation-window",L.current=setTimeout(()=>{L.current=null,T.current==="validation-window"&&(T.current="processing")},dl),Ne("processing");let{baseUrl:ve,sessionId:st,nonce:vt,updateError:Xe,onError:Rt}=hn.current;!st||!vt||new $n(ve).patchAccountSnapshot(st,vt,ts(),{telemetryMode:"best_effort"}).catch(ye=>{if(!ul(ye))return;let xt=ye instanceof Error?ye.message:"Please check your billing address and try again.";Xe(xt),T.current="idle",Ne(null),Rt?.(ye instanceof Sn?ye:new Sn(xt,"api_error"))})}),q=tt.on("complete",async ve=>{if(fr(ve.sessionId??hn.current.sessionId),T.current="terminal",Ne("success"),await new Promise(Xe=>setTimeout(Xe,Tn)),Ao.current)return;Ao.current=!0;let st=hn.current,vt=na(st)||ve.outcome==="authorized";hn.current.onComplete?.(vt?{status:"authorized",paymentIntentId:ve.intentId,paymentId:ve.paymentId??st.paymentId,sessionId:ve.sessionId??st.sessionId,authorizationExpiresAt:ve.authorizationExpiresAt??st.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:ve.intentId,checkoutMethod:"card"})}),X=tt.on("decline",async ve=>{let{updateError:st,emitDecline:vt}=hn.current,Xe=ve.message??"Your payment was declined. Please try another card or contact your bank.";T.current="terminal",st(Xe),Ne("error");let Rt=ve.failureOutcome??Ws(ve.declineReason)??"authorization_declined";vt("card",Xe,{code:Rt,declineCode:Rt}),await new Promise(ye=>setTimeout(ye,vn)),!o&&(T.current="idle",Ne(null))}),N=tt.on("error",async ve=>{let{updateError:st,onError:vt}=hn.current,Xe=ve.message??"There was a problem processing your payment. Please try again.";T.current="terminal",st(Xe),Ne("error"),vt?.(new Sn(Xe,"api_error",{code:ve.failureOutcome??"capture_failed"})),await new Promise(Rt=>setTimeout(Rt,vn)),!o&&(T.current="idle",Ne(null))}),ue=tt.on("blocked",()=>{if(!Ea.current){tn(!0);return}hn.current.updateError(Si)});return()=>{o=!0,L.current&&(clearTimeout(L.current),L.current=null),T.current="idle",b(),q(),X(),N(),ue()}},[Ke,tt]);let Pn=!!Ge?.clientId,_r=Array.isArray(g),Zr=_r&&g.length>0,ns=_r&&g.includes("paypal"),{expressMethods:eo,paymentElementMethods:xr}=lt(()=>ol(g,{excludePaypal:Pn}),[g,Pn]),_a=Pn||!!mt,rs=lt(()=>_a?eo.filter(o=>o!=="paypal"):eo,[eo,_a]),os=lt(()=>{let o=[];return _&&o.push("apple_pay"),ae&&o.push("google_pay"),o},[_,ae]),to=_r?rs:os,as=I&&to.length>0,Bo=Kn?We:Ue,no=lt(()=>{let o=Bo?.trim().toUpperCase();return o?de?xr.filter(b=>{let q=de[b];return!q||q.length===0||q.includes(o)}):tl(xr,Bo):xr},[xr,Bo,de]),Fo=lt(()=>({mode:"payment",amount:xe,currency:Re.toLowerCase(),paymentMethodCreation:"manual",appearance:Mo}),[xe,Re,Mo]),[xa,Ta]=Ce("loading"),[Ma,Aa]=Ce("loading"),[Ba,Fa]=Ce("loading"),[is,Do]=Ce(!1),[Da,Lo]=Ce("loading"),[ro,ss]=Ce();ct(()=>{ss(ui())},[]);let La=k&&(Pn||(_r?ns:ro===!1)),za=I&&as,Tr=!He&&La&&Pn,Oa=Da==="retrying"||Da==="exhausted",Mr=!He&&La&&!!we&&(!Pn||Oa),Ar=!He&&za&&!!me,Br=!He&&I&&Zr&&no.length>0&&!!me,ls=Tr&&!Oa?is:Mr&&Ii(xa),cs=Ar&&Ii(Ma),ds=Br&&Ba!=="load_error",Na=o=>o==="loading"||o==="ready",Ua=Tr||Mr&&Na(xa)||Ar&&Na(Ma)||Br&&Ba!=="load_error",oo=Be(!1);ct(()=>{if(!oo.current){if(!I&&!k){oo.current=!0;let o=new Sn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(o),ce(o.message)}else if(!I&&k&&!Pn&&!we){oo.current=!0;let o=new Sn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(o),ce(o.message)}else if(ro!==void 0&&!He&&!at&&!Ua){oo.current=!0;let o=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?.(o),ce(o.message)}}},[I,k,Pn,we,ro,He,at,Ua,d,ce]);let $a=Be(!1);ct(()=>{if($a.current||!Zr)return;let o=[];_!==!0&&o.push("showApplePay"),ae!==!0&&o.push("showGooglePay"),o.length!==0&&($a.current=!0,console.warn(`[FloPay] ${o.join(" / ")} ${o.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.`))},[Zr,_,ae]);let qa=Se((o,b)=>Oe.applyInlineSessionPatch?Oe.applyInlineSessionPatch(o).then(q=>({error:null,sessionId:q.sessionId||e,nonce:q.session?.clientSecret||t})).catch(q=>{let X=ki(b,q);return ce(X.message),d?.(X),{error:X,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Oe.applyInlineSessionPatch,t,d,e,ce]),un=Se(async o=>{if(!pe)return{proceed:!0};try{let b=await pe({method:o,sessionId:e||void 0,createSession:Oe.inlineSessionDraft});if(b===!1)return{proceed:!1};if(b&&typeof b=="object"){b.account&&ar(X=>({...X??{},...b.account}));let q=await qa(b,o);return q.error?{proceed:!1,accountPatch:b.account}:{proceed:!0,accountPatch:b.account,sessionId:q.sessionId,nonce:q.nonce}}return{proceed:!0}}catch(b){let q=ki(o,b);return ce(q.message),d?.(q),{proceed:!1}}},[qa,Oe.inlineSessionDraft,pe,d,e,ce]),ja=Se(async(o,b)=>{if(E.current)return;E.current=!0,Xt(!0),Ne("processing"),ce(null);let q=b?.sessionId??e,X=b?.nonce??t,N=Xo(p,b?.accountPatch),ue=b?.completionPaymentMethodId??qr(o),ve=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o;try{let vt=await new $n($).processPayment(N.userId??"",{sessionId:q,nonce:X,tokenizedData:ve,accountData:{userId:N.userId??"",email:N.email??"",firstName:N.firstName??"",lastName:N.lastName??"",...Q?(()=>{let ye=kt.current,xt=De(Q.state,ye),Ht=De(Q.address_line_1,ye),Xn=De(Q.postal_code,ye),Qn=Ht&&!xt&&Xn?Pi(ye,(Bt.current??"").trim()):null,Tt=xt?Dt.current:Qn;return{country:ye,...Xn&&Bt.current?{zip:Bt.current}:{},...De(Q.city,ye)&&Ft.current?{city:Ft.current}:{},...Tt?{state:Tt}:{},...Ht&&Zt.current?{addressLine1:Zt.current}:{},...De(Q.address_line_2,ye)&&en.current?{addressLine2:en.current}:{}}})():{}},chv:w,avsCheck:se??!1,checkoutType:x,checkoutLayout:oe,avsConfig:Q?{country:De(Q.country,kt.current),postal_code:De(Q.postal_code,kt.current),address_line_1:De(Q.address_line_1,kt.current),address_line_2:De(Q.address_line_2,kt.current),city:De(Q.city,kt.current),state:De(Q.state,kt.current)}:void 0});if(vt.ok){let ye=vt.status===204?null:await vt.json().catch(()=>null),xt=na(M)||ye?.status==="authorized";fr(q),Ne("success"),be(null),await new Promise(Ht=>setTimeout(Ht,Tn)),i?.(xt?{status:"authorized",...typeof ye?.paymentId=="string"?{paymentId:ye.paymentId}:M?.paymentId?{paymentId:M.paymentId}:{},sessionId:typeof ye?.sessionId=="string"?ye.sessionId:q,...typeof ye?.authorizationExpiresAt=="string"?{authorizationExpiresAt:ye.authorizationExpiresAt}:M?.authorizationExpiresAt?{authorizationExpiresAt:M.authorizationExpiresAt}:{},paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:ue,checkoutMethod:o.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:ue,checkoutMethod:o.isPaypal?"paypal":"card"});return}let Xe=await vt.json().catch(()=>null);if(Xe?.type==="paypal_redirect_required"){let ye=Xe.threeDSecureToken,xt=Xe.paymentMethodId||o.id||"";if(!qe||!ye){Ne("error"),ce("PayPal authorization required but no token provided.");return}try{let Ht=mt?.getRawProvider();if(!Ht){ce("PayPal is not available.");return}let Xn={return_url:window.location.href};xt&&(Xn.payment_method=xt);let{error:Qn}=await Ht.confirmPayment({clientSecret:ye,confirmParams:Xn,redirect:"if_required"});if(Qn){Ne("error");let Tt=Qn.message??"PayPal payment failed.";ce(Tt),dn("paypal",Tt,{code:Qn.code})}}catch(Ht){Ne("error"),ce(Ht instanceof Error?Ht.message:"PayPal authorization failed.")}return}if(Xe?.type==="paypal_direct_required"){let ye=Xe.orderId;if(!ye){Ne("error"),ce("PayPal retry required but no order id provided.");return}let xt=m.current?.attempts??0;if(xt>=2){Ne("error"),ce("PayPal payment could not be completed after multiple attempts."),dn("paypal","paypal_direct_required retry limit exceeded");return}Do(!1),Lo("loading"),be({orderId:ye,attempts:xt+1}),Ne(null);return}Ne("error");let Rt=Xe?.message??"Payment failed. Please try again.";ce(Rt),dn(o.isPaypal?"paypal":"card",Rt,{code:Xe?.code??Xe?.gatewayErrorCode,declineCode:Xe?.declineCode??Xe?.gatewayDeclineReason}),await new Promise(ye=>setTimeout(ye,vn))}catch(st){Ne("error"),ce(st instanceof Error?st.message:"An unexpected error occurred"),await new Promise(vt=>setTimeout(vt,vn))}finally{Xt(!1),Ne(null),E.current=!1}},[$,e,t,p,z,w,qe,mt,M,i,d,ce,dn]),on=Se((o,b)=>{C?C(o):ja(o,b)},[C,ja]),Va=Be(!1);ct(()=>{if(typeof window>"u"||Va.current)return;let o=new URLSearchParams(window.location.search),b=o.get("payment_intent"),q=o.get("payment_intent_client_secret"),X=o.get("redirect_status");if(!b||!q)return;let N=Rt=>{let ye=localStorage.getItem(Rt);if(!ye)return null;try{return JSON.parse(ye)}catch{return localStorage.removeItem(Rt),null}},ue=N(wn)??N(Ci),ve;if(ue?.clientSecret){if(ue.clientSecret!==q)return;ve={...ue.accountPatch?{accountPatch:ue.accountPatch}:{},...ue.sessionId?{sessionId:ue.sessionId}:{},...ue.nonce?{nonce:ue.nonce}:{}}}else if(ue?.sessionId&&ue.sessionId!==e)return;Va.current=!0,localStorage.removeItem(wn),localStorage.removeItem(Ci);let st=new URL(window.location.href);st.searchParams.delete("payment_intent"),st.searchParams.delete("payment_intent_client_secret"),st.searchParams.delete("redirect_status"),window.history.replaceState({},"",st.toString());let vt=ue?.paymentMethodType??ue?.tokenType??"card",Xe="card";(async()=>{let Rt=qe?.getRawProvider();if(!Rt){let Tt="Payment is not available \u2014 please refresh and try again.";ce(Tt),dn(Xe,Tt);return}if(X==="failed"){let Tt="Payment was declined. Please try again.";ce(Tt),dn(Xe,Tt);return}let{paymentIntent:ye,error:xt}=await Rt.retrievePaymentIntent(q);if(xt){let Tt=xt.message??"Failed to retrieve payment status.";ce(Tt),dn(Xe,Tt,{code:xt.code});return}let Ht=ye?.status,Xn=fo(Ht);if(!ye||!Xn){let Tt=Ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ce(Tt),dn(Xe,Tt,{code:Ht??"missing_payment_intent"});return}let Qn=typeof ye.payment_method=="string"?ye.payment_method:ye.payment_method?.id;on({id:Qn??ue?.paymentMethodId??ue?.tokenId??ye.id,type:"card",threeDSecureActionResultTokenId:ye.id,gateway:ue?.gateway??"stripe",paymentMethodType:vt},ve)})()},[e,on,qe,ce,dn]);let zo=Se(o=>{o.preventDefault()},[]);if(!(qe!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Fr=Z==="buttons",Kt=U?.variables,us=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Oo=Kt?.colorBackground,ps=Oo&&!us.has(Oo)?Oo:void 0,Dr=y.cardInputBorder??(Fr?"#e5e7eb":"#A4A4FF"),No=Kt?.colorDanger??"#dc2626",Yn=o=>_t&&o?No:Dr,ao=(zt.malformed||zt.empty)&&(cn||_t),ms=ao?No:Yn(Pt.zip),Uo=y.cardFormContainer?.backgroundColor??ps??(Fr?"white":"#EDEDFF"),Lr=y.cardInputBackground??Kt?.colorBackground??"white",$o=lr(V),Ka=lr(le),sr=y.nameInput,Ha=y.cardInputFontSize??Pl(sr?.fontSize)??Kt?.fontSizeBase??"16px",Wa=typeof sr?.fontFamily=="string"?sr.fontFamily:Kt?.fontFamily??"Poppins, sans-serif",Ya=Ri(sr?.fontWeight)??400,ys=y.cardInputColor??(typeof sr?.color=="string"?sr.color:void 0)??Kt?.colorText??"#262833",fs=y.cardInputPlaceholderColor??"#9ca3af",bt=Kt?.borderRadius??"8px",Gn=Kt?.borderRadius??y.cardButton?.borderRadius??bt,Jn=Kt?.colorPrimary??"#4A49FF",gs=Kt?.colorPrimaryHover??vo(Jn,.12),qo=Kt?.colorText??"#262833",Ga={fontSize:Ha,fontFamily:Wa,fontWeight:Ya,color:ys,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},hs={"--flopay-input-placeholder-color":fs,"--flopay-input-font-size":Ha,"--flopay-input-font-family":Wa,"--flopay-input-font-weight":String(Ya)},zr=y.cardFormContainer??{},jo=zr.padding??(Fr?"0":"1rem"),Vo=zr.borderRadius??bt,Ps=tt&&Ut?u(Wo,{capture:tt,html:Ut.html,messageToken:Ut.messageToken,expectedOrigin:Ut.expectedOrigin,theme:Ee,onReady:()=>{if(!Q||typeof document>"u")return;let o=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};o();let b=0,q=window.setInterval(()=>{b+=1;let X=document.activeElement;!!X&&X.tagName==="IFRAME"&&X.id==="flopay_vault_form_iframe"?(o(),window.clearInterval(q)):b>=50&&window.clearInterval(q)},100)},onError:o=>ce(o),onValidation:o=>{let b=T.current;(b==="idle"||b==="validation-window")&&(ce(o),o&&T.current==="validation-window"&&(L.current&&(clearTimeout(L.current),L.current=null),T.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"}),Ja=Le("div",{style:{backgroundColor:Uo,borderRadius:Vo,...zr,padding:jo,...hs,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 @@ ${qe.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),
|
|
39
|
-
`)}):null,
|
|
40
|
-
`)}):null,Ka=Ae==="apm-expanding"||Ae==="apm-form"||Ae==="apm-collapsing",eo=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,to=wt?{...Io,paymentMethodTypes:[wt]}:null;if(ee==="buttons"){let r=Ae==="buttons"||Ae==="expanding"||Ae==="apm-expanding",v=Ae==="expanding"||Ae==="card"||Ae==="collapsing",z=$===void 0?{boxSizing:"border-box",height:mo,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,L=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:xo,className:S,style:{position:"relative"},children:[p(Go,{}),xt&&p(Sn,{status:xt,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?Zs:{},...X?{animation:X,pointerEvents:"none"}:{}},children:[ja("flopay-direct-paypal-gate-debug"),Va("flopay-stripe-gate-debug"),Ir&&qe&&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(uo,{sessionId:e,nonce:t,billingApiUrl:c,email:y.email,clientId:qe.clientId,environment:qe.environment,currency:ze.toUpperCase(),isSubscription:ot,onTokenizedBody:rn,onComplete:a,onErrorChange:me,onDecline:l,onTechnicalFailure:ar,onButtonClick:Pe,runBeforeButtonClick:mn,isProcessing:he,onLoadStateChange:Eo,onInitializationStateChange:_o,session:N??null,existingOrderId:H?.orderId,debug:Ze},H?.orderId??"fresh")]}),Er&&p(tr,{stripe:We,options:Pa,children:p(hi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:c,onTokenizedBody:rn,onErrorChange:me,isProcessing:he,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:mn,onLoadStateChange:Sa,placeholderBorderRadius:Gn})}),_r?p(tr,{stripe:j,options:ha,children:p(Pi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:c,intentKind:Z>0?"payment":"setup",expressMethods:Yr,onTokenizedBody:rn,onErrorChange:me,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:mn,onLoadStateChange:ka,placeholderBorderRadius:Gn})}):xa?p("div",{style:{height:mo,borderRadius:Gn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,xr&&p(bi,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:c,paymentElementMethods:Gr,stripeInstance:j,paymentElementBaseOptions:Io,onTokenizedBody:rn,onErrorChange:me,onButtonClick:Pe,onDecline:l,runBeforeButtonClick:mn,onLoadStateChange:Ia,isProcessing:he,submitButtonColor:Jn,submitButtonBorderRadius:yt,submitButtonStyle:m.submitButton,onExpandApm:un,expandedApmMethod:wt,themeId:F,buttonAppearance:{backgroundColor:m.cardButton?.backgroundColor,borderColor:m.cardInputBorder,textColor:m.cardButton?.color,borderRadius:Gn}}),Ue&&p("button",{type:"button",onClick:async()=>{he||!(await mn("card")).proceed||(Pe?.("card"),En())},disabled:he,style:{width:"100%",...z,...m.cardButton,...ta({themeBundle:M,resolvedPrimaryColor:Jn,resolvedBorderRadius:yt,submitButtonStyle:m.submitButton,explicitPrimaryColor:Jt?.colorPrimary}),fontSize:m.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=os)},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:$})}),s&&Ae==="buttons"&&p(ur,{margin:"0.25rem 0",styleOverride:m.errorBanner,children:s})]}),Ue&&v&&p("div",{style:{gridArea:"1 / 1",...L?{animation:L}:{},...Ae==="collapsing"?{pointerEvents:"none"}:{}},children:qa}),x&&Ka&&wt&&to&&j&&p("div",{style:{gridArea:"1 / 1",...eo?{animation:eo}:{},...Ae==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Bo,borderRadius:Lo,...Ar,padding:Do},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:Ao?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.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",...m.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:m.titleFontSize??"1.05rem",color:Fo,paddingRight:80,...m.title},children:`Pay with ${hr(wt)}`})]}),p(tr,{stripe:j,options:to,children:p(Xo,{method:wt,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:c,onTokenizedBody:rn,onErrorChange:me,onDecline:l,onCancel:en,runBeforeButtonClick:mn,onButtonClick:Pe,isProcessing:he,submitButtonColor:Jn,submitButtonBorderRadius:yt,submitButtonStyle:m.submitButton,errorText:s})},wt)]})})]})]})}return Ka&&wt&&to&&j&&x?Le("form",{onSubmit:xo,className:S,style:{position:"relative"},children:[p(Go,{}),xt&&p(Sn,{status:xt,errorMessage:s}),p("div",{style:{...eo?{animation:eo}:{},...Ae==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Bo,borderRadius:Lo,...Ar,padding:Do},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:Ao?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.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",...m.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:m.titleFontSize??"1.05rem",color:Fo,paddingRight:80,...m.title},children:`Pay with ${hr(wt)}`})]}),p(tr,{stripe:j,options:to,children:p(Xo,{method:wt,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:c,onTokenizedBody:rn,onErrorChange:me,onDecline:l,onCancel:en,runBeforeButtonClick:mn,onButtonClick:Pe,isProcessing:he,submitButtonColor:Jn,submitButtonBorderRadius:yt,submitButtonStyle:m.submitButton,errorText:s})},wt)]})})]}):Le("form",{onSubmit:xo,className:S,style:{position:"relative"},children:[p(Go,{}),xt&&p(Sn,{status:xt,errorMessage:s}),Le("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ja("flopay-direct-paypal-gate-debug-default"),Va("flopay-stripe-gate-debug-default"),Ir&&qe&&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(uo,{sessionId:e,nonce:t,billingApiUrl:c,email:y.email,clientId:qe.clientId,environment:qe.environment,currency:ze.toUpperCase(),isSubscription:ot,onTokenizedBody:rn,onComplete:a,onErrorChange:me,onDecline:l,onTechnicalFailure:ar,onButtonClick:Pe,runBeforeButtonClick:mn,isProcessing:he,onLoadStateChange:Eo,onInitializationStateChange:_o,session:N??null,existingOrderId:H?.orderId,debug:Ze},H?.orderId??"fresh")]}),Er&&p(tr,{stripe:We,options:Pa,children:p(hi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:c,onTokenizedBody:rn,onErrorChange:me,isProcessing:he,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:mn,onLoadStateChange:Sa,placeholderBorderRadius:Gn})}),_r&&p(tr,{stripe:j,options:ha,children:p(Pi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:c,intentKind:Z>0?"payment":"setup",expressMethods:Yr,onTokenizedBody:rn,onErrorChange:me,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:mn,onLoadStateChange:ka,placeholderBorderRadius:Gn})}),xr&&p(bi,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:c,paymentElementMethods:Gr,stripeInstance:j,paymentElementBaseOptions:Io,onTokenizedBody:rn,onErrorChange:me,onButtonClick:Pe,onDecline:l,runBeforeButtonClick:mn,onLoadStateChange:Ia,isProcessing:he,submitButtonColor:Jn,submitButtonBorderRadius:yt,submitButtonStyle:m.submitButton,themeId:F,onExpandApm:un,expandedApmMethod:wt,buttonAppearance:{backgroundColor:m.cardButton?.backgroundColor,borderColor:m.cardInputBorder,textColor:m.cardButton?.color,borderRadius:Gn}})]}),Ue&&(Xi||Ji||Qi)&&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&&qa]})}import{loadFloPay as Ii,PaymentAPI as Ei}from"@flopay/js";import{FloPayError as rt,isSetupIntentClientSecret as sl}from"@flopay/shared";var $r="card";async function ll(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 cl(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 Rn(e,t){return Object.assign(e,{checkoutMethod:t})}function _i(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function dl(e){return e.status==="succeeded"||e.status==="declined"}async function xi(e){if(typeof document>"u"||typeof window>"u")throw new rt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new rt("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 h=new AbortController,R=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",R);let S=window.setTimeout(()=>h.abort(),i);try{let _=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!_.ok)return{status:"unknown"};let d=await _.json().catch(()=>null);return ul(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 h=await new Promise((R,S)=>{let _=!1,d=0,b=0,I=0,x=!1,P=()=>{window.clearTimeout(d),window.clearInterval(b),window.clearTimeout(I),window.removeEventListener("message",ee),w.removeEventListener("load",U),e.signal?.removeEventListener("abort",le)},ae=async()=>{if(!(_||x)){x=!0;try{let F=await a();if(_||!dl(F))return;_=!0,P(),R(F)}finally{x=!1}}},U=()=>{window.clearTimeout(I),I=window.setTimeout(()=>{ae()},250)},le=()=>{_||(_=!0,P(),S(new rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ee=F=>{if(F.source!==w.contentWindow||B&&F.origin!==B)return;let J=F.data;!J||typeof J!="object"||J.source!=="flopay-vault-3ds-return"||_||(_=!0,P(),R(null))};d=window.setTimeout(()=>{_||(_=!0,P(),S(new rt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),b=window.setInterval(()=>{ae()},n),w.addEventListener("load",U),window.addEventListener("message",ee),e.signal?.addEventListener("abort",le),e.signal?.aborted&&le()});return h||await a()}finally{l.parentNode?.removeChild(l),u?.isConnected&&u.focus()}}function ul(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 Rn(new rt(a,"api_error",{code:e?.gatewayErrorCode}),i)}function ra(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function fo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function pl(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 Ti(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||fo(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||fo(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 h of B)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||fo(h)))return h}}}}async function ml({billingApiUrl:e,sessionId:t,nonce:n,responseJson:i}){let o=Ti(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 Ei(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(fo(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,h=n.customer?.id??n.accountData?.userId??"",R=n.customer?.email??n.accountData?.email??"",S=n.customer?.firstName??n.accountData?.firstName??"",_=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 Ei(l,u===!1?{telemetry:!1}:void 0),x=await pl(()=>I.processPayment(h,{sessionId:w,nonce:B,tokenizedData:o,accountData:{userId:h,email:R,firstName:S,lastName:_,country:d,zip:b},returnUrl:a??ra(n)}));if(x.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:io(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let P=await x.json().catch(()=>null);if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let ae=Ti(P);if(!ae)throw new rt("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:P.type,threeDSecureToken:ae,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let ae=await ml({billingApiUrl:l,sessionId:w,nonce:B,responseJson:P});if(ae)return ae;throw Rn(new rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new rt(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason})}async function go(e,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:o,sessionId:a,session:u,returnUrl:l,telemetry:w}){let B=t?.getRawProvider();if(!B)throw new rt("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!i||!e.threeDSecureToken)throw Rn(new rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=sl(e.threeDSecureToken),R=null,S=e.paymentMethodId,_=await ll(B,e.threeDSecureToken,h);if(_){if(_.error)throw Rn(new rt(_.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let b=_.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 cl(B,e.threeDSecureToken,{payment_method:S,return_url:l??ra(u)??window.location.href},h):null;if(d){if(d.error)throw Rn(new rt(d.error.message??"3DS authentication failed.","api_error",{code:d.error.code}),"card");R=d.intent}else{let b=await B.handleNextAction({clientSecret:e.threeDSecureToken});if(b.error)throw Rn(new rt(b.error.message??"3DS authentication failed.","api_error",{code:b.error.code}),"card");R=(h?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}:go(b,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:o,sessionId:a,session:u,returnUrl:l,telemetry:w})}throw Rn(new rt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw Rn(new rt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:S}=await h.handleNextAction({clientSecret:e.threeDSecureToken});if(S)throw Rn(new rt(S.message??"PayPal authorization failed.","api_error",{code:S.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:R}=await h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??ra(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(R)throw Rn(new rt(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new rt("Unsupported payment redirect state.","api_error")}function nr(e){if(e instanceof rt){let i=zn(e.message);return i&&i!==e.message?Object.assign(new rt(i,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=zn(t)??t;return new rt(n,"api_error")}function ho(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new rt("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 Po({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([Ii(e,{billingApiUrl:n,locale:i,telemetry:o}),a?Ii(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 In,jsx as oe,jsxs as Rt}from"react/jsx-runtime";var br=44,ua="flopay_checkout_saved_payment_resume",So=new Map,vo=new Map;function Ai(e,t){t.settled&&t.consumers===0&&So.get(e)===t&&So.delete(e)}function bl(e,t,n){let i=vo.get(e);if(i&&(!i.sdkGeneratedIdempotencyKey||!t||i.sdkGeneratedIdempotencyKey===t))return i.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};vo.set(e,a);let u=()=>{vo.get(e)===a&&vo.delete(e)};return o.then(u,u),o}function qr(e){return new Promise(t=>setTimeout(t,e))}function Co(e,t,n){let i=no({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ni,enabled:t!==!1});return i.beginCheckout(n),i}function jr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function aa(e,t,n,i,o){let a=Co(e,t,n);a.error({errorCode:i,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),jr(a)}function vl(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 ca(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function ia(e){return!e||e.data.stripe?.publishableKey?!1:!!ca(e)?.clientId}function An(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Cl(){if(!An())return null;try{let e=window.sessionStorage.getItem(ua);return e?JSON.parse(e):null}catch{return null}}function Fi(e){if(An())try{window.sessionStorage.setItem(ua,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function sa(){if(An())try{window.sessionStorage.removeItem(ua)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var pa=":idempotency-key";function Sl(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 Di(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 da(e){if(An())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function wl(e){if(An())try{return window.sessionStorage.getItem(e+pa)??void 0}catch{return}}function kl(e,t){if(An())try{window.sessionStorage.setItem(e+pa,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function Rl(e){if(da(e),!!An())try{window.sessionStorage.removeItem(e+pa)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Il(){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 Li(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function El(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 la(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function ma({sessionId:e,nonce:t,createSession:n,billingApiUrl:i,telemetry:o,appearance:a,locale:u,loading:l,error:w,onComplete:B,onError:h,onDecline:R,onCountryChange:S,onZipChange:_,showPayPal:d=!0,showStripe:b=!0,enabledPaymentMethods:I,showApplePay:x=!0,showGooglePay:P=!0,debug:ae=!1,layout:U,theme:le,buttonsTheme:ee,buttonsStyles:F,cardButtonContent:J,cardBackButtonContent:W,cardTitleContent:ce,showSecurityFooter:$,onButtonClick:K,onBeforeButtonClick:de,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=hl(i),ie=fn(()=>Oi(le),[le]),Ne=a??ie?.appearance,Oe=n?"embedded_checkout":"standard_checkout",ue=ne?"custom_layout":U==="buttons"?"buttons_layout":"default_layout",[k,Q]=bt(null),[Z,ze]=bt(null),ut=jt(null),[qe,ot]=bt(null),N=jt(null),[V,Ze]=bt(null),[Te,at]=bt(e??""),He=e??Te,je=n?"":He,[ln,f]=bt(!0),[be,pt]=bt(null),[et,Je]=bt("full"),[Ve,Xe]=bt(!1),[Ie,$e]=bt(xe),[It,Ye]=bt(null),[Fn,vt]=bt(null),[Dn,cn]=bt(void 0),[gn,tn]=bt(""),[Ln,Ut]=bt(!1),[Et,Vt]=bt(!1),Xt=jt(0),[Ft,Kt]=bt("loading"),[Dt,re]=bt(0),nn=jt(!1),T=jt(!1),gt=jt(!1),mt=jt(null),Ct=fn(()=>({checkoutMode:ke??et,layout:ne?"unknown":U==="buttons"?"buttons":"embedded"}),[ke,ne,et,U]),Ee=jt(B);Ee.current=B;let Ue=jt(h);Ue.current=h;let Kn=jt(R);Kn.current=R,Bn(()=>{At(Z)?.setCheckoutContext(Ct),qe&&qe!==Z&&At(qe)?.setCheckoutContext(Ct)},[Z,qe,Ct]);let Nn=jt(Y);Nn.current=Y;let Hn=rr(g=>{Kt(g),!(g!=="exhausted"||gt.current)&&(gt.current=!0,Ue.current?.(new Pt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),or=rr(()=>{Kt("retrying"),re(g=>g+1)},[]);Bn(()=>{Kt("loading"),re(0),gt.current=!1},[He]),Bn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ni,checkout_type:Oe,checkout_layout:ue,billing_api_url:E})},[ue,Oe,E]);let Ht=fn(()=>n?hn(n,!0):"",[n]),it=fn(()=>gn===Ht?Dn:void 0,[Dn,gn,Ht]),Lt=fn(()=>n?qo(n,it):void 0,[n,it]),Wt=ke??Lt?.checkoutMode??"full",ht=fn(()=>Lt?{...Lt,checkoutMode:Wt}:void 0,[Lt,Wt]);Bn(()=>{cn(void 0),tn(Ht)},[Ht]),Bn(()=>{$e(xe)},[xe]);let Qt=rr((g,q,O)=>{ct(()=>{Kn.current?.(kt(g,q,O))})},[ct]),Yt=rr(async(g,q)=>{$e(null),vt(null),Ye("processing");let O=q?.sessionId??g.id,pe=ut.current??N.current,H=At(pe),se=pe?null:Co(E,o,Ct),C={log:A=>{H?H.log(A):se?.log(A)},error:A=>{H?H.error(A):se?.error(A)},terminal:A=>{H?H.terminal(A):se?.terminal(A)},performance:A=>{H?H.performance(A):se?.performance(A)},now:()=>H?.now()??se?.now()??0,elapsed:A=>H?.elapsed(A)??Math.max(0,(se?.now()??A)-A)},c=C.now(),s=!!(q?.initialAutoProcessingError||q?.initialAutoProcessingPending),M=!1,m,G=()=>{M||(M=!0,s=!0,m=C.now(),C.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),C.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Se=!1,tt=()=>{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"}),m!==void 0&&C.performance({stage:"recovery",durationMs:C.elapsed(m),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=_i(q?.initialAutoProcessingError),y;if(A)G(),A.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Fi({sessionId:O,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey}),y=await go(A,{flopay:ut.current,paypalFlopay:N.current,attempt3DS:q?.attempt3DS,billingApiUrl:E,sessionId:O,session:g,telemetry:!1}),A.type==="paypal_redirect_required"&&sa();else if(q?.initialAutoProcessingPending){let j=await new bo(E,{telemetry:!1}).waitForCheckoutSessionCompletion(q.initialAutoProcessingPending.sessionId,{initialDelayMs:q.initialAutoProcessingPending.retryAfterMs});if(j.data.session?.status!=="complete")throw new Pt("Automatic payment failed. Please try again.","api_error",{code:j.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});y={status:"succeeded"}}else{if(q?.initialAutoProcessingError)throw qn(q.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:q.initialAutoProcessingError.checkoutMethod});if(q?.fromCreateSession)return q?.fallbackToFull&&(Je("full"),Li("full")),!1;{let D=await Pr({billingApiUrl:E,sessionId:O,session:g,telemetry:!1});D.type==="success"?y=D.result:(G(),D.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Fi({sessionId:O,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey}),y=await go(D,{flopay:ut.current,paypalFlopay:N.current,attempt3DS:q?.attempt3DS,billingApiUrl:E,sessionId:O,session:g,telemetry:!1}),D.type==="paypal_redirect_required"&&sa())}}O&&mr(O),tt(),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 qr(Tn),he=()=>Ee.current?.(y)}catch(A){let y=nr(A),D=y.checkoutMethod??$r;return $e(y.message),vt(y.message),q?.fallbackToFull&&(C.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Je("full"),Li("full")),tt(),!!(y.declineCode||y.code?.toLowerCase().includes("declin"))?C.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):y.type==="validation_error"?C.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):C.error({errorCode:s?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:s?"recovery":"processing",paymentMethodCategory:"saved"}),ct(()=>Ue.current?.(y)),Qt(D,y,{code:y.code,declineCode:y.declineCode}),Ye("error"),await Promise.allSettled([qr(Cn),q?.ensureProvidersReady?q.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{tt(),se&&jr(se),Ye(null),vt(null)}return ct(he),!0},[Qt,ct,nr,E,o,Ct]);Bn(()=>{if(typeof window>"u"||T.current)return;let g=new URLSearchParams(window.location.search),q=g.get("payment_intent_client_secret");if(!q)return;let O=Cl();O&&(T.current=!0,(async()=>{let pe,H=0;$e(null),vt(null),Ye("processing"),Xe(!0);try{if(g.get("redirect_status")==="failed")throw Object.assign(new Pt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:se,paypalFlopay:C}=await Po({publishableKey:O.publishableKey,paypalPublishableKey:O.paypalPublishableKey,billingApiUrl:E,locale:u,telemetry:o});pe=At(C??se),H=pe?.now()??0,pe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),pe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let c=(C??se)?.getRawProvider();if(!c)throw Object.assign(new Pt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:s,error:M}=await c.retrievePaymentIntent(q);if(M)throw Object.assign(new Pt(M.message??"Failed to retrieve PayPal payment status.","api_error",{code:M.code}),{checkoutMethod:"paypal"});let m=Za(s?.status);if(!s||m==="failed")throw Object.assign(new Pt("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=m;if(O.sessionId){let A=(await new bo(E,{telemetry:!1}).getUnifiedCheckoutSession(O.sessionId)).data.session;if(A&&A.status!=="complete"){let y=await Pr({billingApiUrl:E,sessionId:O.sessionId,session:A,telemetry:!1,tokenizedData:{id:G??s.id,type:"card",threeDSecureActionResultTokenId:s.id,isPaypal:!0}});if(y.type!=="success")throw Object.assign(new Pt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Se=y.result.status}}O.sessionId&&mr(O.sessionId),pe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),pe?.performance({stage:"redirect_resume",durationMs:pe.elapsed(H),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),pe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ye("success"),await qr(Tn),ct(()=>Ee.current?.({status:Se,paymentIntentId:s.id,paymentMethodId:G,checkoutMethod:"paypal"}))}catch(se){let C=nr(se),c=C.checkoutMethod??"paypal",s=!!(C.declineCode||C.code?.toLowerCase().includes("declin"));if(pe)pe.performance({stage:"redirect_resume",durationMs:pe.elapsed(H),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),s?pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):pe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(s){let M=Co(E,o,Ct);M.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),jr(M)}else aa(E,o,Ct,"REDIRECT_RESUME_FAILED","redirect_resume");$e(C.message),vt(C.message),ct(()=>Ue.current?.(C)),Qt(c,C,{code:C.code,declineCode:C.declineCode}),Ye("error"),await qr(Cn)}finally{sa(),Il(),Ye(null),vt(null),Xe(!1)}})())},[Qt,ct,u,nr,E,o]);let dn=jt(null);function hn(g,q=!1){let O=g?.account?.email?.trim().toLowerCase()??"",pe={c:g?.clientId,cur:g?.currency??"",a:{e:O,u:O?"":g?.account?.userId??"",country:g?.account?.country??""},successUrl:g?.successUrl,cancelUrl:g?.cancelUrl,p:g?.products?.map(C=>la(`${C.type??""}:${C.code??C.providerItemId??C.providerPlanId??""}`,C)).sort(),i:g?.items?.map(C=>la(C.code??C.providerItemId??"",C)).sort(),s:g?.subscriptions?.map(C=>la(C.code??C.providerPlanId??"",C)).sort(),couponCodes:g?.couponCodes?[...g.couponCodes].sort():void 0,...q?{tagsData:g?.tagsData,utmMetadata:g?.utmMetadata,tokenizedData:g?.tokenizedData,checkoutMode:g?.checkoutMode??"full"}:{}},H=JSON.stringify(pe),se=0;for(let C=0;C<H.length;C++)se=(se<<5)-se+H.charCodeAt(C)|0;return`flopay_session_${Math.abs(se).toString(36)}`}let _t=fn(()=>ht?hn(ht):"",[ht]),$t=jt(ht);$t.current=ht,Bn(()=>{at(e??"")},[e]),Bn(()=>{nn.current=!1,$e(xe),vt(null),Ye(null)},[_t,xe,e]);async function Ae(g,q){let O=Co(E,o,Ct),pe=new bo(E,{telemetry:!1}),H=!1;try{let se=g.idempotencyKey!==void 0?Bi(g.idempotencyKey):void 0,C=se??wl(q),c,s=!1,M=Sl(q);O.log({name:M?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let m=M?.sid??null,G=null,Se;if(m)try{if(G=await pe.getUnifiedCheckoutSession(m,M?.nonce),G.data.session?.status==="complete"){if(Vo(m))return{sid:m,result:G};Rl(q),m=null,G=null,s=!0}}catch{O.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),da(q),m=null}if(!m){!se&&(s||!C)&&(C=Bi(),c=C),C&&kl(q,C);let tt=O.now(),he=0;O.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let A={...g,idempotencyKey:C,avsCheck:!!_e,avsConfig:typeof _e=="object"?_e:void 0,checkoutType:"embedded_checkout",checkoutLayout:ne?"custom_layout":U==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(A,yl,{configurable:!1,enumerable:!1,value:{onAttempt:j=>{he=Math.max(he,j)}}});let y=()=>{O.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),O.performance({stage:"session_create",durationMs:O.now()-tt,durationMode:"machine",requestCategory:"session_create",attempt:he,statusClass:"2xx"})},D=j=>{let We=fl(j,"CHECKOUT_SESSION_CREATE_FAILED","unknown");O.performance({stage:"session_create",durationMs:O.now()-tt,durationMode:"machine",requestCategory:"session_create",attempt:he,statusClass:We.statusClass}),j instanceof Pt&&j.type==="validation_error"?O.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):We.statusClass==="4xx"?O.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):O.error({...We,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if(gl(A)){let j=await pe.createDetachedSession(A);j.claimed.catch(()=>{}),G=j.shell,m=j.sessionId,Se=j.claimed.then(We=>{let Tt=We.data.session?.id??j.sessionId;return Tt&&Di(q,Tt,We.data.session?.clientSecret??j.nonce),y(),We},We=>{throw da(q),D(We),We}).finally(()=>jr(O)),Se.catch(()=>{}),H=!0,O.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),O.performance({stage:"session_shell",durationMs:O.now()-tt,durationMode:"machine",requestCategory:"session_create",attempt:he,statusClass:"2xx",paymentMethodCategory:"card"})}else G=await pe.createAndFetchSession(A),y()}catch(j){throw D(j),j}m=G.data.session?.id??m??"",m&&!Se&&Di(q,m,G.data.session?.clientSecret)}return{sid:m??"",result:G,sdkGeneratedIdempotencyKey:c,...Se?{claimed:Se}:{}}}finally{H||jr(O)}}let St=rr(async(g,q)=>{let O=$t.current;if(!O)throw new Pt("createSession is required to bootstrap checkout.","validation_error");let pe=qo(O,g),H=hn(pe),se=So.get(H);if(!se){let s={promise:Ae(pe,H),consumers:0,settled:!1};se=s,So.set(H,s);let M=()=>{s.settled=!0,Ai(H,s)};s.promise.then(M,M)}se.consumers+=1;let C=!1,c=()=>{C||(C=!0,se.consumers-=1,Ai(H,se))};q?.(c);try{let s=await se.promise;dn.current=H,g&&(tn(Ht),cn(y=>Xa(y,g)));let{sid:M,result:m,claimed:G}=s;if(Q(m),m.data.session&&Ze(m.data.session),M&&at(M),G){let y=Xt.current+=1;Vt(!0),G.then(D=>{Xt.current===y&&(Q(D),D.data.session&&Ze(D.data.session),Vt(!1))},D=>{Xt.current===y&&(Vt(!1),pt(D instanceof Pt?D:new Pt(D instanceof Error?D.message:"Failed to create session","api_error")))})}else Xt.current+=1,Vt(!1);let{publishableKey:Se,paypalPublishableKey:tt}=ho(m),{flopay:he,paypalFlopay:A}=await Po({publishableKey:Se,paypalPublishableKey:tt,billingApiUrl:E,locale:u,telemetry:o});return ut.current=he,ze(he),N.current=A,ot(A),f(!1),s}catch(s){throw dn.current===H&&(dn.current=null),s}finally{q||c()}},[u,E,o,Ct]),wt=jt(Yt);wt.current=Yt;let Pn=jt(St);Pn.current=St;let Wn=rr(async g=>{if(!El(g)||Ln)return{sessionId:Te,session:V};Ut(!0);try{let q=await St(g);return{sessionId:q.sid,session:q.result.data.session??null}}finally{Ut(!1)}},[St,Ln,Te,V]);Bn(()=>{let g=!1,q;if(pt(null),_t){let H=$t.current;return Je(Wt),f(!1),dn.current===_t?()=>{g=!0}:(Ze(Qa(H,ke)),(async()=>{let se=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),C=Wt==="auto"&&!nn.current&&!se;C&&($e(null),vt(null),Ye("processing"));try{let c=await Pn.current(void 0,G=>{q=G}),s=c.result.data.session??null;mt.current=ho(c.result);let M=ia(c.result),m=Vo(c.sid||s?.id);if(!g&&C&&s&&!M&&!m){nn.current=!0,await bl(_t,c.sdkGeneratedIdempotencyKey,()=>wt.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}!g&&C&&((M||m)&&(nn.current=!0),Ye(null),vt(null))}catch(c){if(g)return;let s=c instanceof Pt||typeof c=="object"&&c!==null&&"code"in c?c.code:void 0;if(C&&s==="session_auto_completed"){nn.current=!0,Ye("success"),await qr(Tn),g||(ct(()=>{Ee.current?.({status:"succeeded"})}),Ye(null),vt(null));return}C&&(Ye(null),vt(null));let M=c instanceof Pt?c:new Pt(c instanceof Error?c.message:"Failed to create session","api_error");pt(M)}finally{q?.(),q=void 0}})(),()=>{g=!0,q?.()})}f(!0);async function O(){let H=!1;try{let C=await new bo(E,{telemetry:!1}).getUnifiedCheckoutSession(He,t);if(g)return;Q(C);let c=C.data.session??null;if(Ze(c),!c)throw new Pt("No session data returned","api_error");if(c.status==="complete"){f(!1),ct(()=>{Nn.current?.(c.successUrl??"")});return}if(c.status==="expired")throw new Pt("Checkout session has expired.","api_error",{code:"checkout_session_expired"});H=!0;let s=ke??c.checkoutMode??"full";Je(s);let M=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),m=ia(C);if(s==="auto"&&!nn.current&&!M&&!m){nn.current=!0;let G=pe(C);try{if(await wt.current(c,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>G,sessionId:He||c.id}),g)return;await G,g||f(!1);return}catch{if(g)return;await G,g||f(!1);return}}await pe(C),g||f(!1)}catch(se){if(g)return;se instanceof Pt?!H&&!vl(se)&&aa(E,o,Ct,"NETWORK_REQUEST_FAILED","session_read"):aa(E,o,Ct,"INTERNAL_SDK_ERROR","checkout_mount");let C=se instanceof Pt?se:new Pt(se instanceof Error?se.message:"Failed to initialize checkout","api_error");pt(C),f(!1)}}async function pe(H){let{publishableKey:se,paypalPublishableKey:C}=ho(H);mt.current={publishableKey:se,paypalPublishableKey:C};let{flopay:c,paypalFlopay:s}=await Po({publishableKey:se,paypalPublishableKey:C,billingApiUrl:E,locale:u,telemetry:o});ut.current=c,ze(c),N.current=s,ot(s)}return O(),()=>{g=!0}},[ke,_t,Wt,je,ct,t]);let Gt=rr(async()=>{if(!(Ve||!V)){Xe(!0),$e(null);try{await Yt(V,{attempt3DS:!0,fallbackToFull:!0,sessionId:He||V.id})}finally{Xe(!1)}}},[He,Ve,Yt,V]),Zt=ca(k),Nt=ia(k),En=fn(()=>{if(!k||!V||!k.data.stripe?.publishableKey)return;let g={appearance:Ne,paymentMethodCreation:"manual",billingApiUrl:E};if(k.data.stripe?.clientSecret)g.clientSecret=k.data.stripe.clientSecret;else{let q=Mi(V).total;g.amount=Math.round(q*100)||V.amount,g.currency=V.currency?.toLowerCase()}return g},[k,V,Ne,E]),On=!!(n&&!ne&&U==="buttons"&&de&&Wt==="full"),un=fn(()=>({session:V,loading:ln,error:be,checkoutMode:et,inlineSessionDraft:ht,applyInlineSessionPatch:On?Wn:void 0,inlineSessionPatchProcessing:Ln,claimPending:Et}),[V,ln,be,et,ht,On,Wn,Ln,Et]),en=!!n&&U==="buttons"&&!Nt&&(!Z||!En),xt=It?oe(Sn,{status:It,errorMessage:Fn}):null;if(ln){if(l)return Rt(In,{children:[l,xt]});if(U==="buttons"){let g=ie?.buttonsLayout?.cardButton?.borderRadius??ie?.appearance.variables?.borderRadius??8,q=O=>oe("div",{style:{height:O,borderRadius:g,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Rt(In,{children:[Rt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[d&&q(br),b&&(x||P)&&q(br),b&&q(br),oe("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),xt]})}return Rt(In,{children:[Rt("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); } }"})]}),xt]})}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?Rt(In,{children:[oe(yn.Provider,{value:un,children:oe(xl,{onButtonClick:K,showPayPal:d,showStripe:b,showApplePay:x,showGooglePay:P,theme:le,buttonsTheme:ee,buttonsStyles:F,cardButtonContent:J,cardBackButtonContent:W,cardTitleContent:ce})}),xt]}):Nt&&V&&Zt?Rt(In,{children:[oe(yn.Provider,{value:un,children:Rt("div",{className:ge,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ie&&oe(ur,{icon:!1,children:Ie}),Ft==="retrying"&&oe("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ft==="exhausted"&&Rt("div",{role:"alert",children:[oe("div",{children:"PayPal is temporarily unavailable. Please try again."}),oe("button",{type:"button",onClick:or,children:"Retry PayPal"})]}),Ft!=="exhausted"&&oe("div",{"aria-hidden":Ft==="retrying"?!0:void 0,style:Ft==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:oe(ii,{sessionId:He,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:$e,onDecline:R,onButtonClick:K,onInitializationStateChange:Hn,allowAutomaticRetry:Dt===0,session:V,telemetry:o,telemetryContext:Ct,debug:ae},`paypal-init-${Dt}`)})]})}),xt]}):!Z||!En?oe(In,{children:xt}):et==="confirm"?Rt(In,{children:[oe(yn.Provider,{value:un,children:oe(ro,{flopay:Z,paypalFlopay:qe,options:En,children:Rt("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:Ve}):oe("button",{type:"button",onClick:Gt,disabled:Ve,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Ve?"not-allowed":"pointer",opacity:Ve?.6:1},children:Ve?"Processing...":Re??"Confirm Purchase"})]})})}),xt]}):Rt(In,{children:[oe(yn.Provider,{value:un,children:oe(ro,{flopay:Z,paypalFlopay:qe,options:En,children:ne?Rt(In,{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(_l,{sessionId:He,nonce:V?.clientSecret||void 0,billingApiUrl:E,session:V,children:ne})]}):oe(na,{sessionId:He,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(Mi(V).total*100):0,currency:V?.currency?.toLowerCase()??"usd",onComplete:B,onError:h,onDecline:R,error:Ie,onErrorChange:$e,showPayPal:d,showStripe:b,enabledPaymentMethods:I??k?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:k?.data.stripe?.enabledPaymentMethodCountries,showApplePay:x,showGooglePay:P,layout:U,theme:le,buttonsTheme:ee,buttonsStyles:F,appearance:Ne,cardButtonContent:J,cardBackButtonContent:W,cardTitleContent:ce,onButtonClick:K,onBeforeButtonClick:de,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:_,avsCheck:!!_e,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ne?"custom_layout":U==="buttons"?"buttons_layout":"default_layout",className:ge,directPaypal:ca(k),isSubscription:V?.mode==="subscription",session:V,dataAttachmentPending:Et,debug:ae})})}),xt]})}function _l({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:o}){return oe(In,{children:oa.Children.map(o,a=>{if(!oa.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:oa.cloneElement(a,l)})})}function xl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:i,showGooglePay:o,theme:a,buttonsTheme:u,buttonsStyles:l,cardButtonContent:w,cardBackButtonContent:B,cardTitleContent:h}){let[R,S]=bt(!1),_=fn(()=>Oi(a),[a]),d=fn(()=>{let P=_?.buttonsLayout??Pl(u);return l?{...P,...l,cardButton:{...P.cardButton,...l.cardButton},cardFormContainer:{...P.cardFormContainer,...l.cardFormContainer},backButton:{...P.backButton,...l.backButton},backButtonIcon:{...P.backButtonIcon,...l.backButtonIcon},submitButton:{...P.submitButton,...l.submitButton},title:{...P.title,...l.title}}:P},[_,u,l]),b=_?.buttonsLayout?.cardButton?.borderRadius??_?.appearance.variables?.borderRadius??8,I=P=>oe("div",{style:{height:P,borderRadius:b,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),x=w===void 0?{boxSizing:"border-box",height:br,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(R){let P=d.cardInputBorder??"#e5e7eb",ae=d.cardInputBackground??"white",U=sr(B),le=sr(h);return Rt("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:[Rt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Rt("button",{type:"button",onClick:()=>S(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:U?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})]}),le?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(Dr,{content:h})})]}),oe("div",{style:{backgroundColor:ae,border:`1px solid ${P}`,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"}})}),Rt("div",{style:{display:"flex"},children:[oe("div",{style:{flex:1,backgroundColor:ae,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,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:ae,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,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:ae,border:`1px solid ${P}`,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
|
+
`}),Fr&&Wn&&Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ke?-2:0},children:[Le("button",{type:"button",onClick:On,style:{display:"inline-flex",alignItems:"center",gap:$o?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(dr,{content:V})]}),Ka?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(Nr,{content:le})})]}),!Fr&&!Ka&&u("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:qo,order:Ke?-3:0,...y.title},children:u(Nr,{content:le})}),Q&&u("div",{style:{order:Ke?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let o=We,b=(N=!1)=>({backgroundColor:Lr,border:`1px solid ${Yn(N)}`,borderRadius:bt,marginTop:"0.5rem",padding:"10px"}),q=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ga}),X=Gs(o);return Le(Pr,{children:[De(Q.address_line_1,o)&&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:N=>{wt.current.addressLine1=!0,Zt.current=N.target.value,et(N.target.value)},disabled:G,required:!0,"data-testid":"flopay-address-line1",style:q()})}),De(Q.address_line_2,o)&&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:Je,onChange:N=>{wt.current.addressLine2=!0,en.current=N.target.value,Rn(N.target.value)},disabled:G,"data-testid":"flopay-address-line2",style:q()})}),(De(Q.city,o)||De(Q.state,o))&&Le("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[De(Q.city,o)&&u("div",{style:{flex:1,backgroundColor:Lr,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:bt,borderBottomLeftRadius:bt,...De(Q.state,o)?{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:rt,onChange:N=>{wt.current.city=!0,Ft.current=N.target.value,Vn(N.target.value)},disabled:G,required:!0,"data-testid":"flopay-city",style:q()})}),De(Q.state,o)&&u("div",{style:{flex:1,backgroundColor:Lr,border:`1px solid ${Yn(Pt.state)}`,padding:"10px",borderTopRightRadius:bt,borderBottomRightRadius:bt,...De(Q.city,o)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:bt}},children:X?Le("select",{id:"flopay-billing-state",name:"billing-state",value:Wt,onChange:N=>{wt.current.state=!0,Dt.current=N.target.value,yn(N.target.value)},disabled:G,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...q(),cursor:"pointer"},children:[u("option",{value:"",children:hi(o)}),X.map(N=>u("option",{value:N.code,children:N.name},N.code))]}):u("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:hi(o),autoComplete:"billing address-level1",value:Wt,onChange:N=>{wt.current.state=!0,Dt.current=N.target.value,yn(N.target.value)},disabled:G,required:!0,"data-testid":"flopay-state",style:q()})})]}),(De(Q.country,o)||De(Q.postal_code,o))&&Le("div",{style:{display:"flex",flexDirection:te==="column"?"column":"row",gap:te==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[De(Q.country,o)&&u("div",{style:{flex:te==="row"?1:void 0,backgroundColor:Lr,borderTop:`1px solid ${Dr}`,borderRight:`1px solid ${Dr}`,borderBottom:`1px solid ${Dr}`,borderLeft:`1px solid ${Dr}`,padding:"10px",...te==="row"&&De(Q.postal_code,o)?{borderRadius:"0",borderTopLeftRadius:bt,borderBottomLeftRadius:bt,borderRight:"none"}:{borderRadius:bt}},children:u("select",{id:"flopay-billing-country",name:"billing-country",value:We,onChange:N=>{wt.current.country=!0,kt.current=N.target.value,Ie(N.target.value),$e?.(N.target.value),Dt.current="",yn("")},disabled:G,autoComplete:"billing country","data-testid":"flopay-country",style:{...q(),cursor:"pointer"},children:Js.map(N=>Le("option",{value:N.code,children:[N.flag," ",N.name]},N.code))})}),De(Q.postal_code,o)&&u("div",{style:{flex:te==="row"?1:void 0,backgroundColor:Lr,border:`1px solid ${ms}`,padding:"10px",...te==="row"&&De(Q.country,o)?{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:aa(We),autoComplete:"billing postal-code",value:St,onChange:N=>{wt.current.zip=!0,Bt.current=N.target.value,Ve(N.target.value),ze?.(N.target.value)},onBlur:()=>Yt(!0),disabled:G,required:zt.required,"aria-invalid":ao||void 0,"aria-describedby":ao?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:q()})})]}),ao&&u("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:No,...Ga,fontSize:"0.75rem"},children:zt.empty?`${aa(o)} is required`:gl(o)})]})})()}),Ke&&Me&&u("div",{style:{order:-2,width:"100%"},children:Me}),Ke&&Ps,f&&u(pr,{margin:"0.75rem 0",styleOverride:y.errorBanner,children:f})]}),io={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"},Xa=o=>Ze?!k||!Pn?u("pre",{"data-testid":o,style:io,children:"FloPay/DirectPayPal-debug - not enabled"}):u("pre",{"data-testid":o,style:io,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${k}`,` directPaypalConfigured=${Pn}`,` inAppBrowserDetected=${String(ro)}`,` shouldRenderDirectPayPal=${Tr}`,` shouldRenderStripePayPal=${Mr}`,` hasPaypalStripeInstance=${!!we}`].join(`
|
|
39
|
+
`)}):null,Qa=o=>Ze?!I||!me?u("pre",{"data-testid":o,style:io,children:"FloPay/Stripe-debug - not enabled"}):u("pre",{"data-testid":o,style:io,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${I}`,` currency=${Re}`,` amountInCents=${xe}`,` enabledPaymentMethods: ${JSON.stringify(g??[])}`,` enabledPaymentMethodsProvided=${_r}`,` hasEnabledMethods=${Zr}`,` expressMethods: ${JSON.stringify(eo)}`,` walletExpressMethods: ${JSON.stringify(to)}`,` paymentElementMethods: ${JSON.stringify(xr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(no)}`,` hasStripeInstance=${!!me}`,` shouldRenderWallets=${Ar}`,` shouldRenderPaymentElement=${Br}`].join(`
|
|
40
|
+
`)}):null,Za=_e==="apm-expanding"||_e==="apm-form"||_e==="apm-collapsing",so=_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,lo=yt?{...Fo,paymentMethodTypes:[yt]}:null;if(Z==="buttons"){let o=_e==="buttons"||_e==="expanding"||_e==="apm-expanding",b=_e==="expanding"||_e==="card"||_e==="collapsing",q=j===void 0?{boxSizing:"border-box",height:Co,padding:"0 1rem"}:{padding:"0.9rem 1rem"},X=_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,N=_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:zo,className:S,style:{position:"relative"},children:[u(oa,{}),rn&&u(Cn,{status:rn,errorMessage:f,authorized:F}),Le("div",{style:{display:"grid"},children:[Le("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!o&&!X?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!o&&!X?ml:{},...X?{animation:X,pointerEvents:"none"}:{}},children:[Xa("flopay-direct-paypal-gate-debug"),Qa("flopay-stripe-gate-debug"),Tr&&Ge&&Le(Pr,{children:[he&&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(bo,{sessionId:e,nonce:t,billingApiUrl:r,email:p.email,clientId:Ge.clientId,environment:Ge.environment,currency:Re.toUpperCase(),isSubscription:pt,onTokenizedBody:on,onComplete:i,onErrorChange:ce,onDecline:l,onTechnicalFailure:ir,onButtonClick:Pe,runBeforeButtonClick:un,isProcessing:G,onLoadStateChange:Do,onInitializationStateChange:Lo,session:M??null,existingOrderId:he?.orderId,debug:Ze},he?.orderId??"fresh")]}),Mr&&u(nr,{stripe:we,options:Ia,children:u(Ei,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,onTokenizedBody:on,onErrorChange:ce,isProcessing:G,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ir,runBeforeButtonClick:un,onLoadStateChange:Ta,placeholderBorderRadius:Gn})}),Ar?u(nr,{stripe:me,options:Qr,children:u(_i,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,intentKind:W>0?"payment":"setup",expressMethods:to,onTokenizedBody:on,onErrorChange:ce,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ir,runBeforeButtonClick:un,onLoadStateChange:Aa,placeholderBorderRadius:Gn})}):za?u("div",{style:{height:Co,borderRadius:Gn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Br&&u(xi,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,paymentElementMethods:no,stripeInstance:me,paymentElementBaseOptions:Fo,onTokenizedBody:on,onErrorChange:ce,onButtonClick:Pe,onDecline:l,runBeforeButtonClick:un,onLoadStateChange:Fa,isProcessing:G,submitButtonColor:Jn,submitButtonBorderRadius:bt,submitButtonStyle:y.submitButton,onExpandApm:nn,expandedApmMethod:yt,themeId:O,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:Gn}}),Ke&&u("button",{type:"button",onClick:async()=>{G||!(await un("card")).proceed||(Pe?.("card"),zn())},disabled:G,style:{width:"100%",...q,...y.cardButton,...da({themeBundle:A,resolvedPrimaryColor:Jn,resolvedBorderRadius:bt,submitButtonStyle:y.submitButton,explicitPrimaryColor:Kt?.colorPrimary}),fontSize:y.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:G?"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:G?.6:1},onMouseEnter:ue=>{!G&&(A||Kt?.colorPrimary)&&(ue.currentTarget.style.backgroundColor=gs)},onMouseLeave:ue=>{(A||Kt?.colorPrimary)&&(ue.currentTarget.style.backgroundColor=Jn)},onMouseDown:ue=>{ue.currentTarget.style.transform="scale(0.985)"},onMouseUp:ue=>{ue.currentTarget.style.transform="scale(1)"},children:u(cr,{content:j})}),f&&_e==="buttons"&&u(pr,{margin:"0.25rem 0",styleOverride:y.errorBanner,children:f})]}),Ke&&b&&u("div",{style:{gridArea:"1 / 1",...N?{animation:N}:{},..._e==="collapsing"?{pointerEvents:"none"}:{}},children:Ja}),I&&Za&&yt&&lo&&me&&u("div",{style:{gridArea:"1 / 1",...so?{animation:so}:{},..._e==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Uo,borderRadius:Vo,...zr,padding:jo},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:$o?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(dr,{content:V})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:qo,paddingRight:80,...y.title},children:`Pay with ${br(yt)}`})]}),u(nr,{stripe:me,options:lo,children:u(ia,{method:yt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,onTokenizedBody:on,onErrorChange:ce,onDecline:l,onCancel:Gt,runBeforeButtonClick:un,onButtonClick:Pe,isProcessing:G,submitButtonColor:Jn,submitButtonBorderRadius:bt,submitButtonStyle:y.submitButton,errorText:f})},yt)]})})]})]})}return Za&&yt&&lo&&me&&I?Le("form",{onSubmit:zo,className:S,style:{position:"relative"},children:[u(oa,{}),rn&&u(Cn,{status:rn,errorMessage:f,authorized:F}),u("div",{style:{...so?{animation:so}:{},..._e==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Uo,borderRadius:Vo,...zr,padding:jo},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:$o?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(dr,{content:V})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:qo,paddingRight:80,...y.title},children:`Pay with ${br(yt)}`})]}),u(nr,{stripe:me,options:lo,children:u(ia,{method:yt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,onTokenizedBody:on,onErrorChange:ce,onDecline:l,onCancel:Gt,runBeforeButtonClick:un,onButtonClick:Pe,isProcessing:G,submitButtonColor:Jn,submitButtonBorderRadius:bt,submitButtonStyle:y.submitButton,errorText:f})},yt)]})})]}):Le("form",{onSubmit:zo,className:S,style:{position:"relative"},children:[u(oa,{}),rn&&u(Cn,{status:rn,errorMessage:f,authorized:F}),Le("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Xa("flopay-direct-paypal-gate-debug-default"),Qa("flopay-stripe-gate-debug-default"),Tr&&Ge&&Le(Pr,{children:[he&&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(bo,{sessionId:e,nonce:t,billingApiUrl:r,email:p.email,clientId:Ge.clientId,environment:Ge.environment,currency:Re.toUpperCase(),isSubscription:pt,onTokenizedBody:on,onComplete:i,onErrorChange:ce,onDecline:l,onTechnicalFailure:ir,onButtonClick:Pe,runBeforeButtonClick:un,isProcessing:G,onLoadStateChange:Do,onInitializationStateChange:Lo,session:M??null,existingOrderId:he?.orderId,debug:Ze},he?.orderId??"fresh")]}),Mr&&u(nr,{stripe:we,options:Ia,children:u(Ei,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,onTokenizedBody:on,onErrorChange:ce,isProcessing:G,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ir,runBeforeButtonClick:un,onLoadStateChange:Ta,placeholderBorderRadius:Gn})}),Ar&&u(nr,{stripe:me,options:Qr,children:u(_i,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,intentKind:W>0?"payment":"setup",expressMethods:to,onTokenizedBody:on,onErrorChange:ce,onButtonClick:Pe,onDecline:l,onTechnicalFailure:ir,runBeforeButtonClick:un,onLoadStateChange:Aa,placeholderBorderRadius:Gn})}),Br&&u(xi,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,paymentElementMethods:no,stripeInstance:me,paymentElementBaseOptions:Fo,onTokenizedBody:on,onErrorChange:ce,onButtonClick:Pe,onDecline:l,runBeforeButtonClick:un,onLoadStateChange:Fa,isProcessing:G,submitButtonColor:Jn,submitButtonBorderRadius:bt,submitButtonStyle:y.submitButton,themeId:O,onExpandApm:nn,expandedApmMethod:yt,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:Gn}})]}),Ke&&(cs||ls||ds)&&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&&Ja]})}import{loadFloPay as Li,PaymentAPI as Oi}from"@flopay/js";import{classifyPaymentRejection as Cl,FloPayError as nt,isAuthorizationOnlySession as Sl,isSetupIntentClientSecret as wl,normalizeCheckoutFailureOutcome as zi}from"@flopay/shared";var Wr="card";async function kl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:d}=await e.retrieveSetupIntent(t);return{error:d,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:s,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:s??null}}async function Rl(e,t,n,s){if(s){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:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function ma(e,t){return Object.assign(e,{checkoutMethod:t})}function An(e,t){let n=e instanceof nt?e:new nt(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 Hr(e,t){try{return await e()}catch(n){throw An(n,t)}}function Ni(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Il(e){return e.status==="succeeded"||e.status==="declined"}async function Ui(e){if(typeof document>"u"||typeof window>"u")throw new nt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new nt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,s=15e3,a=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let h=new AbortController,w=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",w);let S=window.setTimeout(()=>h.abort(),s);try{let B=await fetch(a,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!B.ok)return{status:"unknown"};let c=await B.json().catch(()=>null);return El(c)}catch{return{status:"unknown"}}finally{window.clearTimeout(S),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 C=document.createElement("iframe");C.setAttribute("title","Card authentication"),C.setAttribute("allow","payment"),C.tabIndex=0,C.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(";"),C.src=e.nextActionRedirectUrl,l.appendChild(C),document.body.appendChild(l),C.focus();let D=null;try{D=new URL(e.billingApiUrl,window.location.href).origin}catch{D=null}try{let h=await new Promise((w,S)=>{let B=!1,c=0,P=0,k=0,I=!1,g=()=>{window.clearTimeout(c),window.clearInterval(P),window.clearTimeout(k),window.removeEventListener("message",Z),C.removeEventListener("load",_),e.signal?.removeEventListener("abort",ae)},de=async()=>{if(!(B||I)){I=!0;try{let O=await i();if(B||!Il(O))return;B=!0,g(),w(O)}finally{I=!1}}},_=()=>{window.clearTimeout(k),k=window.setTimeout(()=>{de()},250)},ae=()=>{B||(B=!0,g(),S(new nt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Z=O=>{if(O.source!==C.contentWindow||D&&O.origin!==D)return;let J=O.data;!J||typeof J!="object"||J.source!=="flopay-vault-3ds-return"||B||(B=!0,g(),w(null))};c=window.setTimeout(()=>{B||(B=!0,g(),S(new nt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),P=window.setInterval(()=>{de()},n),C.addEventListener("load",_),window.addEventListener("message",Z),e.signal?.addEventListener("abort",ae),e.signal?.aborted&&ae()});return h||await i()}finally{l.parentNode?.removeChild(l),d?.isConnected&&d.focus()}}function El(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function qn(e,t="Payment failed. Please try again.",n){let s=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=Nn(a)??a;return ma(new nt(i,"api_error",{code:zi(e?.outcome)??zi(e?.type)??e?.gatewayErrorCode}),s)}function pa(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function wo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function _l(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 $i(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||wo(a)))return a;let s=e?.data;if(s&&typeof s=="object"){let a=s,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||wo(l)))return l;let d=a.gateways;if(d&&typeof d=="object"){let l=d.stripe;if(l&&typeof l=="object"){let C=l,D=[C.stripeClientSecret,C.clientSecret];for(let h of D)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||wo(h)))return h}}}}async function xl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:s}){let a=$i(s,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let l=(await new Oi(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(wo(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function vr({billingApiUrl:e,sessionId:t,session:n,nonce:s,tokenizedData:a,returnUrl:i,telemetry:d}){let l=e.replace(/\/+$/,""),C=t??n.id,D=s??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",w=n.customer?.email??n.accountData?.email??"",S=n.customer?.firstName??n.accountData?.firstName??"",B=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 Oi(l,d===!1?{telemetry:!1}:void 0),I=await _l(()=>k.processPayment(h,{sessionId:C,nonce:D,tokenizedData:a,accountData:{userId:h,email:w,firstName:S,lastName:B,country:c,zip:P},returnUrl:i??pa(n)}));if(I.ok){let _=typeof I.json=="function"?await I.json().catch(()=>null):null;return Sl(n)||_?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof _?.paymentId=="string"?_.paymentId:n.paymentId,sessionId:typeof _?.sessionId=="string"?_.sessionId:C,authorizationExpiresAt:typeof _?.authorizationExpiresAt=="string"?_.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:qr(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:a?.threeDSecureActionResultTokenId,paymentMethodId:qr(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}}let g;try{g=await I.json()}catch{throw new nt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:I.status})}if(g?.type==="paypal_redirect_required"||g?.type==="3ds_required"){let _=$i(g);if(!_)throw new nt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:I.status});return{type:g.type,threeDSecureToken:_,paymentMethodId:g.paymentMethodId}}if(g?.gatewayErrorCode==="authentication_required"){let _=await xl({billingApiUrl:l,sessionId:C,nonce:D,responseJson:g});if(_)return _;throw ma(new nt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let de=new nt(g?.message??"Payment failed. Please try again.","api_error",{code:g?.code??g?.gatewayErrorCode,declineCode:g?.declineCode??g?.gatewayDeclineReason,statusCode:I.status});throw Object.assign(de,{telemetryOutcome:Cl(I.status,g)})}async function ko(e,{flopay:t,paypalFlopay:n,attempt3DS:s,billingApiUrl:a,sessionId:i,session:d,returnUrl:l,telemetry:C}){let D=t?.getRawProvider();if(!D)throw An(new nt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!s||!e.threeDSecureToken)throw ma(new nt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=wl(e.threeDSecureToken),w=null,S=e.paymentMethodId,B=await Hr(()=>kl(D,e.threeDSecureToken,h),"card");if(B){if(B.error)throw An(new nt(B.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:B.error.code}),"card");let P=B.intent;!S&&P?.payment_method&&(typeof P.payment_method=="string"?S=P.payment_method:"id"in P.payment_method&&(S=P.payment_method.id??void 0))}let c=S?await Hr(()=>Rl(D,e.threeDSecureToken,{payment_method:S,return_url:l??pa(d)??window.location.href},h),"card"):null;if(c){if(c.error)throw An(new nt(c.error.message??"3DS authentication failed.","api_error",{code:c.error.code}),"card");w=c.intent}else{let P=await Hr(()=>D.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(P.error)throw An(new nt(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 vr({billingApiUrl:a,sessionId:i,session:d,telemetry:C,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??S}:ko(P,{flopay:t,paypalFlopay:n,attempt3DS:s,billingApiUrl:a,sessionId:i,session:d,returnUrl:l,telemetry:C})}throw An(new nt("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 nt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:S}=await Hr(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(S)throw An(new nt(S.message??"PayPal authorization failed.","api_error",{code:S.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:w}=await Hr(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??pa(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(w)throw An(new nt(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new nt("Unsupported payment redirect state.","api_error")}function rr(e){if(e instanceof nt){let s=Nn(e.message);return s&&s!==e.message?Object.assign(new nt(s,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Nn(t)??t;return new nt(n,"api_error")}function Ro(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new nt("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 Io({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:s,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[d,l]=await Promise.all([Li(e,{billingApiUrl:n,locale:s,telemetry:a}),i?Li(t,{billingApiUrl:n,locale:s,telemetry:a}).catch(C=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",C),null)):Promise.resolve(null)]);return{flopay:d,paypalFlopay:t?i?l:d:null}}import{Fragment as kn,jsx as ne,jsxs as Et}from"react/jsx-runtime";var Cr=44,Ca="flopay_checkout_saved_payment_resume",To=new Map,_o=new Map;function Ki(e,t){t.settled&&t.consumers===0&&To.get(e)===t&&To.delete(e)}function Dl(e,t,n){let s=_o.get(e);if(s&&(!s.sdkGeneratedIdempotencyKey||!t||s.sdkGeneratedIdempotencyKey===t))return s.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};_o.set(e,i);let d=()=>{_o.get(e)===i&&_o.delete(e)};return a.then(d,d),a}function Yr(e){return new Promise(t=>setTimeout(t,e))}function xo(e,t,n){let s=co({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Gi,enabled:t!==!1});return s.beginCheckout(n),s}function Gr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function fa(e,t,n,s,a){let i=xo(e,t,n);i.error({errorCode:s,stage:a,paymentMethodCategory:"unknown",...a==="session_read"?{requestCategory:"session_read"}:{}}),Gr(i)}function Ll(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 ba(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function ga(e){return!e||e.data.stripe?.publishableKey?!1:!!ba(e)?.clientId}function Fn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function zl(){if(!Fn())return null;try{let e=window.sessionStorage.getItem(Ca);return e?JSON.parse(e):null}catch{return null}}function Hi(e){if(Fn())try{window.sessionStorage.setItem(Ca,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ha(){if(Fn())try{window.sessionStorage.removeItem(Ca)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var Sa=":idempotency-key";function Ol(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 Wi(e,t,n){if(Fn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(s){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",s)}}function va(e){if(Fn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function Nl(e){if(Fn())try{return window.sessionStorage.getItem(e+Sa)??void 0}catch{return}}function Ul(e,t){if(Fn())try{window.sessionStorage.setItem(e+Sa,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function $l(e){if(va(e),!!Fn())try{window.sessionStorage.removeItem(e+Sa)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function ql(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let s of t)e.searchParams.has(s)&&(e.searchParams.delete(s),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Yi(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 Pa(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function wa({sessionId:e,nonce:t,createSession:n,billingApiUrl:s,telemetry:a,appearance:i,locale:d,loading:l,error:C,onComplete:D,onError:h,onDecline:w,onCountryChange:S,onZipChange:B,showPayPal:c=!0,showStripe:P=!0,enabledPaymentMethods:k,showApplePay:I=!0,showGooglePay:g=!0,debug:de=!1,layout:_,theme:ae,buttonsTheme:Z,buttonsStyles:O,cardButtonContent:J,cardBackButtonContent:H,cardTitleContent:ie,showSecurityFooter:j,onButtonClick:V,onBeforeButtonClick:le,enableAVS:Te,cardFieldOrder:Pe,cardPreFormSlot:pe,avsLayout:ee,className:fe,initialErrorMessage:Me=null,children:te,checkoutMode:Ue,confirmLabel:Fe,renderConfirmButton:ke,onSessionCompleted:K}){let v=Al(s),re=mn(()=>Ji(ae),[ae]),$e=i??re?.appearance,ze=n?"embedded_checkout":"standard_checkout",se=te?"custom_layout":_==="buttons"?"buttons_layout":"default_layout",[x,oe]=Ct(null),[W,Re]=Ct(null),dt=Nt(null),[Ge,pt]=Ct(null),M=Nt(null),[Y,Ze]=Ct(null),[qe,mt]=Ct(e??""),Oe=e??qe,He=n?"":Oe,[Jt,Ye]=Ct(!0),[Xt,R]=Ct(null),[ge,We]=Ct("full"),[Ie,St]=Ct(!1),[Ve,je]=Ct(Me),[et,Je]=Ct(null),[Rn,rt]=Ct(null),[Vn,Wt]=Ct(!1),[yn,Qt]=Ct(void 0),[ar,Bt]=Ct(""),[kt,Zt]=Ct(!1),[en,Ft]=Ct(!1),Dt=Nt(0),[wt,Q]=Ct("loading"),[Kn,F]=Ct(0),ot=Nt(!1),Lt=Nt(!1),Dn=Nt(!1),Ae=Nt(null),at=mn(()=>({checkoutMode:Ue??ge,layout:te?"unknown":_==="buttons"?"buttons":"embedded"}),[Ue,te,ge,_]),Ke=Nt(D);Ke.current=D;let In=Nt(h);In.current=h;let En=Nt(w);En.current=w,Bn(()=>{Mt(W)?.setCheckoutContext(at),Ge&&Ge!==W&&Mt(Ge)?.setCheckoutContext(at)},[W,Ge,at]);let Ln=Nt(K);Ln.current=K;let Hn=or(E=>{Q(E),!(E!=="exhausted"||Dn.current)&&(Dn.current=!0,In.current?.(new At("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),_n=or(()=>{Q("retrying"),F(E=>E+1)},[]);Bn(()=>{Q("loading"),F(0),Dn.current=!1},[Oe]),Bn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Gi,checkout_type:ze,checkout_layout:se,billing_api_url:v})},[se,ze,v]);let tt=mn(()=>n?Ut(n,!0):"",[n]),zt=mn(()=>ar===tt?yn:void 0,[yn,ar,tt]),ln=mn(()=>n?Jo(n,zt):void 0,[n,zt]),Pt=Ue??ln?.checkoutMode??"full",_t=mn(()=>ln?{...ln,checkoutMode:Pt}:void 0,[ln,Pt]);Bn(()=>{Qt(void 0),Bt(tt)},[tt]),Bn(()=>{je(Me)},[Me]);let tn=or((E,L,T)=>{ut(()=>{En.current?.(It(E,L,T))})},[ut]),cn=or(async(E,L)=>{je(null),rt(null),Wt(!1),Je("processing");let T=L?.sessionId??E.id,he=dt.current??M.current,be=Mt(he),m=he?null:xo(v,a,at),r={log:p=>{be?be.log(p):m?.log(p)},error:p=>{be?be.error(p):m?.error(p)},terminal:p=>{be?be.terminal(p):m?.terminal(p)},performance:p=>{be?be.performance(p):m?.performance(p)},now:()=>be?.now()??m?.now()??0,elapsed:p=>be?.elapsed(p)??Math.max(0,(m?.now()??p)-p)},f=r.now(),A=!!(L?.initialAutoProcessingError||L?.initialAutoProcessingPending),y=!1,U,Ee=()=>{y||(y=!0,A=!0,U=r.now(),r.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},it=!1,G=()=>{it||(it=!0,r.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),r.performance({stage:"processing",durationMs:r.elapsed(f),durationMode:"machine",paymentMethodCategory:"saved"}),U!==void 0&&r.performance({stage:"recovery",durationMs:r.elapsed(U),durationMode:"machine",paymentMethodCategory:"saved"}))};r.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),r.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),A&&Ee();let $;try{let p=Ni(L?.initialAutoProcessingError),z;if(p)Ee(),p.type==="paypal_redirect_required"&&Ae.current?.publishableKey&&Hi({sessionId:T,publishableKey:Ae.current.publishableKey,paypalPublishableKey:Ae.current.paypalPublishableKey}),z=await ko(p,{flopay:dt.current,paypalFlopay:M.current,attempt3DS:L?.attempt3DS,billingApiUrl:v,sessionId:T,session:E,telemetry:!1}),p.type==="paypal_redirect_required"&&ha();else if(L?.initialAutoProcessingPending){let xe=(await new Eo(v,{telemetry:!1}).waitForCheckoutSessionCompletion(L.initialAutoProcessingPending.sessionId,{initialDelayMs:L.initialAutoProcessingPending.retryAfterMs})).data.session;if(!yr(xe))throw yo(xe);z=Zn(xe,T)}else{if(L?.initialAutoProcessingError)throw qn(L.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:L.initialAutoProcessingError.checkoutMethod});if(L?.fromCreateSession)return L?.fallbackToFull&&(We("full"),Yi("full")),!1;{let me=await vr({billingApiUrl:v,sessionId:T,session:E,telemetry:!1});me.type==="success"?z=me.result:(Ee(),me.type==="paypal_redirect_required"&&Ae.current?.publishableKey&&Hi({sessionId:T,publishableKey:Ae.current.publishableKey,paypalPublishableKey:Ae.current.paypalPublishableKey}),z=await ko(me,{flopay:dt.current,paypalFlopay:M.current,attempt3DS:L?.attempt3DS,billingApiUrl:v,sessionId:T,session:E,telemetry:!1}),me.type==="paypal_redirect_required"&&ha())}}T&&fr(T),G(),A&&(r.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),r.terminal({outcome:z.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Wt(z.status==="authorized"),Je("success"),await Yr(Tn),$=()=>Ke.current?.(z)}catch(p){let z=rr(p),me=z.checkoutMethod??Wr;je(z.message),rt(z.message),Wt(!1),L?.fallbackToFull&&(r.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),We("full"),Yi("full")),G();let we=z.statusCode!==void 0?Fl(z.statusCode,"unknown"):void 0,xe=we==="4xx"?{requestCategory:"process_payment",statusClass:we}:{},gn=we===void 0||we==="4xx";if(gn&&(z.telemetryOutcome==="payment_declined"||!!(z.declineCode||z.code?.toLowerCase().includes("declin"))))r.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...xe});else if(gn&&(z.telemetryOutcome==="validation_rejected"||z.type==="validation_error"))r.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...xe});else{let Qr=qi(p,A?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");r.error({...Qr,...z.telemetryFailureCategory?{failureCategory:z.telemetryFailureCategory}:{},stage:A?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:z.telemetryRequestCategory??"process_payment"})}return ut(()=>In.current?.(z)),tn(me,z,{code:z.code,declineCode:z.declineCode}),Je("error"),await Promise.allSettled([Yr(vn),L?.ensureProvidersReady?L.ensureProvidersReady():Promise.resolve()]),A&&(r.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{G(),m&&Gr(m),Je(null),rt(null)}return ut($),!0},[tn,ut,rr,v,a,at]);Bn(()=>{if(typeof window>"u"||Lt.current)return;let E=new URLSearchParams(window.location.search),L=E.get("payment_intent_client_secret");if(!L)return;let T=zl();T&&(Lt.current=!0,(async()=>{let he,be=0;je(null),rt(null),Je("processing"),St(!0);try{if(E.get("redirect_status")==="failed")throw Object.assign(new At("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:m,paypalFlopay:r}=await Io({publishableKey:T.publishableKey,paypalPublishableKey:T.paypalPublishableKey,billingApiUrl:v,locale:d,telemetry:a});he=Mt(r??m),be=he?.now()??0,he?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),he?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let f=(r??m)?.getRawProvider();if(!f)throw Object.assign(new At("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:A,error:y}=await f.retrievePaymentIntent(L);if(y)throw Object.assign(new At(y.message??"Failed to retrieve PayPal payment status.","api_error",{code:y.code}),{checkoutMethod:"paypal"});let U=ci(A?.status);if(!A||U==="failed")throw Object.assign(new At("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Ee=typeof A.payment_method=="string"?A.payment_method:A.payment_method?.id,it=U;if(T.sessionId){let p=(await new Eo(v,{telemetry:!1}).getUnifiedCheckoutSession(T.sessionId)).data.session;if(p&&p.status!=="complete"){let z=await vr({billingApiUrl:v,sessionId:T.sessionId,session:p,telemetry:!1,tokenizedData:{id:Ee??A.id,type:"card",threeDSecureActionResultTokenId:A.id,isPaypal:!0}});if(z.type!=="success")throw Object.assign(new At("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});it=z.result.status}}T.sessionId&&fr(T.sessionId),he?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),he?.performance({stage:"redirect_resume",durationMs:he.elapsed(be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),he?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Je("success"),await Yr(Tn),ut(()=>Ke.current?.({status:it,paymentIntentId:A.id,paymentMethodId:Ee,checkoutMethod:"paypal"}))}catch(m){let r=rr(m),f=r.checkoutMethod??"paypal",A=!!(r.declineCode||r.code?.toLowerCase().includes("declin"));if(he)he.performance({stage:"redirect_resume",durationMs:he.elapsed(be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),A?he.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):he.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(A){let y=xo(v,a,at);y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Gr(y)}else fa(v,a,at,"REDIRECT_RESUME_FAILED","redirect_resume");je(r.message),rt(r.message),ut(()=>In.current?.(r)),tn(f,r,{code:r.code,declineCode:r.declineCode}),Je("error"),await Yr(vn)}finally{ha(),ql(),Je(null),rt(null),St(!1)}})())},[tn,ut,d,rr,v,a]);let Yt=Nt(null);function Ut(E,L=!1){let T=E?.account?.email?.trim().toLowerCase()??"",he={c:E?.clientId,cur:E?.currency??"",captureMethod:E?.captureMethod??"",a:{e:T,u:T?"":E?.account?.userId??"",country:E?.account?.country??""},successUrl:E?.successUrl,cancelUrl:E?.cancelUrl,p:E?.products?.map(r=>Pa(`${r.type??""}:${r.code??r.providerItemId??r.providerPlanId??""}`,r)).sort(),i:E?.items?.map(r=>Pa(r.code??r.providerItemId??"",r)).sort(),s:E?.subscriptions?.map(r=>Pa(r.code??r.providerPlanId??"",r)).sort(),couponCodes:E?.couponCodes?[...E.couponCodes].sort():void 0,...L?{tagsData:E?.tagsData,utmMetadata:E?.utmMetadata,tokenizedData:E?.tokenizedData,checkoutMode:E?.checkoutMode??"full"}:{}},be=JSON.stringify(he),m=0;for(let r=0;r<be.length;r++)m=(m<<5)-m+be.charCodeAt(r)|0;return`flopay_session_${Math.abs(m).toString(36)}`}let $t=mn(()=>_t?Ut(_t):"",[_t]),_e=Nt(_t);_e.current=_t,Bn(()=>{mt(e??"")},[e]),Bn(()=>{ot.current=!1,je(Me),rt(null),Wt(!1),Je(null)},[$t,Me,e]);async function qt(E,L){let T=xo(v,a,at),he=new Eo(v,{telemetry:!1}),be=!1;try{let m=E.idempotencyKey!==void 0?Vi(E.idempotencyKey):void 0,r=m??Nl(L),f,A=!1,y=Ol(L);T.log({name:y?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let U=y?.sid??null,Ee=null,it;if(U)try{if(Ee=await he.getUnifiedCheckoutSession(U,y?.nonce),Ee.data.session?.status==="complete"){if(Qo(U))return{sid:U,result:Ee};$l(L),U=null,Ee=null,A=!0}}catch{T.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),va(L),U=null}if(!U){!m&&(A||!r)&&(r=Vi(),f=r),r&&Ul(L,r);let G=T.now(),$=0;T.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let p={...E,idempotencyKey:r,avsCheck:!!Te,avsConfig:typeof Te=="object"?Te:void 0,checkoutType:"embedded_checkout",checkoutLayout:te?"custom_layout":_==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(p,Tl,{configurable:!1,enumerable:!1,value:{onAttempt:we=>{$=Math.max($,we)}}});let z=()=>{T.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),T.performance({stage:"session_create",durationMs:T.now()-G,durationMode:"machine",requestCategory:"session_create",attempt:$,statusClass:"2xx"})},me=we=>{let xe=qi(we,"CHECKOUT_SESSION_CREATE_FAILED","unknown");T.performance({stage:"session_create",durationMs:T.now()-G,durationMode:"machine",requestCategory:"session_create",attempt:$,statusClass:xe.statusClass}),we instanceof At&&we.type==="validation_error"?T.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):xe.statusClass==="4xx"?T.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):T.error({...xe,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if(Ml(p)){let we=await he.createDetachedSession(p);we.claimed.catch(()=>{}),Ee=we.shell,U=we.sessionId,it=we.claimed.then(xe=>{let gn=xe.data.session?.id??we.sessionId;return gn&&Wi(L,gn,xe.data.session?.clientSecret??we.nonce),z(),xe},xe=>{throw va(L),me(xe),xe}).finally(()=>Gr(T)),it.catch(()=>{}),be=!0,T.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),T.performance({stage:"session_shell",durationMs:T.now()-G,durationMode:"machine",requestCategory:"session_create",attempt:$,statusClass:"2xx",paymentMethodCategory:"card"})}else Ee=await he.createAndFetchSession(p),z()}catch(we){throw me(we),we}U=Ee.data.session?.id??U??"",U&&!it&&Wi(L,U,Ee.data.session?.clientSecret)}return{sid:U??"",result:Ee,sdkGeneratedIdempotencyKey:f,...it?{claimed:it}:{}}}finally{be||Gr(T)}}let yt=or(async(E,L)=>{let T=_e.current;if(!T)throw new At("createSession is required to bootstrap checkout.","validation_error");let he=Jo(T,E),be=Ut(he),m=To.get(be);if(!m){let A={promise:qt(he,be),consumers:0,settled:!1};m=A,To.set(be,A);let y=()=>{A.settled=!0,Ki(be,A)};A.promise.then(y,y)}m.consumers+=1;let r=!1,f=()=>{r||(r=!0,m.consumers-=1,Ki(be,m))};L?.(f);try{let A=await m.promise;Yt.current=be,E&&(Bt(tt),Qt(z=>ii(z,E)));let{sid:y,result:U,claimed:Ee}=A;if(oe(U),U.data.session&&Ze(U.data.session),y&&mt(y),Ee){let z=Dt.current+=1;Ft(!0),Ee.then(me=>{Dt.current===z&&(oe(me),me.data.session&&Ze(me.data.session),Ft(!1))},me=>{Dt.current===z&&(Ft(!1),R(me instanceof At?me:new At(me instanceof Error?me.message:"Failed to create session","api_error")))})}else Dt.current+=1,Ft(!1);let{publishableKey:it,paypalPublishableKey:G}=Ro(U),{flopay:$,paypalFlopay:p}=await Io({publishableKey:it,paypalPublishableKey:G,billingApiUrl:v,locale:d,telemetry:a});return dt.current=$,Re($),M.current=p,pt(p),Ye(!1),A}catch(A){throw Yt.current===be&&(Yt.current=null),A}finally{L||f()}},[d,v,a,at]),fn=Nt(cn);fn.current=cn;let Wn=Nt(yt);Wn.current=yt;let jt=or(async E=>{if(!jl(E)||kt)return{sessionId:qe,session:Y};Zt(!0);try{let L=await yt(E);return{sessionId:L.sid,session:L.result.data.session??null}}finally{Zt(!1)}},[yt,kt,qe,Y]);Bn(()=>{let E=!1,L;if(R(null),$t){let be=_e.current;return We(Pt),Ye(!1),Yt.current===$t?()=>{E=!0}:(Ze(si(be,Ue)),(async()=>{let m=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),r=Pt==="auto"&&!ot.current&&!m;r&&(je(null),rt(null),Je("processing"));try{let f=await Wn.current(void 0,Ee=>{L=Ee}),A=f.result.data.session??null;Ae.current=Ro(f.result);let y=ga(f.result),U=Qo(f.sid||A?.id);if(!E&&r&&A&&!y&&!U){ot.current=!0,await Dl($t,f.sdkGeneratedIdempotencyKey,()=>fn.current(A,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:f.result.autoProcessingError,initialAutoProcessingPending:f.result.autoProcessingPending,autoProcessingAttempted:f.result.autoProcessingAttempted,sessionId:f.sid||A.id}));return}!E&&r&&((y||U)&&(ot.current=!0),Je(null),rt(null))}catch(f){if(E)return;let A=f instanceof At||typeof f=="object"&&f!==null&&"code"in f?f.code:void 0;if(r&&A==="session_auto_completed"){ot.current=!0,Je("success"),await Yr(Tn),E||(ut(()=>{Ke.current?.({status:"succeeded"})}),Je(null),rt(null));return}r&&(Je(null),rt(null));let y=f instanceof At?f:new At(f instanceof Error?f.message:"Failed to create session","api_error");R(y)}finally{L?.(),L=void 0}})(),()=>{E=!0,L?.()})}Ye(!0);async function T(){let be=!1;try{let r=await new Eo(v,{telemetry:!1}).getUnifiedCheckoutSession(Oe,t);if(E)return;oe(r);let f=r.data.session??null;if(Ze(f),!f)throw new At("No session data returned","api_error");if(f.status==="authorized"){Ye(!1),ut(()=>{Ke.current?.(Zn(f,Oe)),Ln.current?.(f.successUrl??"")});return}if(f.status==="complete"){Ye(!1),ut(()=>{Ln.current?.(f.successUrl??"")});return}if(f.status==="expired")throw mo(f);be=!0;let A=Ue??f.checkoutMode??"full";We(A);let y=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),U=ga(r);if(A==="auto"&&!ot.current&&!y&&!U){ot.current=!0;let Ee=he(r);try{if(await fn.current(f,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Ee,sessionId:Oe||f.id}),E)return;await Ee,E||Ye(!1);return}catch{if(E)return;await Ee,E||Ye(!1);return}}await he(r),E||Ye(!1)}catch(m){if(E)return;m instanceof At?!be&&!Ll(m)&&fa(v,a,at,"NETWORK_REQUEST_FAILED","session_read"):fa(v,a,at,"INTERNAL_SDK_ERROR","checkout_mount");let r=m instanceof At?m:new At(m instanceof Error?m.message:"Failed to initialize checkout","api_error");R(r),Ye(!1)}}async function he(be){let{publishableKey:m,paypalPublishableKey:r}=Ro(be);Ae.current={publishableKey:m,paypalPublishableKey:r};let{flopay:f,paypalFlopay:A}=await Io({publishableKey:m,paypalPublishableKey:r,billingApiUrl:v,locale:d,telemetry:a});dt.current=f,Re(f),M.current=A,pt(A)}return T(),()=>{E=!0}},[Ue,$t,Pt,He,ut,t]);let Vt=or(async()=>{if(!(Ie||!Y)){St(!0),je(null);try{await cn(Y,{attempt3DS:!0,fallbackToFull:!0,sessionId:Oe||Y.id})}finally{St(!1)}}},[Oe,Ie,cn,Y]),Ot=ba(x),zn=ga(x),On=mn(()=>{if(!x||!Y||!x.data.stripe?.publishableKey)return;let E={appearance:$e,paymentMethodCreation:"manual",billingApiUrl:v};if(x.data.stripe?.clientSecret)E.clientSecret=x.data.stripe.clientSecret;else{let L=ji(Y).total;E.amount=Math.round(L*100)||Y.amount,E.currency=Y.currency?.toLowerCase()}return E},[x,Y,$e,v]),nn=!!(n&&!te&&_==="buttons"&&le&&Pt==="full"),Gt=mn(()=>({session:Y,loading:Jt,error:Xt,checkoutMode:ge,inlineSessionDraft:_t,applyInlineSessionPatch:nn?jt:void 0,inlineSessionPatchProcessing:kt,claimPending:en}),[Y,Jt,Xt,ge,_t,nn,jt,kt,en]),rn=!!n&&_==="buttons"&&!zn&&(!W||!On),Ne=et?ne(Cn,{status:et,errorMessage:Rn,authorized:Vn}):null;if(Jt){if(l)return Et(kn,{children:[l,Ne]});if(_==="buttons"){let E=re?.buttonsLayout?.cardButton?.borderRadius??re?.appearance.variables?.borderRadius??8,L=T=>ne("div",{style:{height:T,borderRadius:E,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Et(kn,{children:[Et("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[c&&L(Cr),P&&(I||g)&&L(Cr),P&&L(Cr),ne("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ne]})}return Et(kn,{children:[Et("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ne("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ne("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ne]})}return Xt?C?ne(pn.Provider,{value:Gt,children:C(Xt)}):ne(pn.Provider,{value:Gt,children:ne("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Xt.message})}):rn?Et(kn,{children:[ne(pn.Provider,{value:Gt,children:ne(Kl,{onButtonClick:V,showPayPal:c,showStripe:P,showApplePay:I,showGooglePay:g,theme:ae,buttonsTheme:Z,buttonsStyles:O,cardButtonContent:J,cardBackButtonContent:H,cardTitleContent:ie})}),Ne]}):zn&&Y&&Ot?Et(kn,{children:[ne(pn.Provider,{value:Gt,children:Et("div",{className:fe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ve&&ne(pr,{icon:!1,children:Ve}),wt==="retrying"&&ne("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),wt==="exhausted"&&Et("div",{role:"alert",children:[ne("div",{children:"PayPal is temporarily unavailable. Please try again."}),ne("button",{type:"button",onClick:_n,children:"Retry PayPal"})]}),wt!=="exhausted"&&ne("div",{"aria-hidden":wt==="retrying"?!0:void 0,style:wt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ne(gi,{sessionId:Oe,nonce:Y.clientSecret||void 0,billingApiUrl:v,email:Y.customer?.email,clientId:Ot.clientId,environment:Ot.environment,currency:(Y.currency??"usd").toUpperCase(),isSubscription:Y.mode==="subscription",onComplete:D,onErrorChange:je,onDecline:w,onButtonClick:V,onInitializationStateChange:Hn,allowAutomaticRetry:Kn===0,session:Y,telemetry:a,telemetryContext:at,debug:de},`paypal-init-${Kn}`)})]})}),Ne]}):!W||!On?ne(kn,{children:Ne}):ge==="confirm"?Et(kn,{children:[ne(pn.Provider,{value:Gt,children:ne(uo,{flopay:W,paypalFlopay:Ge,options:On,children:Et("div",{className:fe,children:[Ve&&ne("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ve}),ke?ke({onConfirm:Vt,isProcessing:Ie}):ne("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]}):Et(kn,{children:[ne(pn.Provider,{value:Gt,children:ne(uo,{flopay:W,paypalFlopay:Ge,options:On,children:te?Et(kn,{children:[Ve&&ne("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ve}),ne(Vl,{sessionId:Oe,nonce:Y?.clientSecret||void 0,billingApiUrl:v,session:Y,children:te})]}):ne(ua,{sessionId:Oe,nonce:Y?.clientSecret||void 0,email:Y?.customer?.email,userId:Y?.customer?.id,firstName:Y?.customer?.firstName,lastName:Y?.customer?.lastName,totalAmount:Y?Math.round(ji(Y).total*100):0,currency:Y?.currency?.toLowerCase()??"usd",onComplete:D,onError:h,onDecline:w,error:Ve,onErrorChange:je,showPayPal:c,showStripe:P,enabledPaymentMethods:k??x?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:x?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:g,layout:_,theme:ae,buttonsTheme:Z,buttonsStyles:O,appearance:$e,cardButtonContent:J,cardBackButtonContent:H,cardTitleContent:ie,onButtonClick:V,onBeforeButtonClick:le,enableAVS:Te,...Pe?{cardFieldOrder:Pe}:{},...pe?{cardPreFormSlot:pe}:{},avsLayout:ee,country:Y?.customer?.country,city:Y?.customer?.city,state:Y?.customer?.state,onCountryChange:S,onZipChange:B,avsCheck:!!Te,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:te?"custom_layout":_==="buttons"?"buttons_layout":"default_layout",className:fe,directPaypal:ba(x),isSubscription:Y?.mode==="subscription",session:Y,dataAttachmentPending:en,debug:de})})}),Ne]})}function Vl({sessionId:e,nonce:t,billingApiUrl:n,session:s,children:a}){return ne(kn,{children:ya.Children.map(a,i=>{if(!ya.isValidElement(i))return i;let d=i.props,l={};return d.sessionId||(l.sessionId=e),!d.nonce&&t&&(l.nonce=t),d.billingApiUrl||(l.billingApiUrl=n),s?.customer&&(d.email||(l.email=s.customer.email),d.userId||(l.userId=s.customer.id),d.firstName||(l.firstName=s.customer.firstName),d.lastName||(l.lastName=s.customer.lastName)),Object.keys(l).length===0?i:ya.cloneElement(i,l)})})}function Kl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:s,showGooglePay:a,theme:i,buttonsTheme:d,buttonsStyles:l,cardButtonContent:C,cardBackButtonContent:D,cardTitleContent:h}){let[w,S]=Ct(!1),B=mn(()=>Ji(i),[i]),c=mn(()=>{let g=B?.buttonsLayout??Bl(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},[B,d,l]),P=B?.buttonsLayout?.cardButton?.borderRadius??B?.appearance.variables?.borderRadius??8,k=g=>ne("div",{style:{height:g,borderRadius:P,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),I=C===void 0?{boxSizing:"border-box",height:Cr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(w){let g=c.cardInputBorder??"#e5e7eb",de=c.cardInputBackground??"white",_=lr(D),ae=lr(h);return Et("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:[Et("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Et("button",{type:"button",onClick:()=>S(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:_?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:[ne("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...c.backButtonIcon},children:ne("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:ne("path",{d:"M15 18l-6-6 6-6"})})}),ne(dr,{content:D})]}),ae?ne("div",{style:{flex:1}}):ne("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...c.title},children:ne(Nr,{content:h})})]}),ne("div",{style:{backgroundColor:de,border:`1px solid ${g}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ne("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Et("div",{style:{display:"flex"},children:[ne("div",{style:{flex:1,backgroundColor:de,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomLeftRadius:8,padding:12,height:45},children:ne("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ne("div",{style:{flex:1,backgroundColor:de,borderTop:"none",borderRight:`1px solid ${g}`,borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomRightRadius:8,padding:12,height:45},children:ne("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ne("div",{style:{backgroundColor:de,border:`1px solid ${g}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ne("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ne("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...c.submitButton,opacity:.5}}),ne("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 Rt("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%",...x,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:d.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...d.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:oe(lr,{content:w})}),oe("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{dropThirdPartyOnlyError as Du}from"@flopay/shared";import{useEffect as Tl,useRef as zi,useContext as Ml}from"react";import{jsx as Fl}from"react/jsx-runtime";function Ui(e,t){function n({className:i,id:o,style:a,options:u,onChange:l,onReady:w,onFocus:B,onBlur:h,onEscape:R}){let S=zi(null),_=zi(null),{elements:d,reportInteractive:b}=Ml(xn);return Tl(()=>{if(!d||!S.current)return;let I=!0;return(async()=>{let x=d.getElement(e);x||(x=await d.create(e,u)),!(!I||!S.current)&&(x.mount(S.current),_.current=x,l&&x.on("change",l),x.on("ready",()=>{b?.(),w?.()}),B&&x.on("focus",B),h&&x.on("blur",h),R&&x.on("escape",R))})(),()=>{if(I=!1,_.current){try{_.current.unmount()}catch{}_.current=null}}},[d,b]),Fl("div",{ref:S,className:i,id:o,style:a})}return n.displayName=t,n}var Bl=Ui("payment","PaymentElement"),Al=Ui("address","AddressElement");import{PaymentAPI as Dl}from"@flopay/js";import{FloPayError as Ll}from"@flopay/shared";import{useCallback as ya,useEffect as Nl,useRef as Ol,useState as $i}from"react";import{Fragment as Ul,jsx as vr,jsxs as $l}from"react/jsx-runtime";function zl({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:o,firstName:a,lastName:u,chv:l,onTokenizedBody:w,onComplete:B,onErrorChange:h,isProcessing:R=!1}){let S=vn(),_=$o(),d=oo(),[b,I]=$i(!1),[x,P]=$i(!1),ae=Ol(!1),U=(n||d).replace(/\/+$/,""),le=ya(async J=>{try{let ce=await new Dl(U).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:J,accountData:{userId:o??"",email:i??"",firstName:a??"",lastName:u??""},chv:l});if(ce.ok){B?.();return}let $=await ce.json().catch(()=>null);h?.($?.message??"Payment failed. Please try again.")}catch(W){h?.(W instanceof Error?W.message:"An unexpected error occurred")}},[U,e,t,o,i,a,u,l,B,h]),ee=ya(J=>{w?w(J):le(J)},[w,le]);Nl(()=>{if(!S||ae.current)return;let J=new URLSearchParams(window.location.search),W=J.get("payment_intent"),ce=J.get("payment_intent_client_secret"),$=J.get("redirect_status");!W||!ce||(ae.current=!0,(async()=>{try{if(P(!0),$==="failed"){h?.("PayPal payment was declined. Please try again.");return}let K=S.getRawProvider();if(!K?.retrievePaymentIntent){h?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:de,error:_e}=await K.retrievePaymentIntent(ce);if(_e){h?.(_e.message??"Failed to retrieve PayPal payment status.");return}if(de&&(de.status==="requires_capture"||de.status==="succeeded")){let Pe=typeof de.payment_method=="string"?de.payment_method:de.payment_method?.id;ee({id:Pe??de.id,type:"card",threeDSecureActionResultTokenId:de.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 h?.("PayPal payment was not completed. Please try again.")}catch(K){h?.(K instanceof Error?K.message:"Failed to complete PayPal payment.")}finally{P(!1)}})())},[S,ee,h]);let F=ya(async()=>{if(!(!S||!_))try{if(P(!0),h?.(null),!e||!i)throw new Ll("Missing sessionId or email for PayPal payment","validation_error");let J=await S.confirmPayPalPayment({billingApiUrl:U,sessionId:e,nonce:t,email:i,returnUrl:window.location.href});if(J.error){h?.(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){h?.(J instanceof Error?J.message:"PayPal payment failed. Please try again.")}finally{P(!1)}},[S,_,e,t,i,U,ee,h]);return!S||!_?vr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):$l(Ul,{children:[!b&&vr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),vr("div",{style:b?{}:{display:"none"},children:vr("button",{type:"button",onClick:F,disabled:x||R,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:x||R?"not-allowed":"pointer",opacity:x||R?.6:1},ref:()=>I(!0),children:x?"Processing...":"PayPal"})}),(x||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 Vr,useRef as Sr,useState as wo}from"react";import{PaymentAPI as fa}from"@flopay/js";import{FloPayError as Vn,resolveBillingApiUrl as ql,resolveButtonsLayoutTheme as jl,resolveTheme as Vl}from"@flopay/shared";import{Fragment as Jl,jsx as wr,jsxs as Xl}from"react/jsx-runtime";var Kl=44;function qi(e){return new Promise(t=>setTimeout(t,e))}function Hl(e,t){return e instanceof Vn?e:new Vn(e instanceof Error?e.message:t,"api_error")}function Wl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Yl(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 Gl({sessionId:e,nonce:t,createSession:n,paymentMethodId:i,checkoutMethod:o,clientId:a,products:u,items:l,subscriptions:w,account:B,successUrl:h,cancelUrl:R,couponCodes:S,tagsData:_,utmMetadata:d,billingApiUrl:b,locale:I,theme:x,appearance:P,buttonsTheme:ae,buttonsStyles:U,onSuccess:le,onError:ee,onDecline:F,children:J,disabled:W=!1,type:ce="button",style:$,...K}){let de=Vr(()=>ql(b),[b]),_e=Vr(()=>Yl({createSession:n,clientId:a,products:u,items:l,subscriptions:w,account:B,successUrl:h,cancelUrl:R,couponCodes:S,tagsData:_,utmMetadata:d}),[B,R,a,S,n,u,l,w,h,_,d]),[Pe,ye]=wo(!1),[te,ge]=wo(null),[xe,ne]=wo(null),[ke,Re]=wo(null),Ce=Sr(!0),Y=Sr(null),E=Sr(ke),ie=Sr(le),Ne=Sr(ee),Oe=Sr(F);Cr(()=>{E.current=ke},[ke]),Cr(()=>{ie.current=le},[le]),Cr(()=>{Ne.current=ee},[ee]),Cr(()=>{Oe.current=F},[F]),Cr(()=>(Ce.current=!0,()=>{Ce.current=!1,Y.current?.abort()}),[]),Cr(()=>{if(typeof window>"u")return;let f=be=>{be.key==="Escape"&&Re(null)};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f)}},[]);let ue=jn((f,be=$r)=>{Oe.current?.(kt(be,f,{code:f.code,declineCode:f.declineCode}))},[]),k=jn(async f=>{Ce.current&&(ne(null),ge("success"),await qi(Tn),Ce.current&&ie.current?.(f))},[]),Q=jn(async(f,be)=>{Ce.current&&(Ne.current?.(f),be?.emitDecline&&ue(f,be.method),ne(f.message),ge("error"),await qi(Cn))},[ue]),Z=jn(async(f,be,pt)=>{let et=f.data.session??null;if(!et)throw new Vn("No session data returned","api_error");let Je=et.clientSecret||t;if(et.status==="complete"){await k({result:{status:"succeeded"},session:et,sessionId:et.id||be,autoCompleted:!1});return}if(et.status==="expired")throw new Vn("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(f.autoProcessingPending){let $e=(await new fa(de).waitForCheckoutSessionCompletion(f.autoProcessingPending.sessionId,{initialDelayMs:f.autoProcessingPending.retryAfterMs})).data.session;if(!$e||$e.status!=="complete")throw new Vn("Automatic payment failed. Please try again.","api_error",{code:$e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await k({result:{status:"succeeded"},session:$e,sessionId:$e.id||be,autoCompleted:!1});return}if(f.autoProcessingError){if(f.autoProcessingError.type==="3ds_required"&&f.autoProcessingError.nextActionRedirectUrl&&be&&Je){let Xe=new AbortController;Y.current=Xe;let Ie;try{Ie=await xi({billingApiUrl:de,sessionId:be,nonce:Je,nextActionRedirectUrl:f.autoProcessingError.nextActionRedirectUrl,signal:Xe.signal})}finally{Y.current===Xe&&(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:f.autoProcessingError.checkoutMethod});let Ye=(await new fa(de).waitForCheckoutSessionCompletion(be,{initialDelayMs:0,nonce:Je})).data.session;if(!Ye||Ye.status!=="complete")throw qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:f.autoProcessingError.checkoutMethod});await k({result:{status:"succeeded"},session:Ye,sessionId:Ye.id||be,autoCompleted:!1});return}throw qn(f.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:f.autoProcessingError.checkoutMethod})}if(pt?.fromCreateSession&&f.autoProcessingAttempted===!0)throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ve=await Pr({billingApiUrl:de,sessionId:be??et.id,session:et,nonce:Je});if(Ve.type!=="success")throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await k({result:Ve.result,session:et,sessionId:et.id||be,autoCompleted:!1})}catch(Ve){let Xe=nr(Ve),Ie=et.id||be;await Q(Xe,{emitDecline:!0,method:Xe.checkoutMethod??$r}),Wl(Xe,Ie)&&Ie&&Ce.current&&Re({sessionId:Ie,errorMessage:Xe.message,nonce:Je||void 0})}},[t,de,Q,k]),ze=jn(async f=>{if(K.onClick?.(f),!(f.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 fa(de);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(Hl(be,"Automatic payment failed. Please try again."))}finally{Ce.current&&(ge(null),ne(null),ye(!1))}}},[K,_e,W,Pe,t,Z,de,e,Q,k]),ut=jn(f=>{let be=E.current;Re(null),ie.current?.({result:f,session:null,sessionId:be?.sessionId??null,autoCompleted:!1})},[]),qe=jn(f=>{Ne.current?.(f)},[]),ot=jn(f=>{Oe.current?.(f)},[]),N=Vr(()=>Vl(x),[x]),V=Vr(()=>{let f=N?.buttonsLayout??jl(ae);return U?{...f,...U,cardButton:{...f.cardButton,...U.cardButton}}:f},[N,ae,U]),Ze=Vr(()=>{let f=N?.appearance;return P?f?{...f,...P,variables:{...f.variables,...P.variables}}:P:f},[P,N]),Te=Ze?.variables,at=Te?.colorPrimary??"#4A49FF",He=Te?.colorPrimaryHover??po(at,.12),je=Te?.borderRadius??"8px";return Xl(Jl,{children:[wr("button",{...K,type:ce,onClick:ze,disabled:W||Pe,"aria-busy":Pe,style:{width:"100%",...J===void 0?{boxSizing:"border-box",height:Kl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...V.cardButton,...ta({themeBundle:N,resolvedPrimaryColor:at,resolvedBorderRadius:je,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,...$},onMouseEnter:f=>{K.onMouseEnter?.(f),!f.defaultPrevented&&!W&&!Pe&&(N||Te?.colorPrimary)&&(f.currentTarget.style.backgroundColor=He)},onMouseLeave:f=>{K.onMouseLeave?.(f),!f.defaultPrevented&&(N||Te?.colorPrimary)&&(f.currentTarget.style.backgroundColor=at)},onMouseDown:f=>{K.onMouseDown?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(0.985)")},onMouseUp:f=>{K.onMouseUp?.(f),f.defaultPrevented||(f.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:f=>{f.target===f.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(ma,{sessionId:ke.sessionId,nonce:ke.nonce,checkoutMode:"full",billingApiUrl:de,locale:I,theme:x,...Ze?{appearance:Ze}:{},buttonsTheme:ae,buttonsStyles:U,initialErrorMessage:ke.errorMessage,cardTitleContent:null,onComplete:ut,onError:qe,onDecline:ot})})})]})}export{Al as AddressElement,uo as DirectPayPalButton,Gl as FloPayAutomaticPaymentButton,ma as FloPayCheckout,ro as FloPayProvider,zl as PayPalButton,Bl as PaymentElement,na as SplitCardForm,zo as VaultCardFields,Du as dropThirdPartyOnlyError,Cs as useCheckout,$o as useElements,vn as useFloPay,Uo as usePayPalFloPay};
|
|
47
|
+
`})]})}return Et("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&k(Cr),n&&(s||a)&&k(Cr),n&&ne("button",{type:"button",onClick:()=>{e?.("card"),S(!0)},style:{width:"100%",...I,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:ne(cr,{content:C})}),ne("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{dropThirdPartyOnlyError as Ju}from"@flopay/shared";import{useEffect as Hl,useRef as Xi,useContext as Wl}from"react";import{jsx as Jl}from"react/jsx-runtime";function Qi(e,t){function n({className:s,id:a,style:i,options:d,onChange:l,onReady:C,onFocus:D,onBlur:h,onEscape:w}){let S=Xi(null),B=Xi(null),{elements:c,reportInteractive:P}=Wl(xn);return Hl(()=>{if(!c||!S.current)return;let k=!0;return(async()=>{let I=c.getElement(e);I||(I=await c.create(e,d)),!(!k||!S.current)&&(I.mount(S.current),B.current=I,l&&I.on("change",l),I.on("ready",()=>{P?.(),C?.()}),D&&I.on("focus",D),h&&I.on("blur",h),w&&I.on("escape",w))})(),()=>{if(k=!1,B.current){try{B.current.unmount()}catch{}B.current=null}}},[c,P]),Jl("div",{ref:S,className:s,id:a,style:i})}return n.displayName=t,n}var Yl=Qi("payment","PaymentElement"),Gl=Qi("address","AddressElement");import{PaymentAPI as Xl}from"@flopay/js";import{FloPayError as Ql}from"@flopay/shared";import{useCallback as ka,useEffect as Zl,useRef as ec,useState as Zi}from"react";import{Fragment as nc,jsx as Sr,jsxs as rc}from"react/jsx-runtime";function tc({sessionId:e,nonce:t,billingApiUrl:n,email:s,userId:a,firstName:i,lastName:d,chv:l,onTokenizedBody:C,onComplete:D,onErrorChange:h,isProcessing:w=!1}){let S=bn(),B=Go(),c=po(),[P,k]=Zi(!1),[I,g]=Zi(!1),de=ec(!1),_=(n||c).replace(/\/+$/,""),ae=ka(async J=>{try{let ie=await new Xl(_).processPayment(a??"",{sessionId:e,nonce:t,tokenizedData:J,accountData:{userId:a??"",email:s??"",firstName:i??"",lastName:d??""},chv:l});if(ie.ok){D?.();return}let j=await ie.json().catch(()=>null);h?.(j?.message??"Payment failed. Please try again.")}catch(H){h?.(H instanceof Error?H.message:"An unexpected error occurred")}},[_,e,t,a,s,i,d,l,D,h]),Z=ka(J=>{C?C(J):ae(J)},[C,ae]);Zl(()=>{if(!S||de.current)return;let J=new URLSearchParams(window.location.search),H=J.get("payment_intent"),ie=J.get("payment_intent_client_secret"),j=J.get("redirect_status");!H||!ie||(de.current=!0,(async()=>{try{if(g(!0),j==="failed"){h?.("PayPal payment was declined. Please try again.");return}let V=S.getRawProvider();if(!V?.retrievePaymentIntent){h?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:le,error:Te}=await V.retrievePaymentIntent(ie);if(Te){h?.(Te.message??"Failed to retrieve PayPal payment status.");return}if(le&&(le.status==="requires_capture"||le.status==="succeeded")){let Pe=typeof le.payment_method=="string"?le.payment_method:le.payment_method?.id;Z({id:Pe??le.id,type:"card",threeDSecureActionResultTokenId:le.id,isPaypal:!0});let pe=new URL(window.location.href);pe.searchParams.delete("payment_intent"),pe.searchParams.delete("payment_intent_client_secret"),pe.searchParams.delete("redirect_status"),window.history.replaceState({},"",pe.toString())}else h?.("PayPal payment was not completed. Please try again.")}catch(V){h?.(V instanceof Error?V.message:"Failed to complete PayPal payment.")}finally{g(!1)}})())},[S,Z,h]);let O=ka(async()=>{if(!(!S||!B))try{if(g(!0),h?.(null),!e||!s)throw new Ql("Missing sessionId or email for PayPal payment","validation_error");let J=await S.confirmPayPalPayment({billingApiUrl:_,sessionId:e,nonce:t,email:s,returnUrl:window.location.href});if(J.error){h?.(J.error.message);return}J.paymentIntentId&&(J.status==="succeeded"||J.status==="processing"||J.status==="requires_capture")&&Z({id:J.paymentMethodId??J.paymentIntentId,type:"card",threeDSecureActionResultTokenId:J.paymentIntentId,isPaypal:!0})}catch(J){h?.(J instanceof Error?J.message:"PayPal payment failed. Please try again.")}finally{g(!1)}},[S,B,e,t,s,_,Z,h]);return!S||!B?Sr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):rc(nc,{children:[!P&&Sr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),Sr("div",{style:P?{}:{display:"none"},children:Sr("button",{type:"button",onClick:O,disabled:I||w,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:I||w?"not-allowed":"pointer",opacity:I||w?.6:1},ref:()=>k(!0),children:I?"Processing...":"PayPal"})}),(I||w)&&Sr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:Sr("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 wr,useMemo as Jr,useRef as kr,useState as Xr}from"react";import{PaymentAPI as Ra}from"@flopay/js";import{FloPayError as Ir,resolveBillingApiUrl as oc,resolveButtonsLayoutTheme as ac,resolveTheme as ic}from"@flopay/shared";import{Fragment as pc,jsx as Rr,jsxs as mc}from"react/jsx-runtime";var sc=44;function es(e){return new Promise(t=>setTimeout(t,e))}function lc(e,t){return e instanceof Ir?e:new Ir(e instanceof Error?e.message:t,"api_error")}function cc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function dc(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 uc({sessionId:e,nonce:t,createSession:n,paymentMethodId:s,checkoutMethod:a,clientId:i,products:d,items:l,subscriptions:C,account:D,successUrl:h,cancelUrl:w,couponCodes:S,tagsData:B,utmMetadata:c,billingApiUrl:P,locale:k,theme:I,appearance:g,buttonsTheme:de,buttonsStyles:_,onSuccess:ae,onError:Z,onDecline:O,children:J,disabled:H=!1,type:ie="button",style:j,...V}){let le=Jr(()=>oc(P),[P]),Te=Jr(()=>dc({createSession:n,clientId:i,products:d,items:l,subscriptions:C,account:D,successUrl:h,cancelUrl:w,couponCodes:S,tagsData:B,utmMetadata:c}),[D,w,i,S,n,d,l,C,h,B,c]),[Pe,pe]=Xr(!1),[ee,fe]=Xr(null),[Me,te]=Xr(null),[Ue,Fe]=Xr(!1),[ke,K]=Xr(null),v=kr(!0),re=kr(null),$e=kr(ke),ze=kr(ae),se=kr(Z),x=kr(O);wr(()=>{$e.current=ke},[ke]),wr(()=>{ze.current=ae},[ae]),wr(()=>{se.current=Z},[Z]),wr(()=>{x.current=O},[O]),wr(()=>(v.current=!0,()=>{v.current=!1,re.current?.abort()}),[]),wr(()=>{if(typeof window>"u")return;let R=ge=>{ge.key==="Escape"&&K(null)};return window.addEventListener("keydown",R),()=>{window.removeEventListener("keydown",R)}},[]);let oe=jn((R,ge=Wr)=>{x.current?.(It(ge,R,{code:R.code,declineCode:R.declineCode}))},[]),W=jn(async R=>{v.current&&(te(null),Fe(R.result.status==="authorized"),fe("success"),await es(Tn),v.current&&ze.current?.(R))},[]),Re=jn(async(R,ge)=>{v.current&&(se.current?.(R),ge?.emitDecline&&oe(R,ge.method),te(R.message),Fe(!1),fe("error"),await es(vn))},[oe]),dt=jn(async(R,ge,We)=>{let Ie=R.data.session??null;if(!Ie)throw new Ir("No session data returned","api_error");let St=Ie.clientSecret||t;if(yr(Ie)){await W({result:Zn(Ie,ge),session:Ie,sessionId:Ie.id||ge,autoCompleted:!1});return}if(Ie.status==="expired")throw mo(Ie);try{if(R.autoProcessingPending){let Je=(await new Ra(le).waitForCheckoutSessionCompletion(R.autoProcessingPending.sessionId,{initialDelayMs:R.autoProcessingPending.retryAfterMs})).data.session;if(!yr(Je))throw yo(Je);await W({result:Zn(Je,ge),session:Je,sessionId:Je.id||ge,autoCompleted:!1});return}if(R.autoProcessingError){if(R.autoProcessingError.type==="3ds_required"&&R.autoProcessingError.nextActionRedirectUrl&&ge&&St){let je=new AbortController;re.current=je;let et;try{et=await Ui({billingApiUrl:le,sessionId:ge,nonce:St,nextActionRedirectUrl:R.autoProcessingError.nextActionRedirectUrl,signal:je.signal})}finally{re.current===je&&(re.current=null)}if(et.status==="declined")throw qn({type:et.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:et.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:R.autoProcessingError.checkoutMethod});let rt=(await new Ra(le).waitForCheckoutSessionCompletion(ge,{initialDelayMs:0,nonce:St})).data.session;if(!yr(rt))throw qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:R.autoProcessingError.checkoutMethod});await W({result:Zn(rt,ge),session:rt,sessionId:rt.id||ge,autoCompleted:!1});return}throw qn(R.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:R.autoProcessingError.checkoutMethod})}if(We?.fromCreateSession&&R.autoProcessingAttempted===!0)throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ve=await vr({billingApiUrl:le,sessionId:ge??Ie.id,session:Ie,nonce:St});if(Ve.type!=="success")throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await W({result:Ve.result,session:Ie,sessionId:Ie.id||ge,autoCompleted:!1})}catch(Ve){let je=rr(Ve),et=Ie.id||ge;await Re(je,{emitDecline:!0,method:je.checkoutMethod??Wr}),cc(je,et)&&et&&v.current&&K({sessionId:et,errorMessage:je.message,nonce:St||void 0})}},[t,le,Re,W]),Ge=jn(async R=>{if(V.onClick?.(R),!(R.defaultPrevented||H||Pe)){if(K(null),e&&Te){let ge=new Ir("Provide either sessionId or create-session props, not both.","validation_error");await Re(ge),v.current&&(fe(null),te(null));return}if(!e&&!Te){let ge=new Ir("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Re(ge),v.current&&(fe(null),te(null));return}pe(!0),te(null),Fe(!1),fe("processing");try{let ge=new Ra(le);if(e){let We=await ge.getUnifiedCheckoutSession(e,t);await dt(We,e);return}try{let We=await ge.createAndFetchSession({...Te});await dt(We,We.data.session?.id??null,{fromCreateSession:!0})}catch(We){if(We instanceof Ir&&We.code==="session_auto_completed"){await W({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw We}}catch(ge){await Re(lc(ge,"Automatic payment failed. Please try again."))}finally{v.current&&(fe(null),te(null),pe(!1))}}},[V,Te,H,Pe,t,dt,le,e,Re,W]),pt=jn(R=>{let ge=$e.current;K(null),ze.current?.({result:R,session:null,sessionId:ge?.sessionId??null,autoCompleted:!1})},[]),M=jn(R=>{se.current?.(R)},[]),Y=jn(R=>{x.current?.(R)},[]),Ze=Jr(()=>ic(I),[I]),qe=Jr(()=>{let R=Ze?.buttonsLayout??ac(de);return _?{...R,..._,cardButton:{...R.cardButton,..._.cardButton}}:R},[Ze,de,_]),mt=Jr(()=>{let R=Ze?.appearance;return g?R?{...R,...g,variables:{...R.variables,...g.variables}}:g:R},[g,Ze]),Oe=mt?.variables,He=Oe?.colorPrimary??"#4A49FF",Jt=Oe?.colorPrimaryHover??vo(He,.12),Ye=Oe?.borderRadius??"8px";return mc(pc,{children:[Rr("button",{...V,type:ie,onClick:Ge,disabled:H||Pe,"aria-busy":Pe,style:{width:"100%",...J===void 0?{boxSizing:"border-box",height:sc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...qe.cardButton,...da({themeBundle:Ze,resolvedPrimaryColor:He,resolvedBorderRadius:Ye,submitButtonStyle:qe.submitButton,explicitPrimaryColor:Oe?.colorPrimary}),fontSize:qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:H||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:H||Pe?.6:1,...j},onMouseEnter:R=>{V.onMouseEnter?.(R),!R.defaultPrevented&&!H&&!Pe&&(Ze||Oe?.colorPrimary)&&(R.currentTarget.style.backgroundColor=Jt)},onMouseLeave:R=>{V.onMouseLeave?.(R),!R.defaultPrevented&&(Ze||Oe?.colorPrimary)&&(R.currentTarget.style.backgroundColor=He)},onMouseDown:R=>{V.onMouseDown?.(R),R.defaultPrevented||(R.currentTarget.style.transform="scale(0.985)")},onMouseUp:R=>{V.onMouseUp?.(R),R.defaultPrevented||(R.currentTarget.style.transform="scale(1)")},children:Rr(cr,{content:J})}),ee&&Rr(Cn,{status:ee,errorMessage:Me,authorized:Ue}),ke&&Rr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:R=>{R.target===R.currentTarget&&K(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:Rr("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:Rr(wa,{sessionId:ke.sessionId,nonce:ke.nonce,checkoutMode:"full",billingApiUrl:le,locale:k,theme:I,...mt?{appearance:mt}:{},buttonsTheme:de,buttonsStyles:_,initialErrorMessage:ke.errorMessage,cardTitleContent:null,onComplete:pt,onError:M,onDecline:Y})})})]})}export{Gl as AddressElement,bo as DirectPayPalButton,uc as FloPayAutomaticPaymentButton,wa as FloPayCheckout,uo as FloPayProvider,tc as PayPalButton,Yl as PaymentElement,ua as SplitCardForm,Wo as VaultCardFields,Ju as dropThirdPartyOnlyError,Bs as useCheckout,Go as useElements,bn as useFloPay,Yo as usePayPalFloPay};
|