@flopay/react 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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 ys=Object.create;var mo=Object.defineProperty;var fs=Object.getOwnPropertyDescriptor;var gs=Object.getOwnPropertyNames;var hs=Object.getPrototypeOf,Ps=Object.prototype.hasOwnProperty;var vs=(e,t)=>{for(var n in t)mo(e,n,{get:t[n],enumerable:!0})},Xa=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of gs(t))!Ps.call(e,o)&&o!==n&&mo(e,o,{get:()=>t[o],enumerable:!(r=fs(t,o))||r.enumerable});return e};var Za=(e,t,n)=>(n=e!=null?ys(hs(e)):{},Xa(t||!e||!e.__esModule?mo(n,"default",{value:e,enumerable:!0}):n,e)),bs=e=>Xa(mo({},"__esModule",{value:!0}),e);var fl={};vs(fl,{AddressElement:()=>ji,DirectPayPalButton:()=>Kr,FloPayAutomaticPaymentButton:()=>Ui,FloPayCardSetup:()=>Hi,FloPayCardSetupError:()=>eo,FloPayCheckout:()=>No,FloPayProvider:()=>Yr,PayPalButton:()=>Gi,PaymentElement:()=>qi,SplitCardForm:()=>Bo,VaultCardFields:()=>Rr,dropThirdPartyOnlyError:()=>Ji.dropThirdPartyOnlyError,useCheckout:()=>ai,useElements:()=>Po,useFloPay:()=>In,usePayPalFloPay:()=>ho});module.exports=bs(fl);var Cs=()=>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,Ae=Cs();var Ji=require("@flopay/shared");var zo=require("@flopay/js"),an=require("@flopay/shared"),De=require("react");var ct=require("react/jsx-runtime");function Ss(){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 ws(){return(0,ct.jsx)(ct.Fragment,{children:"Go back"})}function ks(){return(0,ct.jsx)(ct.Fragment,{children:"Secure card checkout"})}function fr(e){return e!==void 0&&(e===""||e===null||e===!1)}function gr({content:e}){return(0,ct.jsx)(ct.Fragment,{children:e===void 0?(0,ct.jsx)(Ss,{}):e})}function hr({content:e}){return(0,ct.jsx)(ct.Fragment,{children:e===void 0?(0,ct.jsx)(ws,{}):e})}function qr({content:e}){return(0,ct.jsx)(ct.Fragment,{children:e===void 0?(0,ct.jsx)(ks,{}):e})}var Pr=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 Qo(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ei(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,p)=>a+(p.overrideAmount??p.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,p)=>({uuid:`synthetic-${a.type??"item"}-${p}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function ea(e,t){return t?{...e,...t}:e}function Mt(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var Is=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Xn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Is)if(n.test(t))return r;return e}function sr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function vr(e){return e?.status==="authorized"||e?.status==="complete"}function ti(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function yo(e){let t=ti(e);return new Pr.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function fo(e){let t=ti(e);return new Pr.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 go(e,t){return e==="processing"||(0,Pr.isMoneySettledOutcome)(e,t)}function ni(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function ri(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function jr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var ur=require("@flopay/js"),ge=require("@flopay/shared"),_=Za(require("react"),1);var ta=require("react"),Wt=(0,ta.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),kn=(0,ta.createContext)({session:null,loading:!1,error:null});var wo=require("@flopay/js"),Gt=require("@flopay/shared"),ci=require("@paypal/paypal-js"),z=require("react");function Es(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 lr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function jn(e){if(typeof e!="object"||e===null)return;let t=e;return lr(t.code)??lr(t.type)??lr(t.name)}function br(e){if(!(typeof e!="object"||e===null))return lr(e.decline_code)}function Vr(e){return typeof e!="object"||e===null?!1:lr(e.type)?.toLowerCase()==="card_error"||br(e)!==void 0}function Zn(e){let t=Es(e)?.toLowerCase()??"",r=`${jn(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var oi=require("@flopay/shared"),Cr=require("react");function In(){return(0,Cr.useContext)(Wt).flopay}function ho(){return(0,Cr.useContext)(Wt).paypalFlopay??null}function Po(){return(0,Cr.useContext)(Wt).elements}function ai(){return(0,Cr.useContext)(kn)}function vo(){return(0,Cr.useContext)(Wt).billingApiUrl||(0,oi.resolveBillingApiUrl)()}var ii=require("@flopay/shared"),cr=require("react");function Ne(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 bo=require("react"),Co=typeof window>"u"?bo.useEffect:bo.useLayoutEffect;var Rs={"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 _s(e){return e==="stripe"||e==="paypal"?e:void 0}function xs(e){let t=_s(e.provider),n={schemaVersion:ii.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Rs[e.name];return r?{...n,name:r}: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 na=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Sr(e,t){let n=(0,cr.useRef)(e);n.current=e;let r=(0,cr.useRef)(new Set),o=(0,cr.useRef)(t),a=(0,cr.useRef)(t);return Co(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,cr.useCallback)(p=>{if(a.current!==t)return;let d=xs(p);if(d){if(na.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}Ne(()=>n.current?.(d))}},[t])}var Ts=Symbol.for("@flopay/js.telemetry.bridge.v1"),As=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ms(){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 Fs(e){let t=Ms(),n=(o,a)=>o?o.bind(e):a,r=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:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),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 So(e){let t=globalThis[As];return Fs(t?.(e)??{})}function Tt(e){if(e)return e[Ts]}var En=require("react/jsx-runtime"),ko=45,Bs=1e3,Ds=11e3,Ls=["https://www.paypal.com","https://www.sandbox.paypal.com"],si="We couldn't open PayPal. Try again or choose another payment method.",Os={width:"100%",minHeight:ko,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function li(e){return e.includes("No ack for postMessage init()")&&Ls.some(t=>e.includes(t))&&e.includes("10000ms")}function Ns(e){return e?`${si} Allow pop-ups for this site, then try again.`:si}function di({sessionId:e,nonce:t,billingApiUrl:n,email:r,clientId:o,environment:a,currency:p,isSubscription:d,providerObjectType:I,onTokenizedBody:g,onComplete:h,onErrorChange:k,onDecline:w,onTechnicalFailure:x,isProcessing:y=!1,onLoadStateChange:v,onInitializationStateChange:H,allowAutomaticRetry:M=!0,onButtonClick:f,runBeforeButtonClick:ie,session:O,existingOrderId:Z,telemetry:Q,telemetryContext:ve,onInstrument:B,debug:se=!1}){let xe=In(),Se=Sr(B,e),he=(0,z.useMemo)(()=>{if(xe)return null;let F=So({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Gt.SDK_VERSION,enabled:Q!==!1});return F.setCheckoutContext(ve??{}),F.beginCheckout(ve??{}),F},[n,xe,Q,ve?.checkoutMode,ve?.layout]),$=(0,z.useMemo)(()=>Tt(xe),[xe]);(0,z.useEffect)(()=>()=>{he&&he.flush().catch(()=>{}).finally(()=>he.destroy())},[he]);let N=(0,z.useMemo)(()=>({error:F=>{$?$.error(F):he?.error(F),Se({class:"technical_error",errorCode:F.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":F.errorCode,requestCategory:F.requestCategory,provider:F.provider})},log:F=>{$?$.log(F):he?.log(F),Se({class:"lifecycle",name:F.name,provider:F.provider})},performance:F=>{$?$.performance(F):he?.performance(F)},terminal:F=>{$?$.terminal(F):he?.terminal(F)},startTiming:()=>$?.now()??he?.now()??0,elapsed:F=>$?.elapsed(F)??Math.max(0,(he?.now()??F)-F)}),[Se,$,he]),oe=(0,z.useRef)(null),Me=(0,z.useRef)(0),Te=(0,z.useRef)(null),te=(0,z.useRef)(!1),[K,re]=(0,z.useState)(!1),[ye,be]=(0,z.useState)(!1),[ne,_e]=(0,z.useState)(0),G=(0,z.useRef)(0),[T,fe]=(0,z.useState)(!1),$e=(0,z.useRef)(!1),qe=(0,z.useRef)(!1),[ue,L]=(0,z.useState)(!1),[le,ee]=(0,z.useState)(!1),ze=(0,z.useMemo)(()=>n.replace(/\/+$/,""),[n]),Le=I??(d?"subscription":"order"),Qe=I==="order"||I==="setup_token",ce=(0,z.useMemo)(()=>JSON.stringify([ze,o,p,a??"",Le,Qe,e,Z??""]),[ze,o,p,a,Z,Le,Qe,e]),ft=(0,z.useRef)(ce),V=ft.current!==ce,[je,bt]=(0,z.useState)([]),J=F=>{se&&bt(tt=>[...tt,`${new Date().toISOString().slice(11,23)} ${F}`])},Ct=(0,z.useRef)(g),He=(0,z.useRef)(h),en=(0,z.useRef)(k),Rt=(0,z.useRef)(w),A=(0,z.useRef)(x),Ce=(0,z.useRef)(f),gt=(0,z.useRef)(v),Ue=(0,z.useRef)(H),qt=(0,z.useRef)(ie),Jt=(0,z.useRef)(O),Ze=(0,z.useRef)(r),St=(0,z.useRef)(t),et=(0,z.useRef)(null),Ft=(0,z.useRef)(0),Ge=(0,z.useRef)(null),jt=(0,z.useRef)(null),_t=(0,z.useRef)(new Map),tn=(0,z.useRef)(new Map),Dt=(0,z.useRef)(!1);(0,z.useEffect)(()=>(Dt.current=!0,()=>{Dt.current=!1}),[]),(0,z.useEffect)(()=>{Ct.current=g},[g]),(0,z.useEffect)(()=>{He.current=h},[h]),(0,z.useEffect)(()=>{en.current=k},[k]),(0,z.useEffect)(()=>{Rt.current=w},[w]),(0,z.useEffect)(()=>{A.current=x},[x]),(0,z.useEffect)(()=>{Ce.current=f},[f]),(0,z.useEffect)(()=>{gt.current=v},[v]),(0,z.useEffect)(()=>{Ue.current=H},[H]),(0,z.useEffect)(()=>{qt.current=ie},[ie]),(0,z.useEffect)(()=>{Jt.current=O},[O]),(0,z.useEffect)(()=>{Ze.current=r},[r]),(0,z.useEffect)(()=>{St.current=t},[t]),(0,z.useEffect)(()=>{G.current=ne},[ne]),(0,z.useEffect)(()=>{T&&Te.current?.focus()},[T,ne]);let Tn=(0,z.useCallback)(()=>{window.setTimeout(()=>{Te.current?.focus()},0)},[]),ln=(0,z.useCallback)(()=>{re(!1),_e(F=>F+1)},[]),at=(0,z.useCallback)(()=>{fe(!1),(oe.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??oe.current)?.focus?.()},[]);(0,z.useEffect)(()=>{!K||!te.current||(te.current=!1,at())},[at,K,ne]);let Lt=(0,z.useCallback)((F,tt)=>{let Ie=A.current;if(Ie){Ie("paypal",F,tt);return}en.current?.(Ns(tt?.popupBlocked??Zn(F)))},[]),Je=()=>{Ge.current?.timer&&(clearTimeout(Ge.current.timer),Ge.current.timer=null)},An=()=>{Je();let F=Ft.current+1;return Ft.current=F,jt.current=null,Ge.current={generation:F,timer:null,yieldedControl:!1},fe(!1),F},dt=F=>F!==void 0&&Ge.current?.generation!==F?!1:(Je(),Ge.current=null,jt.current=null,!0),bn=F=>{let tt=F?.generation??Ge.current?.generation??Ft.current;(!F?.generation||Ge.current?.generation===tt)&&(Je(),Ge.current=null),jt.current=tt,F?.showRetry&&fe(!0),F?.remount&&ln(),F?.focus!==!1&&Tn()},Ot=F=>Ge.current?.generation===F&&jt.current!==F,me=F=>{typeof document<"u"&&document.visibilityState!=="visible"||(Je(),F.timer=setTimeout(()=>{Ge.current?.generation===F.generation&&(Ge.current=null,jt.current=F.generation,Lt(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),fe(!0),ln(),Tn())},600))},Yn=()=>{let F=Ge.current;F?.yieldedControl&&me(F)},Mn=()=>{let F=Ge.current;F&&(F.yieldedControl=!0,Je())},Fn=F=>{let tt=et.current;return tt&&tn.current.set(F,tt),F};(0,z.useEffect)(()=>{let F=()=>{document.visibilityState==="visible"?Yn():Mn()};return document.addEventListener("visibilitychange",F),window.addEventListener("focus",Yn),window.addEventListener("blur",Mn),()=>{document.removeEventListener("visibilitychange",F),window.removeEventListener("focus",Yn),window.removeEventListener("blur",Mn),Je()}},[]),(0,z.useEffect)(()=>{ft.current!==ce&&(ft.current=ce,$e.current=!1,qe.current=!1,re(!1),be(!1),L(!1),Ue.current?.("loading"))},[ce]),(0,z.useEffect)(()=>{Ne(()=>gt.current?.(K&&!ue))},[K,ue]);let Bn=(0,Gt.normalizeGatewayEnvironment)(a);(0,z.useEffect)(()=>{let F=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",tt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(J(`mount clientId=${F} env=${a??"(unset)"}\u2192${Bn??"live"} ccy=${p} sub=${d}`),J(`ua=${tt.slice(0,80)}${tt.length>80?"\u2026":""}`),!o){J("FAIL: clientId empty \u2014 gateway misconfigured"),L(!0),N.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!oe.current){J("FAIL: containerRef not attached");return}Me.current=N.startTiming(),N.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ie=!1,Cn=!1,Ve=()=>Ie||Cn,Wn,tr=!1,Vt=()=>{Wn=(0,Gt.generateIdempotencyKey)(),Wn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),tr=!0},ut=null,Xt=!1,Kt=null,it=!1,cn=()=>{!Kt||it||(it=!0,Kt.close().catch(()=>{}))},dn=null,Gn=()=>{dn!==null&&(N.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"overlay_return",durationMs:N.elapsed(dn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),dn=null)},Sn=!1,nn=oe.current,un=null,we=null,wt=[],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)}`},rn=u=>{if(!u)return"(empty)";try{let c=new URL(u,typeof window<"u"?window.location.href:"https://localhost"),m=c.pathname.toLowerCase();return m.includes("checkcaptcha")||m.includes("captcha")?`CAPTCHA(${c.host}${m})`:m.includes("risk")||m.includes("challenge")?`RISK(${c.host}${m})`:m.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${m}`.slice(0,100)}catch{return u.slice(0,80)}},pn=u=>{let c=u.getAttribute("src"),m=u.getAttribute("srcdoc"),q=u.getAttribute("name"),ae=u.getAttribute("sandbox"),Y=[];return c&&Y.push(`src=${rn(c)}`),m&&Y.push(`srcdoc[${m.length}ch]`),!c&&!m&&Y.push("src=(empty) srcdoc=(empty)"),q&&Y.push(`name=${q.slice(0,40)}`),ae!==null&&Y.push(`sandbox="${ae.slice(0,40)}"`),Y.join(" ")},zn=u=>{if(!(u instanceof HTMLIFrameElement))return"";try{let c=u.contentDocument;if(!c)return"cd=null";let m=c.body?.children.length??0,q=c.body?.innerHTML.length??0,ae=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${m}children,${q}ch] head[${ae}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},mn=[],Nt=u=>{if(Ve())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"))&&(J(`window:error ${c.slice(0,140)}`),mn.push(c))},Ht=u=>{if(Ve())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"))&&(J(`window:rejection ${c.slice(0,140)}`),mn.push(c))};se&&typeof window<"u"&&(window.addEventListener("error",Nt),window.addEventListener("unhandledrejection",Ht));let Yt={value:0};if(se&&typeof PerformanceObserver<"u")try{we=new PerformanceObserver(u=>{if(!Ve())for(let c of u.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;Yt.value+=1;let m=Math.round(c.duration);J(`net ${m}ms ${c.name.slice(0,90)}`)}}),we.observe({type:"resource",buffered:!0})}catch{}let Jn=()=>{for(un?.disconnect(),un=null,we?.disconnect(),we=null;wt.length;)clearTimeout(wt.pop());se&&typeof window<"u"&&(window.removeEventListener("error",Nt),window.removeEventListener("unhandledrejection",Ht))},Un=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")},Dn=u=>{if(Ve()||Un(u))return;let c=Xn(u)??u;Ne(()=>en.current?.(c))},$n=u=>{Ie||(L(!0),u.includes("paypal_ineligible")||N.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",u))},zt=(u,c=!1)=>{if(Ie)return;let m=$e.current||!M;if(Xt)return;Xt=!0,Cn=!0,Jn(),cn();let q=c||li(u);if(q&&M&&!$e.current){$e.current=!0,re(!1),ee(!1),be(!0),Ue.current?.("retrying"),ut=setTimeout(()=>{Ie||_e(ae=>ae+1)},Bs);return}if(q||m){if(re(!1),ee(!1),be(!1),L(!0),Ue.current?.("exhausted"),!qe.current){qe.current=!0;let ae=li(u)?"paypal_init_timeout":c?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",ae)}return}$n(u)};L(!1);let nt=async(u,c=et.current)=>{if(Ve())return;let m=c?.sessionId??e;if(Ct.current){await Ct.current(u,{sessionId:m,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let q=N.startTiming();N.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ae=()=>{N.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"processing",durationMs:N.elapsed(q),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Y=Jt.current,E=c?.accountPatch?.email??Ze.current,C=c?.accountPatch?.userId??Y?.customer?.id??Y?.accountData?.userId??"",S=await new wo.PaymentAPI(ze,{telemetry:!1}).processPayment(C,{sessionId:m,nonce:c?.nonce??St.current,tokenizedData:u,accountData:{userId:C,email:E??Y?.customer?.email??"",firstName:c?.accountPatch?.firstName??Y?.customer?.firstName??Y?.accountData?.firstName??"",lastName:c?.accountPatch?.lastName??Y?.customer?.lastName??Y?.accountData?.lastName??"",country:c?.accountPatch?.country??Y?.customer?.country??Y?.accountData?.country??void 0,zip:c?.accountPatch?.zip??Y?.customer?.zip??Y?.accountData?.zip??void 0}});if(S.ok){if(Cn||Ie&&Dt.current)return;ae(),N.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ne(()=>He.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ve())return;let D=await S.json().catch(()=>null),de=D?.message??"PayPal payment failed.",Pe=Xn(de)??de;ae(),S.status===400&&(typeof D?.declineCode=="string"||!Array.isArray(D?.fields))?N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):S.status===400||S.status===422?N.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):N.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:S.status>=500?"5xx":S.status>=400?"4xx":S.status>=300?"3xx":"unknown",failureCategory:S.status>=500?"server_error":void 0}),Dn(Pe),Ne(()=>Rt.current?.(Mt("paypal",Pe,{code:D?.code,declineCode:D?.declineCode})));return}catch(Y){if(Ve())return;ae(),N.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let E=Y instanceof Error?Y.message:"PayPal payment failed.",C=Xn(E)??E;Dn(C),Ne(()=>Rt.current?.(Mt("paypal",C)));return}},yn=()=>new Gt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ut=u=>Ve()?Promise.reject(yn()):Promise.resolve(u),pt=async u=>{if(Ve())throw yn();tr||Vt();let c=et.current,m=c?.sessionId??e,q=c?.nonce??St.current;N.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ae;try{ae=await new wo.PaymentAPI(ze,{telemetry:!1}).createSessionIntent(m,q??"",Qe?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Gt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:Le==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Wn})}catch(Y){throw N.error({...(0,Gt.classifyTelemetryFailure)(Y,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Y}if(Ve())throw yn();if(ae.provider!=="paypal"||ae.providerObjectType!==Le)throw new Error(u);return N.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ae.providerObjectId},Zt=(u,c)=>{let m=c?.nonce??St.current;if(!m)return;let q=c?.sessionId??e,ae=br(u)??jn(u)??"provider_declined";new wo.PaymentAPI(ze,{telemetry:!1}).reportSessionIntentDecline(q,m,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ae}).catch(()=>{})},xt=ne;J("loadScript:scheduled (deferred 1 tick)");let nr=null,mt=setTimeout(()=>{if(Ie){J("loadScript:skipped (cancelled before defer ran)");return}J("loadScript:start");let u=Bn==="live"?"production":Bn;nr=(0,ci.loadScript)({clientId:o,currency:p,...Le==="subscription"?{intent:"subscription",vault:!0}:Le==="order"?{intent:"capture"}:{},...u?{environment:u}:{},...u==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),nr.then(c=>{if(J(`loadScript:resolved inactive=${Ve()} ns=${!!c} buttons=${!!c?.Buttons}`),Ve())return;if(!c?.Buttons){J("FAIL: namespace missing Buttons factory"),zt("PayPal SDK did not expose the Buttons factory.");return}N.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"provider_ready",durationMs:N.elapsed(Me.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let m=async b=>{if(Ve()||G.current!==xt)return;let S=b.vaultSetupToken??b.subscriptionID??b.orderID??"",D=S?tn.current.get(S):_t.current.get(xt);if(!(!D||!Ot(D.generation))&&dt(D.generation)){tn.current.delete(S),_t.current.delete(D.surfaceKey),Gn();try{if(ee(!0),Ne(()=>en.current?.(null)),!S)throw new Gt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await nt(Le==="setup_token"?{id:S,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Gt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Qe?{id:S,isPaypal:!0,gateway:"paypal",paymentMethodType:Gt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:{id:S,isPaypal:!0},D)}catch(de){Dn(de instanceof Error?de.message:"PayPal capture failed.")}finally{Ve()||ee(!1)}}},q=c.Buttons({style:{layout:"horizontal",height:ko,tagline:!1},onClick:async(b,S)=>{if(Ve()){await S.reject();return}Vt();let D=qt.current,de={};if(D)try{let Ye=await D("paypal");if(Ve()){await S.reject();return}if(!Ye.proceed){et.current=null,_t.current.delete(xt),await S.reject();return}de={sessionId:Ye.sessionId,accountPatch:Ye.accountPatch,nonce:Ye.nonce}}catch(Ye){J(`onClick:runBeforeButtonClick rejected msg=${(Ye instanceof Error?Ye.message:String(Ye)).slice(0,120)}`),et.current=null,_t.current.delete(xt),await S.reject();return}Ne(()=>Ce.current?.("paypal"));let Oe={generation:An(),surfaceKey:xt,...de};et.current=Oe,_t.current.set(xt,Oe),await S.resolve(),N.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),dn=N.startTiming()},createOrder:Le==="order"?Z?()=>Ut(Z).then(Fn):()=>pt("Failed to create PayPal order.").then(Fn):void 0,createSubscription:Le==="subscription"?Z?()=>Ut(Z).then(Fn):()=>pt("Failed to create PayPal subscription.").then(Fn):void 0,createVaultSetupToken:Le==="setup_token"?()=>pt("Failed to create PayPal setup token.").then(Fn):void 0,onApprove:m,onCancel:()=>{if(Ve())return;let b=_t.current.get(xt)??et.current;b&&_t.current.delete(b.surfaceKey),et.current=null,Gn(),N.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),te.current=!0,bn({generation:b?.generation,remount:!0,focus:!1})},onError:b=>{if(Ve()||G.current!==xt)return;let S=b instanceof Error?b.message:"PayPal failed to render.";if(J(`onError rendered=${Sn} msg=${S.slice(0,120)}`),Sn){let D=_t.current.get(xt)??et.current;if(D&&!Ot(D.generation)||!D&&jt.current===Ft.current)return;if(Un(S)){dt(D?.generation);return}if(Gn(),Vr(b)){N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Zt(b,D),Ne(()=>Rt.current?.(Mt("paypal",S))),D&&_t.current.delete(D.surfaceKey),et.current=null,dt(D?.generation);return}let de=S.toLowerCase();N.error({errorCode:de.includes("popup")&&de.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),D&&_t.current.delete(D.surfaceKey),et.current=null,bn({generation:D?.generation,remount:!0,showRetry:!0,focus:!0}),Lt(b,{code:"paypal_runtime_failed"});return}zt(S)}}),ae=q.isEligible();if(J(`isEligible=${ae}`),N.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ae){re(!1),zt("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Kt=q,se&&J(`container:dims ${st(nn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),se&&typeof MutationObserver<"u"&&(un=new MutationObserver(b=>{if(!Ve()){for(let S of b)if(S.type==="childList")S.addedNodes.forEach(D=>{if(!(D instanceof Element))return;let de=D.tagName.toLowerCase(),Pe=(D.getAttribute("title")??"").slice(0,40),Oe=de==="iframe"?` ${pn(D)}`:"";J(`child+ ${de}${Pe?` title="${Pe}"`:""}${Oe} dims=${st(D)}`)});else if(S.type==="attributes"&&S.target instanceof Element){let D=S.target;if(D.tagName.toLowerCase()!=="iframe")continue;let de=S.attributeName;(de==="src"||de==="srcdoc")&&J(`attr~ iframe ${de}=${de==="srcdoc"?`[${(D.getAttribute("srcdoc")??"").length}ch]`:rn(D.getAttribute("src"))} dims=${st(D)}`)}}}),un.observe(nn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let E=b=>{if(Ve()||Sn)return;let S=nn.querySelectorAll("iframe"),D=typeof document<"u"&&"hasStorageAccess"in document;J(`watchdog:${b} container=${st(nn)} children=${nn.childElementCount} iframes=${S.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${D} paypalNetRequests=${Yt.value}`),S.forEach((de,Pe)=>{let Oe=(de.getAttribute("title")??"").slice(0,40);J(` iframe[${Pe}] ${st(de)}${Oe?` title="${Oe}"`:""} ${pn(de)}`);let Ye=zn(de);Ye&&J(` ${Ye}`)}),mn.length===0&&J(" (no PayPal/zoid window errors captured)")};se&&(wt.push(setTimeout(()=>E("3s"),3e3)),wt.push(setTimeout(()=>E("8s"),8e3)),wt.push(setTimeout(()=>E("15s"),15e3))),J("render:start");let C=N.startTiming();wt.push(setTimeout(()=>{Ve()||Sn||(J("watchdog:11s retryable render timeout"),zt("PayPal Buttons render did not settle within 11000ms.",!0))},Ds)),q.render(nn).then(()=>{if(J(`render:resolved inactive=${Ve()}`),Jn(),Ve()){cn();return}Sn=!0,re(!0),be(!1),Ue.current?.("ready"),N.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"checkout_render",durationMs:N.elapsed(C),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(b=>{let S=b instanceof Error?b.message:"PayPal failed to render.";J(`render:rejected msg=${S.slice(0,120)}`),Jn(),zt(S)})}).catch(c=>{let m=c instanceof Error?c.message:"PayPal SDK failed to load.";J(`loadScript:rejected msg=${m.slice(0,120)}`),zt(m)})},0);return()=>{Ie=!0,clearTimeout(mt),ut&&clearTimeout(ut),Jn(),cn()}},[M,ze,o,p,a,Le,Qe,e,Z,ne,N]);let mr=se?(0,En.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ue?"#fef2f2":"#f3f4f6",border:`1px solid ${ue?"#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=${K} failed=${ue})`,je.length===0?`
2
+ (waiting for first lifecycle event\u2026)`:`
3
+ ${je.join(`
4
+ `)}`]}):null;return ue&&!V?se?(0,En.jsx)("div",{children:mr}):null:(0,En.jsxs)("div",{children:[mr,(0,En.jsxs)("div",{"aria-hidden":ye?!0:void 0,style:ye?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ko},children:[!K&&!ye&&(0,En.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,En.jsx)("div",{ref:oe,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ko,display:"flex",opacity:K?1:0},"aria-busy":le||y},ne)]},ne),T&&(0,En.jsx)("button",{ref:Te,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:at,style:Os,children:"Try PayPal again"})]})}function Kr(e){return(0,En.jsx)(di,{...e})}function ui(e){return(0,En.jsx)(di,{...e})}var Hr=require("react/jsx-runtime");function wr({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,Hr.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"}:{},...r??{}},children:[n&&(0,Hr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Hr.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 Et=require("react/jsx-runtime");function Pn({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:p="You will be automatically redirected, do not close or navigate away from this window."}){return(0,Et.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,Et.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,Et.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,Et.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,Et.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,Et.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,Et.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,Et.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,Et.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,Et.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,Et.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,Et.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,Et.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,Et.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,Et.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&a]}),e==="success"&&p!==null&&(0,Et.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:p}),e==="error"&&t&&(0,Et.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,Et.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 pi=require("@flopay/shared"),yt=require("react");var mi=require("react/jsx-runtime");function Yr({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,p]=(0,yt.useState)(e instanceof Promise?null:e),[d,I]=(0,yt.useState)(t instanceof Promise||!t?null:t),[g,h]=(0,yt.useState)(null),k=(0,yt.useRef)(null),w=(0,yt.useRef)(null),x=(0,yt.useRef)(null),y=Sr(r);(0,yt.useEffect)(()=>{y({class:"lifecycle",name:"checkout.mount"})},[y]),(0,yt.useEffect)(()=>{a&&y({class:"lifecycle",name:"sdk.initialize.ready"})},[y,a]),(0,yt.useEffect)(()=>{if(a)return Tt(a)?.subscribe?.(y)},[y,a]),(0,yt.useEffect)(()=>{if(!(!d||d===a))return Tt(d)?.subscribe?.(y)},[y,a,d]),(0,yt.useEffect)(()=>{if(!a)return;let f=Tt(a);return k.current=f?.beginCheckout()??f?.now()??0,f?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{f?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,yt.useEffect)(()=>{let f=!1;return e instanceof Promise?e.then(ie=>{f||p(ie)},()=>{f||y({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):p(e),()=>{f=!0}},[y,e]),(0,yt.useEffect)(()=>{let f=!1;if(!t){I(null);return}return t instanceof Promise?t.then(ie=>{f||I(ie)},()=>{f||y({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):I(t),()=>{f=!0}},[y,t]),(0,yt.useEffect)(()=>{if(!a){h(null);return}let f=a.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return h(f),()=>{f.destroy()}},[a,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,yt.useEffect)(()=>{if(!a||!g||w.current===g)return;w.current=g;let f=Tt(a);f?.log({name:"checkout.rendered",stage:"checkout_render"}),y({class:"lifecycle",name:"checkout.rendered"}),f?.performance({stage:"checkout_render",durationMs:f.elapsed(k.current??0),durationMode:"machine"})},[g,y,a]);let v=(0,yt.useCallback)(()=>{if(!a||!g||x.current===g)return;x.current=g;let f=Tt(a);f?.log({name:"checkout.interactive",stage:"checkout_interactive"}),f?.performance({stage:"checkout_interactive",durationMs:f.elapsed(k.current??0),durationMode:"machine"})},[g,a]),H=(0,pi.resolveBillingApiUrl)(n?.billingApiUrl),M=(0,yt.useMemo)(()=>({flopay:a,paypalFlopay:d,elements:g,billingApiUrl:H,reportInteractive:v,emitInstrument:y}),[a,d,g,H,v,y]);return(0,mi.jsx)(Wt.Provider,{value:M,children:o})}var Io="flopay_recent_completion_";function kr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Io+e,JSON.stringify(t))}catch{}}function oa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Io+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Io+e),!1):!0}catch{return!1}}var Ir=require("@flopay/js"),Be=require("@flopay/shared");var Gr="card";async function zs(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:p}=await e.retrieveSetupIntent(t);return{error:p,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function Us(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:p,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:p??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function ia(e,t){return Object.assign(e,{checkoutMethod:t})}function Vn(e,t){let n=e instanceof Be.FloPayError?e:new Be.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 Wr(e,t){try{return await e()}catch(n){throw Vn(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 $s(e){return e.status==="succeeded"||e.status==="declined"}async function fi(e){if(typeof document>"u"||typeof window>"u")throw new Be.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Be.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let h=new AbortController,k=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",k);let w=window.setTimeout(()=>h.abort(),r);try{let x=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!x.ok)return{status:"unknown"};let y=await x.json().catch(()=>null);return qs(y)}catch{return{status:"unknown"}}finally{window.clearTimeout(w),e.signal?.removeEventListener("abort",k)}},p=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let I=document.createElement("iframe");I.setAttribute("title","Card authentication"),I.setAttribute("allow","payment"),I.tabIndex=0,I.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),I.src=e.nextActionRedirectUrl,d.appendChild(I),document.body.appendChild(d),I.focus();let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let h=await new Promise((k,w)=>{let x=!1,y=0,v=0,H=0,M=!1,f=()=>{window.clearTimeout(y),window.clearInterval(v),window.clearTimeout(H),window.removeEventListener("message",Q),I.removeEventListener("load",O),e.signal?.removeEventListener("abort",Z)},ie=async()=>{if(!(x||M)){M=!0;try{let ve=await a();if(x||!$s(ve))return;x=!0,f(),k(ve)}finally{M=!1}}},O=()=>{window.clearTimeout(H),H=window.setTimeout(()=>{ie()},250)},Z=()=>{x||(x=!0,f(),w(new Be.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Q=ve=>{if(ve.source!==I.contentWindow||g&&ve.origin!==g)return;let B=ve.data;!B||typeof B!="object"||B.source!=="flopay-vault-3ds-return"||x||(x=!0,f(),k(null))};y=window.setTimeout(()=>{x||(x=!0,f(),w(new Be.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),v=window.setInterval(()=>{ie()},n),I.addEventListener("load",O),window.addEventListener("message",Q),e.signal?.addEventListener("abort",Z),e.signal?.aborted&&Z()});return h||await a()}finally{d.parentNode?.removeChild(d),p?.isConnected&&p.focus()}}function qs(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Qn(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=Xn(o)??o;return ia(new Be.FloPayError(a,"api_error",{code:(0,Be.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Be.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function aa(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Eo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function js(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 o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Eo(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let d of a)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||Eo(d)))return d;let p=o.gateways;if(p&&typeof p=="object"){let d=p.stripe;if(d&&typeof d=="object"){let I=d,g=[I.stripeClientSecret,I.clientSecret];for(let h of g)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||Eo(h)))return h}}}}async function Vs({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=gi(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new Ir.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Eo(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function Er({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:p}){let d=e.replace(/\/+$/,""),I=t??n.id,g=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",k=n.customer?.email??n.accountData?.email??"",w=n.customer?.firstName??n.accountData?.firstName??"",x=n.customer?.lastName??n.accountData?.lastName??"",y=n.customer?.country??n.accountData?.country??void 0,v=n.customer?.zip??n.accountData?.zip??void 0,H=new Ir.PaymentAPI(d,p===!1?{telemetry:!1}:void 0),M=await js(()=>H.processPayment(h,{sessionId:I,nonce:g,tokenizedData:o,accountData:{userId:h,email:k,firstName:w,lastName:x,country:y,zip:v},returnUrl:a??aa(n)}));if(M.ok){let O=typeof M.json=="function"?await M.json().catch(()=>null):null;return(0,Be.isAuthorizationOnlySession)(n)||O?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof O?.paymentId=="string"?O.paymentId:n.paymentId,sessionId:typeof O?.sessionId=="string"?O.sessionId:I,authorizationExpiresAt:typeof O?.authorizationExpiresAt=="string"?O.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:jr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:jr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let f;try{f=await M.json()}catch{throw new Be.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:M.status})}if(f?.type==="paypal_redirect_required"||f?.type==="3ds_required"){let O=gi(f);if(!O)throw new Be.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:M.status});return{type:f.type,threeDSecureToken:O,paymentMethodId:f.paymentMethodId}}if(f?.gatewayErrorCode==="authentication_required"){let O=await Vs({billingApiUrl:d,sessionId:I,nonce:g,responseJson:f});if(O)return O;throw ia(new Be.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ie=new Be.FloPayError(f?.message??"Payment failed. Please try again.","api_error",{code:f?.code??f?.gatewayErrorCode,declineCode:f?.declineCode??f?.gatewayDeclineReason,statusCode:M.status});throw Object.assign(ie,{telemetryOutcome:(0,Be.classifyPaymentRejection)(M.status,f)})}async function Ro(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:p,returnUrl:d,telemetry:I}){let g=t?.getRawProvider();if(!g)throw Vn(new Be.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw ia(new Be.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=(0,Be.isSetupIntentClientSecret)(e.threeDSecureToken),k=null,w=e.paymentMethodId,x=await Wr(()=>zs(g,e.threeDSecureToken,h),"card");if(x){if(x.error)throw Vn(new Be.FloPayError(x.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:x.error.code}),"card");let v=x.intent;!w&&v?.payment_method&&(typeof v.payment_method=="string"?w=v.payment_method:"id"in v.payment_method&&(w=v.payment_method.id??void 0))}let y=w?await Wr(()=>Us(g,e.threeDSecureToken,{payment_method:w,return_url:d??aa(p)??window.location.href},h),"card"):null;if(y){if(y.error)throw Vn(new Be.FloPayError(y.error.message??"3DS authentication failed.","api_error",{code:y.error.code}),"card");k=y.intent}else{let v=await Wr(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(v.error)throw Vn(new Be.FloPayError(v.error.message??"3DS authentication failed.","api_error",{code:v.error.code}),"card");k=(h?v.setupIntent:v.paymentIntent)??null}if(k&&(k.status==="requires_capture"||k.status==="succeeded"||k.status==="processing")){let v=await Er({billingApiUrl:o,sessionId:a,session:p,telemetry:I,tokenizedData:{id:k.id,type:"card",threeDSecureActionResultTokenId:k.id},returnUrl:d});return v.type==="success"?{...v.result,paymentIntentId:v.result.paymentIntentId??k.id,paymentMethodId:v.result.paymentMethodId??w}:Ro(v,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:p,returnUrl:d,telemetry:I})}throw Vn(new Be.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw Vn(new Be.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:w}=await Wr(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(w)throw Vn(new Be.FloPayError(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:k}=await Wr(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??aa(p)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(k)throw Vn(new Be.FloPayError(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Be.FloPayError("Unsupported payment redirect state.","api_error")}function dr(e){if(e instanceof Be.FloPayError){let r=Xn(e.message);return r&&r!==e.message?Object.assign(new Be.FloPayError(r,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=Xn(t)??t;return new Be.FloPayError(n,"api_error")}function _o(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Be.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 xo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[p,d]=await Promise.all([(0,Ir.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,Ir.loadFloPay)(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(I=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",I),null)):Promise.resolve(null)]);return{flopay:p,paypalFlopay:t?a?d:p:null}}var er=require("@flopay/js"),P=require("@flopay/shared"),vt=require("@stripe/react-stripe-js"),i=Za(require("react"),1);function hi(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var Pi={alipay:new URL("./payment-logos/alipay.svg",Ae).href,bancontact:new URL("./payment-logos/bancontact.svg",Ae).href,blik:new URL("./payment-logos/blik.svg",Ae).href,eps:new URL("./payment-logos/eps.svg",Ae).href,giropay:new URL("./payment-logos/giropay.svg",Ae).href,ideal:new URL("./payment-logos/ideal.svg",Ae).href,klarna:new URL("./payment-logos/klarna.svg",Ae).href,p24:new URL("./payment-logos/p24.svg",Ae).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",Ae).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",Ae).href};var Kn=require("react"),vi=require("react/jsx-runtime");function Rr({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:a,onReady:p,onError:d,onValidation:I}){let g=(0,Kn.useRef)(null),h=(0,Kn.useRef)(p),k=(0,Kn.useRef)(d),w=(0,Kn.useRef)(I);h.current=p,k.current=d,w.current=I;let x=(0,Kn.useRef)(o);return x.current=o,(0,Kn.useEffect)(()=>{let y=g.current;if(!y)return;let v=!0,H=!1,M=()=>{!v||H||(H=!0,h.current?.())},f=e.on("ready",()=>{M()}),ie=e.on("error",Q=>{k.current?.(Q.message??"There was a problem loading the secure card form.")}),O=e.on("validation",Q=>{w.current?.(Q.message??null)}),Z={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...x.current?{theme:x.current}:{}};return e.mount(y,Z).then(()=>{M()}).catch(Q=>{v&&k.current?.(Q instanceof Error?Q.message:"Failed to load the secure card form.")}),()=>{v=!1,f(),ie(),O(),e.unmount()}},[e,t,n,r]),(0,Kn.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,vi.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields",style:a})}function _r(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let r=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),a=Math.round((r>>16&255)*o),p=Math.round((r>>8&255)*o),d=Math.round((r&255)*o);return`#${(1<<24|a<<16|p<<8|d).toString(16).slice(1)}`}function sa(e){if(typeof e=="number"||typeof e=="string")return e}function To({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=g=>typeof g=="string"&&g?g:void 0,a=t.submitButton,p=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",d=n==="buttons",I=t.nameInput;return{primaryColor:p,primaryHoverColor:o(r?.colorPrimaryHover)??_r(p,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(I?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(d?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:o(I?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(sa(I?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px"}}var l=require("react/jsx-runtime"),Ln="flopay_stripe_resume",bi="flopay_wallet_resume";function _i(e){return e instanceof P.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Mo(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new er.PaymentAPI(e).createSessionIntent(...n)}catch(o){throw _i(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Jr="flopay_paypal_resume",Ks=250,Ci="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ua(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Fo({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new er.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Hs(e){return e instanceof P.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function la(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var Ys=`
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
+ `,Ao=44;function pa(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 Ws={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},xi={width:"100%",minHeight:Ao,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 Gs(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Si(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ti(e){return e==="paypal"?"PayPal":(0,P.getStripeMethodDisplayName)(e)}function Js(e,t){let n=`We couldn't open ${Ti(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ai(e){let t=(0,i.useRef)(0),n=(0,i.useRef)(null),r=(0,i.useRef)(null),o=(0,i.useCallback)((y=r.current)=>{let v=y;v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),a=(0,i.useCallback)((y,v)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(y),y.timer=setTimeout(()=>{y.timer=null,r.current?.generation===y.generation&&(r.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"}))},v))},[o,e]),p=(0,i.useCallback)(y=>{y.yieldedControl&&a(y,600)},[a]),d=(0,i.useCallback)(y=>{o();let v=t.current+1;t.current=v,n.current=null;let H={generation:v,method:y,timer:null,yieldedControl:!1};return r.current=H,v},[o]),I=(0,i.useCallback)(y=>{let v=r.current;return typeof y=="number"&&v?.generation!==y?!1:(o(v),r.current=null,(typeof y!="number"||n.current===y)&&(n.current=null),!0)},[o]),g=(0,i.useCallback)(y=>{let v=r.current,H=y??v?.generation??t.current;(!y||v?.generation===y)&&(o(v),r.current=null),n.current=H},[o]),h=(0,i.useCallback)(y=>n.current===(y??t.current),[]),k=(0,i.useCallback)(y=>r.current?.generation===y&&n.current!==y,[]),w=(0,i.useCallback)(()=>{let y=r.current;y&&p(y)},[p]),x=(0,i.useCallback)(()=>{let y=r.current;y&&(y.yieldedControl=!0,o(y))},[o]);return(0,i.useEffect)(()=>{let y=()=>{document.visibilityState==="visible"?w():x()},v=()=>{x()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",v),window.addEventListener("focus",w),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",v),window.removeEventListener("focus",w),o()}},[o,x,w]),{startAttempt:d,finishAttempt:I,invalidateAttempt:g,isAttemptInvalidated:h,isAttemptCurrent:k}}function Xs(e){let t=(0,P.getPostalCodeExample)(e);return`Enter a valid ${(0,P.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Zs(e,t,n){let r=(0,P.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,p=a&&!o,d=a&&!!o&&!(0,P.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:p,malformed:d}}function wi(e,t){return t instanceof P.FloPayError?t:new P.FloPayError(t instanceof Error?t.message:`${Gs(e)} before-click hook failed.`,"validation_error")}function ca(){return(0,l.jsx)("style",{children:Ys})}function Qs(e){return typeof e=="number"?`${e}px`:e}function Mi(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Fi({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){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:r})]})}function ki(e){return e!=="unavailable"&&e!=="load_error"}function Bo(e){return(0,l.jsx)(tl,{...e})}function Ii({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:p=!1,onButtonClick:d,onDecline:I,onTechnicalFailure:g,runBeforeButtonClick:h,onLoadStateChange:k,placeholderBorderRadius:w}){let x=In(),{emitInstrument:y}=(0,i.useContext)(Wt),v=(0,vt.useStripe)(),H=(0,vt.useElements)(),[M,f]=(0,i.useState)("loading");(0,i.useEffect)(()=>{k?.(M)},[M,k]);let[ie,O]=(0,i.useState)(!1),Z=(0,i.useRef)(!1),Q=(0,i.useRef)(null),ve=(0,i.useRef)(null),[B,se]=(0,i.useState)(0),[xe,Se]=(0,i.useState)(!1),he=(0,i.useRef)(!1),$=(0,i.useRef)(new Map),{startAttempt:N,finishAttempt:oe,invalidateAttempt:Me,isAttemptInvalidated:Te,isAttemptCurrent:te}=Ai((G,T,fe)=>{g?.(G,T,{...fe,popupBlocked:fe?.popupBlocked??Zn(T)}),Se(!0),se($e=>$e+1)});(0,i.useEffect)(()=>{xe&&ve.current?.focus()},[xe,B]);let K=(0,i.useCallback)(()=>{se(G=>G+1)},[]),re=(0,i.useCallback)((G,T,fe)=>{Me(fe),g?.("paypal",G,{code:T,popupBlocked:Zn(G)}),Se(!0),K()},[Me,g,K]),ye=(0,i.useCallback)(()=>{window.setTimeout(()=>{(Q.current?.querySelector("iframe")??Q.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{he.current&&(he.current=!1,ye())},[ye,B]);let be=(0,i.useCallback)(()=>{Se(!1),a?.(null),ye()},[ye,a]);(0,i.useEffect)(()=>{if(!v||Z.current)return;let G=new URLSearchParams(window.location.search),T=G.get("payment_intent"),fe=G.get("payment_intent_client_secret"),$e=G.get("redirect_status");if(!T||!fe)return;Z.current=!0;let qe;try{let L=localStorage.getItem(Jr);if(L){let le=JSON.parse(L);le.clientSecret===fe&&(qe={...le.accountPatch?{accountPatch:le.accountPatch}:{},...le.sessionId?{sessionId:le.sessionId}:{},...le.nonce?{nonce:le.nonce}:{}})}}catch{}try{localStorage.removeItem(Jr)}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(O(!0),$e==="failed"){let ee="PayPal payment was declined. Please try again.";a?.(ee),I?.(Mt("paypal",ee));return}let{paymentIntent:L,error:le}=await v.retrievePaymentIntent(fe);if(le){a?.(le.message??"Failed to retrieve PayPal payment status.");return}if(L&&(L.status==="requires_capture"||L.status==="succeeded")){let ee=typeof L.payment_method=="string"?L.payment_method:L.payment_method?.id;o({id:ee??L.id,type:"card",threeDSecureActionResultTokenId:L.id,isPaypal:!0},qe)}else{let ee="PayPal payment was not completed. Please try again.";a?.(ee),I?.(Mt("paypal",ee))}}catch(L){a?.(L instanceof Error?L.message:"Failed to complete PayPal payment.")}finally{O(!1)}})()},[v,o,a,I]);let ne=(0,i.useCallback)(async G=>{if(p||ie){G.reject();return}let T=h?await h("paypal"):{proceed:!0};if(!T.proceed){$.current.delete(B),G.reject();return}let fe=N("paypal");$.current.set(B,{generation:fe,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),Se(!1),d?.("paypal"),G.resolve()},[$,p,d,h,N,ie,B]),_e=(0,i.useCallback)(async G=>{if(!v||!H)return;let T=$.current.get(B);if(T&&!te(T.generation)){$.current.delete(B);return}if(!T&&Te()||T&&!oe(T.generation))return;T||oe();let fe=T??null;if($.current.delete(B),!fe&&h){let L=await h("paypal");if(!L.proceed){G.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}fe={accountPatch:L.accountPatch,sessionId:L.sessionId,nonce:L.nonce}}let $e=fe?.sessionId??e,qe=fe?.nonce??t,ue=fe?.accountPatch?.email??n;try{if(O(!0),a?.(null),!$e||!ue)throw new Error("Missing sessionId or email for PayPal payment");let L=v.createPaymentMethod,{error:le,paymentMethod:ee}=await L({type:"paypal"});if(le){re(le,"stripe_paypal_create_payment_method_failed",T?.generation),G.paymentFailed({reason:"fail"});return}let ze=await Mo(r,y,$e,qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ee?.id??null,intentKind:"payment"});if(ze.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Le=ze.clientSecret,Qe={return_url:window.location.href};if(ee?.id&&(Qe.payment_method=ee.id),typeof window<"u")try{localStorage.setItem(Jr,JSON.stringify({clientSecret:Le,sessionId:$e,nonce:qe,accountPatch:fe?.accountPatch}))}catch{}let{error:ce,paymentIntent:ft}=await v.confirmPayment({clientSecret:Le,confirmParams:Qe,redirect:"if_required"});if(ce){if(typeof window<"u")try{localStorage.removeItem(Jr)}catch{}if(Vr(ce)){let je=ce.message??"Your payment was declined.";a?.(je),I?.(Mt("paypal",je,{code:jn(ce),declineCode:br(ce)})),await Fo({billingApiUrl:r,sessionId:$e,nonce:qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:jn(ce)??"provider_declined"}})}else re(ce,"stripe_paypal_confirm_failed",T?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Jr)}catch{}let V=typeof ft?.payment_method=="string"?ft.payment_method:ft?.payment_method?.id;o({id:V??ft?.id,type:"card",threeDSecureActionResultTokenId:ft?.id,isPaypal:!0},{accountPatch:fe?.accountPatch,sessionId:$e,nonce:qe});return}catch(L){re(L,"stripe_paypal_failed",T?.generation)}finally{O(!1)}},[v,H,e,t,n,r,y,o,a,I,h,re,oe,te,Te,B]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Fi,{state:M,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:(0,l.jsxs)("div",{ref:Q,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[xe&&(0,l.jsx)("button",{ref:ve,type:"button","data-testid":"flopay-paypal-retry-button",onClick:be,style:xi,children:"Try PayPal again"}),(0,l.jsx)(vt.ExpressCheckoutElement,{onReady:G=>f(Mi(G,["paypal"])),onLoadError:()=>{f("load_error"),ua(Tt(x),"paypal","paypal")},onClick:ne,onConfirm:_e,onCancel:()=>{let G=$.current.get(B);$.current.delete(B),Tt(x)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Me(G?.generation),Se(!1),he.current=!0,K()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},B)]})}),ie&&(0,l.jsx)(Pn,{status:"processing"})]})}function Ei({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:p,onErrorChange:d,onButtonClick:I,onDecline:g,onTechnicalFailure:h,runBeforeButtonClick:k,onLoadStateChange:w,placeholderBorderRadius:x}){let y=In(),{emitInstrument:v}=(0,i.useContext)(Wt),H=(0,vt.useStripe)(),M=(0,vt.useElements)(),[f,ie]=(0,i.useState)("loading");(0,i.useEffect)(()=>{w?.(f)},[f,w]);let[O,Z]=(0,i.useState)(!1),Q=(0,i.useRef)(null),ve=(0,i.useRef)(null),[B,se]=(0,i.useState)(0),[xe,Se]=(0,i.useState)(!1),[he,$]=(0,i.useState)("google_pay"),N=(0,i.useRef)(!1),oe=(0,i.useRef)("google_pay"),Me=(0,i.useRef)("google_pay"),Te=(0,i.useRef)(new Map),{startAttempt:te,finishAttempt:K,invalidateAttempt:re,isAttemptInvalidated:ye,isAttemptCurrent:be}=Ai((ue,L,le)=>{h?.(ue,L,{...le,popupBlocked:le?.popupBlocked??Zn(L)}),$(ue),Se(!0),se(ee=>ee+1)});(0,i.useEffect)(()=>{xe&&ve.current?.focus()},[xe,B]);let ne=(0,i.useCallback)(()=>{se(ue=>ue+1)},[]),_e=(0,i.useCallback)((ue,L,le,ee)=>{re(ee),h?.(ue,L,{code:le,popupBlocked:Zn(L)}),$(ue),Se(!0),ne()},[re,h,ne]),G=(0,i.useCallback)(()=>{window.setTimeout(()=>{(Q.current?.querySelector("iframe")??Q.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{N.current&&(N.current=!1,G())},[G,B]);let T=(0,i.useCallback)(()=>{Se(!1),d?.(null),G()},[G,d]),fe=(0,i.useCallback)(async ue=>{if(!H||!M)return;let L=Te.current.get(B);if(L&&!be(L.generation)){Te.current.delete(B);return}if(!L&&ye()||L&&!K(L.generation))return;L||K();let le=ue.expressPaymentType??L?.method??oe.current,ee=L??null;Te.current.delete(B);let ze=Si(le);if(!ee&&k){let V=await k(ze);if(!V.proceed){ue.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}ee={accountPatch:V.accountPatch,sessionId:V.sessionId,nonce:V.nonce}}let Le=ze,Qe=ee?.sessionId??e,ce=ee?.nonce??t,ft=ee?.accountPatch?.email??n;try{Z(!0),d?.(null);let{error:V}=await M.submit();if(V){_e(le,V,"stripe_wallet_submit_failed",L?.generation);return}let{error:je,paymentMethod:bt}=await H.createPaymentMethod({elements:M});if(je||!bt){_e(le,je??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",L?.generation);return}if(!Qe||!ft)throw new Error("Missing sessionId or email for wallet payment");let J=await Mo(r,v,Qe,ce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:le??ze,paymentMethodId:bt.id,intentKind:o});if(J.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Ct=J.clientSecret,{error:He,intentId:en}=(0,P.isSetupIntentClientSecret)(Ct)?await H.confirmCardSetup(Ct,{payment_method:bt.id}).then(Rt=>({error:Rt.error,intentId:Rt.setupIntent?.id})):await H.confirmCardPayment(Ct,{payment_method:bt.id}).then(Rt=>({error:Rt.error,intentId:Rt.paymentIntent?.id}));if(He){if(Vr(He)){let Rt=He.message??"Your payment was declined.";d?.(Rt),g?.(Mt(Le,Rt,{code:jn(He),declineCode:br(He)})),await Fo({billingApiUrl:r,sessionId:Qe,nonce:ce,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:le??ze,providerDeclineReason:jn(He)??"provider_declined"}})}else _e(le,He,"stripe_wallet_confirm_failed",L?.generation);return}p({id:bt.id,type:"card",threeDSecureActionResultTokenId:en},{accountPatch:ee?.accountPatch,sessionId:Qe,nonce:ce})}catch(V){_e(le,V,"stripe_wallet_failed",L?.generation)}finally{Z(!1)}},[H,M,e,t,n,r,v,o,p,d,g,k,_e,K,be,ye,B]),$e=(0,i.useMemo)(()=>{let ue=["applePay","googlePay","paypal","link","amazonPay","klarna"],L=new Set(["applePay","googlePay"]),le=new Set(a.map(P.stripeExpressMethodToOptionKey)),ee={};for(let ze of ue)le.has(ze)?ee[ze]=L.has(ze)?"always":"auto":ee[ze]="never";return ee},[a]),qe=(0,i.useMemo)(()=>a.map(P.stripeExpressMethodToOptionKey),[a]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Fi,{state:f,placeholderTestId:"flopay-wallet-placeholder",borderRadius:x,children:(0,l.jsxs)("div",{ref:Q,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[xe&&(0,l.jsxs)("button",{ref:ve,type:"button","data-testid":"flopay-wallet-retry-button",onClick:T,style:xi,children:["Try ",Ti(he)," again"]}),(0,l.jsx)(vt.ExpressCheckoutElement,{onReady:ue=>{ie(Mi(ue,qe))},onLoadError:ue=>{ie("load_error"),ua(Tt(y),"stripe","wallet")},onClick:async ue=>{oe.current=ue.expressPaymentType,Me.current=Si(ue.expressPaymentType);let L=k?await k(Me.current):{proceed:!0};if(!L.proceed){Te.current.delete(B),ue.reject();return}let le=te(ue.expressPaymentType);Te.current.set(B,{generation:le,method:ue.expressPaymentType,accountPatch:L.accountPatch,sessionId:L.sessionId,nonce:L.nonce}),Se(!1),I?.(Me.current),ue.resolve()},onConfirm:fe,onCancel:()=>{let ue=Te.current.get(B);Te.current.delete(B),Tt(y)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),re(ue?.generation),Se(!1),N.current=!0,ne()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:$e,layout:{maxColumns:1,overflow:"never"}}},B)]})}),O&&(0,l.jsx)(Pn,{status:"processing"})]})}function el({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:p,backgroundColor:d,borderColor:I,textColor:g,borderRadius:h,fontFamily:k}){let w=(0,P.resolveStripeMethodBrandVariant)(e,t),x=Pi[e],y=w?.backgroundColor??d??"#ffffff",v=w?.borderColor??I??"#d1d5db",H=w?.textColor??g??"#262833";return(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&p()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Ao,padding:"0 1rem",backgroundColor:y,color:H,border:`1px solid ${v}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:k,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,l.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,P.getStripeMethodDisplayName)(e)}\u2026`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,P.hasVendoredStripeMethodLogo)(e)?8:0},children:[x?(0,l.jsx)("img",{src:x,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):w?.logoSvg?(0,l.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:w.logoSvg}}):null,(0,l.jsx)("span",{children:(0,P.getStripeMethodDisplayName)(e)})]}),a&&(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:H,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 da({method:e,sessionId:t,nonce:n,email:r,billingName:o,billingApiUrl:a,onTokenizedBody:p,onErrorChange:d,onDecline:I,onCancel:g,runBeforeButtonClick:h,onButtonClick:k,isProcessing:w,submitButtonColor:x,submitButtonBorderRadius:y,submitButtonStyle:v,errorText:H}){let M=In(),{emitInstrument:f}=(0,i.useContext)(Wt),ie=(0,vt.useStripe)(),O=(0,vt.useElements)(),[Z,Q]=(0,i.useState)(!1),ve=(0,i.useRef)(!1),[B,se]=(0,i.useState)(!1),[xe,Se]=(0,i.useState)("loading"),he=(0,i.useCallback)(async()=>{if(!ie||!O||w||ve.current||!B)return;ve.current=!0,Q(!0);let $=h?await h("card"):{proceed:!0};if(!$.proceed){ve.current=!1,Q(!1);return}k?.("card");let N=$.sessionId??t,oe=$.nonce??n,Me=$.accountPatch?.email??r;try{d?.(null);let Te=await O.submit();if(Te.error){d?.(Te.error.message??"Payment failed.");return}let te=await ie.createPaymentMethod({elements:O});if(te.error||!te.paymentMethod){d?.(te.error?.message??"Failed to create payment method.");return}let K=te.paymentMethod;if(!N||!Me)throw new Error("Missing sessionId or email for payment.");let re=K.type||e,ye=await Mo(a,f,N,oe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,paymentMethodId:null,intentKind:"payment"});if(ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let be=ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(Ln,JSON.stringify({clientSecret:be,sessionId:N,nonce:oe,accountPatch:$.accountPatch,paymentMethodId:K.id,paymentMethodType:K.type??e,gateway:"stripe"}))}catch{}let{error:ne,paymentIntent:_e}=await ie.confirmPayment({clientSecret:be,confirmParams:{return_url:window.location.href,payment_method:K.id},redirect:"if_required"});if(ne){if(typeof window<"u")try{localStorage.removeItem(Ln)}catch{}let fe=ne.message??"Payment failed.";d?.(fe),I?.(Mt("card",fe,{code:ne.code})),await Fo({billingApiUrl:a,sessionId:N,nonce:oe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ne.code??"provider_declined"}});return}let G=_e?.status;if(!go(G)){if(typeof window<"u")try{localStorage.removeItem(Ln)}catch{}let fe=G==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(fe),I?.(Mt("card",fe,{code:G??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Ln)}catch{}let T=typeof _e?.payment_method=="string"?_e.payment_method:_e?.payment_method?.id;p({id:T??K.id,type:"card",threeDSecureActionResultTokenId:_e?.id,gateway:"stripe",paymentMethodType:K.type??e},{accountPatch:$.accountPatch,sessionId:N,nonce:oe})}catch(Te){d?.(Te instanceof Error?Te.message:"Payment failed. Please try again.")}finally{ve.current=!1,Q(!1)}},[ie,O,w,B,h,k,t,n,r,a,f,e,p,d,I]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,l.jsx)(vt.PaymentElement,{onReady:()=>Se("ready"),onLoadError:()=>{Se("load_error"),ua(Tt(M),"stripe","apm")},onChange:$=>{se(!!$.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...r?{email:r}:{}}}}}),(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{he()},disabled:!B||Z||w||xe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:x,color:"white",border:"none",borderRadius:y,fontSize:"1rem",fontWeight:600,cursor:!B||Z||w||xe!=="ready"?"not-allowed":"pointer",opacity:!B||Z||w||xe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...v??{}},children:Z?"Processing\u2026":`Pay with ${(0,P.getStripeMethodDisplayName)(e)}`}),H&&(0,l.jsx)(wr,{margin:"0.75rem 0 0",children:H})]})}function Ri({sessionId:e,nonce:t,email:n,billingName:r,billingApiUrl:o,paymentElementMethods:a,stripeInstance:p,paymentElementBaseOptions:d,onTokenizedBody:I,onErrorChange:g,onButtonClick:h,onDecline:k,runBeforeButtonClick:w,onLoadStateChange:x,isProcessing:y=!1,submitButtonColor:v="#4A49FF",submitButtonBorderRadius:H=8,submitButtonStyle:M,buttonAppearance:f,themeId:ie,onExpandApm:O,expandedApmMethod:Z}){let{emitInstrument:Q}=(0,i.useContext)(Wt),[ve,B]=(0,i.useState)(null),[se,xe]=(0,i.useState)(null),Se=(0,i.useRef)(!1);(0,i.useEffect)(()=>{a.length>0&&p?x?.("ready"):p||x?.("loading")},[a.length,p,x]);let he=(0,i.useCallback)(async te=>{if(!p||Se.current||y)return;Se.current=!0,xe(te);let K=w?await w("card"):{proceed:!0};if(!K.proceed){Se.current=!1,xe(null);return}h?.("card");let re=K.sessionId??e,ye=K.nonce??t,be=K.accountPatch?.email??n;try{if(g?.(null),!re||!be)throw new Error("Missing sessionId or email for payment.");let ne=await Mo(o,Q,re,ye??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,paymentMethodId:null,intentKind:"payment"});if(ne.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let _e=ne.clientSecret;if(typeof window<"u")try{localStorage.setItem(Ln,JSON.stringify({clientSecret:_e,sessionId:re,nonce:ye,accountPatch:K.accountPatch,paymentMethodType:te,gateway:"stripe"}))}catch{}let{error:G,paymentIntent:T}=await p.confirmPayment({clientSecret:_e,confirmParams:{return_url:window.location.href,payment_method_data:{type:te,billing_details:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...be?{email:be}:{}}}},redirect:"if_required"});if(G){if(typeof window<"u")try{localStorage.removeItem(Ln)}catch{}let qe=G.message??"Payment failed.";g?.(qe),k?.(Mt("card",qe,{code:G.code})),await Fo({billingApiUrl:o,sessionId:re,nonce:ye,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,providerDeclineReason:G.code??"provider_declined"}});return}let fe=T?.status;if(!go(fe)){if(typeof window<"u")try{localStorage.removeItem(Ln)}catch{}let qe=fe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(qe),k?.(Mt("card",qe,{code:fe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Ln)}catch{}let $e=typeof T?.payment_method=="string"?T.payment_method:T?.payment_method?.id;I({id:$e??T?.id,type:"card",threeDSecureActionResultTokenId:T?.id,gateway:"stripe",paymentMethodType:te},{accountPatch:K.accountPatch,sessionId:re,nonce:ye})}catch(ne){g?.(ne instanceof Error?ne.message:"Payment failed. Please try again.")}finally{Se.current=!1,xe(null)}},[p,y,w,h,e,t,n,o,Q,r,I,g,k]),[$,N]=(0,i.useState)(null),oe=O?Z??null:$,Me=(0,i.useCallback)(te=>{Se.current||y||oe&&oe!==te||((0,P.needsStripeMethodExplicitConfirm)(te)?O?O(te):N(te):he(te))},[oe,y,he,O]),Te=(0,i.useMemo)(()=>$?{...d,paymentMethodTypes:[$]}:null,[$,d]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(te=>{let K=Z===te,re=se===te,ye=se!==null&&se!==te||Z!=null&&Z!==te;return(0,l.jsxs)(i.default.Fragment,{children:[(0,l.jsx)(el,{method:te,themeId:ie,submitting:re,disabled:ye,highlighted:K,hasNextStep:(0,P.needsStripeMethodExplicitConfirm)(te),onClick:()=>Me(te),backgroundColor:f?.backgroundColor,borderColor:f?.borderColor,textColor:f?.textColor,borderRadius:f?.borderRadius,fontFamily:f?.fontFamily}),!O&&$===te&&Te&&p&&(0,l.jsx)(vt.Elements,{stripe:p,options:Te,children:(0,l.jsx)(da,{method:te,sessionId:e,email:n,billingName:r,billingApiUrl:o,onTokenizedBody:I,onErrorChange:g,onDecline:k,onCancel:()=>N(null),runBeforeButtonClick:w,onButtonClick:h,isProcessing:y,submitButtonColor:v,submitButtonBorderRadius:H,submitButtonStyle:M})},te)]},te)})})}function tl({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:p,onDecline:d,onTokenizedBody:I,firstName:g,lastName:h,chv:k,className:w,isProcessing:x,error:y,onErrorChange:v,showPayPal:H=!0,showStripe:M=!0,enabledPaymentMethods:f,enabledPaymentMethodCountries:ie,showApplePay:O=!0,showGooglePay:Z=!0,layout:Q="default",theme:ve,buttonsTheme:B,buttonsStyles:se,appearance:xe,cardButtonContent:Se,cardBackButtonContent:he,cardTitleContent:$,showSecurityFooter:N,onButtonClick:oe,onBeforeButtonClick:Me,enableAVS:Te,cardFieldOrder:te,cardPreFormSlot:K,avsLayout:re="row",country:ye,zip:be,addressLine1:ne,addressLine2:_e,city:G,state:T,onCountryChange:fe,onZipChange:$e,avsCheck:qe,checkoutType:ue,checkoutLayout:L,totalAmount:le=0,currency:ee="usd",initialCardOpen:ze=!1,directPaypal:Le,isSubscription:Qe=!1,session:ce,dataAttachmentPending:ft=!1,debug:V=!1}){let je=In(),bt=ho(),J=(0,i.useContext)(kn),{emitInstrument:Ct}=(0,i.useContext)(Wt),He=ft||J.claimPending===!0,en=vo(),[Rt,A]=(0,i.useState)(!1),[Ce,gt]=(0,i.useState)(null),[Ue,qt]=(0,i.useState)(ye??"US"),[Jt,Ze]=(0,i.useState)(be??""),[St,et]=(0,i.useState)(ne??""),[Ft,Ge]=(0,i.useState)(_e??""),[jt,_t]=(0,i.useState)(G??""),[tn,Dt]=(0,i.useState)(T??""),[Tn,ln]=(0,i.useState)({}),at=(0,i.useRef)(be??""),Lt=(0,i.useRef)(ye??"US"),Je=(0,i.useRef)(ne??""),An=(0,i.useRef)(_e??""),dt=(0,i.useRef)(G??""),bn=(0,i.useRef)(T??""),Ot=(0,i.useRef)({});(0,i.useEffect)(()=>{let s=(U,X,pe,W,ke)=>{if(Ot.current[U])return;let Fe=X?.trim();!Fe||Fe===pe.current||(pe.current=Fe,W(Fe),ke?.(Fe))};s("country",ye,Lt,qt,fe),s("zip",be,at,Ze,$e),s("addressLine1",ne,Je,et),s("addressLine2",_e,An,Ge),s("city",G,dt,_t),s("state",T,bn,Dt)},[ye,be,ne,_e,G,T,fe,$e]);let me=(0,i.useMemo)(()=>(0,P.resolveAVSConfig)(Te),[Te]),Yn=me!==null,Mn=(0,i.useMemo)(()=>(0,P.isAuthorizationOnlySession)(ce),[ce]),Fn=!!ce?.vault?.html,Bn=!!ce?.gateways?.pcivault,F=!!(ce?.gateways?.stripe?.enabledPaymentMethods??f)?.includes("card"),tt=Fn||F||Bn,Ie=!!(M&&tt&&je&&e),[Cn,Ve]=(0,i.useState)(()=>Q!=="buttons"||ze?e??null:null),[Wn,tr]=(0,i.useState)(0),Vt=Q!=="buttons"||ze||!!e&&Cn===e,ut=(0,i.useMemo)(()=>!je||!Ie||!e||!Vt?null:je.cardCapture({sessionId:e,captureMethod:ce?.captureMethod}),[je,Ie,e,Vt,ce?.captureMethod]),Xt=(0,i.useMemo)(()=>{let s=Ue,U=me?(0,P.isAVSFieldVisible)(me.postal_code,s):!1;return Zs(s,Jt,U)},[me,Ue,Jt]),{avsInvalid:Kt,invalidAvsFields:it}=(0,i.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!Ie||!me)return{avsInvalid:!1,invalidAvsFields:s};let U=Ue,X=(ke,Fe)=>(0,P.isAVSFieldVisible)(ke,U)&&!Fe.trim(),pe={line1:X(me.address_line_1,St),city:X(me.city,jt),state:X(me.state,tn),zip:Xt.empty||Xt.malformed};return{avsInvalid:pe.line1||pe.city||pe.state||pe.zip,invalidAvsFields:pe}},[Ie,me,Ue,St,jt,tn,Xt]),[cn,dn]=(0,i.useState)(!1),[Gn,Sn]=(0,i.useState)(!1),[nn,un]=(0,i.useState)(()=>la(ce?.vault)),[we,wt]=(0,i.useState)(ze&&tt?"card":"buttons"),[st,rn]=(0,i.useState)(null),pn=we==="expanding"||we==="card",zn=ce?.gateways?.stripe?"stripe":void 0,mn=(0,i.useCallback)(()=>{Ct?.({class:"card_surface",provider:zn})},[zn,Ct]),Nt=280,Ht=(0,i.useRef)(null),Yt=(0,i.useCallback)(s=>{Ht.current&&clearTimeout(Ht.current),Ht.current=setTimeout(()=>{Ht.current=null,s()},Nt)},[Nt]);(0,i.useEffect)(()=>()=>{Ht.current&&clearTimeout(Ht.current)},[]);let Jn=(0,i.useCallback)(()=>{mn(),Ve(e??null),tr(s=>s+1),wt("expanding"),Yt(()=>wt("card"))},[Yt,mn,e]),Un=(0,i.useCallback)(()=>{wt("collapsing"),Yt(()=>wt("buttons"))},[Yt]),Dn=(0,i.useCallback)(s=>{rn(s),wt("apm-expanding"),Yt(()=>wt("apm-form"))},[Yt]),$n=(0,i.useCallback)(()=>{wt("apm-collapsing"),Yt(()=>{wt("buttons"),rn(null)})},[Yt]);(0,i.useEffect)(()=>{Q==="buttons"&&ze&&tt&&(Ve(e??null),wt("card"))},[Q,ze,tt,e]);let[zt,nt]=(0,i.useState)(null),yn=(0,i.useRef)(!1),Ut=(0,i.useRef)(null),pt=(0,i.useRef)("idle"),[Zt,xt]=(0,i.useState)(null),nr=(0,i.useRef)(Zt);(0,i.useEffect)(()=>{nr.current=Zt},[Zt]);let mt=n||en,u=y??Ce,c=(0,i.useMemo)(()=>(0,P.resolveTheme)(ve),[ve]),m=(0,i.useMemo)(()=>{let s=c?.buttonsLayout??(0,P.resolveButtonsLayoutTheme)(B);return se?{...s,...se,cardButton:{...s.cardButton,...se.cardButton},cardFormContainer:{...s.cardFormContainer,...se.cardFormContainer},backButton:{...s.backButton,...se.backButton},backButtonIcon:{...s.backButtonIcon,...se.backButtonIcon},submitButton:{...s.submitButton,...se.submitButton},title:{...s.title,...se.title}}:s},[c,B,se]),q=xe??c?.appearance,ae=(0,i.useMemo)(()=>To({appearance:q,buttonsStyles:m,layout:Q}),[q,m,Q]),Y=J.inlineSessionPatchProcessing??!1,E=(x??Rt)||Y,C=mt.replace(/\/+$/,""),b=(0,i.useMemo)(()=>ea({userId:o,email:r,firstName:g,lastName:h,country:ye,zip:be},Tn),[o,r,g,h,ye,be,Tn]),S=[b.firstName,b.lastName].filter(s=>!!s?.trim()).join(" "),D=(0,i.useMemo)(()=>je?je.getRawProvider():null,[je]),de=(0,i.useMemo)(()=>bt?bt.getRawProvider():null,[bt]),Pe=le||100,Oe=(0,i.useMemo)(()=>q?(0,er.toStripeAppearance)(q):null,[q]),Ye=Oe?{appearance:Oe}:null,At=(0,i.useMemo)(()=>{let s=Oe??{},U=s.rules??{};return{...s,rules:{...U,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...U[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...U[".AccordionItemContents"]??{}}}}},[Oe]),Ee=(0,i.useMemo)(()=>{let s=ri(le);return{...s,currency:ee.toLowerCase(),paymentMethodCreation:"manual",...s.mode==="payment"?{captureMethod:"manual"}:{},...Ye}},[le,ee,Ye]),Re=(0,i.useMemo)(()=>({mode:"payment",amount:Pe,currency:ee.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Ye}),[Pe,ee,Ye]),j=(0,i.useCallback)(s=>{gt(s),v?.(s)},[v]);(0,i.useEffect)(()=>{!Ie||!ut||ut.setCardFieldOrder?.(te??null,me==null)},[Ie,ut,te,me]),(0,i.useEffect)(()=>{(we==="expanding"||we==="collapsing"||we==="apm-expanding"||we==="apm-collapsing")&&j(null)},[we,j]);let kt=(0,i.useCallback)((s,U,X)=>{d?.(Mt(s,U,X))},[d]),We=(0,i.useCallback)((s,U,X)=>{let pe=X?.popupBlocked??Zn(U),W=Js(s,pe),ke=lr(X?.code)??jn(U)??"external_payment_method_failed",Fe=new P.FloPayError(W,"api_error",{code:"external_payment_method_failed",param:s});nt(null),Q==="buttons"&&(wt("buttons"),rn(null)),j(W),p?.(Fe),console.error("[FloPay] External payment method failed:",{method:s,code:ke,popupBlocked:pe})},[Q,p,j]);(0,i.useEffect)(()=>{if(!Ie||!e){un(null);return}let s=la(ce?.vault);if(s){un(s);return}if(!Vt){un(null);return}un(null);let U=!0;return new er.PaymentAPI(C).getVaultCapture(e,t).then(X=>{if(!U)return;let pe=la(X);pe?un(pe):j("Failed to load the secure card form.")}).catch(X=>{U&&j(X instanceof Error?X.message:"Failed to load the secure card form.")}),()=>{U=!1}},[Ie,Vt,Wn,e,ce?.vault?.html,ce?.vault?.messageToken,ce?.vault?.expectedOrigin,C,t,j]);let rt=(0,i.useRef)({onComplete:a,onError:p,updateError:j,emitDecline:kt,resolvedAccount:b,avsConfig:me,avsCheckProp:qe,sessionId:e,nonce:t,baseUrl:C,captureMethod:ce?.captureMethod,paymentId:ce?.paymentId,authorizationExpiresAt:ce?.authorizationExpiresAt});rt.current={onComplete:a,onError:p,updateError:j,emitDecline:kt,resolvedAccount:b,avsConfig:me,avsCheckProp:qe,sessionId:e,nonce:t,baseUrl:C,captureMethod:ce?.captureMethod,paymentId:ce?.paymentId,authorizationExpiresAt:ce?.authorizationExpiresAt};let rr=(0,i.useRef)(!1),ka=(0,i.useCallback)(()=>{let{resolvedAccount:s,avsConfig:U,avsCheckProp:X}=rt.current,pe=Lt.current||s.country||"US",W=U?(0,P.isAVSFieldVisible)(U.state,pe):!1,ke=U?(0,P.isAVSFieldVisible)(U.address_line_1,pe):!1,Fe=U?(0,P.isAVSFieldVisible)(U.postal_code,pe):!1,ht=U?(0,P.isAVSFieldVisible)(U.city,pe):!1,$t=U?(0,P.isAVSFieldVisible)(U.address_line_2,pe):!1,Pt=ke&&!W&&Fe?(0,P.getStateFromPostalCode)(pe,(at.current??"").trim()):null,lt=W?bn.current:Pt;return{accountData:{userId:s.userId??"",email:s.email??"",firstName:s.firstName??"",lastName:s.lastName??"",...Fe&&at.current?{zip:at.current}:{},...ht&&dt.current?{city:dt.current}:{},...lt?{state:lt}:{},...ke&&Je.current?{addressLine1:Je.current}:{},...$t&&An.current?{addressLine2:An.current}:{},country:pe},...X!==void 0?{avsCheck:X}:{},...U?{avsConfig:{country:(0,P.isAVSFieldVisible)(U.country,pe),postal_code:Fe,address_line_1:ke,address_line_2:$t,city:ht,state:W}}:{}}},[]),to=(0,i.useRef)(He);to.current=He,(0,i.useEffect)(()=>{He||u!==Ci||rt.current.updateError(null)},[He,u]),(0,i.useEffect)(()=>{!Ie||!ut||ut.setSubmitGate?.(Kt||He)},[Ie,ut,Kt,He]),(0,i.useEffect)(()=>{if(!Ie||!ut)return;rr.current=!1;let s=!1,U=ut.on("submitting",()=>{dn(!0),Ut.current&&clearTimeout(Ut.current),pt.current="validation-window",Ut.current=setTimeout(()=>{Ut.current=null,pt.current==="validation-window"&&(pt.current="processing")},Ks),nt("processing");let{baseUrl:Fe,sessionId:ht,nonce:$t,updateError:Pt,onError:lt}=rt.current;!ht||!$t||new er.PaymentAPI(Fe).patchAccountSnapshot(ht,$t,ka(),{telemetryMode:"best_effort"}).catch(Ke=>{if(!Hs(Ke))return;let qn=Ke instanceof Error?Ke.message:"Please check your billing address and try again.";Pt(qn),pt.current="idle",nt(null),lt?.(Ke instanceof P.FloPayError?Ke:new P.FloPayError(qn,"api_error"))})}),X=ut.on("complete",async Fe=>{if(kr(Fe.sessionId??rt.current.sessionId),pt.current="terminal",nt("success"),await new Promise(Pt=>setTimeout(Pt,1200)),rr.current)return;rr.current=!0;let ht=rt.current,$t=(0,P.isAuthorizationOnlySession)(ht)||Fe.outcome==="authorized";rt.current.onComplete?.($t?{status:"authorized",paymentIntentId:Fe.intentId,paymentId:Fe.paymentId??ht.paymentId,sessionId:Fe.sessionId??ht.sessionId,authorizationExpiresAt:Fe.authorizationExpiresAt??ht.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Fe.intentId,checkoutMethod:"card"})}),pe=ut.on("decline",async Fe=>{let{updateError:ht,emitDecline:$t}=rt.current,Pt=Fe.message??"Your payment was declined. Please try another card or contact your bank.";pt.current="terminal",ht(Pt),nt("error");let lt=Fe.failureOutcome??(0,P.normalizeCheckoutFailureOutcome)(Fe.declineReason)??"authorization_declined";$t("card",Pt,{code:lt,declineCode:lt}),await new Promise(Ke=>setTimeout(Ke,1500)),!s&&(pt.current="idle",nt(null))}),W=ut.on("error",async Fe=>{let{updateError:ht,onError:$t}=rt.current,Pt=Fe.message??"There was a problem processing your payment. Please try again.";pt.current="terminal",ht(Pt),nt("error"),$t?.(new P.FloPayError(Pt,"api_error",{code:Fe.failureOutcome??"capture_failed"})),await new Promise(lt=>setTimeout(lt,1500)),!s&&(pt.current="idle",nt(null))}),ke=ut.on("blocked",()=>{if(!to.current){dn(!0);return}rt.current.updateError(Ci)});return()=>{s=!0,Ut.current&&(clearTimeout(Ut.current),Ut.current=null),pt.current="idle",U(),X(),pe(),W(),ke()}},[Ie,ut]);let on=!!Le?.clientId,Tr=Array.isArray(f),no=Tr&&f.length>0,Xi=Tr&&f.includes("paypal"),{expressMethods:ro,paymentElementMethods:Ar}=(0,i.useMemo)(()=>(0,P.partitionStripeMethods)(f,{excludePaypal:on}),[f,on]),Ia=on||!!bt,Zi=(0,i.useMemo)(()=>Ia?ro.filter(s=>s!=="paypal"):ro,[ro,Ia]),Qi=(0,i.useMemo)(()=>{let s=[];return O&&s.push("apple_pay"),Z&&s.push("google_pay"),s},[O,Z]),oo=Tr?Zi:Qi,es=M&&oo.length>0,$o=Yn?Ue:ye,ao=(0,i.useMemo)(()=>{let s=$o?.trim().toUpperCase();return s?ie?Ar.filter(U=>{let X=ie[U];return!X||X.length===0||X.includes(s)}):(0,P.filterStripeMethodsByCountry)(Ar,$o):Ar},[Ar,$o,ie]),qo=(0,i.useMemo)(()=>({mode:"payment",amount:Pe,currency:ee.toLowerCase(),paymentMethodCreation:"manual",appearance:At}),[Pe,ee,At]),[Ea,Ra]=(0,i.useState)("loading"),[_a,xa]=(0,i.useState)("loading"),[Ta,Aa]=(0,i.useState)("loading"),[ts,jo]=(0,i.useState)(!1),[Ma,Vo]=(0,i.useState)("loading"),[io,ns]=(0,i.useState)();(0,i.useEffect)(()=>{ns(hi())},[]);let Fa=H&&(on||(Tr?Xi:io===!1)),Ba=M&&es,Mr=!He&&Fa&&on,Da=Ma==="retrying"||Ma==="exhausted",Fr=!He&&Fa&&!!de&&(!on||Da),Br=!He&&Ba&&!!D,Dr=!He&&M&&no&&ao.length>0&&!!D,rs=Mr&&!Da?ts:Fr&&ki(Ea),os=Br&&ki(_a),as=Dr&&Ta!=="load_error",La=s=>s==="loading"||s==="ready",Oa=Mr||Fr&&La(Ea)||Br&&La(_a)||Dr&&Ta!=="load_error",so=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(!so.current){if(!M&&!H){so.current=!0;let s=new P.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(s),j(s.message)}else if(!M&&H&&!on&&!de){so.current=!0;let s=new P.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(s),j(s.message)}else if(io!==void 0&&!He&&!tt&&!Oa){so.current=!0;let s=new P.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"});p?.(s),j(s.message)}}},[M,H,on,de,io,He,tt,Oa,p,j]);let Na=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(Na.current||!no)return;let s=[];O!==!0&&s.push("showApplePay"),Z!==!0&&s.push("showGooglePay"),s.length!==0&&(Na.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.`))},[no,O,Z]);let za=(0,i.useCallback)((s,U)=>J.applyInlineSessionPatch?J.applyInlineSessionPatch(s).then(X=>({error:null,sessionId:X.sessionId||e,nonce:X.session?.clientSecret||t})).catch(X=>{let pe=wi(U,X);return j(pe.message),p?.(pe),{error:pe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[J.applyInlineSessionPatch,t,p,e,j]),wn=(0,i.useCallback)(async s=>{if(!Me)return{proceed:!0};try{let U=await Me({method:s,sessionId:e||void 0,createSession:J.inlineSessionDraft});if(U===!1)return{proceed:!1};if(U&&typeof U=="object"){U.account&&ln(pe=>({...pe??{},...U.account}));let X=await za(U,s);return X.error?{proceed:!1,accountPatch:U.account}:{proceed:!0,accountPatch:U.account,sessionId:X.sessionId,nonce:X.nonce}}return{proceed:!0}}catch(U){let X=wi(s,U);return j(X.message),p?.(X),{proceed:!1}}},[za,J.inlineSessionDraft,Me,p,e,j]),Ua=(0,i.useCallback)(async(s,U)=>{if(yn.current)return;yn.current=!0,A(!0),nt("processing"),j(null);let X=U?.sessionId??e,pe=U?.nonce??t,W=ea(b,U?.accountPatch),ke=U?.completionPaymentMethodId??jr(s),Fe=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,ht=s.gateway==="stripe"?"stripe":s.gateway==="paypal"||s.isPaypal?"paypal":void 0,$t=()=>{Ct?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:ht})};try{let lt=await new er.PaymentAPI(C).processPayment(W.userId??"",{sessionId:X,nonce:pe,tokenizedData:Fe,accountData:{userId:W.userId??"",email:W.email??"",firstName:W.firstName??"",lastName:W.lastName??"",...me?(()=>{let Xe=Lt.current,gn=(0,P.isAVSFieldVisible)(me.state,Xe),hn=(0,P.isAVSFieldVisible)(me.address_line_1,Xe),Bt=(0,P.isAVSFieldVisible)(me.postal_code,Xe),Ur=hn&&!gn&&Bt?(0,P.getStateFromPostalCode)(Xe,(at.current??"").trim()):null,$r=gn?bn.current:Ur;return{country:Xe,...Bt&&at.current?{zip:at.current}:{},...(0,P.isAVSFieldVisible)(me.city,Xe)&&dt.current?{city:dt.current}:{},...$r?{state:$r}:{},...hn&&Je.current?{addressLine1:Je.current}:{},...(0,P.isAVSFieldVisible)(me.address_line_2,Xe)&&An.current?{addressLine2:An.current}:{}}})():{}},chv:k,avsCheck:qe??!1,checkoutType:ue,checkoutLayout:L,avsConfig:me?{country:(0,P.isAVSFieldVisible)(me.country,Lt.current),postal_code:(0,P.isAVSFieldVisible)(me.postal_code,Lt.current),address_line_1:(0,P.isAVSFieldVisible)(me.address_line_1,Lt.current),address_line_2:(0,P.isAVSFieldVisible)(me.address_line_2,Lt.current),city:(0,P.isAVSFieldVisible)(me.city,Lt.current),state:(0,P.isAVSFieldVisible)(me.state,Lt.current)}:void 0});if(lt.ok){let Xe=lt.status===204?null:await lt.json().catch(()=>null),gn=(0,P.isAuthorizationOnlySession)(ce)||Xe?.status==="authorized";kr(X),nt("success"),xt(null),await new Promise(hn=>setTimeout(hn,1200)),a?.(gn?{status:"authorized",...typeof Xe?.paymentId=="string"?{paymentId:Xe.paymentId}:ce?.paymentId?{paymentId:ce.paymentId}:{},sessionId:typeof Xe?.sessionId=="string"?Xe.sessionId:X,...typeof Xe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Xe.authorizationExpiresAt}:ce?.authorizationExpiresAt?{authorizationExpiresAt:ce.authorizationExpiresAt}:{},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:ke,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:ke,checkoutMethod:s.isPaypal?"paypal":"card"});return}let Ke=await lt.json().catch(()=>null);if(Ke?.type==="paypal_redirect_required"){let Xe=Ke.threeDSecureToken,gn=Ke.paymentMethodId||s.id||"";if(!je||!Xe){nt("error"),j("PayPal authorization required but no token provided.");return}try{let hn=bt?.getRawProvider();if(!hn){j("PayPal is not available.");return}let Bt={return_url:window.location.href};gn&&(Bt.payment_method=gn);let{error:Ur}=await hn.confirmPayment({clientSecret:Xe,confirmParams:Bt,redirect:"if_required"});if(Ur){nt("error");let $r=Ur.message??"PayPal payment failed.";j($r),kt("paypal",$r,{code:Ur.code})}}catch(hn){nt("error"),j(hn instanceof Error?hn.message:"PayPal authorization failed.")}return}if(Ke?.type==="paypal_direct_required"){let Xe=Ke.orderId;if(!Xe){nt("error"),j("PayPal retry required but no order id provided.");return}let gn=nr.current?.attempts??0;if(gn>=2){nt("error"),j("PayPal payment could not be completed after multiple attempts."),kt("paypal","paypal_direct_required retry limit exceeded");return}jo(!1),Vo("loading"),xt({orderId:Xe,attempts:gn+1}),nt(null);return}(0,P.classifyPaymentRejection)(lt.status,Ke)||$t(),nt("error");let qn=Ke?.message??"Payment failed. Please try again.";j(qn),kt(s.isPaypal?"paypal":"card",qn,{code:Ke?.code??Ke?.gatewayErrorCode,declineCode:Ke?.declineCode??Ke?.gatewayDeclineReason}),await new Promise(Xe=>setTimeout(Xe,1500))}catch(Pt){_i(Pt)||$t(),nt("error"),j(Pt instanceof Error?Pt.message:"An unexpected error occurred"),await new Promise(lt=>setTimeout(lt,1500))}finally{A(!1),nt(null),yn.current=!1}},[C,e,t,b,S,k,je,bt,ce,a,p,j,kt,Ct]),fn=(0,i.useCallback)((s,U)=>{I?I(s):Ua(s,U)},[I,Ua]),$a=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(typeof window>"u"||$a.current)return;let s=new URLSearchParams(window.location.search),U=s.get("payment_intent"),X=s.get("payment_intent_client_secret"),pe=s.get("redirect_status");if(!U||!X)return;let W=lt=>{let Ke=localStorage.getItem(lt);if(!Ke)return null;try{return JSON.parse(Ke)}catch{return localStorage.removeItem(lt),null}},ke=W(Ln)??W(bi),Fe;if(ke?.clientSecret){if(ke.clientSecret!==X)return;Fe={...ke.accountPatch?{accountPatch:ke.accountPatch}:{},...ke.sessionId?{sessionId:ke.sessionId}:{},...ke.nonce?{nonce:ke.nonce}:{}}}else if(ke?.sessionId&&ke.sessionId!==e)return;$a.current=!0,localStorage.removeItem(Ln),localStorage.removeItem(bi);let ht=new URL(window.location.href);ht.searchParams.delete("payment_intent"),ht.searchParams.delete("payment_intent_client_secret"),ht.searchParams.delete("redirect_status"),window.history.replaceState({},"",ht.toString());let $t=ke?.paymentMethodType??ke?.tokenType??"card",Pt="card";(async()=>{let lt=je?.getRawProvider();if(!lt){let Bt="Payment is not available \u2014 please refresh and try again.";j(Bt),kt(Pt,Bt);return}if(pe==="failed"){let Bt="Payment was declined. Please try again.";j(Bt),kt(Pt,Bt);return}let{paymentIntent:Ke,error:qn}=await lt.retrievePaymentIntent(X);if(qn){let Bt=qn.message??"Failed to retrieve payment status.";j(Bt),kt(Pt,Bt,{code:qn.code});return}let Xe=Ke?.status,gn=go(Xe);if(!Ke||!gn){let Bt=Xe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";j(Bt),kt(Pt,Bt,{code:Xe??"missing_payment_intent"});return}let hn=typeof Ke.payment_method=="string"?Ke.payment_method:Ke.payment_method?.id;fn({id:hn??ke?.paymentMethodId??ke?.tokenId??Ke.id,type:"card",threeDSecureActionResultTokenId:Ke.id,gateway:ke?.gateway??"stripe",paymentMethodType:$t},Fe)})()},[e,fn,je,j,kt]);let Ko=(0,i.useCallback)(s=>{s.preventDefault()},[]);if(!(je!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Lr=Q==="buttons",Qt=q?.variables,is=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ho=Qt?.colorBackground,ss=Ho&&!is.has(Ho)?Ho:void 0,Or=m.cardInputBorder??(Lr?"#e5e7eb":"#A4A4FF"),Yo=Qt?.colorDanger??"#dc2626",or=s=>cn&&s?Yo:Or,lo=(Xt.malformed||Xt.empty)&&(Gn||cn),ls=lo?Yo:or(it.zip),Wo=m.cardFormContainer?.backgroundColor??ss??(Lr?"white":"#EDEDFF"),Nr=m.cardInputBackground??Qt?.colorBackground??"white",Go=fr(he),qa=fr($),yr=m.nameInput,ja=m.cardInputFontSize??Qs(yr?.fontSize)??Qt?.fontSizeBase??"16px",Va=typeof yr?.fontFamily=="string"?yr.fontFamily:Qt?.fontFamily??"Poppins, sans-serif",Ka=sa(yr?.fontWeight)??400,cs=m.cardInputColor??(typeof yr?.color=="string"?yr.color:void 0)??Qt?.colorText??"#262833",ds=m.cardInputPlaceholderColor??"#9ca3af",It=Qt?.borderRadius??"8px",ar=Qt?.borderRadius??m.cardButton?.borderRadius??It,ir=Qt?.colorPrimary??"#4A49FF",us=Qt?.colorPrimaryHover??_r(ir,.12),Jo=Qt?.colorText??"#262833",Ha={fontSize:ja,fontFamily:Va,fontWeight:Ka,color:cs,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ps={"--flopay-input-placeholder-color":ds,"--flopay-input-font-size":ja,"--flopay-input-font-family":Va,"--flopay-input-font-weight":String(Ka)},zr=m.cardFormContainer??{},Xo=zr.padding??(Lr?"0":"1rem"),Zo=zr.borderRadius??It,ms=ut&&nn?(0,l.jsx)(Rr,{capture:ut,html:nn.html,messageToken:nn.messageToken,expectedOrigin:nn.expectedOrigin,theme:ae,onReady:()=>{if(!me||typeof document>"u")return;let s=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};s();let U=0,X=window.setInterval(()=>{U+=1;let pe=document.activeElement;!!pe&&pe.tagName==="IFRAME"&&pe.id==="flopay_vault_form_iframe"?(s(),window.clearInterval(X)):U>=50&&window.clearInterval(X)},100)},onError:s=>j(s),onValidation:s=>{let U=pt.current;(U==="idle"||U==="validation-window")&&(j(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"}),Ya=(0,l.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&mn()},style:{backgroundColor:Wo,borderRadius:Zo,...zr,padding:Xo,...ps,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
- `}),xr&&ir&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:We?-2:0},children:[(0,c.jsxs)("button",{type:"button",onClick:pn,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})]}),Ia?(0,c.jsx)("div",{style:{flex:1}}):(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:l.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...l.title},children:(0,c.jsx)(Fr,{content:ie})})]}),!xr&&!Ia&&(0,c.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:zo,order:We?-3:0,...l.title},children:(0,c.jsx)(Fr,{content:ie})}),le&&(0,c.jsx)("div",{style:{order:We?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=et,N=(Y=!1)=>({backgroundColor:Mr,border:`1px solid ${Gn(Y)}`,borderRadius:Pt,marginTop:"0.5rem",padding:"10px"}),G=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ma}),fe=(0,v.getStateOptions)(s);return(0,c.jsxs)(c.Fragment,{children:[(0,v.isAVSFieldVisible)(le.address_line_1,s)&&(0,c.jsx)("div",{style:N(St.line1),children:(0,c.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:Oe,onChange:Y=>{Mt.current.addressLine1=!0,dn.current=Y.target.value,gt(Y.target.value)},disabled:Q,required:!0,"data-testid":"flopay-address-line1",style:G()})}),(0,v.isAVSFieldVisible)(le.address_line_2,s)&&(0,c.jsx)("div",{style:N(),children:(0,c.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:Fe,onChange:Y=>{Mt.current.addressLine2=!0,$t.current=Y.target.value,rn(Y.target.value)},disabled:Q,"data-testid":"flopay-address-line2",style:G()})}),((0,v.isAVSFieldVisible)(le.city,s)||(0,v.isAVSFieldVisible)(le.state,s))&&(0,c.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,v.isAVSFieldVisible)(le.city,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Mr,borderTop:`1px solid ${Gn(St.city)}`,borderRight:`1px solid ${Gn(St.city)}`,borderBottom:`1px solid ${Gn(St.city)}`,borderLeft:`1px solid ${Gn(St.city)}`,padding:"10px",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,...(0,v.isAVSFieldVisible)(le.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Pt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Ye,onChange:Y=>{Mt.current.city=!0,jt.current=Y.target.value,zn(Y.target.value)},disabled:Q,required:!0,"data-testid":"flopay-city",style:G()})}),(0,v.isAVSFieldVisible)(le.state,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Mr,border:`1px solid ${Gn(St.state)}`,padding:"10px",borderTopRightRadius:Pt,borderBottomRightRadius:Pt,...(0,v.isAVSFieldVisible)(le.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:Pt}},children:fe?(0,c.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Wt,onChange:Y=>{Mt.current.state=!0,Vt.current=Y.target.value,wn(Y.target.value)},disabled:Q,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...G(),cursor:"pointer"},children:[(0,c.jsx)("option",{value:"",children:(0,v.getStateLabel)(s)}),fe.map(Y=>(0,c.jsx)("option",{value:Y.code,children:Y.name},Y.code))]}):(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,v.getStateLabel)(s),autoComplete:"billing address-level1",value:Wt,onChange:Y=>{Mt.current.state=!0,Vt.current=Y.target.value,wn(Y.target.value)},disabled:Q,required:!0,"data-testid":"flopay-state",style:G()})})]}),((0,v.isAVSFieldVisible)(le.country,s)||(0,v.isAVSFieldVisible)(le.postal_code,s))&&(0,c.jsxs)("div",{style:{display:"flex",flexDirection:ne==="column"?"column":"row",gap:ne==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,v.isAVSFieldVisible)(le.country,s)&&(0,c.jsx)("div",{style:{flex:ne==="row"?1:void 0,backgroundColor:Mr,borderTop:`1px solid ${Tr}`,borderRight:`1px solid ${Tr}`,borderBottom:`1px solid ${Tr}`,borderLeft:`1px solid ${Tr}`,padding:"10px",...ne==="row"&&(0,v.isAVSFieldVisible)(le.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,borderRight:"none"}:{borderRadius:Pt}},children:(0,c.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:et,onChange:Y=>{Mt.current.country=!0,pt.current=Y.target.value,tt(Y.target.value),Qe?.(Y.target.value),Vt.current="",wn("")},disabled:Q,autoComplete:"billing country","data-testid":"flopay-country",style:{...G(),cursor:"pointer"},children:v.COUNTRY_OPTIONS.map(Y=>(0,c.jsxs)("option",{value:Y.code,children:[Y.flag," ",Y.name]},Y.code))})}),(0,v.isAVSFieldVisible)(le.postal_code,s)&&(0,c.jsx)("div",{style:{flex:ne==="row"?1:void 0,backgroundColor:Mr,border:`1px solid ${Hi}`,padding:"10px",...ne==="row"&&(0,v.isAVSFieldVisible)(le.country,s)?{borderRadius:"0",borderTopRightRadius:Pt,borderBottomRightRadius:Pt}:{borderRadius:Pt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,v.getPostalCodeLabel)(et),autoComplete:"billing postal-code",value:It,onChange:Y=>{Mt.current.zip=!0,Ut.current=Y.target.value,ft(Y.target.value),Ve?.(Y.target.value)},onBlur:()=>Jt(!0),disabled:Q,required:qt.required,"aria-invalid":Qr||void 0,"aria-describedby":Qr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:G()})})]}),Qr&&(0,c.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Do,...Ma,fontSize:"0.75rem"},children:qt.empty?`${(0,v.getPostalCodeLabel)(s)} is required`:Rs(s)})]})})()}),We&&J&&(0,c.jsx)("div",{style:{order:-2,width:"100%"},children:J}),We&&Ji,q&&(0,c.jsx)(yr,{margin:"0.75rem 0",styleOverride:l.errorBanner,children:q})]}),Zr={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},Ba=s=>ot?!E||!xn?(0,c.jsx)("pre",{"data-testid":s,style:Zr,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":s,style:Zr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${E}`,` directPaypalConfigured=${xn}`,` inAppBrowserDetected=${String(Jr)}`,` shouldRenderDirectPayPal=${Rr}`,` shouldRenderStripePayPal=${Er}`,` hasPaypalStripeInstance=${!!z}`].join(`
39
- `)}):null,Fa=s=>ot?!_||!I?(0,c.jsx)("pre",{"data-testid":s,style:Zr,children:"FloPay/Stripe-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":s,style:Zr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${_}`,` currency=${be}`,` amountInCents=${ye}`,` enabledPaymentMethods: ${JSON.stringify(f??[])}`,` enabledPaymentMethodsProvided=${wr}`,` hasEnabledMethods=${Kr}`,` expressMethods: ${JSON.stringify(Yr)}`,` walletExpressMethods: ${JSON.stringify(Wr)}`,` paymentElementMethods: ${JSON.stringify(kr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Gr)}`,` hasStripeInstance=${!!I}`,` shouldRenderWallets=${Ir}`,` shouldRenderPaymentElement=${_r}`].join(`
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
+ `}),Lr&&pn&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ie?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:Un,style:{display:"inline-flex",alignItems:"center",gap:Go?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.backButton},"aria-label":"Back to payment methods",children:[(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",...m.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)(hr,{content:he})]}),qa?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:m.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...m.title},children:(0,l.jsx)(qr,{content:$})})]}),!Lr&&!qa&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Jo,order:Ie?-3:0,...m.title},children:(0,l.jsx)(qr,{content:$})}),me&&(0,l.jsx)("div",{style:{order:Ie?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Ue,U=(W=!1)=>({backgroundColor:Nr,border:`1px solid ${or(W)}`,borderRadius:It,marginTop:"0.5rem",padding:"10px"}),X=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ha}),pe=(0,P.getStateOptions)(s);return(0,l.jsxs)(l.Fragment,{children:[(0,P.isAVSFieldVisible)(me.address_line_1,s)&&(0,l.jsx)("div",{style:U(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:St,onChange:W=>{Ot.current.addressLine1=!0,Je.current=W.target.value,et(W.target.value)},disabled:E,required:!0,"data-testid":"flopay-address-line1",style:X()})}),(0,P.isAVSFieldVisible)(me.address_line_2,s)&&(0,l.jsx)("div",{style:U(),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:Ft,onChange:W=>{Ot.current.addressLine2=!0,An.current=W.target.value,Ge(W.target.value)},disabled:E,"data-testid":"flopay-address-line2",style:X()})}),((0,P.isAVSFieldVisible)(me.city,s)||(0,P.isAVSFieldVisible)(me.state,s))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,P.isAVSFieldVisible)(me.city,s)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Nr,borderTop:`1px solid ${or(it.city)}`,borderRight:`1px solid ${or(it.city)}`,borderBottom:`1px solid ${or(it.city)}`,borderLeft:`1px solid ${or(it.city)}`,padding:"10px",borderTopLeftRadius:It,borderBottomLeftRadius:It,...(0,P.isAVSFieldVisible)(me.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:It}},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:W=>{Ot.current.city=!0,dt.current=W.target.value,_t(W.target.value)},disabled:E,required:!0,"data-testid":"flopay-city",style:X()})}),(0,P.isAVSFieldVisible)(me.state,s)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Nr,border:`1px solid ${or(it.state)}`,padding:"10px",borderTopRightRadius:It,borderBottomRightRadius:It,...(0,P.isAVSFieldVisible)(me.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:It}},children:pe?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:tn,onChange:W=>{Ot.current.state=!0,bn.current=W.target.value,Dt(W.target.value)},disabled:E,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...X(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,P.getStateLabel)(s)}),pe.map(W=>(0,l.jsx)("option",{value:W.code,children:W.name},W.code))]}):(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,P.getStateLabel)(s),autoComplete:"billing address-level1",value:tn,onChange:W=>{Ot.current.state=!0,bn.current=W.target.value,Dt(W.target.value)},disabled:E,required:!0,"data-testid":"flopay-state",style:X()})})]}),((0,P.isAVSFieldVisible)(me.country,s)||(0,P.isAVSFieldVisible)(me.postal_code,s))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:re==="column"?"column":"row",gap:re==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,P.isAVSFieldVisible)(me.country,s)&&(0,l.jsx)("div",{style:{flex:re==="row"?1:void 0,backgroundColor:Nr,borderTop:`1px solid ${Or}`,borderRight:`1px solid ${Or}`,borderBottom:`1px solid ${Or}`,borderLeft:`1px solid ${Or}`,padding:"10px",...re==="row"&&(0,P.isAVSFieldVisible)(me.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:It,borderBottomLeftRadius:It,borderRight:"none"}:{borderRadius:It}},children:(0,l.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Ue,onChange:W=>{Ot.current.country=!0,Lt.current=W.target.value,qt(W.target.value),fe?.(W.target.value),bn.current="",Dt("")},disabled:E,autoComplete:"billing country","data-testid":"flopay-country",style:{...X(),cursor:"pointer"},children:P.COUNTRY_OPTIONS.map(W=>(0,l.jsxs)("option",{value:W.code,children:[W.flag," ",W.name]},W.code))})}),(0,P.isAVSFieldVisible)(me.postal_code,s)&&(0,l.jsx)("div",{style:{flex:re==="row"?1:void 0,backgroundColor:Nr,border:`1px solid ${ls}`,padding:"10px",...re==="row"&&(0,P.isAVSFieldVisible)(me.country,s)?{borderRadius:"0",borderTopRightRadius:It,borderBottomRightRadius:It}:{borderRadius:It}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,P.getPostalCodeLabel)(Ue),autoComplete:"billing postal-code",value:Jt,onChange:W=>{Ot.current.zip=!0,at.current=W.target.value,Ze(W.target.value),$e?.(W.target.value)},onBlur:()=>Sn(!0),disabled:E,required:Xt.required,"aria-invalid":lo||void 0,"aria-describedby":lo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:X()})})]}),lo&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Yo,...Ha,fontSize:"0.75rem"},children:Xt.empty?`${(0,P.getPostalCodeLabel)(s)} is required`:Xs(s)})]})})()}),Ie&&K&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:K}),Ie&&ms,u&&(0,l.jsx)(wr,{margin:"0.75rem 0",styleOverride:m.errorBanner,children:u})]}),co={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},Wa=s=>V?!H||!on?(0,l.jsx)("pre",{"data-testid":s,style:co,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":s,style:co,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${H}`,` directPaypalConfigured=${on}`,` inAppBrowserDetected=${String(io)}`,` shouldRenderDirectPayPal=${Mr}`,` shouldRenderStripePayPal=${Fr}`,` hasPaypalStripeInstance=${!!de}`].join(`
39
+ `)}):null,Ga=s=>V?!M||!D?(0,l.jsx)("pre",{"data-testid":s,style:co,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":s,style:co,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${M}`,` currency=${ee}`,` amountInCents=${Pe}`,` enabledPaymentMethods: ${JSON.stringify(f??[])}`,` enabledPaymentMethodsProvided=${Tr}`,` hasEnabledMethods=${no}`,` expressMethods: ${JSON.stringify(ro)}`,` walletExpressMethods: ${JSON.stringify(oo)}`,` paymentElementMethods: ${JSON.stringify(Ar)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(ao)}`,` hasStripeInstance=${!!D}`,` shouldRenderWallets=${Br}`,` shouldRenderPaymentElement=${Dr}`].join(`
40
+ `)}):null,Ja=we==="apm-expanding"||we==="apm-form"||we==="apm-collapsing",uo=we==="apm-expanding"?`flopay-card-enter ${Nt}ms cubic-bezier(0, 0, 0.2, 1) both`:we==="apm-collapsing"?`flopay-card-exit ${Nt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,po=st?{...qo,paymentMethodTypes:[st]}:null;if(Q==="buttons"){let s=we==="buttons"||we==="expanding"||we==="apm-expanding",U=we==="expanding"||we==="card"||we==="collapsing",X=Se===void 0?{boxSizing:"border-box",height:Ao,padding:"0 1rem"}:{padding:"0.9rem 1rem"},pe=we==="expanding"||we==="apm-expanding"?`flopay-buttons-exit ${Nt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:we==="collapsing"||we==="apm-collapsing"?`flopay-buttons-enter ${Nt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,W=we==="expanding"?`flopay-card-enter ${Nt}ms cubic-bezier(0, 0, 0.2, 1) both`:we==="collapsing"?`flopay-card-exit ${Nt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,l.jsxs)("form",{onSubmit:Ko,className:w,style:{position:"relative"},children:[(0,l.jsx)(ca,{}),zt&&(0,l.jsx)(Pn,{status:zt,errorMessage:u,authorized:Mn}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!pe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!pe?Ws:{},...pe?{animation:pe,pointerEvents:"none"}:{}},children:[Wa("flopay-direct-paypal-gate-debug"),Ga("flopay-stripe-gate-debug"),Mr&&Le&&(0,l.jsxs)(l.Fragment,{children:[Zt&&(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)(Kr,{sessionId:e,nonce:t,billingApiUrl:mt,email:b.email,clientId:Le.clientId,environment:Le.environment,currency:ee.toUpperCase(),isSubscription:Qe,providerObjectType:Le.providerObjectType,onTokenizedBody:fn,onComplete:a,onErrorChange:j,onDecline:d,onTechnicalFailure:We,onButtonClick:oe,runBeforeButtonClick:wn,isProcessing:E,onLoadStateChange:jo,onInitializationStateChange:Vo,session:ce??null,existingOrderId:Zt?.orderId,debug:V},Zt?.orderId??"fresh")]}),Fr&&(0,l.jsx)(vt.Elements,{stripe:de,options:Re,children:(0,l.jsx)(Ii,{sessionId:e,nonce:t,email:b.email,billingApiUrl:mt,onTokenizedBody:fn,onErrorChange:j,isProcessing:E,onButtonClick:oe,onDecline:d,onTechnicalFailure:We,runBeforeButtonClick:wn,onLoadStateChange:Ra,placeholderBorderRadius:ar})}),Br?(0,l.jsx)(vt.Elements,{stripe:D,options:Ee,children:(0,l.jsx)(Ei,{sessionId:e,nonce:t,email:b.email,billingApiUrl:mt,intentKind:le>0?"payment":"setup",expressMethods:oo,onTokenizedBody:fn,onErrorChange:j,onButtonClick:oe,onDecline:d,onTechnicalFailure:We,runBeforeButtonClick:wn,onLoadStateChange:xa,placeholderBorderRadius:ar})}):Ba?(0,l.jsx)("div",{style:{height:Ao,borderRadius:ar,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Dr&&(0,l.jsx)(Ri,{sessionId:e,nonce:t,email:b.email,billingName:[b.firstName,b.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:mt,paymentElementMethods:ao,stripeInstance:D,paymentElementBaseOptions:qo,onTokenizedBody:fn,onErrorChange:j,onButtonClick:oe,onDecline:d,runBeforeButtonClick:wn,onLoadStateChange:Aa,isProcessing:E,submitButtonColor:ir,submitButtonBorderRadius:It,submitButtonStyle:m.submitButton,onExpandApm:Dn,expandedApmMethod:st,themeId:ve,buttonAppearance:{backgroundColor:m.cardButton?.backgroundColor,borderColor:m.cardInputBorder,textColor:m.cardButton?.color,borderRadius:ar}}),Ie&&(0,l.jsx)("button",{type:"button",onClick:async()=>{E||!(await wn("card")).proceed||(oe?.("card"),Jn())},disabled:E,style:{width:"100%",...X,...m.cardButton,...pa({themeBundle:c,resolvedPrimaryColor:ir,resolvedBorderRadius:It,submitButtonStyle:m.submitButton,explicitPrimaryColor:Qt?.colorPrimary}),fontSize:m.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:E?"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:E?.6:1},onMouseEnter:ke=>{!E&&(c||Qt?.colorPrimary)&&(ke.currentTarget.style.backgroundColor=us)},onMouseLeave:ke=>{(c||Qt?.colorPrimary)&&(ke.currentTarget.style.backgroundColor=ir)},onMouseDown:ke=>{ke.currentTarget.style.transform="scale(0.985)"},onMouseUp:ke=>{ke.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(gr,{content:Se})}),u&&we==="buttons"&&(0,l.jsx)(wr,{margin:"0.25rem 0",styleOverride:m.errorBanner,children:u})]}),Ie&&U&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...W?{animation:W}:{},...we==="collapsing"?{pointerEvents:"none"}:{}},children:Ya}),M&&Ja&&st&&po&&D&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...uo?{animation:uo}:{},...we==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Wo,borderRadius:Zo,...zr,padding:Xo},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:$n,style:{display:"inline-flex",alignItems:"center",gap:Go?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.backButton},"aria-label":"Back to payment methods",children:[(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",...m.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)(hr,{content:he})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:m.titleFontSize??"1.05rem",color:Jo,paddingRight:80,...m.title},children:`Pay with ${(0,P.getStripeMethodDisplayName)(st)}`})]}),(0,l.jsx)(vt.Elements,{stripe:D,options:po,children:(0,l.jsx)(da,{method:st,sessionId:e,nonce:t,email:b.email,billingName:[b.firstName,b.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:mt,onTokenizedBody:fn,onErrorChange:j,onDecline:d,onCancel:$n,runBeforeButtonClick:wn,onButtonClick:oe,isProcessing:E,submitButtonColor:ir,submitButtonBorderRadius:It,submitButtonStyle:m.submitButton,errorText:u})},st)]})})]})]})}return Ja&&st&&po&&D&&M?(0,l.jsxs)("form",{onSubmit:Ko,className:w,style:{position:"relative"},children:[(0,l.jsx)(ca,{}),zt&&(0,l.jsx)(Pn,{status:zt,errorMessage:u,authorized:Mn}),(0,l.jsx)("div",{style:{...uo?{animation:uo}:{},...we==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Wo,borderRadius:Zo,...zr,padding:Xo},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:$n,style:{display:"inline-flex",alignItems:"center",gap:Go?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.backButton},"aria-label":"Back to payment methods",children:[(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",...m.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)(hr,{content:he})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:m.titleFontSize??"1.05rem",color:Jo,paddingRight:80,...m.title},children:`Pay with ${(0,P.getStripeMethodDisplayName)(st)}`})]}),(0,l.jsx)(vt.Elements,{stripe:D,options:po,children:(0,l.jsx)(da,{method:st,sessionId:e,nonce:t,email:b.email,billingName:[b.firstName,b.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:mt,onTokenizedBody:fn,onErrorChange:j,onDecline:d,onCancel:$n,runBeforeButtonClick:wn,onButtonClick:oe,isProcessing:E,submitButtonColor:ir,submitButtonBorderRadius:It,submitButtonStyle:m.submitButton,errorText:u})},st)]})})]}):(0,l.jsxs)("form",{onSubmit:Ko,className:w,style:{position:"relative"},children:[(0,l.jsx)(ca,{}),zt&&(0,l.jsx)(Pn,{status:zt,errorMessage:u,authorized:Mn}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Wa("flopay-direct-paypal-gate-debug-default"),Ga("flopay-stripe-gate-debug-default"),Mr&&Le&&(0,l.jsxs)(l.Fragment,{children:[Zt&&(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)(Kr,{sessionId:e,nonce:t,billingApiUrl:mt,email:b.email,clientId:Le.clientId,environment:Le.environment,currency:ee.toUpperCase(),isSubscription:Qe,providerObjectType:Le.providerObjectType,onTokenizedBody:fn,onComplete:a,onErrorChange:j,onDecline:d,onTechnicalFailure:We,onButtonClick:oe,runBeforeButtonClick:wn,isProcessing:E,onLoadStateChange:jo,onInitializationStateChange:Vo,session:ce??null,existingOrderId:Zt?.orderId,debug:V},Zt?.orderId??"fresh")]}),Fr&&(0,l.jsx)(vt.Elements,{stripe:de,options:Re,children:(0,l.jsx)(Ii,{sessionId:e,nonce:t,email:b.email,billingApiUrl:mt,onTokenizedBody:fn,onErrorChange:j,isProcessing:E,onButtonClick:oe,onDecline:d,onTechnicalFailure:We,runBeforeButtonClick:wn,onLoadStateChange:Ra,placeholderBorderRadius:ar})}),Br&&(0,l.jsx)(vt.Elements,{stripe:D,options:Ee,children:(0,l.jsx)(Ei,{sessionId:e,nonce:t,email:b.email,billingApiUrl:mt,intentKind:le>0?"payment":"setup",expressMethods:oo,onTokenizedBody:fn,onErrorChange:j,onButtonClick:oe,onDecline:d,onTechnicalFailure:We,runBeforeButtonClick:wn,onLoadStateChange:xa,placeholderBorderRadius:ar})}),Dr&&(0,l.jsx)(Ri,{sessionId:e,nonce:t,email:b.email,billingName:[b.firstName,b.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:mt,paymentElementMethods:ao,stripeInstance:D,paymentElementBaseOptions:qo,onTokenizedBody:fn,onErrorChange:j,onButtonClick:oe,onDecline:d,runBeforeButtonClick:wn,onLoadStateChange:Aa,isProcessing:E,submitButtonColor:ir,submitButtonBorderRadius:It,submitButtonStyle:m.submitButton,themeId:ve,onExpandApm:Dn,expandedApmMethod:st,buttonAppearance:{backgroundColor:m.cardButton?.backgroundColor,borderColor:m.cardInputBorder,textColor:m.cardButton?.color,borderRadius:ar}})]}),Ie&&(os||rs||as)&&(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"}})]}),Ie&&Ya]})}var R=require("react/jsx-runtime"),xr=44,Sa="flopay_checkout_saved_payment_resume",Oo=new Map,Do=new Map;function Bi(e,t){t.settled&&t.consumers===0&&Oo.get(e)===t&&Oo.delete(e)}function nl(e,t,n){let r=Do.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Do.set(e,a);let p=()=>{Do.get(e)===a&&Do.delete(e)};return o.then(p,p),o}function Xr(e){return new Promise(t=>setTimeout(t,e))}function Lo(e,t,n){let r=So({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:ge.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Zr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ma(e,t,n,r,o){let a=Lo(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Zr(a)}function rl(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function ba(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function ya(e){return!e||e.data.stripe?.publishableKey?!1:!!ba(e)?.clientId}function Hn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ol(){if(!Hn())return null;try{let e=window.sessionStorage.getItem(Sa);return e?JSON.parse(e):null}catch{return null}}function Di(e){if(Hn())try{window.sessionStorage.setItem(Sa,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function fa(){if(Hn())try{window.sessionStorage.removeItem(Sa)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var wa=":idempotency-key";function Oi(e,t){if(!Hn())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function ga(e,t,n,r){if(Hn())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function Ca(e,t){if(Hn())try{Oi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Ni(e,t){if(!Hn())return null;try{let n=window.sessionStorage.getItem(e+wa);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function ha(e,t,n){if(Hn())try{window.sessionStorage.setItem(e+wa,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Pa(e,t){if(Ca(e,t),!!Hn())try{Ni(e,t)&&window.sessionStorage.removeItem(e+wa)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function al(){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 r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Li(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function il(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 va(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Qr(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={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(o=>va(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>va(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>va(o.code??o.providerPlanId??"",o)).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(r)}function sl(e,t=!1){let n=Qr(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function ll(e,t){if(!e?.customer||!e.products)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==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 o=(0,ge.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,ge.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??o).toUpperCase()})).sort((g,h)=>`${g.code}:${g.type??""}`.localeCompare(`${h.code}:${h.type??""}`)),p=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,h)=>`${g.code}:${g.type??""}`.localeCompare(`${h.code}:${h.type??""}`));if(a.length!==p.length)return!1;for(let g=0;g<a.length;g+=1){let h=a[g],k=p[g];if(h.code!==k.code||h.type!==void 0&&h.type!==k.type||h.quantity!==k.quantity||h.totalAmount!==k.totalAmount||h.overrideAmount!==k.overrideAmount||h.currency!==k.currency)return!1}let d=[...t.couponCodes??[]].sort(),I=[...e.coupons??[]].sort();return d.length===I.length&&d.every((g,h)=>g===I[h])}function No({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:p,loading:d,error:I,onComplete:g,onError:h,onInstrument:k,onDecline:w,onCountryChange:x,onZipChange:y,showPayPal:v=!0,showStripe:H=!0,enabledPaymentMethods:M,showApplePay:f=!0,showGooglePay:ie=!0,debug:O=!1,layout:Z,theme:Q,buttonsTheme:ve,buttonsStyles:B,cardButtonContent:se,cardBackButtonContent:xe,cardTitleContent:Se,showSecurityFooter:he,onButtonClick:$,onBeforeButtonClick:N,enableAVS:oe,cardFieldOrder:Me,cardPreFormSlot:Te,avsLayout:te,className:K,initialErrorMessage:re=null,children:ye,checkoutMode:be,confirmLabel:ne,renderConfirmButton:_e,onSessionCompleted:G}){let T=(0,ge.resolveBillingApiUrl)(r),fe=(0,_.useMemo)(()=>(0,ge.resolveTheme)(Q),[Q]),$e=a??fe?.appearance,qe=n?"embedded_checkout":"standard_checkout",ue=ye?"custom_layout":Z==="buttons"?"buttons_layout":"default_layout",[L,le]=(0,_.useState)(null),[ee,ze]=(0,_.useState)(null),Le=(0,_.useRef)(null),[Qe,ce]=(0,_.useState)(null),ft=(0,_.useRef)(null),[V,je]=(0,_.useState)(null),bt=(0,_.useMemo)(()=>n?Qr(n):"",[n]),J=n?`create:${bt}`:`session:${e??""}`,Ct=V?.gateways?.stripe?"stripe":V?.gateways?.paypal?"paypal":void 0,He=(0,_.useRef)(new Set),en=(0,_.useRef)(J),Rt=(0,_.useRef)(J);Co(()=>{Rt.current=J,en.current!==J&&(en.current=J,He.current.clear())},[J]);let A=(0,_.useCallback)(u=>{if(Rt.current===J){if(na.has(u.name)){if(He.current.has(u.name))return;He.current.add(u.name)}Ne(()=>k?.(u))}},[J,k]),Ce=Sr(A,J),gt=(0,_.useRef)(!1),Ue=(0,_.useCallback)(u=>{if(gt.current)return;let c=u.gateway||!Ct?u:{...u,gateway:Ct};A(c)},[A,Ct]);(0,_.useEffect)(()=>{Ce({class:"lifecycle",name:"checkout.mount"})},[Ce]);let[qt,Jt]=(0,_.useState)(e??""),Ze=e??qt,St=n?"":Ze,[et,Ft]=(0,_.useState)(!0),[Ge,jt]=(0,_.useState)(null),[_t,tn]=(0,_.useState)("full"),[Dt,Tn]=(0,_.useState)(!1),[ln,at]=(0,_.useState)(re),[Lt,Je]=(0,_.useState)(null),[An,dt]=(0,_.useState)(null),[bn,Ot]=(0,_.useState)(!1),[me,Yn]=(0,_.useState)(void 0),[Mn,Fn]=(0,_.useState)(""),[Bn,mr]=(0,_.useState)(!1),[F,tt]=(0,_.useState)(!1),Ie=(0,_.useRef)(0),[Cn,Ve]=(0,_.useState)("loading"),[Wn,tr]=(0,_.useState)(0),Vt=(0,_.useRef)(!1),ut=(0,_.useRef)(!1),Xt=(0,_.useRef)(!1),Kt=(0,_.useRef)(null),it=(0,_.useMemo)(()=>({checkoutMode:be??_t,layout:ye?"unknown":Z==="buttons"?"buttons":"embedded"}),[be,ye,_t,Z]),cn=(0,_.useRef)(g);cn.current=g;let dn=(0,_.useRef)(h);dn.current=h;let Gn=(0,_.useRef)(w);Gn.current=w,(0,_.useEffect)(()=>{Tt(ee)?.setCheckoutContext(it),Qe&&Qe!==ee&&Tt(Qe)?.setCheckoutContext(it)},[ee,Qe,it]);let Sn=(0,_.useRef)(G);Sn.current=G;let nn=(0,_.useCallback)(u=>{Ve(u),!(u!=="exhausted"||Xt.current)&&(Xt.current=!0,dn.current?.(new ge.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),un=(0,_.useCallback)(()=>{Ve("retrying"),tr(u=>u+1)},[]);(0,_.useEffect)(()=>{Ve("loading"),tr(0),Xt.current=!1},[Ze]),(0,_.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:ge.SDK_VERSION,checkout_type:qe,checkout_layout:ue,billing_api_url:T})},[ue,qe,T]);let we=(0,_.useMemo)(()=>n?Qr(n,!0):"",[n]),wt=(0,_.useMemo)(()=>Mn===we?me:void 0,[me,Mn,we]),st=(0,_.useMemo)(()=>n?Qo(n,wt):void 0,[n,wt]),rn=be??st?.checkoutMode??"full",pn=(0,_.useMemo)(()=>st?{...st,checkoutMode:rn}:void 0,[st,rn]);(0,_.useEffect)(()=>{Yn(void 0),Fn(we)},[we]),(0,_.useEffect)(()=>{at(re)},[re]);let zn=(0,_.useCallback)((u,c,m)=>{Ne(()=>{Gn.current?.(Mt(u,c,m))})},[Ne]),mn=(0,_.useCallback)(async(u,c)=>{at(null),dt(null),Ot(!1),Je("processing");let m=c?.sessionId??u.id,q=u.gateways?.stripe?"stripe":u.gateways?.paypal?"paypal":void 0,ae=Le.current??ft.current,Y=Tt(ae),E=ae?null:Lo(T,o,it),C={log:Ee=>{Y?Y.log(Ee):E?.log(Ee)},error:Ee=>{Y?Y.error(Ee):E?.error(Ee)},terminal:Ee=>{Y?Y.terminal(Ee):E?.terminal(Ee)},performance:Ee=>{Y?Y.performance(Ee):E?.performance(Ee)},now:()=>Y?.now()??E?.now()??0,elapsed:Ee=>Y?.elapsed(Ee)??Math.max(0,(E?.now()??Ee)-Ee)},b=C.now(),S=!!(c?.initialAutoProcessingError||c?.initialAutoProcessingPending),D=!1,de,Pe=()=>{D||(D=!0,S=!0,de=C.now(),C.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),C.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Oe=!1,Ye=()=>{Oe||(Oe=!0,C.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),C.performance({stage:"processing",durationMs:C.elapsed(b),durationMode:"machine",paymentMethodCategory:"saved"}),de!==void 0&&C.performance({stage:"recovery",durationMs:C.elapsed(de),durationMode:"machine",paymentMethodCategory:"saved"}))};C.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),gt.current=!0;try{C.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{gt.current=!1}Ce({class:"lifecycle",name:"payment.processing.started",provider:q}),S&&Pe();let At;try{let Ee=yi(c?.initialAutoProcessingError),Re;if(Ee)Pe(),Ee.type==="paypal_redirect_required"&&Kt.current?.publishableKey&&Di({sessionId:m,publishableKey:Kt.current.publishableKey,paypalPublishableKey:Kt.current.paypalPublishableKey}),Re=await Ro(Ee,{flopay:Le.current,paypalFlopay:ft.current,attempt3DS:c?.attempt3DS,billingApiUrl:T,sessionId:m,session:u,telemetry:!1}),Ee.type==="paypal_redirect_required"&&fa();else if(c?.initialAutoProcessingPending){let We=(await new ur.PaymentAPI(T,{telemetry:!1}).waitForCheckoutSessionCompletion(c.initialAutoProcessingPending.sessionId,{initialDelayMs:c.initialAutoProcessingPending.retryAfterMs})).data.session;if(!vr(We))throw fo(We);Re=sr(We,m)}else{if(c?.initialAutoProcessingError)throw Qn(c.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:c.initialAutoProcessingError.checkoutMethod});if(c?.fromCreateSession)return c?.fallbackToFull&&(tn("full"),Li("full")),!1;{let j=await Er({billingApiUrl:T,sessionId:m,session:u,telemetry:!1});j.type==="success"?Re=j.result:(Pe(),j.type==="paypal_redirect_required"&&Kt.current?.publishableKey&&Di({sessionId:m,publishableKey:Kt.current.publishableKey,paypalPublishableKey:Kt.current.paypalPublishableKey}),Re=await Ro(j,{flopay:Le.current,paypalFlopay:ft.current,attempt3DS:c?.attempt3DS,billingApiUrl:T,sessionId:m,session:u,telemetry:!1}),j.type==="paypal_redirect_required"&&fa())}}m&&kr(m),Ye(),S&&(C.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),C.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),C.terminal({outcome:Re.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Ot(Re.status==="authorized"),Je("success"),await Xr(1200),At=()=>cn.current?.(Re)}catch(Ee){let Re=dr(Ee),j=Re.checkoutMethod??Gr;at(Re.message),dt(Re.message),Ot(!1),c?.fallbackToFull&&(C.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),tn("full"),Li("full")),Ye();let kt=Re.statusCode!==void 0?(0,ge.telemetryStatusClass)(Re.statusCode,"unknown"):void 0,We=kt==="4xx"?{requestCategory:"process_payment",statusClass:kt}:{},rt=kt===void 0||kt==="4xx";if(rt&&(Re.telemetryOutcome==="payment_declined"||!!(Re.declineCode||Re.code?.toLowerCase().includes("declin"))))C.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...We});else if(rt&&(Re.telemetryOutcome==="validation_rejected"||Re.type==="validation_error"))C.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...We});else{let to=(0,ge.classifyTelemetryFailure)(Ee,S?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),on=Re.telemetryRequestCategory??"process_payment";gt.current=!0;try{C.error({...to,...Re.telemetryFailureCategory?{failureCategory:Re.telemetryFailureCategory}:{},stage:S?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:on})}finally{gt.current=!1}Ce({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:on,provider:q})}return Ne(()=>dn.current?.(Re)),zn(j,Re,{code:Re.code,declineCode:Re.declineCode}),Je("error"),await Promise.allSettled([Xr(1500),c?.ensureProvidersReady?c.ensureProvidersReady():Promise.resolve()]),S&&(C.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),C.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ye(),E&&Zr(E),Je(null),dt(null)}return Ne(At),!0},[zn,Ce,Ne,dr,T,o,it]);(0,_.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 m=ol();m&&(ut.current=!0,(async()=>{let q,ae=0;at(null),dt(null),Je("processing"),Tn(!0);try{if(u.get("redirect_status")==="failed")throw Object.assign(new ge.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Y,paypalFlopay:E}=await xo({publishableKey:m.publishableKey,paypalPublishableKey:m.paypalPublishableKey,billingApiUrl:T,locale:p,telemetry:o});q=Tt(E??Y),ae=q?.now()??0,q?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),q?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let C=(E??Y)?.getRawProvider();if(!C)throw Object.assign(new ge.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:b,error:S}=await C.retrievePaymentIntent(c);if(S)throw Object.assign(new ge.FloPayError(S.message??"Failed to retrieve PayPal payment status.","api_error",{code:S.code}),{checkoutMethod:"paypal"});let D=ni(b?.status);if(!b||D==="failed")throw Object.assign(new ge.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let de=typeof b.payment_method=="string"?b.payment_method:b.payment_method?.id,Pe=D;if(m.sessionId){let At=(await new ur.PaymentAPI(T,{telemetry:!1}).getUnifiedCheckoutSession(m.sessionId)).data.session;if(At&&At.status!=="complete"){let Ee=await Er({billingApiUrl:T,sessionId:m.sessionId,session:At,telemetry:!1,tokenizedData:{id:de??b.id,type:"card",threeDSecureActionResultTokenId:b.id,isPaypal:!0}});if(Ee.type!=="success")throw Object.assign(new ge.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Pe=Ee.result.status}}m.sessionId&&kr(m.sessionId),q?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),q?.performance({stage:"redirect_resume",durationMs:q.elapsed(ae),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),q?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Je("success"),await Xr(1200),Ne(()=>cn.current?.({status:Pe,paymentIntentId:b.id,paymentMethodId:de,checkoutMethod:"paypal"}))}catch(Y){let E=dr(Y),C=E.checkoutMethod??"paypal",b=!!(E.declineCode||E.code?.toLowerCase().includes("declin"));if(q)q.performance({stage:"redirect_resume",durationMs:q.elapsed(ae),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),b?q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):q.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(b){let S=Lo(T,o,it);S.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Zr(S)}else ma(T,o,it,"REDIRECT_RESUME_FAILED","redirect_resume");at(E.message),dt(E.message),Ne(()=>dn.current?.(E)),zn(C,E,{code:E.code,declineCode:E.declineCode}),Je("error"),await Xr(1500)}finally{fa(),al(),Je(null),dt(null),Tn(!1)}})())},[zn,Ne,p,dr,T,o]);let Nt=(0,_.useRef)(null),Ht=(0,_.useMemo)(()=>pn?Qr(pn):"",[pn]),Yt=(0,_.useRef)(pn);Yt.current=pn,(0,_.useEffect)(()=>{Jt(e??"")},[e]),(0,_.useEffect)(()=>{Vt.current=!1,at(re),dt(null),Ot(!1),Je(null)},[Ht,re,e]);async function Jn(u,c,m){let q=Lo(T,o,it),ae=new ur.PaymentAPI(T,{telemetry:!1}),Y=!1;try{let E=u.idempotencyKey!==void 0?(0,ge.resolveIdempotencyKey)(u.idempotencyKey):void 0,C=Oi(c,m),b=Ni(c,m);C?.canonicalIdentity===m&&b&&b.canonicalIdentity===void 0&&(ha(c,m,b.idempotencyKey),b={...b,canonicalIdentity:m});let S=E??(b?.canonicalIdentity===m?b.idempotencyKey:void 0),D,de=!1;q.log({name:C?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let Pe=C?.sid??null,Oe=null,Ye;if(Pe)try{Oe=await ae.getUnifiedCheckoutSession(Pe,C?.nonce),C&&C.canonicalIdentity===void 0&&(ll(Oe.data.session,u)?(ga(c,m,Pe,C.nonce??Oe.data.session?.clientSecret),b&&b.canonicalIdentity===void 0&&(ha(c,m,b.idempotencyKey),S??(S=b.idempotencyKey))):(Pa(c,m),b=null,S=E,Pe=null,Oe=null));let At=Oe?.data.session?.status;if(Pe&&Oe&&At==="complete"){if(oa(Pe))return{sid:Pe,result:Oe};Pa(c,m),Pe=null,Oe=null,de=!0}}catch{q.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),C?.canonicalIdentity===void 0?(Pa(c,m),S=E):Ca(c,m),Pe=null}if(!Pe){!E&&(de||!S)&&(S=(0,ge.resolveIdempotencyKey)(),D=S),S&&ha(c,m,S);let At=q.now(),Ee=0;q.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Re={...u,idempotencyKey:S,avsCheck:!!oe,avsConfig:typeof oe=="object"?oe:void 0,checkoutType:"embedded_checkout",checkoutLayout:ye?"custom_layout":Z==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(Re,ur.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:We=>{Ee=Math.max(Ee,We)}}});let j=()=>{q.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),q.performance({stage:"session_create",durationMs:q.now()-At,durationMode:"machine",requestCategory:"session_create",attempt:Ee,statusClass:"2xx"})},kt=We=>{let rt=(0,ge.classifyTelemetryFailure)(We,"CHECKOUT_SESSION_CREATE_FAILED","unknown");q.performance({stage:"session_create",durationMs:q.now()-At,durationMode:"machine",requestCategory:"session_create",attempt:Ee,statusClass:rt.statusClass}),We instanceof ge.FloPayError&&We.type==="validation_error"?q.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):rt.statusClass==="4xx"?q.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(q.error({...rt,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Ce({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if((0,ge.isDetachedSessionEligible)(Re)){let We=await ae.createDetachedSession(Re);We.claimed.catch(()=>{}),Oe=We.shell,Pe=We.sessionId,Ye=We.claimed.then(rt=>{let rr=rt.data.session?.id??We.sessionId;return rr&&ga(c,m,rr,rt.data.session?.clientSecret??We.nonce),j(),rt},rt=>{throw Ca(c,m),kt(rt),rt}).finally(()=>Zr(q)),Ye.catch(()=>{}),Y=!0,q.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),q.performance({stage:"session_shell",durationMs:q.now()-At,durationMode:"machine",requestCategory:"session_create",attempt:Ee,statusClass:"2xx",paymentMethodCategory:"card"})}else Oe=await ae.createAndFetchSession(Re),j()}catch(We){throw kt(We),We}Pe=Oe.data.session?.id??Pe??"",Pe&&!Ye&&ga(c,m,Pe,Oe.data.session?.clientSecret)}return{sid:Pe??"",result:Oe,sdkGeneratedIdempotencyKey:D,...Ye?{claimed:Ye}:{}}}finally{Y||Zr(q)}}let Un=(0,_.useCallback)(async(u,c)=>{let m=Yt.current;if(!m)throw new ge.FloPayError("createSession is required to bootstrap checkout.","validation_error");let q=Qo(m,u),ae=Qr(q),Y=sl(q),E=Oo.get(ae);if(!E){let S={canonicalIdentity:ae,promise:Jn(q,Y,ae),consumers:0,settled:!1};E=S,Oo.set(ae,S);let D=()=>{S.settled=!0,Bi(ae,S)};S.promise.then(D,D)}E.consumers+=1;let C=!1,b=()=>{C||(C=!0,E.consumers-=1,Bi(ae,E))};c?.(b);try{let S=await E.promise;Nt.current=ae,u&&(Fn(we),Yn(Re=>Qa(Re,u)));let{sid:D,result:de,claimed:Pe}=S;if(le(de),de.data.session&&je(de.data.session),D&&Jt(D),Pe){Ie.current+=1;let Re=Ie.current;tt(!0),Pe.then(j=>{Ie.current===Re&&(le(j),j.data.session&&je(j.data.session),tt(!1))},j=>{Ie.current===Re&&(tt(!1),jt(j instanceof ge.FloPayError?j:new ge.FloPayError(j instanceof Error?j.message:"Failed to create session","api_error")))})}else Ie.current+=1,tt(!1);let{publishableKey:Oe,paypalPublishableKey:Ye}=_o(de),{flopay:At,paypalFlopay:Ee}=await xo({publishableKey:Oe,paypalPublishableKey:Ye,billingApiUrl:T,locale:p,telemetry:o});return Le.current=At,ze(At),ft.current=Ee,ce(Ee),Ft(!1),S}catch(S){throw Nt.current===ae&&(Nt.current=null),S}finally{c||b()}},[we,p,T,o,it]),Dn=(0,_.useRef)(mn);Dn.current=mn;let $n=(0,_.useRef)(Un);$n.current=Un;let zt=(0,_.useCallback)(async u=>{if(!il(u)||Bn)return{sessionId:qt,session:V};mr(!0);try{let c=await Un(u);return{sessionId:c.sid,session:c.result.data.session??null}}finally{mr(!1)}},[Un,Bn,qt,V]);(0,_.useEffect)(()=>{let u=!1,c;if(jt(null),Ht){let ae=Yt.current;return tn(rn),Ft(!1),Nt.current===Ht?()=>{u=!0}:(je(ei(ae,be)),(async()=>{let Y=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),E=rn==="auto"&&!Vt.current&&!Y;E&&(at(null),dt(null),Je("processing"));try{let C=await $n.current(void 0,de=>{c=de}),b=C.result.data.session??null;Kt.current=_o(C.result);let S=ya(C.result),D=oa(C.sid||b?.id);if(!u&&E&&b&&!S&&!D){Vt.current=!0,await nl(Ht,C.sdkGeneratedIdempotencyKey,()=>Dn.current(b,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:C.result.autoProcessingError,initialAutoProcessingPending:C.result.autoProcessingPending,autoProcessingAttempted:C.result.autoProcessingAttempted,sessionId:C.sid||b.id}));return}!u&&E&&((S||D)&&(Vt.current=!0),Je(null),dt(null))}catch(C){if(u)return;let b=C instanceof ge.FloPayError||typeof C=="object"&&C!==null&&"code"in C?C.code:void 0;if(E&&b==="session_auto_completed"){Vt.current=!0,Je("success"),await Xr(1200),u||(Ne(()=>{cn.current?.({status:"succeeded"})}),Je(null),dt(null));return}E&&(Je(null),dt(null));let S=C instanceof ge.FloPayError?C:new ge.FloPayError(C instanceof Error?C.message:"Failed to create session","api_error");jt(S)}finally{c?.(),c=void 0}})(),()=>{u=!0,c?.()})}Ft(!0);async function m(){let ae=!1;try{let E=await new ur.PaymentAPI(T,{telemetry:!1}).getUnifiedCheckoutSession(Ze,t);if(u)return;le(E);let C=E.data.session??null;if(je(C),!C)throw new ge.FloPayError("No session data returned","api_error");let b=C.checkoutMode;if(b==="setup")throw new ge.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(C.status==="authorized"){Ft(!1),Ne(()=>{cn.current?.(sr(C,Ze)),Sn.current?.(C.successUrl??"")});return}if(C.status==="complete"){Ft(!1),Ne(()=>{Sn.current?.(C.successUrl??"")});return}if(C.status==="expired")throw yo(C);ae=!0;let S=be??b??"full";tn(S);let D=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),de=ya(E);if(S==="auto"&&!Vt.current&&!D&&!de){Vt.current=!0;let Pe=q(E);try{if(await Dn.current(C,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Pe,sessionId:Ze||C.id}),u)return;await Pe,u||Ft(!1);return}catch{if(u)return;await Pe,u||Ft(!1);return}}await q(E),u||Ft(!1)}catch(Y){if(u)return;ae&&Ce({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),Y instanceof ge.FloPayError?!ae&&!rl(Y)&&ma(T,o,it,"NETWORK_REQUEST_FAILED","session_read"):ma(T,o,it,"INTERNAL_SDK_ERROR","checkout_mount");let E=Y instanceof ge.FloPayError?Y:new ge.FloPayError(Y instanceof Error?Y.message:"Failed to initialize checkout","api_error");jt(E),Ft(!1)}}async function q(ae){let{publishableKey:Y,paypalPublishableKey:E}=_o(ae);Kt.current={publishableKey:Y,paypalPublishableKey:E};let{flopay:C,paypalFlopay:b}=await xo({publishableKey:Y,paypalPublishableKey:E,billingApiUrl:T,locale:p,telemetry:o});Le.current=C,ze(C),ft.current=b,ce(b)}return m(),()=>{u=!0}},[be,Ht,rn,St,Ne,t]);let nt=(0,_.useCallback)(async()=>{if(!(Dt||!V)){Tn(!0),at(null);try{await mn(V,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ze||V.id})}finally{Tn(!1)}}},[Ze,Dt,mn,V]),yn=ba(L),Ut=ya(L),pt=(0,_.useMemo)(()=>{if(!L||!V||!L.data.stripe?.publishableKey)return;let u={appearance:$e,paymentMethodCreation:"manual",billingApiUrl:T};if(L.data.stripe?.clientSecret)u.clientSecret=L.data.stripe.clientSecret;else{let c=(0,ge.buildCheckoutDisplayData)(V).total;u.amount=Math.round(c*100)||V.amount,u.currency=V.currency?.toLowerCase()}return u},[L,V,$e,T]),Zt=!!(n&&!ye&&Z==="buttons"&&N&&rn==="full"),xt=(0,_.useMemo)(()=>({session:V,loading:et,error:Ge,checkoutMode:_t,inlineSessionDraft:pn,applyInlineSessionPatch:Zt?zt:void 0,inlineSessionPatchProcessing:Bn,claimPending:F}),[V,et,Ge,_t,pn,Zt,zt,Bn,F]),nr=!!n&&Z==="buttons"&&!Ut&&(!ee||!pt),mt=Lt?(0,R.jsx)(Pn,{status:Lt,errorMessage:An,authorized:bn}):null;if(et){if(d)return(0,R.jsxs)(R.Fragment,{children:[d,mt]});if(Z==="buttons"){let u=fe?.buttonsLayout?.cardButton?.borderRadius??fe?.appearance.variables?.borderRadius??8,c=m=>(0,R.jsx)("div",{style:{height:m,borderRadius:u,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[v&&c(xr),H&&(f||ie)&&c(xr),H&&c(xr),(0,R.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),mt]})}return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,R.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,R.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),mt]})}return Ge?I?(0,R.jsx)(kn.Provider,{value:xt,children:I(Ge)}):(0,R.jsx)(kn.Provider,{value:xt,children:(0,R.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ge.message})}):nr?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(kn.Provider,{value:xt,children:(0,R.jsx)(dl,{onButtonClick:$,showPayPal:v,showStripe:H,showApplePay:f,showGooglePay:ie,theme:Q,buttonsTheme:ve,buttonsStyles:B,cardButtonContent:se,cardBackButtonContent:xe,cardTitleContent:Se})}),mt]}):Ut&&V&&yn?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(kn.Provider,{value:xt,children:(0,R.jsxs)("div",{className:K,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ln&&(0,R.jsx)(wr,{icon:!1,children:ln}),Cn==="retrying"&&(0,R.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Cn==="exhausted"&&(0,R.jsxs)("div",{role:"alert",children:[(0,R.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,R.jsx)("button",{type:"button",onClick:un,children:"Retry PayPal"})]}),Cn!=="exhausted"&&(0,R.jsx)("div",{"aria-hidden":Cn==="retrying"?!0:void 0,style:Cn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,R.jsx)(ui,{sessionId:Ze,nonce:V.clientSecret||void 0,billingApiUrl:T,email:V.customer?.email,clientId:yn.clientId,environment:yn.environment,currency:(V.currency??"usd").toUpperCase(),isSubscription:V.mode==="subscription",providerObjectType:yn.providerObjectType,onComplete:g,onErrorChange:at,onDecline:w,onButtonClick:$,onInitializationStateChange:nn,allowAutomaticRetry:Wn===0,session:V,telemetry:o,telemetryContext:it,onInstrument:Ue,debug:O},`${J}:paypal-init-${Wn}`)})]})}),mt]}):!ee||!pt?(0,R.jsx)(R.Fragment,{children:mt}):_t==="confirm"?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(kn.Provider,{value:xt,children:(0,R.jsx)(Yr,{flopay:ee,paypalFlopay:Qe,options:pt,onInstrument:Ue,children:(0,R.jsxs)("div",{className:K,children:[ln&&(0,R.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:ln}),_e?_e({onConfirm:nt,isProcessing:Dt}):(0,R.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...":ne??"Confirm Purchase"})]})},J)}),mt]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(kn.Provider,{value:xt,children:(0,R.jsx)(Yr,{flopay:ee,paypalFlopay:Qe,options:pt,onInstrument:Ue,children:ye?(0,R.jsxs)(R.Fragment,{children:[ln&&(0,R.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:ln}),(0,R.jsx)(cl,{sessionId:Ze,nonce:V?.clientSecret||void 0,billingApiUrl:T,session:V,children:ye})]}):(0,R.jsx)(Bo,{sessionId:Ze,nonce:V?.clientSecret||void 0,email:V?.customer?.email,userId:V?.customer?.id,firstName:V?.customer?.firstName,lastName:V?.customer?.lastName,totalAmount:V?Math.round((0,ge.buildCheckoutDisplayData)(V).total*100):0,currency:V?.currency?.toLowerCase()??"usd",onComplete:g,onError:h,onDecline:w,error:ln,onErrorChange:at,showPayPal:v,showStripe:H,enabledPaymentMethods:M??L?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:L?.data.stripe?.enabledPaymentMethodCountries,showApplePay:f,showGooglePay:ie,layout:Z,theme:Q,buttonsTheme:ve,buttonsStyles:B,appearance:$e,cardButtonContent:se,cardBackButtonContent:xe,cardTitleContent:Se,onButtonClick:$,onBeforeButtonClick:N,enableAVS:oe,...Me?{cardFieldOrder:Me}:{},...Te?{cardPreFormSlot:Te}:{},avsLayout:te,country:V?.customer?.country,city:V?.customer?.city,state:V?.customer?.state,onCountryChange:x,onZipChange:y,avsCheck:!!oe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ye?"custom_layout":Z==="buttons"?"buttons_layout":"default_layout",className:K,directPaypal:ba(L),isSubscription:V?.mode==="subscription",session:V,dataAttachmentPending:F,debug:O})},J)}),mt]})}function cl({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,R.jsx)(R.Fragment,{children:_.default.Children.map(o,a=>{if(!_.default.isValidElement(a))return a;let p=a.props,d={};return p.sessionId||(d.sessionId=e),!p.nonce&&t&&(d.nonce=t),p.billingApiUrl||(d.billingApiUrl=n),r?.customer&&(p.email||(d.email=r.customer.email),p.userId||(d.userId=r.customer.id),p.firstName||(d.firstName=r.customer.firstName),p.lastName||(d.lastName=r.customer.lastName)),Object.keys(d).length===0?a:_.default.cloneElement(a,d)})})}function dl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:p,buttonsStyles:d,cardButtonContent:I,cardBackButtonContent:g,cardTitleContent:h}){let[k,w]=(0,_.useState)(!1),x=(0,_.useMemo)(()=>(0,ge.resolveTheme)(a),[a]),y=(0,_.useMemo)(()=>{let f=x?.buttonsLayout??(0,ge.resolveButtonsLayoutTheme)(p);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},[x,p,d]),v=x?.buttonsLayout?.cardButton?.borderRadius??x?.appearance.variables?.borderRadius??8,H=f=>(0,R.jsx)("div",{style:{height:f,borderRadius:v,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),M=I===void 0?{boxSizing:"border-box",height:xr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(k){let f=y.cardInputBorder??"#e5e7eb",ie=y.cardInputBackground??"white",O=fr(g),Z=fr(h);return(0,R.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,R.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,R.jsxs)("button",{type:"button",onClick:()=>w(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:O?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,R.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...y.backButtonIcon},children:(0,R.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,R.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,R.jsx)(hr,{content:g})]}),Z?(0,R.jsx)("div",{style:{flex:1}}):(0,R.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...y.title},children:(0,R.jsx)(qr,{content:h})})]}),(0,R.jsx)("div",{style:{backgroundColor:ie,border:`1px solid ${f}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsxs)("div",{style:{display:"flex"},children:[(0,R.jsx)("div",{style:{flex:1,backgroundColor:ie,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsx)("div",{style:{flex:1,backgroundColor:ie,borderTop:"none",borderRight:`1px solid ${f}`,borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,R.jsx)("div",{style:{backgroundColor:ie,border:`1px solid ${f}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.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,R.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)&&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,R.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&H(xr),n&&(r||o)&&H(xr),n&&(0,R.jsx)("button",{type:"button",onClick:()=>{e?.("card"),w(!0)},style:{width:"100%",...M,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:f=>{f.currentTarget.style.transform="scale(0.985)"},onMouseUp:f=>{f.currentTarget.style.transform="scale(1)"},children:(0,R.jsx)(gr,{content:I})}),(0,R.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Rn=require("react/jsx-runtime"),ul=44;function zi(e){return new Promise(t=>setTimeout(t,e))}function pl(e,t){return e instanceof an.FloPayError?e:new an.FloPayError(e instanceof Error?e.message:t,"api_error")}function ml(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function yl(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function Ui({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:p,items:d,subscriptions:I,account:g,successUrl:h,cancelUrl:k,couponCodes:w,tagsData:x,utmMetadata:y,billingApiUrl:v,locale:H,theme:M,appearance:f,buttonsTheme:ie,buttonsStyles:O,onSuccess:Z,onError:Q,onDecline:ve,children:B,disabled:se=!1,type:xe="button",style:Se,...he}){let $=(0,De.useMemo)(()=>(0,an.resolveBillingApiUrl)(v),[v]),N=(0,De.useMemo)(()=>yl({createSession:n,clientId:a,products:p,items:d,subscriptions:I,account:g,successUrl:h,cancelUrl:k,couponCodes:w,tagsData:x,utmMetadata:y}),[g,k,a,w,n,p,d,I,h,x,y]),[oe,Me]=(0,De.useState)(!1),[Te,te]=(0,De.useState)(null),[K,re]=(0,De.useState)(null),[ye,be]=(0,De.useState)(!1),[ne,_e]=(0,De.useState)(null),G=(0,De.useRef)(!0),T=(0,De.useRef)(null),fe=(0,De.useRef)(ne),$e=(0,De.useRef)(Z),qe=(0,De.useRef)(Q),ue=(0,De.useRef)(ve);(0,De.useEffect)(()=>{fe.current=ne},[ne]),(0,De.useEffect)(()=>{$e.current=Z},[Z]),(0,De.useEffect)(()=>{qe.current=Q},[Q]),(0,De.useEffect)(()=>{ue.current=ve},[ve]),(0,De.useEffect)(()=>(G.current=!0,()=>{G.current=!1,T.current?.abort()}),[]),(0,De.useEffect)(()=>{if(typeof window>"u")return;let A=Ce=>{Ce.key==="Escape"&&_e(null)};return window.addEventListener("keydown",A),()=>{window.removeEventListener("keydown",A)}},[]);let L=(0,De.useCallback)((A,Ce=Gr)=>{ue.current?.(Mt(Ce,A,{code:A.code,declineCode:A.declineCode}))},[]),le=(0,De.useCallback)(async A=>{G.current&&(re(null),be(A.result.status==="authorized"),te("success"),await zi(1200),G.current&&$e.current?.(A))},[]),ee=(0,De.useCallback)(async(A,Ce)=>{G.current&&(qe.current?.(A),Ce?.emitDecline&&L(A,Ce.method),re(A.message),be(!1),te("error"),await zi(1500))},[L]),ze=(0,De.useCallback)(async(A,Ce,gt)=>{let Ue=A.data.session??null;if(!Ue)throw new an.FloPayError("No session data returned","api_error");let qt=Ue.clientSecret||t;if(vr(Ue)){await le({result:sr(Ue,Ce),session:Ue,sessionId:Ue.id||Ce,autoCompleted:!1});return}if(Ue.status==="expired")throw yo(Ue);try{if(A.autoProcessingPending){let et=(await new zo.PaymentAPI($).waitForCheckoutSessionCompletion(A.autoProcessingPending.sessionId,{initialDelayMs:A.autoProcessingPending.retryAfterMs})).data.session;if(!vr(et))throw fo(et);await le({result:sr(et,Ce),session:et,sessionId:et.id||Ce,autoCompleted:!1});return}if(A.autoProcessingError){if(A.autoProcessingError.type==="3ds_required"&&A.autoProcessingError.nextActionRedirectUrl&&Ce&&qt){let Ze=new AbortController;T.current=Ze;let St;try{St=await fi({billingApiUrl:$,sessionId:Ce,nonce:qt,nextActionRedirectUrl:A.autoProcessingError.nextActionRedirectUrl,signal:Ze.signal})}finally{T.current===Ze&&(T.current=null)}if(St.status==="declined")throw Qn({type:St.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:St.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:A.autoProcessingError.checkoutMethod});let Ge=(await new zo.PaymentAPI($).waitForCheckoutSessionCompletion(Ce,{initialDelayMs:0,nonce:qt})).data.session;if(!vr(Ge))throw Qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:A.autoProcessingError.checkoutMethod});await le({result:sr(Ge,Ce),session:Ge,sessionId:Ge.id||Ce,autoCompleted:!1});return}throw Qn(A.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:A.autoProcessingError.checkoutMethod})}if(gt?.fromCreateSession&&A.autoProcessingAttempted===!0)throw Qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Jt=await Er({billingApiUrl:$,sessionId:Ce??Ue.id,session:Ue,nonce:qt});if(Jt.type!=="success")throw Qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await le({result:Jt.result,session:Ue,sessionId:Ue.id||Ce,autoCompleted:!1})}catch(Jt){let Ze=dr(Jt),St=Ue.id||Ce;await ee(Ze,{emitDecline:!0,method:Ze.checkoutMethod??Gr}),ml(Ze,St)&&St&&G.current&&_e({sessionId:St,errorMessage:Ze.message,nonce:qt||void 0})}},[t,$,ee,le]),Le=(0,De.useCallback)(async A=>{if(he.onClick?.(A),!(A.defaultPrevented||se||oe)){if(_e(null),e&&N){let Ce=new an.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await ee(Ce),G.current&&(te(null),re(null));return}if(!e&&!N){let Ce=new an.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await ee(Ce),G.current&&(te(null),re(null));return}Me(!0),re(null),be(!1),te("processing");try{let Ce=new zo.PaymentAPI($);if(e){let gt=await Ce.getUnifiedCheckoutSession(e,t);await ze(gt,e);return}try{let gt=await Ce.createAndFetchSession({...N});await ze(gt,gt.data.session?.id??null,{fromCreateSession:!0})}catch(gt){if(gt instanceof an.FloPayError&&gt.code==="session_auto_completed"){await le({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw gt}}catch(Ce){await ee(pl(Ce,"Automatic payment failed. Please try again."))}finally{G.current&&(te(null),re(null),Me(!1))}}},[he,N,se,oe,t,ze,$,e,ee,le]),Qe=(0,De.useCallback)(A=>{let Ce=fe.current;_e(null),$e.current?.({result:A,session:null,sessionId:Ce?.sessionId??null,autoCompleted:!1})},[]),ce=(0,De.useCallback)(A=>{qe.current?.(A)},[]),ft=(0,De.useCallback)(A=>{ue.current?.(A)},[]),V=(0,De.useMemo)(()=>(0,an.resolveTheme)(M),[M]),je=(0,De.useMemo)(()=>{let A=V?.buttonsLayout??(0,an.resolveButtonsLayoutTheme)(ie);return O?{...A,...O,cardButton:{...A.cardButton,...O.cardButton}}:A},[V,ie,O]),bt=(0,De.useMemo)(()=>{let A=V?.appearance;return f?A?{...A,...f,variables:{...A.variables,...f.variables}}:f:A},[f,V]),J=bt?.variables,Ct=J?.colorPrimary??"#4A49FF",He=J?.colorPrimaryHover??_r(Ct,.12),en=J?.borderRadius??"8px";return(0,Rn.jsxs)(Rn.Fragment,{children:[(0,Rn.jsx)("button",{...he,type:xe,onClick:Le,disabled:se||oe,"aria-busy":oe,style:{width:"100%",...B===void 0?{boxSizing:"border-box",height:ul,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...je.cardButton,...pa({themeBundle:V,resolvedPrimaryColor:Ct,resolvedBorderRadius:en,submitButtonStyle:je.submitButton,explicitPrimaryColor:J?.colorPrimary}),fontSize:je.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:se||oe?"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:se||oe?.6:1,...Se},onMouseEnter:A=>{he.onMouseEnter?.(A),!A.defaultPrevented&&!se&&!oe&&(V||J?.colorPrimary)&&(A.currentTarget.style.backgroundColor=He)},onMouseLeave:A=>{he.onMouseLeave?.(A),!A.defaultPrevented&&(V||J?.colorPrimary)&&(A.currentTarget.style.backgroundColor=Ct)},onMouseDown:A=>{he.onMouseDown?.(A),A.defaultPrevented||(A.currentTarget.style.transform="scale(0.985)")},onMouseUp:A=>{he.onMouseUp?.(A),A.defaultPrevented||(A.currentTarget.style.transform="scale(1)")},children:(0,Rn.jsx)(gr,{content:B})}),Te&&(0,Rn.jsx)(Pn,{status:Te,errorMessage:K,authorized:ye}),ne&&(0,Rn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:A=>{A.target===A.currentTarget&&_e(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,Rn.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,Rn.jsx)(No,{sessionId:ne.sessionId,nonce:ne.nonce,checkoutMode:"full",billingApiUrl:$,locale:H,theme:M,...bt?{appearance:bt}:{},buttonsTheme:ie,buttonsStyles:O,initialErrorMessage:ne.errorMessage,cardTitleContent:null,onComplete:Qe,onError:ce,onDecline:ft})})})]})}var pr=require("react");var Vi=require("react/jsx-runtime");function $i(e,t){function n({className:r,id:o,style:a,options:p,onChange:d,onReady:I,onFocus:g,onBlur:h,onEscape:k}){let w=(0,pr.useRef)(null),x=(0,pr.useRef)(null),{elements:y,reportInteractive:v}=(0,pr.useContext)(Wt);return(0,pr.useEffect)(()=>{if(!y||!w.current)return;let H=!0;return(async()=>{let M=y.getElement(e);M||(M=await y.create(e,p)),!(!H||!w.current)&&(M.mount(w.current),x.current=M,d&&M.on("change",d),M.on("ready",()=>{v?.(),I?.()}),g&&M.on("focus",g),h&&M.on("blur",h),k&&M.on("escape",k))})(),()=>{if(H=!1,x.current){try{x.current.unmount()}catch{}x.current=null}}},[y,v]),(0,Vi.jsx)("div",{ref:w,className:r,id:o,style:a})}return n.displayName=t,n}var qi=$i("payment","PaymentElement"),ji=$i("address","AddressElement");var Uo=require("@flopay/js/card-setup"),sn=require("@flopay/shared"),ot=require("react");var Nn=require("react/jsx-runtime"),eo=class extends sn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Ki(e,t={}){let n=e instanceof sn.FloPayError?e:void 0,r=n?.statusCode,o=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof r=="number"&&r>=500||n?.code==="vault_capture_timeout"||!n);return new eo(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:o,...n?.param?{param:n.param}:{},...r!==void 0?{statusCode:r}:{}})}function Hi({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:p=null,onReady:d,onComplete:I,onDecline:g,onCancel:h,onValidation:k,onError:w}){let[x,y]=(0,ot.useState)(null),[v,H]=(0,ot.useState)(null),[M,f]=(0,ot.useState)(null),[ie,O]=(0,ot.useState)(null),[Z,Q]=(0,ot.useState)(null),ve=(0,ot.useRef)(!1),B=(0,ot.useRef)(!1),se=(0,ot.useMemo)(()=>{if(typeof o=="object")return o;let K=(0,sn.resolveTheme)(o);if(K)return To({appearance:K.appearance,buttonsStyles:K.buttonsLayout,layout:"default"})},[o]),xe=(0,ot.useRef)(d),Se=(0,ot.useRef)(w),he=(0,ot.useRef)(I),$=(0,ot.useRef)(g),N=(0,ot.useRef)(h),oe=(0,ot.useRef)(k),Me=(0,ot.useRef)(!1),Te=(0,ot.useRef)(!1),te=(0,ot.useRef)(0);return xe.current=d,Se.current=w,he.current=I,$.current=g,N.current=h,oe.current=k,(0,ot.useEffect)(()=>{let K=te.current+1;return te.current=K,()=>{queueMicrotask(()=>{te.current===K&&(Me.current||Te.current||(Te.current=!0,Ne(()=>{N.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,ot.useEffect)(()=>{let K=!0,re=new Uo.PaymentAPI((0,sn.resolveBillingApiUrl)(n),{telemetry:r});return y(null),H(null),f(null),Me.current=!1,Te.current=!1,(async()=>{try{if(!e.trim())throw new sn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new sn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ye=await re.getUnifiedCheckoutSession(e,t);if(!K)return;let be=ye.data.session;if(!be||!(0,sn.isCardSetupCheckoutSession)(be))throw new sn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let ne=be.vault;if(ne?.html?.trim()||(ne=await re.getVaultCapture(e,t)),!ne.html?.trim())throw new sn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!K)return;H(ne),y(new Uo.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(ye){if(!K)return;let be=Ki(ye);Me.current=!0,f(be),Ne(()=>Se.current?.(be))}})(),()=>{K=!1,re.destroy()}},[n,t,e,r]),(0,ot.useEffect)(()=>{if(!x)return;let K=!1;B.current=!1,ve.current=!1;let re=x.on("submitting",()=>{ve.current=!0,Q(null),O("processing")}),ye=x.on("complete",ne=>{Me.current=!0,ve.current=!1,O("success"),(async()=>(await new Promise(_e=>setTimeout(_e,1200)),!B.current&&(B.current=!0,Ne(()=>{he.current?.({status:"succeeded",sessionId:e,...ne.paymentMethod?{paymentMethod:ne.paymentMethod}:{}})}),K||O(null))))()}),be=x.on("decline",ne=>{Me.current=!0,ve.current=!1,Q(ne.message??null),O("error"),Ne(()=>{$.current?.({status:"declined",sessionId:e,...ne.declineReason?{reason:ne.declineReason}:{},...ne.message?{message:ne.message}:{}})}),(async()=>(await new Promise(_e=>setTimeout(_e,1500)),K||O(null)))()});return()=>{K=!0,re(),ye(),be()}},[x,e]),M?(0,Nn.jsx)("div",{role:"alert",children:M.message}):!x||!v?.html?(0,Nn.jsx)(Nn.Fragment,{children:p}):(0,Nn.jsxs)(Nn.Fragment,{children:[ie&&(0,Nn.jsx)(Pn,{status:ie,errorMessage:Z,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,Nn.jsx)(Rr,{capture:x,html:v.html,messageToken:v.messageToken,expectedOrigin:v.expectedOrigin,theme:se,containerStyle:a,onReady:()=>{Ne(()=>xe.current?.())},onValidation:K=>{Ne(()=>oe.current?.(K))},onError:K=>{if(!K)return;ve.current&&(ve.current=!1,Q(K),O("error"),setTimeout(()=>O(null),1500));let re=Ki(new Error(K),{code:"card_setup_widget_failed",retryable:!0});Ne(()=>Se.current?.(re))}})]})}var Yi=require("@flopay/js"),Wi=require("@flopay/shared"),xn=require("react");var _n=require("react/jsx-runtime");function Gi({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,firstName:a,lastName:p,chv:d,onTokenizedBody:I,onComplete:g,onErrorChange:h,isProcessing:k=!1}){let w=In(),x=Po(),y=vo(),[v,H]=(0,xn.useState)(!1),[M,f]=(0,xn.useState)(!1),ie=(0,xn.useRef)(!1),O=(n||y).replace(/\/+$/,""),Z=(0,xn.useCallback)(async B=>{try{let xe=await new Yi.PaymentAPI(O).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:B,accountData:{userId:o??"",email:r??"",firstName:a??"",lastName:p??""},chv:d});if(xe.ok){g?.();return}let Se=await xe.json().catch(()=>null);h?.(Se?.message??"Payment failed. Please try again.")}catch(se){h?.(se instanceof Error?se.message:"An unexpected error occurred")}},[O,e,t,o,r,a,p,d,g,h]),Q=(0,xn.useCallback)(B=>{I?I(B):Z(B)},[I,Z]);(0,xn.useEffect)(()=>{if(!w||ie.current)return;let B=new URLSearchParams(window.location.search),se=B.get("payment_intent"),xe=B.get("payment_intent_client_secret"),Se=B.get("redirect_status");!se||!xe||(ie.current=!0,(async()=>{try{if(f(!0),Se==="failed"){h?.("PayPal payment was declined. Please try again.");return}let he=w.getRawProvider();if(!he?.retrievePaymentIntent){h?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:$,error:N}=await he.retrievePaymentIntent(xe);if(N){h?.(N.message??"Failed to retrieve PayPal payment status.");return}if($&&($.status==="requires_capture"||$.status==="succeeded")){let oe=typeof $.payment_method=="string"?$.payment_method:$.payment_method?.id;Q({id:oe??$.id,type:"card",threeDSecureActionResultTokenId:$.id,isPaypal:!0});let Me=new URL(window.location.href);Me.searchParams.delete("payment_intent"),Me.searchParams.delete("payment_intent_client_secret"),Me.searchParams.delete("redirect_status"),window.history.replaceState({},"",Me.toString())}else h?.("PayPal payment was not completed. Please try again.")}catch(he){h?.(he instanceof Error?he.message:"Failed to complete PayPal payment.")}finally{f(!1)}})())},[w,Q,h]);let ve=(0,xn.useCallback)(async()=>{if(!(!w||!x))try{if(f(!0),h?.(null),!e||!r)throw new Wi.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let B=await w.confirmPayPalPayment({billingApiUrl:O,sessionId:e,nonce:t,email:r,returnUrl:window.location.href});if(B.error){h?.(B.error.message);return}B.paymentIntentId&&(B.status==="succeeded"||B.status==="processing"||B.status==="requires_capture")&&Q({id:B.paymentMethodId??B.paymentIntentId,type:"card",threeDSecureActionResultTokenId:B.paymentIntentId,isPaypal:!0})}catch(B){h?.(B instanceof Error?B.message:"PayPal payment failed. Please try again.")}finally{f(!1)}},[w,x,e,t,r,O,Q,h]);return!w||!x?(0,_n.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,_n.jsxs)(_n.Fragment,{children:[!v&&(0,_n.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,_n.jsx)("div",{style:v?{}:{display:"none"},children:(0,_n.jsx)("button",{type:"button",onClick:ve,disabled:M||k,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:M||k?"not-allowed":"pointer",opacity:M||k?.6:1},ref:()=>H(!0),children:M?"Processing...":"PayPal"})}),(M||k)&&(0,_n.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,_n.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..."})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useElements,useFloPay,usePayPalFloPay});