@flopay/react 1.5.0 → 1.7.0

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