@flopay/react 1.9.11 → 1.9.13

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 Tt,b as cr,c as Bo,d as Ja,e as Fo,f as Cs,g as Ss,h as Jl,i as Xl}from"./chunk-M4FGYFX6.mjs";import{dropThirdPartyOnlyError as Sm}from"@flopay/shared";import{PaymentAPI as $i}from"@flopay/js";import{FloPayError as Zo,resolveBillingApiUrl as ru,resolveButtonsLayoutTheme as ou,resolveTheme as au}from"@flopay/shared";import{useCallback as Br,useEffect as vo,useMemo as Jo,useRef as Po,useState as Xo}from"react";import{Fragment as no,jsx as Vn,jsxs as ws}from"react/jsx-runtime";function Zl(){return ws(no,{children:[ws("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:[Vn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Vn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Vn("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:Vn("path",{d:"M9 18l6-6-6-6"})})]})}function Ql(){return Vn(no,{children:"Go back"})}function ec(){return Vn(no,{children:"Secure card checkout"})}function Qr(e){return e!==void 0&&(e===""||e===null||e===!1)}function eo({content:e}){return Vn(no,{children:e===void 0?Vn(Zl,{}):e})}function to({content:e}){return Vn(no,{children:e===void 0?Vn(Ql,{}):e})}function Do({content:e}){return Vn(no,{children:e===void 0?Vn(ec,{}):e})}import{classifyTelemetryFailure as tc,FloPayError as tr,isCardHolderNamePlaceholder as ks,isMoneySettledOutcome as nc,isSetupIntentClientSecret as vu,isValidEmail as rc}from"@flopay/shared";var oc="Checkout is temporarily unavailable. Please try again later.";function Xa(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof tr&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function ac(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 Is(){return new tr(oc,"api_error",{code:"CheckoutInitializationFailed"})}function _s(e,t,n){let r=e?.data.session,a=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||a?.includes("card"))||t&&e?.data.paypal?.publishableKey)}function Rs(e,t){if(t&&(!(e instanceof tr)||e.type==="authentication_error"))return Xa(e);if(!(e instanceof tr&&ac(e))){if(!t&&!(e instanceof tr)&&(e instanceof TypeError||e instanceof SyntaxError))return{...tc(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof tr)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof tr))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function ro(e,t,n,r={}){let a;return(i={})=>{if(a)return a;let c={...r,...i,email:i.email?.trim()||r.email?.trim()},l=ks(c.firstName,c.lastName);if(!rc(c.email))return Promise.reject(new tr("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let h={};for(let[P,y]of Object.entries(c)){if(l&&P.endsWith("Name")||typeof y!="string")continue;let f=y.trim();f&&(h[P]=f)}return a=e.claimCheckoutSession(t,n,{accountData:h}),a.catch(()=>{}),a}}function Es(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Za(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Ts(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}))],r=n.reduce((i,c)=>i+(c.overrideAmount??c.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(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((i,c)=>({uuid:`synthetic-${i.type??"item"}-${c}`,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 Ur(e){if(ks(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Qa(e,t){return t?{...e,...t}:e}function an(e,t,n){let r=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:r,...a?{code:a}:{},...i?{declineCode:i}:{}}}var ic=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Ir(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of ic)if(n.test(t))return r;return e}function qr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function oo(e){return e?.status==="authorized"||e?.status==="complete"}function As(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ca(e){let t=As(e);return new tr(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function da(e){return e instanceof tr||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function ua(e){let t=As(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new tr(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function No(e,t){return e==="processing"||nc(e,t)}function Ms(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function xs(e,t="automatic"){return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}function ei(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Lo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as qd,PaymentAPI as Aa,SESSION_CREATE_TELEMETRY as $d}from"@flopay/js";import{buildCheckoutDisplayData as jd,classifyTelemetryFailure as El,FloPayError as pn,isDetachedSessionEligible as Kd,resolveBillingApiUrl as Vd,resolveButtonsLayoutTheme as Hd,resolveIdempotencyKey as Cl,resolveTheme as Tl,SDK_VERSION as Al,telemetryStatusClass as Wd}from"@flopay/shared";import xi,{useCallback as Pn,useEffect as ur,useMemo as Wn,useRef as Mt,useState as Ot}from"react";import{createContext as Bs}from"react";var Hn=Bs({flopay:null,paypalFlopay:null,billingApiUrl:""}),nr=Bs({session:null,loading:!1,error:null});import{PaymentAPI as oi}from"@flopay/js";import{classifyTelemetryFailure as Sc,FloPayError as ai,generateIdempotencyKey as wc,isValidEmail as qo,normalizeGatewayEnvironment as kc,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as ii,SDK_VERSION as Ic}from"@flopay/shared";import{loadScript as _c}from"@paypal/paypal-js";import{useCallback as hr,useEffect as Ft,useMemo as $o,useRef as it,useState as Er}from"react";import{isValidEmail as sc}from"@flopay/shared";import{useCallback as Fs,useEffect as lc,useRef as Ds,useState as Ls}from"react";import{jsx as Ns,jsxs as Oo}from"react/jsx-runtime";function En(e,t=!1){let{firstName:n,lastName:r,...a}=e,i=n?.trim(),c=r?.trim();return{...a,...i||t?{firstName:i??""}:{},...c||t?{lastName:c??""}:{}}}function ao(){let[e,t]=Ls(null),n=Ds(null),r=Ds(0),a=Fs((c,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:c,identity:l}),new Promise(h=>{n.current=h})),[]),i=Fs(c=>{let l=n.current;n.current=null,t(null),l?.(c)},[]);return lc(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function io({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[c,l]=Ls(e.email?.trim()??""),h=sc(c.trim());return Oo("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[Oo("div",{style:{fontWeight:700},children:["Continue with ",t]}),Oo("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Ns("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:c,onChange:P=>l(P.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Oo("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Ns("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Oo("button",{type:"button",disabled:!h||a,onClick:()=>{n(En({...e,email:c.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function cc(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 $r(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function fr(e){if(typeof e!="object"||e===null)return;let t=e;return $r(t.code)??$r(t.type)??$r(t.name)}function so(e){if(!(typeof e!="object"||e===null))return $r(e.decline_code)}function zo(e){return typeof e!="object"||e===null?!1:$r(e.type)?.toLowerCase()==="card_error"||so(e)!==void 0}function gr(e){let t=cc(e)?.toLowerCase()??"",r=`${fr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as dc}from"@flopay/shared";import{useContext as pa}from"react";function _r(){return pa(Hn).flopay}function ti(){return pa(Hn).paypalFlopay??null}function uc(){return pa(nr)}function Os(){return pa(Hn).billingApiUrl||dc()}function ma(e){let t=e??(typeof navigator>"u"?"":navigator.userAgent),n=r=>({inAppBrowser:r!=="none",appFamily:r,popupCapability:"unknown"});return t?/FBAN|FBAV|FB_IAB|FBIOS/i.test(t)?n("facebook"):/Instagram/i.test(t)?n("instagram"):/musical_ly|BytedanceWebview|TikTok/i.test(t)?n("tiktok"):/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)?n("other_in_app"):/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)?n("generic_webview"):n("none"):n("none")}function ya(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}import{FLO_INSTRUMENT_SCHEMA_VERSION as pc}from"@flopay/shared";import{useCallback as mc,useRef as fa}from"react";var yc={"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 fc(e){return e==="stripe"||e==="paypal"?e:void 0}function gc(e){let t=fc(e.provider),n={schemaVersion:pc,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=yc[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 ni=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function lo(e,t){let n=fa(e);n.current=e;let r=fa(new Set),a=fa(t),i=fa(t);return Bo(()=>{i.current=t,a.current!==t&&(a.current=t,r.current.clear())},[t]),mc(c=>{if(i.current!==t)return;let l=gc(c);if(l){if(ni.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}Tt(()=>n.current?.(l))}},[t])}var hc=Symbol.for("@flopay/js.telemetry.bridge.v1"),vc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Pc(){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 bc(e){let t=Pc(),n=(a,i)=>a?a.bind(e):i,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 ga(e){let t=globalThis[vc];return bc(t?.(e)??{})}function Qt(e){if(e)return e[hc]}import{useCallback as Rr,useEffect as Cc,useRef as ri}from"react";function Uo(e){let t=ri(0),n=ri(null),r=ri(null),a=Rr((p=r.current)=>{p?.timer&&(clearTimeout(p.timer),p.timer=null)},[]),i=Rr(p=>{a();let I=t.current+1;return t.current=I,n.current=null,r.current={generation:I,method:p,timer:null,yieldedControl:!1},I},[a]),c=Rr(p=>{let I=r.current;return p!==void 0&&I?.generation!==p?!1:(a(I),r.current=null,(p===void 0||n.current===p)&&(n.current=null),!0)},[a]),l=Rr(p=>{let I=r.current,M=p??I?.generation??t.current;(p===void 0||I?.generation===p)&&(a(I),r.current=null),n.current=M},[a]),h=Rr(p=>n.current===(p??t.current),[]),P=Rr(p=>r.current?.generation===p&&n.current!==p,[]),y=Rr(()=>{let p=r.current;p&&(p.yieldedControl=!0,a(p))},[a]),f=Rr(()=>{let p=r.current;!p?.yieldedControl||document.visibilityState!=="visible"||(a(p),p.timer=setTimeout(()=>{p.timer=null,r.current?.generation===p.generation&&(r.current=null,n.current=p.generation,e(p.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[a,e]);return Cc(()=>{let p=()=>{document.visibilityState==="visible"?f():y()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",y),window.addEventListener("focus",f),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",y),window.removeEventListener("focus",f),a()}},[a,y,f]),{startAttempt:i,finishAttempt:c,invalidateAttempt:l,isAttemptInvalidated:h,isAttemptCurrent:P,generationRef:t}}import{jsx as jr,jsxs as li}from"react/jsx-runtime";var ha=45,Rc=1e3,Ec=11e3,Tc=["https://www.paypal.com","https://www.sandbox.paypal.com"],si="We couldn't open PayPal. Try again or choose another payment method.",Ac={width:"100%",minHeight:ha,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 Mc(e){return e.includes("No ack for postMessage init()")&&Tc.some(t=>e.includes(t))&&e.includes("10000ms")}var xc={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function Bc(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:xc[e.kind]??null}}function Fc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Mc(t)?"paypal_init_timeout":"paypal_init_failure"}function Dc(e,t=!1){return e?t?`${si} Open this page in your system browser, then try again.`:`${si} Allow pop-ups for this site, then try again.`:si}function Nc(e){let t=zo(e),n=gr(e);return t?{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:"provider_declined"}:{errorCode:n?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:n?"popup_blocked":"provider_error"}}function Lc(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function Oc(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function zs({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:a,onBuyerIdentityReady:i,clientId:c,environment:l,currency:h,isSubscription:P,providerObjectType:y,approvalPresentation:f,onTokenizedBody:p,onComplete:I,onErrorChange:M,onDecline:L,onTechnicalFailure:Te,isProcessing:ne=!1,onLoadStateChange:S,onInitializationStateChange:G,allowAutomaticRetry:J=!0,onButtonClick:oe,runBeforeButtonClick:Ae,session:ie,existingOrderId:ze,telemetry:Xe,telemetryContext:nt,onInstrument:_t,debug:Ne=!1}){let Me=_r(),le=lo(_t,e),we=$o(()=>{if(Me)return null;let F=ga({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ic,enabled:Xe!==!1});return F.setCheckoutContext(nt??{}),F.beginCheckout(nt??{}),F},[n,Me,Xe,nt?.checkoutMode,nt?.layout]),ce=$o(()=>Qt(Me),[Me]);Ft(()=>()=>{we&&we.flush().catch(()=>{}).finally(()=>we.destroy())},[we]);let pe=$o(()=>({error:F=>{ce?ce.error(F):we?.error(F),le({class:"technical_error",errorCode:F.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":F.errorCode,requestCategory:F.requestCategory,provider:F.provider})},log:F=>{ce?ce.log(F):we?.log(F),le({class:"lifecycle",name:F.name,provider:F.provider})},performance:F=>{ce?ce.performance(F):we?.performance(F)},terminal:F=>{ce?ce.terminal(F):we?.terminal(F)},startTiming:()=>ce?.now()??we?.now()??0,elapsed:F=>ce?.elapsed(F)??Math.max(0,(we?.now()??F)-F)}),[le,ce,we]),ke=it(null),Ke=it(0),$e=it(null),Ze=it(null),B=it(null),de=it(!1),[ue,ee]=Er(!1),[O,Ie]=Er(!1),[Oe,xt]=Er(0),rt=it(0),[z,q]=Er(!1),$=it(!1),xe=it(!1),[Qe,be]=Er(!1),[_e,Ve]=Er(!1),{request:g,collect:st,finish:R}=ao(),H=it({sessionId:e,required:!qo(r?.trim()||ie?.customer?.email?.trim())});H.current.sessionId!==e&&(H.current={sessionId:e,required:!qo(r?.trim()||ie?.customer?.email?.trim())});let ye=H.current.required,Be=$o(()=>n.replace(/\/+$/,""),[n]),Pt=ie?.gateways?.paypal?.providerObjectType??y,v=Pt??(P?"subscription":"order"),[T]=Er(ma),mt=ie?.gateways?.paypal?.approvalPresentation??f,je=ya(T,mt==="app_switch"?"app_switch":void 0,v),lt=Pt==="order"||Pt==="setup_token",Wt=$o(()=>JSON.stringify([Be,c,h,l??"",v,lt,je,e,ze??""]),[Be,c,h,l,ze,v,lt,je,e]),te=it(Wt),Gt=te.current!==Wt,ct=it(Ne),Tn=it(null),[cn,Rt]=Er([]),ve=hr(F=>{ct.current&&Rt(Re=>[...Re,`${new Date().toISOString().slice(11,23)} ${F}`])},[]);Ft(()=>{ct.current=Ne,Ne&&ve("debug:enabled"),Tn.current?.setEnabled(Ne)},[ve,Ne]);let mn=it(p),yn=it(I),Fe=it(M),pt=it(L),fn=it(Te),$t=it(oe),dn=it(S),Yt=it(G),Ct=it(i),bn=it(Ae),St=it(ie),Cn=it(r),jt=it(a),Fn=it(t),dt=it(null),yt=it(new Map),gn=it(new Map),Kt=it(!1);Ft(()=>(Kt.current=!0,()=>{Kt.current=!1}),[]),Ft(()=>{mn.current=p},[p]),Ft(()=>{Ct.current=i},[i]),Ft(()=>{yn.current=I},[I]),Ft(()=>{Fe.current=M},[M]),Ft(()=>{pt.current=L},[L]),Ft(()=>{fn.current=Te},[Te]),Ft(()=>{$t.current=oe},[oe]),Ft(()=>{dn.current=S},[S]),Ft(()=>{Yt.current=G},[G]),Ft(()=>{bn.current=Ae},[Ae]),Ft(()=>{St.current=ie},[ie]),Ft(()=>{Cn.current=r},[r]),Ft(()=>{jt.current=a},[a]),Ft(()=>{Fn.current=t},[t]),Ft(()=>{rt.current=Oe},[Oe]),Ft(()=>{z&&B.current?.focus()},[z,Oe]);let tn=hr(()=>{window.setTimeout(()=>{B.current?.focus()},0)},[]),wt=hr(()=>{ee(!1),xt(F=>F+1)},[]),fe=hr(()=>{q(!1),(ke.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ke.current)?.focus?.()},[]);Ft(()=>{!ue||!de.current||(de.current=!1,fe())},[fe,ue,Oe]);let ut=hr((F,Re)=>{let Y=Re?.popupBlocked??gr(F),Jt=Dc(Y,T.inAppBrowser),Gn=fn.current;if(Gn){let ot=Y&&T.inAppBrowser?new ai(Jt,"api_error",{code:Re?.code??"paypal_popup_blocked"}):F;Gn("paypal",ot,Re);return}Fe.current?.(Jt)},[T.inAppBrowser]),E=hr(F=>{let Re=$e.current,Y=Ze.current;Re===null||!Y||(pe.log({...Y,name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:F}),pe.performance({...Y,stage:"overlay_return",durationMs:pe.elapsed(Re),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:F}),$e.current=null)},[pe]),Vt=hr((F,Re,Y)=>{let Jt=Ze.current;E("overlay_timeout"),Jt&&pe.error({...Jt,errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),ut(Re,Y),q(!0),wt(),tn()},[E,tn,ut,wt,pe]),{finishAttempt:zt,generationRef:Sn,invalidateAttempt:nn,isAttemptCurrent:An,isAttemptInvalidated:mr,startAttempt:Mn}=Uo(Vt),We=hr(()=>(q(!1),Mn("paypal")),[Mn]),Fr=hr(F=>{nn(F?.generation),F?.showRetry&&q(!0),F?.remount&&wt(),F?.focus!==!1&&tn()},[tn,nn,wt]),xn=F=>{let Re=dt.current;return Re&&gn.current.set(F,Re),F};Ft(()=>{te.current!==Wt&&(te.current=Wt,$.current=!1,xe.current=!1,ee(!1),Ie(!1),be(!1),Yt.current?.("loading"))},[Wt]),Ft(()=>{Tt(()=>dn.current?.(ue&&!Qe))},[ue,Qe]);let Pr=kc(l);Ft(()=>{let F={attempt:Sn.current+1,...T,presentationMode:je},Re=()=>Ze.current??F,Y={error:u=>pe.error({...u,...Re()}),log:u=>pe.log({...u,...Re()}),performance:u=>pe.performance({...u,...Re()}),terminal:u=>pe.terminal({...u,...Re()}),startTiming:pe.startTiming,elapsed:pe.elapsed},Jt=c?`${c.slice(0,6)}\u2026(len ${c.length})`:"(empty)",Gn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(ve(`mount clientId=${Jt} env=${l??"(unset)"}\u2192${Pr??"live"} ccy=${h} sub=${P}`),ve(`ua=${Gn.slice(0,80)}${Gn.length>80?"\u2026":""}`),!c){ve("FAIL: clientId empty \u2014 gateway misconfigured"),be(!0),Y.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(!ke.current){ve("FAIL: containerRef not attached");return}Ke.current=Y.startTiming(),Y.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ot=!1,un=!1,et=()=>ot||un,Dr,Cr=!1,Dn=()=>{Dr=wc(),Dr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Cr=!0},Sr=null,yr=!1,Nn=null,Xt=!1,or=()=>{!Nn||Xt||(Xt=!0,Nn.close().catch(()=>{}))},wn=!1,Yn=!1,hn=ke.current,Jn=null,ft=null,Ln=[],kn=null,In=!1,On=!1,Ue=null,Ut=u=>{if(!u||typeof u.getBoundingClientRect!="function")return"(no rect)";let s=u.getBoundingClientRect();return`${Math.round(s.width)}\xD7${Math.round(s.height)}`},Ht=u=>{if(!u)return"(empty)";try{let s=new URL(u,typeof window>"u"?"https://localhost":window.location.href),k=s.pathname.toLowerCase();return k.includes("checkcaptcha")||k.includes("captcha")?`CAPTCHA(${s.host}${k})`:k.includes("risk")||k.includes("challenge")?`RISK(${s.host}${k})`:k.includes("smart/buttons")?`smart-buttons(${s.host})`:`${s.host}${k}`.slice(0,100)}catch{return u.slice(0,80)}},wr=u=>{let s=u.getAttribute("src"),k=u.getAttribute("srcdoc"),Se=u.getAttribute("name"),Pe=u.getAttribute("sandbox"),C=[];return s&&C.push(`src=${Ht(s)}`),k&&C.push(`srcdoc[${k.length}ch]`),!s&&!k&&C.push("src=(empty) srcdoc=(empty)"),Se&&C.push(`name=${Se.slice(0,40)}`),Pe!==null&&C.push(`sandbox="${Pe.slice(0,40)}"`),C.join(" ")},Co=u=>{if(!(u instanceof HTMLIFrameElement))return"";try{let s=u.contentDocument;if(!s)return"cd=null";let k=s.body?.children.length??0,Se=s.body?.innerHTML.length??0,Pe=s.head?.innerHTML.length??0;return`cd=same-origin readyState=${s.readyState} body[${k}children,${Se}ch] head[${Pe}ch]`}catch(s){return`cd=cross-origin(${s.message.slice(0,30)})`}},ar=[],zn=u=>{if(et())return;let s=u.message??String(u.error??"(no message)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(ve(`window:error ${s.slice(0,140)}`),ar.push(s))},Un=u=>{if(et())return;let s=u.reason instanceof Error?u.reason.message:String(u.reason??"(no reason)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(ve(`window:rejection ${s.slice(0,140)}`),ar.push(s))},sn={value:0},Nr=()=>{Jn?.disconnect(),Jn=null,ft?.disconnect(),ft=null;for(let u of Ln.splice(0))clearTimeout(u);On=!1,In&&typeof window<"u"&&(window.removeEventListener("error",zn),window.removeEventListener("unhandledrejection",Un)),In=!1},kr=()=>{if(!(In||et()||wn)){if(In=!0,ar.length=0,sn.value=0,typeof window<"u"&&(window.addEventListener("error",zn),window.addEventListener("unhandledrejection",Un)),typeof PerformanceObserver<"u")try{ft=new PerformanceObserver(u=>{if(!et())for(let s of u.getEntries()){if(!s.name.toLowerCase().includes("paypal"))continue;sn.value+=1;let k=Math.round(s.duration);ve(`net ${k}ms ${s.name.slice(0,90)}`)}}),ft.observe({type:"resource",buffered:!0})}catch{}Ue?.()}},Xn=()=>{kn&&(clearTimeout(kn),kn=null)},Zn=()=>{Nr(),Xn()},rn={setEnabled:u=>{u?kr():Nr()}};Tn.current=rn,ct.current&&kr();let m=u=>{if(!u)return!1;let s=u.toLowerCase();return s.includes("zoid destroyed")||s.includes("destroyed all components")||s.includes("window closed")||s.includes("detected container element removed")},_=u=>{if(et()||m(u))return;let s=Ir(u)??u;Tt(()=>Fe.current?.(s))},A=(u,s)=>{if(ot||yr)return;yr=!0,un=!0,Zn(),or();let k=Bc({kind:u,generationActive:!0,automaticRetryAllowed:J,automaticRetryUsed:$.current});if(k.action==="retry"){$.current=!0,ee(!1),Ve(!1),Ie(!0),Yt.current?.("retrying"),Sr=setTimeout(()=>{ot||xt(Se=>Se+1)},Rc);return}if(ee(!1),Ve(!1),Ie(!1),be(!0),k.action!=="ignore"){if(Yt.current?.("exhausted"),k.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",s);return}k.report&&Y.error({errorCode:k.report.errorCode,stage:k.report.stage,operationOutcome:k.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),xe.current||(xe.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Fc(u,s)))}};be(!1);let D=async(u,s=dt.current)=>{if(et())return;let k=s?.sessionId??e;if(mn.current){await mn.current(u,{sessionId:k,accountPatch:s?.accountPatch,nonce:s?.nonce});return}let Se=Y.startTiming();Y.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=()=>{Y.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Y.performance({stage:"processing",durationMs:Y.elapsed(Se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let C=St.current,j=s?.accountPatch?.email??Cn.current,x=s?.accountPatch?.userId??C?.customer?.id??C?.accountData?.userId??"",kt=s?.accountPatch?.firstName??C?.customer?.firstName??C?.accountData?.firstName,Dt=s?.accountPatch?.lastName??C?.customer?.lastName??C?.accountData?.lastName,me=await new oi(Be,{telemetry:!1}).processPayment(x,{sessionId:k,nonce:s?.nonce??Fn.current,paymentMethodCategory:"paypal",tokenizedData:u,accountData:{userId:x,email:j??C?.customer?.email??"",...kt?{firstName:kt}:{},...Dt?{lastName:Dt}:{},country:s?.accountPatch?.country??C?.customer?.country??C?.accountData?.country??void 0,zip:s?.accountPatch?.zip??C?.customer?.zip??C?.accountData?.zip??void 0}});if(me.ok){if(un||ot&&Kt.current)return;Pe(),Y.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Tt(()=>yn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(et())return;let Z=await me.json().catch(()=>null),re=Z?.message??"PayPal payment failed.",K=Ir(re)??re;Pe(),me.status===400&&(typeof Z?.declineCode=="string"||!Array.isArray(Z?.fields))?Y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):me.status===400||me.status===422?Y.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):Y.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Oc(me.status),failureCategory:me.status>=500?"server_error":void 0}),_(K),Tt(()=>pt.current?.(an("paypal",K,{code:Z?.code,declineCode:Z?.declineCode})));return}catch(C){if(et())return;Pe(),Y.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let j=C instanceof Error?C.message:"PayPal payment failed.",x=Ir(j)??j;_(x),Tt(()=>pt.current?.(an("paypal",x)));return}},Ce=()=>new ai("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),gt=u=>et()?Promise.reject(Ce()):Promise.resolve(u),ge=async u=>{if(et())throw Ce();Cr||Dn();let s=dt.current,k=s?.sessionId??e,Se=s?.nonce??Fn.current;Y.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Pe;try{Pe=await new oi(Be,{telemetry:!1}).createSessionIntent(k,Se??"",lt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:ii,paymentMethodId:null,intentKind:v==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Dr})}catch(C){throw Y.error({...Sc(C,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),C}if(et())throw Ce();if(Pe.provider!=="paypal"||Pe.providerObjectType!==v)throw new Error(u);return Y.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Pe.providerObjectId},W=(u,s)=>{let k=s?.nonce??Fn.current;if(!k)return;let Se=s?.sessionId??e,Pe=so(u)??fr(u)??"provider_declined";new oi(Be,{telemetry:!1}).reportSessionIntentDecline(Se,k,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Pe}).catch(()=>{})},V=Oe;ve("loadScript:scheduled (deferred 1 tick)");let w=null,X=setTimeout(()=>{if(ot){ve("loadScript:skipped (cancelled before defer ran)");return}ve("loadScript:start");let u=Pr==="live"?"production":Pr,s={};v==="subscription"?s={intent:"subscription",vault:!0}:v==="order"&&(s={intent:"capture"}),w=_c({clientId:c,currency:h,...s,...u?{environment:u}:{},...u==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let k=!1;w.then(Se=>{if(k=!0,ve(`loadScript:resolved inactive=${et()} ns=${!!Se} buttons=${!!Se?.Buttons}`),et())return;if(!Se?.Buttons){ve("FAIL: namespace missing Buttons factory"),A("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}Y.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),Y.performance({stage:"provider_ready",durationMs:Y.elapsed(Ke.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),Y.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=async(me,Z)=>{if(et()||rt.current!==V)return;let re=me.vaultSetupToken??me.subscriptionID??me.orderID??"",K=re?gn.current.get(re):yt.current.get(V);if(!(!K||!An(K.generation))&&zt(K.generation)){gn.current.delete(re),yt.current.delete(K.surfaceKey),E("approved");try{if(Ve(!0),Tt(()=>Fe.current?.(null)),!re)throw new ai("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let qe=St.current,on=Ur(jt.current??[qe?.customer?.firstName,qe?.customer?.lastName].filter(Boolean).join(" ")),De=En({email:K.accountPatch?.email?.trim()||Cn.current?.trim()||qe?.customer?.email?.trim(),firstName:K.accountPatch?.firstName?.trim()||on.firstName,lastName:K.accountPatch?.lastName?.trim()||on.lastName});if(!qo(De.email)||!(De.firstName||De.lastName))try{let Bn=Lc(await Z?.order?.get?.());De=En({email:Bn.email||De.email,firstName:Bn.firstName||De.firstName,lastName:Bn.lastName||De.lastName})}catch{}if((Ct.current||ye)&&!qo(De.email)){let Bn=await st("PayPal",De);if(!Bn)return;De=Bn}qo(De.email)&&(K.accountPatch=En({...K.accountPatch,...De}),await Ct.current?.(De));let Qn;v==="setup_token"?Qn={id:re,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:ii}:lt?Qn={id:re,isPaypal:!0,gateway:"paypal",paymentMethodType:ii}:Qn={id:re,isPaypal:!0},await D(Qn,K)}catch(qe){_(qe instanceof Error?qe.message:"PayPal capture failed.")}finally{et()||Ve(!1)}}},C=me=>{let Z=ze?()=>gt(ze):()=>ge(me);return async()=>xn(await Z())},j=Se.Buttons({style:{layout:"horizontal",height:ha,tagline:!1},...je==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(me,Z)=>{if(et()){await Z.reject();return}Dn();let re=bn.current,K={};if(re)try{let De=await re("paypal");if(et()){await Z.reject();return}if(!De.proceed){dt.current=null,yt.current.delete(V),await Z.reject();return}K={sessionId:De.sessionId,accountPatch:De.accountPatch,nonce:De.nonce}}catch(De){ve(`onClick:runBeforeButtonClick rejected msg=${(De instanceof Error?De.message:String(De)).slice(0,120)}`),dt.current=null,yt.current.delete(V),await Z.reject();return}Tt(()=>$t.current?.("paypal"));let qe=We(),on={generation:qe,surfaceKey:V,...K};dt.current=on,yt.current.set(V,on),Ze.current={...F,attempt:qe},await Z.resolve(),Y.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Y.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),$e.current=Y.startTiming()},createOrder:v==="order"?C("Failed to create PayPal order."):void 0,createSubscription:v==="subscription"?C("Failed to create PayPal subscription."):void 0,createVaultSetupToken:v==="setup_token"?async()=>xn(await ge("Failed to create PayPal setup token.")):void 0,onApprove:Pe,onCancel:()=>{if(et())return;let me=yt.current.get(V)??dt.current;me&&yt.current.delete(me.surfaceKey),dt.current=null,E("cancelled"),Y.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),de.current=!0,Fr({generation:me?.generation,remount:!0,focus:!1})},onError:me=>{if(et()||rt.current!==V)return;let Z=me instanceof Error?me.message:"PayPal failed to render.";if(ve(`onError rendered=${wn} msg=${Z.slice(0,120)}`),wn){let re=yt.current.get(V)??dt.current;if(re&&!An(re.generation)||!re&&mr())return;if(m(Z)){zt(re?.generation);return}let{errorCode:K,popupBlocked:qe,providerDeclined:on,terminalReason:De}=Nc(me);if(E(De),on){Y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:De}),W(me,re),Tt(()=>pt.current?.(an("paypal",Z))),re&&yt.current.delete(re.surfaceKey),dt.current=null,zt(re?.generation);return}Y.error({errorCode:K,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:De}),re&&yt.current.delete(re.surfaceKey),dt.current=null,Fr({generation:re?.generation,remount:!0,showRetry:!0,focus:!0}),ut(me,{code:"paypal_runtime_failed",popupBlocked:qe});return}A(m(Z)?"teardown":"pre_ready_callback",Z)}}),x=j.isEligible();if(ve(`isEligible=${x}`),Y.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!x){ee(!1),A("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Yn=!0,Nn=j,Ue=()=>{if(!In||On||et()||wn)return;On=!0,ve(`container:dims ${Ut(hn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Jn=new MutationObserver(Z=>{if(!et()){for(let re of Z)if(re.type==="childList")re.addedNodes.forEach(K=>{if(!(K instanceof Element))return;let qe=K.tagName.toLowerCase(),on=(K.getAttribute("title")??"").slice(0,40),De=qe==="iframe"?` ${wr(K)}`:"";ve(`child+ ${qe}${on?` title="${on}"`:""}${De} dims=${Ut(K)}`)});else if(re.type==="attributes"&&re.target instanceof Element){let K=re.target;if(K.tagName.toLowerCase()!=="iframe")continue;let qe=re.attributeName;(qe==="src"||qe==="srcdoc")&&ve(`attr~ iframe ${qe}=${qe==="srcdoc"?`[${(K.getAttribute("srcdoc")??"").length}ch]`:Ht(K.getAttribute("src"))} dims=${Ut(K)}`)}}}),Jn.observe(hn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let me=Z=>{if(et()||wn)return;let re=hn.querySelectorAll("iframe"),K=typeof document<"u"&&"hasStorageAccess"in document;ve(`watchdog:${Z} container=${Ut(hn)} children=${hn.childElementCount} iframes=${re.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${K} paypalNetRequests=${sn.value}`),re.forEach((qe,on)=>{let De=(qe.getAttribute("title")??"").slice(0,40);ve(` iframe[${on}] ${Ut(qe)}${De?` title="${De}"`:""} ${wr(qe)}`);let Qn=Co(qe);Qn&&ve(` ${Qn}`)}),ar.length===0&&ve(" (no PayPal/zoid window errors captured)")};Ln.push(setTimeout(()=>me("3s"),3e3)),Ln.push(setTimeout(()=>me("8s"),8e3)),Ln.push(setTimeout(()=>me("15s"),15e3))},Ue(),ve("render:start");let Dt=Y.startTiming();kn=setTimeout(()=>{et()||wn||(ve("watchdog:11s retryable render timeout"),A("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Ec);let qn=j.render(hn);(async()=>{try{if(await qn,ve(`render:resolved inactive=${et()}`),Zn(),et()){or();return}wn=!0,ee(!0),Ie(!1),Yt.current?.("ready"),Y.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),Y.performance({stage:"checkout_render",durationMs:Y.elapsed(Dt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(me){let Z=me instanceof Error?me.message:"PayPal failed to render.";ve(`render:rejected msg=${Z.slice(0,120)}`),Zn(),A(m(Z)?"teardown":"render_rejected",Z)}})()}).catch(Se=>{let Pe=Se instanceof Error?Se.message:"PayPal operation failed.";ve(`provider:failed msg=${Pe.slice(0,120)}`);let C="script_rejected";k&&m(Pe)?C="teardown":k&&Yn&&(C="render_rejected"),A(C,Pe)})},0);return()=>{ot=!0,clearTimeout(X),Sr&&clearTimeout(Sr),Zn(),Tn.current===rn&&(Tn.current=null),or(),$e.current=null,Ze.current=null}},[J,Be,c,h,l,v,je,lt,e,ze,Oe,pe,st,ye,ve,E]);let br=Ne?li("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Qe?"#fef2f2":"#f3f4f6",border:`1px solid ${Qe?"#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=${ue} failed=${Qe})`,cn.length===0?`
1
+ import{a as Et,b as mr,c as Bo,d as Za,e as Fo,f as Es,g as Ts,h as ic,i as sc}from"./chunk-M4FGYFX6.mjs";import{dropThirdPartyOnlyError as Dm}from"@flopay/shared";import{PaymentAPI as Yi}from"@flopay/js";import{FloPayError as Zo,resolveBillingApiUrl as hu,resolveButtonsLayoutTheme as vu,resolveTheme as Pu}from"@flopay/shared";import{useCallback as Fr,useEffect as vo,useMemo as Jo,useRef as Po,useState as Xo}from"react";import{Fragment as no,jsx as Yn,jsxs as As}from"react/jsx-runtime";function lc(){return As(no,{children:[As("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:[Yn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Yn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Yn("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:Yn("path",{d:"M9 18l6-6-6-6"})})]})}function cc(){return Yn(no,{children:"Go back"})}function dc(){return Yn(no,{children:"Secure card checkout"})}function Qr(e){return e!==void 0&&(e===""||e===null||e===!1)}function eo({content:e}){return Yn(no,{children:e===void 0?Yn(lc,{}):e})}function to({content:e}){return Yn(no,{children:e===void 0?Yn(cc,{}):e})}function Do({content:e}){return Yn(no,{children:e===void 0?Yn(dc,{}):e})}import{classifyTelemetryFailure as uc,FloPayError as Bn,isCardHolderNamePlaceholder as Ms,isMoneySettledOutcome as pc,isSetupIntentClientSecret as mc,isValidEmail as yc}from"@flopay/shared";var fc="Checkout is temporarily unavailable. Please try again later.";function Qa(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Bn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function gc(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 xs(){return new Bn(fc,"api_error",{code:"CheckoutInitializationFailed"})}function Bs(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card"))||t&&e?.data.paypal?.publishableKey)}function Fs(e,t){if(t&&(!(e instanceof Bn)||e.type==="authentication_error"))return Qa(e);if(!(e instanceof Bn&&gc(e))){if(!t&&!(e instanceof Bn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...uc(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Bn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Bn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function ro(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let l={...r,...i,email:i.email?.trim()||r.email?.trim()},c=Ms(l.firstName,l.lastName);if(!yc(l.email))return Promise.reject(new Bn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let h={};for(let[v,f]of Object.entries(l)){if(c&&v.endsWith("Name")||typeof f!="string")continue;let g=f.trim();g&&(h[v]=g)}return o=e.claimCheckoutSession(t,n,{accountData:h}),o.catch(()=>{}),o}}function Ds(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function ei(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Ns(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}))],r=n.reduce((i,l)=>i+(l.overrideAmount??l.totalAmount??0),0),o=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,l)=>({uuid:`synthetic-${i.type??"item"}-${l}`,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??o,metadata:i.metadata??null}))}}function Ur(e){if(Ms(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function ti(e,t){return t?{...e,...t}:e}function nn(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...i?{declineCode:i}:{}}}var hc=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function _r(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of hc)if(n.test(t))return r;return e}function qr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function oo(e){return e?.status==="authorized"||e?.status==="complete"}function Ls(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ca(e){let t=Ls(e);return new Bn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function da(e){return e instanceof Bn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function ua(e){let t=Ls(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new Bn(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function No(e,t){return e==="processing"||pc(e,t)}function Os(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function zs(e,t){let n=e;if(mc(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:l}=await n.retrieveSetupIntent(t);if(l)throw new Bn(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new Bn(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function Us(e,t="automatic"){return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}function ni(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Lo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as tu,PaymentAPI as xa,SESSION_CREATE_TELEMETRY as nu}from"@flopay/js";import{buildCheckoutDisplayData as ru,classifyTelemetryFailure as Ol,FloPayError as fn,isDetachedSessionEligible as ou,resolveBillingApiUrl as au,resolveButtonsLayoutTheme as iu,resolveIdempotencyKey as Ml,resolveTheme as zl,SDK_VERSION as Ul,telemetryStatusClass as su}from"@flopay/shared";import zi,{useCallback as Cn,useEffect as fr,useMemo as Xn,useRef as At,useState as qt}from"react";import{createContext as qs}from"react";var Jn=qs({flopay:null,paypalFlopay:null,billingApiUrl:""}),ar=qs({session:null,loading:!1,error:null});import{PaymentAPI as ii}from"@flopay/js";import{classifyTelemetryFailure as Bc,FloPayError as si,generateIdempotencyKey as Fc,isValidEmail as qo,normalizeGatewayEnvironment as Dc,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as li,SDK_VERSION as Nc}from"@flopay/shared";import{loadScript as Lc}from"@paypal/paypal-js";import{useCallback as br,useEffect as Ft,useMemo as jo,useRef as st,useState as Tr}from"react";import{isValidEmail as vc}from"@flopay/shared";import{useCallback as js,useEffect as Pc,useRef as $s,useState as Vs}from"react";import{jsx as Ks,jsxs as Oo}from"react/jsx-runtime";function An(e,t=!1){let{firstName:n,lastName:r,...o}=e,i=n?.trim(),l=r?.trim();return{...o,...i||t?{firstName:i??""}:{},...l||t?{lastName:l??""}:{}}}function ao(){let[e,t]=Vs(null),n=$s(null),r=$s(0),o=js((l,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:c}),new Promise(h=>{n.current=h})),[]),i=js(l=>{let c=n.current;n.current=null,t(null),c?.(l)},[]);return Pc(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function io({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[l,c]=Vs(e.email?.trim()??""),h=vc(l.trim());return Oo("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[Oo("div",{style:{fontWeight:700},children:["Continue with ",t]}),Oo("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Ks("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:v=>c(v.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Oo("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Ks("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Oo("button",{type:"button",disabled:!h||o,onClick:()=>{n(An({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function bc(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 jr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function vr(e){if(typeof e!="object"||e===null)return;let t=e;return jr(t.code)??jr(t.type)??jr(t.name)}function so(e){if(!(typeof e!="object"||e===null))return jr(e.decline_code)}function zo(e){return typeof e!="object"||e===null?!1:jr(e.type)?.toLowerCase()==="card_error"||so(e)!==void 0}function Pr(e){let t=bc(e)?.toLowerCase()??"",r=`${vr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Cc}from"@flopay/shared";import{useContext as pa}from"react";function Rr(){return pa(Jn).flopay}function ri(){return pa(Jn).paypalFlopay??null}function Sc(){return pa(ar)}function Ws(){return pa(Jn).billingApiUrl||Cc()}function ma(e){let t=e??(typeof navigator>"u"?"":navigator.userAgent),n=r=>({inAppBrowser:r!=="none",appFamily:r,popupCapability:"unknown"});return t?/FBAN|FBAV|FB_IAB|FBIOS/i.test(t)?n("facebook"):/Instagram/i.test(t)?n("instagram"):/musical_ly|BytedanceWebview|TikTok/i.test(t)?n("tiktok"):/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)?n("other_in_app"):/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)?n("generic_webview"):n("none"):n("none")}function ya(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}import{FLO_INSTRUMENT_SCHEMA_VERSION as wc}from"@flopay/shared";import{useCallback as Ic,useRef as fa}from"react";var kc={"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 _c(e){return e==="stripe"||e==="paypal"?e:void 0}function Rc(e){let t=_c(e.provider),n={schemaVersion:wc,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=kc[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 oi=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function lo(e,t){let n=fa(e);n.current=e;let r=fa(new Set),o=fa(t),i=fa(t);return Bo(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Ic(l=>{if(i.current!==t)return;let c=Rc(l);if(c){if(oi.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}Et(()=>n.current?.(c))}},[t])}var Ec=Symbol.for("@flopay/js.telemetry.bridge.v1"),Tc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ac(){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 Mc(e){let t=Ac(),n=(o,i)=>o?o.bind(e):i,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function ga(e){let t=globalThis[Tc];return Mc(t?.(e)??{})}function Jt(e){if(e)return e[Ec]}import{useCallback as Er,useEffect as xc,useRef as ai}from"react";function Uo(e){let t=ai(0),n=ai(null),r=ai(null),o=Er((m=r.current)=>{m?.timer&&(clearTimeout(m.timer),m.timer=null)},[]),i=Er(m=>{o();let _=t.current+1;return t.current=_,n.current=null,r.current={generation:_,method:m,timer:null,yieldedControl:!1},_},[o]),l=Er(m=>{let _=r.current;return m!==void 0&&_?.generation!==m?!1:(o(_),r.current=null,(m===void 0||n.current===m)&&(n.current=null),!0)},[o]),c=Er(m=>{let _=r.current,M=m??_?.generation??t.current;(m===void 0||_?.generation===m)&&(o(_),r.current=null),n.current=M},[o]),h=Er(m=>n.current===(m??t.current),[]),v=Er(m=>r.current?.generation===m&&n.current!==m,[]),f=Er(()=>{let m=r.current;m&&(m.yieldedControl=!0,o(m))},[o]),g=Er(()=>{let m=r.current;!m?.yieldedControl||document.visibilityState!=="visible"||(o(m),m.timer=setTimeout(()=>{m.timer=null,r.current?.generation===m.generation&&(r.current=null,n.current=m.generation,e(m.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[o,e]);return xc(()=>{let m=()=>{document.visibilityState==="visible"?g():f()};return document.addEventListener("visibilitychange",m),window.addEventListener("blur",f),window.addEventListener("focus",g),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("blur",f),window.removeEventListener("focus",g),o()}},[o,f,g]),{startAttempt:i,finishAttempt:l,invalidateAttempt:c,isAttemptInvalidated:h,isAttemptCurrent:v,generationRef:t}}import{jsx as $r,jsxs as di}from"react/jsx-runtime";var ha=45,Oc=1e3,zc=11e3,Uc=["https://www.paypal.com","https://www.sandbox.paypal.com"],ci="We couldn't open PayPal. Try again or choose another payment method.",qc={width:"100%",minHeight:ha,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 jc(e){return e.includes("No ack for postMessage init()")&&Uc.some(t=>e.includes(t))&&e.includes("10000ms")}var $c={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function Kc(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:$c[e.kind]??null}}function Vc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":jc(t)?"paypal_init_timeout":"paypal_init_failure"}function Wc(e,t=!1){return e?t?`${ci} Open this page in your system browser, then try again.`:`${ci} Allow pop-ups for this site, then try again.`:ci}function Hc(e){let t=zo(e),n=Pr(e);return t?{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:"provider_declined"}:{errorCode:n?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:n?"popup_blocked":"provider_error"}}function Gc(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function Yc(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Hs({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:l,environment:c,currency:h,isSubscription:v,providerObjectType:f,approvalPresentation:g,onTokenizedBody:m,onComplete:_,onErrorChange:M,onDecline:z,onTechnicalFailure:Be,isProcessing:oe=!1,onLoadStateChange:C,onInitializationStateChange:Y,allowAutomaticRetry:Q=!0,onButtonClick:se,runBeforeButtonClick:Fe,session:re,existingOrderId:Ke,telemetry:et,telemetryContext:ot,onInstrument:kt,debug:Ue=!1}){let De=Rr(),ue=lo(kt,e),Ee=jo(()=>{if(De)return null;let S=ga({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Nc,enabled:et!==!1});return S.setCheckoutContext(ot??{}),S.beginCheckout(ot??{}),S},[n,De,et,ot?.checkoutMode,ot?.layout]),pe=jo(()=>Jt(De),[De]);Ft(()=>()=>{Ee&&Ee.flush().catch(()=>{}).finally(()=>Ee.destroy())},[Ee]);let me=jo(()=>({error:S=>{pe?pe.error(S):Ee?.error(S),ue({class:"technical_error",errorCode:S.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":S.errorCode,requestCategory:S.requestCategory,provider:S.provider})},log:S=>{pe?pe.log(S):Ee?.log(S),ue({class:"lifecycle",name:S.name,provider:S.provider})},performance:S=>{pe?pe.performance(S):Ee?.performance(S)},terminal:S=>{pe?pe.terminal(S):Ee?.terminal(S)},startTiming:()=>pe?.now()??Ee?.now()??0,elapsed:S=>pe?.elapsed(S)??Math.max(0,(Ee?.now()??S)-S)}),[ue,pe,Ee]),Ce=st(null),ge=st(0),tt=st(null),Ye=st(null),E=st(null),J=st(!1),[Ie,ye]=Tr(!1),[L,Te]=Tr(!1),[Ae,dt]=Tr(0),Ve=st(0),[j,q]=Tr(!1),$=st(!1),je=st(!1),[Je,Se]=Tr(!1),[he,$e]=Tr(!1),{request:x,collect:Zt,finish:X}=ao(),Pt=st({sessionId:e,required:!qo(r?.trim()||re?.customer?.email?.trim())});Pt.current.sessionId!==e&&(Pt.current={sessionId:e,required:!qo(r?.trim()||re?.customer?.email?.trim())});let bt=Pt.current.required,Xe=jo(()=>n.replace(/\/+$/,""),[n]),Ne=re?.gateways?.paypal?.providerObjectType??f,u=Ne??(v?"subscription":"order"),[w]=Tr(ma),fe=re?.gateways?.paypal?.approvalPresentation??g,ve=ya(w,fe==="app_switch"?"app_switch":void 0,u),ut=Ne==="order"||Ne==="setup_token",Mt=jo(()=>JSON.stringify([Xe,l,h,c??"",u,ut,ve,e,Ke??""]),[Xe,l,h,c,Ke,u,ut,ve,e]),Me=st(Mt),Le=Me.current!==Mt,lt=st(Ue),Fn=st(null),[rn,_t]=Tr([]),Z=br(S=>{lt.current&&_t(W=>[...W,`${new Date().toISOString().slice(11,23)} ${S}`])},[]);Ft(()=>{lt.current=Ue,Ue&&Z("debug:enabled"),Fn.current?.setEnabled(Ue)},[Z,Ue]);let gn=st(m),Mn=st(_),Qt=st(M),on=st(z),Dn=st(Be),hn=st(se),Sn=st(C),jt=st(Y),le=st(i),ct=st(Fe),pt=st(re),wn=st(r),xt=st(o),Nn=st(t),mt=st(null),ft=st(new Map),cn=st(new Map),dn=st(!1);Ft(()=>(dn.current=!0,()=>{dn.current=!1}),[]),Ft(()=>{gn.current=m},[m]),Ft(()=>{le.current=i},[i]),Ft(()=>{Mn.current=_},[_]),Ft(()=>{Qt.current=M},[M]),Ft(()=>{on.current=z},[z]),Ft(()=>{Dn.current=Be},[Be]),Ft(()=>{hn.current=se},[se]),Ft(()=>{Sn.current=C},[C]),Ft(()=>{jt.current=Y},[Y]),Ft(()=>{ct.current=Fe},[Fe]),Ft(()=>{pt.current=re},[re]),Ft(()=>{wn.current=r},[r]),Ft(()=>{xt.current=o},[o]),Ft(()=>{Nn.current=t},[t]),Ft(()=>{Ve.current=Ae},[Ae]),Ft(()=>{j&&E.current?.focus()},[j,Ae]);let Dt=br(()=>{window.setTimeout(()=>{E.current?.focus()},0)},[]),Ct=br(()=>{ye(!1),dt(S=>S+1)},[]),Ln=br(()=>{q(!1),(Ce.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Ce.current)?.focus?.()},[]);Ft(()=>{!Ie||!J.current||(J.current=!1,Ln())},[Ln,Ie,Ae]);let Ht=br((S,W)=>{let B=W?.popupBlocked??Pr(S),Lt=Wc(B,w.inAppBrowser),Zn=Dn.current;if(Zn){let at=B&&w.inAppBrowser?new si(Lt,"api_error",{code:W?.code??"paypal_popup_blocked"}):S;Zn("paypal",at,W);return}Qt.current?.(Lt)},[w.inAppBrowser]),D=br(S=>{let W=tt.current,B=Ye.current;W===null||!B||(me.log({...B,name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:S}),me.performance({...B,stage:"overlay_return",durationMs:me.elapsed(W),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:S}),tt.current=null)},[me]),sr=br((S,W,B)=>{let Lt=Ye.current;D("overlay_timeout"),Lt&&me.error({...Lt,errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Ht(W,B),q(!0),Ct(),Dt()},[D,Dt,Ht,Ct,me]),{finishAttempt:Vt,generationRef:vn,invalidateAttempt:Nt,isAttemptCurrent:un,isAttemptInvalidated:On,startAttempt:pn}=Uo(sr),qe=br(()=>(q(!1),pn("paypal")),[pn]),In=br(S=>{Nt(S?.generation),S?.showRetry&&q(!0),S?.remount&&Ct(),S?.focus!==!1&&Dt()},[Dt,Nt,Ct]),an=S=>{let W=mt.current;return W&&cn.current.set(S,W),S};Ft(()=>{Me.current!==Mt&&(Me.current=Mt,$.current=!1,je.current=!1,ye(!1),Te(!1),Se(!1),jt.current?.("loading"))},[Mt]),Ft(()=>{Et(()=>Sn.current?.(Ie&&!Je))},[Ie,Je]);let mn=Dc(c);Ft(()=>{let S={attempt:vn.current+1,...w,presentationMode:ve},W=()=>Ye.current??S,B={error:p=>me.error({...p,...W()}),log:p=>me.log({...p,...W()}),performance:p=>me.performance({...p,...W()}),terminal:p=>me.terminal({...p,...W()}),startTiming:me.startTiming,elapsed:me.elapsed},Lt=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Zn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Z(`mount clientId=${Lt} env=${c??"(unset)"}\u2192${mn??"live"} ccy=${h} sub=${v}`),Z(`ua=${Zn.slice(0,80)}${Zn.length>80?"\u2026":""}`),!l){Z("FAIL: clientId empty \u2014 gateway misconfigured"),Se(!0),B.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(!Ce.current){Z("FAIL: containerRef not attached");return}ge.current=B.startTiming(),B.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let at=!1,yn=!1,nt=()=>at||yn,Dr,Sr=!1,zn=()=>{Dr=Fc(),Dr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Sr=!0},wr=null,hr=!1,Un=null,Gt=!1,lr=()=>{!Un||Gt||(Gt=!0,Un.close().catch(()=>{}))},kn=!1,Qn=!1,Pn=Ce.current,er=null,gt=null,qn=[],_n=null,Rn=!1,jn=!1,We=null,$t=p=>{if(!p||typeof p.getBoundingClientRect!="function")return"(no rect)";let s=p.getBoundingClientRect();return`${Math.round(s.width)}\xD7${Math.round(s.height)}`},Wt=p=>{if(!p)return"(empty)";try{let s=new URL(p,typeof window>"u"?"https://localhost":window.location.href),k=s.pathname.toLowerCase();return k.includes("checkcaptcha")||k.includes("captcha")?`CAPTCHA(${s.host}${k})`:k.includes("risk")||k.includes("challenge")?`RISK(${s.host}${k})`:k.includes("smart/buttons")?`smart-buttons(${s.host})`:`${s.host}${k}`.slice(0,100)}catch{return p.slice(0,80)}},Ir=p=>{let s=p.getAttribute("src"),k=p.getAttribute("srcdoc"),Re=p.getAttribute("name"),ke=p.getAttribute("sandbox"),b=[];return s&&b.push(`src=${Wt(s)}`),k&&b.push(`srcdoc[${k.length}ch]`),!s&&!k&&b.push("src=(empty) srcdoc=(empty)"),Re&&b.push(`name=${Re.slice(0,40)}`),ke!==null&&b.push(`sandbox="${ke.slice(0,40)}"`),b.join(" ")},Co=p=>{if(!(p instanceof HTMLIFrameElement))return"";try{let s=p.contentDocument;if(!s)return"cd=null";let k=s.body?.children.length??0,Re=s.body?.innerHTML.length??0,ke=s.head?.innerHTML.length??0;return`cd=same-origin readyState=${s.readyState} body[${k}children,${Re}ch] head[${ke}ch]`}catch(s){return`cd=cross-origin(${s.message.slice(0,30)})`}},cr=[],$n=p=>{if(nt())return;let s=p.message??String(p.error??"(no message)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(Z(`window:error ${s.slice(0,140)}`),cr.push(s))},Kn=p=>{if(nt())return;let s=p.reason instanceof Error?p.reason.message:String(p.reason??"(no reason)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(Z(`window:rejection ${s.slice(0,140)}`),cr.push(s))},sn={value:0},Nr=()=>{er?.disconnect(),er=null,gt?.disconnect(),gt=null;for(let p of qn.splice(0))clearTimeout(p);jn=!1,Rn&&typeof window<"u"&&(window.removeEventListener("error",$n),window.removeEventListener("unhandledrejection",Kn)),Rn=!1},kr=()=>{if(!(Rn||nt()||kn)){if(Rn=!0,cr.length=0,sn.value=0,typeof window<"u"&&(window.addEventListener("error",$n),window.addEventListener("unhandledrejection",Kn)),typeof PerformanceObserver<"u")try{gt=new PerformanceObserver(p=>{if(!nt())for(let s of p.getEntries()){if(!s.name.toLowerCase().includes("paypal"))continue;sn.value+=1;let k=Math.round(s.duration);Z(`net ${k}ms ${s.name.slice(0,90)}`)}}),gt.observe({type:"resource",buffered:!0})}catch{}We?.()}},tr=()=>{_n&&(clearTimeout(_n),_n=null)},nr=()=>{Nr(),tr()},en={setEnabled:p=>{p?kr():Nr()}};Fn.current=en,lt.current&&kr();let y=p=>{if(!p)return!1;let s=p.toLowerCase();return s.includes("zoid destroyed")||s.includes("destroyed all components")||s.includes("window closed")||s.includes("detected container element removed")},R=p=>{if(nt()||y(p))return;let s=_r(p)??p;Et(()=>Qt.current?.(s))},A=(p,s)=>{if(at||hr)return;hr=!0,yn=!0,nr(),lr();let k=Kc({kind:p,generationActive:!0,automaticRetryAllowed:Q,automaticRetryUsed:$.current});if(k.action==="retry"){$.current=!0,ye(!1),$e(!1),Te(!0),jt.current?.("retrying"),wr=setTimeout(()=>{at||dt(Re=>Re+1)},Oc);return}if(ye(!1),$e(!1),Te(!1),Se(!0),k.action!=="ignore"){if(jt.current?.("exhausted"),k.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",s);return}k.report&&B.error({errorCode:k.report.errorCode,stage:k.report.stage,operationOutcome:k.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),je.current||(je.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Vc(p,s)))}};Se(!1);let N=async(p,s=mt.current)=>{if(nt())return;let k=s?.sessionId??e;if(gn.current){await gn.current(p,{sessionId:k,accountPatch:s?.accountPatch,nonce:s?.nonce});return}let Re=B.startTiming();B.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ke=()=>{B.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"processing",durationMs:B.elapsed(Re),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let b=pt.current,K=s?.accountPatch?.email??wn.current,F=s?.accountPatch?.userId??b?.customer?.id??b?.accountData?.userId??"",wt=s?.accountPatch?.firstName??b?.customer?.firstName??b?.accountData?.firstName,Ot=s?.accountPatch?.lastName??b?.customer?.lastName??b?.accountData?.lastName,be=await new ii(Xe,{telemetry:!1}).processPayment(F,{sessionId:k,nonce:s?.nonce??Nn.current,paymentMethodCategory:"paypal",tokenizedData:p,accountData:{userId:F,email:K??b?.customer?.email??"",...wt?{firstName:wt}:{},...Ot?{lastName:Ot}:{},country:s?.accountPatch?.country??b?.customer?.country??b?.accountData?.country??void 0,zip:s?.accountPatch?.zip??b?.customer?.zip??b?.accountData?.zip??void 0}});if(be.ok){if(yn||at&&dn.current)return;ke(),B.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Et(()=>Mn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(nt())return;let te=await be.json().catch(()=>null),ae=te?.message??"PayPal payment failed.",V=_r(ae)??ae;ke(),be.status===400&&(typeof te?.declineCode=="string"||!Array.isArray(te?.fields))?B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):be.status===400||be.status===422?B.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):B.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Yc(be.status),failureCategory:be.status>=500?"server_error":void 0}),R(V),Et(()=>on.current?.(nn("paypal",V,{code:te?.code,declineCode:te?.declineCode})));return}catch(b){if(nt())return;ke(),B.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let K=b instanceof Error?b.message:"PayPal payment failed.",F=_r(K)??K;R(F),Et(()=>on.current?.(nn("paypal",F)));return}},_e=()=>new si("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ht=p=>nt()?Promise.reject(_e()):Promise.resolve(p),we=async p=>{if(nt())throw _e();Sr||zn();let s=mt.current,k=s?.sessionId??e,Re=s?.nonce??Nn.current;B.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ke;try{ke=await new ii(Xe,{telemetry:!1}).createSessionIntent(k,Re??"",ut?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:li,paymentMethodId:null,intentKind:u==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Dr})}catch(b){throw B.error({...Bc(b,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),b}if(nt())throw _e();if(ke.provider!=="paypal"||ke.providerObjectType!==u)throw new Error(p);return B.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ke.providerObjectId},G=(p,s)=>{let k=s?.nonce??Nn.current;if(!k)return;let Re=s?.sessionId??e,ke=so(p)??vr(p)??"provider_declined";new ii(Xe,{telemetry:!1}).reportSessionIntentDecline(Re,k,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ke}).catch(()=>{})},H=Ae;Z("loadScript:scheduled (deferred 1 tick)");let I=null,ee=setTimeout(()=>{if(at){Z("loadScript:skipped (cancelled before defer ran)");return}Z("loadScript:start");let p=mn==="live"?"production":mn,s={};u==="subscription"?s={intent:"subscription",vault:!0}:u==="order"&&(s={intent:"capture"}),I=Lc({clientId:l,currency:h,...s,...p?{environment:p}:{},...p==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let k=!1;I.then(Re=>{if(k=!0,Z(`loadScript:resolved inactive=${nt()} ns=${!!Re} buttons=${!!Re?.Buttons}`),nt())return;if(!Re?.Buttons){Z("FAIL: namespace missing Buttons factory"),A("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}B.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"provider_ready",durationMs:B.elapsed(ge.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),B.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let ke=async(be,te)=>{if(nt()||Ve.current!==H)return;let ae=be.vaultSetupToken??be.subscriptionID??be.orderID??"",V=ae?cn.current.get(ae):ft.current.get(H);if(!(!V||!un(V.generation))&&Vt(V.generation)){cn.current.delete(ae),ft.current.delete(V.surfaceKey),D("approved");try{if($e(!0),Et(()=>Qt.current?.(null)),!ae)throw new si("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let He=pt.current,tn=Ur(xt.current??[He?.customer?.firstName,He?.customer?.lastName].filter(Boolean).join(" ")),Oe=An({email:V.accountPatch?.email?.trim()||wn.current?.trim()||He?.customer?.email?.trim(),firstName:V.accountPatch?.firstName?.trim()||tn.firstName,lastName:V.accountPatch?.lastName?.trim()||tn.lastName});if(!qo(Oe.email)||!(Oe.firstName||Oe.lastName))try{let xn=Gc(await te?.order?.get?.());Oe=An({email:xn.email||Oe.email,firstName:xn.firstName||Oe.firstName,lastName:xn.lastName||Oe.lastName})}catch{}if((le.current||bt)&&!qo(Oe.email)){let xn=await Zt("PayPal",Oe);if(!xn)return;Oe=xn}qo(Oe.email)&&(V.accountPatch=An({...V.accountPatch,...Oe}),await le.current?.(Oe));let rr;u==="setup_token"?rr={id:ae,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:li}:ut?rr={id:ae,isPaypal:!0,gateway:"paypal",paymentMethodType:li}:rr={id:ae,isPaypal:!0},await N(rr,V)}catch(He){R(He instanceof Error?He.message:"PayPal capture failed.")}finally{nt()||$e(!1)}}},b=be=>{let te=Ke?()=>ht(Ke):()=>we(be);return async()=>an(await te())},K=Re.Buttons({style:{layout:"horizontal",height:ha,tagline:!1},...ve==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(be,te)=>{if(nt()){await te.reject();return}zn();let ae=ct.current,V={};if(ae)try{let Oe=await ae("paypal");if(nt()){await te.reject();return}if(!Oe.proceed){mt.current=null,ft.current.delete(H),await te.reject();return}V={sessionId:Oe.sessionId,accountPatch:Oe.accountPatch,nonce:Oe.nonce}}catch(Oe){Z(`onClick:runBeforeButtonClick rejected msg=${(Oe instanceof Error?Oe.message:String(Oe)).slice(0,120)}`),mt.current=null,ft.current.delete(H),await te.reject();return}Et(()=>hn.current?.("paypal"));let He=qe(),tn={generation:He,surfaceKey:H,...V};mt.current=tn,ft.current.set(H,tn),Ye.current={...S,attempt:He},await te.resolve(),B.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),B.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),tt.current=B.startTiming()},createOrder:u==="order"?b("Failed to create PayPal order."):void 0,createSubscription:u==="subscription"?b("Failed to create PayPal subscription."):void 0,createVaultSetupToken:u==="setup_token"?async()=>an(await we("Failed to create PayPal setup token.")):void 0,onApprove:ke,onCancel:()=>{if(nt())return;let be=ft.current.get(H)??mt.current;be&&ft.current.delete(be.surfaceKey),mt.current=null,D("cancelled"),B.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),J.current=!0,In({generation:be?.generation,remount:!0,focus:!1})},onError:be=>{if(nt()||Ve.current!==H)return;let te=be instanceof Error?be.message:"PayPal failed to render.";if(Z(`onError rendered=${kn} msg=${te.slice(0,120)}`),kn){let ae=ft.current.get(H)??mt.current;if(ae&&!un(ae.generation)||!ae&&On())return;if(y(te)){Vt(ae?.generation);return}let{errorCode:V,popupBlocked:He,providerDeclined:tn,terminalReason:Oe}=Hc(be);if(D(Oe),tn){B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Oe}),G(be,ae),Et(()=>on.current?.(nn("paypal",te))),ae&&ft.current.delete(ae.surfaceKey),mt.current=null,Vt(ae?.generation);return}B.error({errorCode:V,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Oe}),ae&&ft.current.delete(ae.surfaceKey),mt.current=null,In({generation:ae?.generation,remount:!0,showRetry:!0,focus:!0}),Ht(be,{code:"paypal_runtime_failed",popupBlocked:He});return}A(y(te)?"teardown":"pre_ready_callback",te)}}),F=K.isEligible();if(Z(`isEligible=${F}`),B.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!F){ye(!1),A("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Qn=!0,Un=K,We=()=>{if(!Rn||jn||nt()||kn)return;jn=!0,Z(`container:dims ${$t(Pn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(er=new MutationObserver(te=>{if(!nt()){for(let ae of te)if(ae.type==="childList")ae.addedNodes.forEach(V=>{if(!(V instanceof Element))return;let He=V.tagName.toLowerCase(),tn=(V.getAttribute("title")??"").slice(0,40),Oe=He==="iframe"?` ${Ir(V)}`:"";Z(`child+ ${He}${tn?` title="${tn}"`:""}${Oe} dims=${$t(V)}`)});else if(ae.type==="attributes"&&ae.target instanceof Element){let V=ae.target;if(V.tagName.toLowerCase()!=="iframe")continue;let He=ae.attributeName;(He==="src"||He==="srcdoc")&&Z(`attr~ iframe ${He}=${He==="srcdoc"?`[${(V.getAttribute("srcdoc")??"").length}ch]`:Wt(V.getAttribute("src"))} dims=${$t(V)}`)}}}),er.observe(Pn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let be=te=>{if(nt()||kn)return;let ae=Pn.querySelectorAll("iframe"),V=typeof document<"u"&&"hasStorageAccess"in document;Z(`watchdog:${te} container=${$t(Pn)} children=${Pn.childElementCount} iframes=${ae.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${V} paypalNetRequests=${sn.value}`),ae.forEach((He,tn)=>{let Oe=(He.getAttribute("title")??"").slice(0,40);Z(` iframe[${tn}] ${$t(He)}${Oe?` title="${Oe}"`:""} ${Ir(He)}`);let rr=Co(He);rr&&Z(` ${rr}`)}),cr.length===0&&Z(" (no PayPal/zoid window errors captured)")};qn.push(setTimeout(()=>be("3s"),3e3)),qn.push(setTimeout(()=>be("8s"),8e3)),qn.push(setTimeout(()=>be("15s"),15e3))},We(),Z("render:start");let Ot=B.startTiming();_n=setTimeout(()=>{nt()||kn||(Z("watchdog:11s retryable render timeout"),A("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},zc);let Vn=K.render(Pn);(async()=>{try{if(await Vn,Z(`render:resolved inactive=${nt()}`),nr(),nt()){lr();return}kn=!0,ye(!0),Te(!1),jt.current?.("ready"),B.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"checkout_render",durationMs:B.elapsed(Ot),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(be){let te=be instanceof Error?be.message:"PayPal failed to render.";Z(`render:rejected msg=${te.slice(0,120)}`),nr(),A(y(te)?"teardown":"render_rejected",te)}})()}).catch(Re=>{let ke=Re instanceof Error?Re.message:"PayPal operation failed.";Z(`provider:failed msg=${ke.slice(0,120)}`);let b="script_rejected";k&&y(ke)?b="teardown":k&&Qn&&(b="render_rejected"),A(b,ke)})},0);return()=>{at=!0,clearTimeout(ee),wr&&clearTimeout(wr),nr(),Fn.current===en&&(Fn.current=null),lr(),tt.current=null,Ye.current=null}},[Q,Xe,l,h,c,u,ve,ut,e,Ke,Ae,me,Zt,bt,Z,D]);let Pe=Ue?di("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Je?"#fef2f2":"#f3f4f6",border:`1px solid ${Je?"#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=${Ie} failed=${Je})`,rn.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${cn.join(`
4
- `)}`]}):null;return Qe&&!Gt?Ne?jr("div",{children:br}):null:li("div",{children:[br,g&&jr(io,{identity:g.identity,methodLabel:g.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:R,onCancel:()=>R(null)}),li("div",{"aria-hidden":O||g?!0:void 0,style:O||g?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ha},children:[!ue&&!O&&jr("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"}}),jr("div",{ref:ke,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ha,display:"flex",opacity:ue?1:0},"aria-busy":_e||ne},Oe)]},Oe),z&&jr("button",{ref:B,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:fe,style:Ac,children:"Try PayPal again"})]})}function va(e){return jr(zs,{...e})}function Us(e){return jr(zs,{...e})}import{jsx as qs,jsxs as zc}from"react/jsx-runtime";function co({children:e,margin:t,icon:n=!0,styleOverride:r}){return zc("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&&qs("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:qs("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{foldIntoProducts as Uc,resolveSessionCurrency as qc}from"@flopay/shared";function uo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var di=":idempotency-key";function ui(e,t){if(!uo())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 pi(e,t){if(!uo())return null;try{let n=window.sessionStorage.getItem(e+di);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 Pa(e,t){if(uo())try{ui(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ba(e,t){if(Pa(e,t),!!uo())try{pi(e,t)&&window.sessionStorage.removeItem(e+di)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ca(e,t,n,r){if(uo())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 Sa(e,t,n){if(uo())try{window.sessionStorage.setItem(e+di,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function ci(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function $c(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([c],[l])=>c<l?-1:c>l?1:0)),n=1779033703,r=3144134277,a=1013904242,i=2773480762;for(let c=0;c<t.length;c++){let l=t.charCodeAt(c);n=r^Math.imul(n^l,597399067),r=a^Math.imul(r^l,2869860233),a=i^Math.imul(a^l,951274213),i=n^Math.imul(i^l,2716044179)}return n=Math.imul(a^n>>>18,597399067),r=Math.imul(i^r>>>22,2869860233),a=Math.imul(n^a>>>17,951274213),i=Math.imul(r^i>>>19,2716044179),n^=r^a^i,r^=n,a^=n,i^=n,[n,r,a,i].map(c=>(c>>>0).toString(16).padStart(8,"0")).join("")}function po(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=>ci(`${a.type??""}:${a.code??a.providerItemId??a.providerPlanId??""}`,a)).sort(),i:e?.items?.map(a=>ci(a.code??a.providerItemId??"",a)).sort(),s:e?.subscriptions?.map(a=>ci(a.code??a.providerPlanId??"",a)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:$c(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function $s(e,t=!1){let n=po(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 js(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)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=qc(t.currency,t.items,t.subscriptions,t.products);if(!a||e.currency.toUpperCase()!==a.toUpperCase())return!1;let i=(t.products??Uc(t.items,t.subscriptions)).map(P=>({type:P.type,code:P.code??P.providerItemId??P.providerPlanId??"",quantity:P.quantity??1,totalAmount:P.totalAmount,overrideAmount:P.overrideAmount??null,currency:(P.currency??a).toUpperCase()})).sort((P,y)=>`${P.code}:${P.type??""}`.localeCompare(`${y.code}:${y.type??""}`)),c=e.products.map(P=>({type:P.type,code:P.code??"",quantity:P.quantity??1,totalAmount:P.totalAmount,overrideAmount:P.overrideAmount??null,currency:(P.currency??e.currency).toUpperCase()})).sort((P,y)=>`${P.code}:${P.type??""}`.localeCompare(`${y.code}:${y.type??""}`));if(i.length!==c.length)return!1;for(let[P,y]of i.entries()){let f=c[P];if(f===void 0||y.code!==f.code||y.type!==void 0&&y.type!==f.type||y.quantity!==f.quantity||y.totalAmount!==f.totalAmount||y.overrideAmount!==f.overrideAmount||y.currency!==f.currency)return!1}let l=[...t.couponCodes??[]].sort(),h=[...e.coupons??[]].sort();return l.length===h.length&&l.every((P,y)=>P===h[y])}import{resolveBillingApiUrl as jc}from"@flopay/shared";import{useEffect as Tr,useMemo as Kc,useRef as Ks,useState as Vs}from"react";import{jsx as Vc}from"react/jsx-runtime";function wa({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:a}){let[i,c]=Vs(e instanceof Promise?null:e),[l,h]=Vs(t instanceof Promise||!t?null:t),P=Ks(null),y=Ks(null),f=lo(r);Tr(()=>{f({class:"lifecycle",name:"checkout.mount"})},[f]),Tr(()=>{i&&f({class:"lifecycle",name:"sdk.initialize.ready"})},[f,i]),Tr(()=>{if(i)return Qt(i)?.subscribe?.(f)},[f,i]),Tr(()=>{if(!(!l||l===i))return Qt(l)?.subscribe?.(f)},[f,i,l]),Tr(()=>{if(!i)return;let M=Qt(i);return P.current=M?.beginCheckout()??M?.now()??0,M?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{M?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Tr(()=>{let M=!1;return e instanceof Promise?e.then(L=>{M||c(L)},()=>{M||f({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):c(e),()=>{M=!0}},[f,e]),Tr(()=>{let M=!1;if(!t){h(null);return}return t instanceof Promise?t.then(L=>{M||h(L)},()=>{M||f({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):h(t),()=>{M=!0}},[f,t]),Tr(()=>{if(!i||y.current===i)return;y.current=i;let M=Qt(i);M?.log({name:"checkout.rendered",stage:"checkout_render"}),f({class:"lifecycle",name:"checkout.rendered"}),M?.performance({stage:"checkout_render",durationMs:M.elapsed(P.current??0),durationMode:"machine"})},[f,i]);let p=jc(n?.billingApiUrl),I=Kc(()=>({flopay:i,paypalFlopay:l,billingApiUrl:p,emitInstrument:f}),[i,l,p,f]);return Vc(Hn.Provider,{value:I,children:a})}var ka="flopay_recent_completion_";function mo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ka+e,JSON.stringify(t))}catch{}}function mi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ka+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ka+e),!1):!0}catch{return!1}}import{loadFloPay as Hs,PaymentAPI as Ys}from"@flopay/js";import{classifyPaymentRejection as Hc,FloPayError as bt,isAuthorizationOnlySession as Wc,isSetupIntentClientSecret as Gc,normalizeCheckoutFailureOutcome as Ws}from"@flopay/shared";var Ko="card";async function Yc(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:i??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 Jc(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:c??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 fi(e,t){return Object.assign(e,{checkoutMethod:t})}function vr(e,t){let n=e instanceof bt?e:new bt(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 jo(e,t){try{return await e()}catch(n){throw vr(n,t)}}function Js(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 Xc(e){return e.status==="succeeded"||e.status==="declined"}async function Xs(e){if(typeof document>"u"||typeof window>"u")throw new bt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new bt("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`,i=async()=>{let y=new AbortController,f=()=>y.abort();e.signal?.aborted?y.abort():e.signal?.addEventListener("abort",f);let p=window.setTimeout(()=>y.abort(),r);try{let I=await fetch(a,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:y.signal});if(!I.ok)return{status:"unknown"};let M=await I.json().catch(()=>null);return Zc(M)}catch{return{status:"unknown"}}finally{window.clearTimeout(p),e.signal?.removeEventListener("abort",f)}},c=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 h=document.createElement("iframe");h.setAttribute("title","Card authentication"),h.setAttribute("allow","payment"),h.tabIndex=0,h.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(";"),h.src=e.nextActionRedirectUrl,l.appendChild(h),document.body.appendChild(l),h.focus();let P=null;try{P=new URL(e.billingApiUrl,window.location.href).origin}catch{P=null}try{let y=await new Promise((f,p)=>{let I=!1,M=0,L=0,Te=0,ne=!1,S=()=>{window.clearTimeout(M),window.clearInterval(L),window.clearTimeout(Te),window.removeEventListener("message",Ae),h.removeEventListener("load",J),e.signal?.removeEventListener("abort",oe)},G=async()=>{if(!(I||ne)){ne=!0;try{let ie=await i();if(I||!Xc(ie))return;I=!0,S(),f(ie)}finally{ne=!1}}},J=()=>{window.clearTimeout(Te),Te=window.setTimeout(()=>{G()},250)},oe=()=>{I||(I=!0,S(),p(new bt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Ae=ie=>{if(ie.source!==h.contentWindow||P&&ie.origin!==P)return;let ze=ie.data;!ze||typeof ze!="object"||ze.source!=="flopay-vault-3ds-return"||I||(I=!0,S(),f(null))};M=window.setTimeout(()=>{I||(I=!0,S(),p(new bt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),L=window.setInterval(()=>{G()},n),h.addEventListener("load",J),window.addEventListener("message",Ae),e.signal?.addEventListener("abort",oe),e.signal?.aborted&&oe()});return y||await i()}finally{l.parentNode?.removeChild(l),c?.isConnected&&c.focus()}}function Zc(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 Ar(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,i=Ir(a)??a;return fi(new bt(i,"api_error",{code:Ws(e?.outcome)??Ws(e?.type)??e?.gatewayErrorCode}),r)}function yi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ia(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Zs(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ia(a)))return a;let r=e?.data;if(r&&typeof r=="object"){let a=r,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||Ia(l)))return l;let c=a.gateways;if(c&&typeof c=="object"){let l=c.stripe;if(l&&typeof l=="object"){let h=l,P=[h.stripeClientSecret,h.clientSecret];for(let y of P)if(typeof y=="string"&&y.length>0&&(!t?.requirePaymentIntentClientSecret||Ia(y)))return y}}}}async function Qc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let a=Zs(r,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let l=(await new Ys(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ia(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function yo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:a,returnUrl:i,telemetry:c}){let l=e.replace(/\/+$/,""),h=t??n.id,P=r??n.clientSecret,y=n.customer?.id??n.accountData?.userId??"",f=n.customer?.email??n.accountData?.email??"",p=n.customer?.firstName??n.accountData?.firstName??"",I=n.customer?.lastName??n.accountData?.lastName??"",M=n.customer?.country??n.accountData?.country??void 0,L=n.customer?.zip??n.accountData?.zip??void 0,ne=await new Ys(l,c===!1?{telemetry:!1}:void 0).processPayment(y,{sessionId:h,nonce:P,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:y,email:f,firstName:p,lastName:I,country:M,zip:L},returnUrl:i??yi(n)});if(ne.ok){let J=typeof ne.json=="function"?await ne.json().catch(()=>null):null;return Wc(n)||J?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof J?.paymentId=="string"?J.paymentId:n.paymentId,sessionId:typeof J?.sessionId=="string"?J.sessionId:h,authorizationExpiresAt:typeof J?.authorizationExpiresAt=="string"?J.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Lo(a),checkoutMethod:Gs(a)}}:{type:"success",result:{status:"succeeded",paymentIntentId:a?.threeDSecureActionResultTokenId,paymentMethodId:Lo(a),checkoutMethod:Gs(a)}}}let S;try{S=await ne.json()}catch(J){throw new bt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:ne.status,cause:J})}if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let J=Zs(S);if(!J)throw new bt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:ne.status});return{type:S.type,threeDSecureToken:J,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let J=await Qc({billingApiUrl:l,sessionId:h,nonce:P,responseJson:S});if(J)return J;throw fi(new bt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let G=new bt(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:ne.status});throw Object.assign(G,{telemetryOutcome:Hc(ne.status,S)})}async function _a(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:a,sessionId:i,session:c,returnUrl:l,telemetry:h}){let P=t?.getRawProvider();if(!P)throw vr(new bt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw fi(new bt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let y=Gc(e.threeDSecureToken),f=null,p=e.paymentMethodId,I=await jo(()=>Yc(P,e.threeDSecureToken,y),"card");if(I){if(I.error)throw vr(new bt(I.error.message??`Failed to retrieve 3DS ${y?"setup":"payment"} status.`,"api_error",{code:I.error.code}),"card");let L=I.intent;!p&&L?.payment_method&&(typeof L.payment_method=="string"?p=L.payment_method:"id"in L.payment_method&&(p=L.payment_method.id??void 0))}let M=p?await jo(()=>Jc(P,e.threeDSecureToken,{payment_method:p,return_url:l??yi(c)??window.location.href},y),"card"):null;if(M){if(M.error)throw vr(new bt(M.error.message??"3DS authentication failed.","api_error",{code:M.error.code}),"card");f=M.intent}else{let L=await jo(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(L.error)throw vr(new bt(L.error.message??"3DS authentication failed.","api_error",{code:L.error.code}),"card");f=(y?L.setupIntent:L.paymentIntent)??null}if(f&&(f.status==="requires_capture"||f.status==="succeeded"||f.status==="processing")){let L=await yo({billingApiUrl:a,sessionId:i,session:c,telemetry:h,tokenizedData:{id:f.id,type:"card",threeDSecureActionResultTokenId:f.id},returnUrl:l});return L.type==="success"?{...L.result,paymentIntentId:L.result.paymentIntentId??f.id,paymentMethodId:L.result.paymentMethodId??p}:_a(L,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:a,sessionId:i,session:c,returnUrl:l,telemetry:h})}throw vr(new bt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let y=(n??t)?.getRawProvider();if(!y)throw vr(new bt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:p}=await jo(()=>y.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(p)throw vr(new bt(p.message??"PayPal authorization failed.","api_error",{code:p.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:f}=await jo(()=>y.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??yi(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(f)throw vr(new bt(f.message??"PayPal authorization failed.","api_error",{code:f.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new bt("Unsupported payment redirect state.","api_error")}function Vo(e){if(e instanceof bt){let r=Ir(e.message);return r&&r!==e.message?Object.assign(new bt(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=Ir(t)??t;return new bt(n,"api_error")}function gi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html;if(!t&&!n&&!r)throw new bt("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function Gs(e){if(e)return e.isPaypal?"paypal":"card"}async function hi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[c,l]=await Promise.all([Hs(e,{billingApiUrl:n,locale:r,telemetry:a}),i?Hs(i,{billingApiUrl:n,locale:r,telemetry:a}).catch(P=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",P),null)):Promise.resolve(null)]);if(!c)throw new bt("The payment provider did not initialize.","authentication_error");let h=null;return i?h=l:t&&(h=c),{flopay:c,paypalFlopay:h}}import{PaymentAPI as fo,PciVaultCardCapture as ed,toStripeAppearance as td}from"@flopay/js";import{COUNTRY_OPTIONS as nd,classifyPaymentRejection as rd,FloPayError as rr,filterStripeMethodsByCountry as od,getPostalCodeExample as ad,getPostalCodeLabel as ki,getStateFromPostalCode as el,getStateLabel as vi,getStateOptions as id,getStripeMethodDisplayName as Hr,hasVendoredStripeMethodLogo as sd,isAuthorizationOnlySession as Pi,isAVSFieldVisible as Ye,isPostalCodeSupported as ld,isSetupIntentClientSecret as cd,isValidEmail as ln,isValidPostalCode as dd,needsStripeMethodExplicitConfirm as tl,normalizeCheckoutFailureOutcome as ud,partitionStripeMethods as pd,resolveAVSConfig as md,resolveButtonsLayoutTheme as yd,resolveStripeMethodBrandVariant as fd,resolveTheme as gd,stripeExpressMethodToOptionKey as nl}from"@flopay/shared";import{ExpressCheckoutElement as ml,PaymentElement as hd,Elements as Kr,useElements as Ri,useStripe as Ei}from"@stripe/react-stripe-js";import vd,{useCallback as Je,useContext as go,useEffect as vt,useMemo as At,useRef as he,useState as ae}from"react";var Qs={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};import{Fragment as Vr,jsx as d,jsxs as Le}from"react/jsx-runtime";var dr="flopay_stripe_resume",rl="flopay_wallet_resume",yl="fw1",Pd=300*1e3,bd=900,Cd=25e3,Sd=25e3,bi={},Ci={};function wd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function fl(e){return e instanceof rr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Ea(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new fo(e,{telemetry:!1}).createSessionIntent(...n)}catch(a){throw fl(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),a}}var Ho="flopay_paypal_resume",kd=250,ol="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Ti(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Ta({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new fo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Id(e){return e instanceof rr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Si(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function gl({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,a=t?.trim(),i=Ur(n),c=i.firstName?i:Ur(r?.name);return En({email:ln(a)?a:r?.email?.trim(),firstName:c.firstName,lastName:c.lastName})}async function _d({event:e,prepared:t,email:n,billingName:r,methodLabel:a,collect:i}){let c=gl({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return ln(c.email)?c:i(a,c)}var Rd=`
3
+ ${rn.join(`
4
+ `)}`]}):null;return Je&&!Le?Ue?$r("div",{children:Pe}):null:di("div",{children:[Pe,x&&$r(io,{identity:x.identity,methodLabel:x.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:X,onCancel:()=>X(null)}),di("div",{"aria-hidden":L||x?!0:void 0,style:L||x?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ha},children:[!Ie&&!L&&$r("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"}}),$r("div",{ref:Ce,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ha,display:"flex",opacity:Ie?1:0},"aria-busy":he||oe},Ae)]},Ae),j&&$r("button",{ref:E,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Ln,style:qc,children:"Try PayPal again"})]})}function va(e){return $r(Hs,{...e})}function Gs(e){return $r(Hs,{...e})}import{jsx as Ys,jsxs as Jc}from"react/jsx-runtime";function co({children:e,margin:t,icon:n=!0,styleOverride:r}){return Jc("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&&Ys("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Ys("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{foldIntoProducts as Xc,resolveSessionCurrency as Zc}from"@flopay/shared";function uo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var pi=":idempotency-key";function mi(e,t){if(!uo())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 yi(e,t){if(!uo())return null;try{let n=window.sessionStorage.getItem(e+pi);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 Pa(e,t){if(uo())try{mi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ba(e,t){if(Pa(e,t),!!uo())try{yi(e,t)&&window.sessionStorage.removeItem(e+pi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ca(e,t,n,r){if(uo())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function Sa(e,t,n){if(uo())try{window.sessionStorage.setItem(e+pi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function ui(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Qc(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([l],[c])=>l<c?-1:l>c?1:0)),n=1779033703,r=3144134277,o=1013904242,i=2773480762;for(let l=0;l<t.length;l++){let c=t.charCodeAt(l);n=r^Math.imul(n^c,597399067),r=o^Math.imul(r^c,2869860233),o=i^Math.imul(o^c,951274213),i=n^Math.imul(i^c,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(i^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),i=Math.imul(r^i>>>19,2716044179),n^=r^o^i,r^=n,o^=n,i^=n,[n,r,o,i].map(l=>(l>>>0).toString(16).padStart(8,"0")).join("")}function po(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>ui(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ui(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ui(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Qc(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Js(e,t=!1){let n=po(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function Xs(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=Zc(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??Xc(t.items,t.subscriptions)).map(v=>({type:v.type,code:v.code??v.providerItemId??v.providerPlanId??"",quantity:v.quantity??1,totalAmount:v.totalAmount,overrideAmount:v.overrideAmount??null,currency:(v.currency??o).toUpperCase()})).sort((v,f)=>`${v.code}:${v.type??""}`.localeCompare(`${f.code}:${f.type??""}`)),l=e.products.map(v=>({type:v.type,code:v.code??"",quantity:v.quantity??1,totalAmount:v.totalAmount,overrideAmount:v.overrideAmount??null,currency:(v.currency??e.currency).toUpperCase()})).sort((v,f)=>`${v.code}:${v.type??""}`.localeCompare(`${f.code}:${f.type??""}`));if(i.length!==l.length)return!1;for(let[v,f]of i.entries()){let g=l[v];if(g===void 0||f.code!==g.code||f.type!==void 0&&f.type!==g.type||f.quantity!==g.quantity||f.totalAmount!==g.totalAmount||f.overrideAmount!==g.overrideAmount||f.currency!==g.currency)return!1}let c=[...t.couponCodes??[]].sort(),h=[...e.coupons??[]].sort();return c.length===h.length&&c.every((v,f)=>v===h[f])}import{resolveBillingApiUrl as ed}from"@flopay/shared";import{useEffect as Ar,useMemo as td,useRef as Zs,useState as Qs}from"react";import{jsx as nd}from"react/jsx-runtime";function wa({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,l]=Qs(e instanceof Promise?null:e),[c,h]=Qs(t instanceof Promise||!t?null:t),v=Zs(null),f=Zs(null),g=lo(r);Ar(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),Ar(()=>{i&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,i]),Ar(()=>{if(i)return Jt(i)?.subscribe?.(g)},[g,i]),Ar(()=>{if(!(!c||c===i))return Jt(c)?.subscribe?.(g)},[g,i,c]),Ar(()=>{if(!i)return;let M=Jt(i);return v.current=M?.beginCheckout()??M?.now()??0,M?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{M?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Ar(()=>{let M=!1;return e instanceof Promise?e.then(z=>{M||l(z)},()=>{M||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{M=!0}},[g,e]),Ar(()=>{let M=!1;if(!t){h(null);return}return t instanceof Promise?t.then(z=>{M||h(z)},()=>{M||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):h(t),()=>{M=!0}},[g,t]),Ar(()=>{if(!i||f.current===i)return;f.current=i;let M=Jt(i);M?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),M?.performance({stage:"checkout_render",durationMs:M.elapsed(v.current??0),durationMode:"machine"})},[g,i]);let m=ed(n?.billingApiUrl),_=td(()=>({flopay:i,paypalFlopay:c,billingApiUrl:m,emitInstrument:g}),[i,c,m,g]);return nd(Jn.Provider,{value:_,children:o})}var Ia="flopay_recent_completion_";function mo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Ia+e,JSON.stringify(t))}catch{}}function fi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Ia+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Ia+e),!1):!0}catch{return!1}}import{loadFloPay as el,PaymentAPI as rl}from"@flopay/js";import{classifyPaymentRejection as rd,FloPayError as St,isAuthorizationOnlySession as od,isSetupIntentClientSecret as ad,normalizeCheckoutFailureOutcome as tl}from"@flopay/shared";var Ko="card";async function id(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function sd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:o??null}}function hi(e,t){return Object.assign(e,{checkoutMethod:t})}function Cr(e,t){let n=e instanceof St?e:new St(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 $o(e,t){try{return await e()}catch(n){throw Cr(n,t)}}function ol(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 ld(e){return e.status==="succeeded"||e.status==="declined"}async function al(e){if(typeof document>"u"||typeof window>"u")throw new St("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new St("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let f=new AbortController,g=()=>f.abort();e.signal?.aborted?f.abort():e.signal?.addEventListener("abort",g);let m=window.setTimeout(()=>f.abort(),r);try{let _=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:f.signal});if(!_.ok)return{status:"unknown"};let M=await _.json().catch(()=>null);return cd(M)}catch{return{status:"unknown"}}finally{window.clearTimeout(m),e.signal?.removeEventListener("abort",g)}},l=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 h=document.createElement("iframe");h.setAttribute("title","Card authentication"),h.setAttribute("allow","payment"),h.tabIndex=0,h.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(";"),h.src=e.nextActionRedirectUrl,c.appendChild(h),document.body.appendChild(c),h.focus();let v=null;try{v=new URL(e.billingApiUrl,window.location.href).origin}catch{v=null}try{let f=await new Promise((g,m)=>{let _=!1,M=0,z=0,Be=0,oe=!1,C=()=>{window.clearTimeout(M),window.clearInterval(z),window.clearTimeout(Be),window.removeEventListener("message",Fe),h.removeEventListener("load",Q),e.signal?.removeEventListener("abort",se)},Y=async()=>{if(!(_||oe)){oe=!0;try{let re=await i();if(_||!ld(re))return;_=!0,C(),g(re)}finally{oe=!1}}},Q=()=>{window.clearTimeout(Be),Be=window.setTimeout(()=>{Y()},250)},se=()=>{_||(_=!0,C(),m(new St("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Fe=re=>{if(re.source!==h.contentWindow||v&&re.origin!==v)return;let Ke=re.data;!Ke||typeof Ke!="object"||Ke.source!=="flopay-vault-3ds-return"||_||(_=!0,C(),g(null))};M=window.setTimeout(()=>{_||(_=!0,C(),m(new St("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),z=window.setInterval(()=>{Y()},n),h.addEventListener("load",Q),window.addEventListener("message",Fe),e.signal?.addEventListener("abort",se),e.signal?.aborted&&se()});return f||await i()}finally{c.parentNode?.removeChild(c),l?.isConnected&&l.focus()}}function cd(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 Mr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,i=_r(o)??o;return hi(new St(i,"api_error",{code:tl(e?.outcome)??tl(e?.type)??e?.gatewayErrorCode}),r)}function gi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ka(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function il(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ka(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,i=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let c of i)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||ka(c)))return c;let l=o.gateways;if(l&&typeof l=="object"){let c=l.stripe;if(c&&typeof c=="object"){let h=c,v=[h.stripeClientSecret,h.clientSecret];for(let f of v)if(typeof f=="string"&&f.length>0&&(!t?.requirePaymentIntentClientSecret||ka(f)))return f}}}}async function dd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=il(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let c=(await new rl(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ka(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function yo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:l}){let c=e.replace(/\/+$/,""),h=t??n.id,v=r??n.clientSecret,f=n.customer?.id??n.accountData?.userId??"",g=n.customer?.email??n.accountData?.email??"",m=n.customer?.firstName??n.accountData?.firstName??"",_=n.customer?.lastName??n.accountData?.lastName??"",M=n.customer?.country??n.accountData?.country??void 0,z=n.customer?.zip??n.accountData?.zip??void 0,oe=await new rl(c,l===!1?{telemetry:!1}:void 0).processPayment(f,{sessionId:h,nonce:v,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:f,email:g,firstName:m,lastName:_,country:M,zip:z},returnUrl:i??gi(n)});if(oe.ok){let Q=typeof oe.json=="function"?await oe.json().catch(()=>null):null;return od(n)||Q?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof Q?.paymentId=="string"?Q.paymentId:n.paymentId,sessionId:typeof Q?.sessionId=="string"?Q.sessionId:h,authorizationExpiresAt:typeof Q?.authorizationExpiresAt=="string"?Q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Lo(o),checkoutMethod:nl(o)}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Lo(o),checkoutMethod:nl(o)}}}let C;try{C=await oe.json()}catch(Q){throw new St("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:oe.status,cause:Q})}if(C?.type==="paypal_redirect_required"||C?.type==="3ds_required"){let Q=il(C);if(!Q)throw new St("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:oe.status});return{type:C.type,threeDSecureToken:Q,paymentMethodId:C.paymentMethodId}}if(C?.gatewayErrorCode==="authentication_required"){let Q=await dd({billingApiUrl:c,sessionId:h,nonce:v,responseJson:C});if(Q)return Q;throw hi(new St("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let Y=new St(C?.message??"Payment failed. Please try again.","api_error",{code:C?.code??C?.gatewayErrorCode,declineCode:C?.declineCode??C?.gatewayDeclineReason,statusCode:oe.status});throw Object.assign(Y,{telemetryOutcome:rd(oe.status,C)})}async function _a(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:l,returnUrl:c,telemetry:h}){let v=t?.getRawProvider();if(!v)throw Cr(new St("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw hi(new St("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let f=ad(e.threeDSecureToken),g=null,m=e.paymentMethodId,_=await $o(()=>id(v,e.threeDSecureToken,f),"card");if(_){if(_.error)throw Cr(new St(_.error.message??`Failed to retrieve 3DS ${f?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let z=_.intent;!m&&z?.payment_method&&(typeof z.payment_method=="string"?m=z.payment_method:"id"in z.payment_method&&(m=z.payment_method.id??void 0))}let M=m?await $o(()=>sd(v,e.threeDSecureToken,{payment_method:m,return_url:c??gi(l)??window.location.href},f),"card"):null;if(M){if(M.error)throw Cr(new St(M.error.message??"3DS authentication failed.","api_error",{code:M.error.code}),"card");g=M.intent}else{let z=await $o(()=>v.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(z.error)throw Cr(new St(z.error.message??"3DS authentication failed.","api_error",{code:z.error.code}),"card");g=(f?z.setupIntent:z.paymentIntent)??null}if(g&&(g.status==="requires_capture"||g.status==="succeeded"||g.status==="processing")){let z=await yo({billingApiUrl:o,sessionId:i,session:l,telemetry:h,tokenizedData:{id:g.id,type:"card",threeDSecureActionResultTokenId:g.id},returnUrl:c});return z.type==="success"?{...z.result,paymentIntentId:z.result.paymentIntentId??g.id,paymentMethodId:z.result.paymentMethodId??m}:_a(z,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:l,returnUrl:c,telemetry:h})}throw Cr(new St("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let f=(n??t)?.getRawProvider();if(!f)throw Cr(new St("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:m}=await $o(()=>f.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(m)throw Cr(new St(m.message??"PayPal authorization failed.","api_error",{code:m.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:g}=await $o(()=>f.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??gi(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(g)throw Cr(new St(g.message??"PayPal authorization failed.","api_error",{code:g.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new St("Unsupported payment redirect state.","api_error")}function Vo(e){if(e instanceof St){let r=_r(e.message);return r&&r!==e.message?Object.assign(new St(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=_r(t)??t;return new St(n,"api_error")}function vi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html;if(!t&&!n&&!r)throw new St("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function nl(e){if(e)return e.isPaypal?"paypal":"card"}async function Pi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[l,c]=await Promise.all([el(e,{billingApiUrl:n,locale:r,telemetry:o}),i?el(i,{billingApiUrl:n,locale:r,telemetry:o}).catch(v=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",v),null)):Promise.resolve(null)]);if(!l)throw new St("The payment provider did not initialize.","authentication_error");let h=null;return i?h=c:t&&(h=l),{flopay:l,paypalFlopay:h}}import{PaymentAPI as fo,PciVaultCardCapture as ud,toStripeAppearance as pd}from"@flopay/js";import{COUNTRY_OPTIONS as md,classifyPaymentRejection as yd,FloPayError as ir,filterStripeMethodsByCountry as fd,getPostalCodeExample as gd,getPostalCodeLabel as Ti,getStateFromPostalCode as ll,getStateLabel as bi,getStateOptions as hd,getStripeMethodDisplayName as Wr,hasVendoredStripeMethodLogo as vd,isAuthorizationOnlySession as Ci,isAVSFieldVisible as Qe,isPostalCodeSupported as Pd,isSetupIntentClientSecret as Si,isValidEmail as ln,isValidPostalCode as bd,needsStripeMethodExplicitConfirm as cl,normalizeCheckoutFailureOutcome as Cd,partitionStripeMethods as Sd,randomUuidV4 as wd,resolveAVSConfig as Id,resolveButtonsLayoutTheme as kd,resolveStripeMethodBrandVariant as _d,resolveTheme as Rd,stripeExpressMethodToOptionKey as dl}from"@flopay/shared";import{ExpressCheckoutElement as wl,PaymentElement as Ed,Elements as Kr,useElements as Bi,useStripe as Fi}from"@stripe/react-stripe-js";import Td,{useCallback as Ge,useContext as go,useEffect as yt,useMemo as Tt,useRef as de,useState as ie}from"react";var sl={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};import{Fragment as Vr,jsx as d,jsxs as ze}from"react/jsx-runtime";var yr="flopay_stripe_resume",ul="flopay_wallet_resume",Il="fw1",Ad="fw2",kl=300*1e3,Md=900,xd=25e3,Bd=25e3,Fd=1e4,wi={},Ii={};function Di(e){return`${Ad}:${e}`}function Ra(e){if(typeof window>"u")return!1;try{return localStorage.removeItem(Di(e)),!0}catch{return!1}}function Ea(e,t){if(typeof window>"u")return null;let n=Di(e);try{let r=localStorage.getItem(n);if(!r)return null;let o=JSON.parse(r);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>kl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Ra(e),null):o}catch{return Ra(e),null}}function Dd(e){if(typeof window>"u")return!1;try{return localStorage.setItem(Di(e.sessionId),JSON.stringify(e)),!0}catch{return!1}}function pl(e,t,n){let r=Ea(e,t);return!r||r.clientSecret!==n?!1:Ra(e)}function ki(e,t,n){if(typeof window>"u")return;Ea(e,t)?.clientSecret===n&&Ra(e)}function Nd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function _i(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let r=n?e.status==="succeeded":No(e.status),o=Nd(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function ml(e,t,n){let r=null;try{return await Promise.race([zs(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},Fd),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Ld(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function _l(e){return e instanceof ir&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Aa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new fo(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw _l(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Wo="flopay_paypal_resume",Od=250,yl="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Ni(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Ma({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new fo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function zd(e){return e instanceof ir&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ri(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Rl({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=Ur(n),l=i.firstName?i:Ur(r?.name);return An({email:ln(o)?o:r?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Ud({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let l=Rl({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return ln(l.email)?l:i(o,l)}var qd=`
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 @@ ${cn.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
- `,Ra=44,Wo=180,al=`flopay-card-enter ${Wo}ms cubic-bezier(0, 0, 0.2, 1) both`,il=`flopay-card-exit ${Wo}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Ed=`flopay-buttons-enter ${Wo}ms cubic-bezier(0, 0, 0.2, 1) both`,Td=`flopay-buttons-exit ${Wo}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Ad(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Ai(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 Md={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function xd(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var hl={width:"100%",minHeight:Ra,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 Bd(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function sl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ii(e){return e==="paypal"?"PayPal":Hr(e)}function Fd(e,t){let n=`We couldn't open ${Ii(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Dd(e){let t=ad(e);return`Enter a valid ${ki(e)}${t?` (e.g. ${t})`:""}`}function Nd(e,t,n){let r=ld(e),a=t.trim(),i=n&&r,c=i&&!a,l=i&&!!a&&!dd(e,a);return{visible:n,supported:r,required:i,empty:c,malformed:l}}function Ld(e,t){let n=e.trim(),r=t&&!n,a=t&&!!n&&!ln(n);return{required:t,empty:r,malformed:a,value:n}}function ll(e,t){return t instanceof rr?t:new rr(t instanceof Error?t.message:`${Bd(e)} before-click hook failed.`,"validation_error")}function wi(){return d("style",{children:Rd})}function Od(e){return typeof e=="number"?`${e}px`:e}function vl(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Pl({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:Le("div",{style:{position:"relative",minHeight:44},children:[d("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),d("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function cl(e){return e!=="unavailable"&&e!=="load_error"}function Mi(e){return d(Ud,{...e})}function dl({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:a,onErrorChange:i,isProcessing:c=!1,onButtonClick:l,onDecline:h,onTechnicalFailure:P,runBeforeButtonClick:y,billingName:f,onBuyerIdentityReady:p,onLoadStateChange:I,placeholderBorderRadius:M}){let L=_r(),{emitInstrument:Te}=go(Hn),ne=Ei(),S=Ri(),[G,J]=ae("loading");vt(()=>{I?.(G)},[G,I]);let[oe,Ae]=ae(!1),ie=!ln(n?.trim())||!f?.trim(),{request:ze,collect:Xe,finish:nt}=ao(),_t=he(!1),Ne=he(null),Me=he(null),[le,we]=ae(0),[ce,pe]=ae(!1),ke=he(!1),Ke=he(new Map),{startAttempt:$e,finishAttempt:Ze,invalidateAttempt:B,isAttemptInvalidated:de,isAttemptCurrent:ue}=Uo((z,q,$)=>{P?.(z,q,{...$,popupBlocked:$?.popupBlocked??gr(q)}),pe(!0),we(xe=>xe+1)});vt(()=>{ce&&Me.current?.focus()},[ce,le]);let ee=Je(()=>{we(z=>z+1)},[]),O=Je((z,q,$)=>{B($),P?.("paypal",z,{code:q,popupBlocked:gr(z)}),pe(!0),ee()},[B,P,ee]),Ie=Je(()=>{window.setTimeout(()=>{(Ne.current?.querySelector("iframe")??Ne.current)?.focus()},0)},[]);vt(()=>{ke.current&&(ke.current=!1,Ie())},[Ie,le]);let Oe=Je(()=>{pe(!1),i?.(null),Ie()},[Ie,i]);vt(()=>{if(!ne||_t.current)return;let z=new URLSearchParams(window.location.search),q=z.get("payment_intent"),$=z.get("payment_intent_client_secret"),xe=z.get("redirect_status");if(!q||!$)return;_t.current=!0;let Qe;try{let _e=localStorage.getItem(Ho);if(_e){let Ve=JSON.parse(_e);Ve.clientSecret===$&&(Qe={...Ve.accountPatch?{accountPatch:Ve.accountPatch}:{},...Ve.sessionId?{sessionId:Ve.sessionId}:{},...Ve.nonce?{nonce:Ve.nonce}:{}})}}catch{}try{localStorage.removeItem(Ho)}catch{}let be=new URL(window.location.href);be.searchParams.delete("payment_intent"),be.searchParams.delete("payment_intent_client_secret"),be.searchParams.delete("redirect_status"),window.history.replaceState({},"",be.toString()),(async()=>{try{if(Ae(!0),xe==="failed"){let g="PayPal payment was declined. Please try again.";i?.(g),h?.(an("paypal",g));return}let{paymentIntent:_e,error:Ve}=await ne.retrievePaymentIntent($);if(Ve){i?.(Ve.message??"Failed to retrieve PayPal payment status.");return}if(_e&&(_e.status==="requires_capture"||_e.status==="succeeded")){let g=typeof _e.payment_method=="string"?_e.payment_method:_e.payment_method?.id;a({id:g??_e.id,type:"card",threeDSecureActionResultTokenId:_e.id,isPaypal:!0},Qe)}else{let g="PayPal payment was not completed. Please try again.";i?.(g),h?.(an("paypal",g))}}catch(_e){i?.(_e instanceof Error?_e.message:"Failed to complete PayPal payment.")}finally{Ae(!1)}})()},[ne,a,i,h]);let xt=Je(async z=>{if(c||oe){z.reject();return}let q=y?await y("paypal"):{proceed:!0};if(!q.proceed){Ke.current.delete(le),z.reject();return}let $=$e("paypal");Ke.current.set(le,{generation:$,accountPatch:q.accountPatch,sessionId:q.sessionId,nonce:q.nonce}),pe(!1),l?.("paypal"),z.resolve()},[c,l,y,$e,oe,le]),rt=Je(async z=>{if(!ne||!S)return;let q=Ke.current.get(le);if(q&&!ue(q.generation)){Ke.current.delete(le);return}if(!q&&de()||q&&!Ze(q.generation))return;q||Ze();let $=q??null;if(Ke.current.delete(le),!$&&y){let g=await y("paypal");if(!g.proceed){z.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}$={accountPatch:g.accountPatch,sessionId:g.sessionId,nonce:g.nonce}}let xe=$?.sessionId??e,Qe=$?.nonce??t,be=await _d({event:z,prepared:$,email:n,billingName:f,methodLabel:"PayPal",collect:Xe});if(!be){z.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let _e=be.email,Ve={...$?.accountPatch,...En(be,!0)};try{if(Ae(!0),i?.(null),!xe||!ln(_e))throw new Error("Missing sessionId or email for PayPal payment");await p?.(be);let g=ne.createPaymentMethod,{error:st,paymentMethod:R}=await g({type:"paypal"});if(st){O(st,"stripe_paypal_create_payment_method_failed",q?.generation),z.paymentFailed({reason:"fail"});return}let H=await Ea(r,Te,xe,Qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:R?.id??null,intentKind:"payment"});if(H.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ye=H.clientSecret,Be={return_url:window.location.href};if(R?.id&&(Be.payment_method=R.id),typeof window<"u")try{localStorage.setItem(Ho,JSON.stringify({clientSecret:ye,sessionId:xe,nonce:Qe,accountPatch:Ve}))}catch{}let{error:He,paymentIntent:Pt}=await ne.confirmPayment({clientSecret:ye,confirmParams:Be,redirect:"if_required"});if(He){if(typeof window<"u")try{localStorage.removeItem(Ho)}catch{}if(zo(He)){let T=He.message??"Your payment was declined.";i?.(T),h?.(an("paypal",T,{code:fr(He),declineCode:so(He)})),await Ta({billingApiUrl:r,sessionId:xe,nonce:Qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:fr(He)??"provider_declined"}})}else O(He,"stripe_paypal_confirm_failed",q?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Ho)}catch{}let v=typeof Pt?.payment_method=="string"?Pt.payment_method:Pt?.payment_method?.id;a({id:v??Pt?.id,type:"card",threeDSecureActionResultTokenId:Pt?.id,isPaypal:!0},{accountPatch:Ve,paymentMethodCategory:"paypal",sessionId:xe,nonce:Qe});return}catch(g){O(g,"stripe_paypal_failed",q?.generation)}finally{Ae(!1)}},[ne,S,e,t,n,f,Xe,p,r,Te,a,i,h,y,O,Ze,ue,de,le]);return Le(Vr,{children:[d(Pl,{state:G,placeholderTestId:"flopay-paypal-placeholder",borderRadius:M,children:Le("div",{ref:Ne,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[ce&&d("button",{ref:Me,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Oe,style:hl,children:"Try PayPal again"}),ze&&d(io,{identity:ze.identity,methodLabel:ze.methodLabel,onComplete:nt,onCancel:()=>nt(null)},ze.id),d("div",{style:{display:ze?"none":void 0},children:d(ml,{onReady:z=>J(vl(z,["paypal"])),onLoadError:()=>{J("load_error"),Ti(Qt(L),"paypal","paypal")},onClick:xt,onConfirm:rt,onCancel:()=>{let z=Ke.current.get(le);Ke.current.delete(le),Qt(L)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),B(z?.generation),pe(!1),ke.current=!0,ee()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ie,emailRequired:ie,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},le)})]})}),oe&&d(cr,{status:"processing"})]})}function ul({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:a,expressMethods:i,onTokenizedBody:c,onErrorChange:l,onButtonClick:h,onDecline:P,onTechnicalFailure:y,runBeforeButtonClick:f,billingName:p,onBuyerIdentityReady:I,onLoadStateChange:M,placeholderBorderRadius:L}){let Te=_r(),{emitInstrument:ne}=go(Hn),S=Ei(),G=Ri(),[J,oe]=ae("loading");vt(()=>{M?.(J)},[J,M]);let[Ae,ie]=ae(!1),ze=he(!ln(n?.trim())||!p?.trim()).current,{request:Xe,collect:nt,finish:_t}=ao(),Ne=he(null),Me=he(null),[le,we]=ae(0),[ce,pe]=ae(!1),[ke,Ke]=ae("google_pay"),$e=he(!1),Ze=he("google_pay"),B=he("google_pay"),de=he(null),ue=he(new Set);vt(()=>()=>{for(let g of ue.current)window.clearTimeout(g);ue.current.clear()},[]);let ee=he(new Map),{startAttempt:O,finishAttempt:Ie,invalidateAttempt:Oe,isAttemptInvalidated:xt,isAttemptCurrent:rt,generationRef:z}=Uo((g,st,R)=>{y?.(g,st,{...R,popupBlocked:R?.popupBlocked??gr(st)}),Ke(g),pe(!0),we(H=>H+1)});vt(()=>{ce&&Me.current?.focus()},[ce,le]);let q=Je(()=>{we(g=>g+1)},[]),$=Je((g,st,R,H)=>{Oe(H),y?.(g,st,{code:R,popupBlocked:gr(st)}),Ke(g),pe(!0),q()},[Oe,y,q]),xe=Je(()=>{window.setTimeout(()=>{(Ne.current?.querySelector("iframe")??Ne.current)?.focus()},0)},[]);vt(()=>{$e.current&&($e.current=!1,xe())},[xe,le]);let Qe=Je(()=>{pe(!1),l?.(null),xe()},[xe,l]),be=Je(async g=>{let st=!1,R=Fe=>{st||(st=!0,g.paymentFailed({reason:"fail",...Fe?{message:Fe}:{}}))};if(!S||!G){R();return}let H=ee.current.get(le);if(H&&!rt(H.generation)){ee.current.delete(le),R();return}if(!H&&xt()){R();return}if(H&&!Ie(H.generation)){R();return}H||Ie();let ye=g.expressPaymentType??H?.method??Ze.current,Be=H??null,He=sl(ye),Pt;ye==="apple_pay"?Pt="apple_pay":ye==="google_pay"&&(Pt="google_pay");let v=H?.generation??z.current,T=Qt(Te),mt=T?.now()??globalThis.performance?.now()??Date.now(),je=new AbortController,lt=!1,Wt=!1,te=null,Gt=e,ct="processing",Tn="other",cn="provider_runtime",Rt,ve=new Promise((Fe,pt)=>{Rt=pt}),mn=window.setTimeout(()=>{lt=!0,je.abort(),Rt(bi)},Cd),yn=async(Fe,pt,fn)=>{ct=Fe,Tn=pt,cn=pt==="intent_create"||pt==="session_claim"?"transport_error":"provider_runtime";let $t=T?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([fn,ve])}finally{let dn=T?.now()??globalThis.performance?.now()??Date.now();T?.performance({stage:Fe,durationMs:Math.max(0,dn-$t),durationMode:"machine",requestCategory:pt,paymentMethodCategory:"wallet",provider:"stripe",...lt?{statusClass:"timeout"}:{}})}};try{if(ie(!0),l?.(null),!Be&&f){let fe=await yn("processing","other",f(He));if(!fe.proceed){R();return}Be={accountPatch:fe.accountPatch,sessionId:fe.sessionId,nonce:fe.nonce}}let Fe=Be?.sessionId??e;Gt=Fe;let pt=Be?.nonce??t,fn=de.current??Be?.accountPatch,$t=gl({event:g,fallbackEmail:fn?.email??n,fallbackName:[fn?.firstName,fn?.lastName].join(" ").trim()||p});if(!ln($t.email)){R("Buyer details are required."),nt(Ii(ye),$t).then(fe=>{fe&&(de.current=fe)});return}de.current=null;let dn={...Be?.accountPatch,...En($t,!0)};await yn("processing","session_claim",Promise.resolve(I?.($t)));let{error:Yt}=await yn("tokenization","provider_sdk",G.submit());if(Yt){R(),$(ye,Yt,"stripe_wallet_submit_failed",H?.generation);return}if(!Fe)throw new Error("Missing sessionId or email for payment.");let Ct=await yn("processing","intent_create",Ea(r,ne,Fe,pt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ye,paymentMethodId:null,intentKind:a},{signal:je.signal}));if(Ct.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let bn=Ct.clientSecret;window.clearTimeout(mn),Wt=!0,T?.performance({stage:"callback",durationMs:Math.max(0,(T?.now()??globalThis.performance?.now()??Date.now())-mt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let St=T?.now()??globalThis.performance?.now()??Date.now(),Cn={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Pt?{walletType:Pt}:{},attempt:v},jt=!1;T?.log({name:"payment.provider_confirmation.started",...Cn}),te=window.setTimeout(()=>{te!==null&&ue.current.delete(te),jt=!0;let fe=T?.now()??globalThis.performance?.now()??Date.now();T?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Cn,operationOutcome:"watchdog_expired",checkoutSessionId:Fe,durationMs:Math.max(0,fe-St),statusClass:"timeout",failureCategory:"provider_runtime"}),T?.flush?.().catch(()=>{})},Sd),ue.current.add(te);let Fn=fe=>{te!==null&&(window.clearTimeout(te),ue.current.delete(te),te=null);let ut=T?.now()??globalThis.performance?.now()??Date.now(),E=Math.max(0,ut-St),Vt=fe;return jt&&(fe==="resolved"?Vt="resolved_late":fe==="returned_error"?Vt="returned_error_late":Vt="rejected_late"),T?.log({name:"payment.provider_confirmation.returned",...Cn,operationOutcome:Vt}),T?.performance({...Cn,durationMs:E,durationMode:"buyer",operationOutcome:Vt}),{durationMs:E,operationOutcome:Vt}},dt=!1,yt=fe=>{if(!fe||typeof fe!="object")return null;let ut=fe;if(ut.error)return null;let E=ut.setupIntent??ut.paymentIntent,Vt=E?.id,zt=E?.status,Sn=ut.setupIntent?zt==="succeeded":No(typeof zt=="string"?zt:void 0),nn=E?.payment_method,An=null;return typeof nn=="string"?An=nn:typeof nn?.id=="string"&&(An=nn.id),!Sn||typeof Vt!="string"||!An?null:{intentId:Vt,paymentMethodId:An}},gn=fe=>{if(dt||H&&z.current!==H.generation)return;let ut=yt(fe);if(!ut)return;let{intentId:E,paymentMethodId:Vt}=ut;dt=!0;let zt=`${yl}:${Fe}`;if(typeof window<"u")try{localStorage.setItem(zt,JSON.stringify({createdAt:Date.now(),sessionId:Fe,nonce:pt,accountPatch:dn,paymentMethodId:Vt,providerIntentId:E,paymentMethodType:ye}))}catch{}try{c({id:Vt,type:"card",threeDSecureActionResultTokenId:E},{accountPatch:dn,paymentMethodCategory:"wallet",sessionId:Fe,nonce:pt})}finally{if(typeof window<"u")try{localStorage.removeItem(zt)}catch{}}},Kt,tn;try{let fe=await(cd(bn)?S.confirmSetup({elements:G,clientSecret:bn,redirect:"if_required"}):S.confirmPayment({elements:G,clientSecret:bn,redirect:"if_required"}));if(!fe||typeof fe!="object"||(Kt=fe,!Kt.error&&!yt(Kt)))throw Ci;tn=Fn(Kt.error?"returned_error":"resolved")}catch(fe){let ut=fe===Ci,E=Fn(ut?"returned_error":"rejected");throw T?.error({...ut?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:ei(fe),...Cn,operationOutcome:E.operationOutcome,checkoutSessionId:Fe,durationMs:E.durationMs,statusClass:"unknown"}),fe}let wt=Kt.error;if(wt){if(zo(wt)){let fe=wt.message??"Your payment was declined.";R(fe),l?.(fe),P?.(an(He,fe,{code:fr(wt),declineCode:so(wt)})),Ta({billingApiUrl:r,sessionId:Fe,nonce:pt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ye,providerDeclineReason:fr(wt)??"provider_declined",...Ct.intentKind==="payment"&&Ct.providerObjectId.startsWith("pi_")?{providerIntentId:Ct.providerObjectId}:{}}})}else T?.error({...ei(wt),...Cn,operationOutcome:tn.operationOutcome,checkoutSessionId:Fe,durationMs:tn.durationMs,statusClass:"unknown"}),R(),$(ye,wt,"stripe_wallet_confirm_failed",H?.generation);return}if(gn(Kt),!dt)throw new Error("Invalid provider returned for APM intent")}catch(Fe){if(Fe===bi){let pt=T?.now()??globalThis.performance?.now()??Date.now();T?.error({errorCode:wd(Tn),stage:ct,requestCategory:Tn,paymentMethodCategory:"wallet",provider:"stripe",...Pt?{walletType:Pt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Gt,durationMs:Math.max(0,pt-mt),statusClass:"timeout",failureCategory:cn,attempt:v}),T?.flush?.().catch(()=>{})}R(),$(ye,Fe,Fe===bi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",H?.generation)}finally{if(window.clearTimeout(mn),te!==null&&(window.clearTimeout(te),ue.current.delete(te)),!Wt){let Fe=T?.now()??globalThis.performance?.now()??Date.now();T?.performance({stage:"callback",durationMs:Math.max(0,Fe-mt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...lt?{statusClass:"timeout"}:{}})}ie(!1)}},[S,G,e,t,n,p,nt,I,r,ne,a,c,l,P,f,$,Ie,rt,xt,z,Te,le]),_e=At(()=>{let g=["applePay","googlePay","paypal","link","amazonPay","klarna"],st=new Set(["applePay","googlePay"]),R=new Set(i.map(nl)),H={};for(let ye of g)R.has(ye)?H[ye]=st.has(ye)?"always":"auto":H[ye]="never";return H},[i]),Ve=At(()=>i.map(nl),[i]);return Le(Vr,{children:[d(Pl,{state:J,placeholderTestId:"flopay-wallet-placeholder",borderRadius:L,children:Le("div",{ref:Ne,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[ce&&Le("button",{ref:Me,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Qe,style:hl,children:["Try ",Ii(ke)," again"]}),Xe&&d(io,{identity:Xe.identity,methodLabel:Xe.methodLabel,onComplete:_t,onCancel:()=>_t(null)},Xe.id),d("div",{style:{display:Xe?"none":void 0},children:d(ml,{onReady:g=>{oe(vl(g,Ve))},onLoadError:g=>{oe("load_error"),Ti(Qt(Te),"stripe","wallet")},onClick:async g=>{Ze.current=g.expressPaymentType,B.current=sl(g.expressPaymentType);let st=!0,R=window.setTimeout(()=>{st=!1,g.reject()},bd),H=f?await f(B.current):{proceed:!0};if(window.clearTimeout(R),!st)return;if(!H.proceed){ee.current.delete(le),g.reject();return}let ye=O(g.expressPaymentType);ee.current.set(le,{generation:ye,method:g.expressPaymentType,accountPatch:H.accountPatch,sessionId:H.sessionId,nonce:H.nonce}),pe(!1),h?.(B.current),g.resolve()},onConfirm:be,onCancel:()=>{let g=ee.current.get(le);ee.current.delete(le),Qt(Te)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Oe(g?.generation),pe(!1),$e.current=!0,q()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:_e,emailRequired:ze,billingAddressRequired:ze,layout:{maxColumns:1,overflow:"never"}}},le)})]})}),Ae&&d(cr,{status:"processing"})]})}function bl(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function zd({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:a=!1,hasNextStep:i=!1,onClick:c,backgroundColor:l,borderColor:h,textColor:P,borderRadius:y,fontFamily:f}){let p=fd(e,t),I=Qs[e],[M,L]=ae(!1),Te=!!I&&!M,ne=p?.backgroundColor??l??"#ffffff",S=p?.borderColor??h??"#d1d5db",G=p?.textColor??P??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&c()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Ra,padding:"0 1rem",backgroundColor:ne,color:G,border:`1px solid ${S}`,borderRadius:y??8,fontSize:"0.95rem",fontWeight:600,fontFamily:f,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?d("span",{style:{margin:"0 auto"},children:`Connecting to ${Hr(e)}\u2026`}):Le(Vr,{children:[Le("span",{style:{display:"inline-flex",alignItems:"center",gap:sd(e)?8:0},children:[Te?d("img",{src:I,alt:"","aria-hidden":"true",onError:()=>L(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!Te&&p?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:p.logoSvg}}):null,d("span",{children:Hr(e)})]}),i&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:G,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 _i({method:e,sessionId:t,nonce:n,email:r,billingName:a,onBuyerIdentityReady:i,billingApiUrl:c,onTokenizedBody:l,onErrorChange:h,onDecline:P,onCancel:y,runBeforeButtonClick:f,onButtonClick:p,isProcessing:I,submitButtonColor:M,submitButtonBorderRadius:L,submitButtonStyle:Te,errorText:ne}){let S=_r(),{emitInstrument:G}=go(Hn),J=Ei(),oe=Ri(),[Ae,ie]=ae(!1),ze=he(!1),[Xe,nt]=ae(!1),[_t,Ne]=ae("loading"),[Me,le]=ae(""),we=!ln(r?.trim()),ce=!we||ln(Me.trim()),pe=Je(async()=>{if(!J||!oe||I||ze.current||!Xe)return;ze.current=!0,ie(!0);let ke=f?await f("card"):{proceed:!0};if(!ke.proceed){ze.current=!1,ie(!1);return}p?.("card");let Ke=ke.sessionId??t,$e=ke.nonce??n,Ze=Ur(a?.trim()),B=En({email:ke.accountPatch?.email?.trim()||r?.trim()||Me.trim(),firstName:ke.accountPatch?.firstName?.trim()||Ze.firstName,lastName:ke.accountPatch?.lastName?.trim()||Ze.lastName}),de=B.email,ue=En({...ke.accountPatch,...B});try{if(h?.(null),!ln(de))throw new Error("A valid email address is required for payment.");await i?.(B);let ee=await oe.submit();if(ee.error){h?.(ee.error.message??"Payment failed.");return}let O=[B.firstName,B.lastName].filter(Boolean).join(" "),Ie=await J.createPaymentMethod({elements:oe,params:{billing_details:{email:de,...O?{name:O}:{}}}});if(Ie.error||!Ie.paymentMethod){h?.(Ie.error?.message??"Failed to create payment method.");return}let Oe=Ie.paymentMethod;if(!Ke||!de)throw new Error("Missing sessionId or email for payment.");let xt=Oe.type||e,rt=await Ea(c,G,Ke,$e??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:xt,paymentMethodId:null,intentKind:"payment"});if(rt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let z=rt.clientSecret;if(typeof window<"u")try{localStorage.setItem(dr,JSON.stringify({clientSecret:z,sessionId:Ke,nonce:$e,accountPatch:ue,paymentMethodId:Oe.id,paymentMethodType:Oe.type??e,gateway:"stripe"}))}catch{}let{error:q,paymentIntent:$}=await J.confirmPayment({clientSecret:z,confirmParams:{return_url:window.location.href,payment_method:Oe.id},redirect:"if_required"});if(q){if(typeof window<"u")try{localStorage.removeItem(dr)}catch{}let be=q.message??"Payment failed.";h?.(be),P?.(an("card",be,{code:q.code})),await Ta({billingApiUrl:c,sessionId:Ke,nonce:$e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:q.code??"provider_declined"}});return}let xe=$?.status;if(!No(xe)){if(typeof window<"u")try{localStorage.removeItem(dr)}catch{}let be=xe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(be),P?.(an("card",be,{code:xe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(dr)}catch{}let Qe=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;l({id:Qe??Oe.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:Oe.type??e},{accountPatch:ue,paymentMethodCategory:"apm",sessionId:Ke,nonce:$e})}catch(ee){h?.(ee instanceof Error?ee.message:"Payment failed. Please try again.")}finally{ze.current=!1,ie(!1)}},[J,oe,I,Xe,f,p,t,n,r,a,Me,i,c,G,e,l,h,P]);return Le("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[we&&d("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:we&&Le("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",d("input",{type:"email",autoComplete:"email",required:!0,value:Me,onChange:ke=>le(ke.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),d(hd,{onReady:()=>Ne("ready"),onLoadError:()=>{Ne("load_error"),Ti(Qt(S),"stripe","apm")},onChange:ke=>{nt(!!ke.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...ln(r?.trim())?{email:r?.trim()}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{pe()},disabled:!Xe||!ce||Ae||I||_t!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:M,color:"white",border:"none",borderRadius:L,fontSize:"1rem",fontWeight:600,cursor:!Xe||!ce||Ae||I||_t!=="ready"?"not-allowed":"pointer",opacity:!Xe||!ce||Ae||I||_t!=="ready"?.5:1,transition:"opacity 120ms ease-out",...Te??{}},children:Ae?"Processing\u2026":`Pay with ${Hr(e)}`}),ne&&d(co,{margin:"0.75rem 0 0",children:ne})]})}function pl({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:c,stripeInstance:l,paymentElementBaseOptions:h,onTokenizedBody:P,onErrorChange:y,onButtonClick:f,onDecline:p,runBeforeButtonClick:I,onLoadStateChange:M,isProcessing:L=!1,submitButtonColor:Te="#4A49FF",submitButtonBorderRadius:ne=8,submitButtonStyle:S,buttonAppearance:G,themeId:J,onExpandApm:oe,expandedApmMethod:Ae}){let{emitInstrument:ie}=go(Hn),[ze,Xe]=ae(null),[nt,_t]=ae(null),Ne=he(!1),{request:Me,collect:le,finish:we}=ao();vt(()=>{c.length>0&&l?M?.("ready"):l||M?.("loading")},[c.length,l,M]);let ce=Je(async B=>{if(!l||Ne.current||L)return;Ne.current=!0,_t(B);let de=I?await I("card"):{proceed:!0};if(!de.proceed){Ne.current=!1,_t(null);return}f?.("card");let ue=de.sessionId??e,ee=de.nonce??t,O=Ur([de.accountPatch?.firstName,de.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ie=En({email:de.accountPatch?.email?.trim()||n?.trim(),firstName:de.accountPatch?.firstName?.trim()||O.firstName,lastName:de.accountPatch?.lastName?.trim()||O.lastName});if(!ln(Ie.email)){_t(null);let rt=await le(Hr(B),Ie);if(!rt){Ne.current=!1;return}Ie=rt,_t(B)}let Oe=Ie.email,xt=En({...de.accountPatch,...Ie});try{if(y?.(null),!ue||!ln(Oe))throw new Error("Missing sessionId or email for payment.");await a?.(Ie);let rt=await Ea(i,ie,ue,ee??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:B,paymentMethodId:null,intentKind:"payment"});if(rt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let z=rt.clientSecret;if(typeof window<"u")try{localStorage.setItem(dr,JSON.stringify({clientSecret:z,sessionId:ue,nonce:ee,accountPatch:xt,paymentMethodType:B,gateway:"stripe"}))}catch{}let{error:q,paymentIntent:$}=await l.confirmPayment({clientSecret:z,confirmParams:{return_url:window.location.href,payment_method_data:{type:B,billing_details:{name:[Ie.firstName,Ie.lastName].filter(Boolean).join(" "),...Oe?{email:Oe}:{}}}},redirect:"if_required"});if(q){if(typeof window<"u")try{localStorage.removeItem(dr)}catch{}let be=q.message??"Payment failed.";y?.(be),p?.(an("card",be,{code:q.code})),await Ta({billingApiUrl:i,sessionId:ue,nonce:ee,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:B,providerDeclineReason:q.code??"provider_declined"}});return}let xe=$?.status;if(!No(xe)){if(typeof window<"u")try{localStorage.removeItem(dr)}catch{}let be=xe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.(be),p?.(an("card",be,{code:xe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(dr)}catch{}let Qe=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;P({id:Qe??$?.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:B},{accountPatch:xt,paymentMethodCategory:"apm",sessionId:ue,nonce:ee})}catch(rt){y?.(rt instanceof Error?rt.message:"Payment failed. Please try again.")}finally{Ne.current=!1,_t(null)}},[l,L,I,f,e,t,n,le,i,ie,r,a,P,y,p]),[pe,ke]=ae(null),Ke=oe?Ae??null:pe,$e=Je(B=>{Ne.current||L||Ke&&Ke!==B||(tl(B)?oe?oe(B):ke(B):ce(B))},[Ke,L,ce,oe]),Ze=At(()=>pe?bl(h,pe):null,[pe,h]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Me?d(io,{identity:Me.identity,methodLabel:Me.methodLabel,onComplete:we,onCancel:()=>we(null)},Me.id):c.map(B=>{let de=Ae===B,ue=nt===B,ee=nt!==null&&nt!==B||Ae!=null&&Ae!==B;return Le(vd.Fragment,{children:[d(zd,{method:B,themeId:J,submitting:ue,disabled:ee,highlighted:de,hasNextStep:tl(B),onClick:()=>$e(B),backgroundColor:G?.backgroundColor,borderColor:G?.borderColor,textColor:G?.textColor,borderRadius:G?.borderRadius,fontFamily:G?.fontFamily}),!oe&&pe===B&&Ze&&l&&d(Kr,{stripe:l,options:Ze,children:d(_i,{method:B,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:P,onErrorChange:y,onDecline:p,onCancel:()=>ke(null),runBeforeButtonClick:I,onButtonClick:f,isProcessing:L,submitButtonColor:Te,submitButtonBorderRadius:ne,submitButtonStyle:S})},B)]},B)})})}function Ud({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:a,userId:i,onComplete:c,onError:l,onDecline:h,onTokenizedBody:P,firstName:y,lastName:f,chv:p,className:I,isProcessing:M,error:L,onErrorChange:Te,showPayPal:ne=!0,showStripe:S=!0,enabledPaymentMethods:G,enabledPaymentMethodCountries:J,showApplePay:oe=!0,showGooglePay:Ae=!0,layout:ie="default",theme:ze,buttonsTheme:Xe,buttonsStyles:nt,appearance:_t,cardButtonContent:Ne,cardBackButtonContent:Me,cardTitleContent:le,showSecurityFooter:we,onButtonClick:ce,onBeforeButtonClick:pe,onBuyerIdentityReady:ke,enableAVS:Ke,cardFieldOrder:$e,cardPreFormSlot:Ze,avsLayout:B="row",country:de,zip:ue,addressLine1:ee,addressLine2:O,city:Ie,state:Oe,onCountryChange:xt,onZipChange:rt,avsCheck:z,checkoutType:q,checkoutLayout:$,totalAmount:xe=0,currency:Qe="usd",initialCardOpen:be=!1,directPaypal:_e,isSubscription:Ve=!1,session:g,dataAttachmentPending:st=!1,dataAttachmentRequiresIdentity:R=!1,debug:H=!1}){let ye=_r(),Be=ti(),He=go(nr),{emitInstrument:Pt}=go(Hn),v=g??He.session,T=v?.gateways?.paypal?.providerObjectType??_e?.providerObjectType,mt=st||He.claimPending===!0,je=R||He.claimRequiresIdentity===!0,lt=mt&&!je,Wt=Os(),te=n||Wt,[Gt,ct]=ae(!1),[Tn,cn]=ae(null),[Rt,ve]=ae(de??"US"),[mn,yn]=ae(ue??""),[Fe,pt]=ae(ee??""),[fn,$t]=ae(O??""),[dn,Yt]=ae(Ie??""),[Ct,bn]=ae(Oe??""),[St,Cn]=ae(""),[jt,Fn]=ae({}),dt=he(ue??""),yt=he(de??"US"),gn=he(ee??""),Kt=he(O??""),tn=he(Ie??""),wt=he(Oe??""),fe=he(""),ut=he({});vt(()=>{let o=(b,N,Ee,U,at)=>{if(ut.current[b])return;let Ge=N?.trim();!Ge||Ge===Ee.current||(Ee.current=Ge,U(Ge),at?.(Ge))};o("country",de,yt,ve,xt),o("zip",ue,dt,yn,rt),o("addressLine1",ee,gn,pt),o("addressLine2",O,Kt,$t),o("city",Ie,tn,Yt),o("state",Oe,wt,bn)},[de,ue,ee,O,Ie,Oe,xt,rt]);let E=At(()=>md(Ke),[Ke]),Vt=E!==null,zt=At(()=>Pi(g),[g]),Sn=!!g?.vault?.html,nn=!!g?.gateways?.pcivault,mr=!!(g?.gateways?.stripe?.enabledPaymentMethods??G)?.includes("card"),Mn=Sn||mr||nn,We=!!(S&&Mn&&e),[Fr,xn]=ae(()=>ie!=="buttons"||be?e??null:null),[Pr,br]=ae(0),F=ie!=="buttons"||be||!!e&&Fr===e,Re=g?.captureMethod,Y=he(ye);vt(()=>{Y.current=ye},[ye]);let[Jt,Gn]=ae(null);vt(()=>{if(!We||!e||!F){Gn(null);return}let o=Y.current?Y.current.cardCapture({sessionId:e,captureMethod:Re}):new ed({sessionId:e,captureMethod:Re,billingApiUrl:te,telemetry:r});return Gn({sessionId:e,captureMethod:Re,billingApiUrl:te,telemetry:r,capture:o}),()=>{o.unmount()}},[We,e,F,Re,te,r]);let ot=We&&e&&F&&Jt?.sessionId===e&&Jt.captureMethod===Re&&Jt.billingApiUrl===te&&Jt.telemetry===r?Jt.capture:null,un=At(()=>{let o=Rt,b=E?Ye(E.postal_code,o):!1;return Nd(o,mn,b)},[E,Rt,mn]),{avsInvalid:et,invalidAvsFields:Dr}=At(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!We||!E)return{avsInvalid:!1,invalidAvsFields:o};let b=Rt,N=(at,Ge)=>Ye(at,b)&&!Ge.trim(),Ee={line1:N(E.address_line_1,Fe),city:N(E.city,dn),state:N(E.state,Ct),zip:un.empty||un.malformed};return{avsInvalid:Ee.line1||Ee.city||Ee.state||Ee.zip,invalidAvsFields:Ee}},[We,E,Rt,Fe,dn,Ct,un]),[Cr,Dn]=ae(!1),[Sr,yr]=ae(!1),[Nn,Xt]=ae(!1),[or,wn]=ae({line1:!1,city:!1,state:!1}),Yn=he(!1),hn=he({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Jn=he(!1),ft=Je(o=>{hn.current[o]=!0,Jn.current=!0},[]),Ln=Je(o=>!Yn.current&&hn.current[o],[]),kn=Je(o=>{Ln(o)&&wn(b=>b[o]?b:{...b,[o]:!0})},[Ln]),[In,On]=ae(()=>Si(g?.vault)),[Ue,Ut]=ae(be&&Mn?"card":"buttons"),[Ht,wr]=ae(null),Co=Ue==="expanding"||Ue==="card",ar=g?.gateways?.stripe?"stripe":void 0,zn=Je(()=>{Pt?.({class:"card_surface",provider:ar})},[ar,Pt]),Un=he(null),sn=Je(o=>{Un.current&&clearTimeout(Un.current),Un.current=setTimeout(()=>{Un.current=null,o()},Wo)},[]);vt(()=>()=>{Un.current&&clearTimeout(Un.current)},[]);let Nr=Je(()=>{zn(),xn(e??null),br(o=>o+1),Ut("expanding"),sn(()=>Ut("card"))},[sn,zn,e]),kr=Je(()=>{Ut("collapsing"),sn(()=>Ut("buttons"))},[sn]),Xn=Je(o=>{wr(o),Ut("apm-expanding"),sn(()=>Ut("apm-form"))},[sn]),Zn=Je(()=>{Ut("apm-collapsing"),sn(()=>{Ut("buttons"),wr(null)})},[sn]);vt(()=>{ie==="buttons"&&be&&Mn&&(xn(e??null),Ut("card"))},[ie,be,Mn,e]);let[rn,m]=ae(null),_=he(!1),A=he(null),D=he("idle"),[Ce,gt]=ae(null),ge=he(Ce);vt(()=>{ge.current=Ce},[Ce]);let W=he(null),V=At(()=>{if(ke||He.claimBuyerIdentity||g?.buyerIdentified!==!1||!e||!t)return;let o=`${te}|${e}|${t}`;W.current?.key!==o&&(W.current={key:o,claim:ro(new fo(te,{telemetry:!1}),e,t,{...i?{userId:i}:{},...y?{firstName:y}:{},...f?{lastName:f}:{}})});let b=W.current.claim;return async N=>{await b(N)}},[ke,He.claimBuyerIdentity,g?.buyerIdentified,e,t,te,i,y,f]),w=ke??He.claimBuyerIdentity??V,X=L??Tn,u=At(()=>gd(ze),[ze]),s=At(()=>{let o=u?.buttonsLayout??yd(Xe);return nt?{...o,...nt,cardButton:{...o.cardButton,...nt.cardButton},cardFormContainer:{...o.cardFormContainer,...nt.cardFormContainer},backButton:{...o.backButton,...nt.backButton},backButtonIcon:{...o.backButtonIcon,...nt.backButtonIcon},submitButton:{...o.submitButton,...nt.submitButton},title:{...o.title,...nt.title}}:o},[u,Xe,nt]),k=_t??u?.appearance,Se=At(()=>Ss({appearance:k,buttonsStyles:s,layout:ie}),[k,s,ie]),Pe=He.inlineSessionPatchProcessing??!1,C=(M??Gt)||Pe,j=te.replace(/\/+$/,""),x=At(()=>Qa({userId:i,email:a,firstName:y,lastName:f,country:de,zip:ue},jt),[i,a,y,f,de,ue,jt]),kt=[x.firstName,x.lastName].filter(o=>!!o?.trim()).join(" "),Dt=!ln(x.email?.trim()),qn=he(null);We&&qn.current===null&&(qn.current=Dt);let me=We&&(qn.current??Dt),Z=At(()=>Ld(St,me),[St,me]),re=Z.empty||Z.malformed,K=At(()=>ye?ye.getRawProvider():null,[ye]),qe=At(()=>Be?Be.getRawProvider():null,[Be]),on=xe||100,De=Qe.toLowerCase(),Qn=At(()=>k?td(k):null,[k]),Bn=Qn,ji=At(()=>{let o=Qn??{},b=o.rules??{};return{...o,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[Qn]),Ki=At(()=>({...xs(xe,g?.captureMethod),currency:De,...Bn?{appearance:Bn}:null}),[xe,De,g?.captureMethod,Bn]),Vi=At(()=>({mode:"payment",amount:on,currency:De,captureMethod:"manual",setupFutureUsage:"off_session",...Bn?{appearance:Bn}:null}),[on,De,Bn]),se=Je(o=>{cn(o),Te?.(o)},[Te]),Fa=he(""),[Hi,xl]=ae(!1),Da=Je(()=>{xl(!0)},[]);vt(()=>{if(!We||!me||!w||!Hi||re||Fa.current)return;let o=En({email:ln(x.email?.trim())?x.email?.trim():fe.current.trim(),firstName:x.firstName?.trim(),lastName:x.lastName?.trim()});Fa.current=JSON.stringify(o),Fn(b=>({...b,...o})),Promise.resolve(w(o)).catch(b=>{Fa.current="",se(b instanceof Error?b.message:"Failed to attach buyer details.")})},[We,me,w,Hi,re,x.email,x.firstName,x.lastName,se]),vt(()=>{!We||!ot||ot.setCardFieldOrder?.($e??null,E==null&&!me)},[We,ot,$e,E,me]),vt(()=>{(Ue==="expanding"||Ue==="collapsing"||Ue==="apm-expanding"||Ue==="apm-collapsing")&&se(null)},[Ue,se]);let ir=Je((o,b,N)=>{h?.(an(o,b,N))},[h]),Wr=Je((o,b,N)=>{let Ee=N?.popupBlocked??gr(b),U=Fd(o,Ee),at=$r(N?.code)??fr(b)??"external_payment_method_failed",Ge=new rr(U,"api_error",{code:"external_payment_method_failed",param:o});m(null),ie==="buttons"&&(Ut("buttons"),wr(null)),se(U),l?.(Ge),console.error("[FloPay] External payment method failed:",{method:o,code:at,popupBlocked:Ee})},[ie,l,se]);vt(()=>{if(!We||!e){On(null);return}let o=Si(g?.vault);if(o){On(o);return}if(!F){On(null);return}On(null);let b=!0;return new fo(j).getVaultCapture(e,t).then(N=>{if(!b)return;let Ee=Si(N);Ee?On(Ee):se("Failed to load the secure card form.")}).catch(N=>{b&&se(N instanceof Error?N.message:"Failed to load the secure card form.")}),()=>{b=!1}},[We,F,Pr,e,g?.vault,j,t,se]);let sr=he({onComplete:c,onError:l,updateError:se,emitDecline:ir,resolvedAccount:x,avsConfig:E,avsCheckProp:z,sessionId:e,nonce:t,baseUrl:j,captureMethod:g?.captureMethod,paymentId:g?.paymentId,authorizationExpiresAt:g?.authorizationExpiresAt});sr.current={onComplete:c,onError:l,updateError:se,emitDecline:ir,resolvedAccount:x,avsConfig:E,avsCheckProp:z,sessionId:e,nonce:t,baseUrl:j,captureMethod:g?.captureMethod,paymentId:g?.paymentId,authorizationExpiresAt:g?.authorizationExpiresAt};let Na=he(!1),Wi=Je(()=>{let o=sr.current,b=o.resolvedAccount.email?.trim(),N=ln(b)?b:fe.current.trim();if(!ln(N))return null;let Ee=o.resolvedAccount.firstName?.trim(),U=o.resolvedAccount.lastName?.trim(),at=yt.current||o.resolvedAccount.country||"US",Ge=o.avsConfig?Ye(o.avsConfig.state,at):!1,tt=o.avsConfig?Ye(o.avsConfig.address_line_1,at):!1,It=o.avsConfig?Ye(o.avsConfig.postal_code,at):!1,Bt=o.avsConfig?Ye(o.avsConfig.city,at):!1,Lt=o.avsConfig?Ye(o.avsConfig.address_line_2,at):!1,Et=tt&&!Ge&&It?el(at,(dt.current??"").trim()):null,jn=Ge?wt.current:Et;return{accountData:{userId:o.resolvedAccount.userId??"",email:N,...Ee?{firstName:Ee}:{},...U?{lastName:U}:{},...It&&dt.current?{zip:dt.current}:{},...Bt&&tn.current?{city:tn.current}:{},...jn?{state:jn}:{},...tt&&gn.current?{addressLine1:gn.current}:{},...Lt&&Kt.current?{addressLine2:Kt.current}:{},country:at},...o.avsCheckProp===void 0?{}:{avsCheck:o.avsCheckProp},...o.avsConfig?{avsConfig:{country:Ye(o.avsConfig.country,at),postal_code:It,address_line_1:tt,address_line_2:Lt,city:Bt,state:Ge}}:{}}},[]),Gi=he(mt);Gi.current=mt,vt(()=>{mt||X!==ol||sr.current.updateError(null)},[mt,X]),vt(()=>{!We||!ot||ot.setSubmitGate?.(et||mt||re)},[We,ot,et,mt,re]),vt(()=>{if(!We||!ot)return;Na.current=!1;let o=null,b=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,D.current="idle",m(null)},400)},N=ot.on("submitting",()=>{Dn(!0),A.current&&clearTimeout(A.current),D.current="validation-window",A.current=setTimeout(()=>{A.current=null,D.current==="validation-window"&&(D.current="processing")},kd),m("processing");let tt=sr.current;if(!tt.sessionId||!tt.nonce)return;let It=Wi();if(!It){tt.updateError("Enter a valid email address."),D.current="idle",m(null);return}new fo(tt.baseUrl).patchAccountSnapshot(tt.sessionId,tt.nonce,It,{telemetryMode:"best_effort"}).catch(Bt=>{if(!Id(Bt))return;let Lt=Bt instanceof Error?Bt.message:"Please check your billing address and try again.";tt.updateError(Lt),D.current="idle",m(null),tt.onError?.(Bt instanceof rr?Bt:new rr(Lt,"api_error"))})}),Ee=ot.on("complete",async tt=>{if(mo(tt.sessionId??sr.current.sessionId),D.current="terminal",m("success"),await new Promise(Lt=>setTimeout(Lt,600)),Na.current)return;Na.current=!0;let It=sr.current,Bt=Pi(It)||tt.outcome==="authorized";sr.current.onComplete?.(Bt?{status:"authorized",paymentIntentId:tt.intentId,paymentId:tt.paymentId??It.paymentId,sessionId:tt.sessionId??It.sessionId,authorizationExpiresAt:tt.authorizationExpiresAt??It.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:tt.intentId,checkoutMethod:"card"})}),U=ot.on("decline",tt=>{let It=sr.current,Bt=tt.message??"Your payment was declined. Please try another card or contact your bank.";D.current="terminal",It.updateError(Bt),m("error");let Lt=tt.failureOutcome??ud(tt.declineReason)??"authorization_declined";It.emitDecline("card",Bt,{code:Lt,declineCode:Lt}),b()}),at=ot.on("error",tt=>{let It=sr.current,Bt=tt.message??"There was a problem processing your payment. Please try again.";D.current="terminal",It.updateError(Bt),m("error"),It.onError?.(new rr(Bt,"api_error",{code:tt.failureOutcome??"capture_failed"})),b()}),Ge=ot.on("blocked",()=>{if(!Gi.current){Dn(!0);return}Da(),sr.current.updateError(ol)});return()=>{o&&(clearTimeout(o),o=null),A.current&&(clearTimeout(A.current),A.current=null),D.current="idle",m(null),N(),Ee(),U(),at(),Ge()}},[We,ot,Da,Wi]);let lr=!!_e?.clientId,So=Array.isArray(G),Qo=So&&G.length>0,Bl=So&&G.includes("paypal"),{expressMethods:ea,paymentElementMethods:wo}=At(()=>pd(G,{excludePaypal:lr}),[G,lr]),Yi=lr||!!Be,Fl=At(()=>Yi?ea.filter(o=>o!=="paypal"):ea,[ea,Yi]),Dl=At(()=>{let o=[];return oe&&o.push("apple_pay"),Ae&&o.push("google_pay"),o},[oe,Ae]),Gr=So?Fl:Dl,Nl=S&&Gr.length>0,La=Vt?Rt:de,ta=At(()=>{let o=La?.trim().toUpperCase();return o?J?wo.filter(b=>{let N=J[b];return!N||N.length===0||N.includes(o)}):od(wo,La):wo},[wo,La,J]),Oa=At(()=>({mode:"payment",amount:on,currency:De,paymentMethodCreation:"manual",appearance:ji}),[on,De,ji]),[Ji,Xi]=ae("loading"),[Zi,Qi]=ae("loading"),[es,ts]=ae("loading"),[Ll,za]=ae(!1),[ns,Ua]=ae("loading"),[qa,Ol]=ae();vt(()=>{Ol(ma())},[]);let na=qa?.inAppBrowser,ra=qa?ya(qa,_e?.approvalPresentation,T??(Ve?"subscription":"order")):"popup",rs=ne&&(lr||(So?Bl:na===!1)),os=S&&Nl,ko=(!lt||!!He.waitForDataAttachment)&&rs&&lr,as=ns==="retrying"||ns==="exhausted",Io=!lt&&rs&&!!qe&&(!lr||as),Yr=!lt&&os&&!!K,_o=!lt&&S&&Qo&&ta.length>0&&!!K,zl=ko&&!as?Ll:Io&&cl(Ji),Ul=Yr&&cl(Zi),ql=_o&&es!=="load_error",is=o=>o==="loading"||o==="ready",ss=ko||Io&&is(Ji)||Yr&&is(Zi)||_o&&es!=="load_error",oa=he(!1);vt(()=>{if(!oa.current){if(!S&&!ne){oa.current=!0;let o=new rr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(o),se(o.message)}else if(!S&&ne&&!lr&&!qe){oa.current=!0;let o=new rr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(o),se(o.message)}else if(na!==void 0&&!lt&&!Mn&&!ss){oa.current=!0;let o=new rr("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"});l?.(o),se(o.message)}}},[S,ne,lr,qe,na,lt,Mn,ss,l,se]);let ls=he(!1);vt(()=>{if(ls.current||!Qo)return;let o=[];oe!==!0&&o.push("showApplePay"),Ae!==!0&&o.push("showGooglePay"),o.length!==0&&(ls.current=!0,console.warn(`[FloPay] ${o.join(" / ")} ${o.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Qo,oe,Ae]);let cs=Je((o,b)=>He.applyInlineSessionPatch?He.applyInlineSessionPatch(o).then(N=>({error:null,sessionId:N.sessionId||e,nonce:N.session?.clientSecret||t})).catch(N=>{let Ee=ll(b,N);return se(Ee.message),l?.(Ee),{error:Ee,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[He.applyInlineSessionPatch,t,l,e,se]),er=Je(async o=>{if(o!=="card"&&lt&&await He.waitForDataAttachment?.(),!pe)return{proceed:!0};try{let b=await pe({method:o,sessionId:e||void 0,createSession:He.inlineSessionDraft});if(b===!1)return{proceed:!1};if(b&&typeof b=="object"){b.account&&Fn(Ee=>({...Ee??{},...b.account}));let N=await cs(b,o);return N.error?{proceed:!1,accountPatch:b.account}:{proceed:!0,accountPatch:b.account,sessionId:N.sessionId,nonce:N.nonce}}return{proceed:!0}}catch(b){let N=ll(o,b);return se(N.message),l?.(N),{proceed:!1}}},[cs,He.inlineSessionDraft,He.waitForDataAttachment,lt,pe,l,e,se]),ds=Je(async(o,b)=>{if(_.current)return;_.current=!0,ct(!0),m("processing"),se(null);let N=b?.sessionId??e,Ee=b?.nonce??t,U=Qa(x,b?.accountPatch),at=b?.completionPaymentMethodId??Lo(o),Ge=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o,tt=Ad(o),It=()=>{Pt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:tt})};try{let Lt=await new fo(j).processPayment(U.userId??"",{sessionId:N,nonce:Ee,paymentMethodCategory:b?.paymentMethodCategory??xd(o),tokenizedData:Ge,accountData:{...b?.accountPatch,userId:U.userId??"",email:U.email??"",firstName:U.firstName||void 0,lastName:U.lastName||void 0,...E?(()=>{let ht=yt.current,Kn=Ye(E.state,ht),vn=Ye(E.address_line_1,ht),Zt=Ye(E.postal_code,ht),zr=vn&&!Kn&&Zt?el(ht,(dt.current??"").trim()):null,xo=Kn?wt.current:zr;return{country:ht,...Zt&&dt.current?{zip:dt.current}:{},...Ye(E.city,ht)&&tn.current?{city:tn.current}:{},...xo?{state:xo}:{},...vn&&gn.current?{addressLine1:gn.current}:{},...Ye(E.address_line_2,ht)&&Kt.current?{addressLine2:Kt.current}:{}}})():{}},chv:p,avsCheck:z??!1,checkoutType:q,checkoutLayout:$,avsConfig:E?{country:Ye(E.country,yt.current),postal_code:Ye(E.postal_code,yt.current),address_line_1:Ye(E.address_line_1,yt.current),address_line_2:Ye(E.address_line_2,yt.current),city:Ye(E.city,yt.current),state:Ye(E.state,yt.current)}:void 0});if(Lt.ok){let ht=Lt.status===204?null:await Lt.json().catch(()=>null),Kn=Pi(g)||ht?.status==="authorized";mo(N),m("success"),gt(null),await new Promise(zr=>setTimeout(zr,600));let vn;typeof ht?.paymentId=="string"?vn=ht.paymentId:g?.paymentId&&(vn=g.paymentId);let Zt;typeof ht?.authorizationExpiresAt=="string"?Zt=ht.authorizationExpiresAt:g?.authorizationExpiresAt&&(Zt=g.authorizationExpiresAt),c?.(Kn?{status:"authorized",...vn===void 0?{}:{paymentId:vn},sessionId:typeof ht?.sessionId=="string"?ht.sessionId:N,...Zt===void 0?{}:{authorizationExpiresAt:Zt},paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:at,checkoutMethod:o.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:at,checkoutMethod:o.isPaypal?"paypal":"card"});return}let Et=await Lt.json().catch(()=>null);if(Et?.type==="paypal_redirect_required"){let ht=Et.threeDSecureToken,Kn=Et.paymentMethodId||o.id||"";if(!ye||!ht){m("error"),se("PayPal authorization required but no token provided.");return}try{let vn=Be?.getRawProvider();if(!vn){se("PayPal is not available.");return}let Zt={return_url:window.location.href};Kn&&(Zt.payment_method=Kn);let{error:zr}=await vn.confirmPayment({clientSecret:ht,confirmParams:Zt,redirect:"if_required"});if(zr){m("error");let xo=zr.message??"PayPal payment failed.";se(xo),ir("paypal",xo,{code:zr.code})}}catch(vn){m("error"),se(vn instanceof Error?vn.message:"PayPal authorization failed.")}return}if(Et?.type==="paypal_direct_required"){let ht=Et.orderId;if(!ht){m("error"),se("PayPal retry required but no order id provided.");return}let Kn=ge.current?.attempts??0;if(Kn>=2){m("error"),se("PayPal payment could not be completed after multiple attempts."),ir("paypal","paypal_direct_required retry limit exceeded");return}za(!1),Ua("loading"),gt({orderId:ht,attempts:Kn+1}),m(null);return}rd(Lt.status,Et)||It(),m("error");let jn=Et?.message??"Payment failed. Please try again.";se(jn),ir(o.isPaypal?"paypal":"card",jn,{code:Et?.code??Et?.gatewayErrorCode,declineCode:Et?.declineCode??Et?.gatewayDeclineReason}),await new Promise(ht=>setTimeout(ht,400))}catch(Bt){fl(Bt)||It(),m("error"),se(Bt instanceof Error?Bt.message:"An unexpected error occurred"),await new Promise(Lt=>setTimeout(Lt,400))}finally{ct(!1),m(null),_.current=!1}},[j,e,t,x,E,z,q,$,p,ye,Be,g,c,se,ir,Pt]),_n=Je((o,b)=>{P?P(o):ds(o,b)},[P,ds]),Ro=`${yl}:${e}`;vt(()=>{if(typeof window>"u")return;let o=localStorage.getItem(Ro);if(!o)return;let b;try{b=JSON.parse(o)}catch{localStorage.removeItem(Ro);return}if(!b||typeof b.createdAt!="number"||Date.now()-b.createdAt<0||Date.now()-b.createdAt>Pd||typeof b.paymentMethodId!="string"||typeof b.providerIntentId!="string"||typeof b.paymentMethodType!="string"||b.sessionId!==e||!t||b.nonce!==t||!Gr.includes(b.paymentMethodType)){localStorage.removeItem(Ro);return}localStorage.removeItem(Ro),_n({id:b.paymentMethodId,type:"card",threeDSecureActionResultTokenId:b.providerIntentId,gateway:"stripe",paymentMethodType:b.paymentMethodType},{...b.accountPatch?{accountPatch:b.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[_n,t,e,Ro,Gr]);let us=he(!1);vt(()=>{if(typeof window>"u"||us.current)return;let o=new URLSearchParams(window.location.search),b=o.get("payment_intent"),N=o.get("payment_intent_client_secret"),Ee=o.get("redirect_status");if(!b||!N||!ye)return;let U=ye.getRawProvider();if(!U)return;let at=Et=>{let jn=localStorage.getItem(Et);if(!jn)return null;try{return JSON.parse(jn)}catch{return localStorage.removeItem(Et),null}},Ge=at(dr)??at(rl),tt;if(Ge?.clientSecret){if(Ge.clientSecret!==N)return;tt={...Ge.accountPatch?{accountPatch:Ge.accountPatch}:{},...Ge.sessionId?{sessionId:Ge.sessionId}:{},...Ge.nonce?{nonce:Ge.nonce}:{}}}else if(Ge?.sessionId&&Ge.sessionId!==e)return;us.current=!0,localStorage.removeItem(dr),localStorage.removeItem(rl);let It=new URL(window.location.href);It.searchParams.delete("payment_intent"),It.searchParams.delete("payment_intent_client_secret"),It.searchParams.delete("redirect_status"),window.history.replaceState({},"",It.toString());let Bt=Ge?.paymentMethodType??Ge?.tokenType??"card",Lt="card";(async()=>{if(Ee==="failed"){let Zt="Payment was declined. Please try again.";se(Zt),ir(Lt,Zt);return}let{paymentIntent:Et,error:jn}=await U.retrievePaymentIntent(N);if(jn){let Zt=jn.message??"Failed to retrieve payment status.";se(Zt),ir(Lt,Zt,{code:jn.code});return}let ht=Et?.status,Kn=No(ht);if(!Et||!Kn){let Zt=ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";se(Zt),ir(Lt,Zt,{code:ht??"missing_payment_intent"});return}let vn=typeof Et.payment_method=="string"?Et.payment_method:Et.payment_method?.id;_n({id:vn??Ge?.paymentMethodId??Ge?.tokenId??Et.id,type:"card",threeDSecureActionResultTokenId:Et.id,gateway:Ge?.gateway??"stripe",paymentMethodType:Bt},tt)})()},[e,_n,ye,se,ir]);let $a=Je(o=>{o.preventDefault()},[]);if(!(We||ye!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Eo=ie==="buttons",Rn=k?.variables,$l=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ja=Rn?.colorBackground,jl=ja&&!$l.has(ja)?ja:void 0,To=s.cardInputBorder??(Eo?"#e5e7eb":"#A4A4FF"),ps=Rn?.colorDanger??"#dc2626",Nt=o=>Dr[o]&&(or[o]||Cr),aa=re&&(Nn||Cr),$n=o=>o?ps:To,ia=(un.malformed||un.empty)&&(Sr||Cr),Kl=$n(ia),Ka=s.cardFormContainer?.backgroundColor??jl??(Eo?"white":"#EDEDFF"),Jr=s.cardInputBackground??Rn?.colorBackground??"white",Va=Qr(Me),ms=Qr(le),Xr=s.nameInput,ys=s.cardInputFontSize??Od(Xr?.fontSize)??Rn?.fontSizeBase??"16px",fs=typeof Xr?.fontFamily=="string"?Xr.fontFamily:Rn?.fontFamily??"Poppins, sans-serif",gs=Cs(Xr?.fontWeight)??400,Vl=s.cardInputColor??(typeof Xr?.color=="string"?Xr.color:void 0)??Rn?.colorText??"#262833",Hl=s.cardInputPlaceholderColor??"#9ca3af",qt=Rn?.borderRadius??"8px",Lr=Rn?.borderRadius??s.cardButton?.borderRadius??qt,Or=Rn?.colorPrimary??"#4A49FF",Wl=Rn?.colorPrimaryHover??Fo(Or,.12),Ha=Rn?.colorText??"#262833",Wa={fontSize:ys,fontFamily:fs,fontWeight:gs,color:Vl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ao={marginTop:"0.375rem",...Wa,fontSize:"0.75rem",lineHeight:1.4,color:ps},Gl={"--flopay-input-placeholder-color":Hl,"--flopay-input-font-size":ys,"--flopay-input-font-family":fs,"--flopay-input-font-weight":String(gs)},Mo=s.cardFormContainer??{},Ga=Mo.padding??(Eo?"0":"1rem"),Ya=Mo.borderRadius??qt,Yl=ot&&In?d(Ja,{capture:ot,html:In.html,messageToken:In.messageToken,expectedOrigin:In.expectedOrigin,theme:Se,onReady:()=>{if(!me&&!E||typeof document>"u")return;let o=()=>{let N=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(N){Yn.current=!0;try{N.focus()}finally{Yn.current=!1}}};Jn.current||o()},onError:o=>se(o),onValidation:o=>{let b=D.current;(b==="idle"||b==="validation-window")&&(se(o),o&&D.current==="validation-window"&&(A.current&&(clearTimeout(A.current),A.current=null),D.current="idle",m(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"}),hs=Le("div",{onFocusCapture:o=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(o.target.tagName)&&zn()},style:{backgroundColor:Ka,borderRadius:Ya,...Mo,padding:Ga,...Gl,display:"flex",flexDirection:"column"},children:[d("style",{children:`
25
+ `,Ta=44,Ho=180,fl=`flopay-card-enter ${Ho}ms cubic-bezier(0, 0, 0.2, 1) both`,gl=`flopay-card-exit ${Ho}ms cubic-bezier(0.4, 0, 0.2, 1) both`,jd=`flopay-buttons-enter ${Ho}ms cubic-bezier(0, 0, 0.2, 1) both`,$d=`flopay-buttons-exit ${Ho}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Kd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Li(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 Vd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Wd(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var Ai={width:"100%",minHeight:Ta,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 Hd(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function hl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Mi(e){return e==="paypal"?"PayPal":Wr(e)}function Gd(e,t){let n=`We couldn't open ${Mi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Yd(e){let t=gd(e);return`Enter a valid ${Ti(e)}${t?` (e.g. ${t})`:""}`}function Jd(e,t,n){let r=Pd(e),o=t.trim(),i=n&&r,l=i&&!o,c=i&&!!o&&!bd(e,o);return{visible:n,supported:r,required:i,empty:l,malformed:c}}function Xd(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!ln(n);return{required:t,empty:r,malformed:o,value:n}}function vl(e,t){return t instanceof ir?t:new ir(t instanceof Error?t.message:`${Hd(e)} before-click hook failed.`,"validation_error")}function Ei(){return d("style",{children:qd})}function Zd(e){return typeof e=="number"?`${e}px`:e}function El(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Tl({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){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:r})]})}function Pl(e){return e!=="unavailable"&&e!=="load_error"}function Oi(e){return d(eu,{...e})}function bl({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:l=!1,onButtonClick:c,onDecline:h,onTechnicalFailure:v,runBeforeButtonClick:f,billingName:g,onBuyerIdentityReady:m,onLoadStateChange:_,placeholderBorderRadius:M}){let z=Rr(),{emitInstrument:Be}=go(Jn),oe=Fi(),C=Bi(),[Y,Q]=ie("loading");yt(()=>{_?.(Y)},[Y,_]);let[se,Fe]=ie(!1),re=!ln(n?.trim())||!g?.trim(),{request:Ke,collect:et,finish:ot}=ao(),kt=de(!1),Ue=de(null),De=de(null),[ue,Ee]=ie(0),[pe,me]=ie(!1),Ce=de(!1),ge=de(new Map),{startAttempt:tt,finishAttempt:Ye,invalidateAttempt:E,isAttemptInvalidated:J,isAttemptCurrent:Ie}=Uo((j,q,$)=>{v?.(j,q,{...$,popupBlocked:$?.popupBlocked??Pr(q)}),me(!0),Ee(je=>je+1)});yt(()=>{pe&&De.current?.focus()},[pe,ue]);let ye=Ge(()=>{Ee(j=>j+1)},[]),L=Ge((j,q,$)=>{E($),v?.("paypal",j,{code:q,popupBlocked:Pr(j)}),me(!0),ye()},[E,v,ye]),Te=Ge(()=>{window.setTimeout(()=>{(Ue.current?.querySelector("iframe")??Ue.current)?.focus()},0)},[]);yt(()=>{Ce.current&&(Ce.current=!1,Te())},[Te,ue]);let Ae=Ge(()=>{me(!1),i?.(null),Te()},[Te,i]);yt(()=>{if(!oe||kt.current)return;let j=new URLSearchParams(window.location.search),q=j.get("payment_intent"),$=j.get("payment_intent_client_secret"),je=j.get("redirect_status");if(!q||!$)return;kt.current=!0;let Je;try{let he=localStorage.getItem(Wo);if(he){let $e=JSON.parse(he);$e.clientSecret===$&&(Je={...$e.accountPatch?{accountPatch:$e.accountPatch}:{},...$e.sessionId?{sessionId:$e.sessionId}:{},...$e.nonce?{nonce:$e.nonce}:{}})}}catch{}try{localStorage.removeItem(Wo)}catch{}let Se=new URL(window.location.href);Se.searchParams.delete("payment_intent"),Se.searchParams.delete("payment_intent_client_secret"),Se.searchParams.delete("redirect_status"),window.history.replaceState({},"",Se.toString()),(async()=>{try{if(Fe(!0),je==="failed"){let x="PayPal payment was declined. Please try again.";i?.(x),h?.(nn("paypal",x));return}let{paymentIntent:he,error:$e}=await oe.retrievePaymentIntent($);if($e){i?.($e.message??"Failed to retrieve PayPal payment status.");return}if(he&&(he.status==="requires_capture"||he.status==="succeeded")){let x=typeof he.payment_method=="string"?he.payment_method:he.payment_method?.id;o({id:x??he.id,type:"card",threeDSecureActionResultTokenId:he.id,isPaypal:!0},Je)}else{let x="PayPal payment was not completed. Please try again.";i?.(x),h?.(nn("paypal",x))}}catch(he){i?.(he instanceof Error?he.message:"Failed to complete PayPal payment.")}finally{Fe(!1)}})()},[oe,o,i,h]);let dt=Ge(async j=>{if(l||se){j.reject();return}let q=f?await f("paypal"):{proceed:!0};if(!q.proceed){ge.current.delete(ue),j.reject();return}let $=tt("paypal");ge.current.set(ue,{generation:$,accountPatch:q.accountPatch,sessionId:q.sessionId,nonce:q.nonce}),me(!1),c?.("paypal"),j.resolve()},[l,c,f,tt,se,ue]),Ve=Ge(async j=>{if(!oe||!C)return;let q=ge.current.get(ue);if(q&&!Ie(q.generation)){ge.current.delete(ue);return}if(!q&&J()||q&&!Ye(q.generation))return;q||Ye();let $=q??null;if(ge.current.delete(ue),!$&&f){let x=await f("paypal");if(!x.proceed){j.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}$={accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}}let je=$?.sessionId??e,Je=$?.nonce??t,Se=await Ud({event:j,prepared:$,email:n,billingName:g,methodLabel:"PayPal",collect:et});if(!Se){j.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let he=Se.email,$e={...$?.accountPatch,...An(Se,!0)};try{if(Fe(!0),i?.(null),!je||!ln(he))throw new Error("Missing sessionId or email for PayPal payment");await m?.(Se);let x=oe.createPaymentMethod,{error:Zt,paymentMethod:X}=await x({type:"paypal"});if(Zt){L(Zt,"stripe_paypal_create_payment_method_failed",q?.generation),j.paymentFailed({reason:"fail"});return}let Pt=await Aa(r,Be,je,Je??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:X?.id??null,intentKind:"payment"});if(Pt.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let bt=Pt.clientSecret,Xe={return_url:window.location.href};if(X?.id&&(Xe.payment_method=X.id),typeof window<"u")try{localStorage.setItem(Wo,JSON.stringify({clientSecret:bt,sessionId:je,nonce:Je,accountPatch:$e}))}catch{}let{error:T,paymentIntent:Ne}=await oe.confirmPayment({clientSecret:bt,confirmParams:Xe,redirect:"if_required"});if(T){if(typeof window<"u")try{localStorage.removeItem(Wo)}catch{}if(zo(T)){let w=T.message??"Your payment was declined.";i?.(w),h?.(nn("paypal",w,{code:vr(T),declineCode:so(T)})),await Ma({billingApiUrl:r,sessionId:je,nonce:Je,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:vr(T)??"provider_declined"}})}else L(T,"stripe_paypal_confirm_failed",q?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Wo)}catch{}let u=typeof Ne?.payment_method=="string"?Ne.payment_method:Ne?.payment_method?.id;o({id:u??Ne?.id,type:"card",threeDSecureActionResultTokenId:Ne?.id,isPaypal:!0},{accountPatch:$e,paymentMethodCategory:"paypal",sessionId:je,nonce:Je});return}catch(x){L(x,"stripe_paypal_failed",q?.generation)}finally{Fe(!1)}},[oe,C,e,t,n,g,et,m,r,Be,o,i,h,f,L,Ye,Ie,J,ue]);return ze(Vr,{children:[d(Tl,{state:Y,placeholderTestId:"flopay-paypal-placeholder",borderRadius:M,children:ze("div",{ref:Ue,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[pe&&d("button",{ref:De,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ae,style:Ai,children:"Try PayPal again"}),Ke&&d(io,{identity:Ke.identity,methodLabel:Ke.methodLabel,onComplete:ot,onCancel:()=>ot(null)},Ke.id),d("div",{style:{display:Ke?"none":void 0},children:d(wl,{onReady:j=>Q(El(j,["paypal"])),onLoadError:()=>{Q("load_error"),Ni(Jt(z),"paypal","paypal")},onClick:dt,onConfirm:Ve,onCancel:()=>{let j=ge.current.get(ue);ge.current.delete(ue),Jt(z)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),E(j?.generation),me(!1),Ce.current=!0,ye()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:re,emailRequired:re,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ue)})]})}),se&&d(mr,{status:"processing"})]})}function Cl({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:l,onErrorChange:c,onButtonClick:h,onDecline:v,onTechnicalFailure:f,runBeforeButtonClick:g,billingName:m,onBuyerIdentityReady:_,onLoadStateChange:M,placeholderBorderRadius:z}){let Be=Rr(),{emitInstrument:oe}=go(Jn),C=Fi(),Y=Bi(),[Q,se]=ie("loading");yt(()=>{M?.(Q)},[Q,M]);let[Fe,re]=ie(!1),Ke=de(!ln(n?.trim())||!m?.trim()).current,{request:et,collect:ot,finish:kt}=ao(),Ue=de(null),De=de(null),[ue,Ee]=ie(0),[pe,me]=ie(!1),[Ce,ge]=ie(()=>Ea(e,t)?"blocked":"idle"),[tt,Ye]=ie("google_pay"),E=de(null),J=de(!0),Ie=de(!1),ye=de("google_pay"),L=de("google_pay"),Te=de(null),Ae=de(null),dt=de(new Set);yt(()=>(J.current=!0,()=>{J.current=!1;for(let T of dt.current)window.clearTimeout(T);dt.current.clear()}),[]);let Ve=de(new Map),{startAttempt:j,finishAttempt:q,invalidateAttempt:$,isAttemptInvalidated:je,isAttemptCurrent:Je,generationRef:Se}=Uo((T,Ne,u)=>{f?.(T,Ne,{...u,popupBlocked:u?.popupBlocked??Pr(Ne)}),Ye(T),me(!0),Ee(w=>w+1)});yt(()=>{pe&&De.current?.focus()},[pe,ue]);let he=Ge(()=>{Ee(T=>T+1)},[]),$e=Ge((T,Ne,u,w)=>{$(w),f?.(T,Ne,{code:u,popupBlocked:Pr(Ne)}),Ye(T),me(!0),he()},[$,f,he]),x=Ge(()=>{window.setTimeout(()=>{(Ue.current?.querySelector("iframe")??Ue.current)?.focus()},0)},[]);yt(()=>{Ie.current&&(Ie.current=!1,x())},[x,ue]);let Zt=Ge(()=>{me(!1),c?.(null),x()},[x,c]),X=Ge(()=>{E.current?.()},[]);yt(()=>{let T=Ea(e,t);if(!T)return;let Ne=!1,u=!1,w=async()=>{if(!u){u=!0,Ne||ge("checking");try{let fe=await ml(C,T.clientSecret,dt.current);if(Ne)return;let ve=_i(fe,T.providerObjectId,Si(T.clientSecret));if(ve.kind==="confirmed"){if(!pl(e,t,T.clientSecret))return;E.current=null,ge("idle"),l({id:ve.paymentMethodId,type:"card",threeDSecureActionResultTokenId:ve.intentId},{...T.accountPatch?{accountPatch:T.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(ve.kind==="terminal"){ki(e,t,T.clientSecret),E.current=null,ge("idle"),Ye(T.paymentMethodType),me(!0),he();return}ge("blocked")}catch{Ne||ge("blocked")}finally{u=!1}}};return E.current=w,ge("blocked"),()=>{Ne=!0,E.current===w&&(E.current=null)}},[t,l,he,e,C]);let Pt=Ge(async T=>{let Ne=!1,u=le=>{Ne||(Ne=!0,T.paymentFailed({reason:"fail",...le?{message:le}:{}}))};if(!C||!Y){u();return}let w=Ve.current.get(ue);if(w&&!Je(w.generation)){Ve.current.delete(ue),u();return}if(!w&&je()){u();return}if(w&&!q(w.generation)){u();return}w||q();let fe=T.expressPaymentType??w?.method??ye.current,ve=w??null,ut=hl(fe),Mt;fe==="apple_pay"?Mt="apple_pay":fe==="google_pay"&&(Mt="google_pay");let Me=w?.generation??Se.current,Le=Jt(Be),lt=Le?.now()??globalThis.performance?.now()??Date.now(),Fn=new AbortController,rn=!1,_t=!1,Z=null,gn=e,Mn="processing",Qt="other",on="provider_runtime",Dn,hn=new Promise((le,ct)=>{Dn=ct}),Sn=window.setTimeout(()=>{rn=!0,Fn.abort(),Dn(wi)},xd),jt=async(le,ct,pt)=>{Mn=le,Qt=ct,on=ct==="intent_create"||ct==="session_claim"?"transport_error":"provider_runtime";let wn=Le?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([pt,hn])}finally{let xt=Le?.now()??globalThis.performance?.now()??Date.now();Le?.performance({stage:le,durationMs:Math.max(0,xt-wn),durationMode:"machine",requestCategory:ct,paymentMethodCategory:"wallet",provider:"stripe",...rn?{statusClass:"timeout"}:{}})}};try{if(re(!0),c?.(null),!ve&&g){let Pe=await jt("processing","other",g(ut));if(!Pe.proceed){u();return}ve={accountPatch:Pe.accountPatch,sessionId:Pe.sessionId,nonce:Pe.nonce}}let le=ve?.sessionId??e;gn=le;let ct=ve?.nonce??t,pt=Te.current??ve?.accountPatch,wn=Rl({event:T,fallbackEmail:pt?.email??n,fallbackName:[pt?.firstName,pt?.lastName].join(" ").trim()||m});if(!ln(wn.email)){u("Buyer details are required."),ot(Mi(fe),wn).then(Pe=>{Pe&&(Te.current=Pe)});return}Te.current=null;let xt={...ve?.accountPatch,...An(wn,!0)};await jt("processing","session_claim",Promise.resolve(_?.(wn)));let{error:Nn}=await jt("tokenization","provider_sdk",Y.submit());if(Nn){u(),$e(fe,Nn,"stripe_wallet_submit_failed",w?.generation);return}if(!le)throw new Error("Missing sessionId or email for payment.");let mt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:fe,paymentMethodId:null,intentKind:o},ft=JSON.stringify({sessionId:le,nonce:ct??"",request:mt}),cn=Ae.current,dn=cn?.retryIdentity===ft?cn.authorizationAttemptId:wd();Ae.current={authorizationAttemptId:dn,retryIdentity:ft};let Dt=await jt("processing","intent_create",Aa(r,oe,le,ct??"",{...mt,authorizationAttemptId:dn},{signal:Fn.signal}));if(Dt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ct=Dt.clientSecret,Ln=Dd({createdAt:Date.now(),sessionId:le,...ct?{nonce:ct}:{},clientSecret:Ct,providerObjectId:Dt.providerObjectId,paymentMethodType:fe,accountPatch:xt});window.clearTimeout(Sn),_t=!0,Le?.performance({stage:"callback",durationMs:Math.max(0,(Le?.now()??globalThis.performance?.now()??Date.now())-lt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Ht=Le?.now()??globalThis.performance?.now()??Date.now(),D={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Mt?{walletType:Mt}:{},attempt:Me},sr=!1,Vt=null;Le?.log({name:"payment.provider_confirmation.started",...D}),Z=window.setTimeout(()=>{Z!==null&&dt.current.delete(Z),sr=!0;let Pe=Le?.now()??globalThis.performance?.now()??Date.now();Le?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...D,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Pe-Ht),statusClass:"timeout",failureCategory:"provider_runtime"}),Le?.flush?.().catch(()=>{}),Vt?.()},Bd),dt.current.add(Z);let vn=Pe=>{Z!==null&&(window.clearTimeout(Z),dt.current.delete(Z),Z=null);let S=Le?.now()??globalThis.performance?.now()??Date.now(),W=Math.max(0,S-Ht),B=Pe;return sr&&(Pe==="resolved"?B="resolved_late":Pe==="returned_error"?B="returned_error_late":B="rejected_late"),Le?.log({name:"payment.provider_confirmation.returned",...D,operationOutcome:B}),Le?.performance({...D,durationMs:W,durationMode:"buyer",operationOutcome:B}),{durationMs:W,operationOutcome:B}},Nt=!1,un=!1,On=Pe=>{if(!Pe||typeof Pe!="object")return null;let S=Pe;if(S.error)return null;let W=S.setupIntent??S.paymentIntent,B=_i(W??null,void 0,!!S.setupIntent);return B.kind==="confirmed"?B:null},pn=Pe=>{if(Nt||w&&Se.current!==w.generation)return;let S=On(Pe);if(!S)return;if(Ln&&!pl(le,ct,Ct)){Nt=!0;return}let{intentId:W,paymentMethodId:B}=S;Nt=!0,un=!0,Ae.current=null,E.current=null,J.current&&(ge("idle"),re(!1));let Lt=`${Il}:${le}`;if(typeof window<"u")try{localStorage.setItem(Lt,JSON.stringify({createdAt:Date.now(),sessionId:le,nonce:ct,accountPatch:xt,paymentMethodId:B,providerIntentId:W,paymentMethodType:fe}))}catch{}try{l({id:B,type:"card",threeDSecureActionResultTokenId:W},{accountPatch:xt,paymentMethodCategory:"wallet",sessionId:le,nonce:ct})}finally{if(typeof window<"u")try{localStorage.removeItem(Lt)}catch{}}},qe=!1;Vt=async()=>{if(!(qe||Nt||un)){qe=!0,J.current&&ge("checking");try{let Pe=await ml(C,Ct,dt.current);if(Nt||un)return;let S=Si(Ct),W=_i(Pe,Dt.providerObjectId,S);if(W.kind==="confirmed"){pn(S?{setupIntent:Pe}:{paymentIntent:Pe});return}if(W.kind==="terminal"){if(un=!0,ki(le,ct,Ct),Ae.current=null,E.current=null,!J.current)return;ge("idle"),u(),$e(fe,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",w?.generation);return}J.current&&!un&&(ge("blocked"),re(!1))}catch{J.current&&!un&&(ge("blocked"),re(!1))}finally{qe=!1}}},E.current=Vt;let In,an;try{let Pe=await(Si(Ct)?C.confirmSetup({elements:Y,clientSecret:Ct,redirect:"if_required"}):C.confirmPayment({elements:Y,clientSecret:Ct,redirect:"if_required"}));if(!Pe||typeof Pe!="object"||(In=Pe,!In.error&&!On(In)))throw Ii;an=vn(In.error?"returned_error":"resolved")}catch(Pe){let S=Pe===Ii,W=vn(S?"returned_error":"rejected");if(Le?.error({...S?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:ni(Pe),...D,operationOutcome:W.operationOutcome,durationMs:W.durationMs,statusClass:"unknown"}),!J.current||Nt)return;await Vt?.();return}let mn=In.error;if(mn){if(!J.current||Nt)return;if(zo(mn)){un=!0,ki(le,ct,Ct),Ae.current=null,E.current=null,ge("idle");let Pe=mn.message??"Your payment was declined.";u(Pe),c?.(Pe),v?.(nn(ut,Pe,{code:vr(mn),declineCode:so(mn)})),Ma({billingApiUrl:r,sessionId:le,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:fe,providerDeclineReason:vr(mn)??"provider_declined",...Dt.intentKind==="payment"&&Dt.providerObjectId.startsWith("pi_")?{providerIntentId:Dt.providerObjectId}:{}}})}else Le?.error({...ni(mn),...D,operationOutcome:an.operationOutcome,durationMs:an.durationMs,statusClass:"unknown"}),await Vt?.();return}if(pn(In),!Nt)throw new Error("Invalid provider returned for APM intent")}catch(le){if(le===wi){let ct=Le?.now()??globalThis.performance?.now()??Date.now();Le?.error({errorCode:Ld(Qt),stage:Mn,requestCategory:Qt,paymentMethodCategory:"wallet",provider:"stripe",...Mt?{walletType:Mt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:gn,durationMs:Math.max(0,ct-lt),statusClass:"timeout",failureCategory:on,attempt:Me}),Le?.flush?.().catch(()=>{})}u(),$e(fe,le,le===wi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",w?.generation)}finally{if(window.clearTimeout(Sn),Z!==null&&(window.clearTimeout(Z),dt.current.delete(Z)),!_t){let le=Le?.now()??globalThis.performance?.now()??Date.now();Le?.performance({stage:"callback",durationMs:Math.max(0,le-lt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...rn?{statusClass:"timeout"}:{}})}J.current&&re(!1)}},[C,Y,e,t,n,m,ot,_,r,oe,o,l,c,v,g,$e,q,Je,je,Se,Be,ue]),bt=Tt(()=>{let T=["applePay","googlePay","paypal","link","amazonPay","klarna"],Ne=new Set(["applePay","googlePay"]),u=new Set(i.map(dl)),w={};for(let fe of T)u.has(fe)?w[fe]=Ne.has(fe)?"always":"auto":w[fe]="never";return w},[i]),Xe=Tt(()=>i.map(dl),[i]);return ze(Vr,{children:[d(Tl,{state:Q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:z,children:ze("div",{ref:Ue,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[pe&&ze("button",{ref:De,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Zt,style:Ai,children:["Try ",Mi(tt)," again"]}),Ce!=="idle"&&ze("div",{role:"status","aria-live":"polite",children:[d("p",{children:"We are still confirming your payment. Check its status before trying again."}),d("button",{type:"button",onClick:X,disabled:Ce==="checking",style:Ai,children:Ce==="checking"?"Checking payment status\u2026":"Check payment status"})]}),et&&d(io,{identity:et.identity,methodLabel:et.methodLabel,onComplete:kt,onCancel:()=>kt(null)},et.id),Ce==="idle"&&d("div",{style:{display:et?"none":void 0},children:d(wl,{onReady:T=>{se(El(T,Xe))},onLoadError:T=>{se("load_error"),Ni(Jt(Be),"stripe","wallet")},onClick:async T=>{ye.current=T.expressPaymentType,L.current=hl(T.expressPaymentType);let Ne=!0,u=window.setTimeout(()=>{Ne=!1,T.reject()},Md),w=g?await g(L.current):{proceed:!0};if(window.clearTimeout(u),!Ne)return;if(!w.proceed){Ve.current.delete(ue),T.reject();return}let fe=j(T.expressPaymentType);Ve.current.set(ue,{generation:fe,method:T.expressPaymentType,accountPatch:w.accountPatch,sessionId:w.sessionId,nonce:w.nonce}),me(!1),h?.(L.current),T.resolve()},onConfirm:Pt,onCancel:()=>{let T=Ve.current.get(ue);Ve.current.delete(ue),Jt(Be)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),$(T?.generation),Ae.current=null,me(!1),Ie.current=!0,he()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:bt,emailRequired:Ke,billingAddressRequired:Ke,layout:{maxColumns:1,overflow:"never"}}},ue)})]})}),Fe&&d(mr,{status:"processing"})]})}function Al(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function Qd({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:l,backgroundColor:c,borderColor:h,textColor:v,borderRadius:f,fontFamily:g}){let m=_d(e,t),_=sl[e],[M,z]=ie(!1),Be=!!_&&!M,oe=m?.backgroundColor??c??"#ffffff",C=m?.borderColor??h??"#d1d5db",Y=m?.textColor??v??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&l()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Ta,padding:"0 1rem",backgroundColor:oe,color:Y,border:`1px solid ${C}`,borderRadius:f??8,fontSize:"0.95rem",fontWeight:600,fontFamily:g,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?d("span",{style:{margin:"0 auto"},children:`Connecting to ${Wr(e)}\u2026`}):ze(Vr,{children:[ze("span",{style:{display:"inline-flex",alignItems:"center",gap:vd(e)?8:0},children:[Be?d("img",{src:_,alt:"","aria-hidden":"true",onError:()=>z(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!Be&&m?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:m.logoSvg}}):null,d("span",{children:Wr(e)})]}),i&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:Y,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 xi({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:l,onTokenizedBody:c,onErrorChange:h,onDecline:v,onCancel:f,runBeforeButtonClick:g,onButtonClick:m,isProcessing:_,submitButtonColor:M,submitButtonBorderRadius:z,submitButtonStyle:Be,errorText:oe}){let C=Rr(),{emitInstrument:Y}=go(Jn),Q=Fi(),se=Bi(),[Fe,re]=ie(!1),Ke=de(!1),[et,ot]=ie(!1),[kt,Ue]=ie("loading"),[De,ue]=ie(""),Ee=!ln(r?.trim()),pe=!Ee||ln(De.trim()),me=Ge(async()=>{if(!Q||!se||_||Ke.current||!et)return;Ke.current=!0,re(!0);let Ce=g?await g("card"):{proceed:!0};if(!Ce.proceed){Ke.current=!1,re(!1);return}m?.("card");let ge=Ce.sessionId??t,tt=Ce.nonce??n,Ye=Ur(o?.trim()),E=An({email:Ce.accountPatch?.email?.trim()||r?.trim()||De.trim(),firstName:Ce.accountPatch?.firstName?.trim()||Ye.firstName,lastName:Ce.accountPatch?.lastName?.trim()||Ye.lastName}),J=E.email,Ie=An({...Ce.accountPatch,...E});try{if(h?.(null),!ln(J))throw new Error("A valid email address is required for payment.");await i?.(E);let ye=await se.submit();if(ye.error){h?.(ye.error.message??"Payment failed.");return}let L=[E.firstName,E.lastName].filter(Boolean).join(" "),Te=await Q.createPaymentMethod({elements:se,params:{billing_details:{email:J,...L?{name:L}:{}}}});if(Te.error||!Te.paymentMethod){h?.(Te.error?.message??"Failed to create payment method.");return}let Ae=Te.paymentMethod;if(!ge||!J)throw new Error("Missing sessionId or email for payment.");let dt=Ae.type||e,Ve=await Aa(l,Y,ge,tt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:dt,paymentMethodId:null,intentKind:"payment"});if(Ve.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let j=Ve.clientSecret;if(typeof window<"u")try{localStorage.setItem(yr,JSON.stringify({clientSecret:j,sessionId:ge,nonce:tt,accountPatch:Ie,paymentMethodId:Ae.id,paymentMethodType:Ae.type??e,gateway:"stripe"}))}catch{}let{error:q,paymentIntent:$}=await Q.confirmPayment({clientSecret:j,confirmParams:{return_url:window.location.href,payment_method:Ae.id},redirect:"if_required"});if(q){if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let Se=q.message??"Payment failed.";h?.(Se),v?.(nn("card",Se,{code:q.code})),await Ma({billingApiUrl:l,sessionId:ge,nonce:tt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:q.code??"provider_declined"}});return}let je=$?.status;if(!No(je)){if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let Se=je==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(Se),v?.(nn("card",Se,{code:je??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let Je=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;c({id:Je??Ae.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:Ae.type??e},{accountPatch:Ie,paymentMethodCategory:"apm",sessionId:ge,nonce:tt})}catch(ye){h?.(ye instanceof Error?ye.message:"Payment failed. Please try again.")}finally{Ke.current=!1,re(!1)}},[Q,se,_,et,g,m,t,n,r,o,De,i,l,Y,e,c,h,v]);return ze("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Ee&&d("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Ee&&ze("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",d("input",{type:"email",autoComplete:"email",required:!0,value:De,onChange:Ce=>ue(Ce.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),d(Ed,{onReady:()=>Ue("ready"),onLoadError:()=>{Ue("load_error"),Ni(Jt(C),"stripe","apm")},onChange:Ce=>{ot(!!Ce.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...ln(r?.trim())?{email:r?.trim()}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{me()},disabled:!et||!pe||Fe||_||kt!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:M,color:"white",border:"none",borderRadius:z,fontSize:"1rem",fontWeight:600,cursor:!et||!pe||Fe||_||kt!=="ready"?"not-allowed":"pointer",opacity:!et||!pe||Fe||_||kt!=="ready"?.5:1,transition:"opacity 120ms ease-out",...Be??{}},children:Fe?"Processing\u2026":`Pay with ${Wr(e)}`}),oe&&d(co,{margin:"0.75rem 0 0",children:oe})]})}function Sl({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:l,stripeInstance:c,paymentElementBaseOptions:h,onTokenizedBody:v,onErrorChange:f,onButtonClick:g,onDecline:m,runBeforeButtonClick:_,onLoadStateChange:M,isProcessing:z=!1,submitButtonColor:Be="#4A49FF",submitButtonBorderRadius:oe=8,submitButtonStyle:C,buttonAppearance:Y,themeId:Q,onExpandApm:se,expandedApmMethod:Fe}){let{emitInstrument:re}=go(Jn),[Ke,et]=ie(null),[ot,kt]=ie(null),Ue=de(!1),{request:De,collect:ue,finish:Ee}=ao();yt(()=>{l.length>0&&c?M?.("ready"):c||M?.("loading")},[l.length,c,M]);let pe=Ge(async E=>{if(!c||Ue.current||z)return;Ue.current=!0,kt(E);let J=_?await _("card"):{proceed:!0};if(!J.proceed){Ue.current=!1,kt(null);return}g?.("card");let Ie=J.sessionId??e,ye=J.nonce??t,L=Ur([J.accountPatch?.firstName,J.accountPatch?.lastName].filter(Boolean).join(" ")||r),Te=An({email:J.accountPatch?.email?.trim()||n?.trim(),firstName:J.accountPatch?.firstName?.trim()||L.firstName,lastName:J.accountPatch?.lastName?.trim()||L.lastName});if(!ln(Te.email)){kt(null);let Ve=await ue(Wr(E),Te);if(!Ve){Ue.current=!1;return}Te=Ve,kt(E)}let Ae=Te.email,dt=An({...J.accountPatch,...Te});try{if(f?.(null),!Ie||!ln(Ae))throw new Error("Missing sessionId or email for payment.");await o?.(Te);let Ve=await Aa(i,re,Ie,ye??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:E,paymentMethodId:null,intentKind:"payment"});if(Ve.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let j=Ve.clientSecret;if(typeof window<"u")try{localStorage.setItem(yr,JSON.stringify({clientSecret:j,sessionId:Ie,nonce:ye,accountPatch:dt,paymentMethodType:E,gateway:"stripe"}))}catch{}let{error:q,paymentIntent:$}=await c.confirmPayment({clientSecret:j,confirmParams:{return_url:window.location.href,payment_method_data:{type:E,billing_details:{name:[Te.firstName,Te.lastName].filter(Boolean).join(" "),...Ae?{email:Ae}:{}}}},redirect:"if_required"});if(q){if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let Se=q.message??"Payment failed.";f?.(Se),m?.(nn("card",Se,{code:q.code})),await Ma({billingApiUrl:i,sessionId:Ie,nonce:ye,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:E,providerDeclineReason:q.code??"provider_declined"}});return}let je=$?.status;if(!No(je)){if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let Se=je==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(Se),m?.(nn("card",Se,{code:je??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let Je=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;v({id:Je??$?.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:E},{accountPatch:dt,paymentMethodCategory:"apm",sessionId:Ie,nonce:ye})}catch(Ve){f?.(Ve instanceof Error?Ve.message:"Payment failed. Please try again.")}finally{Ue.current=!1,kt(null)}},[c,z,_,g,e,t,n,ue,i,re,r,o,v,f,m]),[me,Ce]=ie(null),ge=se?Fe??null:me,tt=Ge(E=>{Ue.current||z||ge&&ge!==E||(cl(E)?se?se(E):Ce(E):pe(E))},[ge,z,pe,se]),Ye=Tt(()=>me?Al(h,me):null,[me,h]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:De?d(io,{identity:De.identity,methodLabel:De.methodLabel,onComplete:Ee,onCancel:()=>Ee(null)},De.id):l.map(E=>{let J=Fe===E,Ie=ot===E,ye=ot!==null&&ot!==E||Fe!=null&&Fe!==E;return ze(Td.Fragment,{children:[d(Qd,{method:E,themeId:Q,submitting:Ie,disabled:ye,highlighted:J,hasNextStep:cl(E),onClick:()=>tt(E),backgroundColor:Y?.backgroundColor,borderColor:Y?.borderColor,textColor:Y?.textColor,borderRadius:Y?.borderRadius,fontFamily:Y?.fontFamily}),!se&&me===E&&Ye&&c&&d(Kr,{stripe:c,options:Ye,children:d(xi,{method:E,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:v,onErrorChange:f,onDecline:m,onCancel:()=>Ce(null),runBeforeButtonClick:_,onButtonClick:g,isProcessing:z,submitButtonColor:Be,submitButtonBorderRadius:oe,submitButtonStyle:C})},E)]},E)})})}function eu({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:i,onComplete:l,onError:c,onDecline:h,onTokenizedBody:v,firstName:f,lastName:g,chv:m,className:_,isProcessing:M,error:z,onErrorChange:Be,showPayPal:oe=!0,showStripe:C=!0,enabledPaymentMethods:Y,enabledPaymentMethodCountries:Q,showApplePay:se=!0,showGooglePay:Fe=!0,layout:re="default",theme:Ke,buttonsTheme:et,buttonsStyles:ot,appearance:kt,cardButtonContent:Ue,cardBackButtonContent:De,cardTitleContent:ue,showSecurityFooter:Ee,onButtonClick:pe,onBeforeButtonClick:me,onBuyerIdentityReady:Ce,enableAVS:ge,cardFieldOrder:tt,cardPreFormSlot:Ye,avsLayout:E="row",country:J,zip:Ie,addressLine1:ye,addressLine2:L,city:Te,state:Ae,onCountryChange:dt,onZipChange:Ve,avsCheck:j,checkoutType:q,checkoutLayout:$,totalAmount:je=0,currency:Je="usd",initialCardOpen:Se=!1,directPaypal:he,isSubscription:$e=!1,session:x,dataAttachmentPending:Zt=!1,dataAttachmentRequiresIdentity:X=!1,debug:Pt=!1}){let bt=Rr(),Xe=ri(),T=go(ar),{emitInstrument:Ne}=go(Jn),u=x??T.session,w=u?.gateways?.paypal?.providerObjectType??he?.providerObjectType,fe=Zt||T.claimPending===!0,ve=X||T.claimRequiresIdentity===!0,ut=fe&&!ve,Mt=Ws(),Me=n||Mt,[Le,lt]=ie(!1),[Fn,rn]=ie(null),[_t,Z]=ie(J??"US"),[gn,Mn]=ie(Ie??""),[Qt,on]=ie(ye??""),[Dn,hn]=ie(L??""),[Sn,jt]=ie(Te??""),[le,ct]=ie(Ae??""),[pt,wn]=ie(""),[xt,Nn]=ie({}),mt=de(Ie??""),ft=de(J??"US"),cn=de(ye??""),dn=de(L??""),Dt=de(Te??""),Ct=de(Ae??""),Ln=de(""),Ht=de({});yt(()=>{let a=(P,O,xe,U,it)=>{if(Ht.current[P])return;let Ze=O?.trim();!Ze||Ze===xe.current||(xe.current=Ze,U(Ze),it?.(Ze))};a("country",J,ft,Z,dt),a("zip",Ie,mt,Mn,Ve),a("addressLine1",ye,cn,on),a("addressLine2",L,dn,hn),a("city",Te,Dt,jt),a("state",Ae,Ct,ct)},[J,Ie,ye,L,Te,Ae,dt,Ve]);let D=Tt(()=>Id(ge),[ge]),sr=D!==null,Vt=Tt(()=>Ci(x),[x]),vn=!!x?.vault?.html,Nt=!!x?.gateways?.pcivault,On=!!(x?.gateways?.stripe?.enabledPaymentMethods??Y)?.includes("card"),pn=vn||On||Nt,qe=!!(C&&pn&&e),[In,an]=ie(()=>re!=="buttons"||Se?e??null:null),[mn,Pe]=ie(0),S=re!=="buttons"||Se||!!e&&In===e,W=x?.captureMethod,B=de(bt);yt(()=>{B.current=bt},[bt]);let[Lt,Zn]=ie(null);yt(()=>{if(!qe||!e||!S){Zn(null);return}let a=B.current?B.current.cardCapture({sessionId:e,captureMethod:W}):new ud({sessionId:e,captureMethod:W,billingApiUrl:Me,telemetry:r});return Zn({sessionId:e,captureMethod:W,billingApiUrl:Me,telemetry:r,capture:a}),()=>{a.unmount()}},[qe,e,S,W,Me,r]);let at=qe&&e&&S&&Lt?.sessionId===e&&Lt.captureMethod===W&&Lt.billingApiUrl===Me&&Lt.telemetry===r?Lt.capture:null,yn=Tt(()=>{let a=_t,P=D?Qe(D.postal_code,a):!1;return Jd(a,gn,P)},[D,_t,gn]),{avsInvalid:nt,invalidAvsFields:Dr}=Tt(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!qe||!D)return{avsInvalid:!1,invalidAvsFields:a};let P=_t,O=(it,Ze)=>Qe(it,P)&&!Ze.trim(),xe={line1:O(D.address_line_1,Qt),city:O(D.city,Sn),state:O(D.state,le),zip:yn.empty||yn.malformed};return{avsInvalid:xe.line1||xe.city||xe.state||xe.zip,invalidAvsFields:xe}},[qe,D,_t,Qt,Sn,le,yn]),[Sr,zn]=ie(!1),[wr,hr]=ie(!1),[Un,Gt]=ie(!1),[lr,kn]=ie({line1:!1,city:!1,state:!1}),Qn=de(!1),Pn=de({email:!1,line1:!1,city:!1,state:!1,zip:!1}),er=de(!1),gt=Ge(a=>{Pn.current[a]=!0,er.current=!0},[]),qn=Ge(a=>!Qn.current&&Pn.current[a],[]),_n=Ge(a=>{qn(a)&&kn(P=>P[a]?P:{...P,[a]:!0})},[qn]),[Rn,jn]=ie(()=>Ri(x?.vault)),[We,$t]=ie(Se&&pn?"card":"buttons"),[Wt,Ir]=ie(null),Co=We==="expanding"||We==="card",cr=x?.gateways?.stripe?"stripe":void 0,$n=Ge(()=>{Ne?.({class:"card_surface",provider:cr})},[cr,Ne]),Kn=de(null),sn=Ge(a=>{Kn.current&&clearTimeout(Kn.current),Kn.current=setTimeout(()=>{Kn.current=null,a()},Ho)},[]);yt(()=>()=>{Kn.current&&clearTimeout(Kn.current)},[]);let Nr=Ge(()=>{$n(),an(e??null),Pe(a=>a+1),$t("expanding"),sn(()=>$t("card"))},[sn,$n,e]),kr=Ge(()=>{$t("collapsing"),sn(()=>$t("buttons"))},[sn]),tr=Ge(a=>{Ir(a),$t("apm-expanding"),sn(()=>$t("apm-form"))},[sn]),nr=Ge(()=>{$t("apm-collapsing"),sn(()=>{$t("buttons"),Ir(null)})},[sn]);yt(()=>{re==="buttons"&&Se&&pn&&(an(e??null),$t("card"))},[re,Se,pn,e]);let[en,y]=ie(null),R=de(!1),A=de(null),N=de("idle"),[_e,ht]=ie(null),we=de(_e);yt(()=>{we.current=_e},[_e]);let G=de(null),H=Tt(()=>{if(Ce||T.claimBuyerIdentity||x?.buyerIdentified!==!1||!e||!t)return;let a=`${Me}|${e}|${t}`;G.current?.key!==a&&(G.current={key:a,claim:ro(new fo(Me,{telemetry:!1}),e,t,{...i?{userId:i}:{},...f?{firstName:f}:{},...g?{lastName:g}:{}})});let P=G.current.claim;return async O=>{await P(O)}},[Ce,T.claimBuyerIdentity,x?.buyerIdentified,e,t,Me,i,f,g]),I=Ce??T.claimBuyerIdentity??H,ee=z??Fn,p=Tt(()=>Rd(Ke),[Ke]),s=Tt(()=>{let a=p?.buttonsLayout??kd(et);return ot?{...a,...ot,cardButton:{...a.cardButton,...ot.cardButton},cardFormContainer:{...a.cardFormContainer,...ot.cardFormContainer},backButton:{...a.backButton,...ot.backButton},backButtonIcon:{...a.backButtonIcon,...ot.backButtonIcon},submitButton:{...a.submitButton,...ot.submitButton},title:{...a.title,...ot.title}}:a},[p,et,ot]),k=kt??p?.appearance,Re=Tt(()=>Ts({appearance:k,buttonsStyles:s,layout:re}),[k,s,re]),ke=T.inlineSessionPatchProcessing??!1,b=(M??Le)||ke,K=Me.replace(/\/+$/,""),F=Tt(()=>ti({userId:i,email:o,firstName:f,lastName:g,country:J,zip:Ie},xt),[i,o,f,g,J,Ie,xt]),wt=[F.firstName,F.lastName].filter(a=>!!a?.trim()).join(" "),Ot=!ln(F.email?.trim()),Vn=de(null);qe&&Vn.current===null&&(Vn.current=Ot);let be=qe&&(Vn.current??Ot),te=Tt(()=>Xd(pt,be),[pt,be]),ae=te.empty||te.malformed,V=Tt(()=>bt?bt.getRawProvider():null,[bt]),He=Tt(()=>Xe?Xe.getRawProvider():null,[Xe]),tn=je||100,Oe=Je.toLowerCase(),rr=Tt(()=>k?pd(k):null,[k]),xn=rr,Ji=Tt(()=>{let a=rr??{},P=a.rules??{};return{...a,rules:{...P,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...P[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...P[".AccordionItemContents"]??{}}}}},[rr]),Xi=Tt(()=>({...Us(je,x?.captureMethod),currency:Oe,...xn?{appearance:xn}:null}),[je,Oe,x?.captureMethod,xn]),Zi=Tt(()=>({mode:"payment",amount:tn,currency:Oe,captureMethod:"manual",setupFutureUsage:"off_session",...xn?{appearance:xn}:null}),[tn,Oe,xn]),ce=Ge(a=>{rn(a),Be?.(a)},[Be]),Na=de(""),[Qi,jl]=ie(!1),La=Ge(()=>{jl(!0)},[]);yt(()=>{if(!qe||!be||!I||!Qi||ae||Na.current)return;let a=An({email:ln(F.email?.trim())?F.email?.trim():Ln.current.trim(),firstName:F.firstName?.trim(),lastName:F.lastName?.trim()});Na.current=JSON.stringify(a),Nn(P=>({...P,...a})),Promise.resolve(I(a)).catch(P=>{Na.current="",ce(P instanceof Error?P.message:"Failed to attach buyer details.")})},[qe,be,I,Qi,ae,F.email,F.firstName,F.lastName,ce]),yt(()=>{!qe||!at||at.setCardFieldOrder?.(tt??null,D==null&&!be)},[qe,at,tt,D,be]),yt(()=>{(We==="expanding"||We==="collapsing"||We==="apm-expanding"||We==="apm-collapsing")&&ce(null)},[We,ce]);let dr=Ge((a,P,O)=>{h?.(nn(a,P,O))},[h]),Hr=Ge((a,P,O)=>{let xe=O?.popupBlocked??Pr(P),U=Gd(a,xe),it=jr(O?.code)??vr(P)??"external_payment_method_failed",Ze=new ir(U,"api_error",{code:"external_payment_method_failed",param:a});y(null),re==="buttons"&&($t("buttons"),Ir(null)),ce(U),c?.(Ze),console.error("[FloPay] External payment method failed:",{method:a,code:it,popupBlocked:xe})},[re,c,ce]);yt(()=>{if(!qe||!e){jn(null);return}let a=Ri(x?.vault);if(a){jn(a);return}if(!S){jn(null);return}jn(null);let P=!0;return new fo(K).getVaultCapture(e,t).then(O=>{if(!P)return;let xe=Ri(O);xe?jn(xe):ce("Failed to load the secure card form.")}).catch(O=>{P&&ce(O instanceof Error?O.message:"Failed to load the secure card form.")}),()=>{P=!1}},[qe,S,mn,e,x?.vault,K,t,ce]);let ur=de({onComplete:l,onError:c,updateError:ce,emitDecline:dr,resolvedAccount:F,avsConfig:D,avsCheckProp:j,sessionId:e,nonce:t,baseUrl:K,captureMethod:x?.captureMethod,paymentId:x?.paymentId,authorizationExpiresAt:x?.authorizationExpiresAt});ur.current={onComplete:l,onError:c,updateError:ce,emitDecline:dr,resolvedAccount:F,avsConfig:D,avsCheckProp:j,sessionId:e,nonce:t,baseUrl:K,captureMethod:x?.captureMethod,paymentId:x?.paymentId,authorizationExpiresAt:x?.authorizationExpiresAt};let Oa=de(!1),es=Ge(()=>{let a=ur.current,P=a.resolvedAccount.email?.trim(),O=ln(P)?P:Ln.current.trim();if(!ln(O))return null;let xe=a.resolvedAccount.firstName?.trim(),U=a.resolvedAccount.lastName?.trim(),it=ft.current||a.resolvedAccount.country||"US",Ze=a.avsConfig?Qe(a.avsConfig.state,it):!1,rt=a.avsConfig?Qe(a.avsConfig.address_line_1,it):!1,It=a.avsConfig?Qe(a.avsConfig.postal_code,it):!1,Bt=a.avsConfig?Qe(a.avsConfig.city,it):!1,Ut=a.avsConfig?Qe(a.avsConfig.address_line_2,it):!1,Rt=rt&&!Ze&&It?ll(it,(mt.current??"").trim()):null,Hn=Ze?Ct.current:Rt;return{accountData:{userId:a.resolvedAccount.userId??"",email:O,...xe?{firstName:xe}:{},...U?{lastName:U}:{},...It&&mt.current?{zip:mt.current}:{},...Bt&&Dt.current?{city:Dt.current}:{},...Hn?{state:Hn}:{},...rt&&cn.current?{addressLine1:cn.current}:{},...Ut&&dn.current?{addressLine2:dn.current}:{},country:it},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:Qe(a.avsConfig.country,it),postal_code:It,address_line_1:rt,address_line_2:Ut,city:Bt,state:Ze}}:{}}},[]),ts=de(fe);ts.current=fe,yt(()=>{fe||ee!==yl||ur.current.updateError(null)},[fe,ee]),yt(()=>{!qe||!at||at.setSubmitGate?.(nt||fe||ae)},[qe,at,nt,fe,ae]),yt(()=>{if(!qe||!at)return;Oa.current=!1;let a=null,P=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,N.current="idle",y(null)},400)},O=at.on("submitting",()=>{zn(!0),A.current&&clearTimeout(A.current),N.current="validation-window",A.current=setTimeout(()=>{A.current=null,N.current==="validation-window"&&(N.current="processing")},Od),y("processing");let rt=ur.current;if(!rt.sessionId||!rt.nonce)return;let It=es();if(!It){rt.updateError("Enter a valid email address."),N.current="idle",y(null);return}new fo(rt.baseUrl).patchAccountSnapshot(rt.sessionId,rt.nonce,It,{telemetryMode:"best_effort"}).catch(Bt=>{if(!zd(Bt))return;let Ut=Bt instanceof Error?Bt.message:"Please check your billing address and try again.";rt.updateError(Ut),N.current="idle",y(null),rt.onError?.(Bt instanceof ir?Bt:new ir(Ut,"api_error"))})}),xe=at.on("complete",async rt=>{if(mo(rt.sessionId??ur.current.sessionId),N.current="terminal",y("success"),await new Promise(Ut=>setTimeout(Ut,600)),Oa.current)return;Oa.current=!0;let It=ur.current,Bt=Ci(It)||rt.outcome==="authorized";ur.current.onComplete?.(Bt?{status:"authorized",paymentIntentId:rt.intentId,paymentId:rt.paymentId??It.paymentId,sessionId:rt.sessionId??It.sessionId,authorizationExpiresAt:rt.authorizationExpiresAt??It.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:rt.intentId,checkoutMethod:"card"})}),U=at.on("decline",rt=>{let It=ur.current,Bt=rt.message??"Your payment was declined. Please try another card or contact your bank.";N.current="terminal",It.updateError(Bt),y("error");let Ut=rt.failureOutcome??Cd(rt.declineReason)??"authorization_declined";It.emitDecline("card",Bt,{code:Ut,declineCode:Ut}),P()}),it=at.on("error",rt=>{let It=ur.current,Bt=rt.message??"There was a problem processing your payment. Please try again.";N.current="terminal",It.updateError(Bt),y("error"),It.onError?.(new ir(Bt,"api_error",{code:rt.failureOutcome??"capture_failed"})),P()}),Ze=at.on("blocked",()=>{if(!ts.current){zn(!0);return}La(),ur.current.updateError(yl)});return()=>{a&&(clearTimeout(a),a=null),A.current&&(clearTimeout(A.current),A.current=null),N.current="idle",y(null),O(),xe(),U(),it(),Ze()}},[qe,at,La,es]);let pr=!!he?.clientId,So=Array.isArray(Y),Qo=So&&Y.length>0,$l=So&&Y.includes("paypal"),{expressMethods:ea,paymentElementMethods:wo}=Tt(()=>Sd(Y,{excludePaypal:pr}),[Y,pr]),ns=pr||!!Xe,Kl=Tt(()=>ns?ea.filter(a=>a!=="paypal"):ea,[ea,ns]),Vl=Tt(()=>{let a=[];return se&&a.push("apple_pay"),Fe&&a.push("google_pay"),a},[se,Fe]),Gr=So?Kl:Vl,Wl=C&&Gr.length>0,za=sr?_t:J,ta=Tt(()=>{let a=za?.trim().toUpperCase();return a?Q?wo.filter(P=>{let O=Q[P];return!O||O.length===0||O.includes(a)}):fd(wo,za):wo},[wo,za,Q]),Ua=Tt(()=>({mode:"payment",amount:tn,currency:Oe,paymentMethodCreation:"manual",appearance:Ji}),[tn,Oe,Ji]),[rs,os]=ie("loading"),[as,is]=ie("loading"),[ss,ls]=ie("loading"),[Hl,qa]=ie(!1),[cs,ja]=ie("loading"),[$a,Gl]=ie();yt(()=>{Gl(ma())},[]);let na=$a?.inAppBrowser,ra=$a?ya($a,he?.approvalPresentation,w??($e?"subscription":"order")):"popup",ds=oe&&(pr||(So?$l:na===!1)),us=C&&Wl,Io=(!ut||!!T.waitForDataAttachment)&&ds&&pr,ps=cs==="retrying"||cs==="exhausted",ko=!ut&&ds&&!!He&&(!pr||ps),Yr=!ut&&us&&!!V,_o=!ut&&C&&Qo&&ta.length>0&&!!V,Yl=Io&&!ps?Hl:ko&&Pl(rs),Jl=Yr&&Pl(as),Xl=_o&&ss!=="load_error",ms=a=>a==="loading"||a==="ready",ys=Io||ko&&ms(rs)||Yr&&ms(as)||_o&&ss!=="load_error",oa=de(!1);yt(()=>{if(!oa.current){if(!C&&!oe){oa.current=!0;let a=new ir("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(a),ce(a.message)}else if(!C&&oe&&!pr&&!He){oa.current=!0;let a=new ir("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(a),ce(a.message)}else if(na!==void 0&&!ut&&!pn&&!ys){oa.current=!0;let a=new ir("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"});c?.(a),ce(a.message)}}},[C,oe,pr,He,na,ut,pn,ys,c,ce]);let fs=de(!1);yt(()=>{if(fs.current||!Qo)return;let a=[];se!==!0&&a.push("showApplePay"),Fe!==!0&&a.push("showGooglePay"),a.length!==0&&(fs.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.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.`))},[Qo,se,Fe]);let gs=Ge((a,P)=>T.applyInlineSessionPatch?T.applyInlineSessionPatch(a).then(O=>({error:null,sessionId:O.sessionId||e,nonce:O.session?.clientSecret||t})).catch(O=>{let xe=vl(P,O);return ce(xe.message),c?.(xe),{error:xe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[T.applyInlineSessionPatch,t,c,e,ce]),or=Ge(async a=>{if(a!=="card"&&ut&&await T.waitForDataAttachment?.(),!me)return{proceed:!0};try{let P=await me({method:a,sessionId:e||void 0,createSession:T.inlineSessionDraft});if(P===!1)return{proceed:!1};if(P&&typeof P=="object"){P.account&&Nn(xe=>({...xe??{},...P.account}));let O=await gs(P,a);return O.error?{proceed:!1,accountPatch:P.account}:{proceed:!0,accountPatch:P.account,sessionId:O.sessionId,nonce:O.nonce}}return{proceed:!0}}catch(P){let O=vl(a,P);return ce(O.message),c?.(O),{proceed:!1}}},[gs,T.inlineSessionDraft,T.waitForDataAttachment,ut,me,c,e,ce]),hs=Ge(async(a,P)=>{if(R.current)return;R.current=!0,lt(!0),y("processing"),ce(null);let O=P?.sessionId??e,xe=P?.nonce??t,U=ti(F,P?.accountPatch),it=P?.completionPaymentMethodId??Lo(a),Ze=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,rt=Kd(a),It=()=>{Ne?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:rt})};try{let Ut=await new fo(K).processPayment(U.userId??"",{sessionId:O,nonce:xe,paymentMethodCategory:P?.paymentMethodCategory??Wd(a),tokenizedData:Ze,accountData:{...P?.accountPatch,userId:U.userId??"",email:U.email??"",firstName:U.firstName||void 0,lastName:U.lastName||void 0,...D?(()=>{let vt=ft.current,Gn=Qe(D.state,vt),bn=Qe(D.address_line_1,vt),Yt=Qe(D.postal_code,vt),zr=bn&&!Gn&&Yt?ll(vt,(mt.current??"").trim()):null,xo=Gn?Ct.current:zr;return{country:vt,...Yt&&mt.current?{zip:mt.current}:{},...Qe(D.city,vt)&&Dt.current?{city:Dt.current}:{},...xo?{state:xo}:{},...bn&&cn.current?{addressLine1:cn.current}:{},...Qe(D.address_line_2,vt)&&dn.current?{addressLine2:dn.current}:{}}})():{}},chv:m,avsCheck:j??!1,checkoutType:q,checkoutLayout:$,avsConfig:D?{country:Qe(D.country,ft.current),postal_code:Qe(D.postal_code,ft.current),address_line_1:Qe(D.address_line_1,ft.current),address_line_2:Qe(D.address_line_2,ft.current),city:Qe(D.city,ft.current),state:Qe(D.state,ft.current)}:void 0});if(Ut.ok){let vt=Ut.status===204?null:await Ut.json().catch(()=>null),Gn=Ci(x)||vt?.status==="authorized";mo(O),y("success"),ht(null),await new Promise(zr=>setTimeout(zr,600));let bn;typeof vt?.paymentId=="string"?bn=vt.paymentId:x?.paymentId&&(bn=x.paymentId);let Yt;typeof vt?.authorizationExpiresAt=="string"?Yt=vt.authorizationExpiresAt:x?.authorizationExpiresAt&&(Yt=x.authorizationExpiresAt),l?.(Gn?{status:"authorized",...bn===void 0?{}:{paymentId:bn},sessionId:typeof vt?.sessionId=="string"?vt.sessionId:O,...Yt===void 0?{}:{authorizationExpiresAt:Yt},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:it,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:it,checkoutMethod:a.isPaypal?"paypal":"card"});return}let Rt=await Ut.json().catch(()=>null);if(Rt?.type==="paypal_redirect_required"){let vt=Rt.threeDSecureToken,Gn=Rt.paymentMethodId||a.id||"";if(!bt||!vt){y("error"),ce("PayPal authorization required but no token provided.");return}try{let bn=Xe?.getRawProvider();if(!bn){ce("PayPal is not available.");return}let Yt={return_url:window.location.href};Gn&&(Yt.payment_method=Gn);let{error:zr}=await bn.confirmPayment({clientSecret:vt,confirmParams:Yt,redirect:"if_required"});if(zr){y("error");let xo=zr.message??"PayPal payment failed.";ce(xo),dr("paypal",xo,{code:zr.code})}}catch(bn){y("error"),ce(bn instanceof Error?bn.message:"PayPal authorization failed.")}return}if(Rt?.type==="paypal_direct_required"){let vt=Rt.orderId;if(!vt){y("error"),ce("PayPal retry required but no order id provided.");return}let Gn=we.current?.attempts??0;if(Gn>=2){y("error"),ce("PayPal payment could not be completed after multiple attempts."),dr("paypal","paypal_direct_required retry limit exceeded");return}qa(!1),ja("loading"),ht({orderId:vt,attempts:Gn+1}),y(null);return}yd(Ut.status,Rt)||It(),y("error");let Hn=Rt?.message??"Payment failed. Please try again.";ce(Hn),dr(a.isPaypal?"paypal":"card",Hn,{code:Rt?.code??Rt?.gatewayErrorCode,declineCode:Rt?.declineCode??Rt?.gatewayDeclineReason}),await new Promise(vt=>setTimeout(vt,400))}catch(Bt){_l(Bt)||It(),y("error"),ce(Bt instanceof Error?Bt.message:"An unexpected error occurred"),await new Promise(Ut=>setTimeout(Ut,400))}finally{lt(!1),y(null),R.current=!1}},[K,e,t,F,D,j,q,$,m,bt,Xe,x,l,ce,dr,Ne]),En=Ge((a,P)=>{v?v(a):hs(a,P)},[v,hs]),Ro=`${Il}:${e}`;yt(()=>{if(typeof window>"u")return;let a=localStorage.getItem(Ro);if(!a)return;let P;try{P=JSON.parse(a)}catch{localStorage.removeItem(Ro);return}if(!P||typeof P.createdAt!="number"||Date.now()-P.createdAt<0||Date.now()-P.createdAt>kl||typeof P.paymentMethodId!="string"||typeof P.providerIntentId!="string"||typeof P.paymentMethodType!="string"||P.sessionId!==e||!t||P.nonce!==t||!Gr.includes(P.paymentMethodType)){localStorage.removeItem(Ro);return}localStorage.removeItem(Ro),En({id:P.paymentMethodId,type:"card",threeDSecureActionResultTokenId:P.providerIntentId,gateway:"stripe",paymentMethodType:P.paymentMethodType},{...P.accountPatch?{accountPatch:P.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[En,t,e,Ro,Gr]);let vs=de(!1);yt(()=>{if(typeof window>"u"||vs.current)return;let a=new URLSearchParams(window.location.search),P=a.get("payment_intent"),O=a.get("payment_intent_client_secret"),xe=a.get("redirect_status");if(!P||!O||!bt)return;let U=bt.getRawProvider();if(!U)return;let it=Rt=>{let Hn=localStorage.getItem(Rt);if(!Hn)return null;try{return JSON.parse(Hn)}catch{return localStorage.removeItem(Rt),null}},Ze=it(yr)??it(ul),rt;if(Ze?.clientSecret){if(Ze.clientSecret!==O)return;rt={...Ze.accountPatch?{accountPatch:Ze.accountPatch}:{},...Ze.sessionId?{sessionId:Ze.sessionId}:{},...Ze.nonce?{nonce:Ze.nonce}:{}}}else if(Ze?.sessionId&&Ze.sessionId!==e)return;vs.current=!0,localStorage.removeItem(yr),localStorage.removeItem(ul);let It=new URL(window.location.href);It.searchParams.delete("payment_intent"),It.searchParams.delete("payment_intent_client_secret"),It.searchParams.delete("redirect_status"),window.history.replaceState({},"",It.toString());let Bt=Ze?.paymentMethodType??Ze?.tokenType??"card",Ut="card";(async()=>{if(xe==="failed"){let Yt="Payment was declined. Please try again.";ce(Yt),dr(Ut,Yt);return}let{paymentIntent:Rt,error:Hn}=await U.retrievePaymentIntent(O);if(Hn){let Yt=Hn.message??"Failed to retrieve payment status.";ce(Yt),dr(Ut,Yt,{code:Hn.code});return}let vt=Rt?.status,Gn=No(vt);if(!Rt||!Gn){let Yt=vt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ce(Yt),dr(Ut,Yt,{code:vt??"missing_payment_intent"});return}let bn=typeof Rt.payment_method=="string"?Rt.payment_method:Rt.payment_method?.id;En({id:bn??Ze?.paymentMethodId??Ze?.tokenId??Rt.id,type:"card",threeDSecureActionResultTokenId:Rt.id,gateway:Ze?.gateway??"stripe",paymentMethodType:Bt},rt)})()},[e,En,bt,ce,dr]);let Ka=Ge(a=>{a.preventDefault()},[]);if(!(qe||bt!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Eo=re==="buttons",Tn=k?.variables,Zl=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Va=Tn?.colorBackground,Ql=Va&&!Zl.has(Va)?Va:void 0,To=s.cardInputBorder??(Eo?"#e5e7eb":"#A4A4FF"),Ps=Tn?.colorDanger??"#dc2626",zt=a=>Dr[a]&&(lr[a]||Sr),aa=ae&&(Un||Sr),Wn=a=>a?Ps:To,ia=(yn.malformed||yn.empty)&&(wr||Sr),ec=Wn(ia),Wa=s.cardFormContainer?.backgroundColor??Ql??(Eo?"white":"#EDEDFF"),Jr=s.cardInputBackground??Tn?.colorBackground??"white",Ha=Qr(De),bs=Qr(ue),Xr=s.nameInput,Cs=s.cardInputFontSize??Zd(Xr?.fontSize)??Tn?.fontSizeBase??"16px",Ss=typeof Xr?.fontFamily=="string"?Xr.fontFamily:Tn?.fontFamily??"Poppins, sans-serif",ws=Es(Xr?.fontWeight)??400,tc=s.cardInputColor??(typeof Xr?.color=="string"?Xr.color:void 0)??Tn?.colorText??"#262833",nc=s.cardInputPlaceholderColor??"#9ca3af",Kt=Tn?.borderRadius??"8px",Lr=Tn?.borderRadius??s.cardButton?.borderRadius??Kt,Or=Tn?.colorPrimary??"#4A49FF",rc=Tn?.colorPrimaryHover??Fo(Or,.12),Ga=Tn?.colorText??"#262833",Ya={fontSize:Cs,fontFamily:Ss,fontWeight:ws,color:tc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ao={marginTop:"0.375rem",...Ya,fontSize:"0.75rem",lineHeight:1.4,color:Ps},oc={"--flopay-input-placeholder-color":nc,"--flopay-input-font-size":Cs,"--flopay-input-font-family":Ss,"--flopay-input-font-weight":String(ws)},Mo=s.cardFormContainer??{},Ja=Mo.padding??(Eo?"0":"1rem"),Xa=Mo.borderRadius??Kt,ac=at&&Rn?d(Za,{capture:at,html:Rn.html,messageToken:Rn.messageToken,expectedOrigin:Rn.expectedOrigin,theme:Re,onReady:()=>{if(!be&&!D||typeof document>"u")return;let a=()=>{let O=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(O){Qn.current=!0;try{O.focus()}finally{Qn.current=!1}}};er.current||a()},onError:a=>ce(a),onValidation:a=>{let P=N.current;(P==="idle"||P==="validation-window")&&(ce(a),a&&N.current==="validation-window"&&(A.current&&(clearTimeout(A.current),A.current=null),N.current="idle",y(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"}),Is=ze("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&$n()},style:{backgroundColor:Wa,borderRadius:Xa,...Mo,padding:Ja,...oc,display:"flex",flexDirection:"column"},children:[d("style",{children:`
26
26
  .flopay-shared-input::placeholder {
27
27
  color: var(--flopay-input-placeholder-color);
28
28
  opacity: 1;
@@ -30,13 +30,13 @@ ${cn.join(`
30
30
  font-family: var(--flopay-input-font-family);
31
31
  font-weight: var(--flopay-input-font-weight);
32
32
  }
33
- `}),Eo&&Co&&Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:We?-2:0},children:[Le("button",{type:"button",onClick:kr,style:{display:"inline-flex",alignItems:"center",gap:Va?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:s.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...s.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",...s.backButtonIcon},children:d("svg",{"aria-hidden":"true",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(to,{content:Me})]}),ms?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:s.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...s.title},children:d(Do,{content:le})})]}),!Eo&&!ms&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ha,order:We?-3:0,...s.title},children:d(Do,{content:le})}),We&&Ze&&d("div",{style:{order:-2,width:"100%"},children:Ze}),We&&me&&Le("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[d("div",{style:{backgroundColor:Jr,border:`1px solid ${$n(aa)}`,borderRadius:qt,padding:"10px"},children:d("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:St,onChange:o=>{ft("email"),fe.current=o.target.value,Cn(o.target.value)},onPointerDown:()=>ft("email"),onKeyDown:()=>ft("email"),onBlur:()=>{Ln("email")&&Xt(!0),re||Da()},disabled:C,required:!0,"aria-invalid":aa||void 0,"aria-describedby":aa?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Wa}})}),aa&&d("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Ao,children:Z.empty?"Email address is required":"Enter a valid email address"})]}),E&&d("div",{style:{order:We?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let o=Rt,b=(U=!1)=>({backgroundColor:Jr,border:`1px solid ${$n(U)}`,borderRadius:qt,marginTop:"0.5rem",padding:"10px"}),N=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Wa}),Ee=id(o);return Le(Vr,{children:[Ye(E.address_line_1,o)&&Le(Vr,{children:[d("div",{style:b(Nt("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:Fe,onChange:U=>{ft("line1"),ut.current.addressLine1=!0,gn.current=U.target.value,pt(U.target.value)},onPointerDown:()=>ft("line1"),onKeyDown:()=>ft("line1"),onBlur:()=>kn("line1"),disabled:C,required:!0,"aria-invalid":Nt("line1")||void 0,"aria-describedby":Nt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:N()})}),Nt("line1")&&d("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Ao,children:"Street address is required"})]}),Ye(E.address_line_2,o)&&d("div",{style:b(),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:fn,onChange:U=>{ut.current.addressLine2=!0,Kt.current=U.target.value,$t(U.target.value)},disabled:C,"data-testid":"flopay-address-line2",style:N()})}),(Ye(E.city,o)||Ye(E.state,o))&&Le("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Ye(E.city,o)&&d("div",{style:{flex:1,backgroundColor:Jr,borderTop:`1px solid ${$n(Nt("city"))}`,borderRight:`1px solid ${$n(Nt("city"))}`,borderBottom:`1px solid ${$n(Nt("city"))}`,borderLeft:`1px solid ${$n(Nt("city"))}`,padding:"10px",borderTopLeftRadius:qt,borderBottomLeftRadius:qt,...Ye(E.state,o)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:qt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:dn,onChange:U=>{ft("city"),ut.current.city=!0,tn.current=U.target.value,Yt(U.target.value)},onPointerDown:()=>ft("city"),onKeyDown:()=>ft("city"),onBlur:()=>kn("city"),disabled:C,required:!0,"aria-invalid":Nt("city")||void 0,"aria-describedby":Nt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:N()})}),Ye(E.state,o)&&d("div",{style:{flex:1,backgroundColor:Jr,borderTop:`1px solid ${$n(Nt("state"))}`,borderRight:`1px solid ${$n(Nt("state"))}`,borderBottom:`1px solid ${$n(Nt("state"))}`,borderLeft:`1px solid ${$n(Nt("state"))}`,padding:"10px",borderTopRightRadius:qt,borderBottomRightRadius:qt,...Ye(E.city,o)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${$n(Nt("state")||Nt("city"))}`}:{borderRadius:qt}},children:Ee?Le("select",{id:"flopay-billing-state",name:"billing-state",value:Ct,onChange:U=>{ft("state"),ut.current.state=!0,wt.current=U.target.value,bn(U.target.value)},onPointerDown:()=>ft("state"),onKeyDown:()=>ft("state"),onBlur:()=>kn("state"),disabled:C,autoComplete:"billing address-level1",required:!0,"aria-invalid":Nt("state")||void 0,"aria-describedby":Nt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...N(),cursor:"pointer"},children:[d("option",{value:"",children:vi(o)}),Ee.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:vi(o),autoComplete:"billing address-level1",value:Ct,onChange:U=>{ft("state"),ut.current.state=!0,wt.current=U.target.value,bn(U.target.value)},onPointerDown:()=>ft("state"),onKeyDown:()=>ft("state"),onBlur:()=>kn("state"),disabled:C,required:!0,"aria-invalid":Nt("state")||void 0,"aria-describedby":Nt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:N()})})]}),Nt("city")&&d("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Ao,children:"City is required"}),Nt("state")&&Le("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Ao,children:[vi(o)," is required"]}),(Ye(E.country,o)||Ye(E.postal_code,o))&&Le("div",{style:{display:"flex",flexDirection:B==="column"?"column":"row",gap:B==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Ye(E.country,o)&&d("div",{style:{flex:B==="row"?1:void 0,backgroundColor:Jr,borderTop:`1px solid ${To}`,borderRight:`1px solid ${To}`,borderBottom:`1px solid ${To}`,borderLeft:`1px solid ${To}`,padding:"10px",...B==="row"&&Ye(E.postal_code,o)?{borderRadius:"0",borderTopLeftRadius:qt,borderBottomLeftRadius:qt,borderRight:"none"}:{borderRadius:qt}},children:d("select",{id:"flopay-billing-country",name:"billing-country",value:Rt,onChange:U=>{ut.current.country=!0,yt.current=U.target.value,ve(U.target.value),xt?.(U.target.value),wt.current="",bn("")},disabled:C,autoComplete:"billing country","data-testid":"flopay-country",style:{...N(),cursor:"pointer"},children:nd.map(U=>Le("option",{value:U.code,children:[U.flag," ",U.name]},U.code))})}),Ye(E.postal_code,o)&&d("div",{style:{flex:B==="row"?1:void 0,backgroundColor:Jr,border:`1px solid ${Kl}`,padding:"10px",...B==="row"&&Ye(E.country,o)?{borderRadius:"0",borderTopRightRadius:qt,borderBottomRightRadius:qt}:{borderRadius:qt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:ki(Rt),autoComplete:"billing postal-code",value:mn,onChange:U=>{ft("zip"),ut.current.zip=!0,dt.current=U.target.value,yn(U.target.value),rt?.(U.target.value)},onPointerDown:()=>ft("zip"),onKeyDown:()=>ft("zip"),onBlur:()=>{Ln("zip")&&yr(!0)},disabled:C,required:un.required,"aria-invalid":ia||void 0,"aria-describedby":ia?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:N()})})]}),ia&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Ao,children:un.empty?`${ki(o)} is required`:Dd(o)})]})})()}),We&&Yl,X&&d(co,{margin:"0.75rem 0",styleOverride:s.errorBanner,children:X})]}),sa={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"},vs=o=>H?!ne||!lr?d("pre",{"data-testid":o,style:sa,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":o,style:sa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ne}`,` directPaypalConfigured=${lr}`,` inAppBrowserDetected=${String(na)}`,` shouldRenderDirectPayPal=${ko}`,` shouldRenderStripePayPal=${Io}`,` hasPaypalStripeInstance=${!!qe}`].join(`
34
- `)}):null,Ps=o=>H?!S||!K?d("pre",{"data-testid":o,style:sa,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":o,style:sa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${S}`,` currency=${Qe}`,` amountInCents=${on}`,` enabledPaymentMethods: ${JSON.stringify(G??[])}`,` enabledPaymentMethodsProvided=${So}`,` hasEnabledMethods=${Qo}`,` expressMethods: ${JSON.stringify(ea)}`,` walletExpressMethods: ${JSON.stringify(Gr)}`,` paymentElementMethods: ${JSON.stringify(wo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(ta)}`,` hasStripeInstance=${!!K}`,` shouldRenderWallets=${Yr}`,` shouldRenderPaymentElement=${_o}`].join(`
35
- `)}):null,bs=Ue==="apm-expanding"||Ue==="apm-form"||Ue==="apm-collapsing",Zr;Ue==="apm-expanding"?Zr=al:Ue==="apm-collapsing"&&(Zr=il);let la=Ht?bl(Oa,Ht):null;if(ie==="buttons"){let o=Ue==="buttons"||Ue==="expanding"||Ue==="apm-expanding",b=Ue==="expanding"||Ue==="card"||Ue==="collapsing",N=Ne===void 0?{boxSizing:"border-box",height:Ra,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ee;Ue==="expanding"||Ue==="apm-expanding"?Ee=Td:(Ue==="collapsing"||Ue==="apm-collapsing")&&(Ee=Ed);let U;return Ue==="expanding"?U=al:Ue==="collapsing"&&(U=il),Le("form",{onSubmit:$a,className:I,noValidate:!0,style:{position:"relative"},children:[d(wi,{}),rn&&d(cr,{status:rn,errorMessage:X,authorized:zt}),Le("div",{style:{display:"grid"},children:[Le("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!o&&!Ee?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!o&&!Ee?Md:{},...Ee?{animation:Ee,pointerEvents:"none"}:{}},children:[vs("flopay-direct-paypal-gate-debug"),Ps("flopay-stripe-gate-debug"),ko&&_e&&Le(Vr,{children:[Ce&&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(va,{sessionId:e,nonce:t,billingApiUrl:te,email:x.email,billingName:kt||void 0,onBuyerIdentityReady:w,clientId:_e.clientId,environment:_e.environment,currency:Qe.toUpperCase(),isSubscription:Ve,providerObjectType:T,approvalPresentation:ra==="popup"?void 0:ra,onTokenizedBody:_n,onComplete:c,onErrorChange:se,onDecline:h,onTechnicalFailure:Wr,onButtonClick:ce,runBeforeButtonClick:er,isProcessing:C,onLoadStateChange:za,onInitializationStateChange:Ua,session:v,existingOrderId:Ce?.orderId,debug:H},Ce?.orderId??"fresh")]}),Io&&d(Kr,{stripe:qe,options:Vi,children:d(dl,{sessionId:e,nonce:t,email:x.email,billingName:kt||void 0,onBuyerIdentityReady:w,billingApiUrl:te,onTokenizedBody:_n,onErrorChange:se,isProcessing:C,onButtonClick:ce,onDecline:h,onTechnicalFailure:Wr,runBeforeButtonClick:er,onLoadStateChange:Xi,placeholderBorderRadius:Lr})}),Yr?d(Kr,{stripe:K,options:Ki,children:d(ul,{sessionId:e,nonce:t,email:x.email,billingName:kt||void 0,onBuyerIdentityReady:w,billingApiUrl:te,intentKind:xe>0?"payment":"setup",expressMethods:Gr,onTokenizedBody:_n,onErrorChange:se,onButtonClick:ce,onDecline:h,onTechnicalFailure:Wr,runBeforeButtonClick:er,onLoadStateChange:Qi,placeholderBorderRadius:Lr})}):null,!Yr&&os?d("div",{style:{height:Ra,borderRadius:Lr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,_o&&d(pl,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:w,billingApiUrl:te,paymentElementMethods:ta,stripeInstance:K,paymentElementBaseOptions:Oa,onTokenizedBody:_n,onErrorChange:se,onButtonClick:ce,onDecline:h,runBeforeButtonClick:er,onLoadStateChange:ts,isProcessing:C,submitButtonColor:Or,submitButtonBorderRadius:qt,submitButtonStyle:s.submitButton,onExpandApm:Xn,expandedApmMethod:Ht,themeId:ze,buttonAppearance:{backgroundColor:s.cardButton?.backgroundColor,borderColor:s.cardInputBorder,textColor:s.cardButton?.color,borderRadius:Lr}}),We&&d("button",{type:"button",onClick:async()=>{C||!(await er("card")).proceed||(ce?.("card"),Nr())},disabled:C,style:{width:"100%",...N,...s.cardButton,...Ai({themeBundle:u,resolvedPrimaryColor:Or,resolvedBorderRadius:qt,submitButtonStyle:s.submitButton,explicitPrimaryColor:Rn?.colorPrimary}),fontSize:s.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:at=>{!C&&(u||Rn?.colorPrimary)&&(at.currentTarget.style.backgroundColor=Wl)},onMouseLeave:at=>{(u||Rn?.colorPrimary)&&(at.currentTarget.style.backgroundColor=Or)},onMouseDown:at=>{at.currentTarget.style.transform="scale(0.985)"},onMouseUp:at=>{at.currentTarget.style.transform="scale(1)"},children:d(eo,{content:Ne})}),X&&Ue==="buttons"&&d(co,{margin:"0.25rem 0",styleOverride:s.errorBanner,children:X})]}),We&&b&&d("div",{style:{gridArea:"1 / 1",...U?{animation:U}:{},...Ue==="collapsing"?{pointerEvents:"none"}:{}},children:hs}),S&&bs&&Ht&&la&&K&&d("div",{style:{gridArea:"1 / 1",...Zr?{animation:Zr}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Ka,borderRadius:Ya,...Mo,padding:Ga},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Zn,style:{display:"inline-flex",alignItems:"center",gap:Va?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:s.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...s.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",...s.backButtonIcon},children:d("svg",{"aria-hidden":"true",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(to,{content:Me})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:s.titleFontSize??"1.05rem",color:Ha,paddingRight:80,...s.title},children:`Pay with ${Hr(Ht)}`})]}),d(Kr,{stripe:K,options:la,children:d(_i,{method:Ht,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:w,billingApiUrl:te,onTokenizedBody:_n,onErrorChange:se,onDecline:h,onCancel:Zn,runBeforeButtonClick:er,onButtonClick:ce,isProcessing:C,submitButtonColor:Or,submitButtonBorderRadius:qt,submitButtonStyle:s.submitButton,errorText:X})},Ht)]})})]})]})}return bs&&Ht&&la&&K&&S?Le("form",{onSubmit:$a,className:I,noValidate:!0,style:{position:"relative"},children:[d(wi,{}),rn&&d(cr,{status:rn,errorMessage:X,authorized:zt}),d("div",{style:{...Zr?{animation:Zr}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:Ka,borderRadius:Ya,...Mo,padding:Ga},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Zn,style:{display:"inline-flex",alignItems:"center",gap:Va?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:s.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...s.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",...s.backButtonIcon},children:d("svg",{"aria-hidden":"true",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(to,{content:Me})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:s.titleFontSize??"1.05rem",color:Ha,paddingRight:80,...s.title},children:`Pay with ${Hr(Ht)}`})]}),d(Kr,{stripe:K,options:la,children:d(_i,{method:Ht,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:w,billingApiUrl:te,onTokenizedBody:_n,onErrorChange:se,onDecline:h,onCancel:Zn,runBeforeButtonClick:er,onButtonClick:ce,isProcessing:C,submitButtonColor:Or,submitButtonBorderRadius:qt,submitButtonStyle:s.submitButton,errorText:X})},Ht)]})})]}):Le("form",{onSubmit:$a,className:I,noValidate:!0,style:{position:"relative"},children:[d(wi,{}),rn&&d(cr,{status:rn,errorMessage:X,authorized:zt}),Le("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[vs("flopay-direct-paypal-gate-debug-default"),Ps("flopay-stripe-gate-debug-default"),ko&&_e&&Le(Vr,{children:[Ce&&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(va,{sessionId:e,nonce:t,billingApiUrl:te,email:x.email,billingName:kt||void 0,onBuyerIdentityReady:w,clientId:_e.clientId,environment:_e.environment,currency:Qe.toUpperCase(),isSubscription:Ve,providerObjectType:T,approvalPresentation:ra==="popup"?void 0:ra,onTokenizedBody:_n,onComplete:c,onErrorChange:se,onDecline:h,onTechnicalFailure:Wr,onButtonClick:ce,runBeforeButtonClick:er,isProcessing:C,onLoadStateChange:za,onInitializationStateChange:Ua,session:v,existingOrderId:Ce?.orderId,debug:H},Ce?.orderId??"fresh")]}),Io&&d(Kr,{stripe:qe,options:Vi,children:d(dl,{sessionId:e,nonce:t,email:x.email,billingName:kt||void 0,onBuyerIdentityReady:w,billingApiUrl:te,onTokenizedBody:_n,onErrorChange:se,isProcessing:C,onButtonClick:ce,onDecline:h,onTechnicalFailure:Wr,runBeforeButtonClick:er,onLoadStateChange:Xi,placeholderBorderRadius:Lr})}),Yr&&d(Kr,{stripe:K,options:Ki,children:d(ul,{sessionId:e,nonce:t,email:x.email,billingName:kt||void 0,onBuyerIdentityReady:w,billingApiUrl:te,intentKind:xe>0?"payment":"setup",expressMethods:Gr,onTokenizedBody:_n,onErrorChange:se,onButtonClick:ce,onDecline:h,onTechnicalFailure:Wr,runBeforeButtonClick:er,onLoadStateChange:Qi,placeholderBorderRadius:Lr})}),_o&&d(pl,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:te,paymentElementMethods:ta,stripeInstance:K,paymentElementBaseOptions:Oa,onTokenizedBody:_n,onErrorChange:se,onButtonClick:ce,onDecline:h,runBeforeButtonClick:er,onLoadStateChange:ts,isProcessing:C,submitButtonColor:Or,submitButtonBorderRadius:qt,submitButtonStyle:s.submitButton,themeId:ze,onExpandApm:Xn,expandedApmMethod:Ht,buttonAppearance:{backgroundColor:s.cardButton?.backgroundColor,borderColor:s.cardInputBorder,textColor:s.cardButton?.color,borderRadius:Lr}})]}),We&&(Ul||zl||ql)&&Le("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),d("span",{children:"or pay with card"}),d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),We&&hs]})}import{Fragment as pr,jsx as Q,jsxs as en}from"react/jsx-runtime";var ho=44,zi="flopay_checkout_saved_payment_resume",Ba=new Map,Ma=new Map;function Sl(e,t){t.settled&&t.consumers===0&&Ba.get(e)===t&&Ba.delete(e)}function Gd(e,t,n){let r=Ma.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};Ma.set(e,i);let c=()=>{Ma.get(e)===i&&Ma.delete(e)};return a.then(c,c),a}function Go(e){return new Promise(t=>setTimeout(t,e))}function xa(e,t,n){let r=ga({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Al,enabled:t!==!1});return r.beginCheckout(n),r}function Yo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Bi(e,t,n,r,a,i){let c=xa(e,t,n);c.error({errorCode:r,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Yo(c)}function wl(e,t,n,r){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function kl(e,t,n,r,a){let i=El(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:n,attempt:a,statusClass:i.statusClass}),t instanceof pn&&t.code==="session_auto_completed"?!1:t instanceof pn&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...i,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function Oi(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation}}function Fi(e){return!e||e.data.stripe?.publishableKey?!1:!!Oi(e)?.clientId}var Yd={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Jd(e){return new qd(Yd,{publishableKey:"provider_unavailable",...e})}async function Di(e,t){let{publishableKey:n,paypalPublishableKey:r}=gi(e);return{...await hi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Ui(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Xd(){if(!Ui())return null;try{let e=window.sessionStorage.getItem(zi);return e?JSON.parse(e):null}catch{return null}}function Il(e){if(Ui())try{window.sessionStorage.setItem(zi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ni(){if(Ui())try{window.sessionStorage.removeItem(zi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Zd(){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 _l(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 Li(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Qd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Rl(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function eu(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function qi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:a,appearance:i,locale:c,loading:l,error:h,onComplete:P,onError:y,onInstrument:f,onDecline:p,onCountryChange:I,onZipChange:M,showPayPal:L=!0,showStripe:Te=!0,enabledPaymentMethods:ne,showApplePay:S=!0,showGooglePay:G=!0,debug:J=!1,layout:oe,theme:Ae,buttonsTheme:ie,buttonsStyles:ze,cardButtonContent:Xe,cardBackButtonContent:nt,cardTitleContent:_t,showSecurityFooter:Ne,onButtonClick:Me,onBeforeButtonClick:le,enableAVS:we,cardFieldOrder:ce,cardPreFormSlot:pe,avsLayout:ke,className:Ke,initialErrorMessage:$e=null,children:Ze,checkoutMode:B,confirmLabel:de,renderConfirmButton:ue,onSessionCompleted:ee}){let O=Vd(r),Ie=Wn(()=>Tl(Ae),[Ae]),Oe=i??Ie?.appearance,xt=n?"embedded_checkout":"standard_checkout",rt=Li(Ze,oe),[z,q]=Ot(null),[$,xe]=Ot(null),Qe=Mt(null),be=Mt(null),_e=Mt(0),[Ve,g]=Ot(null),st=Mt(null),[R,H]=Ot(null),ye=Wn(()=>n?po(n):"",[n]),Be=n?`create:${ye}`:`session:${e??""}`,He=Rl(R),Pt=Mt(new Set),v=Mt(Be),T=Mt(Be);Bo(()=>{T.current=Be,v.current!==Be&&(v.current=Be,Pt.current.clear())},[Be]);let mt=Pn(m=>{if(T.current===Be){if(ni.has(m.name)){if(Pt.current.has(m.name))return;Pt.current.add(m.name)}Tt(()=>f?.(m))}},[Be,f]),je=lo(mt,Be),lt=Mt(!1),Wt=Pn(m=>{if(lt.current)return;let _=m.gateway||!He?m:{...m,gateway:He};mt(_)},[mt,He]);ur(()=>{je({class:"lifecycle",name:"checkout.mount"})},[je]);let[te,Gt]=Ot(e??""),ct=e??te,Tn=n?"":ct,[cn,Rt]=Ot(!0),[ve,mn]=Ot(null),[yn,Fe]=Ot(0),[pt,fn]=Ot("full"),[$t,dn]=Ot(!1),[Yt,Ct]=Ot($e),[bn,St]=Ot(null),[Cn,jt]=Ot(null),[Fn,dt]=Ot(!1),[yt,gn]=Ot(void 0),[Kt,tn]=Ot(""),[wt,fe]=Ot(!1),[ut,E]=Ot(!1),[Vt,zt]=Ot(!1),Sn=Mt(null),nn=Mt(0),An=Mt(void 0),[mr,Mn]=Ot("loading"),[We,Fr]=Ot(0),xn=Mt(!1),Pr=Mt(!1),br=Mt(!1),F=Mt(null),Re=Wn(()=>({checkoutMode:B??pt,layout:Qd(Ze,oe)}),[B,Ze,pt,oe]),Y=Mt(P);Y.current=P;let Jt=Mt(y);Jt.current=y;let Gn=Mt(p);Gn.current=p;let ot=Pn((m,_)=>{Qe.current=m,xe(m),st.current=_,g(_)},[]),un=Pn(()=>{let m=be.current;m&&(be.current=null,m.destroy())},[]);ur(()=>{Qt($)?.setCheckoutContext(Re),Ve&&Ve!==$&&Qt(Ve)?.setCheckoutContext(Re)},[$,Ve,Re]);let et=Mt(ee);et.current=ee;let Dr=Pn(m=>{Mn(m),!(m!=="exhausted"||br.current)&&(br.current=!0,Jt.current?.(new pn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Cr=Pn(()=>{Mn("retrying"),Fr(m=>m+1)},[]);ur(()=>{Mn("loading"),Fr(0),br.current=!1},[ct]),ur(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Al,checkout_type:xt,checkout_layout:rt,billing_api_url:O})},[rt,xt,O]);let Dn=Wn(()=>n?po(n,!0):"",[n]),Sr=Wn(()=>Kt===Dn?yt:void 0,[yt,Kt,Dn]),yr=Wn(()=>n?Za(n,Sr):void 0,[n,Sr]),Nn=B??yr?.checkoutMode??"full",Xt=Wn(()=>yr?{...yr,checkoutMode:Nn}:void 0,[yr,Nn]);ur(()=>{gn(void 0),tn(Dn),An.current=void 0,Sn.current=null,zt(!1)},[Dn]),ur(()=>{Ct($e)},[$e]);let or=Pn((m,_,A)=>{Tt(()=>{Gn.current?.(an(m,_,A))})},[]),wn=Pn(async(m,_)=>{Ct(null),jt(null),dt(!1),St("processing");let A=_?.sessionId??m.id,D=Rl(m),Ce=Qe.current??st.current,gt=Qt(Ce),ge=Ce?null:xa(O,a,Re),W={log:C=>{gt?gt.log(C):ge?.log(C)},error:C=>{gt?gt.error(C):ge?.error(C)},terminal:C=>{gt?gt.terminal(C):ge?.terminal(C)},performance:C=>{gt?gt.performance(C):ge?.performance(C)},now:()=>gt?.now()??ge?.now()??0,elapsed:C=>gt?.elapsed(C)??Math.max(0,(ge?.now()??C)-C)},V=W.now(),w=!!(_?.initialAutoProcessingError||_?.initialAutoProcessingPending),X=!1,u,s=()=>{X||(X=!0,w=!0,u=W.now(),W.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),W.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},k=!1,Se=()=>{k||(k=!0,W.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),W.performance({stage:"processing",durationMs:W.elapsed(V),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),u!==void 0&&W.performance({stage:"recovery",durationMs:W.elapsed(u),durationMode:"machine",paymentMethodCategory:"saved"}))};W.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),lt.current=!0;try{W.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{lt.current=!1}je({class:"lifecycle",name:"payment.processing.started",provider:D}),w&&s();let Pe;try{let C=Js(_?.initialAutoProcessingError),j;if(C)s(),C.type==="paypal_redirect_required"&&F.current?.publishableKey&&Il({sessionId:A,publishableKey:F.current.publishableKey,paypalPublishableKey:F.current.paypalPublishableKey}),j=await _a(C,{flopay:Qe.current,paypalFlopay:st.current,attempt3DS:_?.attempt3DS,billingApiUrl:O,sessionId:A,session:m,telemetry:!1}),C.type==="paypal_redirect_required"&&Ni();else if(_?.initialAutoProcessingPending){let Dt=(await new Aa(O,{telemetry:!1}).waitForCheckoutSessionCompletion(_.initialAutoProcessingPending.sessionId,{initialDelayMs:_.initialAutoProcessingPending.retryAfterMs})).data.session;if(!oo(Dt))throw ua(Dt);j=qr(Dt,A)}else{if(_?.initialAutoProcessingError)throw Ar(_.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:_.initialAutoProcessingError.checkoutMethod});if(_?.fromCreateSession)return _?.fallbackToFull&&(fn("full"),_l("full")),!1;{let x=await yo({billingApiUrl:O,sessionId:A,session:m,telemetry:!1});x.type==="success"?j=x.result:(s(),x.type==="paypal_redirect_required"&&F.current?.publishableKey&&Il({sessionId:A,publishableKey:F.current.publishableKey,paypalPublishableKey:F.current.paypalPublishableKey}),j=await _a(x,{flopay:Qe.current,paypalFlopay:st.current,attempt3DS:_?.attempt3DS,billingApiUrl:O,sessionId:A,session:m,telemetry:!1}),x.type==="paypal_redirect_required"&&Ni())}}A&&mo(A),Se(),w&&(W.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),W.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),W.terminal({outcome:j.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),dt(j.status==="authorized"),St("success"),await Go(600),Pe=()=>Y.current?.(j)}catch(C){let j=Vo(C),x=j.checkoutMethod??Ko;Ct(j.message),jt(j.message),dt(!1),_?.fallbackToFull&&(W.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),fn("full"),_l("full")),Se();let kt=j.statusCode===void 0?void 0:Wd(j.statusCode,"unknown"),Dt=kt==="4xx"?{requestCategory:"process_payment",statusClass:kt}:{},qn=kt===void 0||kt==="4xx";if(qn&&(j.telemetryOutcome==="payment_declined"||!!(j.declineCode||j.code?.toLowerCase().includes("declin"))))W.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Dt});else if(qn&&(j.telemetryOutcome==="validation_rejected"||j.type==="validation_error"))W.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Dt});else{let re=El(C,w?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),K=j.telemetryRequestCategory??"process_payment";lt.current=!0;try{W.error({...re,...j.telemetryFailureCategory?{failureCategory:j.telemetryFailureCategory}:{},stage:w?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:K})}finally{lt.current=!1}je({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:K,provider:D})}return Tt(()=>Jt.current?.(j)),or(x,j,{code:j.code,declineCode:j.declineCode}),St("error"),await Promise.allSettled([Go(400),_?.ensureProvidersReady?_.ensureProvidersReady():Promise.resolve()]),w&&(W.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),W.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Se(),ge&&Yo(ge),St(null),jt(null)}return Tt(Pe),!0},[or,je,O,a,Re]);ur(()=>{if(typeof window>"u"||Pr.current)return;let m=new URLSearchParams(window.location.search),_=m.get("payment_intent_client_secret");if(!_)return;let A=Xd();A&&(Pr.current=!0,(async()=>{let D,Ce=0;Ct(null),jt(null),St("processing"),dn(!0);try{if(m.get("redirect_status")==="failed")throw Object.assign(new pn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:gt,paypalFlopay:ge}=await hi({publishableKey:A.publishableKey,paypalPublishableKey:A.paypalPublishableKey,billingApiUrl:O,locale:c,telemetry:a});D=Qt(ge??gt),D?.setCheckoutContext(Re),Ce=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 W=(ge??gt)?.getRawProvider();if(!W)throw Object.assign(new pn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:V,error:w}=await W.retrievePaymentIntent(_);if(w)throw Object.assign(new pn(w.message??"Failed to retrieve PayPal payment status.","api_error",{code:w.code}),{checkoutMethod:"paypal"});let X=Ms(V?.status);if(!V||X==="failed")throw Object.assign(new pn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let u=typeof V.payment_method=="string"?V.payment_method:V.payment_method?.id,s=X;if(A.sessionId){let Pe=(await new Aa(O,{telemetry:!1}).getUnifiedCheckoutSession(A.sessionId)).data.session;if(Pe&&Pe.status!=="complete"){let C=await yo({billingApiUrl:O,sessionId:A.sessionId,session:Pe,telemetry:!1,tokenizedData:{id:u??V.id,type:"card",threeDSecureActionResultTokenId:V.id,isPaypal:!0}});if(C.type!=="success")throw Object.assign(new pn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});s=C.result.status}}A.sessionId&&mo(A.sessionId),D?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),D?.performance({stage:"redirect_resume",durationMs:D.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),D?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),St("success"),await Go(600),Tt(()=>Y.current?.({status:s,paymentIntentId:V.id,paymentMethodId:u,checkoutMethod:"paypal"}))}catch(gt){let ge=Vo(gt),W=ge.checkoutMethod??"paypal",V=!!(ge.declineCode||ge.code?.toLowerCase().includes("declin"));if(D)D.performance({stage:"redirect_resume",durationMs:D.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),V?D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):D.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(V){let w=xa(O,a,Re);w.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Yo(w)}else Bi(O,a,Re,"REDIRECT_RESUME_FAILED","redirect_resume");Ct(ge.message),jt(ge.message),Tt(()=>Jt.current?.(ge)),or(W,ge,{code:ge.code,declineCode:ge.declineCode}),St("error"),await Go(400)}finally{Ni(),Zd(),St(null),jt(null),dn(!1)}})())},[or,c,O,a,Re]);let Yn=Mt(null),hn=Wn(()=>Xt?po(Xt):"",[Xt]),Jn=Mt(Xt);Jn.current=Xt,ur(()=>{Gt(e??"")},[e]),ur(()=>{xn.current=!1,Ct($e),jt(null),dt(!1),St(null)},[hn,$e,e]);async function ft(m,_,A){let D=xa(O,a,Re),Ce=new Aa(O,{telemetry:!1}),gt=!1;try{let ge=m.idempotencyKey===void 0?void 0:Cl(m.idempotencyKey),W=ui(_,A),V=pi(_,A);W?.canonicalIdentity===A&&V&&V.canonicalIdentity===void 0&&(Sa(_,A,V.idempotencyKey),V={...V,canonicalIdentity:A});let w=ge??(V?.canonicalIdentity===A?V.idempotencyKey:void 0),X,u=!1;D.log({name:W?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let s=W?.sid??null,k=null,Se,Pe,C=!1;if(s)try{k=await Ce.getUnifiedCheckoutSession(s,W?.nonce),W&&W.canonicalIdentity===void 0&&(js(k.data.session,m)?(Ca(_,A,s,W.nonce??k.data.session?.clientSecret),V&&V.canonicalIdentity===void 0&&(Sa(_,A,V.idempotencyKey),w??(w=V.idempotencyKey))):(ba(_,A),V=null,w=ge,s=null,k=null));let x=k?.data.session?.status,kt=k?.data.session,Dt=kt?.clientSecret||W?.nonce;if(s&&kt?.buyerIdentified===!1&&Dt&&(Pe=ro(Ce,s,Dt,m.account)),s&&k&&x==="complete"){if(mi(s))return{sid:s,result:k};ba(_,A),s=null,k=null,u=!0}}catch{D.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),W?.canonicalIdentity===void 0?(ba(_,A),w=ge):Pa(_,A),s=null}if(!s){!ge&&(u||!w)&&(w=Cl(),X=w),w&&Sa(_,A,w);let x=D.now(),kt=0;D.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Dt={...m,idempotencyKey:w,avsCheck:!!we,avsConfig:typeof we=="object"?we:void 0,checkoutType:"embedded_checkout",checkoutLayout:Li(Ze,oe)};Object.defineProperty(Dt,$d,{configurable:!1,enumerable:!1,value:{onAttempt:Z=>{kt=Math.max(kt,Z)}}});let qn=()=>{wl(D,"session_create",x,kt)},me=Z=>{kl(D,Z,"session_create",x,kt)&&je({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(Kd(Dt)){let Z=await Ce.createDetachedSession(Dt);Z.claimed.catch(()=>{}),k=Z.shell,s=Z.sessionId,Pe=Z.claim;let re=D.now();D.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Se=Z.claimed.then(K=>{let qe=K.data.session?.id??Z.sessionId;return qe&&Ca(_,A,qe,K.data.session?.clientSecret??Z.nonce),wl(D,"session_claim",re),qn(),K},K=>{throw Pa(_,A),kl(D,K,"session_claim",re,0)&&je({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),K}).finally(()=>Yo(D)),Se.catch(()=>{}),gt=!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()-x,durationMode:"machine",requestCategory:"session_create",attempt:kt,statusClass:"2xx",paymentMethodCategory:"card"})}else k=await Ce.createAndFetchSession(Dt),qn()}catch(Z){throw me(Z),Z}s=k.data.session?.id??s??"",s&&!Se&&Ca(_,A,s,k.data.session?.clientSecret)}let j=k?.data.session;return!Pe&&s&&j?.buyerIdentified===!1&&j.clientSecret&&(Pe=ro(Ce,s,j.clientSecret,m.account)),{sid:s??"",result:k,sdkGeneratedIdempotencyKey:X,...Se?{claimed:Se}:{},...Pe?{claim:Pe}:{},...C?{claimRequiresIdentity:!0}:{}}}finally{gt||Yo(D)}}let Ln=Mt(ft);Bo(()=>{Ln.current=ft},[ft]);let kn=Pn(async(m,_)=>{let A=Jn.current;if(!A)throw new pn("createSession is required to bootstrap checkout.","validation_error");let D=Za(A,m),Ce=po(D),gt=$s(D),ge=Ba.get(Ce);if(!ge){let w={canonicalIdentity:Ce,promise:Ln.current(D,gt,Ce),consumers:0,settled:!1};ge=w,Ba.set(Ce,w);let X=()=>{w.settled=!0,Sl(Ce,w)};w.promise.then(X,X)}ge.consumers+=1;let W=!1,V=()=>{W||(W=!0,ge.consumers-=1,Sl(Ce,ge))};_?.(V);try{let w=await ge.promise;Yn.current=Ce,m&&(tn(Dn),gn(j=>Es(j,m)));let{sid:X,result:u,claimed:s,claim:k,claimRequiresIdentity:Se}=w;if(An.current=k,zt(Se===!0),q(u),u.data.session&&H(u.data.session),X&&Gt(X),s){nn.current+=1;let j=nn.current;Sn.current=s,E(!0),s.then(x=>{nn.current===j&&(Sn.current===s&&(Sn.current=null),q(x),x.data.session&&H(x.data.session),E(!1),zt(!1))},x=>{nn.current===j&&(Sn.current===s&&(Sn.current=null),E(!1),zt(!1),mn(x instanceof pn?x:new pn(x instanceof Error?x.message:"Failed to create session","api_error")))})}else nn.current+=1,Sn.current=null,E(!1),zt(!1);let{flopay:Pe,paypalFlopay:C}=await Di(u,{billingApiUrl:O,locale:c,telemetry:a});return ot(Pe,C),Rt(!1),w}catch(w){throw Yn.current===Ce&&(Yn.current=null),w}finally{_||V()}},[Dn,ot,c,O,a]),In=Mt(wn);In.current=wn;let On=Mt(kn);On.current=kn;let Ue=Pn(async m=>{if(!eu(m)||wt)return{sessionId:te,session:R};fe(!0);try{let _=await kn(m);return{sessionId:_.sid,session:_.result.data.session??null}}finally{fe(!1)}},[kn,wt,te,R]),Ut=Pn(async m=>{let _=An.current;if(!_)return;let A=nn.current,D=await _(m);nn.current===A&&(q(D),D.data.session&&H(D.data.session))},[]),Ht=Pn(async()=>{await Sn.current},[]),wr=Pn(async()=>(await Ht(),{proceed:!0}),[Ht]);ur(()=>{let m=!1,_,A=++_e.current;un(),mn(null),Fe(0);let D=()=>{m=!0,_e.current===A&&(_e.current+=1,un())},Ce=Jn.current;if(hn&&Ce)return fn(Nn),Rt(!1),Yn.current===hn?D:(H(Ts(Ce,B)),(async()=>{let W=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),V=Nn==="auto"&&!xn.current&&!W;V&&(Ct(null),jt(null),St("processing"));try{let w=await On.current(void 0,k=>{_=k}),X=w.result.data.session??null;F.current=gi(w.result);let u=Fi(w.result),s=mi(w.sid||X?.id);if(!m&&V&&X&&!u&&!s){xn.current=!0,await Gd(hn,w.sdkGeneratedIdempotencyKey,()=>In.current(X,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:w.result.autoProcessingError,initialAutoProcessingPending:w.result.autoProcessingPending,autoProcessingAttempted:w.result.autoProcessingAttempted,sessionId:w.sid||X.id}));return}!m&&V&&((u||s)&&(xn.current=!0),St(null),jt(null))}catch(w){if(m)return;let X=da(w);if(V&&X==="session_auto_completed"){xn.current=!0,St("success"),await Go(600),m||(Tt(()=>{Y.current?.({status:"succeeded"})}),St(null),jt(null));return}V&&(St(null),jt(null));let u=w instanceof pn?w:new pn(w instanceof Error?w.message:"Failed to create session","api_error");mn(u)}finally{_?.(),_=void 0}})(),()=>{D(),_?.()});Rt(!0);async function gt(){let W=!1,V=null;try{let w=new Aa(O,{telemetry:!1}),X=await w.getUnifiedCheckoutSession(ct,t);if(V=X,m)return;q(X);let u=X.data.session??null;if(H(u),!u)throw new pn("No session data returned","api_error");let s=u.checkoutMode;if(s==="setup")throw new pn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(u.status==="authorized"){Rt(!1),Tt(()=>{Y.current?.(qr(u,ct)),et.current?.(u.successUrl??"")});return}if(u.status==="complete"){Rt(!1),Tt(()=>{et.current?.(u.successUrl??"")});return}if(u.status==="expired")throw ca(u);W=!0;let k=B??s??"full";fn(k),nn.current+=1;let Se=u.clientSecret||t;An.current=u.buyerIdentified===!1&&Se?ro(w,ct,Se,{...u.customer?.id?{userId:u.customer.id}:{}}):void 0,E(!1),zt(!1);let Pe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),C=Fi(X);if(k==="auto"&&!xn.current&&!Pe&&!C){xn.current=!0;let j=ge(X);try{if(await In.current(u,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>j,sessionId:ct||u.id}),m)return;await j,m||Rt(!1);return}catch{if(m)return;await j,m||Rt(!1);return}}await ge(X),m||Rt(!1)}catch(w){if(m)return;let X=Rs(w,W);if(W&&je({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),X){let{errorCode:s,stage:k,...Se}=X;Bi(O,a,Re,s,k,Se)}if(X?.stage==="provider_load"&&(B??V?.data.session?.checkoutMode??"full")==="full"&&_s(V,L,Te)){let s=Jd({billingApiUrl:O,locale:c,telemetry:a});be.current=s,ot(s,null),Fe(1),Rt(!1);return}let u=w instanceof pn&&X?.stage!=="provider_load"?w:Is();u!==w&&Tt(()=>Jt.current?.(u)),mn(u),Rt(!1)}}async function ge(W){let{flopay:V,paypalFlopay:w,...X}=await Di(W,{billingApiUrl:O,locale:c,telemetry:a});F.current={publishableKey:X.publishableKey,paypalPublishableKey:X.paypalPublishableKey},ot(V,w),Fe(0)}return gt(),D},[B,hn,Nn,Tn,t,L,Te]);let Co=Pn(async()=>{if(!z||yn!==1)return;let m=_e.current;Fe(2);try{let{flopay:_,paypalFlopay:A}=await Di(z,{billingApiUrl:O,locale:c,telemetry:a});if(_e.current!==m)return;un(),ot(_,A),Fe(0)}catch(_){if(_e.current!==m)return;let{errorCode:A,stage:D,...Ce}=Xa(_);Bi(O,a,Re,A,D,Ce)}},[un,ot,c,yn,O,a,Re,z]),ar=Pn(async()=>{if(!($t||!R)){dn(!0),Ct(null);try{await wn(R,{attempt3DS:!0,fallbackToFull:!0,sessionId:ct||R.id})}finally{dn(!1)}}},[ct,$t,wn,R]),zn=Oi(z),Un=Fi(z),sn=Wn(()=>{if(!(!z||!R||!z.data.stripe?.publishableKey))return{billingApiUrl:O}},[z,R,O]),Nr=!!(n&&!Ze&&oe==="buttons"&&le&&Nn==="full"),kr=!!(ct&&R?.vault?.html),Xn=Wn(()=>({session:R,loading:cn,error:ve,checkoutMode:pt,inlineSessionDraft:Xt,applyInlineSessionPatch:Nr?Ue:void 0,inlineSessionPatchProcessing:wt,claimPending:ut,claimRequiresIdentity:Vt,claimBuyerIdentity:Ut,waitForDataAttachment:Ht}),[R,cn,ve,pt,Xt,Nr,Ue,wt,ut,Vt,Ut,Ht]),Zn=!!n&&oe==="buttons"&&!Un&&!kr&&(!$||!sn),rn=bn?Q(cr,{status:bn,errorMessage:Cn,authorized:Fn}):null;if(cn&&!kr){if(l)return en(pr,{children:[l,rn]});if(oe==="buttons"){let m=Ie?.buttonsLayout?.cardButton?.borderRadius??Ie?.appearance.variables?.borderRadius??8,_=A=>Q("div",{style:{height:A,borderRadius:m,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return en(pr,{children:[en("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[L&&_(ho),Te&&(S||G)&&_(ho),Te&&_(ho),Q("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),rn]})}return en(pr,{children:[en("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[Q("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),Q("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),rn]})}return ve?h?Q(nr.Provider,{value:Xn,children:h(ve)}):Q(nr.Provider,{value:Xn,children:Q("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:ve.message})}):Zn?en(pr,{children:[Q(nr.Provider,{value:Xn,children:Q(nu,{onButtonClick:Me,showPayPal:L,showStripe:Te,showApplePay:S,showGooglePay:G,theme:Ae,buttonsTheme:ie,buttonsStyles:ze,cardButtonContent:Xe,cardBackButtonContent:nt,cardTitleContent:_t})}),rn]}):Un&&R&&zn?en(pr,{children:[Q(nr.Provider,{value:Xn,children:en("div",{className:Ke,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Yt&&Q(co,{icon:!1,children:Yt}),mr==="retrying"&&Q("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),mr==="exhausted"&&en("div",{role:"alert",children:[Q("div",{children:"PayPal is temporarily unavailable. Please try again."}),Q("button",{type:"button",onClick:Cr,children:"Retry PayPal"})]}),mr!=="exhausted"&&Q("div",{"aria-hidden":mr==="retrying"?!0:void 0,style:mr==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:Q(Us,{sessionId:ct,nonce:R.clientSecret||void 0,billingApiUrl:O,email:R.customer?.email||Xt?.account?.email,billingName:[R.customer?.firstName,R.customer?.lastName].filter(Boolean).join(" ")||[Xt?.account?.firstName,Xt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Ut,clientId:zn.clientId,environment:zn.environment,currency:(R.currency??"usd").toUpperCase(),isSubscription:R.mode==="subscription",providerObjectType:zn.providerObjectType,approvalPresentation:zn.approvalPresentation,onComplete:P,onErrorChange:Ct,onDecline:p,onButtonClick:Me,runBeforeButtonClick:wr,onInitializationStateChange:Dr,allowAutomaticRetry:We===0,session:R,telemetry:a,telemetryContext:Re,onInstrument:Wt,debug:J},`${Be}:paypal-init-${We}`)})]})}),rn]}):(!$||!sn)&&!(kr&&pt==="full")?Q(pr,{children:rn}):pt==="confirm"?en(pr,{children:[Q(nr.Provider,{value:Xn,children:Q(wa,{flopay:$,paypalFlopay:Ve,options:sn??{billingApiUrl:O},onInstrument:Wt,children:en("div",{className:Ke,children:[Yt&&Q("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Yt}),ue?ue({onConfirm:ar,isProcessing:$t}):Q("button",{type:"button",onClick:ar,disabled:$t,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:$t?"not-allowed":"pointer",opacity:$t?.6:1},children:$t?"Processing...":de??"Confirm Purchase"})]})},Be)}),rn]}):en(pr,{children:[Q(nr.Provider,{value:Xn,children:en(wa,{flopay:$,paypalFlopay:Ve,options:sn??{billingApiUrl:O},onInstrument:Wt,children:[yn===1&&Q("button",{type:"button",onClick:Co,children:"Retry payment methods"}),Ze?en(pr,{children:[Yt&&Q("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Yt}),Q(tu,{sessionId:ct,nonce:R?.clientSecret||void 0,billingApiUrl:O,session:R,children:Ze})]}):Q(Mi,{sessionId:ct,nonce:R?.clientSecret||void 0,telemetry:a,email:R?.customer?.email||Xt?.account?.email,userId:R?.customer?.id||Xt?.account?.userId,firstName:R?.customer?.firstName||Xt?.account?.firstName,lastName:R?.customer?.lastName||Xt?.account?.lastName,totalAmount:R?Math.round(jd(R).total*100):0,currency:R?.currency?.toLowerCase()??"usd",onComplete:P,onError:y,onDecline:p,error:Yt,onErrorChange:Ct,showPayPal:L,showStripe:Te,enabledPaymentMethods:yn?[]:ne??z?.data.stripe?.enabledPaymentMethods??R?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:z?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:G,layout:oe,theme:Ae,buttonsTheme:ie,buttonsStyles:ze,appearance:Oe,cardButtonContent:Xe,cardBackButtonContent:nt,cardTitleContent:_t,onButtonClick:Me,onBeforeButtonClick:le,onBuyerIdentityReady:Ut,enableAVS:we,...ce?{cardFieldOrder:ce}:{},...pe?{cardPreFormSlot:pe}:{},avsLayout:ke,country:R?.customer?.country,city:R?.customer?.city,state:R?.customer?.state,onCountryChange:I,onZipChange:M,avsCheck:!!we,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Li(Ze,oe),className:Ke,directPaypal:Oi(z),isSubscription:R?.mode==="subscription",session:R,dataAttachmentPending:ut,dataAttachmentRequiresIdentity:Vt,debug:J})]},Be)}),rn]})}function tu({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:a}){return Q(pr,{children:xi.Children.map(a,i=>{if(!xi.isValidElement(i))return i;let c=i.props,l={};return c.sessionId||(l.sessionId=e),!c.nonce&&t&&(l.nonce=t),c.billingApiUrl||(l.billingApiUrl=n),r?.customer&&(c.email||(l.email=r.customer.email),c.userId||(l.userId=r.customer.id),c.firstName||(l.firstName=r.customer.firstName),c.lastName||(l.lastName=r.customer.lastName)),Object.keys(l).length===0?i:xi.cloneElement(i,l)})})}function nu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:a,theme:i,buttonsTheme:c,buttonsStyles:l,cardButtonContent:h,cardBackButtonContent:P,cardTitleContent:y}){let[f,p]=Ot(!1),I=Wn(()=>Tl(i),[i]),M=Wn(()=>{let S=I?.buttonsLayout??Hd(c);return l?{...S,...l,cardButton:{...S.cardButton,...l.cardButton},cardFormContainer:{...S.cardFormContainer,...l.cardFormContainer},backButton:{...S.backButton,...l.backButton},backButtonIcon:{...S.backButtonIcon,...l.backButtonIcon},submitButton:{...S.submitButton,...l.submitButton},title:{...S.title,...l.title}}:S},[I,c,l]),L=I?.buttonsLayout?.cardButton?.borderRadius??I?.appearance.variables?.borderRadius??8,Te=S=>Q("div",{style:{height:S,borderRadius:L,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),ne=h===void 0?{boxSizing:"border-box",height:ho,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(f){let S=M.cardInputBorder??"#e5e7eb",G=M.cardInputBackground??"white",J=Qr(P),oe=Qr(y);return en("div",{style:{backgroundColor:M.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...M.cardFormContainer},children:[en("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[en("button",{type:"button",onClick:()=>p(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:J?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...M.backButton},children:[Q("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...M.backButtonIcon},children:Q("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:Q("path",{d:"M15 18l-6-6 6-6"})})}),Q(to,{content:P})]}),oe?Q("div",{style:{flex:1}}):Q("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...M.title},children:Q(Do,{content:y})})]}),Q("div",{style:{backgroundColor:G,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:Q("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),en("div",{style:{display:"flex"},children:[Q("div",{style:{flex:1,backgroundColor:G,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:Q("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Q("div",{style:{flex:1,backgroundColor:G,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:Q("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),Q("div",{style:{backgroundColor:G,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:Q("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Q("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...M.submitButton,opacity:.5}}),Q("style",{children:`
33
+ `}),Eo&&Co&&ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:qe?-2:0},children:[ze("button",{type:"button",onClick:kr,style:{display:"inline-flex",alignItems:"center",gap:Ha?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:s.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...s.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",...s.backButtonIcon},children:d("svg",{"aria-hidden":"true",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(to,{content:De})]}),bs?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:s.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...s.title},children:d(Do,{content:ue})})]}),!Eo&&!bs&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ga,order:qe?-3:0,...s.title},children:d(Do,{content:ue})}),qe&&Ye&&d("div",{style:{order:-2,width:"100%"},children:Ye}),qe&&be&&ze("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[d("div",{style:{backgroundColor:Jr,border:`1px solid ${Wn(aa)}`,borderRadius:Kt,padding:"10px"},children:d("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:pt,onChange:a=>{gt("email"),Ln.current=a.target.value,wn(a.target.value)},onPointerDown:()=>gt("email"),onKeyDown:()=>gt("email"),onBlur:()=>{qn("email")&&Gt(!0),ae||La()},disabled:b,required:!0,"aria-invalid":aa||void 0,"aria-describedby":aa?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ya}})}),aa&&d("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Ao,children:te.empty?"Email address is required":"Enter a valid email address"})]}),D&&d("div",{style:{order:qe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=_t,P=(U=!1)=>({backgroundColor:Jr,border:`1px solid ${Wn(U)}`,borderRadius:Kt,marginTop:"0.5rem",padding:"10px"}),O=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ya}),xe=hd(a);return ze(Vr,{children:[Qe(D.address_line_1,a)&&ze(Vr,{children:[d("div",{style:P(zt("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:Qt,onChange:U=>{gt("line1"),Ht.current.addressLine1=!0,cn.current=U.target.value,on(U.target.value)},onPointerDown:()=>gt("line1"),onKeyDown:()=>gt("line1"),onBlur:()=>_n("line1"),disabled:b,required:!0,"aria-invalid":zt("line1")||void 0,"aria-describedby":zt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:O()})}),zt("line1")&&d("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Ao,children:"Street address is required"})]}),Qe(D.address_line_2,a)&&d("div",{style:P(),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:Dn,onChange:U=>{Ht.current.addressLine2=!0,dn.current=U.target.value,hn(U.target.value)},disabled:b,"data-testid":"flopay-address-line2",style:O()})}),(Qe(D.city,a)||Qe(D.state,a))&&ze("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Qe(D.city,a)&&d("div",{style:{flex:1,backgroundColor:Jr,borderTop:`1px solid ${Wn(zt("city"))}`,borderRight:`1px solid ${Wn(zt("city"))}`,borderBottom:`1px solid ${Wn(zt("city"))}`,borderLeft:`1px solid ${Wn(zt("city"))}`,padding:"10px",borderTopLeftRadius:Kt,borderBottomLeftRadius:Kt,...Qe(D.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Kt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Sn,onChange:U=>{gt("city"),Ht.current.city=!0,Dt.current=U.target.value,jt(U.target.value)},onPointerDown:()=>gt("city"),onKeyDown:()=>gt("city"),onBlur:()=>_n("city"),disabled:b,required:!0,"aria-invalid":zt("city")||void 0,"aria-describedby":zt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:O()})}),Qe(D.state,a)&&d("div",{style:{flex:1,backgroundColor:Jr,borderTop:`1px solid ${Wn(zt("state"))}`,borderRight:`1px solid ${Wn(zt("state"))}`,borderBottom:`1px solid ${Wn(zt("state"))}`,borderLeft:`1px solid ${Wn(zt("state"))}`,padding:"10px",borderTopRightRadius:Kt,borderBottomRightRadius:Kt,...Qe(D.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Wn(zt("state")||zt("city"))}`}:{borderRadius:Kt}},children:xe?ze("select",{id:"flopay-billing-state",name:"billing-state",value:le,onChange:U=>{gt("state"),Ht.current.state=!0,Ct.current=U.target.value,ct(U.target.value)},onPointerDown:()=>gt("state"),onKeyDown:()=>gt("state"),onBlur:()=>_n("state"),disabled:b,autoComplete:"billing address-level1",required:!0,"aria-invalid":zt("state")||void 0,"aria-describedby":zt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...O(),cursor:"pointer"},children:[d("option",{value:"",children:bi(a)}),xe.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:bi(a),autoComplete:"billing address-level1",value:le,onChange:U=>{gt("state"),Ht.current.state=!0,Ct.current=U.target.value,ct(U.target.value)},onPointerDown:()=>gt("state"),onKeyDown:()=>gt("state"),onBlur:()=>_n("state"),disabled:b,required:!0,"aria-invalid":zt("state")||void 0,"aria-describedby":zt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:O()})})]}),zt("city")&&d("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Ao,children:"City is required"}),zt("state")&&ze("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Ao,children:[bi(a)," is required"]}),(Qe(D.country,a)||Qe(D.postal_code,a))&&ze("div",{style:{display:"flex",flexDirection:E==="column"?"column":"row",gap:E==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Qe(D.country,a)&&d("div",{style:{flex:E==="row"?1:void 0,backgroundColor:Jr,borderTop:`1px solid ${To}`,borderRight:`1px solid ${To}`,borderBottom:`1px solid ${To}`,borderLeft:`1px solid ${To}`,padding:"10px",...E==="row"&&Qe(D.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:Kt,borderBottomLeftRadius:Kt,borderRight:"none"}:{borderRadius:Kt}},children:d("select",{id:"flopay-billing-country",name:"billing-country",value:_t,onChange:U=>{Ht.current.country=!0,ft.current=U.target.value,Z(U.target.value),dt?.(U.target.value),Ct.current="",ct("")},disabled:b,autoComplete:"billing country","data-testid":"flopay-country",style:{...O(),cursor:"pointer"},children:md.map(U=>ze("option",{value:U.code,children:[U.flag," ",U.name]},U.code))})}),Qe(D.postal_code,a)&&d("div",{style:{flex:E==="row"?1:void 0,backgroundColor:Jr,border:`1px solid ${ec}`,padding:"10px",...E==="row"&&Qe(D.country,a)?{borderRadius:"0",borderTopRightRadius:Kt,borderBottomRightRadius:Kt}:{borderRadius:Kt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Ti(_t),autoComplete:"billing postal-code",value:gn,onChange:U=>{gt("zip"),Ht.current.zip=!0,mt.current=U.target.value,Mn(U.target.value),Ve?.(U.target.value)},onPointerDown:()=>gt("zip"),onKeyDown:()=>gt("zip"),onBlur:()=>{qn("zip")&&hr(!0)},disabled:b,required:yn.required,"aria-invalid":ia||void 0,"aria-describedby":ia?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:O()})})]}),ia&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Ao,children:yn.empty?`${Ti(a)} is required`:Yd(a)})]})})()}),qe&&ac,ee&&d(co,{margin:"0.75rem 0",styleOverride:s.errorBanner,children:ee})]}),sa={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"},ks=a=>Pt?!oe||!pr?d("pre",{"data-testid":a,style:sa,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":a,style:sa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${oe}`,` directPaypalConfigured=${pr}`,` inAppBrowserDetected=${String(na)}`,` shouldRenderDirectPayPal=${Io}`,` shouldRenderStripePayPal=${ko}`,` hasPaypalStripeInstance=${!!He}`].join(`
34
+ `)}):null,_s=a=>Pt?!C||!V?d("pre",{"data-testid":a,style:sa,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":a,style:sa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${C}`,` currency=${Je}`,` amountInCents=${tn}`,` enabledPaymentMethods: ${JSON.stringify(Y??[])}`,` enabledPaymentMethodsProvided=${So}`,` hasEnabledMethods=${Qo}`,` expressMethods: ${JSON.stringify(ea)}`,` walletExpressMethods: ${JSON.stringify(Gr)}`,` paymentElementMethods: ${JSON.stringify(wo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(ta)}`,` hasStripeInstance=${!!V}`,` shouldRenderWallets=${Yr}`,` shouldRenderPaymentElement=${_o}`].join(`
35
+ `)}):null,Rs=We==="apm-expanding"||We==="apm-form"||We==="apm-collapsing",Zr;We==="apm-expanding"?Zr=fl:We==="apm-collapsing"&&(Zr=gl);let la=Wt?Al(Ua,Wt):null;if(re==="buttons"){let a=We==="buttons"||We==="expanding"||We==="apm-expanding",P=We==="expanding"||We==="card"||We==="collapsing",O=Ue===void 0?{boxSizing:"border-box",height:Ta,padding:"0 1rem"}:{padding:"0.9rem 1rem"},xe;We==="expanding"||We==="apm-expanding"?xe=$d:(We==="collapsing"||We==="apm-collapsing")&&(xe=jd);let U;return We==="expanding"?U=fl:We==="collapsing"&&(U=gl),ze("form",{onSubmit:Ka,className:_,noValidate:!0,style:{position:"relative"},children:[d(Ei,{}),en&&d(mr,{status:en,errorMessage:ee,authorized:Vt}),ze("div",{style:{display:"grid"},children:[ze("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!xe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!xe?Vd:{},...xe?{animation:xe,pointerEvents:"none"}:{}},children:[ks("flopay-direct-paypal-gate-debug"),_s("flopay-stripe-gate-debug"),Io&&he&&ze(Vr,{children:[_e&&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(va,{sessionId:e,nonce:t,billingApiUrl:Me,email:F.email,billingName:wt||void 0,onBuyerIdentityReady:I,clientId:he.clientId,environment:he.environment,currency:Je.toUpperCase(),isSubscription:$e,providerObjectType:w,approvalPresentation:ra==="popup"?void 0:ra,onTokenizedBody:En,onComplete:l,onErrorChange:ce,onDecline:h,onTechnicalFailure:Hr,onButtonClick:pe,runBeforeButtonClick:or,isProcessing:b,onLoadStateChange:qa,onInitializationStateChange:ja,session:u,existingOrderId:_e?.orderId,debug:Pt},_e?.orderId??"fresh")]}),ko&&d(Kr,{stripe:He,options:Zi,children:d(bl,{sessionId:e,nonce:t,email:F.email,billingName:wt||void 0,onBuyerIdentityReady:I,billingApiUrl:Me,onTokenizedBody:En,onErrorChange:ce,isProcessing:b,onButtonClick:pe,onDecline:h,onTechnicalFailure:Hr,runBeforeButtonClick:or,onLoadStateChange:os,placeholderBorderRadius:Lr})}),Yr?d(Kr,{stripe:V,options:Xi,children:d(Cl,{sessionId:e,nonce:t,email:F.email,billingName:wt||void 0,onBuyerIdentityReady:I,billingApiUrl:Me,intentKind:je>0?"payment":"setup",expressMethods:Gr,onTokenizedBody:En,onErrorChange:ce,onButtonClick:pe,onDecline:h,onTechnicalFailure:Hr,runBeforeButtonClick:or,onLoadStateChange:is,placeholderBorderRadius:Lr})}):null,!Yr&&us?d("div",{style:{height:Ta,borderRadius:Lr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,_o&&d(Sl,{sessionId:e,nonce:t,email:F.email,billingName:[F.firstName,F.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:I,billingApiUrl:Me,paymentElementMethods:ta,stripeInstance:V,paymentElementBaseOptions:Ua,onTokenizedBody:En,onErrorChange:ce,onButtonClick:pe,onDecline:h,runBeforeButtonClick:or,onLoadStateChange:ls,isProcessing:b,submitButtonColor:Or,submitButtonBorderRadius:Kt,submitButtonStyle:s.submitButton,onExpandApm:tr,expandedApmMethod:Wt,themeId:Ke,buttonAppearance:{backgroundColor:s.cardButton?.backgroundColor,borderColor:s.cardInputBorder,textColor:s.cardButton?.color,borderRadius:Lr}}),qe&&d("button",{type:"button",onClick:async()=>{b||!(await or("card")).proceed||(pe?.("card"),Nr())},disabled:b,style:{width:"100%",...O,...s.cardButton,...Li({themeBundle:p,resolvedPrimaryColor:Or,resolvedBorderRadius:Kt,submitButtonStyle:s.submitButton,explicitPrimaryColor:Tn?.colorPrimary}),fontSize:s.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:b?"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:b?.6:1},onMouseEnter:it=>{!b&&(p||Tn?.colorPrimary)&&(it.currentTarget.style.backgroundColor=rc)},onMouseLeave:it=>{(p||Tn?.colorPrimary)&&(it.currentTarget.style.backgroundColor=Or)},onMouseDown:it=>{it.currentTarget.style.transform="scale(0.985)"},onMouseUp:it=>{it.currentTarget.style.transform="scale(1)"},children:d(eo,{content:Ue})}),ee&&We==="buttons"&&d(co,{margin:"0.25rem 0",styleOverride:s.errorBanner,children:ee})]}),qe&&P&&d("div",{style:{gridArea:"1 / 1",...U?{animation:U}:{},...We==="collapsing"?{pointerEvents:"none"}:{}},children:Is}),C&&Rs&&Wt&&la&&V&&d("div",{style:{gridArea:"1 / 1",...Zr?{animation:Zr}:{},...We==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:Wa,borderRadius:Xa,...Mo,padding:Ja},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:nr,style:{display:"inline-flex",alignItems:"center",gap:Ha?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:s.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...s.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",...s.backButtonIcon},children:d("svg",{"aria-hidden":"true",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(to,{content:De})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:s.titleFontSize??"1.05rem",color:Ga,paddingRight:80,...s.title},children:`Pay with ${Wr(Wt)}`})]}),d(Kr,{stripe:V,options:la,children:d(xi,{method:Wt,sessionId:e,nonce:t,email:F.email,billingName:[F.firstName,F.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:I,billingApiUrl:Me,onTokenizedBody:En,onErrorChange:ce,onDecline:h,onCancel:nr,runBeforeButtonClick:or,onButtonClick:pe,isProcessing:b,submitButtonColor:Or,submitButtonBorderRadius:Kt,submitButtonStyle:s.submitButton,errorText:ee})},Wt)]})})]})]})}return Rs&&Wt&&la&&V&&C?ze("form",{onSubmit:Ka,className:_,noValidate:!0,style:{position:"relative"},children:[d(Ei,{}),en&&d(mr,{status:en,errorMessage:ee,authorized:Vt}),d("div",{style:{...Zr?{animation:Zr}:{},...We==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:Wa,borderRadius:Xa,...Mo,padding:Ja},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:nr,style:{display:"inline-flex",alignItems:"center",gap:Ha?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:s.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...s.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",...s.backButtonIcon},children:d("svg",{"aria-hidden":"true",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(to,{content:De})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:s.titleFontSize??"1.05rem",color:Ga,paddingRight:80,...s.title},children:`Pay with ${Wr(Wt)}`})]}),d(Kr,{stripe:V,options:la,children:d(xi,{method:Wt,sessionId:e,nonce:t,email:F.email,billingName:[F.firstName,F.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:I,billingApiUrl:Me,onTokenizedBody:En,onErrorChange:ce,onDecline:h,onCancel:nr,runBeforeButtonClick:or,onButtonClick:pe,isProcessing:b,submitButtonColor:Or,submitButtonBorderRadius:Kt,submitButtonStyle:s.submitButton,errorText:ee})},Wt)]})})]}):ze("form",{onSubmit:Ka,className:_,noValidate:!0,style:{position:"relative"},children:[d(Ei,{}),en&&d(mr,{status:en,errorMessage:ee,authorized:Vt}),ze("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ks("flopay-direct-paypal-gate-debug-default"),_s("flopay-stripe-gate-debug-default"),Io&&he&&ze(Vr,{children:[_e&&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(va,{sessionId:e,nonce:t,billingApiUrl:Me,email:F.email,billingName:wt||void 0,onBuyerIdentityReady:I,clientId:he.clientId,environment:he.environment,currency:Je.toUpperCase(),isSubscription:$e,providerObjectType:w,approvalPresentation:ra==="popup"?void 0:ra,onTokenizedBody:En,onComplete:l,onErrorChange:ce,onDecline:h,onTechnicalFailure:Hr,onButtonClick:pe,runBeforeButtonClick:or,isProcessing:b,onLoadStateChange:qa,onInitializationStateChange:ja,session:u,existingOrderId:_e?.orderId,debug:Pt},_e?.orderId??"fresh")]}),ko&&d(Kr,{stripe:He,options:Zi,children:d(bl,{sessionId:e,nonce:t,email:F.email,billingName:wt||void 0,onBuyerIdentityReady:I,billingApiUrl:Me,onTokenizedBody:En,onErrorChange:ce,isProcessing:b,onButtonClick:pe,onDecline:h,onTechnicalFailure:Hr,runBeforeButtonClick:or,onLoadStateChange:os,placeholderBorderRadius:Lr})}),Yr&&d(Kr,{stripe:V,options:Xi,children:d(Cl,{sessionId:e,nonce:t,email:F.email,billingName:wt||void 0,onBuyerIdentityReady:I,billingApiUrl:Me,intentKind:je>0?"payment":"setup",expressMethods:Gr,onTokenizedBody:En,onErrorChange:ce,onButtonClick:pe,onDecline:h,onTechnicalFailure:Hr,runBeforeButtonClick:or,onLoadStateChange:is,placeholderBorderRadius:Lr})}),_o&&d(Sl,{sessionId:e,nonce:t,email:F.email,billingName:[F.firstName,F.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Me,paymentElementMethods:ta,stripeInstance:V,paymentElementBaseOptions:Ua,onTokenizedBody:En,onErrorChange:ce,onButtonClick:pe,onDecline:h,runBeforeButtonClick:or,onLoadStateChange:ls,isProcessing:b,submitButtonColor:Or,submitButtonBorderRadius:Kt,submitButtonStyle:s.submitButton,themeId:Ke,onExpandApm:tr,expandedApmMethod:Wt,buttonAppearance:{backgroundColor:s.cardButton?.backgroundColor,borderColor:s.cardInputBorder,textColor:s.cardButton?.color,borderRadius:Lr}})]}),qe&&(Jl||Yl||Xl)&&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"}})]}),qe&&Is]})}import{Fragment as gr,jsx as ne,jsxs as Xt}from"react/jsx-runtime";var ho=44,Wi="flopay_checkout_saved_payment_resume",Da=new Map,Ba=new Map;function xl(e,t){t.settled&&t.consumers===0&&Da.get(e)===t&&Da.delete(e)}function lu(e,t,n){let r=Ba.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};Ba.set(e,i);let l=()=>{Ba.get(e)===i&&Ba.delete(e)};return o.then(l,l),o}function Go(e){return new Promise(t=>setTimeout(t,e))}function Fa(e,t,n){let r=ga({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ul,enabled:t!==!1});return r.beginCheckout(n),r}function Yo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ui(e,t,n,r,o,i){let l=Fa(e,t,n);l.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),Yo(l)}function Bl(e,t,n,r){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function Fl(e,t,n,r,o){let i=Ol(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:n,attempt:o,statusClass:i.statusClass}),t instanceof fn&&t.code==="session_auto_completed"?!1:t instanceof fn&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...i,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function Vi(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation}}function qi(e){return!e||e.data.stripe?.publishableKey?!1:!!Vi(e)?.clientId}var cu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function du(e){return new tu(cu,{publishableKey:"provider_unavailable",...e})}async function ji(e,t){let{publishableKey:n,paypalPublishableKey:r}=vi(e);return{...await Pi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Hi(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function uu(){if(!Hi())return null;try{let e=window.sessionStorage.getItem(Wi);return e?JSON.parse(e):null}catch{return null}}function Dl(e){if(Hi())try{window.sessionStorage.setItem(Wi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function $i(){if(Hi())try{window.sessionStorage.removeItem(Wi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function pu(){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 Nl(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 Ki(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function mu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Ll(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function yu(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function Gi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:l,loading:c,error:h,onComplete:v,onError:f,onInstrument:g,onDecline:m,onCountryChange:_,onZipChange:M,showPayPal:z=!0,showStripe:Be=!0,enabledPaymentMethods:oe,showApplePay:C=!0,showGooglePay:Y=!0,debug:Q=!1,layout:se,theme:Fe,buttonsTheme:re,buttonsStyles:Ke,cardButtonContent:et,cardBackButtonContent:ot,cardTitleContent:kt,showSecurityFooter:Ue,onButtonClick:De,onBeforeButtonClick:ue,enableAVS:Ee,cardFieldOrder:pe,cardPreFormSlot:me,avsLayout:Ce,className:ge,initialErrorMessage:tt=null,children:Ye,checkoutMode:E,confirmLabel:J,renderConfirmButton:Ie,onSessionCompleted:ye}){let L=au(r),Te=Xn(()=>zl(Fe),[Fe]),Ae=i??Te?.appearance,dt=n?"embedded_checkout":"standard_checkout",Ve=Ki(Ye,se),[j,q]=qt(null),[$,je]=qt(null),Je=At(null),Se=At(null),he=At(0),[$e,x]=qt(null),Zt=At(null),[X,Pt]=qt(null),bt=Xn(()=>n?po(n):"",[n]),Xe=n?`create:${bt}`:`session:${e??""}`,T=Ll(X),Ne=At(new Set),u=At(Xe),w=At(Xe);Bo(()=>{w.current=Xe,u.current!==Xe&&(u.current=Xe,Ne.current.clear())},[Xe]);let fe=Cn(y=>{if(w.current===Xe){if(oi.has(y.name)){if(Ne.current.has(y.name))return;Ne.current.add(y.name)}Et(()=>g?.(y))}},[Xe,g]),ve=lo(fe,Xe),ut=At(!1),Mt=Cn(y=>{if(ut.current)return;let R=y.gateway||!T?y:{...y,gateway:T};fe(R)},[fe,T]);fr(()=>{ve({class:"lifecycle",name:"checkout.mount"})},[ve]);let[Me,Le]=qt(e??""),lt=e??Me,Fn=n?"":lt,[rn,_t]=qt(!0),[Z,gn]=qt(null),[Mn,Qt]=qt(0),[on,Dn]=qt("full"),[hn,Sn]=qt(!1),[jt,le]=qt(tt),[ct,pt]=qt(null),[wn,xt]=qt(null),[Nn,mt]=qt(!1),[ft,cn]=qt(void 0),[dn,Dt]=qt(""),[Ct,Ln]=qt(!1),[Ht,D]=qt(!1),[sr,Vt]=qt(!1),vn=At(null),Nt=At(0),un=At(void 0),[On,pn]=qt("loading"),[qe,In]=qt(0),an=At(!1),mn=At(!1),Pe=At(!1),S=At(null),W=Xn(()=>({checkoutMode:E??on,layout:mu(Ye,se)}),[E,Ye,on,se]),B=At(v);B.current=v;let Lt=At(f);Lt.current=f;let Zn=At(m);Zn.current=m;let at=Cn((y,R)=>{Je.current=y,je(y),Zt.current=R,x(R)},[]),yn=Cn(()=>{let y=Se.current;y&&(Se.current=null,y.destroy())},[]);fr(()=>{Jt($)?.setCheckoutContext(W),$e&&$e!==$&&Jt($e)?.setCheckoutContext(W)},[$,$e,W]);let nt=At(ye);nt.current=ye;let Dr=Cn(y=>{pn(y),!(y!=="exhausted"||Pe.current)&&(Pe.current=!0,Lt.current?.(new fn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Sr=Cn(()=>{pn("retrying"),In(y=>y+1)},[]);fr(()=>{pn("loading"),In(0),Pe.current=!1},[lt]),fr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ul,checkout_type:dt,checkout_layout:Ve,billing_api_url:L})},[Ve,dt,L]);let zn=Xn(()=>n?po(n,!0):"",[n]),wr=Xn(()=>dn===zn?ft:void 0,[ft,dn,zn]),hr=Xn(()=>n?ei(n,wr):void 0,[n,wr]),Un=E??hr?.checkoutMode??"full",Gt=Xn(()=>hr?{...hr,checkoutMode:Un}:void 0,[hr,Un]);fr(()=>{cn(void 0),Dt(zn),un.current=void 0,vn.current=null,Vt(!1)},[zn]),fr(()=>{le(tt)},[tt]);let lr=Cn((y,R,A)=>{Et(()=>{Zn.current?.(nn(y,R,A))})},[]),kn=Cn(async(y,R)=>{le(null),xt(null),mt(!1),pt("processing");let A=R?.sessionId??y.id,N=Ll(y),_e=Je.current??Zt.current,ht=Jt(_e),we=_e?null:Fa(L,o,W),G={log:b=>{ht?ht.log(b):we?.log(b)},error:b=>{ht?ht.error(b):we?.error(b)},terminal:b=>{ht?ht.terminal(b):we?.terminal(b)},performance:b=>{ht?ht.performance(b):we?.performance(b)},now:()=>ht?.now()??we?.now()??0,elapsed:b=>ht?.elapsed(b)??Math.max(0,(we?.now()??b)-b)},H=G.now(),I=!!(R?.initialAutoProcessingError||R?.initialAutoProcessingPending),ee=!1,p,s=()=>{ee||(ee=!0,I=!0,p=G.now(),G.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),G.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},k=!1,Re=()=>{k||(k=!0,G.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),G.performance({stage:"processing",durationMs:G.elapsed(H),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),p!==void 0&&G.performance({stage:"recovery",durationMs:G.elapsed(p),durationMode:"machine",paymentMethodCategory:"saved"}))};G.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ut.current=!0;try{G.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ut.current=!1}ve({class:"lifecycle",name:"payment.processing.started",provider:N}),I&&s();let ke;try{let b=ol(R?.initialAutoProcessingError),K;if(b)s(),b.type==="paypal_redirect_required"&&S.current?.publishableKey&&Dl({sessionId:A,publishableKey:S.current.publishableKey,paypalPublishableKey:S.current.paypalPublishableKey}),K=await _a(b,{flopay:Je.current,paypalFlopay:Zt.current,attempt3DS:R?.attempt3DS,billingApiUrl:L,sessionId:A,session:y,telemetry:!1}),b.type==="paypal_redirect_required"&&$i();else if(R?.initialAutoProcessingPending){let Ot=(await new xa(L,{telemetry:!1}).waitForCheckoutSessionCompletion(R.initialAutoProcessingPending.sessionId,{initialDelayMs:R.initialAutoProcessingPending.retryAfterMs})).data.session;if(!oo(Ot))throw ua(Ot);K=qr(Ot,A)}else{if(R?.initialAutoProcessingError)throw Mr(R.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:R.initialAutoProcessingError.checkoutMethod});if(R?.fromCreateSession)return R?.fallbackToFull&&(Dn("full"),Nl("full")),!1;{let F=await yo({billingApiUrl:L,sessionId:A,session:y,telemetry:!1});F.type==="success"?K=F.result:(s(),F.type==="paypal_redirect_required"&&S.current?.publishableKey&&Dl({sessionId:A,publishableKey:S.current.publishableKey,paypalPublishableKey:S.current.paypalPublishableKey}),K=await _a(F,{flopay:Je.current,paypalFlopay:Zt.current,attempt3DS:R?.attempt3DS,billingApiUrl:L,sessionId:A,session:y,telemetry:!1}),F.type==="paypal_redirect_required"&&$i())}}A&&mo(A),Re(),I&&(G.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),G.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),G.terminal({outcome:K.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),mt(K.status==="authorized"),pt("success"),await Go(600),ke=()=>B.current?.(K)}catch(b){let K=Vo(b),F=K.checkoutMethod??Ko;le(K.message),xt(K.message),mt(!1),R?.fallbackToFull&&(G.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Dn("full"),Nl("full")),Re();let wt=K.statusCode===void 0?void 0:su(K.statusCode,"unknown"),Ot=wt==="4xx"?{requestCategory:"process_payment",statusClass:wt}:{},Vn=wt===void 0||wt==="4xx";if(Vn&&(K.telemetryOutcome==="payment_declined"||!!(K.declineCode||K.code?.toLowerCase().includes("declin"))))G.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ot});else if(Vn&&(K.telemetryOutcome==="validation_rejected"||K.type==="validation_error"))G.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ot});else{let ae=Ol(b,I?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),V=K.telemetryRequestCategory??"process_payment";ut.current=!0;try{G.error({...ae,...K.telemetryFailureCategory?{failureCategory:K.telemetryFailureCategory}:{},stage:I?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:V})}finally{ut.current=!1}ve({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:V,provider:N})}return Et(()=>Lt.current?.(K)),lr(F,K,{code:K.code,declineCode:K.declineCode}),pt("error"),await Promise.allSettled([Go(400),R?.ensureProvidersReady?R.ensureProvidersReady():Promise.resolve()]),I&&(G.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),G.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Re(),we&&Yo(we),pt(null),xt(null)}return Et(ke),!0},[lr,ve,L,o,W]);fr(()=>{if(typeof window>"u"||mn.current)return;let y=new URLSearchParams(window.location.search),R=y.get("payment_intent_client_secret");if(!R)return;let A=uu();A&&(mn.current=!0,(async()=>{let N,_e=0;le(null),xt(null),pt("processing"),Sn(!0);try{if(y.get("redirect_status")==="failed")throw Object.assign(new fn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ht,paypalFlopay:we}=await Pi({publishableKey:A.publishableKey,paypalPublishableKey:A.paypalPublishableKey,billingApiUrl:L,locale:l,telemetry:o});N=Jt(we??ht),N?.setCheckoutContext(W),_e=N?.now()??0,N?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),N?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let G=(we??ht)?.getRawProvider();if(!G)throw Object.assign(new fn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:H,error:I}=await G.retrievePaymentIntent(R);if(I)throw Object.assign(new fn(I.message??"Failed to retrieve PayPal payment status.","api_error",{code:I.code}),{checkoutMethod:"paypal"});let ee=Os(H?.status);if(!H||ee==="failed")throw Object.assign(new fn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let p=typeof H.payment_method=="string"?H.payment_method:H.payment_method?.id,s=ee;if(A.sessionId){let ke=(await new xa(L,{telemetry:!1}).getUnifiedCheckoutSession(A.sessionId)).data.session;if(ke&&ke.status!=="complete"){let b=await yo({billingApiUrl:L,sessionId:A.sessionId,session:ke,telemetry:!1,tokenizedData:{id:p??H.id,type:"card",threeDSecureActionResultTokenId:H.id,isPaypal:!0}});if(b.type!=="success")throw Object.assign(new fn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});s=b.result.status}}A.sessionId&&mo(A.sessionId),N?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),N?.performance({stage:"redirect_resume",durationMs:N.elapsed(_e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),N?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),pt("success"),await Go(600),Et(()=>B.current?.({status:s,paymentIntentId:H.id,paymentMethodId:p,checkoutMethod:"paypal"}))}catch(ht){let we=Vo(ht),G=we.checkoutMethod??"paypal",H=!!(we.declineCode||we.code?.toLowerCase().includes("declin"));if(N)N.performance({stage:"redirect_resume",durationMs:N.elapsed(_e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),H?N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):N.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(H){let I=Fa(L,o,W);I.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Yo(I)}else Ui(L,o,W,"REDIRECT_RESUME_FAILED","redirect_resume");le(we.message),xt(we.message),Et(()=>Lt.current?.(we)),lr(G,we,{code:we.code,declineCode:we.declineCode}),pt("error"),await Go(400)}finally{$i(),pu(),pt(null),xt(null),Sn(!1)}})())},[lr,l,L,o,W]);let Qn=At(null),Pn=Xn(()=>Gt?po(Gt):"",[Gt]),er=At(Gt);er.current=Gt,fr(()=>{Le(e??"")},[e]),fr(()=>{an.current=!1,le(tt),xt(null),mt(!1),pt(null)},[Pn,tt,e]);async function gt(y,R,A){let N=Fa(L,o,W),_e=new xa(L,{telemetry:!1}),ht=!1;try{let we=y.idempotencyKey===void 0?void 0:Ml(y.idempotencyKey),G=mi(R,A),H=yi(R,A);G?.canonicalIdentity===A&&H&&H.canonicalIdentity===void 0&&(Sa(R,A,H.idempotencyKey),H={...H,canonicalIdentity:A});let I=we??(H?.canonicalIdentity===A?H.idempotencyKey:void 0),ee,p=!1;N.log({name:G?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let s=G?.sid??null,k=null,Re,ke,b=!1;if(s)try{k=await _e.getUnifiedCheckoutSession(s,G?.nonce),G&&G.canonicalIdentity===void 0&&(Xs(k.data.session,y)?(Ca(R,A,s,G.nonce??k.data.session?.clientSecret),H&&H.canonicalIdentity===void 0&&(Sa(R,A,H.idempotencyKey),I??(I=H.idempotencyKey))):(ba(R,A),H=null,I=we,s=null,k=null));let F=k?.data.session?.status,wt=k?.data.session,Ot=wt?.clientSecret||G?.nonce;if(s&&wt?.buyerIdentified===!1&&Ot&&(ke=ro(_e,s,Ot,y.account)),s&&k&&F==="complete"){if(fi(s))return{sid:s,result:k};ba(R,A),s=null,k=null,p=!0}}catch{N.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),G?.canonicalIdentity===void 0?(ba(R,A),I=we):Pa(R,A),s=null}if(!s){!we&&(p||!I)&&(I=Ml(),ee=I),I&&Sa(R,A,I);let F=N.now(),wt=0;N.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ot={...y,idempotencyKey:I,avsCheck:!!Ee,avsConfig:typeof Ee=="object"?Ee:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ki(Ye,se)};Object.defineProperty(Ot,nu,{configurable:!1,enumerable:!1,value:{onAttempt:te=>{wt=Math.max(wt,te)}}});let Vn=()=>{Bl(N,"session_create",F,wt)},be=te=>{Fl(N,te,"session_create",F,wt)&&ve({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(ou(Ot)){let te=await _e.createDetachedSession(Ot);te.claimed.catch(()=>{}),k=te.shell,s=te.sessionId,ke=te.claim;let ae=N.now();N.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Re=te.claimed.then(V=>{let He=V.data.session?.id??te.sessionId;return He&&Ca(R,A,He,V.data.session?.clientSecret??te.nonce),Bl(N,"session_claim",ae),Vn(),V},V=>{throw Pa(R,A),Fl(N,V,"session_claim",ae,0)&&ve({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),V}).finally(()=>Yo(N)),Re.catch(()=>{}),ht=!0,N.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),N.performance({stage:"session_shell",durationMs:N.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:wt,statusClass:"2xx",paymentMethodCategory:"card"})}else k=await _e.createAndFetchSession(Ot),Vn()}catch(te){throw be(te),te}s=k.data.session?.id??s??"",s&&!Re&&Ca(R,A,s,k.data.session?.clientSecret)}let K=k?.data.session;return!ke&&s&&K?.buyerIdentified===!1&&K.clientSecret&&(ke=ro(_e,s,K.clientSecret,y.account)),{sid:s??"",result:k,sdkGeneratedIdempotencyKey:ee,...Re?{claimed:Re}:{},...ke?{claim:ke}:{},...b?{claimRequiresIdentity:!0}:{}}}finally{ht||Yo(N)}}let qn=At(gt);Bo(()=>{qn.current=gt},[gt]);let _n=Cn(async(y,R)=>{let A=er.current;if(!A)throw new fn("createSession is required to bootstrap checkout.","validation_error");let N=ei(A,y),_e=po(N),ht=Js(N),we=Da.get(_e);if(!we){let I={canonicalIdentity:_e,promise:qn.current(N,ht,_e),consumers:0,settled:!1};we=I,Da.set(_e,I);let ee=()=>{I.settled=!0,xl(_e,I)};I.promise.then(ee,ee)}we.consumers+=1;let G=!1,H=()=>{G||(G=!0,we.consumers-=1,xl(_e,we))};R?.(H);try{let I=await we.promise;Qn.current=_e,y&&(Dt(zn),cn(K=>Ds(K,y)));let{sid:ee,result:p,claimed:s,claim:k,claimRequiresIdentity:Re}=I;if(un.current=k,Vt(Re===!0),q(p),p.data.session&&Pt(p.data.session),ee&&Le(ee),s){Nt.current+=1;let K=Nt.current;vn.current=s,D(!0),s.then(F=>{Nt.current===K&&(vn.current===s&&(vn.current=null),q(F),F.data.session&&Pt(F.data.session),D(!1),Vt(!1))},F=>{Nt.current===K&&(vn.current===s&&(vn.current=null),D(!1),Vt(!1),gn(F instanceof fn?F:new fn(F instanceof Error?F.message:"Failed to create session","api_error")))})}else Nt.current+=1,vn.current=null,D(!1),Vt(!1);let{flopay:ke,paypalFlopay:b}=await ji(p,{billingApiUrl:L,locale:l,telemetry:o});return at(ke,b),_t(!1),I}catch(I){throw Qn.current===_e&&(Qn.current=null),I}finally{R||H()}},[zn,at,l,L,o]),Rn=At(kn);Rn.current=kn;let jn=At(_n);jn.current=_n;let We=Cn(async y=>{if(!yu(y)||Ct)return{sessionId:Me,session:X};Ln(!0);try{let R=await _n(y);return{sessionId:R.sid,session:R.result.data.session??null}}finally{Ln(!1)}},[_n,Ct,Me,X]),$t=Cn(async y=>{let R=un.current;if(!R)return;let A=Nt.current,N=await R(y);Nt.current===A&&(q(N),N.data.session&&Pt(N.data.session))},[]),Wt=Cn(async()=>{await vn.current},[]),Ir=Cn(async()=>(await Wt(),{proceed:!0}),[Wt]);fr(()=>{let y=!1,R,A=++he.current;yn(),gn(null),Qt(0);let N=()=>{y=!0,he.current===A&&(he.current+=1,yn())},_e=er.current;if(Pn&&_e)return Dn(Un),_t(!1),Qn.current===Pn?N:(Pt(Ns(_e,E)),(async()=>{let G=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),H=Un==="auto"&&!an.current&&!G;H&&(le(null),xt(null),pt("processing"));try{let I=await jn.current(void 0,k=>{R=k}),ee=I.result.data.session??null;S.current=vi(I.result);let p=qi(I.result),s=fi(I.sid||ee?.id);if(!y&&H&&ee&&!p&&!s){an.current=!0,await lu(Pn,I.sdkGeneratedIdempotencyKey,()=>Rn.current(ee,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:I.result.autoProcessingError,initialAutoProcessingPending:I.result.autoProcessingPending,autoProcessingAttempted:I.result.autoProcessingAttempted,sessionId:I.sid||ee.id}));return}!y&&H&&((p||s)&&(an.current=!0),pt(null),xt(null))}catch(I){if(y)return;let ee=da(I);if(H&&ee==="session_auto_completed"){an.current=!0,pt("success"),await Go(600),y||(Et(()=>{B.current?.({status:"succeeded"})}),pt(null),xt(null));return}H&&(pt(null),xt(null));let p=I instanceof fn?I:new fn(I instanceof Error?I.message:"Failed to create session","api_error");gn(p)}finally{R?.(),R=void 0}})(),()=>{N(),R?.()});_t(!0);async function ht(){let G=!1,H=null;try{let I=new xa(L,{telemetry:!1}),ee=await I.getUnifiedCheckoutSession(lt,t);if(H=ee,y)return;q(ee);let p=ee.data.session??null;if(Pt(p),!p)throw new fn("No session data returned","api_error");let s=p.checkoutMode;if(s==="setup")throw new fn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(p.status==="authorized"){_t(!1),Et(()=>{B.current?.(qr(p,lt)),nt.current?.(p.successUrl??"")});return}if(p.status==="complete"){_t(!1),Et(()=>{nt.current?.(p.successUrl??"")});return}if(p.status==="expired")throw ca(p);G=!0;let k=E??s??"full";Dn(k),Nt.current+=1;let Re=p.clientSecret||t;un.current=p.buyerIdentified===!1&&Re?ro(I,lt,Re,{...p.customer?.id?{userId:p.customer.id}:{}}):void 0,D(!1),Vt(!1);let ke=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),b=qi(ee);if(k==="auto"&&!an.current&&!ke&&!b){an.current=!0;let K=we(ee);try{if(await Rn.current(p,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>K,sessionId:lt||p.id}),y)return;await K,y||_t(!1);return}catch{if(y)return;await K,y||_t(!1);return}}await we(ee),y||_t(!1)}catch(I){if(y)return;let ee=Fs(I,G);if(G&&ve({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ee){let{errorCode:s,stage:k,...Re}=ee;Ui(L,o,W,s,k,Re)}if(ee?.stage==="provider_load"&&(E??H?.data.session?.checkoutMode??"full")==="full"&&Bs(H,z,Be)){let s=du({billingApiUrl:L,locale:l,telemetry:o});Se.current=s,at(s,null),Qt(1),_t(!1);return}let p=I instanceof fn&&ee?.stage!=="provider_load"?I:xs();p!==I&&Et(()=>Lt.current?.(p)),gn(p),_t(!1)}}async function we(G){let{flopay:H,paypalFlopay:I,...ee}=await ji(G,{billingApiUrl:L,locale:l,telemetry:o});S.current={publishableKey:ee.publishableKey,paypalPublishableKey:ee.paypalPublishableKey},at(H,I),Qt(0)}return ht(),N},[E,Pn,Un,Fn,t,z,Be]);let Co=Cn(async()=>{if(!j||Mn!==1)return;let y=he.current;Qt(2);try{let{flopay:R,paypalFlopay:A}=await ji(j,{billingApiUrl:L,locale:l,telemetry:o});if(he.current!==y)return;yn(),at(R,A),Qt(0)}catch(R){if(he.current!==y)return;let{errorCode:A,stage:N,..._e}=Qa(R);Ui(L,o,W,A,N,_e)}},[yn,at,l,Mn,L,o,W,j]),cr=Cn(async()=>{if(!(hn||!X)){Sn(!0),le(null);try{await kn(X,{attempt3DS:!0,fallbackToFull:!0,sessionId:lt||X.id})}finally{Sn(!1)}}},[lt,hn,kn,X]),$n=Vi(j),Kn=qi(j),sn=Xn(()=>{if(!(!j||!X||!j.data.stripe?.publishableKey))return{billingApiUrl:L}},[j,X,L]),Nr=!!(n&&!Ye&&se==="buttons"&&ue&&Un==="full"),kr=!!(lt&&X?.vault?.html),tr=Xn(()=>({session:X,loading:rn,error:Z,checkoutMode:on,inlineSessionDraft:Gt,applyInlineSessionPatch:Nr?We:void 0,inlineSessionPatchProcessing:Ct,claimPending:Ht,claimRequiresIdentity:sr,claimBuyerIdentity:$t,waitForDataAttachment:Wt}),[X,rn,Z,on,Gt,Nr,We,Ct,Ht,sr,$t,Wt]),nr=!!n&&se==="buttons"&&!Kn&&!kr&&(!$||!sn),en=ct?ne(mr,{status:ct,errorMessage:wn,authorized:Nn}):null;if(rn&&!kr){if(c)return Xt(gr,{children:[c,en]});if(se==="buttons"){let y=Te?.buttonsLayout?.cardButton?.borderRadius??Te?.appearance.variables?.borderRadius??8,R=A=>ne("div",{style:{height:A,borderRadius:y,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Xt(gr,{children:[Xt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[z&&R(ho),Be&&(C||Y)&&R(ho),Be&&R(ho),ne("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),en]})}return Xt(gr,{children:[Xt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ne("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ne("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),en]})}return Z?h?ne(ar.Provider,{value:tr,children:h(Z)}):ne(ar.Provider,{value:tr,children:ne("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Z.message})}):nr?Xt(gr,{children:[ne(ar.Provider,{value:tr,children:ne(gu,{onButtonClick:De,showPayPal:z,showStripe:Be,showApplePay:C,showGooglePay:Y,theme:Fe,buttonsTheme:re,buttonsStyles:Ke,cardButtonContent:et,cardBackButtonContent:ot,cardTitleContent:kt})}),en]}):Kn&&X&&$n?Xt(gr,{children:[ne(ar.Provider,{value:tr,children:Xt("div",{className:ge,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[jt&&ne(co,{icon:!1,children:jt}),On==="retrying"&&ne("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),On==="exhausted"&&Xt("div",{role:"alert",children:[ne("div",{children:"PayPal is temporarily unavailable. Please try again."}),ne("button",{type:"button",onClick:Sr,children:"Retry PayPal"})]}),On!=="exhausted"&&ne("div",{"aria-hidden":On==="retrying"?!0:void 0,style:On==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ne(Gs,{sessionId:lt,nonce:X.clientSecret||void 0,billingApiUrl:L,email:X.customer?.email||Gt?.account?.email,billingName:[X.customer?.firstName,X.customer?.lastName].filter(Boolean).join(" ")||[Gt?.account?.firstName,Gt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:$t,clientId:$n.clientId,environment:$n.environment,currency:(X.currency??"usd").toUpperCase(),isSubscription:X.mode==="subscription",providerObjectType:$n.providerObjectType,approvalPresentation:$n.approvalPresentation,onComplete:v,onErrorChange:le,onDecline:m,onButtonClick:De,runBeforeButtonClick:Ir,onInitializationStateChange:Dr,allowAutomaticRetry:qe===0,session:X,telemetry:o,telemetryContext:W,onInstrument:Mt,debug:Q},`${Xe}:paypal-init-${qe}`)})]})}),en]}):(!$||!sn)&&!(kr&&on==="full")?ne(gr,{children:en}):on==="confirm"?Xt(gr,{children:[ne(ar.Provider,{value:tr,children:ne(wa,{flopay:$,paypalFlopay:$e,options:sn??{billingApiUrl:L},onInstrument:Mt,children:Xt("div",{className:ge,children:[jt&&ne("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:jt}),Ie?Ie({onConfirm:cr,isProcessing:hn}):ne("button",{type:"button",onClick:cr,disabled:hn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:hn?"not-allowed":"pointer",opacity:hn?.6:1},children:hn?"Processing...":J??"Confirm Purchase"})]})},Xe)}),en]}):Xt(gr,{children:[ne(ar.Provider,{value:tr,children:Xt(wa,{flopay:$,paypalFlopay:$e,options:sn??{billingApiUrl:L},onInstrument:Mt,children:[Mn===1&&ne("button",{type:"button",onClick:Co,children:"Retry payment methods"}),Ye?Xt(gr,{children:[jt&&ne("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:jt}),ne(fu,{sessionId:lt,nonce:X?.clientSecret||void 0,billingApiUrl:L,session:X,children:Ye})]}):ne(Oi,{sessionId:lt,nonce:X?.clientSecret||void 0,telemetry:o,email:X?.customer?.email||Gt?.account?.email,userId:X?.customer?.id||Gt?.account?.userId,firstName:X?.customer?.firstName||Gt?.account?.firstName,lastName:X?.customer?.lastName||Gt?.account?.lastName,totalAmount:X?Math.round(ru(X).total*100):0,currency:X?.currency?.toLowerCase()??"usd",onComplete:v,onError:f,onDecline:m,error:jt,onErrorChange:le,showPayPal:z,showStripe:Be,enabledPaymentMethods:Mn?[]:oe??j?.data.stripe?.enabledPaymentMethods??X?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:j?.data.stripe?.enabledPaymentMethodCountries,showApplePay:C,showGooglePay:Y,layout:se,theme:Fe,buttonsTheme:re,buttonsStyles:Ke,appearance:Ae,cardButtonContent:et,cardBackButtonContent:ot,cardTitleContent:kt,onButtonClick:De,onBeforeButtonClick:ue,onBuyerIdentityReady:$t,enableAVS:Ee,...pe?{cardFieldOrder:pe}:{},...me?{cardPreFormSlot:me}:{},avsLayout:Ce,country:X?.customer?.country,city:X?.customer?.city,state:X?.customer?.state,onCountryChange:_,onZipChange:M,avsCheck:!!Ee,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Ki(Ye,se),className:ge,directPaypal:Vi(j),isSubscription:X?.mode==="subscription",session:X,dataAttachmentPending:Ht,dataAttachmentRequiresIdentity:sr,debug:Q})]},Xe)}),en]})}function fu({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return ne(gr,{children:zi.Children.map(o,i=>{if(!zi.isValidElement(i))return i;let l=i.props,c={};return l.sessionId||(c.sessionId=e),!l.nonce&&t&&(c.nonce=t),l.billingApiUrl||(c.billingApiUrl=n),r?.customer&&(l.email||(c.email=r.customer.email),l.userId||(c.userId=r.customer.id),l.firstName||(c.firstName=r.customer.firstName),l.lastName||(c.lastName=r.customer.lastName)),Object.keys(c).length===0?i:zi.cloneElement(i,c)})})}function gu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:l,buttonsStyles:c,cardButtonContent:h,cardBackButtonContent:v,cardTitleContent:f}){let[g,m]=qt(!1),_=Xn(()=>zl(i),[i]),M=Xn(()=>{let C=_?.buttonsLayout??iu(l);return c?{...C,...c,cardButton:{...C.cardButton,...c.cardButton},cardFormContainer:{...C.cardFormContainer,...c.cardFormContainer},backButton:{...C.backButton,...c.backButton},backButtonIcon:{...C.backButtonIcon,...c.backButtonIcon},submitButton:{...C.submitButton,...c.submitButton},title:{...C.title,...c.title}}:C},[_,l,c]),z=_?.buttonsLayout?.cardButton?.borderRadius??_?.appearance.variables?.borderRadius??8,Be=C=>ne("div",{style:{height:C,borderRadius:z,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),oe=h===void 0?{boxSizing:"border-box",height:ho,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(g){let C=M.cardInputBorder??"#e5e7eb",Y=M.cardInputBackground??"white",Q=Qr(v),se=Qr(f);return Xt("div",{style:{backgroundColor:M.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...M.cardFormContainer},children:[Xt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Xt("button",{type:"button",onClick:()=>m(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...M.backButton},children:[ne("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...M.backButtonIcon},children:ne("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:ne("path",{d:"M15 18l-6-6 6-6"})})}),ne(to,{content:v})]}),se?ne("div",{style:{flex:1}}):ne("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...M.title},children:ne(Do,{content:f})})]}),ne("div",{style:{backgroundColor:Y,border:`1px solid ${C}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ne("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Xt("div",{style:{display:"flex"},children:[ne("div",{style:{flex:1,backgroundColor:Y,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomLeftRadius:8,padding:12,height:45},children:ne("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ne("div",{style:{flex:1,backgroundColor:Y,borderTop:"none",borderRight:`1px solid ${C}`,borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomRightRadius:8,padding:12,height:45},children:ne("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ne("div",{style:{backgroundColor:Y,border:`1px solid ${C}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ne("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ne("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...M.submitButton,opacity:.5}}),ne("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 en("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&Te(ho),n&&(r||a)&&Te(ho),n&&Q("button",{type:"button",onClick:()=>{e?.("card"),p(!0)},style:{width:"100%",...ne,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:M.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,...M.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:Q(eo,{content:h})}),Q("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as uu,jsx as bo,jsxs as pu}from"react/jsx-runtime";var iu=44;function Ml(e){return new Promise(t=>setTimeout(t,e))}function su(e,t){return e instanceof Zo?e:new Zo(e instanceof Error?e.message:t,"api_error")}function lu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function cu(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 du({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:a,clientId:i,products:c,items:l,subscriptions:h,account:P,successUrl:y,cancelUrl:f,couponCodes:p,tagsData:I,utmMetadata:M,billingApiUrl:L,locale:Te,theme:ne,appearance:S,buttonsTheme:G,buttonsStyles:J,onSuccess:oe,onError:Ae,onDecline:ie,children:ze,disabled:Xe=!1,type:nt="button",style:_t,...Ne}){let Me=Jo(()=>ru(L),[L]),le=Jo(()=>cu({createSession:n,clientId:i,products:c,items:l,subscriptions:h,account:P,successUrl:y,cancelUrl:f,couponCodes:p,tagsData:I,utmMetadata:M}),[P,f,i,p,n,c,l,h,y,I,M]),[we,ce]=Xo(!1),[pe,ke]=Xo(null),[Ke,$e]=Xo(null),[Ze,B]=Xo(!1),[de,ue]=Xo(null),ee=Po(!0),O=Po(null),Ie=Po(de),Oe=Po(oe),xt=Po(Ae),rt=Po(ie);vo(()=>{Ie.current=de},[de]),vo(()=>{Oe.current=oe},[oe]),vo(()=>{xt.current=Ae},[Ae]),vo(()=>{rt.current=ie},[ie]),vo(()=>(ee.current=!0,()=>{ee.current=!1,O.current?.abort()}),[]),vo(()=>{if(typeof window>"u")return;let v=T=>{T.key==="Escape"&&ue(null)};return window.addEventListener("keydown",v),()=>{window.removeEventListener("keydown",v)}},[]);let z=Br((v,T=Ko)=>{rt.current?.(an(T,v,{code:v.code,declineCode:v.declineCode}))},[]),q=Br(async v=>{ee.current&&($e(null),B(v.result.status==="authorized"),ke("success"),await Ml(600),ee.current&&Tt(()=>Oe.current?.(v)))},[]),$=Br(async(v,T)=>{ee.current&&(xt.current?.(v),T?.emitDecline&&z(v,T.method),$e(v.message),B(!1),ke("error"),await Ml(400))},[z]),xe=Br(async(v,T,mt)=>{let je=v.data.session??null;if(!je)throw new Zo("No session data returned","api_error");let lt=je.clientSecret||t;if(oo(je)){await q({result:qr(je,T),session:je,sessionId:je.id||T,autoCompleted:!1});return}if(je.status==="expired")throw ca(je);try{if(v.autoProcessingPending){let ct=(await new $i(Me).waitForCheckoutSessionCompletion(v.autoProcessingPending.sessionId,{initialDelayMs:v.autoProcessingPending.retryAfterMs})).data.session;if(!oo(ct))throw ua(ct);await q({result:qr(ct,T),session:ct,sessionId:ct.id||T,autoCompleted:!1});return}if(v.autoProcessingError){if(v.autoProcessingError.type==="3ds_required"&&v.autoProcessingError.nextActionRedirectUrl&&T&&lt){let te=new AbortController;O.current=te;let Gt;try{Gt=await Xs({billingApiUrl:Me,sessionId:T,nonce:lt,nextActionRedirectUrl:v.autoProcessingError.nextActionRedirectUrl,signal:te.signal})}finally{O.current===te&&(O.current=null)}if(Gt.status==="declined")throw Ar({type:Gt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Gt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:v.autoProcessingError.checkoutMethod});let cn=(await new $i(Me).waitForCheckoutSessionCompletion(T,{initialDelayMs:0,nonce:lt})).data.session;if(!oo(cn))throw Ar({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:v.autoProcessingError.checkoutMethod});await q({result:qr(cn,T),session:cn,sessionId:cn.id||T,autoCompleted:!1});return}throw Ar(v.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:v.autoProcessingError.checkoutMethod})}if(mt?.fromCreateSession&&v.autoProcessingAttempted===!0)throw Ar({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Wt=await yo({billingApiUrl:Me,sessionId:T??je.id,session:je,nonce:lt});if(Wt.type!=="success")throw Ar({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await q({result:Wt.result,session:je,sessionId:je.id||T,autoCompleted:!1})}catch(Wt){let te=Vo(Wt),Gt=je.id||T;await $(te,{emitDecline:!0,method:te.checkoutMethod??Ko}),lu(te,Gt)&&Gt&&ee.current&&ue({sessionId:Gt,errorMessage:te.message,nonce:lt||void 0})}},[t,Me,$,q]),Qe=Br(async v=>{if(Ne.onClick?.(v),!(v.defaultPrevented||Xe||we)){if(ue(null),e&&le){let T=new Zo("Provide either sessionId or create-session props, not both.","validation_error");await $(T),ee.current&&(ke(null),$e(null));return}if(!e&&!le){let T=new Zo("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $(T),ee.current&&(ke(null),$e(null));return}ce(!0),$e(null),B(!1),ke("processing");try{let T=new $i(Me);if(e){let mt=await T.getUnifiedCheckoutSession(e,t);await xe(mt,e);return}try{let mt=await T.createAndFetchSession({...le});await xe(mt,mt.data.session?.id??null,{fromCreateSession:!0})}catch(mt){if(da(mt)==="session_auto_completed"){await q({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw mt}}catch(T){await $(su(T,"Automatic payment failed. Please try again."))}finally{ee.current&&(ke(null),$e(null),ce(!1))}}},[Ne.onClick,le,Xe,we,t,xe,Me,e,$,q]),be=Br(v=>{let T=Ie.current;ue(null),Oe.current?.({result:v,session:null,sessionId:T?.sessionId??null,autoCompleted:!1})},[]),_e=Br(v=>{xt.current?.(v)},[]),Ve=Br(v=>{rt.current?.(v)},[]),g=Jo(()=>au(ne),[ne]),st=Jo(()=>{let v=g?.buttonsLayout??ou(G);return J?{...v,...J,cardButton:{...v.cardButton,...J.cardButton}}:v},[g,G,J]),R=Jo(()=>{let v=g?.appearance;return S?v?{...v,...S,variables:{...v.variables,...S.variables}}:S:v},[S,g]),H=R?.variables,ye=H?.colorPrimary??"#4A49FF",Be=H?.colorPrimaryHover??Fo(ye,.12),He=H?.borderRadius??"8px";return pu(uu,{children:[bo("button",{...Ne,type:nt,onClick:Qe,disabled:Xe||we,"aria-busy":we,style:{width:"100%",...ze===void 0?{boxSizing:"border-box",height:iu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...st.cardButton,...Ai({themeBundle:g,resolvedPrimaryColor:ye,resolvedBorderRadius:He,submitButtonStyle:st.submitButton,explicitPrimaryColor:H?.colorPrimary}),fontSize:st.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Xe||we?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Xe||we?.6:1,..._t},onMouseEnter:v=>{Ne.onMouseEnter?.(v),!v.defaultPrevented&&!Xe&&!we&&(g||H?.colorPrimary)&&(v.currentTarget.style.backgroundColor=Be)},onMouseLeave:v=>{Ne.onMouseLeave?.(v),!v.defaultPrevented&&(g||H?.colorPrimary)&&(v.currentTarget.style.backgroundColor=ye)},onMouseDown:v=>{Ne.onMouseDown?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(0.985)")},onMouseUp:v=>{Ne.onMouseUp?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(1)")},children:bo(eo,{content:ze})}),pe&&bo(cr,{status:pe,errorMessage:Ke,authorized:Ze}),de&&bo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:v=>{v.target===v.currentTarget&&ue(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:bo("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:bo(qi,{sessionId:de.sessionId,nonce:de.nonce,checkoutMode:"full",billingApiUrl:Me,locale:Te,theme:ne,...R?{appearance:R}:{},buttonsTheme:G,buttonsStyles:J,initialErrorMessage:de.errorMessage,cardTitleContent:null,onComplete:be,onError:_e,onDecline:Ve})})})]})}export{va as DirectPayPalButton,du as FloPayAutomaticPaymentButton,Xl as FloPayCardSetup,Jl as FloPayCardSetupError,qi as FloPayCheckout,wa as FloPayProvider,Mi as SplitCardForm,Ja as VaultCardFields,Sm as dropThirdPartyOnlyError,uc as useCheckout,_r as useFloPay,ti as usePayPalFloPay};
42
+ `})]})}return Xt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&Be(ho),n&&(r||o)&&Be(ho),n&&ne("button",{type:"button",onClick:()=>{e?.("card"),m(!0)},style:{width:"100%",...oe,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:M.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,...M.cardButton},onMouseDown:C=>{C.currentTarget.style.transform="scale(0.985)"},onMouseUp:C=>{C.currentTarget.style.transform="scale(1)"},children:ne(eo,{content:h})}),ne("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as ku,jsx as bo,jsxs as _u}from"react/jsx-runtime";var bu=44;function ql(e){return new Promise(t=>setTimeout(t,e))}function Cu(e,t){return e instanceof Zo?e:new Zo(e instanceof Error?e.message:t,"api_error")}function Su(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function wu(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 Iu({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:l,items:c,subscriptions:h,account:v,successUrl:f,cancelUrl:g,couponCodes:m,tagsData:_,utmMetadata:M,billingApiUrl:z,locale:Be,theme:oe,appearance:C,buttonsTheme:Y,buttonsStyles:Q,onSuccess:se,onError:Fe,onDecline:re,children:Ke,disabled:et=!1,type:ot="button",style:kt,...Ue}){let De=Jo(()=>hu(z),[z]),ue=Jo(()=>wu({createSession:n,clientId:i,products:l,items:c,subscriptions:h,account:v,successUrl:f,cancelUrl:g,couponCodes:m,tagsData:_,utmMetadata:M}),[v,g,i,m,n,l,c,h,f,_,M]),[Ee,pe]=Xo(!1),[me,Ce]=Xo(null),[ge,tt]=Xo(null),[Ye,E]=Xo(!1),[J,Ie]=Xo(null),ye=Po(!0),L=Po(null),Te=Po(J),Ae=Po(se),dt=Po(Fe),Ve=Po(re);vo(()=>{Te.current=J},[J]),vo(()=>{Ae.current=se},[se]),vo(()=>{dt.current=Fe},[Fe]),vo(()=>{Ve.current=re},[re]),vo(()=>(ye.current=!0,()=>{ye.current=!1,L.current?.abort()}),[]),vo(()=>{if(typeof window>"u")return;let u=w=>{w.key==="Escape"&&Ie(null)};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u)}},[]);let j=Fr((u,w=Ko)=>{Ve.current?.(nn(w,u,{code:u.code,declineCode:u.declineCode}))},[]),q=Fr(async u=>{ye.current&&(tt(null),E(u.result.status==="authorized"),Ce("success"),await ql(600),ye.current&&Et(()=>Ae.current?.(u)))},[]),$=Fr(async(u,w)=>{ye.current&&(dt.current?.(u),w?.emitDecline&&j(u,w.method),tt(u.message),E(!1),Ce("error"),await ql(400))},[j]),je=Fr(async(u,w,fe)=>{let ve=u.data.session??null;if(!ve)throw new Zo("No session data returned","api_error");let ut=ve.clientSecret||t;if(oo(ve)){await q({result:qr(ve,w),session:ve,sessionId:ve.id||w,autoCompleted:!1});return}if(ve.status==="expired")throw ca(ve);try{if(u.autoProcessingPending){let lt=(await new Yi(De).waitForCheckoutSessionCompletion(u.autoProcessingPending.sessionId,{initialDelayMs:u.autoProcessingPending.retryAfterMs})).data.session;if(!oo(lt))throw ua(lt);await q({result:qr(lt,w),session:lt,sessionId:lt.id||w,autoCompleted:!1});return}if(u.autoProcessingError){if(u.autoProcessingError.type==="3ds_required"&&u.autoProcessingError.nextActionRedirectUrl&&w&&ut){let Me=new AbortController;L.current=Me;let Le;try{Le=await al({billingApiUrl:De,sessionId:w,nonce:ut,nextActionRedirectUrl:u.autoProcessingError.nextActionRedirectUrl,signal:Me.signal})}finally{L.current===Me&&(L.current=null)}if(Le.status==="declined")throw Mr({type:Le.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Le.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:u.autoProcessingError.checkoutMethod});let rn=(await new Yi(De).waitForCheckoutSessionCompletion(w,{initialDelayMs:0,nonce:ut})).data.session;if(!oo(rn))throw Mr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:u.autoProcessingError.checkoutMethod});await q({result:qr(rn,w),session:rn,sessionId:rn.id||w,autoCompleted:!1});return}throw Mr(u.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:u.autoProcessingError.checkoutMethod})}if(fe?.fromCreateSession&&u.autoProcessingAttempted===!0)throw Mr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Mt=await yo({billingApiUrl:De,sessionId:w??ve.id,session:ve,nonce:ut});if(Mt.type!=="success")throw Mr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await q({result:Mt.result,session:ve,sessionId:ve.id||w,autoCompleted:!1})}catch(Mt){let Me=Vo(Mt),Le=ve.id||w;await $(Me,{emitDecline:!0,method:Me.checkoutMethod??Ko}),Su(Me,Le)&&Le&&ye.current&&Ie({sessionId:Le,errorMessage:Me.message,nonce:ut||void 0})}},[t,De,$,q]),Je=Fr(async u=>{if(Ue.onClick?.(u),!(u.defaultPrevented||et||Ee)){if(Ie(null),e&&ue){let w=new Zo("Provide either sessionId or create-session props, not both.","validation_error");await $(w),ye.current&&(Ce(null),tt(null));return}if(!e&&!ue){let w=new Zo("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $(w),ye.current&&(Ce(null),tt(null));return}pe(!0),tt(null),E(!1),Ce("processing");try{let w=new Yi(De);if(e){let fe=await w.getUnifiedCheckoutSession(e,t);await je(fe,e);return}try{let fe=await w.createAndFetchSession({...ue});await je(fe,fe.data.session?.id??null,{fromCreateSession:!0})}catch(fe){if(da(fe)==="session_auto_completed"){await q({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw fe}}catch(w){await $(Cu(w,"Automatic payment failed. Please try again."))}finally{ye.current&&(Ce(null),tt(null),pe(!1))}}},[Ue.onClick,ue,et,Ee,t,je,De,e,$,q]),Se=Fr(u=>{let w=Te.current;Ie(null),Ae.current?.({result:u,session:null,sessionId:w?.sessionId??null,autoCompleted:!1})},[]),he=Fr(u=>{dt.current?.(u)},[]),$e=Fr(u=>{Ve.current?.(u)},[]),x=Jo(()=>Pu(oe),[oe]),Zt=Jo(()=>{let u=x?.buttonsLayout??vu(Y);return Q?{...u,...Q,cardButton:{...u.cardButton,...Q.cardButton}}:u},[x,Y,Q]),X=Jo(()=>{let u=x?.appearance;return C?u?{...u,...C,variables:{...u.variables,...C.variables}}:C:u},[C,x]),Pt=X?.variables,bt=Pt?.colorPrimary??"#4A49FF",Xe=Pt?.colorPrimaryHover??Fo(bt,.12),T=Pt?.borderRadius??"8px";return _u(ku,{children:[bo("button",{...Ue,type:ot,onClick:Je,disabled:et||Ee,"aria-busy":Ee,style:{width:"100%",...Ke===void 0?{boxSizing:"border-box",height:bu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Zt.cardButton,...Li({themeBundle:x,resolvedPrimaryColor:bt,resolvedBorderRadius:T,submitButtonStyle:Zt.submitButton,explicitPrimaryColor:Pt?.colorPrimary}),fontSize:Zt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:et||Ee?"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:et||Ee?.6:1,...kt},onMouseEnter:u=>{Ue.onMouseEnter?.(u),!u.defaultPrevented&&!et&&!Ee&&(x||Pt?.colorPrimary)&&(u.currentTarget.style.backgroundColor=Xe)},onMouseLeave:u=>{Ue.onMouseLeave?.(u),!u.defaultPrevented&&(x||Pt?.colorPrimary)&&(u.currentTarget.style.backgroundColor=bt)},onMouseDown:u=>{Ue.onMouseDown?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(0.985)")},onMouseUp:u=>{Ue.onMouseUp?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(1)")},children:bo(eo,{content:Ke})}),me&&bo(mr,{status:me,errorMessage:ge,authorized:Ye}),J&&bo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:u=>{u.target===u.currentTarget&&Ie(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:bo("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:bo(Gi,{sessionId:J.sessionId,nonce:J.nonce,checkoutMode:"full",billingApiUrl:De,locale:Be,theme:oe,...X?{appearance:X}:{},buttonsTheme:Y,buttonsStyles:Q,initialErrorMessage:J.errorMessage,cardTitleContent:null,onComplete:Se,onError:he,onDecline:$e})})})]})}export{va as DirectPayPalButton,Iu as FloPayAutomaticPaymentButton,sc as FloPayCardSetup,ic as FloPayCardSetupError,Gi as FloPayCheckout,wa as FloPayProvider,Oi as SplitCardForm,Za as VaultCardFields,Dm as dropThirdPartyOnlyError,Sc as useCheckout,Rr as useFloPay,ri as usePayPalFloPay};