@flopay/react 1.6.0 → 1.8.1
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 +37 -72
- package/dist/card-setup-entry.cjs +2 -2
- package/dist/card-setup-entry.d.cts +1 -1
- package/dist/card-setup-entry.d.ts +1 -1
- package/dist/card-setup-entry.mjs +1 -1
- package/dist/chunk-VWT2TDA6.mjs +6 -0
- package/dist/index.cjs +10 -10
- package/dist/index.d.cts +241 -364
- package/dist/index.d.ts +241 -364
- package/dist/index.mjs +8 -8
- package/package.json +3 -3
- package/dist/chunk-P5QXEIBB.mjs +0 -6
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var Xi=Object.create;var no=Object.defineProperty;var Qi=Object.getOwnPropertyDescriptor;var Zi=Object.getOwnPropertyNames;var es=Object.getPrototypeOf,ts=Object.prototype.hasOwnProperty;var ns=(e,t)=>{for(var n in t)no(e,n,{get:t[n],enumerable:!0})},La=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Zi(t))!ts.call(e,r)&&r!==n&&no(e,r,{get:()=>t[r],enumerable:!(a=Qi(t,r))||a.enumerable});return e};var Oa=(e,t,n)=>(n=e!=null?Xi(es(e)):{},La(t||!e||!e.__esModule?no(n,"default",{value:e,enumerable:!0}):n,e)),rs=e=>La(no({},"__esModule",{value:!0}),e);var Xs={};ns(Xs,{AddressElement:()=>wi,DirectPayPalButton:()=>zr,FloPayAutomaticPaymentButton:()=>Mi,FloPayCardSetup:()=>Ei,FloPayCardSetupError:()=>qr,FloPayCheckout:()=>Ro,FloPayProvider:()=>Br,PayPalButton:()=>xi,PaymentElement:()=>Si,SplitCardForm:()=>ho,VaultCardFields:()=>mr,dropThirdPartyOnlyError:()=>Ai.dropThirdPartyOnlyError,useCheckout:()=>Va,useElements:()=>io,useFloPay:()=>gn,usePayPalFloPay:()=>ao});module.exports=rs(Xs);var os=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,je=os();var Rt=require("react"),za=require("@flopay/shared");var $o=require("react"),Bn=(0,$o.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),fn=(0,$o.createContext)({session:null,loading:!1,error:null});var as=Symbol.for("@flopay/js.telemetry.bridge.v1"),is=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function ss(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},flush:async()=>{},destroy:()=>{}}}function ls(e){let t=ss(),n=(r,i)=>r?r.bind(e):i,a=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:a,elapsed:e.elapsed?e.elapsed.bind(e):r=>Math.max(0,a()-r),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function ro(e){let t=globalThis[is];return ls(t?.(e)??{})}function Tt(e){if(e)return e[as]}var Na=require("react/jsx-runtime");function Br({flopay:e,paypalFlopay:t,options:n,children:a}){let[r,i]=(0,Rt.useState)(e instanceof Promise?null:e),[u,d]=(0,Rt.useState)(t instanceof Promise||!t?null:t),[b,M]=(0,Rt.useState)(null),g=(0,Rt.useRef)(null),R=(0,Rt.useRef)(null),C=(0,Rt.useRef)(null);(0,Rt.useEffect)(()=>{if(!r)return;let E=Tt(r);return g.current=E?.beginCheckout()??E?.now()??0,E?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{E?.log({name:"checkout.unmount",stage:"unmount"})}},[r]),(0,Rt.useEffect)(()=>{let E=!1;return e instanceof Promise?e.then(_=>{E||i(_)}):i(e),()=>{E=!0}},[e]),(0,Rt.useEffect)(()=>{let E=!1;if(!t){d(null);return}return t instanceof Promise?t.then(_=>{E||d(_)}):d(t),()=>{E=!0}},[t]),(0,Rt.useEffect)(()=>{if(!r){M(null);return}let E=r.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return M(E),()=>{E.destroy()}},[r,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,Rt.useEffect)(()=>{if(!r||!b||R.current===b)return;R.current=b;let E=Tt(r);E?.log({name:"checkout.rendered",stage:"checkout_render"}),E?.performance({stage:"checkout_render",durationMs:E.elapsed(g.current??0),durationMode:"machine"})},[b,r]);let k=(0,Rt.useCallback)(()=>{if(!r||!b||C.current===b)return;C.current=b;let E=Tt(r);E?.log({name:"checkout.interactive",stage:"checkout_interactive"}),E?.performance({stage:"checkout_interactive",durationMs:E.elapsed(g.current??0),durationMode:"machine"})},[b,r]),p=(0,za.resolveBillingApiUrl)(n?.billingApiUrl),h=(0,Rt.useMemo)(()=>({flopay:r,paypalFlopay:u,elements:b,billingApiUrl:p,reportInteractive:k}),[r,u,b,p,k]);return(0,Na.jsx)(Bn.Provider,{value:h,children:a})}var B=Oa(require("react"),1),rr=require("@flopay/js"),_e=require("@flopay/shared");var dl=require("react"),ut=require("react/jsx-runtime");function cs(){return(0,ut.jsxs)(ut.Fragment,{children:[(0,ut.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,ut.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,ut.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,ut.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,ut.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function ds(){return(0,ut.jsx)(ut.Fragment,{children:"Go back"})}function us(){return(0,ut.jsx)(ut.Fragment,{children:"Secure card checkout"})}function cr(e){return e!==void 0&&(e===""||e===null||e===!1)}function dr({content:e}){return(0,ut.jsx)(ut.Fragment,{children:e===void 0?(0,ut.jsx)(cs,{}):e})}function ur({content:e}){return(0,ut.jsx)(ut.Fragment,{children:e===void 0?(0,ut.jsx)(ds,{}):e})}function Fr({content:e}){return(0,ut.jsx)(ut.Fragment,{children:e===void 0?(0,ut.jsx)(us,{}):e})}var mt=require("@stripe/react-stripe-js"),v=require("@flopay/shared");function pr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let a=parseInt(n[1],16),r=Math.max(0,Math.min(1,1-t)),i=Math.round((a>>16&255)*r),u=Math.round((a>>8&255)*r),d=Math.round((a&255)*r);return`#${(1<<24|i<<16|u<<8|d).toString(16).slice(1)}`}function jo(e){if(typeof e=="number"||typeof e=="string")return e}function oo({appearance:e,buttonsStyles:t,layout:n="default"}){let a=e?.variables,r=M=>typeof M=="string"&&M?M:void 0,i=t.submitButton,u=r(a?.colorPrimary)??r(i?.backgroundColor)??"#4A49FF",d=n==="buttons",b=t.nameInput;return{primaryColor:u,primaryHoverColor:r(a?.colorPrimaryHover)??pr(u,.12),inputBackgroundColor:r(t.cardInputBackground)??r(a?.colorBackground)??"#ffffff",textColor:r(t.cardInputColor)??r(b?.color)??r(a?.colorText)??"#262833",borderColor:r(t.cardInputBorder)??(d?"#e5e7eb":"#A4A4FF"),placeholderColor:r(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:r(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:r(b?.fontFamily)??r(a?.fontFamily)??"Poppins, sans-serif",fontSize:r(t.cardInputFontSize)??r(a?.fontSizeBase)??"16px",fontWeight:String(jo(b?.fontWeight)??400),borderRadius:r(a?.borderRadius)??"8px"}}var bn=require("@flopay/js");var Fn=require("react"),Ua=require("react/jsx-runtime");function mr({capture:e,html:t,messageToken:n,expectedOrigin:a,theme:r,containerStyle:i,onReady:u,onError:d,onValidation:b}){let M=(0,Fn.useRef)(null),g=(0,Fn.useRef)(u),R=(0,Fn.useRef)(d),C=(0,Fn.useRef)(b);g.current=u,R.current=d,C.current=b;let k=(0,Fn.useRef)(r);return k.current=r,(0,Fn.useEffect)(()=>{let p=M.current;if(!p)return;let h=!0,E=!1,_=()=>{!h||E||(E=!0,g.current?.())},f=e.on("ready",()=>{_()}),ge=e.on("error",ae=>{R.current?.(ae.message??"There was a problem loading the secure card form.")}),x=e.on("validation",ae=>{C.current?.(ae.message??null)}),oe={html:t,...n?{messageToken:n}:{},...a?{expectedOrigin:a}:{},...k.current?{theme:k.current}:{}};return e.mount(p,oe).then(()=>{_()}).catch(ae=>{h&&R.current?.(ae instanceof Error?ae.message:"Failed to load the secure card form.")}),()=>{h=!1,f(),ge(),x(),e.unmount()}},[e,t,n,a]),(0,Fn.useEffect)(()=>{r&&e.applyTheme?.(r)},[e,r]),(0,Ua.jsx)("div",{ref:M,"data-testid":"flopay-vault-card-fields",style:i})}var bl=require("react"),Dr=require("react/jsx-runtime");function yr({children:e,margin:t,icon:n=!0,styleOverride:a}){return(0,Dr.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"}:{},...a??{}},children:[n&&(0,Dr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Dr.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var $a={alipay:new URL("./payment-logos/alipay.svg",je).href,bancontact:new URL("./payment-logos/bancontact.svg",je).href,blik:new URL("./payment-logos/blik.svg",je).href,eps:new URL("./payment-logos/eps.svg",je).href,giropay:new URL("./payment-logos/giropay.svg",je).href,ideal:new URL("./payment-logos/ideal.svg",je).href,klarna:new URL("./payment-logos/klarna.svg",je).href,p24:new URL("./payment-logos/p24.svg",je).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",je).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",je).href};var o=Oa(require("react"),1);var fr=require("react"),ja=require("@flopay/shared");function gn(){return(0,fr.useContext)(Bn).flopay}function ao(){return(0,fr.useContext)(Bn).paypalFlopay??null}function io(){return(0,fr.useContext)(Bn).elements}function Va(){return(0,fr.useContext)(fn)}function so(){return(0,fr.useContext)(Bn).billingApiUrl||(0,ja.resolveBillingApiUrl)()}var _l=require("react"),vt=require("react/jsx-runtime"),hn=1200,Qt=1500;function cn({status:e,errorMessage:t,authorized:n=!1,processingLabel:a="PROCESSING...",successLabel:r,errorLabel:i="PAYMENT FAILED",successNote:u="You will be automatically redirected, do not close or navigate away from this window."}){return(0,vt.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,vt.jsxs)("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,vt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,vt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,vt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,vt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,vt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,vt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,vt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,vt.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,vt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,vt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,vt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,vt.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,vt.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&a,e==="success"&&(r??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&u!==null&&(0,vt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:u}),e==="error"&&t&&(0,vt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,vt.jsx)("style",{children:`
|
|
1
|
+
"use strict";var rs=Object.create;var co=Object.defineProperty;var os=Object.getOwnPropertyDescriptor;var as=Object.getOwnPropertyNames;var is=Object.getPrototypeOf,ss=Object.prototype.hasOwnProperty;var ls=(e,t)=>{for(var n in t)co(e,n,{get:t[n],enumerable:!0})},Ha=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of as(t))!ss.call(e,r)&&r!==n&&co(e,r,{get:()=>t[r],enumerable:!(o=os(t,r))||o.enumerable});return e};var Ya=(e,t,n)=>(n=e!=null?rs(is(e)):{},Ha(t||!e||!e.__esModule?co(n,"default",{value:e,enumerable:!0}):n,e)),cs=e=>Ha(co({},"__esModule",{value:!0}),e);var ol={};ls(ol,{DirectPayPalButton:()=>qr,FloPayAutomaticPaymentButton:()=>Li,FloPayCardSetup:()=>Ni,FloPayCardSetupError:()=>Xr,FloPayCheckout:()=>Bo,FloPayProvider:()=>Vr,SplitCardForm:()=>To,VaultCardFields:()=>wr,dropThirdPartyOnlyError:()=>zi.dropThirdPartyOnlyError,useCheckout:()=>ei,useFloPay:()=>$n,usePayPalFloPay:()=>yo});module.exports=cs(ol);var ds=()=>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,Fe=ds();var zi=require("@flopay/shared");var Fo=require("@flopay/js"),on=require("@flopay/shared"),Me=require("react");var ct=require("react/jsx-runtime");function us(){return(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.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,ct.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,ct.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,ct.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,ct.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function ps(){return(0,ct.jsx)(ct.Fragment,{children:"Go back"})}function ms(){return(0,ct.jsx)(ct.Fragment,{children:"Secure card checkout"})}function pr(e){return e!==void 0&&(e===""||e===null||e===!1)}function mr({content:e}){return(0,ct.jsx)(ct.Fragment,{children:e===void 0?(0,ct.jsx)(us,{}):e})}function yr({content:e}){return(0,ct.jsx)(ct.Fragment,{children:e===void 0?(0,ct.jsx)(ps,{}):e})}function Nr({content:e}){return(0,ct.jsx)(ct.Fragment,{children:e===void 0?(0,ct.jsx)(ms,{}):e})}var fr=require("@flopay/shared");function Wa(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 Wo(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 Ga(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],o=n.reduce((i,m)=>i+(m.overrideAmount??m.totalAmount??0),0),r=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(o*100),currency:r,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,m)=>({uuid:`synthetic-${i.type??"item"}-${m}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??r,metadata:i.metadata??null}))}}function Go(e,t){return t?{...e,...t}:e}function xt(e,t,n){let o=typeof t=="string"?t:t.message,r=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:o,...r?{code:r}:{},...i?{declineCode:i}:{}}}var ys=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Gn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:o}of ys)if(n.test(t))return o;return e}function ar(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function gr(e){return e?.status==="authorized"||e?.status==="complete"}function Ja(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function uo(e){let t=Ja(e);return new fr.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function po(e){let t=Ja(e);return new fr.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function mo(e,t){return e==="processing"||(0,fr.isMoneySettledOutcome)(e,t)}function Xa(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Za(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function zr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var cr=require("@flopay/js"),fe=require("@flopay/shared"),E=Ya(require("react"),1);var Jo=require("react"),hn=(0,Jo.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),kn=(0,Jo.createContext)({session:null,loading:!1,error:null});var vo=require("@flopay/js"),Wt=require("@flopay/shared"),ai=require("@paypal/paypal-js"),F=require("react");function fs(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 ir(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Un(e){if(typeof e!="object"||e===null)return;let t=e;return ir(t.code)??ir(t.type)??ir(t.name)}function hr(e){if(!(typeof e!="object"||e===null))return ir(e.decline_code)}function Ur(e){return typeof e!="object"||e===null?!1:ir(e.type)?.toLowerCase()==="card_error"||hr(e)!==void 0}function Jn(e){let t=fs(e)?.toLowerCase()??"",o=`${Un(e)?.toLowerCase()??""} ${t}`;return o.includes("popup")&&o.includes("block")}var Qa=require("@flopay/shared"),$r=require("react");function $n(){return(0,$r.useContext)(hn).flopay}function yo(){return(0,$r.useContext)(hn).paypalFlopay??null}function ei(){return(0,$r.useContext)(kn)}function ti(){return(0,$r.useContext)(hn).billingApiUrl||(0,Qa.resolveBillingApiUrl)()}var ni=require("@flopay/shared"),sr=require("react");function Le(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)}}var fo=require("react"),go=typeof window>"u"?fo.useEffect:fo.useLayoutEffect;var gs={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function hs(e){return e==="stripe"||e==="paypal"?e:void 0}function vs(e){let t=hs(e.provider),n={schemaVersion:ni.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let o=gs[e.name];return o?{...n,name:o}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var Xo=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function vr(e,t){let n=(0,sr.useRef)(e);n.current=e;let o=(0,sr.useRef)(new Set),r=(0,sr.useRef)(t),i=(0,sr.useRef)(t);return go(()=>{i.current=t,r.current!==t&&(r.current=t,o.current.clear())},[t]),(0,sr.useCallback)(m=>{if(i.current!==t)return;let d=vs(m);if(d){if(Xo.has(d.name)){if(o.current.has(d.name))return;o.current.add(d.name)}Le(()=>n.current?.(d))}},[t])}var Ps=Symbol.for("@flopay/js.telemetry.bridge.v1"),bs=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Cs(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function Ss(e){let t=Cs(),n=(r,i)=>r?r.bind(e):i,o=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:o,elapsed:e.elapsed?e.elapsed.bind(e):r=>Math.max(0,o()-r),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function ho(e){let t=globalThis[bs];return Ss(t?.(e)??{})}function At(e){if(e)return e[Ps]}var In=require("react/jsx-runtime"),Po=45,ws=1e3,ks=11e3,Is=["https://www.paypal.com","https://www.sandbox.paypal.com"],ri="We couldn't open PayPal. Try again or choose another payment method.",Es={width:"100%",minHeight:Po,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function oi(e){return e.includes("No ack for postMessage init()")&&Is.some(t=>e.includes(t))&&e.includes("10000ms")}function Rs(e){return e?`${ri} Allow pop-ups for this site, then try again.`:ri}function ii({sessionId:e,nonce:t,billingApiUrl:n,email:o,clientId:r,environment:i,currency:m,isSubscription:d,providerObjectType:R,onTokenizedBody:g,onComplete:v,onErrorChange:b,onDecline:A,onTechnicalFailure:D,isProcessing:y=!1,onLoadStateChange:C,onInitializationStateChange:Q,allowAutomaticRetry:J=!0,onButtonClick:w,runBeforeButtonClick:ge,session:U,existingOrderId:ee,telemetry:re,telemetryContext:be,onInstrument:oe,debug:he=!1}){let ze=$n(),_e=vr(oe,e),Se=(0,F.useMemo)(()=>{if(ze)return null;let x=ho({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Wt.SDK_VERSION,enabled:re!==!1});return x.setCheckoutContext(be??{}),x.beginCheckout(be??{}),x},[n,ze,re,be?.checkoutMode,be?.layout]),K=(0,F.useMemo)(()=>At(ze),[ze]);(0,F.useEffect)(()=>()=>{Se&&Se.flush().catch(()=>{}).finally(()=>Se.destroy())},[Se]);let O=(0,F.useMemo)(()=>({error:x=>{K?K.error(x):Se?.error(x),_e({class:"technical_error",errorCode:x.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":x.errorCode,requestCategory:x.requestCategory,provider:x.provider})},log:x=>{K?K.log(x):Se?.log(x),_e({class:"lifecycle",name:x.name,provider:x.provider})},performance:x=>{K?K.performance(x):Se?.performance(x)},terminal:x=>{K?K.terminal(x):Se?.terminal(x)},startTiming:()=>K?.now()??Se?.now()??0,elapsed:x=>K?.elapsed(x)??Math.max(0,(Se?.now()??x)-x)}),[_e,K,Se]),ae=(0,F.useRef)(null),Ue=(0,F.useRef)(0),Te=(0,F.useRef)(null),X=(0,F.useRef)(!1),[$,te]=(0,F.useState)(!1),[pe,ve]=(0,F.useState)(!1),[Z,Re]=(0,F.useState)(0),H=(0,F.useRef)(0),[_,me]=(0,F.useState)(!1),We=(0,F.useRef)(!1),$e=(0,F.useRef)(!1),[ce,B]=(0,F.useState)(!1),[ie,G]=(0,F.useState)(!1),Oe=(0,F.useMemo)(()=>n.replace(/\/+$/,""),[n]),Be=R??(d?"subscription":"order"),Qe=R==="order"||R==="setup_token",se=(0,F.useMemo)(()=>JSON.stringify([Oe,r,m,i??"",Be,Qe,e,ee??""]),[Oe,r,m,i,ee,Be,Qe,e]),yt=(0,F.useRef)(se),j=yt.current!==se,[qe,Pt]=(0,F.useState)([]),Y=x=>{he&&Pt(tt=>[...tt,`${new Date().toISOString().slice(11,23)} ${x}`])},bt=(0,F.useRef)(g),Ke=(0,F.useRef)(v),Qt=(0,F.useRef)(b),Et=(0,F.useRef)(A),T=(0,F.useRef)(D),Pe=(0,F.useRef)(w),ft=(0,F.useRef)(C),Ne=(0,F.useRef)(Q),qt=(0,F.useRef)(ge),Gt=(0,F.useRef)(U),Ze=(0,F.useRef)(o),Ct=(0,F.useRef)(t),et=(0,F.useRef)(null),Mt=(0,F.useRef)(0),Ge=(0,F.useRef)(null),jt=(0,F.useRef)(null),Rt=(0,F.useRef)(new Map),en=(0,F.useRef)(new Map),Dt=(0,F.useRef)(!1);(0,F.useEffect)(()=>(Dt.current=!0,()=>{Dt.current=!1}),[]),(0,F.useEffect)(()=>{bt.current=g},[g]),(0,F.useEffect)(()=>{Ke.current=v},[v]),(0,F.useEffect)(()=>{Qt.current=b},[b]),(0,F.useEffect)(()=>{Et.current=A},[A]),(0,F.useEffect)(()=>{T.current=D},[D]),(0,F.useEffect)(()=>{Pe.current=w},[w]),(0,F.useEffect)(()=>{ft.current=C},[C]),(0,F.useEffect)(()=>{Ne.current=Q},[Q]),(0,F.useEffect)(()=>{qt.current=ge},[ge]),(0,F.useEffect)(()=>{Gt.current=U},[U]),(0,F.useEffect)(()=>{Ze.current=o},[o]),(0,F.useEffect)(()=>{Ct.current=t},[t]),(0,F.useEffect)(()=>{H.current=Z},[Z]),(0,F.useEffect)(()=>{_&&Te.current?.focus()},[_,Z]);let Rn=(0,F.useCallback)(()=>{window.setTimeout(()=>{Te.current?.focus()},0)},[]),sn=(0,F.useCallback)(()=>{te(!1),Re(x=>x+1)},[]),at=(0,F.useCallback)(()=>{me(!1),(ae.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ae.current)?.focus?.()},[]);(0,F.useEffect)(()=>{!$||!X.current||(X.current=!1,at())},[at,$,Z]);let Lt=(0,F.useCallback)((x,tt)=>{let ke=T.current;if(ke){ke("paypal",x,tt);return}Qt.current?.(Rs(tt?.popupBlocked??Jn(x)))},[]),Je=()=>{Ge.current?.timer&&(clearTimeout(Ge.current.timer),Ge.current.timer=null)},_n=()=>{Je();let x=Mt.current+1;return Mt.current=x,jt.current=null,Ge.current={generation:x,timer:null,yieldedControl:!1},me(!1),x},dt=x=>x!==void 0&&Ge.current?.generation!==x?!1:(Je(),Ge.current=null,jt.current=null,!0),bn=x=>{let tt=x?.generation??Ge.current?.generation??Mt.current;(!x?.generation||Ge.current?.generation===tt)&&(Je(),Ge.current=null),jt.current=tt,x?.showRetry&&me(!0),x?.remount&&sn(),x?.focus!==!1&&Rn()},Ot=x=>Ge.current?.generation===x&&jt.current!==x,ue=x=>{typeof document<"u"&&document.visibilityState!=="visible"||(Je(),x.timer=setTimeout(()=>{Ge.current?.generation===x.generation&&(Ge.current=null,jt.current=x.generation,Lt(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),me(!0),sn(),Rn())},600))},Kn=()=>{let x=Ge.current;x?.yieldedControl&&ue(x)},Tn=()=>{let x=Ge.current;x&&(x.yieldedControl=!0,Je())},xn=x=>{let tt=et.current;return tt&&en.current.set(x,tt),x};(0,F.useEffect)(()=>{let x=()=>{document.visibilityState==="visible"?Kn():Tn()};return document.addEventListener("visibilitychange",x),window.addEventListener("focus",Kn),window.addEventListener("blur",Tn),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("focus",Kn),window.removeEventListener("blur",Tn),Je()}},[]),(0,F.useEffect)(()=>{yt.current!==se&&(yt.current=se,We.current=!1,$e.current=!1,te(!1),ve(!1),B(!1),Ne.current?.("loading"))},[se]),(0,F.useEffect)(()=>{Le(()=>ft.current?.($&&!ce))},[$,ce]);let An=(0,Wt.normalizeGatewayEnvironment)(i);(0,F.useEffect)(()=>{let x=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",tt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(Y(`mount clientId=${x} env=${i??"(unset)"}\u2192${An??"live"} ccy=${m} sub=${d}`),Y(`ua=${tt.slice(0,80)}${tt.length>80?"\u2026":""}`),!r){Y("FAIL: clientId empty \u2014 gateway misconfigured"),B(!0),O.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(!ae.current){Y("FAIL: containerRef not attached");return}Ue.current=O.startTiming(),O.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ke=!1,Cn=!1,je=()=>ke||Cn,Hn,Qn=!1,Vt=()=>{Hn=(0,Wt.generateIdempotencyKey)(),Hn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Qn=!0},ut=null,Jt=!1,Kt=null,it=!1,ln=()=>{!Kt||it||(it=!0,Kt.close().catch(()=>{}))},cn=null,Yn=()=>{cn!==null&&(O.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"overlay_return",durationMs:O.elapsed(cn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),cn=null)},Sn=!1,tn=ae.current,dn=null,Ce=null,St=[],st=u=>{if(!u||typeof u.getBoundingClientRect!="function")return"(no rect)";let c=u.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},nn=u=>{if(!u)return"(empty)";try{let c=new URL(u,typeof window<"u"?window.location.href:"https://localhost"),p=c.pathname.toLowerCase();return p.includes("checkcaptcha")||p.includes("captcha")?`CAPTCHA(${c.host}${p})`:p.includes("risk")||p.includes("challenge")?`RISK(${c.host}${p})`:p.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${p}`.slice(0,100)}catch{return u.slice(0,80)}},un=u=>{let c=u.getAttribute("src"),p=u.getAttribute("srcdoc"),N=u.getAttribute("name"),ne=u.getAttribute("sandbox"),q=[];return c&&q.push(`src=${nn(c)}`),p&&q.push(`srcdoc[${p.length}ch]`),!c&&!p&&q.push("src=(empty) srcdoc=(empty)"),N&&q.push(`name=${N.slice(0,40)}`),ne!==null&&q.push(`sandbox="${ne.slice(0,40)}"`),q.join(" ")},Ln=u=>{if(!(u instanceof HTMLIFrameElement))return"";try{let c=u.contentDocument;if(!c)return"cd=null";let p=c.body?.children.length??0,N=c.body?.innerHTML.length??0,ne=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${p}children,${N}ch] head[${ne}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},pn=[],Nt=u=>{if(je())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"))&&(Y(`window:error ${c.slice(0,140)}`),pn.push(c))},Ht=u=>{if(je())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"))&&(Y(`window:rejection ${c.slice(0,140)}`),pn.push(c))};he&&typeof window<"u"&&(window.addEventListener("error",Nt),window.addEventListener("unhandledrejection",Ht));let Yt={value:0};if(he&&typeof PerformanceObserver<"u")try{Ce=new PerformanceObserver(u=>{if(!je())for(let c of u.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;Yt.value+=1;let p=Math.round(c.duration);Y(`net ${p}ms ${c.name.slice(0,90)}`)}}),Ce.observe({type:"resource",buffered:!0})}catch{}let Wn=()=>{for(dn?.disconnect(),dn=null,Ce?.disconnect(),Ce=null;St.length;)clearTimeout(St.pop());he&&typeof window<"u"&&(window.removeEventListener("error",Nt),window.removeEventListener("unhandledrejection",Ht))},On=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")},Mn=u=>{if(je()||On(u))return;let c=Gn(u)??u;Le(()=>Qt.current?.(c))},Nn=u=>{ke||(B(!0),u.includes("paypal_ineligible")||O.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))},zt=(u,c=!1)=>{if(ke)return;let p=We.current||!J;if(Jt)return;Jt=!0,Cn=!0,Wn(),ln();let N=c||oi(u);if(N&&J&&!We.current){We.current=!0,te(!1),G(!1),ve(!0),Ne.current?.("retrying"),ut=setTimeout(()=>{ke||Re(ne=>ne+1)},ws);return}if(N||p){if(te(!1),G(!1),ve(!1),B(!0),Ne.current?.("exhausted"),!$e.current){$e.current=!0;let ne=oi(u)?"paypal_init_timeout":c?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",ne)}return}Nn(u)};B(!1);let nt=async(u,c=et.current)=>{if(je())return;let p=c?.sessionId??e;if(bt.current){await bt.current(u,{sessionId:p,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let N=O.startTiming();O.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ne=()=>{O.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"processing",durationMs:O.elapsed(N),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let q=Gt.current,k=c?.accountPatch?.email??Ze.current,P=c?.accountPatch?.userId??q?.customer?.id??q?.accountData?.userId??"",S=await new vo.PaymentAPI(Oe,{telemetry:!1}).processPayment(P,{sessionId:p,nonce:c?.nonce??Ct.current,tokenizedData:u,accountData:{userId:P,email:k??q?.customer?.email??"",firstName:c?.accountPatch?.firstName??q?.customer?.firstName??q?.accountData?.firstName??"",lastName:c?.accountPatch?.lastName??q?.customer?.lastName??q?.accountData?.lastName??"",country:c?.accountPatch?.country??q?.customer?.country??q?.accountData?.country??void 0,zip:c?.accountPatch?.zip??q?.customer?.zip??q?.accountData?.zip??void 0}});if(S.ok){if(Cn||ke&&Dt.current)return;ne(),O.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Le(()=>Ke.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(je())return;let M=await S.json().catch(()=>null),le=M?.message??"PayPal payment failed.",ye=Gn(le)??le;ne(),S.status===400&&(typeof M?.declineCode=="string"||!Array.isArray(M?.fields))?O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):S.status===400||S.status===422?O.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):O.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:S.status>=500?"5xx":S.status>=400?"4xx":S.status>=300?"3xx":"unknown",failureCategory:S.status>=500?"server_error":void 0}),Mn(ye),Le(()=>Et.current?.(xt("paypal",ye,{code:M?.code,declineCode:M?.declineCode})));return}catch(q){if(je())return;ne(),O.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let k=q instanceof Error?q.message:"PayPal payment failed.",P=Gn(k)??k;Mn(P),Le(()=>Et.current?.(xt("paypal",P)));return}},mn=()=>new Wt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ut=u=>je()?Promise.reject(mn()):Promise.resolve(u),pt=async u=>{if(je())throw mn();Qn||Vt();let c=et.current,p=c?.sessionId??e,N=c?.nonce??Ct.current;O.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ne;try{ne=await new vo.PaymentAPI(Oe,{telemetry:!1}).createSessionIntent(p,N??"",Qe?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Wt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:Be==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Hn})}catch(q){throw O.error({...(0,Wt.classifyTelemetryFailure)(q,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),q}if(je())throw mn();if(ne.provider!=="paypal"||ne.providerObjectType!==Be)throw new Error(u);return O.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ne.providerObjectId},Xt=(u,c)=>{let p=c?.nonce??Ct.current;if(!p)return;let N=c?.sessionId??e,ne=hr(u)??Un(u)??"provider_declined";new vo.PaymentAPI(Oe,{telemetry:!1}).reportSessionIntentDecline(N,p,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ne}).catch(()=>{})},_t=Z;Y("loadScript:scheduled (deferred 1 tick)");let er=null,mt=setTimeout(()=>{if(ke){Y("loadScript:skipped (cancelled before defer ran)");return}Y("loadScript:start");let u=An==="live"?"production":An;er=(0,ai.loadScript)({clientId:r,currency:m,...Be==="subscription"?{intent:"subscription",vault:!0}:Be==="order"?{intent:"capture"}:{},...u?{environment:u}:{},...u==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),er.then(c=>{if(Y(`loadScript:resolved inactive=${je()} ns=${!!c} buttons=${!!c?.Buttons}`),je())return;if(!c?.Buttons){Y("FAIL: namespace missing Buttons factory"),zt("PayPal SDK did not expose the Buttons factory.");return}O.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"provider_ready",durationMs:O.elapsed(Ue.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let p=async h=>{if(je()||H.current!==_t)return;let S=h.vaultSetupToken??h.subscriptionID??h.orderID??"",M=S?en.current.get(S):Rt.current.get(_t);if(!(!M||!Ot(M.generation))&&dt(M.generation)){en.current.delete(S),Rt.current.delete(M.surfaceKey),Yn();try{if(G(!0),Le(()=>Qt.current?.(null)),!S)throw new Wt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await nt(Be==="setup_token"?{id:S,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Wt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Qe?{id:S,isPaypal:!0,gateway:"paypal",paymentMethodType:Wt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:{id:S,isPaypal:!0},M)}catch(le){Mn(le instanceof Error?le.message:"PayPal capture failed.")}finally{je()||G(!1)}}},N=c.Buttons({style:{layout:"horizontal",height:Po,tagline:!1},onClick:async(h,S)=>{if(je()){await S.reject();return}Vt();let M=qt.current,le={};if(M)try{let He=await M("paypal");if(je()){await S.reject();return}if(!He.proceed){et.current=null,Rt.current.delete(_t),await S.reject();return}le={sessionId:He.sessionId,accountPatch:He.accountPatch,nonce:He.nonce}}catch(He){Y(`onClick:runBeforeButtonClick rejected msg=${(He instanceof Error?He.message:String(He)).slice(0,120)}`),et.current=null,Rt.current.delete(_t),await S.reject();return}Le(()=>Pe.current?.("paypal"));let De={generation:_n(),surfaceKey:_t,...le};et.current=De,Rt.current.set(_t,De),await S.resolve(),O.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),cn=O.startTiming()},createOrder:Be==="order"?ee?()=>Ut(ee).then(xn):()=>pt("Failed to create PayPal order.").then(xn):void 0,createSubscription:Be==="subscription"?ee?()=>Ut(ee).then(xn):()=>pt("Failed to create PayPal subscription.").then(xn):void 0,createVaultSetupToken:Be==="setup_token"?()=>pt("Failed to create PayPal setup token.").then(xn):void 0,onApprove:p,onCancel:()=>{if(je())return;let h=Rt.current.get(_t)??et.current;h&&Rt.current.delete(h.surfaceKey),et.current=null,Yn(),O.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),X.current=!0,bn({generation:h?.generation,remount:!0,focus:!1})},onError:h=>{if(je()||H.current!==_t)return;let S=h instanceof Error?h.message:"PayPal failed to render.";if(Y(`onError rendered=${Sn} msg=${S.slice(0,120)}`),Sn){let M=Rt.current.get(_t)??et.current;if(M&&!Ot(M.generation)||!M&&jt.current===Mt.current)return;if(On(S)){dt(M?.generation);return}if(Yn(),Ur(h)){O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Xt(h,M),Le(()=>Et.current?.(xt("paypal",S))),M&&Rt.current.delete(M.surfaceKey),et.current=null,dt(M?.generation);return}let le=S.toLowerCase();O.error({errorCode:le.includes("popup")&&le.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),M&&Rt.current.delete(M.surfaceKey),et.current=null,bn({generation:M?.generation,remount:!0,showRetry:!0,focus:!0}),Lt(h,{code:"paypal_runtime_failed"});return}zt(S)}}),ne=N.isEligible();if(Y(`isEligible=${ne}`),O.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ne){te(!1),zt("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Kt=N,he&&Y(`container:dims ${st(tn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),he&&typeof MutationObserver<"u"&&(dn=new MutationObserver(h=>{if(!je()){for(let S of h)if(S.type==="childList")S.addedNodes.forEach(M=>{if(!(M instanceof Element))return;let le=M.tagName.toLowerCase(),ye=(M.getAttribute("title")??"").slice(0,40),De=le==="iframe"?` ${un(M)}`:"";Y(`child+ ${le}${ye?` title="${ye}"`:""}${De} dims=${st(M)}`)});else if(S.type==="attributes"&&S.target instanceof Element){let M=S.target;if(M.tagName.toLowerCase()!=="iframe")continue;let le=S.attributeName;(le==="src"||le==="srcdoc")&&Y(`attr~ iframe ${le}=${le==="srcdoc"?`[${(M.getAttribute("srcdoc")??"").length}ch]`:nn(M.getAttribute("src"))} dims=${st(M)}`)}}}),dn.observe(tn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let k=h=>{if(je()||Sn)return;let S=tn.querySelectorAll("iframe"),M=typeof document<"u"&&"hasStorageAccess"in document;Y(`watchdog:${h} container=${st(tn)} children=${tn.childElementCount} iframes=${S.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${M} paypalNetRequests=${Yt.value}`),S.forEach((le,ye)=>{let De=(le.getAttribute("title")??"").slice(0,40);Y(` iframe[${ye}] ${st(le)}${De?` title="${De}"`:""} ${un(le)}`);let He=Ln(le);He&&Y(` ${He}`)}),pn.length===0&&Y(" (no PayPal/zoid window errors captured)")};he&&(St.push(setTimeout(()=>k("3s"),3e3)),St.push(setTimeout(()=>k("8s"),8e3)),St.push(setTimeout(()=>k("15s"),15e3))),Y("render:start");let P=O.startTiming();St.push(setTimeout(()=>{je()||Sn||(Y("watchdog:11s retryable render timeout"),zt("PayPal Buttons render did not settle within 11000ms.",!0))},ks)),N.render(tn).then(()=>{if(Y(`render:resolved inactive=${je()}`),Wn(),je()){ln();return}Sn=!0,te(!0),ve(!1),Ne.current?.("ready"),O.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"checkout_render",durationMs:O.elapsed(P),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(h=>{let S=h instanceof Error?h.message:"PayPal failed to render.";Y(`render:rejected msg=${S.slice(0,120)}`),Wn(),zt(S)})}).catch(c=>{let p=c instanceof Error?c.message:"PayPal SDK failed to load.";Y(`loadScript:rejected msg=${p.slice(0,120)}`),zt(p)})},0);return()=>{ke=!0,clearTimeout(mt),ut&&clearTimeout(ut),Wn(),ln()}},[J,Oe,r,m,i,Be,Qe,e,ee,Z,O]);let dr=he?(0,In.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ce?"#fef2f2":"#f3f4f6",border:`1px solid ${ce?"#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=${$} failed=${ce})`,qe.length===0?`
|
|
2
|
+
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
+
${qe.join(`
|
|
4
|
+
`)}`]}):null;return ce&&!j?he?(0,In.jsx)("div",{children:dr}):null:(0,In.jsxs)("div",{children:[dr,(0,In.jsxs)("div",{"aria-hidden":pe?!0:void 0,style:pe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Po},children:[!$&&!pe&&(0,In.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,In.jsx)("div",{ref:ae,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Po,display:"flex",opacity:$?1:0},"aria-busy":ie||y},Z)]},Z),_&&(0,In.jsx)("button",{ref:Te,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:at,style:Es,children:"Try PayPal again"})]})}function qr(e){return(0,In.jsx)(ii,{...e})}function si(e){return(0,In.jsx)(ii,{...e})}var jr=require("react/jsx-runtime");function Pr({children:e,margin:t,icon:n=!0,styleOverride:o}){return(0,jr.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"}:{},...o??{}},children:[n&&(0,jr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,jr.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 It=require("react/jsx-runtime");function vn({status:e,errorMessage:t,authorized:n=!1,processingLabel:o="PROCESSING...",successLabel:r,errorLabel:i="PAYMENT FAILED",successNote:m="You will be automatically redirected, do not close or navigate away from this window."}){return(0,It.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,It.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,It.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,It.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,It.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,It.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,It.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,It.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,It.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,It.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,It.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,It.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,It.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,It.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,It.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&o,e==="success"&&(r??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&m!==null&&(0,It.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:m}),e==="error"&&t&&(0,It.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,It.jsx)("style",{children:`
|
|
2
5
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
3
6
|
@keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
|
|
4
7
|
@keyframes flopay-draw { to { stroke-dashoffset: 0; } }
|
|
5
8
|
@keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
|
|
6
|
-
`})]})})}var gr=require("@flopay/shared");function qa(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Vo(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Ha(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],a=n.reduce((i,u)=>i+(u.overrideAmount??u.totalAmount??0),0),r=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(a*100),currency:r,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,u)=>({uuid:`synthetic-${i.type??"item"}-${u}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??r,metadata:i.metadata??null}))}}function qo(e,t){return t?{...e,...t}:e}function Et(e,t,n){let a=typeof t=="string"?t:t.message,r=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:a,...r?{code:r}:{},...i?{declineCode:i}:{}}}var ps=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function qn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:a}of ps)if(n.test(t))return a;return e}function er(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function hr(e){return e?.status==="authorized"||e?.status==="complete"}function Ka(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function lo(e){let t=Ka(e);return new gr.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function co(e){let t=Ka(e);return new gr.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function uo(e,t){return e==="processing"||(0,gr.isMoneySettledOutcome)(e,t)}function Ya(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Wa(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Lr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var po="flopay_recent_completion_";function Pr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(po+e,JSON.stringify(t))}catch{}}function Ho(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(po+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(po+e),!1):!0}catch{return!1}}function Ga(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var D=require("react"),Qa=require("@paypal/paypal-js"),mo=require("@flopay/js"),Zt=require("@flopay/shared");function Xe(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function ms(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function tr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Dn(e){if(typeof e!="object"||e===null)return;let t=e;return tr(t.code)??tr(t.type)??tr(t.name)}function br(e){if(!(typeof e!="object"||e===null))return tr(e.decline_code)}function Or(e){return typeof e!="object"||e===null?!1:tr(e.type)?.toLowerCase()==="card_error"||br(e)!==void 0}function Hn(e){let t=ms(e)?.toLowerCase()??"",a=`${Dn(e)?.toLowerCase()??""} ${t}`;return a.includes("popup")&&a.includes("block")}var Pn=require("react/jsx-runtime"),yo=45,ys=1e3,fs=11e3,gs=["https://www.paypal.com","https://www.sandbox.paypal.com"],Ja="We couldn't open PayPal. Try again or choose another payment method.",hs={width:"100%",minHeight:yo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Xa(e){return e.includes("No ack for postMessage init()")&&gs.some(t=>e.includes(t))&&e.includes("10000ms")}function Ps(e){return e?`${Ja} Allow pop-ups for this site, then try again.`:Ja}function Za({sessionId:e,nonce:t,billingApiUrl:n,email:a,clientId:r,environment:i,currency:u,isSubscription:d,providerObjectType:b,onTokenizedBody:M,onComplete:g,onErrorChange:R,onDecline:C,onTechnicalFailure:k,isProcessing:p=!1,onLoadStateChange:h,onInitializationStateChange:E,allowAutomaticRetry:_=!0,onButtonClick:f,runBeforeButtonClick:ge,session:x,existingOrderId:oe,telemetry:ae,telemetryContext:j,debug:K=!1}){let ce=gn(),pe=(0,D.useMemo)(()=>{if(ce)return null;let U=ro({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Zt.SDK_VERSION,enabled:ae!==!1});return U.setCheckoutContext(j??{}),U.beginCheckout(j??{}),U},[n,ce,ae,j?.checkoutMode,j?.layout]),De=(0,D.useMemo)(()=>Tt(ce),[ce]);(0,D.useEffect)(()=>()=>{pe&&pe.flush().catch(()=>{}).finally(()=>pe.destroy())},[pe]);let P=(0,D.useMemo)(()=>({error:U=>{De?De.error(U):pe?.error(U)},log:U=>{De?De.log(U):pe?.log(U)},performance:U=>{De?De.performance(U):pe?.performance(U)},terminal:U=>{De?De.terminal(U):pe?.terminal(U)},startTiming:()=>De?.now()??pe?.now()??0,elapsed:U=>De?.elapsed(U)??Math.max(0,(pe?.now()??U)-U)}),[De,pe]),ie=(0,D.useRef)(null),Le=(0,D.useRef)(0),we=(0,D.useRef)(null),he=(0,D.useRef)(!1),[Z,me]=(0,D.useState)(!1),[J,ne]=(0,D.useState)(!1),[ke,xe]=(0,D.useState)(0),se=(0,D.useRef)(0),[W,S]=(0,D.useState)(!1),de=(0,D.useRef)(!1),Qe=(0,D.useRef)(!1),[Ve,ue]=(0,D.useState)(!1),[L,Pe]=(0,D.useState)(!1),X=(0,D.useMemo)(()=>n.replace(/\/+$/,""),[n]),be=b??(d?"subscription":"order"),rt=b==="order"||b==="setup_token",qe=(0,D.useMemo)(()=>JSON.stringify([X,r,u,i??"",be,rt,e,oe??""]),[X,r,u,i,oe,be,rt,e]),ct=(0,D.useRef)(qe),ve=ct.current!==qe,[re,ot]=(0,D.useState)([]),ee=U=>{K&&ot(it=>[...it,`${new Date().toISOString().slice(11,23)} ${U}`])},yt=(0,D.useRef)(M),He=(0,D.useRef)(g),Ke=(0,D.useRef)(R),Nt=(0,D.useRef)(C),at=(0,D.useRef)(k),nn=(0,D.useRef)(f),T=(0,D.useRef)(h),Ce=(0,D.useRef)(E),et=(0,D.useRef)(ge),tt=(0,D.useRef)(x),It=(0,D.useRef)(a),ft=(0,D.useRef)(t),Oe=(0,D.useRef)(null),gt=(0,D.useRef)(0),Fe=(0,D.useRef)(null),rn=(0,D.useRef)(null),Ye=(0,D.useRef)(new Map),zn=(0,D.useRef)(new Map),Wt=(0,D.useRef)(!1);(0,D.useEffect)(()=>(Wt.current=!0,()=>{Wt.current=!1}),[]),(0,D.useEffect)(()=>{yt.current=M},[M]),(0,D.useEffect)(()=>{He.current=g},[g]),(0,D.useEffect)(()=>{Ke.current=R},[R]),(0,D.useEffect)(()=>{Nt.current=C},[C]),(0,D.useEffect)(()=>{at.current=k},[k]),(0,D.useEffect)(()=>{nn.current=f},[f]),(0,D.useEffect)(()=>{T.current=h},[h]),(0,D.useEffect)(()=>{Ce.current=E},[E]),(0,D.useEffect)(()=>{et.current=ge},[ge]),(0,D.useEffect)(()=>{tt.current=x},[x]),(0,D.useEffect)(()=>{It.current=a},[a]),(0,D.useEffect)(()=>{ft.current=t},[t]),(0,D.useEffect)(()=>{se.current=ke},[ke]),(0,D.useEffect)(()=>{W&&we.current?.focus()},[W,ke]);let wn=(0,D.useCallback)(()=>{window.setTimeout(()=>{we.current?.focus()},0)},[]),Nn=(0,D.useCallback)(()=>{me(!1),xe(U=>U+1)},[]),Un=(0,D.useCallback)(()=>{S(!1),(ie.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ie.current)?.focus?.()},[]);(0,D.useEffect)(()=>{!Z||!he.current||(he.current=!1,Un())},[Un,Z,ke]);let Ut=(0,D.useCallback)((U,it)=>{let Ge=at.current;if(Ge){Ge("paypal",U,it);return}Ke.current?.(Ps(it?.popupBlocked??Hn(U)))},[]),pt=()=>{Fe.current?.timer&&(clearTimeout(Fe.current.timer),Fe.current.timer=null)},dn=()=>{pt();let U=gt.current+1;return gt.current=U,rn.current=null,Fe.current={generation:U,timer:null,yieldedControl:!1},S(!1),U},$t=U=>U!==void 0&&Fe.current?.generation!==U?!1:(pt(),Fe.current=null,rn.current=null,!0),jt=U=>{let it=U?.generation??Fe.current?.generation??gt.current;(!U?.generation||Fe.current?.generation===it)&&(pt(),Fe.current=null),rn.current=it,U?.showRetry&&S(!0),U?.remount&&Nn(),U?.focus!==!1&&wn()},Vt=U=>Fe.current?.generation===U&&rn.current!==U,Mt=U=>{typeof document<"u"&&document.visibilityState!=="visible"||(pt(),U.timer=setTimeout(()=>{Fe.current?.generation===U.generation&&(Fe.current=null,rn.current=U.generation,Ut(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),S(!0),Nn(),wn())},600))},le=()=>{let U=Fe.current;U?.yieldedControl&&Mt(U)},$n=()=>{let U=Fe.current;U&&(U.yieldedControl=!0,pt())},on=U=>{let it=Oe.current;return it&&zn.current.set(U,it),U};(0,D.useEffect)(()=>{let U=()=>{document.visibilityState==="visible"?le():$n()};return document.addEventListener("visibilitychange",U),window.addEventListener("focus",le),window.addEventListener("blur",$n),()=>{document.removeEventListener("visibilitychange",U),window.removeEventListener("focus",le),window.removeEventListener("blur",$n),pt()}},[]),(0,D.useEffect)(()=>{ct.current!==qe&&(ct.current=qe,de.current=!1,Qe.current=!1,me(!1),ne(!1),ue(!1),Ce.current?.("loading"))},[qe]),(0,D.useEffect)(()=>{Xe(()=>T.current?.(Z&&!Ve))},[Z,Ve]);let Gt=(0,Zt.normalizeGatewayEnvironment)(i);(0,D.useEffect)(()=>{let U=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",it=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(ee(`mount clientId=${U} env=${i??"(unset)"}\u2192${Gt??"live"} ccy=${u} sub=${d}`),ee(`ua=${it.slice(0,80)}${it.length>80?"\u2026":""}`),!r){ee("FAIL: clientId empty \u2014 gateway misconfigured"),ue(!0),P.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(!ie.current){ee("FAIL: containerRef not attached");return}Le.current=P.startTiming(),P.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ge=!1,We=!1,Je=()=>Ge||We,An,jn=!1,ar=()=>{An=(0,Zt.generateIdempotencyKey)(),An||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),jn=!0},kn=null,st=!1,qt=null,Rn=!1,St=()=>{!qt||Rn||(Rn=!0,qt.close().catch(()=>{}))},Ft=null,un=()=>{Ft!==null&&(P.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),P.performance({stage:"overlay_return",durationMs:P.elapsed(Ft),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Ft=null)},an=!1,Jt=ie.current,Xt=null,At=null,Ae=[],wt=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let l=m.getBoundingClientRect();return`${Math.round(l.width)}\xD7${Math.round(l.height)}`},ht=m=>{if(!m)return"(empty)";try{let l=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),F=l.pathname.toLowerCase();return F.includes("checkcaptcha")||F.includes("captcha")?`CAPTCHA(${l.host}${F})`:F.includes("risk")||F.includes("challenge")?`RISK(${l.host}${F})`:F.includes("smart/buttons")?`smart-buttons(${l.host})`:`${l.host}${F}`.slice(0,100)}catch{return m.slice(0,80)}},En=m=>{let l=m.getAttribute("src"),F=m.getAttribute("srcdoc"),Re=m.getAttribute("name"),Te=m.getAttribute("sandbox"),Q=[];return l&&Q.push(`src=${ht(l)}`),F&&Q.push(`srcdoc[${F.length}ch]`),!l&&!F&&Q.push("src=(empty) srcdoc=(empty)"),Re&&Q.push(`name=${Re.slice(0,40)}`),Te!==null&&Q.push(`sandbox="${Te.slice(0,40)}"`),Q.join(" ")},ir=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let l=m.contentDocument;if(!l)return"cd=null";let F=l.body?.children.length??0,Re=l.body?.innerHTML.length??0,Te=l.head?.innerHTML.length??0;return`cd=same-origin readyState=${l.readyState} body[${F}children,${Re}ch] head[${Te}ch]`}catch(l){return`cd=cross-origin(${l.message.slice(0,30)})`}},Dt=[],sn=m=>{if(Je())return;let l=m.message??String(m.error??"(no message)");l&&(l.toLowerCase().includes("paypal")||l.toLowerCase().includes("zoid")||l.toLowerCase().includes("postrobot")||l.toLowerCase().includes("storage"))&&(ee(`window:error ${l.slice(0,140)}`),Dt.push(l))},Bt=m=>{if(Je())return;let l=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");l&&(l.toLowerCase().includes("paypal")||l.toLowerCase().includes("zoid")||l.toLowerCase().includes("postrobot")||l.toLowerCase().includes("storage"))&&(ee(`window:rejection ${l.slice(0,140)}`),Dt.push(l))};K&&typeof window<"u"&&(window.addEventListener("error",sn),window.addEventListener("unhandledrejection",Bt));let Wn={value:0};if(K&&typeof PerformanceObserver<"u")try{At=new PerformanceObserver(m=>{if(!Je())for(let l of m.getEntries()){if(!l.name.toLowerCase().includes("paypal"))continue;Wn.value+=1;let F=Math.round(l.duration);ee(`net ${F}ms ${l.name.slice(0,90)}`)}}),At.observe({type:"resource",buffered:!0})}catch{}let pn=()=>{for(Xt?.disconnect(),Xt=null,At?.disconnect(),At=null;Ae.length;)clearTimeout(Ae.pop());K&&typeof window<"u"&&(window.removeEventListener("error",sn),window.removeEventListener("unhandledrejection",Bt))},Vn=m=>{if(!m)return!1;let l=m.toLowerCase();return l.includes("zoid destroyed")||l.includes("destroyed all components")||l.includes("window closed")||l.includes("detected container element removed")},Lt=m=>{if(Je()||Vn(m))return;let l=qn(m)??m;Xe(()=>Ke.current?.(l))},In=m=>{Ge||(ue(!0),m.includes("paypal_ineligible")||P.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",m))},ze=(m,l=!1)=>{if(Ge)return;let F=de.current||!_;if(st)return;st=!0,We=!0,pn(),St();let Re=l||Xa(m);if(Re&&_&&!de.current){de.current=!0,me(!1),Pe(!1),ne(!0),Ce.current?.("retrying"),kn=setTimeout(()=>{Ge||xe(Te=>Te+1)},ys);return}if(Re||F){if(me(!1),Pe(!1),ne(!1),ue(!0),Ce.current?.("exhausted"),!Qe.current){Qe.current=!0;let Te=Xa(m)?"paypal_init_timeout":l?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",Te)}return}In(m)};ue(!1);let A=async(m,l=Oe.current)=>{if(Je())return;let F=l?.sessionId??e;if(yt.current){await yt.current(m,{sessionId:F,accountPatch:l?.accountPatch,nonce:l?.nonce});return}let Re=P.startTiming();P.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Te=()=>{P.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),P.performance({stage:"processing",durationMs:P.elapsed(Re),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Q=tt.current,Ze=l?.accountPatch?.email??It.current,O=l?.accountPatch?.userId??Q?.customer?.id??Q?.accountData?.userId??"",I=await new mo.PaymentAPI(X,{telemetry:!1}).processPayment(O,{sessionId:F,nonce:l?.nonce??ft.current,tokenizedData:m,accountData:{userId:O,email:Ze??Q?.customer?.email??"",firstName:l?.accountPatch?.firstName??Q?.customer?.firstName??Q?.accountData?.firstName??"",lastName:l?.accountPatch?.lastName??Q?.customer?.lastName??Q?.accountData?.lastName??"",country:l?.accountPatch?.country??Q?.customer?.country??Q?.accountData?.country??void 0,zip:l?.accountPatch?.zip??Q?.customer?.zip??Q?.accountData?.zip??void 0}});if(I.ok){if(We||Ge&&Wt.current)return;Te(),P.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Xe(()=>He.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Je())return;let z=await I.json().catch(()=>null),ye=z?.message??"PayPal payment failed.",Ct=qn(ye)??ye;Te(),I.status===400&&(typeof z?.declineCode=="string"||!Array.isArray(z?.fields))?P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):I.status===400||I.status===422?P.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):P.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:I.status>=500?"5xx":I.status>=400?"4xx":I.status>=300?"3xx":"unknown",failureCategory:I.status>=500?"server_error":void 0}),Lt(Ct),Xe(()=>Nt.current?.(Et("paypal",Ct,{code:z?.code,declineCode:z?.declineCode})));return}catch(Q){if(Je())return;Te(),P.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ze=Q instanceof Error?Q.message:"PayPal payment failed.",O=qn(Ze)??Ze;Lt(O),Xe(()=>Nt.current?.(Et("paypal",O)));return}},$=()=>new Zt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),V=m=>Je()?Promise.reject($()):Promise.resolve(m),Ee=async m=>{if(Je())throw $();jn||ar();let l=Oe.current,F=l?.sessionId??e,Re=l?.nonce??ft.current;P.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Te=await new mo.PaymentAPI(X,{telemetry:!1}).createSessionIntent(F,Re??"",rt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Zt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:be==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:An});if(Je())throw $();if(Te.provider!=="paypal"||Te.providerObjectType!==be)throw new Error(m);return P.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Te.providerObjectId},Me=(m,l)=>{let F=l?.nonce??ft.current;if(!F)return;let Re=l?.sessionId??e,Te=br(m)??Dn(m)??"provider_declined";new mo.PaymentAPI(X,{telemetry:!1}).reportSessionIntentDecline(Re,F,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Te}).catch(()=>{})},te=ke;ee("loadScript:scheduled (deferred 1 tick)");let y=null,q=setTimeout(()=>{if(Ge){ee("loadScript:skipped (cancelled before defer ran)");return}ee("loadScript:start");let m=Gt==="live"?"production":Gt;y=(0,Qa.loadScript)({clientId:r,currency:u,...be==="subscription"?{intent:"subscription",vault:!0}:be==="order"?{intent:"capture"}:{},...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),y.then(l=>{if(ee(`loadScript:resolved inactive=${Je()} ns=${!!l} buttons=${!!l?.Buttons}`),Je())return;if(!l?.Buttons){ee("FAIL: namespace missing Buttons factory"),ze("PayPal SDK did not expose the Buttons factory.");return}P.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),P.performance({stage:"provider_ready",durationMs:P.elapsed(Le.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),P.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let F=async H=>{if(Je()||se.current!==te)return;let I=H.vaultSetupToken??H.subscriptionID??H.orderID??"",z=I?zn.current.get(I):Ye.current.get(te);if(!(!z||!Vt(z.generation))&&$t(z.generation)){zn.current.delete(I),Ye.current.delete(z.surfaceKey),un();try{if(Pe(!0),Xe(()=>Ke.current?.(null)),!I)throw new Zt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await A(be==="setup_token"?{id:I,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Zt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:rt?{id:I,isPaypal:!0,gateway:"paypal",paymentMethodType:Zt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:{id:I,isPaypal:!0},z)}catch(ye){Lt(ye instanceof Error?ye.message:"PayPal capture failed.")}finally{Je()||Pe(!1)}}},Re=l.Buttons({style:{layout:"horizontal",height:yo,tagline:!1},onClick:async(H,I)=>{if(Je()){await I.reject();return}ar();let z=et.current,ye={};if(z)try{let Ot=await z("paypal");if(Je()){await I.reject();return}if(!Ot.proceed){Oe.current=null,Ye.current.delete(te),await I.reject();return}ye={sessionId:Ot.sessionId,accountPatch:Ot.accountPatch,nonce:Ot.nonce}}catch(Ot){ee(`onClick:runBeforeButtonClick rejected msg=${(Ot instanceof Error?Ot.message:String(Ot)).slice(0,120)}`),Oe.current=null,Ye.current.delete(te),await I.reject();return}Xe(()=>nn.current?.("paypal"));let Ht={generation:dn(),surfaceKey:te,...ye};Oe.current=Ht,Ye.current.set(te,Ht),await I.resolve(),P.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),P.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),P.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Ft=P.startTiming()},createOrder:be==="order"?oe?()=>V(oe).then(on):()=>Ee("Failed to create PayPal order.").then(on):void 0,createSubscription:be==="subscription"?oe?()=>V(oe).then(on):()=>Ee("Failed to create PayPal subscription.").then(on):void 0,createVaultSetupToken:be==="setup_token"?()=>Ee("Failed to create PayPal setup token.").then(on):void 0,onApprove:F,onCancel:()=>{if(Je())return;let H=Ye.current.get(te)??Oe.current;H&&Ye.current.delete(H.surfaceKey),Oe.current=null,un(),P.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),he.current=!0,jt({generation:H?.generation,remount:!0,focus:!1})},onError:H=>{if(Je()||se.current!==te)return;let I=H instanceof Error?H.message:"PayPal failed to render.";if(ee(`onError rendered=${an} msg=${I.slice(0,120)}`),an){let z=Ye.current.get(te)??Oe.current;if(z&&!Vt(z.generation)||!z&&rn.current===gt.current)return;if(Vn(I)){$t(z?.generation);return}if(un(),Or(H)){P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Me(H,z),Xe(()=>Nt.current?.(Et("paypal",I))),z&&Ye.current.delete(z.surfaceKey),Oe.current=null,$t(z?.generation);return}let ye=I.toLowerCase();P.error({errorCode:ye.includes("popup")&&ye.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),z&&Ye.current.delete(z.surfaceKey),Oe.current=null,jt({generation:z?.generation,remount:!0,showRetry:!0,focus:!0}),Ut(H,{code:"paypal_runtime_failed"});return}ze(I)}}),Te=Re.isEligible();if(ee(`isEligible=${Te}`),P.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Te){me(!1),ze("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}qt=Re,K&&ee(`container:dims ${wt(Jt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),K&&typeof MutationObserver<"u"&&(Xt=new MutationObserver(H=>{if(!Je()){for(let I of H)if(I.type==="childList")I.addedNodes.forEach(z=>{if(!(z instanceof Element))return;let ye=z.tagName.toLowerCase(),Ct=(z.getAttribute("title")??"").slice(0,40),Ht=ye==="iframe"?` ${En(z)}`:"";ee(`child+ ${ye}${Ct?` title="${Ct}"`:""}${Ht} dims=${wt(z)}`)});else if(I.type==="attributes"&&I.target instanceof Element){let z=I.target;if(z.tagName.toLowerCase()!=="iframe")continue;let ye=I.attributeName;(ye==="src"||ye==="srcdoc")&&ee(`attr~ iframe ${ye}=${ye==="srcdoc"?`[${(z.getAttribute("srcdoc")??"").length}ch]`:ht(z.getAttribute("src"))} dims=${wt(z)}`)}}}),Xt.observe(Jt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ze=H=>{if(Je()||an)return;let I=Jt.querySelectorAll("iframe"),z=typeof document<"u"&&"hasStorageAccess"in document;ee(`watchdog:${H} container=${wt(Jt)} children=${Jt.childElementCount} iframes=${I.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${z} paypalNetRequests=${Wn.value}`),I.forEach((ye,Ct)=>{let Ht=(ye.getAttribute("title")??"").slice(0,40);ee(` iframe[${Ct}] ${wt(ye)}${Ht?` title="${Ht}"`:""} ${En(ye)}`);let Ot=ir(ye);Ot&&ee(` ${Ot}`)}),Dt.length===0&&ee(" (no PayPal/zoid window errors captured)")};K&&(Ae.push(setTimeout(()=>Ze("3s"),3e3)),Ae.push(setTimeout(()=>Ze("8s"),8e3)),Ae.push(setTimeout(()=>Ze("15s"),15e3))),ee("render:start");let O=P.startTiming();Ae.push(setTimeout(()=>{Je()||an||(ee("watchdog:11s retryable render timeout"),ze("PayPal Buttons render did not settle within 11000ms.",!0))},fs)),Re.render(Jt).then(()=>{if(ee(`render:resolved inactive=${Je()}`),pn(),Je()){St();return}an=!0,me(!0),ne(!1),Ce.current?.("ready"),P.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),P.performance({stage:"checkout_render",durationMs:P.elapsed(O),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(H=>{let I=H instanceof Error?H.message:"PayPal failed to render.";ee(`render:rejected msg=${I.slice(0,120)}`),pn(),ze(I)})}).catch(l=>{let F=l instanceof Error?l.message:"PayPal SDK failed to load.";ee(`loadScript:rejected msg=${F.slice(0,120)}`),ze(F)})},0);return()=>{Ge=!0,clearTimeout(q),kn&&clearTimeout(kn),pn(),St()}},[_,X,r,u,i,be,rt,e,oe,ke,P]);let Yn=K?(0,Pn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ve?"#fef2f2":"#f3f4f6",border:`1px solid ${Ve?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Z} failed=${Ve})`,re.length===0?`
|
|
7
|
-
(waiting for first lifecycle event\u2026)`:`
|
|
8
|
-
${re.join(`
|
|
9
|
-
`)}`]}):null;return Ve&&!ve?K?(0,Pn.jsx)("div",{children:Yn}):null:(0,Pn.jsxs)("div",{children:[Yn,(0,Pn.jsxs)("div",{"aria-hidden":J?!0:void 0,style:J?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:yo},children:[!Z&&!J&&(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:ie,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:yo,display:"flex",opacity:Z?1:0},"aria-busy":L||p},ke)]},ke),W&&(0,Pn.jsx)("button",{ref:we,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Un,style:hs,children:"Try PayPal again"})]})}function zr(e){return(0,Pn.jsx)(Za,{...e})}function ei(e){return(0,Pn.jsx)(Za,{...e})}var zt=require("@flopay/shared"),c=require("react/jsx-runtime"),Tn="flopay_stripe_resume",ti="flopay_wallet_resume",Nr="flopay_paypal_resume",bs=250,ni="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Jo(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function go({billingApiUrl:e,sessionId:t,nonce:n,request:a}){if(!(!t||!n))try{await new bn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,a)}catch{}}function vs(e){return e instanceof zt.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Yo(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var Cs=`
|
|
9
|
+
`})]})})}var li=require("@flopay/shared"),Ft=require("react");var ci=require("react/jsx-runtime");function Vr({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:r}){let[i,m]=(0,Ft.useState)(e instanceof Promise?null:e),[d,R]=(0,Ft.useState)(t instanceof Promise||!t?null:t),g=(0,Ft.useRef)(null),v=(0,Ft.useRef)(null),b=vr(o);(0,Ft.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,Ft.useEffect)(()=>{i&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,i]),(0,Ft.useEffect)(()=>{if(i)return At(i)?.subscribe?.(b)},[b,i]),(0,Ft.useEffect)(()=>{if(!(!d||d===i))return At(d)?.subscribe?.(b)},[b,i,d]),(0,Ft.useEffect)(()=>{if(!i)return;let y=At(i);return g.current=y?.beginCheckout()??y?.now()??0,y?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{y?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,Ft.useEffect)(()=>{let y=!1;return e instanceof Promise?e.then(C=>{y||m(C)},()=>{y||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):m(e),()=>{y=!0}},[b,e]),(0,Ft.useEffect)(()=>{let y=!1;if(!t){R(null);return}return t instanceof Promise?t.then(C=>{y||R(C)},()=>{y||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):R(t),()=>{y=!0}},[b,t]),(0,Ft.useEffect)(()=>{if(!i||v.current===i)return;v.current=i;let y=At(i);y?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),y?.performance({stage:"checkout_render",durationMs:y.elapsed(g.current??0),durationMode:"machine"})},[b,i]);let A=(0,li.resolveBillingApiUrl)(n?.billingApiUrl),D=(0,Ft.useMemo)(()=>({flopay:i,paypalFlopay:d,billingApiUrl:A,emitInstrument:b}),[i,d,A,b]);return(0,ci.jsx)(hn.Provider,{value:D,children:r})}var bo="flopay_recent_completion_";function br(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(bo+e,JSON.stringify(t))}catch{}}function Qo(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(bo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(bo+e),!1):!0}catch{return!1}}var Cr=require("@flopay/js"),Ae=require("@flopay/shared");var Hr="card";async function _s(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:m}=await e.retrieveSetupIntent(t);return{error:m,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:o,error:r}=await e.retrievePaymentIntent(t);return{error:r,intent:o??null}}async function Ts(e,t,n,o){if(o){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:r,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:r??null}}function ta(e,t){return Object.assign(e,{checkoutMethod:t})}function qn(e,t){let n=e instanceof Ae.FloPayError?e:new Ae.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Kr(e,t){try{return await e()}catch(n){throw qn(n,t)}}function di(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 xs(e){return e.status==="succeeded"||e.status==="declined"}async function ui(e){if(typeof document>"u"||typeof window>"u")throw new Ae.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ae.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,o=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let v=new AbortController,b=()=>v.abort();e.signal?.aborted?v.abort():e.signal?.addEventListener("abort",b);let A=window.setTimeout(()=>v.abort(),o);try{let D=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:v.signal});if(!D.ok)return{status:"unknown"};let y=await D.json().catch(()=>null);return As(y)}catch{return{status:"unknown"}}finally{window.clearTimeout(A),e.signal?.removeEventListener("abort",b)}},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 R=document.createElement("iframe");R.setAttribute("title","Card authentication"),R.setAttribute("allow","payment"),R.tabIndex=0,R.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(";"),R.src=e.nextActionRedirectUrl,d.appendChild(R),document.body.appendChild(d),R.focus();let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let v=await new Promise((b,A)=>{let D=!1,y=0,C=0,Q=0,J=!1,w=()=>{window.clearTimeout(y),window.clearInterval(C),window.clearTimeout(Q),window.removeEventListener("message",re),R.removeEventListener("load",U),e.signal?.removeEventListener("abort",ee)},ge=async()=>{if(!(D||J)){J=!0;try{let be=await i();if(D||!xs(be))return;D=!0,w(),b(be)}finally{J=!1}}},U=()=>{window.clearTimeout(Q),Q=window.setTimeout(()=>{ge()},250)},ee=()=>{D||(D=!0,w(),A(new Ae.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},re=be=>{if(be.source!==R.contentWindow||g&&be.origin!==g)return;let oe=be.data;!oe||typeof oe!="object"||oe.source!=="flopay-vault-3ds-return"||D||(D=!0,w(),b(null))};y=window.setTimeout(()=>{D||(D=!0,w(),A(new Ae.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),C=window.setInterval(()=>{ge()},n),R.addEventListener("load",U),window.addEventListener("message",re),e.signal?.addEventListener("abort",ee),e.signal?.aborted&&ee()});return v||await i()}finally{d.parentNode?.removeChild(d),m?.isConnected&&m.focus()}}function As(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Xn(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),r=e?.message??t,i=Gn(r)??r;return ta(new Ae.FloPayError(i,"api_error",{code:(0,Ae.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ae.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),o)}function ea(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Co(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Ms(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 pi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||Co(r)))return r;let o=e?.data;if(o&&typeof o=="object"){let r=o,i=[r.threeDSecureToken,r.clientSecret,r.stripeClientSecret,r.id];for(let d of i)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||Co(d)))return d;let m=r.gateways;if(m&&typeof m=="object"){let d=m.stripe;if(d&&typeof d=="object"){let R=d,g=[R.stripeClientSecret,R.clientSecret];for(let v of g)if(typeof v=="string"&&v.length>0&&(!t?.requirePaymentIntentClientSecret||Co(v)))return v}}}}async function Bs({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let r=pi(o,{requirePaymentIntentClientSecret:!0});if(typeof r=="string"&&r.length>0)return{type:"3ds_required",threeDSecureToken:r};if(!t)return null;try{let d=(await new Cr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Co(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function Sr({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:r,returnUrl:i,telemetry:m}){let d=e.replace(/\/+$/,""),R=t??n.id,g=o??n.clientSecret,v=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",A=n.customer?.firstName??n.accountData?.firstName??"",D=n.customer?.lastName??n.accountData?.lastName??"",y=n.customer?.country??n.accountData?.country??void 0,C=n.customer?.zip??n.accountData?.zip??void 0,Q=new Cr.PaymentAPI(d,m===!1?{telemetry:!1}:void 0),J=await Ms(()=>Q.processPayment(v,{sessionId:R,nonce:g,tokenizedData:r,accountData:{userId:v,email:b,firstName:A,lastName:D,country:y,zip:C},returnUrl:i??ea(n)}));if(J.ok){let U=typeof J.json=="function"?await J.json().catch(()=>null):null;return(0,Ae.isAuthorizationOnlySession)(n)||U?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof U?.paymentId=="string"?U.paymentId:n.paymentId,sessionId:typeof U?.sessionId=="string"?U.sessionId:R,authorizationExpiresAt:typeof U?.authorizationExpiresAt=="string"?U.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:zr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:zr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}}let w;try{w=await J.json()}catch{throw new Ae.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:J.status})}if(w?.type==="paypal_redirect_required"||w?.type==="3ds_required"){let U=pi(w);if(!U)throw new Ae.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:J.status});return{type:w.type,threeDSecureToken:U,paymentMethodId:w.paymentMethodId}}if(w?.gatewayErrorCode==="authentication_required"){let U=await Bs({billingApiUrl:d,sessionId:R,nonce:g,responseJson:w});if(U)return U;throw ta(new Ae.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ge=new Ae.FloPayError(w?.message??"Payment failed. Please try again.","api_error",{code:w?.code??w?.gatewayErrorCode,declineCode:w?.declineCode??w?.gatewayDeclineReason,statusCode:J.status});throw Object.assign(ge,{telemetryOutcome:(0,Ae.classifyPaymentRejection)(J.status,w)})}async function So(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:r,sessionId:i,session:m,returnUrl:d,telemetry:R}){let g=t?.getRawProvider();if(!g)throw qn(new Ae.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw ta(new Ae.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let v=(0,Ae.isSetupIntentClientSecret)(e.threeDSecureToken),b=null,A=e.paymentMethodId,D=await Kr(()=>_s(g,e.threeDSecureToken,v),"card");if(D){if(D.error)throw qn(new Ae.FloPayError(D.error.message??`Failed to retrieve 3DS ${v?"setup":"payment"} status.`,"api_error",{code:D.error.code}),"card");let C=D.intent;!A&&C?.payment_method&&(typeof C.payment_method=="string"?A=C.payment_method:"id"in C.payment_method&&(A=C.payment_method.id??void 0))}let y=A?await Kr(()=>Ts(g,e.threeDSecureToken,{payment_method:A,return_url:d??ea(m)??window.location.href},v),"card"):null;if(y){if(y.error)throw qn(new Ae.FloPayError(y.error.message??"3DS authentication failed.","api_error",{code:y.error.code}),"card");b=y.intent}else{let C=await Kr(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(C.error)throw qn(new Ae.FloPayError(C.error.message??"3DS authentication failed.","api_error",{code:C.error.code}),"card");b=(v?C.setupIntent:C.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let C=await Sr({billingApiUrl:r,sessionId:i,session:m,telemetry:R,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:d});return C.type==="success"?{...C.result,paymentIntentId:C.result.paymentIntentId??b.id,paymentMethodId:C.result.paymentMethodId??A}:So(C,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:r,sessionId:i,session:m,returnUrl:d,telemetry:R})}throw qn(new Ae.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let v=(n??t)?.getRawProvider();if(!v)throw qn(new Ae.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:A}=await Kr(()=>v.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(A)throw qn(new Ae.FloPayError(A.message??"PayPal authorization failed.","api_error",{code:A.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await Kr(()=>v.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??ea(m)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw qn(new Ae.FloPayError(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ae.FloPayError("Unsupported payment redirect state.","api_error")}function lr(e){if(e instanceof Ae.FloPayError){let o=Gn(e.message);return o&&o!==e.message?Object.assign(new Ae.FloPayError(o,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Gn(t)??t;return new Ae.FloPayError(n,"api_error")}function wo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ae.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 ko({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:o,telemetry:r}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[m,d]=await Promise.all([(0,Cr.loadFloPay)(e,{billingApiUrl:n,locale:o,telemetry:r}),i?(0,Cr.loadFloPay)(t,{billingApiUrl:n,locale:o,telemetry:r}).catch(R=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",R),null)):Promise.resolve(null)]);return{flopay:m,paypalFlopay:t?i?d:m:null}}var Zn=require("@flopay/js"),f=require("@flopay/shared"),vt=require("@stripe/react-stripe-js"),a=Ya(require("react"),1);function mi(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 yi={alipay:new URL("./payment-logos/alipay.svg",Fe).href,bancontact:new URL("./payment-logos/bancontact.svg",Fe).href,blik:new URL("./payment-logos/blik.svg",Fe).href,eps:new URL("./payment-logos/eps.svg",Fe).href,giropay:new URL("./payment-logos/giropay.svg",Fe).href,ideal:new URL("./payment-logos/ideal.svg",Fe).href,klarna:new URL("./payment-logos/klarna.svg",Fe).href,p24:new URL("./payment-logos/p24.svg",Fe).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",Fe).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",Fe).href};var jn=require("react"),fi=require("react/jsx-runtime");function wr({capture:e,html:t,messageToken:n,expectedOrigin:o,theme:r,containerStyle:i,onReady:m,onError:d,onValidation:R}){let g=(0,jn.useRef)(null),v=(0,jn.useRef)(m),b=(0,jn.useRef)(d),A=(0,jn.useRef)(R);v.current=m,b.current=d,A.current=R;let D=(0,jn.useRef)(r);return D.current=r,(0,jn.useEffect)(()=>{let y=g.current;if(!y)return;let C=!0,Q=!1,J=()=>{!C||Q||(Q=!0,v.current?.())},w=e.on("ready",()=>{J()}),ge=e.on("error",re=>{b.current?.(re.message??"There was a problem loading the secure card form.")}),U=e.on("validation",re=>{A.current?.(re.message??null)}),ee={html:t,...n?{messageToken:n}:{},...o?{expectedOrigin:o}:{},...D.current?{theme:D.current}:{}};return e.mount(y,ee).then(()=>{J()}).catch(re=>{C&&b.current?.(re instanceof Error?re.message:"Failed to load the secure card form.")}),()=>{C=!1,w(),ge(),U(),e.unmount()}},[e,t,n,o]),(0,jn.useEffect)(()=>{r&&e.applyTheme?.(r)},[e,r]),(0,fi.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields",style:i})}function kr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let o=parseInt(n[1],16),r=Math.max(0,Math.min(1,1-t)),i=Math.round((o>>16&255)*r),m=Math.round((o>>8&255)*r),d=Math.round((o&255)*r);return`#${(1<<24|i<<16|m<<8|d).toString(16).slice(1)}`}function na(e){if(typeof e=="number"||typeof e=="string")return e}function Io({appearance:e,buttonsStyles:t,layout:n="default"}){let o=e?.variables,r=g=>typeof g=="string"&&g?g:void 0,i=t.submitButton,m=r(o?.colorPrimary)??r(i?.backgroundColor)??"#4A49FF",d=n==="buttons",R=t.nameInput;return{primaryColor:m,primaryHoverColor:r(o?.colorPrimaryHover)??kr(m,.12),inputBackgroundColor:r(t.cardInputBackground)??r(o?.colorBackground)??"#ffffff",textColor:r(t.cardInputColor)??r(R?.color)??r(o?.colorText)??"#262833",borderColor:r(t.cardInputBorder)??(d?"#e5e7eb":"#A4A4FF"),placeholderColor:r(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:r(o?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:r(R?.fontFamily)??r(o?.fontFamily)??"Poppins, sans-serif",fontSize:r(t.cardInputFontSize)??r(o?.fontSizeBase)??"16px",fontWeight:String(na(R?.fontWeight)??400),borderRadius:r(o?.borderRadius)??"8px"}}var l=require("react/jsx-runtime"),Bn="flopay_stripe_resume",gi="flopay_wallet_resume";function ki(e){return e instanceof f.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Ro(e,t,...n){let o=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:o});try{return await new Zn.PaymentAPI(e).createSessionIntent(...n)}catch(r){throw ki(r)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),r}}var Yr="flopay_paypal_resume",Fs=250,hi="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ia(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function _o({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new Zn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function Ds(e){return e instanceof f.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ra(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var Ls=`
|
|
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 @@ ${re.join(`
|
|
|
27
27
|
0% { opacity: 1; transform: translateX(0) scale(1); }
|
|
28
28
|
100% { opacity: 0; transform: translateX(16px) scale(0.97); }
|
|
29
29
|
}
|
|
30
|
-
`,fo=44;function Xo(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var Ss={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ci={width:"100%",minHeight:fo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function ws(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ri(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function di(e){return e==="paypal"?"PayPal":(0,v.getStripeMethodDisplayName)(e)}function ks(e,t){let n=`We couldn't open ${di(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function ui(e){let t=(0,o.useRef)(0),n=(0,o.useRef)(null),a=(0,o.useRef)(null),r=(0,o.useCallback)((p=a.current)=>{let h=p;h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),i=(0,o.useCallback)((p,h)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(p),p.timer=setTimeout(()=>{p.timer=null,a.current?.generation===p.generation&&(a.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"}))},h))},[r,e]),u=(0,o.useCallback)(p=>{p.yieldedControl&&i(p,600)},[i]),d=(0,o.useCallback)(p=>{r();let h=t.current+1;t.current=h,n.current=null;let E={generation:h,method:p,timer:null,yieldedControl:!1};return a.current=E,h},[r]),b=(0,o.useCallback)(p=>{let h=a.current;return typeof p=="number"&&h?.generation!==p?!1:(r(h),a.current=null,(typeof p!="number"||n.current===p)&&(n.current=null),!0)},[r]),M=(0,o.useCallback)(p=>{let h=a.current,E=p??h?.generation??t.current;(!p||h?.generation===p)&&(r(h),a.current=null),n.current=E},[r]),g=(0,o.useCallback)(p=>n.current===(p??t.current),[]),R=(0,o.useCallback)(p=>a.current?.generation===p&&n.current!==p,[]),C=(0,o.useCallback)(()=>{let p=a.current;p&&u(p)},[u]),k=(0,o.useCallback)(()=>{let p=a.current;p&&(p.yieldedControl=!0,r(p))},[r]);return(0,o.useEffect)(()=>{let p=()=>{document.visibilityState==="visible"?C():k()},h=()=>{k()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",h),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",h),window.removeEventListener("focus",C),r()}},[r,k,C]),{startAttempt:d,finishAttempt:b,invalidateAttempt:M,isAttemptInvalidated:g,isAttemptCurrent:R}}function Rs(e){let t=(0,v.getPostalCodeExample)(e);return`Enter a valid ${(0,v.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Es(e,t,n){let a=(0,v.isPostalCodeSupported)(e),r=t.trim(),i=n&&a,u=i&&!r,d=i&&!!r&&!(0,v.isValidPostalCode)(e,r);return{visible:n,supported:a,required:i,empty:u,malformed:d}}function oi(e,t){return t instanceof zt.FloPayError?t:new zt.FloPayError(t instanceof Error?t.message:`${ws(e)} before-click hook failed.`,"validation_error")}function Wo(){return(0,c.jsx)("style",{children:Cs})}function Is(e){return typeof e=="number"?`${e}px`:e}function pi(e,t){let n=e.availablePaymentMethods;return n&&t.some(a=>n[a])?"ready":"unavailable"}function mi({state:e,placeholderTestId:t,borderRadius:n=8,children:a}){return e==="unavailable"||e==="load_error"?null:(0,c.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,c.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,c.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:a})]})}function ai(e){return e!=="unavailable"&&e!=="load_error"}function ho(e){return(0,c.jsx)(xs,{...e})}function ii({sessionId:e,nonce:t,email:n,billingApiUrl:a,onTokenizedBody:r,onErrorChange:i,isProcessing:u=!1,onButtonClick:d,onDecline:b,onTechnicalFailure:M,runBeforeButtonClick:g,onLoadStateChange:R,placeholderBorderRadius:C}){let k=gn(),p=(0,mt.useStripe)(),h=(0,mt.useElements)(),[E,_]=(0,o.useState)("loading");(0,o.useEffect)(()=>{R?.(E)},[E,R]);let[f,ge]=(0,o.useState)(!1),x=(0,o.useRef)(!1),oe=(0,o.useRef)(null),ae=(0,o.useRef)(null),[j,K]=(0,o.useState)(0),[ce,pe]=(0,o.useState)(!1),De=(0,o.useRef)(!1),P=(0,o.useRef)(new Map),{startAttempt:ie,finishAttempt:Le,invalidateAttempt:we,isAttemptInvalidated:he,isAttemptCurrent:Z}=ui((W,S,de)=>{M?.(W,S,{...de,popupBlocked:de?.popupBlocked??Hn(S)}),pe(!0),K(Qe=>Qe+1)});(0,o.useEffect)(()=>{ce&&ae.current?.focus()},[ce,j]);let me=(0,o.useCallback)(()=>{K(W=>W+1)},[]),J=(0,o.useCallback)((W,S,de)=>{we(de),M?.("paypal",W,{code:S,popupBlocked:Hn(W)}),pe(!0),me()},[we,M,me]),ne=(0,o.useCallback)(()=>{window.setTimeout(()=>{(oe.current?.querySelector("iframe")??oe.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{De.current&&(De.current=!1,ne())},[ne,j]);let ke=(0,o.useCallback)(()=>{pe(!1),i?.(null),ne()},[ne,i]);(0,o.useEffect)(()=>{if(!p||x.current)return;let W=new URLSearchParams(window.location.search),S=W.get("payment_intent"),de=W.get("payment_intent_client_secret"),Qe=W.get("redirect_status");if(!S||!de)return;x.current=!0;let Ve;try{let L=localStorage.getItem(Nr);if(L){let Pe=JSON.parse(L);Pe.clientSecret===de&&(Ve={...Pe.accountPatch?{accountPatch:Pe.accountPatch}:{},...Pe.sessionId?{sessionId:Pe.sessionId}:{},...Pe.nonce?{nonce:Pe.nonce}:{}})}}catch{}try{localStorage.removeItem(Nr)}catch{}let ue=new URL(window.location.href);ue.searchParams.delete("payment_intent"),ue.searchParams.delete("payment_intent_client_secret"),ue.searchParams.delete("redirect_status"),window.history.replaceState({},"",ue.toString()),(async()=>{try{if(ge(!0),Qe==="failed"){let X="PayPal payment was declined. Please try again.";i?.(X),b?.(Et("paypal",X));return}let{paymentIntent:L,error:Pe}=await p.retrievePaymentIntent(de);if(Pe){i?.(Pe.message??"Failed to retrieve PayPal payment status.");return}if(L&&(L.status==="requires_capture"||L.status==="succeeded")){let X=typeof L.payment_method=="string"?L.payment_method:L.payment_method?.id;r({id:X??L.id,type:"card",threeDSecureActionResultTokenId:L.id,isPaypal:!0},Ve)}else{let X="PayPal payment was not completed. Please try again.";i?.(X),b?.(Et("paypal",X))}}catch(L){i?.(L instanceof Error?L.message:"Failed to complete PayPal payment.")}finally{ge(!1)}})()},[p,r,i,b]);let xe=(0,o.useCallback)(async W=>{if(u||f){W.reject();return}let S=g?await g("paypal"):{proceed:!0};if(!S.proceed){P.current.delete(j),W.reject();return}let de=ie("paypal");P.current.set(j,{generation:de,accountPatch:S.accountPatch,sessionId:S.sessionId,nonce:S.nonce}),pe(!1),d?.("paypal"),W.resolve()},[P,u,d,g,ie,f,j]),se=(0,o.useCallback)(async W=>{if(!p||!h)return;let S=P.current.get(j);if(S&&!Z(S.generation)){P.current.delete(j);return}if(!S&&he()||S&&!Le(S.generation))return;S||Le();let de=S??null;if(P.current.delete(j),!de&&g){let L=await g("paypal");if(!L.proceed){W.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}de={accountPatch:L.accountPatch,sessionId:L.sessionId,nonce:L.nonce}}let Qe=de?.sessionId??e,Ve=de?.nonce??t,ue=de?.accountPatch?.email??n;try{if(ge(!0),i?.(null),!Qe||!ue)throw new Error("Missing sessionId or email for PayPal payment");let L=p.createPaymentMethod,{error:Pe,paymentMethod:X}=await L({type:"paypal"});if(Pe){J(Pe,"stripe_paypal_create_payment_method_failed",S?.generation),W.paymentFailed({reason:"fail"});return}let be=await new bn.PaymentAPI(a).createSessionIntent(Qe,Ve??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:X?.id??null,intentKind:"payment"});if(be.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let rt=be.clientSecret,qe={return_url:window.location.href};if(X?.id&&(qe.payment_method=X.id),typeof window<"u")try{localStorage.setItem(Nr,JSON.stringify({clientSecret:rt,sessionId:Qe,nonce:Ve,accountPatch:de?.accountPatch}))}catch{}let{error:ct,paymentIntent:ve}=await p.confirmPayment({clientSecret:rt,confirmParams:qe,redirect:"if_required"});if(ct){if(typeof window<"u")try{localStorage.removeItem(Nr)}catch{}if(Or(ct)){let ot=ct.message??"Your payment was declined.";i?.(ot),b?.(Et("paypal",ot,{code:Dn(ct),declineCode:br(ct)})),await go({billingApiUrl:a,sessionId:Qe,nonce:Ve,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Dn(ct)??"provider_declined"}})}else J(ct,"stripe_paypal_confirm_failed",S?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Nr)}catch{}let re=typeof ve?.payment_method=="string"?ve.payment_method:ve?.payment_method?.id;r({id:re??ve?.id,type:"card",threeDSecureActionResultTokenId:ve?.id,isPaypal:!0},{accountPatch:de?.accountPatch,sessionId:Qe,nonce:Ve});return}catch(L){J(L,"stripe_paypal_failed",S?.generation)}finally{ge(!1)}},[p,h,e,t,n,a,r,i,b,g,J,Le,Z,he,j]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(mi,{state:E,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:(0,c.jsxs)("div",{ref:oe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[ce&&(0,c.jsx)("button",{ref:ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ke,style:ci,children:"Try PayPal again"}),(0,c.jsx)(mt.ExpressCheckoutElement,{onReady:W=>_(pi(W,["paypal"])),onLoadError:()=>{_("load_error"),Jo(Tt(k),"paypal","paypal")},onClick:xe,onConfirm:se,onCancel:()=>{let W=P.current.get(j);P.current.delete(j),Tt(k)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we(W?.generation),pe(!1),De.current=!0,me()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},j)]})}),f&&(0,c.jsx)(cn,{status:"processing"})]})}function si({sessionId:e,nonce:t,email:n,billingApiUrl:a,intentKind:r,expressMethods:i,onTokenizedBody:u,onErrorChange:d,onButtonClick:b,onDecline:M,onTechnicalFailure:g,runBeforeButtonClick:R,onLoadStateChange:C,placeholderBorderRadius:k}){let p=gn(),h=(0,mt.useStripe)(),E=(0,mt.useElements)(),[_,f]=(0,o.useState)("loading");(0,o.useEffect)(()=>{C?.(_)},[_,C]);let[ge,x]=(0,o.useState)(!1),oe=(0,o.useRef)(null),ae=(0,o.useRef)(null),[j,K]=(0,o.useState)(0),[ce,pe]=(0,o.useState)(!1),[De,P]=(0,o.useState)("google_pay"),ie=(0,o.useRef)(!1),Le=(0,o.useRef)("google_pay"),we=(0,o.useRef)("google_pay"),he=(0,o.useRef)(new Map),{startAttempt:Z,finishAttempt:me,invalidateAttempt:J,isAttemptInvalidated:ne,isAttemptCurrent:ke}=ui((ue,L,Pe)=>{g?.(ue,L,{...Pe,popupBlocked:Pe?.popupBlocked??Hn(L)}),P(ue),pe(!0),K(X=>X+1)});(0,o.useEffect)(()=>{ce&&ae.current?.focus()},[ce,j]);let xe=(0,o.useCallback)(()=>{K(ue=>ue+1)},[]),se=(0,o.useCallback)((ue,L,Pe,X)=>{J(X),g?.(ue,L,{code:Pe,popupBlocked:Hn(L)}),P(ue),pe(!0),xe()},[J,g,xe]),W=(0,o.useCallback)(()=>{window.setTimeout(()=>{(oe.current?.querySelector("iframe")??oe.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{ie.current&&(ie.current=!1,W())},[W,j]);let S=(0,o.useCallback)(()=>{pe(!1),d?.(null),W()},[W,d]),de=(0,o.useCallback)(async ue=>{if(!h||!E)return;let L=he.current.get(j);if(L&&!ke(L.generation)){he.current.delete(j);return}if(!L&&ne()||L&&!me(L.generation))return;L||me();let Pe=ue.expressPaymentType??L?.method??Le.current,X=L??null;he.current.delete(j);let be=ri(Pe);if(!X&&R){let re=await R(be);if(!re.proceed){ue.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}X={accountPatch:re.accountPatch,sessionId:re.sessionId,nonce:re.nonce}}let rt=be,qe=X?.sessionId??e,ct=X?.nonce??t,ve=X?.accountPatch?.email??n;try{x(!0),d?.(null);let{error:re}=await E.submit();if(re){se(Pe,re,"stripe_wallet_submit_failed",L?.generation);return}let{error:ot,paymentMethod:ee}=await h.createPaymentMethod({elements:E});if(ot||!ee){se(Pe,ot??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",L?.generation);return}if(!qe||!ve)throw new Error("Missing sessionId or email for wallet payment");let yt=await new bn.PaymentAPI(a).createSessionIntent(qe,ct??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Pe??be,paymentMethodId:ee.id,intentKind:r});if(yt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let He=yt.clientSecret,{error:Ke,intentId:Nt}=(0,zt.isSetupIntentClientSecret)(He)?await h.confirmCardSetup(He,{payment_method:ee.id}).then(at=>({error:at.error,intentId:at.setupIntent?.id})):await h.confirmCardPayment(He,{payment_method:ee.id}).then(at=>({error:at.error,intentId:at.paymentIntent?.id}));if(Ke){if(Or(Ke)){let at=Ke.message??"Your payment was declined.";d?.(at),M?.(Et(rt,at,{code:Dn(Ke),declineCode:br(Ke)})),await go({billingApiUrl:a,sessionId:qe,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Pe??be,providerDeclineReason:Dn(Ke)??"provider_declined"}})}else se(Pe,Ke,"stripe_wallet_confirm_failed",L?.generation);return}u({id:ee.id,type:"card",threeDSecureActionResultTokenId:Nt},{accountPatch:X?.accountPatch,sessionId:qe,nonce:ct})}catch(re){se(Pe,re,"stripe_wallet_failed",L?.generation)}finally{x(!1)}},[h,E,e,t,n,a,r,u,d,M,R,se,me,ke,ne,j]),Qe=(0,o.useMemo)(()=>{let ue=["applePay","googlePay","paypal","link","amazonPay","klarna"],L=new Set(["applePay","googlePay"]),Pe=new Set(i.map(v.stripeExpressMethodToOptionKey)),X={};for(let be of ue)Pe.has(be)?X[be]=L.has(be)?"always":"auto":X[be]="never";return X},[i]),Ve=(0,o.useMemo)(()=>i.map(v.stripeExpressMethodToOptionKey),[i]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(mi,{state:_,placeholderTestId:"flopay-wallet-placeholder",borderRadius:k,children:(0,c.jsxs)("div",{ref:oe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[ce&&(0,c.jsxs)("button",{ref:ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:S,style:ci,children:["Try ",di(De)," again"]}),(0,c.jsx)(mt.ExpressCheckoutElement,{onReady:ue=>{f(pi(ue,Ve))},onLoadError:ue=>{f("load_error"),Jo(Tt(p),"stripe","wallet")},onClick:async ue=>{Le.current=ue.expressPaymentType,we.current=ri(ue.expressPaymentType);let L=R?await R(we.current):{proceed:!0};if(!L.proceed){he.current.delete(j),ue.reject();return}let Pe=Z(ue.expressPaymentType);he.current.set(j,{generation:Pe,method:ue.expressPaymentType,accountPatch:L.accountPatch,sessionId:L.sessionId,nonce:L.nonce}),pe(!1),b?.(we.current),ue.resolve()},onConfirm:de,onCancel:()=>{let ue=he.current.get(j);he.current.delete(j),Tt(p)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),J(ue?.generation),pe(!1),ie.current=!0,xe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Qe,layout:{maxColumns:1,overflow:"never"}}},j)]})}),ge&&(0,c.jsx)(cn,{status:"processing"})]})}function _s({method:e,themeId:t,submitting:n=!1,disabled:a=!1,highlighted:r=!1,hasNextStep:i=!1,onClick:u,backgroundColor:d,borderColor:b,textColor:M,borderRadius:g,fontFamily:R}){let C=(0,v.resolveStripeMethodBrandVariant)(e,t),k=$a[e],p=C?.backgroundColor??d??"#ffffff",h=C?.borderColor??b??"#d1d5db",E=C?.textColor??M??"#262833";return(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!a&&u()},disabled:n||a,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:fo,padding:"0 1rem",backgroundColor:p,color:E,border:`1px solid ${h}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,cursor:n||a?"not-allowed":"pointer",opacity:a&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:r?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,c.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,v.getStripeMethodDisplayName)(e)}\u2026`}):(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,v.hasVendoredStripeMethodLogo)(e)?8:0},children:[k?(0,c.jsx)("img",{src:k,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):C?.logoSvg?(0,c.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:C.logoSvg}}):null,(0,c.jsx)("span",{children:(0,v.getStripeMethodDisplayName)(e)})]}),i&&(0,c.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:E,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,c.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Go({method:e,sessionId:t,nonce:n,email:a,billingName:r,billingApiUrl:i,onTokenizedBody:u,onErrorChange:d,onDecline:b,onCancel:M,runBeforeButtonClick:g,onButtonClick:R,isProcessing:C,submitButtonColor:k,submitButtonBorderRadius:p,submitButtonStyle:h,errorText:E}){let _=gn(),f=(0,mt.useStripe)(),ge=(0,mt.useElements)(),[x,oe]=(0,o.useState)(!1),ae=(0,o.useRef)(!1),[j,K]=(0,o.useState)(!1),[ce,pe]=(0,o.useState)("loading"),De=(0,o.useCallback)(async()=>{if(!f||!ge||C||ae.current||!j)return;ae.current=!0,oe(!0);let P=g?await g("card"):{proceed:!0};if(!P.proceed){ae.current=!1,oe(!1);return}R?.("card");let ie=P.sessionId??t,Le=P.nonce??n,we=P.accountPatch?.email??a;try{d?.(null);let he=await ge.submit();if(he.error){d?.(he.error.message??"Payment failed.");return}let Z=await f.createPaymentMethod({elements:ge});if(Z.error||!Z.paymentMethod){d?.(Z.error?.message??"Failed to create payment method.");return}let me=Z.paymentMethod;if(!ie||!we)throw new Error("Missing sessionId or email for payment.");let J=me.type||e,ne=await new bn.PaymentAPI(i).createSessionIntent(ie,Le??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:J,paymentMethodId:null,intentKind:"payment"});if(ne.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ke=ne.clientSecret;if(typeof window<"u")try{localStorage.setItem(Tn,JSON.stringify({clientSecret:ke,sessionId:ie,nonce:Le,accountPatch:P.accountPatch,paymentMethodId:me.id,paymentMethodType:me.type??e,gateway:"stripe"}))}catch{}let{error:xe,paymentIntent:se}=await f.confirmPayment({clientSecret:ke,confirmParams:{return_url:window.location.href,payment_method:me.id},redirect:"if_required"});if(xe){if(typeof window<"u")try{localStorage.removeItem(Tn)}catch{}let de=xe.message??"Payment failed.";d?.(de),b?.(Et("card",de,{code:xe.code})),await go({billingApiUrl:i,sessionId:ie,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:xe.code??"provider_declined"}});return}let W=se?.status;if(!uo(W)){if(typeof window<"u")try{localStorage.removeItem(Tn)}catch{}let de=W==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(de),b?.(Et("card",de,{code:W??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Tn)}catch{}let S=typeof se?.payment_method=="string"?se.payment_method:se?.payment_method?.id;u({id:S??me.id,type:"card",threeDSecureActionResultTokenId:se?.id,gateway:"stripe",paymentMethodType:me.type??e},{accountPatch:P.accountPatch,sessionId:ie,nonce:Le})}catch(he){d?.(he instanceof Error?he.message:"Payment failed. Please try again.")}finally{ae.current=!1,oe(!1)}},[f,ge,C,j,g,R,t,n,a,i,e,u,d,b]);return(0,c.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,c.jsx)(mt.PaymentElement,{onReady:()=>pe("ready"),onLoadError:()=>{pe("load_error"),Jo(Tt(_),"stripe","apm")},onChange:P=>{K(!!P.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...a?{email:a}:{}}}}}),(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{De()},disabled:!j||x||C||ce!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:k,color:"white",border:"none",borderRadius:p,fontSize:"1rem",fontWeight:600,cursor:!j||x||C||ce!=="ready"?"not-allowed":"pointer",opacity:!j||x||C||ce!=="ready"?.5:1,transition:"opacity 120ms ease-out",...h??{}},children:x?"Processing\u2026":`Pay with ${(0,v.getStripeMethodDisplayName)(e)}`}),E&&(0,c.jsx)(yr,{margin:"0.75rem 0 0",children:E})]})}function li({sessionId:e,nonce:t,email:n,billingName:a,billingApiUrl:r,paymentElementMethods:i,stripeInstance:u,paymentElementBaseOptions:d,onTokenizedBody:b,onErrorChange:M,onButtonClick:g,onDecline:R,runBeforeButtonClick:C,onLoadStateChange:k,isProcessing:p=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:E=8,submitButtonStyle:_,buttonAppearance:f,themeId:ge,onExpandApm:x,expandedApmMethod:oe}){let[ae,j]=(0,o.useState)(null),[K,ce]=(0,o.useState)(null),pe=(0,o.useRef)(!1);(0,o.useEffect)(()=>{i.length>0&&u?k?.("ready"):u||k?.("loading")},[i.length,u,k]);let De=(0,o.useCallback)(async Z=>{if(!u||pe.current||p)return;pe.current=!0,ce(Z);let me=C?await C("card"):{proceed:!0};if(!me.proceed){pe.current=!1,ce(null);return}g?.("card");let J=me.sessionId??e,ne=me.nonce??t,ke=me.accountPatch?.email??n;try{if(M?.(null),!J||!ke)throw new Error("Missing sessionId or email for payment.");let xe=await new bn.PaymentAPI(r).createSessionIntent(J,ne??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,paymentMethodId:null,intentKind:"payment"});if(xe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let se=xe.clientSecret;if(typeof window<"u")try{localStorage.setItem(Tn,JSON.stringify({clientSecret:se,sessionId:J,nonce:ne,accountPatch:me.accountPatch,paymentMethodType:Z,gateway:"stripe"}))}catch{}let{error:W,paymentIntent:S}=await u.confirmPayment({clientSecret:se,confirmParams:{return_url:window.location.href,payment_method_data:{type:Z,billing_details:{name:a&&a.trim().length>=3?a.trim():"FloPay Customer",...ke?{email:ke}:{}}}},redirect:"if_required"});if(W){if(typeof window<"u")try{localStorage.removeItem(Tn)}catch{}let Ve=W.message??"Payment failed.";M?.(Ve),R?.(Et("card",Ve,{code:W.code})),await go({billingApiUrl:r,sessionId:J,nonce:ne,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,providerDeclineReason:W.code??"provider_declined"}});return}let de=S?.status;if(!uo(de)){if(typeof window<"u")try{localStorage.removeItem(Tn)}catch{}let Ve=de==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";M?.(Ve),R?.(Et("card",Ve,{code:de??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Tn)}catch{}let Qe=typeof S?.payment_method=="string"?S.payment_method:S?.payment_method?.id;b({id:Qe??S?.id,type:"card",threeDSecureActionResultTokenId:S?.id,gateway:"stripe",paymentMethodType:Z},{accountPatch:me.accountPatch,sessionId:J,nonce:ne})}catch(xe){M?.(xe instanceof Error?xe.message:"Payment failed. Please try again.")}finally{pe.current=!1,ce(null)}},[u,p,C,g,e,t,n,r,a,b,M,R]),[P,ie]=(0,o.useState)(null),Le=x?oe??null:P,we=(0,o.useCallback)(Z=>{pe.current||p||Le&&Le!==Z||((0,v.needsStripeMethodExplicitConfirm)(Z)?x?x(Z):ie(Z):De(Z))},[Le,p,De,x]),he=(0,o.useMemo)(()=>P?{...d,paymentMethodTypes:[P]}:null,[P,d]);return(0,c.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:i.map(Z=>{let me=oe===Z,J=K===Z,ne=K!==null&&K!==Z||oe!=null&&oe!==Z;return(0,c.jsxs)(o.default.Fragment,{children:[(0,c.jsx)(_s,{method:Z,themeId:ge,submitting:J,disabled:ne,highlighted:me,hasNextStep:(0,v.needsStripeMethodExplicitConfirm)(Z),onClick:()=>we(Z),backgroundColor:f?.backgroundColor,borderColor:f?.borderColor,textColor:f?.textColor,borderRadius:f?.borderRadius,fontFamily:f?.fontFamily}),!x&&P===Z&&he&&u&&(0,c.jsx)(mt.Elements,{stripe:u,options:he,children:(0,c.jsx)(Go,{method:Z,sessionId:e,email:n,billingName:a,billingApiUrl:r,onTokenizedBody:b,onErrorChange:M,onDecline:R,onCancel:()=>ie(null),runBeforeButtonClick:C,onButtonClick:g,isProcessing:p,submitButtonColor:h,submitButtonBorderRadius:E,submitButtonStyle:_})},Z)]},Z)})})}function xs({sessionId:e,nonce:t,billingApiUrl:n,email:a,userId:r,onComplete:i,onError:u,onDecline:d,onTokenizedBody:b,firstName:M,lastName:g,chv:R,className:C,isProcessing:k,error:p,onErrorChange:h,showPayPal:E=!0,showStripe:_=!0,enabledPaymentMethods:f,enabledPaymentMethodCountries:ge,showApplePay:x=!0,showGooglePay:oe=!0,layout:ae="default",theme:j,buttonsTheme:K,buttonsStyles:ce,appearance:pe,cardButtonContent:De,cardBackButtonContent:P,cardTitleContent:ie,showSecurityFooter:Le,onButtonClick:we,onBeforeButtonClick:he,enableAVS:Z,cardFieldOrder:me,cardPreFormSlot:J,avsLayout:ne="row",country:ke,zip:xe,addressLine1:se,addressLine2:W,city:S,state:de,onCountryChange:Qe,onZipChange:Ve,avsCheck:ue,checkoutType:L,checkoutLayout:Pe,totalAmount:X=0,currency:be="usd",initialCardOpen:rt=!1,directPaypal:qe,isSubscription:ct=!1,session:ve,dataAttachmentPending:re=!1,debug:ot=!1}){let ee=gn(),yt=ao(),He=(0,o.useContext)(fn),Ke=re||He.claimPending===!0,Nt=so(),[at,nn]=(0,o.useState)(!1),[T,Ce]=(0,o.useState)(null),[et,tt]=(0,o.useState)(ke??"US"),[It,ft]=(0,o.useState)(xe??""),[Oe,gt]=(0,o.useState)(se??""),[Fe,rn]=(0,o.useState)(W??""),[Ye,zn]=(0,o.useState)(S??""),[Wt,wn]=(0,o.useState)(de??""),[Nn,Un]=(0,o.useState)({}),Ut=(0,o.useRef)(xe??""),pt=(0,o.useRef)(ke??"US"),dn=(0,o.useRef)(se??""),$t=(0,o.useRef)(W??""),jt=(0,o.useRef)(S??""),Vt=(0,o.useRef)(de??""),Mt=(0,o.useRef)({});(0,o.useEffect)(()=>{let s=(N,G,fe,Y,Be)=>{if(Mt.current[N])return;let Ne=G?.trim();!Ne||Ne===fe.current||(fe.current=Ne,Y(Ne),Be?.(Ne))};s("country",ke,pt,tt,Qe),s("zip",xe,Ut,ft,Ve),s("addressLine1",se,dn,gt),s("addressLine2",W,$t,rn),s("city",S,jt,zn),s("state",de,Vt,wn)},[ke,xe,se,W,S,de,Qe,Ve]);let le=(0,o.useMemo)(()=>(0,v.resolveAVSConfig)(Z),[Z]),$n=le!==null,on=(0,o.useMemo)(()=>(0,v.isAuthorizationOnlySession)(ve),[ve]),Gt=!!ve?.vault?.html,Yn=!!ve?.gateways?.pcivault,it=!!(ve?.gateways?.stripe?.enabledPaymentMethods??f)?.includes("card"),Ge=Gt||it||Yn,We=!!(_&&Ge&&ee&&e),[Je,An]=(0,o.useState)(()=>ae!=="buttons"||rt?e??null:null),[jn,ar]=(0,o.useState)(0),kn=ae!=="buttons"||rt||!!e&&Je===e,st=(0,o.useMemo)(()=>!ee||!We||!e||!kn?null:ee.cardCapture({sessionId:e,captureMethod:ve?.captureMethod}),[ee,We,e,kn,ve?.captureMethod]),qt=(0,o.useMemo)(()=>{let s=et,N=le?(0,v.isAVSFieldVisible)(le.postal_code,s):!1;return Es(s,It,N)},[le,et,It]),{avsInvalid:Rn,invalidAvsFields:St}=(0,o.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!We||!le)return{avsInvalid:!1,invalidAvsFields:s};let N=et,G=(Be,Ne)=>(0,v.isAVSFieldVisible)(Be,N)&&!Ne.trim(),fe={line1:G(le.address_line_1,Oe),city:G(le.city,Ye),state:G(le.state,Wt),zip:qt.empty||qt.malformed};return{avsInvalid:fe.line1||fe.city||fe.state||fe.zip,invalidAvsFields:fe}},[We,le,et,Oe,Ye,Wt,qt]),[Ft,un]=(0,o.useState)(!1),[an,Jt]=(0,o.useState)(!1),[Xt,At]=(0,o.useState)(()=>Yo(ve?.vault)),[Ae,wt]=(0,o.useState)(rt&&Ge?"card":"buttons"),[ht,En]=(0,o.useState)(null),ir=Ae==="expanding"||Ae==="card",Dt=280,sn=(0,o.useRef)(null),Bt=(0,o.useCallback)(s=>{sn.current&&clearTimeout(sn.current),sn.current=setTimeout(()=>{sn.current=null,s()},Dt)},[Dt]);(0,o.useEffect)(()=>()=>{sn.current&&clearTimeout(sn.current)},[]);let Wn=(0,o.useCallback)(()=>{An(e??null),ar(s=>s+1),wt("expanding"),Bt(()=>wt("card"))},[Bt,e]),pn=(0,o.useCallback)(()=>{wt("collapsing"),Bt(()=>wt("buttons"))},[Bt]),Vn=(0,o.useCallback)(s=>{En(s),wt("apm-expanding"),Bt(()=>wt("apm-form"))},[Bt]),Lt=(0,o.useCallback)(()=>{wt("apm-collapsing"),Bt(()=>{wt("buttons"),En(null)})},[Bt]);(0,o.useEffect)(()=>{ae==="buttons"&&rt&&Ge&&(An(e??null),wt("card"))},[ae,rt,Ge,e]);let[In,ze]=(0,o.useState)(null),A=(0,o.useRef)(!1),$=(0,o.useRef)(null),V=(0,o.useRef)("idle"),[Ee,Me]=(0,o.useState)(null),te=(0,o.useRef)(Ee);(0,o.useEffect)(()=>{te.current=Ee},[Ee]);let y=n||Nt,q=p??T,m=(0,o.useMemo)(()=>(0,zt.resolveTheme)(j),[j]),l=(0,o.useMemo)(()=>{let s=m?.buttonsLayout??(0,v.resolveButtonsLayoutTheme)(K);return ce?{...s,...ce,cardButton:{...s.cardButton,...ce.cardButton},cardFormContainer:{...s.cardFormContainer,...ce.cardFormContainer},backButton:{...s.backButton,...ce.backButton},backButtonIcon:{...s.backButtonIcon,...ce.backButtonIcon},submitButton:{...s.submitButton,...ce.submitButton},title:{...s.title,...ce.title}}:s},[m,K,ce]),F=pe??m?.appearance,Re=(0,o.useMemo)(()=>oo({appearance:F,buttonsStyles:l,layout:ae}),[F,l,ae]),Te=He.inlineSessionPatchProcessing??!1,Q=(k??at)||Te,Ze=y.replace(/\/+$/,""),O=(0,o.useMemo)(()=>qo({userId:r,email:a,firstName:M,lastName:g,country:ke,zip:xe},Nn),[r,a,M,g,ke,xe,Nn]),H=[O.firstName,O.lastName].filter(s=>!!s?.trim()).join(" "),I=(0,o.useMemo)(()=>ee?ee.getRawProvider():null,[ee]),z=(0,o.useMemo)(()=>yt?yt.getRawProvider():null,[yt]),ye=X||100,Ct=(0,o.useMemo)(()=>F?(0,bn.toStripeAppearance)(F):null,[F]),Ht=Ct?{appearance:Ct}:null,Ot=(0,o.useMemo)(()=>{let s=Ct??{},N=s.rules??{};return{...s,rules:{...N,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...N[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...N[".AccordionItemContents"]??{}}}}},[Ct]),Hr=(0,o.useMemo)(()=>{let s=Wa(X);return{...s,currency:be.toLowerCase(),paymentMethodCreation:"manual",...s.mode==="payment"?{captureMethod:"manual"}:{},...Ht}},[X,be,Ht]),la=(0,o.useMemo)(()=>({mode:"payment",amount:ye,currency:be.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Ht}),[ye,be,Ht]),Se=(0,o.useCallback)(s=>{Ce(s),h?.(s)},[h]);(0,o.useEffect)(()=>{!We||!st||st.setCardFieldOrder?.(me??null,le==null)},[We,st,me,le]),(0,o.useEffect)(()=>{(Ae==="expanding"||Ae==="collapsing"||Ae==="apm-expanding"||Ae==="apm-collapsing")&&Se(null)},[Ae,Se]);let mn=(0,o.useCallback)((s,N,G)=>{d?.(Et(s,N,G))},[d]),sr=(0,o.useCallback)((s,N,G)=>{let fe=G?.popupBlocked??Hn(N),Y=ks(s,fe),Be=tr(G?.code)??Dn(N)??"external_payment_method_failed",Ne=new zt.FloPayError(Y,"api_error",{code:"external_payment_method_failed",param:s});ze(null),ae==="buttons"&&(wt("buttons"),En(null)),Se(Y),u?.(Ne),console.error("[FloPay] External payment method failed:",{method:s,code:Be,popupBlocked:fe})},[ae,u,Se]);(0,o.useEffect)(()=>{if(!We||!e){At(null);return}let s=Yo(ve?.vault);if(s){At(s);return}if(!kn){At(null);return}At(null);let N=!0;return new bn.PaymentAPI(Ze).getVaultCapture(e,t).then(G=>{if(!N)return;let fe=Yo(G);fe?At(fe):Se("Failed to load the secure card form.")}).catch(G=>{N&&Se(G instanceof Error?G.message:"Failed to load the secure card form.")}),()=>{N=!1}},[We,kn,jn,e,ve?.vault?.html,ve?.vault?.messageToken,ve?.vault?.expectedOrigin,Ze,t,Se]);let _n=(0,o.useRef)({onComplete:i,onError:u,updateError:Se,emitDecline:mn,resolvedAccount:O,avsConfig:le,avsCheckProp:ue,sessionId:e,nonce:t,baseUrl:Ze,captureMethod:ve?.captureMethod,paymentId:ve?.paymentId,authorizationExpiresAt:ve?.authorizationExpiresAt});_n.current={onComplete:i,onError:u,updateError:Se,emitDecline:mn,resolvedAccount:O,avsConfig:le,avsCheckProp:ue,sessionId:e,nonce:t,baseUrl:Ze,captureMethod:ve?.captureMethod,paymentId:ve?.paymentId,authorizationExpiresAt:ve?.authorizationExpiresAt};let _o=(0,o.useRef)(!1),Bi=(0,o.useCallback)(()=>{let{resolvedAccount:s,avsConfig:N,avsCheckProp:G}=_n.current,fe=pt.current||s.country||"US",Y=N?(0,v.isAVSFieldVisible)(N.state,fe):!1,Be=N?(0,v.isAVSFieldVisible)(N.address_line_1,fe):!1,Ne=N?(0,v.isAVSFieldVisible)(N.postal_code,fe):!1,dt=N?(0,v.isAVSFieldVisible)(N.city,fe):!1,bt=N?(0,v.isAVSFieldVisible)(N.address_line_2,fe):!1,nt=Be&&!Y&&Ne?(0,v.getStateFromPostalCode)(fe,(Ut.current??"").trim()):null,kt=Y?Vt.current:nt;return{accountData:{userId:s.userId??"",email:s.email??"",firstName:s.firstName??"",lastName:s.lastName??"",...Ne&&Ut.current?{zip:Ut.current}:{},...dt&&jt.current?{city:jt.current}:{},...kt?{state:kt}:{},...Be&&dn.current?{addressLine1:dn.current}:{},...bt&&$t.current?{addressLine2:$t.current}:{},country:fe},...G!==void 0?{avsCheck:G}:{},...N?{avsConfig:{country:(0,v.isAVSFieldVisible)(N.country,fe),postal_code:Ne,address_line_1:Be,address_line_2:bt,city:dt,state:Y}}:{}}},[]),ca=(0,o.useRef)(Ke);ca.current=Ke,(0,o.useEffect)(()=>{Ke||q!==ni||_n.current.updateError(null)},[Ke,q]),(0,o.useEffect)(()=>{!We||!st||st.setSubmitGate?.(Rn||Ke)},[We,st,Rn,Ke]),(0,o.useEffect)(()=>{if(!We||!st)return;_o.current=!1;let s=!1,N=st.on("submitting",()=>{un(!0),$.current&&clearTimeout($.current),V.current="validation-window",$.current=setTimeout(()=>{$.current=null,V.current==="validation-window"&&(V.current="processing")},bs),ze("processing");let{baseUrl:Ne,sessionId:dt,nonce:bt,updateError:nt,onError:kt}=_n.current;!dt||!bt||new bn.PaymentAPI(Ne).patchAccountSnapshot(dt,bt,Bi(),{telemetryMode:"best_effort"}).catch(Ie=>{if(!vs(Ie))return;let _t=Ie instanceof Error?Ie.message:"Please check your billing address and try again.";nt(_t),V.current="idle",ze(null),kt?.(Ie instanceof zt.FloPayError?Ie:new zt.FloPayError(_t,"api_error"))})}),G=st.on("complete",async Ne=>{if(Pr(Ne.sessionId??_n.current.sessionId),V.current="terminal",ze("success"),await new Promise(nt=>setTimeout(nt,hn)),_o.current)return;_o.current=!0;let dt=_n.current,bt=(0,v.isAuthorizationOnlySession)(dt)||Ne.outcome==="authorized";_n.current.onComplete?.(bt?{status:"authorized",paymentIntentId:Ne.intentId,paymentId:Ne.paymentId??dt.paymentId,sessionId:Ne.sessionId??dt.sessionId,authorizationExpiresAt:Ne.authorizationExpiresAt??dt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ne.intentId,checkoutMethod:"card"})}),fe=st.on("decline",async Ne=>{let{updateError:dt,emitDecline:bt}=_n.current,nt=Ne.message??"Your payment was declined. Please try another card or contact your bank.";V.current="terminal",dt(nt),ze("error");let kt=Ne.failureOutcome??(0,v.normalizeCheckoutFailureOutcome)(Ne.declineReason)??"authorization_declined";bt("card",nt,{code:kt,declineCode:kt}),await new Promise(Ie=>setTimeout(Ie,Qt)),!s&&(V.current="idle",ze(null))}),Y=st.on("error",async Ne=>{let{updateError:dt,onError:bt}=_n.current,nt=Ne.message??"There was a problem processing your payment. Please try again.";V.current="terminal",dt(nt),ze("error"),bt?.(new zt.FloPayError(nt,"api_error",{code:Ne.failureOutcome??"capture_failed"})),await new Promise(kt=>setTimeout(kt,Qt)),!s&&(V.current="idle",ze(null))}),Be=st.on("blocked",()=>{if(!ca.current){un(!0);return}_n.current.updateError(ni)});return()=>{s=!0,$.current&&(clearTimeout($.current),$.current=null),V.current="idle",N(),G(),fe(),Y(),Be()}},[We,st]);let xn=!!qe?.clientId,wr=Array.isArray(f),Kr=wr&&f.length>0,Fi=wr&&f.includes("paypal"),{expressMethods:Yr,paymentElementMethods:kr}=(0,o.useMemo)(()=>(0,v.partitionStripeMethods)(f,{excludePaypal:xn}),[f,xn]),da=xn||!!yt,Di=(0,o.useMemo)(()=>da?Yr.filter(s=>s!=="paypal"):Yr,[Yr,da]),Li=(0,o.useMemo)(()=>{let s=[];return x&&s.push("apple_pay"),oe&&s.push("google_pay"),s},[x,oe]),Wr=wr?Di:Li,Oi=_&&Wr.length>0,xo=$n?et:ke,Gr=(0,o.useMemo)(()=>{let s=xo?.trim().toUpperCase();return s?ge?kr.filter(N=>{let G=ge[N];return!G||G.length===0||G.includes(s)}):(0,v.filterStripeMethodsByCountry)(kr,xo):kr},[kr,xo,ge]),To=(0,o.useMemo)(()=>({mode:"payment",amount:ye,currency:be.toLowerCase(),paymentMethodCreation:"manual",appearance:Ot}),[ye,be,Ot]),[ua,pa]=(0,o.useState)("loading"),[ma,ya]=(0,o.useState)("loading"),[fa,ga]=(0,o.useState)("loading"),[zi,Mo]=(0,o.useState)(!1),[ha,Ao]=(0,o.useState)("loading"),[Jr,Ni]=(0,o.useState)();(0,o.useEffect)(()=>{Ni(Ga())},[]);let Pa=E&&(xn||(wr?Fi:Jr===!1)),ba=_&&Oi,Rr=!Ke&&Pa&&xn,va=ha==="retrying"||ha==="exhausted",Er=!Ke&&Pa&&!!z&&(!xn||va),Ir=!Ke&&ba&&!!I,_r=!Ke&&_&&Kr&&Gr.length>0&&!!I,Ui=Rr&&!va?zi:Er&&ai(ua),$i=Ir&&ai(ma),ji=_r&&fa!=="load_error",Ca=s=>s==="loading"||s==="ready",Sa=Rr||Er&&Ca(ua)||Ir&&Ca(ma)||_r&&fa!=="load_error",Xr=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Xr.current){if(!_&&!E){Xr.current=!0;let s=new zt.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(s),Se(s.message)}else if(!_&&E&&!xn&&!z){Xr.current=!0;let s=new zt.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(s),Se(s.message)}else if(Jr!==void 0&&!Ke&&!Ge&&!Sa){Xr.current=!0;let s=new zt.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});u?.(s),Se(s.message)}}},[_,E,xn,z,Jr,Ke,Ge,Sa,u,Se]);let wa=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(wa.current||!Kr)return;let s=[];x!==!0&&s.push("showApplePay"),oe!==!0&&s.push("showGooglePay"),s.length!==0&&(wa.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Kr,x,oe]);let ka=(0,o.useCallback)((s,N)=>He.applyInlineSessionPatch?He.applyInlineSessionPatch(s).then(G=>({error:null,sessionId:G.sessionId||e,nonce:G.session?.clientSecret||t})).catch(G=>{let fe=oi(N,G);return Se(fe.message),u?.(fe),{error:fe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[He.applyInlineSessionPatch,t,u,e,Se]),yn=(0,o.useCallback)(async s=>{if(!he)return{proceed:!0};try{let N=await he({method:s,sessionId:e||void 0,createSession:He.inlineSessionDraft});if(N===!1)return{proceed:!1};if(N&&typeof N=="object"){N.account&&Un(fe=>({...fe??{},...N.account}));let G=await ka(N,s);return G.error?{proceed:!1,accountPatch:N.account}:{proceed:!0,accountPatch:N.account,sessionId:G.sessionId,nonce:G.nonce}}return{proceed:!0}}catch(N){let G=oi(s,N);return Se(G.message),u?.(G),{proceed:!1}}},[ka,He.inlineSessionDraft,he,u,e,Se]),Ra=(0,o.useCallback)(async(s,N)=>{if(A.current)return;A.current=!0,nn(!0),ze("processing"),Se(null);let G=N?.sessionId??e,fe=N?.nonce??t,Y=qo(O,N?.accountPatch),Be=N?.completionPaymentMethodId??Lr(s),Ne=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s;try{let bt=await new bn.PaymentAPI(Ze).processPayment(Y.userId??"",{sessionId:G,nonce:fe,tokenizedData:Ne,accountData:{userId:Y.userId??"",email:Y.email??"",firstName:Y.firstName??"",lastName:Y.lastName??"",...le?(()=>{let Ie=pt.current,_t=(0,v.isAVSFieldVisible)(le.state,Ie),Yt=(0,v.isAVSFieldVisible)(le.address_line_1,Ie),Qn=(0,v.isAVSFieldVisible)(le.postal_code,Ie),Zn=Yt&&!_t&&Qn?(0,v.getStateFromPostalCode)(Ie,(Ut.current??"").trim()):null,xt=_t?Vt.current:Zn;return{country:Ie,...Qn&&Ut.current?{zip:Ut.current}:{},...(0,v.isAVSFieldVisible)(le.city,Ie)&&jt.current?{city:jt.current}:{},...xt?{state:xt}:{},...Yt&&dn.current?{addressLine1:dn.current}:{},...(0,v.isAVSFieldVisible)(le.address_line_2,Ie)&&$t.current?{addressLine2:$t.current}:{}}})():{}},chv:R,avsCheck:ue??!1,checkoutType:L,checkoutLayout:Pe,avsConfig:le?{country:(0,v.isAVSFieldVisible)(le.country,pt.current),postal_code:(0,v.isAVSFieldVisible)(le.postal_code,pt.current),address_line_1:(0,v.isAVSFieldVisible)(le.address_line_1,pt.current),address_line_2:(0,v.isAVSFieldVisible)(le.address_line_2,pt.current),city:(0,v.isAVSFieldVisible)(le.city,pt.current),state:(0,v.isAVSFieldVisible)(le.state,pt.current)}:void 0});if(bt.ok){let Ie=bt.status===204?null:await bt.json().catch(()=>null),_t=(0,v.isAuthorizationOnlySession)(ve)||Ie?.status==="authorized";Pr(G),ze("success"),Me(null),await new Promise(Yt=>setTimeout(Yt,hn)),i?.(_t?{status:"authorized",...typeof Ie?.paymentId=="string"?{paymentId:Ie.paymentId}:ve?.paymentId?{paymentId:ve.paymentId}:{},sessionId:typeof Ie?.sessionId=="string"?Ie.sessionId:G,...typeof Ie?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Ie.authorizationExpiresAt}:ve?.authorizationExpiresAt?{authorizationExpiresAt:ve.authorizationExpiresAt}:{},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Be,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Be,checkoutMethod:s.isPaypal?"paypal":"card"});return}let nt=await bt.json().catch(()=>null);if(nt?.type==="paypal_redirect_required"){let Ie=nt.threeDSecureToken,_t=nt.paymentMethodId||s.id||"";if(!ee||!Ie){ze("error"),Se("PayPal authorization required but no token provided.");return}try{let Yt=yt?.getRawProvider();if(!Yt){Se("PayPal is not available.");return}let Qn={return_url:window.location.href};_t&&(Qn.payment_method=_t);let{error:Zn}=await Yt.confirmPayment({clientSecret:Ie,confirmParams:Qn,redirect:"if_required"});if(Zn){ze("error");let xt=Zn.message??"PayPal payment failed.";Se(xt),mn("paypal",xt,{code:Zn.code})}}catch(Yt){ze("error"),Se(Yt instanceof Error?Yt.message:"PayPal authorization failed.")}return}if(nt?.type==="paypal_direct_required"){let Ie=nt.orderId;if(!Ie){ze("error"),Se("PayPal retry required but no order id provided.");return}let _t=te.current?.attempts??0;if(_t>=2){ze("error"),Se("PayPal payment could not be completed after multiple attempts."),mn("paypal","paypal_direct_required retry limit exceeded");return}Mo(!1),Ao("loading"),Me({orderId:Ie,attempts:_t+1}),ze(null);return}ze("error");let kt=nt?.message??"Payment failed. Please try again.";Se(kt),mn(s.isPaypal?"paypal":"card",kt,{code:nt?.code??nt?.gatewayErrorCode,declineCode:nt?.declineCode??nt?.gatewayDeclineReason}),await new Promise(Ie=>setTimeout(Ie,Qt))}catch(dt){ze("error"),Se(dt instanceof Error?dt.message:"An unexpected error occurred"),await new Promise(bt=>setTimeout(bt,Qt))}finally{nn(!1),ze(null),A.current=!1}},[Ze,e,t,O,H,R,ee,yt,ve,i,u,Se,mn]),ln=(0,o.useCallback)((s,N)=>{b?b(s):Ra(s,N)},[b,Ra]),Ea=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||Ea.current)return;let s=new URLSearchParams(window.location.search),N=s.get("payment_intent"),G=s.get("payment_intent_client_secret"),fe=s.get("redirect_status");if(!N||!G)return;let Y=kt=>{let Ie=localStorage.getItem(kt);if(!Ie)return null;try{return JSON.parse(Ie)}catch{return localStorage.removeItem(kt),null}},Be=Y(Tn)??Y(ti),Ne;if(Be?.clientSecret){if(Be.clientSecret!==G)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;Ea.current=!0,localStorage.removeItem(Tn),localStorage.removeItem(ti);let dt=new URL(window.location.href);dt.searchParams.delete("payment_intent"),dt.searchParams.delete("payment_intent_client_secret"),dt.searchParams.delete("redirect_status"),window.history.replaceState({},"",dt.toString());let bt=Be?.paymentMethodType??Be?.tokenType??"card",nt="card";(async()=>{let kt=ee?.getRawProvider();if(!kt){let xt="Payment is not available \u2014 please refresh and try again.";Se(xt),mn(nt,xt);return}if(fe==="failed"){let xt="Payment was declined. Please try again.";Se(xt),mn(nt,xt);return}let{paymentIntent:Ie,error:_t}=await kt.retrievePaymentIntent(G);if(_t){let xt=_t.message??"Failed to retrieve payment status.";Se(xt),mn(nt,xt,{code:_t.code});return}let Yt=Ie?.status,Qn=uo(Yt);if(!Ie||!Qn){let xt=Yt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Se(xt),mn(nt,xt,{code:Yt??"missing_payment_intent"});return}let Zn=typeof Ie.payment_method=="string"?Ie.payment_method:Ie.payment_method?.id;ln({id:Zn??Be?.paymentMethodId??Be?.tokenId??Ie.id,type:"card",threeDSecureActionResultTokenId:Ie.id,gateway:Be?.gateway??"stripe",paymentMethodType:bt},Ne)})()},[e,ln,ee,Se,mn]);let Bo=(0,o.useCallback)(s=>{s.preventDefault()},[]);if(!(ee!==null))return(0,c.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let xr=ae==="buttons",Kt=F?.variables,Vi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Fo=Kt?.colorBackground,qi=Fo&&!Vi.has(Fo)?Fo:void 0,Tr=l.cardInputBorder??(xr?"#e5e7eb":"#A4A4FF"),Do=Kt?.colorDanger??"#dc2626",Gn=s=>Ft&&s?Do:Tr,Qr=(qt.malformed||qt.empty)&&(an||Ft),Hi=Qr?Do:Gn(St.zip),Lo=l.cardFormContainer?.backgroundColor??qi??(xr?"white":"#EDEDFF"),Mr=l.cardInputBackground??Kt?.colorBackground??"white",Oo=cr(P),Ia=cr(ie),lr=l.nameInput,_a=l.cardInputFontSize??Is(lr?.fontSize)??Kt?.fontSizeBase??"16px",xa=typeof lr?.fontFamily=="string"?lr.fontFamily:Kt?.fontFamily??"Poppins, sans-serif",Ta=jo(lr?.fontWeight)??400,Ki=l.cardInputColor??(typeof lr?.color=="string"?lr.color:void 0)??Kt?.colorText??"#262833",Yi=l.cardInputPlaceholderColor??"#9ca3af",Pt=Kt?.borderRadius??"8px",Jn=Kt?.borderRadius??l.cardButton?.borderRadius??Pt,Xn=Kt?.colorPrimary??"#4A49FF",Wi=Kt?.colorPrimaryHover??pr(Xn,.12),zo=Kt?.colorText??"#262833",Ma={fontSize:_a,fontFamily:xa,fontWeight:Ta,color:Ki,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Gi={"--flopay-input-placeholder-color":Yi,"--flopay-input-font-size":_a,"--flopay-input-font-family":xa,"--flopay-input-font-weight":String(Ta)},Ar=l.cardFormContainer??{},No=Ar.padding??(xr?"0":"1rem"),Uo=Ar.borderRadius??Pt,Ji=st&&Xt?(0,c.jsx)(mr,{capture:st,html:Xt.html,messageToken:Xt.messageToken,expectedOrigin:Xt.expectedOrigin,theme:Re,onReady:()=>{if(!le||typeof document>"u")return;let s=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};s();let N=0,G=window.setInterval(()=>{N+=1;let fe=document.activeElement;!!fe&&fe.tagName==="IFRAME"&&fe.id==="flopay_vault_form_iframe"?(s(),window.clearInterval(G)):N>=50&&window.clearInterval(G)},100)},onError:s=>Se(s),onValidation:s=>{let N=V.current;(N==="idle"||N==="validation-window")&&(Se(s),s&&V.current==="validation-window"&&($.current&&(clearTimeout($.current),$.current=null),V.current="idle",ze(null)))}}):(0,c.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Aa=(0,c.jsxs)("div",{style:{backgroundColor:Lo,borderRadius:Uo,...Ar,padding:No,...Gi,display:"flex",flexDirection:"column"},children:[(0,c.jsx)("style",{children:`
|
|
30
|
+
`,Eo=44;function sa(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 Os={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Ii={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 Ns(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function vi(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ei(e){return e==="paypal"?"PayPal":(0,f.getStripeMethodDisplayName)(e)}function zs(e,t){let n=`We couldn't open ${Ei(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ri(e){let t=(0,a.useRef)(0),n=(0,a.useRef)(null),o=(0,a.useRef)(null),r=(0,a.useCallback)((y=o.current)=>{let C=y;C?.timer&&(clearTimeout(C.timer),C.timer=null)},[]),i=(0,a.useCallback)((y,C)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(y),y.timer=setTimeout(()=>{y.timer=null,o.current?.generation===y.generation&&(o.current=null,n.current=y.generation,e(y.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},C))},[r,e]),m=(0,a.useCallback)(y=>{y.yieldedControl&&i(y,600)},[i]),d=(0,a.useCallback)(y=>{r();let C=t.current+1;t.current=C,n.current=null;let Q={generation:C,method:y,timer:null,yieldedControl:!1};return o.current=Q,C},[r]),R=(0,a.useCallback)(y=>{let C=o.current;return typeof y=="number"&&C?.generation!==y?!1:(r(C),o.current=null,(typeof y!="number"||n.current===y)&&(n.current=null),!0)},[r]),g=(0,a.useCallback)(y=>{let C=o.current,Q=y??C?.generation??t.current;(!y||C?.generation===y)&&(r(C),o.current=null),n.current=Q},[r]),v=(0,a.useCallback)(y=>n.current===(y??t.current),[]),b=(0,a.useCallback)(y=>o.current?.generation===y&&n.current!==y,[]),A=(0,a.useCallback)(()=>{let y=o.current;y&&m(y)},[m]),D=(0,a.useCallback)(()=>{let y=o.current;y&&(y.yieldedControl=!0,r(y))},[r]);return(0,a.useEffect)(()=>{let y=()=>{document.visibilityState==="visible"?A():D()},C=()=>{D()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",C),window.addEventListener("focus",A),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",C),window.removeEventListener("focus",A),r()}},[r,D,A]),{startAttempt:d,finishAttempt:R,invalidateAttempt:g,isAttemptInvalidated:v,isAttemptCurrent:b}}function Us(e){let t=(0,f.getPostalCodeExample)(e);return`Enter a valid ${(0,f.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function $s(e,t,n){let o=(0,f.isPostalCodeSupported)(e),r=t.trim(),i=n&&o,m=i&&!r,d=i&&!!r&&!(0,f.isValidPostalCode)(e,r);return{visible:n,supported:o,required:i,empty:m,malformed:d}}function Pi(e,t){return t instanceof f.FloPayError?t:new f.FloPayError(t instanceof Error?t.message:`${Ns(e)} before-click hook failed.`,"validation_error")}function oa(){return(0,l.jsx)("style",{children:Ls})}function qs(e){return typeof e=="number"?`${e}px`:e}function _i(e,t){let n=e.availablePaymentMethods;return n&&t.some(o=>n[o])?"ready":"unavailable"}function Ti({state:e,placeholderTestId:t,borderRadius:n=8,children:o}){return e==="unavailable"||e==="load_error"?null:(0,l.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,l.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,l.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:o})]})}function bi(e){return e!=="unavailable"&&e!=="load_error"}function To(e){return(0,l.jsx)(Vs,{...e})}function Ci({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:r,onErrorChange:i,isProcessing:m=!1,onButtonClick:d,onDecline:R,onTechnicalFailure:g,runBeforeButtonClick:v,onLoadStateChange:b,placeholderBorderRadius:A}){let D=$n(),{emitInstrument:y}=(0,a.useContext)(hn),C=(0,vt.useStripe)(),Q=(0,vt.useElements)(),[J,w]=(0,a.useState)("loading");(0,a.useEffect)(()=>{b?.(J)},[J,b]);let[ge,U]=(0,a.useState)(!1),ee=(0,a.useRef)(!1),re=(0,a.useRef)(null),be=(0,a.useRef)(null),[oe,he]=(0,a.useState)(0),[ze,_e]=(0,a.useState)(!1),Se=(0,a.useRef)(!1),K=(0,a.useRef)(new Map),{startAttempt:O,finishAttempt:ae,invalidateAttempt:Ue,isAttemptInvalidated:Te,isAttemptCurrent:X}=Ri((H,_,me)=>{g?.(H,_,{...me,popupBlocked:me?.popupBlocked??Jn(_)}),_e(!0),he(We=>We+1)});(0,a.useEffect)(()=>{ze&&be.current?.focus()},[ze,oe]);let $=(0,a.useCallback)(()=>{he(H=>H+1)},[]),te=(0,a.useCallback)((H,_,me)=>{Ue(me),g?.("paypal",H,{code:_,popupBlocked:Jn(H)}),_e(!0),$()},[Ue,g,$]),pe=(0,a.useCallback)(()=>{window.setTimeout(()=>{(re.current?.querySelector("iframe")??re.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{Se.current&&(Se.current=!1,pe())},[pe,oe]);let ve=(0,a.useCallback)(()=>{_e(!1),i?.(null),pe()},[pe,i]);(0,a.useEffect)(()=>{if(!C||ee.current)return;let H=new URLSearchParams(window.location.search),_=H.get("payment_intent"),me=H.get("payment_intent_client_secret"),We=H.get("redirect_status");if(!_||!me)return;ee.current=!0;let $e;try{let B=localStorage.getItem(Yr);if(B){let ie=JSON.parse(B);ie.clientSecret===me&&($e={...ie.accountPatch?{accountPatch:ie.accountPatch}:{},...ie.sessionId?{sessionId:ie.sessionId}:{},...ie.nonce?{nonce:ie.nonce}:{}})}}catch{}try{localStorage.removeItem(Yr)}catch{}let ce=new URL(window.location.href);ce.searchParams.delete("payment_intent"),ce.searchParams.delete("payment_intent_client_secret"),ce.searchParams.delete("redirect_status"),window.history.replaceState({},"",ce.toString()),(async()=>{try{if(U(!0),We==="failed"){let G="PayPal payment was declined. Please try again.";i?.(G),R?.(xt("paypal",G));return}let{paymentIntent:B,error:ie}=await C.retrievePaymentIntent(me);if(ie){i?.(ie.message??"Failed to retrieve PayPal payment status.");return}if(B&&(B.status==="requires_capture"||B.status==="succeeded")){let G=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id;r({id:G??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0},$e)}else{let G="PayPal payment was not completed. Please try again.";i?.(G),R?.(xt("paypal",G))}}catch(B){i?.(B instanceof Error?B.message:"Failed to complete PayPal payment.")}finally{U(!1)}})()},[C,r,i,R]);let Z=(0,a.useCallback)(async H=>{if(m||ge){H.reject();return}let _=v?await v("paypal"):{proceed:!0};if(!_.proceed){K.current.delete(oe),H.reject();return}let me=O("paypal");K.current.set(oe,{generation:me,accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}),_e(!1),d?.("paypal"),H.resolve()},[K,m,d,v,O,ge,oe]),Re=(0,a.useCallback)(async H=>{if(!C||!Q)return;let _=K.current.get(oe);if(_&&!X(_.generation)){K.current.delete(oe);return}if(!_&&Te()||_&&!ae(_.generation))return;_||ae();let me=_??null;if(K.current.delete(oe),!me&&v){let B=await v("paypal");if(!B.proceed){H.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}me={accountPatch:B.accountPatch,sessionId:B.sessionId,nonce:B.nonce}}let We=me?.sessionId??e,$e=me?.nonce??t,ce=me?.accountPatch?.email??n;try{if(U(!0),i?.(null),!We||!ce)throw new Error("Missing sessionId or email for PayPal payment");let B=C.createPaymentMethod,{error:ie,paymentMethod:G}=await B({type:"paypal"});if(ie){te(ie,"stripe_paypal_create_payment_method_failed",_?.generation),H.paymentFailed({reason:"fail"});return}let Oe=await Ro(o,y,We,$e??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:G?.id??null,intentKind:"payment"});if(Oe.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Be=Oe.clientSecret,Qe={return_url:window.location.href};if(G?.id&&(Qe.payment_method=G.id),typeof window<"u")try{localStorage.setItem(Yr,JSON.stringify({clientSecret:Be,sessionId:We,nonce:$e,accountPatch:me?.accountPatch}))}catch{}let{error:se,paymentIntent:yt}=await C.confirmPayment({clientSecret:Be,confirmParams:Qe,redirect:"if_required"});if(se){if(typeof window<"u")try{localStorage.removeItem(Yr)}catch{}if(Ur(se)){let qe=se.message??"Your payment was declined.";i?.(qe),R?.(xt("paypal",qe,{code:Un(se),declineCode:hr(se)})),await _o({billingApiUrl:o,sessionId:We,nonce:$e,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Un(se)??"provider_declined"}})}else te(se,"stripe_paypal_confirm_failed",_?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Yr)}catch{}let j=typeof yt?.payment_method=="string"?yt.payment_method:yt?.payment_method?.id;r({id:j??yt?.id,type:"card",threeDSecureActionResultTokenId:yt?.id,isPaypal:!0},{accountPatch:me?.accountPatch,sessionId:We,nonce:$e});return}catch(B){te(B,"stripe_paypal_failed",_?.generation)}finally{U(!1)}},[C,Q,e,t,n,o,y,r,i,R,v,te,ae,X,Te,oe]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Ti,{state:J,placeholderTestId:"flopay-paypal-placeholder",borderRadius:A,children:(0,l.jsxs)("div",{ref:re,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[ze&&(0,l.jsx)("button",{ref:be,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ve,style:Ii,children:"Try PayPal again"}),(0,l.jsx)(vt.ExpressCheckoutElement,{onReady:H=>w(_i(H,["paypal"])),onLoadError:()=>{w("load_error"),ia(At(D),"paypal","paypal")},onClick:Z,onConfirm:Re,onCancel:()=>{let H=K.current.get(oe);K.current.delete(oe),At(D)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ue(H?.generation),_e(!1),Se.current=!0,$()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},oe)]})}),ge&&(0,l.jsx)(vn,{status:"processing"})]})}function Si({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:r,expressMethods:i,onTokenizedBody:m,onErrorChange:d,onButtonClick:R,onDecline:g,onTechnicalFailure:v,runBeforeButtonClick:b,onLoadStateChange:A,placeholderBorderRadius:D}){let y=$n(),{emitInstrument:C}=(0,a.useContext)(hn),Q=(0,vt.useStripe)(),J=(0,vt.useElements)(),[w,ge]=(0,a.useState)("loading");(0,a.useEffect)(()=>{A?.(w)},[w,A]);let[U,ee]=(0,a.useState)(!1),re=(0,a.useRef)(null),be=(0,a.useRef)(null),[oe,he]=(0,a.useState)(0),[ze,_e]=(0,a.useState)(!1),[Se,K]=(0,a.useState)("google_pay"),O=(0,a.useRef)(!1),ae=(0,a.useRef)("google_pay"),Ue=(0,a.useRef)("google_pay"),Te=(0,a.useRef)(new Map),{startAttempt:X,finishAttempt:$,invalidateAttempt:te,isAttemptInvalidated:pe,isAttemptCurrent:ve}=Ri((ce,B,ie)=>{v?.(ce,B,{...ie,popupBlocked:ie?.popupBlocked??Jn(B)}),K(ce),_e(!0),he(G=>G+1)});(0,a.useEffect)(()=>{ze&&be.current?.focus()},[ze,oe]);let Z=(0,a.useCallback)(()=>{he(ce=>ce+1)},[]),Re=(0,a.useCallback)((ce,B,ie,G)=>{te(G),v?.(ce,B,{code:ie,popupBlocked:Jn(B)}),K(ce),_e(!0),Z()},[te,v,Z]),H=(0,a.useCallback)(()=>{window.setTimeout(()=>{(re.current?.querySelector("iframe")??re.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{O.current&&(O.current=!1,H())},[H,oe]);let _=(0,a.useCallback)(()=>{_e(!1),d?.(null),H()},[H,d]),me=(0,a.useCallback)(async ce=>{if(!Q||!J)return;let B=Te.current.get(oe);if(B&&!ve(B.generation)){Te.current.delete(oe);return}if(!B&&pe()||B&&!$(B.generation))return;B||$();let ie=ce.expressPaymentType??B?.method??ae.current,G=B??null;Te.current.delete(oe);let Oe=vi(ie);if(!G&&b){let j=await b(Oe);if(!j.proceed){ce.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}G={accountPatch:j.accountPatch,sessionId:j.sessionId,nonce:j.nonce}}let Be=Oe,Qe=G?.sessionId??e,se=G?.nonce??t,yt=G?.accountPatch?.email??n;try{ee(!0),d?.(null);let{error:j}=await J.submit();if(j){Re(ie,j,"stripe_wallet_submit_failed",B?.generation);return}let{error:qe,paymentMethod:Pt}=await Q.createPaymentMethod({elements:J});if(qe||!Pt){Re(ie,qe??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",B?.generation);return}if(!Qe||!yt)throw new Error("Missing sessionId or email for wallet payment");let Y=await Ro(o,C,Qe,se??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ie??Oe,paymentMethodId:Pt.id,intentKind:r});if(Y.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let bt=Y.clientSecret,{error:Ke,intentId:Qt}=(0,f.isSetupIntentClientSecret)(bt)?await Q.confirmCardSetup(bt,{payment_method:Pt.id}).then(Et=>({error:Et.error,intentId:Et.setupIntent?.id})):await Q.confirmCardPayment(bt,{payment_method:Pt.id}).then(Et=>({error:Et.error,intentId:Et.paymentIntent?.id}));if(Ke){if(Ur(Ke)){let Et=Ke.message??"Your payment was declined.";d?.(Et),g?.(xt(Be,Et,{code:Un(Ke),declineCode:hr(Ke)})),await _o({billingApiUrl:o,sessionId:Qe,nonce:se,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ie??Oe,providerDeclineReason:Un(Ke)??"provider_declined"}})}else Re(ie,Ke,"stripe_wallet_confirm_failed",B?.generation);return}m({id:Pt.id,type:"card",threeDSecureActionResultTokenId:Qt},{accountPatch:G?.accountPatch,sessionId:Qe,nonce:se})}catch(j){Re(ie,j,"stripe_wallet_failed",B?.generation)}finally{ee(!1)}},[Q,J,e,t,n,o,C,r,m,d,g,b,Re,$,ve,pe,oe]),We=(0,a.useMemo)(()=>{let ce=["applePay","googlePay","paypal","link","amazonPay","klarna"],B=new Set(["applePay","googlePay"]),ie=new Set(i.map(f.stripeExpressMethodToOptionKey)),G={};for(let Oe of ce)ie.has(Oe)?G[Oe]=B.has(Oe)?"always":"auto":G[Oe]="never";return G},[i]),$e=(0,a.useMemo)(()=>i.map(f.stripeExpressMethodToOptionKey),[i]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Ti,{state:w,placeholderTestId:"flopay-wallet-placeholder",borderRadius:D,children:(0,l.jsxs)("div",{ref:re,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[ze&&(0,l.jsxs)("button",{ref:be,type:"button","data-testid":"flopay-wallet-retry-button",onClick:_,style:Ii,children:["Try ",Ei(Se)," again"]}),(0,l.jsx)(vt.ExpressCheckoutElement,{onReady:ce=>{ge(_i(ce,$e))},onLoadError:ce=>{ge("load_error"),ia(At(y),"stripe","wallet")},onClick:async ce=>{ae.current=ce.expressPaymentType,Ue.current=vi(ce.expressPaymentType);let B=b?await b(Ue.current):{proceed:!0};if(!B.proceed){Te.current.delete(oe),ce.reject();return}let ie=X(ce.expressPaymentType);Te.current.set(oe,{generation:ie,method:ce.expressPaymentType,accountPatch:B.accountPatch,sessionId:B.sessionId,nonce:B.nonce}),_e(!1),R?.(Ue.current),ce.resolve()},onConfirm:me,onCancel:()=>{let ce=Te.current.get(oe);Te.current.delete(oe),At(y)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),te(ce?.generation),_e(!1),O.current=!0,Z()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:We,layout:{maxColumns:1,overflow:"never"}}},oe)]})}),U&&(0,l.jsx)(vn,{status:"processing"})]})}function js({method:e,themeId:t,submitting:n=!1,disabled:o=!1,highlighted:r=!1,hasNextStep:i=!1,onClick:m,backgroundColor:d,borderColor:R,textColor:g,borderRadius:v,fontFamily:b}){let A=(0,f.resolveStripeMethodBrandVariant)(e,t),D=yi[e],y=A?.backgroundColor??d??"#ffffff",C=A?.borderColor??R??"#d1d5db",Q=A?.textColor??g??"#262833";return(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!o&&m()},disabled:n||o,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Eo,padding:"0 1rem",backgroundColor:y,color:Q,border:`1px solid ${C}`,borderRadius:v??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||o?"not-allowed":"pointer",opacity:o&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:r?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,l.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,f.getStripeMethodDisplayName)(e)}\u2026`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,f.hasVendoredStripeMethodLogo)(e)?8:0},children:[D?(0,l.jsx)("img",{src:D,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"}}):A?.logoSvg?(0,l.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:A.logoSvg}}):null,(0,l.jsx)("span",{children:(0,f.getStripeMethodDisplayName)(e)})]}),i&&(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:Q,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,l.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function aa({method:e,sessionId:t,nonce:n,email:o,billingName:r,billingApiUrl:i,onTokenizedBody:m,onErrorChange:d,onDecline:R,onCancel:g,runBeforeButtonClick:v,onButtonClick:b,isProcessing:A,submitButtonColor:D,submitButtonBorderRadius:y,submitButtonStyle:C,errorText:Q}){let J=$n(),{emitInstrument:w}=(0,a.useContext)(hn),ge=(0,vt.useStripe)(),U=(0,vt.useElements)(),[ee,re]=(0,a.useState)(!1),be=(0,a.useRef)(!1),[oe,he]=(0,a.useState)(!1),[ze,_e]=(0,a.useState)("loading"),Se=(0,a.useCallback)(async()=>{if(!ge||!U||A||be.current||!oe)return;be.current=!0,re(!0);let K=v?await v("card"):{proceed:!0};if(!K.proceed){be.current=!1,re(!1);return}b?.("card");let O=K.sessionId??t,ae=K.nonce??n,Ue=K.accountPatch?.email??o;try{d?.(null);let Te=await U.submit();if(Te.error){d?.(Te.error.message??"Payment failed.");return}let X=await ge.createPaymentMethod({elements:U});if(X.error||!X.paymentMethod){d?.(X.error?.message??"Failed to create payment method.");return}let $=X.paymentMethod;if(!O||!Ue)throw new Error("Missing sessionId or email for payment.");let te=$.type||e,pe=await Ro(i,w,O,ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,paymentMethodId:null,intentKind:"payment"});if(pe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ve=pe.clientSecret;if(typeof window<"u")try{localStorage.setItem(Bn,JSON.stringify({clientSecret:ve,sessionId:O,nonce:ae,accountPatch:K.accountPatch,paymentMethodId:$.id,paymentMethodType:$.type??e,gateway:"stripe"}))}catch{}let{error:Z,paymentIntent:Re}=await ge.confirmPayment({clientSecret:ve,confirmParams:{return_url:window.location.href,payment_method:$.id},redirect:"if_required"});if(Z){if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let me=Z.message??"Payment failed.";d?.(me),R?.(xt("card",me,{code:Z.code})),await _o({billingApiUrl:i,sessionId:O,nonce:ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Z.code??"provider_declined"}});return}let H=Re?.status;if(!mo(H)){if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let me=H==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(me),R?.(xt("card",me,{code:H??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let _=typeof Re?.payment_method=="string"?Re.payment_method:Re?.payment_method?.id;m({id:_??$.id,type:"card",threeDSecureActionResultTokenId:Re?.id,gateway:"stripe",paymentMethodType:$.type??e},{accountPatch:K.accountPatch,sessionId:O,nonce:ae})}catch(Te){d?.(Te instanceof Error?Te.message:"Payment failed. Please try again.")}finally{be.current=!1,re(!1)}},[ge,U,A,oe,v,b,t,n,o,i,w,e,m,d,R]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,l.jsx)(vt.PaymentElement,{onReady:()=>_e("ready"),onLoadError:()=>{_e("load_error"),ia(At(J),"stripe","apm")},onChange:K=>{he(!!K.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...o?{email:o}:{}}}}}),(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Se()},disabled:!oe||ee||A||ze!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:D,color:"white",border:"none",borderRadius:y,fontSize:"1rem",fontWeight:600,cursor:!oe||ee||A||ze!=="ready"?"not-allowed":"pointer",opacity:!oe||ee||A||ze!=="ready"?.5:1,transition:"opacity 120ms ease-out",...C??{}},children:ee?"Processing\u2026":`Pay with ${(0,f.getStripeMethodDisplayName)(e)}`}),Q&&(0,l.jsx)(Pr,{margin:"0.75rem 0 0",children:Q})]})}function wi({sessionId:e,nonce:t,email:n,billingName:o,billingApiUrl:r,paymentElementMethods:i,stripeInstance:m,paymentElementBaseOptions:d,onTokenizedBody:R,onErrorChange:g,onButtonClick:v,onDecline:b,runBeforeButtonClick:A,onLoadStateChange:D,isProcessing:y=!1,submitButtonColor:C="#4A49FF",submitButtonBorderRadius:Q=8,submitButtonStyle:J,buttonAppearance:w,themeId:ge,onExpandApm:U,expandedApmMethod:ee}){let{emitInstrument:re}=(0,a.useContext)(hn),[be,oe]=(0,a.useState)(null),[he,ze]=(0,a.useState)(null),_e=(0,a.useRef)(!1);(0,a.useEffect)(()=>{i.length>0&&m?D?.("ready"):m||D?.("loading")},[i.length,m,D]);let Se=(0,a.useCallback)(async X=>{if(!m||_e.current||y)return;_e.current=!0,ze(X);let $=A?await A("card"):{proceed:!0};if(!$.proceed){_e.current=!1,ze(null);return}v?.("card");let te=$.sessionId??e,pe=$.nonce??t,ve=$.accountPatch?.email??n;try{if(g?.(null),!te||!ve)throw new Error("Missing sessionId or email for payment.");let Z=await Ro(r,re,te,pe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,paymentMethodId:null,intentKind:"payment"});if(Z.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Re=Z.clientSecret;if(typeof window<"u")try{localStorage.setItem(Bn,JSON.stringify({clientSecret:Re,sessionId:te,nonce:pe,accountPatch:$.accountPatch,paymentMethodType:X,gateway:"stripe"}))}catch{}let{error:H,paymentIntent:_}=await m.confirmPayment({clientSecret:Re,confirmParams:{return_url:window.location.href,payment_method_data:{type:X,billing_details:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...ve?{email:ve}:{}}}},redirect:"if_required"});if(H){if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let $e=H.message??"Payment failed.";g?.($e),b?.(xt("card",$e,{code:H.code})),await _o({billingApiUrl:r,sessionId:te,nonce:pe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,providerDeclineReason:H.code??"provider_declined"}});return}let me=_?.status;if(!mo(me)){if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let $e=me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.($e),b?.(xt("card",$e,{code:me??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let We=typeof _?.payment_method=="string"?_.payment_method:_?.payment_method?.id;R({id:We??_?.id,type:"card",threeDSecureActionResultTokenId:_?.id,gateway:"stripe",paymentMethodType:X},{accountPatch:$.accountPatch,sessionId:te,nonce:pe})}catch(Z){g?.(Z instanceof Error?Z.message:"Payment failed. Please try again.")}finally{_e.current=!1,ze(null)}},[m,y,A,v,e,t,n,r,re,o,R,g,b]),[K,O]=(0,a.useState)(null),ae=U?ee??null:K,Ue=(0,a.useCallback)(X=>{_e.current||y||ae&&ae!==X||((0,f.needsStripeMethodExplicitConfirm)(X)?U?U(X):O(X):Se(X))},[ae,y,Se,U]),Te=(0,a.useMemo)(()=>K?{...d,paymentMethodTypes:[K]}:null,[K,d]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:i.map(X=>{let $=ee===X,te=he===X,pe=he!==null&&he!==X||ee!=null&&ee!==X;return(0,l.jsxs)(a.default.Fragment,{children:[(0,l.jsx)(js,{method:X,themeId:ge,submitting:te,disabled:pe,highlighted:$,hasNextStep:(0,f.needsStripeMethodExplicitConfirm)(X),onClick:()=>Ue(X),backgroundColor:w?.backgroundColor,borderColor:w?.borderColor,textColor:w?.textColor,borderRadius:w?.borderRadius,fontFamily:w?.fontFamily}),!U&&K===X&&Te&&m&&(0,l.jsx)(vt.Elements,{stripe:m,options:Te,children:(0,l.jsx)(aa,{method:X,sessionId:e,email:n,billingName:o,billingApiUrl:r,onTokenizedBody:R,onErrorChange:g,onDecline:b,onCancel:()=>O(null),runBeforeButtonClick:A,onButtonClick:v,isProcessing:y,submitButtonColor:C,submitButtonBorderRadius:Q,submitButtonStyle:J})},X)]},X)})})}function Vs({sessionId:e,nonce:t,billingApiUrl:n,email:o,userId:r,onComplete:i,onError:m,onDecline:d,onTokenizedBody:R,firstName:g,lastName:v,chv:b,className:A,isProcessing:D,error:y,onErrorChange:C,showPayPal:Q=!0,showStripe:J=!0,enabledPaymentMethods:w,enabledPaymentMethodCountries:ge,showApplePay:U=!0,showGooglePay:ee=!0,layout:re="default",theme:be,buttonsTheme:oe,buttonsStyles:he,appearance:ze,cardButtonContent:_e,cardBackButtonContent:Se,cardTitleContent:K,showSecurityFooter:O,onButtonClick:ae,onBeforeButtonClick:Ue,enableAVS:Te,cardFieldOrder:X,cardPreFormSlot:$,avsLayout:te="row",country:pe,zip:ve,addressLine1:Z,addressLine2:Re,city:H,state:_,onCountryChange:me,onZipChange:We,avsCheck:$e,checkoutType:ce,checkoutLayout:B,totalAmount:ie=0,currency:G="usd",initialCardOpen:Oe=!1,directPaypal:Be,isSubscription:Qe=!1,session:se,dataAttachmentPending:yt=!1,debug:j=!1}){let qe=$n(),Pt=yo(),Y=(0,a.useContext)(kn),{emitInstrument:bt}=(0,a.useContext)(hn),Ke=yt||Y.claimPending===!0,Qt=ti(),[Et,T]=(0,a.useState)(!1),[Pe,ft]=(0,a.useState)(null),[Ne,qt]=(0,a.useState)(pe??"US"),[Gt,Ze]=(0,a.useState)(ve??""),[Ct,et]=(0,a.useState)(Z??""),[Mt,Ge]=(0,a.useState)(Re??""),[jt,Rt]=(0,a.useState)(H??""),[en,Dt]=(0,a.useState)(_??""),[Rn,sn]=(0,a.useState)({}),at=(0,a.useRef)(ve??""),Lt=(0,a.useRef)(pe??"US"),Je=(0,a.useRef)(Z??""),_n=(0,a.useRef)(Re??""),dt=(0,a.useRef)(H??""),bn=(0,a.useRef)(_??""),Ot=(0,a.useRef)({});(0,a.useEffect)(()=>{let s=(L,W,de,V,we)=>{if(Ot.current[L])return;let xe=W?.trim();!xe||xe===de.current||(de.current=xe,V(xe),we?.(xe))};s("country",pe,Lt,qt,me),s("zip",ve,at,Ze,We),s("addressLine1",Z,Je,et),s("addressLine2",Re,_n,Ge),s("city",H,dt,Rt),s("state",_,bn,Dt)},[pe,ve,Z,Re,H,_,me,We]);let ue=(0,a.useMemo)(()=>(0,f.resolveAVSConfig)(Te),[Te]),Kn=ue!==null,Tn=(0,a.useMemo)(()=>(0,f.isAuthorizationOnlySession)(se),[se]),xn=!!se?.vault?.html,An=!!se?.gateways?.pcivault,x=!!(se?.gateways?.stripe?.enabledPaymentMethods??w)?.includes("card"),tt=xn||x||An,ke=!!(J&&tt&&qe&&e),[Cn,je]=(0,a.useState)(()=>re!=="buttons"||Oe?e??null:null),[Hn,Qn]=(0,a.useState)(0),Vt=re!=="buttons"||Oe||!!e&&Cn===e,ut=(0,a.useMemo)(()=>!qe||!ke||!e||!Vt?null:qe.cardCapture({sessionId:e,captureMethod:se?.captureMethod}),[qe,ke,e,Vt,se?.captureMethod]),Jt=(0,a.useMemo)(()=>{let s=Ne,L=ue?(0,f.isAVSFieldVisible)(ue.postal_code,s):!1;return $s(s,Gt,L)},[ue,Ne,Gt]),{avsInvalid:Kt,invalidAvsFields:it}=(0,a.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!ke||!ue)return{avsInvalid:!1,invalidAvsFields:s};let L=Ne,W=(we,xe)=>(0,f.isAVSFieldVisible)(we,L)&&!xe.trim(),de={line1:W(ue.address_line_1,Ct),city:W(ue.city,jt),state:W(ue.state,en),zip:Jt.empty||Jt.malformed};return{avsInvalid:de.line1||de.city||de.state||de.zip,invalidAvsFields:de}},[ke,ue,Ne,Ct,jt,en,Jt]),[ln,cn]=(0,a.useState)(!1),[Yn,Sn]=(0,a.useState)(!1),[tn,dn]=(0,a.useState)(()=>ra(se?.vault)),[Ce,St]=(0,a.useState)(Oe&&tt?"card":"buttons"),[st,nn]=(0,a.useState)(null),un=Ce==="expanding"||Ce==="card",Ln=se?.gateways?.stripe?"stripe":void 0,pn=(0,a.useCallback)(()=>{bt?.({class:"card_surface",provider:Ln})},[Ln,bt]),Nt=280,Ht=(0,a.useRef)(null),Yt=(0,a.useCallback)(s=>{Ht.current&&clearTimeout(Ht.current),Ht.current=setTimeout(()=>{Ht.current=null,s()},Nt)},[Nt]);(0,a.useEffect)(()=>()=>{Ht.current&&clearTimeout(Ht.current)},[]);let Wn=(0,a.useCallback)(()=>{pn(),je(e??null),Qn(s=>s+1),St("expanding"),Yt(()=>St("card"))},[Yt,pn,e]),On=(0,a.useCallback)(()=>{St("collapsing"),Yt(()=>St("buttons"))},[Yt]),Mn=(0,a.useCallback)(s=>{nn(s),St("apm-expanding"),Yt(()=>St("apm-form"))},[Yt]),Nn=(0,a.useCallback)(()=>{St("apm-collapsing"),Yt(()=>{St("buttons"),nn(null)})},[Yt]);(0,a.useEffect)(()=>{re==="buttons"&&Oe&&tt&&(je(e??null),St("card"))},[re,Oe,tt,e]);let[zt,nt]=(0,a.useState)(null),mn=(0,a.useRef)(!1),Ut=(0,a.useRef)(null),pt=(0,a.useRef)("idle"),[Xt,_t]=(0,a.useState)(null),er=(0,a.useRef)(Xt);(0,a.useEffect)(()=>{er.current=Xt},[Xt]);let mt=n||Qt,u=y??Pe,c=(0,a.useMemo)(()=>(0,f.resolveTheme)(be),[be]),p=(0,a.useMemo)(()=>{let s=c?.buttonsLayout??(0,f.resolveButtonsLayoutTheme)(oe);return he?{...s,...he,cardButton:{...s.cardButton,...he.cardButton},cardFormContainer:{...s.cardFormContainer,...he.cardFormContainer},backButton:{...s.backButton,...he.backButton},backButtonIcon:{...s.backButtonIcon,...he.backButtonIcon},submitButton:{...s.submitButton,...he.submitButton},title:{...s.title,...he.title}}:s},[c,oe,he]),N=ze??c?.appearance,ne=(0,a.useMemo)(()=>Io({appearance:N,buttonsStyles:p,layout:re}),[N,p,re]),q=Y.inlineSessionPatchProcessing??!1,k=(D??Et)||q,P=mt.replace(/\/+$/,""),h=(0,a.useMemo)(()=>Go({userId:r,email:o,firstName:g,lastName:v,country:pe,zip:ve},Rn),[r,o,g,v,pe,ve,Rn]),S=[h.firstName,h.lastName].filter(s=>!!s?.trim()).join(" "),M=(0,a.useMemo)(()=>qe?qe.getRawProvider():null,[qe]),le=(0,a.useMemo)(()=>Pt?Pt.getRawProvider():null,[Pt]),ye=ie||100,De=(0,a.useMemo)(()=>N?(0,Zn.toStripeAppearance)(N):null,[N]),He=De?{appearance:De}:null,Tt=(0,a.useMemo)(()=>{let s=De??{},L=s.rules??{};return{...s,rules:{...L,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...L[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...L[".AccordionItemContents"]??{}}}}},[De]),Ie=(0,a.useMemo)(()=>{let s=Za(ie);return{...s,currency:G.toLowerCase(),paymentMethodCreation:"manual",...s.mode==="payment"?{captureMethod:"manual"}:{},...He}},[ie,G,He]),Ee=(0,a.useMemo)(()=>({mode:"payment",amount:ye,currency:G.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...He}),[ye,G,He]),z=(0,a.useCallback)(s=>{ft(s),C?.(s)},[C]);(0,a.useEffect)(()=>{!ke||!ut||ut.setCardFieldOrder?.(X??null,ue==null)},[ke,ut,X,ue]),(0,a.useEffect)(()=>{(Ce==="expanding"||Ce==="collapsing"||Ce==="apm-expanding"||Ce==="apm-collapsing")&&z(null)},[Ce,z]);let wt=(0,a.useCallback)((s,L,W)=>{d?.(xt(s,L,W))},[d]),Ye=(0,a.useCallback)((s,L,W)=>{let de=W?.popupBlocked??Jn(L),V=zs(s,de),we=ir(W?.code)??Un(L)??"external_payment_method_failed",xe=new f.FloPayError(V,"api_error",{code:"external_payment_method_failed",param:s});nt(null),re==="buttons"&&(St("buttons"),nn(null)),z(V),m?.(xe),console.error("[FloPay] External payment method failed:",{method:s,code:we,popupBlocked:de})},[re,m,z]);(0,a.useEffect)(()=>{if(!ke||!e){dn(null);return}let s=ra(se?.vault);if(s){dn(s);return}if(!Vt){dn(null);return}dn(null);let L=!0;return new Zn.PaymentAPI(P).getVaultCapture(e,t).then(W=>{if(!L)return;let de=ra(W);de?dn(de):z("Failed to load the secure card form.")}).catch(W=>{L&&z(W instanceof Error?W.message:"Failed to load the secure card form.")}),()=>{L=!1}},[ke,Vt,Hn,e,se?.vault?.html,se?.vault?.messageToken,se?.vault?.expectedOrigin,P,t,z]);let rt=(0,a.useRef)({onComplete:i,onError:m,updateError:z,emitDecline:wt,resolvedAccount:h,avsConfig:ue,avsCheckProp:$e,sessionId:e,nonce:t,baseUrl:P,captureMethod:se?.captureMethod,paymentId:se?.paymentId,authorizationExpiresAt:se?.authorizationExpiresAt});rt.current={onComplete:i,onError:m,updateError:z,emitDecline:wt,resolvedAccount:h,avsConfig:ue,avsCheckProp:$e,sessionId:e,nonce:t,baseUrl:P,captureMethod:se?.captureMethod,paymentId:se?.paymentId,authorizationExpiresAt:se?.authorizationExpiresAt};let tr=(0,a.useRef)(!1),Pa=(0,a.useCallback)(()=>{let{resolvedAccount:s,avsConfig:L,avsCheckProp:W}=rt.current,de=Lt.current||s.country||"US",V=L?(0,f.isAVSFieldVisible)(L.state,de):!1,we=L?(0,f.isAVSFieldVisible)(L.address_line_1,de):!1,xe=L?(0,f.isAVSFieldVisible)(L.postal_code,de):!1,gt=L?(0,f.isAVSFieldVisible)(L.city,de):!1,$t=L?(0,f.isAVSFieldVisible)(L.address_line_2,de):!1,ht=we&&!V&&xe?(0,f.getStateFromPostalCode)(de,(at.current??"").trim()):null,lt=V?bn.current:ht;return{accountData:{userId:s.userId??"",email:s.email??"",firstName:s.firstName??"",lastName:s.lastName??"",...xe&&at.current?{zip:at.current}:{},...gt&&dt.current?{city:dt.current}:{},...lt?{state:lt}:{},...we&&Je.current?{addressLine1:Je.current}:{},...$t&&_n.current?{addressLine2:_n.current}:{},country:de},...W!==void 0?{avsCheck:W}:{},...L?{avsConfig:{country:(0,f.isAVSFieldVisible)(L.country,de),postal_code:xe,address_line_1:we,address_line_2:$t,city:gt,state:V}}:{}}},[]),Zr=(0,a.useRef)(Ke);Zr.current=Ke,(0,a.useEffect)(()=>{Ke||u!==hi||rt.current.updateError(null)},[Ke,u]),(0,a.useEffect)(()=>{!ke||!ut||ut.setSubmitGate?.(Kt||Ke)},[ke,ut,Kt,Ke]),(0,a.useEffect)(()=>{if(!ke||!ut)return;tr.current=!1;let s=!1,L=ut.on("submitting",()=>{cn(!0),Ut.current&&clearTimeout(Ut.current),pt.current="validation-window",Ut.current=setTimeout(()=>{Ut.current=null,pt.current==="validation-window"&&(pt.current="processing")},Fs),nt("processing");let{baseUrl:xe,sessionId:gt,nonce:$t,updateError:ht,onError:lt}=rt.current;!gt||!$t||new Zn.PaymentAPI(xe).patchAccountSnapshot(gt,$t,Pa(),{telemetryMode:"best_effort"}).catch(Ve=>{if(!Ds(Ve))return;let zn=Ve instanceof Error?Ve.message:"Please check your billing address and try again.";ht(zn),pt.current="idle",nt(null),lt?.(Ve instanceof f.FloPayError?Ve:new f.FloPayError(zn,"api_error"))})}),W=ut.on("complete",async xe=>{if(br(xe.sessionId??rt.current.sessionId),pt.current="terminal",nt("success"),await new Promise(ht=>setTimeout(ht,1200)),tr.current)return;tr.current=!0;let gt=rt.current,$t=(0,f.isAuthorizationOnlySession)(gt)||xe.outcome==="authorized";rt.current.onComplete?.($t?{status:"authorized",paymentIntentId:xe.intentId,paymentId:xe.paymentId??gt.paymentId,sessionId:xe.sessionId??gt.sessionId,authorizationExpiresAt:xe.authorizationExpiresAt??gt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:xe.intentId,checkoutMethod:"card"})}),de=ut.on("decline",async xe=>{let{updateError:gt,emitDecline:$t}=rt.current,ht=xe.message??"Your payment was declined. Please try another card or contact your bank.";pt.current="terminal",gt(ht),nt("error");let lt=xe.failureOutcome??(0,f.normalizeCheckoutFailureOutcome)(xe.declineReason)??"authorization_declined";$t("card",ht,{code:lt,declineCode:lt}),await new Promise(Ve=>setTimeout(Ve,1500)),!s&&(pt.current="idle",nt(null))}),V=ut.on("error",async xe=>{let{updateError:gt,onError:$t}=rt.current,ht=xe.message??"There was a problem processing your payment. Please try again.";pt.current="terminal",gt(ht),nt("error"),$t?.(new f.FloPayError(ht,"api_error",{code:xe.failureOutcome??"capture_failed"})),await new Promise(lt=>setTimeout(lt,1500)),!s&&(pt.current="idle",nt(null))}),we=ut.on("blocked",()=>{if(!Zr.current){cn(!0);return}rt.current.updateError(hi)});return()=>{s=!0,Ut.current&&(clearTimeout(Ut.current),Ut.current=null),pt.current="idle",L(),W(),de(),V(),we()}},[ke,ut]);let rn=!!Be?.clientId,Er=Array.isArray(w),Qr=Er&&w.length>0,Ui=Er&&w.includes("paypal"),{expressMethods:eo,paymentElementMethods:Rr}=(0,a.useMemo)(()=>(0,f.partitionStripeMethods)(w,{excludePaypal:rn}),[w,rn]),ba=rn||!!Pt,$i=(0,a.useMemo)(()=>ba?eo.filter(s=>s!=="paypal"):eo,[eo,ba]),qi=(0,a.useMemo)(()=>{let s=[];return U&&s.push("apple_pay"),ee&&s.push("google_pay"),s},[U,ee]),to=Er?$i:qi,ji=J&&to.length>0,Lo=Kn?Ne:pe,no=(0,a.useMemo)(()=>{let s=Lo?.trim().toUpperCase();return s?ge?Rr.filter(L=>{let W=ge[L];return!W||W.length===0||W.includes(s)}):(0,f.filterStripeMethodsByCountry)(Rr,Lo):Rr},[Rr,Lo,ge]),Oo=(0,a.useMemo)(()=>({mode:"payment",amount:ye,currency:G.toLowerCase(),paymentMethodCreation:"manual",appearance:Tt}),[ye,G,Tt]),[Ca,Sa]=(0,a.useState)("loading"),[wa,ka]=(0,a.useState)("loading"),[Ia,Ea]=(0,a.useState)("loading"),[Vi,No]=(0,a.useState)(!1),[Ra,zo]=(0,a.useState)("loading"),[ro,Ki]=(0,a.useState)();(0,a.useEffect)(()=>{Ki(mi())},[]);let _a=Q&&(rn||(Er?Ui:ro===!1)),Ta=J&&ji,_r=!Ke&&_a&&rn,xa=Ra==="retrying"||Ra==="exhausted",Tr=!Ke&&_a&&!!le&&(!rn||xa),xr=!Ke&&Ta&&!!M,Ar=!Ke&&J&&Qr&&no.length>0&&!!M,Hi=_r&&!xa?Vi:Tr&&bi(Ca),Yi=xr&&bi(wa),Wi=Ar&&Ia!=="load_error",Aa=s=>s==="loading"||s==="ready",Ma=_r||Tr&&Aa(Ca)||xr&&Aa(wa)||Ar&&Ia!=="load_error",oo=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(!oo.current){if(!J&&!Q){oo.current=!0;let s=new f.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");m?.(s),z(s.message)}else if(!J&&Q&&!rn&&!le){oo.current=!0;let s=new f.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");m?.(s),z(s.message)}else if(ro!==void 0&&!Ke&&!tt&&!Ma){oo.current=!0;let s=new f.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?.(s),z(s.message)}}},[J,Q,rn,le,ro,Ke,tt,Ma,m,z]);let Ba=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(Ba.current||!Qr)return;let s=[];U!==!0&&s.push("showApplePay"),ee!==!0&&s.push("showGooglePay"),s.length!==0&&(Ba.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Qr,U,ee]);let Fa=(0,a.useCallback)((s,L)=>Y.applyInlineSessionPatch?Y.applyInlineSessionPatch(s).then(W=>({error:null,sessionId:W.sessionId||e,nonce:W.session?.clientSecret||t})).catch(W=>{let de=Pi(L,W);return z(de.message),m?.(de),{error:de,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Y.applyInlineSessionPatch,t,m,e,z]),wn=(0,a.useCallback)(async s=>{if(!Ue)return{proceed:!0};try{let L=await Ue({method:s,sessionId:e||void 0,createSession:Y.inlineSessionDraft});if(L===!1)return{proceed:!1};if(L&&typeof L=="object"){L.account&&sn(de=>({...de??{},...L.account}));let W=await Fa(L,s);return W.error?{proceed:!1,accountPatch:L.account}:{proceed:!0,accountPatch:L.account,sessionId:W.sessionId,nonce:W.nonce}}return{proceed:!0}}catch(L){let W=Pi(s,L);return z(W.message),m?.(W),{proceed:!1}}},[Fa,Y.inlineSessionDraft,Ue,m,e,z]),Da=(0,a.useCallback)(async(s,L)=>{if(mn.current)return;mn.current=!0,T(!0),nt("processing"),z(null);let W=L?.sessionId??e,de=L?.nonce??t,V=Go(h,L?.accountPatch),we=L?.completionPaymentMethodId??zr(s),xe=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,gt=s.gateway==="stripe"?"stripe":s.gateway==="paypal"||s.isPaypal?"paypal":void 0,$t=()=>{bt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:gt})};try{let lt=await new Zn.PaymentAPI(P).processPayment(V.userId??"",{sessionId:W,nonce:de,tokenizedData:xe,accountData:{userId:V.userId??"",email:V.email??"",firstName:V.firstName??"",lastName:V.lastName??"",...ue?(()=>{let Xe=Lt.current,fn=(0,f.isAVSFieldVisible)(ue.state,Xe),gn=(0,f.isAVSFieldVisible)(ue.address_line_1,Xe),Bt=(0,f.isAVSFieldVisible)(ue.postal_code,Xe),Lr=gn&&!fn&&Bt?(0,f.getStateFromPostalCode)(Xe,(at.current??"").trim()):null,Or=fn?bn.current:Lr;return{country:Xe,...Bt&&at.current?{zip:at.current}:{},...(0,f.isAVSFieldVisible)(ue.city,Xe)&&dt.current?{city:dt.current}:{},...Or?{state:Or}:{},...gn&&Je.current?{addressLine1:Je.current}:{},...(0,f.isAVSFieldVisible)(ue.address_line_2,Xe)&&_n.current?{addressLine2:_n.current}:{}}})():{}},chv:b,avsCheck:$e??!1,checkoutType:ce,checkoutLayout:B,avsConfig:ue?{country:(0,f.isAVSFieldVisible)(ue.country,Lt.current),postal_code:(0,f.isAVSFieldVisible)(ue.postal_code,Lt.current),address_line_1:(0,f.isAVSFieldVisible)(ue.address_line_1,Lt.current),address_line_2:(0,f.isAVSFieldVisible)(ue.address_line_2,Lt.current),city:(0,f.isAVSFieldVisible)(ue.city,Lt.current),state:(0,f.isAVSFieldVisible)(ue.state,Lt.current)}:void 0});if(lt.ok){let Xe=lt.status===204?null:await lt.json().catch(()=>null),fn=(0,f.isAuthorizationOnlySession)(se)||Xe?.status==="authorized";br(W),nt("success"),_t(null),await new Promise(gn=>setTimeout(gn,1200)),i?.(fn?{status:"authorized",...typeof Xe?.paymentId=="string"?{paymentId:Xe.paymentId}:se?.paymentId?{paymentId:se.paymentId}:{},sessionId:typeof Xe?.sessionId=="string"?Xe.sessionId:W,...typeof Xe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Xe.authorizationExpiresAt}:se?.authorizationExpiresAt?{authorizationExpiresAt:se.authorizationExpiresAt}:{},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:we,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:we,checkoutMethod:s.isPaypal?"paypal":"card"});return}let Ve=await lt.json().catch(()=>null);if(Ve?.type==="paypal_redirect_required"){let Xe=Ve.threeDSecureToken,fn=Ve.paymentMethodId||s.id||"";if(!qe||!Xe){nt("error"),z("PayPal authorization required but no token provided.");return}try{let gn=Pt?.getRawProvider();if(!gn){z("PayPal is not available.");return}let Bt={return_url:window.location.href};fn&&(Bt.payment_method=fn);let{error:Lr}=await gn.confirmPayment({clientSecret:Xe,confirmParams:Bt,redirect:"if_required"});if(Lr){nt("error");let Or=Lr.message??"PayPal payment failed.";z(Or),wt("paypal",Or,{code:Lr.code})}}catch(gn){nt("error"),z(gn instanceof Error?gn.message:"PayPal authorization failed.")}return}if(Ve?.type==="paypal_direct_required"){let Xe=Ve.orderId;if(!Xe){nt("error"),z("PayPal retry required but no order id provided.");return}let fn=er.current?.attempts??0;if(fn>=2){nt("error"),z("PayPal payment could not be completed after multiple attempts."),wt("paypal","paypal_direct_required retry limit exceeded");return}No(!1),zo("loading"),_t({orderId:Xe,attempts:fn+1}),nt(null);return}(0,f.classifyPaymentRejection)(lt.status,Ve)||$t(),nt("error");let zn=Ve?.message??"Payment failed. Please try again.";z(zn),wt(s.isPaypal?"paypal":"card",zn,{code:Ve?.code??Ve?.gatewayErrorCode,declineCode:Ve?.declineCode??Ve?.gatewayDeclineReason}),await new Promise(Xe=>setTimeout(Xe,1500))}catch(ht){ki(ht)||$t(),nt("error"),z(ht instanceof Error?ht.message:"An unexpected error occurred"),await new Promise(lt=>setTimeout(lt,1500))}finally{T(!1),nt(null),mn.current=!1}},[P,e,t,h,S,b,qe,Pt,se,i,m,z,wt,bt]),yn=(0,a.useCallback)((s,L)=>{R?R(s):Da(s,L)},[R,Da]),La=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||La.current)return;let s=new URLSearchParams(window.location.search),L=s.get("payment_intent"),W=s.get("payment_intent_client_secret"),de=s.get("redirect_status");if(!L||!W)return;let V=lt=>{let Ve=localStorage.getItem(lt);if(!Ve)return null;try{return JSON.parse(Ve)}catch{return localStorage.removeItem(lt),null}},we=V(Bn)??V(gi),xe;if(we?.clientSecret){if(we.clientSecret!==W)return;xe={...we.accountPatch?{accountPatch:we.accountPatch}:{},...we.sessionId?{sessionId:we.sessionId}:{},...we.nonce?{nonce:we.nonce}:{}}}else if(we?.sessionId&&we.sessionId!==e)return;La.current=!0,localStorage.removeItem(Bn),localStorage.removeItem(gi);let gt=new URL(window.location.href);gt.searchParams.delete("payment_intent"),gt.searchParams.delete("payment_intent_client_secret"),gt.searchParams.delete("redirect_status"),window.history.replaceState({},"",gt.toString());let $t=we?.paymentMethodType??we?.tokenType??"card",ht="card";(async()=>{let lt=qe?.getRawProvider();if(!lt){let Bt="Payment is not available \u2014 please refresh and try again.";z(Bt),wt(ht,Bt);return}if(de==="failed"){let Bt="Payment was declined. Please try again.";z(Bt),wt(ht,Bt);return}let{paymentIntent:Ve,error:zn}=await lt.retrievePaymentIntent(W);if(zn){let Bt=zn.message??"Failed to retrieve payment status.";z(Bt),wt(ht,Bt,{code:zn.code});return}let Xe=Ve?.status,fn=mo(Xe);if(!Ve||!fn){let Bt=Xe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";z(Bt),wt(ht,Bt,{code:Xe??"missing_payment_intent"});return}let gn=typeof Ve.payment_method=="string"?Ve.payment_method:Ve.payment_method?.id;yn({id:gn??we?.paymentMethodId??we?.tokenId??Ve.id,type:"card",threeDSecureActionResultTokenId:Ve.id,gateway:we?.gateway??"stripe",paymentMethodType:$t},xe)})()},[e,yn,qe,z,wt]);let Uo=(0,a.useCallback)(s=>{s.preventDefault()},[]);if(!(qe!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Mr=re==="buttons",Zt=N?.variables,Gi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),$o=Zt?.colorBackground,Ji=$o&&!Gi.has($o)?$o:void 0,Br=p.cardInputBorder??(Mr?"#e5e7eb":"#A4A4FF"),qo=Zt?.colorDanger??"#dc2626",nr=s=>ln&&s?qo:Br,ao=(Jt.malformed||Jt.empty)&&(Yn||ln),Xi=ao?qo:nr(it.zip),jo=p.cardFormContainer?.backgroundColor??Ji??(Mr?"white":"#EDEDFF"),Fr=p.cardInputBackground??Zt?.colorBackground??"white",Vo=pr(Se),Oa=pr(K),ur=p.nameInput,Na=p.cardInputFontSize??qs(ur?.fontSize)??Zt?.fontSizeBase??"16px",za=typeof ur?.fontFamily=="string"?ur.fontFamily:Zt?.fontFamily??"Poppins, sans-serif",Ua=na(ur?.fontWeight)??400,Zi=p.cardInputColor??(typeof ur?.color=="string"?ur.color:void 0)??Zt?.colorText??"#262833",Qi=p.cardInputPlaceholderColor??"#9ca3af",kt=Zt?.borderRadius??"8px",rr=Zt?.borderRadius??p.cardButton?.borderRadius??kt,or=Zt?.colorPrimary??"#4A49FF",es=Zt?.colorPrimaryHover??kr(or,.12),Ko=Zt?.colorText??"#262833",$a={fontSize:Na,fontFamily:za,fontWeight:Ua,color:Zi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ts={"--flopay-input-placeholder-color":Qi,"--flopay-input-font-size":Na,"--flopay-input-font-family":za,"--flopay-input-font-weight":String(Ua)},Dr=p.cardFormContainer??{},Ho=Dr.padding??(Mr?"0":"1rem"),Yo=Dr.borderRadius??kt,ns=ut&&tn?(0,l.jsx)(wr,{capture:ut,html:tn.html,messageToken:tn.messageToken,expectedOrigin:tn.expectedOrigin,theme:ne,onReady:()=>{if(!ue||typeof document>"u")return;let s=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};s();let L=0,W=window.setInterval(()=>{L+=1;let de=document.activeElement;!!de&&de.tagName==="IFRAME"&&de.id==="flopay_vault_form_iframe"?(s(),window.clearInterval(W)):L>=50&&window.clearInterval(W)},100)},onError:s=>z(s),onValidation:s=>{let L=pt.current;(L==="idle"||L==="validation-window")&&(z(s),s&&pt.current==="validation-window"&&(Ut.current&&(clearTimeout(Ut.current),Ut.current=null),pt.current="idle",nt(null)))}}):(0,l.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),qa=(0,l.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&pn()},style:{backgroundColor:jo,borderRadius:Yo,...Dr,padding:Ho,...ts,display:"flex",flexDirection:"column"},children:[(0,l.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 @@ ${re.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),
|
|
39
|
-
`)}):null,
|
|
40
|
-
`)}):null,Da=Ae==="apm-expanding"||Ae==="apm-form"||Ae==="apm-collapsing",eo=Ae==="apm-expanding"?`flopay-card-enter ${Dt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ae==="apm-collapsing"?`flopay-card-exit ${Dt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,to=ht?{...To,paymentMethodTypes:[ht]}:null;if(ae==="buttons"){let s=Ae==="buttons"||Ae==="expanding"||Ae==="apm-expanding",N=Ae==="expanding"||Ae==="card"||Ae==="collapsing",G=De===void 0?{boxSizing:"border-box",height:fo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},fe=Ae==="expanding"||Ae==="apm-expanding"?`flopay-buttons-exit ${Dt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ae==="collapsing"||Ae==="apm-collapsing"?`flopay-buttons-enter ${Dt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,Y=Ae==="expanding"?`flopay-card-enter ${Dt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ae==="collapsing"?`flopay-card-exit ${Dt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,c.jsxs)("form",{onSubmit:Bo,className:C,style:{position:"relative"},children:[(0,c.jsx)(Wo,{}),In&&(0,c.jsx)(cn,{status:In,errorMessage:q,authorized:on}),(0,c.jsxs)("div",{style:{display:"grid"},children:[(0,c.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!fe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!fe?Ss:{},...fe?{animation:fe,pointerEvents:"none"}:{}},children:[Ba("flopay-direct-paypal-gate-debug"),Fa("flopay-stripe-gate-debug"),Rr&&qe&&(0,c.jsxs)(c.Fragment,{children:[Ee&&(0,c.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,c.jsx)(zr,{sessionId:e,nonce:t,billingApiUrl:y,email:O.email,clientId:qe.clientId,environment:qe.environment,currency:be.toUpperCase(),isSubscription:ct,providerObjectType:qe.providerObjectType,onTokenizedBody:ln,onComplete:i,onErrorChange:Se,onDecline:d,onTechnicalFailure:sr,onButtonClick:we,runBeforeButtonClick:yn,isProcessing:Q,onLoadStateChange:Mo,onInitializationStateChange:Ao,session:ve??null,existingOrderId:Ee?.orderId,debug:ot},Ee?.orderId??"fresh")]}),Er&&(0,c.jsx)(mt.Elements,{stripe:z,options:la,children:(0,c.jsx)(ii,{sessionId:e,nonce:t,email:O.email,billingApiUrl:y,onTokenizedBody:ln,onErrorChange:Se,isProcessing:Q,onButtonClick:we,onDecline:d,onTechnicalFailure:sr,runBeforeButtonClick:yn,onLoadStateChange:pa,placeholderBorderRadius:Jn})}),Ir?(0,c.jsx)(mt.Elements,{stripe:I,options:Hr,children:(0,c.jsx)(si,{sessionId:e,nonce:t,email:O.email,billingApiUrl:y,intentKind:X>0?"payment":"setup",expressMethods:Wr,onTokenizedBody:ln,onErrorChange:Se,onButtonClick:we,onDecline:d,onTechnicalFailure:sr,runBeforeButtonClick:yn,onLoadStateChange:ya,placeholderBorderRadius:Jn})}):ba?(0,c.jsx)("div",{style:{height:fo,borderRadius:Jn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,_r&&(0,c.jsx)(li,{sessionId:e,nonce:t,email:O.email,billingName:[O.firstName,O.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:y,paymentElementMethods:Gr,stripeInstance:I,paymentElementBaseOptions:To,onTokenizedBody:ln,onErrorChange:Se,onButtonClick:we,onDecline:d,runBeforeButtonClick:yn,onLoadStateChange:ga,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:Pt,submitButtonStyle:l.submitButton,onExpandApm:Vn,expandedApmMethod:ht,themeId:j,buttonAppearance:{backgroundColor:l.cardButton?.backgroundColor,borderColor:l.cardInputBorder,textColor:l.cardButton?.color,borderRadius:Jn}}),We&&(0,c.jsx)("button",{type:"button",onClick:async()=>{Q||!(await yn("card")).proceed||(we?.("card"),Wn())},disabled:Q,style:{width:"100%",...G,...l.cardButton,...Xo({themeBundle:m,resolvedPrimaryColor:Xn,resolvedBorderRadius:Pt,submitButtonStyle:l.submitButton,explicitPrimaryColor:Kt?.colorPrimary}),fontSize:l.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Q?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Q?.6:1},onMouseEnter:Be=>{!Q&&(m||Kt?.colorPrimary)&&(Be.currentTarget.style.backgroundColor=Wi)},onMouseLeave:Be=>{(m||Kt?.colorPrimary)&&(Be.currentTarget.style.backgroundColor=Xn)},onMouseDown:Be=>{Be.currentTarget.style.transform="scale(0.985)"},onMouseUp:Be=>{Be.currentTarget.style.transform="scale(1)"},children:(0,c.jsx)(dr,{content:De})}),q&&Ae==="buttons"&&(0,c.jsx)(yr,{margin:"0.25rem 0",styleOverride:l.errorBanner,children:q})]}),We&&N&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...Y?{animation:Y}:{},...Ae==="collapsing"?{pointerEvents:"none"}:{}},children:Aa}),_&&Da&&ht&&to&&I&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...eo?{animation:eo}:{},...Ae==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Lo,borderRadius:Uo,...Ar,padding:No},children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,c.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Lt,style:{display:"inline-flex",alignItems:"center",gap:Oo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:l.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...l.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...l.backButtonIcon},children:(0,c.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(ur,{content:P})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:l.titleFontSize??"1.05rem",color:zo,paddingRight:80,...l.title},children:`Pay with ${(0,v.getStripeMethodDisplayName)(ht)}`})]}),(0,c.jsx)(mt.Elements,{stripe:I,options:to,children:(0,c.jsx)(Go,{method:ht,sessionId:e,nonce:t,email:O.email,billingName:[O.firstName,O.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:y,onTokenizedBody:ln,onErrorChange:Se,onDecline:d,onCancel:Lt,runBeforeButtonClick:yn,onButtonClick:we,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:Pt,submitButtonStyle:l.submitButton,errorText:q})},ht)]})})]})]})}return Da&&ht&&to&&I&&_?(0,c.jsxs)("form",{onSubmit:Bo,className:C,style:{position:"relative"},children:[(0,c.jsx)(Wo,{}),In&&(0,c.jsx)(cn,{status:In,errorMessage:q,authorized:on}),(0,c.jsx)("div",{style:{...eo?{animation:eo}:{},...Ae==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Lo,borderRadius:Uo,...Ar,padding:No},children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,c.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Lt,style:{display:"inline-flex",alignItems:"center",gap:Oo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:l.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...l.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...l.backButtonIcon},children:(0,c.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(ur,{content:P})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:l.titleFontSize??"1.05rem",color:zo,paddingRight:80,...l.title},children:`Pay with ${(0,v.getStripeMethodDisplayName)(ht)}`})]}),(0,c.jsx)(mt.Elements,{stripe:I,options:to,children:(0,c.jsx)(Go,{method:ht,sessionId:e,nonce:t,email:O.email,billingName:[O.firstName,O.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:y,onTokenizedBody:ln,onErrorChange:Se,onDecline:d,onCancel:Lt,runBeforeButtonClick:yn,onButtonClick:we,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:Pt,submitButtonStyle:l.submitButton,errorText:q})},ht)]})})]}):(0,c.jsxs)("form",{onSubmit:Bo,className:C,style:{position:"relative"},children:[(0,c.jsx)(Wo,{}),In&&(0,c.jsx)(cn,{status:In,errorMessage:q,authorized:on}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ba("flopay-direct-paypal-gate-debug-default"),Fa("flopay-stripe-gate-debug-default"),Rr&&qe&&(0,c.jsxs)(c.Fragment,{children:[Ee&&(0,c.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,c.jsx)(zr,{sessionId:e,nonce:t,billingApiUrl:y,email:O.email,clientId:qe.clientId,environment:qe.environment,currency:be.toUpperCase(),isSubscription:ct,providerObjectType:qe.providerObjectType,onTokenizedBody:ln,onComplete:i,onErrorChange:Se,onDecline:d,onTechnicalFailure:sr,onButtonClick:we,runBeforeButtonClick:yn,isProcessing:Q,onLoadStateChange:Mo,onInitializationStateChange:Ao,session:ve??null,existingOrderId:Ee?.orderId,debug:ot},Ee?.orderId??"fresh")]}),Er&&(0,c.jsx)(mt.Elements,{stripe:z,options:la,children:(0,c.jsx)(ii,{sessionId:e,nonce:t,email:O.email,billingApiUrl:y,onTokenizedBody:ln,onErrorChange:Se,isProcessing:Q,onButtonClick:we,onDecline:d,onTechnicalFailure:sr,runBeforeButtonClick:yn,onLoadStateChange:pa,placeholderBorderRadius:Jn})}),Ir&&(0,c.jsx)(mt.Elements,{stripe:I,options:Hr,children:(0,c.jsx)(si,{sessionId:e,nonce:t,email:O.email,billingApiUrl:y,intentKind:X>0?"payment":"setup",expressMethods:Wr,onTokenizedBody:ln,onErrorChange:Se,onButtonClick:we,onDecline:d,onTechnicalFailure:sr,runBeforeButtonClick:yn,onLoadStateChange:ya,placeholderBorderRadius:Jn})}),_r&&(0,c.jsx)(li,{sessionId:e,nonce:t,email:O.email,billingName:[O.firstName,O.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:y,paymentElementMethods:Gr,stripeInstance:I,paymentElementBaseOptions:To,onTokenizedBody:ln,onErrorChange:Se,onButtonClick:we,onDecline:d,runBeforeButtonClick:yn,onLoadStateChange:ga,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:Pt,submitButtonStyle:l.submitButton,themeId:j,onExpandApm:Vn,expandedApmMethod:ht,buttonAppearance:{backgroundColor:l.cardButton?.backgroundColor,borderColor:l.cardInputBorder,textColor:l.cardButton?.color,borderRadius:Jn}})]}),We&&($i||Ui||ji)&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,c.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,c.jsx)("span",{children:"or pay with card"}),(0,c.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),We&&Aa]})}var vr=require("@flopay/js"),Ue=require("@flopay/shared");var $r="card";async function Ts(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:u}=await e.retrieveSetupIntent(t);return{error:u,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:a,error:r}=await e.retrievePaymentIntent(t);return{error:r,intent:a??null}}async function Ms(e,t,n,a){if(a){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:u,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:u??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:r,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:r??null}}function Zo(e,t){return Object.assign(e,{checkoutMethod:t})}function Ln(e,t){let n=e instanceof Ue.FloPayError?e:new Ue.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Ur(e,t){try{return await e()}catch(n){throw Ln(n,t)}}function yi(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function As(e){return e.status==="succeeded"||e.status==="declined"}async function fi(e){if(typeof document>"u"||typeof window>"u")throw new Ue.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ue.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,a=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let g=new AbortController,R=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",R);let C=window.setTimeout(()=>g.abort(),a);try{let k=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!k.ok)return{status:"unknown"};let p=await k.json().catch(()=>null);return Bs(p)}catch{return{status:"unknown"}}finally{window.clearTimeout(C),e.signal?.removeEventListener("abort",R)}},u=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let b=document.createElement("iframe");b.setAttribute("title","Card authentication"),b.setAttribute("allow","payment"),b.tabIndex=0,b.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),b.src=e.nextActionRedirectUrl,d.appendChild(b),document.body.appendChild(d),b.focus();let M=null;try{M=new URL(e.billingApiUrl,window.location.href).origin}catch{M=null}try{let g=await new Promise((R,C)=>{let k=!1,p=0,h=0,E=0,_=!1,f=()=>{window.clearTimeout(p),window.clearInterval(h),window.clearTimeout(E),window.removeEventListener("message",ae),b.removeEventListener("load",x),e.signal?.removeEventListener("abort",oe)},ge=async()=>{if(!(k||_)){_=!0;try{let j=await i();if(k||!As(j))return;k=!0,f(),R(j)}finally{_=!1}}},x=()=>{window.clearTimeout(E),E=window.setTimeout(()=>{ge()},250)},oe=()=>{k||(k=!0,f(),C(new Ue.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ae=j=>{if(j.source!==b.contentWindow||M&&j.origin!==M)return;let K=j.data;!K||typeof K!="object"||K.source!=="flopay-vault-3ds-return"||k||(k=!0,f(),R(null))};p=window.setTimeout(()=>{k||(k=!0,f(),C(new Ue.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),h=window.setInterval(()=>{ge()},n),b.addEventListener("load",x),window.addEventListener("message",ae),e.signal?.addEventListener("abort",oe),e.signal?.aborted&&oe()});return g||await i()}finally{d.parentNode?.removeChild(d),u?.isConnected&&u.focus()}}function Bs(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Kn(e,t="Payment failed. Please try again.",n){let a=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),r=e?.message??t,i=qn(r)??r;return Zo(new Ue.FloPayError(i,"api_error",{code:(0,Ue.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ue.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),a)}function Qo(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Po(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Fs(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function gi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||Po(r)))return r;let a=e?.data;if(a&&typeof a=="object"){let r=a,i=[r.threeDSecureToken,r.clientSecret,r.stripeClientSecret,r.id];for(let d of i)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||Po(d)))return d;let u=r.gateways;if(u&&typeof u=="object"){let d=u.stripe;if(d&&typeof d=="object"){let b=d,M=[b.stripeClientSecret,b.clientSecret];for(let g of M)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||Po(g)))return g}}}}async function Ds({billingApiUrl:e,sessionId:t,nonce:n,responseJson:a}){let r=gi(a,{requirePaymentIntentClientSecret:!0});if(typeof r=="string"&&r.length>0)return{type:"3ds_required",threeDSecureToken:r};if(!t)return null;try{let d=(await new vr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Po(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function Cr({billingApiUrl:e,sessionId:t,session:n,nonce:a,tokenizedData:r,returnUrl:i,telemetry:u}){let d=e.replace(/\/+$/,""),b=t??n.id,M=a??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",R=n.customer?.email??n.accountData?.email??"",C=n.customer?.firstName??n.accountData?.firstName??"",k=n.customer?.lastName??n.accountData?.lastName??"",p=n.customer?.country??n.accountData?.country??void 0,h=n.customer?.zip??n.accountData?.zip??void 0,E=new vr.PaymentAPI(d,u===!1?{telemetry:!1}:void 0),_=await Fs(()=>E.processPayment(g,{sessionId:b,nonce:M,tokenizedData:r,accountData:{userId:g,email:R,firstName:C,lastName:k,country:p,zip:h},returnUrl:i??Qo(n)}));if(_.ok){let x=typeof _.json=="function"?await _.json().catch(()=>null):null;return(0,Ue.isAuthorizationOnlySession)(n)||x?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof x?.paymentId=="string"?x.paymentId:n.paymentId,sessionId:typeof x?.sessionId=="string"?x.sessionId:b,authorizationExpiresAt:typeof x?.authorizationExpiresAt=="string"?x.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Lr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:Lr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}}let f;try{f=await _.json()}catch{throw new Ue.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:_.status})}if(f?.type==="paypal_redirect_required"||f?.type==="3ds_required"){let x=gi(f);if(!x)throw new Ue.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:_.status});return{type:f.type,threeDSecureToken:x,paymentMethodId:f.paymentMethodId}}if(f?.gatewayErrorCode==="authentication_required"){let x=await Ds({billingApiUrl:d,sessionId:b,nonce:M,responseJson:f});if(x)return x;throw Zo(new Ue.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ge=new Ue.FloPayError(f?.message??"Payment failed. Please try again.","api_error",{code:f?.code??f?.gatewayErrorCode,declineCode:f?.declineCode??f?.gatewayDeclineReason,statusCode:_.status});throw Object.assign(ge,{telemetryOutcome:(0,Ue.classifyPaymentRejection)(_.status,f)})}async function bo(e,{flopay:t,paypalFlopay:n,attempt3DS:a,billingApiUrl:r,sessionId:i,session:u,returnUrl:d,telemetry:b}){let M=t?.getRawProvider();if(!M)throw Ln(new Ue.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!a||!e.threeDSecureToken)throw Zo(new Ue.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=(0,Ue.isSetupIntentClientSecret)(e.threeDSecureToken),R=null,C=e.paymentMethodId,k=await Ur(()=>Ts(M,e.threeDSecureToken,g),"card");if(k){if(k.error)throw Ln(new Ue.FloPayError(k.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:k.error.code}),"card");let h=k.intent;!C&&h?.payment_method&&(typeof h.payment_method=="string"?C=h.payment_method:"id"in h.payment_method&&(C=h.payment_method.id??void 0))}let p=C?await Ur(()=>Ms(M,e.threeDSecureToken,{payment_method:C,return_url:d??Qo(u)??window.location.href},g),"card"):null;if(p){if(p.error)throw Ln(new Ue.FloPayError(p.error.message??"3DS authentication failed.","api_error",{code:p.error.code}),"card");R=p.intent}else{let h=await Ur(()=>M.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(h.error)throw Ln(new Ue.FloPayError(h.error.message??"3DS authentication failed.","api_error",{code:h.error.code}),"card");R=(g?h.setupIntent:h.paymentIntent)??null}if(R&&(R.status==="requires_capture"||R.status==="succeeded"||R.status==="processing")){let h=await Cr({billingApiUrl:r,sessionId:i,session:u,telemetry:b,tokenizedData:{id:R.id,type:"card",threeDSecureActionResultTokenId:R.id},returnUrl:d});return h.type==="success"?{...h.result,paymentIntentId:h.result.paymentIntentId??R.id,paymentMethodId:h.result.paymentMethodId??C}:bo(h,{flopay:t,paypalFlopay:n,attempt3DS:a,billingApiUrl:r,sessionId:i,session:u,returnUrl:d,telemetry:b})}throw Ln(new Ue.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw Ln(new Ue.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:C}=await Ur(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(C)throw Ln(new Ue.FloPayError(C.message??"PayPal authorization failed.","api_error",{code:C.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:R}=await Ur(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Qo(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(R)throw Ln(new Ue.FloPayError(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ue.FloPayError("Unsupported payment redirect state.","api_error")}function nr(e){if(e instanceof Ue.FloPayError){let a=qn(e.message);return a&&a!==e.message?Object.assign(new Ue.FloPayError(a,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=qn(t)??t;return new Ue.FloPayError(n,"api_error")}function vo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ue.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 Co({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:a,telemetry:r}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[u,d]=await Promise.all([(0,vr.loadFloPay)(e,{billingApiUrl:n,locale:a,telemetry:r}),i?(0,vr.loadFloPay)(t,{billingApiUrl:n,locale:a,telemetry:r}).catch(b=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",b),null)):Promise.resolve(null)]);return{flopay:u,paypalFlopay:t?i?d:u:null}}var w=require("react/jsx-runtime"),Sr=44,ia="flopay_checkout_saved_payment_resume",ko=new Map,So=new Map;function hi(e,t){t.settled&&t.consumers===0&&ko.get(e)===t&&ko.delete(e)}function Ls(e,t,n){let a=So.get(e);if(a&&(!a.sdkGeneratedIdempotencyKey||!t||a.sdkGeneratedIdempotencyKey===t))return a.attempt;let r=n(),i={attempt:r,sdkGeneratedIdempotencyKey:t};So.set(e,i);let u=()=>{So.get(e)===i&&So.delete(e)};return r.then(u,u),r}function jr(e){return new Promise(t=>setTimeout(t,e))}function wo(e,t,n){let a=ro({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:_e.SDK_VERSION,enabled:t!==!1});return a.beginCheckout(n),a}function Vr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ea(e,t,n,a,r){let i=wo(e,t,n);i.error({errorCode:a,stage:r,paymentMethodCategory:"unknown",...r==="session_read"?{requestCategory:"session_read"}:{}}),Vr(i)}function Os(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function oa(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function ta(e){return!e||e.data.stripe?.publishableKey?!1:!!oa(e)?.clientId}function On(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function zs(){if(!On())return null;try{let e=window.sessionStorage.getItem(ia);return e?JSON.parse(e):null}catch{return null}}function Pi(e){if(On())try{window.sessionStorage.setItem(ia,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function na(){if(On())try{window.sessionStorage.removeItem(ia)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var sa=":idempotency-key";function Ns(e){if(!On())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function bi(e,t,n){if(On())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(a){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",a)}}function aa(e){if(On())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function Us(e){if(On())try{return window.sessionStorage.getItem(e+sa)??void 0}catch{return}}function $s(e,t){if(On())try{window.sessionStorage.setItem(e+sa,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function js(e){if(aa(e),!!On())try{window.sessionStorage.removeItem(e+sa)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Vs(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let a of t)e.searchParams.has(a)&&(e.searchParams.delete(a),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function vi(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function qs(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function ra(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Ro({sessionId:e,nonce:t,createSession:n,billingApiUrl:a,telemetry:r,appearance:i,locale:u,loading:d,error:b,onComplete:M,onError:g,onDecline:R,onCountryChange:C,onZipChange:k,showPayPal:p=!0,showStripe:h=!0,enabledPaymentMethods:E,showApplePay:_=!0,showGooglePay:f=!0,debug:ge=!1,layout:x,theme:oe,buttonsTheme:ae,buttonsStyles:j,cardButtonContent:K,cardBackButtonContent:ce,cardTitleContent:pe,showSecurityFooter:De,onButtonClick:P,onBeforeButtonClick:ie,enableAVS:Le,cardFieldOrder:we,cardPreFormSlot:he,avsLayout:Z,className:me,initialErrorMessage:J=null,children:ne,checkoutMode:ke,confirmLabel:xe,renderConfirmButton:se,onSessionCompleted:W}){let S=(0,_e.resolveBillingApiUrl)(a),de=(0,B.useMemo)(()=>(0,_e.resolveTheme)(oe),[oe]),Qe=i??de?.appearance,Ve=n?"embedded_checkout":"standard_checkout",ue=ne?"custom_layout":x==="buttons"?"buttons_layout":"default_layout",[L,Pe]=(0,B.useState)(null),[X,be]=(0,B.useState)(null),rt=(0,B.useRef)(null),[qe,ct]=(0,B.useState)(null),ve=(0,B.useRef)(null),[re,ot]=(0,B.useState)(null),[ee,yt]=(0,B.useState)(e??""),He=e??ee,Ke=n?"":He,[Nt,at]=(0,B.useState)(!0),[nn,T]=(0,B.useState)(null),[Ce,et]=(0,B.useState)("full"),[tt,It]=(0,B.useState)(!1),[ft,Oe]=(0,B.useState)(J),[gt,Fe]=(0,B.useState)(null),[rn,Ye]=(0,B.useState)(null),[zn,Wt]=(0,B.useState)(!1),[wn,Nn]=(0,B.useState)(void 0),[Un,Ut]=(0,B.useState)(""),[pt,dn]=(0,B.useState)(!1),[$t,jt]=(0,B.useState)(!1),Vt=(0,B.useRef)(0),[Mt,le]=(0,B.useState)("loading"),[$n,on]=(0,B.useState)(0),Gt=(0,B.useRef)(!1),Yn=(0,B.useRef)(!1),U=(0,B.useRef)(!1),it=(0,B.useRef)(null),Ge=(0,B.useMemo)(()=>({checkoutMode:ke??Ce,layout:ne?"unknown":x==="buttons"?"buttons":"embedded"}),[ke,ne,Ce,x]),We=(0,B.useRef)(M);We.current=M;let Je=(0,B.useRef)(g);Je.current=g;let An=(0,B.useRef)(R);An.current=R,(0,B.useEffect)(()=>{Tt(X)?.setCheckoutContext(Ge),qe&&qe!==X&&Tt(qe)?.setCheckoutContext(Ge)},[X,qe,Ge]);let jn=(0,B.useRef)(W);jn.current=W;let ar=(0,B.useCallback)(A=>{le(A),!(A!=="exhausted"||U.current)&&(U.current=!0,Je.current?.(new _e.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),kn=(0,B.useCallback)(()=>{le("retrying"),on(A=>A+1)},[]);(0,B.useEffect)(()=>{le("loading"),on(0),U.current=!1},[He]),(0,B.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:_e.SDK_VERSION,checkout_type:Ve,checkout_layout:ue,billing_api_url:S})},[ue,Ve,S]);let st=(0,B.useMemo)(()=>n?Xt(n,!0):"",[n]),qt=(0,B.useMemo)(()=>Un===st?wn:void 0,[wn,Un,st]),Rn=(0,B.useMemo)(()=>n?Vo(n,qt):void 0,[n,qt]),St=ke??Rn?.checkoutMode??"full",Ft=(0,B.useMemo)(()=>Rn?{...Rn,checkoutMode:St}:void 0,[Rn,St]);(0,B.useEffect)(()=>{Nn(void 0),Ut(st)},[st]),(0,B.useEffect)(()=>{Oe(J)},[J]);let un=(0,B.useCallback)((A,$,V)=>{Xe(()=>{An.current?.(Et(A,$,V))})},[Xe]),an=(0,B.useCallback)(async(A,$)=>{Oe(null),Ye(null),Wt(!1),Fe("processing");let V=$?.sessionId??A.id,Ee=rt.current??ve.current,Me=Tt(Ee),te=Ee?null:wo(S,r,Ge),y={log:O=>{Me?Me.log(O):te?.log(O)},error:O=>{Me?Me.error(O):te?.error(O)},terminal:O=>{Me?Me.terminal(O):te?.terminal(O)},performance:O=>{Me?Me.performance(O):te?.performance(O)},now:()=>Me?.now()??te?.now()??0,elapsed:O=>Me?.elapsed(O)??Math.max(0,(te?.now()??O)-O)},q=y.now(),m=!!($?.initialAutoProcessingError||$?.initialAutoProcessingPending),l=!1,F,Re=()=>{l||(l=!0,m=!0,F=y.now(),y.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),y.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Te=!1,Q=()=>{Te||(Te=!0,y.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),y.performance({stage:"processing",durationMs:y.elapsed(q),durationMode:"machine",paymentMethodCategory:"saved"}),F!==void 0&&y.performance({stage:"recovery",durationMs:y.elapsed(F),durationMode:"machine",paymentMethodCategory:"saved"}))};y.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),y.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),m&&Re();let Ze;try{let O=yi($?.initialAutoProcessingError),H;if(O)Re(),O.type==="paypal_redirect_required"&&it.current?.publishableKey&&Pi({sessionId:V,publishableKey:it.current.publishableKey,paypalPublishableKey:it.current.paypalPublishableKey}),H=await bo(O,{flopay:rt.current,paypalFlopay:ve.current,attempt3DS:$?.attempt3DS,billingApiUrl:S,sessionId:V,session:A,telemetry:!1}),O.type==="paypal_redirect_required"&&na();else if($?.initialAutoProcessingPending){let ye=(await new rr.PaymentAPI(S,{telemetry:!1}).waitForCheckoutSessionCompletion($.initialAutoProcessingPending.sessionId,{initialDelayMs:$.initialAutoProcessingPending.retryAfterMs})).data.session;if(!hr(ye))throw co(ye);H=er(ye,V)}else{if($?.initialAutoProcessingError)throw Kn($.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:$.initialAutoProcessingError.checkoutMethod});if($?.fromCreateSession)return $?.fallbackToFull&&(et("full"),vi("full")),!1;{let I=await Cr({billingApiUrl:S,sessionId:V,session:A,telemetry:!1});I.type==="success"?H=I.result:(Re(),I.type==="paypal_redirect_required"&&it.current?.publishableKey&&Pi({sessionId:V,publishableKey:it.current.publishableKey,paypalPublishableKey:it.current.paypalPublishableKey}),H=await bo(I,{flopay:rt.current,paypalFlopay:ve.current,attempt3DS:$?.attempt3DS,billingApiUrl:S,sessionId:V,session:A,telemetry:!1}),I.type==="paypal_redirect_required"&&na())}}V&&Pr(V),Q(),m&&(y.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),y.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),y.terminal({outcome:H.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Wt(H.status==="authorized"),Fe("success"),await jr(hn),Ze=()=>We.current?.(H)}catch(O){let H=nr(O),I=H.checkoutMethod??$r;Oe(H.message),Ye(H.message),Wt(!1),$?.fallbackToFull&&(y.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),et("full"),vi("full")),Q();let z=H.statusCode!==void 0?(0,_e.telemetryStatusClass)(H.statusCode,"unknown"):void 0,ye=z==="4xx"?{requestCategory:"process_payment",statusClass:z}:{},Ct=z===void 0||z==="4xx";if(Ct&&(H.telemetryOutcome==="payment_declined"||!!(H.declineCode||H.code?.toLowerCase().includes("declin"))))y.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...ye});else if(Ct&&(H.telemetryOutcome==="validation_rejected"||H.type==="validation_error"))y.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...ye});else{let Hr=(0,_e.classifyTelemetryFailure)(O,m?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");y.error({...Hr,...H.telemetryFailureCategory?{failureCategory:H.telemetryFailureCategory}:{},stage:m?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:H.telemetryRequestCategory??"process_payment"})}return Xe(()=>Je.current?.(H)),un(I,H,{code:H.code,declineCode:H.declineCode}),Fe("error"),await Promise.allSettled([jr(Qt),$?.ensureProvidersReady?$.ensureProvidersReady():Promise.resolve()]),m&&(y.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),y.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Q(),te&&Vr(te),Fe(null),Ye(null)}return Xe(Ze),!0},[un,Xe,nr,S,r,Ge]);(0,B.useEffect)(()=>{if(typeof window>"u"||Yn.current)return;let A=new URLSearchParams(window.location.search),$=A.get("payment_intent_client_secret");if(!$)return;let V=zs();V&&(Yn.current=!0,(async()=>{let Ee,Me=0;Oe(null),Ye(null),Fe("processing"),It(!0);try{if(A.get("redirect_status")==="failed")throw Object.assign(new _e.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:te,paypalFlopay:y}=await Co({publishableKey:V.publishableKey,paypalPublishableKey:V.paypalPublishableKey,billingApiUrl:S,locale:u,telemetry:r});Ee=Tt(y??te),Me=Ee?.now()??0,Ee?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Ee?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let q=(y??te)?.getRawProvider();if(!q)throw Object.assign(new _e.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:m,error:l}=await q.retrievePaymentIntent($);if(l)throw Object.assign(new _e.FloPayError(l.message??"Failed to retrieve PayPal payment status.","api_error",{code:l.code}),{checkoutMethod:"paypal"});let F=Ya(m?.status);if(!m||F==="failed")throw Object.assign(new _e.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Re=typeof m.payment_method=="string"?m.payment_method:m.payment_method?.id,Te=F;if(V.sessionId){let O=(await new rr.PaymentAPI(S,{telemetry:!1}).getUnifiedCheckoutSession(V.sessionId)).data.session;if(O&&O.status!=="complete"){let H=await Cr({billingApiUrl:S,sessionId:V.sessionId,session:O,telemetry:!1,tokenizedData:{id:Re??m.id,type:"card",threeDSecureActionResultTokenId:m.id,isPaypal:!0}});if(H.type!=="success")throw Object.assign(new _e.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Te=H.result.status}}V.sessionId&&Pr(V.sessionId),Ee?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Ee?.performance({stage:"redirect_resume",durationMs:Ee.elapsed(Me),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Ee?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Fe("success"),await jr(hn),Xe(()=>We.current?.({status:Te,paymentIntentId:m.id,paymentMethodId:Re,checkoutMethod:"paypal"}))}catch(te){let y=nr(te),q=y.checkoutMethod??"paypal",m=!!(y.declineCode||y.code?.toLowerCase().includes("declin"));if(Ee)Ee.performance({stage:"redirect_resume",durationMs:Ee.elapsed(Me),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),m?Ee.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Ee.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(m){let l=wo(S,r,Ge);l.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Vr(l)}else ea(S,r,Ge,"REDIRECT_RESUME_FAILED","redirect_resume");Oe(y.message),Ye(y.message),Xe(()=>Je.current?.(y)),un(q,y,{code:y.code,declineCode:y.declineCode}),Fe("error"),await jr(Qt)}finally{na(),Vs(),Fe(null),Ye(null),It(!1)}})())},[un,Xe,u,nr,S,r]);let Jt=(0,B.useRef)(null);function Xt(A,$=!1){let V=A?.account?.email?.trim().toLowerCase()??"",Ee={c:A?.clientId,cur:A?.currency??"",captureMethod:A?.captureMethod??"",a:{e:V,u:V?"":A?.account?.userId??"",country:A?.account?.country??""},successUrl:A?.successUrl,cancelUrl:A?.cancelUrl,p:A?.products?.map(y=>ra(`${y.type??""}:${y.code??y.providerItemId??y.providerPlanId??""}`,y)).sort(),i:A?.items?.map(y=>ra(y.code??y.providerItemId??"",y)).sort(),s:A?.subscriptions?.map(y=>ra(y.code??y.providerPlanId??"",y)).sort(),couponCodes:A?.couponCodes?[...A.couponCodes].sort():void 0,...$?{tagsData:A?.tagsData,utmMetadata:A?.utmMetadata,tokenizedData:A?.tokenizedData,checkoutMode:A?.checkoutMode??"full"}:{}},Me=JSON.stringify(Ee),te=0;for(let y=0;y<Me.length;y++)te=(te<<5)-te+Me.charCodeAt(y)|0;return`flopay_session_${Math.abs(te).toString(36)}`}let At=(0,B.useMemo)(()=>Ft?Xt(Ft):"",[Ft]),Ae=(0,B.useRef)(Ft);Ae.current=Ft,(0,B.useEffect)(()=>{yt(e??"")},[e]),(0,B.useEffect)(()=>{Gt.current=!1,Oe(J),Ye(null),Wt(!1),Fe(null)},[At,J,e]);async function wt(A,$){let V=wo(S,r,Ge),Ee=new rr.PaymentAPI(S,{telemetry:!1}),Me=!1;try{let te=A.idempotencyKey!==void 0?(0,_e.resolveIdempotencyKey)(A.idempotencyKey):void 0,y=te??Us($),q,m=!1,l=Ns($);V.log({name:l?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let F=l?.sid??null,Re=null,Te;if(F)try{if(Re=await Ee.getUnifiedCheckoutSession(F,l?.nonce),Re.data.session?.status==="complete"){if(Ho(F))return{sid:F,result:Re};js($),F=null,Re=null,m=!0}}catch{V.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),aa($),F=null}if(!F){!te&&(m||!y)&&(y=(0,_e.resolveIdempotencyKey)(),q=y),y&&$s($,y);let Q=V.now(),Ze=0;V.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let O={...A,idempotencyKey:y,avsCheck:!!Le,avsConfig:typeof Le=="object"?Le:void 0,checkoutType:"embedded_checkout",checkoutLayout:ne?"custom_layout":x==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(O,rr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:z=>{Ze=Math.max(Ze,z)}}});let H=()=>{V.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),V.performance({stage:"session_create",durationMs:V.now()-Q,durationMode:"machine",requestCategory:"session_create",attempt:Ze,statusClass:"2xx"})},I=z=>{let ye=(0,_e.classifyTelemetryFailure)(z,"CHECKOUT_SESSION_CREATE_FAILED","unknown");V.performance({stage:"session_create",durationMs:V.now()-Q,durationMode:"machine",requestCategory:"session_create",attempt:Ze,statusClass:ye.statusClass}),z instanceof _e.FloPayError&&z.type==="validation_error"?V.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):ye.statusClass==="4xx"?V.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):V.error({...ye,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if((0,_e.isDetachedSessionEligible)(O)){let z=await Ee.createDetachedSession(O);z.claimed.catch(()=>{}),Re=z.shell,F=z.sessionId,Te=z.claimed.then(ye=>{let Ct=ye.data.session?.id??z.sessionId;return Ct&&bi($,Ct,ye.data.session?.clientSecret??z.nonce),H(),ye},ye=>{throw aa($),I(ye),ye}).finally(()=>Vr(V)),Te.catch(()=>{}),Me=!0,V.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),V.performance({stage:"session_shell",durationMs:V.now()-Q,durationMode:"machine",requestCategory:"session_create",attempt:Ze,statusClass:"2xx",paymentMethodCategory:"card"})}else Re=await Ee.createAndFetchSession(O),H()}catch(z){throw I(z),z}F=Re.data.session?.id??F??"",F&&!Te&&bi($,F,Re.data.session?.clientSecret)}return{sid:F??"",result:Re,sdkGeneratedIdempotencyKey:q,...Te?{claimed:Te}:{}}}finally{Me||Vr(V)}}let ht=(0,B.useCallback)(async(A,$)=>{let V=Ae.current;if(!V)throw new _e.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Ee=Vo(V,A),Me=Xt(Ee),te=ko.get(Me);if(!te){let m={promise:wt(Ee,Me),consumers:0,settled:!1};te=m,ko.set(Me,m);let l=()=>{m.settled=!0,hi(Me,m)};m.promise.then(l,l)}te.consumers+=1;let y=!1,q=()=>{y||(y=!0,te.consumers-=1,hi(Me,te))};$?.(q);try{let m=await te.promise;Jt.current=Me,A&&(Ut(st),Nn(H=>qa(H,A)));let{sid:l,result:F,claimed:Re}=m;if(Pe(F),F.data.session&&ot(F.data.session),l&&yt(l),Re){let H=Vt.current+=1;jt(!0),Re.then(I=>{Vt.current===H&&(Pe(I),I.data.session&&ot(I.data.session),jt(!1))},I=>{Vt.current===H&&(jt(!1),T(I instanceof _e.FloPayError?I:new _e.FloPayError(I instanceof Error?I.message:"Failed to create session","api_error")))})}else Vt.current+=1,jt(!1);let{publishableKey:Te,paypalPublishableKey:Q}=vo(F),{flopay:Ze,paypalFlopay:O}=await Co({publishableKey:Te,paypalPublishableKey:Q,billingApiUrl:S,locale:u,telemetry:r});return rt.current=Ze,be(Ze),ve.current=O,ct(O),at(!1),m}catch(m){throw Jt.current===Me&&(Jt.current=null),m}finally{$||q()}},[u,S,r,Ge]),En=(0,B.useRef)(an);En.current=an;let ir=(0,B.useRef)(ht);ir.current=ht;let Dt=(0,B.useCallback)(async A=>{if(!qs(A)||pt)return{sessionId:ee,session:re};dn(!0);try{let $=await ht(A);return{sessionId:$.sid,session:$.result.data.session??null}}finally{dn(!1)}},[ht,pt,ee,re]);(0,B.useEffect)(()=>{let A=!1,$;if(T(null),At){let Me=Ae.current;return et(St),at(!1),Jt.current===At?()=>{A=!0}:(ot(Ha(Me,ke)),(async()=>{let te=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),y=St==="auto"&&!Gt.current&&!te;y&&(Oe(null),Ye(null),Fe("processing"));try{let q=await ir.current(void 0,Re=>{$=Re}),m=q.result.data.session??null;it.current=vo(q.result);let l=ta(q.result),F=Ho(q.sid||m?.id);if(!A&&y&&m&&!l&&!F){Gt.current=!0,await Ls(At,q.sdkGeneratedIdempotencyKey,()=>En.current(m,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:q.result.autoProcessingError,initialAutoProcessingPending:q.result.autoProcessingPending,autoProcessingAttempted:q.result.autoProcessingAttempted,sessionId:q.sid||m.id}));return}!A&&y&&((l||F)&&(Gt.current=!0),Fe(null),Ye(null))}catch(q){if(A)return;let m=q instanceof _e.FloPayError||typeof q=="object"&&q!==null&&"code"in q?q.code:void 0;if(y&&m==="session_auto_completed"){Gt.current=!0,Fe("success"),await jr(hn),A||(Xe(()=>{We.current?.({status:"succeeded"})}),Fe(null),Ye(null));return}y&&(Fe(null),Ye(null));let l=q instanceof _e.FloPayError?q:new _e.FloPayError(q instanceof Error?q.message:"Failed to create session","api_error");T(l)}finally{$?.(),$=void 0}})(),()=>{A=!0,$?.()})}at(!0);async function V(){let Me=!1;try{let y=await new rr.PaymentAPI(S,{telemetry:!1}).getUnifiedCheckoutSession(He,t);if(A)return;Pe(y);let q=y.data.session??null;if(ot(q),!q)throw new _e.FloPayError("No session data returned","api_error");let m=q.checkoutMode;if(m==="setup")throw new _e.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(q.status==="authorized"){at(!1),Xe(()=>{We.current?.(er(q,He)),jn.current?.(q.successUrl??"")});return}if(q.status==="complete"){at(!1),Xe(()=>{jn.current?.(q.successUrl??"")});return}if(q.status==="expired")throw lo(q);Me=!0;let l=ke??m??"full";et(l);let F=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Re=ta(y);if(l==="auto"&&!Gt.current&&!F&&!Re){Gt.current=!0;let Te=Ee(y);try{if(await En.current(q,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Te,sessionId:He||q.id}),A)return;await Te,A||at(!1);return}catch{if(A)return;await Te,A||at(!1);return}}await Ee(y),A||at(!1)}catch(te){if(A)return;te instanceof _e.FloPayError?!Me&&!Os(te)&&ea(S,r,Ge,"NETWORK_REQUEST_FAILED","session_read"):ea(S,r,Ge,"INTERNAL_SDK_ERROR","checkout_mount");let y=te instanceof _e.FloPayError?te:new _e.FloPayError(te instanceof Error?te.message:"Failed to initialize checkout","api_error");T(y),at(!1)}}async function Ee(Me){let{publishableKey:te,paypalPublishableKey:y}=vo(Me);it.current={publishableKey:te,paypalPublishableKey:y};let{flopay:q,paypalFlopay:m}=await Co({publishableKey:te,paypalPublishableKey:y,billingApiUrl:S,locale:u,telemetry:r});rt.current=q,be(q),ve.current=m,ct(m)}return V(),()=>{A=!0}},[ke,At,St,Ke,Xe,t]);let sn=(0,B.useCallback)(async()=>{if(!(tt||!re)){It(!0),Oe(null);try{await an(re,{attempt3DS:!0,fallbackToFull:!0,sessionId:He||re.id})}finally{It(!1)}}},[He,tt,an,re]),Bt=oa(L),Wn=ta(L),pn=(0,B.useMemo)(()=>{if(!L||!re||!L.data.stripe?.publishableKey)return;let A={appearance:Qe,paymentMethodCreation:"manual",billingApiUrl:S};if(L.data.stripe?.clientSecret)A.clientSecret=L.data.stripe.clientSecret;else{let $=(0,_e.buildCheckoutDisplayData)(re).total;A.amount=Math.round($*100)||re.amount,A.currency=re.currency?.toLowerCase()}return A},[L,re,Qe,S]),Vn=!!(n&&!ne&&x==="buttons"&&ie&&St==="full"),Lt=(0,B.useMemo)(()=>({session:re,loading:Nt,error:nn,checkoutMode:Ce,inlineSessionDraft:Ft,applyInlineSessionPatch:Vn?Dt:void 0,inlineSessionPatchProcessing:pt,claimPending:$t}),[re,Nt,nn,Ce,Ft,Vn,Dt,pt,$t]),In=!!n&&x==="buttons"&&!Wn&&(!X||!pn),ze=gt?(0,w.jsx)(cn,{status:gt,errorMessage:rn,authorized:zn}):null;if(Nt){if(d)return(0,w.jsxs)(w.Fragment,{children:[d,ze]});if(x==="buttons"){let A=de?.buttonsLayout?.cardButton?.borderRadius??de?.appearance.variables?.borderRadius??8,$=V=>(0,w.jsx)("div",{style:{height:V,borderRadius:A,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&&$(Sr),h&&(_||f)&&$(Sr),h&&$(Sr),(0,w.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),ze]})}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); } }"})]}),ze]})}return nn?b?(0,w.jsx)(fn.Provider,{value:Lt,children:b(nn)}):(0,w.jsx)(fn.Provider,{value:Lt,children:(0,w.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:nn.message})}):In?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(fn.Provider,{value:Lt,children:(0,w.jsx)(Ks,{onButtonClick:P,showPayPal:p,showStripe:h,showApplePay:_,showGooglePay:f,theme:oe,buttonsTheme:ae,buttonsStyles:j,cardButtonContent:K,cardBackButtonContent:ce,cardTitleContent:pe})}),ze]}):Wn&&re&&Bt?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(fn.Provider,{value:Lt,children:(0,w.jsxs)("div",{className:me,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ft&&(0,w.jsx)(yr,{icon:!1,children:ft}),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:kn,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)(ei,{sessionId:He,nonce:re.clientSecret||void 0,billingApiUrl:S,email:re.customer?.email,clientId:Bt.clientId,environment:Bt.environment,currency:(re.currency??"usd").toUpperCase(),isSubscription:re.mode==="subscription",providerObjectType:Bt.providerObjectType,onComplete:M,onErrorChange:Oe,onDecline:R,onButtonClick:P,onInitializationStateChange:ar,allowAutomaticRetry:$n===0,session:re,telemetry:r,telemetryContext:Ge,debug:ge},`paypal-init-${$n}`)})]})}),ze]}):!X||!pn?(0,w.jsx)(w.Fragment,{children:ze}):Ce==="confirm"?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(fn.Provider,{value:Lt,children:(0,w.jsx)(Br,{flopay:X,paypalFlopay:qe,options:pn,children:(0,w.jsxs)("div",{className:me,children:[ft&&(0,w.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:ft}),se?se({onConfirm:sn,isProcessing:tt}):(0,w.jsx)("button",{type:"button",onClick:sn,disabled:tt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:tt?"not-allowed":"pointer",opacity:tt?.6:1},children:tt?"Processing...":xe??"Confirm Purchase"})]})})}),ze]}):(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(fn.Provider,{value:Lt,children:(0,w.jsx)(Br,{flopay:X,paypalFlopay:qe,options:pn,children:ne?(0,w.jsxs)(w.Fragment,{children:[ft&&(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:ft}),(0,w.jsx)(Hs,{sessionId:He,nonce:re?.clientSecret||void 0,billingApiUrl:S,session:re,children:ne})]}):(0,w.jsx)(ho,{sessionId:He,nonce:re?.clientSecret||void 0,email:re?.customer?.email,userId:re?.customer?.id,firstName:re?.customer?.firstName,lastName:re?.customer?.lastName,totalAmount:re?Math.round((0,_e.buildCheckoutDisplayData)(re).total*100):0,currency:re?.currency?.toLowerCase()??"usd",onComplete:M,onError:g,onDecline:R,error:ft,onErrorChange:Oe,showPayPal:p,showStripe:h,enabledPaymentMethods:E??L?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:L?.data.stripe?.enabledPaymentMethodCountries,showApplePay:_,showGooglePay:f,layout:x,theme:oe,buttonsTheme:ae,buttonsStyles:j,appearance:Qe,cardButtonContent:K,cardBackButtonContent:ce,cardTitleContent:pe,onButtonClick:P,onBeforeButtonClick:ie,enableAVS:Le,...we?{cardFieldOrder:we}:{},...he?{cardPreFormSlot:he}:{},avsLayout:Z,country:re?.customer?.country,city:re?.customer?.city,state:re?.customer?.state,onCountryChange:C,onZipChange:k,avsCheck:!!Le,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ne?"custom_layout":x==="buttons"?"buttons_layout":"default_layout",className:me,directPaypal:oa(L),isSubscription:re?.mode==="subscription",session:re,dataAttachmentPending:$t,debug:ge})})}),ze]})}function Hs({sessionId:e,nonce:t,billingApiUrl:n,session:a,children:r}){return(0,w.jsx)(w.Fragment,{children:B.default.Children.map(r,i=>{if(!B.default.isValidElement(i))return i;let u=i.props,d={};return u.sessionId||(d.sessionId=e),!u.nonce&&t&&(d.nonce=t),u.billingApiUrl||(d.billingApiUrl=n),a?.customer&&(u.email||(d.email=a.customer.email),u.userId||(d.userId=a.customer.id),u.firstName||(d.firstName=a.customer.firstName),u.lastName||(d.lastName=a.customer.lastName)),Object.keys(d).length===0?i:B.default.cloneElement(i,d)})})}function Ks({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:a,showGooglePay:r,theme:i,buttonsTheme:u,buttonsStyles:d,cardButtonContent:b,cardBackButtonContent:M,cardTitleContent:g}){let[R,C]=(0,B.useState)(!1),k=(0,B.useMemo)(()=>(0,_e.resolveTheme)(i),[i]),p=(0,B.useMemo)(()=>{let f=k?.buttonsLayout??(0,_e.resolveButtonsLayoutTheme)(u);return d?{...f,...d,cardButton:{...f.cardButton,...d.cardButton},cardFormContainer:{...f.cardFormContainer,...d.cardFormContainer},backButton:{...f.backButton,...d.backButton},backButtonIcon:{...f.backButtonIcon,...d.backButtonIcon},submitButton:{...f.submitButton,...d.submitButton},title:{...f.title,...d.title}}:f},[k,u,d]),h=k?.buttonsLayout?.cardButton?.borderRadius??k?.appearance.variables?.borderRadius??8,E=f=>(0,w.jsx)("div",{style:{height:f,borderRadius:h,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),_=b===void 0?{boxSizing:"border-box",height:Sr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(R){let f=p.cardInputBorder??"#e5e7eb",ge=p.cardInputBackground??"white",x=cr(M),oe=cr(g);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:()=>C(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:x?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)(ur,{content:M})]}),oe?(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)(Fr,{content:g})})]}),(0,w.jsx)("div",{style:{backgroundColor:ge,border:`1px solid ${f}`,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:ge,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,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:ge,borderTop:"none",borderRight:`1px solid ${f}`,borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,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:ge,border:`1px solid ${f}`,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:`
|
|
38
|
+
`}),Mr&&un&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ke?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:On,style:{display:"inline-flex",alignItems:"center",gap:Vo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(yr,{content:Se})]}),Oa?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...p.title},children:(0,l.jsx)(Nr,{content:K})})]}),!Mr&&!Oa&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ko,order:ke?-3:0,...p.title},children:(0,l.jsx)(Nr,{content:K})}),ue&&(0,l.jsx)("div",{style:{order:ke?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Ne,L=(V=!1)=>({backgroundColor:Fr,border:`1px solid ${nr(V)}`,borderRadius:kt,marginTop:"0.5rem",padding:"10px"}),W=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...$a}),de=(0,f.getStateOptions)(s);return(0,l.jsxs)(l.Fragment,{children:[(0,f.isAVSFieldVisible)(ue.address_line_1,s)&&(0,l.jsx)("div",{style:L(it.line1),children:(0,l.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:Ct,onChange:V=>{Ot.current.addressLine1=!0,Je.current=V.target.value,et(V.target.value)},disabled:k,required:!0,"data-testid":"flopay-address-line1",style:W()})}),(0,f.isAVSFieldVisible)(ue.address_line_2,s)&&(0,l.jsx)("div",{style:L(),children:(0,l.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:Mt,onChange:V=>{Ot.current.addressLine2=!0,_n.current=V.target.value,Ge(V.target.value)},disabled:k,"data-testid":"flopay-address-line2",style:W()})}),((0,f.isAVSFieldVisible)(ue.city,s)||(0,f.isAVSFieldVisible)(ue.state,s))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,f.isAVSFieldVisible)(ue.city,s)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Fr,borderTop:`1px solid ${nr(it.city)}`,borderRight:`1px solid ${nr(it.city)}`,borderBottom:`1px solid ${nr(it.city)}`,borderLeft:`1px solid ${nr(it.city)}`,padding:"10px",borderTopLeftRadius:kt,borderBottomLeftRadius:kt,...(0,f.isAVSFieldVisible)(ue.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:kt}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:jt,onChange:V=>{Ot.current.city=!0,dt.current=V.target.value,Rt(V.target.value)},disabled:k,required:!0,"data-testid":"flopay-city",style:W()})}),(0,f.isAVSFieldVisible)(ue.state,s)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Fr,border:`1px solid ${nr(it.state)}`,padding:"10px",borderTopRightRadius:kt,borderBottomRightRadius:kt,...(0,f.isAVSFieldVisible)(ue.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:kt}},children:de?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:en,onChange:V=>{Ot.current.state=!0,bn.current=V.target.value,Dt(V.target.value)},disabled:k,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...W(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,f.getStateLabel)(s)}),de.map(V=>(0,l.jsx)("option",{value:V.code,children:V.name},V.code))]}):(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,f.getStateLabel)(s),autoComplete:"billing address-level1",value:en,onChange:V=>{Ot.current.state=!0,bn.current=V.target.value,Dt(V.target.value)},disabled:k,required:!0,"data-testid":"flopay-state",style:W()})})]}),((0,f.isAVSFieldVisible)(ue.country,s)||(0,f.isAVSFieldVisible)(ue.postal_code,s))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:te==="column"?"column":"row",gap:te==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,f.isAVSFieldVisible)(ue.country,s)&&(0,l.jsx)("div",{style:{flex:te==="row"?1:void 0,backgroundColor:Fr,borderTop:`1px solid ${Br}`,borderRight:`1px solid ${Br}`,borderBottom:`1px solid ${Br}`,borderLeft:`1px solid ${Br}`,padding:"10px",...te==="row"&&(0,f.isAVSFieldVisible)(ue.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:kt,borderBottomLeftRadius:kt,borderRight:"none"}:{borderRadius:kt}},children:(0,l.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Ne,onChange:V=>{Ot.current.country=!0,Lt.current=V.target.value,qt(V.target.value),me?.(V.target.value),bn.current="",Dt("")},disabled:k,autoComplete:"billing country","data-testid":"flopay-country",style:{...W(),cursor:"pointer"},children:f.COUNTRY_OPTIONS.map(V=>(0,l.jsxs)("option",{value:V.code,children:[V.flag," ",V.name]},V.code))})}),(0,f.isAVSFieldVisible)(ue.postal_code,s)&&(0,l.jsx)("div",{style:{flex:te==="row"?1:void 0,backgroundColor:Fr,border:`1px solid ${Xi}`,padding:"10px",...te==="row"&&(0,f.isAVSFieldVisible)(ue.country,s)?{borderRadius:"0",borderTopRightRadius:kt,borderBottomRightRadius:kt}:{borderRadius:kt}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,f.getPostalCodeLabel)(Ne),autoComplete:"billing postal-code",value:Gt,onChange:V=>{Ot.current.zip=!0,at.current=V.target.value,Ze(V.target.value),We?.(V.target.value)},onBlur:()=>Sn(!0),disabled:k,required:Jt.required,"aria-invalid":ao||void 0,"aria-describedby":ao?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:W()})})]}),ao&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:qo,...$a,fontSize:"0.75rem"},children:Jt.empty?`${(0,f.getPostalCodeLabel)(s)} is required`:Us(s)})]})})()}),ke&&$&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:$}),ke&&ns,u&&(0,l.jsx)(Pr,{margin:"0.75rem 0",styleOverride:p.errorBanner,children:u})]}),io={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},ja=s=>j?!Q||!rn?(0,l.jsx)("pre",{"data-testid":s,style:io,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":s,style:io,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${Q}`,` directPaypalConfigured=${rn}`,` inAppBrowserDetected=${String(ro)}`,` shouldRenderDirectPayPal=${_r}`,` shouldRenderStripePayPal=${Tr}`,` hasPaypalStripeInstance=${!!le}`].join(`
|
|
39
|
+
`)}):null,Va=s=>j?!J||!M?(0,l.jsx)("pre",{"data-testid":s,style:io,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":s,style:io,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${J}`,` currency=${G}`,` amountInCents=${ye}`,` enabledPaymentMethods: ${JSON.stringify(w??[])}`,` enabledPaymentMethodsProvided=${Er}`,` hasEnabledMethods=${Qr}`,` expressMethods: ${JSON.stringify(eo)}`,` walletExpressMethods: ${JSON.stringify(to)}`,` paymentElementMethods: ${JSON.stringify(Rr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(no)}`,` hasStripeInstance=${!!M}`,` shouldRenderWallets=${xr}`,` shouldRenderPaymentElement=${Ar}`].join(`
|
|
40
|
+
`)}):null,Ka=Ce==="apm-expanding"||Ce==="apm-form"||Ce==="apm-collapsing",so=Ce==="apm-expanding"?`flopay-card-enter ${Nt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ce==="apm-collapsing"?`flopay-card-exit ${Nt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,lo=st?{...Oo,paymentMethodTypes:[st]}:null;if(re==="buttons"){let s=Ce==="buttons"||Ce==="expanding"||Ce==="apm-expanding",L=Ce==="expanding"||Ce==="card"||Ce==="collapsing",W=_e===void 0?{boxSizing:"border-box",height:Eo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},de=Ce==="expanding"||Ce==="apm-expanding"?`flopay-buttons-exit ${Nt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ce==="collapsing"||Ce==="apm-collapsing"?`flopay-buttons-enter ${Nt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,V=Ce==="expanding"?`flopay-card-enter ${Nt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ce==="collapsing"?`flopay-card-exit ${Nt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,l.jsxs)("form",{onSubmit:Uo,className:A,style:{position:"relative"},children:[(0,l.jsx)(oa,{}),zt&&(0,l.jsx)(vn,{status:zt,errorMessage:u,authorized:Tn}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!de?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!de?Os:{},...de?{animation:de,pointerEvents:"none"}:{}},children:[ja("flopay-direct-paypal-gate-debug"),Va("flopay-stripe-gate-debug"),_r&&Be&&(0,l.jsxs)(l.Fragment,{children:[Xt&&(0,l.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,l.jsx)(qr,{sessionId:e,nonce:t,billingApiUrl:mt,email:h.email,clientId:Be.clientId,environment:Be.environment,currency:G.toUpperCase(),isSubscription:Qe,providerObjectType:Be.providerObjectType,onTokenizedBody:yn,onComplete:i,onErrorChange:z,onDecline:d,onTechnicalFailure:Ye,onButtonClick:ae,runBeforeButtonClick:wn,isProcessing:k,onLoadStateChange:No,onInitializationStateChange:zo,session:se??null,existingOrderId:Xt?.orderId,debug:j},Xt?.orderId??"fresh")]}),Tr&&(0,l.jsx)(vt.Elements,{stripe:le,options:Ee,children:(0,l.jsx)(Ci,{sessionId:e,nonce:t,email:h.email,billingApiUrl:mt,onTokenizedBody:yn,onErrorChange:z,isProcessing:k,onButtonClick:ae,onDecline:d,onTechnicalFailure:Ye,runBeforeButtonClick:wn,onLoadStateChange:Sa,placeholderBorderRadius:rr})}),xr?(0,l.jsx)(vt.Elements,{stripe:M,options:Ie,children:(0,l.jsx)(Si,{sessionId:e,nonce:t,email:h.email,billingApiUrl:mt,intentKind:ie>0?"payment":"setup",expressMethods:to,onTokenizedBody:yn,onErrorChange:z,onButtonClick:ae,onDecline:d,onTechnicalFailure:Ye,runBeforeButtonClick:wn,onLoadStateChange:ka,placeholderBorderRadius:rr})}):Ta?(0,l.jsx)("div",{style:{height:Eo,borderRadius:rr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Ar&&(0,l.jsx)(wi,{sessionId:e,nonce:t,email:h.email,billingName:[h.firstName,h.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:mt,paymentElementMethods:no,stripeInstance:M,paymentElementBaseOptions:Oo,onTokenizedBody:yn,onErrorChange:z,onButtonClick:ae,onDecline:d,runBeforeButtonClick:wn,onLoadStateChange:Ea,isProcessing:k,submitButtonColor:or,submitButtonBorderRadius:kt,submitButtonStyle:p.submitButton,onExpandApm:Mn,expandedApmMethod:st,themeId:be,buttonAppearance:{backgroundColor:p.cardButton?.backgroundColor,borderColor:p.cardInputBorder,textColor:p.cardButton?.color,borderRadius:rr}}),ke&&(0,l.jsx)("button",{type:"button",onClick:async()=>{k||!(await wn("card")).proceed||(ae?.("card"),Wn())},disabled:k,style:{width:"100%",...W,...p.cardButton,...sa({themeBundle:c,resolvedPrimaryColor:or,resolvedBorderRadius:kt,submitButtonStyle:p.submitButton,explicitPrimaryColor:Zt?.colorPrimary}),fontSize:p.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:k?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:k?.6:1},onMouseEnter:we=>{!k&&(c||Zt?.colorPrimary)&&(we.currentTarget.style.backgroundColor=es)},onMouseLeave:we=>{(c||Zt?.colorPrimary)&&(we.currentTarget.style.backgroundColor=or)},onMouseDown:we=>{we.currentTarget.style.transform="scale(0.985)"},onMouseUp:we=>{we.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(mr,{content:_e})}),u&&Ce==="buttons"&&(0,l.jsx)(Pr,{margin:"0.25rem 0",styleOverride:p.errorBanner,children:u})]}),ke&&L&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...V?{animation:V}:{},...Ce==="collapsing"?{pointerEvents:"none"}:{}},children:qa}),J&&Ka&&st&&lo&&M&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...so?{animation:so}:{},...Ce==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:jo,borderRadius:Yo,...Dr,padding:Ho},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Nn,style:{display:"inline-flex",alignItems:"center",gap:Vo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(yr,{content:Se})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:Ko,paddingRight:80,...p.title},children:`Pay with ${(0,f.getStripeMethodDisplayName)(st)}`})]}),(0,l.jsx)(vt.Elements,{stripe:M,options:lo,children:(0,l.jsx)(aa,{method:st,sessionId:e,nonce:t,email:h.email,billingName:[h.firstName,h.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:mt,onTokenizedBody:yn,onErrorChange:z,onDecline:d,onCancel:Nn,runBeforeButtonClick:wn,onButtonClick:ae,isProcessing:k,submitButtonColor:or,submitButtonBorderRadius:kt,submitButtonStyle:p.submitButton,errorText:u})},st)]})})]})]})}return Ka&&st&&lo&&M&&J?(0,l.jsxs)("form",{onSubmit:Uo,className:A,style:{position:"relative"},children:[(0,l.jsx)(oa,{}),zt&&(0,l.jsx)(vn,{status:zt,errorMessage:u,authorized:Tn}),(0,l.jsx)("div",{style:{...so?{animation:so}:{},...Ce==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:jo,borderRadius:Yo,...Dr,padding:Ho},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Nn,style:{display:"inline-flex",alignItems:"center",gap:Vo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(yr,{content:Se})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:Ko,paddingRight:80,...p.title},children:`Pay with ${(0,f.getStripeMethodDisplayName)(st)}`})]}),(0,l.jsx)(vt.Elements,{stripe:M,options:lo,children:(0,l.jsx)(aa,{method:st,sessionId:e,nonce:t,email:h.email,billingName:[h.firstName,h.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:mt,onTokenizedBody:yn,onErrorChange:z,onDecline:d,onCancel:Nn,runBeforeButtonClick:wn,onButtonClick:ae,isProcessing:k,submitButtonColor:or,submitButtonBorderRadius:kt,submitButtonStyle:p.submitButton,errorText:u})},st)]})})]}):(0,l.jsxs)("form",{onSubmit:Uo,className:A,style:{position:"relative"},children:[(0,l.jsx)(oa,{}),zt&&(0,l.jsx)(vn,{status:zt,errorMessage:u,authorized:Tn}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ja("flopay-direct-paypal-gate-debug-default"),Va("flopay-stripe-gate-debug-default"),_r&&Be&&(0,l.jsxs)(l.Fragment,{children:[Xt&&(0,l.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,l.jsx)(qr,{sessionId:e,nonce:t,billingApiUrl:mt,email:h.email,clientId:Be.clientId,environment:Be.environment,currency:G.toUpperCase(),isSubscription:Qe,providerObjectType:Be.providerObjectType,onTokenizedBody:yn,onComplete:i,onErrorChange:z,onDecline:d,onTechnicalFailure:Ye,onButtonClick:ae,runBeforeButtonClick:wn,isProcessing:k,onLoadStateChange:No,onInitializationStateChange:zo,session:se??null,existingOrderId:Xt?.orderId,debug:j},Xt?.orderId??"fresh")]}),Tr&&(0,l.jsx)(vt.Elements,{stripe:le,options:Ee,children:(0,l.jsx)(Ci,{sessionId:e,nonce:t,email:h.email,billingApiUrl:mt,onTokenizedBody:yn,onErrorChange:z,isProcessing:k,onButtonClick:ae,onDecline:d,onTechnicalFailure:Ye,runBeforeButtonClick:wn,onLoadStateChange:Sa,placeholderBorderRadius:rr})}),xr&&(0,l.jsx)(vt.Elements,{stripe:M,options:Ie,children:(0,l.jsx)(Si,{sessionId:e,nonce:t,email:h.email,billingApiUrl:mt,intentKind:ie>0?"payment":"setup",expressMethods:to,onTokenizedBody:yn,onErrorChange:z,onButtonClick:ae,onDecline:d,onTechnicalFailure:Ye,runBeforeButtonClick:wn,onLoadStateChange:ka,placeholderBorderRadius:rr})}),Ar&&(0,l.jsx)(wi,{sessionId:e,nonce:t,email:h.email,billingName:[h.firstName,h.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:mt,paymentElementMethods:no,stripeInstance:M,paymentElementBaseOptions:Oo,onTokenizedBody:yn,onErrorChange:z,onButtonClick:ae,onDecline:d,runBeforeButtonClick:wn,onLoadStateChange:Ea,isProcessing:k,submitButtonColor:or,submitButtonBorderRadius:kt,submitButtonStyle:p.submitButton,themeId:be,onExpandApm:Mn,expandedApmMethod:st,buttonAppearance:{backgroundColor:p.cardButton?.backgroundColor,borderColor:p.cardInputBorder,textColor:p.cardButton?.color,borderRadius:rr}})]}),ke&&(Yi||Hi||Wi)&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,l.jsx)("span",{children:"or pay with card"}),(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),ke&&qa]})}var I=require("react/jsx-runtime"),Ir=44,ha="flopay_checkout_saved_payment_resume",Mo=new Map,xo=new Map;function xi(e,t){t.settled&&t.consumers===0&&Mo.get(e)===t&&Mo.delete(e)}function Ks(e,t,n){let o=xo.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let r=n(),i={attempt:r,sdkGeneratedIdempotencyKey:t};xo.set(e,i);let m=()=>{xo.get(e)===i&&xo.delete(e)};return r.then(m,m),r}function Wr(e){return new Promise(t=>setTimeout(t,e))}function Ao(e,t,n){let o=ho({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:fe.SDK_VERSION,enabled:t!==!1});return o.beginCheckout(n),o}function Gr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function la(e,t,n,o,r){let i=Ao(e,t,n);i.error({errorCode:o,stage:r,paymentMethodCategory:"unknown",...r==="session_read"?{requestCategory:"session_read"}:{}}),Gr(i)}function Hs(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 fa(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function ca(e){return!e||e.data.stripe?.publishableKey?!1:!!fa(e)?.clientId}function Vn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Ys(){if(!Vn())return null;try{let e=window.sessionStorage.getItem(ha);return e?JSON.parse(e):null}catch{return null}}function Ai(e){if(Vn())try{window.sessionStorage.setItem(ha,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function da(){if(Vn())try{window.sessionStorage.removeItem(ha)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var va=":idempotency-key";function Bi(e,t){if(!Vn())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let o=JSON.parse(n);return!o||typeof o.sid!="string"||!o.sid||"canonicalIdentity"in o&&o.canonicalIdentity!==t?null:{..."canonicalIdentity"in o?{canonicalIdentity:t}:{},sid:o.sid,nonce:typeof o.nonce=="string"?o.nonce:void 0}}catch{return{sid:n}}}function ua(e,t,n,o){if(Vn())try{window.sessionStorage.setItem(e,JSON.stringify(o?{canonicalIdentity:t,sid:n,nonce:o}:{canonicalIdentity:t,sid:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",r)}}function ga(e,t){if(Vn())try{Bi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Fi(e,t){if(!Vn())return null;try{let n=window.sessionStorage.getItem(e+va);if(!n)return null;try{let o=JSON.parse(n);return typeof o=="string"?o?{idempotencyKey:o}:null:!o||typeof o.idempotencyKey!="string"||!o.idempotencyKey||"canonicalIdentity"in o&&o.canonicalIdentity!==t?null:{..."canonicalIdentity"in o?{canonicalIdentity:t}:{},idempotencyKey:o.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function pa(e,t,n){if(Vn())try{window.sessionStorage.setItem(e+va,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",o)}}function ma(e,t){if(ga(e,t),!!Vn())try{Fi(e,t)&&window.sessionStorage.removeItem(e+va)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ws(){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 o of t)e.searchParams.has(o)&&(e.searchParams.delete(o),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Mi(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 Gs(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 ya(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Jr(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",o={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(r=>ya(`${r.type??""}:${r.code??r.providerItemId??r.providerPlanId??""}`,r)).sort(),i:e?.items?.map(r=>ya(r.code??r.providerItemId??"",r)).sort(),s:e?.subscriptions?.map(r=>ya(r.code??r.providerPlanId??"",r)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(o)}function Js(e,t=!1){let n=Jr(e,t),o=0;for(let r=0;r<n.length;r++)o=(o<<5)-o+n.charCodeAt(r)|0;return`flopay_session_${Math.abs(o).toString(36)}`}function Xs(e,t){if(!e?.customer||!e.products)return!1;let n=t.account.email?.trim().toLowerCase()??"",o=e.customer.email?.trim().toLowerCase()??"";if((n?o!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let r=(0,fe.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!r||e.currency.toUpperCase()!==r.toUpperCase())return!1;let i=(t.products??(0,fe.foldIntoProducts)(t.items,t.subscriptions)).map(g=>({type:g.type,code:g.code??g.providerItemId??g.providerPlanId??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??r).toUpperCase()})).sort((g,v)=>`${g.code}:${g.type??""}`.localeCompare(`${v.code}:${v.type??""}`)),m=e.products.map(g=>({type:g.type,code:g.code??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??e.currency).toUpperCase()})).sort((g,v)=>`${g.code}:${g.type??""}`.localeCompare(`${v.code}:${v.type??""}`));if(i.length!==m.length)return!1;for(let g=0;g<i.length;g+=1){let v=i[g],b=m[g];if(v.code!==b.code||v.type!==void 0&&v.type!==b.type||v.quantity!==b.quantity||v.totalAmount!==b.totalAmount||v.overrideAmount!==b.overrideAmount||v.currency!==b.currency)return!1}let d=[...t.couponCodes??[]].sort(),R=[...e.coupons??[]].sort();return d.length===R.length&&d.every((g,v)=>g===R[v])}function Bo({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:r,appearance:i,locale:m,loading:d,error:R,onComplete:g,onError:v,onInstrument:b,onDecline:A,onCountryChange:D,onZipChange:y,showPayPal:C=!0,showStripe:Q=!0,enabledPaymentMethods:J,showApplePay:w=!0,showGooglePay:ge=!0,debug:U=!1,layout:ee,theme:re,buttonsTheme:be,buttonsStyles:oe,cardButtonContent:he,cardBackButtonContent:ze,cardTitleContent:_e,showSecurityFooter:Se,onButtonClick:K,onBeforeButtonClick:O,enableAVS:ae,cardFieldOrder:Ue,cardPreFormSlot:Te,avsLayout:X,className:$,initialErrorMessage:te=null,children:pe,checkoutMode:ve,confirmLabel:Z,renderConfirmButton:Re,onSessionCompleted:H}){let _=(0,fe.resolveBillingApiUrl)(o),me=(0,E.useMemo)(()=>(0,fe.resolveTheme)(re),[re]),We=i??me?.appearance,$e=n?"embedded_checkout":"standard_checkout",ce=pe?"custom_layout":ee==="buttons"?"buttons_layout":"default_layout",[B,ie]=(0,E.useState)(null),[G,Oe]=(0,E.useState)(null),Be=(0,E.useRef)(null),[Qe,se]=(0,E.useState)(null),yt=(0,E.useRef)(null),[j,qe]=(0,E.useState)(null),Pt=(0,E.useMemo)(()=>n?Jr(n):"",[n]),Y=n?`create:${Pt}`:`session:${e??""}`,bt=j?.gateways?.stripe?"stripe":j?.gateways?.paypal?"paypal":void 0,Ke=(0,E.useRef)(new Set),Qt=(0,E.useRef)(Y),Et=(0,E.useRef)(Y);go(()=>{Et.current=Y,Qt.current!==Y&&(Qt.current=Y,Ke.current.clear())},[Y]);let T=(0,E.useCallback)(u=>{if(Et.current===Y){if(Xo.has(u.name)){if(Ke.current.has(u.name))return;Ke.current.add(u.name)}Le(()=>b?.(u))}},[Y,b]),Pe=vr(T,Y),ft=(0,E.useRef)(!1),Ne=(0,E.useCallback)(u=>{if(ft.current)return;let c=u.gateway||!bt?u:{...u,gateway:bt};T(c)},[T,bt]);(0,E.useEffect)(()=>{Pe({class:"lifecycle",name:"checkout.mount"})},[Pe]);let[qt,Gt]=(0,E.useState)(e??""),Ze=e??qt,Ct=n?"":Ze,[et,Mt]=(0,E.useState)(!0),[Ge,jt]=(0,E.useState)(null),[Rt,en]=(0,E.useState)("full"),[Dt,Rn]=(0,E.useState)(!1),[sn,at]=(0,E.useState)(te),[Lt,Je]=(0,E.useState)(null),[_n,dt]=(0,E.useState)(null),[bn,Ot]=(0,E.useState)(!1),[ue,Kn]=(0,E.useState)(void 0),[Tn,xn]=(0,E.useState)(""),[An,dr]=(0,E.useState)(!1),[x,tt]=(0,E.useState)(!1),ke=(0,E.useRef)(0),[Cn,je]=(0,E.useState)("loading"),[Hn,Qn]=(0,E.useState)(0),Vt=(0,E.useRef)(!1),ut=(0,E.useRef)(!1),Jt=(0,E.useRef)(!1),Kt=(0,E.useRef)(null),it=(0,E.useMemo)(()=>({checkoutMode:ve??Rt,layout:pe?"unknown":ee==="buttons"?"buttons":"embedded"}),[ve,pe,Rt,ee]),ln=(0,E.useRef)(g);ln.current=g;let cn=(0,E.useRef)(v);cn.current=v;let Yn=(0,E.useRef)(A);Yn.current=A,(0,E.useEffect)(()=>{At(G)?.setCheckoutContext(it),Qe&&Qe!==G&&At(Qe)?.setCheckoutContext(it)},[G,Qe,it]);let Sn=(0,E.useRef)(H);Sn.current=H;let tn=(0,E.useCallback)(u=>{je(u),!(u!=="exhausted"||Jt.current)&&(Jt.current=!0,cn.current?.(new fe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),dn=(0,E.useCallback)(()=>{je("retrying"),Qn(u=>u+1)},[]);(0,E.useEffect)(()=>{je("loading"),Qn(0),Jt.current=!1},[Ze]),(0,E.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:fe.SDK_VERSION,checkout_type:$e,checkout_layout:ce,billing_api_url:_})},[ce,$e,_]);let Ce=(0,E.useMemo)(()=>n?Jr(n,!0):"",[n]),St=(0,E.useMemo)(()=>Tn===Ce?ue:void 0,[ue,Tn,Ce]),st=(0,E.useMemo)(()=>n?Wo(n,St):void 0,[n,St]),nn=ve??st?.checkoutMode??"full",un=(0,E.useMemo)(()=>st?{...st,checkoutMode:nn}:void 0,[st,nn]);(0,E.useEffect)(()=>{Kn(void 0),xn(Ce)},[Ce]),(0,E.useEffect)(()=>{at(te)},[te]);let Ln=(0,E.useCallback)((u,c,p)=>{Le(()=>{Yn.current?.(xt(u,c,p))})},[Le]),pn=(0,E.useCallback)(async(u,c)=>{at(null),dt(null),Ot(!1),Je("processing");let p=c?.sessionId??u.id,N=u.gateways?.stripe?"stripe":u.gateways?.paypal?"paypal":void 0,ne=Be.current??yt.current,q=At(ne),k=ne?null:Ao(_,r,it),P={log:Ie=>{q?q.log(Ie):k?.log(Ie)},error:Ie=>{q?q.error(Ie):k?.error(Ie)},terminal:Ie=>{q?q.terminal(Ie):k?.terminal(Ie)},performance:Ie=>{q?q.performance(Ie):k?.performance(Ie)},now:()=>q?.now()??k?.now()??0,elapsed:Ie=>q?.elapsed(Ie)??Math.max(0,(k?.now()??Ie)-Ie)},h=P.now(),S=!!(c?.initialAutoProcessingError||c?.initialAutoProcessingPending),M=!1,le,ye=()=>{M||(M=!0,S=!0,le=P.now(),P.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},De=!1,He=()=>{De||(De=!0,P.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),P.performance({stage:"processing",durationMs:P.elapsed(h),durationMode:"machine",paymentMethodCategory:"saved"}),le!==void 0&&P.performance({stage:"recovery",durationMs:P.elapsed(le),durationMode:"machine",paymentMethodCategory:"saved"}))};P.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ft.current=!0;try{P.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ft.current=!1}Pe({class:"lifecycle",name:"payment.processing.started",provider:N}),S&&ye();let Tt;try{let Ie=di(c?.initialAutoProcessingError),Ee;if(Ie)ye(),Ie.type==="paypal_redirect_required"&&Kt.current?.publishableKey&&Ai({sessionId:p,publishableKey:Kt.current.publishableKey,paypalPublishableKey:Kt.current.paypalPublishableKey}),Ee=await So(Ie,{flopay:Be.current,paypalFlopay:yt.current,attempt3DS:c?.attempt3DS,billingApiUrl:_,sessionId:p,session:u,telemetry:!1}),Ie.type==="paypal_redirect_required"&&da();else if(c?.initialAutoProcessingPending){let Ye=(await new cr.PaymentAPI(_,{telemetry:!1}).waitForCheckoutSessionCompletion(c.initialAutoProcessingPending.sessionId,{initialDelayMs:c.initialAutoProcessingPending.retryAfterMs})).data.session;if(!gr(Ye))throw po(Ye);Ee=ar(Ye,p)}else{if(c?.initialAutoProcessingError)throw Xn(c.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:c.initialAutoProcessingError.checkoutMethod});if(c?.fromCreateSession)return c?.fallbackToFull&&(en("full"),Mi("full")),!1;{let z=await Sr({billingApiUrl:_,sessionId:p,session:u,telemetry:!1});z.type==="success"?Ee=z.result:(ye(),z.type==="paypal_redirect_required"&&Kt.current?.publishableKey&&Ai({sessionId:p,publishableKey:Kt.current.publishableKey,paypalPublishableKey:Kt.current.paypalPublishableKey}),Ee=await So(z,{flopay:Be.current,paypalFlopay:yt.current,attempt3DS:c?.attempt3DS,billingApiUrl:_,sessionId:p,session:u,telemetry:!1}),z.type==="paypal_redirect_required"&&da())}}p&&br(p),He(),S&&(P.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),P.terminal({outcome:Ee.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Ot(Ee.status==="authorized"),Je("success"),await Wr(1200),Tt=()=>ln.current?.(Ee)}catch(Ie){let Ee=lr(Ie),z=Ee.checkoutMethod??Hr;at(Ee.message),dt(Ee.message),Ot(!1),c?.fallbackToFull&&(P.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),en("full"),Mi("full")),He();let wt=Ee.statusCode!==void 0?(0,fe.telemetryStatusClass)(Ee.statusCode,"unknown"):void 0,Ye=wt==="4xx"?{requestCategory:"process_payment",statusClass:wt}:{},rt=wt===void 0||wt==="4xx";if(rt&&(Ee.telemetryOutcome==="payment_declined"||!!(Ee.declineCode||Ee.code?.toLowerCase().includes("declin"))))P.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ye});else if(rt&&(Ee.telemetryOutcome==="validation_rejected"||Ee.type==="validation_error"))P.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ye});else{let Zr=(0,fe.classifyTelemetryFailure)(Ie,S?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),rn=Ee.telemetryRequestCategory??"process_payment";ft.current=!0;try{P.error({...Zr,...Ee.telemetryFailureCategory?{failureCategory:Ee.telemetryFailureCategory}:{},stage:S?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:rn})}finally{ft.current=!1}Pe({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:rn,provider:N})}return Le(()=>cn.current?.(Ee)),Ln(z,Ee,{code:Ee.code,declineCode:Ee.declineCode}),Je("error"),await Promise.allSettled([Wr(1500),c?.ensureProvidersReady?c.ensureProvidersReady():Promise.resolve()]),S&&(P.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{He(),k&&Gr(k),Je(null),dt(null)}return Le(Tt),!0},[Ln,Pe,Le,lr,_,r,it]);(0,E.useEffect)(()=>{if(typeof window>"u"||ut.current)return;let u=new URLSearchParams(window.location.search),c=u.get("payment_intent_client_secret");if(!c)return;let p=Ys();p&&(ut.current=!0,(async()=>{let N,ne=0;at(null),dt(null),Je("processing"),Rn(!0);try{if(u.get("redirect_status")==="failed")throw Object.assign(new fe.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:q,paypalFlopay:k}=await ko({publishableKey:p.publishableKey,paypalPublishableKey:p.paypalPublishableKey,billingApiUrl:_,locale:m,telemetry:r});N=At(k??q),ne=N?.now()??0,N?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),N?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let P=(k??q)?.getRawProvider();if(!P)throw Object.assign(new fe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:h,error:S}=await P.retrievePaymentIntent(c);if(S)throw Object.assign(new fe.FloPayError(S.message??"Failed to retrieve PayPal payment status.","api_error",{code:S.code}),{checkoutMethod:"paypal"});let M=Xa(h?.status);if(!h||M==="failed")throw Object.assign(new fe.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let le=typeof h.payment_method=="string"?h.payment_method:h.payment_method?.id,ye=M;if(p.sessionId){let Tt=(await new cr.PaymentAPI(_,{telemetry:!1}).getUnifiedCheckoutSession(p.sessionId)).data.session;if(Tt&&Tt.status!=="complete"){let Ie=await Sr({billingApiUrl:_,sessionId:p.sessionId,session:Tt,telemetry:!1,tokenizedData:{id:le??h.id,type:"card",threeDSecureActionResultTokenId:h.id,isPaypal:!0}});if(Ie.type!=="success")throw Object.assign(new fe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});ye=Ie.result.status}}p.sessionId&&br(p.sessionId),N?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),N?.performance({stage:"redirect_resume",durationMs:N.elapsed(ne),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),N?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Je("success"),await Wr(1200),Le(()=>ln.current?.({status:ye,paymentIntentId:h.id,paymentMethodId:le,checkoutMethod:"paypal"}))}catch(q){let k=lr(q),P=k.checkoutMethod??"paypal",h=!!(k.declineCode||k.code?.toLowerCase().includes("declin"));if(N)N.performance({stage:"redirect_resume",durationMs:N.elapsed(ne),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),h?N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):N.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(h){let S=Ao(_,r,it);S.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Gr(S)}else la(_,r,it,"REDIRECT_RESUME_FAILED","redirect_resume");at(k.message),dt(k.message),Le(()=>cn.current?.(k)),Ln(P,k,{code:k.code,declineCode:k.declineCode}),Je("error"),await Wr(1500)}finally{da(),Ws(),Je(null),dt(null),Rn(!1)}})())},[Ln,Le,m,lr,_,r]);let Nt=(0,E.useRef)(null),Ht=(0,E.useMemo)(()=>un?Jr(un):"",[un]),Yt=(0,E.useRef)(un);Yt.current=un,(0,E.useEffect)(()=>{Gt(e??"")},[e]),(0,E.useEffect)(()=>{Vt.current=!1,at(te),dt(null),Ot(!1),Je(null)},[Ht,te,e]);async function Wn(u,c,p){let N=Ao(_,r,it),ne=new cr.PaymentAPI(_,{telemetry:!1}),q=!1;try{let k=u.idempotencyKey!==void 0?(0,fe.resolveIdempotencyKey)(u.idempotencyKey):void 0,P=Bi(c,p),h=Fi(c,p);P?.canonicalIdentity===p&&h&&h.canonicalIdentity===void 0&&(pa(c,p,h.idempotencyKey),h={...h,canonicalIdentity:p});let S=k??(h?.canonicalIdentity===p?h.idempotencyKey:void 0),M,le=!1;N.log({name:P?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let ye=P?.sid??null,De=null,He;if(ye)try{De=await ne.getUnifiedCheckoutSession(ye,P?.nonce),P&&P.canonicalIdentity===void 0&&(Xs(De.data.session,u)?(ua(c,p,ye,P.nonce??De.data.session?.clientSecret),h&&h.canonicalIdentity===void 0&&(pa(c,p,h.idempotencyKey),S??(S=h.idempotencyKey))):(ma(c,p),h=null,S=k,ye=null,De=null));let Tt=De?.data.session?.status;if(ye&&De&&Tt==="complete"){if(Qo(ye))return{sid:ye,result:De};ma(c,p),ye=null,De=null,le=!0}}catch{N.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),P?.canonicalIdentity===void 0?(ma(c,p),S=k):ga(c,p),ye=null}if(!ye){!k&&(le||!S)&&(S=(0,fe.resolveIdempotencyKey)(),M=S),S&&pa(c,p,S);let Tt=N.now(),Ie=0;N.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ee={...u,idempotencyKey:S,avsCheck:!!ae,avsConfig:typeof ae=="object"?ae:void 0,checkoutType:"embedded_checkout",checkoutLayout:pe?"custom_layout":ee==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(Ee,cr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Ye=>{Ie=Math.max(Ie,Ye)}}});let z=()=>{N.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),N.performance({stage:"session_create",durationMs:N.now()-Tt,durationMode:"machine",requestCategory:"session_create",attempt:Ie,statusClass:"2xx"})},wt=Ye=>{let rt=(0,fe.classifyTelemetryFailure)(Ye,"CHECKOUT_SESSION_CREATE_FAILED","unknown");N.performance({stage:"session_create",durationMs:N.now()-Tt,durationMode:"machine",requestCategory:"session_create",attempt:Ie,statusClass:rt.statusClass}),Ye instanceof fe.FloPayError&&Ye.type==="validation_error"?N.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):rt.statusClass==="4xx"?N.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(N.error({...rt,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Pe({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if((0,fe.isDetachedSessionEligible)(Ee)){let Ye=await ne.createDetachedSession(Ee);Ye.claimed.catch(()=>{}),De=Ye.shell,ye=Ye.sessionId,He=Ye.claimed.then(rt=>{let tr=rt.data.session?.id??Ye.sessionId;return tr&&ua(c,p,tr,rt.data.session?.clientSecret??Ye.nonce),z(),rt},rt=>{throw ga(c,p),wt(rt),rt}).finally(()=>Gr(N)),He.catch(()=>{}),q=!0,N.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),N.performance({stage:"session_shell",durationMs:N.now()-Tt,durationMode:"machine",requestCategory:"session_create",attempt:Ie,statusClass:"2xx",paymentMethodCategory:"card"})}else De=await ne.createAndFetchSession(Ee),z()}catch(Ye){throw wt(Ye),Ye}ye=De.data.session?.id??ye??"",ye&&!He&&ua(c,p,ye,De.data.session?.clientSecret)}return{sid:ye??"",result:De,sdkGeneratedIdempotencyKey:M,...He?{claimed:He}:{}}}finally{q||Gr(N)}}let On=(0,E.useCallback)(async(u,c)=>{let p=Yt.current;if(!p)throw new fe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let N=Wo(p,u),ne=Jr(N),q=Js(N),k=Mo.get(ne);if(!k){let S={canonicalIdentity:ne,promise:Wn(N,q,ne),consumers:0,settled:!1};k=S,Mo.set(ne,S);let M=()=>{S.settled=!0,xi(ne,S)};S.promise.then(M,M)}k.consumers+=1;let P=!1,h=()=>{P||(P=!0,k.consumers-=1,xi(ne,k))};c?.(h);try{let S=await k.promise;Nt.current=ne,u&&(xn(Ce),Kn(Ee=>Wa(Ee,u)));let{sid:M,result:le,claimed:ye}=S;if(ie(le),le.data.session&&qe(le.data.session),M&&Gt(M),ye){ke.current+=1;let Ee=ke.current;tt(!0),ye.then(z=>{ke.current===Ee&&(ie(z),z.data.session&&qe(z.data.session),tt(!1))},z=>{ke.current===Ee&&(tt(!1),jt(z instanceof fe.FloPayError?z:new fe.FloPayError(z instanceof Error?z.message:"Failed to create session","api_error")))})}else ke.current+=1,tt(!1);let{publishableKey:De,paypalPublishableKey:He}=wo(le),{flopay:Tt,paypalFlopay:Ie}=await ko({publishableKey:De,paypalPublishableKey:He,billingApiUrl:_,locale:m,telemetry:r});return Be.current=Tt,Oe(Tt),yt.current=Ie,se(Ie),Mt(!1),S}catch(S){throw Nt.current===ne&&(Nt.current=null),S}finally{c||h()}},[Ce,m,_,r,it]),Mn=(0,E.useRef)(pn);Mn.current=pn;let Nn=(0,E.useRef)(On);Nn.current=On;let zt=(0,E.useCallback)(async u=>{if(!Gs(u)||An)return{sessionId:qt,session:j};dr(!0);try{let c=await On(u);return{sessionId:c.sid,session:c.result.data.session??null}}finally{dr(!1)}},[On,An,qt,j]);(0,E.useEffect)(()=>{let u=!1,c;if(jt(null),Ht){let ne=Yt.current;return en(nn),Mt(!1),Nt.current===Ht?()=>{u=!0}:(qe(Ga(ne,ve)),(async()=>{let q=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),k=nn==="auto"&&!Vt.current&&!q;k&&(at(null),dt(null),Je("processing"));try{let P=await Nn.current(void 0,le=>{c=le}),h=P.result.data.session??null;Kt.current=wo(P.result);let S=ca(P.result),M=Qo(P.sid||h?.id);if(!u&&k&&h&&!S&&!M){Vt.current=!0,await Ks(Ht,P.sdkGeneratedIdempotencyKey,()=>Mn.current(h,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:P.result.autoProcessingError,initialAutoProcessingPending:P.result.autoProcessingPending,autoProcessingAttempted:P.result.autoProcessingAttempted,sessionId:P.sid||h.id}));return}!u&&k&&((S||M)&&(Vt.current=!0),Je(null),dt(null))}catch(P){if(u)return;let h=P instanceof fe.FloPayError||typeof P=="object"&&P!==null&&"code"in P?P.code:void 0;if(k&&h==="session_auto_completed"){Vt.current=!0,Je("success"),await Wr(1200),u||(Le(()=>{ln.current?.({status:"succeeded"})}),Je(null),dt(null));return}k&&(Je(null),dt(null));let S=P instanceof fe.FloPayError?P:new fe.FloPayError(P instanceof Error?P.message:"Failed to create session","api_error");jt(S)}finally{c?.(),c=void 0}})(),()=>{u=!0,c?.()})}Mt(!0);async function p(){let ne=!1;try{let k=await new cr.PaymentAPI(_,{telemetry:!1}).getUnifiedCheckoutSession(Ze,t);if(u)return;ie(k);let P=k.data.session??null;if(qe(P),!P)throw new fe.FloPayError("No session data returned","api_error");let h=P.checkoutMode;if(h==="setup")throw new fe.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(P.status==="authorized"){Mt(!1),Le(()=>{ln.current?.(ar(P,Ze)),Sn.current?.(P.successUrl??"")});return}if(P.status==="complete"){Mt(!1),Le(()=>{Sn.current?.(P.successUrl??"")});return}if(P.status==="expired")throw uo(P);ne=!0;let S=ve??h??"full";en(S);let M=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),le=ca(k);if(S==="auto"&&!Vt.current&&!M&&!le){Vt.current=!0;let ye=N(k);try{if(await Mn.current(P,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ye,sessionId:Ze||P.id}),u)return;await ye,u||Mt(!1);return}catch{if(u)return;await ye,u||Mt(!1);return}}await N(k),u||Mt(!1)}catch(q){if(u)return;ne&&Pe({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),q instanceof fe.FloPayError?!ne&&!Hs(q)&&la(_,r,it,"NETWORK_REQUEST_FAILED","session_read"):la(_,r,it,"INTERNAL_SDK_ERROR","checkout_mount");let k=q instanceof fe.FloPayError?q:new fe.FloPayError(q instanceof Error?q.message:"Failed to initialize checkout","api_error");jt(k),Mt(!1)}}async function N(ne){let{publishableKey:q,paypalPublishableKey:k}=wo(ne);Kt.current={publishableKey:q,paypalPublishableKey:k};let{flopay:P,paypalFlopay:h}=await ko({publishableKey:q,paypalPublishableKey:k,billingApiUrl:_,locale:m,telemetry:r});Be.current=P,Oe(P),yt.current=h,se(h)}return p(),()=>{u=!0}},[ve,Ht,nn,Ct,Le,t]);let nt=(0,E.useCallback)(async()=>{if(!(Dt||!j)){Rn(!0),at(null);try{await pn(j,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ze||j.id})}finally{Rn(!1)}}},[Ze,Dt,pn,j]),mn=fa(B),Ut=ca(B),pt=(0,E.useMemo)(()=>{if(!(!B||!j||!B.data.stripe?.publishableKey))return{billingApiUrl:_}},[B,j,_]),Xt=!!(n&&!pe&&ee==="buttons"&&O&&nn==="full"),_t=(0,E.useMemo)(()=>({session:j,loading:et,error:Ge,checkoutMode:Rt,inlineSessionDraft:un,applyInlineSessionPatch:Xt?zt:void 0,inlineSessionPatchProcessing:An,claimPending:x}),[j,et,Ge,Rt,un,Xt,zt,An,x]),er=!!n&&ee==="buttons"&&!Ut&&(!G||!pt),mt=Lt?(0,I.jsx)(vn,{status:Lt,errorMessage:_n,authorized:bn}):null;if(et){if(d)return(0,I.jsxs)(I.Fragment,{children:[d,mt]});if(ee==="buttons"){let u=me?.buttonsLayout?.cardButton?.borderRadius??me?.appearance.variables?.borderRadius??8,c=p=>(0,I.jsx)("div",{style:{height:p,borderRadius:u,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[C&&c(Ir),Q&&(w||ge)&&c(Ir),Q&&c(Ir),(0,I.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),mt]})}return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,I.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,I.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),mt]})}return Ge?R?(0,I.jsx)(kn.Provider,{value:_t,children:R(Ge)}):(0,I.jsx)(kn.Provider,{value:_t,children:(0,I.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ge.message})}):er?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(kn.Provider,{value:_t,children:(0,I.jsx)(Qs,{onButtonClick:K,showPayPal:C,showStripe:Q,showApplePay:w,showGooglePay:ge,theme:re,buttonsTheme:be,buttonsStyles:oe,cardButtonContent:he,cardBackButtonContent:ze,cardTitleContent:_e})}),mt]}):Ut&&j&&mn?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(kn.Provider,{value:_t,children:(0,I.jsxs)("div",{className:$,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[sn&&(0,I.jsx)(Pr,{icon:!1,children:sn}),Cn==="retrying"&&(0,I.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Cn==="exhausted"&&(0,I.jsxs)("div",{role:"alert",children:[(0,I.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,I.jsx)("button",{type:"button",onClick:dn,children:"Retry PayPal"})]}),Cn!=="exhausted"&&(0,I.jsx)("div",{"aria-hidden":Cn==="retrying"?!0:void 0,style:Cn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,I.jsx)(si,{sessionId:Ze,nonce:j.clientSecret||void 0,billingApiUrl:_,email:j.customer?.email,clientId:mn.clientId,environment:mn.environment,currency:(j.currency??"usd").toUpperCase(),isSubscription:j.mode==="subscription",providerObjectType:mn.providerObjectType,onComplete:g,onErrorChange:at,onDecline:A,onButtonClick:K,onInitializationStateChange:tn,allowAutomaticRetry:Hn===0,session:j,telemetry:r,telemetryContext:it,onInstrument:Ne,debug:U},`${Y}:paypal-init-${Hn}`)})]})}),mt]}):!G||!pt?(0,I.jsx)(I.Fragment,{children:mt}):Rt==="confirm"?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(kn.Provider,{value:_t,children:(0,I.jsx)(Vr,{flopay:G,paypalFlopay:Qe,options:pt,onInstrument:Ne,children:(0,I.jsxs)("div",{className:$,children:[sn&&(0,I.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:sn}),Re?Re({onConfirm:nt,isProcessing:Dt}):(0,I.jsx)("button",{type:"button",onClick:nt,disabled:Dt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Dt?"not-allowed":"pointer",opacity:Dt?.6:1},children:Dt?"Processing...":Z??"Confirm Purchase"})]})},Y)}),mt]}):(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(kn.Provider,{value:_t,children:(0,I.jsx)(Vr,{flopay:G,paypalFlopay:Qe,options:pt,onInstrument:Ne,children:pe?(0,I.jsxs)(I.Fragment,{children:[sn&&(0,I.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:sn}),(0,I.jsx)(Zs,{sessionId:Ze,nonce:j?.clientSecret||void 0,billingApiUrl:_,session:j,children:pe})]}):(0,I.jsx)(To,{sessionId:Ze,nonce:j?.clientSecret||void 0,email:j?.customer?.email,userId:j?.customer?.id,firstName:j?.customer?.firstName,lastName:j?.customer?.lastName,totalAmount:j?Math.round((0,fe.buildCheckoutDisplayData)(j).total*100):0,currency:j?.currency?.toLowerCase()??"usd",onComplete:g,onError:v,onDecline:A,error:sn,onErrorChange:at,showPayPal:C,showStripe:Q,enabledPaymentMethods:J??B?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:B?.data.stripe?.enabledPaymentMethodCountries,showApplePay:w,showGooglePay:ge,layout:ee,theme:re,buttonsTheme:be,buttonsStyles:oe,appearance:We,cardButtonContent:he,cardBackButtonContent:ze,cardTitleContent:_e,onButtonClick:K,onBeforeButtonClick:O,enableAVS:ae,...Ue?{cardFieldOrder:Ue}:{},...Te?{cardPreFormSlot:Te}:{},avsLayout:X,country:j?.customer?.country,city:j?.customer?.city,state:j?.customer?.state,onCountryChange:D,onZipChange:y,avsCheck:!!ae,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:pe?"custom_layout":ee==="buttons"?"buttons_layout":"default_layout",className:$,directPaypal:fa(B),isSubscription:j?.mode==="subscription",session:j,dataAttachmentPending:x,debug:U})},Y)}),mt]})}function Zs({sessionId:e,nonce:t,billingApiUrl:n,session:o,children:r}){return(0,I.jsx)(I.Fragment,{children:E.default.Children.map(r,i=>{if(!E.default.isValidElement(i))return i;let m=i.props,d={};return m.sessionId||(d.sessionId=e),!m.nonce&&t&&(d.nonce=t),m.billingApiUrl||(d.billingApiUrl=n),o?.customer&&(m.email||(d.email=o.customer.email),m.userId||(d.userId=o.customer.id),m.firstName||(d.firstName=o.customer.firstName),m.lastName||(d.lastName=o.customer.lastName)),Object.keys(d).length===0?i:E.default.cloneElement(i,d)})})}function Qs({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:o,showGooglePay:r,theme:i,buttonsTheme:m,buttonsStyles:d,cardButtonContent:R,cardBackButtonContent:g,cardTitleContent:v}){let[b,A]=(0,E.useState)(!1),D=(0,E.useMemo)(()=>(0,fe.resolveTheme)(i),[i]),y=(0,E.useMemo)(()=>{let w=D?.buttonsLayout??(0,fe.resolveButtonsLayoutTheme)(m);return d?{...w,...d,cardButton:{...w.cardButton,...d.cardButton},cardFormContainer:{...w.cardFormContainer,...d.cardFormContainer},backButton:{...w.backButton,...d.backButton},backButtonIcon:{...w.backButtonIcon,...d.backButtonIcon},submitButton:{...w.submitButton,...d.submitButton},title:{...w.title,...d.title}}:w},[D,m,d]),C=D?.buttonsLayout?.cardButton?.borderRadius??D?.appearance.variables?.borderRadius??8,Q=w=>(0,I.jsx)("div",{style:{height:w,borderRadius:C,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),J=R===void 0?{boxSizing:"border-box",height:Ir,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let w=y.cardInputBorder??"#e5e7eb",ge=y.cardInputBackground??"white",U=pr(g),ee=pr(v);return(0,I.jsxs)("div",{style:{backgroundColor:y.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...y.cardFormContainer},children:[(0,I.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,I.jsxs)("button",{type:"button",onClick:()=>A(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:U?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...y.backButton},children:[(0,I.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...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)(yr,{content:g})]}),ee?(0,I.jsx)("div",{style:{flex:1}}):(0,I.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...y.title},children:(0,I.jsx)(Nr,{content:v})})]}),(0,I.jsx)("div",{style:{backgroundColor:ge,border:`1px solid ${w}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsxs)("div",{style:{display:"flex"},children:[(0,I.jsx)("div",{style:{flex:1,backgroundColor:ge,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsx)("div",{style:{flex:1,backgroundColor:ge,borderTop:"none",borderRight:`1px solid ${w}`,borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,I.jsx)("div",{style:{backgroundColor:ge,border:`1px solid ${w}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...y.submitButton,opacity:.5}}),(0,I.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&&E(Sr),n&&(a||r)&&E(Sr),n&&(0,w.jsx)("button",{type:"button",onClick:()=>{e?.("card"),C(!0)},style:{width:"100%",..._,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:f=>{f.currentTarget.style.transform="scale(0.985)"},onMouseUp:f=>{f.currentTarget.style.transform="scale(1)"},children:(0,w.jsx)(dr,{content:b})}),(0,w.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Ai=require("@flopay/shared");var or=require("react");var ki=require("react/jsx-runtime");function Ci(e,t){function n({className:a,id:r,style:i,options:u,onChange:d,onReady:b,onFocus:M,onBlur:g,onEscape:R}){let C=(0,or.useRef)(null),k=(0,or.useRef)(null),{elements:p,reportInteractive:h}=(0,or.useContext)(Bn);return(0,or.useEffect)(()=>{if(!p||!C.current)return;let E=!0;return(async()=>{let _=p.getElement(e);_||(_=await p.create(e,u)),!(!E||!C.current)&&(_.mount(C.current),k.current=_,d&&_.on("change",d),_.on("ready",()=>{h?.(),b?.()}),M&&_.on("focus",M),g&&_.on("blur",g),R&&_.on("escape",R))})(),()=>{if(E=!1,k.current){try{k.current.unmount()}catch{}k.current=null}}},[p,h]),(0,ki.jsx)("div",{ref:C,className:a,id:r,style:i})}return n.displayName=t,n}var Si=Ci("payment","PaymentElement"),wi=Ci("address","AddressElement");var lt=require("react"),Eo=require("@flopay/js/card-setup"),en=require("@flopay/shared");var Mn=require("react/jsx-runtime"),qr=class extends en.FloPayError{constructor(t,n,a){super(t,n,a),this.name="FloPayCardSetupError",this.retryable=a.retryable}};function Ri(e,t={}){let n=e instanceof en.FloPayError?e:void 0,a=n?.statusCode,r=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof a=="number"&&a>=500||n?.code==="vault_capture_timeout"||!n);return new qr(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:r,...n?.param?{param:n.param}:{},...a!==void 0?{statusCode:a}:{}})}function Ei({sessionId:e,nonce:t,billingApiUrl:n,telemetry:a,theme:r="modern-light",containerStyle:i,loading:u=null,onReady:d,onComplete:b,onDecline:M,onCancel:g,onValidation:R,onError:C}){let[k,p]=(0,lt.useState)(null),[h,E]=(0,lt.useState)(null),[_,f]=(0,lt.useState)(null),[ge,x]=(0,lt.useState)(null),[oe,ae]=(0,lt.useState)(null),j=(0,lt.useRef)(!1),K=(0,lt.useRef)(!1),ce=(0,lt.useMemo)(()=>{if(typeof r=="object")return r;let J=(0,en.resolveTheme)(r);if(J)return oo({appearance:J.appearance,buttonsStyles:J.buttonsLayout,layout:"default"})},[r]),pe=(0,lt.useRef)(d),De=(0,lt.useRef)(C),P=(0,lt.useRef)(b),ie=(0,lt.useRef)(M),Le=(0,lt.useRef)(g),we=(0,lt.useRef)(R),he=(0,lt.useRef)(!1),Z=(0,lt.useRef)(!1),me=(0,lt.useRef)(0);return pe.current=d,De.current=C,P.current=b,ie.current=M,Le.current=g,we.current=R,(0,lt.useEffect)(()=>{let J=me.current+1;return me.current=J,()=>{queueMicrotask(()=>{me.current===J&&(he.current||Z.current||(Z.current=!0,Xe(()=>{Le.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,lt.useEffect)(()=>{let J=!0,ne=new Eo.PaymentAPI((0,en.resolveBillingApiUrl)(n),{telemetry:a});return p(null),E(null),f(null),he.current=!1,Z.current=!1,(async()=>{try{if(!e.trim())throw new en.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new en.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ke=await ne.getUnifiedCheckoutSession(e,t);if(!J)return;let xe=ke.data.session;if(!xe||!(0,en.isCardSetupCheckoutSession)(xe))throw new en.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let se=xe.vault;if(se?.html?.trim()||(se=await ne.getVaultCapture(e,t)),!se.html?.trim())throw new en.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!J)return;E(se),p(new Eo.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:a}))}catch(ke){if(!J)return;let xe=Ri(ke);he.current=!0,f(xe),Xe(()=>De.current?.(xe))}})(),()=>{J=!1,ne.destroy()}},[n,t,e,a]),(0,lt.useEffect)(()=>{if(!k)return;let J=!1;K.current=!1,j.current=!1;let ne=k.on("submitting",()=>{j.current=!0,ae(null),x("processing")}),ke=k.on("complete",se=>{he.current=!0,j.current=!1,x("success"),(async()=>(await new Promise(W=>setTimeout(W,hn)),!K.current&&(K.current=!0,Xe(()=>{P.current?.({status:"succeeded",sessionId:e,...se.paymentMethod?{paymentMethod:se.paymentMethod}:{}})}),J||x(null))))()}),xe=k.on("decline",se=>{he.current=!0,j.current=!1,ae(se.message??null),x("error"),Xe(()=>{ie.current?.({status:"declined",sessionId:e,...se.declineReason?{reason:se.declineReason}:{},...se.message?{message:se.message}:{}})}),(async()=>(await new Promise(W=>setTimeout(W,Qt)),J||x(null)))()});return()=>{J=!0,ne(),ke(),xe()}},[k,e]),_?(0,Mn.jsx)("div",{role:"alert",children:_.message}):!k||!h?.html?(0,Mn.jsx)(Mn.Fragment,{children:u}):(0,Mn.jsxs)(Mn.Fragment,{children:[ge&&(0,Mn.jsx)(cn,{status:ge,errorMessage:oe,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,Mn.jsx)(mr,{capture:k,html:h.html,messageToken:h.messageToken,expectedOrigin:h.expectedOrigin,theme:ce,containerStyle:i,onReady:()=>{Xe(()=>pe.current?.())},onValidation:J=>{Xe(()=>we.current?.(J))},onError:J=>{if(!J)return;j.current&&(j.current=!1,ae(J),x("error"),setTimeout(()=>x(null),Qt));let ne=Ri(new Error(J),{code:"card_setup_widget_failed",retryable:!0});Xe(()=>De.current?.(ne))}})]})}var Ii=require("@flopay/js"),_i=require("@flopay/shared"),Cn=require("react");var vn=require("react/jsx-runtime");function xi({sessionId:e,nonce:t,billingApiUrl:n,email:a,userId:r,firstName:i,lastName:u,chv:d,onTokenizedBody:b,onComplete:M,onErrorChange:g,isProcessing:R=!1}){let C=gn(),k=io(),p=so(),[h,E]=(0,Cn.useState)(!1),[_,f]=(0,Cn.useState)(!1),ge=(0,Cn.useRef)(!1),x=(n||p).replace(/\/+$/,""),oe=(0,Cn.useCallback)(async K=>{try{let pe=await new Ii.PaymentAPI(x).processPayment(r??"",{sessionId:e,nonce:t,tokenizedData:K,accountData:{userId:r??"",email:a??"",firstName:i??"",lastName:u??""},chv:d});if(pe.ok){M?.();return}let De=await pe.json().catch(()=>null);g?.(De?.message??"Payment failed. Please try again.")}catch(ce){g?.(ce instanceof Error?ce.message:"An unexpected error occurred")}},[x,e,t,r,a,i,u,d,M,g]),ae=(0,Cn.useCallback)(K=>{b?b(K):oe(K)},[b,oe]);(0,Cn.useEffect)(()=>{if(!C||ge.current)return;let K=new URLSearchParams(window.location.search),ce=K.get("payment_intent"),pe=K.get("payment_intent_client_secret"),De=K.get("redirect_status");!ce||!pe||(ge.current=!0,(async()=>{try{if(f(!0),De==="failed"){g?.("PayPal payment was declined. Please try again.");return}let P=C.getRawProvider();if(!P?.retrievePaymentIntent){g?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ie,error:Le}=await P.retrievePaymentIntent(pe);if(Le){g?.(Le.message??"Failed to retrieve PayPal payment status.");return}if(ie&&(ie.status==="requires_capture"||ie.status==="succeeded")){let we=typeof ie.payment_method=="string"?ie.payment_method:ie.payment_method?.id;ae({id:we??ie.id,type:"card",threeDSecureActionResultTokenId:ie.id,isPaypal:!0});let he=new URL(window.location.href);he.searchParams.delete("payment_intent"),he.searchParams.delete("payment_intent_client_secret"),he.searchParams.delete("redirect_status"),window.history.replaceState({},"",he.toString())}else g?.("PayPal payment was not completed. Please try again.")}catch(P){g?.(P instanceof Error?P.message:"Failed to complete PayPal payment.")}finally{f(!1)}})())},[C,ae,g]);let j=(0,Cn.useCallback)(async()=>{if(!(!C||!k))try{if(f(!0),g?.(null),!e||!a)throw new _i.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let K=await C.confirmPayPalPayment({billingApiUrl:x,sessionId:e,nonce:t,email:a,returnUrl:window.location.href});if(K.error){g?.(K.error.message);return}K.paymentIntentId&&(K.status==="succeeded"||K.status==="processing"||K.status==="requires_capture")&&ae({id:K.paymentMethodId??K.paymentIntentId,type:"card",threeDSecureActionResultTokenId:K.paymentIntentId,isPaypal:!0})}catch(K){g?.(K instanceof Error?K.message:"PayPal payment failed. Please try again.")}finally{f(!1)}},[C,k,e,t,a,x,ae,g]);return!C||!k?(0,vn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,vn.jsxs)(vn.Fragment,{children:[!h&&(0,vn.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,vn.jsx)("div",{style:h?{}:{display:"none"},children:(0,vn.jsx)("button",{type:"button",onClick:j,disabled:_||R,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:_||R?"not-allowed":"pointer",opacity:_||R?.6:1},ref:()=>E(!0),children:_?"Processing...":"PayPal"})}),(_||R)&&(0,vn.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,vn.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 $e=require("react"),Io=require("@flopay/js"),tn=require("@flopay/shared");var Sn=require("react/jsx-runtime"),Ys=44;function Ti(e){return new Promise(t=>setTimeout(t,e))}function Ws(e,t){return e instanceof tn.FloPayError?e:new tn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Gs(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Js(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function Mi({sessionId:e,nonce:t,createSession:n,paymentMethodId:a,checkoutMethod:r,clientId:i,products:u,items:d,subscriptions:b,account:M,successUrl:g,cancelUrl:R,couponCodes:C,tagsData:k,utmMetadata:p,billingApiUrl:h,locale:E,theme:_,appearance:f,buttonsTheme:ge,buttonsStyles:x,onSuccess:oe,onError:ae,onDecline:j,children:K,disabled:ce=!1,type:pe="button",style:De,...P}){let ie=(0,$e.useMemo)(()=>(0,tn.resolveBillingApiUrl)(h),[h]),Le=(0,$e.useMemo)(()=>Js({createSession:n,clientId:i,products:u,items:d,subscriptions:b,account:M,successUrl:g,cancelUrl:R,couponCodes:C,tagsData:k,utmMetadata:p}),[M,R,i,C,n,u,d,b,g,k,p]),[we,he]=(0,$e.useState)(!1),[Z,me]=(0,$e.useState)(null),[J,ne]=(0,$e.useState)(null),[ke,xe]=(0,$e.useState)(!1),[se,W]=(0,$e.useState)(null),S=(0,$e.useRef)(!0),de=(0,$e.useRef)(null),Qe=(0,$e.useRef)(se),Ve=(0,$e.useRef)(oe),ue=(0,$e.useRef)(ae),L=(0,$e.useRef)(j);(0,$e.useEffect)(()=>{Qe.current=se},[se]),(0,$e.useEffect)(()=>{Ve.current=oe},[oe]),(0,$e.useEffect)(()=>{ue.current=ae},[ae]),(0,$e.useEffect)(()=>{L.current=j},[j]),(0,$e.useEffect)(()=>(S.current=!0,()=>{S.current=!1,de.current?.abort()}),[]),(0,$e.useEffect)(()=>{if(typeof window>"u")return;let T=Ce=>{Ce.key==="Escape"&&W(null)};return window.addEventListener("keydown",T),()=>{window.removeEventListener("keydown",T)}},[]);let Pe=(0,$e.useCallback)((T,Ce=$r)=>{L.current?.(Et(Ce,T,{code:T.code,declineCode:T.declineCode}))},[]),X=(0,$e.useCallback)(async T=>{S.current&&(ne(null),xe(T.result.status==="authorized"),me("success"),await Ti(hn),S.current&&Ve.current?.(T))},[]),be=(0,$e.useCallback)(async(T,Ce)=>{S.current&&(ue.current?.(T),Ce?.emitDecline&&Pe(T,Ce.method),ne(T.message),xe(!1),me("error"),await Ti(Qt))},[Pe]),rt=(0,$e.useCallback)(async(T,Ce,et)=>{let tt=T.data.session??null;if(!tt)throw new tn.FloPayError("No session data returned","api_error");let It=tt.clientSecret||t;if(hr(tt)){await X({result:er(tt,Ce),session:tt,sessionId:tt.id||Ce,autoCompleted:!1});return}if(tt.status==="expired")throw lo(tt);try{if(T.autoProcessingPending){let Fe=(await new Io.PaymentAPI(ie).waitForCheckoutSessionCompletion(T.autoProcessingPending.sessionId,{initialDelayMs:T.autoProcessingPending.retryAfterMs})).data.session;if(!hr(Fe))throw co(Fe);await X({result:er(Fe,Ce),session:Fe,sessionId:Fe.id||Ce,autoCompleted:!1});return}if(T.autoProcessingError){if(T.autoProcessingError.type==="3ds_required"&&T.autoProcessingError.nextActionRedirectUrl&&Ce&&It){let Oe=new AbortController;de.current=Oe;let gt;try{gt=await fi({billingApiUrl:ie,sessionId:Ce,nonce:It,nextActionRedirectUrl:T.autoProcessingError.nextActionRedirectUrl,signal:Oe.signal})}finally{de.current===Oe&&(de.current=null)}if(gt.status==="declined")throw Kn({type:gt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:gt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:T.autoProcessingError.checkoutMethod});let Ye=(await new Io.PaymentAPI(ie).waitForCheckoutSessionCompletion(Ce,{initialDelayMs:0,nonce:It})).data.session;if(!hr(Ye))throw Kn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:T.autoProcessingError.checkoutMethod});await X({result:er(Ye,Ce),session:Ye,sessionId:Ye.id||Ce,autoCompleted:!1});return}throw Kn(T.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:T.autoProcessingError.checkoutMethod})}if(et?.fromCreateSession&&T.autoProcessingAttempted===!0)throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ft=await Cr({billingApiUrl:ie,sessionId:Ce??tt.id,session:tt,nonce:It});if(ft.type!=="success")throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await X({result:ft.result,session:tt,sessionId:tt.id||Ce,autoCompleted:!1})}catch(ft){let Oe=nr(ft),gt=tt.id||Ce;await be(Oe,{emitDecline:!0,method:Oe.checkoutMethod??$r}),Gs(Oe,gt)&>&&S.current&&W({sessionId:gt,errorMessage:Oe.message,nonce:It||void 0})}},[t,ie,be,X]),qe=(0,$e.useCallback)(async T=>{if(P.onClick?.(T),!(T.defaultPrevented||ce||we)){if(W(null),e&&Le){let Ce=new tn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await be(Ce),S.current&&(me(null),ne(null));return}if(!e&&!Le){let Ce=new tn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await be(Ce),S.current&&(me(null),ne(null));return}he(!0),ne(null),xe(!1),me("processing");try{let Ce=new Io.PaymentAPI(ie);if(e){let et=await Ce.getUnifiedCheckoutSession(e,t);await rt(et,e);return}try{let et=await Ce.createAndFetchSession({...Le});await rt(et,et.data.session?.id??null,{fromCreateSession:!0})}catch(et){if(et instanceof tn.FloPayError&&et.code==="session_auto_completed"){await X({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw et}}catch(Ce){await be(Ws(Ce,"Automatic payment failed. Please try again."))}finally{S.current&&(me(null),ne(null),he(!1))}}},[P,Le,ce,we,t,rt,ie,e,be,X]),ct=(0,$e.useCallback)(T=>{let Ce=Qe.current;W(null),Ve.current?.({result:T,session:null,sessionId:Ce?.sessionId??null,autoCompleted:!1})},[]),ve=(0,$e.useCallback)(T=>{ue.current?.(T)},[]),re=(0,$e.useCallback)(T=>{L.current?.(T)},[]),ot=(0,$e.useMemo)(()=>(0,tn.resolveTheme)(_),[_]),ee=(0,$e.useMemo)(()=>{let T=ot?.buttonsLayout??(0,tn.resolveButtonsLayoutTheme)(ge);return x?{...T,...x,cardButton:{...T.cardButton,...x.cardButton}}:T},[ot,ge,x]),yt=(0,$e.useMemo)(()=>{let T=ot?.appearance;return f?T?{...T,...f,variables:{...T.variables,...f.variables}}:f:T},[f,ot]),He=yt?.variables,Ke=He?.colorPrimary??"#4A49FF",Nt=He?.colorPrimaryHover??pr(Ke,.12),at=He?.borderRadius??"8px";return(0,Sn.jsxs)(Sn.Fragment,{children:[(0,Sn.jsx)("button",{...P,type:pe,onClick:qe,disabled:ce||we,"aria-busy":we,style:{width:"100%",...K===void 0?{boxSizing:"border-box",height:Ys,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...ee.cardButton,...Xo({themeBundle:ot,resolvedPrimaryColor:Ke,resolvedBorderRadius:at,submitButtonStyle:ee.submitButton,explicitPrimaryColor:He?.colorPrimary}),fontSize:ee.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ce||we?"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||we?.6:1,...De},onMouseEnter:T=>{P.onMouseEnter?.(T),!T.defaultPrevented&&!ce&&!we&&(ot||He?.colorPrimary)&&(T.currentTarget.style.backgroundColor=Nt)},onMouseLeave:T=>{P.onMouseLeave?.(T),!T.defaultPrevented&&(ot||He?.colorPrimary)&&(T.currentTarget.style.backgroundColor=Ke)},onMouseDown:T=>{P.onMouseDown?.(T),T.defaultPrevented||(T.currentTarget.style.transform="scale(0.985)")},onMouseUp:T=>{P.onMouseUp?.(T),T.defaultPrevented||(T.currentTarget.style.transform="scale(1)")},children:(0,Sn.jsx)(dr,{content:K})}),Z&&(0,Sn.jsx)(cn,{status:Z,errorMessage:J,authorized:ke}),se&&(0,Sn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:T=>{T.target===T.currentTarget&&W(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,Sn.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,Sn.jsx)(Ro,{sessionId:se.sessionId,nonce:se.nonce,checkoutMode:"full",billingApiUrl:ie,locale:E,theme:_,...yt?{appearance:yt}:{},buttonsTheme:ge,buttonsStyles:x,initialErrorMessage:se.errorMessage,cardTitleContent:null,onComplete:ct,onError:ve,onDecline:re})})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useElements,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}return(0,I.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&Q(Ir),n&&(o||r)&&Q(Ir),n&&(0,I.jsx)("button",{type:"button",onClick:()=>{e?.("card"),A(!0)},style:{width:"100%",...J,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:y.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,...y.cardButton},onMouseDown:w=>{w.currentTarget.style.transform="scale(0.985)"},onMouseUp:w=>{w.currentTarget.style.transform="scale(1)"},children:(0,I.jsx)(mr,{content:R})}),(0,I.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var En=require("react/jsx-runtime"),el=44;function Di(e){return new Promise(t=>setTimeout(t,e))}function tl(e,t){return e instanceof on.FloPayError?e:new on.FloPayError(e instanceof Error?e.message:t,"api_error")}function nl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function rl(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 Li({sessionId:e,nonce:t,createSession:n,paymentMethodId:o,checkoutMethod:r,clientId:i,products:m,items:d,subscriptions:R,account:g,successUrl:v,cancelUrl:b,couponCodes:A,tagsData:D,utmMetadata:y,billingApiUrl:C,locale:Q,theme:J,appearance:w,buttonsTheme:ge,buttonsStyles:U,onSuccess:ee,onError:re,onDecline:be,children:oe,disabled:he=!1,type:ze="button",style:_e,...Se}){let K=(0,Me.useMemo)(()=>(0,on.resolveBillingApiUrl)(C),[C]),O=(0,Me.useMemo)(()=>rl({createSession:n,clientId:i,products:m,items:d,subscriptions:R,account:g,successUrl:v,cancelUrl:b,couponCodes:A,tagsData:D,utmMetadata:y}),[g,b,i,A,n,m,d,R,v,D,y]),[ae,Ue]=(0,Me.useState)(!1),[Te,X]=(0,Me.useState)(null),[$,te]=(0,Me.useState)(null),[pe,ve]=(0,Me.useState)(!1),[Z,Re]=(0,Me.useState)(null),H=(0,Me.useRef)(!0),_=(0,Me.useRef)(null),me=(0,Me.useRef)(Z),We=(0,Me.useRef)(ee),$e=(0,Me.useRef)(re),ce=(0,Me.useRef)(be);(0,Me.useEffect)(()=>{me.current=Z},[Z]),(0,Me.useEffect)(()=>{We.current=ee},[ee]),(0,Me.useEffect)(()=>{$e.current=re},[re]),(0,Me.useEffect)(()=>{ce.current=be},[be]),(0,Me.useEffect)(()=>(H.current=!0,()=>{H.current=!1,_.current?.abort()}),[]),(0,Me.useEffect)(()=>{if(typeof window>"u")return;let T=Pe=>{Pe.key==="Escape"&&Re(null)};return window.addEventListener("keydown",T),()=>{window.removeEventListener("keydown",T)}},[]);let B=(0,Me.useCallback)((T,Pe=Hr)=>{ce.current?.(xt(Pe,T,{code:T.code,declineCode:T.declineCode}))},[]),ie=(0,Me.useCallback)(async T=>{H.current&&(te(null),ve(T.result.status==="authorized"),X("success"),await Di(1200),H.current&&We.current?.(T))},[]),G=(0,Me.useCallback)(async(T,Pe)=>{H.current&&($e.current?.(T),Pe?.emitDecline&&B(T,Pe.method),te(T.message),ve(!1),X("error"),await Di(1500))},[B]),Oe=(0,Me.useCallback)(async(T,Pe,ft)=>{let Ne=T.data.session??null;if(!Ne)throw new on.FloPayError("No session data returned","api_error");let qt=Ne.clientSecret||t;if(gr(Ne)){await ie({result:ar(Ne,Pe),session:Ne,sessionId:Ne.id||Pe,autoCompleted:!1});return}if(Ne.status==="expired")throw uo(Ne);try{if(T.autoProcessingPending){let et=(await new Fo.PaymentAPI(K).waitForCheckoutSessionCompletion(T.autoProcessingPending.sessionId,{initialDelayMs:T.autoProcessingPending.retryAfterMs})).data.session;if(!gr(et))throw po(et);await ie({result:ar(et,Pe),session:et,sessionId:et.id||Pe,autoCompleted:!1});return}if(T.autoProcessingError){if(T.autoProcessingError.type==="3ds_required"&&T.autoProcessingError.nextActionRedirectUrl&&Pe&&qt){let Ze=new AbortController;_.current=Ze;let Ct;try{Ct=await ui({billingApiUrl:K,sessionId:Pe,nonce:qt,nextActionRedirectUrl:T.autoProcessingError.nextActionRedirectUrl,signal:Ze.signal})}finally{_.current===Ze&&(_.current=null)}if(Ct.status==="declined")throw Xn({type:Ct.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ct.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:T.autoProcessingError.checkoutMethod});let Ge=(await new Fo.PaymentAPI(K).waitForCheckoutSessionCompletion(Pe,{initialDelayMs:0,nonce:qt})).data.session;if(!gr(Ge))throw Xn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:T.autoProcessingError.checkoutMethod});await ie({result:ar(Ge,Pe),session:Ge,sessionId:Ge.id||Pe,autoCompleted:!1});return}throw Xn(T.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:T.autoProcessingError.checkoutMethod})}if(ft?.fromCreateSession&&T.autoProcessingAttempted===!0)throw Xn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Gt=await Sr({billingApiUrl:K,sessionId:Pe??Ne.id,session:Ne,nonce:qt});if(Gt.type!=="success")throw Xn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await ie({result:Gt.result,session:Ne,sessionId:Ne.id||Pe,autoCompleted:!1})}catch(Gt){let Ze=lr(Gt),Ct=Ne.id||Pe;await G(Ze,{emitDecline:!0,method:Ze.checkoutMethod??Hr}),nl(Ze,Ct)&&Ct&&H.current&&Re({sessionId:Ct,errorMessage:Ze.message,nonce:qt||void 0})}},[t,K,G,ie]),Be=(0,Me.useCallback)(async T=>{if(Se.onClick?.(T),!(T.defaultPrevented||he||ae)){if(Re(null),e&&O){let Pe=new on.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await G(Pe),H.current&&(X(null),te(null));return}if(!e&&!O){let Pe=new on.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await G(Pe),H.current&&(X(null),te(null));return}Ue(!0),te(null),ve(!1),X("processing");try{let Pe=new Fo.PaymentAPI(K);if(e){let ft=await Pe.getUnifiedCheckoutSession(e,t);await Oe(ft,e);return}try{let ft=await Pe.createAndFetchSession({...O});await Oe(ft,ft.data.session?.id??null,{fromCreateSession:!0})}catch(ft){if(ft instanceof on.FloPayError&&ft.code==="session_auto_completed"){await ie({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw ft}}catch(Pe){await G(tl(Pe,"Automatic payment failed. Please try again."))}finally{H.current&&(X(null),te(null),Ue(!1))}}},[Se,O,he,ae,t,Oe,K,e,G,ie]),Qe=(0,Me.useCallback)(T=>{let Pe=me.current;Re(null),We.current?.({result:T,session:null,sessionId:Pe?.sessionId??null,autoCompleted:!1})},[]),se=(0,Me.useCallback)(T=>{$e.current?.(T)},[]),yt=(0,Me.useCallback)(T=>{ce.current?.(T)},[]),j=(0,Me.useMemo)(()=>(0,on.resolveTheme)(J),[J]),qe=(0,Me.useMemo)(()=>{let T=j?.buttonsLayout??(0,on.resolveButtonsLayoutTheme)(ge);return U?{...T,...U,cardButton:{...T.cardButton,...U.cardButton}}:T},[j,ge,U]),Pt=(0,Me.useMemo)(()=>{let T=j?.appearance;return w?T?{...T,...w,variables:{...T.variables,...w.variables}}:w:T},[w,j]),Y=Pt?.variables,bt=Y?.colorPrimary??"#4A49FF",Ke=Y?.colorPrimaryHover??kr(bt,.12),Qt=Y?.borderRadius??"8px";return(0,En.jsxs)(En.Fragment,{children:[(0,En.jsx)("button",{...Se,type:ze,onClick:Be,disabled:he||ae,"aria-busy":ae,style:{width:"100%",...oe===void 0?{boxSizing:"border-box",height:el,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...qe.cardButton,...sa({themeBundle:j,resolvedPrimaryColor:bt,resolvedBorderRadius:Qt,submitButtonStyle:qe.submitButton,explicitPrimaryColor:Y?.colorPrimary}),fontSize:qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:he||ae?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:he||ae?.6:1,..._e},onMouseEnter:T=>{Se.onMouseEnter?.(T),!T.defaultPrevented&&!he&&!ae&&(j||Y?.colorPrimary)&&(T.currentTarget.style.backgroundColor=Ke)},onMouseLeave:T=>{Se.onMouseLeave?.(T),!T.defaultPrevented&&(j||Y?.colorPrimary)&&(T.currentTarget.style.backgroundColor=bt)},onMouseDown:T=>{Se.onMouseDown?.(T),T.defaultPrevented||(T.currentTarget.style.transform="scale(0.985)")},onMouseUp:T=>{Se.onMouseUp?.(T),T.defaultPrevented||(T.currentTarget.style.transform="scale(1)")},children:(0,En.jsx)(mr,{content:oe})}),Te&&(0,En.jsx)(vn,{status:Te,errorMessage:$,authorized:pe}),Z&&(0,En.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:T=>{T.target===T.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:(0,En.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,En.jsx)(Bo,{sessionId:Z.sessionId,nonce:Z.nonce,checkoutMode:"full",billingApiUrl:K,locale:Q,theme:J,...Pt?{appearance:Pt}:{},buttonsTheme:ge,buttonsStyles:U,initialErrorMessage:Z.errorMessage,cardTitleContent:null,onComplete:Qe,onError:se,onDecline:yt})})})]})}var Do=require("@flopay/js/card-setup"),an=require("@flopay/shared"),ot=require("react");var Dn=require("react/jsx-runtime"),Xr=class extends an.FloPayError{constructor(t,n,o){super(t,n,o),this.name="FloPayCardSetupError",this.retryable=o.retryable}};function Oi(e,t={}){let n=e instanceof an.FloPayError?e:void 0,o=n?.statusCode,r=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof o=="number"&&o>=500||n?.code==="vault_capture_timeout"||!n);return new Xr(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:r,...n?.param?{param:n.param}:{},...o!==void 0?{statusCode:o}:{}})}function Ni({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,theme:r="modern-light",containerStyle:i,loading:m=null,onReady:d,onComplete:R,onDecline:g,onCancel:v,onValidation:b,onError:A}){let[D,y]=(0,ot.useState)(null),[C,Q]=(0,ot.useState)(null),[J,w]=(0,ot.useState)(null),[ge,U]=(0,ot.useState)(null),[ee,re]=(0,ot.useState)(null),be=(0,ot.useRef)(!1),oe=(0,ot.useRef)(!1),he=(0,ot.useMemo)(()=>{if(typeof r=="object")return r;let $=(0,an.resolveTheme)(r);if($)return Io({appearance:$.appearance,buttonsStyles:$.buttonsLayout,layout:"default"})},[r]),ze=(0,ot.useRef)(d),_e=(0,ot.useRef)(A),Se=(0,ot.useRef)(R),K=(0,ot.useRef)(g),O=(0,ot.useRef)(v),ae=(0,ot.useRef)(b),Ue=(0,ot.useRef)(!1),Te=(0,ot.useRef)(!1),X=(0,ot.useRef)(0);return ze.current=d,_e.current=A,Se.current=R,K.current=g,O.current=v,ae.current=b,(0,ot.useEffect)(()=>{let $=X.current+1;return X.current=$,()=>{queueMicrotask(()=>{X.current===$&&(Ue.current||Te.current||(Te.current=!0,Le(()=>{O.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,ot.useEffect)(()=>{let $=!0,te=new Do.PaymentAPI((0,an.resolveBillingApiUrl)(n),{telemetry:o});return y(null),Q(null),w(null),Ue.current=!1,Te.current=!1,(async()=>{try{if(!e.trim())throw new an.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new an.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let pe=await te.getUnifiedCheckoutSession(e,t);if(!$)return;let ve=pe.data.session;if(!ve||!(0,an.isCardSetupCheckoutSession)(ve))throw new an.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Z=ve.vault;if(Z?.html?.trim()||(Z=await te.getVaultCapture(e,t)),!Z.html?.trim())throw new an.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!$)return;Q(Z),y(new Do.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:o}))}catch(pe){if(!$)return;let ve=Oi(pe);Ue.current=!0,w(ve),Le(()=>_e.current?.(ve))}})(),()=>{$=!1,te.destroy()}},[n,t,e,o]),(0,ot.useEffect)(()=>{if(!D)return;let $=!1;oe.current=!1,be.current=!1;let te=D.on("submitting",()=>{be.current=!0,re(null),U("processing")}),pe=D.on("complete",Z=>{Ue.current=!0,be.current=!1,U("success"),(async()=>(await new Promise(Re=>setTimeout(Re,1200)),!oe.current&&(oe.current=!0,Le(()=>{Se.current?.({status:"succeeded",sessionId:e,...Z.paymentMethod?{paymentMethod:Z.paymentMethod}:{}})}),$||U(null))))()}),ve=D.on("decline",Z=>{Ue.current=!0,be.current=!1,re(Z.message??null),U("error"),Le(()=>{K.current?.({status:"declined",sessionId:e,...Z.declineReason?{reason:Z.declineReason}:{},...Z.message?{message:Z.message}:{}})}),(async()=>(await new Promise(Re=>setTimeout(Re,1500)),$||U(null)))()});return()=>{$=!0,te(),pe(),ve()}},[D,e]),J?(0,Dn.jsx)("div",{role:"alert",children:J.message}):!D||!C?.html?(0,Dn.jsx)(Dn.Fragment,{children:m}):(0,Dn.jsxs)(Dn.Fragment,{children:[ge&&(0,Dn.jsx)(vn,{status:ge,errorMessage:ee,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,Dn.jsx)(wr,{capture:D,html:C.html,messageToken:C.messageToken,expectedOrigin:C.expectedOrigin,theme:he,containerStyle:i,onReady:()=>{Le(()=>ze.current?.())},onValidation:$=>{Le(()=>ae.current?.($))},onError:$=>{if(!$)return;be.current&&(be.current=!1,re($),U("error"),setTimeout(()=>U(null),1500));let te=Oi(new Error($),{code:"card_setup_widget_failed",retryable:!0});Le(()=>_e.current?.(te))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|