@flopay/react 1.4.17 → 1.4.18

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 CHANGED
@@ -759,6 +759,24 @@ No endpoint, custom tag, user context, message, stack, or metadata can be
759
759
  configured. See [`docs/TELEMETRY.md`](../../docs/TELEMETRY.md) for the complete
760
760
  privacy and retention contract.
761
761
 
762
+ If the React host has its own Sentry client, use the re-exported pure filter as
763
+ the host's `beforeSend` callback:
764
+
765
+ ```ts
766
+ import * as Sentry from '@sentry/browser';
767
+ import { dropThirdPartyOnlyError } from '@flopay/react';
768
+
769
+ Sentry.init({ beforeSend: dropThirdPartyOnlyError });
770
+ ```
771
+
772
+ No Sentry package or configuration is bundled by FloPay. The predicate drops
773
+ only complete exception stacks with no app or `@flopay/*` frame and at least
774
+ one recognised browser-extension URL or Stripe `dahlia/stripe.js` path/module
775
+ marker. Anonymous frames may accompany that marker. Mixed, unrelated,
776
+ incomplete, and anonymous-only errors pass through unchanged. The `in_app`
777
+ flag is ignored because host rewriting may set it to `true` on third-party
778
+ frames.
779
+
762
780
  Inline session creation classifies bounded failures without inspecting raw
763
781
  errors: network/CORS/timeouts emit `transport_error`, 5xx responses emit
764
782
  `server_error`, and malformed response discriminants emit `invalid_response`.
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var Fi=Object.create;var qr=Object.defineProperty;var Di=Object.getOwnPropertyDescriptor;var Li=Object.getOwnPropertyNames;var Ni=Object.getPrototypeOf,Oi=Object.prototype.hasOwnProperty;var zi=(e,t)=>{for(var n in t)qr(e,n,{get:t[n],enumerable:!0})},Ca=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Li(t))!Oi.call(e,o)&&o!==n&&qr(e,o,{get:()=>t[o],enumerable:!(l=Di(t,o))||l.enumerable});return e};var Sa=(e,t,n)=>(n=e!=null?Fi(Ni(e)):{},Ca(t||!e||!e.__esModule?qr(n,"default",{value:e,enumerable:!0}):n,e)),Ui=e=>Ca(qr({},"__esModule",{value:!0}),e);var Fs={};zi(Fs,{AddressElement:()=>ci,DirectPayPalButton:()=>Ir,FloPayAutomaticPaymentButton:()=>fi,FloPayCheckout:()=>uo,FloPayProvider:()=>Sr,PayPalButton:()=>mi,PaymentElement:()=>li,SplitCardForm:()=>no,VaultCardFields:()=>Vr,useCheckout:()=>_a,useElements:()=>Hr,useFloPay:()=>un,usePayPalFloPay:()=>Kr});module.exports=Ui(Fs);var $i=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,Ue=$i();var Ct=require("react"),wa=require("@flopay/shared");var Io=require("react"),En=(0,Io.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),dn=(0,Io.createContext)({session:null,loading:!1,error:null});var qi=Symbol.for("@flopay/js.telemetry.bridge.v1"),ji=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Vi(){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 Ki(e){let t=Vi(),n=(o,s)=>o?o.bind(e):s,l=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:l,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,l()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function jr(e){let t=globalThis[ji];return Ki(t?.(e)??{})}function Tt(e){if(e)return e[qi]}var ka=require("react/jsx-runtime");function Sr({flopay:e,paypalFlopay:t,options:n,children:l}){let[o,s]=(0,Ct.useState)(e instanceof Promise?null:e),[m,d]=(0,Ct.useState)(t instanceof Promise||!t?null:t),[I,N]=(0,Ct.useState)(null),P=(0,Ct.useRef)(null),_=(0,Ct.useRef)(null),k=(0,Ct.useRef)(null);(0,Ct.useEffect)(()=>{if(!o)return;let x=Tt(o);return P.current=x?.beginCheckout()??x?.now()??0,x?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{x?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),(0,Ct.useEffect)(()=>{let x=!1;return e instanceof Promise?e.then(F=>{x||s(F)}):s(e),()=>{x=!0}},[e]),(0,Ct.useEffect)(()=>{let x=!1;if(!t){d(null);return}return t instanceof Promise?t.then(F=>{x||d(F)}):d(t),()=>{x=!0}},[t]),(0,Ct.useEffect)(()=>{if(!o){N(null);return}let x=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return N(x),()=>{x.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,Ct.useEffect)(()=>{if(!o||!I||_.current===I)return;_.current=I;let x=Tt(o);x?.log({name:"checkout.rendered",stage:"checkout_render"}),x?.performance({stage:"checkout_render",durationMs:x.elapsed(P.current??0),durationMode:"machine"})},[I,o]);let A=(0,Ct.useCallback)(()=>{if(!o||!I||k.current===I)return;k.current=I;let x=Tt(o);x?.log({name:"checkout.interactive",stage:"checkout_interactive"}),x?.performance({stage:"checkout_interactive",durationMs:x.elapsed(P.current??0),durationMode:"machine"})},[I,o]),p=(0,wa.resolveBillingApiUrl)(n?.billingApiUrl),v=(0,Ct.useMemo)(()=>({flopay:o,paypalFlopay:m,elements:I,billingApiUrl:p,reportInteractive:A}),[o,m,I,p,A]);return(0,ka.jsx)(En.Provider,{value:v,children:l})}var M=Sa(require("react"),1),Xn=require("@flopay/js"),we=require("@flopay/shared");var Ws=require("react"),et=require("react/jsx-runtime");function Hi(){return(0,et.jsxs)(et.Fragment,{children:[(0,et.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,et.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,et.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,et.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,et.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Wi(){return(0,et.jsx)(et.Fragment,{children:"Go back"})}function Yi(){return(0,et.jsx)(et.Fragment,{children:"Secure card checkout"})}function nr(e){return e!==void 0&&(e===""||e===null||e===!1)}function rr({content:e}){return(0,et.jsx)(et.Fragment,{children:e===void 0?(0,et.jsx)(Hi,{}):e})}function or({content:e}){return(0,et.jsx)(et.Fragment,{children:e===void 0?(0,et.jsx)(Wi,{}):e})}function wr({content:e}){return(0,et.jsx)(et.Fragment,{children:e===void 0?(0,et.jsx)(Yi,{}):e})}var lt=require("@stripe/react-stripe-js"),R=require("@flopay/shared"),mn=require("@flopay/js");var _n=require("react"),Ra=require("react/jsx-runtime");function Vr({capture:e,html:t,messageToken:n,expectedOrigin:l,theme:o,containerStyle:s,onReady:m,onError:d,onValidation:I}){let N=(0,_n.useRef)(null),P=(0,_n.useRef)(m),_=(0,_n.useRef)(d),k=(0,_n.useRef)(I);P.current=m,_.current=d,k.current=I;let A=(0,_n.useRef)(o);return A.current=o,(0,_n.useEffect)(()=>{let p=N.current;if(!p)return;let v=!0,x=!1,F=()=>{!v||x||(x=!0,P.current?.())},b=e.on("ready",()=>{F()}),ce=e.on("error",ae=>{_.current?.(ae.message??"There was a problem loading the secure card form.")}),K=e.on("validation",ae=>{k.current?.(ae.message??null)}),pe={html:t,...n?{messageToken:n}:{},...l?{expectedOrigin:l}:{},...A.current?{theme:A.current}:{}};return e.mount(p,pe).then(()=>{F()}).catch(ae=>{v&&_.current?.(ae instanceof Error?ae.message:"Failed to load the secure card form.")}),()=>{v=!1,b(),ce(),K(),e.unmount()}},[e,t,n,l]),(0,_n.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,Ra.jsx)("div",{ref:N,"data-testid":"flopay-vault-card-fields",style:s})}var el=require("react"),kr=require("react/jsx-runtime");function ar({children:e,margin:t,icon:n=!0,styleOverride:l}){return(0,kr.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...l??{}},children:[n&&(0,kr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,kr.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var Ia={alipay:new URL("./payment-logos/alipay.svg",Ue).href,bancontact:new URL("./payment-logos/bancontact.svg",Ue).href,blik:new URL("./payment-logos/blik.svg",Ue).href,eps:new URL("./payment-logos/eps.svg",Ue).href,giropay:new URL("./payment-logos/giropay.svg",Ue).href,ideal:new URL("./payment-logos/ideal.svg",Ue).href,klarna:new URL("./payment-logos/klarna.svg",Ue).href,p24:new URL("./payment-logos/p24.svg",Ue).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",Ue).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",Ue).href};var r=Sa(require("react"),1);var ir=require("react"),Ea=require("@flopay/shared");function un(){return(0,ir.useContext)(En).flopay}function Kr(){return(0,ir.useContext)(En).paypalFlopay??null}function Hr(){return(0,ir.useContext)(En).elements}function _a(){return(0,ir.useContext)(dn)}function Wr(){return(0,ir.useContext)(En).billingApiUrl||(0,Ea.resolveBillingApiUrl)()}var cl=require("react"),yt=require("react/jsx-runtime"),xn=1200,Cn=1500;function Sn({status:e,errorMessage:t}){return(0,yt.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,yt.jsxs)("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,yt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,yt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,yt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,yt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,yt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,yt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,yt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,yt.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,yt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,yt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,yt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,yt.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,yt.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&"PROCESSING...",e==="success"&&"PAYMENT SUCCESSFUL",e==="error"&&"PAYMENT FAILED"]}),e==="success"&&(0,yt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:"You will be automatically redirected, do not close or navigate away from this window."}),e==="error"&&t&&(0,yt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,yt.jsx)("style",{children:`
1
+ "use strict";var Di=Object.create;var qr=Object.defineProperty;var Li=Object.getOwnPropertyDescriptor;var Ni=Object.getOwnPropertyNames;var Oi=Object.getPrototypeOf,zi=Object.prototype.hasOwnProperty;var Ui=(e,t)=>{for(var n in t)qr(e,n,{get:t[n],enumerable:!0})},Ca=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ni(t))!zi.call(e,o)&&o!==n&&qr(e,o,{get:()=>t[o],enumerable:!(l=Li(t,o))||l.enumerable});return e};var Sa=(e,t,n)=>(n=e!=null?Di(Oi(e)):{},Ca(t||!e||!e.__esModule?qr(n,"default",{value:e,enumerable:!0}):n,e)),$i=e=>Ca(qr({},"__esModule",{value:!0}),e);var Ds={};Ui(Ds,{AddressElement:()=>ci,DirectPayPalButton:()=>Ir,FloPayAutomaticPaymentButton:()=>fi,FloPayCheckout:()=>uo,FloPayProvider:()=>Sr,PayPalButton:()=>mi,PaymentElement:()=>li,SplitCardForm:()=>no,VaultCardFields:()=>Vr,dropThirdPartyOnlyError:()=>gi.dropThirdPartyOnlyError,useCheckout:()=>_a,useElements:()=>Hr,useFloPay:()=>un,usePayPalFloPay:()=>Kr});module.exports=$i(Ds);var qi=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,Ue=qi();var Ct=require("react"),wa=require("@flopay/shared");var Io=require("react"),En=(0,Io.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),dn=(0,Io.createContext)({session:null,loading:!1,error:null});var ji=Symbol.for("@flopay/js.telemetry.bridge.v1"),Vi=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ki(){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 Hi(e){let t=Ki(),n=(o,s)=>o?o.bind(e):s,l=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:l,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,l()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function jr(e){let t=globalThis[Vi];return Hi(t?.(e)??{})}function Tt(e){if(e)return e[ji]}var ka=require("react/jsx-runtime");function Sr({flopay:e,paypalFlopay:t,options:n,children:l}){let[o,s]=(0,Ct.useState)(e instanceof Promise?null:e),[m,d]=(0,Ct.useState)(t instanceof Promise||!t?null:t),[I,N]=(0,Ct.useState)(null),P=(0,Ct.useRef)(null),_=(0,Ct.useRef)(null),k=(0,Ct.useRef)(null);(0,Ct.useEffect)(()=>{if(!o)return;let x=Tt(o);return P.current=x?.beginCheckout()??x?.now()??0,x?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{x?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),(0,Ct.useEffect)(()=>{let x=!1;return e instanceof Promise?e.then(F=>{x||s(F)}):s(e),()=>{x=!0}},[e]),(0,Ct.useEffect)(()=>{let x=!1;if(!t){d(null);return}return t instanceof Promise?t.then(F=>{x||d(F)}):d(t),()=>{x=!0}},[t]),(0,Ct.useEffect)(()=>{if(!o){N(null);return}let x=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return N(x),()=>{x.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,Ct.useEffect)(()=>{if(!o||!I||_.current===I)return;_.current=I;let x=Tt(o);x?.log({name:"checkout.rendered",stage:"checkout_render"}),x?.performance({stage:"checkout_render",durationMs:x.elapsed(P.current??0),durationMode:"machine"})},[I,o]);let A=(0,Ct.useCallback)(()=>{if(!o||!I||k.current===I)return;k.current=I;let x=Tt(o);x?.log({name:"checkout.interactive",stage:"checkout_interactive"}),x?.performance({stage:"checkout_interactive",durationMs:x.elapsed(P.current??0),durationMode:"machine"})},[I,o]),p=(0,wa.resolveBillingApiUrl)(n?.billingApiUrl),v=(0,Ct.useMemo)(()=>({flopay:o,paypalFlopay:m,elements:I,billingApiUrl:p,reportInteractive:A}),[o,m,I,p,A]);return(0,ka.jsx)(En.Provider,{value:v,children:l})}var M=Sa(require("react"),1),Xn=require("@flopay/js"),we=require("@flopay/shared");var Ys=require("react"),et=require("react/jsx-runtime");function Wi(){return(0,et.jsxs)(et.Fragment,{children:[(0,et.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,et.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,et.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,et.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,et.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Yi(){return(0,et.jsx)(et.Fragment,{children:"Go back"})}function Gi(){return(0,et.jsx)(et.Fragment,{children:"Secure card checkout"})}function nr(e){return e!==void 0&&(e===""||e===null||e===!1)}function rr({content:e}){return(0,et.jsx)(et.Fragment,{children:e===void 0?(0,et.jsx)(Wi,{}):e})}function or({content:e}){return(0,et.jsx)(et.Fragment,{children:e===void 0?(0,et.jsx)(Yi,{}):e})}function wr({content:e}){return(0,et.jsx)(et.Fragment,{children:e===void 0?(0,et.jsx)(Gi,{}):e})}var lt=require("@stripe/react-stripe-js"),R=require("@flopay/shared"),mn=require("@flopay/js");var _n=require("react"),Ra=require("react/jsx-runtime");function Vr({capture:e,html:t,messageToken:n,expectedOrigin:l,theme:o,containerStyle:s,onReady:m,onError:d,onValidation:I}){let N=(0,_n.useRef)(null),P=(0,_n.useRef)(m),_=(0,_n.useRef)(d),k=(0,_n.useRef)(I);P.current=m,_.current=d,k.current=I;let A=(0,_n.useRef)(o);return A.current=o,(0,_n.useEffect)(()=>{let p=N.current;if(!p)return;let v=!0,x=!1,F=()=>{!v||x||(x=!0,P.current?.())},b=e.on("ready",()=>{F()}),ce=e.on("error",ae=>{_.current?.(ae.message??"There was a problem loading the secure card form.")}),K=e.on("validation",ae=>{k.current?.(ae.message??null)}),pe={html:t,...n?{messageToken:n}:{},...l?{expectedOrigin:l}:{},...A.current?{theme:A.current}:{}};return e.mount(p,pe).then(()=>{F()}).catch(ae=>{v&&_.current?.(ae instanceof Error?ae.message:"Failed to load the secure card form.")}),()=>{v=!1,b(),ce(),K(),e.unmount()}},[e,t,n,l]),(0,_n.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,Ra.jsx)("div",{ref:N,"data-testid":"flopay-vault-card-fields",style:s})}var tl=require("react"),kr=require("react/jsx-runtime");function ar({children:e,margin:t,icon:n=!0,styleOverride:l}){return(0,kr.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...l??{}},children:[n&&(0,kr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,kr.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var Ia={alipay:new URL("./payment-logos/alipay.svg",Ue).href,bancontact:new URL("./payment-logos/bancontact.svg",Ue).href,blik:new URL("./payment-logos/blik.svg",Ue).href,eps:new URL("./payment-logos/eps.svg",Ue).href,giropay:new URL("./payment-logos/giropay.svg",Ue).href,ideal:new URL("./payment-logos/ideal.svg",Ue).href,klarna:new URL("./payment-logos/klarna.svg",Ue).href,p24:new URL("./payment-logos/p24.svg",Ue).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",Ue).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",Ue).href};var r=Sa(require("react"),1);var ir=require("react"),Ea=require("@flopay/shared");function un(){return(0,ir.useContext)(En).flopay}function Kr(){return(0,ir.useContext)(En).paypalFlopay??null}function Hr(){return(0,ir.useContext)(En).elements}function _a(){return(0,ir.useContext)(dn)}function Wr(){return(0,ir.useContext)(En).billingApiUrl||(0,Ea.resolveBillingApiUrl)()}var dl=require("react"),yt=require("react/jsx-runtime"),xn=1200,Cn=1500;function Sn({status:e,errorMessage:t}){return(0,yt.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,yt.jsxs)("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,yt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,yt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,yt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,yt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,yt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,yt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,yt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,yt.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,yt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,yt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,yt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,yt.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,yt.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&"PROCESSING...",e==="success"&&"PAYMENT SUCCESSFUL",e==="error"&&"PAYMENT FAILED"]}),e==="success"&&(0,yt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:"You will be automatically redirected, do not close or navigate away from this window."}),e==="error"&&t&&(0,yt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,yt.jsx)("style",{children:`
2
2
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
3
3
  @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
4
4
  @keyframes flopay-draw { to { stroke-dashoffset: 0; } }
5
5
  @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
6
- `})]})})}var xa=require("@flopay/shared");function Ta(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Eo(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 Ma(e,t){let n=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],l=n.reduce((s,m)=>s+(m.overrideAmount??m.totalAmount??0),0),o=e.currency??n.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(l*100),currency:o,status:"open",customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((s,m)=>({uuid:`synthetic-${s.type??"item"}-${m}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??o,metadata:s.metadata??null}))}}function _o(e,t){return t?{...e,...t}:e}function St(e,t,n){let l=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,s=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:l,...o?{code:o}:{},...s?{declineCode:s}:{}}}var Gi=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function On(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:l}of Gi)if(n.test(t))return l;return e}function Yr(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Ba(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Aa(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Gr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Jr="flopay_recent_completion_";function sr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Jr+e,JSON.stringify(t))}catch{}}function xo(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Jr+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Jr+e),!1):!0}catch{return!1}}function Fa(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var B=require("react"),Na=require("@paypal/paypal-js"),Xr=require("@flopay/js"),Mn=require("@flopay/shared");function st(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function Ji(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Gn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Tn(e){if(typeof e!="object"||e===null)return;let t=e;return Gn(t.code)??Gn(t.type)??Gn(t.name)}function lr(e){if(!(typeof e!="object"||e===null))return Gn(e.decline_code)}function Rr(e){return typeof e!="object"||e===null?!1:Gn(e.type)?.toLowerCase()==="card_error"||lr(e)!==void 0}function zn(e){let t=Ji(e)?.toLowerCase()??"",l=`${Tn(e)?.toLowerCase()??""} ${t}`;return l.includes("popup")&&l.includes("block")}var pn=require("react/jsx-runtime"),Qr=45,Xi=1e3,Qi=11e3,Zi=["https://www.paypal.com","https://www.sandbox.paypal.com"],Da="We couldn't open PayPal. Try again or choose another payment method.",es={width:"100%",minHeight:Qr,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 La(e){return e.includes("No ack for postMessage init()")&&Zi.some(t=>e.includes(t))&&e.includes("10000ms")}function ts(e){return e?`${Da} Allow pop-ups for this site, then try again.`:Da}function Oa({sessionId:e,nonce:t,billingApiUrl:n,email:l,clientId:o,environment:s,currency:m,isSubscription:d,onTokenizedBody:I,onComplete:N,onErrorChange:P,onDecline:_,onTechnicalFailure:k,isProcessing:A=!1,onLoadStateChange:p,onInitializationStateChange:v,allowAutomaticRetry:x=!0,onButtonClick:F,runBeforeButtonClick:b,session:ce,existingOrderId:K,telemetry:pe,telemetryContext:ae,debug:z=!1}){let te=un(),Q=(0,B.useMemo)(()=>{if(te)return null;let D=jr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Mn.SDK_VERSION,enabled:pe!==!1});return D.setCheckoutContext(ae??{}),D.beginCheckout(ae??{}),D},[n,te,pe,ae?.checkoutMode,ae?.layout]),me=(0,B.useMemo)(()=>Tt(te),[te]);(0,B.useEffect)(()=>()=>{Q&&Q.flush().catch(()=>{}).finally(()=>Q.destroy())},[Q]);let H=(0,B.useMemo)(()=>({error:D=>{me?me.error(D):Q?.error(D)},log:D=>{me?me.log(D):Q?.log(D)},performance:D=>{me?me.performance(D):Q?.performance(D)},terminal:D=>{me?me.terminal(D):Q?.terminal(D)},startTiming:()=>me?.now()??Q?.now()??0,elapsed:D=>me?.elapsed(D)??Math.max(0,(Q?.now()??D)-D)}),[me,Q]),J=(0,B.useRef)(null),ye=(0,B.useRef)(0),Me=(0,B.useRef)(null),Se=(0,B.useRef)(!1),[Pe,ie]=(0,B.useState)(!1),[ve,Be]=(0,B.useState)(!1),[se,Ee]=(0,B.useState)(0),_e=(0,B.useRef)(0),[Re,Z]=(0,B.useState)(!1),T=(0,B.useRef)(!1),de=(0,B.useRef)(!1),[Oe,ze]=(0,B.useState)(!1),[fe,E]=(0,B.useState)(!1),re=(0,B.useMemo)(()=>n.replace(/\/+$/,""),[n]),oe=(0,B.useMemo)(()=>JSON.stringify([re,o,m,s??"",d,e,K??""]),[re,o,m,s,K,d,e]),$e=(0,B.useRef)(oe),ct=$e.current!==oe,[Ve,ot]=(0,B.useState)([]),q=D=>{z&&ot(ft=>[...ft,`${new Date().toISOString().slice(11,23)} ${D}`])},G=(0,B.useRef)(I),tt=(0,B.useRef)(N),Ae=(0,B.useRef)(P),at=(0,B.useRef)(_),We=(0,B.useRef)(k),Ke=(0,B.useRef)(F),rn=(0,B.useRef)(p),g=(0,B.useRef)(v),ke=(0,B.useRef)(b),dt=(0,B.useRef)(ce),nt=(0,B.useRef)(l),Qe=(0,B.useRef)(t),He=(0,B.useRef)(null),Ze=(0,B.useRef)(0),xe=(0,B.useRef)(null),je=(0,B.useRef)(null),wt=(0,B.useRef)(new Map),Ge=(0,B.useRef)(new Map),An=(0,B.useRef)(!1);(0,B.useEffect)(()=>(An.current=!0,()=>{An.current=!1}),[]),(0,B.useEffect)(()=>{G.current=I},[I]),(0,B.useEffect)(()=>{tt.current=N},[N]),(0,B.useEffect)(()=>{Ae.current=P},[P]),(0,B.useEffect)(()=>{at.current=_},[_]),(0,B.useEffect)(()=>{We.current=k},[k]),(0,B.useEffect)(()=>{Ke.current=F},[F]),(0,B.useEffect)(()=>{rn.current=p},[p]),(0,B.useEffect)(()=>{g.current=v},[v]),(0,B.useEffect)(()=>{ke.current=b},[b]),(0,B.useEffect)(()=>{dt.current=ce},[ce]),(0,B.useEffect)(()=>{nt.current=l},[l]),(0,B.useEffect)(()=>{Qe.current=t},[t]),(0,B.useEffect)(()=>{_e.current=se},[se]),(0,B.useEffect)(()=>{Re&&Me.current?.focus()},[Re,se]);let ht=(0,B.useCallback)(()=>{window.setTimeout(()=>{Me.current?.focus()},0)},[]),Fn=(0,B.useCallback)(()=>{ie(!1),Ee(D=>D+1)},[]),on=(0,B.useCallback)(()=>{Z(!1),(J.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??J.current)?.focus?.()},[]);(0,B.useEffect)(()=>{!Pe||!Se.current||(Se.current=!1,on())},[on,Pe,se]);let hn=(0,B.useCallback)((D,ft)=>{let ut=We.current;if(ut){ut("paypal",D,ft);return}Ae.current?.(ts(ft?.popupBlocked??zn(D)))},[]),Zt=()=>{xe.current?.timer&&(clearTimeout(xe.current.timer),xe.current.timer=null)},Dn=()=>{Zt();let D=Ze.current+1;return Ze.current=D,je.current=null,xe.current={generation:D,timer:null,yieldedControl:!1},Z(!1),D},Nt=D=>D!==void 0&&xe.current?.generation!==D?!1:(Zt(),xe.current=null,je.current=null,!0),kt=D=>{let ft=D?.generation??xe.current?.generation??Ze.current;(!D?.generation||xe.current?.generation===ft)&&(Zt(),xe.current=null),je.current=ft,D?.showRetry&&Z(!0),D?.remount&&Fn(),D?.focus!==!1&&ht()},qt=D=>xe.current?.generation===D&&je.current!==D,Gt=D=>{typeof document<"u"&&document.visibilityState!=="visible"||(Zt(),D.timer=setTimeout(()=>{xe.current?.generation===D.generation&&(xe.current=null,je.current=D.generation,hn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),Z(!0),Fn(),ht())},600))},Mt=()=>{let D=xe.current;D?.yieldedControl&&Gt(D)},jt=()=>{let D=xe.current;D&&(D.yieldedControl=!0,Zt())},Bt=D=>{let ft=He.current;return ft&&Ge.current.set(D,ft),D};(0,B.useEffect)(()=>{let D=()=>{document.visibilityState==="visible"?Mt():jt()};return document.addEventListener("visibilitychange",D),window.addEventListener("focus",Mt),window.addEventListener("blur",jt),()=>{document.removeEventListener("visibilitychange",D),window.removeEventListener("focus",Mt),window.removeEventListener("blur",jt),Zt()}},[]),(0,B.useEffect)(()=>{$e.current!==oe&&($e.current=oe,T.current=!1,de.current=!1,ie(!1),Be(!1),ze(!1),g.current?.("loading"))},[oe]),(0,B.useEffect)(()=>{st(()=>rn.current?.(Pe&&!Oe))},[Pe,Oe]);let le=(0,Mn.normalizeGatewayEnvironment)(s);(0,B.useEffect)(()=>{let D=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",ft=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(q(`mount clientId=${D} env=${s??"(unset)"}\u2192${le??"live"} ccy=${m} sub=${d}`),q(`ua=${ft.slice(0,80)}${ft.length>80?"\u2026":""}`),!o){q("FAIL: clientId empty \u2014 gateway misconfigured"),ze(!0),H.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!J.current){q("FAIL: containerRef not attached");return}ye.current=H.startTiming(),H.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ut=!1,Pt=!1,Te=()=>ut||Pt,qe,$n=!1,Ln=()=>{qe=(0,Mn.generateIdempotencyKey)(),qe||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),$n=!0},qn=null,Zn=!1,Vt=null,it=!1,At=()=>{!Vt||it||(it=!0,Vt.close().catch(()=>{}))},Kt=null,gt=()=>{Kt!==null&&(H.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),H.performance({stage:"overlay_return",durationMs:H.elapsed(Kt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Kt=null)},Jt=!1,Ht=J.current,an=null,Pn=null,Rt=[],Ot=u=>{if(!u||typeof u.getBoundingClientRect!="function")return"(no rect)";let c=u.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},Le=u=>{if(!u)return"(empty)";try{let c=new URL(u,typeof window<"u"?window.location.href:"https://localhost"),L=c.pathname.toLowerCase();return L.includes("checkcaptcha")||L.includes("captcha")?`CAPTCHA(${c.host}${L})`:L.includes("risk")||L.includes("challenge")?`RISK(${c.host}${L})`:L.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${L}`.slice(0,100)}catch{return u.slice(0,80)}},bt=u=>{let c=u.getAttribute("src"),L=u.getAttribute("srcdoc"),y=u.getAttribute("name"),ee=u.getAttribute("sandbox"),Ie=[];return c&&Ie.push(`src=${Le(c)}`),L&&Ie.push(`srcdoc[${L.length}ch]`),!c&&!L&&Ie.push("src=(empty) srcdoc=(empty)"),y&&Ie.push(`name=${y.slice(0,40)}`),ee!==null&&Ie.push(`sandbox="${ee.slice(0,40)}"`),Ie.join(" ")},vt=u=>{if(!(u instanceof HTMLIFrameElement))return"";try{let c=u.contentDocument;if(!c)return"cd=null";let L=c.body?.children.length??0,y=c.body?.innerHTML.length??0,ee=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${L}children,${y}ch] head[${ee}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},bn=[],jn=u=>{if(Te())return;let c=u.message??String(u.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(q(`window:error ${c.slice(0,140)}`),bn.push(c))},Wt=u=>{if(Te())return;let c=u.reason instanceof Error?u.reason.message:String(u.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(q(`window:rejection ${c.slice(0,140)}`),bn.push(c))};z&&typeof window<"u"&&(window.addEventListener("error",jn),window.addEventListener("unhandledrejection",Wt));let Xt={value:0};if(z&&typeof PerformanceObserver<"u")try{Pn=new PerformanceObserver(u=>{if(!Te())for(let c of u.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;Xt.value+=1;let L=Math.round(c.duration);q(`net ${L}ms ${c.name.slice(0,90)}`)}}),Pn.observe({type:"resource",buffered:!0})}catch{}let Ft=()=>{for(an?.disconnect(),an=null,Pn?.disconnect(),Pn=null;Rt.length;)clearTimeout(Rt.pop());z&&typeof window<"u"&&(window.removeEventListener("error",jn),window.removeEventListener("unhandledrejection",Wt))},Rn=u=>{if(!u)return!1;let c=u.toLowerCase();return c.includes("zoid destroyed")||c.includes("destroyed all components")||c.includes("window closed")||c.includes("detected container element removed")},Nn=u=>{if(Te()||Rn(u))return;let c=On(u)??u;st(()=>Ae.current?.(c))},sn=u=>{ut||(ze(!0),u.includes("paypal_ineligible")||H.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",u))},Qt=(u,c=!1)=>{if(ut)return;let L=T.current||!x;if(Zn)return;Zn=!0,Pt=!0,Ft(),At();let y=c||La(u);if(y&&x&&!T.current){T.current=!0,ie(!1),E(!1),Be(!0),g.current?.("retrying"),qn=setTimeout(()=>{ut||Ee(ee=>ee+1)},Xi);return}if(y||L){if(ie(!1),E(!1),Be(!1),ze(!0),g.current?.("exhausted"),!de.current){de.current=!0;let ee=La(u)?"paypal_init_timeout":c?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",ee)}return}sn(u)};ze(!1);let It=async(u,c=He.current)=>{if(Te())return;let L=c?.sessionId??e;if(G.current){await G.current(u,{sessionId:L,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let y=H.startTiming();H.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ee=()=>{H.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),H.performance({stage:"processing",durationMs:H.elapsed(y),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Ie=dt.current,rt=c?.accountPatch?.email??nt.current,Ce=c?.accountPatch?.userId??Ie?.customer?.id??Ie?.accountData?.userId??"",f=await new Xr.PaymentAPI(re,{telemetry:!1}).processPayment(Ce,{sessionId:L,nonce:c?.nonce??Qe.current,tokenizedData:u,accountData:{userId:Ce,email:rt??Ie?.customer?.email??"",firstName:c?.accountPatch?.firstName??Ie?.customer?.firstName??Ie?.accountData?.firstName??"",lastName:c?.accountPatch?.lastName??Ie?.customer?.lastName??Ie?.accountData?.lastName??"",country:c?.accountPatch?.country??Ie?.customer?.country??Ie?.accountData?.country??void 0,zip:c?.accountPatch?.zip??Ie?.customer?.zip??Ie?.accountData?.zip??void 0}});if(f.ok){if(Pt||ut&&An.current)return;ee(),H.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),st(()=>tt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Te())return;let U=await f.json().catch(()=>null),Y=U?.message??"PayPal payment failed.",Ye=On(Y)??Y;ee(),f.status===400&&(typeof U?.declineCode=="string"||!Array.isArray(U?.fields))?H.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):f.status===400||f.status===422?H.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):H.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:f.status>=500?"5xx":f.status>=400?"4xx":f.status>=300?"3xx":"unknown",failureCategory:f.status>=500?"server_error":void 0}),Nn(Ye),st(()=>at.current?.(St("paypal",Ye,{code:U?.code,declineCode:U?.declineCode})));return}catch(Ie){if(Te())return;ee(),H.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let rt=Ie instanceof Error?Ie.message:"PayPal payment failed.",Ce=On(rt)??rt;Nn(Ce),st(()=>at.current?.(St("paypal",Ce)));return}},h=()=>new Mn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),W=u=>Te()?Promise.reject(h()):Promise.resolve(u),j=async u=>{if(Te())throw h();$n||Ln();let c=He.current,L=c?.sessionId??e,y=c?.nonce??Qe.current;H.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ee=await new Xr.PaymentAPI(re,{telemetry:!1}).createSessionIntent(L,y??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:qe});if(Te())throw h();if(ee.provider!=="paypal")throw new Error(u);return H.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ee.providerObjectId},ge=(u,c)=>{let L=c?.nonce??Qe.current;if(!L)return;let y=c?.sessionId??e,ee=lr(u)??Tn(u)??"provider_declined";new Xr.PaymentAPI(re,{telemetry:!1}).reportSessionIntentDecline(y,L,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ee}).catch(()=>{})},X=se;q("loadScript:scheduled (deferred 1 tick)");let ue=null,S=setTimeout(()=>{if(ut){q("loadScript:skipped (cancelled before defer ran)");return}q("loadScript:start");let u=le==="live"?"production":le;ue=(0,Na.loadScript)({clientId:o,currency:m,intent:d?"subscription":"capture",vault:d?!0:void 0,...u?{environment:u}:{},...u==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),ue.then(c=>{if(q(`loadScript:resolved inactive=${Te()} ns=${!!c} buttons=${!!c?.Buttons}`),Te())return;if(!c?.Buttons){q("FAIL: namespace missing Buttons factory"),Qt("PayPal SDK did not expose the Buttons factory.");return}H.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),H.performance({stage:"provider_ready",durationMs:H.elapsed(ye.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),H.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let L=async O=>{if(Te()||_e.current!==X)return;let f=O.subscriptionID??O.orderID??"",U=f?Ge.current.get(f):wt.current.get(X);if(!(!U||!qt(U.generation))&&Nt(U.generation)){Ge.current.delete(f),wt.current.delete(U.surfaceKey),gt();try{if(E(!0),st(()=>Ae.current?.(null)),!f)throw new Mn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await It({id:f,isPaypal:!0},U)}catch(Y){Nn(Y instanceof Error?Y.message:"PayPal capture failed.")}finally{Te()||E(!1)}}},y=c.Buttons({style:{layout:"horizontal",height:Qr,tagline:!1},onClick:async(O,f)=>{if(Te()){await f.reject();return}Ln();let U=ke.current,Y={};if(U)try{let Dt=await U("paypal");if(Te()){await f.reject();return}if(!Dt.proceed){He.current=null,wt.current.delete(X),await f.reject();return}Y={sessionId:Dt.sessionId,accountPatch:Dt.accountPatch,nonce:Dt.nonce}}catch(Dt){q(`onClick:runBeforeButtonClick rejected msg=${(Dt instanceof Error?Dt.message:String(Dt)).slice(0,120)}`),He.current=null,wt.current.delete(X),await f.reject();return}st(()=>Ke.current?.("paypal"));let Et={generation:Dn(),surfaceKey:X,...Y};He.current=Et,wt.current.set(X,Et),await f.resolve(),H.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),H.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),H.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Kt=H.startTiming()},createOrder:d?void 0:K?()=>W(K).then(Bt):()=>j("Failed to create PayPal order.").then(Bt),createSubscription:d?K?()=>W(K).then(Bt):()=>j("Failed to create PayPal subscription.").then(Bt):void 0,onApprove:L,onCancel:()=>{if(Te())return;let O=wt.current.get(X)??He.current;O&&wt.current.delete(O.surfaceKey),He.current=null,gt(),H.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Se.current=!0,kt({generation:O?.generation,remount:!0,focus:!1})},onError:O=>{if(Te()||_e.current!==X)return;let f=O instanceof Error?O.message:"PayPal failed to render.";if(q(`onError rendered=${Jt} msg=${f.slice(0,120)}`),Jt){let U=wt.current.get(X)??He.current;if(U&&!qt(U.generation)||!U&&je.current===Ze.current)return;if(Rn(f)){Nt(U?.generation);return}if(gt(),Rr(O)){H.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ge(O,U),st(()=>at.current?.(St("paypal",f))),U&&wt.current.delete(U.surfaceKey),He.current=null,Nt(U?.generation);return}let Y=f.toLowerCase();H.error({errorCode:Y.includes("popup")&&Y.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),U&&wt.current.delete(U.surfaceKey),He.current=null,kt({generation:U?.generation,remount:!0,showRetry:!0,focus:!0}),hn(O,{code:"paypal_runtime_failed"});return}Qt(f)}}),ee=y.isEligible();if(q(`isEligible=${ee}`),H.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ee){ie(!1),Qt("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Vt=y,z&&q(`container:dims ${Ot(Ht)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),z&&typeof MutationObserver<"u"&&(an=new MutationObserver(O=>{if(!Te()){for(let f of O)if(f.type==="childList")f.addedNodes.forEach(U=>{if(!(U instanceof Element))return;let Y=U.tagName.toLowerCase(),Ye=(U.getAttribute("title")??"").slice(0,40),Et=Y==="iframe"?` ${bt(U)}`:"";q(`child+ ${Y}${Ye?` title="${Ye}"`:""}${Et} dims=${Ot(U)}`)});else if(f.type==="attributes"&&f.target instanceof Element){let U=f.target;if(U.tagName.toLowerCase()!=="iframe")continue;let Y=f.attributeName;(Y==="src"||Y==="srcdoc")&&q(`attr~ iframe ${Y}=${Y==="srcdoc"?`[${(U.getAttribute("srcdoc")??"").length}ch]`:Le(U.getAttribute("src"))} dims=${Ot(U)}`)}}}),an.observe(Ht,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let rt=O=>{if(Te()||Jt)return;let f=Ht.querySelectorAll("iframe"),U=typeof document<"u"&&"hasStorageAccess"in document;q(`watchdog:${O} container=${Ot(Ht)} children=${Ht.childElementCount} iframes=${f.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${U} paypalNetRequests=${Xt.value}`),f.forEach((Y,Ye)=>{let Et=(Y.getAttribute("title")??"").slice(0,40);q(` iframe[${Ye}] ${Ot(Y)}${Et?` title="${Et}"`:""} ${bt(Y)}`);let Dt=vt(Y);Dt&&q(` ${Dt}`)}),bn.length===0&&q(" (no PayPal/zoid window errors captured)")};z&&(Rt.push(setTimeout(()=>rt("3s"),3e3)),Rt.push(setTimeout(()=>rt("8s"),8e3)),Rt.push(setTimeout(()=>rt("15s"),15e3))),q("render:start");let Ce=H.startTiming();Rt.push(setTimeout(()=>{Te()||Jt||(q("watchdog:11s retryable render timeout"),Qt("PayPal Buttons render did not settle within 11000ms.",!0))},Qi)),y.render(Ht).then(()=>{if(q(`render:resolved inactive=${Te()}`),Ft(),Te()){At();return}Jt=!0,ie(!0),Be(!1),g.current?.("ready"),H.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),H.performance({stage:"checkout_render",durationMs:H.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(O=>{let f=O instanceof Error?O.message:"PayPal failed to render.";q(`render:rejected msg=${f.slice(0,120)}`),Ft(),Qt(f)})}).catch(c=>{let L=c instanceof Error?c.message:"PayPal SDK failed to load.";q(`loadScript:rejected msg=${L.slice(0,120)}`),Qt(L)})},0);return()=>{ut=!0,clearTimeout(S),qn&&clearTimeout(qn),Ft(),At()}},[x,re,o,m,s,d,e,K,se,H]);let en=z?(0,pn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Oe?"#fef2f2":"#f3f4f6",border:`1px solid ${Oe?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Pe} failed=${Oe})`,Ve.length===0?`
6
+ `})]})})}var xa=require("@flopay/shared");function Ta(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Eo(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 Ma(e,t){let n=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],l=n.reduce((s,m)=>s+(m.overrideAmount??m.totalAmount??0),0),o=e.currency??n.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(l*100),currency:o,status:"open",customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((s,m)=>({uuid:`synthetic-${s.type??"item"}-${m}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??o,metadata:s.metadata??null}))}}function _o(e,t){return t?{...e,...t}:e}function St(e,t,n){let l=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,s=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:l,...o?{code:o}:{},...s?{declineCode:s}:{}}}var Ji=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function On(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:l}of Ji)if(n.test(t))return l;return e}function Yr(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Ba(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Aa(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Gr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Jr="flopay_recent_completion_";function sr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Jr+e,JSON.stringify(t))}catch{}}function xo(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Jr+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Jr+e),!1):!0}catch{return!1}}function Fa(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var B=require("react"),Na=require("@paypal/paypal-js"),Xr=require("@flopay/js"),Mn=require("@flopay/shared");function st(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function Xi(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Gn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Tn(e){if(typeof e!="object"||e===null)return;let t=e;return Gn(t.code)??Gn(t.type)??Gn(t.name)}function lr(e){if(!(typeof e!="object"||e===null))return Gn(e.decline_code)}function Rr(e){return typeof e!="object"||e===null?!1:Gn(e.type)?.toLowerCase()==="card_error"||lr(e)!==void 0}function zn(e){let t=Xi(e)?.toLowerCase()??"",l=`${Tn(e)?.toLowerCase()??""} ${t}`;return l.includes("popup")&&l.includes("block")}var pn=require("react/jsx-runtime"),Qr=45,Qi=1e3,Zi=11e3,es=["https://www.paypal.com","https://www.sandbox.paypal.com"],Da="We couldn't open PayPal. Try again or choose another payment method.",ts={width:"100%",minHeight:Qr,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 La(e){return e.includes("No ack for postMessage init()")&&es.some(t=>e.includes(t))&&e.includes("10000ms")}function ns(e){return e?`${Da} Allow pop-ups for this site, then try again.`:Da}function Oa({sessionId:e,nonce:t,billingApiUrl:n,email:l,clientId:o,environment:s,currency:m,isSubscription:d,onTokenizedBody:I,onComplete:N,onErrorChange:P,onDecline:_,onTechnicalFailure:k,isProcessing:A=!1,onLoadStateChange:p,onInitializationStateChange:v,allowAutomaticRetry:x=!0,onButtonClick:F,runBeforeButtonClick:b,session:ce,existingOrderId:K,telemetry:pe,telemetryContext:ae,debug:z=!1}){let te=un(),Q=(0,B.useMemo)(()=>{if(te)return null;let D=jr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Mn.SDK_VERSION,enabled:pe!==!1});return D.setCheckoutContext(ae??{}),D.beginCheckout(ae??{}),D},[n,te,pe,ae?.checkoutMode,ae?.layout]),me=(0,B.useMemo)(()=>Tt(te),[te]);(0,B.useEffect)(()=>()=>{Q&&Q.flush().catch(()=>{}).finally(()=>Q.destroy())},[Q]);let H=(0,B.useMemo)(()=>({error:D=>{me?me.error(D):Q?.error(D)},log:D=>{me?me.log(D):Q?.log(D)},performance:D=>{me?me.performance(D):Q?.performance(D)},terminal:D=>{me?me.terminal(D):Q?.terminal(D)},startTiming:()=>me?.now()??Q?.now()??0,elapsed:D=>me?.elapsed(D)??Math.max(0,(Q?.now()??D)-D)}),[me,Q]),J=(0,B.useRef)(null),ye=(0,B.useRef)(0),Me=(0,B.useRef)(null),Se=(0,B.useRef)(!1),[Pe,ie]=(0,B.useState)(!1),[ve,Be]=(0,B.useState)(!1),[se,Ee]=(0,B.useState)(0),_e=(0,B.useRef)(0),[Re,Z]=(0,B.useState)(!1),T=(0,B.useRef)(!1),de=(0,B.useRef)(!1),[Oe,ze]=(0,B.useState)(!1),[fe,E]=(0,B.useState)(!1),re=(0,B.useMemo)(()=>n.replace(/\/+$/,""),[n]),oe=(0,B.useMemo)(()=>JSON.stringify([re,o,m,s??"",d,e,K??""]),[re,o,m,s,K,d,e]),$e=(0,B.useRef)(oe),ct=$e.current!==oe,[Ve,ot]=(0,B.useState)([]),q=D=>{z&&ot(ft=>[...ft,`${new Date().toISOString().slice(11,23)} ${D}`])},G=(0,B.useRef)(I),tt=(0,B.useRef)(N),Ae=(0,B.useRef)(P),at=(0,B.useRef)(_),We=(0,B.useRef)(k),Ke=(0,B.useRef)(F),rn=(0,B.useRef)(p),g=(0,B.useRef)(v),ke=(0,B.useRef)(b),dt=(0,B.useRef)(ce),nt=(0,B.useRef)(l),Qe=(0,B.useRef)(t),He=(0,B.useRef)(null),Ze=(0,B.useRef)(0),xe=(0,B.useRef)(null),je=(0,B.useRef)(null),wt=(0,B.useRef)(new Map),Ge=(0,B.useRef)(new Map),An=(0,B.useRef)(!1);(0,B.useEffect)(()=>(An.current=!0,()=>{An.current=!1}),[]),(0,B.useEffect)(()=>{G.current=I},[I]),(0,B.useEffect)(()=>{tt.current=N},[N]),(0,B.useEffect)(()=>{Ae.current=P},[P]),(0,B.useEffect)(()=>{at.current=_},[_]),(0,B.useEffect)(()=>{We.current=k},[k]),(0,B.useEffect)(()=>{Ke.current=F},[F]),(0,B.useEffect)(()=>{rn.current=p},[p]),(0,B.useEffect)(()=>{g.current=v},[v]),(0,B.useEffect)(()=>{ke.current=b},[b]),(0,B.useEffect)(()=>{dt.current=ce},[ce]),(0,B.useEffect)(()=>{nt.current=l},[l]),(0,B.useEffect)(()=>{Qe.current=t},[t]),(0,B.useEffect)(()=>{_e.current=se},[se]),(0,B.useEffect)(()=>{Re&&Me.current?.focus()},[Re,se]);let ht=(0,B.useCallback)(()=>{window.setTimeout(()=>{Me.current?.focus()},0)},[]),Fn=(0,B.useCallback)(()=>{ie(!1),Ee(D=>D+1)},[]),on=(0,B.useCallback)(()=>{Z(!1),(J.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??J.current)?.focus?.()},[]);(0,B.useEffect)(()=>{!Pe||!Se.current||(Se.current=!1,on())},[on,Pe,se]);let hn=(0,B.useCallback)((D,ft)=>{let ut=We.current;if(ut){ut("paypal",D,ft);return}Ae.current?.(ns(ft?.popupBlocked??zn(D)))},[]),Zt=()=>{xe.current?.timer&&(clearTimeout(xe.current.timer),xe.current.timer=null)},Dn=()=>{Zt();let D=Ze.current+1;return Ze.current=D,je.current=null,xe.current={generation:D,timer:null,yieldedControl:!1},Z(!1),D},Nt=D=>D!==void 0&&xe.current?.generation!==D?!1:(Zt(),xe.current=null,je.current=null,!0),kt=D=>{let ft=D?.generation??xe.current?.generation??Ze.current;(!D?.generation||xe.current?.generation===ft)&&(Zt(),xe.current=null),je.current=ft,D?.showRetry&&Z(!0),D?.remount&&Fn(),D?.focus!==!1&&ht()},qt=D=>xe.current?.generation===D&&je.current!==D,Gt=D=>{typeof document<"u"&&document.visibilityState!=="visible"||(Zt(),D.timer=setTimeout(()=>{xe.current?.generation===D.generation&&(xe.current=null,je.current=D.generation,hn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),Z(!0),Fn(),ht())},600))},Mt=()=>{let D=xe.current;D?.yieldedControl&&Gt(D)},jt=()=>{let D=xe.current;D&&(D.yieldedControl=!0,Zt())},Bt=D=>{let ft=He.current;return ft&&Ge.current.set(D,ft),D};(0,B.useEffect)(()=>{let D=()=>{document.visibilityState==="visible"?Mt():jt()};return document.addEventListener("visibilitychange",D),window.addEventListener("focus",Mt),window.addEventListener("blur",jt),()=>{document.removeEventListener("visibilitychange",D),window.removeEventListener("focus",Mt),window.removeEventListener("blur",jt),Zt()}},[]),(0,B.useEffect)(()=>{$e.current!==oe&&($e.current=oe,T.current=!1,de.current=!1,ie(!1),Be(!1),ze(!1),g.current?.("loading"))},[oe]),(0,B.useEffect)(()=>{st(()=>rn.current?.(Pe&&!Oe))},[Pe,Oe]);let le=(0,Mn.normalizeGatewayEnvironment)(s);(0,B.useEffect)(()=>{let D=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",ft=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(q(`mount clientId=${D} env=${s??"(unset)"}\u2192${le??"live"} ccy=${m} sub=${d}`),q(`ua=${ft.slice(0,80)}${ft.length>80?"\u2026":""}`),!o){q("FAIL: clientId empty \u2014 gateway misconfigured"),ze(!0),H.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!J.current){q("FAIL: containerRef not attached");return}ye.current=H.startTiming(),H.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ut=!1,Pt=!1,Te=()=>ut||Pt,qe,$n=!1,Ln=()=>{qe=(0,Mn.generateIdempotencyKey)(),qe||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),$n=!0},qn=null,Zn=!1,Vt=null,it=!1,At=()=>{!Vt||it||(it=!0,Vt.close().catch(()=>{}))},Kt=null,gt=()=>{Kt!==null&&(H.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),H.performance({stage:"overlay_return",durationMs:H.elapsed(Kt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Kt=null)},Jt=!1,Ht=J.current,an=null,Pn=null,Rt=[],Ot=u=>{if(!u||typeof u.getBoundingClientRect!="function")return"(no rect)";let c=u.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},Le=u=>{if(!u)return"(empty)";try{let c=new URL(u,typeof window<"u"?window.location.href:"https://localhost"),L=c.pathname.toLowerCase();return L.includes("checkcaptcha")||L.includes("captcha")?`CAPTCHA(${c.host}${L})`:L.includes("risk")||L.includes("challenge")?`RISK(${c.host}${L})`:L.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${L}`.slice(0,100)}catch{return u.slice(0,80)}},bt=u=>{let c=u.getAttribute("src"),L=u.getAttribute("srcdoc"),y=u.getAttribute("name"),ee=u.getAttribute("sandbox"),Ie=[];return c&&Ie.push(`src=${Le(c)}`),L&&Ie.push(`srcdoc[${L.length}ch]`),!c&&!L&&Ie.push("src=(empty) srcdoc=(empty)"),y&&Ie.push(`name=${y.slice(0,40)}`),ee!==null&&Ie.push(`sandbox="${ee.slice(0,40)}"`),Ie.join(" ")},vt=u=>{if(!(u instanceof HTMLIFrameElement))return"";try{let c=u.contentDocument;if(!c)return"cd=null";let L=c.body?.children.length??0,y=c.body?.innerHTML.length??0,ee=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${L}children,${y}ch] head[${ee}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},bn=[],jn=u=>{if(Te())return;let c=u.message??String(u.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(q(`window:error ${c.slice(0,140)}`),bn.push(c))},Wt=u=>{if(Te())return;let c=u.reason instanceof Error?u.reason.message:String(u.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(q(`window:rejection ${c.slice(0,140)}`),bn.push(c))};z&&typeof window<"u"&&(window.addEventListener("error",jn),window.addEventListener("unhandledrejection",Wt));let Xt={value:0};if(z&&typeof PerformanceObserver<"u")try{Pn=new PerformanceObserver(u=>{if(!Te())for(let c of u.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;Xt.value+=1;let L=Math.round(c.duration);q(`net ${L}ms ${c.name.slice(0,90)}`)}}),Pn.observe({type:"resource",buffered:!0})}catch{}let Ft=()=>{for(an?.disconnect(),an=null,Pn?.disconnect(),Pn=null;Rt.length;)clearTimeout(Rt.pop());z&&typeof window<"u"&&(window.removeEventListener("error",jn),window.removeEventListener("unhandledrejection",Wt))},Rn=u=>{if(!u)return!1;let c=u.toLowerCase();return c.includes("zoid destroyed")||c.includes("destroyed all components")||c.includes("window closed")||c.includes("detected container element removed")},Nn=u=>{if(Te()||Rn(u))return;let c=On(u)??u;st(()=>Ae.current?.(c))},sn=u=>{ut||(ze(!0),u.includes("paypal_ineligible")||H.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",u))},Qt=(u,c=!1)=>{if(ut)return;let L=T.current||!x;if(Zn)return;Zn=!0,Pt=!0,Ft(),At();let y=c||La(u);if(y&&x&&!T.current){T.current=!0,ie(!1),E(!1),Be(!0),g.current?.("retrying"),qn=setTimeout(()=>{ut||Ee(ee=>ee+1)},Qi);return}if(y||L){if(ie(!1),E(!1),Be(!1),ze(!0),g.current?.("exhausted"),!de.current){de.current=!0;let ee=La(u)?"paypal_init_timeout":c?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",ee)}return}sn(u)};ze(!1);let It=async(u,c=He.current)=>{if(Te())return;let L=c?.sessionId??e;if(G.current){await G.current(u,{sessionId:L,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let y=H.startTiming();H.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ee=()=>{H.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),H.performance({stage:"processing",durationMs:H.elapsed(y),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Ie=dt.current,rt=c?.accountPatch?.email??nt.current,Ce=c?.accountPatch?.userId??Ie?.customer?.id??Ie?.accountData?.userId??"",f=await new Xr.PaymentAPI(re,{telemetry:!1}).processPayment(Ce,{sessionId:L,nonce:c?.nonce??Qe.current,tokenizedData:u,accountData:{userId:Ce,email:rt??Ie?.customer?.email??"",firstName:c?.accountPatch?.firstName??Ie?.customer?.firstName??Ie?.accountData?.firstName??"",lastName:c?.accountPatch?.lastName??Ie?.customer?.lastName??Ie?.accountData?.lastName??"",country:c?.accountPatch?.country??Ie?.customer?.country??Ie?.accountData?.country??void 0,zip:c?.accountPatch?.zip??Ie?.customer?.zip??Ie?.accountData?.zip??void 0}});if(f.ok){if(Pt||ut&&An.current)return;ee(),H.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),st(()=>tt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Te())return;let U=await f.json().catch(()=>null),Y=U?.message??"PayPal payment failed.",Ye=On(Y)??Y;ee(),f.status===400&&(typeof U?.declineCode=="string"||!Array.isArray(U?.fields))?H.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):f.status===400||f.status===422?H.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):H.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:f.status>=500?"5xx":f.status>=400?"4xx":f.status>=300?"3xx":"unknown",failureCategory:f.status>=500?"server_error":void 0}),Nn(Ye),st(()=>at.current?.(St("paypal",Ye,{code:U?.code,declineCode:U?.declineCode})));return}catch(Ie){if(Te())return;ee(),H.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let rt=Ie instanceof Error?Ie.message:"PayPal payment failed.",Ce=On(rt)??rt;Nn(Ce),st(()=>at.current?.(St("paypal",Ce)));return}},h=()=>new Mn.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),W=u=>Te()?Promise.reject(h()):Promise.resolve(u),j=async u=>{if(Te())throw h();$n||Ln();let c=He.current,L=c?.sessionId??e,y=c?.nonce??Qe.current;H.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ee=await new Xr.PaymentAPI(re,{telemetry:!1}).createSessionIntent(L,y??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:qe});if(Te())throw h();if(ee.provider!=="paypal")throw new Error(u);return H.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ee.providerObjectId},ge=(u,c)=>{let L=c?.nonce??Qe.current;if(!L)return;let y=c?.sessionId??e,ee=lr(u)??Tn(u)??"provider_declined";new Xr.PaymentAPI(re,{telemetry:!1}).reportSessionIntentDecline(y,L,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ee}).catch(()=>{})},X=se;q("loadScript:scheduled (deferred 1 tick)");let ue=null,S=setTimeout(()=>{if(ut){q("loadScript:skipped (cancelled before defer ran)");return}q("loadScript:start");let u=le==="live"?"production":le;ue=(0,Na.loadScript)({clientId:o,currency:m,intent:d?"subscription":"capture",vault:d?!0:void 0,...u?{environment:u}:{},...u==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),ue.then(c=>{if(q(`loadScript:resolved inactive=${Te()} ns=${!!c} buttons=${!!c?.Buttons}`),Te())return;if(!c?.Buttons){q("FAIL: namespace missing Buttons factory"),Qt("PayPal SDK did not expose the Buttons factory.");return}H.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),H.performance({stage:"provider_ready",durationMs:H.elapsed(ye.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),H.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let L=async O=>{if(Te()||_e.current!==X)return;let f=O.subscriptionID??O.orderID??"",U=f?Ge.current.get(f):wt.current.get(X);if(!(!U||!qt(U.generation))&&Nt(U.generation)){Ge.current.delete(f),wt.current.delete(U.surfaceKey),gt();try{if(E(!0),st(()=>Ae.current?.(null)),!f)throw new Mn.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await It({id:f,isPaypal:!0},U)}catch(Y){Nn(Y instanceof Error?Y.message:"PayPal capture failed.")}finally{Te()||E(!1)}}},y=c.Buttons({style:{layout:"horizontal",height:Qr,tagline:!1},onClick:async(O,f)=>{if(Te()){await f.reject();return}Ln();let U=ke.current,Y={};if(U)try{let Dt=await U("paypal");if(Te()){await f.reject();return}if(!Dt.proceed){He.current=null,wt.current.delete(X),await f.reject();return}Y={sessionId:Dt.sessionId,accountPatch:Dt.accountPatch,nonce:Dt.nonce}}catch(Dt){q(`onClick:runBeforeButtonClick rejected msg=${(Dt instanceof Error?Dt.message:String(Dt)).slice(0,120)}`),He.current=null,wt.current.delete(X),await f.reject();return}st(()=>Ke.current?.("paypal"));let Et={generation:Dn(),surfaceKey:X,...Y};He.current=Et,wt.current.set(X,Et),await f.resolve(),H.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),H.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),H.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Kt=H.startTiming()},createOrder:d?void 0:K?()=>W(K).then(Bt):()=>j("Failed to create PayPal order.").then(Bt),createSubscription:d?K?()=>W(K).then(Bt):()=>j("Failed to create PayPal subscription.").then(Bt):void 0,onApprove:L,onCancel:()=>{if(Te())return;let O=wt.current.get(X)??He.current;O&&wt.current.delete(O.surfaceKey),He.current=null,gt(),H.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Se.current=!0,kt({generation:O?.generation,remount:!0,focus:!1})},onError:O=>{if(Te()||_e.current!==X)return;let f=O instanceof Error?O.message:"PayPal failed to render.";if(q(`onError rendered=${Jt} msg=${f.slice(0,120)}`),Jt){let U=wt.current.get(X)??He.current;if(U&&!qt(U.generation)||!U&&je.current===Ze.current)return;if(Rn(f)){Nt(U?.generation);return}if(gt(),Rr(O)){H.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ge(O,U),st(()=>at.current?.(St("paypal",f))),U&&wt.current.delete(U.surfaceKey),He.current=null,Nt(U?.generation);return}let Y=f.toLowerCase();H.error({errorCode:Y.includes("popup")&&Y.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),U&&wt.current.delete(U.surfaceKey),He.current=null,kt({generation:U?.generation,remount:!0,showRetry:!0,focus:!0}),hn(O,{code:"paypal_runtime_failed"});return}Qt(f)}}),ee=y.isEligible();if(q(`isEligible=${ee}`),H.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ee){ie(!1),Qt("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Vt=y,z&&q(`container:dims ${Ot(Ht)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),z&&typeof MutationObserver<"u"&&(an=new MutationObserver(O=>{if(!Te()){for(let f of O)if(f.type==="childList")f.addedNodes.forEach(U=>{if(!(U instanceof Element))return;let Y=U.tagName.toLowerCase(),Ye=(U.getAttribute("title")??"").slice(0,40),Et=Y==="iframe"?` ${bt(U)}`:"";q(`child+ ${Y}${Ye?` title="${Ye}"`:""}${Et} dims=${Ot(U)}`)});else if(f.type==="attributes"&&f.target instanceof Element){let U=f.target;if(U.tagName.toLowerCase()!=="iframe")continue;let Y=f.attributeName;(Y==="src"||Y==="srcdoc")&&q(`attr~ iframe ${Y}=${Y==="srcdoc"?`[${(U.getAttribute("srcdoc")??"").length}ch]`:Le(U.getAttribute("src"))} dims=${Ot(U)}`)}}}),an.observe(Ht,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let rt=O=>{if(Te()||Jt)return;let f=Ht.querySelectorAll("iframe"),U=typeof document<"u"&&"hasStorageAccess"in document;q(`watchdog:${O} container=${Ot(Ht)} children=${Ht.childElementCount} iframes=${f.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${U} paypalNetRequests=${Xt.value}`),f.forEach((Y,Ye)=>{let Et=(Y.getAttribute("title")??"").slice(0,40);q(` iframe[${Ye}] ${Ot(Y)}${Et?` title="${Et}"`:""} ${bt(Y)}`);let Dt=vt(Y);Dt&&q(` ${Dt}`)}),bn.length===0&&q(" (no PayPal/zoid window errors captured)")};z&&(Rt.push(setTimeout(()=>rt("3s"),3e3)),Rt.push(setTimeout(()=>rt("8s"),8e3)),Rt.push(setTimeout(()=>rt("15s"),15e3))),q("render:start");let Ce=H.startTiming();Rt.push(setTimeout(()=>{Te()||Jt||(q("watchdog:11s retryable render timeout"),Qt("PayPal Buttons render did not settle within 11000ms.",!0))},Zi)),y.render(Ht).then(()=>{if(q(`render:resolved inactive=${Te()}`),Ft(),Te()){At();return}Jt=!0,ie(!0),Be(!1),g.current?.("ready"),H.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),H.performance({stage:"checkout_render",durationMs:H.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(O=>{let f=O instanceof Error?O.message:"PayPal failed to render.";q(`render:rejected msg=${f.slice(0,120)}`),Ft(),Qt(f)})}).catch(c=>{let L=c instanceof Error?c.message:"PayPal SDK failed to load.";q(`loadScript:rejected msg=${L.slice(0,120)}`),Qt(L)})},0);return()=>{ut=!0,clearTimeout(S),qn&&clearTimeout(qn),Ft(),At()}},[x,re,o,m,s,d,e,K,se,H]);let en=z?(0,pn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Oe?"#fef2f2":"#f3f4f6",border:`1px solid ${Oe?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Pe} failed=${Oe})`,Ve.length===0?`
7
7
  (waiting for first lifecycle event\u2026)`:`
8
8
  ${Ve.join(`
9
- `)}`]}):null;return Oe&&!ct?z?(0,pn.jsx)("div",{children:en}):null:(0,pn.jsxs)("div",{children:[en,(0,pn.jsxs)("div",{"aria-hidden":ve?!0:void 0,style:ve?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Qr},children:[!Pe&&!ve&&(0,pn.jsx)("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),(0,pn.jsx)("div",{ref:J,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:Qr,display:"flex",opacity:Pe?1:0},"aria-busy":fe||A},se)]},se),Re&&(0,pn.jsx)("button",{ref:Me,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:on,style:es,children:"Try PayPal again"})]})}function Ir(e){return(0,pn.jsx)(Oa,{...e})}function za(e){return(0,pn.jsx)(Oa,{...e})}var Ut=require("@flopay/shared"),i=require("react/jsx-runtime"),wn="flopay_stripe_resume",Ua="flopay_wallet_resume",Er="flopay_paypal_resume",ns=250,$a="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Fo(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function to({billingApiUrl:e,sessionId:t,nonce:n,request:l}){if(!(!t||!n))try{await new mn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,l)}catch{}}function rs(e){return e instanceof Ut.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Mo(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Zr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let l=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),s=Math.round((l>>16&255)*o),m=Math.round((l>>8&255)*o),d=Math.round((l&255)*o);return`#${(1<<24|s<<16|m<<8|d).toString(16).slice(1)}`}var os=`
9
+ `)}`]}):null;return Oe&&!ct?z?(0,pn.jsx)("div",{children:en}):null:(0,pn.jsxs)("div",{children:[en,(0,pn.jsxs)("div",{"aria-hidden":ve?!0:void 0,style:ve?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Qr},children:[!Pe&&!ve&&(0,pn.jsx)("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),(0,pn.jsx)("div",{ref:J,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:Qr,display:"flex",opacity:Pe?1:0},"aria-busy":fe||A},se)]},se),Re&&(0,pn.jsx)("button",{ref:Me,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:on,style:ts,children:"Try PayPal again"})]})}function Ir(e){return(0,pn.jsx)(Oa,{...e})}function za(e){return(0,pn.jsx)(Oa,{...e})}var Ut=require("@flopay/shared"),i=require("react/jsx-runtime"),wn="flopay_stripe_resume",Ua="flopay_wallet_resume",Er="flopay_paypal_resume",rs=250,$a="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Fo(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function to({billingApiUrl:e,sessionId:t,nonce:n,request:l}){if(!(!t||!n))try{await new mn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,l)}catch{}}function os(e){return e instanceof Ut.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Mo(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Zr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let l=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),s=Math.round((l>>16&255)*o),m=Math.round((l>>8&255)*o),d=Math.round((l&255)*o);return`#${(1<<24|s<<16|m<<8|d).toString(16).slice(1)}`}var as=`
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 @@ ${Ve.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
- `,eo=44;function Do(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 as={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Ga={width:"100%",minHeight:eo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function is(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function qa(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ja(e){return e==="paypal"?"PayPal":(0,R.getStripeMethodDisplayName)(e)}function ss(e,t){let n=`We couldn't open ${Ja(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Xa(e){let t=(0,r.useRef)(0),n=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useCallback)((p=l.current)=>{let v=p;v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),s=(0,r.useCallback)((p,v)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(p),p.timer=setTimeout(()=>{p.timer=null,l.current?.generation===p.generation&&(l.current=null,n.current=p.generation,e(p.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},v))},[o,e]),m=(0,r.useCallback)(p=>{p.yieldedControl&&s(p,600)},[s]),d=(0,r.useCallback)(p=>{o();let v=t.current+1;t.current=v,n.current=null;let x={generation:v,method:p,timer:null,yieldedControl:!1};return l.current=x,v},[o]),I=(0,r.useCallback)(p=>{let v=l.current;return typeof p=="number"&&v?.generation!==p?!1:(o(v),l.current=null,(typeof p!="number"||n.current===p)&&(n.current=null),!0)},[o]),N=(0,r.useCallback)(p=>{let v=l.current,x=p??v?.generation??t.current;(!p||v?.generation===p)&&(o(v),l.current=null),n.current=x},[o]),P=(0,r.useCallback)(p=>n.current===(p??t.current),[]),_=(0,r.useCallback)(p=>l.current?.generation===p&&n.current!==p,[]),k=(0,r.useCallback)(()=>{let p=l.current;p&&m(p)},[m]),A=(0,r.useCallback)(()=>{let p=l.current;p&&(p.yieldedControl=!0,o(p))},[o]);return(0,r.useEffect)(()=>{let p=()=>{document.visibilityState==="visible"?k():A()},v=()=>{A()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",v),window.addEventListener("focus",k),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",v),window.removeEventListener("focus",k),o()}},[o,A,k]),{startAttempt:d,finishAttempt:I,invalidateAttempt:N,isAttemptInvalidated:P,isAttemptCurrent:_}}function ls(e){let t=(0,R.getPostalCodeExample)(e);return`Enter a valid ${(0,R.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function cs(e,t,n){let l=(0,R.isPostalCodeSupported)(e),o=t.trim(),s=n&&l,m=s&&!o,d=s&&!!o&&!(0,R.isValidPostalCode)(e,o);return{visible:n,supported:l,required:s,empty:m,malformed:d}}function ja(e,t){return t instanceof Ut.FloPayError?t:new Ut.FloPayError(t instanceof Error?t.message:`${is(e)} before-click hook failed.`,"validation_error")}function Bo(){return(0,i.jsx)("style",{children:os})}function ds(e){return typeof e=="number"?`${e}px`:e}function Va(e){if(typeof e=="number"||typeof e=="string")return e}function Qa(e,t){let n=e.availablePaymentMethods;return n&&t.some(l=>n[l])?"ready":"unavailable"}function Za({state:e,placeholderTestId:t,borderRadius:n=8,children:l}){return e==="unavailable"||e==="load_error"?null:(0,i.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,i.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,i.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:l})]})}function Ka(e){return e!=="unavailable"&&e!=="load_error"}function no(e){return(0,i.jsx)(ps,{...e})}function Ha({sessionId:e,nonce:t,email:n,billingApiUrl:l,onTokenizedBody:o,onErrorChange:s,isProcessing:m=!1,onButtonClick:d,onDecline:I,onTechnicalFailure:N,runBeforeButtonClick:P,onLoadStateChange:_,placeholderBorderRadius:k}){let A=un(),p=(0,lt.useStripe)(),v=(0,lt.useElements)(),[x,F]=(0,r.useState)("loading");(0,r.useEffect)(()=>{_?.(x)},[x,_]);let[b,ce]=(0,r.useState)(!1),K=(0,r.useRef)(!1),pe=(0,r.useRef)(null),ae=(0,r.useRef)(null),[z,te]=(0,r.useState)(0),[Q,me]=(0,r.useState)(!1),H=(0,r.useRef)(!1),J=(0,r.useRef)(new Map),{startAttempt:ye,finishAttempt:Me,invalidateAttempt:Se,isAttemptInvalidated:Pe,isAttemptCurrent:ie}=Xa((Z,T,de)=>{N?.(Z,T,{...de,popupBlocked:de?.popupBlocked??zn(T)}),me(!0),te(Oe=>Oe+1)});(0,r.useEffect)(()=>{Q&&ae.current?.focus()},[Q,z]);let ve=(0,r.useCallback)(()=>{te(Z=>Z+1)},[]),Be=(0,r.useCallback)((Z,T,de)=>{Se(de),N?.("paypal",Z,{code:T,popupBlocked:zn(Z)}),me(!0),ve()},[Se,N,ve]),se=(0,r.useCallback)(()=>{window.setTimeout(()=>{(pe.current?.querySelector("iframe")??pe.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{H.current&&(H.current=!1,se())},[se,z]);let Ee=(0,r.useCallback)(()=>{me(!1),s?.(null),se()},[se,s]);(0,r.useEffect)(()=>{if(!p||K.current)return;let Z=new URLSearchParams(window.location.search),T=Z.get("payment_intent"),de=Z.get("payment_intent_client_secret"),Oe=Z.get("redirect_status");if(!T||!de)return;K.current=!0;let ze;try{let E=localStorage.getItem(Er);if(E){let re=JSON.parse(E);re.clientSecret===de&&(ze={...re.accountPatch?{accountPatch:re.accountPatch}:{},...re.sessionId?{sessionId:re.sessionId}:{},...re.nonce?{nonce:re.nonce}:{}})}}catch{}try{localStorage.removeItem(Er)}catch{}let fe=new URL(window.location.href);fe.searchParams.delete("payment_intent"),fe.searchParams.delete("payment_intent_client_secret"),fe.searchParams.delete("redirect_status"),window.history.replaceState({},"",fe.toString()),(async()=>{try{if(ce(!0),Oe==="failed"){let oe="PayPal payment was declined. Please try again.";s?.(oe),I?.(St("paypal",oe));return}let{paymentIntent:E,error:re}=await p.retrievePaymentIntent(de);if(re){s?.(re.message??"Failed to retrieve PayPal payment status.");return}if(E&&(E.status==="requires_capture"||E.status==="succeeded")){let oe=typeof E.payment_method=="string"?E.payment_method:E.payment_method?.id;o({id:oe??E.id,type:"card",threeDSecureActionResultTokenId:E.id,isPaypal:!0},ze)}else{let oe="PayPal payment was not completed. Please try again.";s?.(oe),I?.(St("paypal",oe))}}catch(E){s?.(E instanceof Error?E.message:"Failed to complete PayPal payment.")}finally{ce(!1)}})()},[p,o,s,I]);let _e=(0,r.useCallback)(async Z=>{if(m||b){Z.reject();return}let T=P?await P("paypal"):{proceed:!0};if(!T.proceed){J.current.delete(z),Z.reject();return}let de=ye("paypal");J.current.set(z,{generation:de,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),me(!1),d?.("paypal"),Z.resolve()},[J,m,d,P,ye,b,z]),Re=(0,r.useCallback)(async Z=>{if(!p||!v)return;let T=J.current.get(z);if(T&&!ie(T.generation)){J.current.delete(z);return}if(!T&&Pe()||T&&!Me(T.generation))return;T||Me();let de=T??null;if(J.current.delete(z),!de&&P){let E=await P("paypal");if(!E.proceed){Z.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}de={accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}}let Oe=de?.sessionId??e,ze=de?.nonce??t,fe=de?.accountPatch?.email??n;try{if(ce(!0),s?.(null),!Oe||!fe)throw new Error("Missing sessionId or email for PayPal payment");let E=p.createPaymentMethod,{error:re,paymentMethod:oe}=await E({type:"paypal"});if(re){Be(re,"stripe_paypal_create_payment_method_failed",T?.generation),Z.paymentFailed({reason:"fail"});return}let $e=await new mn.PaymentAPI(l).createSessionIntent(Oe,ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:oe?.id??null,intentKind:"payment"});if($e.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ct=$e.clientSecret,Ve={return_url:window.location.href};if(oe?.id&&(Ve.payment_method=oe.id),typeof window<"u")try{localStorage.setItem(Er,JSON.stringify({clientSecret:ct,sessionId:Oe,nonce:ze,accountPatch:de?.accountPatch}))}catch{}let{error:ot,paymentIntent:q}=await p.confirmPayment({clientSecret:ct,confirmParams:Ve,redirect:"if_required"});if(ot){if(typeof window<"u")try{localStorage.removeItem(Er)}catch{}if(Rr(ot)){let tt=ot.message??"Your payment was declined.";s?.(tt),I?.(St("paypal",tt,{code:Tn(ot),declineCode:lr(ot)})),await to({billingApiUrl:l,sessionId:Oe,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Tn(ot)??"provider_declined"}})}else Be(ot,"stripe_paypal_confirm_failed",T?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Er)}catch{}let G=typeof q?.payment_method=="string"?q.payment_method:q?.payment_method?.id;o({id:G??q?.id,type:"card",threeDSecureActionResultTokenId:q?.id,isPaypal:!0},{accountPatch:de?.accountPatch,sessionId:Oe,nonce:ze});return}catch(E){Be(E,"stripe_paypal_failed",T?.generation)}finally{ce(!1)}},[p,v,e,t,n,l,o,s,I,P,Be,Me,ie,Pe,z]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Za,{state:x,placeholderTestId:"flopay-paypal-placeholder",borderRadius:k,children:(0,i.jsxs)("div",{ref:pe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Q&&(0,i.jsx)("button",{ref:ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ee,style:Ga,children:"Try PayPal again"}),(0,i.jsx)(lt.ExpressCheckoutElement,{onReady:Z=>F(Qa(Z,["paypal"])),onLoadError:()=>{F("load_error"),Fo(Tt(A),"paypal","paypal")},onClick:_e,onConfirm:Re,onCancel:()=>{let Z=J.current.get(z);J.current.delete(z),Tt(A)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Se(Z?.generation),me(!1),H.current=!0,ve()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},z)]})}),b&&(0,i.jsx)(Sn,{status:"processing"})]})}function Wa({sessionId:e,nonce:t,email:n,billingApiUrl:l,intentKind:o,expressMethods:s,onTokenizedBody:m,onErrorChange:d,onButtonClick:I,onDecline:N,onTechnicalFailure:P,runBeforeButtonClick:_,onLoadStateChange:k,placeholderBorderRadius:A}){let p=un(),v=(0,lt.useStripe)(),x=(0,lt.useElements)(),[F,b]=(0,r.useState)("loading");(0,r.useEffect)(()=>{k?.(F)},[F,k]);let[ce,K]=(0,r.useState)(!1),pe=(0,r.useRef)(null),ae=(0,r.useRef)(null),[z,te]=(0,r.useState)(0),[Q,me]=(0,r.useState)(!1),[H,J]=(0,r.useState)("google_pay"),ye=(0,r.useRef)(!1),Me=(0,r.useRef)("google_pay"),Se=(0,r.useRef)("google_pay"),Pe=(0,r.useRef)(new Map),{startAttempt:ie,finishAttempt:ve,invalidateAttempt:Be,isAttemptInvalidated:se,isAttemptCurrent:Ee}=Xa((fe,E,re)=>{P?.(fe,E,{...re,popupBlocked:re?.popupBlocked??zn(E)}),J(fe),me(!0),te(oe=>oe+1)});(0,r.useEffect)(()=>{Q&&ae.current?.focus()},[Q,z]);let _e=(0,r.useCallback)(()=>{te(fe=>fe+1)},[]),Re=(0,r.useCallback)((fe,E,re,oe)=>{Be(oe),P?.(fe,E,{code:re,popupBlocked:zn(E)}),J(fe),me(!0),_e()},[Be,P,_e]),Z=(0,r.useCallback)(()=>{window.setTimeout(()=>{(pe.current?.querySelector("iframe")??pe.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{ye.current&&(ye.current=!1,Z())},[Z,z]);let T=(0,r.useCallback)(()=>{me(!1),d?.(null),Z()},[Z,d]),de=(0,r.useCallback)(async fe=>{if(!v||!x)return;let E=Pe.current.get(z);if(E&&!Ee(E.generation)){Pe.current.delete(z);return}if(!E&&se()||E&&!ve(E.generation))return;E||ve();let re=fe.expressPaymentType??E?.method??Me.current,oe=E??null;Pe.current.delete(z);let $e=qa(re);if(!oe&&_){let G=await _($e);if(!G.proceed){fe.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}oe={accountPatch:G.accountPatch,sessionId:G.sessionId,nonce:G.nonce}}let ct=$e,Ve=oe?.sessionId??e,ot=oe?.nonce??t,q=oe?.accountPatch?.email??n;try{K(!0),d?.(null);let{error:G}=await x.submit();if(G){Re(re,G,"stripe_wallet_submit_failed",E?.generation);return}let{error:tt,paymentMethod:Ae}=await v.createPaymentMethod({elements:x});if(tt||!Ae){Re(re,tt??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",E?.generation);return}if(!Ve||!q)throw new Error("Missing sessionId or email for wallet payment");let at=await new mn.PaymentAPI(l).createSessionIntent(Ve,ot??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:re??$e,paymentMethodId:Ae.id,intentKind:o});if(at.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let We=at.clientSecret,{error:Ke,intentId:rn}=(0,Ut.isSetupIntentClientSecret)(We)?await v.confirmCardSetup(We,{payment_method:Ae.id}).then(g=>({error:g.error,intentId:g.setupIntent?.id})):await v.confirmCardPayment(We,{payment_method:Ae.id}).then(g=>({error:g.error,intentId:g.paymentIntent?.id}));if(Ke){if(Rr(Ke)){let g=Ke.message??"Your payment was declined.";d?.(g),N?.(St(ct,g,{code:Tn(Ke),declineCode:lr(Ke)})),await to({billingApiUrl:l,sessionId:Ve,nonce:ot,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:re??$e,providerDeclineReason:Tn(Ke)??"provider_declined"}})}else Re(re,Ke,"stripe_wallet_confirm_failed",E?.generation);return}m({id:Ae.id,type:"card",threeDSecureActionResultTokenId:rn},{accountPatch:oe?.accountPatch,sessionId:Ve,nonce:ot})}catch(G){Re(re,G,"stripe_wallet_failed",E?.generation)}finally{K(!1)}},[v,x,e,t,n,l,o,m,d,N,_,Re,ve,Ee,se,z]),Oe=(0,r.useMemo)(()=>{let fe=["applePay","googlePay","paypal","link","amazonPay","klarna"],E=new Set(["applePay","googlePay"]),re=new Set(s.map(R.stripeExpressMethodToOptionKey)),oe={};for(let $e of fe)re.has($e)?oe[$e]=E.has($e)?"always":"auto":oe[$e]="never";return oe},[s]),ze=(0,r.useMemo)(()=>s.map(R.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Za,{state:F,placeholderTestId:"flopay-wallet-placeholder",borderRadius:A,children:(0,i.jsxs)("div",{ref:pe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Q&&(0,i.jsxs)("button",{ref:ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:T,style:Ga,children:["Try ",Ja(H)," again"]}),(0,i.jsx)(lt.ExpressCheckoutElement,{onReady:fe=>{b(Qa(fe,ze))},onLoadError:fe=>{b("load_error"),Fo(Tt(p),"stripe","wallet")},onClick:async fe=>{Me.current=fe.expressPaymentType,Se.current=qa(fe.expressPaymentType);let E=_?await _(Se.current):{proceed:!0};if(!E.proceed){Pe.current.delete(z),fe.reject();return}let re=ie(fe.expressPaymentType);Pe.current.set(z,{generation:re,method:fe.expressPaymentType,accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}),me(!1),I?.(Se.current),fe.resolve()},onConfirm:de,onCancel:()=>{let fe=Pe.current.get(z);Pe.current.delete(z),Tt(p)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Be(fe?.generation),me(!1),ye.current=!0,_e()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Oe,layout:{maxColumns:1,overflow:"never"}}},z)]})}),ce&&(0,i.jsx)(Sn,{status:"processing"})]})}function us({method:e,themeId:t,submitting:n=!1,disabled:l=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:m,backgroundColor:d,borderColor:I,textColor:N,borderRadius:P,fontFamily:_}){let k=(0,R.resolveStripeMethodBrandVariant)(e,t),A=Ia[e],p=k?.backgroundColor??d??"#ffffff",v=k?.borderColor??I??"#d1d5db",x=k?.textColor??N??"#262833";return(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!l&&m()},disabled:n||l,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:eo,padding:"0 1rem",backgroundColor:p,color:x,border:`1px solid ${v}`,borderRadius:P??8,fontSize:"0.95rem",fontWeight:600,fontFamily:_,cursor:n||l?"not-allowed":"pointer",opacity:l&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,i.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,R.getStripeMethodDisplayName)(e)}\u2026`}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,R.hasVendoredStripeMethodLogo)(e)?8:0},children:[A?(0,i.jsx)("img",{src:A,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):k?.logoSvg?(0,i.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:k.logoSvg}}):null,(0,i.jsx)("span",{children:(0,R.getStripeMethodDisplayName)(e)})]}),s&&(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:x,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,i.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Ao({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:m,onErrorChange:d,onDecline:I,onCancel:N,runBeforeButtonClick:P,onButtonClick:_,isProcessing:k,submitButtonColor:A,submitButtonBorderRadius:p,submitButtonStyle:v,errorText:x}){let F=un(),b=(0,lt.useStripe)(),ce=(0,lt.useElements)(),[K,pe]=(0,r.useState)(!1),ae=(0,r.useRef)(!1),[z,te]=(0,r.useState)(!1),[Q,me]=(0,r.useState)("loading"),H=(0,r.useCallback)(async()=>{if(!b||!ce||k||ae.current||!z)return;ae.current=!0,pe(!0);let J=P?await P("card"):{proceed:!0};if(!J.proceed){ae.current=!1,pe(!1);return}_?.("card");let ye=J.sessionId??t,Me=J.nonce??n,Se=J.accountPatch?.email??l;try{d?.(null);let Pe=await ce.submit();if(Pe.error){d?.(Pe.error.message??"Payment failed.");return}let ie=await b.createPaymentMethod({elements:ce});if(ie.error||!ie.paymentMethod){d?.(ie.error?.message??"Failed to create payment method.");return}let ve=ie.paymentMethod;if(!ye||!Se)throw new Error("Missing sessionId or email for payment.");let Be=ve.type||e,se=await new mn.PaymentAPI(s).createSessionIntent(ye,Me??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Be,paymentMethodId:null,intentKind:"payment"});if(se.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ee=se.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Ee,sessionId:ye,nonce:Me,accountPatch:J.accountPatch,paymentMethodId:ve.id,paymentMethodType:ve.type??e,gateway:"stripe"}))}catch{}let{error:_e,paymentIntent:Re}=await b.confirmPayment({clientSecret:Ee,confirmParams:{return_url:window.location.href,payment_method:ve.id},redirect:"if_required"});if(_e){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let de=_e.message??"Payment failed.";d?.(de),I?.(St("card",de,{code:_e.code})),await to({billingApiUrl:s,sessionId:ye,nonce:Me,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:_e.code??"provider_declined"}});return}let Z=Re?.status;if(!Yr(Z)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let de=Z==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(de),I?.(St("card",de,{code:Z??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let T=typeof Re?.payment_method=="string"?Re.payment_method:Re?.payment_method?.id;m({id:T??ve.id,type:"card",threeDSecureActionResultTokenId:Re?.id,gateway:"stripe",paymentMethodType:ve.type??e},{accountPatch:J.accountPatch,sessionId:ye,nonce:Me})}catch(Pe){d?.(Pe instanceof Error?Pe.message:"Payment failed. Please try again.")}finally{ae.current=!1,pe(!1)}},[b,ce,k,z,P,_,t,n,l,s,e,m,d,I]);return(0,i.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,i.jsx)(lt.PaymentElement,{onReady:()=>me("ready"),onLoadError:()=>{me("load_error"),Fo(Tt(F),"stripe","apm")},onChange:J=>{te(!!J.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...l?{email:l}:{}}}}}),(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{H()},disabled:!z||K||k||Q!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:A,color:"white",border:"none",borderRadius:p,fontSize:"1rem",fontWeight:600,cursor:!z||K||k||Q!=="ready"?"not-allowed":"pointer",opacity:!z||K||k||Q!=="ready"?.5:1,transition:"opacity 120ms ease-out",...v??{}},children:K?"Processing\u2026":`Pay with ${(0,R.getStripeMethodDisplayName)(e)}`}),x&&(0,i.jsx)(ar,{margin:"0.75rem 0 0",children:x})]})}function Ya({sessionId:e,nonce:t,email:n,billingName:l,billingApiUrl:o,paymentElementMethods:s,stripeInstance:m,paymentElementBaseOptions:d,onTokenizedBody:I,onErrorChange:N,onButtonClick:P,onDecline:_,runBeforeButtonClick:k,onLoadStateChange:A,isProcessing:p=!1,submitButtonColor:v="#4A49FF",submitButtonBorderRadius:x=8,submitButtonStyle:F,buttonAppearance:b,themeId:ce,onExpandApm:K,expandedApmMethod:pe}){let[ae,z]=(0,r.useState)(null),[te,Q]=(0,r.useState)(null),me=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&m?A?.("ready"):m||A?.("loading")},[s.length,m,A]);let H=(0,r.useCallback)(async ie=>{if(!m||me.current||p)return;me.current=!0,Q(ie);let ve=k?await k("card"):{proceed:!0};if(!ve.proceed){me.current=!1,Q(null);return}P?.("card");let Be=ve.sessionId??e,se=ve.nonce??t,Ee=ve.accountPatch?.email??n;try{if(N?.(null),!Be||!Ee)throw new Error("Missing sessionId or email for payment.");let _e=await new mn.PaymentAPI(o).createSessionIntent(Be,se??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ie,paymentMethodId:null,intentKind:"payment"});if(_e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Re=_e.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Re,sessionId:Be,nonce:se,accountPatch:ve.accountPatch,paymentMethodType:ie,gateway:"stripe"}))}catch{}let{error:Z,paymentIntent:T}=await m.confirmPayment({clientSecret:Re,confirmParams:{return_url:window.location.href,payment_method_data:{type:ie,billing_details:{name:l&&l.trim().length>=3?l.trim():"FloPay Customer",...Ee?{email:Ee}:{}}}},redirect:"if_required"});if(Z){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=Z.message??"Payment failed.";N?.(ze),_?.(St("card",ze,{code:Z.code})),await to({billingApiUrl:o,sessionId:Be,nonce:se,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ie,providerDeclineReason:Z.code??"provider_declined"}});return}let de=T?.status;if(!Yr(de)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=de==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";N?.(ze),_?.(St("card",ze,{code:de??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let Oe=typeof T?.payment_method=="string"?T.payment_method:T?.payment_method?.id;I({id:Oe??T?.id,type:"card",threeDSecureActionResultTokenId:T?.id,gateway:"stripe",paymentMethodType:ie},{accountPatch:ve.accountPatch,sessionId:Be,nonce:se})}catch(_e){N?.(_e instanceof Error?_e.message:"Payment failed. Please try again.")}finally{me.current=!1,Q(null)}},[m,p,k,P,e,t,n,o,l,I,N,_]),[J,ye]=(0,r.useState)(null),Me=K?pe??null:J,Se=(0,r.useCallback)(ie=>{me.current||p||Me&&Me!==ie||((0,R.needsStripeMethodExplicitConfirm)(ie)?K?K(ie):ye(ie):H(ie))},[Me,p,H,K]),Pe=(0,r.useMemo)(()=>J?{...d,paymentMethodTypes:[J]}:null,[J,d]);return(0,i.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(ie=>{let ve=pe===ie,Be=te===ie,se=te!==null&&te!==ie||pe!=null&&pe!==ie;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(us,{method:ie,themeId:ce,submitting:Be,disabled:se,highlighted:ve,hasNextStep:(0,R.needsStripeMethodExplicitConfirm)(ie),onClick:()=>Se(ie),backgroundColor:b?.backgroundColor,borderColor:b?.borderColor,textColor:b?.textColor,borderRadius:b?.borderRadius,fontFamily:b?.fontFamily}),!K&&J===ie&&Pe&&m&&(0,i.jsx)(lt.Elements,{stripe:m,options:Pe,children:(0,i.jsx)(Ao,{method:ie,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:I,onErrorChange:N,onDecline:_,onCancel:()=>ye(null),runBeforeButtonClick:k,onButtonClick:P,isProcessing:p,submitButtonColor:v,submitButtonBorderRadius:x,submitButtonStyle:F})},ie)]},ie)})})}function ps({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:m,onDecline:d,onTokenizedBody:I,firstName:N,lastName:P,chv:_,className:k,isProcessing:A,error:p,onErrorChange:v,showPayPal:x=!0,showStripe:F=!0,enabledPaymentMethods:b,enabledPaymentMethodCountries:ce,showApplePay:K=!0,showGooglePay:pe=!0,layout:ae="default",theme:z,buttonsTheme:te,buttonsStyles:Q,appearance:me,cardButtonContent:H,cardBackButtonContent:J,cardTitleContent:ye,showSecurityFooter:Me,onButtonClick:Se,onBeforeButtonClick:Pe,enableAVS:ie,cardFieldOrder:ve,cardPreFormSlot:Be,avsLayout:se="row",country:Ee,zip:_e,addressLine1:Re,addressLine2:Z,city:T,state:de,onCountryChange:Oe,onZipChange:ze,avsCheck:fe,checkoutType:E,checkoutLayout:re,totalAmount:oe=0,currency:$e="usd",initialCardOpen:ct=!1,directPaypal:Ve,isSubscription:ot=!1,session:q,dataAttachmentPending:G=!1,debug:tt=!1}){let Ae=un(),at=Kr(),We=(0,r.useContext)(dn),Ke=G||We.claimPending===!0,rn=Wr(),[g,ke]=(0,r.useState)(!1),[dt,nt]=(0,r.useState)(null),[Qe,He]=(0,r.useState)(Ee??"US"),[Ze,xe]=(0,r.useState)(_e??""),[je,wt]=(0,r.useState)(Re??""),[Ge,An]=(0,r.useState)(Z??""),[ht,Fn]=(0,r.useState)(T??""),[on,hn]=(0,r.useState)(de??""),[Zt,Dn]=(0,r.useState)({}),Nt=(0,r.useRef)(_e??""),kt=(0,r.useRef)(Ee??"US"),qt=(0,r.useRef)(Re??""),Gt=(0,r.useRef)(Z??""),Mt=(0,r.useRef)(T??""),jt=(0,r.useRef)(de??""),Bt=(0,r.useRef)({});(0,r.useEffect)(()=>{let a=(C,V,ne,$,be)=>{if(Bt.current[C])return;let Ne=V?.trim();!Ne||Ne===ne.current||(ne.current=Ne,$(Ne),be?.(Ne))};a("country",Ee,kt,He,Oe),a("zip",_e,Nt,xe,ze),a("addressLine1",Re,qt,wt),a("addressLine2",Z,Gt,An),a("city",T,Mt,Fn),a("state",de,jt,hn)},[Ee,_e,Re,Z,T,de,Oe,ze]);let le=(0,r.useMemo)(()=>(0,R.resolveAVSConfig)(ie),[ie]),en=le!==null,D=!!q?.vault?.html,ft=!!q?.gateways?.pcivault,Pt=!!(q?.gateways?.stripe?.enabledPaymentMethods??b)?.includes("card"),Te=D||Pt||ft,qe=!!(F&&Te&&Ae&&e),[$n,Ln]=(0,r.useState)(()=>ae!=="buttons"||ct?e??null:null),[qn,Zn]=(0,r.useState)(0),Vt=ae!=="buttons"||ct||!!e&&$n===e,it=(0,r.useMemo)(()=>!Ae||!qe||!e||!Vt?null:Ae.cardCapture({sessionId:e}),[Ae,qe,e,Vt]),At=(0,r.useMemo)(()=>{let a=Qe,C=le?(0,R.isAVSFieldVisible)(le.postal_code,a):!1;return cs(a,Ze,C)},[le,Qe,Ze]),{avsInvalid:Kt,invalidAvsFields:gt}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!qe||!le)return{avsInvalid:!1,invalidAvsFields:a};let C=Qe,V=(be,Ne)=>(0,R.isAVSFieldVisible)(be,C)&&!Ne.trim(),ne={line1:V(le.address_line_1,je),city:V(le.city,ht),state:V(le.state,on),zip:At.empty||At.malformed};return{avsInvalid:ne.line1||ne.city||ne.state||ne.zip,invalidAvsFields:ne}},[qe,le,Qe,je,ht,on,At]),[Jt,Ht]=(0,r.useState)(!1),[an,Pn]=(0,r.useState)(!1),[Rt,Ot]=(0,r.useState)(()=>Mo(q?.vault)),[Le,bt]=(0,r.useState)(ct&&Te?"card":"buttons"),[vt,bn]=(0,r.useState)(null),jn=Le==="expanding"||Le==="card",Wt=280,Xt=(0,r.useRef)(null),Ft=(0,r.useCallback)(a=>{Xt.current&&clearTimeout(Xt.current),Xt.current=setTimeout(()=>{Xt.current=null,a()},Wt)},[Wt]);(0,r.useEffect)(()=>()=>{Xt.current&&clearTimeout(Xt.current)},[]);let Rn=(0,r.useCallback)(()=>{Ln(e??null),Zn(a=>a+1),bt("expanding"),Ft(()=>bt("card"))},[Ft,e]),Nn=(0,r.useCallback)(()=>{bt("collapsing"),Ft(()=>bt("buttons"))},[Ft]),sn=(0,r.useCallback)(a=>{bn(a),bt("apm-expanding"),Ft(()=>bt("apm-form"))},[Ft]),Qt=(0,r.useCallback)(()=>{bt("apm-collapsing"),Ft(()=>{bt("buttons"),bn(null)})},[Ft]);(0,r.useEffect)(()=>{ae==="buttons"&&ct&&Te&&(Ln(e??null),bt("card"))},[ae,ct,Te,e]);let[It,h]=(0,r.useState)(null),W=(0,r.useRef)(!1),j=(0,r.useRef)(null),ge=(0,r.useRef)("idle"),[X,ue]=(0,r.useState)(null),S=(0,r.useRef)(X);(0,r.useEffect)(()=>{S.current=X},[X]);let u=n||rn,c=p??dt,L=(0,r.useMemo)(()=>(0,Ut.resolveTheme)(z),[z]),y=(0,r.useMemo)(()=>{let a=L?.buttonsLayout??(0,R.resolveButtonsLayoutTheme)(te);return Q?{...a,...Q,cardButton:{...a.cardButton,...Q.cardButton},cardFormContainer:{...a.cardFormContainer,...Q.cardFormContainer},backButton:{...a.backButton,...Q.backButton},backButtonIcon:{...a.backButtonIcon,...Q.backButtonIcon},submitButton:{...a.submitButton,...Q.submitButton},title:{...a.title,...Q.title}}:a},[L,te,Q]),ee=me??L?.appearance,Ie=(0,r.useMemo)(()=>{let a=ee?.variables,C=Ne=>typeof Ne=="string"&&Ne?Ne:void 0,V=y.submitButton,ne=C(a?.colorPrimary)??C(V?.backgroundColor)??"#4A49FF",$=ae==="buttons",be=y.nameInput;return{primaryColor:ne,primaryHoverColor:C(a?.colorPrimaryHover)??Zr(ne,.12),inputBackgroundColor:C(y.cardInputBackground)??C(a?.colorBackground)??"#ffffff",textColor:C(y.cardInputColor)??C(be?.color)??C(a?.colorText)??"#262833",borderColor:C(y.cardInputBorder)??($?"#e5e7eb":"#A4A4FF"),placeholderColor:C(y.cardInputPlaceholderColor)??"#9ca3af",errorColor:C(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:C(be?.fontFamily)??C(a?.fontFamily)??"Poppins, sans-serif",fontSize:C(y.cardInputFontSize)??C(a?.fontSizeBase)??"16px",fontWeight:String(Va(be?.fontWeight)??400),borderRadius:C(a?.borderRadius)??"8px"}},[ee,y,ae]),rt=We.inlineSessionPatchProcessing??!1,Ce=(A??g)||rt,O=u.replace(/\/+$/,""),f=(0,r.useMemo)(()=>_o({userId:o,email:l,firstName:N,lastName:P,country:Ee,zip:_e},Zt),[o,l,N,P,Ee,_e,Zt]),U=[f.firstName,f.lastName].filter(a=>!!a?.trim()).join(" "),Y=(0,r.useMemo)(()=>Ae?Ae.getRawProvider():null,[Ae]),Ye=(0,r.useMemo)(()=>at?at.getRawProvider():null,[at]),Et=oe||100,Dt=(0,r.useMemo)(()=>ee?(0,mn.toStripeAppearance)(ee):null,[ee]),Mr=Dt?{appearance:Dt}:null,Ko=(0,r.useMemo)(()=>{let a=Dt??{},C=a.rules??{};return{...a,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[Dt]),Ho=(0,r.useMemo)(()=>{let a=Aa(oe);return{...a,currency:$e.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...Mr}},[oe,$e,Mr]),Wo=(0,r.useMemo)(()=>({mode:"payment",amount:Et,currency:$e.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Mr}),[Et,$e,Mr]),he=(0,r.useCallback)(a=>{nt(a),v?.(a)},[v]);(0,r.useEffect)(()=>{!qe||!it||it.setCardFieldOrder?.(ve??null,le==null)},[qe,it,ve,le]),(0,r.useEffect)(()=>{(Le==="expanding"||Le==="collapsing"||Le==="apm-expanding"||Le==="apm-collapsing")&&he(null)},[Le,he]);let ln=(0,r.useCallback)((a,C,V)=>{d?.(St(a,C,V))},[d]),er=(0,r.useCallback)((a,C,V)=>{let ne=V?.popupBlocked??zn(C),$=ss(a,ne),be=Gn(V?.code)??Tn(C)??"external_payment_method_failed",Ne=new Ut.FloPayError($,"api_error",{code:"external_payment_method_failed",param:a});h(null),ae==="buttons"&&(bt("buttons"),bn(null)),he($),m?.(Ne),console.error("[FloPay] External payment method failed:",{method:a,code:be,popupBlocked:ne})},[ae,m,he]);(0,r.useEffect)(()=>{if(!qe||!e){Ot(null);return}let a=Mo(q?.vault);if(a){Ot(a);return}if(!Vt){Ot(null);return}Ot(null);let C=!0;return new mn.PaymentAPI(O).getVaultCapture(e,t).then(V=>{if(!C)return;let ne=Mo(V);ne?Ot(ne):he("Failed to load the secure card form.")}).catch(V=>{C&&he(V instanceof Error?V.message:"Failed to load the secure card form.")}),()=>{C=!1}},[qe,Vt,qn,e,q?.vault?.html,q?.vault?.messageToken,q?.vault?.expectedOrigin,O,t,he]);let In=(0,r.useRef)({onComplete:s,onError:m,updateError:he,emitDecline:ln,resolvedAccount:f,avsConfig:le,avsCheckProp:fe,sessionId:e,nonce:t,baseUrl:O});In.current={onComplete:s,onError:m,updateError:he,emitDecline:ln,resolvedAccount:f,avsConfig:le,avsCheckProp:fe,sessionId:e,nonce:t,baseUrl:O};let mo=(0,r.useRef)(!1),gi=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:C,avsCheckProp:V}=In.current,ne=kt.current||a.country||"US",$=C?(0,R.isAVSFieldVisible)(C.state,ne):!1,be=C?(0,R.isAVSFieldVisible)(C.address_line_1,ne):!1,Ne=C?(0,R.isAVSFieldVisible)(C.postal_code,ne):!1,mt=C?(0,R.isAVSFieldVisible)(C.city,ne):!1,Lt=C?(0,R.isAVSFieldVisible)(C.address_line_2,ne):!1,Je=be&&!$&&Ne?(0,R.getStateFromPostalCode)(ne,(Nt.current??"").trim()):null,_t=$?jt.current:Je;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Ne&&Nt.current?{zip:Nt.current}:{},...mt&&Mt.current?{city:Mt.current}:{},..._t?{state:_t}:{},...be&&qt.current?{addressLine1:qt.current}:{},...Lt&&Gt.current?{addressLine2:Gt.current}:{},country:ne},...V!==void 0?{avsCheck:V}:{},...C?{avsConfig:{country:(0,R.isAVSFieldVisible)(C.country,ne),postal_code:Ne,address_line_1:be,address_line_2:Lt,city:mt,state:$}}:{}}},[]),Yo=(0,r.useRef)(Ke);Yo.current=Ke,(0,r.useEffect)(()=>{Ke||c!==$a||In.current.updateError(null)},[Ke,c]),(0,r.useEffect)(()=>{!qe||!it||it.setSubmitGate?.(Kt||Ke)},[qe,it,Kt,Ke]),(0,r.useEffect)(()=>{if(!qe||!it)return;mo.current=!1;let a=!1,C=it.on("submitting",()=>{Ht(!0),j.current&&clearTimeout(j.current),ge.current="validation-window",j.current=setTimeout(()=>{j.current=null,ge.current==="validation-window"&&(ge.current="processing")},ns),h("processing");let{baseUrl:Ne,sessionId:mt,nonce:Lt,updateError:Je,onError:_t}=In.current;!mt||!Lt||new mn.PaymentAPI(Ne).patchAccountSnapshot(mt,Lt,gi(),{telemetryMode:"best_effort"}).catch(Fe=>{if(!rs(Fe))return;let zt=Fe instanceof Error?Fe.message:"Please check your billing address and try again.";Je(zt),ge.current="idle",h(null),_t?.(Fe instanceof Ut.FloPayError?Fe:new Ut.FloPayError(zt,"api_error"))})}),V=it.on("complete",async Ne=>{sr(Ne.sessionId??In.current.sessionId),ge.current="terminal",h("success"),await new Promise(mt=>setTimeout(mt,xn)),!mo.current&&(mo.current=!0,In.current.onComplete?.({status:"succeeded",paymentIntentId:Ne.intentId,checkoutMethod:"card"}))}),ne=it.on("decline",async Ne=>{let{updateError:mt,emitDecline:Lt}=In.current,Je=Ne.message??"Your payment was declined. Please try another card or contact your bank.";ge.current="terminal",mt(Je),h("error"),Lt("card",Je,Ne.declineReason?{declineCode:Ne.declineReason}:void 0),await new Promise(_t=>setTimeout(_t,Cn)),!a&&(ge.current="idle",h(null))}),$=it.on("error",async Ne=>{let{updateError:mt,onError:Lt}=In.current,Je=Ne.message??"There was a problem processing your payment. Please try again.";ge.current="terminal",mt(Je),h("error"),Lt?.(new Ut.FloPayError(Je,"api_error")),await new Promise(_t=>setTimeout(_t,Cn)),!a&&(ge.current="idle",h(null))}),be=it.on("blocked",()=>{if(!Yo.current){Ht(!0);return}In.current.updateError($a)});return()=>{a=!0,j.current&&(clearTimeout(j.current),j.current=null),ge.current="idle",C(),V(),ne(),$(),be()}},[qe,it]);let vn=!!Ve?.clientId,pr=Array.isArray(b),Br=pr&&b.length>0,hi=pr&&b.includes("paypal"),{expressMethods:Ar,paymentElementMethods:mr}=(0,r.useMemo)(()=>(0,R.partitionStripeMethods)(b,{excludePaypal:vn}),[b,vn]),Go=vn||!!at,Pi=(0,r.useMemo)(()=>Go?Ar.filter(a=>a!=="paypal"):Ar,[Ar,Go]),bi=(0,r.useMemo)(()=>{let a=[];return K&&a.push("apple_pay"),pe&&a.push("google_pay"),a},[K,pe]),Fr=pr?Pi:bi,vi=F&&Fr.length>0,yo=en?Qe:Ee,Dr=(0,r.useMemo)(()=>{let a=yo?.trim().toUpperCase();return a?ce?mr.filter(C=>{let V=ce[C];return!V||V.length===0||V.includes(a)}):(0,R.filterStripeMethodsByCountry)(mr,yo):mr},[mr,yo,ce]),fo=(0,r.useMemo)(()=>({mode:"payment",amount:Et,currency:$e.toLowerCase(),paymentMethodCreation:"manual",appearance:Ko}),[Et,$e,Ko]),[Jo,Xo]=(0,r.useState)("loading"),[Qo,Zo]=(0,r.useState)("loading"),[ea,ta]=(0,r.useState)("loading"),[Ci,go]=(0,r.useState)(!1),[na,ho]=(0,r.useState)("loading"),[Lr,Si]=(0,r.useState)();(0,r.useEffect)(()=>{Si(Fa())},[]);let ra=x&&(vn||(pr?hi:Lr===!1)),oa=F&&vi,yr=!Ke&&ra&&vn,aa=na==="retrying"||na==="exhausted",fr=!Ke&&ra&&!!Ye&&(!vn||aa),gr=!Ke&&oa&&!!Y,hr=!Ke&&F&&Br&&Dr.length>0&&!!Y,wi=yr&&!aa?Ci:fr&&Ka(Jo),ki=gr&&Ka(Qo),Ri=hr&&ea!=="load_error",ia=a=>a==="loading"||a==="ready",sa=yr||fr&&ia(Jo)||gr&&ia(Qo)||hr&&ea!=="load_error",Nr=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!Nr.current){if(!F&&!x){Nr.current=!0;let a=new Ut.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");m?.(a),he(a.message)}else if(!F&&x&&!vn&&!Ye){Nr.current=!0;let a=new Ut.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");m?.(a),he(a.message)}else if(Lr!==void 0&&!Ke&&!Te&&!sa){Nr.current=!0;let a=new Ut.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});m?.(a),he(a.message)}}},[F,x,vn,Ye,Lr,Ke,Te,sa,m,he]);let la=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(la.current||!Br)return;let a=[];K!==!0&&a.push("showApplePay"),pe!==!0&&a.push("showGooglePay"),a.length!==0&&(la.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Br,K,pe]);let ca=(0,r.useCallback)((a,C)=>We.applyInlineSessionPatch?We.applyInlineSessionPatch(a).then(V=>({error:null,sessionId:V.sessionId||e,nonce:V.session?.clientSecret||t})).catch(V=>{let ne=ja(C,V);return he(ne.message),m?.(ne),{error:ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[We.applyInlineSessionPatch,t,m,e,he]),cn=(0,r.useCallback)(async a=>{if(!Pe)return{proceed:!0};try{let C=await Pe({method:a,sessionId:e||void 0,createSession:We.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&Dn(ne=>({...ne??{},...C.account}));let V=await ca(C,a);return V.error?{proceed:!1,accountPatch:C.account}:{proceed:!0,accountPatch:C.account,sessionId:V.sessionId,nonce:V.nonce}}return{proceed:!0}}catch(C){let V=ja(a,C);return he(V.message),m?.(V),{proceed:!1}}},[ca,We.inlineSessionDraft,Pe,m,e,he]),da=(0,r.useCallback)(async(a,C)=>{if(W.current)return;W.current=!0,ke(!0),h("processing"),he(null);let V=C?.sessionId??e,ne=C?.nonce??t,$=_o(f,C?.accountPatch),be=C?.completionPaymentMethodId??Gr(a),Ne=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let Lt=await new mn.PaymentAPI(O).processPayment($.userId??"",{sessionId:V,nonce:ne,tokenizedData:Ne,accountData:{userId:$.userId??"",email:$.email??"",firstName:$.firstName??"",lastName:$.lastName??"",...le?(()=>{let Fe=kt.current,zt=(0,R.isAVSFieldVisible)(le.state,Fe),nn=(0,R.isAVSFieldVisible)(le.address_line_1,Fe),Wn=(0,R.isAVSFieldVisible)(le.postal_code,Fe),Yn=nn&&!zt&&Wn?(0,R.getStateFromPostalCode)(Fe,(Nt.current??"").trim()):null,xt=zt?jt.current:Yn;return{country:Fe,...Wn&&Nt.current?{zip:Nt.current}:{},...(0,R.isAVSFieldVisible)(le.city,Fe)&&Mt.current?{city:Mt.current}:{},...xt?{state:xt}:{},...nn&&qt.current?{addressLine1:qt.current}:{},...(0,R.isAVSFieldVisible)(le.address_line_2,Fe)&&Gt.current?{addressLine2:Gt.current}:{}}})():{}},chv:_,avsCheck:fe??!1,checkoutType:E,checkoutLayout:re,avsConfig:le?{country:(0,R.isAVSFieldVisible)(le.country,kt.current),postal_code:(0,R.isAVSFieldVisible)(le.postal_code,kt.current),address_line_1:(0,R.isAVSFieldVisible)(le.address_line_1,kt.current),address_line_2:(0,R.isAVSFieldVisible)(le.address_line_2,kt.current),city:(0,R.isAVSFieldVisible)(le.city,kt.current),state:(0,R.isAVSFieldVisible)(le.state,kt.current)}:void 0});if(Lt.ok){sr(V),h("success"),ue(null),await new Promise(Fe=>setTimeout(Fe,xn)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:be,checkoutMethod:a.isPaypal?"paypal":"card"});return}let Je=await Lt.json().catch(()=>null);if(Je?.type==="paypal_redirect_required"){let Fe=Je.threeDSecureToken,zt=Je.paymentMethodId||a.id||"";if(!Ae||!Fe){h("error"),he("PayPal authorization required but no token provided.");return}try{let nn=at?.getRawProvider();if(!nn){he("PayPal is not available.");return}let Wn={return_url:window.location.href};zt&&(Wn.payment_method=zt);let{error:Yn}=await nn.confirmPayment({clientSecret:Fe,confirmParams:Wn,redirect:"if_required"});if(Yn){h("error");let xt=Yn.message??"PayPal payment failed.";he(xt),ln("paypal",xt,{code:Yn.code})}}catch(nn){h("error"),he(nn instanceof Error?nn.message:"PayPal authorization failed.")}return}if(Je?.type==="paypal_direct_required"){let Fe=Je.orderId;if(!Fe){h("error"),he("PayPal retry required but no order id provided.");return}let zt=S.current?.attempts??0;if(zt>=2){h("error"),he("PayPal payment could not be completed after multiple attempts."),ln("paypal","paypal_direct_required retry limit exceeded");return}go(!1),ho("loading"),ue({orderId:Fe,attempts:zt+1}),h(null);return}h("error");let _t=Je?.message??"Payment failed. Please try again.";he(_t),ln(a.isPaypal?"paypal":"card",_t,{code:Je?.code??Je?.gatewayErrorCode,declineCode:Je?.declineCode??Je?.gatewayDeclineReason}),await new Promise(Fe=>setTimeout(Fe,Cn))}catch(mt){h("error"),he(mt instanceof Error?mt.message:"An unexpected error occurred"),await new Promise(Lt=>setTimeout(Lt,Cn))}finally{ke(!1),h(null),W.current=!1}},[O,e,t,f,U,_,Ae,at,s,m,he,ln]),tn=(0,r.useCallback)((a,C)=>{I?I(a):da(a,C)},[I,da]),ua=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(typeof window>"u"||ua.current)return;let a=new URLSearchParams(window.location.search),C=a.get("payment_intent"),V=a.get("payment_intent_client_secret"),ne=a.get("redirect_status");if(!C||!V)return;let $=_t=>{let Fe=localStorage.getItem(_t);if(!Fe)return null;try{return JSON.parse(Fe)}catch{return localStorage.removeItem(_t),null}},be=$(wn)??$(Ua),Ne;if(be?.clientSecret){if(be.clientSecret!==V)return;Ne={...be.accountPatch?{accountPatch:be.accountPatch}:{},...be.sessionId?{sessionId:be.sessionId}:{},...be.nonce?{nonce:be.nonce}:{}}}else if(be?.sessionId&&be.sessionId!==e)return;ua.current=!0,localStorage.removeItem(wn),localStorage.removeItem(Ua);let mt=new URL(window.location.href);mt.searchParams.delete("payment_intent"),mt.searchParams.delete("payment_intent_client_secret"),mt.searchParams.delete("redirect_status"),window.history.replaceState({},"",mt.toString());let Lt=be?.paymentMethodType??be?.tokenType??"card",Je="card";(async()=>{let _t=Ae?.getRawProvider();if(!_t){let xt="Payment is not available \u2014 please refresh and try again.";he(xt),ln(Je,xt);return}if(ne==="failed"){let xt="Payment was declined. Please try again.";he(xt),ln(Je,xt);return}let{paymentIntent:Fe,error:zt}=await _t.retrievePaymentIntent(V);if(zt){let xt=zt.message??"Failed to retrieve payment status.";he(xt),ln(Je,xt,{code:zt.code});return}let nn=Fe?.status,Wn=Yr(nn);if(!Fe||!Wn){let xt=nn==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";he(xt),ln(Je,xt,{code:nn??"missing_payment_intent"});return}let Yn=typeof Fe.payment_method=="string"?Fe.payment_method:Fe.payment_method?.id;tn({id:Yn??be?.paymentMethodId??be?.tokenId??Fe.id,type:"card",threeDSecureActionResultTokenId:Fe.id,gateway:be?.gateway??"stripe",paymentMethodType:Lt},Ne)})()},[e,tn,Ae,he,ln]);let Po=(0,r.useCallback)(a=>{a.preventDefault()},[]);if(!(Ae!==null))return(0,i.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Pr=ae==="buttons",Yt=ee?.variables,Ii=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),bo=Yt?.colorBackground,Ei=bo&&!Ii.has(bo)?bo:void 0,br=y.cardInputBorder??(Pr?"#e5e7eb":"#A4A4FF"),vo=Yt?.colorDanger??"#dc2626",Vn=a=>Jt&&a?vo:br,Or=(At.malformed||At.empty)&&(an||Jt),_i=Or?vo:Vn(gt.zip),Co=y.cardFormContainer?.backgroundColor??Ei??(Pr?"white":"#EDEDFF"),vr=y.cardInputBackground??Yt?.colorBackground??"white",So=nr(J),pa=nr(ye),tr=y.nameInput,ma=y.cardInputFontSize??ds(tr?.fontSize)??Yt?.fontSizeBase??"16px",ya=typeof tr?.fontFamily=="string"?tr.fontFamily:Yt?.fontFamily??"Poppins, sans-serif",fa=Va(tr?.fontWeight)??400,xi=y.cardInputColor??(typeof tr?.color=="string"?tr.color:void 0)??Yt?.colorText??"#262833",Ti=y.cardInputPlaceholderColor??"#9ca3af",pt=Yt?.borderRadius??"8px",Kn=Yt?.borderRadius??y.cardButton?.borderRadius??pt,Hn=Yt?.colorPrimary??"#4A49FF",Mi=Yt?.colorPrimaryHover??Zr(Hn,.12),wo=Yt?.colorText??"#262833",ga={fontSize:ma,fontFamily:ya,fontWeight:fa,color:xi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Bi={"--flopay-input-placeholder-color":Ti,"--flopay-input-font-size":ma,"--flopay-input-font-family":ya,"--flopay-input-font-weight":String(fa)},Cr=y.cardFormContainer??{},ko=Cr.padding??(Pr?"0":"1rem"),Ro=Cr.borderRadius??pt,Ai=it&&Rt?(0,i.jsx)(Vr,{capture:it,html:Rt.html,messageToken:Rt.messageToken,expectedOrigin:Rt.expectedOrigin,theme:Ie,onReady:()=>{if(!le||typeof document>"u")return;let a=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};a();let C=0,V=window.setInterval(()=>{C+=1;let ne=document.activeElement;!!ne&&ne.tagName==="IFRAME"&&ne.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(V)):C>=50&&window.clearInterval(V)},100)},onError:a=>he(a),onValidation:a=>{let C=ge.current;(C==="idle"||C==="validation-window")&&(he(a),a&&ge.current==="validation-window"&&(j.current&&(clearTimeout(j.current),j.current=null),ge.current="idle",h(null)))}}):(0,i.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),ha=(0,i.jsxs)("div",{style:{backgroundColor:Co,borderRadius:Ro,...Cr,padding:ko,...Bi,display:"flex",flexDirection:"column"},children:[(0,i.jsx)("style",{children:`
30
+ `,eo=44;function Do(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 is={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Ga={width:"100%",minHeight:eo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function ss(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function qa(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ja(e){return e==="paypal"?"PayPal":(0,R.getStripeMethodDisplayName)(e)}function ls(e,t){let n=`We couldn't open ${Ja(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Xa(e){let t=(0,r.useRef)(0),n=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useCallback)((p=l.current)=>{let v=p;v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),s=(0,r.useCallback)((p,v)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(p),p.timer=setTimeout(()=>{p.timer=null,l.current?.generation===p.generation&&(l.current=null,n.current=p.generation,e(p.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},v))},[o,e]),m=(0,r.useCallback)(p=>{p.yieldedControl&&s(p,600)},[s]),d=(0,r.useCallback)(p=>{o();let v=t.current+1;t.current=v,n.current=null;let x={generation:v,method:p,timer:null,yieldedControl:!1};return l.current=x,v},[o]),I=(0,r.useCallback)(p=>{let v=l.current;return typeof p=="number"&&v?.generation!==p?!1:(o(v),l.current=null,(typeof p!="number"||n.current===p)&&(n.current=null),!0)},[o]),N=(0,r.useCallback)(p=>{let v=l.current,x=p??v?.generation??t.current;(!p||v?.generation===p)&&(o(v),l.current=null),n.current=x},[o]),P=(0,r.useCallback)(p=>n.current===(p??t.current),[]),_=(0,r.useCallback)(p=>l.current?.generation===p&&n.current!==p,[]),k=(0,r.useCallback)(()=>{let p=l.current;p&&m(p)},[m]),A=(0,r.useCallback)(()=>{let p=l.current;p&&(p.yieldedControl=!0,o(p))},[o]);return(0,r.useEffect)(()=>{let p=()=>{document.visibilityState==="visible"?k():A()},v=()=>{A()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",v),window.addEventListener("focus",k),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",v),window.removeEventListener("focus",k),o()}},[o,A,k]),{startAttempt:d,finishAttempt:I,invalidateAttempt:N,isAttemptInvalidated:P,isAttemptCurrent:_}}function cs(e){let t=(0,R.getPostalCodeExample)(e);return`Enter a valid ${(0,R.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function ds(e,t,n){let l=(0,R.isPostalCodeSupported)(e),o=t.trim(),s=n&&l,m=s&&!o,d=s&&!!o&&!(0,R.isValidPostalCode)(e,o);return{visible:n,supported:l,required:s,empty:m,malformed:d}}function ja(e,t){return t instanceof Ut.FloPayError?t:new Ut.FloPayError(t instanceof Error?t.message:`${ss(e)} before-click hook failed.`,"validation_error")}function Bo(){return(0,i.jsx)("style",{children:as})}function us(e){return typeof e=="number"?`${e}px`:e}function Va(e){if(typeof e=="number"||typeof e=="string")return e}function Qa(e,t){let n=e.availablePaymentMethods;return n&&t.some(l=>n[l])?"ready":"unavailable"}function Za({state:e,placeholderTestId:t,borderRadius:n=8,children:l}){return e==="unavailable"||e==="load_error"?null:(0,i.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,i.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,i.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:l})]})}function Ka(e){return e!=="unavailable"&&e!=="load_error"}function no(e){return(0,i.jsx)(ms,{...e})}function Ha({sessionId:e,nonce:t,email:n,billingApiUrl:l,onTokenizedBody:o,onErrorChange:s,isProcessing:m=!1,onButtonClick:d,onDecline:I,onTechnicalFailure:N,runBeforeButtonClick:P,onLoadStateChange:_,placeholderBorderRadius:k}){let A=un(),p=(0,lt.useStripe)(),v=(0,lt.useElements)(),[x,F]=(0,r.useState)("loading");(0,r.useEffect)(()=>{_?.(x)},[x,_]);let[b,ce]=(0,r.useState)(!1),K=(0,r.useRef)(!1),pe=(0,r.useRef)(null),ae=(0,r.useRef)(null),[z,te]=(0,r.useState)(0),[Q,me]=(0,r.useState)(!1),H=(0,r.useRef)(!1),J=(0,r.useRef)(new Map),{startAttempt:ye,finishAttempt:Me,invalidateAttempt:Se,isAttemptInvalidated:Pe,isAttemptCurrent:ie}=Xa((Z,T,de)=>{N?.(Z,T,{...de,popupBlocked:de?.popupBlocked??zn(T)}),me(!0),te(Oe=>Oe+1)});(0,r.useEffect)(()=>{Q&&ae.current?.focus()},[Q,z]);let ve=(0,r.useCallback)(()=>{te(Z=>Z+1)},[]),Be=(0,r.useCallback)((Z,T,de)=>{Se(de),N?.("paypal",Z,{code:T,popupBlocked:zn(Z)}),me(!0),ve()},[Se,N,ve]),se=(0,r.useCallback)(()=>{window.setTimeout(()=>{(pe.current?.querySelector("iframe")??pe.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{H.current&&(H.current=!1,se())},[se,z]);let Ee=(0,r.useCallback)(()=>{me(!1),s?.(null),se()},[se,s]);(0,r.useEffect)(()=>{if(!p||K.current)return;let Z=new URLSearchParams(window.location.search),T=Z.get("payment_intent"),de=Z.get("payment_intent_client_secret"),Oe=Z.get("redirect_status");if(!T||!de)return;K.current=!0;let ze;try{let E=localStorage.getItem(Er);if(E){let re=JSON.parse(E);re.clientSecret===de&&(ze={...re.accountPatch?{accountPatch:re.accountPatch}:{},...re.sessionId?{sessionId:re.sessionId}:{},...re.nonce?{nonce:re.nonce}:{}})}}catch{}try{localStorage.removeItem(Er)}catch{}let fe=new URL(window.location.href);fe.searchParams.delete("payment_intent"),fe.searchParams.delete("payment_intent_client_secret"),fe.searchParams.delete("redirect_status"),window.history.replaceState({},"",fe.toString()),(async()=>{try{if(ce(!0),Oe==="failed"){let oe="PayPal payment was declined. Please try again.";s?.(oe),I?.(St("paypal",oe));return}let{paymentIntent:E,error:re}=await p.retrievePaymentIntent(de);if(re){s?.(re.message??"Failed to retrieve PayPal payment status.");return}if(E&&(E.status==="requires_capture"||E.status==="succeeded")){let oe=typeof E.payment_method=="string"?E.payment_method:E.payment_method?.id;o({id:oe??E.id,type:"card",threeDSecureActionResultTokenId:E.id,isPaypal:!0},ze)}else{let oe="PayPal payment was not completed. Please try again.";s?.(oe),I?.(St("paypal",oe))}}catch(E){s?.(E instanceof Error?E.message:"Failed to complete PayPal payment.")}finally{ce(!1)}})()},[p,o,s,I]);let _e=(0,r.useCallback)(async Z=>{if(m||b){Z.reject();return}let T=P?await P("paypal"):{proceed:!0};if(!T.proceed){J.current.delete(z),Z.reject();return}let de=ye("paypal");J.current.set(z,{generation:de,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),me(!1),d?.("paypal"),Z.resolve()},[J,m,d,P,ye,b,z]),Re=(0,r.useCallback)(async Z=>{if(!p||!v)return;let T=J.current.get(z);if(T&&!ie(T.generation)){J.current.delete(z);return}if(!T&&Pe()||T&&!Me(T.generation))return;T||Me();let de=T??null;if(J.current.delete(z),!de&&P){let E=await P("paypal");if(!E.proceed){Z.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}de={accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}}let Oe=de?.sessionId??e,ze=de?.nonce??t,fe=de?.accountPatch?.email??n;try{if(ce(!0),s?.(null),!Oe||!fe)throw new Error("Missing sessionId or email for PayPal payment");let E=p.createPaymentMethod,{error:re,paymentMethod:oe}=await E({type:"paypal"});if(re){Be(re,"stripe_paypal_create_payment_method_failed",T?.generation),Z.paymentFailed({reason:"fail"});return}let $e=await new mn.PaymentAPI(l).createSessionIntent(Oe,ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:oe?.id??null,intentKind:"payment"});if($e.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ct=$e.clientSecret,Ve={return_url:window.location.href};if(oe?.id&&(Ve.payment_method=oe.id),typeof window<"u")try{localStorage.setItem(Er,JSON.stringify({clientSecret:ct,sessionId:Oe,nonce:ze,accountPatch:de?.accountPatch}))}catch{}let{error:ot,paymentIntent:q}=await p.confirmPayment({clientSecret:ct,confirmParams:Ve,redirect:"if_required"});if(ot){if(typeof window<"u")try{localStorage.removeItem(Er)}catch{}if(Rr(ot)){let tt=ot.message??"Your payment was declined.";s?.(tt),I?.(St("paypal",tt,{code:Tn(ot),declineCode:lr(ot)})),await to({billingApiUrl:l,sessionId:Oe,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Tn(ot)??"provider_declined"}})}else Be(ot,"stripe_paypal_confirm_failed",T?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Er)}catch{}let G=typeof q?.payment_method=="string"?q.payment_method:q?.payment_method?.id;o({id:G??q?.id,type:"card",threeDSecureActionResultTokenId:q?.id,isPaypal:!0},{accountPatch:de?.accountPatch,sessionId:Oe,nonce:ze});return}catch(E){Be(E,"stripe_paypal_failed",T?.generation)}finally{ce(!1)}},[p,v,e,t,n,l,o,s,I,P,Be,Me,ie,Pe,z]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Za,{state:x,placeholderTestId:"flopay-paypal-placeholder",borderRadius:k,children:(0,i.jsxs)("div",{ref:pe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Q&&(0,i.jsx)("button",{ref:ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ee,style:Ga,children:"Try PayPal again"}),(0,i.jsx)(lt.ExpressCheckoutElement,{onReady:Z=>F(Qa(Z,["paypal"])),onLoadError:()=>{F("load_error"),Fo(Tt(A),"paypal","paypal")},onClick:_e,onConfirm:Re,onCancel:()=>{let Z=J.current.get(z);J.current.delete(z),Tt(A)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Se(Z?.generation),me(!1),H.current=!0,ve()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},z)]})}),b&&(0,i.jsx)(Sn,{status:"processing"})]})}function Wa({sessionId:e,nonce:t,email:n,billingApiUrl:l,intentKind:o,expressMethods:s,onTokenizedBody:m,onErrorChange:d,onButtonClick:I,onDecline:N,onTechnicalFailure:P,runBeforeButtonClick:_,onLoadStateChange:k,placeholderBorderRadius:A}){let p=un(),v=(0,lt.useStripe)(),x=(0,lt.useElements)(),[F,b]=(0,r.useState)("loading");(0,r.useEffect)(()=>{k?.(F)},[F,k]);let[ce,K]=(0,r.useState)(!1),pe=(0,r.useRef)(null),ae=(0,r.useRef)(null),[z,te]=(0,r.useState)(0),[Q,me]=(0,r.useState)(!1),[H,J]=(0,r.useState)("google_pay"),ye=(0,r.useRef)(!1),Me=(0,r.useRef)("google_pay"),Se=(0,r.useRef)("google_pay"),Pe=(0,r.useRef)(new Map),{startAttempt:ie,finishAttempt:ve,invalidateAttempt:Be,isAttemptInvalidated:se,isAttemptCurrent:Ee}=Xa((fe,E,re)=>{P?.(fe,E,{...re,popupBlocked:re?.popupBlocked??zn(E)}),J(fe),me(!0),te(oe=>oe+1)});(0,r.useEffect)(()=>{Q&&ae.current?.focus()},[Q,z]);let _e=(0,r.useCallback)(()=>{te(fe=>fe+1)},[]),Re=(0,r.useCallback)((fe,E,re,oe)=>{Be(oe),P?.(fe,E,{code:re,popupBlocked:zn(E)}),J(fe),me(!0),_e()},[Be,P,_e]),Z=(0,r.useCallback)(()=>{window.setTimeout(()=>{(pe.current?.querySelector("iframe")??pe.current)?.focus()},0)},[]);(0,r.useEffect)(()=>{ye.current&&(ye.current=!1,Z())},[Z,z]);let T=(0,r.useCallback)(()=>{me(!1),d?.(null),Z()},[Z,d]),de=(0,r.useCallback)(async fe=>{if(!v||!x)return;let E=Pe.current.get(z);if(E&&!Ee(E.generation)){Pe.current.delete(z);return}if(!E&&se()||E&&!ve(E.generation))return;E||ve();let re=fe.expressPaymentType??E?.method??Me.current,oe=E??null;Pe.current.delete(z);let $e=qa(re);if(!oe&&_){let G=await _($e);if(!G.proceed){fe.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}oe={accountPatch:G.accountPatch,sessionId:G.sessionId,nonce:G.nonce}}let ct=$e,Ve=oe?.sessionId??e,ot=oe?.nonce??t,q=oe?.accountPatch?.email??n;try{K(!0),d?.(null);let{error:G}=await x.submit();if(G){Re(re,G,"stripe_wallet_submit_failed",E?.generation);return}let{error:tt,paymentMethod:Ae}=await v.createPaymentMethod({elements:x});if(tt||!Ae){Re(re,tt??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",E?.generation);return}if(!Ve||!q)throw new Error("Missing sessionId or email for wallet payment");let at=await new mn.PaymentAPI(l).createSessionIntent(Ve,ot??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:re??$e,paymentMethodId:Ae.id,intentKind:o});if(at.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let We=at.clientSecret,{error:Ke,intentId:rn}=(0,Ut.isSetupIntentClientSecret)(We)?await v.confirmCardSetup(We,{payment_method:Ae.id}).then(g=>({error:g.error,intentId:g.setupIntent?.id})):await v.confirmCardPayment(We,{payment_method:Ae.id}).then(g=>({error:g.error,intentId:g.paymentIntent?.id}));if(Ke){if(Rr(Ke)){let g=Ke.message??"Your payment was declined.";d?.(g),N?.(St(ct,g,{code:Tn(Ke),declineCode:lr(Ke)})),await to({billingApiUrl:l,sessionId:Ve,nonce:ot,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:re??$e,providerDeclineReason:Tn(Ke)??"provider_declined"}})}else Re(re,Ke,"stripe_wallet_confirm_failed",E?.generation);return}m({id:Ae.id,type:"card",threeDSecureActionResultTokenId:rn},{accountPatch:oe?.accountPatch,sessionId:Ve,nonce:ot})}catch(G){Re(re,G,"stripe_wallet_failed",E?.generation)}finally{K(!1)}},[v,x,e,t,n,l,o,m,d,N,_,Re,ve,Ee,se,z]),Oe=(0,r.useMemo)(()=>{let fe=["applePay","googlePay","paypal","link","amazonPay","klarna"],E=new Set(["applePay","googlePay"]),re=new Set(s.map(R.stripeExpressMethodToOptionKey)),oe={};for(let $e of fe)re.has($e)?oe[$e]=E.has($e)?"always":"auto":oe[$e]="never";return oe},[s]),ze=(0,r.useMemo)(()=>s.map(R.stripeExpressMethodToOptionKey),[s]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Za,{state:F,placeholderTestId:"flopay-wallet-placeholder",borderRadius:A,children:(0,i.jsxs)("div",{ref:pe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Q&&(0,i.jsxs)("button",{ref:ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:T,style:Ga,children:["Try ",Ja(H)," again"]}),(0,i.jsx)(lt.ExpressCheckoutElement,{onReady:fe=>{b(Qa(fe,ze))},onLoadError:fe=>{b("load_error"),Fo(Tt(p),"stripe","wallet")},onClick:async fe=>{Me.current=fe.expressPaymentType,Se.current=qa(fe.expressPaymentType);let E=_?await _(Se.current):{proceed:!0};if(!E.proceed){Pe.current.delete(z),fe.reject();return}let re=ie(fe.expressPaymentType);Pe.current.set(z,{generation:re,method:fe.expressPaymentType,accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}),me(!1),I?.(Se.current),fe.resolve()},onConfirm:de,onCancel:()=>{let fe=Pe.current.get(z);Pe.current.delete(z),Tt(p)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Be(fe?.generation),me(!1),ye.current=!0,_e()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Oe,layout:{maxColumns:1,overflow:"never"}}},z)]})}),ce&&(0,i.jsx)(Sn,{status:"processing"})]})}function ps({method:e,themeId:t,submitting:n=!1,disabled:l=!1,highlighted:o=!1,hasNextStep:s=!1,onClick:m,backgroundColor:d,borderColor:I,textColor:N,borderRadius:P,fontFamily:_}){let k=(0,R.resolveStripeMethodBrandVariant)(e,t),A=Ia[e],p=k?.backgroundColor??d??"#ffffff",v=k?.borderColor??I??"#d1d5db",x=k?.textColor??N??"#262833";return(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!l&&m()},disabled:n||l,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:eo,padding:"0 1rem",backgroundColor:p,color:x,border:`1px solid ${v}`,borderRadius:P??8,fontSize:"0.95rem",fontWeight:600,fontFamily:_,cursor:n||l?"not-allowed":"pointer",opacity:l&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,i.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,R.getStripeMethodDisplayName)(e)}\u2026`}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,R.hasVendoredStripeMethodLogo)(e)?8:0},children:[A?(0,i.jsx)("img",{src:A,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):k?.logoSvg?(0,i.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:k.logoSvg}}):null,(0,i.jsx)("span",{children:(0,R.getStripeMethodDisplayName)(e)})]}),s&&(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:x,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,i.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Ao({method:e,sessionId:t,nonce:n,email:l,billingName:o,billingApiUrl:s,onTokenizedBody:m,onErrorChange:d,onDecline:I,onCancel:N,runBeforeButtonClick:P,onButtonClick:_,isProcessing:k,submitButtonColor:A,submitButtonBorderRadius:p,submitButtonStyle:v,errorText:x}){let F=un(),b=(0,lt.useStripe)(),ce=(0,lt.useElements)(),[K,pe]=(0,r.useState)(!1),ae=(0,r.useRef)(!1),[z,te]=(0,r.useState)(!1),[Q,me]=(0,r.useState)("loading"),H=(0,r.useCallback)(async()=>{if(!b||!ce||k||ae.current||!z)return;ae.current=!0,pe(!0);let J=P?await P("card"):{proceed:!0};if(!J.proceed){ae.current=!1,pe(!1);return}_?.("card");let ye=J.sessionId??t,Me=J.nonce??n,Se=J.accountPatch?.email??l;try{d?.(null);let Pe=await ce.submit();if(Pe.error){d?.(Pe.error.message??"Payment failed.");return}let ie=await b.createPaymentMethod({elements:ce});if(ie.error||!ie.paymentMethod){d?.(ie.error?.message??"Failed to create payment method.");return}let ve=ie.paymentMethod;if(!ye||!Se)throw new Error("Missing sessionId or email for payment.");let Be=ve.type||e,se=await new mn.PaymentAPI(s).createSessionIntent(ye,Me??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Be,paymentMethodId:null,intentKind:"payment"});if(se.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ee=se.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Ee,sessionId:ye,nonce:Me,accountPatch:J.accountPatch,paymentMethodId:ve.id,paymentMethodType:ve.type??e,gateway:"stripe"}))}catch{}let{error:_e,paymentIntent:Re}=await b.confirmPayment({clientSecret:Ee,confirmParams:{return_url:window.location.href,payment_method:ve.id},redirect:"if_required"});if(_e){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let de=_e.message??"Payment failed.";d?.(de),I?.(St("card",de,{code:_e.code})),await to({billingApiUrl:s,sessionId:ye,nonce:Me,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:_e.code??"provider_declined"}});return}let Z=Re?.status;if(!Yr(Z)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let de=Z==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(de),I?.(St("card",de,{code:Z??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let T=typeof Re?.payment_method=="string"?Re.payment_method:Re?.payment_method?.id;m({id:T??ve.id,type:"card",threeDSecureActionResultTokenId:Re?.id,gateway:"stripe",paymentMethodType:ve.type??e},{accountPatch:J.accountPatch,sessionId:ye,nonce:Me})}catch(Pe){d?.(Pe instanceof Error?Pe.message:"Payment failed. Please try again.")}finally{ae.current=!1,pe(!1)}},[b,ce,k,z,P,_,t,n,l,s,e,m,d,I]);return(0,i.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,i.jsx)(lt.PaymentElement,{onReady:()=>me("ready"),onLoadError:()=>{me("load_error"),Fo(Tt(F),"stripe","apm")},onChange:J=>{te(!!J.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...l?{email:l}:{}}}}}),(0,i.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{H()},disabled:!z||K||k||Q!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:A,color:"white",border:"none",borderRadius:p,fontSize:"1rem",fontWeight:600,cursor:!z||K||k||Q!=="ready"?"not-allowed":"pointer",opacity:!z||K||k||Q!=="ready"?.5:1,transition:"opacity 120ms ease-out",...v??{}},children:K?"Processing\u2026":`Pay with ${(0,R.getStripeMethodDisplayName)(e)}`}),x&&(0,i.jsx)(ar,{margin:"0.75rem 0 0",children:x})]})}function Ya({sessionId:e,nonce:t,email:n,billingName:l,billingApiUrl:o,paymentElementMethods:s,stripeInstance:m,paymentElementBaseOptions:d,onTokenizedBody:I,onErrorChange:N,onButtonClick:P,onDecline:_,runBeforeButtonClick:k,onLoadStateChange:A,isProcessing:p=!1,submitButtonColor:v="#4A49FF",submitButtonBorderRadius:x=8,submitButtonStyle:F,buttonAppearance:b,themeId:ce,onExpandApm:K,expandedApmMethod:pe}){let[ae,z]=(0,r.useState)(null),[te,Q]=(0,r.useState)(null),me=(0,r.useRef)(!1);(0,r.useEffect)(()=>{s.length>0&&m?A?.("ready"):m||A?.("loading")},[s.length,m,A]);let H=(0,r.useCallback)(async ie=>{if(!m||me.current||p)return;me.current=!0,Q(ie);let ve=k?await k("card"):{proceed:!0};if(!ve.proceed){me.current=!1,Q(null);return}P?.("card");let Be=ve.sessionId??e,se=ve.nonce??t,Ee=ve.accountPatch?.email??n;try{if(N?.(null),!Be||!Ee)throw new Error("Missing sessionId or email for payment.");let _e=await new mn.PaymentAPI(o).createSessionIntent(Be,se??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ie,paymentMethodId:null,intentKind:"payment"});if(_e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Re=_e.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Re,sessionId:Be,nonce:se,accountPatch:ve.accountPatch,paymentMethodType:ie,gateway:"stripe"}))}catch{}let{error:Z,paymentIntent:T}=await m.confirmPayment({clientSecret:Re,confirmParams:{return_url:window.location.href,payment_method_data:{type:ie,billing_details:{name:l&&l.trim().length>=3?l.trim():"FloPay Customer",...Ee?{email:Ee}:{}}}},redirect:"if_required"});if(Z){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=Z.message??"Payment failed.";N?.(ze),_?.(St("card",ze,{code:Z.code})),await to({billingApiUrl:o,sessionId:Be,nonce:se,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ie,providerDeclineReason:Z.code??"provider_declined"}});return}let de=T?.status;if(!Yr(de)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ze=de==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";N?.(ze),_?.(St("card",ze,{code:de??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let Oe=typeof T?.payment_method=="string"?T.payment_method:T?.payment_method?.id;I({id:Oe??T?.id,type:"card",threeDSecureActionResultTokenId:T?.id,gateway:"stripe",paymentMethodType:ie},{accountPatch:ve.accountPatch,sessionId:Be,nonce:se})}catch(_e){N?.(_e instanceof Error?_e.message:"Payment failed. Please try again.")}finally{me.current=!1,Q(null)}},[m,p,k,P,e,t,n,o,l,I,N,_]),[J,ye]=(0,r.useState)(null),Me=K?pe??null:J,Se=(0,r.useCallback)(ie=>{me.current||p||Me&&Me!==ie||((0,R.needsStripeMethodExplicitConfirm)(ie)?K?K(ie):ye(ie):H(ie))},[Me,p,H,K]),Pe=(0,r.useMemo)(()=>J?{...d,paymentMethodTypes:[J]}:null,[J,d]);return(0,i.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:s.map(ie=>{let ve=pe===ie,Be=te===ie,se=te!==null&&te!==ie||pe!=null&&pe!==ie;return(0,i.jsxs)(r.default.Fragment,{children:[(0,i.jsx)(ps,{method:ie,themeId:ce,submitting:Be,disabled:se,highlighted:ve,hasNextStep:(0,R.needsStripeMethodExplicitConfirm)(ie),onClick:()=>Se(ie),backgroundColor:b?.backgroundColor,borderColor:b?.borderColor,textColor:b?.textColor,borderRadius:b?.borderRadius,fontFamily:b?.fontFamily}),!K&&J===ie&&Pe&&m&&(0,i.jsx)(lt.Elements,{stripe:m,options:Pe,children:(0,i.jsx)(Ao,{method:ie,sessionId:e,email:n,billingName:l,billingApiUrl:o,onTokenizedBody:I,onErrorChange:N,onDecline:_,onCancel:()=>ye(null),runBeforeButtonClick:k,onButtonClick:P,isProcessing:p,submitButtonColor:v,submitButtonBorderRadius:x,submitButtonStyle:F})},ie)]},ie)})})}function ms({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,onComplete:s,onError:m,onDecline:d,onTokenizedBody:I,firstName:N,lastName:P,chv:_,className:k,isProcessing:A,error:p,onErrorChange:v,showPayPal:x=!0,showStripe:F=!0,enabledPaymentMethods:b,enabledPaymentMethodCountries:ce,showApplePay:K=!0,showGooglePay:pe=!0,layout:ae="default",theme:z,buttonsTheme:te,buttonsStyles:Q,appearance:me,cardButtonContent:H,cardBackButtonContent:J,cardTitleContent:ye,showSecurityFooter:Me,onButtonClick:Se,onBeforeButtonClick:Pe,enableAVS:ie,cardFieldOrder:ve,cardPreFormSlot:Be,avsLayout:se="row",country:Ee,zip:_e,addressLine1:Re,addressLine2:Z,city:T,state:de,onCountryChange:Oe,onZipChange:ze,avsCheck:fe,checkoutType:E,checkoutLayout:re,totalAmount:oe=0,currency:$e="usd",initialCardOpen:ct=!1,directPaypal:Ve,isSubscription:ot=!1,session:q,dataAttachmentPending:G=!1,debug:tt=!1}){let Ae=un(),at=Kr(),We=(0,r.useContext)(dn),Ke=G||We.claimPending===!0,rn=Wr(),[g,ke]=(0,r.useState)(!1),[dt,nt]=(0,r.useState)(null),[Qe,He]=(0,r.useState)(Ee??"US"),[Ze,xe]=(0,r.useState)(_e??""),[je,wt]=(0,r.useState)(Re??""),[Ge,An]=(0,r.useState)(Z??""),[ht,Fn]=(0,r.useState)(T??""),[on,hn]=(0,r.useState)(de??""),[Zt,Dn]=(0,r.useState)({}),Nt=(0,r.useRef)(_e??""),kt=(0,r.useRef)(Ee??"US"),qt=(0,r.useRef)(Re??""),Gt=(0,r.useRef)(Z??""),Mt=(0,r.useRef)(T??""),jt=(0,r.useRef)(de??""),Bt=(0,r.useRef)({});(0,r.useEffect)(()=>{let a=(C,V,ne,$,be)=>{if(Bt.current[C])return;let Ne=V?.trim();!Ne||Ne===ne.current||(ne.current=Ne,$(Ne),be?.(Ne))};a("country",Ee,kt,He,Oe),a("zip",_e,Nt,xe,ze),a("addressLine1",Re,qt,wt),a("addressLine2",Z,Gt,An),a("city",T,Mt,Fn),a("state",de,jt,hn)},[Ee,_e,Re,Z,T,de,Oe,ze]);let le=(0,r.useMemo)(()=>(0,R.resolveAVSConfig)(ie),[ie]),en=le!==null,D=!!q?.vault?.html,ft=!!q?.gateways?.pcivault,Pt=!!(q?.gateways?.stripe?.enabledPaymentMethods??b)?.includes("card"),Te=D||Pt||ft,qe=!!(F&&Te&&Ae&&e),[$n,Ln]=(0,r.useState)(()=>ae!=="buttons"||ct?e??null:null),[qn,Zn]=(0,r.useState)(0),Vt=ae!=="buttons"||ct||!!e&&$n===e,it=(0,r.useMemo)(()=>!Ae||!qe||!e||!Vt?null:Ae.cardCapture({sessionId:e}),[Ae,qe,e,Vt]),At=(0,r.useMemo)(()=>{let a=Qe,C=le?(0,R.isAVSFieldVisible)(le.postal_code,a):!1;return ds(a,Ze,C)},[le,Qe,Ze]),{avsInvalid:Kt,invalidAvsFields:gt}=(0,r.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!qe||!le)return{avsInvalid:!1,invalidAvsFields:a};let C=Qe,V=(be,Ne)=>(0,R.isAVSFieldVisible)(be,C)&&!Ne.trim(),ne={line1:V(le.address_line_1,je),city:V(le.city,ht),state:V(le.state,on),zip:At.empty||At.malformed};return{avsInvalid:ne.line1||ne.city||ne.state||ne.zip,invalidAvsFields:ne}},[qe,le,Qe,je,ht,on,At]),[Jt,Ht]=(0,r.useState)(!1),[an,Pn]=(0,r.useState)(!1),[Rt,Ot]=(0,r.useState)(()=>Mo(q?.vault)),[Le,bt]=(0,r.useState)(ct&&Te?"card":"buttons"),[vt,bn]=(0,r.useState)(null),jn=Le==="expanding"||Le==="card",Wt=280,Xt=(0,r.useRef)(null),Ft=(0,r.useCallback)(a=>{Xt.current&&clearTimeout(Xt.current),Xt.current=setTimeout(()=>{Xt.current=null,a()},Wt)},[Wt]);(0,r.useEffect)(()=>()=>{Xt.current&&clearTimeout(Xt.current)},[]);let Rn=(0,r.useCallback)(()=>{Ln(e??null),Zn(a=>a+1),bt("expanding"),Ft(()=>bt("card"))},[Ft,e]),Nn=(0,r.useCallback)(()=>{bt("collapsing"),Ft(()=>bt("buttons"))},[Ft]),sn=(0,r.useCallback)(a=>{bn(a),bt("apm-expanding"),Ft(()=>bt("apm-form"))},[Ft]),Qt=(0,r.useCallback)(()=>{bt("apm-collapsing"),Ft(()=>{bt("buttons"),bn(null)})},[Ft]);(0,r.useEffect)(()=>{ae==="buttons"&&ct&&Te&&(Ln(e??null),bt("card"))},[ae,ct,Te,e]);let[It,h]=(0,r.useState)(null),W=(0,r.useRef)(!1),j=(0,r.useRef)(null),ge=(0,r.useRef)("idle"),[X,ue]=(0,r.useState)(null),S=(0,r.useRef)(X);(0,r.useEffect)(()=>{S.current=X},[X]);let u=n||rn,c=p??dt,L=(0,r.useMemo)(()=>(0,Ut.resolveTheme)(z),[z]),y=(0,r.useMemo)(()=>{let a=L?.buttonsLayout??(0,R.resolveButtonsLayoutTheme)(te);return Q?{...a,...Q,cardButton:{...a.cardButton,...Q.cardButton},cardFormContainer:{...a.cardFormContainer,...Q.cardFormContainer},backButton:{...a.backButton,...Q.backButton},backButtonIcon:{...a.backButtonIcon,...Q.backButtonIcon},submitButton:{...a.submitButton,...Q.submitButton},title:{...a.title,...Q.title}}:a},[L,te,Q]),ee=me??L?.appearance,Ie=(0,r.useMemo)(()=>{let a=ee?.variables,C=Ne=>typeof Ne=="string"&&Ne?Ne:void 0,V=y.submitButton,ne=C(a?.colorPrimary)??C(V?.backgroundColor)??"#4A49FF",$=ae==="buttons",be=y.nameInput;return{primaryColor:ne,primaryHoverColor:C(a?.colorPrimaryHover)??Zr(ne,.12),inputBackgroundColor:C(y.cardInputBackground)??C(a?.colorBackground)??"#ffffff",textColor:C(y.cardInputColor)??C(be?.color)??C(a?.colorText)??"#262833",borderColor:C(y.cardInputBorder)??($?"#e5e7eb":"#A4A4FF"),placeholderColor:C(y.cardInputPlaceholderColor)??"#9ca3af",errorColor:C(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:C(be?.fontFamily)??C(a?.fontFamily)??"Poppins, sans-serif",fontSize:C(y.cardInputFontSize)??C(a?.fontSizeBase)??"16px",fontWeight:String(Va(be?.fontWeight)??400),borderRadius:C(a?.borderRadius)??"8px"}},[ee,y,ae]),rt=We.inlineSessionPatchProcessing??!1,Ce=(A??g)||rt,O=u.replace(/\/+$/,""),f=(0,r.useMemo)(()=>_o({userId:o,email:l,firstName:N,lastName:P,country:Ee,zip:_e},Zt),[o,l,N,P,Ee,_e,Zt]),U=[f.firstName,f.lastName].filter(a=>!!a?.trim()).join(" "),Y=(0,r.useMemo)(()=>Ae?Ae.getRawProvider():null,[Ae]),Ye=(0,r.useMemo)(()=>at?at.getRawProvider():null,[at]),Et=oe||100,Dt=(0,r.useMemo)(()=>ee?(0,mn.toStripeAppearance)(ee):null,[ee]),Mr=Dt?{appearance:Dt}:null,Ko=(0,r.useMemo)(()=>{let a=Dt??{},C=a.rules??{};return{...a,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[Dt]),Ho=(0,r.useMemo)(()=>{let a=Aa(oe);return{...a,currency:$e.toLowerCase(),paymentMethodCreation:"manual",...a.mode==="payment"?{captureMethod:"manual"}:{},...Mr}},[oe,$e,Mr]),Wo=(0,r.useMemo)(()=>({mode:"payment",amount:Et,currency:$e.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Mr}),[Et,$e,Mr]),he=(0,r.useCallback)(a=>{nt(a),v?.(a)},[v]);(0,r.useEffect)(()=>{!qe||!it||it.setCardFieldOrder?.(ve??null,le==null)},[qe,it,ve,le]),(0,r.useEffect)(()=>{(Le==="expanding"||Le==="collapsing"||Le==="apm-expanding"||Le==="apm-collapsing")&&he(null)},[Le,he]);let ln=(0,r.useCallback)((a,C,V)=>{d?.(St(a,C,V))},[d]),er=(0,r.useCallback)((a,C,V)=>{let ne=V?.popupBlocked??zn(C),$=ls(a,ne),be=Gn(V?.code)??Tn(C)??"external_payment_method_failed",Ne=new Ut.FloPayError($,"api_error",{code:"external_payment_method_failed",param:a});h(null),ae==="buttons"&&(bt("buttons"),bn(null)),he($),m?.(Ne),console.error("[FloPay] External payment method failed:",{method:a,code:be,popupBlocked:ne})},[ae,m,he]);(0,r.useEffect)(()=>{if(!qe||!e){Ot(null);return}let a=Mo(q?.vault);if(a){Ot(a);return}if(!Vt){Ot(null);return}Ot(null);let C=!0;return new mn.PaymentAPI(O).getVaultCapture(e,t).then(V=>{if(!C)return;let ne=Mo(V);ne?Ot(ne):he("Failed to load the secure card form.")}).catch(V=>{C&&he(V instanceof Error?V.message:"Failed to load the secure card form.")}),()=>{C=!1}},[qe,Vt,qn,e,q?.vault?.html,q?.vault?.messageToken,q?.vault?.expectedOrigin,O,t,he]);let In=(0,r.useRef)({onComplete:s,onError:m,updateError:he,emitDecline:ln,resolvedAccount:f,avsConfig:le,avsCheckProp:fe,sessionId:e,nonce:t,baseUrl:O});In.current={onComplete:s,onError:m,updateError:he,emitDecline:ln,resolvedAccount:f,avsConfig:le,avsCheckProp:fe,sessionId:e,nonce:t,baseUrl:O};let mo=(0,r.useRef)(!1),hi=(0,r.useCallback)(()=>{let{resolvedAccount:a,avsConfig:C,avsCheckProp:V}=In.current,ne=kt.current||a.country||"US",$=C?(0,R.isAVSFieldVisible)(C.state,ne):!1,be=C?(0,R.isAVSFieldVisible)(C.address_line_1,ne):!1,Ne=C?(0,R.isAVSFieldVisible)(C.postal_code,ne):!1,mt=C?(0,R.isAVSFieldVisible)(C.city,ne):!1,Lt=C?(0,R.isAVSFieldVisible)(C.address_line_2,ne):!1,Je=be&&!$&&Ne?(0,R.getStateFromPostalCode)(ne,(Nt.current??"").trim()):null,_t=$?jt.current:Je;return{accountData:{userId:a.userId??"",email:a.email??"",firstName:a.firstName??"",lastName:a.lastName??"",...Ne&&Nt.current?{zip:Nt.current}:{},...mt&&Mt.current?{city:Mt.current}:{},..._t?{state:_t}:{},...be&&qt.current?{addressLine1:qt.current}:{},...Lt&&Gt.current?{addressLine2:Gt.current}:{},country:ne},...V!==void 0?{avsCheck:V}:{},...C?{avsConfig:{country:(0,R.isAVSFieldVisible)(C.country,ne),postal_code:Ne,address_line_1:be,address_line_2:Lt,city:mt,state:$}}:{}}},[]),Yo=(0,r.useRef)(Ke);Yo.current=Ke,(0,r.useEffect)(()=>{Ke||c!==$a||In.current.updateError(null)},[Ke,c]),(0,r.useEffect)(()=>{!qe||!it||it.setSubmitGate?.(Kt||Ke)},[qe,it,Kt,Ke]),(0,r.useEffect)(()=>{if(!qe||!it)return;mo.current=!1;let a=!1,C=it.on("submitting",()=>{Ht(!0),j.current&&clearTimeout(j.current),ge.current="validation-window",j.current=setTimeout(()=>{j.current=null,ge.current==="validation-window"&&(ge.current="processing")},rs),h("processing");let{baseUrl:Ne,sessionId:mt,nonce:Lt,updateError:Je,onError:_t}=In.current;!mt||!Lt||new mn.PaymentAPI(Ne).patchAccountSnapshot(mt,Lt,hi(),{telemetryMode:"best_effort"}).catch(Fe=>{if(!os(Fe))return;let zt=Fe instanceof Error?Fe.message:"Please check your billing address and try again.";Je(zt),ge.current="idle",h(null),_t?.(Fe instanceof Ut.FloPayError?Fe:new Ut.FloPayError(zt,"api_error"))})}),V=it.on("complete",async Ne=>{sr(Ne.sessionId??In.current.sessionId),ge.current="terminal",h("success"),await new Promise(mt=>setTimeout(mt,xn)),!mo.current&&(mo.current=!0,In.current.onComplete?.({status:"succeeded",paymentIntentId:Ne.intentId,checkoutMethod:"card"}))}),ne=it.on("decline",async Ne=>{let{updateError:mt,emitDecline:Lt}=In.current,Je=Ne.message??"Your payment was declined. Please try another card or contact your bank.";ge.current="terminal",mt(Je),h("error"),Lt("card",Je,Ne.declineReason?{declineCode:Ne.declineReason}:void 0),await new Promise(_t=>setTimeout(_t,Cn)),!a&&(ge.current="idle",h(null))}),$=it.on("error",async Ne=>{let{updateError:mt,onError:Lt}=In.current,Je=Ne.message??"There was a problem processing your payment. Please try again.";ge.current="terminal",mt(Je),h("error"),Lt?.(new Ut.FloPayError(Je,"api_error")),await new Promise(_t=>setTimeout(_t,Cn)),!a&&(ge.current="idle",h(null))}),be=it.on("blocked",()=>{if(!Yo.current){Ht(!0);return}In.current.updateError($a)});return()=>{a=!0,j.current&&(clearTimeout(j.current),j.current=null),ge.current="idle",C(),V(),ne(),$(),be()}},[qe,it]);let vn=!!Ve?.clientId,pr=Array.isArray(b),Br=pr&&b.length>0,Pi=pr&&b.includes("paypal"),{expressMethods:Ar,paymentElementMethods:mr}=(0,r.useMemo)(()=>(0,R.partitionStripeMethods)(b,{excludePaypal:vn}),[b,vn]),Go=vn||!!at,bi=(0,r.useMemo)(()=>Go?Ar.filter(a=>a!=="paypal"):Ar,[Ar,Go]),vi=(0,r.useMemo)(()=>{let a=[];return K&&a.push("apple_pay"),pe&&a.push("google_pay"),a},[K,pe]),Fr=pr?bi:vi,Ci=F&&Fr.length>0,yo=en?Qe:Ee,Dr=(0,r.useMemo)(()=>{let a=yo?.trim().toUpperCase();return a?ce?mr.filter(C=>{let V=ce[C];return!V||V.length===0||V.includes(a)}):(0,R.filterStripeMethodsByCountry)(mr,yo):mr},[mr,yo,ce]),fo=(0,r.useMemo)(()=>({mode:"payment",amount:Et,currency:$e.toLowerCase(),paymentMethodCreation:"manual",appearance:Ko}),[Et,$e,Ko]),[Jo,Xo]=(0,r.useState)("loading"),[Qo,Zo]=(0,r.useState)("loading"),[ea,ta]=(0,r.useState)("loading"),[Si,go]=(0,r.useState)(!1),[na,ho]=(0,r.useState)("loading"),[Lr,wi]=(0,r.useState)();(0,r.useEffect)(()=>{wi(Fa())},[]);let ra=x&&(vn||(pr?Pi:Lr===!1)),oa=F&&Ci,yr=!Ke&&ra&&vn,aa=na==="retrying"||na==="exhausted",fr=!Ke&&ra&&!!Ye&&(!vn||aa),gr=!Ke&&oa&&!!Y,hr=!Ke&&F&&Br&&Dr.length>0&&!!Y,ki=yr&&!aa?Si:fr&&Ka(Jo),Ri=gr&&Ka(Qo),Ii=hr&&ea!=="load_error",ia=a=>a==="loading"||a==="ready",sa=yr||fr&&ia(Jo)||gr&&ia(Qo)||hr&&ea!=="load_error",Nr=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!Nr.current){if(!F&&!x){Nr.current=!0;let a=new Ut.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");m?.(a),he(a.message)}else if(!F&&x&&!vn&&!Ye){Nr.current=!0;let a=new Ut.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");m?.(a),he(a.message)}else if(Lr!==void 0&&!Ke&&!Te&&!sa){Nr.current=!0;let a=new Ut.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});m?.(a),he(a.message)}}},[F,x,vn,Ye,Lr,Ke,Te,sa,m,he]);let la=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(la.current||!Br)return;let a=[];K!==!0&&a.push("showApplePay"),pe!==!0&&a.push("showGooglePay"),a.length!==0&&(la.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Br,K,pe]);let ca=(0,r.useCallback)((a,C)=>We.applyInlineSessionPatch?We.applyInlineSessionPatch(a).then(V=>({error:null,sessionId:V.sessionId||e,nonce:V.session?.clientSecret||t})).catch(V=>{let ne=ja(C,V);return he(ne.message),m?.(ne),{error:ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[We.applyInlineSessionPatch,t,m,e,he]),cn=(0,r.useCallback)(async a=>{if(!Pe)return{proceed:!0};try{let C=await Pe({method:a,sessionId:e||void 0,createSession:We.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&Dn(ne=>({...ne??{},...C.account}));let V=await ca(C,a);return V.error?{proceed:!1,accountPatch:C.account}:{proceed:!0,accountPatch:C.account,sessionId:V.sessionId,nonce:V.nonce}}return{proceed:!0}}catch(C){let V=ja(a,C);return he(V.message),m?.(V),{proceed:!1}}},[ca,We.inlineSessionDraft,Pe,m,e,he]),da=(0,r.useCallback)(async(a,C)=>{if(W.current)return;W.current=!0,ke(!0),h("processing"),he(null);let V=C?.sessionId??e,ne=C?.nonce??t,$=_o(f,C?.accountPatch),be=C?.completionPaymentMethodId??Gr(a),Ne=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a;try{let Lt=await new mn.PaymentAPI(O).processPayment($.userId??"",{sessionId:V,nonce:ne,tokenizedData:Ne,accountData:{userId:$.userId??"",email:$.email??"",firstName:$.firstName??"",lastName:$.lastName??"",...le?(()=>{let Fe=kt.current,zt=(0,R.isAVSFieldVisible)(le.state,Fe),nn=(0,R.isAVSFieldVisible)(le.address_line_1,Fe),Wn=(0,R.isAVSFieldVisible)(le.postal_code,Fe),Yn=nn&&!zt&&Wn?(0,R.getStateFromPostalCode)(Fe,(Nt.current??"").trim()):null,xt=zt?jt.current:Yn;return{country:Fe,...Wn&&Nt.current?{zip:Nt.current}:{},...(0,R.isAVSFieldVisible)(le.city,Fe)&&Mt.current?{city:Mt.current}:{},...xt?{state:xt}:{},...nn&&qt.current?{addressLine1:qt.current}:{},...(0,R.isAVSFieldVisible)(le.address_line_2,Fe)&&Gt.current?{addressLine2:Gt.current}:{}}})():{}},chv:_,avsCheck:fe??!1,checkoutType:E,checkoutLayout:re,avsConfig:le?{country:(0,R.isAVSFieldVisible)(le.country,kt.current),postal_code:(0,R.isAVSFieldVisible)(le.postal_code,kt.current),address_line_1:(0,R.isAVSFieldVisible)(le.address_line_1,kt.current),address_line_2:(0,R.isAVSFieldVisible)(le.address_line_2,kt.current),city:(0,R.isAVSFieldVisible)(le.city,kt.current),state:(0,R.isAVSFieldVisible)(le.state,kt.current)}:void 0});if(Lt.ok){sr(V),h("success"),ue(null),await new Promise(Fe=>setTimeout(Fe,xn)),s?.({status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:be,checkoutMethod:a.isPaypal?"paypal":"card"});return}let Je=await Lt.json().catch(()=>null);if(Je?.type==="paypal_redirect_required"){let Fe=Je.threeDSecureToken,zt=Je.paymentMethodId||a.id||"";if(!Ae||!Fe){h("error"),he("PayPal authorization required but no token provided.");return}try{let nn=at?.getRawProvider();if(!nn){he("PayPal is not available.");return}let Wn={return_url:window.location.href};zt&&(Wn.payment_method=zt);let{error:Yn}=await nn.confirmPayment({clientSecret:Fe,confirmParams:Wn,redirect:"if_required"});if(Yn){h("error");let xt=Yn.message??"PayPal payment failed.";he(xt),ln("paypal",xt,{code:Yn.code})}}catch(nn){h("error"),he(nn instanceof Error?nn.message:"PayPal authorization failed.")}return}if(Je?.type==="paypal_direct_required"){let Fe=Je.orderId;if(!Fe){h("error"),he("PayPal retry required but no order id provided.");return}let zt=S.current?.attempts??0;if(zt>=2){h("error"),he("PayPal payment could not be completed after multiple attempts."),ln("paypal","paypal_direct_required retry limit exceeded");return}go(!1),ho("loading"),ue({orderId:Fe,attempts:zt+1}),h(null);return}h("error");let _t=Je?.message??"Payment failed. Please try again.";he(_t),ln(a.isPaypal?"paypal":"card",_t,{code:Je?.code??Je?.gatewayErrorCode,declineCode:Je?.declineCode??Je?.gatewayDeclineReason}),await new Promise(Fe=>setTimeout(Fe,Cn))}catch(mt){h("error"),he(mt instanceof Error?mt.message:"An unexpected error occurred"),await new Promise(Lt=>setTimeout(Lt,Cn))}finally{ke(!1),h(null),W.current=!1}},[O,e,t,f,U,_,Ae,at,s,m,he,ln]),tn=(0,r.useCallback)((a,C)=>{I?I(a):da(a,C)},[I,da]),ua=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(typeof window>"u"||ua.current)return;let a=new URLSearchParams(window.location.search),C=a.get("payment_intent"),V=a.get("payment_intent_client_secret"),ne=a.get("redirect_status");if(!C||!V)return;let $=_t=>{let Fe=localStorage.getItem(_t);if(!Fe)return null;try{return JSON.parse(Fe)}catch{return localStorage.removeItem(_t),null}},be=$(wn)??$(Ua),Ne;if(be?.clientSecret){if(be.clientSecret!==V)return;Ne={...be.accountPatch?{accountPatch:be.accountPatch}:{},...be.sessionId?{sessionId:be.sessionId}:{},...be.nonce?{nonce:be.nonce}:{}}}else if(be?.sessionId&&be.sessionId!==e)return;ua.current=!0,localStorage.removeItem(wn),localStorage.removeItem(Ua);let mt=new URL(window.location.href);mt.searchParams.delete("payment_intent"),mt.searchParams.delete("payment_intent_client_secret"),mt.searchParams.delete("redirect_status"),window.history.replaceState({},"",mt.toString());let Lt=be?.paymentMethodType??be?.tokenType??"card",Je="card";(async()=>{let _t=Ae?.getRawProvider();if(!_t){let xt="Payment is not available \u2014 please refresh and try again.";he(xt),ln(Je,xt);return}if(ne==="failed"){let xt="Payment was declined. Please try again.";he(xt),ln(Je,xt);return}let{paymentIntent:Fe,error:zt}=await _t.retrievePaymentIntent(V);if(zt){let xt=zt.message??"Failed to retrieve payment status.";he(xt),ln(Je,xt,{code:zt.code});return}let nn=Fe?.status,Wn=Yr(nn);if(!Fe||!Wn){let xt=nn==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";he(xt),ln(Je,xt,{code:nn??"missing_payment_intent"});return}let Yn=typeof Fe.payment_method=="string"?Fe.payment_method:Fe.payment_method?.id;tn({id:Yn??be?.paymentMethodId??be?.tokenId??Fe.id,type:"card",threeDSecureActionResultTokenId:Fe.id,gateway:be?.gateway??"stripe",paymentMethodType:Lt},Ne)})()},[e,tn,Ae,he,ln]);let Po=(0,r.useCallback)(a=>{a.preventDefault()},[]);if(!(Ae!==null))return(0,i.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Pr=ae==="buttons",Yt=ee?.variables,Ei=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),bo=Yt?.colorBackground,_i=bo&&!Ei.has(bo)?bo:void 0,br=y.cardInputBorder??(Pr?"#e5e7eb":"#A4A4FF"),vo=Yt?.colorDanger??"#dc2626",Vn=a=>Jt&&a?vo:br,Or=(At.malformed||At.empty)&&(an||Jt),xi=Or?vo:Vn(gt.zip),Co=y.cardFormContainer?.backgroundColor??_i??(Pr?"white":"#EDEDFF"),vr=y.cardInputBackground??Yt?.colorBackground??"white",So=nr(J),pa=nr(ye),tr=y.nameInput,ma=y.cardInputFontSize??us(tr?.fontSize)??Yt?.fontSizeBase??"16px",ya=typeof tr?.fontFamily=="string"?tr.fontFamily:Yt?.fontFamily??"Poppins, sans-serif",fa=Va(tr?.fontWeight)??400,Ti=y.cardInputColor??(typeof tr?.color=="string"?tr.color:void 0)??Yt?.colorText??"#262833",Mi=y.cardInputPlaceholderColor??"#9ca3af",pt=Yt?.borderRadius??"8px",Kn=Yt?.borderRadius??y.cardButton?.borderRadius??pt,Hn=Yt?.colorPrimary??"#4A49FF",Bi=Yt?.colorPrimaryHover??Zr(Hn,.12),wo=Yt?.colorText??"#262833",ga={fontSize:ma,fontFamily:ya,fontWeight:fa,color:Ti,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ai={"--flopay-input-placeholder-color":Mi,"--flopay-input-font-size":ma,"--flopay-input-font-family":ya,"--flopay-input-font-weight":String(fa)},Cr=y.cardFormContainer??{},ko=Cr.padding??(Pr?"0":"1rem"),Ro=Cr.borderRadius??pt,Fi=it&&Rt?(0,i.jsx)(Vr,{capture:it,html:Rt.html,messageToken:Rt.messageToken,expectedOrigin:Rt.expectedOrigin,theme:Ie,onReady:()=>{if(!le||typeof document>"u")return;let a=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};a();let C=0,V=window.setInterval(()=>{C+=1;let ne=document.activeElement;!!ne&&ne.tagName==="IFRAME"&&ne.id==="flopay_vault_form_iframe"?(a(),window.clearInterval(V)):C>=50&&window.clearInterval(V)},100)},onError:a=>he(a),onValidation:a=>{let C=ge.current;(C==="idle"||C==="validation-window")&&(he(a),a&&ge.current==="validation-window"&&(j.current&&(clearTimeout(j.current),j.current=null),ge.current="idle",h(null)))}}):(0,i.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),ha=(0,i.jsxs)("div",{style:{backgroundColor:Co,borderRadius:Ro,...Cr,padding:ko,...Ai,display:"flex",flexDirection:"column"},children:[(0,i.jsx)("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${Ve.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),Pr&&jn&&(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:qe?-2:0},children:[(0,i.jsxs)("button",{type:"button",onClick:Nn,style:{display:"inline-flex",alignItems:"center",gap:So?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:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...y.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(or,{content:J})]}),pa?(0,i.jsx)("div",{style:{flex:1}}):(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...y.title},children:(0,i.jsx)(wr,{content:ye})})]}),!Pr&&!pa&&(0,i.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:wo,order:qe?-3:0,...y.title},children:(0,i.jsx)(wr,{content:ye})}),le&&(0,i.jsx)("div",{style:{order:qe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=Qe,C=($=!1)=>({backgroundColor:vr,border:`1px solid ${Vn($)}`,borderRadius:pt,marginTop:"0.5rem",padding:"10px"}),V=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ga}),ne=(0,R.getStateOptions)(a);return(0,i.jsxs)(i.Fragment,{children:[(0,R.isAVSFieldVisible)(le.address_line_1,a)&&(0,i.jsx)("div",{style:C(gt.line1),children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:je,onChange:$=>{Bt.current.addressLine1=!0,qt.current=$.target.value,wt($.target.value)},disabled:Ce,required:!0,"data-testid":"flopay-address-line1",style:V()})}),(0,R.isAVSFieldVisible)(le.address_line_2,a)&&(0,i.jsx)("div",{style:C(),children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Ge,onChange:$=>{Bt.current.addressLine2=!0,Gt.current=$.target.value,An($.target.value)},disabled:Ce,"data-testid":"flopay-address-line2",style:V()})}),((0,R.isAVSFieldVisible)(le.city,a)||(0,R.isAVSFieldVisible)(le.state,a))&&(0,i.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,R.isAVSFieldVisible)(le.city,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:vr,borderTop:`1px solid ${Vn(gt.city)}`,borderRight:`1px solid ${Vn(gt.city)}`,borderBottom:`1px solid ${Vn(gt.city)}`,borderLeft:`1px solid ${Vn(gt.city)}`,padding:"10px",borderTopLeftRadius:pt,borderBottomLeftRadius:pt,...(0,R.isAVSFieldVisible)(le.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:pt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:ht,onChange:$=>{Bt.current.city=!0,Mt.current=$.target.value,Fn($.target.value)},disabled:Ce,required:!0,"data-testid":"flopay-city",style:V()})}),(0,R.isAVSFieldVisible)(le.state,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:vr,border:`1px solid ${Vn(gt.state)}`,padding:"10px",borderTopRightRadius:pt,borderBottomRightRadius:pt,...(0,R.isAVSFieldVisible)(le.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:pt}},children:ne?(0,i.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:on,onChange:$=>{Bt.current.state=!0,jt.current=$.target.value,hn($.target.value)},disabled:Ce,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...V(),cursor:"pointer"},children:[(0,i.jsx)("option",{value:"",children:(0,R.getStateLabel)(a)}),ne.map($=>(0,i.jsx)("option",{value:$.code,children:$.name},$.code))]}):(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,R.getStateLabel)(a),autoComplete:"billing address-level1",value:on,onChange:$=>{Bt.current.state=!0,jt.current=$.target.value,hn($.target.value)},disabled:Ce,required:!0,"data-testid":"flopay-state",style:V()})})]}),((0,R.isAVSFieldVisible)(le.country,a)||(0,R.isAVSFieldVisible)(le.postal_code,a))&&(0,i.jsxs)("div",{style:{display:"flex",flexDirection:se==="column"?"column":"row",gap:se==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,R.isAVSFieldVisible)(le.country,a)&&(0,i.jsx)("div",{style:{flex:se==="row"?1:void 0,backgroundColor:vr,borderTop:`1px solid ${br}`,borderRight:`1px solid ${br}`,borderBottom:`1px solid ${br}`,borderLeft:`1px solid ${br}`,padding:"10px",...se==="row"&&(0,R.isAVSFieldVisible)(le.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:pt,borderBottomLeftRadius:pt,borderRight:"none"}:{borderRadius:pt}},children:(0,i.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Qe,onChange:$=>{Bt.current.country=!0,kt.current=$.target.value,He($.target.value),Oe?.($.target.value),jt.current="",hn("")},disabled:Ce,autoComplete:"billing country","data-testid":"flopay-country",style:{...V(),cursor:"pointer"},children:R.COUNTRY_OPTIONS.map($=>(0,i.jsxs)("option",{value:$.code,children:[$.flag," ",$.name]},$.code))})}),(0,R.isAVSFieldVisible)(le.postal_code,a)&&(0,i.jsx)("div",{style:{flex:se==="row"?1:void 0,backgroundColor:vr,border:`1px solid ${_i}`,padding:"10px",...se==="row"&&(0,R.isAVSFieldVisible)(le.country,a)?{borderRadius:"0",borderTopRightRadius:pt,borderBottomRightRadius:pt}:{borderRadius:pt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,R.getPostalCodeLabel)(Qe),autoComplete:"billing postal-code",value:Ze,onChange:$=>{Bt.current.zip=!0,Nt.current=$.target.value,xe($.target.value),ze?.($.target.value)},onBlur:()=>Pn(!0),disabled:Ce,required:At.required,"aria-invalid":Or||void 0,"aria-describedby":Or?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:V()})})]}),Or&&(0,i.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:vo,...ga,fontSize:"0.75rem"},children:At.empty?`${(0,R.getPostalCodeLabel)(a)} is required`:ls(a)})]})})()}),qe&&Be&&(0,i.jsx)("div",{style:{order:-2,width:"100%"},children:Be}),qe&&Ai,c&&(0,i.jsx)(ar,{margin:"0.75rem 0",styleOverride:y.errorBanner,children:c})]}),zr={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"},Pa=a=>tt?!x||!vn?(0,i.jsx)("pre",{"data-testid":a,style:zr,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:zr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${x}`,` directPaypalConfigured=${vn}`,` inAppBrowserDetected=${String(Lr)}`,` shouldRenderDirectPayPal=${yr}`,` shouldRenderStripePayPal=${fr}`,` hasPaypalStripeInstance=${!!Ye}`].join(`
38
+ `}),Pr&&jn&&(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:qe?-2:0},children:[(0,i.jsxs)("button",{type:"button",onClick:Nn,style:{display:"inline-flex",alignItems:"center",gap:So?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:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...y.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(or,{content:J})]}),pa?(0,i.jsx)("div",{style:{flex:1}}):(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...y.title},children:(0,i.jsx)(wr,{content:ye})})]}),!Pr&&!pa&&(0,i.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:wo,order:qe?-3:0,...y.title},children:(0,i.jsx)(wr,{content:ye})}),le&&(0,i.jsx)("div",{style:{order:qe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=Qe,C=($=!1)=>({backgroundColor:vr,border:`1px solid ${Vn($)}`,borderRadius:pt,marginTop:"0.5rem",padding:"10px"}),V=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ga}),ne=(0,R.getStateOptions)(a);return(0,i.jsxs)(i.Fragment,{children:[(0,R.isAVSFieldVisible)(le.address_line_1,a)&&(0,i.jsx)("div",{style:C(gt.line1),children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:je,onChange:$=>{Bt.current.addressLine1=!0,qt.current=$.target.value,wt($.target.value)},disabled:Ce,required:!0,"data-testid":"flopay-address-line1",style:V()})}),(0,R.isAVSFieldVisible)(le.address_line_2,a)&&(0,i.jsx)("div",{style:C(),children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Ge,onChange:$=>{Bt.current.addressLine2=!0,Gt.current=$.target.value,An($.target.value)},disabled:Ce,"data-testid":"flopay-address-line2",style:V()})}),((0,R.isAVSFieldVisible)(le.city,a)||(0,R.isAVSFieldVisible)(le.state,a))&&(0,i.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,R.isAVSFieldVisible)(le.city,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:vr,borderTop:`1px solid ${Vn(gt.city)}`,borderRight:`1px solid ${Vn(gt.city)}`,borderBottom:`1px solid ${Vn(gt.city)}`,borderLeft:`1px solid ${Vn(gt.city)}`,padding:"10px",borderTopLeftRadius:pt,borderBottomLeftRadius:pt,...(0,R.isAVSFieldVisible)(le.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:pt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:ht,onChange:$=>{Bt.current.city=!0,Mt.current=$.target.value,Fn($.target.value)},disabled:Ce,required:!0,"data-testid":"flopay-city",style:V()})}),(0,R.isAVSFieldVisible)(le.state,a)&&(0,i.jsx)("div",{style:{flex:1,backgroundColor:vr,border:`1px solid ${Vn(gt.state)}`,padding:"10px",borderTopRightRadius:pt,borderBottomRightRadius:pt,...(0,R.isAVSFieldVisible)(le.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:pt}},children:ne?(0,i.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:on,onChange:$=>{Bt.current.state=!0,jt.current=$.target.value,hn($.target.value)},disabled:Ce,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...V(),cursor:"pointer"},children:[(0,i.jsx)("option",{value:"",children:(0,R.getStateLabel)(a)}),ne.map($=>(0,i.jsx)("option",{value:$.code,children:$.name},$.code))]}):(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,R.getStateLabel)(a),autoComplete:"billing address-level1",value:on,onChange:$=>{Bt.current.state=!0,jt.current=$.target.value,hn($.target.value)},disabled:Ce,required:!0,"data-testid":"flopay-state",style:V()})})]}),((0,R.isAVSFieldVisible)(le.country,a)||(0,R.isAVSFieldVisible)(le.postal_code,a))&&(0,i.jsxs)("div",{style:{display:"flex",flexDirection:se==="column"?"column":"row",gap:se==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,R.isAVSFieldVisible)(le.country,a)&&(0,i.jsx)("div",{style:{flex:se==="row"?1:void 0,backgroundColor:vr,borderTop:`1px solid ${br}`,borderRight:`1px solid ${br}`,borderBottom:`1px solid ${br}`,borderLeft:`1px solid ${br}`,padding:"10px",...se==="row"&&(0,R.isAVSFieldVisible)(le.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:pt,borderBottomLeftRadius:pt,borderRight:"none"}:{borderRadius:pt}},children:(0,i.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Qe,onChange:$=>{Bt.current.country=!0,kt.current=$.target.value,He($.target.value),Oe?.($.target.value),jt.current="",hn("")},disabled:Ce,autoComplete:"billing country","data-testid":"flopay-country",style:{...V(),cursor:"pointer"},children:R.COUNTRY_OPTIONS.map($=>(0,i.jsxs)("option",{value:$.code,children:[$.flag," ",$.name]},$.code))})}),(0,R.isAVSFieldVisible)(le.postal_code,a)&&(0,i.jsx)("div",{style:{flex:se==="row"?1:void 0,backgroundColor:vr,border:`1px solid ${xi}`,padding:"10px",...se==="row"&&(0,R.isAVSFieldVisible)(le.country,a)?{borderRadius:"0",borderTopRightRadius:pt,borderBottomRightRadius:pt}:{borderRadius:pt}},children:(0,i.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,R.getPostalCodeLabel)(Qe),autoComplete:"billing postal-code",value:Ze,onChange:$=>{Bt.current.zip=!0,Nt.current=$.target.value,xe($.target.value),ze?.($.target.value)},onBlur:()=>Pn(!0),disabled:Ce,required:At.required,"aria-invalid":Or||void 0,"aria-describedby":Or?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:V()})})]}),Or&&(0,i.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:vo,...ga,fontSize:"0.75rem"},children:At.empty?`${(0,R.getPostalCodeLabel)(a)} is required`:cs(a)})]})})()}),qe&&Be&&(0,i.jsx)("div",{style:{order:-2,width:"100%"},children:Be}),qe&&Fi,c&&(0,i.jsx)(ar,{margin:"0.75rem 0",styleOverride:y.errorBanner,children:c})]}),zr={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"},Pa=a=>tt?!x||!vn?(0,i.jsx)("pre",{"data-testid":a,style:zr,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:zr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${x}`,` directPaypalConfigured=${vn}`,` inAppBrowserDetected=${String(Lr)}`,` shouldRenderDirectPayPal=${yr}`,` shouldRenderStripePayPal=${fr}`,` hasPaypalStripeInstance=${!!Ye}`].join(`
39
39
  `)}):null,ba=a=>tt?!F||!Y?(0,i.jsx)("pre",{"data-testid":a,style:zr,children:"FloPay/Stripe-debug - not enabled"}):(0,i.jsx)("pre",{"data-testid":a,style:zr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${F}`,` currency=${$e}`,` amountInCents=${Et}`,` enabledPaymentMethods: ${JSON.stringify(b??[])}`,` enabledPaymentMethodsProvided=${pr}`,` hasEnabledMethods=${Br}`,` expressMethods: ${JSON.stringify(Ar)}`,` walletExpressMethods: ${JSON.stringify(Fr)}`,` paymentElementMethods: ${JSON.stringify(mr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Dr)}`,` hasStripeInstance=${!!Y}`,` shouldRenderWallets=${gr}`,` shouldRenderPaymentElement=${hr}`].join(`
40
- `)}):null,va=Le==="apm-expanding"||Le==="apm-form"||Le==="apm-collapsing",Ur=Le==="apm-expanding"?`flopay-card-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:Le==="apm-collapsing"?`flopay-card-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,$r=vt?{...fo,paymentMethodTypes:[vt]}:null;if(ae==="buttons"){let a=Le==="buttons"||Le==="expanding"||Le==="apm-expanding",C=Le==="expanding"||Le==="card"||Le==="collapsing",V=H===void 0?{boxSizing:"border-box",height:eo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ne=Le==="expanding"||Le==="apm-expanding"?`flopay-buttons-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Le==="collapsing"||Le==="apm-collapsing"?`flopay-buttons-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,$=Le==="expanding"?`flopay-card-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:Le==="collapsing"?`flopay-card-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,i.jsxs)("form",{onSubmit:Po,className:k,style:{position:"relative"},children:[(0,i.jsx)(Bo,{}),It&&(0,i.jsx)(Sn,{status:It,errorMessage:c}),(0,i.jsxs)("div",{style:{display:"grid"},children:[(0,i.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!ne?as:{},...ne?{animation:ne,pointerEvents:"none"}:{}},children:[Pa("flopay-direct-paypal-gate-debug"),ba("flopay-stripe-gate-debug"),yr&&Ve&&(0,i.jsxs)(i.Fragment,{children:[X&&(0,i.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,i.jsx)(Ir,{sessionId:e,nonce:t,billingApiUrl:u,email:f.email,clientId:Ve.clientId,environment:Ve.environment,currency:$e.toUpperCase(),isSubscription:ot,onTokenizedBody:tn,onComplete:s,onErrorChange:he,onDecline:d,onTechnicalFailure:er,onButtonClick:Se,runBeforeButtonClick:cn,isProcessing:Ce,onLoadStateChange:go,onInitializationStateChange:ho,session:q??null,existingOrderId:X?.orderId,debug:tt},X?.orderId??"fresh")]}),fr&&(0,i.jsx)(lt.Elements,{stripe:Ye,options:Wo,children:(0,i.jsx)(Ha,{sessionId:e,nonce:t,email:f.email,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:he,isProcessing:Ce,onButtonClick:Se,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:Xo,placeholderBorderRadius:Kn})}),gr?(0,i.jsx)(lt.Elements,{stripe:Y,options:Ho,children:(0,i.jsx)(Wa,{sessionId:e,nonce:t,email:f.email,billingApiUrl:u,intentKind:oe>0?"payment":"setup",expressMethods:Fr,onTokenizedBody:tn,onErrorChange:he,onButtonClick:Se,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:Zo,placeholderBorderRadius:Kn})}):oa?(0,i.jsx)("div",{style:{height:eo,borderRadius:Kn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,hr&&(0,i.jsx)(Ya,{sessionId:e,nonce:t,email:f.email,billingName:[f.firstName,f.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,paymentElementMethods:Dr,stripeInstance:Y,paymentElementBaseOptions:fo,onTokenizedBody:tn,onErrorChange:he,onButtonClick:Se,onDecline:d,runBeforeButtonClick:cn,onLoadStateChange:ta,isProcessing:Ce,submitButtonColor:Hn,submitButtonBorderRadius:pt,submitButtonStyle:y.submitButton,onExpandApm:sn,expandedApmMethod:vt,themeId:z,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:Kn}}),qe&&(0,i.jsx)("button",{type:"button",onClick:async()=>{Ce||!(await cn("card")).proceed||(Se?.("card"),Rn())},disabled:Ce,style:{width:"100%",...V,...y.cardButton,...Do({themeBundle:L,resolvedPrimaryColor:Hn,resolvedBorderRadius:pt,submitButtonStyle:y.submitButton,explicitPrimaryColor:Yt?.colorPrimary}),fontSize:y.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ce?"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:Ce?.6:1},onMouseEnter:be=>{!Ce&&(L||Yt?.colorPrimary)&&(be.currentTarget.style.backgroundColor=Mi)},onMouseLeave:be=>{(L||Yt?.colorPrimary)&&(be.currentTarget.style.backgroundColor=Hn)},onMouseDown:be=>{be.currentTarget.style.transform="scale(0.985)"},onMouseUp:be=>{be.currentTarget.style.transform="scale(1)"},children:(0,i.jsx)(rr,{content:H})}),c&&Le==="buttons"&&(0,i.jsx)(ar,{margin:"0.25rem 0",styleOverride:y.errorBanner,children:c})]}),qe&&C&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...$?{animation:$}:{},...Le==="collapsing"?{pointerEvents:"none"}:{}},children:ha}),F&&va&&vt&&$r&&Y&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...Ur?{animation:Ur}:{},...Le==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:Co,borderRadius:Ro,...Cr,padding:ko},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,i.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Qt,style:{display:"inline-flex",alignItems:"center",gap:So?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:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...y.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(or,{content:J})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:wo,paddingRight:80,...y.title},children:`Pay with ${(0,R.getStripeMethodDisplayName)(vt)}`})]}),(0,i.jsx)(lt.Elements,{stripe:Y,options:$r,children:(0,i.jsx)(Ao,{method:vt,sessionId:e,nonce:t,email:f.email,billingName:[f.firstName,f.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:he,onDecline:d,onCancel:Qt,runBeforeButtonClick:cn,onButtonClick:Se,isProcessing:Ce,submitButtonColor:Hn,submitButtonBorderRadius:pt,submitButtonStyle:y.submitButton,errorText:c})},vt)]})})]})]})}return va&&vt&&$r&&Y&&F?(0,i.jsxs)("form",{onSubmit:Po,className:k,style:{position:"relative"},children:[(0,i.jsx)(Bo,{}),It&&(0,i.jsx)(Sn,{status:It,errorMessage:c}),(0,i.jsx)("div",{style:{...Ur?{animation:Ur}:{},...Le==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:Co,borderRadius:Ro,...Cr,padding:ko},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,i.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Qt,style:{display:"inline-flex",alignItems:"center",gap:So?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:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...y.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(or,{content:J})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:wo,paddingRight:80,...y.title},children:`Pay with ${(0,R.getStripeMethodDisplayName)(vt)}`})]}),(0,i.jsx)(lt.Elements,{stripe:Y,options:$r,children:(0,i.jsx)(Ao,{method:vt,sessionId:e,nonce:t,email:f.email,billingName:[f.firstName,f.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:he,onDecline:d,onCancel:Qt,runBeforeButtonClick:cn,onButtonClick:Se,isProcessing:Ce,submitButtonColor:Hn,submitButtonBorderRadius:pt,submitButtonStyle:y.submitButton,errorText:c})},vt)]})})]}):(0,i.jsxs)("form",{onSubmit:Po,className:k,style:{position:"relative"},children:[(0,i.jsx)(Bo,{}),It&&(0,i.jsx)(Sn,{status:It,errorMessage:c}),(0,i.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Pa("flopay-direct-paypal-gate-debug-default"),ba("flopay-stripe-gate-debug-default"),yr&&Ve&&(0,i.jsxs)(i.Fragment,{children:[X&&(0,i.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,i.jsx)(Ir,{sessionId:e,nonce:t,billingApiUrl:u,email:f.email,clientId:Ve.clientId,environment:Ve.environment,currency:$e.toUpperCase(),isSubscription:ot,onTokenizedBody:tn,onComplete:s,onErrorChange:he,onDecline:d,onTechnicalFailure:er,onButtonClick:Se,runBeforeButtonClick:cn,isProcessing:Ce,onLoadStateChange:go,onInitializationStateChange:ho,session:q??null,existingOrderId:X?.orderId,debug:tt},X?.orderId??"fresh")]}),fr&&(0,i.jsx)(lt.Elements,{stripe:Ye,options:Wo,children:(0,i.jsx)(Ha,{sessionId:e,nonce:t,email:f.email,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:he,isProcessing:Ce,onButtonClick:Se,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:Xo,placeholderBorderRadius:Kn})}),gr&&(0,i.jsx)(lt.Elements,{stripe:Y,options:Ho,children:(0,i.jsx)(Wa,{sessionId:e,nonce:t,email:f.email,billingApiUrl:u,intentKind:oe>0?"payment":"setup",expressMethods:Fr,onTokenizedBody:tn,onErrorChange:he,onButtonClick:Se,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:Zo,placeholderBorderRadius:Kn})}),hr&&(0,i.jsx)(Ya,{sessionId:e,nonce:t,email:f.email,billingName:[f.firstName,f.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,paymentElementMethods:Dr,stripeInstance:Y,paymentElementBaseOptions:fo,onTokenizedBody:tn,onErrorChange:he,onButtonClick:Se,onDecline:d,runBeforeButtonClick:cn,onLoadStateChange:ta,isProcessing:Ce,submitButtonColor:Hn,submitButtonBorderRadius:pt,submitButtonStyle:y.submitButton,themeId:z,onExpandApm:sn,expandedApmMethod:vt,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:Kn}})]}),qe&&(ki||wi||Ri)&&(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,i.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,i.jsx)("span",{children:"or pay with card"}),(0,i.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),qe&&ha]})}var cr=require("@flopay/js"),Xe=require("@flopay/shared");var _r="card";async function ms(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:m}=await e.retrieveSetupIntent(t);return{error:m,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:l,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:l??null}}async function ys(e,t,n,l){if(l){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:m,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:m??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:s}=await e.confirmCardPayment(t,n);return{error:s,intent:o??null}}function kn(e,t){return Object.assign(e,{checkoutMethod:t})}function ei(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 fs(e){return e.status==="succeeded"||e.status==="declined"}async function ti(e){if(typeof document>"u"||typeof window>"u")throw new Xe.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Xe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,l=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,s=async()=>{let P=new AbortController,_=()=>P.abort();e.signal?.aborted?P.abort():e.signal?.addEventListener("abort",_);let k=window.setTimeout(()=>P.abort(),l);try{let A=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:P.signal});if(!A.ok)return{status:"unknown"};let p=await A.json().catch(()=>null);return gs(p)}catch{return{status:"unknown"}}finally{window.clearTimeout(k),e.signal?.removeEventListener("abort",_)}},m=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let I=document.createElement("iframe");I.setAttribute("title","Card authentication"),I.setAttribute("allow","payment"),I.tabIndex=0,I.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),I.src=e.nextActionRedirectUrl,d.appendChild(I),document.body.appendChild(d),I.focus();let N=null;try{N=new URL(e.billingApiUrl,window.location.href).origin}catch{N=null}try{let P=await new Promise((_,k)=>{let A=!1,p=0,v=0,x=0,F=!1,b=()=>{window.clearTimeout(p),window.clearInterval(v),window.clearTimeout(x),window.removeEventListener("message",ae),I.removeEventListener("load",K),e.signal?.removeEventListener("abort",pe)},ce=async()=>{if(!(A||F)){F=!0;try{let z=await s();if(A||!fs(z))return;A=!0,b(),_(z)}finally{F=!1}}},K=()=>{window.clearTimeout(x),x=window.setTimeout(()=>{ce()},250)},pe=()=>{A||(A=!0,b(),k(new Xe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ae=z=>{if(z.source!==I.contentWindow||N&&z.origin!==N)return;let te=z.data;!te||typeof te!="object"||te.source!=="flopay-vault-3ds-return"||A||(A=!0,b(),_(null))};p=window.setTimeout(()=>{A||(A=!0,b(),k(new Xe.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),v=window.setInterval(()=>{ce()},n),I.addEventListener("load",K),window.addEventListener("message",ae),e.signal?.addEventListener("abort",pe),e.signal?.aborted&&pe()});return P||await s()}finally{d.parentNode?.removeChild(d),m?.isConnected&&m.focus()}}function gs(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Un(e,t="Payment failed. Please try again.",n){let l=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,s=On(o)??o;return kn(new Xe.FloPayError(s,"api_error",{code:e?.gatewayErrorCode}),l)}function Lo(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ro(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function hs(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 ni(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ro(o)))return o;let l=e?.data;if(l&&typeof l=="object"){let o=l,s=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let d of s)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||ro(d)))return d;let m=o.gateways;if(m&&typeof m=="object"){let d=m.stripe;if(d&&typeof d=="object"){let I=d,N=[I.stripeClientSecret,I.clientSecret];for(let P of N)if(typeof P=="string"&&P.length>0&&(!t?.requirePaymentIntentClientSecret||ro(P)))return P}}}}async function Ps({billingApiUrl:e,sessionId:t,nonce:n,responseJson:l}){let o=ni(l,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new cr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ro(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function dr({billingApiUrl:e,sessionId:t,session:n,nonce:l,tokenizedData:o,returnUrl:s,telemetry:m}){let d=e.replace(/\/+$/,""),I=t??n.id,N=l??n.clientSecret,P=n.customer?.id??n.accountData?.userId??"",_=n.customer?.email??n.accountData?.email??"",k=n.customer?.firstName??n.accountData?.firstName??"",A=n.customer?.lastName??n.accountData?.lastName??"",p=n.customer?.country??n.accountData?.country??void 0,v=n.customer?.zip??n.accountData?.zip??void 0,x=new cr.PaymentAPI(d,m===!1?{telemetry:!1}:void 0),F=await hs(()=>x.processPayment(P,{sessionId:I,nonce:N,tokenizedData:o,accountData:{userId:P,email:_,firstName:k,lastName:A,country:p,zip:v},returnUrl:s??Lo(n)}));if(F.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Gr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let b=await F.json().catch(()=>null);if(b?.type==="paypal_redirect_required"||b?.type==="3ds_required"){let ce=ni(b);if(!ce)throw new Xe.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:b.type,threeDSecureToken:ce,paymentMethodId:b.paymentMethodId}}if(b?.gatewayErrorCode==="authentication_required"){let ce=await Ps({billingApiUrl:d,sessionId:I,nonce:N,responseJson:b});if(ce)return ce;throw kn(new Xe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new Xe.FloPayError(b?.message??"Payment failed. Please try again.","api_error",{code:b?.code??b?.gatewayErrorCode,declineCode:b?.declineCode??b?.gatewayDeclineReason})}async function oo(e,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:m,returnUrl:d,telemetry:I}){let N=t?.getRawProvider();if(!N)throw new Xe.FloPayError("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!l||!e.threeDSecureToken)throw kn(new Xe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let P=(0,Xe.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,k=e.paymentMethodId,A=await ms(N,e.threeDSecureToken,P);if(A){if(A.error)throw kn(new Xe.FloPayError(A.error.message??`Failed to retrieve 3DS ${P?"setup":"payment"} status.`,"api_error",{code:A.error.code}),"card");let v=A.intent;!k&&v?.payment_method&&(typeof v.payment_method=="string"?k=v.payment_method:"id"in v.payment_method&&(k=v.payment_method.id??void 0))}let p=k?await ys(N,e.threeDSecureToken,{payment_method:k,return_url:d??Lo(m)??window.location.href},P):null;if(p){if(p.error)throw kn(new Xe.FloPayError(p.error.message??"3DS authentication failed.","api_error",{code:p.error.code}),"card");_=p.intent}else{let v=await N.handleNextAction({clientSecret:e.threeDSecureToken});if(v.error)throw kn(new Xe.FloPayError(v.error.message??"3DS authentication failed.","api_error",{code:v.error.code}),"card");_=(P?v.setupIntent:v.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let v=await dr({billingApiUrl:o,sessionId:s,session:m,telemetry:I,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:d});return v.type==="success"?{...v.result,paymentIntentId:v.result.paymentIntentId??_.id,paymentMethodId:v.result.paymentMethodId??k}:oo(v,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:m,returnUrl:d,telemetry:I})}throw kn(new Xe.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let P=(n??t)?.getRawProvider();if(!P)throw kn(new Xe.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:k}=await P.handleNextAction({clientSecret:e.threeDSecureToken});if(k)throw kn(new Xe.FloPayError(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await P.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Lo(m)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(_)throw kn(new Xe.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Xe.FloPayError("Unsupported payment redirect state.","api_error")}function Jn(e){if(e instanceof Xe.FloPayError){let l=On(e.message);return l&&l!==e.message?Object.assign(new Xe.FloPayError(l,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=On(t)??t;return new Xe.FloPayError(n,"api_error")}function ao(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Xe.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function io({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:l,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let s=!!t&&t!==e,[m,d]=await Promise.all([(0,cr.loadFloPay)(e,{billingApiUrl:n,locale:l,telemetry:o}),s?(0,cr.loadFloPay)(t,{billingApiUrl:n,locale:l,telemetry:o}).catch(I=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",I),null)):Promise.resolve(null)]);return{flopay:m,paypalFlopay:t?s?d:m:null}}var w=require("react/jsx-runtime"),ur=44,jo="flopay_checkout_saved_payment_resume",co=new Map,so=new Map;function ri(e,t){t.settled&&t.consumers===0&&co.get(e)===t&&co.delete(e)}function bs(e,t,n){let l=so.get(e);if(l&&(!l.sdkGeneratedIdempotencyKey||!t||l.sdkGeneratedIdempotencyKey===t))return l.attempt;let o=n(),s={attempt:o,sdkGeneratedIdempotencyKey:t};so.set(e,s);let m=()=>{so.get(e)===s&&so.delete(e)};return o.then(m,m),o}function xr(e){return new Promise(t=>setTimeout(t,e))}function lo(e,t,n){let l=jr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:we.SDK_VERSION,enabled:t!==!1});return l.beginCheckout(n),l}function Tr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function No(e,t,n,l,o){let s=lo(e,t,n);s.error({errorCode:l,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Tr(s)}function vs(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 $o(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function Oo(e){return!e||e.data.stripe?.publishableKey?!1:!!$o(e)?.clientId}function Bn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Cs(){if(!Bn())return null;try{let e=window.sessionStorage.getItem(jo);return e?JSON.parse(e):null}catch{return null}}function oi(e){if(Bn())try{window.sessionStorage.setItem(jo,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function zo(){if(Bn())try{window.sessionStorage.removeItem(jo)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var Vo=":idempotency-key";function Ss(e){if(!Bn())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function ai(e,t,n){if(Bn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(l){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",l)}}function qo(e){if(Bn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function ws(e){if(Bn())try{return window.sessionStorage.getItem(e+Vo)??void 0}catch{return}}function ks(e,t){if(Bn())try{window.sessionStorage.setItem(e+Vo,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function Rs(e){if(qo(e),!!Bn())try{window.sessionStorage.removeItem(e+Vo)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Is(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let l of t)e.searchParams.has(l)&&(e.searchParams.delete(l),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function ii(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 Es(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 Uo(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function uo({sessionId:e,nonce:t,createSession:n,billingApiUrl:l,telemetry:o,appearance:s,locale:m,loading:d,error:I,onComplete:N,onError:P,onDecline:_,onCountryChange:k,onZipChange:A,showPayPal:p=!0,showStripe:v=!0,enabledPaymentMethods:x,showApplePay:F=!0,showGooglePay:b=!0,debug:ce=!1,layout:K,theme:pe,buttonsTheme:ae,buttonsStyles:z,cardButtonContent:te,cardBackButtonContent:Q,cardTitleContent:me,showSecurityFooter:H,onButtonClick:J,onBeforeButtonClick:ye,enableAVS:Me,cardFieldOrder:Se,cardPreFormSlot:Pe,avsLayout:ie,className:ve,initialErrorMessage:Be=null,children:se,checkoutMode:Ee,confirmLabel:_e,renderConfirmButton:Re,onSessionCompleted:Z}){let T=(0,we.resolveBillingApiUrl)(l),de=(0,M.useMemo)(()=>(0,we.resolveTheme)(pe),[pe]),Oe=s??de?.appearance,ze=n?"embedded_checkout":"standard_checkout",fe=se?"custom_layout":K==="buttons"?"buttons_layout":"default_layout",[E,re]=(0,M.useState)(null),[oe,$e]=(0,M.useState)(null),ct=(0,M.useRef)(null),[Ve,ot]=(0,M.useState)(null),q=(0,M.useRef)(null),[G,tt]=(0,M.useState)(null),[Ae,at]=(0,M.useState)(e??""),We=e??Ae,Ke=n?"":We,[rn,g]=(0,M.useState)(!0),[ke,dt]=(0,M.useState)(null),[nt,Qe]=(0,M.useState)("full"),[He,Ze]=(0,M.useState)(!1),[xe,je]=(0,M.useState)(Be),[wt,Ge]=(0,M.useState)(null),[An,ht]=(0,M.useState)(null),[Fn,on]=(0,M.useState)(void 0),[hn,Zt]=(0,M.useState)(""),[Dn,Nt]=(0,M.useState)(!1),[kt,qt]=(0,M.useState)(!1),Gt=(0,M.useRef)(0),[Mt,jt]=(0,M.useState)("loading"),[Bt,le]=(0,M.useState)(0),en=(0,M.useRef)(!1),D=(0,M.useRef)(!1),ft=(0,M.useRef)(!1),ut=(0,M.useRef)(null),Pt=(0,M.useMemo)(()=>({checkoutMode:Ee??nt,layout:se?"unknown":K==="buttons"?"buttons":"embedded"}),[Ee,se,nt,K]),Te=(0,M.useRef)(N);Te.current=N;let qe=(0,M.useRef)(P);qe.current=P;let $n=(0,M.useRef)(_);$n.current=_,(0,M.useEffect)(()=>{Tt(oe)?.setCheckoutContext(Pt),Ve&&Ve!==oe&&Tt(Ve)?.setCheckoutContext(Pt)},[oe,Ve,Pt]);let Ln=(0,M.useRef)(Z);Ln.current=Z;let qn=(0,M.useCallback)(h=>{jt(h),!(h!=="exhausted"||ft.current)&&(ft.current=!0,qe.current?.(new we.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Zn=(0,M.useCallback)(()=>{jt("retrying"),le(h=>h+1)},[]);(0,M.useEffect)(()=>{jt("loading"),le(0),ft.current=!1},[We]),(0,M.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:we.SDK_VERSION,checkout_type:ze,checkout_layout:fe,billing_api_url:T})},[fe,ze,T]);let Vt=(0,M.useMemo)(()=>n?Pn(n,!0):"",[n]),it=(0,M.useMemo)(()=>hn===Vt?Fn:void 0,[Fn,hn,Vt]),At=(0,M.useMemo)(()=>n?Eo(n,it):void 0,[n,it]),Kt=Ee??At?.checkoutMode??"full",gt=(0,M.useMemo)(()=>At?{...At,checkoutMode:Kt}:void 0,[At,Kt]);(0,M.useEffect)(()=>{on(void 0),Zt(Vt)},[Vt]),(0,M.useEffect)(()=>{je(Be)},[Be]);let Jt=(0,M.useCallback)((h,W,j)=>{st(()=>{$n.current?.(St(h,W,j))})},[st]),Ht=(0,M.useCallback)(async(h,W)=>{je(null),ht(null),Ge("processing");let j=W?.sessionId??h.id,ge=ct.current??q.current,X=Tt(ge),ue=ge?null:lo(T,o,Pt),S={log:O=>{X?X.log(O):ue?.log(O)},error:O=>{X?X.error(O):ue?.error(O)},terminal:O=>{X?X.terminal(O):ue?.terminal(O)},performance:O=>{X?X.performance(O):ue?.performance(O)},now:()=>X?.now()??ue?.now()??0,elapsed:O=>X?.elapsed(O)??Math.max(0,(ue?.now()??O)-O)},u=S.now(),c=!!(W?.initialAutoProcessingError||W?.initialAutoProcessingPending),L=!1,y,ee=()=>{L||(L=!0,c=!0,y=S.now(),S.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ie=!1,rt=()=>{Ie||(Ie=!0,S.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),S.performance({stage:"processing",durationMs:S.elapsed(u),durationMode:"machine",paymentMethodCategory:"saved"}),y!==void 0&&S.performance({stage:"recovery",durationMs:S.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}))};S.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),S.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),c&&ee();let Ce;try{let O=ei(W?.initialAutoProcessingError),f;if(O)ee(),O.type==="paypal_redirect_required"&&ut.current?.publishableKey&&oi({sessionId:j,publishableKey:ut.current.publishableKey,paypalPublishableKey:ut.current.paypalPublishableKey}),f=await oo(O,{flopay:ct.current,paypalFlopay:q.current,attempt3DS:W?.attempt3DS,billingApiUrl:T,sessionId:j,session:h,telemetry:!1}),O.type==="paypal_redirect_required"&&zo();else if(W?.initialAutoProcessingPending){let Y=await new Xn.PaymentAPI(T,{telemetry:!1}).waitForCheckoutSessionCompletion(W.initialAutoProcessingPending.sessionId,{initialDelayMs:W.initialAutoProcessingPending.retryAfterMs});if(Y.data.session?.status!=="complete")throw new we.FloPayError("Automatic payment failed. Please try again.","api_error",{code:Y.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});f={status:"succeeded"}}else{if(W?.initialAutoProcessingError)throw Un(W.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:W.initialAutoProcessingError.checkoutMethod});if(W?.fromCreateSession)return W?.fallbackToFull&&(Qe("full"),ii("full")),!1;{let U=await dr({billingApiUrl:T,sessionId:j,session:h,telemetry:!1});U.type==="success"?f=U.result:(ee(),U.type==="paypal_redirect_required"&&ut.current?.publishableKey&&oi({sessionId:j,publishableKey:ut.current.publishableKey,paypalPublishableKey:ut.current.paypalPublishableKey}),f=await oo(U,{flopay:ct.current,paypalFlopay:q.current,attempt3DS:W?.attempt3DS,billingApiUrl:T,sessionId:j,session:h,telemetry:!1}),U.type==="paypal_redirect_required"&&zo())}}j&&sr(j),rt(),c&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),S.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Ge("success"),await xr(xn),Ce=()=>Te.current?.(f)}catch(O){let f=Jn(O),U=f.checkoutMethod??_r;return je(f.message),ht(f.message),W?.fallbackToFull&&(S.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Qe("full"),ii("full")),rt(),!!(f.declineCode||f.code?.toLowerCase().includes("declin"))?S.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):f.type==="validation_error"?S.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):S.error({errorCode:c?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:c?"recovery":"processing",paymentMethodCategory:"saved"}),st(()=>qe.current?.(f)),Jt(U,f,{code:f.code,declineCode:f.declineCode}),Ge("error"),await Promise.allSettled([xr(Cn),W?.ensureProvidersReady?W.ensureProvidersReady():Promise.resolve()]),c&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{rt(),ue&&Tr(ue),Ge(null),ht(null)}return st(Ce),!0},[Jt,st,Jn,T,o,Pt]);(0,M.useEffect)(()=>{if(typeof window>"u"||D.current)return;let h=new URLSearchParams(window.location.search),W=h.get("payment_intent_client_secret");if(!W)return;let j=Cs();j&&(D.current=!0,(async()=>{let ge,X=0;je(null),ht(null),Ge("processing"),Ze(!0);try{if(h.get("redirect_status")==="failed")throw Object.assign(new we.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ue,paypalFlopay:S}=await io({publishableKey:j.publishableKey,paypalPublishableKey:j.paypalPublishableKey,billingApiUrl:T,locale:m,telemetry:o});ge=Tt(S??ue),X=ge?.now()??0,ge?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let u=(S??ue)?.getRawProvider();if(!u)throw Object.assign(new we.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:c,error:L}=await u.retrievePaymentIntent(W);if(L)throw Object.assign(new we.FloPayError(L.message??"Failed to retrieve PayPal payment status.","api_error",{code:L.code}),{checkoutMethod:"paypal"});let y=Ba(c?.status);if(!c||y==="failed")throw Object.assign(new we.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let ee=typeof c.payment_method=="string"?c.payment_method:c.payment_method?.id,Ie=y;if(j.sessionId){let O=(await new Xn.PaymentAPI(T,{telemetry:!1}).getUnifiedCheckoutSession(j.sessionId)).data.session;if(O&&O.status!=="complete"){let f=await dr({billingApiUrl:T,sessionId:j.sessionId,session:O,telemetry:!1,tokenizedData:{id:ee??c.id,type:"card",threeDSecureActionResultTokenId:c.id,isPaypal:!0}});if(f.type!=="success")throw Object.assign(new we.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Ie=f.result.status}}j.sessionId&&sr(j.sessionId),ge?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.performance({stage:"redirect_resume",durationMs:ge.elapsed(X),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ge("success"),await xr(xn),st(()=>Te.current?.({status:Ie,paymentIntentId:c.id,paymentMethodId:ee,checkoutMethod:"paypal"}))}catch(ue){let S=Jn(ue),u=S.checkoutMethod??"paypal",c=!!(S.declineCode||S.code?.toLowerCase().includes("declin"));if(ge)ge.performance({stage:"redirect_resume",durationMs:ge.elapsed(X),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),c?ge.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ge.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(c){let L=lo(T,o,Pt);L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Tr(L)}else No(T,o,Pt,"REDIRECT_RESUME_FAILED","redirect_resume");je(S.message),ht(S.message),st(()=>qe.current?.(S)),Jt(u,S,{code:S.code,declineCode:S.declineCode}),Ge("error"),await xr(Cn)}finally{zo(),Is(),Ge(null),ht(null),Ze(!1)}})())},[Jt,st,m,Jn,T,o]);let an=(0,M.useRef)(null);function Pn(h,W=!1){let j=h?.account?.email?.trim().toLowerCase()??"",ge={c:h?.clientId,cur:h?.currency??"",a:{e:j,u:j?"":h?.account?.userId??"",country:h?.account?.country??""},successUrl:h?.successUrl,cancelUrl:h?.cancelUrl,p:h?.products?.map(S=>Uo(`${S.type??""}:${S.code??S.providerItemId??S.providerPlanId??""}`,S)).sort(),i:h?.items?.map(S=>Uo(S.code??S.providerItemId??"",S)).sort(),s:h?.subscriptions?.map(S=>Uo(S.code??S.providerPlanId??"",S)).sort(),couponCodes:h?.couponCodes?[...h.couponCodes].sort():void 0,...W?{tagsData:h?.tagsData,utmMetadata:h?.utmMetadata,tokenizedData:h?.tokenizedData,checkoutMode:h?.checkoutMode??"full"}:{}},X=JSON.stringify(ge),ue=0;for(let S=0;S<X.length;S++)ue=(ue<<5)-ue+X.charCodeAt(S)|0;return`flopay_session_${Math.abs(ue).toString(36)}`}let Rt=(0,M.useMemo)(()=>gt?Pn(gt):"",[gt]),Ot=(0,M.useRef)(gt);Ot.current=gt,(0,M.useEffect)(()=>{at(e??"")},[e]),(0,M.useEffect)(()=>{en.current=!1,je(Be),ht(null),Ge(null)},[Rt,Be,e]);async function Le(h,W){let j=lo(T,o,Pt),ge=new Xn.PaymentAPI(T,{telemetry:!1}),X=!1;try{let ue=h.idempotencyKey!==void 0?(0,we.resolveIdempotencyKey)(h.idempotencyKey):void 0,S=ue??ws(W),u,c=!1,L=Ss(W);j.log({name:L?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let y=L?.sid??null,ee=null,Ie;if(y)try{if(ee=await ge.getUnifiedCheckoutSession(y,L?.nonce),ee.data.session?.status==="complete"){if(xo(y))return{sid:y,result:ee};Rs(W),y=null,ee=null,c=!0}}catch{j.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),qo(W),y=null}if(!y){!ue&&(c||!S)&&(S=(0,we.resolveIdempotencyKey)(),u=S),S&&ks(W,S);let rt=j.now(),Ce=0;j.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let O={...h,idempotencyKey:S,avsCheck:!!Me,avsConfig:typeof Me=="object"?Me:void 0,checkoutType:"embedded_checkout",checkoutLayout:se?"custom_layout":K==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(O,Xn.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Y=>{Ce=Math.max(Ce,Y)}}});let f=()=>{j.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),j.performance({stage:"session_create",durationMs:j.now()-rt,durationMode:"machine",requestCategory:"session_create",attempt:Ce,statusClass:"2xx"})},U=Y=>{let Ye=(0,we.classifyTelemetryFailure)(Y,"CHECKOUT_SESSION_CREATE_FAILED","unknown");j.performance({stage:"session_create",durationMs:j.now()-rt,durationMode:"machine",requestCategory:"session_create",attempt:Ce,statusClass:Ye.statusClass}),Y instanceof we.FloPayError&&Y.type==="validation_error"?j.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):Ye.statusClass==="4xx"?j.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):j.error({...Ye,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if((0,we.isDetachedSessionEligible)(O)){let Y=await ge.createDetachedSession(O);Y.claimed.catch(()=>{}),ee=Y.shell,y=Y.sessionId,Ie=Y.claimed.then(Ye=>{let Et=Ye.data.session?.id??Y.sessionId;return Et&&ai(W,Et,Ye.data.session?.clientSecret??Y.nonce),f(),Ye},Ye=>{throw qo(W),U(Ye),Ye}).finally(()=>Tr(j)),Ie.catch(()=>{}),X=!0,j.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),j.performance({stage:"session_shell",durationMs:j.now()-rt,durationMode:"machine",requestCategory:"session_create",attempt:Ce,statusClass:"2xx",paymentMethodCategory:"card"})}else ee=await ge.createAndFetchSession(O),f()}catch(Y){throw U(Y),Y}y=ee.data.session?.id??y??"",y&&!Ie&&ai(W,y,ee.data.session?.clientSecret)}return{sid:y??"",result:ee,sdkGeneratedIdempotencyKey:u,...Ie?{claimed:Ie}:{}}}finally{X||Tr(j)}}let bt=(0,M.useCallback)(async(h,W)=>{let j=Ot.current;if(!j)throw new we.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ge=Eo(j,h),X=Pn(ge),ue=co.get(X);if(!ue){let c={promise:Le(ge,X),consumers:0,settled:!1};ue=c,co.set(X,c);let L=()=>{c.settled=!0,ri(X,c)};c.promise.then(L,L)}ue.consumers+=1;let S=!1,u=()=>{S||(S=!0,ue.consumers-=1,ri(X,ue))};W?.(u);try{let c=await ue.promise;an.current=X,h&&(Zt(Vt),on(f=>Ta(f,h)));let{sid:L,result:y,claimed:ee}=c;if(re(y),y.data.session&&tt(y.data.session),L&&at(L),ee){let f=Gt.current+=1;qt(!0),ee.then(U=>{Gt.current===f&&(re(U),U.data.session&&tt(U.data.session),qt(!1))},U=>{Gt.current===f&&(qt(!1),dt(U instanceof we.FloPayError?U:new we.FloPayError(U instanceof Error?U.message:"Failed to create session","api_error")))})}else Gt.current+=1,qt(!1);let{publishableKey:Ie,paypalPublishableKey:rt}=ao(y),{flopay:Ce,paypalFlopay:O}=await io({publishableKey:Ie,paypalPublishableKey:rt,billingApiUrl:T,locale:m,telemetry:o});return ct.current=Ce,$e(Ce),q.current=O,ot(O),g(!1),c}catch(c){throw an.current===X&&(an.current=null),c}finally{W||u()}},[m,T,o,Pt]),vt=(0,M.useRef)(Ht);vt.current=Ht;let bn=(0,M.useRef)(bt);bn.current=bt;let jn=(0,M.useCallback)(async h=>{if(!Es(h)||Dn)return{sessionId:Ae,session:G};Nt(!0);try{let W=await bt(h);return{sessionId:W.sid,session:W.result.data.session??null}}finally{Nt(!1)}},[bt,Dn,Ae,G]);(0,M.useEffect)(()=>{let h=!1,W;if(dt(null),Rt){let X=Ot.current;return Qe(Kt),g(!1),an.current===Rt?()=>{h=!0}:(tt(Ma(X,Ee)),(async()=>{let ue=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),S=Kt==="auto"&&!en.current&&!ue;S&&(je(null),ht(null),Ge("processing"));try{let u=await bn.current(void 0,ee=>{W=ee}),c=u.result.data.session??null;ut.current=ao(u.result);let L=Oo(u.result),y=xo(u.sid||c?.id);if(!h&&S&&c&&!L&&!y){en.current=!0,await bs(Rt,u.sdkGeneratedIdempotencyKey,()=>vt.current(c,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:u.result.autoProcessingError,initialAutoProcessingPending:u.result.autoProcessingPending,autoProcessingAttempted:u.result.autoProcessingAttempted,sessionId:u.sid||c.id}));return}!h&&S&&((L||y)&&(en.current=!0),Ge(null),ht(null))}catch(u){if(h)return;let c=u instanceof we.FloPayError||typeof u=="object"&&u!==null&&"code"in u?u.code:void 0;if(S&&c==="session_auto_completed"){en.current=!0,Ge("success"),await xr(xn),h||(st(()=>{Te.current?.({status:"succeeded"})}),Ge(null),ht(null));return}S&&(Ge(null),ht(null));let L=u instanceof we.FloPayError?u:new we.FloPayError(u instanceof Error?u.message:"Failed to create session","api_error");dt(L)}finally{W?.(),W=void 0}})(),()=>{h=!0,W?.()})}g(!0);async function j(){let X=!1;try{let S=await new Xn.PaymentAPI(T,{telemetry:!1}).getUnifiedCheckoutSession(We,t);if(h)return;re(S);let u=S.data.session??null;if(tt(u),!u)throw new we.FloPayError("No session data returned","api_error");if(u.status==="complete"){g(!1),st(()=>{Ln.current?.(u.successUrl??"")});return}if(u.status==="expired")throw new we.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});X=!0;let c=Ee??u.checkoutMode??"full";Qe(c);let L=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),y=Oo(S);if(c==="auto"&&!en.current&&!L&&!y){en.current=!0;let ee=ge(S);try{if(await vt.current(u,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ee,sessionId:We||u.id}),h)return;await ee,h||g(!1);return}catch{if(h)return;await ee,h||g(!1);return}}await ge(S),h||g(!1)}catch(ue){if(h)return;ue instanceof we.FloPayError?!X&&!vs(ue)&&No(T,o,Pt,"NETWORK_REQUEST_FAILED","session_read"):No(T,o,Pt,"INTERNAL_SDK_ERROR","checkout_mount");let S=ue instanceof we.FloPayError?ue:new we.FloPayError(ue instanceof Error?ue.message:"Failed to initialize checkout","api_error");dt(S),g(!1)}}async function ge(X){let{publishableKey:ue,paypalPublishableKey:S}=ao(X);ut.current={publishableKey:ue,paypalPublishableKey:S};let{flopay:u,paypalFlopay:c}=await io({publishableKey:ue,paypalPublishableKey:S,billingApiUrl:T,locale:m,telemetry:o});ct.current=u,$e(u),q.current=c,ot(c)}return j(),()=>{h=!0}},[Ee,Rt,Kt,Ke,st,t]);let Wt=(0,M.useCallback)(async()=>{if(!(He||!G)){Ze(!0),je(null);try{await Ht(G,{attempt3DS:!0,fallbackToFull:!0,sessionId:We||G.id})}finally{Ze(!1)}}},[We,He,Ht,G]),Xt=$o(E),Ft=Oo(E),Rn=(0,M.useMemo)(()=>{if(!E||!G||!E.data.stripe?.publishableKey)return;let h={appearance:Oe,paymentMethodCreation:"manual",billingApiUrl:T};if(E.data.stripe?.clientSecret)h.clientSecret=E.data.stripe.clientSecret;else{let W=(0,we.buildCheckoutDisplayData)(G).total;h.amount=Math.round(W*100)||G.amount,h.currency=G.currency?.toLowerCase()}return h},[E,G,Oe,T]),Nn=!!(n&&!se&&K==="buttons"&&ye&&Kt==="full"),sn=(0,M.useMemo)(()=>({session:G,loading:rn,error:ke,checkoutMode:nt,inlineSessionDraft:gt,applyInlineSessionPatch:Nn?jn:void 0,inlineSessionPatchProcessing:Dn,claimPending:kt}),[G,rn,ke,nt,gt,Nn,jn,Dn,kt]),Qt=!!n&&K==="buttons"&&!Ft&&(!oe||!Rn),It=wt?(0,w.jsx)(Sn,{status:wt,errorMessage:An}):null;if(rn){if(d)return(0,w.jsxs)(w.Fragment,{children:[d,It]});if(K==="buttons"){let h=de?.buttonsLayout?.cardButton?.borderRadius??de?.appearance.variables?.borderRadius??8,W=j=>(0,w.jsx)("div",{style:{height:j,borderRadius:h,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[p&&W(ur),v&&(F||b)&&W(ur),v&&W(ur),(0,w.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),It]})}return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,w.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,w.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),It]})}return ke?I?(0,w.jsx)(dn.Provider,{value:sn,children:I(ke)}):(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:ke.message})}):Qt?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)(xs,{onButtonClick:J,showPayPal:p,showStripe:v,showApplePay:F,showGooglePay:b,theme:pe,buttonsTheme:ae,buttonsStyles:z,cardButtonContent:te,cardBackButtonContent:Q,cardTitleContent:me})}),It]}):Ft&&G&&Xt?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsxs)("div",{className:ve,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[xe&&(0,w.jsx)(ar,{icon:!1,children:xe}),Mt==="retrying"&&(0,w.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Mt==="exhausted"&&(0,w.jsxs)("div",{role:"alert",children:[(0,w.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,w.jsx)("button",{type:"button",onClick:Zn,children:"Retry PayPal"})]}),Mt!=="exhausted"&&(0,w.jsx)("div",{"aria-hidden":Mt==="retrying"?!0:void 0,style:Mt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,w.jsx)(za,{sessionId:We,nonce:G.clientSecret||void 0,billingApiUrl:T,email:G.customer?.email,clientId:Xt.clientId,environment:Xt.environment,currency:(G.currency??"usd").toUpperCase(),isSubscription:G.mode==="subscription",onComplete:N,onErrorChange:je,onDecline:_,onButtonClick:J,onInitializationStateChange:qn,allowAutomaticRetry:Bt===0,session:G,telemetry:o,telemetryContext:Pt,debug:ce},`paypal-init-${Bt}`)})]})}),It]}):!oe||!Rn?(0,w.jsx)(w.Fragment,{children:It}):nt==="confirm"?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)(Sr,{flopay:oe,paypalFlopay:Ve,options:Rn,children:(0,w.jsxs)("div",{className:ve,children:[xe&&(0,w.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:xe}),Re?Re({onConfirm:Wt,isProcessing:He}):(0,w.jsx)("button",{type:"button",onClick:Wt,disabled:He,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:He?"not-allowed":"pointer",opacity:He?.6:1},children:He?"Processing...":_e??"Confirm Purchase"})]})})}),It]}):(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)(Sr,{flopay:oe,paypalFlopay:Ve,options:Rn,children:se?(0,w.jsxs)(w.Fragment,{children:[xe&&(0,w.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:xe}),(0,w.jsx)(_s,{sessionId:We,nonce:G?.clientSecret||void 0,billingApiUrl:T,session:G,children:se})]}):(0,w.jsx)(no,{sessionId:We,nonce:G?.clientSecret||void 0,email:G?.customer?.email,userId:G?.customer?.id,firstName:G?.customer?.firstName,lastName:G?.customer?.lastName,totalAmount:G?Math.round((0,we.buildCheckoutDisplayData)(G).total*100):0,currency:G?.currency?.toLowerCase()??"usd",onComplete:N,onError:P,onDecline:_,error:xe,onErrorChange:je,showPayPal:p,showStripe:v,enabledPaymentMethods:x??E?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:E?.data.stripe?.enabledPaymentMethodCountries,showApplePay:F,showGooglePay:b,layout:K,theme:pe,buttonsTheme:ae,buttonsStyles:z,appearance:Oe,cardButtonContent:te,cardBackButtonContent:Q,cardTitleContent:me,onButtonClick:J,onBeforeButtonClick:ye,enableAVS:Me,...Se?{cardFieldOrder:Se}:{},...Pe?{cardPreFormSlot:Pe}:{},avsLayout:ie,country:G?.customer?.country,city:G?.customer?.city,state:G?.customer?.state,onCountryChange:k,onZipChange:A,avsCheck:!!Me,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:se?"custom_layout":K==="buttons"?"buttons_layout":"default_layout",className:ve,directPaypal:$o(E),isSubscription:G?.mode==="subscription",session:G,dataAttachmentPending:kt,debug:ce})})}),It]})}function _s({sessionId:e,nonce:t,billingApiUrl:n,session:l,children:o}){return(0,w.jsx)(w.Fragment,{children:M.default.Children.map(o,s=>{if(!M.default.isValidElement(s))return s;let m=s.props,d={};return m.sessionId||(d.sessionId=e),!m.nonce&&t&&(d.nonce=t),m.billingApiUrl||(d.billingApiUrl=n),l?.customer&&(m.email||(d.email=l.customer.email),m.userId||(d.userId=l.customer.id),m.firstName||(d.firstName=l.customer.firstName),m.lastName||(d.lastName=l.customer.lastName)),Object.keys(d).length===0?s:M.default.cloneElement(s,d)})})}function xs({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:l,showGooglePay:o,theme:s,buttonsTheme:m,buttonsStyles:d,cardButtonContent:I,cardBackButtonContent:N,cardTitleContent:P}){let[_,k]=(0,M.useState)(!1),A=(0,M.useMemo)(()=>(0,we.resolveTheme)(s),[s]),p=(0,M.useMemo)(()=>{let b=A?.buttonsLayout??(0,we.resolveButtonsLayoutTheme)(m);return d?{...b,...d,cardButton:{...b.cardButton,...d.cardButton},cardFormContainer:{...b.cardFormContainer,...d.cardFormContainer},backButton:{...b.backButton,...d.backButton},backButtonIcon:{...b.backButtonIcon,...d.backButtonIcon},submitButton:{...b.submitButton,...d.submitButton},title:{...b.title,...d.title}}:b},[A,m,d]),v=A?.buttonsLayout?.cardButton?.borderRadius??A?.appearance.variables?.borderRadius??8,x=b=>(0,w.jsx)("div",{style:{height:b,borderRadius:v,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),F=I===void 0?{boxSizing:"border-box",height:ur,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let b=p.cardInputBorder??"#e5e7eb",ce=p.cardInputBackground??"white",K=nr(N),pe=nr(P);return(0,w.jsxs)("div",{style:{backgroundColor:p.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...p.cardFormContainer},children:[(0,w.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,w.jsxs)("button",{type:"button",onClick:()=>k(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:K?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...p.backButton},children:[(0,w.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...p.backButtonIcon},children:(0,w.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,w.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,w.jsx)(or,{content:N})]}),pe?(0,w.jsx)("div",{style:{flex:1}}):(0,w.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...p.title},children:(0,w.jsx)(wr,{content:P})})]}),(0,w.jsx)("div",{style:{backgroundColor:ce,border:`1px solid ${b}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsxs)("div",{style:{display:"flex"},children:[(0,w.jsx)("div",{style:{flex:1,backgroundColor:ce,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsx)("div",{style:{flex:1,backgroundColor:ce,borderTop:"none",borderRight:`1px solid ${b}`,borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,w.jsx)("div",{style:{backgroundColor:ce,border:`1px solid ${b}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...p.submitButton,opacity:.5}}),(0,w.jsx)("style",{children:`
40
+ `)}):null,va=Le==="apm-expanding"||Le==="apm-form"||Le==="apm-collapsing",Ur=Le==="apm-expanding"?`flopay-card-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:Le==="apm-collapsing"?`flopay-card-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,$r=vt?{...fo,paymentMethodTypes:[vt]}:null;if(ae==="buttons"){let a=Le==="buttons"||Le==="expanding"||Le==="apm-expanding",C=Le==="expanding"||Le==="card"||Le==="collapsing",V=H===void 0?{boxSizing:"border-box",height:eo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ne=Le==="expanding"||Le==="apm-expanding"?`flopay-buttons-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Le==="collapsing"||Le==="apm-collapsing"?`flopay-buttons-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,$=Le==="expanding"?`flopay-card-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:Le==="collapsing"?`flopay-card-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,i.jsxs)("form",{onSubmit:Po,className:k,style:{position:"relative"},children:[(0,i.jsx)(Bo,{}),It&&(0,i.jsx)(Sn,{status:It,errorMessage:c}),(0,i.jsxs)("div",{style:{display:"grid"},children:[(0,i.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!ne?is:{},...ne?{animation:ne,pointerEvents:"none"}:{}},children:[Pa("flopay-direct-paypal-gate-debug"),ba("flopay-stripe-gate-debug"),yr&&Ve&&(0,i.jsxs)(i.Fragment,{children:[X&&(0,i.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,i.jsx)(Ir,{sessionId:e,nonce:t,billingApiUrl:u,email:f.email,clientId:Ve.clientId,environment:Ve.environment,currency:$e.toUpperCase(),isSubscription:ot,onTokenizedBody:tn,onComplete:s,onErrorChange:he,onDecline:d,onTechnicalFailure:er,onButtonClick:Se,runBeforeButtonClick:cn,isProcessing:Ce,onLoadStateChange:go,onInitializationStateChange:ho,session:q??null,existingOrderId:X?.orderId,debug:tt},X?.orderId??"fresh")]}),fr&&(0,i.jsx)(lt.Elements,{stripe:Ye,options:Wo,children:(0,i.jsx)(Ha,{sessionId:e,nonce:t,email:f.email,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:he,isProcessing:Ce,onButtonClick:Se,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:Xo,placeholderBorderRadius:Kn})}),gr?(0,i.jsx)(lt.Elements,{stripe:Y,options:Ho,children:(0,i.jsx)(Wa,{sessionId:e,nonce:t,email:f.email,billingApiUrl:u,intentKind:oe>0?"payment":"setup",expressMethods:Fr,onTokenizedBody:tn,onErrorChange:he,onButtonClick:Se,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:Zo,placeholderBorderRadius:Kn})}):oa?(0,i.jsx)("div",{style:{height:eo,borderRadius:Kn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,hr&&(0,i.jsx)(Ya,{sessionId:e,nonce:t,email:f.email,billingName:[f.firstName,f.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,paymentElementMethods:Dr,stripeInstance:Y,paymentElementBaseOptions:fo,onTokenizedBody:tn,onErrorChange:he,onButtonClick:Se,onDecline:d,runBeforeButtonClick:cn,onLoadStateChange:ta,isProcessing:Ce,submitButtonColor:Hn,submitButtonBorderRadius:pt,submitButtonStyle:y.submitButton,onExpandApm:sn,expandedApmMethod:vt,themeId:z,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:Kn}}),qe&&(0,i.jsx)("button",{type:"button",onClick:async()=>{Ce||!(await cn("card")).proceed||(Se?.("card"),Rn())},disabled:Ce,style:{width:"100%",...V,...y.cardButton,...Do({themeBundle:L,resolvedPrimaryColor:Hn,resolvedBorderRadius:pt,submitButtonStyle:y.submitButton,explicitPrimaryColor:Yt?.colorPrimary}),fontSize:y.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ce?"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:Ce?.6:1},onMouseEnter:be=>{!Ce&&(L||Yt?.colorPrimary)&&(be.currentTarget.style.backgroundColor=Bi)},onMouseLeave:be=>{(L||Yt?.colorPrimary)&&(be.currentTarget.style.backgroundColor=Hn)},onMouseDown:be=>{be.currentTarget.style.transform="scale(0.985)"},onMouseUp:be=>{be.currentTarget.style.transform="scale(1)"},children:(0,i.jsx)(rr,{content:H})}),c&&Le==="buttons"&&(0,i.jsx)(ar,{margin:"0.25rem 0",styleOverride:y.errorBanner,children:c})]}),qe&&C&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...$?{animation:$}:{},...Le==="collapsing"?{pointerEvents:"none"}:{}},children:ha}),F&&va&&vt&&$r&&Y&&(0,i.jsx)("div",{style:{gridArea:"1 / 1",...Ur?{animation:Ur}:{},...Le==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:Co,borderRadius:Ro,...Cr,padding:ko},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,i.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Qt,style:{display:"inline-flex",alignItems:"center",gap:So?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:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...y.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(or,{content:J})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:wo,paddingRight:80,...y.title},children:`Pay with ${(0,R.getStripeMethodDisplayName)(vt)}`})]}),(0,i.jsx)(lt.Elements,{stripe:Y,options:$r,children:(0,i.jsx)(Ao,{method:vt,sessionId:e,nonce:t,email:f.email,billingName:[f.firstName,f.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:he,onDecline:d,onCancel:Qt,runBeforeButtonClick:cn,onButtonClick:Se,isProcessing:Ce,submitButtonColor:Hn,submitButtonBorderRadius:pt,submitButtonStyle:y.submitButton,errorText:c})},vt)]})})]})]})}return va&&vt&&$r&&Y&&F?(0,i.jsxs)("form",{onSubmit:Po,className:k,style:{position:"relative"},children:[(0,i.jsx)(Bo,{}),It&&(0,i.jsx)(Sn,{status:It,errorMessage:c}),(0,i.jsx)("div",{style:{...Ur?{animation:Ur}:{},...Le==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,i.jsxs)("div",{style:{backgroundColor:Co,borderRadius:Ro,...Cr,padding:ko},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,i.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Qt,style:{display:"inline-flex",alignItems:"center",gap:So?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:[(0,i.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...y.backButtonIcon},children:(0,i.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,i.jsx)(or,{content:J})]}),(0,i.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:wo,paddingRight:80,...y.title},children:`Pay with ${(0,R.getStripeMethodDisplayName)(vt)}`})]}),(0,i.jsx)(lt.Elements,{stripe:Y,options:$r,children:(0,i.jsx)(Ao,{method:vt,sessionId:e,nonce:t,email:f.email,billingName:[f.firstName,f.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:he,onDecline:d,onCancel:Qt,runBeforeButtonClick:cn,onButtonClick:Se,isProcessing:Ce,submitButtonColor:Hn,submitButtonBorderRadius:pt,submitButtonStyle:y.submitButton,errorText:c})},vt)]})})]}):(0,i.jsxs)("form",{onSubmit:Po,className:k,style:{position:"relative"},children:[(0,i.jsx)(Bo,{}),It&&(0,i.jsx)(Sn,{status:It,errorMessage:c}),(0,i.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Pa("flopay-direct-paypal-gate-debug-default"),ba("flopay-stripe-gate-debug-default"),yr&&Ve&&(0,i.jsxs)(i.Fragment,{children:[X&&(0,i.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,i.jsx)(Ir,{sessionId:e,nonce:t,billingApiUrl:u,email:f.email,clientId:Ve.clientId,environment:Ve.environment,currency:$e.toUpperCase(),isSubscription:ot,onTokenizedBody:tn,onComplete:s,onErrorChange:he,onDecline:d,onTechnicalFailure:er,onButtonClick:Se,runBeforeButtonClick:cn,isProcessing:Ce,onLoadStateChange:go,onInitializationStateChange:ho,session:q??null,existingOrderId:X?.orderId,debug:tt},X?.orderId??"fresh")]}),fr&&(0,i.jsx)(lt.Elements,{stripe:Ye,options:Wo,children:(0,i.jsx)(Ha,{sessionId:e,nonce:t,email:f.email,billingApiUrl:u,onTokenizedBody:tn,onErrorChange:he,isProcessing:Ce,onButtonClick:Se,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:Xo,placeholderBorderRadius:Kn})}),gr&&(0,i.jsx)(lt.Elements,{stripe:Y,options:Ho,children:(0,i.jsx)(Wa,{sessionId:e,nonce:t,email:f.email,billingApiUrl:u,intentKind:oe>0?"payment":"setup",expressMethods:Fr,onTokenizedBody:tn,onErrorChange:he,onButtonClick:Se,onDecline:d,onTechnicalFailure:er,runBeforeButtonClick:cn,onLoadStateChange:Zo,placeholderBorderRadius:Kn})}),hr&&(0,i.jsx)(Ya,{sessionId:e,nonce:t,email:f.email,billingName:[f.firstName,f.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:u,paymentElementMethods:Dr,stripeInstance:Y,paymentElementBaseOptions:fo,onTokenizedBody:tn,onErrorChange:he,onButtonClick:Se,onDecline:d,runBeforeButtonClick:cn,onLoadStateChange:ta,isProcessing:Ce,submitButtonColor:Hn,submitButtonBorderRadius:pt,submitButtonStyle:y.submitButton,themeId:z,onExpandApm:sn,expandedApmMethod:vt,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:Kn}})]}),qe&&(Ri||ki||Ii)&&(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,i.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,i.jsx)("span",{children:"or pay with card"}),(0,i.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),qe&&ha]})}var cr=require("@flopay/js"),Xe=require("@flopay/shared");var _r="card";async function ys(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:m}=await e.retrieveSetupIntent(t);return{error:m,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:l,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:l??null}}async function fs(e,t,n,l){if(l){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:m,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:m??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:s}=await e.confirmCardPayment(t,n);return{error:s,intent:o??null}}function kn(e,t){return Object.assign(e,{checkoutMethod:t})}function ei(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 gs(e){return e.status==="succeeded"||e.status==="declined"}async function ti(e){if(typeof document>"u"||typeof window>"u")throw new Xe.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Xe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,l=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,s=async()=>{let P=new AbortController,_=()=>P.abort();e.signal?.aborted?P.abort():e.signal?.addEventListener("abort",_);let k=window.setTimeout(()=>P.abort(),l);try{let A=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:P.signal});if(!A.ok)return{status:"unknown"};let p=await A.json().catch(()=>null);return hs(p)}catch{return{status:"unknown"}}finally{window.clearTimeout(k),e.signal?.removeEventListener("abort",_)}},m=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let I=document.createElement("iframe");I.setAttribute("title","Card authentication"),I.setAttribute("allow","payment"),I.tabIndex=0,I.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),I.src=e.nextActionRedirectUrl,d.appendChild(I),document.body.appendChild(d),I.focus();let N=null;try{N=new URL(e.billingApiUrl,window.location.href).origin}catch{N=null}try{let P=await new Promise((_,k)=>{let A=!1,p=0,v=0,x=0,F=!1,b=()=>{window.clearTimeout(p),window.clearInterval(v),window.clearTimeout(x),window.removeEventListener("message",ae),I.removeEventListener("load",K),e.signal?.removeEventListener("abort",pe)},ce=async()=>{if(!(A||F)){F=!0;try{let z=await s();if(A||!gs(z))return;A=!0,b(),_(z)}finally{F=!1}}},K=()=>{window.clearTimeout(x),x=window.setTimeout(()=>{ce()},250)},pe=()=>{A||(A=!0,b(),k(new Xe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ae=z=>{if(z.source!==I.contentWindow||N&&z.origin!==N)return;let te=z.data;!te||typeof te!="object"||te.source!=="flopay-vault-3ds-return"||A||(A=!0,b(),_(null))};p=window.setTimeout(()=>{A||(A=!0,b(),k(new Xe.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),v=window.setInterval(()=>{ce()},n),I.addEventListener("load",K),window.addEventListener("message",ae),e.signal?.addEventListener("abort",pe),e.signal?.aborted&&pe()});return P||await s()}finally{d.parentNode?.removeChild(d),m?.isConnected&&m.focus()}}function hs(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Un(e,t="Payment failed. Please try again.",n){let l=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,s=On(o)??o;return kn(new Xe.FloPayError(s,"api_error",{code:e?.gatewayErrorCode}),l)}function Lo(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ro(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Ps(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 ni(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ro(o)))return o;let l=e?.data;if(l&&typeof l=="object"){let o=l,s=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let d of s)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||ro(d)))return d;let m=o.gateways;if(m&&typeof m=="object"){let d=m.stripe;if(d&&typeof d=="object"){let I=d,N=[I.stripeClientSecret,I.clientSecret];for(let P of N)if(typeof P=="string"&&P.length>0&&(!t?.requirePaymentIntentClientSecret||ro(P)))return P}}}}async function bs({billingApiUrl:e,sessionId:t,nonce:n,responseJson:l}){let o=ni(l,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new cr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ro(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function dr({billingApiUrl:e,sessionId:t,session:n,nonce:l,tokenizedData:o,returnUrl:s,telemetry:m}){let d=e.replace(/\/+$/,""),I=t??n.id,N=l??n.clientSecret,P=n.customer?.id??n.accountData?.userId??"",_=n.customer?.email??n.accountData?.email??"",k=n.customer?.firstName??n.accountData?.firstName??"",A=n.customer?.lastName??n.accountData?.lastName??"",p=n.customer?.country??n.accountData?.country??void 0,v=n.customer?.zip??n.accountData?.zip??void 0,x=new cr.PaymentAPI(d,m===!1?{telemetry:!1}:void 0),F=await Ps(()=>x.processPayment(P,{sessionId:I,nonce:N,tokenizedData:o,accountData:{userId:P,email:_,firstName:k,lastName:A,country:p,zip:v},returnUrl:s??Lo(n)}));if(F.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Gr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let b=await F.json().catch(()=>null);if(b?.type==="paypal_redirect_required"||b?.type==="3ds_required"){let ce=ni(b);if(!ce)throw new Xe.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:b.type,threeDSecureToken:ce,paymentMethodId:b.paymentMethodId}}if(b?.gatewayErrorCode==="authentication_required"){let ce=await bs({billingApiUrl:d,sessionId:I,nonce:N,responseJson:b});if(ce)return ce;throw kn(new Xe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new Xe.FloPayError(b?.message??"Payment failed. Please try again.","api_error",{code:b?.code??b?.gatewayErrorCode,declineCode:b?.declineCode??b?.gatewayDeclineReason})}async function oo(e,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:m,returnUrl:d,telemetry:I}){let N=t?.getRawProvider();if(!N)throw new Xe.FloPayError("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!l||!e.threeDSecureToken)throw kn(new Xe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let P=(0,Xe.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,k=e.paymentMethodId,A=await ys(N,e.threeDSecureToken,P);if(A){if(A.error)throw kn(new Xe.FloPayError(A.error.message??`Failed to retrieve 3DS ${P?"setup":"payment"} status.`,"api_error",{code:A.error.code}),"card");let v=A.intent;!k&&v?.payment_method&&(typeof v.payment_method=="string"?k=v.payment_method:"id"in v.payment_method&&(k=v.payment_method.id??void 0))}let p=k?await fs(N,e.threeDSecureToken,{payment_method:k,return_url:d??Lo(m)??window.location.href},P):null;if(p){if(p.error)throw kn(new Xe.FloPayError(p.error.message??"3DS authentication failed.","api_error",{code:p.error.code}),"card");_=p.intent}else{let v=await N.handleNextAction({clientSecret:e.threeDSecureToken});if(v.error)throw kn(new Xe.FloPayError(v.error.message??"3DS authentication failed.","api_error",{code:v.error.code}),"card");_=(P?v.setupIntent:v.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let v=await dr({billingApiUrl:o,sessionId:s,session:m,telemetry:I,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:d});return v.type==="success"?{...v.result,paymentIntentId:v.result.paymentIntentId??_.id,paymentMethodId:v.result.paymentMethodId??k}:oo(v,{flopay:t,paypalFlopay:n,attempt3DS:l,billingApiUrl:o,sessionId:s,session:m,returnUrl:d,telemetry:I})}throw kn(new Xe.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let P=(n??t)?.getRawProvider();if(!P)throw kn(new Xe.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:k}=await P.handleNextAction({clientSecret:e.threeDSecureToken});if(k)throw kn(new Xe.FloPayError(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await P.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Lo(m)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(_)throw kn(new Xe.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Xe.FloPayError("Unsupported payment redirect state.","api_error")}function Jn(e){if(e instanceof Xe.FloPayError){let l=On(e.message);return l&&l!==e.message?Object.assign(new Xe.FloPayError(l,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=On(t)??t;return new Xe.FloPayError(n,"api_error")}function ao(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Xe.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function io({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:l,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let s=!!t&&t!==e,[m,d]=await Promise.all([(0,cr.loadFloPay)(e,{billingApiUrl:n,locale:l,telemetry:o}),s?(0,cr.loadFloPay)(t,{billingApiUrl:n,locale:l,telemetry:o}).catch(I=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",I),null)):Promise.resolve(null)]);return{flopay:m,paypalFlopay:t?s?d:m:null}}var w=require("react/jsx-runtime"),ur=44,jo="flopay_checkout_saved_payment_resume",co=new Map,so=new Map;function ri(e,t){t.settled&&t.consumers===0&&co.get(e)===t&&co.delete(e)}function vs(e,t,n){let l=so.get(e);if(l&&(!l.sdkGeneratedIdempotencyKey||!t||l.sdkGeneratedIdempotencyKey===t))return l.attempt;let o=n(),s={attempt:o,sdkGeneratedIdempotencyKey:t};so.set(e,s);let m=()=>{so.get(e)===s&&so.delete(e)};return o.then(m,m),o}function xr(e){return new Promise(t=>setTimeout(t,e))}function lo(e,t,n){let l=jr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:we.SDK_VERSION,enabled:t!==!1});return l.beginCheckout(n),l}function Tr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function No(e,t,n,l,o){let s=lo(e,t,n);s.error({errorCode:l,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Tr(s)}function Cs(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 $o(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function Oo(e){return!e||e.data.stripe?.publishableKey?!1:!!$o(e)?.clientId}function Bn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Ss(){if(!Bn())return null;try{let e=window.sessionStorage.getItem(jo);return e?JSON.parse(e):null}catch{return null}}function oi(e){if(Bn())try{window.sessionStorage.setItem(jo,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function zo(){if(Bn())try{window.sessionStorage.removeItem(jo)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var Vo=":idempotency-key";function ws(e){if(!Bn())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function ai(e,t,n){if(Bn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(l){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",l)}}function qo(e){if(Bn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function ks(e){if(Bn())try{return window.sessionStorage.getItem(e+Vo)??void 0}catch{return}}function Rs(e,t){if(Bn())try{window.sessionStorage.setItem(e+Vo,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function Is(e){if(qo(e),!!Bn())try{window.sessionStorage.removeItem(e+Vo)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Es(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let l of t)e.searchParams.has(l)&&(e.searchParams.delete(l),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function ii(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 _s(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 Uo(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function uo({sessionId:e,nonce:t,createSession:n,billingApiUrl:l,telemetry:o,appearance:s,locale:m,loading:d,error:I,onComplete:N,onError:P,onDecline:_,onCountryChange:k,onZipChange:A,showPayPal:p=!0,showStripe:v=!0,enabledPaymentMethods:x,showApplePay:F=!0,showGooglePay:b=!0,debug:ce=!1,layout:K,theme:pe,buttonsTheme:ae,buttonsStyles:z,cardButtonContent:te,cardBackButtonContent:Q,cardTitleContent:me,showSecurityFooter:H,onButtonClick:J,onBeforeButtonClick:ye,enableAVS:Me,cardFieldOrder:Se,cardPreFormSlot:Pe,avsLayout:ie,className:ve,initialErrorMessage:Be=null,children:se,checkoutMode:Ee,confirmLabel:_e,renderConfirmButton:Re,onSessionCompleted:Z}){let T=(0,we.resolveBillingApiUrl)(l),de=(0,M.useMemo)(()=>(0,we.resolveTheme)(pe),[pe]),Oe=s??de?.appearance,ze=n?"embedded_checkout":"standard_checkout",fe=se?"custom_layout":K==="buttons"?"buttons_layout":"default_layout",[E,re]=(0,M.useState)(null),[oe,$e]=(0,M.useState)(null),ct=(0,M.useRef)(null),[Ve,ot]=(0,M.useState)(null),q=(0,M.useRef)(null),[G,tt]=(0,M.useState)(null),[Ae,at]=(0,M.useState)(e??""),We=e??Ae,Ke=n?"":We,[rn,g]=(0,M.useState)(!0),[ke,dt]=(0,M.useState)(null),[nt,Qe]=(0,M.useState)("full"),[He,Ze]=(0,M.useState)(!1),[xe,je]=(0,M.useState)(Be),[wt,Ge]=(0,M.useState)(null),[An,ht]=(0,M.useState)(null),[Fn,on]=(0,M.useState)(void 0),[hn,Zt]=(0,M.useState)(""),[Dn,Nt]=(0,M.useState)(!1),[kt,qt]=(0,M.useState)(!1),Gt=(0,M.useRef)(0),[Mt,jt]=(0,M.useState)("loading"),[Bt,le]=(0,M.useState)(0),en=(0,M.useRef)(!1),D=(0,M.useRef)(!1),ft=(0,M.useRef)(!1),ut=(0,M.useRef)(null),Pt=(0,M.useMemo)(()=>({checkoutMode:Ee??nt,layout:se?"unknown":K==="buttons"?"buttons":"embedded"}),[Ee,se,nt,K]),Te=(0,M.useRef)(N);Te.current=N;let qe=(0,M.useRef)(P);qe.current=P;let $n=(0,M.useRef)(_);$n.current=_,(0,M.useEffect)(()=>{Tt(oe)?.setCheckoutContext(Pt),Ve&&Ve!==oe&&Tt(Ve)?.setCheckoutContext(Pt)},[oe,Ve,Pt]);let Ln=(0,M.useRef)(Z);Ln.current=Z;let qn=(0,M.useCallback)(h=>{jt(h),!(h!=="exhausted"||ft.current)&&(ft.current=!0,qe.current?.(new we.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Zn=(0,M.useCallback)(()=>{jt("retrying"),le(h=>h+1)},[]);(0,M.useEffect)(()=>{jt("loading"),le(0),ft.current=!1},[We]),(0,M.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:we.SDK_VERSION,checkout_type:ze,checkout_layout:fe,billing_api_url:T})},[fe,ze,T]);let Vt=(0,M.useMemo)(()=>n?Pn(n,!0):"",[n]),it=(0,M.useMemo)(()=>hn===Vt?Fn:void 0,[Fn,hn,Vt]),At=(0,M.useMemo)(()=>n?Eo(n,it):void 0,[n,it]),Kt=Ee??At?.checkoutMode??"full",gt=(0,M.useMemo)(()=>At?{...At,checkoutMode:Kt}:void 0,[At,Kt]);(0,M.useEffect)(()=>{on(void 0),Zt(Vt)},[Vt]),(0,M.useEffect)(()=>{je(Be)},[Be]);let Jt=(0,M.useCallback)((h,W,j)=>{st(()=>{$n.current?.(St(h,W,j))})},[st]),Ht=(0,M.useCallback)(async(h,W)=>{je(null),ht(null),Ge("processing");let j=W?.sessionId??h.id,ge=ct.current??q.current,X=Tt(ge),ue=ge?null:lo(T,o,Pt),S={log:O=>{X?X.log(O):ue?.log(O)},error:O=>{X?X.error(O):ue?.error(O)},terminal:O=>{X?X.terminal(O):ue?.terminal(O)},performance:O=>{X?X.performance(O):ue?.performance(O)},now:()=>X?.now()??ue?.now()??0,elapsed:O=>X?.elapsed(O)??Math.max(0,(ue?.now()??O)-O)},u=S.now(),c=!!(W?.initialAutoProcessingError||W?.initialAutoProcessingPending),L=!1,y,ee=()=>{L||(L=!0,c=!0,y=S.now(),S.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ie=!1,rt=()=>{Ie||(Ie=!0,S.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),S.performance({stage:"processing",durationMs:S.elapsed(u),durationMode:"machine",paymentMethodCategory:"saved"}),y!==void 0&&S.performance({stage:"recovery",durationMs:S.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}))};S.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),S.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),c&&ee();let Ce;try{let O=ei(W?.initialAutoProcessingError),f;if(O)ee(),O.type==="paypal_redirect_required"&&ut.current?.publishableKey&&oi({sessionId:j,publishableKey:ut.current.publishableKey,paypalPublishableKey:ut.current.paypalPublishableKey}),f=await oo(O,{flopay:ct.current,paypalFlopay:q.current,attempt3DS:W?.attempt3DS,billingApiUrl:T,sessionId:j,session:h,telemetry:!1}),O.type==="paypal_redirect_required"&&zo();else if(W?.initialAutoProcessingPending){let Y=await new Xn.PaymentAPI(T,{telemetry:!1}).waitForCheckoutSessionCompletion(W.initialAutoProcessingPending.sessionId,{initialDelayMs:W.initialAutoProcessingPending.retryAfterMs});if(Y.data.session?.status!=="complete")throw new we.FloPayError("Automatic payment failed. Please try again.","api_error",{code:Y.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});f={status:"succeeded"}}else{if(W?.initialAutoProcessingError)throw Un(W.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:W.initialAutoProcessingError.checkoutMethod});if(W?.fromCreateSession)return W?.fallbackToFull&&(Qe("full"),ii("full")),!1;{let U=await dr({billingApiUrl:T,sessionId:j,session:h,telemetry:!1});U.type==="success"?f=U.result:(ee(),U.type==="paypal_redirect_required"&&ut.current?.publishableKey&&oi({sessionId:j,publishableKey:ut.current.publishableKey,paypalPublishableKey:ut.current.paypalPublishableKey}),f=await oo(U,{flopay:ct.current,paypalFlopay:q.current,attempt3DS:W?.attempt3DS,billingApiUrl:T,sessionId:j,session:h,telemetry:!1}),U.type==="paypal_redirect_required"&&zo())}}j&&sr(j),rt(),c&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),S.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Ge("success"),await xr(xn),Ce=()=>Te.current?.(f)}catch(O){let f=Jn(O),U=f.checkoutMethod??_r;return je(f.message),ht(f.message),W?.fallbackToFull&&(S.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Qe("full"),ii("full")),rt(),!!(f.declineCode||f.code?.toLowerCase().includes("declin"))?S.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):f.type==="validation_error"?S.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):S.error({errorCode:c?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:c?"recovery":"processing",paymentMethodCategory:"saved"}),st(()=>qe.current?.(f)),Jt(U,f,{code:f.code,declineCode:f.declineCode}),Ge("error"),await Promise.allSettled([xr(Cn),W?.ensureProvidersReady?W.ensureProvidersReady():Promise.resolve()]),c&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{rt(),ue&&Tr(ue),Ge(null),ht(null)}return st(Ce),!0},[Jt,st,Jn,T,o,Pt]);(0,M.useEffect)(()=>{if(typeof window>"u"||D.current)return;let h=new URLSearchParams(window.location.search),W=h.get("payment_intent_client_secret");if(!W)return;let j=Ss();j&&(D.current=!0,(async()=>{let ge,X=0;je(null),ht(null),Ge("processing"),Ze(!0);try{if(h.get("redirect_status")==="failed")throw Object.assign(new we.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ue,paypalFlopay:S}=await io({publishableKey:j.publishableKey,paypalPublishableKey:j.paypalPublishableKey,billingApiUrl:T,locale:m,telemetry:o});ge=Tt(S??ue),X=ge?.now()??0,ge?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let u=(S??ue)?.getRawProvider();if(!u)throw Object.assign(new we.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:c,error:L}=await u.retrievePaymentIntent(W);if(L)throw Object.assign(new we.FloPayError(L.message??"Failed to retrieve PayPal payment status.","api_error",{code:L.code}),{checkoutMethod:"paypal"});let y=Ba(c?.status);if(!c||y==="failed")throw Object.assign(new we.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let ee=typeof c.payment_method=="string"?c.payment_method:c.payment_method?.id,Ie=y;if(j.sessionId){let O=(await new Xn.PaymentAPI(T,{telemetry:!1}).getUnifiedCheckoutSession(j.sessionId)).data.session;if(O&&O.status!=="complete"){let f=await dr({billingApiUrl:T,sessionId:j.sessionId,session:O,telemetry:!1,tokenizedData:{id:ee??c.id,type:"card",threeDSecureActionResultTokenId:c.id,isPaypal:!0}});if(f.type!=="success")throw Object.assign(new we.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Ie=f.result.status}}j.sessionId&&sr(j.sessionId),ge?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.performance({stage:"redirect_resume",durationMs:ge.elapsed(X),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ge("success"),await xr(xn),st(()=>Te.current?.({status:Ie,paymentIntentId:c.id,paymentMethodId:ee,checkoutMethod:"paypal"}))}catch(ue){let S=Jn(ue),u=S.checkoutMethod??"paypal",c=!!(S.declineCode||S.code?.toLowerCase().includes("declin"));if(ge)ge.performance({stage:"redirect_resume",durationMs:ge.elapsed(X),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),c?ge.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ge.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(c){let L=lo(T,o,Pt);L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Tr(L)}else No(T,o,Pt,"REDIRECT_RESUME_FAILED","redirect_resume");je(S.message),ht(S.message),st(()=>qe.current?.(S)),Jt(u,S,{code:S.code,declineCode:S.declineCode}),Ge("error"),await xr(Cn)}finally{zo(),Es(),Ge(null),ht(null),Ze(!1)}})())},[Jt,st,m,Jn,T,o]);let an=(0,M.useRef)(null);function Pn(h,W=!1){let j=h?.account?.email?.trim().toLowerCase()??"",ge={c:h?.clientId,cur:h?.currency??"",a:{e:j,u:j?"":h?.account?.userId??"",country:h?.account?.country??""},successUrl:h?.successUrl,cancelUrl:h?.cancelUrl,p:h?.products?.map(S=>Uo(`${S.type??""}:${S.code??S.providerItemId??S.providerPlanId??""}`,S)).sort(),i:h?.items?.map(S=>Uo(S.code??S.providerItemId??"",S)).sort(),s:h?.subscriptions?.map(S=>Uo(S.code??S.providerPlanId??"",S)).sort(),couponCodes:h?.couponCodes?[...h.couponCodes].sort():void 0,...W?{tagsData:h?.tagsData,utmMetadata:h?.utmMetadata,tokenizedData:h?.tokenizedData,checkoutMode:h?.checkoutMode??"full"}:{}},X=JSON.stringify(ge),ue=0;for(let S=0;S<X.length;S++)ue=(ue<<5)-ue+X.charCodeAt(S)|0;return`flopay_session_${Math.abs(ue).toString(36)}`}let Rt=(0,M.useMemo)(()=>gt?Pn(gt):"",[gt]),Ot=(0,M.useRef)(gt);Ot.current=gt,(0,M.useEffect)(()=>{at(e??"")},[e]),(0,M.useEffect)(()=>{en.current=!1,je(Be),ht(null),Ge(null)},[Rt,Be,e]);async function Le(h,W){let j=lo(T,o,Pt),ge=new Xn.PaymentAPI(T,{telemetry:!1}),X=!1;try{let ue=h.idempotencyKey!==void 0?(0,we.resolveIdempotencyKey)(h.idempotencyKey):void 0,S=ue??ks(W),u,c=!1,L=ws(W);j.log({name:L?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let y=L?.sid??null,ee=null,Ie;if(y)try{if(ee=await ge.getUnifiedCheckoutSession(y,L?.nonce),ee.data.session?.status==="complete"){if(xo(y))return{sid:y,result:ee};Is(W),y=null,ee=null,c=!0}}catch{j.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),qo(W),y=null}if(!y){!ue&&(c||!S)&&(S=(0,we.resolveIdempotencyKey)(),u=S),S&&Rs(W,S);let rt=j.now(),Ce=0;j.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let O={...h,idempotencyKey:S,avsCheck:!!Me,avsConfig:typeof Me=="object"?Me:void 0,checkoutType:"embedded_checkout",checkoutLayout:se?"custom_layout":K==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(O,Xn.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Y=>{Ce=Math.max(Ce,Y)}}});let f=()=>{j.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),j.performance({stage:"session_create",durationMs:j.now()-rt,durationMode:"machine",requestCategory:"session_create",attempt:Ce,statusClass:"2xx"})},U=Y=>{let Ye=(0,we.classifyTelemetryFailure)(Y,"CHECKOUT_SESSION_CREATE_FAILED","unknown");j.performance({stage:"session_create",durationMs:j.now()-rt,durationMode:"machine",requestCategory:"session_create",attempt:Ce,statusClass:Ye.statusClass}),Y instanceof we.FloPayError&&Y.type==="validation_error"?j.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):Ye.statusClass==="4xx"?j.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):j.error({...Ye,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if((0,we.isDetachedSessionEligible)(O)){let Y=await ge.createDetachedSession(O);Y.claimed.catch(()=>{}),ee=Y.shell,y=Y.sessionId,Ie=Y.claimed.then(Ye=>{let Et=Ye.data.session?.id??Y.sessionId;return Et&&ai(W,Et,Ye.data.session?.clientSecret??Y.nonce),f(),Ye},Ye=>{throw qo(W),U(Ye),Ye}).finally(()=>Tr(j)),Ie.catch(()=>{}),X=!0,j.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),j.performance({stage:"session_shell",durationMs:j.now()-rt,durationMode:"machine",requestCategory:"session_create",attempt:Ce,statusClass:"2xx",paymentMethodCategory:"card"})}else ee=await ge.createAndFetchSession(O),f()}catch(Y){throw U(Y),Y}y=ee.data.session?.id??y??"",y&&!Ie&&ai(W,y,ee.data.session?.clientSecret)}return{sid:y??"",result:ee,sdkGeneratedIdempotencyKey:u,...Ie?{claimed:Ie}:{}}}finally{X||Tr(j)}}let bt=(0,M.useCallback)(async(h,W)=>{let j=Ot.current;if(!j)throw new we.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ge=Eo(j,h),X=Pn(ge),ue=co.get(X);if(!ue){let c={promise:Le(ge,X),consumers:0,settled:!1};ue=c,co.set(X,c);let L=()=>{c.settled=!0,ri(X,c)};c.promise.then(L,L)}ue.consumers+=1;let S=!1,u=()=>{S||(S=!0,ue.consumers-=1,ri(X,ue))};W?.(u);try{let c=await ue.promise;an.current=X,h&&(Zt(Vt),on(f=>Ta(f,h)));let{sid:L,result:y,claimed:ee}=c;if(re(y),y.data.session&&tt(y.data.session),L&&at(L),ee){let f=Gt.current+=1;qt(!0),ee.then(U=>{Gt.current===f&&(re(U),U.data.session&&tt(U.data.session),qt(!1))},U=>{Gt.current===f&&(qt(!1),dt(U instanceof we.FloPayError?U:new we.FloPayError(U instanceof Error?U.message:"Failed to create session","api_error")))})}else Gt.current+=1,qt(!1);let{publishableKey:Ie,paypalPublishableKey:rt}=ao(y),{flopay:Ce,paypalFlopay:O}=await io({publishableKey:Ie,paypalPublishableKey:rt,billingApiUrl:T,locale:m,telemetry:o});return ct.current=Ce,$e(Ce),q.current=O,ot(O),g(!1),c}catch(c){throw an.current===X&&(an.current=null),c}finally{W||u()}},[m,T,o,Pt]),vt=(0,M.useRef)(Ht);vt.current=Ht;let bn=(0,M.useRef)(bt);bn.current=bt;let jn=(0,M.useCallback)(async h=>{if(!_s(h)||Dn)return{sessionId:Ae,session:G};Nt(!0);try{let W=await bt(h);return{sessionId:W.sid,session:W.result.data.session??null}}finally{Nt(!1)}},[bt,Dn,Ae,G]);(0,M.useEffect)(()=>{let h=!1,W;if(dt(null),Rt){let X=Ot.current;return Qe(Kt),g(!1),an.current===Rt?()=>{h=!0}:(tt(Ma(X,Ee)),(async()=>{let ue=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),S=Kt==="auto"&&!en.current&&!ue;S&&(je(null),ht(null),Ge("processing"));try{let u=await bn.current(void 0,ee=>{W=ee}),c=u.result.data.session??null;ut.current=ao(u.result);let L=Oo(u.result),y=xo(u.sid||c?.id);if(!h&&S&&c&&!L&&!y){en.current=!0,await vs(Rt,u.sdkGeneratedIdempotencyKey,()=>vt.current(c,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:u.result.autoProcessingError,initialAutoProcessingPending:u.result.autoProcessingPending,autoProcessingAttempted:u.result.autoProcessingAttempted,sessionId:u.sid||c.id}));return}!h&&S&&((L||y)&&(en.current=!0),Ge(null),ht(null))}catch(u){if(h)return;let c=u instanceof we.FloPayError||typeof u=="object"&&u!==null&&"code"in u?u.code:void 0;if(S&&c==="session_auto_completed"){en.current=!0,Ge("success"),await xr(xn),h||(st(()=>{Te.current?.({status:"succeeded"})}),Ge(null),ht(null));return}S&&(Ge(null),ht(null));let L=u instanceof we.FloPayError?u:new we.FloPayError(u instanceof Error?u.message:"Failed to create session","api_error");dt(L)}finally{W?.(),W=void 0}})(),()=>{h=!0,W?.()})}g(!0);async function j(){let X=!1;try{let S=await new Xn.PaymentAPI(T,{telemetry:!1}).getUnifiedCheckoutSession(We,t);if(h)return;re(S);let u=S.data.session??null;if(tt(u),!u)throw new we.FloPayError("No session data returned","api_error");if(u.status==="complete"){g(!1),st(()=>{Ln.current?.(u.successUrl??"")});return}if(u.status==="expired")throw new we.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});X=!0;let c=Ee??u.checkoutMode??"full";Qe(c);let L=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),y=Oo(S);if(c==="auto"&&!en.current&&!L&&!y){en.current=!0;let ee=ge(S);try{if(await vt.current(u,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ee,sessionId:We||u.id}),h)return;await ee,h||g(!1);return}catch{if(h)return;await ee,h||g(!1);return}}await ge(S),h||g(!1)}catch(ue){if(h)return;ue instanceof we.FloPayError?!X&&!Cs(ue)&&No(T,o,Pt,"NETWORK_REQUEST_FAILED","session_read"):No(T,o,Pt,"INTERNAL_SDK_ERROR","checkout_mount");let S=ue instanceof we.FloPayError?ue:new we.FloPayError(ue instanceof Error?ue.message:"Failed to initialize checkout","api_error");dt(S),g(!1)}}async function ge(X){let{publishableKey:ue,paypalPublishableKey:S}=ao(X);ut.current={publishableKey:ue,paypalPublishableKey:S};let{flopay:u,paypalFlopay:c}=await io({publishableKey:ue,paypalPublishableKey:S,billingApiUrl:T,locale:m,telemetry:o});ct.current=u,$e(u),q.current=c,ot(c)}return j(),()=>{h=!0}},[Ee,Rt,Kt,Ke,st,t]);let Wt=(0,M.useCallback)(async()=>{if(!(He||!G)){Ze(!0),je(null);try{await Ht(G,{attempt3DS:!0,fallbackToFull:!0,sessionId:We||G.id})}finally{Ze(!1)}}},[We,He,Ht,G]),Xt=$o(E),Ft=Oo(E),Rn=(0,M.useMemo)(()=>{if(!E||!G||!E.data.stripe?.publishableKey)return;let h={appearance:Oe,paymentMethodCreation:"manual",billingApiUrl:T};if(E.data.stripe?.clientSecret)h.clientSecret=E.data.stripe.clientSecret;else{let W=(0,we.buildCheckoutDisplayData)(G).total;h.amount=Math.round(W*100)||G.amount,h.currency=G.currency?.toLowerCase()}return h},[E,G,Oe,T]),Nn=!!(n&&!se&&K==="buttons"&&ye&&Kt==="full"),sn=(0,M.useMemo)(()=>({session:G,loading:rn,error:ke,checkoutMode:nt,inlineSessionDraft:gt,applyInlineSessionPatch:Nn?jn:void 0,inlineSessionPatchProcessing:Dn,claimPending:kt}),[G,rn,ke,nt,gt,Nn,jn,Dn,kt]),Qt=!!n&&K==="buttons"&&!Ft&&(!oe||!Rn),It=wt?(0,w.jsx)(Sn,{status:wt,errorMessage:An}):null;if(rn){if(d)return(0,w.jsxs)(w.Fragment,{children:[d,It]});if(K==="buttons"){let h=de?.buttonsLayout?.cardButton?.borderRadius??de?.appearance.variables?.borderRadius??8,W=j=>(0,w.jsx)("div",{style:{height:j,borderRadius:h,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[p&&W(ur),v&&(F||b)&&W(ur),v&&W(ur),(0,w.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),It]})}return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,w.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,w.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),It]})}return ke?I?(0,w.jsx)(dn.Provider,{value:sn,children:I(ke)}):(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:ke.message})}):Qt?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)(Ts,{onButtonClick:J,showPayPal:p,showStripe:v,showApplePay:F,showGooglePay:b,theme:pe,buttonsTheme:ae,buttonsStyles:z,cardButtonContent:te,cardBackButtonContent:Q,cardTitleContent:me})}),It]}):Ft&&G&&Xt?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsxs)("div",{className:ve,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[xe&&(0,w.jsx)(ar,{icon:!1,children:xe}),Mt==="retrying"&&(0,w.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Mt==="exhausted"&&(0,w.jsxs)("div",{role:"alert",children:[(0,w.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,w.jsx)("button",{type:"button",onClick:Zn,children:"Retry PayPal"})]}),Mt!=="exhausted"&&(0,w.jsx)("div",{"aria-hidden":Mt==="retrying"?!0:void 0,style:Mt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,w.jsx)(za,{sessionId:We,nonce:G.clientSecret||void 0,billingApiUrl:T,email:G.customer?.email,clientId:Xt.clientId,environment:Xt.environment,currency:(G.currency??"usd").toUpperCase(),isSubscription:G.mode==="subscription",onComplete:N,onErrorChange:je,onDecline:_,onButtonClick:J,onInitializationStateChange:qn,allowAutomaticRetry:Bt===0,session:G,telemetry:o,telemetryContext:Pt,debug:ce},`paypal-init-${Bt}`)})]})}),It]}):!oe||!Rn?(0,w.jsx)(w.Fragment,{children:It}):nt==="confirm"?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)(Sr,{flopay:oe,paypalFlopay:Ve,options:Rn,children:(0,w.jsxs)("div",{className:ve,children:[xe&&(0,w.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:xe}),Re?Re({onConfirm:Wt,isProcessing:He}):(0,w.jsx)("button",{type:"button",onClick:Wt,disabled:He,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:He?"not-allowed":"pointer",opacity:He?.6:1},children:He?"Processing...":_e??"Confirm Purchase"})]})})}),It]}):(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(dn.Provider,{value:sn,children:(0,w.jsx)(Sr,{flopay:oe,paypalFlopay:Ve,options:Rn,children:se?(0,w.jsxs)(w.Fragment,{children:[xe&&(0,w.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:xe}),(0,w.jsx)(xs,{sessionId:We,nonce:G?.clientSecret||void 0,billingApiUrl:T,session:G,children:se})]}):(0,w.jsx)(no,{sessionId:We,nonce:G?.clientSecret||void 0,email:G?.customer?.email,userId:G?.customer?.id,firstName:G?.customer?.firstName,lastName:G?.customer?.lastName,totalAmount:G?Math.round((0,we.buildCheckoutDisplayData)(G).total*100):0,currency:G?.currency?.toLowerCase()??"usd",onComplete:N,onError:P,onDecline:_,error:xe,onErrorChange:je,showPayPal:p,showStripe:v,enabledPaymentMethods:x??E?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:E?.data.stripe?.enabledPaymentMethodCountries,showApplePay:F,showGooglePay:b,layout:K,theme:pe,buttonsTheme:ae,buttonsStyles:z,appearance:Oe,cardButtonContent:te,cardBackButtonContent:Q,cardTitleContent:me,onButtonClick:J,onBeforeButtonClick:ye,enableAVS:Me,...Se?{cardFieldOrder:Se}:{},...Pe?{cardPreFormSlot:Pe}:{},avsLayout:ie,country:G?.customer?.country,city:G?.customer?.city,state:G?.customer?.state,onCountryChange:k,onZipChange:A,avsCheck:!!Me,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:se?"custom_layout":K==="buttons"?"buttons_layout":"default_layout",className:ve,directPaypal:$o(E),isSubscription:G?.mode==="subscription",session:G,dataAttachmentPending:kt,debug:ce})})}),It]})}function xs({sessionId:e,nonce:t,billingApiUrl:n,session:l,children:o}){return(0,w.jsx)(w.Fragment,{children:M.default.Children.map(o,s=>{if(!M.default.isValidElement(s))return s;let m=s.props,d={};return m.sessionId||(d.sessionId=e),!m.nonce&&t&&(d.nonce=t),m.billingApiUrl||(d.billingApiUrl=n),l?.customer&&(m.email||(d.email=l.customer.email),m.userId||(d.userId=l.customer.id),m.firstName||(d.firstName=l.customer.firstName),m.lastName||(d.lastName=l.customer.lastName)),Object.keys(d).length===0?s:M.default.cloneElement(s,d)})})}function Ts({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:l,showGooglePay:o,theme:s,buttonsTheme:m,buttonsStyles:d,cardButtonContent:I,cardBackButtonContent:N,cardTitleContent:P}){let[_,k]=(0,M.useState)(!1),A=(0,M.useMemo)(()=>(0,we.resolveTheme)(s),[s]),p=(0,M.useMemo)(()=>{let b=A?.buttonsLayout??(0,we.resolveButtonsLayoutTheme)(m);return d?{...b,...d,cardButton:{...b.cardButton,...d.cardButton},cardFormContainer:{...b.cardFormContainer,...d.cardFormContainer},backButton:{...b.backButton,...d.backButton},backButtonIcon:{...b.backButtonIcon,...d.backButtonIcon},submitButton:{...b.submitButton,...d.submitButton},title:{...b.title,...d.title}}:b},[A,m,d]),v=A?.buttonsLayout?.cardButton?.borderRadius??A?.appearance.variables?.borderRadius??8,x=b=>(0,w.jsx)("div",{style:{height:b,borderRadius:v,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),F=I===void 0?{boxSizing:"border-box",height:ur,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let b=p.cardInputBorder??"#e5e7eb",ce=p.cardInputBackground??"white",K=nr(N),pe=nr(P);return(0,w.jsxs)("div",{style:{backgroundColor:p.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...p.cardFormContainer},children:[(0,w.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,w.jsxs)("button",{type:"button",onClick:()=>k(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:K?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...p.backButton},children:[(0,w.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...p.backButtonIcon},children:(0,w.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,w.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,w.jsx)(or,{content:N})]}),pe?(0,w.jsx)("div",{style:{flex:1}}):(0,w.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...p.title},children:(0,w.jsx)(wr,{content:P})})]}),(0,w.jsx)("div",{style:{backgroundColor:ce,border:`1px solid ${b}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsxs)("div",{style:{display:"flex"},children:[(0,w.jsx)("div",{style:{flex:1,backgroundColor:ce,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsx)("div",{style:{flex:1,backgroundColor:ce,borderTop:"none",borderRight:`1px solid ${b}`,borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,w.jsx)("div",{style:{backgroundColor:ce,border:`1px solid ${b}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,w.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,w.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...p.submitButton,opacity:.5}}),(0,w.jsx)("style",{children:`
41
41
  @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
42
42
  @keyframes flopay-interim-expand {
43
43
  0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
44
44
  40% { opacity: 1; }
45
45
  100% { opacity: 1; max-height: 600px; transform: translateY(0); }
46
46
  }
47
- `})]})}return(0,w.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&x(ur),n&&(l||o)&&x(ur),n&&(0,w.jsx)("button",{type:"button",onClick:()=>{e?.("card"),k(!0)},style:{width:"100%",...F,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:p.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...p.cardButton},onMouseDown:b=>{b.currentTarget.style.transform="scale(0.985)"},onMouseUp:b=>{b.currentTarget.style.transform="scale(1)"},children:(0,w.jsx)(rr,{content:I})}),(0,w.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Qn=require("react");var di=require("react/jsx-runtime");function si(e,t){function n({className:l,id:o,style:s,options:m,onChange:d,onReady:I,onFocus:N,onBlur:P,onEscape:_}){let k=(0,Qn.useRef)(null),A=(0,Qn.useRef)(null),{elements:p,reportInteractive:v}=(0,Qn.useContext)(En);return(0,Qn.useEffect)(()=>{if(!p||!k.current)return;let x=!0;return(async()=>{let F=p.getElement(e);F||(F=await p.create(e,m)),!(!x||!k.current)&&(F.mount(k.current),A.current=F,d&&F.on("change",d),F.on("ready",()=>{v?.(),I?.()}),N&&F.on("focus",N),P&&F.on("blur",P),_&&F.on("escape",_))})(),()=>{if(x=!1,A.current){try{A.current.unmount()}catch{}A.current=null}}},[p,v]),(0,di.jsx)("div",{ref:k,className:l,id:o,style:s})}return n.displayName=t,n}var li=si("payment","PaymentElement"),ci=si("address","AddressElement");var ui=require("@flopay/js"),pi=require("@flopay/shared"),fn=require("react");var yn=require("react/jsx-runtime");function mi({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,firstName:s,lastName:m,chv:d,onTokenizedBody:I,onComplete:N,onErrorChange:P,isProcessing:_=!1}){let k=un(),A=Hr(),p=Wr(),[v,x]=(0,fn.useState)(!1),[F,b]=(0,fn.useState)(!1),ce=(0,fn.useRef)(!1),K=(n||p).replace(/\/+$/,""),pe=(0,fn.useCallback)(async te=>{try{let me=await new ui.PaymentAPI(K).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:te,accountData:{userId:o??"",email:l??"",firstName:s??"",lastName:m??""},chv:d});if(me.ok){N?.();return}let H=await me.json().catch(()=>null);P?.(H?.message??"Payment failed. Please try again.")}catch(Q){P?.(Q instanceof Error?Q.message:"An unexpected error occurred")}},[K,e,t,o,l,s,m,d,N,P]),ae=(0,fn.useCallback)(te=>{I?I(te):pe(te)},[I,pe]);(0,fn.useEffect)(()=>{if(!k||ce.current)return;let te=new URLSearchParams(window.location.search),Q=te.get("payment_intent"),me=te.get("payment_intent_client_secret"),H=te.get("redirect_status");!Q||!me||(ce.current=!0,(async()=>{try{if(b(!0),H==="failed"){P?.("PayPal payment was declined. Please try again.");return}let J=k.getRawProvider();if(!J?.retrievePaymentIntent){P?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ye,error:Me}=await J.retrievePaymentIntent(me);if(Me){P?.(Me.message??"Failed to retrieve PayPal payment status.");return}if(ye&&(ye.status==="requires_capture"||ye.status==="succeeded")){let Se=typeof ye.payment_method=="string"?ye.payment_method:ye.payment_method?.id;ae({id:Se??ye.id,type:"card",threeDSecureActionResultTokenId:ye.id,isPaypal:!0});let Pe=new URL(window.location.href);Pe.searchParams.delete("payment_intent"),Pe.searchParams.delete("payment_intent_client_secret"),Pe.searchParams.delete("redirect_status"),window.history.replaceState({},"",Pe.toString())}else P?.("PayPal payment was not completed. Please try again.")}catch(J){P?.(J instanceof Error?J.message:"Failed to complete PayPal payment.")}finally{b(!1)}})())},[k,ae,P]);let z=(0,fn.useCallback)(async()=>{if(!(!k||!A))try{if(b(!0),P?.(null),!e||!l)throw new pi.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let te=await k.confirmPayPalPayment({billingApiUrl:K,sessionId:e,nonce:t,email:l,returnUrl:window.location.href});if(te.error){P?.(te.error.message);return}te.paymentIntentId&&(te.status==="succeeded"||te.status==="processing"||te.status==="requires_capture")&&ae({id:te.paymentMethodId??te.paymentIntentId,type:"card",threeDSecureActionResultTokenId:te.paymentIntentId,isPaypal:!0})}catch(te){P?.(te instanceof Error?te.message:"PayPal payment failed. Please try again.")}finally{b(!1)}},[k,A,e,t,l,K,ae,P]);return!k||!A?(0,yn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,yn.jsxs)(yn.Fragment,{children:[!v&&(0,yn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,yn.jsx)("div",{style:v?{}:{display:"none"},children:(0,yn.jsx)("button",{type:"button",onClick:z,disabled:F||_,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:F||_?"not-allowed":"pointer",opacity:F||_?.6:1},ref:()=>x(!0),children:F?"Processing...":"PayPal"})}),(F||_)&&(0,yn.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,yn.jsx)("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}var De=require("react"),po=require("@flopay/js"),$t=require("@flopay/shared");var gn=require("react/jsx-runtime"),Ts=44;function yi(e){return new Promise(t=>setTimeout(t,e))}function Ms(e,t){return e instanceof $t.FloPayError?e:new $t.FloPayError(e instanceof Error?e.message:t,"api_error")}function Bs(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function As(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 fi({sessionId:e,nonce:t,createSession:n,paymentMethodId:l,checkoutMethod:o,clientId:s,products:m,items:d,subscriptions:I,account:N,successUrl:P,cancelUrl:_,couponCodes:k,tagsData:A,utmMetadata:p,billingApiUrl:v,locale:x,theme:F,appearance:b,buttonsTheme:ce,buttonsStyles:K,onSuccess:pe,onError:ae,onDecline:z,children:te,disabled:Q=!1,type:me="button",style:H,...J}){let ye=(0,De.useMemo)(()=>(0,$t.resolveBillingApiUrl)(v),[v]),Me=(0,De.useMemo)(()=>As({createSession:n,clientId:s,products:m,items:d,subscriptions:I,account:N,successUrl:P,cancelUrl:_,couponCodes:k,tagsData:A,utmMetadata:p}),[N,_,s,k,n,m,d,I,P,A,p]),[Se,Pe]=(0,De.useState)(!1),[ie,ve]=(0,De.useState)(null),[Be,se]=(0,De.useState)(null),[Ee,_e]=(0,De.useState)(null),Re=(0,De.useRef)(!0),Z=(0,De.useRef)(null),T=(0,De.useRef)(Ee),de=(0,De.useRef)(pe),Oe=(0,De.useRef)(ae),ze=(0,De.useRef)(z);(0,De.useEffect)(()=>{T.current=Ee},[Ee]),(0,De.useEffect)(()=>{de.current=pe},[pe]),(0,De.useEffect)(()=>{Oe.current=ae},[ae]),(0,De.useEffect)(()=>{ze.current=z},[z]),(0,De.useEffect)(()=>(Re.current=!0,()=>{Re.current=!1,Z.current?.abort()}),[]),(0,De.useEffect)(()=>{if(typeof window>"u")return;let g=ke=>{ke.key==="Escape"&&_e(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let fe=(0,De.useCallback)((g,ke=_r)=>{ze.current?.(St(ke,g,{code:g.code,declineCode:g.declineCode}))},[]),E=(0,De.useCallback)(async g=>{Re.current&&(se(null),ve("success"),await yi(xn),Re.current&&de.current?.(g))},[]),re=(0,De.useCallback)(async(g,ke)=>{Re.current&&(Oe.current?.(g),ke?.emitDecline&&fe(g,ke.method),se(g.message),ve("error"),await yi(Cn))},[fe]),oe=(0,De.useCallback)(async(g,ke,dt)=>{let nt=g.data.session??null;if(!nt)throw new $t.FloPayError("No session data returned","api_error");let Qe=nt.clientSecret||t;if(nt.status==="complete"){await E({result:{status:"succeeded"},session:nt,sessionId:nt.id||ke,autoCompleted:!1});return}if(nt.status==="expired")throw new $t.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(g.autoProcessingPending){let je=(await new po.PaymentAPI(ye).waitForCheckoutSessionCompletion(g.autoProcessingPending.sessionId,{initialDelayMs:g.autoProcessingPending.retryAfterMs})).data.session;if(!je||je.status!=="complete")throw new $t.FloPayError("Automatic payment failed. Please try again.","api_error",{code:je?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await E({result:{status:"succeeded"},session:je,sessionId:je.id||ke,autoCompleted:!1});return}if(g.autoProcessingError){if(g.autoProcessingError.type==="3ds_required"&&g.autoProcessingError.nextActionRedirectUrl&&ke&&Qe){let Ze=new AbortController;Z.current=Ze;let xe;try{xe=await ti({billingApiUrl:ye,sessionId:ke,nonce:Qe,nextActionRedirectUrl:g.autoProcessingError.nextActionRedirectUrl,signal:Ze.signal})}finally{Z.current===Ze&&(Z.current=null)}if(xe.status==="declined")throw Un({type:xe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:xe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let Ge=(await new po.PaymentAPI(ye).waitForCheckoutSessionCompletion(ke,{initialDelayMs:0,nonce:Qe})).data.session;if(!Ge||Ge.status!=="complete")throw Un({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await E({result:{status:"succeeded"},session:Ge,sessionId:Ge.id||ke,autoCompleted:!1});return}throw Un(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(dt?.fromCreateSession&&g.autoProcessingAttempted===!0)throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let He=await dr({billingApiUrl:ye,sessionId:ke??nt.id,session:nt,nonce:Qe});if(He.type!=="success")throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await E({result:He.result,session:nt,sessionId:nt.id||ke,autoCompleted:!1})}catch(He){let Ze=Jn(He),xe=nt.id||ke;await re(Ze,{emitDecline:!0,method:Ze.checkoutMethod??_r}),Bs(Ze,xe)&&xe&&Re.current&&_e({sessionId:xe,errorMessage:Ze.message,nonce:Qe||void 0})}},[t,ye,re,E]),$e=(0,De.useCallback)(async g=>{if(J.onClick?.(g),!(g.defaultPrevented||Q||Se)){if(_e(null),e&&Me){let ke=new $t.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await re(ke),Re.current&&(ve(null),se(null));return}if(!e&&!Me){let ke=new $t.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await re(ke),Re.current&&(ve(null),se(null));return}Pe(!0),se(null),ve("processing");try{let ke=new po.PaymentAPI(ye);if(e){let dt=await ke.getUnifiedCheckoutSession(e,t);await oe(dt,e);return}try{let dt=await ke.createAndFetchSession({...Me});await oe(dt,dt.data.session?.id??null,{fromCreateSession:!0})}catch(dt){if(dt instanceof $t.FloPayError&&dt.code==="session_auto_completed"){await E({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw dt}}catch(ke){await re(Ms(ke,"Automatic payment failed. Please try again."))}finally{Re.current&&(ve(null),se(null),Pe(!1))}}},[J,Me,Q,Se,t,oe,ye,e,re,E]),ct=(0,De.useCallback)(g=>{let ke=T.current;_e(null),de.current?.({result:g,session:null,sessionId:ke?.sessionId??null,autoCompleted:!1})},[]),Ve=(0,De.useCallback)(g=>{Oe.current?.(g)},[]),ot=(0,De.useCallback)(g=>{ze.current?.(g)},[]),q=(0,De.useMemo)(()=>(0,$t.resolveTheme)(F),[F]),G=(0,De.useMemo)(()=>{let g=q?.buttonsLayout??(0,$t.resolveButtonsLayoutTheme)(ce);return K?{...g,...K,cardButton:{...g.cardButton,...K.cardButton}}:g},[q,ce,K]),tt=(0,De.useMemo)(()=>{let g=q?.appearance;return b?g?{...g,...b,variables:{...g.variables,...b.variables}}:b:g},[b,q]),Ae=tt?.variables,at=Ae?.colorPrimary??"#4A49FF",We=Ae?.colorPrimaryHover??Zr(at,.12),Ke=Ae?.borderRadius??"8px";return(0,gn.jsxs)(gn.Fragment,{children:[(0,gn.jsx)("button",{...J,type:me,onClick:$e,disabled:Q||Se,"aria-busy":Se,style:{width:"100%",...te===void 0?{boxSizing:"border-box",height:Ts,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...G.cardButton,...Do({themeBundle:q,resolvedPrimaryColor:at,resolvedBorderRadius:Ke,submitButtonStyle:G.submitButton,explicitPrimaryColor:Ae?.colorPrimary}),fontSize:G.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Q||Se?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Q||Se?.6:1,...H},onMouseEnter:g=>{J.onMouseEnter?.(g),!g.defaultPrevented&&!Q&&!Se&&(q||Ae?.colorPrimary)&&(g.currentTarget.style.backgroundColor=We)},onMouseLeave:g=>{J.onMouseLeave?.(g),!g.defaultPrevented&&(q||Ae?.colorPrimary)&&(g.currentTarget.style.backgroundColor=at)},onMouseDown:g=>{J.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{J.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:(0,gn.jsx)(rr,{content:te})}),ie&&(0,gn.jsx)(Sn,{status:ie,errorMessage:Be}),Ee&&(0,gn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&_e(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,gn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,gn.jsx)(uo,{sessionId:Ee.sessionId,nonce:Ee.nonce,checkoutMode:"full",billingApiUrl:ye,locale:x,theme:F,...tt?{appearance:tt}:{},buttonsTheme:ce,buttonsStyles:K,initialErrorMessage:Ee.errorMessage,cardTitleContent:null,onComplete:ct,onError:Ve,onDecline:ot})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,useCheckout,useElements,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,w.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&x(ur),n&&(l||o)&&x(ur),n&&(0,w.jsx)("button",{type:"button",onClick:()=>{e?.("card"),k(!0)},style:{width:"100%",...F,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:p.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...p.cardButton},onMouseDown:b=>{b.currentTarget.style.transform="scale(0.985)"},onMouseUp:b=>{b.currentTarget.style.transform="scale(1)"},children:(0,w.jsx)(rr,{content:I})}),(0,w.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var gi=require("@flopay/shared");var Qn=require("react");var di=require("react/jsx-runtime");function si(e,t){function n({className:l,id:o,style:s,options:m,onChange:d,onReady:I,onFocus:N,onBlur:P,onEscape:_}){let k=(0,Qn.useRef)(null),A=(0,Qn.useRef)(null),{elements:p,reportInteractive:v}=(0,Qn.useContext)(En);return(0,Qn.useEffect)(()=>{if(!p||!k.current)return;let x=!0;return(async()=>{let F=p.getElement(e);F||(F=await p.create(e,m)),!(!x||!k.current)&&(F.mount(k.current),A.current=F,d&&F.on("change",d),F.on("ready",()=>{v?.(),I?.()}),N&&F.on("focus",N),P&&F.on("blur",P),_&&F.on("escape",_))})(),()=>{if(x=!1,A.current){try{A.current.unmount()}catch{}A.current=null}}},[p,v]),(0,di.jsx)("div",{ref:k,className:l,id:o,style:s})}return n.displayName=t,n}var li=si("payment","PaymentElement"),ci=si("address","AddressElement");var ui=require("@flopay/js"),pi=require("@flopay/shared"),fn=require("react");var yn=require("react/jsx-runtime");function mi({sessionId:e,nonce:t,billingApiUrl:n,email:l,userId:o,firstName:s,lastName:m,chv:d,onTokenizedBody:I,onComplete:N,onErrorChange:P,isProcessing:_=!1}){let k=un(),A=Hr(),p=Wr(),[v,x]=(0,fn.useState)(!1),[F,b]=(0,fn.useState)(!1),ce=(0,fn.useRef)(!1),K=(n||p).replace(/\/+$/,""),pe=(0,fn.useCallback)(async te=>{try{let me=await new ui.PaymentAPI(K).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:te,accountData:{userId:o??"",email:l??"",firstName:s??"",lastName:m??""},chv:d});if(me.ok){N?.();return}let H=await me.json().catch(()=>null);P?.(H?.message??"Payment failed. Please try again.")}catch(Q){P?.(Q instanceof Error?Q.message:"An unexpected error occurred")}},[K,e,t,o,l,s,m,d,N,P]),ae=(0,fn.useCallback)(te=>{I?I(te):pe(te)},[I,pe]);(0,fn.useEffect)(()=>{if(!k||ce.current)return;let te=new URLSearchParams(window.location.search),Q=te.get("payment_intent"),me=te.get("payment_intent_client_secret"),H=te.get("redirect_status");!Q||!me||(ce.current=!0,(async()=>{try{if(b(!0),H==="failed"){P?.("PayPal payment was declined. Please try again.");return}let J=k.getRawProvider();if(!J?.retrievePaymentIntent){P?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ye,error:Me}=await J.retrievePaymentIntent(me);if(Me){P?.(Me.message??"Failed to retrieve PayPal payment status.");return}if(ye&&(ye.status==="requires_capture"||ye.status==="succeeded")){let Se=typeof ye.payment_method=="string"?ye.payment_method:ye.payment_method?.id;ae({id:Se??ye.id,type:"card",threeDSecureActionResultTokenId:ye.id,isPaypal:!0});let Pe=new URL(window.location.href);Pe.searchParams.delete("payment_intent"),Pe.searchParams.delete("payment_intent_client_secret"),Pe.searchParams.delete("redirect_status"),window.history.replaceState({},"",Pe.toString())}else P?.("PayPal payment was not completed. Please try again.")}catch(J){P?.(J instanceof Error?J.message:"Failed to complete PayPal payment.")}finally{b(!1)}})())},[k,ae,P]);let z=(0,fn.useCallback)(async()=>{if(!(!k||!A))try{if(b(!0),P?.(null),!e||!l)throw new pi.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let te=await k.confirmPayPalPayment({billingApiUrl:K,sessionId:e,nonce:t,email:l,returnUrl:window.location.href});if(te.error){P?.(te.error.message);return}te.paymentIntentId&&(te.status==="succeeded"||te.status==="processing"||te.status==="requires_capture")&&ae({id:te.paymentMethodId??te.paymentIntentId,type:"card",threeDSecureActionResultTokenId:te.paymentIntentId,isPaypal:!0})}catch(te){P?.(te instanceof Error?te.message:"PayPal payment failed. Please try again.")}finally{b(!1)}},[k,A,e,t,l,K,ae,P]);return!k||!A?(0,yn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,yn.jsxs)(yn.Fragment,{children:[!v&&(0,yn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,yn.jsx)("div",{style:v?{}:{display:"none"},children:(0,yn.jsx)("button",{type:"button",onClick:z,disabled:F||_,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:F||_?"not-allowed":"pointer",opacity:F||_?.6:1},ref:()=>x(!0),children:F?"Processing...":"PayPal"})}),(F||_)&&(0,yn.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,yn.jsx)("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}var De=require("react"),po=require("@flopay/js"),$t=require("@flopay/shared");var gn=require("react/jsx-runtime"),Ms=44;function yi(e){return new Promise(t=>setTimeout(t,e))}function Bs(e,t){return e instanceof $t.FloPayError?e:new $t.FloPayError(e instanceof Error?e.message:t,"api_error")}function As(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Fs(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 fi({sessionId:e,nonce:t,createSession:n,paymentMethodId:l,checkoutMethod:o,clientId:s,products:m,items:d,subscriptions:I,account:N,successUrl:P,cancelUrl:_,couponCodes:k,tagsData:A,utmMetadata:p,billingApiUrl:v,locale:x,theme:F,appearance:b,buttonsTheme:ce,buttonsStyles:K,onSuccess:pe,onError:ae,onDecline:z,children:te,disabled:Q=!1,type:me="button",style:H,...J}){let ye=(0,De.useMemo)(()=>(0,$t.resolveBillingApiUrl)(v),[v]),Me=(0,De.useMemo)(()=>Fs({createSession:n,clientId:s,products:m,items:d,subscriptions:I,account:N,successUrl:P,cancelUrl:_,couponCodes:k,tagsData:A,utmMetadata:p}),[N,_,s,k,n,m,d,I,P,A,p]),[Se,Pe]=(0,De.useState)(!1),[ie,ve]=(0,De.useState)(null),[Be,se]=(0,De.useState)(null),[Ee,_e]=(0,De.useState)(null),Re=(0,De.useRef)(!0),Z=(0,De.useRef)(null),T=(0,De.useRef)(Ee),de=(0,De.useRef)(pe),Oe=(0,De.useRef)(ae),ze=(0,De.useRef)(z);(0,De.useEffect)(()=>{T.current=Ee},[Ee]),(0,De.useEffect)(()=>{de.current=pe},[pe]),(0,De.useEffect)(()=>{Oe.current=ae},[ae]),(0,De.useEffect)(()=>{ze.current=z},[z]),(0,De.useEffect)(()=>(Re.current=!0,()=>{Re.current=!1,Z.current?.abort()}),[]),(0,De.useEffect)(()=>{if(typeof window>"u")return;let g=ke=>{ke.key==="Escape"&&_e(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let fe=(0,De.useCallback)((g,ke=_r)=>{ze.current?.(St(ke,g,{code:g.code,declineCode:g.declineCode}))},[]),E=(0,De.useCallback)(async g=>{Re.current&&(se(null),ve("success"),await yi(xn),Re.current&&de.current?.(g))},[]),re=(0,De.useCallback)(async(g,ke)=>{Re.current&&(Oe.current?.(g),ke?.emitDecline&&fe(g,ke.method),se(g.message),ve("error"),await yi(Cn))},[fe]),oe=(0,De.useCallback)(async(g,ke,dt)=>{let nt=g.data.session??null;if(!nt)throw new $t.FloPayError("No session data returned","api_error");let Qe=nt.clientSecret||t;if(nt.status==="complete"){await E({result:{status:"succeeded"},session:nt,sessionId:nt.id||ke,autoCompleted:!1});return}if(nt.status==="expired")throw new $t.FloPayError("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(g.autoProcessingPending){let je=(await new po.PaymentAPI(ye).waitForCheckoutSessionCompletion(g.autoProcessingPending.sessionId,{initialDelayMs:g.autoProcessingPending.retryAfterMs})).data.session;if(!je||je.status!=="complete")throw new $t.FloPayError("Automatic payment failed. Please try again.","api_error",{code:je?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await E({result:{status:"succeeded"},session:je,sessionId:je.id||ke,autoCompleted:!1});return}if(g.autoProcessingError){if(g.autoProcessingError.type==="3ds_required"&&g.autoProcessingError.nextActionRedirectUrl&&ke&&Qe){let Ze=new AbortController;Z.current=Ze;let xe;try{xe=await ti({billingApiUrl:ye,sessionId:ke,nonce:Qe,nextActionRedirectUrl:g.autoProcessingError.nextActionRedirectUrl,signal:Ze.signal})}finally{Z.current===Ze&&(Z.current=null)}if(xe.status==="declined")throw Un({type:xe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:xe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let Ge=(await new po.PaymentAPI(ye).waitForCheckoutSessionCompletion(ke,{initialDelayMs:0,nonce:Qe})).data.session;if(!Ge||Ge.status!=="complete")throw Un({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await E({result:{status:"succeeded"},session:Ge,sessionId:Ge.id||ke,autoCompleted:!1});return}throw Un(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(dt?.fromCreateSession&&g.autoProcessingAttempted===!0)throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let He=await dr({billingApiUrl:ye,sessionId:ke??nt.id,session:nt,nonce:Qe});if(He.type!=="success")throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await E({result:He.result,session:nt,sessionId:nt.id||ke,autoCompleted:!1})}catch(He){let Ze=Jn(He),xe=nt.id||ke;await re(Ze,{emitDecline:!0,method:Ze.checkoutMethod??_r}),As(Ze,xe)&&xe&&Re.current&&_e({sessionId:xe,errorMessage:Ze.message,nonce:Qe||void 0})}},[t,ye,re,E]),$e=(0,De.useCallback)(async g=>{if(J.onClick?.(g),!(g.defaultPrevented||Q||Se)){if(_e(null),e&&Me){let ke=new $t.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await re(ke),Re.current&&(ve(null),se(null));return}if(!e&&!Me){let ke=new $t.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await re(ke),Re.current&&(ve(null),se(null));return}Pe(!0),se(null),ve("processing");try{let ke=new po.PaymentAPI(ye);if(e){let dt=await ke.getUnifiedCheckoutSession(e,t);await oe(dt,e);return}try{let dt=await ke.createAndFetchSession({...Me});await oe(dt,dt.data.session?.id??null,{fromCreateSession:!0})}catch(dt){if(dt instanceof $t.FloPayError&&dt.code==="session_auto_completed"){await E({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw dt}}catch(ke){await re(Bs(ke,"Automatic payment failed. Please try again."))}finally{Re.current&&(ve(null),se(null),Pe(!1))}}},[J,Me,Q,Se,t,oe,ye,e,re,E]),ct=(0,De.useCallback)(g=>{let ke=T.current;_e(null),de.current?.({result:g,session:null,sessionId:ke?.sessionId??null,autoCompleted:!1})},[]),Ve=(0,De.useCallback)(g=>{Oe.current?.(g)},[]),ot=(0,De.useCallback)(g=>{ze.current?.(g)},[]),q=(0,De.useMemo)(()=>(0,$t.resolveTheme)(F),[F]),G=(0,De.useMemo)(()=>{let g=q?.buttonsLayout??(0,$t.resolveButtonsLayoutTheme)(ce);return K?{...g,...K,cardButton:{...g.cardButton,...K.cardButton}}:g},[q,ce,K]),tt=(0,De.useMemo)(()=>{let g=q?.appearance;return b?g?{...g,...b,variables:{...g.variables,...b.variables}}:b:g},[b,q]),Ae=tt?.variables,at=Ae?.colorPrimary??"#4A49FF",We=Ae?.colorPrimaryHover??Zr(at,.12),Ke=Ae?.borderRadius??"8px";return(0,gn.jsxs)(gn.Fragment,{children:[(0,gn.jsx)("button",{...J,type:me,onClick:$e,disabled:Q||Se,"aria-busy":Se,style:{width:"100%",...te===void 0?{boxSizing:"border-box",height:Ms,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...G.cardButton,...Do({themeBundle:q,resolvedPrimaryColor:at,resolvedBorderRadius:Ke,submitButtonStyle:G.submitButton,explicitPrimaryColor:Ae?.colorPrimary}),fontSize:G.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Q||Se?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Q||Se?.6:1,...H},onMouseEnter:g=>{J.onMouseEnter?.(g),!g.defaultPrevented&&!Q&&!Se&&(q||Ae?.colorPrimary)&&(g.currentTarget.style.backgroundColor=We)},onMouseLeave:g=>{J.onMouseLeave?.(g),!g.defaultPrevented&&(q||Ae?.colorPrimary)&&(g.currentTarget.style.backgroundColor=at)},onMouseDown:g=>{J.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{J.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:(0,gn.jsx)(rr,{content:te})}),ie&&(0,gn.jsx)(Sn,{status:ie,errorMessage:Be}),Ee&&(0,gn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&_e(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,gn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,gn.jsx)(uo,{sessionId:Ee.sessionId,nonce:Ee.nonce,checkoutMode:"full",billingApiUrl:ye,locale:x,theme:F,...tt?{appearance:tt}:{},buttonsTheme:ce,buttonsStyles:K,initialErrorMessage:Ee.errorMessage,cardTitleContent:null,onComplete:ct,onError:Ve,onDecline:ot})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useElements,useFloPay,usePayPalFloPay});
package/dist/index.d.cts CHANGED
@@ -2,7 +2,7 @@ import React from 'react';
2
2
  import { FloPay, FloPayElements } from '@flopay/js';
3
3
  import * as _flopay_shared from '@flopay/shared';
4
4
  import { FloPayAppearance, InlineSessionDraft, FloPayError, PaymentResult, DeclineEvent, CheckoutButtonMethod, BeforeButtonClickEvent, InlineSessionPatch, CheckoutMode, CheckoutSession, ElementOptions, ElementChangeEvent, TokenizedBody, AVSFieldConfig, GatewayEnvironment, CardCaptureAdapter, VaultCardThemeColors, CheckoutProduct, CheckoutItem, CheckoutSubscription, ThemeId, ButtonsLayoutTheme, ButtonsLayoutStyles } from '@flopay/shared';
5
- export { BeforeButtonClickEvent, CheckoutButtonMethod, DeclineEvent, InlineSessionDraft, InlineSessionPatch } from '@flopay/shared';
5
+ export { BeforeButtonClickEvent, CheckoutButtonMethod, DeclineEvent, InlineSessionDraft, InlineSessionPatch, SentryEventLike, SentryStackFrameLike, dropThirdPartyOnlyError } from '@flopay/shared';
6
6
 
7
7
  /** Props for the `FloPayProvider` component. */
8
8
  interface FloPayProviderProps {
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import React from 'react';
2
2
  import { FloPay, FloPayElements } from '@flopay/js';
3
3
  import * as _flopay_shared from '@flopay/shared';
4
4
  import { FloPayAppearance, InlineSessionDraft, FloPayError, PaymentResult, DeclineEvent, CheckoutButtonMethod, BeforeButtonClickEvent, InlineSessionPatch, CheckoutMode, CheckoutSession, ElementOptions, ElementChangeEvent, TokenizedBody, AVSFieldConfig, GatewayEnvironment, CardCaptureAdapter, VaultCardThemeColors, CheckoutProduct, CheckoutItem, CheckoutSubscription, ThemeId, ButtonsLayoutTheme, ButtonsLayoutStyles } from '@flopay/shared';
5
- export { BeforeButtonClickEvent, CheckoutButtonMethod, DeclineEvent, InlineSessionDraft, InlineSessionPatch } from '@flopay/shared';
5
+ export { BeforeButtonClickEvent, CheckoutButtonMethod, DeclineEvent, InlineSessionDraft, InlineSessionPatch, SentryEventLike, SentryStackFrameLike, dropThirdPartyOnlyError } from '@flopay/shared';
6
6
 
7
7
  /** Props for the `FloPayProvider` component. */
8
8
  interface FloPayProviderProps {
package/dist/index.mjs CHANGED
@@ -44,4 +44,4 @@ ${qe.join(`
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{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,Cs as useCheckout,$o as useElements,vn as useFloPay,Uo as usePayPalFloPay};
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flopay/react",
3
- "version": "1.4.17",
3
+ "version": "1.4.18",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "publishConfig": {
@@ -29,8 +29,8 @@
29
29
  "@paypal/paypal-js": "^10.0.0",
30
30
  "@stripe/react-stripe-js": "^6.6.0",
31
31
  "@stripe/stripe-js": "^9.8.0",
32
- "@flopay/js": "1.4.17",
33
- "@flopay/shared": "1.4.17"
32
+ "@flopay/js": "1.4.18",
33
+ "@flopay/shared": "1.4.18"
34
34
  },
35
35
  "peerDependencies": {
36
36
  "react": ">=18.0.0",