@flopay/react 1.5.0 → 1.6.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.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import{a as qo,b as ut,c as _n,d as Pn,e as bn,f as Lr,g as Xa,h as Qa,i as gs,j as hs}from"./chunk-P5QXEIBB.mjs";import{useCallback as Ss,useEffect as zr,useState as jo,useMemo as ws,useRef as Ko}from"react";import{resolveBillingApiUrl as ks}from"@flopay/shared";import{createContext as Za}from"react";var xn=Za({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),un=Za({session:null,loading:!1,error:null});var Ps=Symbol.for("@flopay/js.telemetry.bridge.v1"),bs=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function vs(){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 Cs(e){let t=vs(),n=(a,i)=>a?a.bind(e):i,s=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:s,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,s()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function so(e){let t=globalThis[bs];return Cs(t?.(e)??{})}function At(e){if(e)return e[Ps]}import{jsx as Rs}from"react/jsx-runtime";function lo({flopay:e,paypalFlopay:t,options:n,children:s}){let[a,i]=jo(e instanceof Promise?null:e),[u,l]=jo(t instanceof Promise||!t?null:t),[v,N]=jo(null),h=Ko(null),E=Ko(null),C=Ko(null);zr(()=>{if(!a)return;let k=At(a);return h.current=k?.beginCheckout()??k?.now()??0,k?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{k?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),zr(()=>{let k=!1;return e instanceof Promise?e.then(T=>{k||i(T)}):i(e),()=>{k=!0}},[e]),zr(()=>{let k=!1;if(!t){l(null);return}return t instanceof Promise?t.then(T=>{k||l(T)}):l(t),()=>{k=!0}},[t]),zr(()=>{if(!a){N(null);return}let k=a.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return N(k),()=>{k.destroy()}},[a,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),zr(()=>{if(!a||!v||E.current===v)return;E.current=v;let k=At(a);k?.log({name:"checkout.rendered",stage:"checkout_render"}),k?.performance({stage:"checkout_render",durationMs:k.elapsed(h.current??0),durationMode:"machine"})},[v,a]);let F=Ss(()=>{if(!a||!v||C.current===v)return;C.current=v;let k=At(a);k?.log({name:"checkout.interactive",stage:"checkout_interactive"}),k?.performance({stage:"checkout_interactive",durationMs:k.elapsed(h.current??0),durationMode:"machine"})},[v,a]),c=ks(n?.billingApiUrl),P=ws(()=>({flopay:a,paypalFlopay:u,elements:v,billingApiUrl:c,reportInteractive:F}),[a,u,v,c,F]);return Rs(xn.Provider,{value:P,children:s})}import ua,{useCallback as rr,useEffect as An,useMemo as pn,useRef as Ot,useState as bt}from"react";import{PaymentAPI as ko,SESSION_CREATE_TELEMETRY as _l}from"@flopay/js";import{SDK_VERSION as Hi,FloPayError as Et,classifyTelemetryFailure as Oi,isDetachedSessionEligible as xl,resolveBillingApiUrl as Tl,buildCheckoutDisplayData as Ui,resolveButtonsLayoutTheme as Ml,resolveIdempotencyKey as $i,resolveTheme as Wi,telemetryStatusClass as Al}from"@flopay/shared";import"react";import{Fragment as dr,jsx as an,jsxs as ei}from"react/jsx-runtime";function Is(){return ei(dr,{children:[ei("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[an("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),an("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",an("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:an("path",{d:"M9 18l6-6-6-6"})})]})}function Es(){return an(dr,{children:"Go back"})}function _s(){return an(dr,{children:"Secure card checkout"})}function sr(e){return e!==void 0&&(e===""||e===null||e===!1)}function lr({content:e}){return an(dr,{children:e===void 0?an(Is,{}):e})}function cr({content:e}){return an(dr,{children:e===void 0?an(Es,{}):e})}function Nr({content:e}){return an(dr,{children:e===void 0?an(_s,{}):e})}import{ExpressCheckoutElement as Ei,PaymentElement as Ks,Elements as tr,useElements as oa,useStripe as aa}from"@stripe/react-stripe-js";import{isAuthorizationOnlySession as Zo,normalizeCheckoutFailureOutcome as Vs,resolveButtonsLayoutTheme as Hs,getPostalCodeLabel as na,getStateLabel as fi,getStateOptions as Ws,COUNTRY_OPTIONS as Ys,resolveAVSConfig as Gs,isAVSFieldVisible as De,getStateFromPostalCode as gi,isPostalCodeSupported as Js,isValidPostalCode as Xs,getPostalCodeExample as Qs,filterStripeMethodsByCountry as Zs,getStripeMethodDisplayName as hr,hasVendoredStripeMethodLogo as el,needsStripeMethodExplicitConfirm as hi,resolveStripeMethodBrandVariant as tl,partitionStripeMethods as nl,stripeExpressMethodToOptionKey as Pi}from"@flopay/shared";import{PaymentAPI as Un,toStripeAppearance as rl}from"@flopay/js";import"react";import{jsx as ti,jsxs as xs}from"react/jsx-runtime";function ur({children:e,margin:t,icon:n=!0,styleOverride:s}){return xs("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...s??{}},children:[n&&ti("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ti("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 ni={alipay:new URL("./payment-logos/alipay.svg",import.meta.url).href,bancontact:new URL("./payment-logos/bancontact.svg",import.meta.url).href,blik:new URL("./payment-logos/blik.svg",import.meta.url).href,eps:new URL("./payment-logos/eps.svg",import.meta.url).href,giropay:new URL("./payment-logos/giropay.svg",import.meta.url).href,ideal:new URL("./payment-logos/ideal.svg",import.meta.url).href,klarna:new URL("./payment-logos/klarna.svg",import.meta.url).href,p24:new URL("./payment-logos/p24.svg",import.meta.url).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",import.meta.url).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",import.meta.url).href};import ol,{useCallback as Ce,useContext as al,useEffect as ct,useMemo as lt,useRef as Be,useState as ve}from"react";import{useContext as Or}from"react";import{resolveBillingApiUrl as Ts}from"@flopay/shared";function vn(){return Or(xn).flopay}function Vo(){return Or(xn).paypalFlopay??null}function Ho(){return Or(xn).elements}function Ms(){return Or(un)}function co(){return Or(xn).billingApiUrl||Ts()}import{FloPayError as ri,isMoneySettledOutcome as As,isSetupIntentClientSecret as Kc}from"@flopay/shared";function oi(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Wo(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ai(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],s=n.reduce((i,u)=>i+(u.overrideAmount??u.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(s*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,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??a,metadata:i.metadata??null}))}}function Yo(e,t){return t?{...e,...t}:e}function It(e,t,n){let s=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:s,...a?{code:a}:{},...i?{declineCode:i}:{}}}var Bs=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Nn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:s}of Bs)if(n.test(t))return s;return e}function Qn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function pr(e){return e?.status==="authorized"||e?.status==="complete"}function ii(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function uo(e){let t=ii(e);return new ri(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function po(e){let t=ii(e);return new ri(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function mo(e,t){return e==="processing"||As(e,t)}function si(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function li(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Ur(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var yo="flopay_recent_completion_";function mr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(yo+e,JSON.stringify(t))}catch{}}function Go(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(yo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(yo+e),!1):!0}catch{return!1}}function ci(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}import{useCallback as fo,useEffect as ft,useMemo as qr,useRef as Ze,useState as er}from"react";import{loadScript as Ds}from"@paypal/paypal-js";import{PaymentAPI as Jo}from"@flopay/js";import{FloPayError as di,SDK_VERSION as Ls,generateIdempotencyKey as zs,normalizeGatewayEnvironment as Ns}from"@flopay/shared";function Fs(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Zn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Tn(e){if(typeof e!="object"||e===null)return;let t=e;return Zn(t.code)??Zn(t.type)??Zn(t.name)}function yr(e){if(!(typeof e!="object"||e===null))return Zn(e.decline_code)}function $r(e){return typeof e!="object"||e===null?!1:Zn(e.type)?.toLowerCase()==="card_error"||yr(e)!==void 0}function On(e){let t=Fs(e)?.toLowerCase()??"",s=`${Tn(e)?.toLowerCase()??""} ${t}`;return s.includes("popup")&&s.includes("block")}import{jsx as fr,jsxs as Xo}from"react/jsx-runtime";var go=45,Os=1e3,Us=11e3,$s=["https://www.paypal.com","https://www.sandbox.paypal.com"],ui="We couldn't open PayPal. Try again or choose another payment method.",qs={width:"100%",minHeight:go,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 pi(e){return e.includes("No ack for postMessage init()")&&$s.some(t=>e.includes(t))&&e.includes("10000ms")}function js(e){return e?`${ui} Allow pop-ups for this site, then try again.`:ui}function mi({sessionId:e,nonce:t,billingApiUrl:n,email:s,clientId:a,environment:i,currency:u,isSubscription:l,onTokenizedBody:v,onComplete:N,onErrorChange:h,onDecline:E,onTechnicalFailure:C,isProcessing:F=!1,onLoadStateChange:c,onInitializationStateChange:P,allowAutomaticRetry:k=!0,onButtonClick:T,runBeforeButtonClick:g,session:me,existingOrderId:M,telemetry:le,telemetryContext:ce,debug:z=!1}){let J=vn(),H=qr(()=>{if(J)return null;let A=so({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ls,enabled:le!==!1});return A.setCheckoutContext(ce??{}),A.beginCheckout(ce??{}),A},[n,J,le,ce?.checkoutMode,ce?.layout]),oe=qr(()=>At(J),[J]);ft(()=>()=>{H&&H.flush().catch(()=>{}).finally(()=>H.destroy())},[H]);let j=qr(()=>({error:A=>{oe?oe.error(A):H?.error(A)},log:A=>{oe?oe.log(A):H?.log(A)},performance:A=>{oe?oe.performance(A):H?.performance(A)},terminal:A=>{oe?oe.terminal(A):H?.terminal(A)},startTiming:()=>oe?.now()??H?.now()??0,elapsed:A=>oe?.elapsed(A)??Math.max(0,(H?.now()??A)-A)}),[oe,H]),K=Ze(null),ie=Ze(0),xe=Ze(null),he=Ze(!1),[de,Q]=er(!1),[ye,Te]=er(!1),[Z,Ue]=er(0),Fe=Ze(0),[we,V]=er(!1),b=Ze(!1),te=Ze(!1),[$e,ze]=er(!1),[ae,R]=er(!1),re=qr(()=>n.replace(/\/+$/,""),[n]),W=qr(()=>JSON.stringify([re,a,u,i??"",l,e,M??""]),[re,a,u,i,M,l,e]),ke=Ze(W),dt=ke.current!==W,[Ge,pt]=er([]),_=A=>{z&&pt(at=>[...at,`${new Date().toISOString().slice(11,23)} ${A}`])},Y=Ze(v),et=Ze(N),qe=Ze(h),mt=Ze(E),Ne=Ze(C),He=Ze(T),Jt=Ze(c),Ye=Ze(P),Xt=Ze(g),S=Ze(me),fe=Ze(s),We=Ze(t),Re=Ze(null),vt=Ze(0),Ke=Ze(null),je=Ze(null),tt=Ze(new Map),Je=Ze(new Map),kn=Ze(!1);ft(()=>(kn.current=!0,()=>{kn.current=!1}),[]),ft(()=>{Y.current=v},[v]),ft(()=>{et.current=N},[N]),ft(()=>{qe.current=h},[h]),ft(()=>{mt.current=E},[E]),ft(()=>{Ne.current=C},[C]),ft(()=>{He.current=T},[T]),ft(()=>{Jt.current=c},[c]),ft(()=>{Ye.current=P},[P]),ft(()=>{Xt.current=g},[g]),ft(()=>{S.current=me},[me]),ft(()=>{fe.current=s},[s]),ft(()=>{We.current=t},[t]),ft(()=>{Fe.current=Z},[Z]),ft(()=>{we&&xe.current?.focus()},[we,Z]);let ot=fo(()=>{window.setTimeout(()=>{xe.current?.focus()},0)},[]),jn=fo(()=>{Q(!1),Ue(A=>A+1)},[]),Wt=fo(()=>{V(!1),(K.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??K.current)?.focus?.()},[]);ft(()=>{!de||!he.current||(he.current=!1,Wt())},[Wt,de,Z]);let mn=fo((A,at)=>{let Lt=Ne.current;if(Lt){Lt("paypal",A,at);return}qe.current?.(js(at?.popupBlocked??On(A)))},[]),Qt=()=>{Ke.current?.timer&&(clearTimeout(Ke.current.timer),Ke.current.timer=null)},or=()=>{Qt();let A=vt.current+1;return vt.current=A,je.current=null,Ke.current={generation:A,timer:null,yieldedControl:!1},V(!1),A},Bt=A=>A!==void 0&&Ke.current?.generation!==A?!1:(Qt(),Ke.current=null,je.current=null,!0),St=A=>{let at=A?.generation??Ke.current?.generation??vt.current;(!A?.generation||Ke.current?.generation===at)&&(Qt(),Ke.current=null),je.current=at,A?.showRetry&&V(!0),A?.remount&&jn(),A?.focus!==!1&&ot()},Zt=A=>Ke.current?.generation===A&&je.current!==A,en=A=>{typeof document<"u"&&document.visibilityState!=="visible"||(Qt(),A.timer=setTimeout(()=>{Ke.current?.generation===A.generation&&(Ke.current=null,je.current=A.generation,mn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),V(!0),jn(),ot())},600))},Ft=()=>{let A=Ke.current;A?.yieldedControl&&en(A)},Dt=()=>{let A=Ke.current;A&&(A.yieldedControl=!0,Qt())},Ct=A=>{let at=Re.current;return at&&Je.current.set(A,at),A};ft(()=>{let A=()=>{document.visibilityState==="visible"?Ft():Dt()};return document.addEventListener("visibilitychange",A),window.addEventListener("focus",Ft),window.addEventListener("blur",Dt),()=>{document.removeEventListener("visibilitychange",A),window.removeEventListener("focus",Ft),window.removeEventListener("blur",Dt),Qt()}},[]),ft(()=>{ke.current!==W&&(ke.current=W,b.current=!1,te.current=!1,Q(!1),Te(!1),ze(!1),Ye.current?.("loading"))},[W]),ft(()=>{ut(()=>Jt.current?.(de&&!$e))},[de,$e]);let X=Ns(i);ft(()=>{let A=a?`${a.slice(0,6)}\u2026(len ${a.length})`:"(empty)",at=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(_(`mount clientId=${A} env=${i??"(unset)"}\u2192${X??"live"} ccy=${u} sub=${l}`),_(`ua=${at.slice(0,80)}${at.length>80?"\u2026":""}`),!a){_("FAIL: clientId empty \u2014 gateway misconfigured"),ze(!0),j.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!K.current){_("FAIL: containerRef not attached");return}ie.current=j.startTiming(),j.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Lt=!1,Fn=!1,Me=()=>Lt||Fn,it,Ve=!1,Rn=()=>{it=zs(),it||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Ve=!0},In=null,Dn=!1,Vn=null,En=!1,nt=()=>{!Vn||En||(En=!0,Vn.close().catch(()=>{}))},zt=null,sn=()=>{zt!==null&&(j.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"overlay_return",durationMs:j.elapsed(zt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),zt=null)},gt=!1,xt=K.current,tn=null,ln=null,Yt=[],Ut=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let r=m.getBoundingClientRect();return`${Math.round(r.width)}\xD7${Math.round(r.height)}`},$t=m=>{if(!m)return"(empty)";try{let r=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),y=r.pathname.toLowerCase();return y.includes("checkcaptcha")||y.includes("captcha")?`CAPTCHA(${r.host}${y})`:y.includes("risk")||y.includes("challenge")?`RISK(${r.host}${y})`:y.includes("smart/buttons")?`smart-buttons(${r.host})`:`${r.host}${y}`.slice(0,100)}catch{return m.slice(0,80)}},Ie=m=>{let r=m.getAttribute("src"),y=m.getAttribute("srcdoc"),x=m.getAttribute("name"),f=m.getAttribute("sandbox"),O=[];return r&&O.push(`src=${$t(r)}`),y&&O.push(`srcdoc[${y.length}ch]`),!r&&!y&&O.push("src=(empty) srcdoc=(empty)"),x&&O.push(`name=${x.slice(0,40)}`),f!==null&&O.push(`sandbox="${f.slice(0,40)}"`),O.join(" ")},qt=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let r=m.contentDocument;if(!r)return"cd=null";let y=r.body?.children.length??0,x=r.body?.innerHTML.length??0,f=r.head?.innerHTML.length??0;return`cd=same-origin readyState=${r.readyState} body[${y}children,${x}ch] head[${f}ch]`}catch(r){return`cd=cross-origin(${r.message.slice(0,30)})`}},yt=[],yn=m=>{if(Me())return;let r=m.message??String(m.error??"(no message)");r&&(r.toLowerCase().includes("paypal")||r.toLowerCase().includes("zoid")||r.toLowerCase().includes("postrobot")||r.toLowerCase().includes("storage"))&&(_(`window:error ${r.slice(0,140)}`),yt.push(r))},Hn=m=>{if(Me())return;let r=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");r&&(r.toLowerCase().includes("paypal")||r.toLowerCase().includes("zoid")||r.toLowerCase().includes("postrobot")||r.toLowerCase().includes("storage"))&&(_(`window:rejection ${r.slice(0,140)}`),yt.push(r))};z&&typeof window<"u"&&(window.addEventListener("error",yn),window.addEventListener("unhandledrejection",Hn));let jt={value:0};if(z&&typeof PerformanceObserver<"u")try{ln=new PerformanceObserver(m=>{if(!Me())for(let r of m.getEntries()){if(!r.name.toLowerCase().includes("paypal"))continue;jt.value+=1;let y=Math.round(r.duration);_(`net ${y}ms ${r.name.slice(0,90)}`)}}),ln.observe({type:"resource",buffered:!0})}catch{}let Kt=()=>{for(tn?.disconnect(),tn=null,ln?.disconnect(),ln=null;Yt.length;)clearTimeout(Yt.pop());z&&typeof window<"u"&&(window.removeEventListener("error",yn),window.removeEventListener("unhandledrejection",Hn))},Nt=m=>{if(!m)return!1;let r=m.toLowerCase();return r.includes("zoid destroyed")||r.includes("destroyed all components")||r.includes("window closed")||r.includes("detected container element removed")},Ln=m=>{if(Me()||Nt(m))return;let r=Nn(m)??m;ut(()=>qe.current?.(r))},zn=m=>{Lt||(ze(!0),m.includes("paypal_ineligible")||j.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",m))},nn=(m,r=!1)=>{if(Lt)return;let y=b.current||!k;if(Dn)return;Dn=!0,Fn=!0,Kt(),nt();let x=r||pi(m);if(x&&k&&!b.current){b.current=!0,Q(!1),R(!1),Te(!0),Ye.current?.("retrying"),In=setTimeout(()=>{Lt||Ue(f=>f+1)},Os);return}if(x||y){if(Q(!1),R(!1),Te(!1),ze(!0),Ye.current?.("exhausted"),!te.current){te.current=!0;let f=pi(m)?"paypal_init_timeout":r?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",f)}return}zn(m)};ze(!1);let Gt=async(m,r=Re.current)=>{if(Me())return;let y=r?.sessionId??e;if(Y.current){await Y.current(m,{sessionId:y,accountPatch:r?.accountPatch,nonce:r?.nonce});return}let x=j.startTiming();j.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let f=()=>{j.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"processing",durationMs:j.elapsed(x),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let O=S.current,Ae=r?.accountPatch?.email??fe.current,Xe=r?.accountPatch?.userId??O?.customer?.id??O?.accountData?.userId??"",U=await new Jo(re,{telemetry:!1}).processPayment(Xe,{sessionId:y,nonce:r?.nonce??We.current,tokenizedData:m,accountData:{userId:Xe,email:Ae??O?.customer?.email??"",firstName:r?.accountPatch?.firstName??O?.customer?.firstName??O?.accountData?.firstName??"",lastName:r?.accountPatch?.lastName??O?.customer?.lastName??O?.accountData?.lastName??"",country:r?.accountPatch?.country??O?.customer?.country??O?.accountData?.country??void 0,zip:r?.accountPatch?.zip??O?.customer?.zip??O?.accountData?.zip??void 0}});if(U.ok){if(Fn||Lt&&kn.current)return;f(),j.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ut(()=>et.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Me())return;let p=await U.json().catch(()=>null),L=p?.message??"PayPal payment failed.",ue=Nn(L)??L;f(),U.status===400&&(typeof p?.declineCode=="string"||!Array.isArray(p?.fields))?j.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):U.status===400||U.status===422?j.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):j.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:U.status>=500?"5xx":U.status>=400?"4xx":U.status>=300?"3xx":"unknown",failureCategory:U.status>=500?"server_error":void 0}),Ln(ue),ut(()=>mt.current?.(It("paypal",ue,{code:p?.code,declineCode:p?.declineCode})));return}catch(O){if(Me())return;f(),j.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ae=O instanceof Error?O.message:"PayPal payment failed.",Xe=Nn(Ae)??Ae;Ln(Xe),ut(()=>mt.current?.(It("paypal",Xe)));return}},rn=()=>new di("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Oe=m=>Me()?Promise.reject(rn()):Promise.resolve(m),w=async m=>{if(Me())throw rn();Ve||Rn();let r=Re.current,y=r?.sessionId??e,x=r?.nonce??We.current;j.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let f=await new Jo(re,{telemetry:!1}).createSessionIntent(y,x??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:it});if(Me())throw rn();if(f.provider!=="paypal")throw new Error(m);return j.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),f.providerObjectId},D=(m,r)=>{let y=r?.nonce??We.current;if(!y)return;let x=r?.sessionId??e,f=yr(m)??Tn(m)??"provider_declined";new Jo(re,{telemetry:!1}).reportSessionIntentDecline(x,y,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:f}).catch(()=>{})},I=Z;_("loadScript:scheduled (deferred 1 tick)");let ge=null,Pe=setTimeout(()=>{if(Lt){_("loadScript:skipped (cancelled before defer ran)");return}_("loadScript:start");let m=X==="live"?"production":X;ge=Ds({clientId:a,currency:u,intent:l?"subscription":"capture",vault:l?!0:void 0,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),ge.then(r=>{if(_(`loadScript:resolved inactive=${Me()} ns=${!!r} buttons=${!!r?.Buttons}`),Me())return;if(!r?.Buttons){_("FAIL: namespace missing Buttons factory"),nn("PayPal SDK did not expose the Buttons factory.");return}j.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"provider_ready",durationMs:j.elapsed(ie.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let y=async G=>{if(Me()||Fe.current!==I)return;let U=G.subscriptionID??G.orderID??"",p=U?Je.current.get(U):tt.current.get(I);if(!(!p||!Zt(p.generation))&&Bt(p.generation)){Je.current.delete(U),tt.current.delete(p.surfaceKey),sn();try{if(R(!0),ut(()=>qe.current?.(null)),!U)throw new di("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Gt({id:U,isPaypal:!0},p)}catch(L){Ln(L instanceof Error?L.message:"PayPal capture failed.")}finally{Me()||R(!1)}}},x=r.Buttons({style:{layout:"horizontal",height:go,tagline:!1},onClick:async(G,U)=>{if(Me()){await U.reject();return}Rn();let p=Xt.current,L={};if(p)try{let Ee=await p("paypal");if(Me()){await U.reject();return}if(!Ee.proceed){Re.current=null,tt.current.delete(I),await U.reject();return}L={sessionId:Ee.sessionId,accountPatch:Ee.accountPatch,nonce:Ee.nonce}}catch(Ee){_(`onClick:runBeforeButtonClick rejected msg=${(Ee instanceof Error?Ee.message:String(Ee)).slice(0,120)}`),Re.current=null,tt.current.delete(I),await U.reject();return}ut(()=>He.current?.("paypal"));let Se={generation:or(),surfaceKey:I,...L};Re.current=Se,tt.current.set(I,Se),await U.resolve(),j.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),zt=j.startTiming()},createOrder:l?void 0:M?()=>Oe(M).then(Ct):()=>w("Failed to create PayPal order.").then(Ct),createSubscription:l?M?()=>Oe(M).then(Ct):()=>w("Failed to create PayPal subscription.").then(Ct):void 0,onApprove:y,onCancel:()=>{if(Me())return;let G=tt.current.get(I)??Re.current;G&&tt.current.delete(G.surfaceKey),Re.current=null,sn(),j.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),he.current=!0,St({generation:G?.generation,remount:!0,focus:!1})},onError:G=>{if(Me()||Fe.current!==I)return;let U=G instanceof Error?G.message:"PayPal failed to render.";if(_(`onError rendered=${gt} msg=${U.slice(0,120)}`),gt){let p=tt.current.get(I)??Re.current;if(p&&!Zt(p.generation)||!p&&je.current===vt.current)return;if(Nt(U)){Bt(p?.generation);return}if(sn(),$r(G)){j.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),D(G,p),ut(()=>mt.current?.(It("paypal",U))),p&&tt.current.delete(p.surfaceKey),Re.current=null,Bt(p?.generation);return}let L=U.toLowerCase();j.error({errorCode:L.includes("popup")&&L.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),p&&tt.current.delete(p.surfaceKey),Re.current=null,St({generation:p?.generation,remount:!0,showRetry:!0,focus:!0}),mn(G,{code:"paypal_runtime_failed"});return}nn(U)}}),f=x.isEligible();if(_(`isEligible=${f}`),j.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!f){Q(!1),nn("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Vn=x,z&&_(`container:dims ${Ut(xt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),z&&typeof MutationObserver<"u"&&(tn=new MutationObserver(G=>{if(!Me()){for(let U of G)if(U.type==="childList")U.addedNodes.forEach(p=>{if(!(p instanceof Element))return;let L=p.tagName.toLowerCase(),ue=(p.getAttribute("title")??"").slice(0,40),Se=L==="iframe"?` ${Ie(p)}`:"";_(`child+ ${L}${ue?` title="${ue}"`:""}${Se} dims=${Ut(p)}`)});else if(U.type==="attributes"&&U.target instanceof Element){let p=U.target;if(p.tagName.toLowerCase()!=="iframe")continue;let L=U.attributeName;(L==="src"||L==="srcdoc")&&_(`attr~ iframe ${L}=${L==="srcdoc"?`[${(p.getAttribute("srcdoc")??"").length}ch]`:$t(p.getAttribute("src"))} dims=${Ut(p)}`)}}}),tn.observe(xt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ae=G=>{if(Me()||gt)return;let U=xt.querySelectorAll("iframe"),p=typeof document<"u"&&"hasStorageAccess"in document;_(`watchdog:${G} container=${Ut(xt)} children=${xt.childElementCount} iframes=${U.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${p} paypalNetRequests=${jt.value}`),U.forEach((L,ue)=>{let Se=(L.getAttribute("title")??"").slice(0,40);_(` iframe[${ue}] ${Ut(L)}${Se?` title="${Se}"`:""} ${Ie(L)}`);let Ee=qt(L);Ee&&_(` ${Ee}`)}),yt.length===0&&_(" (no PayPal/zoid window errors captured)")};z&&(Yt.push(setTimeout(()=>Ae("3s"),3e3)),Yt.push(setTimeout(()=>Ae("8s"),8e3)),Yt.push(setTimeout(()=>Ae("15s"),15e3))),_("render:start");let Xe=j.startTiming();Yt.push(setTimeout(()=>{Me()||gt||(_("watchdog:11s retryable render timeout"),nn("PayPal Buttons render did not settle within 11000ms.",!0))},Us)),x.render(xt).then(()=>{if(_(`render:resolved inactive=${Me()}`),Kt(),Me()){nt();return}gt=!0,Q(!0),Te(!1),Ye.current?.("ready"),j.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"checkout_render",durationMs:j.elapsed(Xe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(G=>{let U=G instanceof Error?G.message:"PayPal failed to render.";_(`render:rejected msg=${U.slice(0,120)}`),Kt(),nn(U)})}).catch(r=>{let y=r instanceof Error?r.message:"PayPal SDK failed to load.";_(`loadScript:rejected msg=${y.slice(0,120)}`),nn(y)})},0);return()=>{Lt=!0,clearTimeout(Pe),In&&clearTimeout(In),Kt(),nt()}},[k,re,a,u,i,l,e,M,Z,j]);let Kn=z?Xo("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:$e?"#fef2f2":"#f3f4f6",border:`1px solid ${$e?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${de} failed=${$e})`,Ge.length===0?`
1
+ import{a as jo,b as ut,c as xn,d as Sn,e as wn,f as Or,g as Qa,h as Za,i as hs,j as Ps}from"./chunk-P5QXEIBB.mjs";import{useCallback as ws,useEffect as zr,useState as qo,useMemo as ks,useRef as Ko}from"react";import{resolveBillingApiUrl as Rs}from"@flopay/shared";import{createContext as ei}from"react";var Tn=ei({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),mn=ei({session:null,loading:!1,error:null});var bs=Symbol.for("@flopay/js.telemetry.bridge.v1"),vs=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Cs(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},flush:async()=>{},destroy:()=>{}}}function Ss(e){let t=Cs(),n=(a,i)=>a?a.bind(e):i,s=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:s,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,s()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function lo(e){let t=globalThis[vs];return Ss(t?.(e)??{})}function At(e){if(e)return e[bs]}import{jsx as Is}from"react/jsx-runtime";function co({flopay:e,paypalFlopay:t,options:n,children:s}){let[a,i]=qo(e instanceof Promise?null:e),[p,l]=qo(t instanceof Promise||!t?null:t),[b,z]=qo(null),g=Ko(null),R=Ko(null),v=Ko(null);zr(()=>{if(!a)return;let w=At(a);return g.current=w?.beginCheckout()??w?.now()??0,w?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{w?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),zr(()=>{let w=!1;return e instanceof Promise?e.then(I=>{w||i(I)}):i(e),()=>{w=!0}},[e]),zr(()=>{let w=!1;if(!t){l(null);return}return t instanceof Promise?t.then(I=>{w||l(I)}):l(t),()=>{w=!0}},[t]),zr(()=>{if(!a){z(null);return}let w=a.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return z(w),()=>{w.destroy()}},[a,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),zr(()=>{if(!a||!b||R.current===b)return;R.current=b;let w=At(a);w?.log({name:"checkout.rendered",stage:"checkout_render"}),w?.performance({stage:"checkout_render",durationMs:w.elapsed(g.current??0),durationMode:"machine"})},[b,a]);let A=ws(()=>{if(!a||!b||v.current===b)return;v.current=b;let w=At(a);w?.log({name:"checkout.interactive",stage:"checkout_interactive"}),w?.performance({stage:"checkout_interactive",durationMs:w.elapsed(g.current??0),durationMode:"machine"})},[b,a]),u=Rs(n?.billingApiUrl),h=ks(()=>({flopay:a,paypalFlopay:p,elements:b,billingApiUrl:u,reportInteractive:A}),[a,p,b,u,A]);return Is(Tn.Provider,{value:h,children:s})}import pa,{useCallback as or,useEffect as Bn,useMemo as yn,useRef as Ut,useState as bt}from"react";import{PaymentAPI as Ro,SESSION_CREATE_TELEMETRY as xl}from"@flopay/js";import{SDK_VERSION as Yi,FloPayError as Et,classifyTelemetryFailure as Ui,isDetachedSessionEligible as Tl,resolveBillingApiUrl as Ml,buildCheckoutDisplayData as $i,resolveButtonsLayoutTheme as Al,resolveIdempotencyKey as ji,resolveTheme as Wi,telemetryStatusClass as Bl}from"@flopay/shared";import"react";import{Fragment as pr,jsx as sn,jsxs as ti}from"react/jsx-runtime";function Es(){return ti(pr,{children:[ti("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[sn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),sn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",sn("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:sn("path",{d:"M9 18l6-6-6-6"})})]})}function _s(){return sn(pr,{children:"Go back"})}function xs(){return sn(pr,{children:"Secure card checkout"})}function cr(e){return e!==void 0&&(e===""||e===null||e===!1)}function dr({content:e}){return sn(pr,{children:e===void 0?sn(Es,{}):e})}function ur({content:e}){return sn(pr,{children:e===void 0?sn(_s,{}):e})}function Nr({content:e}){return sn(pr,{children:e===void 0?sn(xs,{}):e})}import{ExpressCheckoutElement as _i,PaymentElement as Vs,Elements as nr,useElements as aa,useStripe as ia}from"@stripe/react-stripe-js";import{isAuthorizationOnlySession as ea,normalizeCheckoutFailureOutcome as Hs,resolveButtonsLayoutTheme as Ys,getPostalCodeLabel as ra,getStateLabel as gi,getStateOptions as Ws,COUNTRY_OPTIONS as Gs,resolveAVSConfig as Js,isAVSFieldVisible as Oe,getStateFromPostalCode as hi,isPostalCodeSupported as Xs,isValidPostalCode as Qs,getPostalCodeExample as Zs,filterStripeMethodsByCountry as el,getStripeMethodDisplayName as br,hasVendoredStripeMethodLogo as tl,needsStripeMethodExplicitConfirm as Pi,resolveStripeMethodBrandVariant as nl,partitionStripeMethods as rl,stripeExpressMethodToOptionKey as bi}from"@flopay/shared";import{PaymentAPI as qn,toStripeAppearance as ol}from"@flopay/js";import"react";import{jsx as ni,jsxs as Ts}from"react/jsx-runtime";function mr({children:e,margin:t,icon:n=!0,styleOverride:s}){return Ts("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...s??{}},children:[n&&ni("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ni("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 ri={alipay:new URL("./payment-logos/alipay.svg",import.meta.url).href,bancontact:new URL("./payment-logos/bancontact.svg",import.meta.url).href,blik:new URL("./payment-logos/blik.svg",import.meta.url).href,eps:new URL("./payment-logos/eps.svg",import.meta.url).href,giropay:new URL("./payment-logos/giropay.svg",import.meta.url).href,ideal:new URL("./payment-logos/ideal.svg",import.meta.url).href,klarna:new URL("./payment-logos/klarna.svg",import.meta.url).href,p24:new URL("./payment-logos/p24.svg",import.meta.url).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",import.meta.url).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",import.meta.url).href};import al,{useCallback as Ee,useContext as il,useEffect as ct,useMemo as lt,useRef as Be,useState as ke}from"react";import{useContext as Ur}from"react";import{resolveBillingApiUrl as Ms}from"@flopay/shared";function kn(){return Ur(Tn).flopay}function Vo(){return Ur(Tn).paypalFlopay??null}function Ho(){return Ur(Tn).elements}function As(){return Ur(mn)}function uo(){return Ur(Tn).billingApiUrl||Ms()}import{FloPayError as oi,isMoneySettledOutcome as Bs,isSetupIntentClientSecret as Vc}from"@flopay/shared";function ai(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 Yo(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 ii(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],s=n.reduce((i,p)=>i+(p.overrideAmount??p.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(s*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,p)=>({uuid:`synthetic-${i.type??"item"}-${p}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Wo(e,t){return t?{...e,...t}:e}function It(e,t,n){let s=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:s,...a?{code:a}:{},...i?{declineCode:i}:{}}}var Fs=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function $n(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:s}of Fs)if(n.test(t))return s;return e}function Zn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function yr(e){return e?.status==="authorized"||e?.status==="complete"}function si(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function po(e){let t=si(e);return new oi(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function mo(e){let t=si(e);return new oi(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 yo(e,t){return e==="processing"||Bs(e,t)}function li(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function ci(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function $r(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var fo="flopay_recent_completion_";function fr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(fo+e,JSON.stringify(t))}catch{}}function Go(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(fo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(fo+e),!1):!0}catch{return!1}}function di(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}import{useCallback as go,useEffect as pt,useMemo as qr,useRef as Ze,useState as tr}from"react";import{loadScript as Ls}from"@paypal/paypal-js";import{PaymentAPI as Jo}from"@flopay/js";import{FloPayError as ui,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Xo,SDK_VERSION as Os,generateIdempotencyKey as zs,normalizeGatewayEnvironment as Ns}from"@flopay/shared";function Ds(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function er(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Mn(e){if(typeof e!="object"||e===null)return;let t=e;return er(t.code)??er(t.type)??er(t.name)}function gr(e){if(!(typeof e!="object"||e===null))return er(e.decline_code)}function jr(e){return typeof e!="object"||e===null?!1:er(e.type)?.toLowerCase()==="card_error"||gr(e)!==void 0}function jn(e){let t=Ds(e)?.toLowerCase()??"",s=`${Mn(e)?.toLowerCase()??""} ${t}`;return s.includes("popup")&&s.includes("block")}import{jsx as hr,jsxs as Qo}from"react/jsx-runtime";var ho=45,Us=1e3,$s=11e3,js=["https://www.paypal.com","https://www.sandbox.paypal.com"],pi="We couldn't open PayPal. Try again or choose another payment method.",qs={width:"100%",minHeight:ho,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 mi(e){return e.includes("No ack for postMessage init()")&&js.some(t=>e.includes(t))&&e.includes("10000ms")}function Ks(e){return e?`${pi} Allow pop-ups for this site, then try again.`:pi}function yi({sessionId:e,nonce:t,billingApiUrl:n,email:s,clientId:a,environment:i,currency:p,isSubscription:l,providerObjectType:b,onTokenizedBody:z,onComplete:g,onErrorChange:R,onDecline:v,onTechnicalFailure:A,isProcessing:u=!1,onLoadStateChange:h,onInitializationStateChange:w,allowAutomaticRetry:I=!0,onButtonClick:y,runBeforeButtonClick:he,session:F,existingOrderId:te,telemetry:be,telemetryContext:j,debug:q=!1}){let oe=kn(),ie=qr(()=>{if(oe)return null;let B=lo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Os,enabled:be!==!1});return B.setCheckoutContext(j??{}),B.beginCheckout(j??{}),B},[n,oe,be,j?.checkoutMode,j?.layout]),Ne=qr(()=>At(oe),[oe]);pt(()=>()=>{ie&&ie.flush().catch(()=>{}).finally(()=>ie.destroy())},[ie]);let f=qr(()=>({error:B=>{Ne?Ne.error(B):ie?.error(B)},log:B=>{Ne?Ne.log(B):ie?.log(B)},performance:B=>{Ne?Ne.performance(B):ie?.performance(B)},terminal:B=>{Ne?Ne.terminal(B):ie?.terminal(B)},startTiming:()=>Ne?.now()??ie?.now()??0,elapsed:B=>Ne?.elapsed(B)??Math.max(0,(ie?.now()??B)-B)}),[Ne,ie]),ae=Ze(null),Fe=Ze(0),ve=Ze(null),Re=Ze(!1),[J,le]=tr(!1),[De,se]=tr(!1),[_e,Ue]=tr(0),xe=Ze(0),[H,P]=tr(!1),Q=Ze(!1),We=Ze(!1),[Le,Z]=tr(!1),[_,ce]=tr(!1),K=qr(()=>n.replace(/\/+$/,""),[n]),de=b??(l?"subscription":"order"),et=b==="order"||b==="setup_token",$e=qr(()=>JSON.stringify([K,a,p,i??"",de,et,e,te??""]),[K,a,p,i,te,de,et,e]),it=Ze($e),ue=it.current!==$e,[G,tt]=tr([]),Y=B=>{q&&tt(ot=>[...ot,`${new Date().toISOString().slice(11,23)} ${B}`])},mt=Ze(z),je=Ze(g),qe=Ze(R),$t=Ze(v),nt=Ze(A),en=Ze(y),S=Ze(h),pe=Ze(w),Je=Ze(he),Xe=Ze(F),xt=Ze(s),yt=Ze(t),Te=Ze(null),ft=Ze(0),Ie=Ze(null),tn=Ze(null),Ke=Ze(new Map),Dn=Ze(new Map),Jt=Ze(!1);pt(()=>(Jt.current=!0,()=>{Jt.current=!1}),[]),pt(()=>{mt.current=z},[z]),pt(()=>{je.current=g},[g]),pt(()=>{qe.current=R},[R]),pt(()=>{$t.current=v},[v]),pt(()=>{nt.current=A},[A]),pt(()=>{en.current=y},[y]),pt(()=>{S.current=h},[h]),pt(()=>{pe.current=w},[w]),pt(()=>{Je.current=he},[he]),pt(()=>{Xe.current=F},[F]),pt(()=>{xt.current=s},[s]),pt(()=>{yt.current=t},[t]),pt(()=>{xe.current=_e},[_e]),pt(()=>{H&&ve.current?.focus()},[H,_e]);let fn=go(()=>{window.setTimeout(()=>{ve.current?.focus()},0)},[]),Ln=go(()=>{le(!1),Ue(B=>B+1)},[]),On=go(()=>{P(!1),(ae.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ae.current)?.focus?.()},[]);pt(()=>{!J||!Re.current||(Re.current=!1,On())},[On,J,_e]);let jt=go((B,ot)=>{let He=nt.current;if(He){He("paypal",B,ot);return}qe.current?.(Ks(ot?.popupBlocked??jn(B)))},[]),dt=()=>{Ie.current?.timer&&(clearTimeout(Ie.current.timer),Ie.current.timer=null)},ln=()=>{dt();let B=ft.current+1;return ft.current=B,tn.current=null,Ie.current={generation:B,timer:null,yieldedControl:!1},P(!1),B},qt=B=>B!==void 0&&Ie.current?.generation!==B?!1:(dt(),Ie.current=null,tn.current=null,!0),Kt=B=>{let ot=B?.generation??Ie.current?.generation??ft.current;(!B?.generation||Ie.current?.generation===ot)&&(dt(),Ie.current=null),tn.current=ot,B?.showRetry&&P(!0),B?.remount&&Ln(),B?.focus!==!1&&fn()},Vt=B=>Ie.current?.generation===B&&tn.current!==B,Bt=B=>{typeof document<"u"&&document.visibilityState!=="visible"||(dt(),B.timer=setTimeout(()=>{Ie.current?.generation===B.generation&&(Ie.current=null,tn.current=B.generation,jt(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),P(!0),Ln(),fn())},600))},X=()=>{let B=Ie.current;B?.yieldedControl&&Bt(B)},zn=()=>{let B=Ie.current;B&&(B.yieldedControl=!0,dt())},nn=B=>{let ot=Te.current;return ot&&Dn.current.set(B,ot),B};pt(()=>{let B=()=>{document.visibilityState==="visible"?X():zn()};return document.addEventListener("visibilitychange",B),window.addEventListener("focus",X),window.addEventListener("blur",zn),()=>{document.removeEventListener("visibilitychange",B),window.removeEventListener("focus",X),window.removeEventListener("blur",zn),dt()}},[]),pt(()=>{it.current!==$e&&(it.current=$e,Q.current=!1,We.current=!1,le(!1),se(!1),Z(!1),pe.current?.("loading"))},[$e]),pt(()=>{ut(()=>S.current?.(J&&!Le))},[J,Le]);let Xt=Ns(i);pt(()=>{let B=a?`${a.slice(0,6)}\u2026(len ${a.length})`:"(empty)",ot=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(Y(`mount clientId=${B} env=${i??"(unset)"}\u2192${Xt??"live"} ccy=${p} sub=${l}`),Y(`ua=${ot.slice(0,80)}${ot.length>80?"\u2026":""}`),!a){Y("FAIL: clientId empty \u2014 gateway misconfigured"),Z(!0),f.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!ae.current){Y("FAIL: containerRef not attached");return}Fe.current=f.startTiming(),f.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let He=!1,Ve=!1,Ye=()=>He||Ve,_n,Nn=!1,ar=()=>{_n=zs(),_n||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Nn=!0},gn=null,at=!1,Ht=null,hn=!1,Ct=()=>{!Ht||hn||(hn=!0,Ht.close().catch(()=>{}))},Lt=null,cn=()=>{Lt!==null&&(f.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),f.performance({stage:"overlay_return",durationMs:f.elapsed(Lt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Lt=null)},rn=!1,Qt=ae.current,Zt=null,Ft=null,Se=[],St=c=>{if(!c||typeof c.getBoundingClientRect!="function")return"(no rect)";let o=c.getBoundingClientRect();return`${Math.round(o.width)}\xD7${Math.round(o.height)}`},gt=c=>{if(!c)return"(empty)";try{let o=new URL(c,typeof window<"u"?window.location.href:"https://localhost"),E=o.pathname.toLowerCase();return E.includes("checkcaptcha")||E.includes("captcha")?`CAPTCHA(${o.host}${E})`:E.includes("risk")||E.includes("challenge")?`RISK(${o.host}${E})`:E.includes("smart/buttons")?`smart-buttons(${o.host})`:`${o.host}${E}`.slice(0,100)}catch{return c.slice(0,80)}},Pn=c=>{let o=c.getAttribute("src"),E=c.getAttribute("srcdoc"),ye=c.getAttribute("name"),Pe=c.getAttribute("sandbox"),V=[];return o&&V.push(`src=${gt(o)}`),E&&V.push(`srcdoc[${E.length}ch]`),!o&&!E&&V.push("src=(empty) srcdoc=(empty)"),ye&&V.push(`name=${ye.slice(0,40)}`),Pe!==null&&V.push(`sandbox="${Pe.slice(0,40)}"`),V.join(" ")},ir=c=>{if(!(c instanceof HTMLIFrameElement))return"";try{let o=c.contentDocument;if(!o)return"cd=null";let E=o.body?.children.length??0,ye=o.body?.innerHTML.length??0,Pe=o.head?.innerHTML.length??0;return`cd=same-origin readyState=${o.readyState} body[${E}children,${ye}ch] head[${Pe}ch]`}catch(o){return`cd=cross-origin(${o.message.slice(0,30)})`}},Ot=[],on=c=>{if(Ye())return;let o=c.message??String(c.error??"(no message)");o&&(o.toLowerCase().includes("paypal")||o.toLowerCase().includes("zoid")||o.toLowerCase().includes("postrobot")||o.toLowerCase().includes("storage"))&&(Y(`window:error ${o.slice(0,140)}`),Ot.push(o))},Dt=c=>{if(Ye())return;let o=c.reason instanceof Error?c.reason.message:String(c.reason??"(no reason)");o&&(o.toLowerCase().includes("paypal")||o.toLowerCase().includes("zoid")||o.toLowerCase().includes("postrobot")||o.toLowerCase().includes("storage"))&&(Y(`window:rejection ${o.slice(0,140)}`),Ot.push(o))};q&&typeof window<"u"&&(window.addEventListener("error",on),window.addEventListener("unhandledrejection",Dt));let Yn={value:0};if(q&&typeof PerformanceObserver<"u")try{Ft=new PerformanceObserver(c=>{if(!Ye())for(let o of c.getEntries()){if(!o.name.toLowerCase().includes("paypal"))continue;Yn.value+=1;let E=Math.round(o.duration);Y(`net ${E}ms ${o.name.slice(0,90)}`)}}),Ft.observe({type:"resource",buffered:!0})}catch{}let dn=()=>{for(Zt?.disconnect(),Zt=null,Ft?.disconnect(),Ft=null;Se.length;)clearTimeout(Se.pop());q&&typeof window<"u"&&(window.removeEventListener("error",on),window.removeEventListener("unhandledrejection",Dt))},Un=c=>{if(!c)return!1;let o=c.toLowerCase();return o.includes("zoid destroyed")||o.includes("destroyed all components")||o.includes("window closed")||o.includes("detected container element removed")},zt=c=>{if(Ye()||Un(c))return;let o=$n(c)??c;ut(()=>qe.current?.(o))},bn=c=>{He||(Z(!0),c.includes("paypal_ineligible")||f.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",c))},Me=(c,o=!1)=>{if(He)return;let E=Q.current||!I;if(at)return;at=!0,Ve=!0,dn(),Ct();let ye=o||mi(c);if(ye&&I&&!Q.current){Q.current=!0,le(!1),ce(!1),se(!0),pe.current?.("retrying"),gn=setTimeout(()=>{He||Ue(Pe=>Pe+1)},Us);return}if(ye||E){if(le(!1),ce(!1),se(!1),Z(!0),pe.current?.("exhausted"),!We.current){We.current=!0;let Pe=mi(c)?"paypal_init_timeout":o?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",Pe)}return}bn(c)};Z(!1);let k=async(c,o=Te.current)=>{if(Ye())return;let E=o?.sessionId??e;if(mt.current){await mt.current(c,{sessionId:E,accountPatch:o?.accountPatch,nonce:o?.nonce});return}let ye=f.startTiming();f.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=()=>{f.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),f.performance({stage:"processing",durationMs:f.elapsed(ye),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let V=Xe.current,Ge=o?.accountPatch?.email??xt.current,x=o?.accountPatch?.userId??V?.customer?.id??V?.accountData?.userId??"",C=await new Jo(K,{telemetry:!1}).processPayment(x,{sessionId:E,nonce:o?.nonce??yt.current,tokenizedData:c,accountData:{userId:x,email:Ge??V?.customer?.email??"",firstName:o?.accountPatch?.firstName??V?.customer?.firstName??V?.accountData?.firstName??"",lastName:o?.accountPatch?.lastName??V?.customer?.lastName??V?.accountData?.lastName??"",country:o?.accountPatch?.country??V?.customer?.country??V?.accountData?.country??void 0,zip:o?.accountPatch?.zip??V?.customer?.zip??V?.accountData?.zip??void 0}});if(C.ok){if(Ve||He&&Jt.current)return;Pe(),f.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ut(()=>je.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ye())return;let T=await C.json().catch(()=>null),ne=T?.message??"PayPal payment failed.",vt=$n(ne)??ne;Pe(),C.status===400&&(typeof T?.declineCode=="string"||!Array.isArray(T?.fields))?f.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):C.status===400||C.status===422?f.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):f.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:C.status>=500?"5xx":C.status>=400?"4xx":C.status>=300?"3xx":"unknown",failureCategory:C.status>=500?"server_error":void 0}),zt(vt),ut(()=>$t.current?.(It("paypal",vt,{code:T?.code,declineCode:T?.declineCode})));return}catch(V){if(Ye())return;Pe(),f.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ge=V instanceof Error?V.message:"PayPal payment failed.",x=$n(Ge)??Ge;zt(x),ut(()=>$t.current?.(It("paypal",x)));return}},D=()=>new ui("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),L=c=>Ye()?Promise.reject(D()):Promise.resolve(c),fe=async c=>{if(Ye())throw D();Nn||ar();let o=Te.current,E=o?.sessionId??e,ye=o?.nonce??yt.current;f.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Pe=await new Jo(K,{telemetry:!1}).createSessionIntent(E,ye??"",et?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Xo,paymentMethodId:null,intentKind:de==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:_n});if(Ye())throw D();if(Pe.provider!=="paypal"||Pe.providerObjectType!==de)throw new Error(c);return f.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Pe.providerObjectId},Ce=(c,o)=>{let E=o?.nonce??yt.current;if(!E)return;let ye=o?.sessionId??e,Pe=gr(c)??Mn(c)??"provider_declined";new Jo(K,{telemetry:!1}).reportSessionIntentDecline(ye,E,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Pe}).catch(()=>{})},W=_e;Y("loadScript:scheduled (deferred 1 tick)");let m=null,O=setTimeout(()=>{if(He){Y("loadScript:skipped (cancelled before defer ran)");return}Y("loadScript:start");let c=Xt==="live"?"production":Xt;m=Ls({clientId:a,currency:p,...de==="subscription"?{intent:"subscription",vault:!0}:de==="order"?{intent:"capture"}:{},...c?{environment:c}:{},...c==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),m.then(o=>{if(Y(`loadScript:resolved inactive=${Ye()} ns=${!!o} buttons=${!!o?.Buttons}`),Ye())return;if(!o?.Buttons){Y("FAIL: namespace missing Buttons factory"),Me("PayPal SDK did not expose the Buttons factory.");return}f.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),f.performance({stage:"provider_ready",durationMs:f.elapsed(Fe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),f.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let E=async N=>{if(Ye()||xe.current!==W)return;let C=N.vaultSetupToken??N.subscriptionID??N.orderID??"",T=C?Dn.current.get(C):Ke.current.get(W);if(!(!T||!Vt(T.generation))&&qt(T.generation)){Dn.current.delete(C),Ke.current.delete(T.surfaceKey),cn();try{if(ce(!0),ut(()=>qe.current?.(null)),!C)throw new ui("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await k(de==="setup_token"?{id:C,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Xo}:et?{id:C,isPaypal:!0,gateway:"paypal",paymentMethodType:Xo}:{id:C,isPaypal:!0},T)}catch(ne){zt(ne instanceof Error?ne.message:"PayPal capture failed.")}finally{Ye()||ce(!1)}}},ye=o.Buttons({style:{layout:"horizontal",height:ho,tagline:!1},onClick:async(N,C)=>{if(Ye()){await C.reject();return}ar();let T=Je.current,ne={};if(T)try{let Nt=await T("paypal");if(Ye()){await C.reject();return}if(!Nt.proceed){Te.current=null,Ke.current.delete(W),await C.reject();return}ne={sessionId:Nt.sessionId,accountPatch:Nt.accountPatch,nonce:Nt.nonce}}catch(Nt){Y(`onClick:runBeforeButtonClick rejected msg=${(Nt instanceof Error?Nt.message:String(Nt)).slice(0,120)}`),Te.current=null,Ke.current.delete(W),await C.reject();return}ut(()=>en.current?.("paypal"));let Yt={generation:ln(),surfaceKey:W,...ne};Te.current=Yt,Ke.current.set(W,Yt),await C.resolve(),f.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),f.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),f.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Lt=f.startTiming()},createOrder:de==="order"?te?()=>L(te).then(nn):()=>fe("Failed to create PayPal order.").then(nn):void 0,createSubscription:de==="subscription"?te?()=>L(te).then(nn):()=>fe("Failed to create PayPal subscription.").then(nn):void 0,createVaultSetupToken:de==="setup_token"?()=>fe("Failed to create PayPal setup token.").then(nn):void 0,onApprove:E,onCancel:()=>{if(Ye())return;let N=Ke.current.get(W)??Te.current;N&&Ke.current.delete(N.surfaceKey),Te.current=null,cn(),f.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Re.current=!0,Kt({generation:N?.generation,remount:!0,focus:!1})},onError:N=>{if(Ye()||xe.current!==W)return;let C=N instanceof Error?N.message:"PayPal failed to render.";if(Y(`onError rendered=${rn} msg=${C.slice(0,120)}`),rn){let T=Ke.current.get(W)??Te.current;if(T&&!Vt(T.generation)||!T&&tn.current===ft.current)return;if(Un(C)){qt(T?.generation);return}if(cn(),jr(N)){f.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ce(N,T),ut(()=>$t.current?.(It("paypal",C))),T&&Ke.current.delete(T.surfaceKey),Te.current=null,qt(T?.generation);return}let ne=C.toLowerCase();f.error({errorCode:ne.includes("popup")&&ne.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),T&&Ke.current.delete(T.surfaceKey),Te.current=null,Kt({generation:T?.generation,remount:!0,showRetry:!0,focus:!0}),jt(N,{code:"paypal_runtime_failed"});return}Me(C)}}),Pe=ye.isEligible();if(Y(`isEligible=${Pe}`),f.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Pe){le(!1),Me("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ht=ye,q&&Y(`container:dims ${St(Qt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),q&&typeof MutationObserver<"u"&&(Zt=new MutationObserver(N=>{if(!Ye()){for(let C of N)if(C.type==="childList")C.addedNodes.forEach(T=>{if(!(T instanceof Element))return;let ne=T.tagName.toLowerCase(),vt=(T.getAttribute("title")??"").slice(0,40),Yt=ne==="iframe"?` ${Pn(T)}`:"";Y(`child+ ${ne}${vt?` title="${vt}"`:""}${Yt} dims=${St(T)}`)});else if(C.type==="attributes"&&C.target instanceof Element){let T=C.target;if(T.tagName.toLowerCase()!=="iframe")continue;let ne=C.attributeName;(ne==="src"||ne==="srcdoc")&&Y(`attr~ iframe ${ne}=${ne==="srcdoc"?`[${(T.getAttribute("srcdoc")??"").length}ch]`:gt(T.getAttribute("src"))} dims=${St(T)}`)}}}),Zt.observe(Qt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ge=N=>{if(Ye()||rn)return;let C=Qt.querySelectorAll("iframe"),T=typeof document<"u"&&"hasStorageAccess"in document;Y(`watchdog:${N} container=${St(Qt)} children=${Qt.childElementCount} iframes=${C.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${T} paypalNetRequests=${Yn.value}`),C.forEach((ne,vt)=>{let Yt=(ne.getAttribute("title")??"").slice(0,40);Y(` iframe[${vt}] ${St(ne)}${Yt?` title="${Yt}"`:""} ${Pn(ne)}`);let Nt=ir(ne);Nt&&Y(` ${Nt}`)}),Ot.length===0&&Y(" (no PayPal/zoid window errors captured)")};q&&(Se.push(setTimeout(()=>Ge("3s"),3e3)),Se.push(setTimeout(()=>Ge("8s"),8e3)),Se.push(setTimeout(()=>Ge("15s"),15e3))),Y("render:start");let x=f.startTiming();Se.push(setTimeout(()=>{Ye()||rn||(Y("watchdog:11s retryable render timeout"),Me("PayPal Buttons render did not settle within 11000ms.",!0))},$s)),ye.render(Qt).then(()=>{if(Y(`render:resolved inactive=${Ye()}`),dn(),Ye()){Ct();return}rn=!0,le(!0),se(!1),pe.current?.("ready"),f.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),f.performance({stage:"checkout_render",durationMs:f.elapsed(x),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(N=>{let C=N instanceof Error?N.message:"PayPal failed to render.";Y(`render:rejected msg=${C.slice(0,120)}`),dn(),Me(C)})}).catch(o=>{let E=o instanceof Error?o.message:"PayPal SDK failed to load.";Y(`loadScript:rejected msg=${E.slice(0,120)}`),Me(E)})},0);return()=>{He=!0,clearTimeout(O),gn&&clearTimeout(gn),dn(),Ct()}},[I,K,a,p,i,de,et,e,te,_e,f]);let Hn=q?Qo("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Le?"#fef2f2":"#f3f4f6",border:`1px solid ${Le?"#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=${J} failed=${Le})`,G.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${Ge.join(`
4
- `)}`]}):null;return $e&&!dt?z?fr("div",{children:Kn}):null:Xo("div",{children:[Kn,Xo("div",{"aria-hidden":ye?!0:void 0,style:ye?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:go},children:[!de&&!ye&&fr("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),fr("div",{ref:K,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:go,display:"flex",opacity:de?1:0},"aria-busy":ae||F},Z)]},Z),we&&fr("button",{ref:xe,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Wt,style:qs,children:"Try PayPal again"})]})}function ho(e){return fr(mi,{...e})}function yi(e){return fr(mi,{...e})}import{FloPayError as Cn,isSetupIntentClientSecret as il,resolveTheme as sl}from"@flopay/shared";import{Fragment as gr,jsx as d,jsxs as Le}from"react/jsx-runtime";var Sn="flopay_stripe_resume",bi="flopay_wallet_resume",jr="flopay_paypal_resume",ll=250,vi="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ia(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function bo({billingApiUrl:e,sessionId:t,nonce:n,request:s}){if(!(!t||!n))try{await new Un(e,{telemetry:!1}).reportSessionIntentDecline(t,n,s)}catch{}}function cl(e){return e instanceof Cn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ea(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var dl=`
3
+ ${G.join(`
4
+ `)}`]}):null;return Le&&!ue?q?hr("div",{children:Hn}):null:Qo("div",{children:[Hn,Qo("div",{"aria-hidden":De?!0:void 0,style:De?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ho},children:[!J&&!De&&hr("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),hr("div",{ref:ae,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:ho,display:"flex",opacity:J?1:0},"aria-busy":_||u},_e)]},_e),H&&hr("button",{ref:ve,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:On,style:qs,children:"Try PayPal again"})]})}function Po(e){return hr(yi,{...e})}function fi(e){return hr(yi,{...e})}import{FloPayError as Rn,isSetupIntentClientSecret as sl,resolveTheme as ll}from"@flopay/shared";import{Fragment as Pr,jsx as d,jsxs as ze}from"react/jsx-runtime";var In="flopay_stripe_resume",vi="flopay_wallet_resume",Kr="flopay_paypal_resume",cl=250,Ci="Just a moment \u2014 we are finalizing your order. Please press pay again.";function sa(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function vo({billingApiUrl:e,sessionId:t,nonce:n,request:s}){if(!(!t||!n))try{await new qn(e,{telemetry:!1}).reportSessionIntentDecline(t,n,s)}catch{}}function dl(e){return e instanceof Rn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ta(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var ul=`
5
5
  .paypal-buttons { margin: 0 !important; vertical-align: top !important; }
6
6
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
7
7
  @keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
@@ -22,7 +22,7 @@ ${Ge.join(`
22
22
  0% { opacity: 1; transform: translateX(0) scale(1); }
23
23
  100% { opacity: 0; transform: translateX(16px) scale(0.97); }
24
24
  }
25
- `,Po=44;function sa(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var ul={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},_i={width:"100%",minHeight:Po,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function pl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ci(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function xi(e){return e==="paypal"?"PayPal":hr(e)}function ml(e,t){let n=`We couldn't open ${xi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ti(e){let t=Be(0),n=Be(null),s=Be(null),a=Ce((c=s.current)=>{let P=c;P?.timer&&(clearTimeout(P.timer),P.timer=null)},[]),i=Ce((c,P)=>{typeof document<"u"&&document.visibilityState!=="visible"||(a(c),c.timer=setTimeout(()=>{c.timer=null,s.current?.generation===c.generation&&(s.current=null,n.current=c.generation,e(c.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},P))},[a,e]),u=Ce(c=>{c.yieldedControl&&i(c,600)},[i]),l=Ce(c=>{a();let P=t.current+1;t.current=P,n.current=null;let k={generation:P,method:c,timer:null,yieldedControl:!1};return s.current=k,P},[a]),v=Ce(c=>{let P=s.current;return typeof c=="number"&&P?.generation!==c?!1:(a(P),s.current=null,(typeof c!="number"||n.current===c)&&(n.current=null),!0)},[a]),N=Ce(c=>{let P=s.current,k=c??P?.generation??t.current;(!c||P?.generation===c)&&(a(P),s.current=null),n.current=k},[a]),h=Ce(c=>n.current===(c??t.current),[]),E=Ce(c=>s.current?.generation===c&&n.current!==c,[]),C=Ce(()=>{let c=s.current;c&&u(c)},[u]),F=Ce(()=>{let c=s.current;c&&(c.yieldedControl=!0,a(c))},[a]);return ct(()=>{let c=()=>{document.visibilityState==="visible"?C():F()},P=()=>{F()};return document.addEventListener("visibilitychange",c),window.addEventListener("blur",P),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",c),window.removeEventListener("blur",P),window.removeEventListener("focus",C),a()}},[a,F,C]),{startAttempt:l,finishAttempt:v,invalidateAttempt:N,isAttemptInvalidated:h,isAttemptCurrent:E}}function yl(e){let t=Qs(e);return`Enter a valid ${na(e)}${t?` (e.g. ${t})`:""}`}function fl(e,t,n){let s=Js(e),a=t.trim(),i=n&&s,u=i&&!a,l=i&&!!a&&!Xs(e,a);return{visible:n,supported:s,required:i,empty:u,malformed:l}}function Si(e,t){return t instanceof Cn?t:new Cn(t instanceof Error?t.message:`${pl(e)} before-click hook failed.`,"validation_error")}function ta(){return d("style",{children:dl})}function gl(e){return typeof e=="number"?`${e}px`:e}function Mi(e,t){let n=e.availablePaymentMethods;return n&&t.some(s=>n[s])?"ready":"unavailable"}function Ai({state:e,placeholderTestId:t,borderRadius:n=8,children:s}){return e==="unavailable"||e==="load_error"?null:Le("div",{style:{position:"relative",minHeight:44},children:[d("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"}}),d("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:s})]})}function wi(e){return e!=="unavailable"&&e!=="load_error"}function la(e){return d(Pl,{...e})}function ki({sessionId:e,nonce:t,email:n,billingApiUrl:s,onTokenizedBody:a,onErrorChange:i,isProcessing:u=!1,onButtonClick:l,onDecline:v,onTechnicalFailure:N,runBeforeButtonClick:h,onLoadStateChange:E,placeholderBorderRadius:C}){let F=vn(),c=aa(),P=oa(),[k,T]=ve("loading");ct(()=>{E?.(k)},[k,E]);let[g,me]=ve(!1),M=Be(!1),le=Be(null),ce=Be(null),[z,J]=ve(0),[H,oe]=ve(!1),j=Be(!1),K=Be(new Map),{startAttempt:ie,finishAttempt:xe,invalidateAttempt:he,isAttemptInvalidated:de,isAttemptCurrent:Q}=Ti((V,b,te)=>{N?.(V,b,{...te,popupBlocked:te?.popupBlocked??On(b)}),oe(!0),J($e=>$e+1)});ct(()=>{H&&ce.current?.focus()},[H,z]);let ye=Ce(()=>{J(V=>V+1)},[]),Te=Ce((V,b,te)=>{he(te),N?.("paypal",V,{code:b,popupBlocked:On(V)}),oe(!0),ye()},[he,N,ye]),Z=Ce(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);ct(()=>{j.current&&(j.current=!1,Z())},[Z,z]);let Ue=Ce(()=>{oe(!1),i?.(null),Z()},[Z,i]);ct(()=>{if(!c||M.current)return;let V=new URLSearchParams(window.location.search),b=V.get("payment_intent"),te=V.get("payment_intent_client_secret"),$e=V.get("redirect_status");if(!b||!te)return;M.current=!0;let ze;try{let R=localStorage.getItem(jr);if(R){let re=JSON.parse(R);re.clientSecret===te&&(ze={...re.accountPatch?{accountPatch:re.accountPatch}:{},...re.sessionId?{sessionId:re.sessionId}:{},...re.nonce?{nonce:re.nonce}:{}})}}catch{}try{localStorage.removeItem(jr)}catch{}let ae=new URL(window.location.href);ae.searchParams.delete("payment_intent"),ae.searchParams.delete("payment_intent_client_secret"),ae.searchParams.delete("redirect_status"),window.history.replaceState({},"",ae.toString()),(async()=>{try{if(me(!0),$e==="failed"){let W="PayPal payment was declined. Please try again.";i?.(W),v?.(It("paypal",W));return}let{paymentIntent:R,error:re}=await c.retrievePaymentIntent(te);if(re){i?.(re.message??"Failed to retrieve PayPal payment status.");return}if(R&&(R.status==="requires_capture"||R.status==="succeeded")){let W=typeof R.payment_method=="string"?R.payment_method:R.payment_method?.id;a({id:W??R.id,type:"card",threeDSecureActionResultTokenId:R.id,isPaypal:!0},ze)}else{let W="PayPal payment was not completed. Please try again.";i?.(W),v?.(It("paypal",W))}}catch(R){i?.(R instanceof Error?R.message:"Failed to complete PayPal payment.")}finally{me(!1)}})()},[c,a,i,v]);let Fe=Ce(async V=>{if(u||g){V.reject();return}let b=h?await h("paypal"):{proceed:!0};if(!b.proceed){K.current.delete(z),V.reject();return}let te=ie("paypal");K.current.set(z,{generation:te,accountPatch:b.accountPatch,sessionId:b.sessionId,nonce:b.nonce}),oe(!1),l?.("paypal"),V.resolve()},[K,u,l,h,ie,g,z]),we=Ce(async V=>{if(!c||!P)return;let b=K.current.get(z);if(b&&!Q(b.generation)){K.current.delete(z);return}if(!b&&de()||b&&!xe(b.generation))return;b||xe();let te=b??null;if(K.current.delete(z),!te&&h){let R=await h("paypal");if(!R.proceed){V.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}te={accountPatch:R.accountPatch,sessionId:R.sessionId,nonce:R.nonce}}let $e=te?.sessionId??e,ze=te?.nonce??t,ae=te?.accountPatch?.email??n;try{if(me(!0),i?.(null),!$e||!ae)throw new Error("Missing sessionId or email for PayPal payment");let R=c.createPaymentMethod,{error:re,paymentMethod:W}=await R({type:"paypal"});if(re){Te(re,"stripe_paypal_create_payment_method_failed",b?.generation),V.paymentFailed({reason:"fail"});return}let ke=await new Un(s).createSessionIntent($e,ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:W?.id??null,intentKind:"payment"});if(ke.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let dt=ke.clientSecret,Ge={return_url:window.location.href};if(W?.id&&(Ge.payment_method=W.id),typeof window<"u")try{localStorage.setItem(jr,JSON.stringify({clientSecret:dt,sessionId:$e,nonce:ze,accountPatch:te?.accountPatch}))}catch{}let{error:pt,paymentIntent:_}=await c.confirmPayment({clientSecret:dt,confirmParams:Ge,redirect:"if_required"});if(pt){if(typeof window<"u")try{localStorage.removeItem(jr)}catch{}if($r(pt)){let et=pt.message??"Your payment was declined.";i?.(et),v?.(It("paypal",et,{code:Tn(pt),declineCode:yr(pt)})),await bo({billingApiUrl:s,sessionId:$e,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Tn(pt)??"provider_declined"}})}else Te(pt,"stripe_paypal_confirm_failed",b?.generation);return}if(typeof window<"u")try{localStorage.removeItem(jr)}catch{}let Y=typeof _?.payment_method=="string"?_.payment_method:_?.payment_method?.id;a({id:Y??_?.id,type:"card",threeDSecureActionResultTokenId:_?.id,isPaypal:!0},{accountPatch:te?.accountPatch,sessionId:$e,nonce:ze});return}catch(R){Te(R,"stripe_paypal_failed",b?.generation)}finally{me(!1)}},[c,P,e,t,n,s,a,i,v,h,Te,xe,Q,de,z]);return Le(gr,{children:[d(Ai,{state:k,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:Le("div",{ref:le,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[H&&d("button",{ref:ce,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ue,style:_i,children:"Try PayPal again"}),d(Ei,{onReady:V=>T(Mi(V,["paypal"])),onLoadError:()=>{T("load_error"),ia(At(F),"paypal","paypal")},onClick:Fe,onConfirm:we,onCancel:()=>{let V=K.current.get(z);K.current.delete(z),At(F)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),he(V?.generation),oe(!1),j.current=!0,ye()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},z)]})}),g&&d(bn,{status:"processing"})]})}function Ri({sessionId:e,nonce:t,email:n,billingApiUrl:s,intentKind:a,expressMethods:i,onTokenizedBody:u,onErrorChange:l,onButtonClick:v,onDecline:N,onTechnicalFailure:h,runBeforeButtonClick:E,onLoadStateChange:C,placeholderBorderRadius:F}){let c=vn(),P=aa(),k=oa(),[T,g]=ve("loading");ct(()=>{C?.(T)},[T,C]);let[me,M]=ve(!1),le=Be(null),ce=Be(null),[z,J]=ve(0),[H,oe]=ve(!1),[j,K]=ve("google_pay"),ie=Be(!1),xe=Be("google_pay"),he=Be("google_pay"),de=Be(new Map),{startAttempt:Q,finishAttempt:ye,invalidateAttempt:Te,isAttemptInvalidated:Z,isAttemptCurrent:Ue}=Ti((ae,R,re)=>{h?.(ae,R,{...re,popupBlocked:re?.popupBlocked??On(R)}),K(ae),oe(!0),J(W=>W+1)});ct(()=>{H&&ce.current?.focus()},[H,z]);let Fe=Ce(()=>{J(ae=>ae+1)},[]),we=Ce((ae,R,re,W)=>{Te(W),h?.(ae,R,{code:re,popupBlocked:On(R)}),K(ae),oe(!0),Fe()},[Te,h,Fe]),V=Ce(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);ct(()=>{ie.current&&(ie.current=!1,V())},[V,z]);let b=Ce(()=>{oe(!1),l?.(null),V()},[V,l]),te=Ce(async ae=>{if(!P||!k)return;let R=de.current.get(z);if(R&&!Ue(R.generation)){de.current.delete(z);return}if(!R&&Z()||R&&!ye(R.generation))return;R||ye();let re=ae.expressPaymentType??R?.method??xe.current,W=R??null;de.current.delete(z);let ke=Ci(re);if(!W&&E){let Y=await E(ke);if(!Y.proceed){ae.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}W={accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}}let dt=ke,Ge=W?.sessionId??e,pt=W?.nonce??t,_=W?.accountPatch?.email??n;try{M(!0),l?.(null);let{error:Y}=await k.submit();if(Y){we(re,Y,"stripe_wallet_submit_failed",R?.generation);return}let{error:et,paymentMethod:qe}=await P.createPaymentMethod({elements:k});if(et||!qe){we(re,et??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",R?.generation);return}if(!Ge||!_)throw new Error("Missing sessionId or email for wallet payment");let mt=await new Un(s).createSessionIntent(Ge,pt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:re??ke,paymentMethodId:qe.id,intentKind:a});if(mt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Ne=mt.clientSecret,{error:He,intentId:Jt}=il(Ne)?await P.confirmCardSetup(Ne,{payment_method:qe.id}).then(Ye=>({error:Ye.error,intentId:Ye.setupIntent?.id})):await P.confirmCardPayment(Ne,{payment_method:qe.id}).then(Ye=>({error:Ye.error,intentId:Ye.paymentIntent?.id}));if(He){if($r(He)){let Ye=He.message??"Your payment was declined.";l?.(Ye),N?.(It(dt,Ye,{code:Tn(He),declineCode:yr(He)})),await bo({billingApiUrl:s,sessionId:Ge,nonce:pt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:re??ke,providerDeclineReason:Tn(He)??"provider_declined"}})}else we(re,He,"stripe_wallet_confirm_failed",R?.generation);return}u({id:qe.id,type:"card",threeDSecureActionResultTokenId:Jt},{accountPatch:W?.accountPatch,sessionId:Ge,nonce:pt})}catch(Y){we(re,Y,"stripe_wallet_failed",R?.generation)}finally{M(!1)}},[P,k,e,t,n,s,a,u,l,N,E,we,ye,Ue,Z,z]),$e=lt(()=>{let ae=["applePay","googlePay","paypal","link","amazonPay","klarna"],R=new Set(["applePay","googlePay"]),re=new Set(i.map(Pi)),W={};for(let ke of ae)re.has(ke)?W[ke]=R.has(ke)?"always":"auto":W[ke]="never";return W},[i]),ze=lt(()=>i.map(Pi),[i]);return Le(gr,{children:[d(Ai,{state:T,placeholderTestId:"flopay-wallet-placeholder",borderRadius:F,children:Le("div",{ref:le,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[H&&Le("button",{ref:ce,type:"button","data-testid":"flopay-wallet-retry-button",onClick:b,style:_i,children:["Try ",xi(j)," again"]}),d(Ei,{onReady:ae=>{g(Mi(ae,ze))},onLoadError:ae=>{g("load_error"),ia(At(c),"stripe","wallet")},onClick:async ae=>{xe.current=ae.expressPaymentType,he.current=Ci(ae.expressPaymentType);let R=E?await E(he.current):{proceed:!0};if(!R.proceed){de.current.delete(z),ae.reject();return}let re=Q(ae.expressPaymentType);de.current.set(z,{generation:re,method:ae.expressPaymentType,accountPatch:R.accountPatch,sessionId:R.sessionId,nonce:R.nonce}),oe(!1),v?.(he.current),ae.resolve()},onConfirm:te,onCancel:()=>{let ae=de.current.get(z);de.current.delete(z),At(c)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Te(ae?.generation),oe(!1),ie.current=!0,Fe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:$e,layout:{maxColumns:1,overflow:"never"}}},z)]})}),me&&d(bn,{status:"processing"})]})}function hl({method:e,themeId:t,submitting:n=!1,disabled:s=!1,highlighted:a=!1,hasNextStep:i=!1,onClick:u,backgroundColor:l,borderColor:v,textColor:N,borderRadius:h,fontFamily:E}){let C=tl(e,t),F=ni[e],c=C?.backgroundColor??l??"#ffffff",P=C?.borderColor??v??"#d1d5db",k=C?.textColor??N??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!s&&u()},disabled:n||s,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Po,padding:"0 1rem",backgroundColor:c,color:k,border:`1px solid ${P}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:E,cursor:n||s?"not-allowed":"pointer",opacity:s&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?d("span",{style:{margin:"0 auto"},children:`Connecting to ${hr(e)}\u2026`}):Le(gr,{children:[Le("span",{style:{display:"inline-flex",alignItems:"center",gap:el(e)?8:0},children:[F?d("img",{src:F,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?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:C.logoSvg}}):null,d("span",{children:hr(e)})]}),i&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:k,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:d("path",{d:"M9 18l6-6-6-6"})})]})})}function ra({method:e,sessionId:t,nonce:n,email:s,billingName:a,billingApiUrl:i,onTokenizedBody:u,onErrorChange:l,onDecline:v,onCancel:N,runBeforeButtonClick:h,onButtonClick:E,isProcessing:C,submitButtonColor:F,submitButtonBorderRadius:c,submitButtonStyle:P,errorText:k}){let T=vn(),g=aa(),me=oa(),[M,le]=ve(!1),ce=Be(!1),[z,J]=ve(!1),[H,oe]=ve("loading"),j=Ce(async()=>{if(!g||!me||C||ce.current||!z)return;ce.current=!0,le(!0);let K=h?await h("card"):{proceed:!0};if(!K.proceed){ce.current=!1,le(!1);return}E?.("card");let ie=K.sessionId??t,xe=K.nonce??n,he=K.accountPatch?.email??s;try{l?.(null);let de=await me.submit();if(de.error){l?.(de.error.message??"Payment failed.");return}let Q=await g.createPaymentMethod({elements:me});if(Q.error||!Q.paymentMethod){l?.(Q.error?.message??"Failed to create payment method.");return}let ye=Q.paymentMethod;if(!ie||!he)throw new Error("Missing sessionId or email for payment.");let Te=ye.type||e,Z=await new Un(i).createSessionIntent(ie,xe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Te,paymentMethodId:null,intentKind:"payment"});if(Z.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ue=Z.clientSecret;if(typeof window<"u")try{localStorage.setItem(Sn,JSON.stringify({clientSecret:Ue,sessionId:ie,nonce:xe,accountPatch:K.accountPatch,paymentMethodId:ye.id,paymentMethodType:ye.type??e,gateway:"stripe"}))}catch{}let{error:Fe,paymentIntent:we}=await g.confirmPayment({clientSecret:Ue,confirmParams:{return_url:window.location.href,payment_method:ye.id},redirect:"if_required"});if(Fe){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let te=Fe.message??"Payment failed.";l?.(te),v?.(It("card",te,{code:Fe.code})),await bo({billingApiUrl:i,sessionId:ie,nonce:xe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Fe.code??"provider_declined"}});return}let V=we?.status;if(!mo(V)){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let te=V==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";l?.(te),v?.(It("card",te,{code:V??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let b=typeof we?.payment_method=="string"?we.payment_method:we?.payment_method?.id;u({id:b??ye.id,type:"card",threeDSecureActionResultTokenId:we?.id,gateway:"stripe",paymentMethodType:ye.type??e},{accountPatch:K.accountPatch,sessionId:ie,nonce:xe})}catch(de){l?.(de instanceof Error?de.message:"Payment failed. Please try again.")}finally{ce.current=!1,le(!1)}},[g,me,C,z,h,E,t,n,s,i,e,u,l,v]);return Le("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(Ks,{onReady:()=>oe("ready"),onLoadError:()=>{oe("load_error"),ia(At(T),"stripe","apm")},onChange:K=>{J(!!K.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:a&&a.trim().length>=3?a.trim():"FloPay Customer",...s?{email:s}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{j()},disabled:!z||M||C||H!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:F,color:"white",border:"none",borderRadius:c,fontSize:"1rem",fontWeight:600,cursor:!z||M||C||H!=="ready"?"not-allowed":"pointer",opacity:!z||M||C||H!=="ready"?.5:1,transition:"opacity 120ms ease-out",...P??{}},children:M?"Processing\u2026":`Pay with ${hr(e)}`}),k&&d(ur,{margin:"0.75rem 0 0",children:k})]})}function Ii({sessionId:e,nonce:t,email:n,billingName:s,billingApiUrl:a,paymentElementMethods:i,stripeInstance:u,paymentElementBaseOptions:l,onTokenizedBody:v,onErrorChange:N,onButtonClick:h,onDecline:E,runBeforeButtonClick:C,onLoadStateChange:F,isProcessing:c=!1,submitButtonColor:P="#4A49FF",submitButtonBorderRadius:k=8,submitButtonStyle:T,buttonAppearance:g,themeId:me,onExpandApm:M,expandedApmMethod:le}){let[ce,z]=ve(null),[J,H]=ve(null),oe=Be(!1);ct(()=>{i.length>0&&u?F?.("ready"):u||F?.("loading")},[i.length,u,F]);let j=Ce(async Q=>{if(!u||oe.current||c)return;oe.current=!0,H(Q);let ye=C?await C("card"):{proceed:!0};if(!ye.proceed){oe.current=!1,H(null);return}h?.("card");let Te=ye.sessionId??e,Z=ye.nonce??t,Ue=ye.accountPatch?.email??n;try{if(N?.(null),!Te||!Ue)throw new Error("Missing sessionId or email for payment.");let Fe=await new Un(a).createSessionIntent(Te,Z??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,paymentMethodId:null,intentKind:"payment"});if(Fe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let we=Fe.clientSecret;if(typeof window<"u")try{localStorage.setItem(Sn,JSON.stringify({clientSecret:we,sessionId:Te,nonce:Z,accountPatch:ye.accountPatch,paymentMethodType:Q,gateway:"stripe"}))}catch{}let{error:V,paymentIntent:b}=await u.confirmPayment({clientSecret:we,confirmParams:{return_url:window.location.href,payment_method_data:{type:Q,billing_details:{name:s&&s.trim().length>=3?s.trim():"FloPay Customer",...Ue?{email:Ue}:{}}}},redirect:"if_required"});if(V){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let ze=V.message??"Payment failed.";N?.(ze),E?.(It("card",ze,{code:V.code})),await bo({billingApiUrl:a,sessionId:Te,nonce:Z,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,providerDeclineReason:V.code??"provider_declined"}});return}let te=b?.status;if(!mo(te)){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let ze=te==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";N?.(ze),E?.(It("card",ze,{code:te??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let $e=typeof b?.payment_method=="string"?b.payment_method:b?.payment_method?.id;v({id:$e??b?.id,type:"card",threeDSecureActionResultTokenId:b?.id,gateway:"stripe",paymentMethodType:Q},{accountPatch:ye.accountPatch,sessionId:Te,nonce:Z})}catch(Fe){N?.(Fe instanceof Error?Fe.message:"Payment failed. Please try again.")}finally{oe.current=!1,H(null)}},[u,c,C,h,e,t,n,a,s,v,N,E]),[K,ie]=ve(null),xe=M?le??null:K,he=Ce(Q=>{oe.current||c||xe&&xe!==Q||(hi(Q)?M?M(Q):ie(Q):j(Q))},[xe,c,j,M]),de=lt(()=>K?{...l,paymentMethodTypes:[K]}:null,[K,l]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:i.map(Q=>{let ye=le===Q,Te=J===Q,Z=J!==null&&J!==Q||le!=null&&le!==Q;return Le(ol.Fragment,{children:[d(hl,{method:Q,themeId:me,submitting:Te,disabled:Z,highlighted:ye,hasNextStep:hi(Q),onClick:()=>he(Q),backgroundColor:g?.backgroundColor,borderColor:g?.borderColor,textColor:g?.textColor,borderRadius:g?.borderRadius,fontFamily:g?.fontFamily}),!M&&K===Q&&de&&u&&d(tr,{stripe:u,options:de,children:d(ra,{method:Q,sessionId:e,email:n,billingName:s,billingApiUrl:a,onTokenizedBody:v,onErrorChange:N,onDecline:E,onCancel:()=>ie(null),runBeforeButtonClick:C,onButtonClick:h,isProcessing:c,submitButtonColor:P,submitButtonBorderRadius:k,submitButtonStyle:T})},Q)]},Q)})})}function Pl({sessionId:e,nonce:t,billingApiUrl:n,email:s,userId:a,onComplete:i,onError:u,onDecline:l,onTokenizedBody:v,firstName:N,lastName:h,chv:E,className:C,isProcessing:F,error:c,onErrorChange:P,showPayPal:k=!0,showStripe:T=!0,enabledPaymentMethods:g,enabledPaymentMethodCountries:me,showApplePay:M=!0,showGooglePay:le=!0,layout:ce="default",theme:z,buttonsTheme:J,buttonsStyles:H,appearance:oe,cardButtonContent:j,cardBackButtonContent:K,cardTitleContent:ie,showSecurityFooter:xe,onButtonClick:he,onBeforeButtonClick:de,enableAVS:Q,cardFieldOrder:ye,cardPreFormSlot:Te,avsLayout:Z="row",country:Ue,zip:Fe,addressLine1:we,addressLine2:V,city:b,state:te,onCountryChange:$e,onZipChange:ze,avsCheck:ae,checkoutType:R,checkoutLayout:re,totalAmount:W=0,currency:ke="usd",initialCardOpen:dt=!1,directPaypal:Ge,isSubscription:pt=!1,session:_,dataAttachmentPending:Y=!1,debug:et=!1}){let qe=vn(),mt=Vo(),Ne=al(un),He=Y||Ne.claimPending===!0,Jt=co(),[Ye,Xt]=ve(!1),[S,fe]=ve(null),[We,Re]=ve(Ue??"US"),[vt,Ke]=ve(Fe??""),[je,tt]=ve(we??""),[Je,kn]=ve(V??""),[ot,jn]=ve(b??""),[Wt,mn]=ve(te??""),[Qt,or]=ve({}),Bt=Be(Fe??""),St=Be(Ue??"US"),Zt=Be(we??""),en=Be(V??""),Ft=Be(b??""),Dt=Be(te??""),Ct=Be({});ct(()=>{let o=(B,q,ne,$,be)=>{if(Ct.current[B])return;let _e=q?.trim();!_e||_e===ne.current||(ne.current=_e,$(_e),be?.(_e))};o("country",Ue,St,Re,$e),o("zip",Fe,Bt,Ke,ze),o("addressLine1",we,Zt,tt),o("addressLine2",V,en,kn),o("city",b,Ft,jn),o("state",te,Dt,mn)},[Ue,Fe,we,V,b,te,$e,ze]);let X=lt(()=>Gs(Q),[Q]),Kn=X!==null,A=lt(()=>Zo(_),[_]),at=!!_?.vault?.html,Lt=!!_?.gateways?.pcivault,Me=!!(_?.gateways?.stripe?.enabledPaymentMethods??g)?.includes("card"),it=at||Me||Lt,Ve=!!(T&&it&&qe&&e),[Rn,In]=ve(()=>ce!=="buttons"||dt?e??null:null),[Dn,Vn]=ve(0),En=ce!=="buttons"||dt||!!e&&Rn===e,nt=lt(()=>!qe||!Ve||!e||!En?null:qe.cardCapture({sessionId:e,captureMethod:_?.captureMethod}),[qe,Ve,e,En,_?.captureMethod]),zt=lt(()=>{let o=We,B=X?De(X.postal_code,o):!1;return fl(o,vt,B)},[X,We,vt]),{avsInvalid:sn,invalidAvsFields:gt}=lt(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!Ve||!X)return{avsInvalid:!1,invalidAvsFields:o};let B=We,q=(be,_e)=>De(be,B)&&!_e.trim(),ne={line1:q(X.address_line_1,je),city:q(X.city,ot),state:q(X.state,Wt),zip:zt.empty||zt.malformed};return{avsInvalid:ne.line1||ne.city||ne.state||ne.zip,invalidAvsFields:ne}},[Ve,X,We,je,ot,Wt,zt]),[xt,tn]=ve(!1),[ln,Yt]=ve(!1),[Ut,$t]=ve(()=>ea(_?.vault)),[Ie,qt]=ve(dt&&it?"card":"buttons"),[yt,yn]=ve(null),Hn=Ie==="expanding"||Ie==="card",jt=280,Kt=Be(null),Nt=Ce(o=>{Kt.current&&clearTimeout(Kt.current),Kt.current=setTimeout(()=>{Kt.current=null,o()},jt)},[jt]);ct(()=>()=>{Kt.current&&clearTimeout(Kt.current)},[]);let Ln=Ce(()=>{In(e??null),Vn(o=>o+1),qt("expanding"),Nt(()=>qt("card"))},[Nt,e]),zn=Ce(()=>{qt("collapsing"),Nt(()=>qt("buttons"))},[Nt]),nn=Ce(o=>{yn(o),qt("apm-expanding"),Nt(()=>qt("apm-form"))},[Nt]),Gt=Ce(()=>{qt("apm-collapsing"),Nt(()=>{qt("buttons"),yn(null)})},[Nt]);ct(()=>{ce==="buttons"&&dt&&it&&(In(e??null),qt("card"))},[ce,dt,it,e]);let[rn,Oe]=ve(null),w=Be(!1),D=Be(null),I=Be("idle"),[ge,Pe]=ve(null),m=Be(ge);ct(()=>{m.current=ge},[ge]);let r=n||Jt,y=c??S,x=lt(()=>sl(z),[z]),f=lt(()=>{let o=x?.buttonsLayout??Hs(J);return H?{...o,...H,cardButton:{...o.cardButton,...H.cardButton},cardFormContainer:{...o.cardFormContainer,...H.cardFormContainer},backButton:{...o.backButton,...H.backButton},backButtonIcon:{...o.backButtonIcon,...H.backButtonIcon},submitButton:{...o.submitButton,...H.submitButton},title:{...o.title,...H.title}}:o},[x,J,H]),O=oe??x?.appearance,Ae=lt(()=>Qa({appearance:O,buttonsStyles:f,layout:ce}),[O,f,ce]),Xe=Ne.inlineSessionPatchProcessing??!1,G=(F??Ye)||Xe,U=r.replace(/\/+$/,""),p=lt(()=>Yo({userId:a,email:s,firstName:N,lastName:h,country:Ue,zip:Fe},Qt),[a,s,N,h,Ue,Fe,Qt]),L=[p.firstName,p.lastName].filter(o=>!!o?.trim()).join(" "),ue=lt(()=>qe?qe.getRawProvider():null,[qe]),Se=lt(()=>mt?mt.getRawProvider():null,[mt]),Ee=W||100,fn=lt(()=>O?rl(O):null,[O]),Rr=fn?{appearance:fn}:null,_o=lt(()=>{let o=fn??{},B=o.rules??{};return{...o,rules:{...B,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...B[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...B[".AccordionItemContents"]??{}}}}},[fn]),Jr=lt(()=>{let o=li(W);return{...o,currency:ke.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...Rr}},[W,ke,Rr]),wa=lt(()=>({mode:"payment",amount:Ee,currency:ke.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Rr}),[Ee,ke,Rr]),se=Ce(o=>{fe(o),P?.(o)},[P]);ct(()=>{!Ve||!nt||nt.setCardFieldOrder?.(ye??null,X==null)},[Ve,nt,ye,X]),ct(()=>{(Ie==="expanding"||Ie==="collapsing"||Ie==="apm-expanding"||Ie==="apm-collapsing")&&se(null)},[Ie,se]);let cn=Ce((o,B,q)=>{l?.(It(o,B,q))},[l]),ar=Ce((o,B,q)=>{let ne=q?.popupBlocked??On(B),$=ml(o,ne),be=Zn(q?.code)??Tn(B)??"external_payment_method_failed",_e=new Cn($,"api_error",{code:"external_payment_method_failed",param:o});Oe(null),ce==="buttons"&&(qt("buttons"),yn(null)),se($),u?.(_e),console.error("[FloPay] External payment method failed:",{method:o,code:be,popupBlocked:ne})},[ce,u,se]);ct(()=>{if(!Ve||!e){$t(null);return}let o=ea(_?.vault);if(o){$t(o);return}if(!En){$t(null);return}$t(null);let B=!0;return new Un(U).getVaultCapture(e,t).then(q=>{if(!B)return;let ne=ea(q);ne?$t(ne):se("Failed to load the secure card form.")}).catch(q=>{B&&se(q instanceof Error?q.message:"Failed to load the secure card form.")}),()=>{B=!1}},[Ve,En,Dn,e,_?.vault?.html,_?.vault?.messageToken,_?.vault?.expectedOrigin,U,t,se]);let gn=Be({onComplete:i,onError:u,updateError:se,emitDecline:cn,resolvedAccount:p,avsConfig:X,avsCheckProp:ae,sessionId:e,nonce:t,baseUrl:U,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt});gn.current={onComplete:i,onError:u,updateError:se,emitDecline:cn,resolvedAccount:p,avsConfig:X,avsCheckProp:ae,sessionId:e,nonce:t,baseUrl:U,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt};let xo=Be(!1),Qi=Ce(()=>{let{resolvedAccount:o,avsConfig:B,avsCheckProp:q}=gn.current,ne=St.current||o.country||"US",$=B?De(B.state,ne):!1,be=B?De(B.address_line_1,ne):!1,_e=B?De(B.postal_code,ne):!1,st=B?De(B.city,ne):!1,Pt=B?De(B.address_line_2,ne):!1,Qe=be&&!$&&_e?gi(ne,(Bt.current??"").trim()):null,wt=$?Dt.current:Qe;return{accountData:{userId:o.userId??"",email:o.email??"",firstName:o.firstName??"",lastName:o.lastName??"",..._e&&Bt.current?{zip:Bt.current}:{},...st&&Ft.current?{city:Ft.current}:{},...wt?{state:wt}:{},...be&&Zt.current?{addressLine1:Zt.current}:{},...Pt&&en.current?{addressLine2:en.current}:{},country:ne},...q!==void 0?{avsCheck:q}:{},...B?{avsConfig:{country:De(B.country,ne),postal_code:_e,address_line_1:be,address_line_2:Pt,city:st,state:$}}:{}}},[]),ka=Be(He);ka.current=He,ct(()=>{He||y!==vi||gn.current.updateError(null)},[He,y]),ct(()=>{!Ve||!nt||nt.setSubmitGate?.(sn||He)},[Ve,nt,sn,He]),ct(()=>{if(!Ve||!nt)return;xo.current=!1;let o=!1,B=nt.on("submitting",()=>{tn(!0),D.current&&clearTimeout(D.current),I.current="validation-window",D.current=setTimeout(()=>{D.current=null,I.current==="validation-window"&&(I.current="processing")},ll),Oe("processing");let{baseUrl:_e,sessionId:st,nonce:Pt,updateError:Qe,onError:wt}=gn.current;!st||!Pt||new Un(_e).patchAccountSnapshot(st,Pt,Qi(),{telemetryMode:"best_effort"}).catch(pe=>{if(!cl(pe))return;let Tt=pe instanceof Error?pe.message:"Please check your billing address and try again.";Qe(Tt),I.current="idle",Oe(null),wt?.(pe instanceof Cn?pe:new Cn(Tt,"api_error"))})}),q=nt.on("complete",async _e=>{if(mr(_e.sessionId??gn.current.sessionId),I.current="terminal",Oe("success"),await new Promise(Qe=>setTimeout(Qe,_n)),xo.current)return;xo.current=!0;let st=gn.current,Pt=Zo(st)||_e.outcome==="authorized";gn.current.onComplete?.(Pt?{status:"authorized",paymentIntentId:_e.intentId,paymentId:_e.paymentId??st.paymentId,sessionId:_e.sessionId??st.sessionId,authorizationExpiresAt:_e.authorizationExpiresAt??st.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:_e.intentId,checkoutMethod:"card"})}),ne=nt.on("decline",async _e=>{let{updateError:st,emitDecline:Pt}=gn.current,Qe=_e.message??"Your payment was declined. Please try another card or contact your bank.";I.current="terminal",st(Qe),Oe("error");let wt=_e.failureOutcome??Vs(_e.declineReason)??"authorization_declined";Pt("card",Qe,{code:wt,declineCode:wt}),await new Promise(pe=>setTimeout(pe,Pn)),!o&&(I.current="idle",Oe(null))}),$=nt.on("error",async _e=>{let{updateError:st,onError:Pt}=gn.current,Qe=_e.message??"There was a problem processing your payment. Please try again.";I.current="terminal",st(Qe),Oe("error"),Pt?.(new Cn(Qe,"api_error",{code:_e.failureOutcome??"capture_failed"})),await new Promise(wt=>setTimeout(wt,Pn)),!o&&(I.current="idle",Oe(null))}),be=nt.on("blocked",()=>{if(!ka.current){tn(!0);return}gn.current.updateError(vi)});return()=>{o=!0,D.current&&(clearTimeout(D.current),D.current=null),I.current="idle",B(),q(),ne(),$(),be()}},[Ve,nt]);let hn=!!Ge?.clientId,Ir=Array.isArray(g),Xr=Ir&&g.length>0,Zi=Ir&&g.includes("paypal"),{expressMethods:Qr,paymentElementMethods:Er}=lt(()=>nl(g,{excludePaypal:hn}),[g,hn]),Ra=hn||!!mt,es=lt(()=>Ra?Qr.filter(o=>o!=="paypal"):Qr,[Qr,Ra]),ts=lt(()=>{let o=[];return M&&o.push("apple_pay"),le&&o.push("google_pay"),o},[M,le]),Zr=Ir?es:ts,ns=T&&Zr.length>0,To=Kn?We:Ue,eo=lt(()=>{let o=To?.trim().toUpperCase();return o?me?Er.filter(B=>{let q=me[B];return!q||q.length===0||q.includes(o)}):Zs(Er,To):Er},[Er,To,me]),Mo=lt(()=>({mode:"payment",amount:Ee,currency:ke.toLowerCase(),paymentMethodCreation:"manual",appearance:_o}),[Ee,ke,_o]),[Ia,Ea]=ve("loading"),[_a,xa]=ve("loading"),[Ta,Ma]=ve("loading"),[rs,Ao]=ve(!1),[Aa,Bo]=ve("loading"),[to,os]=ve();ct(()=>{os(ci())},[]);let Ba=k&&(hn||(Ir?Zi:to===!1)),Fa=T&&ns,_r=!He&&Ba&&hn,Da=Aa==="retrying"||Aa==="exhausted",xr=!He&&Ba&&!!Se&&(!hn||Da),Tr=!He&&Fa&&!!ue,Mr=!He&&T&&Xr&&eo.length>0&&!!ue,as=_r&&!Da?rs:xr&&wi(Ia),is=Tr&&wi(_a),ss=Mr&&Ta!=="load_error",La=o=>o==="loading"||o==="ready",za=_r||xr&&La(Ia)||Tr&&La(_a)||Mr&&Ta!=="load_error",no=Be(!1);ct(()=>{if(!no.current){if(!T&&!k){no.current=!0;let o=new Cn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(o),se(o.message)}else if(!T&&k&&!hn&&!Se){no.current=!0;let o=new Cn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(o),se(o.message)}else if(to!==void 0&&!He&&!it&&!za){no.current=!0;let o=new Cn("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?.(o),se(o.message)}}},[T,k,hn,Se,to,He,it,za,u,se]);let Na=Be(!1);ct(()=>{if(Na.current||!Xr)return;let o=[];M!==!0&&o.push("showApplePay"),le!==!0&&o.push("showGooglePay"),o.length!==0&&(Na.current=!0,console.warn(`[FloPay] ${o.join(" / ")} ${o.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Xr,M,le]);let Oa=Ce((o,B)=>Ne.applyInlineSessionPatch?Ne.applyInlineSessionPatch(o).then(q=>({error:null,sessionId:q.sessionId||e,nonce:q.session?.clientSecret||t})).catch(q=>{let ne=Si(B,q);return se(ne.message),u?.(ne),{error:ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ne.applyInlineSessionPatch,t,u,e,se]),dn=Ce(async o=>{if(!de)return{proceed:!0};try{let B=await de({method:o,sessionId:e||void 0,createSession:Ne.inlineSessionDraft});if(B===!1)return{proceed:!1};if(B&&typeof B=="object"){B.account&&or(ne=>({...ne??{},...B.account}));let q=await Oa(B,o);return q.error?{proceed:!1,accountPatch:B.account}:{proceed:!0,accountPatch:B.account,sessionId:q.sessionId,nonce:q.nonce}}return{proceed:!0}}catch(B){let q=Si(o,B);return se(q.message),u?.(q),{proceed:!1}}},[Oa,Ne.inlineSessionDraft,de,u,e,se]),Ua=Ce(async(o,B)=>{if(w.current)return;w.current=!0,Xt(!0),Oe("processing"),se(null);let q=B?.sessionId??e,ne=B?.nonce??t,$=Yo(p,B?.accountPatch),be=B?.completionPaymentMethodId??Ur(o),_e=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o;try{let Pt=await new Un(U).processPayment($.userId??"",{sessionId:q,nonce:ne,tokenizedData:_e,accountData:{userId:$.userId??"",email:$.email??"",firstName:$.firstName??"",lastName:$.lastName??"",...X?(()=>{let pe=St.current,Tt=De(X.state,pe),Ht=De(X.address_line_1,pe),Jn=De(X.postal_code,pe),Xn=Ht&&!Tt&&Jn?gi(pe,(Bt.current??"").trim()):null,Mt=Tt?Dt.current:Xn;return{country:pe,...Jn&&Bt.current?{zip:Bt.current}:{},...De(X.city,pe)&&Ft.current?{city:Ft.current}:{},...Mt?{state:Mt}:{},...Ht&&Zt.current?{addressLine1:Zt.current}:{},...De(X.address_line_2,pe)&&en.current?{addressLine2:en.current}:{}}})():{}},chv:E,avsCheck:ae??!1,checkoutType:R,checkoutLayout:re,avsConfig:X?{country:De(X.country,St.current),postal_code:De(X.postal_code,St.current),address_line_1:De(X.address_line_1,St.current),address_line_2:De(X.address_line_2,St.current),city:De(X.city,St.current),state:De(X.state,St.current)}:void 0});if(Pt.ok){let pe=Pt.status===204?null:await Pt.json().catch(()=>null),Tt=Zo(_)||pe?.status==="authorized";mr(q),Oe("success"),Pe(null),await new Promise(Ht=>setTimeout(Ht,_n)),i?.(Tt?{status:"authorized",...typeof pe?.paymentId=="string"?{paymentId:pe.paymentId}:_?.paymentId?{paymentId:_.paymentId}:{},sessionId:typeof pe?.sessionId=="string"?pe.sessionId:q,...typeof pe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:pe.authorizationExpiresAt}:_?.authorizationExpiresAt?{authorizationExpiresAt:_.authorizationExpiresAt}:{},paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:be,checkoutMethod:o.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:be,checkoutMethod:o.isPaypal?"paypal":"card"});return}let Qe=await Pt.json().catch(()=>null);if(Qe?.type==="paypal_redirect_required"){let pe=Qe.threeDSecureToken,Tt=Qe.paymentMethodId||o.id||"";if(!qe||!pe){Oe("error"),se("PayPal authorization required but no token provided.");return}try{let Ht=mt?.getRawProvider();if(!Ht){se("PayPal is not available.");return}let Jn={return_url:window.location.href};Tt&&(Jn.payment_method=Tt);let{error:Xn}=await Ht.confirmPayment({clientSecret:pe,confirmParams:Jn,redirect:"if_required"});if(Xn){Oe("error");let Mt=Xn.message??"PayPal payment failed.";se(Mt),cn("paypal",Mt,{code:Xn.code})}}catch(Ht){Oe("error"),se(Ht instanceof Error?Ht.message:"PayPal authorization failed.")}return}if(Qe?.type==="paypal_direct_required"){let pe=Qe.orderId;if(!pe){Oe("error"),se("PayPal retry required but no order id provided.");return}let Tt=m.current?.attempts??0;if(Tt>=2){Oe("error"),se("PayPal payment could not be completed after multiple attempts."),cn("paypal","paypal_direct_required retry limit exceeded");return}Ao(!1),Bo("loading"),Pe({orderId:pe,attempts:Tt+1}),Oe(null);return}Oe("error");let wt=Qe?.message??"Payment failed. Please try again.";se(wt),cn(o.isPaypal?"paypal":"card",wt,{code:Qe?.code??Qe?.gatewayErrorCode,declineCode:Qe?.declineCode??Qe?.gatewayDeclineReason}),await new Promise(pe=>setTimeout(pe,Pn))}catch(st){Oe("error"),se(st instanceof Error?st.message:"An unexpected error occurred"),await new Promise(Pt=>setTimeout(Pt,Pn))}finally{Xt(!1),Oe(null),w.current=!1}},[U,e,t,p,L,E,qe,mt,_,i,u,se,cn]),on=Ce((o,B)=>{v?v(o):Ua(o,B)},[v,Ua]),$a=Be(!1);ct(()=>{if(typeof window>"u"||$a.current)return;let o=new URLSearchParams(window.location.search),B=o.get("payment_intent"),q=o.get("payment_intent_client_secret"),ne=o.get("redirect_status");if(!B||!q)return;let $=wt=>{let pe=localStorage.getItem(wt);if(!pe)return null;try{return JSON.parse(pe)}catch{return localStorage.removeItem(wt),null}},be=$(Sn)??$(bi),_e;if(be?.clientSecret){if(be.clientSecret!==q)return;_e={...be.accountPatch?{accountPatch:be.accountPatch}:{},...be.sessionId?{sessionId:be.sessionId}:{},...be.nonce?{nonce:be.nonce}:{}}}else if(be?.sessionId&&be.sessionId!==e)return;$a.current=!0,localStorage.removeItem(Sn),localStorage.removeItem(bi);let st=new URL(window.location.href);st.searchParams.delete("payment_intent"),st.searchParams.delete("payment_intent_client_secret"),st.searchParams.delete("redirect_status"),window.history.replaceState({},"",st.toString());let Pt=be?.paymentMethodType??be?.tokenType??"card",Qe="card";(async()=>{let wt=qe?.getRawProvider();if(!wt){let Mt="Payment is not available \u2014 please refresh and try again.";se(Mt),cn(Qe,Mt);return}if(ne==="failed"){let Mt="Payment was declined. Please try again.";se(Mt),cn(Qe,Mt);return}let{paymentIntent:pe,error:Tt}=await wt.retrievePaymentIntent(q);if(Tt){let Mt=Tt.message??"Failed to retrieve payment status.";se(Mt),cn(Qe,Mt,{code:Tt.code});return}let Ht=pe?.status,Jn=mo(Ht);if(!pe||!Jn){let Mt=Ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";se(Mt),cn(Qe,Mt,{code:Ht??"missing_payment_intent"});return}let Xn=typeof pe.payment_method=="string"?pe.payment_method:pe.payment_method?.id;on({id:Xn??be?.paymentMethodId??be?.tokenId??pe.id,type:"card",threeDSecureActionResultTokenId:pe.id,gateway:be?.gateway??"stripe",paymentMethodType:Pt},_e)})()},[e,on,qe,se,cn]);let Fo=Ce(o=>{o.preventDefault()},[]);if(!(qe!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Ar=ce==="buttons",Vt=O?.variables,ls=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Do=Vt?.colorBackground,cs=Do&&!ls.has(Do)?Do:void 0,Br=f.cardInputBorder??(Ar?"#e5e7eb":"#A4A4FF"),Lo=Vt?.colorDanger??"#dc2626",Wn=o=>xt&&o?Lo:Br,ro=(zt.malformed||zt.empty)&&(ln||xt),ds=ro?Lo:Wn(gt.zip),zo=f.cardFormContainer?.backgroundColor??cs??(Ar?"white":"#EDEDFF"),Fr=f.cardInputBackground??Vt?.colorBackground??"white",No=sr(K),qa=sr(ie),ir=f.nameInput,ja=f.cardInputFontSize??gl(ir?.fontSize)??Vt?.fontSizeBase??"16px",Ka=typeof ir?.fontFamily=="string"?ir.fontFamily:Vt?.fontFamily??"Poppins, sans-serif",Va=Xa(ir?.fontWeight)??400,us=f.cardInputColor??(typeof ir?.color=="string"?ir.color:void 0)??Vt?.colorText??"#262833",ps=f.cardInputPlaceholderColor??"#9ca3af",ht=Vt?.borderRadius??"8px",Yn=Vt?.borderRadius??f.cardButton?.borderRadius??ht,Gn=Vt?.colorPrimary??"#4A49FF",ms=Vt?.colorPrimaryHover??Lr(Gn,.12),Oo=Vt?.colorText??"#262833",Ha={fontSize:ja,fontFamily:Ka,fontWeight:Va,color:us,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ys={"--flopay-input-placeholder-color":ps,"--flopay-input-font-size":ja,"--flopay-input-font-family":Ka,"--flopay-input-font-weight":String(Va)},Dr=f.cardFormContainer??{},Uo=Dr.padding??(Ar?"0":"1rem"),$o=Dr.borderRadius??ht,fs=nt&&Ut?d(qo,{capture:nt,html:Ut.html,messageToken:Ut.messageToken,expectedOrigin:Ut.expectedOrigin,theme:Ae,onReady:()=>{if(!X||typeof document>"u")return;let o=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};o();let B=0,q=window.setInterval(()=>{B+=1;let ne=document.activeElement;!!ne&&ne.tagName==="IFRAME"&&ne.id==="flopay_vault_form_iframe"?(o(),window.clearInterval(q)):B>=50&&window.clearInterval(q)},100)},onError:o=>se(o),onValidation:o=>{let B=I.current;(B==="idle"||B==="validation-window")&&(se(o),o&&I.current==="validation-window"&&(D.current&&(clearTimeout(D.current),D.current=null),I.current="idle",Oe(null)))}}):d("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"}),Wa=Le("div",{style:{backgroundColor:zo,borderRadius:$o,...Dr,padding:Uo,...ys,display:"flex",flexDirection:"column"},children:[d("style",{children:`
25
+ `,bo=44;function la(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 pl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},xi={width:"100%",minHeight:bo,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 ml(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":br(e)}function yl(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 Mi(e){let t=Be(0),n=Be(null),s=Be(null),a=Ee((u=s.current)=>{let h=u;h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),i=Ee((u,h)=>{typeof document<"u"&&document.visibilityState!=="visible"||(a(u),u.timer=setTimeout(()=>{u.timer=null,s.current?.generation===u.generation&&(s.current=null,n.current=u.generation,e(u.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},h))},[a,e]),p=Ee(u=>{u.yieldedControl&&i(u,600)},[i]),l=Ee(u=>{a();let h=t.current+1;t.current=h,n.current=null;let w={generation:h,method:u,timer:null,yieldedControl:!1};return s.current=w,h},[a]),b=Ee(u=>{let h=s.current;return typeof u=="number"&&h?.generation!==u?!1:(a(h),s.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[a]),z=Ee(u=>{let h=s.current,w=u??h?.generation??t.current;(!u||h?.generation===u)&&(a(h),s.current=null),n.current=w},[a]),g=Ee(u=>n.current===(u??t.current),[]),R=Ee(u=>s.current?.generation===u&&n.current!==u,[]),v=Ee(()=>{let u=s.current;u&&p(u)},[p]),A=Ee(()=>{let u=s.current;u&&(u.yieldedControl=!0,a(u))},[a]);return ct(()=>{let u=()=>{document.visibilityState==="visible"?v():A()},h=()=>{A()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",h),window.addEventListener("focus",v),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",h),window.removeEventListener("focus",v),a()}},[a,A,v]),{startAttempt:l,finishAttempt:b,invalidateAttempt:z,isAttemptInvalidated:g,isAttemptCurrent:R}}function fl(e){let t=Zs(e);return`Enter a valid ${ra(e)}${t?` (e.g. ${t})`:""}`}function gl(e,t,n){let s=Xs(e),a=t.trim(),i=n&&s,p=i&&!a,l=i&&!!a&&!Qs(e,a);return{visible:n,supported:s,required:i,empty:p,malformed:l}}function wi(e,t){return t instanceof Rn?t:new Rn(t instanceof Error?t.message:`${ml(e)} before-click hook failed.`,"validation_error")}function na(){return d("style",{children:ul})}function hl(e){return typeof e=="number"?`${e}px`:e}function Ai(e,t){let n=e.availablePaymentMethods;return n&&t.some(s=>n[s])?"ready":"unavailable"}function Bi({state:e,placeholderTestId:t,borderRadius:n=8,children:s}){return e==="unavailable"||e==="load_error"?null:ze("div",{style:{position:"relative",minHeight:44},children:[d("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"}}),d("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:s})]})}function ki(e){return e!=="unavailable"&&e!=="load_error"}function ca(e){return d(bl,{...e})}function Ri({sessionId:e,nonce:t,email:n,billingApiUrl:s,onTokenizedBody:a,onErrorChange:i,isProcessing:p=!1,onButtonClick:l,onDecline:b,onTechnicalFailure:z,runBeforeButtonClick:g,onLoadStateChange:R,placeholderBorderRadius:v}){let A=kn(),u=ia(),h=aa(),[w,I]=ke("loading");ct(()=>{R?.(w)},[w,R]);let[y,he]=ke(!1),F=Be(!1),te=Be(null),be=Be(null),[j,q]=ke(0),[oe,ie]=ke(!1),Ne=Be(!1),f=Be(new Map),{startAttempt:ae,finishAttempt:Fe,invalidateAttempt:ve,isAttemptInvalidated:Re,isAttemptCurrent:J}=Mi((H,P,Q)=>{z?.(H,P,{...Q,popupBlocked:Q?.popupBlocked??jn(P)}),ie(!0),q(We=>We+1)});ct(()=>{oe&&be.current?.focus()},[oe,j]);let le=Ee(()=>{q(H=>H+1)},[]),De=Ee((H,P,Q)=>{ve(Q),z?.("paypal",H,{code:P,popupBlocked:jn(H)}),ie(!0),le()},[ve,z,le]),se=Ee(()=>{window.setTimeout(()=>{(te.current?.querySelector("iframe")??te.current)?.focus()},0)},[]);ct(()=>{Ne.current&&(Ne.current=!1,se())},[se,j]);let _e=Ee(()=>{ie(!1),i?.(null),se()},[se,i]);ct(()=>{if(!u||F.current)return;let H=new URLSearchParams(window.location.search),P=H.get("payment_intent"),Q=H.get("payment_intent_client_secret"),We=H.get("redirect_status");if(!P||!Q)return;F.current=!0;let Le;try{let _=localStorage.getItem(Kr);if(_){let ce=JSON.parse(_);ce.clientSecret===Q&&(Le={...ce.accountPatch?{accountPatch:ce.accountPatch}:{},...ce.sessionId?{sessionId:ce.sessionId}:{},...ce.nonce?{nonce:ce.nonce}:{}})}}catch{}try{localStorage.removeItem(Kr)}catch{}let Z=new URL(window.location.href);Z.searchParams.delete("payment_intent"),Z.searchParams.delete("payment_intent_client_secret"),Z.searchParams.delete("redirect_status"),window.history.replaceState({},"",Z.toString()),(async()=>{try{if(he(!0),We==="failed"){let K="PayPal payment was declined. Please try again.";i?.(K),b?.(It("paypal",K));return}let{paymentIntent:_,error:ce}=await u.retrievePaymentIntent(Q);if(ce){i?.(ce.message??"Failed to retrieve PayPal payment status.");return}if(_&&(_.status==="requires_capture"||_.status==="succeeded")){let K=typeof _.payment_method=="string"?_.payment_method:_.payment_method?.id;a({id:K??_.id,type:"card",threeDSecureActionResultTokenId:_.id,isPaypal:!0},Le)}else{let K="PayPal payment was not completed. Please try again.";i?.(K),b?.(It("paypal",K))}}catch(_){i?.(_ instanceof Error?_.message:"Failed to complete PayPal payment.")}finally{he(!1)}})()},[u,a,i,b]);let Ue=Ee(async H=>{if(p||y){H.reject();return}let P=g?await g("paypal"):{proceed:!0};if(!P.proceed){f.current.delete(j),H.reject();return}let Q=ae("paypal");f.current.set(j,{generation:Q,accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}),ie(!1),l?.("paypal"),H.resolve()},[f,p,l,g,ae,y,j]),xe=Ee(async H=>{if(!u||!h)return;let P=f.current.get(j);if(P&&!J(P.generation)){f.current.delete(j);return}if(!P&&Re()||P&&!Fe(P.generation))return;P||Fe();let Q=P??null;if(f.current.delete(j),!Q&&g){let _=await g("paypal");if(!_.proceed){H.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Q={accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}}let We=Q?.sessionId??e,Le=Q?.nonce??t,Z=Q?.accountPatch?.email??n;try{if(he(!0),i?.(null),!We||!Z)throw new Error("Missing sessionId or email for PayPal payment");let _=u.createPaymentMethod,{error:ce,paymentMethod:K}=await _({type:"paypal"});if(ce){De(ce,"stripe_paypal_create_payment_method_failed",P?.generation),H.paymentFailed({reason:"fail"});return}let de=await new qn(s).createSessionIntent(We,Le??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:K?.id??null,intentKind:"payment"});if(de.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let et=de.clientSecret,$e={return_url:window.location.href};if(K?.id&&($e.payment_method=K.id),typeof window<"u")try{localStorage.setItem(Kr,JSON.stringify({clientSecret:et,sessionId:We,nonce:Le,accountPatch:Q?.accountPatch}))}catch{}let{error:it,paymentIntent:ue}=await u.confirmPayment({clientSecret:et,confirmParams:$e,redirect:"if_required"});if(it){if(typeof window<"u")try{localStorage.removeItem(Kr)}catch{}if(jr(it)){let tt=it.message??"Your payment was declined.";i?.(tt),b?.(It("paypal",tt,{code:Mn(it),declineCode:gr(it)})),await vo({billingApiUrl:s,sessionId:We,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(it)??"provider_declined"}})}else De(it,"stripe_paypal_confirm_failed",P?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Kr)}catch{}let G=typeof ue?.payment_method=="string"?ue.payment_method:ue?.payment_method?.id;a({id:G??ue?.id,type:"card",threeDSecureActionResultTokenId:ue?.id,isPaypal:!0},{accountPatch:Q?.accountPatch,sessionId:We,nonce:Le});return}catch(_){De(_,"stripe_paypal_failed",P?.generation)}finally{he(!1)}},[u,h,e,t,n,s,a,i,b,g,De,Fe,J,Re,j]);return ze(Pr,{children:[d(Bi,{state:w,placeholderTestId:"flopay-paypal-placeholder",borderRadius:v,children:ze("div",{ref:te,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[oe&&d("button",{ref:be,type:"button","data-testid":"flopay-paypal-retry-button",onClick:_e,style:xi,children:"Try PayPal again"}),d(_i,{onReady:H=>I(Ai(H,["paypal"])),onLoadError:()=>{I("load_error"),sa(At(A),"paypal","paypal")},onClick:Ue,onConfirm:xe,onCancel:()=>{let H=f.current.get(j);f.current.delete(j),At(A)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ve(H?.generation),ie(!1),Ne.current=!0,le()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},j)]})}),y&&d(wn,{status:"processing"})]})}function Ii({sessionId:e,nonce:t,email:n,billingApiUrl:s,intentKind:a,expressMethods:i,onTokenizedBody:p,onErrorChange:l,onButtonClick:b,onDecline:z,onTechnicalFailure:g,runBeforeButtonClick:R,onLoadStateChange:v,placeholderBorderRadius:A}){let u=kn(),h=ia(),w=aa(),[I,y]=ke("loading");ct(()=>{v?.(I)},[I,v]);let[he,F]=ke(!1),te=Be(null),be=Be(null),[j,q]=ke(0),[oe,ie]=ke(!1),[Ne,f]=ke("google_pay"),ae=Be(!1),Fe=Be("google_pay"),ve=Be("google_pay"),Re=Be(new Map),{startAttempt:J,finishAttempt:le,invalidateAttempt:De,isAttemptInvalidated:se,isAttemptCurrent:_e}=Mi((Z,_,ce)=>{g?.(Z,_,{...ce,popupBlocked:ce?.popupBlocked??jn(_)}),f(Z),ie(!0),q(K=>K+1)});ct(()=>{oe&&be.current?.focus()},[oe,j]);let Ue=Ee(()=>{q(Z=>Z+1)},[]),xe=Ee((Z,_,ce,K)=>{De(K),g?.(Z,_,{code:ce,popupBlocked:jn(_)}),f(Z),ie(!0),Ue()},[De,g,Ue]),H=Ee(()=>{window.setTimeout(()=>{(te.current?.querySelector("iframe")??te.current)?.focus()},0)},[]);ct(()=>{ae.current&&(ae.current=!1,H())},[H,j]);let P=Ee(()=>{ie(!1),l?.(null),H()},[H,l]),Q=Ee(async Z=>{if(!h||!w)return;let _=Re.current.get(j);if(_&&!_e(_.generation)){Re.current.delete(j);return}if(!_&&se()||_&&!le(_.generation))return;_||le();let ce=Z.expressPaymentType??_?.method??Fe.current,K=_??null;Re.current.delete(j);let de=Si(ce);if(!K&&R){let G=await R(de);if(!G.proceed){Z.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}K={accountPatch:G.accountPatch,sessionId:G.sessionId,nonce:G.nonce}}let et=de,$e=K?.sessionId??e,it=K?.nonce??t,ue=K?.accountPatch?.email??n;try{F(!0),l?.(null);let{error:G}=await w.submit();if(G){xe(ce,G,"stripe_wallet_submit_failed",_?.generation);return}let{error:tt,paymentMethod:Y}=await h.createPaymentMethod({elements:w});if(tt||!Y){xe(ce,tt??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",_?.generation);return}if(!$e||!ue)throw new Error("Missing sessionId or email for wallet payment");let mt=await new qn(s).createSessionIntent($e,it??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ce??de,paymentMethodId:Y.id,intentKind:a});if(mt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let je=mt.clientSecret,{error:qe,intentId:$t}=sl(je)?await h.confirmCardSetup(je,{payment_method:Y.id}).then(nt=>({error:nt.error,intentId:nt.setupIntent?.id})):await h.confirmCardPayment(je,{payment_method:Y.id}).then(nt=>({error:nt.error,intentId:nt.paymentIntent?.id}));if(qe){if(jr(qe)){let nt=qe.message??"Your payment was declined.";l?.(nt),z?.(It(et,nt,{code:Mn(qe),declineCode:gr(qe)})),await vo({billingApiUrl:s,sessionId:$e,nonce:it,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ce??de,providerDeclineReason:Mn(qe)??"provider_declined"}})}else xe(ce,qe,"stripe_wallet_confirm_failed",_?.generation);return}p({id:Y.id,type:"card",threeDSecureActionResultTokenId:$t},{accountPatch:K?.accountPatch,sessionId:$e,nonce:it})}catch(G){xe(ce,G,"stripe_wallet_failed",_?.generation)}finally{F(!1)}},[h,w,e,t,n,s,a,p,l,z,R,xe,le,_e,se,j]),We=lt(()=>{let Z=["applePay","googlePay","paypal","link","amazonPay","klarna"],_=new Set(["applePay","googlePay"]),ce=new Set(i.map(bi)),K={};for(let de of Z)ce.has(de)?K[de]=_.has(de)?"always":"auto":K[de]="never";return K},[i]),Le=lt(()=>i.map(bi),[i]);return ze(Pr,{children:[d(Bi,{state:I,placeholderTestId:"flopay-wallet-placeholder",borderRadius:A,children:ze("div",{ref:te,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[oe&&ze("button",{ref:be,type:"button","data-testid":"flopay-wallet-retry-button",onClick:P,style:xi,children:["Try ",Ti(Ne)," again"]}),d(_i,{onReady:Z=>{y(Ai(Z,Le))},onLoadError:Z=>{y("load_error"),sa(At(u),"stripe","wallet")},onClick:async Z=>{Fe.current=Z.expressPaymentType,ve.current=Si(Z.expressPaymentType);let _=R?await R(ve.current):{proceed:!0};if(!_.proceed){Re.current.delete(j),Z.reject();return}let ce=J(Z.expressPaymentType);Re.current.set(j,{generation:ce,method:Z.expressPaymentType,accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}),ie(!1),b?.(ve.current),Z.resolve()},onConfirm:Q,onCancel:()=>{let Z=Re.current.get(j);Re.current.delete(j),At(u)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),De(Z?.generation),ie(!1),ae.current=!0,Ue()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:We,layout:{maxColumns:1,overflow:"never"}}},j)]})}),he&&d(wn,{status:"processing"})]})}function Pl({method:e,themeId:t,submitting:n=!1,disabled:s=!1,highlighted:a=!1,hasNextStep:i=!1,onClick:p,backgroundColor:l,borderColor:b,textColor:z,borderRadius:g,fontFamily:R}){let v=nl(e,t),A=ri[e],u=v?.backgroundColor??l??"#ffffff",h=v?.borderColor??b??"#d1d5db",w=v?.textColor??z??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!s&&p()},disabled:n||s,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:bo,padding:"0 1rem",backgroundColor:u,color:w,border:`1px solid ${h}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,cursor:n||s?"not-allowed":"pointer",opacity:s&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?d("span",{style:{margin:"0 auto"},children:`Connecting to ${br(e)}\u2026`}):ze(Pr,{children:[ze("span",{style:{display:"inline-flex",alignItems:"center",gap:tl(e)?8:0},children:[A?d("img",{src:A,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):v?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:v.logoSvg}}):null,d("span",{children:br(e)})]}),i&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:w,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:d("path",{d:"M9 18l6-6-6-6"})})]})})}function oa({method:e,sessionId:t,nonce:n,email:s,billingName:a,billingApiUrl:i,onTokenizedBody:p,onErrorChange:l,onDecline:b,onCancel:z,runBeforeButtonClick:g,onButtonClick:R,isProcessing:v,submitButtonColor:A,submitButtonBorderRadius:u,submitButtonStyle:h,errorText:w}){let I=kn(),y=ia(),he=aa(),[F,te]=ke(!1),be=Be(!1),[j,q]=ke(!1),[oe,ie]=ke("loading"),Ne=Ee(async()=>{if(!y||!he||v||be.current||!j)return;be.current=!0,te(!0);let f=g?await g("card"):{proceed:!0};if(!f.proceed){be.current=!1,te(!1);return}R?.("card");let ae=f.sessionId??t,Fe=f.nonce??n,ve=f.accountPatch?.email??s;try{l?.(null);let Re=await he.submit();if(Re.error){l?.(Re.error.message??"Payment failed.");return}let J=await y.createPaymentMethod({elements:he});if(J.error||!J.paymentMethod){l?.(J.error?.message??"Failed to create payment method.");return}let le=J.paymentMethod;if(!ae||!ve)throw new Error("Missing sessionId or email for payment.");let De=le.type||e,se=await new qn(i).createSessionIntent(ae,Fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:De,paymentMethodId:null,intentKind:"payment"});if(se.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let _e=se.clientSecret;if(typeof window<"u")try{localStorage.setItem(In,JSON.stringify({clientSecret:_e,sessionId:ae,nonce:Fe,accountPatch:f.accountPatch,paymentMethodId:le.id,paymentMethodType:le.type??e,gateway:"stripe"}))}catch{}let{error:Ue,paymentIntent:xe}=await y.confirmPayment({clientSecret:_e,confirmParams:{return_url:window.location.href,payment_method:le.id},redirect:"if_required"});if(Ue){if(typeof window<"u")try{localStorage.removeItem(In)}catch{}let Q=Ue.message??"Payment failed.";l?.(Q),b?.(It("card",Q,{code:Ue.code})),await vo({billingApiUrl:i,sessionId:ae,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ue.code??"provider_declined"}});return}let H=xe?.status;if(!yo(H)){if(typeof window<"u")try{localStorage.removeItem(In)}catch{}let Q=H==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";l?.(Q),b?.(It("card",Q,{code:H??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(In)}catch{}let P=typeof xe?.payment_method=="string"?xe.payment_method:xe?.payment_method?.id;p({id:P??le.id,type:"card",threeDSecureActionResultTokenId:xe?.id,gateway:"stripe",paymentMethodType:le.type??e},{accountPatch:f.accountPatch,sessionId:ae,nonce:Fe})}catch(Re){l?.(Re instanceof Error?Re.message:"Payment failed. Please try again.")}finally{be.current=!1,te(!1)}},[y,he,v,j,g,R,t,n,s,i,e,p,l,b]);return ze("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(Vs,{onReady:()=>ie("ready"),onLoadError:()=>{ie("load_error"),sa(At(I),"stripe","apm")},onChange:f=>{q(!!f.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:a&&a.trim().length>=3?a.trim():"FloPay Customer",...s?{email:s}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ne()},disabled:!j||F||v||oe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:A,color:"white",border:"none",borderRadius:u,fontSize:"1rem",fontWeight:600,cursor:!j||F||v||oe!=="ready"?"not-allowed":"pointer",opacity:!j||F||v||oe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...h??{}},children:F?"Processing\u2026":`Pay with ${br(e)}`}),w&&d(mr,{margin:"0.75rem 0 0",children:w})]})}function Ei({sessionId:e,nonce:t,email:n,billingName:s,billingApiUrl:a,paymentElementMethods:i,stripeInstance:p,paymentElementBaseOptions:l,onTokenizedBody:b,onErrorChange:z,onButtonClick:g,onDecline:R,runBeforeButtonClick:v,onLoadStateChange:A,isProcessing:u=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:w=8,submitButtonStyle:I,buttonAppearance:y,themeId:he,onExpandApm:F,expandedApmMethod:te}){let[be,j]=ke(null),[q,oe]=ke(null),ie=Be(!1);ct(()=>{i.length>0&&p?A?.("ready"):p||A?.("loading")},[i.length,p,A]);let Ne=Ee(async J=>{if(!p||ie.current||u)return;ie.current=!0,oe(J);let le=v?await v("card"):{proceed:!0};if(!le.proceed){ie.current=!1,oe(null);return}g?.("card");let De=le.sessionId??e,se=le.nonce??t,_e=le.accountPatch?.email??n;try{if(z?.(null),!De||!_e)throw new Error("Missing sessionId or email for payment.");let Ue=await new qn(a).createSessionIntent(De,se??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:J,paymentMethodId:null,intentKind:"payment"});if(Ue.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let xe=Ue.clientSecret;if(typeof window<"u")try{localStorage.setItem(In,JSON.stringify({clientSecret:xe,sessionId:De,nonce:se,accountPatch:le.accountPatch,paymentMethodType:J,gateway:"stripe"}))}catch{}let{error:H,paymentIntent:P}=await p.confirmPayment({clientSecret:xe,confirmParams:{return_url:window.location.href,payment_method_data:{type:J,billing_details:{name:s&&s.trim().length>=3?s.trim():"FloPay Customer",..._e?{email:_e}:{}}}},redirect:"if_required"});if(H){if(typeof window<"u")try{localStorage.removeItem(In)}catch{}let Le=H.message??"Payment failed.";z?.(Le),R?.(It("card",Le,{code:H.code})),await vo({billingApiUrl:a,sessionId:De,nonce:se,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:J,providerDeclineReason:H.code??"provider_declined"}});return}let Q=P?.status;if(!yo(Q)){if(typeof window<"u")try{localStorage.removeItem(In)}catch{}let Le=Q==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";z?.(Le),R?.(It("card",Le,{code:Q??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(In)}catch{}let We=typeof P?.payment_method=="string"?P.payment_method:P?.payment_method?.id;b({id:We??P?.id,type:"card",threeDSecureActionResultTokenId:P?.id,gateway:"stripe",paymentMethodType:J},{accountPatch:le.accountPatch,sessionId:De,nonce:se})}catch(Ue){z?.(Ue instanceof Error?Ue.message:"Payment failed. Please try again.")}finally{ie.current=!1,oe(null)}},[p,u,v,g,e,t,n,a,s,b,z,R]),[f,ae]=ke(null),Fe=F?te??null:f,ve=Ee(J=>{ie.current||u||Fe&&Fe!==J||(Pi(J)?F?F(J):ae(J):Ne(J))},[Fe,u,Ne,F]),Re=lt(()=>f?{...l,paymentMethodTypes:[f]}:null,[f,l]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:i.map(J=>{let le=te===J,De=q===J,se=q!==null&&q!==J||te!=null&&te!==J;return ze(al.Fragment,{children:[d(Pl,{method:J,themeId:he,submitting:De,disabled:se,highlighted:le,hasNextStep:Pi(J),onClick:()=>ve(J),backgroundColor:y?.backgroundColor,borderColor:y?.borderColor,textColor:y?.textColor,borderRadius:y?.borderRadius,fontFamily:y?.fontFamily}),!F&&f===J&&Re&&p&&d(nr,{stripe:p,options:Re,children:d(oa,{method:J,sessionId:e,email:n,billingName:s,billingApiUrl:a,onTokenizedBody:b,onErrorChange:z,onDecline:R,onCancel:()=>ae(null),runBeforeButtonClick:v,onButtonClick:g,isProcessing:u,submitButtonColor:h,submitButtonBorderRadius:w,submitButtonStyle:I})},J)]},J)})})}function bl({sessionId:e,nonce:t,billingApiUrl:n,email:s,userId:a,onComplete:i,onError:p,onDecline:l,onTokenizedBody:b,firstName:z,lastName:g,chv:R,className:v,isProcessing:A,error:u,onErrorChange:h,showPayPal:w=!0,showStripe:I=!0,enabledPaymentMethods:y,enabledPaymentMethodCountries:he,showApplePay:F=!0,showGooglePay:te=!0,layout:be="default",theme:j,buttonsTheme:q,buttonsStyles:oe,appearance:ie,cardButtonContent:Ne,cardBackButtonContent:f,cardTitleContent:ae,showSecurityFooter:Fe,onButtonClick:ve,onBeforeButtonClick:Re,enableAVS:J,cardFieldOrder:le,cardPreFormSlot:De,avsLayout:se="row",country:_e,zip:Ue,addressLine1:xe,addressLine2:H,city:P,state:Q,onCountryChange:We,onZipChange:Le,avsCheck:Z,checkoutType:_,checkoutLayout:ce,totalAmount:K=0,currency:de="usd",initialCardOpen:et=!1,directPaypal:$e,isSubscription:it=!1,session:ue,dataAttachmentPending:G=!1,debug:tt=!1}){let Y=kn(),mt=Vo(),je=il(mn),qe=G||je.claimPending===!0,$t=uo(),[nt,en]=ke(!1),[S,pe]=ke(null),[Je,Xe]=ke(_e??"US"),[xt,yt]=ke(Ue??""),[Te,ft]=ke(xe??""),[Ie,tn]=ke(H??""),[Ke,Dn]=ke(P??""),[Jt,fn]=ke(Q??""),[Ln,On]=ke({}),jt=Be(Ue??""),dt=Be(_e??"US"),ln=Be(xe??""),qt=Be(H??""),Kt=Be(P??""),Vt=Be(Q??""),Bt=Be({});ct(()=>{let r=(M,$,re,U,we)=>{if(Bt.current[M])return;let Ae=$?.trim();!Ae||Ae===re.current||(re.current=Ae,U(Ae),we?.(Ae))};r("country",_e,dt,Xe,We),r("zip",Ue,jt,yt,Le),r("addressLine1",xe,ln,ft),r("addressLine2",H,qt,tn),r("city",P,Kt,Dn),r("state",Q,Vt,fn)},[_e,Ue,xe,H,P,Q,We,Le]);let X=lt(()=>Js(J),[J]),zn=X!==null,nn=lt(()=>ea(ue),[ue]),Xt=!!ue?.vault?.html,Hn=!!ue?.gateways?.pcivault,ot=!!(ue?.gateways?.stripe?.enabledPaymentMethods??y)?.includes("card"),He=Xt||ot||Hn,Ve=!!(I&&He&&Y&&e),[Ye,_n]=ke(()=>be!=="buttons"||et?e??null:null),[Nn,ar]=ke(0),gn=be!=="buttons"||et||!!e&&Ye===e,at=lt(()=>!Y||!Ve||!e||!gn?null:Y.cardCapture({sessionId:e,captureMethod:ue?.captureMethod}),[Y,Ve,e,gn,ue?.captureMethod]),Ht=lt(()=>{let r=Je,M=X?Oe(X.postal_code,r):!1;return gl(r,xt,M)},[X,Je,xt]),{avsInvalid:hn,invalidAvsFields:Ct}=lt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!Ve||!X)return{avsInvalid:!1,invalidAvsFields:r};let M=Je,$=(we,Ae)=>Oe(we,M)&&!Ae.trim(),re={line1:$(X.address_line_1,Te),city:$(X.city,Ke),state:$(X.state,Jt),zip:Ht.empty||Ht.malformed};return{avsInvalid:re.line1||re.city||re.state||re.zip,invalidAvsFields:re}},[Ve,X,Je,Te,Ke,Jt,Ht]),[Lt,cn]=ke(!1),[rn,Qt]=ke(!1),[Zt,Ft]=ke(()=>ta(ue?.vault)),[Se,St]=ke(et&&He?"card":"buttons"),[gt,Pn]=ke(null),ir=Se==="expanding"||Se==="card",Ot=280,on=Be(null),Dt=Ee(r=>{on.current&&clearTimeout(on.current),on.current=setTimeout(()=>{on.current=null,r()},Ot)},[Ot]);ct(()=>()=>{on.current&&clearTimeout(on.current)},[]);let Yn=Ee(()=>{_n(e??null),ar(r=>r+1),St("expanding"),Dt(()=>St("card"))},[Dt,e]),dn=Ee(()=>{St("collapsing"),Dt(()=>St("buttons"))},[Dt]),Un=Ee(r=>{Pn(r),St("apm-expanding"),Dt(()=>St("apm-form"))},[Dt]),zt=Ee(()=>{St("apm-collapsing"),Dt(()=>{St("buttons"),Pn(null)})},[Dt]);ct(()=>{be==="buttons"&&et&&He&&(_n(e??null),St("card"))},[be,et,He,e]);let[bn,Me]=ke(null),k=Be(!1),D=Be(null),L=Be("idle"),[fe,Ce]=ke(null),W=Be(fe);ct(()=>{W.current=fe},[fe]);let m=n||$t,O=u??S,c=lt(()=>ll(j),[j]),o=lt(()=>{let r=c?.buttonsLayout??Ys(q);return oe?{...r,...oe,cardButton:{...r.cardButton,...oe.cardButton},cardFormContainer:{...r.cardFormContainer,...oe.cardFormContainer},backButton:{...r.backButton,...oe.backButton},backButtonIcon:{...r.backButtonIcon,...oe.backButtonIcon},submitButton:{...r.submitButton,...oe.submitButton},title:{...r.title,...oe.title}}:r},[c,q,oe]),E=ie??c?.appearance,ye=lt(()=>Za({appearance:E,buttonsStyles:o,layout:be}),[E,o,be]),Pe=je.inlineSessionPatchProcessing??!1,V=(A??nt)||Pe,Ge=m.replace(/\/+$/,""),x=lt(()=>Wo({userId:a,email:s,firstName:z,lastName:g,country:_e,zip:Ue},Ln),[a,s,z,g,_e,Ue,Ln]),N=[x.firstName,x.lastName].filter(r=>!!r?.trim()).join(" "),C=lt(()=>Y?Y.getRawProvider():null,[Y]),T=lt(()=>mt?mt.getRawProvider():null,[mt]),ne=K||100,vt=lt(()=>E?ol(E):null,[E]),Yt=vt?{appearance:vt}:null,Nt=lt(()=>{let r=vt??{},M=r.rules??{};return{...r,rules:{...M,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...M[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...M[".AccordionItemContents"]??{}}}}},[vt]),Xr=lt(()=>{let r=ci(K);return{...r,currency:de.toLowerCase(),paymentMethodCreation:"manual",...r.mode==="payment"?{captureMethod:"manual"}:{},...Yt}},[K,de,Yt]),ka=lt(()=>({mode:"payment",amount:ne,currency:de.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Yt}),[ne,de,Yt]),me=Ee(r=>{pe(r),h?.(r)},[h]);ct(()=>{!Ve||!at||at.setCardFieldOrder?.(le??null,X==null)},[Ve,at,le,X]),ct(()=>{(Se==="expanding"||Se==="collapsing"||Se==="apm-expanding"||Se==="apm-collapsing")&&me(null)},[Se,me]);let un=Ee((r,M,$)=>{l?.(It(r,M,$))},[l]),sr=Ee((r,M,$)=>{let re=$?.popupBlocked??jn(M),U=yl(r,re),we=er($?.code)??Mn(M)??"external_payment_method_failed",Ae=new Rn(U,"api_error",{code:"external_payment_method_failed",param:r});Me(null),be==="buttons"&&(St("buttons"),Pn(null)),me(U),p?.(Ae),console.error("[FloPay] External payment method failed:",{method:r,code:we,popupBlocked:re})},[be,p,me]);ct(()=>{if(!Ve||!e){Ft(null);return}let r=ta(ue?.vault);if(r){Ft(r);return}if(!gn){Ft(null);return}Ft(null);let M=!0;return new qn(Ge).getVaultCapture(e,t).then($=>{if(!M)return;let re=ta($);re?Ft(re):me("Failed to load the secure card form.")}).catch($=>{M&&me($ instanceof Error?$.message:"Failed to load the secure card form.")}),()=>{M=!1}},[Ve,gn,Nn,e,ue?.vault?.html,ue?.vault?.messageToken,ue?.vault?.expectedOrigin,Ge,t,me]);let vn=Be({onComplete:i,onError:p,updateError:me,emitDecline:un,resolvedAccount:x,avsConfig:X,avsCheckProp:Z,sessionId:e,nonce:t,baseUrl:Ge,captureMethod:ue?.captureMethod,paymentId:ue?.paymentId,authorizationExpiresAt:ue?.authorizationExpiresAt});vn.current={onComplete:i,onError:p,updateError:me,emitDecline:un,resolvedAccount:x,avsConfig:X,avsCheckProp:Z,sessionId:e,nonce:t,baseUrl:Ge,captureMethod:ue?.captureMethod,paymentId:ue?.paymentId,authorizationExpiresAt:ue?.authorizationExpiresAt};let xo=Be(!1),Zi=Ee(()=>{let{resolvedAccount:r,avsConfig:M,avsCheckProp:$}=vn.current,re=dt.current||r.country||"US",U=M?Oe(M.state,re):!1,we=M?Oe(M.address_line_1,re):!1,Ae=M?Oe(M.postal_code,re):!1,st=M?Oe(M.city,re):!1,Pt=M?Oe(M.address_line_2,re):!1,Qe=we&&!U&&Ae?hi(re,(jt.current??"").trim()):null,wt=U?Vt.current:Qe;return{accountData:{userId:r.userId??"",email:r.email??"",firstName:r.firstName??"",lastName:r.lastName??"",...Ae&&jt.current?{zip:jt.current}:{},...st&&Kt.current?{city:Kt.current}:{},...wt?{state:wt}:{},...we&&ln.current?{addressLine1:ln.current}:{},...Pt&&qt.current?{addressLine2:qt.current}:{},country:re},...$!==void 0?{avsCheck:$}:{},...M?{avsConfig:{country:Oe(M.country,re),postal_code:Ae,address_line_1:we,address_line_2:Pt,city:st,state:U}}:{}}},[]),Ra=Be(qe);Ra.current=qe,ct(()=>{qe||O!==Ci||vn.current.updateError(null)},[qe,O]),ct(()=>{!Ve||!at||at.setSubmitGate?.(hn||qe)},[Ve,at,hn,qe]),ct(()=>{if(!Ve||!at)return;xo.current=!1;let r=!1,M=at.on("submitting",()=>{cn(!0),D.current&&clearTimeout(D.current),L.current="validation-window",D.current=setTimeout(()=>{D.current=null,L.current==="validation-window"&&(L.current="processing")},cl),Me("processing");let{baseUrl:Ae,sessionId:st,nonce:Pt,updateError:Qe,onError:wt}=vn.current;!st||!Pt||new qn(Ae).patchAccountSnapshot(st,Pt,Zi(),{telemetryMode:"best_effort"}).catch(ge=>{if(!dl(ge))return;let Tt=ge instanceof Error?ge.message:"Please check your billing address and try again.";Qe(Tt),L.current="idle",Me(null),wt?.(ge instanceof Rn?ge:new Rn(Tt,"api_error"))})}),$=at.on("complete",async Ae=>{if(fr(Ae.sessionId??vn.current.sessionId),L.current="terminal",Me("success"),await new Promise(Qe=>setTimeout(Qe,xn)),xo.current)return;xo.current=!0;let st=vn.current,Pt=ea(st)||Ae.outcome==="authorized";vn.current.onComplete?.(Pt?{status:"authorized",paymentIntentId:Ae.intentId,paymentId:Ae.paymentId??st.paymentId,sessionId:Ae.sessionId??st.sessionId,authorizationExpiresAt:Ae.authorizationExpiresAt??st.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ae.intentId,checkoutMethod:"card"})}),re=at.on("decline",async Ae=>{let{updateError:st,emitDecline:Pt}=vn.current,Qe=Ae.message??"Your payment was declined. Please try another card or contact your bank.";L.current="terminal",st(Qe),Me("error");let wt=Ae.failureOutcome??Hs(Ae.declineReason)??"authorization_declined";Pt("card",Qe,{code:wt,declineCode:wt}),await new Promise(ge=>setTimeout(ge,Sn)),!r&&(L.current="idle",Me(null))}),U=at.on("error",async Ae=>{let{updateError:st,onError:Pt}=vn.current,Qe=Ae.message??"There was a problem processing your payment. Please try again.";L.current="terminal",st(Qe),Me("error"),Pt?.(new Rn(Qe,"api_error",{code:Ae.failureOutcome??"capture_failed"})),await new Promise(wt=>setTimeout(wt,Sn)),!r&&(L.current="idle",Me(null))}),we=at.on("blocked",()=>{if(!Ra.current){cn(!0);return}vn.current.updateError(Ci)});return()=>{r=!0,D.current&&(clearTimeout(D.current),D.current=null),L.current="idle",M(),$(),re(),U(),we()}},[Ve,at]);let Cn=!!$e?.clientId,Er=Array.isArray(y),Qr=Er&&y.length>0,es=Er&&y.includes("paypal"),{expressMethods:Zr,paymentElementMethods:_r}=lt(()=>rl(y,{excludePaypal:Cn}),[y,Cn]),Ia=Cn||!!mt,ts=lt(()=>Ia?Zr.filter(r=>r!=="paypal"):Zr,[Zr,Ia]),ns=lt(()=>{let r=[];return F&&r.push("apple_pay"),te&&r.push("google_pay"),r},[F,te]),eo=Er?ts:ns,rs=I&&eo.length>0,To=zn?Je:_e,to=lt(()=>{let r=To?.trim().toUpperCase();return r?he?_r.filter(M=>{let $=he[M];return!$||$.length===0||$.includes(r)}):el(_r,To):_r},[_r,To,he]),Mo=lt(()=>({mode:"payment",amount:ne,currency:de.toLowerCase(),paymentMethodCreation:"manual",appearance:Nt}),[ne,de,Nt]),[Ea,_a]=ke("loading"),[xa,Ta]=ke("loading"),[Ma,Aa]=ke("loading"),[os,Ao]=ke(!1),[Ba,Bo]=ke("loading"),[no,as]=ke();ct(()=>{as(di())},[]);let Fa=w&&(Cn||(Er?es:no===!1)),Da=I&&rs,xr=!qe&&Fa&&Cn,La=Ba==="retrying"||Ba==="exhausted",Tr=!qe&&Fa&&!!T&&(!Cn||La),Mr=!qe&&Da&&!!C,Ar=!qe&&I&&Qr&&to.length>0&&!!C,is=xr&&!La?os:Tr&&ki(Ea),ss=Mr&&ki(xa),ls=Ar&&Ma!=="load_error",Oa=r=>r==="loading"||r==="ready",za=xr||Tr&&Oa(Ea)||Mr&&Oa(xa)||Ar&&Ma!=="load_error",ro=Be(!1);ct(()=>{if(!ro.current){if(!I&&!w){ro.current=!0;let r=new Rn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(r),me(r.message)}else if(!I&&w&&!Cn&&!T){ro.current=!0;let r=new Rn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(r),me(r.message)}else if(no!==void 0&&!qe&&!He&&!za){ro.current=!0;let r=new Rn("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?.(r),me(r.message)}}},[I,w,Cn,T,no,qe,He,za,p,me]);let Na=Be(!1);ct(()=>{if(Na.current||!Qr)return;let r=[];F!==!0&&r.push("showApplePay"),te!==!0&&r.push("showGooglePay"),r.length!==0&&(Na.current=!0,console.warn(`[FloPay] ${r.join(" / ")} ${r.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Qr,F,te]);let Ua=Ee((r,M)=>je.applyInlineSessionPatch?je.applyInlineSessionPatch(r).then($=>({error:null,sessionId:$.sessionId||e,nonce:$.session?.clientSecret||t})).catch($=>{let re=wi(M,$);return me(re.message),p?.(re),{error:re,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[je.applyInlineSessionPatch,t,p,e,me]),pn=Ee(async r=>{if(!Re)return{proceed:!0};try{let M=await Re({method:r,sessionId:e||void 0,createSession:je.inlineSessionDraft});if(M===!1)return{proceed:!1};if(M&&typeof M=="object"){M.account&&On(re=>({...re??{},...M.account}));let $=await Ua(M,r);return $.error?{proceed:!1,accountPatch:M.account}:{proceed:!0,accountPatch:M.account,sessionId:$.sessionId,nonce:$.nonce}}return{proceed:!0}}catch(M){let $=wi(r,M);return me($.message),p?.($),{proceed:!1}}},[Ua,je.inlineSessionDraft,Re,p,e,me]),$a=Ee(async(r,M)=>{if(k.current)return;k.current=!0,en(!0),Me("processing"),me(null);let $=M?.sessionId??e,re=M?.nonce??t,U=Wo(x,M?.accountPatch),we=M?.completionPaymentMethodId??$r(r),Ae=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r;try{let Pt=await new qn(Ge).processPayment(U.userId??"",{sessionId:$,nonce:re,tokenizedData:Ae,accountData:{userId:U.userId??"",email:U.email??"",firstName:U.firstName??"",lastName:U.lastName??"",...X?(()=>{let ge=dt.current,Tt=Oe(X.state,ge),Gt=Oe(X.address_line_1,ge),Xn=Oe(X.postal_code,ge),Qn=Gt&&!Tt&&Xn?hi(ge,(jt.current??"").trim()):null,Mt=Tt?Vt.current:Qn;return{country:ge,...Xn&&jt.current?{zip:jt.current}:{},...Oe(X.city,ge)&&Kt.current?{city:Kt.current}:{},...Mt?{state:Mt}:{},...Gt&&ln.current?{addressLine1:ln.current}:{},...Oe(X.address_line_2,ge)&&qt.current?{addressLine2:qt.current}:{}}})():{}},chv:R,avsCheck:Z??!1,checkoutType:_,checkoutLayout:ce,avsConfig:X?{country:Oe(X.country,dt.current),postal_code:Oe(X.postal_code,dt.current),address_line_1:Oe(X.address_line_1,dt.current),address_line_2:Oe(X.address_line_2,dt.current),city:Oe(X.city,dt.current),state:Oe(X.state,dt.current)}:void 0});if(Pt.ok){let ge=Pt.status===204?null:await Pt.json().catch(()=>null),Tt=ea(ue)||ge?.status==="authorized";fr($),Me("success"),Ce(null),await new Promise(Gt=>setTimeout(Gt,xn)),i?.(Tt?{status:"authorized",...typeof ge?.paymentId=="string"?{paymentId:ge.paymentId}:ue?.paymentId?{paymentId:ue.paymentId}:{},sessionId:typeof ge?.sessionId=="string"?ge.sessionId:$,...typeof ge?.authorizationExpiresAt=="string"?{authorizationExpiresAt:ge.authorizationExpiresAt}:ue?.authorizationExpiresAt?{authorizationExpiresAt:ue.authorizationExpiresAt}:{},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:we,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:we,checkoutMethod:r.isPaypal?"paypal":"card"});return}let Qe=await Pt.json().catch(()=>null);if(Qe?.type==="paypal_redirect_required"){let ge=Qe.threeDSecureToken,Tt=Qe.paymentMethodId||r.id||"";if(!Y||!ge){Me("error"),me("PayPal authorization required but no token provided.");return}try{let Gt=mt?.getRawProvider();if(!Gt){me("PayPal is not available.");return}let Xn={return_url:window.location.href};Tt&&(Xn.payment_method=Tt);let{error:Qn}=await Gt.confirmPayment({clientSecret:ge,confirmParams:Xn,redirect:"if_required"});if(Qn){Me("error");let Mt=Qn.message??"PayPal payment failed.";me(Mt),un("paypal",Mt,{code:Qn.code})}}catch(Gt){Me("error"),me(Gt instanceof Error?Gt.message:"PayPal authorization failed.")}return}if(Qe?.type==="paypal_direct_required"){let ge=Qe.orderId;if(!ge){Me("error"),me("PayPal retry required but no order id provided.");return}let Tt=W.current?.attempts??0;if(Tt>=2){Me("error"),me("PayPal payment could not be completed after multiple attempts."),un("paypal","paypal_direct_required retry limit exceeded");return}Ao(!1),Bo("loading"),Ce({orderId:ge,attempts:Tt+1}),Me(null);return}Me("error");let wt=Qe?.message??"Payment failed. Please try again.";me(wt),un(r.isPaypal?"paypal":"card",wt,{code:Qe?.code??Qe?.gatewayErrorCode,declineCode:Qe?.declineCode??Qe?.gatewayDeclineReason}),await new Promise(ge=>setTimeout(ge,Sn))}catch(st){Me("error"),me(st instanceof Error?st.message:"An unexpected error occurred"),await new Promise(Pt=>setTimeout(Pt,Sn))}finally{en(!1),Me(null),k.current=!1}},[Ge,e,t,x,N,R,Y,mt,ue,i,p,me,un]),an=Ee((r,M)=>{b?b(r):$a(r,M)},[b,$a]),ja=Be(!1);ct(()=>{if(typeof window>"u"||ja.current)return;let r=new URLSearchParams(window.location.search),M=r.get("payment_intent"),$=r.get("payment_intent_client_secret"),re=r.get("redirect_status");if(!M||!$)return;let U=wt=>{let ge=localStorage.getItem(wt);if(!ge)return null;try{return JSON.parse(ge)}catch{return localStorage.removeItem(wt),null}},we=U(In)??U(vi),Ae;if(we?.clientSecret){if(we.clientSecret!==$)return;Ae={...we.accountPatch?{accountPatch:we.accountPatch}:{},...we.sessionId?{sessionId:we.sessionId}:{},...we.nonce?{nonce:we.nonce}:{}}}else if(we?.sessionId&&we.sessionId!==e)return;ja.current=!0,localStorage.removeItem(In),localStorage.removeItem(vi);let st=new URL(window.location.href);st.searchParams.delete("payment_intent"),st.searchParams.delete("payment_intent_client_secret"),st.searchParams.delete("redirect_status"),window.history.replaceState({},"",st.toString());let Pt=we?.paymentMethodType??we?.tokenType??"card",Qe="card";(async()=>{let wt=Y?.getRawProvider();if(!wt){let Mt="Payment is not available \u2014 please refresh and try again.";me(Mt),un(Qe,Mt);return}if(re==="failed"){let Mt="Payment was declined. Please try again.";me(Mt),un(Qe,Mt);return}let{paymentIntent:ge,error:Tt}=await wt.retrievePaymentIntent($);if(Tt){let Mt=Tt.message??"Failed to retrieve payment status.";me(Mt),un(Qe,Mt,{code:Tt.code});return}let Gt=ge?.status,Xn=yo(Gt);if(!ge||!Xn){let Mt=Gt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";me(Mt),un(Qe,Mt,{code:Gt??"missing_payment_intent"});return}let Qn=typeof ge.payment_method=="string"?ge.payment_method:ge.payment_method?.id;an({id:Qn??we?.paymentMethodId??we?.tokenId??ge.id,type:"card",threeDSecureActionResultTokenId:ge.id,gateway:we?.gateway??"stripe",paymentMethodType:Pt},Ae)})()},[e,an,Y,me,un]);let Fo=Ee(r=>{r.preventDefault()},[]);if(!(Y!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Br=be==="buttons",Wt=E?.variables,cs=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Do=Wt?.colorBackground,ds=Do&&!cs.has(Do)?Do:void 0,Fr=o.cardInputBorder??(Br?"#e5e7eb":"#A4A4FF"),Lo=Wt?.colorDanger??"#dc2626",Wn=r=>Lt&&r?Lo:Fr,oo=(Ht.malformed||Ht.empty)&&(rn||Lt),us=oo?Lo:Wn(Ct.zip),Oo=o.cardFormContainer?.backgroundColor??ds??(Br?"white":"#EDEDFF"),Dr=o.cardInputBackground??Wt?.colorBackground??"white",zo=cr(f),qa=cr(ae),lr=o.nameInput,Ka=o.cardInputFontSize??hl(lr?.fontSize)??Wt?.fontSizeBase??"16px",Va=typeof lr?.fontFamily=="string"?lr.fontFamily:Wt?.fontFamily??"Poppins, sans-serif",Ha=Qa(lr?.fontWeight)??400,ps=o.cardInputColor??(typeof lr?.color=="string"?lr.color:void 0)??Wt?.colorText??"#262833",ms=o.cardInputPlaceholderColor??"#9ca3af",ht=Wt?.borderRadius??"8px",Gn=Wt?.borderRadius??o.cardButton?.borderRadius??ht,Jn=Wt?.colorPrimary??"#4A49FF",ys=Wt?.colorPrimaryHover??Or(Jn,.12),No=Wt?.colorText??"#262833",Ya={fontSize:Ka,fontFamily:Va,fontWeight:Ha,color:ps,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},fs={"--flopay-input-placeholder-color":ms,"--flopay-input-font-size":Ka,"--flopay-input-font-family":Va,"--flopay-input-font-weight":String(Ha)},Lr=o.cardFormContainer??{},Uo=Lr.padding??(Br?"0":"1rem"),$o=Lr.borderRadius??ht,gs=at&&Zt?d(jo,{capture:at,html:Zt.html,messageToken:Zt.messageToken,expectedOrigin:Zt.expectedOrigin,theme:ye,onReady:()=>{if(!X||typeof document>"u")return;let r=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};r();let M=0,$=window.setInterval(()=>{M+=1;let re=document.activeElement;!!re&&re.tagName==="IFRAME"&&re.id==="flopay_vault_form_iframe"?(r(),window.clearInterval($)):M>=50&&window.clearInterval($)},100)},onError:r=>me(r),onValidation:r=>{let M=L.current;(M==="idle"||M==="validation-window")&&(me(r),r&&L.current==="validation-window"&&(D.current&&(clearTimeout(D.current),D.current=null),L.current="idle",Me(null)))}}):d("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"}),Wa=ze("div",{style:{backgroundColor:Oo,borderRadius:$o,...Lr,padding:Uo,...fs,display:"flex",flexDirection:"column"},children:[d("style",{children:`
26
26
  .flopay-shared-input::placeholder {
27
27
  color: var(--flopay-input-placeholder-color);
28
28
  opacity: 1;
@@ -30,13 +30,13 @@ ${Ge.join(`
30
30
  font-family: var(--flopay-input-font-family);
31
31
  font-weight: var(--flopay-input-font-weight);
32
32
  }
33
- `}),Ar&&Hn&&Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ve?-2:0},children:[Le("button",{type:"button",onClick:zn,style:{display:"inline-flex",alignItems:"center",gap:No?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(cr,{content:K})]}),qa?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...f.title},children:d(Nr,{content:ie})})]}),!Ar&&!qa&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Oo,order:Ve?-3:0,...f.title},children:d(Nr,{content:ie})}),X&&d("div",{style:{order:Ve?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let o=We,B=($=!1)=>({backgroundColor:Fr,border:`1px solid ${Wn($)}`,borderRadius:ht,marginTop:"0.5rem",padding:"10px"}),q=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ha}),ne=Ws(o);return Le(gr,{children:[De(X.address_line_1,o)&&d("div",{style:B(gt.line1),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:je,onChange:$=>{Ct.current.addressLine1=!0,Zt.current=$.target.value,tt($.target.value)},disabled:G,required:!0,"data-testid":"flopay-address-line1",style:q()})}),De(X.address_line_2,o)&&d("div",{style:B(),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Je,onChange:$=>{Ct.current.addressLine2=!0,en.current=$.target.value,kn($.target.value)},disabled:G,"data-testid":"flopay-address-line2",style:q()})}),(De(X.city,o)||De(X.state,o))&&Le("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[De(X.city,o)&&d("div",{style:{flex:1,backgroundColor:Fr,borderTop:`1px solid ${Wn(gt.city)}`,borderRight:`1px solid ${Wn(gt.city)}`,borderBottom:`1px solid ${Wn(gt.city)}`,borderLeft:`1px solid ${Wn(gt.city)}`,padding:"10px",borderTopLeftRadius:ht,borderBottomLeftRadius:ht,...De(X.state,o)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:ht}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:ot,onChange:$=>{Ct.current.city=!0,Ft.current=$.target.value,jn($.target.value)},disabled:G,required:!0,"data-testid":"flopay-city",style:q()})}),De(X.state,o)&&d("div",{style:{flex:1,backgroundColor:Fr,border:`1px solid ${Wn(gt.state)}`,padding:"10px",borderTopRightRadius:ht,borderBottomRightRadius:ht,...De(X.city,o)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:ht}},children:ne?Le("select",{id:"flopay-billing-state",name:"billing-state",value:Wt,onChange:$=>{Ct.current.state=!0,Dt.current=$.target.value,mn($.target.value)},disabled:G,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...q(),cursor:"pointer"},children:[d("option",{value:"",children:fi(o)}),ne.map($=>d("option",{value:$.code,children:$.name},$.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:fi(o),autoComplete:"billing address-level1",value:Wt,onChange:$=>{Ct.current.state=!0,Dt.current=$.target.value,mn($.target.value)},disabled:G,required:!0,"data-testid":"flopay-state",style:q()})})]}),(De(X.country,o)||De(X.postal_code,o))&&Le("div",{style:{display:"flex",flexDirection:Z==="column"?"column":"row",gap:Z==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[De(X.country,o)&&d("div",{style:{flex:Z==="row"?1:void 0,backgroundColor:Fr,borderTop:`1px solid ${Br}`,borderRight:`1px solid ${Br}`,borderBottom:`1px solid ${Br}`,borderLeft:`1px solid ${Br}`,padding:"10px",...Z==="row"&&De(X.postal_code,o)?{borderRadius:"0",borderTopLeftRadius:ht,borderBottomLeftRadius:ht,borderRight:"none"}:{borderRadius:ht}},children:d("select",{id:"flopay-billing-country",name:"billing-country",value:We,onChange:$=>{Ct.current.country=!0,St.current=$.target.value,Re($.target.value),$e?.($.target.value),Dt.current="",mn("")},disabled:G,autoComplete:"billing country","data-testid":"flopay-country",style:{...q(),cursor:"pointer"},children:Ys.map($=>Le("option",{value:$.code,children:[$.flag," ",$.name]},$.code))})}),De(X.postal_code,o)&&d("div",{style:{flex:Z==="row"?1:void 0,backgroundColor:Fr,border:`1px solid ${ds}`,padding:"10px",...Z==="row"&&De(X.country,o)?{borderRadius:"0",borderTopRightRadius:ht,borderBottomRightRadius:ht}:{borderRadius:ht}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:na(We),autoComplete:"billing postal-code",value:vt,onChange:$=>{Ct.current.zip=!0,Bt.current=$.target.value,Ke($.target.value),ze?.($.target.value)},onBlur:()=>Yt(!0),disabled:G,required:zt.required,"aria-invalid":ro||void 0,"aria-describedby":ro?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:q()})})]}),ro&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Lo,...Ha,fontSize:"0.75rem"},children:zt.empty?`${na(o)} is required`:yl(o)})]})})()}),Ve&&Te&&d("div",{style:{order:-2,width:"100%"},children:Te}),Ve&&fs,y&&d(ur,{margin:"0.75rem 0",styleOverride:f.errorBanner,children:y})]}),oo={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"},Ya=o=>et?!k||!hn?d("pre",{"data-testid":o,style:oo,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":o,style:oo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${k}`,` directPaypalConfigured=${hn}`,` inAppBrowserDetected=${String(to)}`,` shouldRenderDirectPayPal=${_r}`,` shouldRenderStripePayPal=${xr}`,` hasPaypalStripeInstance=${!!Se}`].join(`
34
- `)}):null,Ga=o=>et?!T||!ue?d("pre",{"data-testid":o,style:oo,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":o,style:oo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${T}`,` currency=${ke}`,` amountInCents=${Ee}`,` enabledPaymentMethods: ${JSON.stringify(g??[])}`,` enabledPaymentMethodsProvided=${Ir}`,` hasEnabledMethods=${Xr}`,` expressMethods: ${JSON.stringify(Qr)}`,` walletExpressMethods: ${JSON.stringify(Zr)}`,` paymentElementMethods: ${JSON.stringify(Er)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(eo)}`,` hasStripeInstance=${!!ue}`,` shouldRenderWallets=${Tr}`,` shouldRenderPaymentElement=${Mr}`].join(`
35
- `)}):null,Ja=Ie==="apm-expanding"||Ie==="apm-form"||Ie==="apm-collapsing",ao=Ie==="apm-expanding"?`flopay-card-enter ${jt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ie==="apm-collapsing"?`flopay-card-exit ${jt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,io=yt?{...Mo,paymentMethodTypes:[yt]}:null;if(ce==="buttons"){let o=Ie==="buttons"||Ie==="expanding"||Ie==="apm-expanding",B=Ie==="expanding"||Ie==="card"||Ie==="collapsing",q=j===void 0?{boxSizing:"border-box",height:Po,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ne=Ie==="expanding"||Ie==="apm-expanding"?`flopay-buttons-exit ${jt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ie==="collapsing"||Ie==="apm-collapsing"?`flopay-buttons-enter ${jt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,$=Ie==="expanding"?`flopay-card-enter ${jt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ie==="collapsing"?`flopay-card-exit ${jt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Le("form",{onSubmit:Fo,className:C,style:{position:"relative"},children:[d(ta,{}),rn&&d(bn,{status:rn,errorMessage:y,authorized:A}),Le("div",{style:{display:"grid"},children:[Le("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!o&&!ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!o&&!ne?ul:{},...ne?{animation:ne,pointerEvents:"none"}:{}},children:[Ya("flopay-direct-paypal-gate-debug"),Ga("flopay-stripe-gate-debug"),_r&&Ge&&Le(gr,{children:[ge&&d("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."}),d(ho,{sessionId:e,nonce:t,billingApiUrl:r,email:p.email,clientId:Ge.clientId,environment:Ge.environment,currency:ke.toUpperCase(),isSubscription:pt,onTokenizedBody:on,onComplete:i,onErrorChange:se,onDecline:l,onTechnicalFailure:ar,onButtonClick:he,runBeforeButtonClick:dn,isProcessing:G,onLoadStateChange:Ao,onInitializationStateChange:Bo,session:_??null,existingOrderId:ge?.orderId,debug:et},ge?.orderId??"fresh")]}),xr&&d(tr,{stripe:Se,options:wa,children:d(ki,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,onTokenizedBody:on,onErrorChange:se,isProcessing:G,onButtonClick:he,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:dn,onLoadStateChange:Ea,placeholderBorderRadius:Yn})}),Tr?d(tr,{stripe:ue,options:Jr,children:d(Ri,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,intentKind:W>0?"payment":"setup",expressMethods:Zr,onTokenizedBody:on,onErrorChange:se,onButtonClick:he,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:dn,onLoadStateChange:xa,placeholderBorderRadius:Yn})}):Fa?d("div",{style:{height:Po,borderRadius:Yn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Mr&&d(Ii,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,paymentElementMethods:eo,stripeInstance:ue,paymentElementBaseOptions:Mo,onTokenizedBody:on,onErrorChange:se,onButtonClick:he,onDecline:l,runBeforeButtonClick:dn,onLoadStateChange:Ma,isProcessing:G,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,onExpandApm:nn,expandedApmMethod:yt,themeId:z,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Yn}}),Ve&&d("button",{type:"button",onClick:async()=>{G||!(await dn("card")).proceed||(he?.("card"),Ln())},disabled:G,style:{width:"100%",...q,...f.cardButton,...sa({themeBundle:x,resolvedPrimaryColor:Gn,resolvedBorderRadius:ht,submitButtonStyle:f.submitButton,explicitPrimaryColor:Vt?.colorPrimary}),fontSize:f.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:G?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:G?.6:1},onMouseEnter:be=>{!G&&(x||Vt?.colorPrimary)&&(be.currentTarget.style.backgroundColor=ms)},onMouseLeave:be=>{(x||Vt?.colorPrimary)&&(be.currentTarget.style.backgroundColor=Gn)},onMouseDown:be=>{be.currentTarget.style.transform="scale(0.985)"},onMouseUp:be=>{be.currentTarget.style.transform="scale(1)"},children:d(lr,{content:j})}),y&&Ie==="buttons"&&d(ur,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:y})]}),Ve&&B&&d("div",{style:{gridArea:"1 / 1",...$?{animation:$}:{},...Ie==="collapsing"?{pointerEvents:"none"}:{}},children:Wa}),T&&Ja&&yt&&io&&ue&&d("div",{style:{gridArea:"1 / 1",...ao?{animation:ao}:{},...Ie==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:zo,borderRadius:$o,...Dr,padding:Uo},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:No?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(cr,{content:K})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Oo,paddingRight:80,...f.title},children:`Pay with ${hr(yt)}`})]}),d(tr,{stripe:ue,options:io,children:d(ra,{method:yt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,onTokenizedBody:on,onErrorChange:se,onDecline:l,onCancel:Gt,runBeforeButtonClick:dn,onButtonClick:he,isProcessing:G,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,errorText:y})},yt)]})})]})]})}return Ja&&yt&&io&&ue&&T?Le("form",{onSubmit:Fo,className:C,style:{position:"relative"},children:[d(ta,{}),rn&&d(bn,{status:rn,errorMessage:y,authorized:A}),d("div",{style:{...ao?{animation:ao}:{},...Ie==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:zo,borderRadius:$o,...Dr,padding:Uo},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:No?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(cr,{content:K})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Oo,paddingRight:80,...f.title},children:`Pay with ${hr(yt)}`})]}),d(tr,{stripe:ue,options:io,children:d(ra,{method:yt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,onTokenizedBody:on,onErrorChange:se,onDecline:l,onCancel:Gt,runBeforeButtonClick:dn,onButtonClick:he,isProcessing:G,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,errorText:y})},yt)]})})]}):Le("form",{onSubmit:Fo,className:C,style:{position:"relative"},children:[d(ta,{}),rn&&d(bn,{status:rn,errorMessage:y,authorized:A}),Le("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ya("flopay-direct-paypal-gate-debug-default"),Ga("flopay-stripe-gate-debug-default"),_r&&Ge&&Le(gr,{children:[ge&&d("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."}),d(ho,{sessionId:e,nonce:t,billingApiUrl:r,email:p.email,clientId:Ge.clientId,environment:Ge.environment,currency:ke.toUpperCase(),isSubscription:pt,onTokenizedBody:on,onComplete:i,onErrorChange:se,onDecline:l,onTechnicalFailure:ar,onButtonClick:he,runBeforeButtonClick:dn,isProcessing:G,onLoadStateChange:Ao,onInitializationStateChange:Bo,session:_??null,existingOrderId:ge?.orderId,debug:et},ge?.orderId??"fresh")]}),xr&&d(tr,{stripe:Se,options:wa,children:d(ki,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,onTokenizedBody:on,onErrorChange:se,isProcessing:G,onButtonClick:he,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:dn,onLoadStateChange:Ea,placeholderBorderRadius:Yn})}),Tr&&d(tr,{stripe:ue,options:Jr,children:d(Ri,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,intentKind:W>0?"payment":"setup",expressMethods:Zr,onTokenizedBody:on,onErrorChange:se,onButtonClick:he,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:dn,onLoadStateChange:xa,placeholderBorderRadius:Yn})}),Mr&&d(Ii,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,paymentElementMethods:eo,stripeInstance:ue,paymentElementBaseOptions:Mo,onTokenizedBody:on,onErrorChange:se,onButtonClick:he,onDecline:l,runBeforeButtonClick:dn,onLoadStateChange:Ma,isProcessing:G,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,themeId:z,onExpandApm:nn,expandedApmMethod:yt,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Yn}})]}),Ve&&(is||as||ss)&&Le("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),d("span",{children:"or pay with card"}),d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ve&&Wa]})}import{loadFloPay as Bi,PaymentAPI as Di}from"@flopay/js";import{classifyPaymentRejection as bl,FloPayError as rt,isAuthorizationOnlySession as vl,isSetupIntentClientSecret as Cl,normalizeCheckoutFailureOutcome as Fi}from"@flopay/shared";var Vr="card";async function Sl(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:s,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:s??null}}async function wl(e,t,n,s){if(s){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:u,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:u??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function da(e,t){return Object.assign(e,{checkoutMethod:t})}function Mn(e,t){let n=e instanceof rt?e:new rt(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Kr(e,t){try{return await e()}catch(n){throw Mn(n,t)}}function Li(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 kl(e){return e.status==="succeeded"||e.status==="declined"}async function zi(e){if(typeof document>"u"||typeof window>"u")throw new rt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,s=15e3,a=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let h=new AbortController,E=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",E);let C=window.setTimeout(()=>h.abort(),s);try{let F=await fetch(a,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!F.ok)return{status:"unknown"};let c=await F.json().catch(()=>null);return Rl(c)}catch{return{status:"unknown"}}finally{window.clearTimeout(C),e.signal?.removeEventListener("abort",E)}},u=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let v=document.createElement("iframe");v.setAttribute("title","Card authentication"),v.setAttribute("allow","payment"),v.tabIndex=0,v.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),v.src=e.nextActionRedirectUrl,l.appendChild(v),document.body.appendChild(l),v.focus();let N=null;try{N=new URL(e.billingApiUrl,window.location.href).origin}catch{N=null}try{let h=await new Promise((E,C)=>{let F=!1,c=0,P=0,k=0,T=!1,g=()=>{window.clearTimeout(c),window.clearInterval(P),window.clearTimeout(k),window.removeEventListener("message",ce),v.removeEventListener("load",M),e.signal?.removeEventListener("abort",le)},me=async()=>{if(!(F||T)){T=!0;try{let z=await i();if(F||!kl(z))return;F=!0,g(),E(z)}finally{T=!1}}},M=()=>{window.clearTimeout(k),k=window.setTimeout(()=>{me()},250)},le=()=>{F||(F=!0,g(),C(new rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ce=z=>{if(z.source!==v.contentWindow||N&&z.origin!==N)return;let J=z.data;!J||typeof J!="object"||J.source!=="flopay-vault-3ds-return"||F||(F=!0,g(),E(null))};c=window.setTimeout(()=>{F||(F=!0,g(),C(new rt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),P=window.setInterval(()=>{me()},n),v.addEventListener("load",M),window.addEventListener("message",ce),e.signal?.addEventListener("abort",le),e.signal?.aborted&&le()});return h||await i()}finally{l.parentNode?.removeChild(l),u?.isConnected&&u.focus()}}function Rl(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 $n(e,t="Payment failed. Please try again.",n){let s=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=Nn(a)??a;return da(new rt(i,"api_error",{code:Fi(e?.outcome)??Fi(e?.type)??e?.gatewayErrorCode}),s)}function ca(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function vo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Il(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function Ni(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||vo(a)))return a;let s=e?.data;if(s&&typeof s=="object"){let a=s,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||vo(l)))return l;let u=a.gateways;if(u&&typeof u=="object"){let l=u.stripe;if(l&&typeof l=="object"){let v=l,N=[v.stripeClientSecret,v.clientSecret];for(let h of N)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||vo(h)))return h}}}}async function El({billingApiUrl:e,sessionId:t,nonce:n,responseJson:s}){let a=Ni(s,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let l=(await new Di(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(vo(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Pr({billingApiUrl:e,sessionId:t,session:n,nonce:s,tokenizedData:a,returnUrl:i,telemetry:u}){let l=e.replace(/\/+$/,""),v=t??n.id,N=s??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",E=n.customer?.email??n.accountData?.email??"",C=n.customer?.firstName??n.accountData?.firstName??"",F=n.customer?.lastName??n.accountData?.lastName??"",c=n.customer?.country??n.accountData?.country??void 0,P=n.customer?.zip??n.accountData?.zip??void 0,k=new Di(l,u===!1?{telemetry:!1}:void 0),T=await Il(()=>k.processPayment(h,{sessionId:v,nonce:N,tokenizedData:a,accountData:{userId:h,email:E,firstName:C,lastName:F,country:c,zip:P},returnUrl:i??ca(n)}));if(T.ok){let M=typeof T.json=="function"?await T.json().catch(()=>null):null;return vl(n)||M?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof M?.paymentId=="string"?M.paymentId:n.paymentId,sessionId:typeof M?.sessionId=="string"?M.sessionId:v,authorizationExpiresAt:typeof M?.authorizationExpiresAt=="string"?M.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Ur(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:a?.threeDSecureActionResultTokenId,paymentMethodId:Ur(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}}let g;try{g=await T.json()}catch{throw new rt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:T.status})}if(g?.type==="paypal_redirect_required"||g?.type==="3ds_required"){let M=Ni(g);if(!M)throw new rt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:T.status});return{type:g.type,threeDSecureToken:M,paymentMethodId:g.paymentMethodId}}if(g?.gatewayErrorCode==="authentication_required"){let M=await El({billingApiUrl:l,sessionId:v,nonce:N,responseJson:g});if(M)return M;throw da(new rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let me=new rt(g?.message??"Payment failed. Please try again.","api_error",{code:g?.code??g?.gatewayErrorCode,declineCode:g?.declineCode??g?.gatewayDeclineReason,statusCode:T.status});throw Object.assign(me,{telemetryOutcome:bl(T.status,g)})}async function Co(e,{flopay:t,paypalFlopay:n,attempt3DS:s,billingApiUrl:a,sessionId:i,session:u,returnUrl:l,telemetry:v}){let N=t?.getRawProvider();if(!N)throw Mn(new rt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!s||!e.threeDSecureToken)throw da(new rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=Cl(e.threeDSecureToken),E=null,C=e.paymentMethodId,F=await Kr(()=>Sl(N,e.threeDSecureToken,h),"card");if(F){if(F.error)throw Mn(new rt(F.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:F.error.code}),"card");let P=F.intent;!C&&P?.payment_method&&(typeof P.payment_method=="string"?C=P.payment_method:"id"in P.payment_method&&(C=P.payment_method.id??void 0))}let c=C?await Kr(()=>wl(N,e.threeDSecureToken,{payment_method:C,return_url:l??ca(u)??window.location.href},h),"card"):null;if(c){if(c.error)throw Mn(new rt(c.error.message??"3DS authentication failed.","api_error",{code:c.error.code}),"card");E=c.intent}else{let P=await Kr(()=>N.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(P.error)throw Mn(new rt(P.error.message??"3DS authentication failed.","api_error",{code:P.error.code}),"card");E=(h?P.setupIntent:P.paymentIntent)??null}if(E&&(E.status==="requires_capture"||E.status==="succeeded"||E.status==="processing")){let P=await Pr({billingApiUrl:a,sessionId:i,session:u,telemetry:v,tokenizedData:{id:E.id,type:"card",threeDSecureActionResultTokenId:E.id},returnUrl:l});return P.type==="success"?{...P.result,paymentIntentId:P.result.paymentIntentId??E.id,paymentMethodId:P.result.paymentMethodId??C}:Co(P,{flopay:t,paypalFlopay:n,attempt3DS:s,billingApiUrl:a,sessionId:i,session:u,returnUrl:l,telemetry:v})}throw Mn(new rt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw Mn(new rt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:C}=await Kr(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(C)throw Mn(new rt(C.message??"PayPal authorization failed.","api_error",{code:C.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:E}=await Kr(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??ca(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(E)throw Mn(new rt(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new rt("Unsupported payment redirect state.","api_error")}function nr(e){if(e instanceof rt){let s=Nn(e.message);return s&&s!==e.message?Object.assign(new rt(s,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Nn(t)??t;return new rt(n,"api_error")}function So(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new rt("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function wo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:s,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[u,l]=await Promise.all([Bi(e,{billingApiUrl:n,locale:s,telemetry:a}),i?Bi(t,{billingApiUrl:n,locale:s,telemetry:a}).catch(v=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",v),null)):Promise.resolve(null)]);return{flopay:u,paypalFlopay:t?i?l:u:null}}import{Fragment as wn,jsx as ee,jsxs as _t}from"react/jsx-runtime";var br=44,Pa="flopay_checkout_saved_payment_resume",Eo=new Map,Ro=new Map;function qi(e,t){t.settled&&t.consumers===0&&Eo.get(e)===t&&Eo.delete(e)}function Bl(e,t,n){let s=Ro.get(e);if(s&&(!s.sdkGeneratedIdempotencyKey||!t||s.sdkGeneratedIdempotencyKey===t))return s.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};Ro.set(e,i);let u=()=>{Ro.get(e)===i&&Ro.delete(e)};return a.then(u,u),a}function Hr(e){return new Promise(t=>setTimeout(t,e))}function Io(e,t,n){let s=so({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Hi,enabled:t!==!1});return s.beginCheckout(n),s}function Wr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function pa(e,t,n,s,a){let i=Io(e,t,n);i.error({errorCode:s,stage:a,paymentMethodCategory:"unknown",...a==="session_read"?{requestCategory:"session_read"}:{}}),Wr(i)}function Fl(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 ga(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function ma(e){return!e||e.data.stripe?.publishableKey?!1:!!ga(e)?.clientId}function Bn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Dl(){if(!Bn())return null;try{let e=window.sessionStorage.getItem(Pa);return e?JSON.parse(e):null}catch{return null}}function ji(e){if(Bn())try{window.sessionStorage.setItem(Pa,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ya(){if(Bn())try{window.sessionStorage.removeItem(Pa)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ba=":idempotency-key";function Ll(e){if(!Bn())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function Ki(e,t,n){if(Bn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(s){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",s)}}function ha(e){if(Bn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function zl(e){if(Bn())try{return window.sessionStorage.getItem(e+ba)??void 0}catch{return}}function Nl(e,t){if(Bn())try{window.sessionStorage.setItem(e+ba,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function Ol(e){if(ha(e),!!Bn())try{window.sessionStorage.removeItem(e+ba)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Ul(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let s of t)e.searchParams.has(s)&&(e.searchParams.delete(s),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function 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 $l(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 fa(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function va({sessionId:e,nonce:t,createSession:n,billingApiUrl:s,telemetry:a,appearance:i,locale:u,loading:l,error:v,onComplete:N,onError:h,onDecline:E,onCountryChange:C,onZipChange:F,showPayPal:c=!0,showStripe:P=!0,enabledPaymentMethods:k,showApplePay:T=!0,showGooglePay:g=!0,debug:me=!1,layout:M,theme:le,buttonsTheme:ce,buttonsStyles:z,cardButtonContent:J,cardBackButtonContent:H,cardTitleContent:oe,showSecurityFooter:j,onButtonClick:K,onBeforeButtonClick:ie,enableAVS:xe,cardFieldOrder:he,cardPreFormSlot:de,avsLayout:Q,className:ye,initialErrorMessage:Te=null,children:Z,checkoutMode:Ue,confirmLabel:Fe,renderConfirmButton:we,onSessionCompleted:V}){let b=Tl(s),te=pn(()=>Wi(le),[le]),$e=i??te?.appearance,ze=n?"embedded_checkout":"standard_checkout",ae=Z?"custom_layout":M==="buttons"?"buttons_layout":"default_layout",[R,re]=bt(null),[W,ke]=bt(null),dt=Ot(null),[Ge,pt]=bt(null),_=Ot(null),[Y,et]=bt(null),[qe,mt]=bt(e??""),Ne=e??qe,He=n?"":Ne,[Jt,Ye]=bt(!0),[Xt,S]=bt(null),[fe,We]=bt("full"),[Re,vt]=bt(!1),[Ke,je]=bt(Te),[tt,Je]=bt(null),[kn,ot]=bt(null),[jn,Wt]=bt(!1),[mn,Qt]=bt(void 0),[or,Bt]=bt(""),[St,Zt]=bt(!1),[en,Ft]=bt(!1),Dt=Ot(0),[Ct,X]=bt("loading"),[Kn,A]=bt(0),at=Ot(!1),Lt=Ot(!1),Fn=Ot(!1),Me=Ot(null),it=pn(()=>({checkoutMode:Ue??fe,layout:Z?"unknown":M==="buttons"?"buttons":"embedded"}),[Ue,Z,fe,M]),Ve=Ot(N);Ve.current=N;let Rn=Ot(h);Rn.current=h;let In=Ot(E);In.current=E,An(()=>{At(W)?.setCheckoutContext(it),Ge&&Ge!==W&&At(Ge)?.setCheckoutContext(it)},[W,Ge,it]);let Dn=Ot(V);Dn.current=V;let Vn=rr(w=>{X(w),!(w!=="exhausted"||Fn.current)&&(Fn.current=!0,Rn.current?.(new Et("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),En=rr(()=>{X("retrying"),A(w=>w+1)},[]);An(()=>{X("loading"),A(0),Fn.current=!1},[Ne]),An(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Hi,checkout_type:ze,checkout_layout:ae,billing_api_url:b})},[ae,ze,b]);let nt=pn(()=>n?Ut(n,!0):"",[n]),zt=pn(()=>or===nt?mn:void 0,[mn,or,nt]),sn=pn(()=>n?Wo(n,zt):void 0,[n,zt]),gt=Ue??sn?.checkoutMode??"full",xt=pn(()=>sn?{...sn,checkoutMode:gt}:void 0,[sn,gt]);An(()=>{Qt(void 0),Bt(nt)},[nt]),An(()=>{je(Te)},[Te]);let tn=rr((w,D,I)=>{ut(()=>{In.current?.(It(w,D,I))})},[ut]),ln=rr(async(w,D)=>{je(null),ot(null),Wt(!1),Je("processing");let I=D?.sessionId??w.id,ge=dt.current??_.current,Pe=At(ge),m=ge?null:Io(b,a,it),r={log:p=>{Pe?Pe.log(p):m?.log(p)},error:p=>{Pe?Pe.error(p):m?.error(p)},terminal:p=>{Pe?Pe.terminal(p):m?.terminal(p)},performance:p=>{Pe?Pe.performance(p):m?.performance(p)},now:()=>Pe?.now()??m?.now()??0,elapsed:p=>Pe?.elapsed(p)??Math.max(0,(m?.now()??p)-p)},y=r.now(),x=!!(D?.initialAutoProcessingError||D?.initialAutoProcessingPending),f=!1,O,Ae=()=>{f||(f=!0,x=!0,O=r.now(),r.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Xe=!1,G=()=>{Xe||(Xe=!0,r.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),r.performance({stage:"processing",durationMs:r.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}),O!==void 0&&r.performance({stage:"recovery",durationMs:r.elapsed(O),durationMode:"machine",paymentMethodCategory:"saved"}))};r.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),r.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),x&&Ae();let U;try{let p=Li(D?.initialAutoProcessingError),L;if(p)Ae(),p.type==="paypal_redirect_required"&&Me.current?.publishableKey&&ji({sessionId:I,publishableKey:Me.current.publishableKey,paypalPublishableKey:Me.current.paypalPublishableKey}),L=await Co(p,{flopay:dt.current,paypalFlopay:_.current,attempt3DS:D?.attempt3DS,billingApiUrl:b,sessionId:I,session:w,telemetry:!1}),p.type==="paypal_redirect_required"&&ya();else if(D?.initialAutoProcessingPending){let Ee=(await new ko(b,{telemetry:!1}).waitForCheckoutSessionCompletion(D.initialAutoProcessingPending.sessionId,{initialDelayMs:D.initialAutoProcessingPending.retryAfterMs})).data.session;if(!pr(Ee))throw po(Ee);L=Qn(Ee,I)}else{if(D?.initialAutoProcessingError)throw $n(D.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:D.initialAutoProcessingError.checkoutMethod});if(D?.fromCreateSession)return D?.fallbackToFull&&(We("full"),Vi("full")),!1;{let ue=await Pr({billingApiUrl:b,sessionId:I,session:w,telemetry:!1});ue.type==="success"?L=ue.result:(Ae(),ue.type==="paypal_redirect_required"&&Me.current?.publishableKey&&ji({sessionId:I,publishableKey:Me.current.publishableKey,paypalPublishableKey:Me.current.paypalPublishableKey}),L=await Co(ue,{flopay:dt.current,paypalFlopay:_.current,attempt3DS:D?.attempt3DS,billingApiUrl:b,sessionId:I,session:w,telemetry:!1}),ue.type==="paypal_redirect_required"&&ya())}}I&&mr(I),G(),x&&(r.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),r.terminal({outcome:L.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Wt(L.status==="authorized"),Je("success"),await Hr(_n),U=()=>Ve.current?.(L)}catch(p){let L=nr(p),ue=L.checkoutMethod??Vr;je(L.message),ot(L.message),Wt(!1),D?.fallbackToFull&&(r.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),We("full"),Vi("full")),G();let Se=L.statusCode!==void 0?Al(L.statusCode,"unknown"):void 0,Ee=Se==="4xx"?{requestCategory:"process_payment",statusClass:Se}:{},fn=Se===void 0||Se==="4xx";if(fn&&(L.telemetryOutcome==="payment_declined"||!!(L.declineCode||L.code?.toLowerCase().includes("declin"))))r.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ee});else if(fn&&(L.telemetryOutcome==="validation_rejected"||L.type==="validation_error"))r.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ee});else{let Jr=Oi(p,x?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");r.error({...Jr,...L.telemetryFailureCategory?{failureCategory:L.telemetryFailureCategory}:{},stage:x?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:L.telemetryRequestCategory??"process_payment"})}return ut(()=>Rn.current?.(L)),tn(ue,L,{code:L.code,declineCode:L.declineCode}),Je("error"),await Promise.allSettled([Hr(Pn),D?.ensureProvidersReady?D.ensureProvidersReady():Promise.resolve()]),x&&(r.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{G(),m&&Wr(m),Je(null),ot(null)}return ut(U),!0},[tn,ut,nr,b,a,it]);An(()=>{if(typeof window>"u"||Lt.current)return;let w=new URLSearchParams(window.location.search),D=w.get("payment_intent_client_secret");if(!D)return;let I=Dl();I&&(Lt.current=!0,(async()=>{let ge,Pe=0;je(null),ot(null),Je("processing"),vt(!0);try{if(w.get("redirect_status")==="failed")throw Object.assign(new Et("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:m,paypalFlopay:r}=await wo({publishableKey:I.publishableKey,paypalPublishableKey:I.paypalPublishableKey,billingApiUrl:b,locale:u,telemetry:a});ge=At(r??m),Pe=ge?.now()??0,ge?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let y=(r??m)?.getRawProvider();if(!y)throw Object.assign(new Et("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:x,error:f}=await y.retrievePaymentIntent(D);if(f)throw Object.assign(new Et(f.message??"Failed to retrieve PayPal payment status.","api_error",{code:f.code}),{checkoutMethod:"paypal"});let O=si(x?.status);if(!x||O==="failed")throw Object.assign(new Et("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Ae=typeof x.payment_method=="string"?x.payment_method:x.payment_method?.id,Xe=O;if(I.sessionId){let p=(await new ko(b,{telemetry:!1}).getUnifiedCheckoutSession(I.sessionId)).data.session;if(p&&p.status!=="complete"){let L=await Pr({billingApiUrl:b,sessionId:I.sessionId,session:p,telemetry:!1,tokenizedData:{id:Ae??x.id,type:"card",threeDSecureActionResultTokenId:x.id,isPaypal:!0}});if(L.type!=="success")throw Object.assign(new Et("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Xe=L.result.status}}I.sessionId&&mr(I.sessionId),ge?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.performance({stage:"redirect_resume",durationMs:ge.elapsed(Pe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Je("success"),await Hr(_n),ut(()=>Ve.current?.({status:Xe,paymentIntentId:x.id,paymentMethodId:Ae,checkoutMethod:"paypal"}))}catch(m){let r=nr(m),y=r.checkoutMethod??"paypal",x=!!(r.declineCode||r.code?.toLowerCase().includes("declin"));if(ge)ge.performance({stage:"redirect_resume",durationMs:ge.elapsed(Pe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),x?ge.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ge.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(x){let f=Io(b,a,it);f.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Wr(f)}else pa(b,a,it,"REDIRECT_RESUME_FAILED","redirect_resume");je(r.message),ot(r.message),ut(()=>Rn.current?.(r)),tn(y,r,{code:r.code,declineCode:r.declineCode}),Je("error"),await Hr(Pn)}finally{ya(),Ul(),Je(null),ot(null),vt(!1)}})())},[tn,ut,u,nr,b,a]);let Yt=Ot(null);function Ut(w,D=!1){let I=w?.account?.email?.trim().toLowerCase()??"",ge={c:w?.clientId,cur:w?.currency??"",captureMethod:w?.captureMethod??"",a:{e:I,u:I?"":w?.account?.userId??"",country:w?.account?.country??""},successUrl:w?.successUrl,cancelUrl:w?.cancelUrl,p:w?.products?.map(r=>fa(`${r.type??""}:${r.code??r.providerItemId??r.providerPlanId??""}`,r)).sort(),i:w?.items?.map(r=>fa(r.code??r.providerItemId??"",r)).sort(),s:w?.subscriptions?.map(r=>fa(r.code??r.providerPlanId??"",r)).sort(),couponCodes:w?.couponCodes?[...w.couponCodes].sort():void 0,...D?{tagsData:w?.tagsData,utmMetadata:w?.utmMetadata,tokenizedData:w?.tokenizedData,checkoutMode:w?.checkoutMode??"full"}:{}},Pe=JSON.stringify(ge),m=0;for(let r=0;r<Pe.length;r++)m=(m<<5)-m+Pe.charCodeAt(r)|0;return`flopay_session_${Math.abs(m).toString(36)}`}let $t=pn(()=>xt?Ut(xt):"",[xt]),Ie=Ot(xt);Ie.current=xt,An(()=>{mt(e??"")},[e]),An(()=>{at.current=!1,je(Te),ot(null),Wt(!1),Je(null)},[$t,Te,e]);async function qt(w,D){let I=Io(b,a,it),ge=new ko(b,{telemetry:!1}),Pe=!1;try{let m=w.idempotencyKey!==void 0?$i(w.idempotencyKey):void 0,r=m??zl(D),y,x=!1,f=Ll(D);I.log({name:f?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let O=f?.sid??null,Ae=null,Xe;if(O)try{if(Ae=await ge.getUnifiedCheckoutSession(O,f?.nonce),Ae.data.session?.status==="complete"){if(Go(O))return{sid:O,result:Ae};Ol(D),O=null,Ae=null,x=!0}}catch{I.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),ha(D),O=null}if(!O){!m&&(x||!r)&&(r=$i(),y=r),r&&Nl(D,r);let G=I.now(),U=0;I.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let p={...w,idempotencyKey:r,avsCheck:!!xe,avsConfig:typeof xe=="object"?xe:void 0,checkoutType:"embedded_checkout",checkoutLayout:Z?"custom_layout":M==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(p,_l,{configurable:!1,enumerable:!1,value:{onAttempt:Se=>{U=Math.max(U,Se)}}});let L=()=>{I.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),I.performance({stage:"session_create",durationMs:I.now()-G,durationMode:"machine",requestCategory:"session_create",attempt:U,statusClass:"2xx"})},ue=Se=>{let Ee=Oi(Se,"CHECKOUT_SESSION_CREATE_FAILED","unknown");I.performance({stage:"session_create",durationMs:I.now()-G,durationMode:"machine",requestCategory:"session_create",attempt:U,statusClass:Ee.statusClass}),Se instanceof Et&&Se.type==="validation_error"?I.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):Ee.statusClass==="4xx"?I.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):I.error({...Ee,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if(xl(p)){let Se=await ge.createDetachedSession(p);Se.claimed.catch(()=>{}),Ae=Se.shell,O=Se.sessionId,Xe=Se.claimed.then(Ee=>{let fn=Ee.data.session?.id??Se.sessionId;return fn&&Ki(D,fn,Ee.data.session?.clientSecret??Se.nonce),L(),Ee},Ee=>{throw ha(D),ue(Ee),Ee}).finally(()=>Wr(I)),Xe.catch(()=>{}),Pe=!0,I.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),I.performance({stage:"session_shell",durationMs:I.now()-G,durationMode:"machine",requestCategory:"session_create",attempt:U,statusClass:"2xx",paymentMethodCategory:"card"})}else Ae=await ge.createAndFetchSession(p),L()}catch(Se){throw ue(Se),Se}O=Ae.data.session?.id??O??"",O&&!Xe&&Ki(D,O,Ae.data.session?.clientSecret)}return{sid:O??"",result:Ae,sdkGeneratedIdempotencyKey:y,...Xe?{claimed:Xe}:{}}}finally{Pe||Wr(I)}}let yt=rr(async(w,D)=>{let I=Ie.current;if(!I)throw new Et("createSession is required to bootstrap checkout.","validation_error");let ge=Wo(I,w),Pe=Ut(ge),m=Eo.get(Pe);if(!m){let x={promise:qt(ge,Pe),consumers:0,settled:!1};m=x,Eo.set(Pe,x);let f=()=>{x.settled=!0,qi(Pe,x)};x.promise.then(f,f)}m.consumers+=1;let r=!1,y=()=>{r||(r=!0,m.consumers-=1,qi(Pe,m))};D?.(y);try{let x=await m.promise;Yt.current=Pe,w&&(Bt(nt),Qt(L=>oi(L,w)));let{sid:f,result:O,claimed:Ae}=x;if(re(O),O.data.session&&et(O.data.session),f&&mt(f),Ae){let L=Dt.current+=1;Ft(!0),Ae.then(ue=>{Dt.current===L&&(re(ue),ue.data.session&&et(ue.data.session),Ft(!1))},ue=>{Dt.current===L&&(Ft(!1),S(ue instanceof Et?ue:new Et(ue instanceof Error?ue.message:"Failed to create session","api_error")))})}else Dt.current+=1,Ft(!1);let{publishableKey:Xe,paypalPublishableKey:G}=So(O),{flopay:U,paypalFlopay:p}=await wo({publishableKey:Xe,paypalPublishableKey:G,billingApiUrl:b,locale:u,telemetry:a});return dt.current=U,ke(U),_.current=p,pt(p),Ye(!1),x}catch(x){throw Yt.current===Pe&&(Yt.current=null),x}finally{D||y()}},[u,b,a,it]),yn=Ot(ln);yn.current=ln;let Hn=Ot(yt);Hn.current=yt;let jt=rr(async w=>{if(!$l(w)||St)return{sessionId:qe,session:Y};Zt(!0);try{let D=await yt(w);return{sessionId:D.sid,session:D.result.data.session??null}}finally{Zt(!1)}},[yt,St,qe,Y]);An(()=>{let w=!1,D;if(S(null),$t){let Pe=Ie.current;return We(gt),Ye(!1),Yt.current===$t?()=>{w=!0}:(et(ai(Pe,Ue)),(async()=>{let m=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),r=gt==="auto"&&!at.current&&!m;r&&(je(null),ot(null),Je("processing"));try{let y=await Hn.current(void 0,Ae=>{D=Ae}),x=y.result.data.session??null;Me.current=So(y.result);let f=ma(y.result),O=Go(y.sid||x?.id);if(!w&&r&&x&&!f&&!O){at.current=!0,await Bl($t,y.sdkGeneratedIdempotencyKey,()=>yn.current(x,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:y.result.autoProcessingError,initialAutoProcessingPending:y.result.autoProcessingPending,autoProcessingAttempted:y.result.autoProcessingAttempted,sessionId:y.sid||x.id}));return}!w&&r&&((f||O)&&(at.current=!0),Je(null),ot(null))}catch(y){if(w)return;let x=y instanceof Et||typeof y=="object"&&y!==null&&"code"in y?y.code:void 0;if(r&&x==="session_auto_completed"){at.current=!0,Je("success"),await Hr(_n),w||(ut(()=>{Ve.current?.({status:"succeeded"})}),Je(null),ot(null));return}r&&(Je(null),ot(null));let f=y instanceof Et?y:new Et(y instanceof Error?y.message:"Failed to create session","api_error");S(f)}finally{D?.(),D=void 0}})(),()=>{w=!0,D?.()})}Ye(!0);async function I(){let Pe=!1;try{let r=await new ko(b,{telemetry:!1}).getUnifiedCheckoutSession(Ne,t);if(w)return;re(r);let y=r.data.session??null;if(et(y),!y)throw new Et("No session data returned","api_error");let x=y.checkoutMode;if(x==="setup")throw new Et("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(y.status==="authorized"){Ye(!1),ut(()=>{Ve.current?.(Qn(y,Ne)),Dn.current?.(y.successUrl??"")});return}if(y.status==="complete"){Ye(!1),ut(()=>{Dn.current?.(y.successUrl??"")});return}if(y.status==="expired")throw uo(y);Pe=!0;let f=Ue??x??"full";We(f);let O=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ae=ma(r);if(f==="auto"&&!at.current&&!O&&!Ae){at.current=!0;let Xe=ge(r);try{if(await yn.current(y,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Xe,sessionId:Ne||y.id}),w)return;await Xe,w||Ye(!1);return}catch{if(w)return;await Xe,w||Ye(!1);return}}await ge(r),w||Ye(!1)}catch(m){if(w)return;m instanceof Et?!Pe&&!Fl(m)&&pa(b,a,it,"NETWORK_REQUEST_FAILED","session_read"):pa(b,a,it,"INTERNAL_SDK_ERROR","checkout_mount");let r=m instanceof Et?m:new Et(m instanceof Error?m.message:"Failed to initialize checkout","api_error");S(r),Ye(!1)}}async function ge(Pe){let{publishableKey:m,paypalPublishableKey:r}=So(Pe);Me.current={publishableKey:m,paypalPublishableKey:r};let{flopay:y,paypalFlopay:x}=await wo({publishableKey:m,paypalPublishableKey:r,billingApiUrl:b,locale:u,telemetry:a});dt.current=y,ke(y),_.current=x,pt(x)}return I(),()=>{w=!0}},[Ue,$t,gt,He,ut,t]);let Kt=rr(async()=>{if(!(Re||!Y)){vt(!0),je(null);try{await ln(Y,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ne||Y.id})}finally{vt(!1)}}},[Ne,Re,ln,Y]),Nt=ga(R),Ln=ma(R),zn=pn(()=>{if(!R||!Y||!R.data.stripe?.publishableKey)return;let w={appearance:$e,paymentMethodCreation:"manual",billingApiUrl:b};if(R.data.stripe?.clientSecret)w.clientSecret=R.data.stripe.clientSecret;else{let D=Ui(Y).total;w.amount=Math.round(D*100)||Y.amount,w.currency=Y.currency?.toLowerCase()}return w},[R,Y,$e,b]),nn=!!(n&&!Z&&M==="buttons"&&ie&&gt==="full"),Gt=pn(()=>({session:Y,loading:Jt,error:Xt,checkoutMode:fe,inlineSessionDraft:xt,applyInlineSessionPatch:nn?jt:void 0,inlineSessionPatchProcessing:St,claimPending:en}),[Y,Jt,Xt,fe,xt,nn,jt,St,en]),rn=!!n&&M==="buttons"&&!Ln&&(!W||!zn),Oe=tt?ee(bn,{status:tt,errorMessage:kn,authorized:jn}):null;if(Jt){if(l)return _t(wn,{children:[l,Oe]});if(M==="buttons"){let w=te?.buttonsLayout?.cardButton?.borderRadius??te?.appearance.variables?.borderRadius??8,D=I=>ee("div",{style:{height:I,borderRadius:w,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return _t(wn,{children:[_t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[c&&D(br),P&&(T||g)&&D(br),P&&D(br),ee("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Oe]})}return _t(wn,{children:[_t("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ee("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ee("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Oe]})}return Xt?v?ee(un.Provider,{value:Gt,children:v(Xt)}):ee(un.Provider,{value:Gt,children:ee("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Xt.message})}):rn?_t(wn,{children:[ee(un.Provider,{value:Gt,children:ee(jl,{onButtonClick:K,showPayPal:c,showStripe:P,showApplePay:T,showGooglePay:g,theme:le,buttonsTheme:ce,buttonsStyles:z,cardButtonContent:J,cardBackButtonContent:H,cardTitleContent:oe})}),Oe]}):Ln&&Y&&Nt?_t(wn,{children:[ee(un.Provider,{value:Gt,children:_t("div",{className:ye,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ke&&ee(ur,{icon:!1,children:Ke}),Ct==="retrying"&&ee("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ct==="exhausted"&&_t("div",{role:"alert",children:[ee("div",{children:"PayPal is temporarily unavailable. Please try again."}),ee("button",{type:"button",onClick:En,children:"Retry PayPal"})]}),Ct!=="exhausted"&&ee("div",{"aria-hidden":Ct==="retrying"?!0:void 0,style:Ct==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ee(yi,{sessionId:Ne,nonce:Y.clientSecret||void 0,billingApiUrl:b,email:Y.customer?.email,clientId:Nt.clientId,environment:Nt.environment,currency:(Y.currency??"usd").toUpperCase(),isSubscription:Y.mode==="subscription",onComplete:N,onErrorChange:je,onDecline:E,onButtonClick:K,onInitializationStateChange:Vn,allowAutomaticRetry:Kn===0,session:Y,telemetry:a,telemetryContext:it,debug:me},`paypal-init-${Kn}`)})]})}),Oe]}):!W||!zn?ee(wn,{children:Oe}):fe==="confirm"?_t(wn,{children:[ee(un.Provider,{value:Gt,children:ee(lo,{flopay:W,paypalFlopay:Ge,options:zn,children:_t("div",{className:ye,children:[Ke&&ee("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ke}),we?we({onConfirm:Kt,isProcessing:Re}):ee("button",{type:"button",onClick:Kt,disabled:Re,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Re?"not-allowed":"pointer",opacity:Re?.6:1},children:Re?"Processing...":Fe??"Confirm Purchase"})]})})}),Oe]}):_t(wn,{children:[ee(un.Provider,{value:Gt,children:ee(lo,{flopay:W,paypalFlopay:Ge,options:zn,children:Z?_t(wn,{children:[Ke&&ee("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ke}),ee(ql,{sessionId:Ne,nonce:Y?.clientSecret||void 0,billingApiUrl:b,session:Y,children:Z})]}):ee(la,{sessionId:Ne,nonce:Y?.clientSecret||void 0,email:Y?.customer?.email,userId:Y?.customer?.id,firstName:Y?.customer?.firstName,lastName:Y?.customer?.lastName,totalAmount:Y?Math.round(Ui(Y).total*100):0,currency:Y?.currency?.toLowerCase()??"usd",onComplete:N,onError:h,onDecline:E,error:Ke,onErrorChange:je,showPayPal:c,showStripe:P,enabledPaymentMethods:k??R?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:R?.data.stripe?.enabledPaymentMethodCountries,showApplePay:T,showGooglePay:g,layout:M,theme:le,buttonsTheme:ce,buttonsStyles:z,appearance:$e,cardButtonContent:J,cardBackButtonContent:H,cardTitleContent:oe,onButtonClick:K,onBeforeButtonClick:ie,enableAVS:xe,...he?{cardFieldOrder:he}:{},...de?{cardPreFormSlot:de}:{},avsLayout:Q,country:Y?.customer?.country,city:Y?.customer?.city,state:Y?.customer?.state,onCountryChange:C,onZipChange:F,avsCheck:!!xe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Z?"custom_layout":M==="buttons"?"buttons_layout":"default_layout",className:ye,directPaypal:ga(R),isSubscription:Y?.mode==="subscription",session:Y,dataAttachmentPending:en,debug:me})})}),Oe]})}function ql({sessionId:e,nonce:t,billingApiUrl:n,session:s,children:a}){return ee(wn,{children:ua.Children.map(a,i=>{if(!ua.isValidElement(i))return i;let u=i.props,l={};return u.sessionId||(l.sessionId=e),!u.nonce&&t&&(l.nonce=t),u.billingApiUrl||(l.billingApiUrl=n),s?.customer&&(u.email||(l.email=s.customer.email),u.userId||(l.userId=s.customer.id),u.firstName||(l.firstName=s.customer.firstName),u.lastName||(l.lastName=s.customer.lastName)),Object.keys(l).length===0?i:ua.cloneElement(i,l)})})}function jl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:s,showGooglePay:a,theme:i,buttonsTheme:u,buttonsStyles:l,cardButtonContent:v,cardBackButtonContent:N,cardTitleContent:h}){let[E,C]=bt(!1),F=pn(()=>Wi(i),[i]),c=pn(()=>{let g=F?.buttonsLayout??Ml(u);return l?{...g,...l,cardButton:{...g.cardButton,...l.cardButton},cardFormContainer:{...g.cardFormContainer,...l.cardFormContainer},backButton:{...g.backButton,...l.backButton},backButtonIcon:{...g.backButtonIcon,...l.backButtonIcon},submitButton:{...g.submitButton,...l.submitButton},title:{...g.title,...l.title}}:g},[F,u,l]),P=F?.buttonsLayout?.cardButton?.borderRadius??F?.appearance.variables?.borderRadius??8,k=g=>ee("div",{style:{height:g,borderRadius:P,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),T=v===void 0?{boxSizing:"border-box",height:br,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(E){let g=c.cardInputBorder??"#e5e7eb",me=c.cardInputBackground??"white",M=sr(N),le=sr(h);return _t("div",{style:{backgroundColor:c.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...c.cardFormContainer},children:[_t("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[_t("button",{type:"button",onClick:()=>C(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:M?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...c.backButton},children:[ee("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...c.backButtonIcon},children:ee("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:ee("path",{d:"M15 18l-6-6 6-6"})})}),ee(cr,{content:N})]}),le?ee("div",{style:{flex:1}}):ee("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...c.title},children:ee(Nr,{content:h})})]}),ee("div",{style:{backgroundColor:me,border:`1px solid ${g}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ee("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),_t("div",{style:{display:"flex"},children:[ee("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomLeftRadius:8,padding:12,height:45},children:ee("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ee("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:`1px solid ${g}`,borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomRightRadius:8,padding:12,height:45},children:ee("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ee("div",{style:{backgroundColor:me,border:`1px solid ${g}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ee("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ee("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...c.submitButton,opacity:.5}}),ee("style",{children:`
33
+ `}),Br&&ir&&ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ve?-2:0},children:[ze("button",{type:"button",onClick:dn,style:{display:"inline-flex",alignItems:"center",gap:zo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:o.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...o.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...o.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(ur,{content:f})]}),qa?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:o.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...o.title},children:d(Nr,{content:ae})})]}),!Br&&!qa&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:No,order:Ve?-3:0,...o.title},children:d(Nr,{content:ae})}),X&&d("div",{style:{order:Ve?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=Je,M=(U=!1)=>({backgroundColor:Dr,border:`1px solid ${Wn(U)}`,borderRadius:ht,marginTop:"0.5rem",padding:"10px"}),$=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ya}),re=Ws(r);return ze(Pr,{children:[Oe(X.address_line_1,r)&&d("div",{style:M(Ct.line1),children:d("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:Te,onChange:U=>{Bt.current.addressLine1=!0,ln.current=U.target.value,ft(U.target.value)},disabled:V,required:!0,"data-testid":"flopay-address-line1",style:$()})}),Oe(X.address_line_2,r)&&d("div",{style:M(),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Ie,onChange:U=>{Bt.current.addressLine2=!0,qt.current=U.target.value,tn(U.target.value)},disabled:V,"data-testid":"flopay-address-line2",style:$()})}),(Oe(X.city,r)||Oe(X.state,r))&&ze("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Oe(X.city,r)&&d("div",{style:{flex:1,backgroundColor:Dr,borderTop:`1px solid ${Wn(Ct.city)}`,borderRight:`1px solid ${Wn(Ct.city)}`,borderBottom:`1px solid ${Wn(Ct.city)}`,borderLeft:`1px solid ${Wn(Ct.city)}`,padding:"10px",borderTopLeftRadius:ht,borderBottomLeftRadius:ht,...Oe(X.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:ht}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Ke,onChange:U=>{Bt.current.city=!0,Kt.current=U.target.value,Dn(U.target.value)},disabled:V,required:!0,"data-testid":"flopay-city",style:$()})}),Oe(X.state,r)&&d("div",{style:{flex:1,backgroundColor:Dr,border:`1px solid ${Wn(Ct.state)}`,padding:"10px",borderTopRightRadius:ht,borderBottomRightRadius:ht,...Oe(X.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:ht}},children:re?ze("select",{id:"flopay-billing-state",name:"billing-state",value:Jt,onChange:U=>{Bt.current.state=!0,Vt.current=U.target.value,fn(U.target.value)},disabled:V,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...$(),cursor:"pointer"},children:[d("option",{value:"",children:gi(r)}),re.map(U=>d("option",{value:U.code,children:U.name},U.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:gi(r),autoComplete:"billing address-level1",value:Jt,onChange:U=>{Bt.current.state=!0,Vt.current=U.target.value,fn(U.target.value)},disabled:V,required:!0,"data-testid":"flopay-state",style:$()})})]}),(Oe(X.country,r)||Oe(X.postal_code,r))&&ze("div",{style:{display:"flex",flexDirection:se==="column"?"column":"row",gap:se==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Oe(X.country,r)&&d("div",{style:{flex:se==="row"?1:void 0,backgroundColor:Dr,borderTop:`1px solid ${Fr}`,borderRight:`1px solid ${Fr}`,borderBottom:`1px solid ${Fr}`,borderLeft:`1px solid ${Fr}`,padding:"10px",...se==="row"&&Oe(X.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:ht,borderBottomLeftRadius:ht,borderRight:"none"}:{borderRadius:ht}},children:d("select",{id:"flopay-billing-country",name:"billing-country",value:Je,onChange:U=>{Bt.current.country=!0,dt.current=U.target.value,Xe(U.target.value),We?.(U.target.value),Vt.current="",fn("")},disabled:V,autoComplete:"billing country","data-testid":"flopay-country",style:{...$(),cursor:"pointer"},children:Gs.map(U=>ze("option",{value:U.code,children:[U.flag," ",U.name]},U.code))})}),Oe(X.postal_code,r)&&d("div",{style:{flex:se==="row"?1:void 0,backgroundColor:Dr,border:`1px solid ${us}`,padding:"10px",...se==="row"&&Oe(X.country,r)?{borderRadius:"0",borderTopRightRadius:ht,borderBottomRightRadius:ht}:{borderRadius:ht}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:ra(Je),autoComplete:"billing postal-code",value:xt,onChange:U=>{Bt.current.zip=!0,jt.current=U.target.value,yt(U.target.value),Le?.(U.target.value)},onBlur:()=>Qt(!0),disabled:V,required:Ht.required,"aria-invalid":oo||void 0,"aria-describedby":oo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:$()})})]}),oo&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Lo,...Ya,fontSize:"0.75rem"},children:Ht.empty?`${ra(r)} is required`:fl(r)})]})})()}),Ve&&De&&d("div",{style:{order:-2,width:"100%"},children:De}),Ve&&gs,O&&d(mr,{margin:"0.75rem 0",styleOverride:o.errorBanner,children:O})]}),ao={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"},Ga=r=>tt?!w||!Cn?d("pre",{"data-testid":r,style:ao,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":r,style:ao,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${w}`,` directPaypalConfigured=${Cn}`,` inAppBrowserDetected=${String(no)}`,` shouldRenderDirectPayPal=${xr}`,` shouldRenderStripePayPal=${Tr}`,` hasPaypalStripeInstance=${!!T}`].join(`
34
+ `)}):null,Ja=r=>tt?!I||!C?d("pre",{"data-testid":r,style:ao,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":r,style:ao,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${I}`,` currency=${de}`,` amountInCents=${ne}`,` enabledPaymentMethods: ${JSON.stringify(y??[])}`,` enabledPaymentMethodsProvided=${Er}`,` hasEnabledMethods=${Qr}`,` expressMethods: ${JSON.stringify(Zr)}`,` walletExpressMethods: ${JSON.stringify(eo)}`,` paymentElementMethods: ${JSON.stringify(_r)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(to)}`,` hasStripeInstance=${!!C}`,` shouldRenderWallets=${Mr}`,` shouldRenderPaymentElement=${Ar}`].join(`
35
+ `)}):null,Xa=Se==="apm-expanding"||Se==="apm-form"||Se==="apm-collapsing",io=Se==="apm-expanding"?`flopay-card-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:Se==="apm-collapsing"?`flopay-card-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,so=gt?{...Mo,paymentMethodTypes:[gt]}:null;if(be==="buttons"){let r=Se==="buttons"||Se==="expanding"||Se==="apm-expanding",M=Se==="expanding"||Se==="card"||Se==="collapsing",$=Ne===void 0?{boxSizing:"border-box",height:bo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},re=Se==="expanding"||Se==="apm-expanding"?`flopay-buttons-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Se==="collapsing"||Se==="apm-collapsing"?`flopay-buttons-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,U=Se==="expanding"?`flopay-card-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:Se==="collapsing"?`flopay-card-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return ze("form",{onSubmit:Fo,className:v,style:{position:"relative"},children:[d(na,{}),bn&&d(wn,{status:bn,errorMessage:O,authorized:nn}),ze("div",{style:{display:"grid"},children:[ze("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!re?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!re?pl:{},...re?{animation:re,pointerEvents:"none"}:{}},children:[Ga("flopay-direct-paypal-gate-debug"),Ja("flopay-stripe-gate-debug"),xr&&$e&&ze(Pr,{children:[fe&&d("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."}),d(Po,{sessionId:e,nonce:t,billingApiUrl:m,email:x.email,clientId:$e.clientId,environment:$e.environment,currency:de.toUpperCase(),isSubscription:it,providerObjectType:$e.providerObjectType,onTokenizedBody:an,onComplete:i,onErrorChange:me,onDecline:l,onTechnicalFailure:sr,onButtonClick:ve,runBeforeButtonClick:pn,isProcessing:V,onLoadStateChange:Ao,onInitializationStateChange:Bo,session:ue??null,existingOrderId:fe?.orderId,debug:tt},fe?.orderId??"fresh")]}),Tr&&d(nr,{stripe:T,options:ka,children:d(Ri,{sessionId:e,nonce:t,email:x.email,billingApiUrl:m,onTokenizedBody:an,onErrorChange:me,isProcessing:V,onButtonClick:ve,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:pn,onLoadStateChange:_a,placeholderBorderRadius:Gn})}),Mr?d(nr,{stripe:C,options:Xr,children:d(Ii,{sessionId:e,nonce:t,email:x.email,billingApiUrl:m,intentKind:K>0?"payment":"setup",expressMethods:eo,onTokenizedBody:an,onErrorChange:me,onButtonClick:ve,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:pn,onLoadStateChange:Ta,placeholderBorderRadius:Gn})}):Da?d("div",{style:{height:bo,borderRadius:Gn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Ar&&d(Ei,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:m,paymentElementMethods:to,stripeInstance:C,paymentElementBaseOptions:Mo,onTokenizedBody:an,onErrorChange:me,onButtonClick:ve,onDecline:l,runBeforeButtonClick:pn,onLoadStateChange:Aa,isProcessing:V,submitButtonColor:Jn,submitButtonBorderRadius:ht,submitButtonStyle:o.submitButton,onExpandApm:Un,expandedApmMethod:gt,themeId:j,buttonAppearance:{backgroundColor:o.cardButton?.backgroundColor,borderColor:o.cardInputBorder,textColor:o.cardButton?.color,borderRadius:Gn}}),Ve&&d("button",{type:"button",onClick:async()=>{V||!(await pn("card")).proceed||(ve?.("card"),Yn())},disabled:V,style:{width:"100%",...$,...o.cardButton,...la({themeBundle:c,resolvedPrimaryColor:Jn,resolvedBorderRadius:ht,submitButtonStyle:o.submitButton,explicitPrimaryColor:Wt?.colorPrimary}),fontSize:o.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:V?"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:V?.6:1},onMouseEnter:we=>{!V&&(c||Wt?.colorPrimary)&&(we.currentTarget.style.backgroundColor=ys)},onMouseLeave:we=>{(c||Wt?.colorPrimary)&&(we.currentTarget.style.backgroundColor=Jn)},onMouseDown:we=>{we.currentTarget.style.transform="scale(0.985)"},onMouseUp:we=>{we.currentTarget.style.transform="scale(1)"},children:d(dr,{content:Ne})}),O&&Se==="buttons"&&d(mr,{margin:"0.25rem 0",styleOverride:o.errorBanner,children:O})]}),Ve&&M&&d("div",{style:{gridArea:"1 / 1",...U?{animation:U}:{},...Se==="collapsing"?{pointerEvents:"none"}:{}},children:Wa}),I&&Xa&&gt&&so&&C&&d("div",{style:{gridArea:"1 / 1",...io?{animation:io}:{},...Se==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:Oo,borderRadius:$o,...Lr,padding:Uo},children:[ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ze("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:zt,style:{display:"inline-flex",alignItems:"center",gap:zo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:o.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...o.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...o.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(ur,{content:f})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:o.titleFontSize??"1.05rem",color:No,paddingRight:80,...o.title},children:`Pay with ${br(gt)}`})]}),d(nr,{stripe:C,options:so,children:d(oa,{method:gt,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:m,onTokenizedBody:an,onErrorChange:me,onDecline:l,onCancel:zt,runBeforeButtonClick:pn,onButtonClick:ve,isProcessing:V,submitButtonColor:Jn,submitButtonBorderRadius:ht,submitButtonStyle:o.submitButton,errorText:O})},gt)]})})]})]})}return Xa&&gt&&so&&C&&I?ze("form",{onSubmit:Fo,className:v,style:{position:"relative"},children:[d(na,{}),bn&&d(wn,{status:bn,errorMessage:O,authorized:nn}),d("div",{style:{...io?{animation:io}:{},...Se==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:Oo,borderRadius:$o,...Lr,padding:Uo},children:[ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ze("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:zt,style:{display:"inline-flex",alignItems:"center",gap:zo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:o.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...o.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...o.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(ur,{content:f})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:o.titleFontSize??"1.05rem",color:No,paddingRight:80,...o.title},children:`Pay with ${br(gt)}`})]}),d(nr,{stripe:C,options:so,children:d(oa,{method:gt,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:m,onTokenizedBody:an,onErrorChange:me,onDecline:l,onCancel:zt,runBeforeButtonClick:pn,onButtonClick:ve,isProcessing:V,submitButtonColor:Jn,submitButtonBorderRadius:ht,submitButtonStyle:o.submitButton,errorText:O})},gt)]})})]}):ze("form",{onSubmit:Fo,className:v,style:{position:"relative"},children:[d(na,{}),bn&&d(wn,{status:bn,errorMessage:O,authorized:nn}),ze("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ga("flopay-direct-paypal-gate-debug-default"),Ja("flopay-stripe-gate-debug-default"),xr&&$e&&ze(Pr,{children:[fe&&d("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."}),d(Po,{sessionId:e,nonce:t,billingApiUrl:m,email:x.email,clientId:$e.clientId,environment:$e.environment,currency:de.toUpperCase(),isSubscription:it,providerObjectType:$e.providerObjectType,onTokenizedBody:an,onComplete:i,onErrorChange:me,onDecline:l,onTechnicalFailure:sr,onButtonClick:ve,runBeforeButtonClick:pn,isProcessing:V,onLoadStateChange:Ao,onInitializationStateChange:Bo,session:ue??null,existingOrderId:fe?.orderId,debug:tt},fe?.orderId??"fresh")]}),Tr&&d(nr,{stripe:T,options:ka,children:d(Ri,{sessionId:e,nonce:t,email:x.email,billingApiUrl:m,onTokenizedBody:an,onErrorChange:me,isProcessing:V,onButtonClick:ve,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:pn,onLoadStateChange:_a,placeholderBorderRadius:Gn})}),Mr&&d(nr,{stripe:C,options:Xr,children:d(Ii,{sessionId:e,nonce:t,email:x.email,billingApiUrl:m,intentKind:K>0?"payment":"setup",expressMethods:eo,onTokenizedBody:an,onErrorChange:me,onButtonClick:ve,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:pn,onLoadStateChange:Ta,placeholderBorderRadius:Gn})}),Ar&&d(Ei,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:m,paymentElementMethods:to,stripeInstance:C,paymentElementBaseOptions:Mo,onTokenizedBody:an,onErrorChange:me,onButtonClick:ve,onDecline:l,runBeforeButtonClick:pn,onLoadStateChange:Aa,isProcessing:V,submitButtonColor:Jn,submitButtonBorderRadius:ht,submitButtonStyle:o.submitButton,themeId:j,onExpandApm:Un,expandedApmMethod:gt,buttonAppearance:{backgroundColor:o.cardButton?.backgroundColor,borderColor:o.cardInputBorder,textColor:o.cardButton?.color,borderRadius:Gn}})]}),Ve&&(ss||is||ls)&&ze("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),d("span",{children:"or pay with card"}),d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ve&&Wa]})}import{loadFloPay as Fi,PaymentAPI as Li}from"@flopay/js";import{classifyPaymentRejection as vl,FloPayError as rt,isAuthorizationOnlySession as Cl,isSetupIntentClientSecret as Sl,normalizeCheckoutFailureOutcome as Di}from"@flopay/shared";var Hr="card";async function wl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:p}=await e.retrieveSetupIntent(t);return{error:p,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:s,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:s??null}}async function kl(e,t,n,s){if(s){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:p,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:p??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function ua(e,t){return Object.assign(e,{checkoutMethod:t})}function An(e,t){let n=e instanceof rt?e:new rt(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 Vr(e,t){try{return await e()}catch(n){throw An(n,t)}}function Oi(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 Rl(e){return e.status==="succeeded"||e.status==="declined"}async function zi(e){if(typeof document>"u"||typeof window>"u")throw new rt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,s=15e3,a=`${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 v=window.setTimeout(()=>g.abort(),s);try{let A=await fetch(a,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!A.ok)return{status:"unknown"};let u=await A.json().catch(()=>null);return Il(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(v),e.signal?.removeEventListener("abort",R)}},p=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let 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,l.appendChild(b),document.body.appendChild(l),b.focus();let z=null;try{z=new URL(e.billingApiUrl,window.location.href).origin}catch{z=null}try{let g=await new Promise((R,v)=>{let A=!1,u=0,h=0,w=0,I=!1,y=()=>{window.clearTimeout(u),window.clearInterval(h),window.clearTimeout(w),window.removeEventListener("message",be),b.removeEventListener("load",F),e.signal?.removeEventListener("abort",te)},he=async()=>{if(!(A||I)){I=!0;try{let j=await i();if(A||!Rl(j))return;A=!0,y(),R(j)}finally{I=!1}}},F=()=>{window.clearTimeout(w),w=window.setTimeout(()=>{he()},250)},te=()=>{A||(A=!0,y(),v(new rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},be=j=>{if(j.source!==b.contentWindow||z&&j.origin!==z)return;let q=j.data;!q||typeof q!="object"||q.source!=="flopay-vault-3ds-return"||A||(A=!0,y(),R(null))};u=window.setTimeout(()=>{A||(A=!0,y(),v(new rt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),h=window.setInterval(()=>{he()},n),b.addEventListener("load",F),window.addEventListener("message",be),e.signal?.addEventListener("abort",te),e.signal?.aborted&&te()});return g||await i()}finally{l.parentNode?.removeChild(l),p?.isConnected&&p.focus()}}function Il(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 s=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=$n(a)??a;return ua(new rt(i,"api_error",{code:Di(e?.outcome)??Di(e?.type)??e?.gatewayErrorCode}),s)}function da(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Co(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function El(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function Ni(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Co(a)))return a;let s=e?.data;if(s&&typeof s=="object"){let a=s,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||Co(l)))return l;let p=a.gateways;if(p&&typeof p=="object"){let l=p.stripe;if(l&&typeof l=="object"){let b=l,z=[b.stripeClientSecret,b.clientSecret];for(let g of z)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||Co(g)))return g}}}}async function _l({billingApiUrl:e,sessionId:t,nonce:n,responseJson:s}){let a=Ni(s,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let l=(await new Li(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Co(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function vr({billingApiUrl:e,sessionId:t,session:n,nonce:s,tokenizedData:a,returnUrl:i,telemetry:p}){let l=e.replace(/\/+$/,""),b=t??n.id,z=s??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",R=n.customer?.email??n.accountData?.email??"",v=n.customer?.firstName??n.accountData?.firstName??"",A=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,h=n.customer?.zip??n.accountData?.zip??void 0,w=new Li(l,p===!1?{telemetry:!1}:void 0),I=await El(()=>w.processPayment(g,{sessionId:b,nonce:z,tokenizedData:a,accountData:{userId:g,email:R,firstName:v,lastName:A,country:u,zip:h},returnUrl:i??da(n)}));if(I.ok){let F=typeof I.json=="function"?await I.json().catch(()=>null):null;return Cl(n)||F?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof F?.paymentId=="string"?F.paymentId:n.paymentId,sessionId:typeof F?.sessionId=="string"?F.sessionId:b,authorizationExpiresAt:typeof F?.authorizationExpiresAt=="string"?F.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:$r(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:a?.threeDSecureActionResultTokenId,paymentMethodId:$r(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}}let y;try{y=await I.json()}catch{throw new rt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:I.status})}if(y?.type==="paypal_redirect_required"||y?.type==="3ds_required"){let F=Ni(y);if(!F)throw new rt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:I.status});return{type:y.type,threeDSecureToken:F,paymentMethodId:y.paymentMethodId}}if(y?.gatewayErrorCode==="authentication_required"){let F=await _l({billingApiUrl:l,sessionId:b,nonce:z,responseJson:y});if(F)return F;throw ua(new rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let he=new rt(y?.message??"Payment failed. Please try again.","api_error",{code:y?.code??y?.gatewayErrorCode,declineCode:y?.declineCode??y?.gatewayDeclineReason,statusCode:I.status});throw Object.assign(he,{telemetryOutcome:vl(I.status,y)})}async function So(e,{flopay:t,paypalFlopay:n,attempt3DS:s,billingApiUrl:a,sessionId:i,session:p,returnUrl:l,telemetry:b}){let z=t?.getRawProvider();if(!z)throw An(new rt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!s||!e.threeDSecureToken)throw ua(new rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Sl(e.threeDSecureToken),R=null,v=e.paymentMethodId,A=await Vr(()=>wl(z,e.threeDSecureToken,g),"card");if(A){if(A.error)throw An(new rt(A.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:A.error.code}),"card");let h=A.intent;!v&&h?.payment_method&&(typeof h.payment_method=="string"?v=h.payment_method:"id"in h.payment_method&&(v=h.payment_method.id??void 0))}let u=v?await Vr(()=>kl(z,e.threeDSecureToken,{payment_method:v,return_url:l??da(p)??window.location.href},g),"card"):null;if(u){if(u.error)throw An(new rt(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");R=u.intent}else{let h=await Vr(()=>z.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(h.error)throw An(new rt(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 vr({billingApiUrl:a,sessionId:i,session:p,telemetry:b,tokenizedData:{id:R.id,type:"card",threeDSecureActionResultTokenId:R.id},returnUrl:l});return h.type==="success"?{...h.result,paymentIntentId:h.result.paymentIntentId??R.id,paymentMethodId:h.result.paymentMethodId??v}:So(h,{flopay:t,paypalFlopay:n,attempt3DS:s,billingApiUrl:a,sessionId:i,session:p,returnUrl:l,telemetry:b})}throw An(new rt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw An(new rt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:v}=await Vr(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(v)throw An(new rt(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:R}=await Vr(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??da(p)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(R)throw An(new rt(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new rt("Unsupported payment redirect state.","api_error")}function rr(e){if(e instanceof rt){let s=$n(e.message);return s&&s!==e.message?Object.assign(new rt(s,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=$n(t)??t;return new rt(n,"api_error")}function wo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new rt("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function ko({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:s,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[p,l]=await Promise.all([Fi(e,{billingApiUrl:n,locale:s,telemetry:a}),i?Fi(t,{billingApiUrl:n,locale:s,telemetry:a}).catch(b=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",b),null)):Promise.resolve(null)]);return{flopay:p,paypalFlopay:t?i?l:p:null}}import{Fragment as En,jsx as ee,jsxs as _t}from"react/jsx-runtime";var Cr=44,ba="flopay_checkout_saved_payment_resume",_o=new Map,Io=new Map;function qi(e,t){t.settled&&t.consumers===0&&_o.get(e)===t&&_o.delete(e)}function Fl(e,t,n){let s=Io.get(e);if(s&&(!s.sdkGeneratedIdempotencyKey||!t||s.sdkGeneratedIdempotencyKey===t))return s.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};Io.set(e,i);let p=()=>{Io.get(e)===i&&Io.delete(e)};return a.then(p,p),a}function Yr(e){return new Promise(t=>setTimeout(t,e))}function Eo(e,t,n){let s=lo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Yi,enabled:t!==!1});return s.beginCheckout(n),s}function Wr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ma(e,t,n,s,a){let i=Eo(e,t,n);i.error({errorCode:s,stage:a,paymentMethodCategory:"unknown",...a==="session_read"?{requestCategory:"session_read"}:{}}),Wr(i)}function Dl(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 ha(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:!!ha(e)?.clientId}function Fn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Ll(){if(!Fn())return null;try{let e=window.sessionStorage.getItem(ba);return e?JSON.parse(e):null}catch{return null}}function Ki(e){if(Fn())try{window.sessionStorage.setItem(ba,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function fa(){if(Fn())try{window.sessionStorage.removeItem(ba)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var va=":idempotency-key";function Ol(e){if(!Fn())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function Vi(e,t,n){if(Fn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(s){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",s)}}function Pa(e){if(Fn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function zl(e){if(Fn())try{return window.sessionStorage.getItem(e+va)??void 0}catch{return}}function Nl(e,t){if(Fn())try{window.sessionStorage.setItem(e+va,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function Ul(e){if(Pa(e),!!Fn())try{window.sessionStorage.removeItem(e+va)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function $l(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let s of t)e.searchParams.has(s)&&(e.searchParams.delete(s),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Hi(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function jl(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function ga(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Ca({sessionId:e,nonce:t,createSession:n,billingApiUrl:s,telemetry:a,appearance:i,locale:p,loading:l,error:b,onComplete:z,onError:g,onDecline:R,onCountryChange:v,onZipChange:A,showPayPal:u=!0,showStripe:h=!0,enabledPaymentMethods:w,showApplePay:I=!0,showGooglePay:y=!0,debug:he=!1,layout:F,theme:te,buttonsTheme:be,buttonsStyles:j,cardButtonContent:q,cardBackButtonContent:oe,cardTitleContent:ie,showSecurityFooter:Ne,onButtonClick:f,onBeforeButtonClick:ae,enableAVS:Fe,cardFieldOrder:ve,cardPreFormSlot:Re,avsLayout:J,className:le,initialErrorMessage:De=null,children:se,checkoutMode:_e,confirmLabel:Ue,renderConfirmButton:xe,onSessionCompleted:H}){let P=Ml(s),Q=yn(()=>Wi(te),[te]),We=i??Q?.appearance,Le=n?"embedded_checkout":"standard_checkout",Z=se?"custom_layout":F==="buttons"?"buttons_layout":"default_layout",[_,ce]=bt(null),[K,de]=bt(null),et=Ut(null),[$e,it]=bt(null),ue=Ut(null),[G,tt]=bt(null),[Y,mt]=bt(e??""),je=e??Y,qe=n?"":je,[$t,nt]=bt(!0),[en,S]=bt(null),[pe,Je]=bt("full"),[Xe,xt]=bt(!1),[yt,Te]=bt(De),[ft,Ie]=bt(null),[tn,Ke]=bt(null),[Dn,Jt]=bt(!1),[fn,Ln]=bt(void 0),[On,jt]=bt(""),[dt,ln]=bt(!1),[qt,Kt]=bt(!1),Vt=Ut(0),[Bt,X]=bt("loading"),[zn,nn]=bt(0),Xt=Ut(!1),Hn=Ut(!1),B=Ut(!1),ot=Ut(null),He=yn(()=>({checkoutMode:_e??pe,layout:se?"unknown":F==="buttons"?"buttons":"embedded"}),[_e,se,pe,F]),Ve=Ut(z);Ve.current=z;let Ye=Ut(g);Ye.current=g;let _n=Ut(R);_n.current=R,Bn(()=>{At(K)?.setCheckoutContext(He),$e&&$e!==K&&At($e)?.setCheckoutContext(He)},[K,$e,He]);let Nn=Ut(H);Nn.current=H;let ar=or(k=>{X(k),!(k!=="exhausted"||B.current)&&(B.current=!0,Ye.current?.(new Et("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),gn=or(()=>{X("retrying"),nn(k=>k+1)},[]);Bn(()=>{X("loading"),nn(0),B.current=!1},[je]),Bn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Yi,checkout_type:Le,checkout_layout:Z,billing_api_url:P})},[Z,Le,P]);let at=yn(()=>n?Zt(n,!0):"",[n]),Ht=yn(()=>On===at?fn:void 0,[fn,On,at]),hn=yn(()=>n?Yo(n,Ht):void 0,[n,Ht]),Ct=_e??hn?.checkoutMode??"full",Lt=yn(()=>hn?{...hn,checkoutMode:Ct}:void 0,[hn,Ct]);Bn(()=>{Ln(void 0),jt(at)},[at]),Bn(()=>{Te(De)},[De]);let cn=or((k,D,L)=>{ut(()=>{_n.current?.(It(k,D,L))})},[ut]),rn=or(async(k,D)=>{Te(null),Ke(null),Jt(!1),Ie("processing");let L=D?.sessionId??k.id,fe=et.current??ue.current,Ce=At(fe),W=fe?null:Eo(P,a,He),m={log:x=>{Ce?Ce.log(x):W?.log(x)},error:x=>{Ce?Ce.error(x):W?.error(x)},terminal:x=>{Ce?Ce.terminal(x):W?.terminal(x)},performance:x=>{Ce?Ce.performance(x):W?.performance(x)},now:()=>Ce?.now()??W?.now()??0,elapsed:x=>Ce?.elapsed(x)??Math.max(0,(W?.now()??x)-x)},O=m.now(),c=!!(D?.initialAutoProcessingError||D?.initialAutoProcessingPending),o=!1,E,ye=()=>{o||(o=!0,c=!0,E=m.now(),m.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),m.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Pe=!1,V=()=>{Pe||(Pe=!0,m.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),m.performance({stage:"processing",durationMs:m.elapsed(O),durationMode:"machine",paymentMethodCategory:"saved"}),E!==void 0&&m.performance({stage:"recovery",durationMs:m.elapsed(E),durationMode:"machine",paymentMethodCategory:"saved"}))};m.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),m.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),c&&ye();let Ge;try{let x=Oi(D?.initialAutoProcessingError),N;if(x)ye(),x.type==="paypal_redirect_required"&&ot.current?.publishableKey&&Ki({sessionId:L,publishableKey:ot.current.publishableKey,paypalPublishableKey:ot.current.paypalPublishableKey}),N=await So(x,{flopay:et.current,paypalFlopay:ue.current,attempt3DS:D?.attempt3DS,billingApiUrl:P,sessionId:L,session:k,telemetry:!1}),x.type==="paypal_redirect_required"&&fa();else if(D?.initialAutoProcessingPending){let ne=(await new Ro(P,{telemetry:!1}).waitForCheckoutSessionCompletion(D.initialAutoProcessingPending.sessionId,{initialDelayMs:D.initialAutoProcessingPending.retryAfterMs})).data.session;if(!yr(ne))throw mo(ne);N=Zn(ne,L)}else{if(D?.initialAutoProcessingError)throw Kn(D.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:D.initialAutoProcessingError.checkoutMethod});if(D?.fromCreateSession)return D?.fallbackToFull&&(Je("full"),Hi("full")),!1;{let C=await vr({billingApiUrl:P,sessionId:L,session:k,telemetry:!1});C.type==="success"?N=C.result:(ye(),C.type==="paypal_redirect_required"&&ot.current?.publishableKey&&Ki({sessionId:L,publishableKey:ot.current.publishableKey,paypalPublishableKey:ot.current.paypalPublishableKey}),N=await So(C,{flopay:et.current,paypalFlopay:ue.current,attempt3DS:D?.attempt3DS,billingApiUrl:P,sessionId:L,session:k,telemetry:!1}),C.type==="paypal_redirect_required"&&fa())}}L&&fr(L),V(),c&&(m.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),m.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),m.terminal({outcome:N.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Jt(N.status==="authorized"),Ie("success"),await Yr(xn),Ge=()=>Ve.current?.(N)}catch(x){let N=rr(x),C=N.checkoutMethod??Hr;Te(N.message),Ke(N.message),Jt(!1),D?.fallbackToFull&&(m.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Je("full"),Hi("full")),V();let T=N.statusCode!==void 0?Bl(N.statusCode,"unknown"):void 0,ne=T==="4xx"?{requestCategory:"process_payment",statusClass:T}:{},vt=T===void 0||T==="4xx";if(vt&&(N.telemetryOutcome==="payment_declined"||!!(N.declineCode||N.code?.toLowerCase().includes("declin"))))m.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...ne});else if(vt&&(N.telemetryOutcome==="validation_rejected"||N.type==="validation_error"))m.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...ne});else{let Xr=Ui(x,c?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");m.error({...Xr,...N.telemetryFailureCategory?{failureCategory:N.telemetryFailureCategory}:{},stage:c?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:N.telemetryRequestCategory??"process_payment"})}return ut(()=>Ye.current?.(N)),cn(C,N,{code:N.code,declineCode:N.declineCode}),Ie("error"),await Promise.allSettled([Yr(Sn),D?.ensureProvidersReady?D.ensureProvidersReady():Promise.resolve()]),c&&(m.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),m.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{V(),W&&Wr(W),Ie(null),Ke(null)}return ut(Ge),!0},[cn,ut,rr,P,a,He]);Bn(()=>{if(typeof window>"u"||Hn.current)return;let k=new URLSearchParams(window.location.search),D=k.get("payment_intent_client_secret");if(!D)return;let L=Ll();L&&(Hn.current=!0,(async()=>{let fe,Ce=0;Te(null),Ke(null),Ie("processing"),xt(!0);try{if(k.get("redirect_status")==="failed")throw Object.assign(new Et("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:W,paypalFlopay:m}=await ko({publishableKey:L.publishableKey,paypalPublishableKey:L.paypalPublishableKey,billingApiUrl:P,locale:p,telemetry:a});fe=At(m??W),Ce=fe?.now()??0,fe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let O=(m??W)?.getRawProvider();if(!O)throw Object.assign(new Et("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:c,error:o}=await O.retrievePaymentIntent(D);if(o)throw Object.assign(new Et(o.message??"Failed to retrieve PayPal payment status.","api_error",{code:o.code}),{checkoutMethod:"paypal"});let E=li(c?.status);if(!c||E==="failed")throw Object.assign(new Et("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let ye=typeof c.payment_method=="string"?c.payment_method:c.payment_method?.id,Pe=E;if(L.sessionId){let x=(await new Ro(P,{telemetry:!1}).getUnifiedCheckoutSession(L.sessionId)).data.session;if(x&&x.status!=="complete"){let N=await vr({billingApiUrl:P,sessionId:L.sessionId,session:x,telemetry:!1,tokenizedData:{id:ye??c.id,type:"card",threeDSecureActionResultTokenId:c.id,isPaypal:!0}});if(N.type!=="success")throw Object.assign(new Et("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Pe=N.result.status}}L.sessionId&&fr(L.sessionId),fe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.performance({stage:"redirect_resume",durationMs:fe.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ie("success"),await Yr(xn),ut(()=>Ve.current?.({status:Pe,paymentIntentId:c.id,paymentMethodId:ye,checkoutMethod:"paypal"}))}catch(W){let m=rr(W),O=m.checkoutMethod??"paypal",c=!!(m.declineCode||m.code?.toLowerCase().includes("declin"));if(fe)fe.performance({stage:"redirect_resume",durationMs:fe.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),c?fe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):fe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(c){let o=Eo(P,a,He);o.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Wr(o)}else ma(P,a,He,"REDIRECT_RESUME_FAILED","redirect_resume");Te(m.message),Ke(m.message),ut(()=>Ye.current?.(m)),cn(O,m,{code:m.code,declineCode:m.declineCode}),Ie("error"),await Yr(Sn)}finally{fa(),$l(),Ie(null),Ke(null),xt(!1)}})())},[cn,ut,p,rr,P,a]);let Qt=Ut(null);function Zt(k,D=!1){let L=k?.account?.email?.trim().toLowerCase()??"",fe={c:k?.clientId,cur:k?.currency??"",captureMethod:k?.captureMethod??"",a:{e:L,u:L?"":k?.account?.userId??"",country:k?.account?.country??""},successUrl:k?.successUrl,cancelUrl:k?.cancelUrl,p:k?.products?.map(m=>ga(`${m.type??""}:${m.code??m.providerItemId??m.providerPlanId??""}`,m)).sort(),i:k?.items?.map(m=>ga(m.code??m.providerItemId??"",m)).sort(),s:k?.subscriptions?.map(m=>ga(m.code??m.providerPlanId??"",m)).sort(),couponCodes:k?.couponCodes?[...k.couponCodes].sort():void 0,...D?{tagsData:k?.tagsData,utmMetadata:k?.utmMetadata,tokenizedData:k?.tokenizedData,checkoutMode:k?.checkoutMode??"full"}:{}},Ce=JSON.stringify(fe),W=0;for(let m=0;m<Ce.length;m++)W=(W<<5)-W+Ce.charCodeAt(m)|0;return`flopay_session_${Math.abs(W).toString(36)}`}let Ft=yn(()=>Lt?Zt(Lt):"",[Lt]),Se=Ut(Lt);Se.current=Lt,Bn(()=>{mt(e??"")},[e]),Bn(()=>{Xt.current=!1,Te(De),Ke(null),Jt(!1),Ie(null)},[Ft,De,e]);async function St(k,D){let L=Eo(P,a,He),fe=new Ro(P,{telemetry:!1}),Ce=!1;try{let W=k.idempotencyKey!==void 0?ji(k.idempotencyKey):void 0,m=W??zl(D),O,c=!1,o=Ol(D);L.log({name:o?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let E=o?.sid??null,ye=null,Pe;if(E)try{if(ye=await fe.getUnifiedCheckoutSession(E,o?.nonce),ye.data.session?.status==="complete"){if(Go(E))return{sid:E,result:ye};Ul(D),E=null,ye=null,c=!0}}catch{L.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Pa(D),E=null}if(!E){!W&&(c||!m)&&(m=ji(),O=m),m&&Nl(D,m);let V=L.now(),Ge=0;L.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let x={...k,idempotencyKey:m,avsCheck:!!Fe,avsConfig:typeof Fe=="object"?Fe:void 0,checkoutType:"embedded_checkout",checkoutLayout:se?"custom_layout":F==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(x,xl,{configurable:!1,enumerable:!1,value:{onAttempt:T=>{Ge=Math.max(Ge,T)}}});let N=()=>{L.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),L.performance({stage:"session_create",durationMs:L.now()-V,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:"2xx"})},C=T=>{let ne=Ui(T,"CHECKOUT_SESSION_CREATE_FAILED","unknown");L.performance({stage:"session_create",durationMs:L.now()-V,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:ne.statusClass}),T instanceof Et&&T.type==="validation_error"?L.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):ne.statusClass==="4xx"?L.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):L.error({...ne,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if(Tl(x)){let T=await fe.createDetachedSession(x);T.claimed.catch(()=>{}),ye=T.shell,E=T.sessionId,Pe=T.claimed.then(ne=>{let vt=ne.data.session?.id??T.sessionId;return vt&&Vi(D,vt,ne.data.session?.clientSecret??T.nonce),N(),ne},ne=>{throw Pa(D),C(ne),ne}).finally(()=>Wr(L)),Pe.catch(()=>{}),Ce=!0,L.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),L.performance({stage:"session_shell",durationMs:L.now()-V,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:"2xx",paymentMethodCategory:"card"})}else ye=await fe.createAndFetchSession(x),N()}catch(T){throw C(T),T}E=ye.data.session?.id??E??"",E&&!Pe&&Vi(D,E,ye.data.session?.clientSecret)}return{sid:E??"",result:ye,sdkGeneratedIdempotencyKey:O,...Pe?{claimed:Pe}:{}}}finally{Ce||Wr(L)}}let gt=or(async(k,D)=>{let L=Se.current;if(!L)throw new Et("createSession is required to bootstrap checkout.","validation_error");let fe=Yo(L,k),Ce=Zt(fe),W=_o.get(Ce);if(!W){let c={promise:St(fe,Ce),consumers:0,settled:!1};W=c,_o.set(Ce,c);let o=()=>{c.settled=!0,qi(Ce,c)};c.promise.then(o,o)}W.consumers+=1;let m=!1,O=()=>{m||(m=!0,W.consumers-=1,qi(Ce,W))};D?.(O);try{let c=await W.promise;Qt.current=Ce,k&&(jt(at),Ln(N=>ai(N,k)));let{sid:o,result:E,claimed:ye}=c;if(ce(E),E.data.session&&tt(E.data.session),o&&mt(o),ye){let N=Vt.current+=1;Kt(!0),ye.then(C=>{Vt.current===N&&(ce(C),C.data.session&&tt(C.data.session),Kt(!1))},C=>{Vt.current===N&&(Kt(!1),S(C instanceof Et?C:new Et(C instanceof Error?C.message:"Failed to create session","api_error")))})}else Vt.current+=1,Kt(!1);let{publishableKey:Pe,paypalPublishableKey:V}=wo(E),{flopay:Ge,paypalFlopay:x}=await ko({publishableKey:Pe,paypalPublishableKey:V,billingApiUrl:P,locale:p,telemetry:a});return et.current=Ge,de(Ge),ue.current=x,it(x),nt(!1),c}catch(c){throw Qt.current===Ce&&(Qt.current=null),c}finally{D||O()}},[p,P,a,He]),Pn=Ut(rn);Pn.current=rn;let ir=Ut(gt);ir.current=gt;let Ot=or(async k=>{if(!jl(k)||dt)return{sessionId:Y,session:G};ln(!0);try{let D=await gt(k);return{sessionId:D.sid,session:D.result.data.session??null}}finally{ln(!1)}},[gt,dt,Y,G]);Bn(()=>{let k=!1,D;if(S(null),Ft){let Ce=Se.current;return Je(Ct),nt(!1),Qt.current===Ft?()=>{k=!0}:(tt(ii(Ce,_e)),(async()=>{let W=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),m=Ct==="auto"&&!Xt.current&&!W;m&&(Te(null),Ke(null),Ie("processing"));try{let O=await ir.current(void 0,ye=>{D=ye}),c=O.result.data.session??null;ot.current=wo(O.result);let o=ya(O.result),E=Go(O.sid||c?.id);if(!k&&m&&c&&!o&&!E){Xt.current=!0,await Fl(Ft,O.sdkGeneratedIdempotencyKey,()=>Pn.current(c,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:O.result.autoProcessingError,initialAutoProcessingPending:O.result.autoProcessingPending,autoProcessingAttempted:O.result.autoProcessingAttempted,sessionId:O.sid||c.id}));return}!k&&m&&((o||E)&&(Xt.current=!0),Ie(null),Ke(null))}catch(O){if(k)return;let c=O instanceof Et||typeof O=="object"&&O!==null&&"code"in O?O.code:void 0;if(m&&c==="session_auto_completed"){Xt.current=!0,Ie("success"),await Yr(xn),k||(ut(()=>{Ve.current?.({status:"succeeded"})}),Ie(null),Ke(null));return}m&&(Ie(null),Ke(null));let o=O instanceof Et?O:new Et(O instanceof Error?O.message:"Failed to create session","api_error");S(o)}finally{D?.(),D=void 0}})(),()=>{k=!0,D?.()})}nt(!0);async function L(){let Ce=!1;try{let m=await new Ro(P,{telemetry:!1}).getUnifiedCheckoutSession(je,t);if(k)return;ce(m);let O=m.data.session??null;if(tt(O),!O)throw new Et("No session data returned","api_error");let c=O.checkoutMode;if(c==="setup")throw new Et("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(O.status==="authorized"){nt(!1),ut(()=>{Ve.current?.(Zn(O,je)),Nn.current?.(O.successUrl??"")});return}if(O.status==="complete"){nt(!1),ut(()=>{Nn.current?.(O.successUrl??"")});return}if(O.status==="expired")throw po(O);Ce=!0;let o=_e??c??"full";Je(o);let E=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ye=ya(m);if(o==="auto"&&!Xt.current&&!E&&!ye){Xt.current=!0;let Pe=fe(m);try{if(await Pn.current(O,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Pe,sessionId:je||O.id}),k)return;await Pe,k||nt(!1);return}catch{if(k)return;await Pe,k||nt(!1);return}}await fe(m),k||nt(!1)}catch(W){if(k)return;W instanceof Et?!Ce&&!Dl(W)&&ma(P,a,He,"NETWORK_REQUEST_FAILED","session_read"):ma(P,a,He,"INTERNAL_SDK_ERROR","checkout_mount");let m=W instanceof Et?W:new Et(W instanceof Error?W.message:"Failed to initialize checkout","api_error");S(m),nt(!1)}}async function fe(Ce){let{publishableKey:W,paypalPublishableKey:m}=wo(Ce);ot.current={publishableKey:W,paypalPublishableKey:m};let{flopay:O,paypalFlopay:c}=await ko({publishableKey:W,paypalPublishableKey:m,billingApiUrl:P,locale:p,telemetry:a});et.current=O,de(O),ue.current=c,it(c)}return L(),()=>{k=!0}},[_e,Ft,Ct,qe,ut,t]);let on=or(async()=>{if(!(Xe||!G)){xt(!0),Te(null);try{await rn(G,{attempt3DS:!0,fallbackToFull:!0,sessionId:je||G.id})}finally{xt(!1)}}},[je,Xe,rn,G]),Dt=ha(_),Yn=ya(_),dn=yn(()=>{if(!_||!G||!_.data.stripe?.publishableKey)return;let k={appearance:We,paymentMethodCreation:"manual",billingApiUrl:P};if(_.data.stripe?.clientSecret)k.clientSecret=_.data.stripe.clientSecret;else{let D=$i(G).total;k.amount=Math.round(D*100)||G.amount,k.currency=G.currency?.toLowerCase()}return k},[_,G,We,P]),Un=!!(n&&!se&&F==="buttons"&&ae&&Ct==="full"),zt=yn(()=>({session:G,loading:$t,error:en,checkoutMode:pe,inlineSessionDraft:Lt,applyInlineSessionPatch:Un?Ot:void 0,inlineSessionPatchProcessing:dt,claimPending:qt}),[G,$t,en,pe,Lt,Un,Ot,dt,qt]),bn=!!n&&F==="buttons"&&!Yn&&(!K||!dn),Me=ft?ee(wn,{status:ft,errorMessage:tn,authorized:Dn}):null;if($t){if(l)return _t(En,{children:[l,Me]});if(F==="buttons"){let k=Q?.buttonsLayout?.cardButton?.borderRadius??Q?.appearance.variables?.borderRadius??8,D=L=>ee("div",{style:{height:L,borderRadius:k,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return _t(En,{children:[_t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[u&&D(Cr),h&&(I||y)&&D(Cr),h&&D(Cr),ee("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Me]})}return _t(En,{children:[_t("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ee("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ee("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Me]})}return en?b?ee(mn.Provider,{value:zt,children:b(en)}):ee(mn.Provider,{value:zt,children:ee("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:en.message})}):bn?_t(En,{children:[ee(mn.Provider,{value:zt,children:ee(Kl,{onButtonClick:f,showPayPal:u,showStripe:h,showApplePay:I,showGooglePay:y,theme:te,buttonsTheme:be,buttonsStyles:j,cardButtonContent:q,cardBackButtonContent:oe,cardTitleContent:ie})}),Me]}):Yn&&G&&Dt?_t(En,{children:[ee(mn.Provider,{value:zt,children:_t("div",{className:le,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[yt&&ee(mr,{icon:!1,children:yt}),Bt==="retrying"&&ee("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Bt==="exhausted"&&_t("div",{role:"alert",children:[ee("div",{children:"PayPal is temporarily unavailable. Please try again."}),ee("button",{type:"button",onClick:gn,children:"Retry PayPal"})]}),Bt!=="exhausted"&&ee("div",{"aria-hidden":Bt==="retrying"?!0:void 0,style:Bt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ee(fi,{sessionId:je,nonce:G.clientSecret||void 0,billingApiUrl:P,email:G.customer?.email,clientId:Dt.clientId,environment:Dt.environment,currency:(G.currency??"usd").toUpperCase(),isSubscription:G.mode==="subscription",providerObjectType:Dt.providerObjectType,onComplete:z,onErrorChange:Te,onDecline:R,onButtonClick:f,onInitializationStateChange:ar,allowAutomaticRetry:zn===0,session:G,telemetry:a,telemetryContext:He,debug:he},`paypal-init-${zn}`)})]})}),Me]}):!K||!dn?ee(En,{children:Me}):pe==="confirm"?_t(En,{children:[ee(mn.Provider,{value:zt,children:ee(co,{flopay:K,paypalFlopay:$e,options:dn,children:_t("div",{className:le,children:[yt&&ee("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:yt}),xe?xe({onConfirm:on,isProcessing:Xe}):ee("button",{type:"button",onClick:on,disabled:Xe,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Xe?"not-allowed":"pointer",opacity:Xe?.6:1},children:Xe?"Processing...":Ue??"Confirm Purchase"})]})})}),Me]}):_t(En,{children:[ee(mn.Provider,{value:zt,children:ee(co,{flopay:K,paypalFlopay:$e,options:dn,children:se?_t(En,{children:[yt&&ee("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:yt}),ee(ql,{sessionId:je,nonce:G?.clientSecret||void 0,billingApiUrl:P,session:G,children:se})]}):ee(ca,{sessionId:je,nonce:G?.clientSecret||void 0,email:G?.customer?.email,userId:G?.customer?.id,firstName:G?.customer?.firstName,lastName:G?.customer?.lastName,totalAmount:G?Math.round($i(G).total*100):0,currency:G?.currency?.toLowerCase()??"usd",onComplete:z,onError:g,onDecline:R,error:yt,onErrorChange:Te,showPayPal:u,showStripe:h,enabledPaymentMethods:w??_?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:_?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:y,layout:F,theme:te,buttonsTheme:be,buttonsStyles:j,appearance:We,cardButtonContent:q,cardBackButtonContent:oe,cardTitleContent:ie,onButtonClick:f,onBeforeButtonClick:ae,enableAVS:Fe,...ve?{cardFieldOrder:ve}:{},...Re?{cardPreFormSlot:Re}:{},avsLayout:J,country:G?.customer?.country,city:G?.customer?.city,state:G?.customer?.state,onCountryChange:v,onZipChange:A,avsCheck:!!Fe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:se?"custom_layout":F==="buttons"?"buttons_layout":"default_layout",className:le,directPaypal:ha(_),isSubscription:G?.mode==="subscription",session:G,dataAttachmentPending:qt,debug:he})})}),Me]})}function ql({sessionId:e,nonce:t,billingApiUrl:n,session:s,children:a}){return ee(En,{children:pa.Children.map(a,i=>{if(!pa.isValidElement(i))return i;let p=i.props,l={};return p.sessionId||(l.sessionId=e),!p.nonce&&t&&(l.nonce=t),p.billingApiUrl||(l.billingApiUrl=n),s?.customer&&(p.email||(l.email=s.customer.email),p.userId||(l.userId=s.customer.id),p.firstName||(l.firstName=s.customer.firstName),p.lastName||(l.lastName=s.customer.lastName)),Object.keys(l).length===0?i:pa.cloneElement(i,l)})})}function Kl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:s,showGooglePay:a,theme:i,buttonsTheme:p,buttonsStyles:l,cardButtonContent:b,cardBackButtonContent:z,cardTitleContent:g}){let[R,v]=bt(!1),A=yn(()=>Wi(i),[i]),u=yn(()=>{let y=A?.buttonsLayout??Al(p);return l?{...y,...l,cardButton:{...y.cardButton,...l.cardButton},cardFormContainer:{...y.cardFormContainer,...l.cardFormContainer},backButton:{...y.backButton,...l.backButton},backButtonIcon:{...y.backButtonIcon,...l.backButtonIcon},submitButton:{...y.submitButton,...l.submitButton},title:{...y.title,...l.title}}:y},[A,p,l]),h=A?.buttonsLayout?.cardButton?.borderRadius??A?.appearance.variables?.borderRadius??8,w=y=>ee("div",{style:{height:y,borderRadius:h,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),I=b===void 0?{boxSizing:"border-box",height:Cr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(R){let y=u.cardInputBorder??"#e5e7eb",he=u.cardInputBackground??"white",F=cr(z),te=cr(g);return _t("div",{style:{backgroundColor:u.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...u.cardFormContainer},children:[_t("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[_t("button",{type:"button",onClick:()=>v(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:F?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...u.backButton},children:[ee("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:ee("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:ee("path",{d:"M15 18l-6-6 6-6"})})}),ee(ur,{content:z})]}),te?ee("div",{style:{flex:1}}):ee("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:ee(Nr,{content:g})})]}),ee("div",{style:{backgroundColor:he,border:`1px solid ${y}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ee("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),_t("div",{style:{display:"flex"},children:[ee("div",{style:{flex:1,backgroundColor:he,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${y}`,borderLeft:`1px solid ${y}`,borderBottomLeftRadius:8,padding:12,height:45},children:ee("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ee("div",{style:{flex:1,backgroundColor:he,borderTop:"none",borderRight:`1px solid ${y}`,borderBottom:`1px solid ${y}`,borderLeft:`1px solid ${y}`,borderBottomRightRadius:8,padding:12,height:45},children:ee("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ee("div",{style:{backgroundColor:he,border:`1px solid ${y}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ee("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ee("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...u.submitButton,opacity:.5}}),ee("style",{children:`
36
36
  @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
37
37
  @keyframes flopay-interim-expand {
38
38
  0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
39
39
  40% { opacity: 1; }
40
40
  100% { opacity: 1; max-height: 600px; transform: translateY(0); }
41
41
  }
42
- `})]})}return _t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&k(br),n&&(s||a)&&k(br),n&&ee("button",{type:"button",onClick:()=>{e?.("card"),C(!0)},style:{width:"100%",...T,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:c.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...c.cardButton},onMouseDown:g=>{g.currentTarget.style.transform="scale(0.985)"},onMouseUp:g=>{g.currentTarget.style.transform="scale(1)"},children:ee(lr,{content:v})}),ee("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{dropThirdPartyOnlyError as Nu}from"@flopay/shared";import{useEffect as Kl,useRef as Yi,useContext as Vl}from"react";import{jsx as Yl}from"react/jsx-runtime";function Gi(e,t){function n({className:s,id:a,style:i,options:u,onChange:l,onReady:v,onFocus:N,onBlur:h,onEscape:E}){let C=Yi(null),F=Yi(null),{elements:c,reportInteractive:P}=Vl(xn);return Kl(()=>{if(!c||!C.current)return;let k=!0;return(async()=>{let T=c.getElement(e);T||(T=await c.create(e,u)),!(!k||!C.current)&&(T.mount(C.current),F.current=T,l&&T.on("change",l),T.on("ready",()=>{P?.(),v?.()}),N&&T.on("focus",N),h&&T.on("blur",h),E&&T.on("escape",E))})(),()=>{if(k=!1,F.current){try{F.current.unmount()}catch{}F.current=null}}},[c,P]),Yl("div",{ref:C,className:s,id:a,style:i})}return n.displayName=t,n}var Hl=Gi("payment","PaymentElement"),Wl=Gi("address","AddressElement");import{PaymentAPI as Gl}from"@flopay/js";import{FloPayError as Jl}from"@flopay/shared";import{useCallback as Ca,useEffect as Xl,useRef as Ql,useState as Ji}from"react";import{Fragment as ec,jsx as vr,jsxs as tc}from"react/jsx-runtime";function Zl({sessionId:e,nonce:t,billingApiUrl:n,email:s,userId:a,firstName:i,lastName:u,chv:l,onTokenizedBody:v,onComplete:N,onErrorChange:h,isProcessing:E=!1}){let C=vn(),F=Ho(),c=co(),[P,k]=Ji(!1),[T,g]=Ji(!1),me=Ql(!1),M=(n||c).replace(/\/+$/,""),le=Ca(async J=>{try{let oe=await new Gl(M).processPayment(a??"",{sessionId:e,nonce:t,tokenizedData:J,accountData:{userId:a??"",email:s??"",firstName:i??"",lastName:u??""},chv:l});if(oe.ok){N?.();return}let j=await oe.json().catch(()=>null);h?.(j?.message??"Payment failed. Please try again.")}catch(H){h?.(H instanceof Error?H.message:"An unexpected error occurred")}},[M,e,t,a,s,i,u,l,N,h]),ce=Ca(J=>{v?v(J):le(J)},[v,le]);Xl(()=>{if(!C||me.current)return;let J=new URLSearchParams(window.location.search),H=J.get("payment_intent"),oe=J.get("payment_intent_client_secret"),j=J.get("redirect_status");!H||!oe||(me.current=!0,(async()=>{try{if(g(!0),j==="failed"){h?.("PayPal payment was declined. Please try again.");return}let K=C.getRawProvider();if(!K?.retrievePaymentIntent){h?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ie,error:xe}=await K.retrievePaymentIntent(oe);if(xe){h?.(xe.message??"Failed to retrieve PayPal payment status.");return}if(ie&&(ie.status==="requires_capture"||ie.status==="succeeded")){let he=typeof ie.payment_method=="string"?ie.payment_method:ie.payment_method?.id;ce({id:he??ie.id,type:"card",threeDSecureActionResultTokenId:ie.id,isPaypal:!0});let de=new URL(window.location.href);de.searchParams.delete("payment_intent"),de.searchParams.delete("payment_intent_client_secret"),de.searchParams.delete("redirect_status"),window.history.replaceState({},"",de.toString())}else h?.("PayPal payment was not completed. Please try again.")}catch(K){h?.(K instanceof Error?K.message:"Failed to complete PayPal payment.")}finally{g(!1)}})())},[C,ce,h]);let z=Ca(async()=>{if(!(!C||!F))try{if(g(!0),h?.(null),!e||!s)throw new Jl("Missing sessionId or email for PayPal payment","validation_error");let J=await C.confirmPayPalPayment({billingApiUrl:M,sessionId:e,nonce:t,email:s,returnUrl:window.location.href});if(J.error){h?.(J.error.message);return}J.paymentIntentId&&(J.status==="succeeded"||J.status==="processing"||J.status==="requires_capture")&&ce({id:J.paymentMethodId??J.paymentIntentId,type:"card",threeDSecureActionResultTokenId:J.paymentIntentId,isPaypal:!0})}catch(J){h?.(J instanceof Error?J.message:"PayPal payment failed. Please try again.")}finally{g(!1)}},[C,F,e,t,s,M,ce,h]);return!C||!F?vr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):tc(ec,{children:[!P&&vr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),vr("div",{style:P?{}:{display:"none"},children:vr("button",{type:"button",onClick:z,disabled:T||E,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:T||E?"not-allowed":"pointer",opacity:T||E?.6:1},ref:()=>k(!0),children:T?"Processing...":"PayPal"})}),(T||E)&&vr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:vr("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}import{useCallback as qn,useEffect as Cr,useMemo as Yr,useRef as Sr,useState as Gr}from"react";import{PaymentAPI as Sa}from"@flopay/js";import{FloPayError as kr,resolveBillingApiUrl as nc,resolveButtonsLayoutTheme as rc,resolveTheme as oc}from"@flopay/shared";import{Fragment as dc,jsx as wr,jsxs as uc}from"react/jsx-runtime";var ac=44;function Xi(e){return new Promise(t=>setTimeout(t,e))}function ic(e,t){return e instanceof kr?e:new kr(e instanceof Error?e.message:t,"api_error")}function sc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function lc(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 cc({sessionId:e,nonce:t,createSession:n,paymentMethodId:s,checkoutMethod:a,clientId:i,products:u,items:l,subscriptions:v,account:N,successUrl:h,cancelUrl:E,couponCodes:C,tagsData:F,utmMetadata:c,billingApiUrl:P,locale:k,theme:T,appearance:g,buttonsTheme:me,buttonsStyles:M,onSuccess:le,onError:ce,onDecline:z,children:J,disabled:H=!1,type:oe="button",style:j,...K}){let ie=Yr(()=>nc(P),[P]),xe=Yr(()=>lc({createSession:n,clientId:i,products:u,items:l,subscriptions:v,account:N,successUrl:h,cancelUrl:E,couponCodes:C,tagsData:F,utmMetadata:c}),[N,E,i,C,n,u,l,v,h,F,c]),[he,de]=Gr(!1),[Q,ye]=Gr(null),[Te,Z]=Gr(null),[Ue,Fe]=Gr(!1),[we,V]=Gr(null),b=Sr(!0),te=Sr(null),$e=Sr(we),ze=Sr(le),ae=Sr(ce),R=Sr(z);Cr(()=>{$e.current=we},[we]),Cr(()=>{ze.current=le},[le]),Cr(()=>{ae.current=ce},[ce]),Cr(()=>{R.current=z},[z]),Cr(()=>(b.current=!0,()=>{b.current=!1,te.current?.abort()}),[]),Cr(()=>{if(typeof window>"u")return;let S=fe=>{fe.key==="Escape"&&V(null)};return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[]);let re=qn((S,fe=Vr)=>{R.current?.(It(fe,S,{code:S.code,declineCode:S.declineCode}))},[]),W=qn(async S=>{b.current&&(Z(null),Fe(S.result.status==="authorized"),ye("success"),await Xi(_n),b.current&&ze.current?.(S))},[]),ke=qn(async(S,fe)=>{b.current&&(ae.current?.(S),fe?.emitDecline&&re(S,fe.method),Z(S.message),Fe(!1),ye("error"),await Xi(Pn))},[re]),dt=qn(async(S,fe,We)=>{let Re=S.data.session??null;if(!Re)throw new kr("No session data returned","api_error");let vt=Re.clientSecret||t;if(pr(Re)){await W({result:Qn(Re,fe),session:Re,sessionId:Re.id||fe,autoCompleted:!1});return}if(Re.status==="expired")throw uo(Re);try{if(S.autoProcessingPending){let Je=(await new Sa(ie).waitForCheckoutSessionCompletion(S.autoProcessingPending.sessionId,{initialDelayMs:S.autoProcessingPending.retryAfterMs})).data.session;if(!pr(Je))throw po(Je);await W({result:Qn(Je,fe),session:Je,sessionId:Je.id||fe,autoCompleted:!1});return}if(S.autoProcessingError){if(S.autoProcessingError.type==="3ds_required"&&S.autoProcessingError.nextActionRedirectUrl&&fe&&vt){let je=new AbortController;te.current=je;let tt;try{tt=await zi({billingApiUrl:ie,sessionId:fe,nonce:vt,nextActionRedirectUrl:S.autoProcessingError.nextActionRedirectUrl,signal:je.signal})}finally{te.current===je&&(te.current=null)}if(tt.status==="declined")throw $n({type:tt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:tt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:S.autoProcessingError.checkoutMethod});let ot=(await new Sa(ie).waitForCheckoutSessionCompletion(fe,{initialDelayMs:0,nonce:vt})).data.session;if(!pr(ot))throw $n({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:S.autoProcessingError.checkoutMethod});await W({result:Qn(ot,fe),session:ot,sessionId:ot.id||fe,autoCompleted:!1});return}throw $n(S.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:S.autoProcessingError.checkoutMethod})}if(We?.fromCreateSession&&S.autoProcessingAttempted===!0)throw $n({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ke=await Pr({billingApiUrl:ie,sessionId:fe??Re.id,session:Re,nonce:vt});if(Ke.type!=="success")throw $n({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await W({result:Ke.result,session:Re,sessionId:Re.id||fe,autoCompleted:!1})}catch(Ke){let je=nr(Ke),tt=Re.id||fe;await ke(je,{emitDecline:!0,method:je.checkoutMethod??Vr}),sc(je,tt)&&tt&&b.current&&V({sessionId:tt,errorMessage:je.message,nonce:vt||void 0})}},[t,ie,ke,W]),Ge=qn(async S=>{if(K.onClick?.(S),!(S.defaultPrevented||H||he)){if(V(null),e&&xe){let fe=new kr("Provide either sessionId or create-session props, not both.","validation_error");await ke(fe),b.current&&(ye(null),Z(null));return}if(!e&&!xe){let fe=new kr("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await ke(fe),b.current&&(ye(null),Z(null));return}de(!0),Z(null),Fe(!1),ye("processing");try{let fe=new Sa(ie);if(e){let We=await fe.getUnifiedCheckoutSession(e,t);await dt(We,e);return}try{let We=await fe.createAndFetchSession({...xe});await dt(We,We.data.session?.id??null,{fromCreateSession:!0})}catch(We){if(We instanceof kr&&We.code==="session_auto_completed"){await W({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw We}}catch(fe){await ke(ic(fe,"Automatic payment failed. Please try again."))}finally{b.current&&(ye(null),Z(null),de(!1))}}},[K,xe,H,he,t,dt,ie,e,ke,W]),pt=qn(S=>{let fe=$e.current;V(null),ze.current?.({result:S,session:null,sessionId:fe?.sessionId??null,autoCompleted:!1})},[]),_=qn(S=>{ae.current?.(S)},[]),Y=qn(S=>{R.current?.(S)},[]),et=Yr(()=>oc(T),[T]),qe=Yr(()=>{let S=et?.buttonsLayout??rc(me);return M?{...S,...M,cardButton:{...S.cardButton,...M.cardButton}}:S},[et,me,M]),mt=Yr(()=>{let S=et?.appearance;return g?S?{...S,...g,variables:{...S.variables,...g.variables}}:g:S},[g,et]),Ne=mt?.variables,He=Ne?.colorPrimary??"#4A49FF",Jt=Ne?.colorPrimaryHover??Lr(He,.12),Ye=Ne?.borderRadius??"8px";return uc(dc,{children:[wr("button",{...K,type:oe,onClick:Ge,disabled:H||he,"aria-busy":he,style:{width:"100%",...J===void 0?{boxSizing:"border-box",height:ac,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...qe.cardButton,...sa({themeBundle:et,resolvedPrimaryColor:He,resolvedBorderRadius:Ye,submitButtonStyle:qe.submitButton,explicitPrimaryColor:Ne?.colorPrimary}),fontSize:qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:H||he?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:H||he?.6:1,...j},onMouseEnter:S=>{K.onMouseEnter?.(S),!S.defaultPrevented&&!H&&!he&&(et||Ne?.colorPrimary)&&(S.currentTarget.style.backgroundColor=Jt)},onMouseLeave:S=>{K.onMouseLeave?.(S),!S.defaultPrevented&&(et||Ne?.colorPrimary)&&(S.currentTarget.style.backgroundColor=He)},onMouseDown:S=>{K.onMouseDown?.(S),S.defaultPrevented||(S.currentTarget.style.transform="scale(0.985)")},onMouseUp:S=>{K.onMouseUp?.(S),S.defaultPrevented||(S.currentTarget.style.transform="scale(1)")},children:wr(lr,{content:J})}),Q&&wr(bn,{status:Q,errorMessage:Te,authorized:Ue}),we&&wr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:S=>{S.target===S.currentTarget&&V(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:wr("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:wr(va,{sessionId:we.sessionId,nonce:we.nonce,checkoutMode:"full",billingApiUrl:ie,locale:k,theme:T,...mt?{appearance:mt}:{},buttonsTheme:me,buttonsStyles:M,initialErrorMessage:we.errorMessage,cardTitleContent:null,onComplete:pt,onError:_,onDecline:Y})})})]})}export{Wl as AddressElement,ho as DirectPayPalButton,cc as FloPayAutomaticPaymentButton,hs as FloPayCardSetup,gs as FloPayCardSetupError,va as FloPayCheckout,lo as FloPayProvider,Zl as PayPalButton,Hl as PaymentElement,la as SplitCardForm,qo as VaultCardFields,Nu as dropThirdPartyOnlyError,Ms as useCheckout,Ho as useElements,vn as useFloPay,Vo as usePayPalFloPay};
42
+ `})]})}return _t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&w(Cr),n&&(s||a)&&w(Cr),n&&ee("button",{type:"button",onClick:()=>{e?.("card"),v(!0)},style:{width:"100%",...I,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:u.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,...u.cardButton},onMouseDown:y=>{y.currentTarget.style.transform="scale(0.985)"},onMouseUp:y=>{y.currentTarget.style.transform="scale(1)"},children:ee(dr,{content:b})}),ee("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{dropThirdPartyOnlyError as Nu}from"@flopay/shared";import{useEffect as Vl,useRef as Gi,useContext as Hl}from"react";import{jsx as Gl}from"react/jsx-runtime";function Ji(e,t){function n({className:s,id:a,style:i,options:p,onChange:l,onReady:b,onFocus:z,onBlur:g,onEscape:R}){let v=Gi(null),A=Gi(null),{elements:u,reportInteractive:h}=Hl(Tn);return Vl(()=>{if(!u||!v.current)return;let w=!0;return(async()=>{let I=u.getElement(e);I||(I=await u.create(e,p)),!(!w||!v.current)&&(I.mount(v.current),A.current=I,l&&I.on("change",l),I.on("ready",()=>{h?.(),b?.()}),z&&I.on("focus",z),g&&I.on("blur",g),R&&I.on("escape",R))})(),()=>{if(w=!1,A.current){try{A.current.unmount()}catch{}A.current=null}}},[u,h]),Gl("div",{ref:v,className:s,id:a,style:i})}return n.displayName=t,n}var Yl=Ji("payment","PaymentElement"),Wl=Ji("address","AddressElement");import{PaymentAPI as Jl}from"@flopay/js";import{FloPayError as Xl}from"@flopay/shared";import{useCallback as Sa,useEffect as Ql,useRef as Zl,useState as Xi}from"react";import{Fragment as tc,jsx as Sr,jsxs as nc}from"react/jsx-runtime";function ec({sessionId:e,nonce:t,billingApiUrl:n,email:s,userId:a,firstName:i,lastName:p,chv:l,onTokenizedBody:b,onComplete:z,onErrorChange:g,isProcessing:R=!1}){let v=kn(),A=Ho(),u=uo(),[h,w]=Xi(!1),[I,y]=Xi(!1),he=Zl(!1),F=(n||u).replace(/\/+$/,""),te=Sa(async q=>{try{let ie=await new Jl(F).processPayment(a??"",{sessionId:e,nonce:t,tokenizedData:q,accountData:{userId:a??"",email:s??"",firstName:i??"",lastName:p??""},chv:l});if(ie.ok){z?.();return}let Ne=await ie.json().catch(()=>null);g?.(Ne?.message??"Payment failed. Please try again.")}catch(oe){g?.(oe instanceof Error?oe.message:"An unexpected error occurred")}},[F,e,t,a,s,i,p,l,z,g]),be=Sa(q=>{b?b(q):te(q)},[b,te]);Ql(()=>{if(!v||he.current)return;let q=new URLSearchParams(window.location.search),oe=q.get("payment_intent"),ie=q.get("payment_intent_client_secret"),Ne=q.get("redirect_status");!oe||!ie||(he.current=!0,(async()=>{try{if(y(!0),Ne==="failed"){g?.("PayPal payment was declined. Please try again.");return}let f=v.getRawProvider();if(!f?.retrievePaymentIntent){g?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ae,error:Fe}=await f.retrievePaymentIntent(ie);if(Fe){g?.(Fe.message??"Failed to retrieve PayPal payment status.");return}if(ae&&(ae.status==="requires_capture"||ae.status==="succeeded")){let ve=typeof ae.payment_method=="string"?ae.payment_method:ae.payment_method?.id;be({id:ve??ae.id,type:"card",threeDSecureActionResultTokenId:ae.id,isPaypal:!0});let Re=new URL(window.location.href);Re.searchParams.delete("payment_intent"),Re.searchParams.delete("payment_intent_client_secret"),Re.searchParams.delete("redirect_status"),window.history.replaceState({},"",Re.toString())}else g?.("PayPal payment was not completed. Please try again.")}catch(f){g?.(f instanceof Error?f.message:"Failed to complete PayPal payment.")}finally{y(!1)}})())},[v,be,g]);let j=Sa(async()=>{if(!(!v||!A))try{if(y(!0),g?.(null),!e||!s)throw new Xl("Missing sessionId or email for PayPal payment","validation_error");let q=await v.confirmPayPalPayment({billingApiUrl:F,sessionId:e,nonce:t,email:s,returnUrl:window.location.href});if(q.error){g?.(q.error.message);return}q.paymentIntentId&&(q.status==="succeeded"||q.status==="processing"||q.status==="requires_capture")&&be({id:q.paymentMethodId??q.paymentIntentId,type:"card",threeDSecureActionResultTokenId:q.paymentIntentId,isPaypal:!0})}catch(q){g?.(q instanceof Error?q.message:"PayPal payment failed. Please try again.")}finally{y(!1)}},[v,A,e,t,s,F,be,g]);return!v||!A?Sr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):nc(tc,{children:[!h&&Sr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),Sr("div",{style:h?{}:{display:"none"},children:Sr("button",{type:"button",onClick:j,disabled:I||R,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:I||R?"not-allowed":"pointer",opacity:I||R?.6:1},ref:()=>w(!0),children:I?"Processing...":"PayPal"})}),(I||R)&&Sr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:Sr("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}import{useCallback as Vn,useEffect as wr,useMemo as Gr,useRef as kr,useState as Jr}from"react";import{PaymentAPI as wa}from"@flopay/js";import{FloPayError as Ir,resolveBillingApiUrl as rc,resolveButtonsLayoutTheme as oc,resolveTheme as ac}from"@flopay/shared";import{Fragment as uc,jsx as Rr,jsxs as pc}from"react/jsx-runtime";var ic=44;function Qi(e){return new Promise(t=>setTimeout(t,e))}function sc(e,t){return e instanceof Ir?e:new Ir(e instanceof Error?e.message:t,"api_error")}function lc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function cc(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 dc({sessionId:e,nonce:t,createSession:n,paymentMethodId:s,checkoutMethod:a,clientId:i,products:p,items:l,subscriptions:b,account:z,successUrl:g,cancelUrl:R,couponCodes:v,tagsData:A,utmMetadata:u,billingApiUrl:h,locale:w,theme:I,appearance:y,buttonsTheme:he,buttonsStyles:F,onSuccess:te,onError:be,onDecline:j,children:q,disabled:oe=!1,type:ie="button",style:Ne,...f}){let ae=Gr(()=>rc(h),[h]),Fe=Gr(()=>cc({createSession:n,clientId:i,products:p,items:l,subscriptions:b,account:z,successUrl:g,cancelUrl:R,couponCodes:v,tagsData:A,utmMetadata:u}),[z,R,i,v,n,p,l,b,g,A,u]),[ve,Re]=Jr(!1),[J,le]=Jr(null),[De,se]=Jr(null),[_e,Ue]=Jr(!1),[xe,H]=Jr(null),P=kr(!0),Q=kr(null),We=kr(xe),Le=kr(te),Z=kr(be),_=kr(j);wr(()=>{We.current=xe},[xe]),wr(()=>{Le.current=te},[te]),wr(()=>{Z.current=be},[be]),wr(()=>{_.current=j},[j]),wr(()=>(P.current=!0,()=>{P.current=!1,Q.current?.abort()}),[]),wr(()=>{if(typeof window>"u")return;let S=pe=>{pe.key==="Escape"&&H(null)};return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[]);let ce=Vn((S,pe=Hr)=>{_.current?.(It(pe,S,{code:S.code,declineCode:S.declineCode}))},[]),K=Vn(async S=>{P.current&&(se(null),Ue(S.result.status==="authorized"),le("success"),await Qi(xn),P.current&&Le.current?.(S))},[]),de=Vn(async(S,pe)=>{P.current&&(Z.current?.(S),pe?.emitDecline&&ce(S,pe.method),se(S.message),Ue(!1),le("error"),await Qi(Sn))},[ce]),et=Vn(async(S,pe,Je)=>{let Xe=S.data.session??null;if(!Xe)throw new Ir("No session data returned","api_error");let xt=Xe.clientSecret||t;if(yr(Xe)){await K({result:Zn(Xe,pe),session:Xe,sessionId:Xe.id||pe,autoCompleted:!1});return}if(Xe.status==="expired")throw po(Xe);try{if(S.autoProcessingPending){let Ie=(await new wa(ae).waitForCheckoutSessionCompletion(S.autoProcessingPending.sessionId,{initialDelayMs:S.autoProcessingPending.retryAfterMs})).data.session;if(!yr(Ie))throw mo(Ie);await K({result:Zn(Ie,pe),session:Ie,sessionId:Ie.id||pe,autoCompleted:!1});return}if(S.autoProcessingError){if(S.autoProcessingError.type==="3ds_required"&&S.autoProcessingError.nextActionRedirectUrl&&pe&&xt){let Te=new AbortController;Q.current=Te;let ft;try{ft=await zi({billingApiUrl:ae,sessionId:pe,nonce:xt,nextActionRedirectUrl:S.autoProcessingError.nextActionRedirectUrl,signal:Te.signal})}finally{Q.current===Te&&(Q.current=null)}if(ft.status==="declined")throw Kn({type:ft.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:ft.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:S.autoProcessingError.checkoutMethod});let Ke=(await new wa(ae).waitForCheckoutSessionCompletion(pe,{initialDelayMs:0,nonce:xt})).data.session;if(!yr(Ke))throw Kn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:S.autoProcessingError.checkoutMethod});await K({result:Zn(Ke,pe),session:Ke,sessionId:Ke.id||pe,autoCompleted:!1});return}throw Kn(S.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:S.autoProcessingError.checkoutMethod})}if(Je?.fromCreateSession&&S.autoProcessingAttempted===!0)throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let yt=await vr({billingApiUrl:ae,sessionId:pe??Xe.id,session:Xe,nonce:xt});if(yt.type!=="success")throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await K({result:yt.result,session:Xe,sessionId:Xe.id||pe,autoCompleted:!1})}catch(yt){let Te=rr(yt),ft=Xe.id||pe;await de(Te,{emitDecline:!0,method:Te.checkoutMethod??Hr}),lc(Te,ft)&&ft&&P.current&&H({sessionId:ft,errorMessage:Te.message,nonce:xt||void 0})}},[t,ae,de,K]),$e=Vn(async S=>{if(f.onClick?.(S),!(S.defaultPrevented||oe||ve)){if(H(null),e&&Fe){let pe=new Ir("Provide either sessionId or create-session props, not both.","validation_error");await de(pe),P.current&&(le(null),se(null));return}if(!e&&!Fe){let pe=new Ir("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await de(pe),P.current&&(le(null),se(null));return}Re(!0),se(null),Ue(!1),le("processing");try{let pe=new wa(ae);if(e){let Je=await pe.getUnifiedCheckoutSession(e,t);await et(Je,e);return}try{let Je=await pe.createAndFetchSession({...Fe});await et(Je,Je.data.session?.id??null,{fromCreateSession:!0})}catch(Je){if(Je instanceof Ir&&Je.code==="session_auto_completed"){await K({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Je}}catch(pe){await de(sc(pe,"Automatic payment failed. Please try again."))}finally{P.current&&(le(null),se(null),Re(!1))}}},[f,Fe,oe,ve,t,et,ae,e,de,K]),it=Vn(S=>{let pe=We.current;H(null),Le.current?.({result:S,session:null,sessionId:pe?.sessionId??null,autoCompleted:!1})},[]),ue=Vn(S=>{Z.current?.(S)},[]),G=Vn(S=>{_.current?.(S)},[]),tt=Gr(()=>ac(I),[I]),Y=Gr(()=>{let S=tt?.buttonsLayout??oc(he);return F?{...S,...F,cardButton:{...S.cardButton,...F.cardButton}}:S},[tt,he,F]),mt=Gr(()=>{let S=tt?.appearance;return y?S?{...S,...y,variables:{...S.variables,...y.variables}}:y:S},[y,tt]),je=mt?.variables,qe=je?.colorPrimary??"#4A49FF",$t=je?.colorPrimaryHover??Or(qe,.12),nt=je?.borderRadius??"8px";return pc(uc,{children:[Rr("button",{...f,type:ie,onClick:$e,disabled:oe||ve,"aria-busy":ve,style:{width:"100%",...q===void 0?{boxSizing:"border-box",height:ic,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Y.cardButton,...la({themeBundle:tt,resolvedPrimaryColor:qe,resolvedBorderRadius:nt,submitButtonStyle:Y.submitButton,explicitPrimaryColor:je?.colorPrimary}),fontSize:Y.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:oe||ve?"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:oe||ve?.6:1,...Ne},onMouseEnter:S=>{f.onMouseEnter?.(S),!S.defaultPrevented&&!oe&&!ve&&(tt||je?.colorPrimary)&&(S.currentTarget.style.backgroundColor=$t)},onMouseLeave:S=>{f.onMouseLeave?.(S),!S.defaultPrevented&&(tt||je?.colorPrimary)&&(S.currentTarget.style.backgroundColor=qe)},onMouseDown:S=>{f.onMouseDown?.(S),S.defaultPrevented||(S.currentTarget.style.transform="scale(0.985)")},onMouseUp:S=>{f.onMouseUp?.(S),S.defaultPrevented||(S.currentTarget.style.transform="scale(1)")},children:Rr(dr,{content:q})}),J&&Rr(wn,{status:J,errorMessage:De,authorized:_e}),xe&&Rr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:S=>{S.target===S.currentTarget&&H(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:Rr("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:Rr(Ca,{sessionId:xe.sessionId,nonce:xe.nonce,checkoutMode:"full",billingApiUrl:ae,locale:w,theme:I,...mt?{appearance:mt}:{},buttonsTheme:he,buttonsStyles:F,initialErrorMessage:xe.errorMessage,cardTitleContent:null,onComplete:it,onError:ue,onDecline:G})})})]})}export{Wl as AddressElement,Po as DirectPayPalButton,dc as FloPayAutomaticPaymentButton,Ps as FloPayCardSetup,hs as FloPayCardSetupError,Ca as FloPayCheckout,co as FloPayProvider,ec as PayPalButton,Yl as PaymentElement,ca as SplitCardForm,jo as VaultCardFields,Nu as dropThirdPartyOnlyError,As as useCheckout,Ho as useElements,kn as useFloPay,Vo as usePayPalFloPay};