@flopay/react 1.6.0 → 1.7.0

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