@flopay/react 1.9.21 → 1.9.24

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 Bt,b as fr,c as Uo,d as si,e as qo,f as zs,g as Us,h as hc,i as vc}from"./chunk-CSBYK62Y.mjs";import{dropThirdPartyOnlyError as Xm}from"@flopay/shared";import{PaymentAPI as is}from"@flopay/js";import{FloPayError as ia,resolveBillingApiUrl as Au,resolveButtonsLayoutTheme as xu,resolveTheme as Mu}from"@flopay/shared";import{useCallback as Rr,useEffect as _o,useMemo as oa,useRef as Ro,useState as aa}from"react";import{Fragment as co,jsx as Qn,jsxs as qs}from"react/jsx-runtime";function Pc(){return qs(co,{children:[qs("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:[Qn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Qn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Qn("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:Qn("path",{d:"M9 18l6-6-6-6"})})]})}function bc(){return Qn(co,{children:"Go back"})}function Cc(){return Qn(co,{children:"Secure card checkout"})}function io(e){return e!==void 0&&(e===""||e===null||e===!1)}function so({content:e}){return Qn(co,{children:e===void 0?Qn(Pc,{}):e})}function lo({content:e}){return Qn(co,{children:e===void 0?Qn(bc,{}):e})}function jo({content:e}){return Qn(co,{children:e===void 0?Qn(Cc,{}):e})}import{classifyTelemetryFailure as Sc,FloPayError as jn,isCardHolderNamePlaceholder as js,isMoneySettledOutcome as wc,isSetupIntentClientSecret as Ic,isValidEmail as kc}from"@flopay/shared";var _c="Checkout is temporarily unavailable. Please try again later.";function li(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof jn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Rc(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 $s(){return new jn(_c,"api_error",{code:"CheckoutInitializationFailed"})}function ci(e){return!!e?.gateways?.worldpayCorporateGateway}function Ar(e){return e?.status==="open"&&ci(e)}function Ks(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")||Ar(r))||t&&e?.data.paypal?.publishableKey)}function Vs(e,t){if(t&&(!(e instanceof jn)||e.type==="authentication_error"))return li(e);if(!(e instanceof jn&&Rc(e))){if(!t&&!(e instanceof jn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...Sc(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof jn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof jn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function uo(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let s={...r,...i,email:i.email?.trim()||r.email?.trim()},l=js(s.firstName,s.lastName);if(!kc(s.email))return Promise.reject(new jn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[f,C]of Object.entries(s)){if(l&&f.endsWith("Name")||typeof C!="string")continue;let h=C.trim();h&&(p[f]=h)}return o=e.claimCheckoutSession(t,n,{accountData:p}),o.catch(()=>{}),o}}function Hs(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 di(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 Ws(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,s)=>i+(s.overrideAmount??s.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,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,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 Vr(e){if(js(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function ui(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 Ec=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function xr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Ec)if(n.test(t))return r;return e}function Sr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Mr(e){return e?.status==="authorized"||e?.status==="complete"}function Gs(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ha(e){let t=Gs(e);return new jn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function va(e){return e instanceof jn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function po(e){let t=Gs(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new jn(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function $o(e,t){return e==="processing"||wc(e,t)}function Ys(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Js(e,t){let n=e;if(Ic(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new jn(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new jn(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}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 pi(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 Ko(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as yu,PaymentAPI as Ua,SESSION_CREATE_TELEMETRY as fu}from"@flopay/js";import{buildCheckoutDisplayData as gu,classifyTelemetryFailure as Gl,FloPayError as bn,isDetachedSessionEligible as hu,resolveBillingApiUrl as vu,resolveButtonsLayoutTheme as Pu,resolveIdempotencyKey as ql,resolveTheme as Yl,SDK_VERSION as Jl,telemetryStatusClass as bu}from"@flopay/shared";import Xi,{useCallback as Pn,useEffect as ur,useMemo as tr,useRef as Rt,useState as jt}from"react";import{createContext as Zs}from"react";var er=Zs({flopay:null,paypalFlopay:null,billingApiUrl:""}),cr=Zs({session:null,loading:!1,error:null});import{PaymentAPI as gi}from"@flopay/js";import{classifyTelemetryFailure as Kc,FloPayError as hi,generateIdempotencyKey as Vc,isValidEmail as Go,normalizeGatewayEnvironment as Hc,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as vi,SDK_VERSION as Wc}from"@flopay/shared";import{loadScript as Gc}from"@paypal/paypal-js";import{useCallback as kr,useEffect as Lt,useMemo as Yo,useRef as lt,useState as Dr}from"react";import{isValidEmail as Tc}from"@flopay/shared";import{useCallback as Qs,useEffect as Ac,useRef as el,useState as nl}from"react";import{jsx as tl,jsxs as Vo}from"react/jsx-runtime";function Bn(e,t=!1){let{firstName:n,lastName:r,...o}=e,i=n?.trim(),s=r?.trim();return{...o,...i||t?{firstName:i??""}:{},...s||t?{lastName:s??""}:{}}}function mo(){let[e,t]=nl(null),n=el(null),r=el(0),o=Qs((s,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:l}),new Promise(p=>{n.current=p})),[]),i=Qs(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return Ac(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function yo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=nl(e.email?.trim()??""),p=Tc(s.trim());return Vo("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:[Vo("div",{style:{fontWeight:700},children:["Continue with ",t]}),Vo("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",tl("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:f=>l(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Vo("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&tl("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Vo("button",{type:"button",disabled:!p||o,onClick:()=>{n(Bn({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function xc(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 Hr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function wr(e){if(typeof e!="object"||e===null)return;let t=e;return Hr(t.code)??Hr(t.type)??Hr(t.name)}function fo(e){if(!(typeof e!="object"||e===null))return Hr(e.decline_code)}function Ho(e){return typeof e!="object"||e===null?!1:Hr(e.type)?.toLowerCase()==="card_error"||fo(e)!==void 0}function Ir(e){let t=xc(e)?.toLowerCase()??"",r=`${wr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Mc}from"@flopay/shared";import{useContext as Pa}from"react";function Br(){return Pa(er).flopay}function mi(){return Pa(er).paypalFlopay??null}function Bc(){return Pa(cr)}function rl(){return Pa(er).billingApiUrl||Mc()}function ba(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 Ca(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}import{FLO_INSTRUMENT_SCHEMA_VERSION as Fc}from"@flopay/shared";import{useCallback as Dc,useRef as Sa}from"react";var Nc={"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 Lc(e){return e==="stripe"||e==="paypal"?e:void 0}function Oc(e){let t=Lc(e.provider),n={schemaVersion:Fc,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Nc[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 yi=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function go(e,t){let n=Sa(e);n.current=e;let r=Sa(new Set),o=Sa(t),i=Sa(t);return Uo(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Dc(s=>{if(i.current!==t)return;let l=Oc(s);if(l){if(yi.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}Bt(()=>n.current?.(l))}},[t])}var zc=Symbol.for("@flopay/js.telemetry.bridge.v1"),Uc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function qc(){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 jc(e){let t=qc(),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 wa(e){let t=globalThis[Uc];return jc(t?.(e)??{})}function Qt(e){if(e)return e[zc]}import{useCallback as Fr,useEffect as $c,useRef as fi}from"react";function Wo(e){let t=fi(0),n=fi(null),r=fi(null),o=Fr((m=r.current)=>{m?.timer&&(clearTimeout(m.timer),m.timer=null)},[]),i=Fr(m=>{o();let w=t.current+1;return t.current=w,n.current=null,r.current={generation:w,method:m,timer:null,yieldedControl:!1},w},[o]),s=Fr(m=>{let w=r.current;return m!==void 0&&w?.generation!==m?!1:(o(w),r.current=null,(m===void 0||n.current===m)&&(n.current=null),!0)},[o]),l=Fr(m=>{let w=r.current,_=m??w?.generation??t.current;(m===void 0||w?.generation===m)&&(o(w),r.current=null),n.current=_},[o]),p=Fr(m=>n.current===(m??t.current),[]),f=Fr(m=>r.current?.generation===m&&n.current!==m,[]),C=Fr(()=>{let m=r.current;m&&(m.yieldedControl=!0,o(m))},[o]),h=Fr(()=>{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 $c(()=>{let m=()=>{document.visibilityState==="visible"?h():C()};return document.addEventListener("visibilitychange",m),window.addEventListener("blur",C),window.addEventListener("focus",h),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("blur",C),window.removeEventListener("focus",h),o()}},[o,C,h]),{startAttempt:i,finishAttempt:s,invalidateAttempt:l,isAttemptInvalidated:p,isAttemptCurrent:f,generationRef:t}}import{jsx as Wr,jsxs as bi}from"react/jsx-runtime";var Ia=45,Yc=1e3,Jc=11e3,Xc=["https://www.paypal.com","https://www.sandbox.paypal.com"],Pi="We couldn't open PayPal. Try again or choose another payment method.",Zc={width:"100%",minHeight:Ia,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 Qc(e){return e.includes("No ack for postMessage init()")&&Xc.some(t=>e.includes(t))&&e.includes("10000ms")}var ed={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 td(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:ed[e.kind]??null}}function nd(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Qc(t)?"paypal_init_timeout":"paypal_init_failure"}function rd(e,t=!1){return e?t?`${Pi} Open this page in your system browser, then try again.`:`${Pi} Allow pop-ups for this site, then try again.`:Pi}function od(e){let t=Ho(e),n=Ir(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 ad(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 id(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function ol({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:s,environment:l,currency:p,isSubscription:f,providerObjectType:C,approvalPresentation:h,onTokenizedBody:m,onComplete:w,onErrorChange:_,onDecline:ae,onTechnicalFailure:Y,isProcessing:Pe=!1,onLoadStateChange:S,onInitializationStateChange:G,allowAutomaticRetry:X=!0,onButtonClick:ce,runBeforeButtonClick:Te,session:Fe,existingOrderId:ve,telemetry:Ue,telemetryContext:bt,onInstrument:ot,debug:$e=!1}){let De=Br(),ye=go(ot,e),we=Yo(()=>{if(De)return null;let M=wa({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Wc,enabled:Ue!==!1});return M.setCheckoutContext(bt??{}),M.beginCheckout(bt??{}),M},[n,De,Ue,bt?.checkoutMode,bt?.layout]),Qe=Yo(()=>Qt(De),[De]);Lt(()=>()=>{we&&we.flush().catch(()=>{}).finally(()=>we.destroy())},[we]);let Z=Yo(()=>({error:M=>{Qe?Qe.error(M):we?.error(M),ye({class:"technical_error",errorCode:M.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":M.errorCode,requestCategory:M.requestCategory,provider:M.provider})},log:M=>{Qe?Qe.log(M):we?.log(M),ye({class:"lifecycle",name:M.name,provider:M.provider})},performance:M=>{Qe?Qe.performance(M):we?.performance(M)},terminal:M=>{Qe?Qe.terminal(M):we?.terminal(M)},startTiming:()=>Qe?.now()??we?.now()??0,elapsed:M=>Qe?.elapsed(M)??Math.max(0,(we?.now()??M)-M)}),[ye,Qe,we]),Ie=lt(null),be=lt(0),ct=lt(null),dt=lt(null),U=lt(null),V=lt(!1),[de,fe]=Dr(!1),[ut,Ne]=Dr(!1),[x,at]=Dr(0),Ye=lt(0),[re,Q]=Dr(!1),L=lt(!1),Ae=lt(!1),[xe,Me]=Dr(!1),[qe,ke]=Dr(!1),{request:Ee,collect:ee,finish:dn}=mo(),Yt=lt({sessionId:e,required:!Go(r?.trim()||Fe?.customer?.email?.trim())});Yt.current.sessionId!==e&&(Yt.current={sessionId:e,required:!Go(r?.trim()||Fe?.customer?.email?.trim())});let H=Yt.current.required,Je=Yo(()=>n.replace(/\/+$/,""),[n]),K=Fe?.gateways?.paypal?.providerObjectType??C,ie=K??(f?"subscription":"order"),[u]=Dr(ba),B=Fe?.gateways?.paypal?.approvalPresentation??h,_e=Ca(u,B==="app_switch"?"app_switch":void 0,ie),Ke=K==="order"||K==="setup_token",Re=Yo(()=>JSON.stringify([Je,s,p,l??"",ie,Ke,_e,e,ve??""]),[Je,s,p,l,ve,ie,Ke,_e,e]),$t=lt(Re),N=$t.current!==Re,Ct=lt($e),Et=lt(null),[pt,un]=Dr([]),O=kr(M=>{Ct.current&&un(Oe=>[...Oe,`${new Date().toISOString().slice(11,23)} ${M}`])},[]);Lt(()=>{Ct.current=$e,$e&&O("debug:enabled"),Et.current?.setEnabled($e)},[O,$e]);let Ot=lt(m),Cn=lt(w),pn=lt(_),mn=lt(ae),_n=lt(Y),Fn=lt(ce),Dn=lt(S),Jt=lt(G),je=lt(i),He=lt(Te),St=lt(Fe),rn=lt(r),wt=lt(o),$n=lt(t),mt=lt(null),Tt=lt(new Map),zt=lt(new Map),yn=lt(!1);Lt(()=>(yn.current=!0,()=>{yn.current=!1}),[]),Lt(()=>{Ot.current=m},[m]),Lt(()=>{je.current=i},[i]),Lt(()=>{Cn.current=w},[w]),Lt(()=>{pn.current=_},[_]),Lt(()=>{mn.current=ae},[ae]),Lt(()=>{_n.current=Y},[Y]),Lt(()=>{Fn.current=ce},[ce]),Lt(()=>{Dn.current=S},[S]),Lt(()=>{Jt.current=G},[G]),Lt(()=>{He.current=Te},[Te]),Lt(()=>{St.current=Fe},[Fe]),Lt(()=>{rn.current=r},[r]),Lt(()=>{wt.current=o},[o]),Lt(()=>{$n.current=t},[t]),Lt(()=>{Ye.current=x},[x]),Lt(()=>{re&&U.current?.focus()},[re,x]);let Ut=kr(()=>{window.setTimeout(()=>{U.current?.focus()},0)},[]),At=kr(()=>{fe(!1),at(M=>M+1)},[]),Sn=kr(()=>{Q(!1),(Ie.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Ie.current)?.focus?.()},[]);Lt(()=>{!de||!V.current||(V.current=!1,Sn())},[Sn,de,x]);let wn=kr((M,Oe)=>{let D=Oe?.popupBlocked??Ir(M),kt=rd(D,u.inAppBrowser),xt=_n.current;if(xt){let Gt=D&&u.inAppBrowser?new hi(kt,"api_error",{code:Oe?.code??"paypal_popup_blocked"}):M;xt("paypal",Gt,Oe);return}pn.current?.(kt)},[u.inAppBrowser]),It=kr(M=>{let Oe=ct.current,D=dt.current;Oe===null||!D||(Z.log({...D,name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:M}),Z.performance({...D,stage:"overlay_return",durationMs:Z.elapsed(Oe),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:M}),ct.current=null)},[Z]),te=kr((M,Oe,D)=>{let kt=dt.current;It("overlay_timeout"),kt&&Z.error({...kt,errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),wn(Oe,D),Q(!0),At(),Ut()},[It,Ut,wn,At,Z]),{finishAttempt:on,generationRef:Kn,invalidateAttempt:Ht,isAttemptCurrent:Kt,isAttemptInvalidated:an,startAttempt:nr}=Wo(te),Nn=kr(()=>(Q(!1),nr("paypal")),[nr]),Wt=kr(M=>{Ht(M?.generation),M?.showRetry&&Q(!0),M?.remount&&At(),M?.focus!==!1&&Ut()},[Ut,Ht,At]),Le=M=>{let Oe=mt.current;return Oe&&zt.current.set(M,Oe),M};Lt(()=>{$t.current!==Re&&($t.current=Re,L.current=!1,Ae.current=!1,fe(!1),Ne(!1),Me(!1),Jt.current?.("loading"))},[Re]),Lt(()=>{Bt(()=>Dn.current?.(de&&!xe))},[de,xe]);let fn=Hc(l);Lt(()=>{let M={attempt:Kn.current+1,...u,presentationMode:_e},Oe=()=>dt.current??M,D={error:R=>Z.error({...R,...Oe()}),log:R=>Z.log({...R,...Oe()}),performance:R=>Z.performance({...R,...Oe()}),terminal:R=>Z.terminal({...R,...Oe()}),startTiming:Z.startTiming,elapsed:Z.elapsed},kt=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",xt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(O(`mount clientId=${kt} env=${l??"(unset)"}\u2192${fn??"live"} ccy=${p} sub=${f}`),O(`ua=${xt.slice(0,80)}${xt.length>80?"\u2026":""}`),!s){O("FAIL: clientId empty \u2014 gateway misconfigured"),Me(!0),D.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Ie.current){O("FAIL: containerRef not attached");return}be.current=D.startTiming(),D.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Gt=!1,Vn=!1,ge=()=>Gt||Vn,sn,Hn=!1,Pr=()=>{sn=Vc(),sn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Hn=!0},rr=null,zr=!1,Ur=null,or=!1,Er=()=>{!Ur||or||(or=!0,Ur.close().catch(()=>{}))},Rn=!1,ar=!1,Dt=Ie.current,Ln=null,Wn=null,Gn=[],yt=null,En=!1,Yn=!1,ir=null,gn=R=>{if(!R||typeof R.getBoundingClientRect!="function")return"(no rect)";let d=R.getBoundingClientRect();return`${Math.round(d.width)}\xD7${Math.round(d.height)}`},We=R=>{if(!R)return"(empty)";try{let d=new URL(R,typeof window>"u"?"https://localhost":window.location.href),A=d.pathname.toLowerCase();return A.includes("checkcaptcha")||A.includes("captcha")?`CAPTCHA(${d.host}${A})`:A.includes("risk")||A.includes("challenge")?`RISK(${d.host}${A})`:A.includes("smart/buttons")?`smart-buttons(${d.host})`:`${d.host}${A}`.slice(0,100)}catch{return R.slice(0,80)}},hn=R=>{let d=R.getAttribute("src"),A=R.getAttribute("srcdoc"),g=R.getAttribute("name"),P=R.getAttribute("sandbox"),I=[];return d&&I.push(`src=${We(d)}`),A&&I.push(`srcdoc[${A.length}ch]`),!d&&!A&&I.push("src=(empty) srcdoc=(empty)"),g&&I.push(`name=${g.slice(0,40)}`),P!==null&&I.push(`sandbox="${P.slice(0,40)}"`),I.join(" ")},ln=R=>{if(!(R instanceof HTMLIFrameElement))return"";try{let d=R.contentDocument;if(!d)return"cd=null";let A=d.body?.children.length??0,g=d.body?.innerHTML.length??0,P=d.head?.innerHTML.length??0;return`cd=same-origin readyState=${d.readyState} body[${A}children,${g}ch] head[${P}ch]`}catch(d){return`cd=cross-origin(${d.message.slice(0,30)})`}},On=[],br=R=>{if(ge())return;let d=R.message??String(R.error??"(no message)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(O(`window:error ${d.slice(0,140)}`),On.push(d))},qr=R=>{if(ge())return;let d=R.reason instanceof Error?R.reason.message:String(R.reason??"(no reason)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(O(`window:rejection ${d.slice(0,140)}`),On.push(d))},Cr={value:0},zn=()=>{Ln?.disconnect(),Ln=null,Wn?.disconnect(),Wn=null;for(let R of Gn.splice(0))clearTimeout(R);Yn=!1,En&&typeof window<"u"&&(window.removeEventListener("error",br),window.removeEventListener("unhandledrejection",qr)),En=!1},vn=()=>{if(!(En||ge()||Rn)){if(En=!0,On.length=0,Cr.value=0,typeof window<"u"&&(window.addEventListener("error",br),window.addEventListener("unhandledrejection",qr)),typeof PerformanceObserver<"u")try{Wn=new PerformanceObserver(R=>{if(!ge())for(let d of R.getEntries()){if(!d.name.toLowerCase().includes("paypal"))continue;Cr.value+=1;let A=Math.round(d.duration);O(`net ${A}ms ${d.name.slice(0,90)}`)}}),Wn.observe({type:"resource",buffered:!0})}catch{}ir?.()}},Xr=()=>{yt&&(clearTimeout(yt),yt=null)},Tn=()=>{zn(),Xr()},Tr={setEnabled:R=>{R?vn():zn()}};Et.current=Tr,Ct.current&&vn();let In=R=>{if(!R)return!1;let d=R.toLowerCase();return d.includes("zoid destroyed")||d.includes("destroyed all components")||d.includes("window closed")||d.includes("detected container element removed")},Un=R=>{if(ge()||In(R))return;let d=xr(R)??R;Bt(()=>pn.current?.(d))},et=(R,d)=>{if(Gt||zr)return;zr=!0,Vn=!0,Tn(),Er();let A=td({kind:R,generationActive:!0,automaticRetryAllowed:X,automaticRetryUsed:L.current});if(A.action==="retry"){L.current=!0,fe(!1),ke(!1),Ne(!0),Jt.current?.("retrying"),rr=setTimeout(()=>{Gt||at(g=>g+1)},Yc);return}if(fe(!1),ke(!1),Ne(!1),Me(!0),A.action!=="ignore"){if(Jt.current?.("exhausted"),A.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",d);return}A.report&&D.error({errorCode:A.report.errorCode,stage:A.report.stage,operationOutcome:A.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),Ae.current||(Ae.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",nd(R,d)))}};Me(!1);let Jn=async(R,d=mt.current)=>{if(ge())return;let A=d?.sessionId??e;if(Ot.current){await Ot.current(R,{sessionId:A,accountPatch:d?.accountPatch,nonce:d?.nonce});return}let g=D.startTiming();D.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let P=()=>{D.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"processing",durationMs:D.elapsed(g),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let I=St.current,v=d?.accountPatch?.email??rn.current,q=d?.accountPatch?.userId??I?.customer?.id??I?.accountData?.userId??"",Ve=d?.accountPatch?.firstName??I?.customer?.firstName??I?.accountData?.firstName,Nt=d?.accountPatch?.lastName??I?.customer?.lastName??I?.accountData?.lastName,ne=await new gi(Je,{telemetry:!1}).processPayment(q,{sessionId:A,nonce:d?.nonce??$n.current,paymentMethodCategory:"paypal",tokenizedData:R,accountData:{userId:q,email:v??I?.customer?.email??"",...Ve?{firstName:Ve}:{},...Nt?{lastName:Nt}:{},country:d?.accountPatch?.country??I?.customer?.country??I?.accountData?.country??void 0,zip:d?.accountPatch?.zip??I?.customer?.zip??I?.accountData?.zip??void 0}});if(ne.ok){if(Vn||Gt&&yn.current)return;P(),D.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Bt(()=>Cn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ge())return;let y=await ne.json().catch(()=>null),k=y?.message??"PayPal payment failed.",J=xr(k)??k;P(),ne.status===400&&(typeof y?.declineCode=="string"||!Array.isArray(y?.fields))?D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ne.status===400||ne.status===422?D.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):D.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:id(ne.status),failureCategory:ne.status>=500?"server_error":void 0}),Un(J),Bt(()=>mn.current?.(nn("paypal",J,{code:y?.code,declineCode:y?.declineCode})));return}catch(I){if(ge())return;P(),D.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let v=I instanceof Error?I.message:"PayPal payment failed.",q=xr(v)??v;Un(q),Bt(()=>mn.current?.(nn("paypal",q)));return}},Xt=()=>new hi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),_t=R=>ge()?Promise.reject(Xt()):Promise.resolve(R),T=async R=>{if(ge())throw Xt();Hn||Pr();let d=mt.current,A=d?.sessionId??e,g=d?.nonce??$n.current;D.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let P;try{P=await new gi(Je,{telemetry:!1}).createSessionIntent(A,g??"",Ke?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:vi,paymentMethodId:null,intentKind:ie==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:sn})}catch(I){throw D.error({...Kc(I,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),I}if(ge())throw Xt();if(P.provider!=="paypal"||P.providerObjectType!==ie)throw new Error(R);return D.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),P.providerObjectId},E=(R,d)=>{let A=d?.nonce??$n.current;if(!A)return;let g=d?.sessionId??e,P=fo(R)??wr(R)??"provider_declined";new gi(Je,{telemetry:!1}).reportSessionIntentDecline(g,A,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:P}).catch(()=>{})},F=x;O("loadScript:scheduled (deferred 1 tick)");let z=null,it=setTimeout(()=>{if(Gt){O("loadScript:skipped (cancelled before defer ran)");return}O("loadScript:start");let R=fn==="live"?"production":fn,d={};ie==="subscription"?d={intent:"subscription",vault:!0}:ie==="order"&&(d={intent:"capture"}),z=Gc({clientId:s,currency:p,...d,...R?{environment:R}:{},...R==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let A=!1;z.then(g=>{if(A=!0,O(`loadScript:resolved inactive=${ge()} ns=${!!g} buttons=${!!g?.Buttons}`),ge())return;if(!g?.Buttons){O("FAIL: namespace missing Buttons factory"),et("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}D.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"provider_ready",durationMs:D.elapsed(be.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),D.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let P=async(ne,y)=>{if(ge()||Ye.current!==F)return;let k=ne.vaultSetupToken??ne.subscriptionID??ne.orderID??"",J=k?zt.current.get(k):Tt.current.get(F);if(!(!J||!Kt(J.generation))&&on(J.generation)){zt.current.delete(k),Tt.current.delete(J.surfaceKey),It("approved");try{if(ke(!0),Bt(()=>pn.current?.(null)),!k)throw new hi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ue=St.current,Se=Vr(wt.current??[ue?.customer?.firstName,ue?.customer?.lastName].filter(Boolean).join(" ")),pe=Bn({email:J.accountPatch?.email?.trim()||rn.current?.trim()||ue?.customer?.email?.trim(),firstName:J.accountPatch?.firstName?.trim()||Se.firstName,lastName:J.accountPatch?.lastName?.trim()||Se.lastName});if(!Go(pe.email)||!(pe.firstName||pe.lastName))try{let ht=ad(await y?.order?.get?.());pe=Bn({email:ht.email||pe.email,firstName:ht.firstName||pe.firstName,lastName:ht.lastName||pe.lastName})}catch{}if((je.current||H)&&!Go(pe.email)){let ht=await ee("PayPal",pe);if(!ht)return;pe=ht}Go(pe.email)&&(J.accountPatch=Bn({...J.accountPatch,...pe}),await je.current?.(pe));let Ge;ie==="setup_token"?Ge={id:k,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:vi}:Ke?Ge={id:k,isPaypal:!0,gateway:"paypal",paymentMethodType:vi}:Ge={id:k,isPaypal:!0},await Jn(Ge,J)}catch(ue){Un(ue instanceof Error?ue.message:"PayPal capture failed.")}finally{ge()||ke(!1)}}},I=ne=>{let y=ve?()=>_t(ve):()=>T(ne);return async()=>Le(await y())},v=g.Buttons({style:{layout:"horizontal",height:Ia,tagline:!1},..._e==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ne,y)=>{if(ge()){await y.reject();return}Pr();let k=He.current,J={};if(k)try{let pe=await k("paypal");if(ge()){await y.reject();return}if(!pe.proceed){mt.current=null,Tt.current.delete(F),await y.reject();return}J={sessionId:pe.sessionId,accountPatch:pe.accountPatch,nonce:pe.nonce}}catch(pe){O(`onClick:runBeforeButtonClick rejected msg=${(pe instanceof Error?pe.message:String(pe)).slice(0,120)}`),mt.current=null,Tt.current.delete(F),await y.reject();return}Bt(()=>Fn.current?.("paypal"));let ue=Nn(),Se={generation:ue,surfaceKey:F,...J};mt.current=Se,Tt.current.set(F,Se),dt.current={...M,attempt:ue},await y.resolve(),D.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),ct.current=D.startTiming()},createOrder:ie==="order"?I("Failed to create PayPal order."):void 0,createSubscription:ie==="subscription"?I("Failed to create PayPal subscription."):void 0,createVaultSetupToken:ie==="setup_token"?async()=>Le(await T("Failed to create PayPal setup token.")):void 0,onApprove:P,onCancel:()=>{if(ge())return;let ne=Tt.current.get(F)??mt.current;ne&&Tt.current.delete(ne.surfaceKey),mt.current=null,It("cancelled"),D.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),V.current=!0,Wt({generation:ne?.generation,remount:!0,focus:!1})},onError:ne=>{if(ge()||Ye.current!==F)return;let y=ne instanceof Error?ne.message:"PayPal failed to render.";if(O(`onError rendered=${Rn} msg=${y.slice(0,120)}`),Rn){let k=Tt.current.get(F)??mt.current;if(k&&!Kt(k.generation)||!k&&an())return;if(In(y)){on(k?.generation);return}let{errorCode:J,popupBlocked:ue,providerDeclined:Se,terminalReason:pe}=od(ne);if(It(pe),Se){D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:pe}),E(ne,k),Bt(()=>mn.current?.(nn("paypal",y))),k&&Tt.current.delete(k.surfaceKey),mt.current=null,on(k?.generation);return}D.error({errorCode:J,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:pe}),k&&Tt.current.delete(k.surfaceKey),mt.current=null,Wt({generation:k?.generation,remount:!0,showRetry:!0,focus:!0}),wn(ne,{code:"paypal_runtime_failed",popupBlocked:ue});return}et(In(y)?"teardown":"pre_ready_callback",y)}}),q=v.isEligible();if(O(`isEligible=${q}`),D.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!q){fe(!1),et("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}ar=!0,Ur=v,ir=()=>{if(!En||Yn||ge()||Rn)return;Yn=!0,O(`container:dims ${gn(Dt)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Ln=new MutationObserver(y=>{if(!ge()){for(let k of y)if(k.type==="childList")k.addedNodes.forEach(J=>{if(!(J instanceof Element))return;let ue=J.tagName.toLowerCase(),Se=(J.getAttribute("title")??"").slice(0,40),pe=ue==="iframe"?` ${hn(J)}`:"";O(`child+ ${ue}${Se?` title="${Se}"`:""}${pe} dims=${gn(J)}`)});else if(k.type==="attributes"&&k.target instanceof Element){let J=k.target;if(J.tagName.toLowerCase()!=="iframe")continue;let ue=k.attributeName;(ue==="src"||ue==="srcdoc")&&O(`attr~ iframe ${ue}=${ue==="srcdoc"?`[${(J.getAttribute("srcdoc")??"").length}ch]`:We(J.getAttribute("src"))} dims=${gn(J)}`)}}}),Ln.observe(Dt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ne=y=>{if(ge()||Rn)return;let k=Dt.querySelectorAll("iframe"),J=typeof document<"u"&&"hasStorageAccess"in document;O(`watchdog:${y} container=${gn(Dt)} children=${Dt.childElementCount} iframes=${k.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${J} paypalNetRequests=${Cr.value}`),k.forEach((ue,Se)=>{let pe=(ue.getAttribute("title")??"").slice(0,40);O(` iframe[${Se}] ${gn(ue)}${pe?` title="${pe}"`:""} ${hn(ue)}`);let Ge=ln(ue);Ge&&O(` ${Ge}`)}),On.length===0&&O(" (no PayPal/zoid window errors captured)")};Gn.push(setTimeout(()=>ne("3s"),3e3)),Gn.push(setTimeout(()=>ne("8s"),8e3)),Gn.push(setTimeout(()=>ne("15s"),15e3))},ir(),O("render:start");let Nt=D.startTiming();yt=setTimeout(()=>{ge()||Rn||(O("watchdog:11s retryable render timeout"),et("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Jc);let Ce=v.render(Dt);(async()=>{try{if(await Ce,O(`render:resolved inactive=${ge()}`),Tn(),ge()){Er();return}Rn=!0,fe(!0),Ne(!1),Jt.current?.("ready"),D.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"checkout_render",durationMs:D.elapsed(Nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ne){let y=ne instanceof Error?ne.message:"PayPal failed to render.";O(`render:rejected msg=${y.slice(0,120)}`),Tn(),et(In(y)?"teardown":"render_rejected",y)}})()}).catch(g=>{let P=g instanceof Error?g.message:"PayPal operation failed.";O(`provider:failed msg=${P.slice(0,120)}`);let I="script_rejected";A&&In(P)?I="teardown":A&&ar&&(I="render_rejected"),et(I,P)})},0);return()=>{Gt=!0,clearTimeout(it),rr&&clearTimeout(rr),Tn(),Et.current===Tr&&(Et.current=null),Er(),ct.current=null,dt.current=null}},[X,Je,s,p,l,ie,_e,Ke,e,ve,x,Z,ee,H,O,It]);let se=$e?bi("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:xe?"#fef2f2":"#f3f4f6",border:`1px solid ${xe?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${de} failed=${xe})`,pt.length===0?`
1
+ import{a as Ft,b as kr,c as Zo,d as Ei,e as Qo,f as dl,g as ul,h as Wc,i as Gc}from"./chunk-CSBYK62Y.mjs";import{dropThirdPartyOnlyError as Bm}from"@flopay/shared";import{PaymentAPI as Rs}from"@flopay/js";import{FloPayError as Sa,resolveBillingApiUrl as ap,resolveButtonsLayoutTheme as ip,resolveTheme as sp}from"@flopay/shared";import{useCallback as Nr,useEffect as Oo,useMemo as Ca,useRef as No,useState as wa}from"react";import{Fragment as vo,jsx as Zn,jsxs as pl}from"react/jsx-runtime";function Yc(){return pl(vo,{children:[pl("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:[Zn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Zn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Zn("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:Zn("path",{d:"M9 18l6-6-6-6"})})]})}function Jc(){return Zn(vo,{children:"Go back"})}function Xc(){return Zn(vo,{children:"Secure card checkout"})}function go(e){return e!==void 0&&(e===""||e===null||e===!1)}function ho({content:e}){return Zn(vo,{children:e===void 0?Zn(Yc,{}):e})}function Po({content:e}){return Zn(vo,{children:e===void 0?Zn(Jc,{}):e})}function ea({content:e}){return Zn(vo,{children:e===void 0?Zn(Xc,{}):e})}import{classifyTelemetryFailure as Zc,FloPayError as $n,isCardHolderNamePlaceholder as yl,isMoneySettledOutcome as Qc,isSetupIntentClientSecret as ed,isValidEmail as td}from"@flopay/shared";var nd="Checkout is temporarily unavailable. Please try again later.";function Ti(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof $n&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function rd(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 ml(){return new $n(nd,"api_error",{code:"CheckoutInitializationFailed"})}function Ai(e){return!!e?.gateways?.worldpayCorporateGateway}function Ur(e){return e?.status==="open"&&Ai(e)}function fl(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")||Ur(r))||t&&e?.data.paypal?.publishableKey)}function gl(e,t){if(t&&(!(e instanceof $n)||e.type==="authentication_error"))return Ti(e);if(!(e instanceof $n&&rd(e))){if(!t&&!(e instanceof $n)&&(e instanceof TypeError||e instanceof SyntaxError))return{...Zc(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof $n)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof $n))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function bo(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let s={...r,...i,email:i.email?.trim()||r.email?.trim()},l=yl(s.firstName,s.lastName);if(!td(s.email))return Promise.reject(new $n("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[y,b]of Object.entries(s)){if(l&&y.endsWith("Name")||typeof b!="string")continue;let g=b.trim();g&&(m[y]=g)}return o=e.claimCheckoutSession(t,n,{accountData:m}),o.catch(()=>{}),o}}function hl(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 xi(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 Pl(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,s)=>i+(s.overrideAmount??s.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,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,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 Qr(e){if(yl(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Mi(e,t){return t?{...e,...t}:e}function ln(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 od=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function qr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of od)if(n.test(t))return r;return e}function Dr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function jr(e){return e?.status==="authorized"||e?.status==="complete"}function vl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Da(e){let t=vl(e);return new $n(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Oa(e){return e instanceof $n||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Co(e){let t=vl(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new $n(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function ta(e,t){return e==="processing"||Qc(e,t)}function bl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Cl(e,t){let n=e;if(ed(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new $n(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new $n(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function wl(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 Bi(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 na(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as $u,PaymentAPI as si,SESSION_CREATE_TELEMETRY as Ku}from"@flopay/js";import{buildCheckoutDisplayData as Vu,classifyTelemetryFailure as Ic,FloPayError as Sn,isDetachedSessionEligible as Hu,resolveBillingApiUrl as Wu,resolveButtonsLayoutTheme as Gu,resolveIdempotencyKey as Pc,resolveTheme as _c,SDK_VERSION as Rc,telemetryStatusClass as Yu}from"@flopay/shared";import Ps,{useCallback as wn,useEffect as yr,useMemo as er,useRef as xt,useState as qt}from"react";import{createContext as Sl}from"react";var Qn=Sl({flopay:null,paypalFlopay:null,billingApiUrl:""}),dr=Sl({session:null,loading:!1,error:null});import{PaymentAPI as Ni}from"@flopay/js";import{classifyTelemetryFailure as wd,FloPayError as Li,generateIdempotencyKey as Sd,isValidEmail as ca,normalizeGatewayEnvironment as kd,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as zi,SDK_VERSION as Id}from"@flopay/shared";import{loadScript as _d}from"@paypal/paypal-js";import{useCallback as _r,useContext as Rd,useEffect as Nt,useMemo as da,useRef as ot,useState as Hr}from"react";import{isValidEmail as ad}from"@flopay/shared";import{useCallback as kl,useEffect as id,useRef as Il,useState as Rl}from"react";import{jsx as _l,jsxs as ra}from"react/jsx-runtime";function Fn(e,t=!1){let{firstName:n,lastName:r,...o}=e,i=n?.trim(),s=r?.trim();return{...o,...i||t?{firstName:i??""}:{},...s||t?{lastName:s??""}:{}}}function wo(){let[e,t]=Rl(null),n=Il(null),r=Il(0),o=kl((s,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:l}),new Promise(m=>{n.current=m})),[]),i=kl(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return id(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function So({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=Rl(e.email?.trim()??""),m=ad(s.trim());return ra("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:[ra("div",{style:{fontWeight:700},children:["Continue with ",t]}),ra("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",_l("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:y=>l(y.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),ra("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&_l("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),ra("button",{type:"button",disabled:!m||o,onClick:()=>{n(Fn({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var sd=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),ld=["https://www.paypal.com","https://www.sandbox.paypal.com"];function Na(e,t,n){let r=`We couldn't open ${e}. Try again or choose another payment method.`;return t?n?`${r} Open this page in your system browser, then try again.`:`${r} Allow pop-ups for this site, then try again.`:r}function El(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 eo(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Ir(e){if(typeof e!="object"||e===null)return;let t=e;return eo(t.code)??eo(t.type)??eo(t.name)}function ko(e){if(!(typeof e!="object"||e===null))return eo(e.decline_code)}function oa(e){return typeof e!="object"||e===null?!1:eo(e.type)?.toLowerCase()==="card_error"||ko(e)!==void 0}function cd(e){let t=El(e)?.toLowerCase()??"",n=Ir(e)?.toLowerCase()??"";return sd.has(n)?!0:/(?:popup|pop-up).{0,40}(?:block|denied|prevent)/i.test(t)||/(?:block|denied|prevent).{0,40}(?:popup|pop-up)/i.test(t)}function Fi(e){if(Ir(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=El(e)??"";return n.includes("No ack for postMessage init()")&&ld.some(r=>n.includes(r))&&n.includes("10000ms")}function La(e,t){if(oa(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=cd(e)||t.inAppBrowser&&!t.handoffObserved&&Fi(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function $r(e){return La(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}import{resolveBillingApiUrl as dd}from"@flopay/shared";import{useContext as za}from"react";function Kr(){return za(Qn).flopay}function Di(){return za(Qn).paypalFlopay??null}function ud(){return za(dr)}function Tl(){return za(Qn).billingApiUrl||dd()}function aa(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 Al(e,t,n=e.popupCapability){return e.inAppBrowser||n==="blocked"||t==="prefer_redirect"?"redirect":"popup"}function Ua(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}import{FLO_INSTRUMENT_SCHEMA_VERSION as pd}from"@flopay/shared";import{useCallback as yd,useRef as qa}from"react";var md={"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 fd(e){return e==="stripe"||e==="paypal"?e:void 0}function gd(e){let t=fd(e.provider),n={schemaVersion:pd,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=md[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 Io(e,t){let n=qa(e);n.current=e;let r=qa(new Set),o=qa(t),i=qa(t);return Zo(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),yd(s=>{if(i.current!==t)return;let l=gd(s);if(l){if(Oi.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}Ft(()=>n.current?.(l))}},[t])}import{createContext as hd}from"react";var ia=hd(null);function ja(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Pd=Symbol.for("@flopay/js.telemetry.bridge.v1"),vd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function bd(){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 Cd(e){let t=bd(),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 $a(e){let t=globalThis[vd];return Cd(t?.(e)??{})}function cn(e){if(e)return e[Pd]}import{useCallback as Vr,useEffect as xl,useRef as sa}from"react";function la(e,t){let n=sa(0),r=sa(null),o=sa(null),i=sa(e),s=sa(t?.onHandoffObserved);xl(()=>{i.current=e,s.current=t?.onHandoffObserved},[e,t?.onHandoffObserved]);let l=Vr((v=o.current)=>{v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),m=Vr(v=>{l();let U=n.current+1;return n.current=U,r.current=null,o.current={generation:U,method:v,timer:null,yieldedControl:!1},U},[l]),y=Vr(v=>{let U=o.current;return v!==void 0&&U?.generation!==v?!1:(l(U),o.current=null,(v===void 0||r.current===v)&&(r.current=null),!0)},[l]),b=Vr(v=>{let U=o.current,ue=v??U?.generation??n.current;(v===void 0||U?.generation===v)&&(l(U),o.current=null),r.current=ue},[l]),g=Vr(v=>r.current===(v??n.current),[]),F=Vr(v=>o.current?.generation===v&&r.current!==v,[]),M=Vr(()=>{let v=o.current;v&&(l(v),!v.yieldedControl&&(v.yieldedControl=!0,s.current?.(v.method)))},[l]),w=Vr(()=>{let v=o.current;!v?.yieldedControl||document.visibilityState!=="visible"||(l(v),v.timer=setTimeout(()=>{v.timer=null,o.current?.generation===v.generation&&(o.current=null,r.current=v.generation,i.current(v.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[l]);return xl(()=>{let v=()=>{document.visibilityState==="visible"?w():M()};return document.addEventListener("visibilitychange",v),window.addEventListener("blur",M),window.addEventListener("focus",w),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("blur",M),window.removeEventListener("focus",w),l()}},[l,M,w]),{startAttempt:m,finishAttempt:y,invalidateAttempt:b,isAttemptInvalidated:g,isAttemptCurrent:F,generationRef:n}}import{jsx as to,jsxs as Ui}from"react/jsx-runtime";var Ka=45,Ed=1e3,Td=11e3,Ad={width:"100%",minHeight:Ka,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"},xd={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 Md(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:xd[e.kind]??null}}function Ml(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Fi(t)?"paypal_init_timeout":"paypal_init_failure"}function Bd(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 Fd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Bl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:s,environment:l,currency:m,isSubscription:y,providerObjectType:b,approvalPresentation:g,onTokenizedBody:F,onComplete:M,onErrorChange:w,onDecline:v,onTechnicalFailure:U,isProcessing:ue=!1,onLoadStateChange:E,onInitializationStateChange:J,allowAutomaticRetry:K=!0,onButtonClick:se,runBeforeButtonClick:G,session:xe,existingOrderId:Ye,telemetry:be,telemetryContext:et,onInstrument:It,debug:pe=!1}){let De=Kr(),_t=Io(It,e),Re=da(()=>{if(De)return null;let I=$a({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Id,enabled:be!==!1});return I.setCheckoutContext(et??{}),I.beginCheckout(et??{}),I},[n,De,be,et?.checkoutMode,et?.layout]),Oe=da(()=>cn(De),[De]);Nt(()=>()=>{Re&&Re.flush().catch(()=>{}).finally(()=>Re.destroy())},[Re]);let he=da(()=>({error:I=>{Oe?Oe.error(I):Re?.error(I),_t({class:"technical_error",errorCode:I.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":I.errorCode,requestCategory:I.requestCategory,provider:I.provider})},log:I=>{Oe?Oe.log(I):Re?.log(I),_t({class:"lifecycle",name:I.name,provider:I.provider})},performance:I=>{Oe?Oe.performance(I):Re?.performance(I)},terminal:I=>{Oe?Oe.terminal(I):Re?.terminal(I)},startTiming:()=>Oe?.now()??Re?.now()??0,elapsed:I=>Oe?.elapsed(I)??Math.max(0,(Re?.now()??I)-I)}),[_t,Oe,Re]),le=ot(null),Ne=ot(0),Je=ot(null),pt=ot(null),D=ot(null),qe=Rd(ia),ce=ot(null);ce.current||(ce.current=ja());let O=qe??ce.current,$e=ot(null),Ke=ot(!1),[Ve,V]=Hr(!1),[tt,nt]=Hr(!1),[_e,Pe]=Hr(0),He=ot(0),[ft,Le]=Hr(!1),en=ot(!1),jt=ot(!1),[lt,it]=Hr(!1),[T,ye]=Hr(!1),{request:Me,collect:L,finish:ze}=wo(),Ct=ot({sessionId:e,required:!ca(r?.trim()||xe?.customer?.email?.trim())});Ct.current.sessionId!==e&&(Ct.current={sessionId:e,required:!ca(r?.trim()||xe?.customer?.email?.trim())});let Ue=Ct.current.required,c=da(()=>n.replace(/\/+$/,""),[n]),N=xe?.gateways?.paypal?.providerObjectType??b,h=N??(y?"subscription":"order"),[j]=Hr(aa),Ae=xe?.gateways?.paypal?.approvalPresentation??g,me=Ua(j,Ae==="app_switch"?"app_switch":void 0,h),rt=N==="order"||N==="setup_token",Xe=da(()=>JSON.stringify([c,s,m,l??"",h,rt,me,e,Ye??""]),[c,s,m,l,Ye,h,rt,me,e]),oe=ot(Xe),ct=oe.current!==Xe,Rt=ot(pe),Pn=ot(null),[Ze,$t]=Hr([]),Ee=_r(I=>{Rt.current&&$t(je=>[...je,`${new Date().toISOString().slice(11,23)} ${I}`])},[]);Nt(()=>{Rt.current=pe,pe&&Ee("debug:enabled"),Pn.current?.setEnabled(pe)},[Ee,pe]);let Dn=ot(F),Rn=ot(M),Mt=ot(w),kn=ot(v),On=ot(U),Nn=ot(se),tn=ot(E),fe=ot(J),gt=ot(i),Et=ot(G),vn=ot(xe),Bt=ot(r),Kn=ot(o),dn=ot(t),Kt=ot(null),on=ot(new Map),Vn=ot(new Map),un=ot(!1);Nt(()=>(un.current=!0,()=>{un.current=!1}),[]),Nt(()=>{Dn.current=F},[F]),Nt(()=>{gt.current=i},[i]),Nt(()=>{Rn.current=M},[M]),Nt(()=>{Mt.current=w},[w]),Nt(()=>{kn.current=v},[v]),Nt(()=>{On.current=U},[U]),Nt(()=>{Nn.current=se},[se]),Nt(()=>{tn.current=E},[E]),Nt(()=>{fe.current=J},[J]),Nt(()=>{Et.current=G},[G]),Nt(()=>{vn.current=xe},[xe]),Nt(()=>{Bt.current=r},[r]),Nt(()=>{Kn.current=o},[o]),Nt(()=>{dn.current=t},[t]),Nt(()=>{He.current=_e},[_e]),Nt(()=>{ft&&$e.current?.focus()},[ft,_e]);let ht=_r(()=>{window.setTimeout(()=>{$e.current?.focus()},0)},[]),Jt=_r(()=>{V(!1),Pe(I=>I+1)},[]),pn=_r(()=>{Le(!1),(le.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??le.current)?.focus?.()},[]);Nt(()=>{!Ve||!Ke.current||(Ke.current=!1,pn())},[pn,Ve,_e]);let Dt=_r((I,je)=>{let Z=je?.popupBlocked??$r(I);Z&&O.markBlocked();let Hn=Na("PayPal",Z,j.inAppBrowser),mn=On.current;if(mn){let Ht=Z&&j.inAppBrowser?new Li(Hn,"api_error",{code:je?.code??"paypal_popup_blocked"}):I;mn("paypal",Ht,je);return}Mt.current?.(Hn)},[O,j.inAppBrowser]),Xt=_r(I=>{let je=Je.current,Z=pt.current;je===null||!Z||(he.log({...Z,popupCapability:O.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:I}),he.performance({...Z,popupCapability:O.current(),stage:"overlay_return",durationMs:he.elapsed(je),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:I}),Je.current=null)},[O,he]),Vt=_r((I,je,Z)=>{let Hn=pt.current;Xt("overlay_timeout"),Hn&&he.error({...Hn,popupCapability:O.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Dt(je,{...Z,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:me,terminalReason:"overlay_timeout"}),Le(!0),Jt(),ht()},[Xt,ht,Dt,O,me,Jt,he]),yn=_r(()=>{O.markAvailable();let I=pt.current;I&&(D.current=I.attempt,he.log({...I,popupCapability:O.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[O,he]),{finishAttempt:yt,generationRef:H,invalidateAttempt:Ln,isAttemptCurrent:zn,isAttemptInvalidated:mr,startAttempt:bn}=la(Vt,{onHandoffObserved:yn}),an=_r(()=>(Le(!1),bn("paypal")),[bn]),En=_r(I=>{Ln(I?.generation),I?.showRetry&&Le(!0),I?.remount&&Jt(),I?.focus!==!1&&ht()},[ht,Ln,Jt]),Ce=I=>{let je=Kt.current;return je&&Vn.current.set(I,je),I};Nt(()=>{oe.current!==Xe&&(oe.current=Xe,en.current=!1,jt.current=!1,V(!1),nt(!1),it(!1),fe.current?.("loading"))},[Xe]),Nt(()=>{Ft(()=>tn.current?.(Ve&&!lt))},[Ve,lt]);let mt=kd(l);Nt(()=>{let I={attempt:H.current+1,inAppBrowser:j.inAppBrowser,appFamily:j.appFamily,popupCapability:O.current(),presentationMode:me},je=()=>({...pt.current??I,popupCapability:O.current()}),Z={error:d=>he.error({...d,...je()}),log:d=>he.log({...d,...je()}),performance:d=>he.performance({...d,...je()}),terminal:d=>he.terminal({...d,...je()}),startTiming:he.startTiming,elapsed:he.elapsed},Hn=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",mn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Ee(`mount clientId=${Hn} env=${l??"(unset)"}\u2192${mt??"live"} ccy=${m} sub=${y}`),Ee(`ua=${mn.slice(0,80)}${mn.length>80?"\u2026":""}`),!s){Ee("FAIL: clientId empty \u2014 gateway misconfigured"),it(!0),Z.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(!le.current){Ee("FAIL: containerRef not attached");return}Ne.current=Z.startTiming(),Z.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ht=!1,Wn=!1,Qe=()=>Ht||Wn,Lr,Wt=!1,fn=()=>{Lr=Sd(),Lr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Wt=!0},Ar=null,xr=!1,Tn=null,Zt=!1,fr=()=>{!Tn||Zt||(Zt=!0,Tn.close().catch(()=>{}))},An=!1,Mr=!1,xn=le.current,gr=null,hr=null,tr=[],Gn=null,Yn=!1,At=!1,nr=null,In=d=>{if(!d||typeof d.getBoundingClientRect!="function")return"(no rect)";let p=d.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},Jn=d=>{if(!d)return"(empty)";try{let p=new URL(d,typeof window>"u"?"https://localhost":window.location.href),_=p.pathname.toLowerCase();return _.includes("checkcaptcha")||_.includes("captcha")?`CAPTCHA(${p.host}${_})`:_.includes("risk")||_.includes("challenge")?`RISK(${p.host}${_})`:_.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${_}`.slice(0,100)}catch{return d.slice(0,80)}},Pr=d=>{let p=d.getAttribute("src"),_=d.getAttribute("srcdoc"),x=d.getAttribute("name"),ee=d.getAttribute("sandbox"),$=[];return p&&$.push(`src=${Jn(p)}`),_&&$.push(`srcdoc[${_.length}ch]`),!p&&!_&&$.push("src=(empty) srcdoc=(empty)"),x&&$.push(`name=${x.slice(0,40)}`),ee!==null&&$.push(`sandbox="${ee.slice(0,40)}"`),$.join(" ")},st=d=>{if(!(d instanceof HTMLIFrameElement))return"";try{let p=d.contentDocument;if(!p)return"cd=null";let _=p.body?.children.length??0,x=p.body?.innerHTML.length??0,ee=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${_}children,${x}ch] head[${ee}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},nn=[],Qt=d=>{if(Qe())return;let p=d.message??String(d.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(Ee(`window:error ${p.slice(0,140)}`),nn.push(p))},Br=d=>{if(Qe())return;let p=d.reason instanceof Error?d.reason.message:String(d.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(Ee(`window:rejection ${p.slice(0,140)}`),nn.push(p))},Un={value:0},zr=()=>{gr?.disconnect(),gr=null,hr?.disconnect(),hr=null;for(let d of tr.splice(0))clearTimeout(d);At=!1,Yn&&typeof window<"u"&&(window.removeEventListener("error",Qt),window.removeEventListener("unhandledrejection",Br)),Yn=!1},rr=()=>{if(!(Yn||Qe()||An)){if(Yn=!0,nn.length=0,Un.value=0,typeof window<"u"&&(window.addEventListener("error",Qt),window.addEventListener("unhandledrejection",Br)),typeof PerformanceObserver<"u")try{hr=new PerformanceObserver(d=>{if(!Qe())for(let p of d.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;Un.value+=1;let _=Math.round(p.duration);Ee(`net ${_}ms ${p.name.slice(0,90)}`)}}),hr.observe({type:"resource",buffered:!0})}catch{}nr?.()}},or=()=>{Gn&&(clearTimeout(Gn),Gn=null)},gn=()=>{zr(),or()},ar={setEnabled:d=>{d?rr():zr()}};Pn.current=ar,Rt.current&&rr();let Fr=d=>{if(!d)return!1;let p=d.toLowerCase();return p.includes("zoid destroyed")||p.includes("destroyed all components")||p.includes("window closed")||p.includes("detected container element removed")},_n=d=>{if(Qe()||Fr(d))return;let p=qr(d)??d;Ft(()=>Mt.current?.(p))},S=(d,p)=>{if(Ht||xr)return;xr=!0,Wn=!0,gn(),fr();let _=Md({kind:d,generationActive:!0,automaticRetryAllowed:K,automaticRetryUsed:en.current});if(_.action==="retry"){en.current=!0,V(!1),ye(!1),nt(!0),fe.current?.("retrying"),Ar=setTimeout(()=>{Ht||Pe(x=>x+1)},Ed);return}if(V(!1),ye(!1),nt(!1),it(!0),_.action!=="ignore"){if(fe.current?.("exhausted"),_.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",p);return}if(_.report){let x=La({code:Ml(d,p),message:p},{inAppBrowser:j.inAppBrowser,handoffObserved:!1});x.popupBlocked&&O.markBlocked(),Z.error({errorCode:x.popupBlocked?x.errorCode:_.report.errorCode,stage:_.report.stage,operationOutcome:_.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:x.terminalReason})}jt.current||(jt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Ml(d,p)))}};it(!1);let R=async(d,p=Kt.current)=>{if(Qe())return;let _=p?.sessionId??e;if(Dn.current){await Dn.current(d,{sessionId:_,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let x=Z.startTiming();Z.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ee=()=>{Z.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Z.performance({stage:"processing",durationMs:Z.elapsed(x),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let $=vn.current,Be=p?.accountPatch?.email??Bt.current,wt=p?.accountPatch?.userId??$?.customer?.id??$?.accountData?.userId??"",C=p?.accountPatch?.firstName??$?.customer?.firstName??$?.accountData?.firstName,de=p?.accountPatch?.lastName??$?.customer?.lastName??$?.accountData?.lastName,ne=await new Ni(c,{telemetry:!1}).processPayment(wt,{sessionId:_,nonce:p?.nonce??dn.current,paymentMethodCategory:"paypal",tokenizedData:d,accountData:{userId:wt,email:Be??$?.customer?.email??"",...C?{firstName:C}:{},...de?{lastName:de}:{},country:p?.accountPatch?.country??$?.customer?.country??$?.accountData?.country??void 0,zip:p?.accountPatch?.zip??$?.customer?.zip??$?.accountData?.zip??void 0}});if(ne.ok){if(Wn||Ht&&un.current)return;ee(),Z.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Ft(()=>Rn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Qe())return;let B=await ne.json().catch(()=>null),Y=B?.message??"PayPal payment failed.",P=qr(Y)??Y;ee(),ne.status===400&&(typeof B?.declineCode=="string"||!Array.isArray(B?.fields))?Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ne.status===400||ne.status===422?Z.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):Z.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Fd(ne.status),failureCategory:ne.status>=500?"server_error":void 0}),_n(P),Ft(()=>kn.current?.(ln("paypal",P,{code:B?.code,declineCode:B?.declineCode})));return}catch($){if(Qe())return;ee(),Z.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Be=$ instanceof Error?$.message:"PayPal payment failed.",wt=qr(Be)??Be;_n(wt),Ft(()=>kn.current?.(ln("paypal",wt)));return}},k=()=>new Li("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Q=d=>Qe()?Promise.reject(k()):Promise.resolve(d),ke=async d=>{if(Qe())throw k();Wt||fn();let p=Kt.current,_=p?.sessionId??e,x=p?.nonce??dn.current;Z.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ee;try{ee=await new Ni(c,{telemetry:!1}).createSessionIntent(_,x??"",rt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:zi,paymentMethodId:null,intentKind:h==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Lr})}catch($){throw Z.error({...wd($,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),$}if(Qe())throw k();if(ee.provider!=="paypal"||ee.providerObjectType!==h)throw new Error(d);return Z.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ee.providerObjectId},dt=(d,p)=>{let _=p?.nonce??dn.current;if(!_)return;let x=p?.sessionId??e,ee=ko(d)??Ir(d)??"provider_declined";new Ni(c,{telemetry:!1}).reportSessionIntentDecline(x,_,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ee}).catch(()=>{})},te=_e;Ee("loadScript:scheduled (deferred 1 tick)");let Ie=null,z=setTimeout(()=>{if(Ht){Ee("loadScript:skipped (cancelled before defer ran)");return}Ee("loadScript:start");let d=mt==="live"?"production":mt,p={};h==="subscription"?p={intent:"subscription",vault:!0}:h==="order"&&(p={intent:"capture"}),Ie=_d({clientId:s,currency:m,...p,...d?{environment:d}:{},...d==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let _=!1;Ie.then(x=>{if(_=!0,Ee(`loadScript:resolved inactive=${Qe()} ns=${!!x} buttons=${!!x?.Buttons}`),Qe())return;if(!x?.Buttons){Ee("FAIL: namespace missing Buttons factory"),S("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}Z.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),Z.performance({stage:"provider_ready",durationMs:Z.elapsed(Ne.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),Z.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let ee=async(ne,B)=>{if(Qe()||He.current!==te)return;let Y=ne.vaultSetupToken??ne.subscriptionID??ne.orderID??"",P=Y?Vn.current.get(Y):on.current.get(te);if(!(!P||!zn(P.generation))&&yt(P.generation)){Vn.current.delete(Y),on.current.delete(P.surfaceKey),Xt("approved");try{if(ye(!0),Ft(()=>Mt.current?.(null)),!Y)throw new Li("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Te=vn.current,St=Qr(Kn.current??[Te?.customer?.firstName,Te?.customer?.lastName].filter(Boolean).join(" ")),we=Fn({email:P.accountPatch?.email?.trim()||Bt.current?.trim()||Te?.customer?.email?.trim(),firstName:P.accountPatch?.firstName?.trim()||St.firstName,lastName:P.accountPatch?.lastName?.trim()||St.lastName});if(!ca(we.email)||!(we.firstName||we.lastName))try{let vr=Bd(await B?.order?.get?.());we=Fn({email:vr.email||we.email,firstName:vr.firstName||we.firstName,lastName:vr.lastName||we.lastName})}catch{}if((gt.current||Ue)&&!ca(we.email)){let vr=await L("PayPal",we);if(!vr)return;we=vr}ca(we.email)&&(P.accountPatch=Fn({...P.accountPatch,...we}),await gt.current?.(we));let Cn;h==="setup_token"?Cn={id:Y,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:zi}:rt?Cn={id:Y,isPaypal:!0,gateway:"paypal",paymentMethodType:zi}:Cn={id:Y,isPaypal:!0},await R(Cn,P)}catch(Te){_n(Te instanceof Error?Te.message:"PayPal capture failed.")}finally{Qe()||ye(!1)}}},$=ne=>{let B=Ye?()=>Q(Ye):()=>ke(ne);return async()=>Ce(await B())},Be=x.Buttons({style:{layout:"horizontal",height:Ka,tagline:!1},...me==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ne,B)=>{if(Qe()){await B.reject();return}fn();let Y=Et.current,P={};if(Y)try{let we=await Y("paypal");if(Qe()){await B.reject();return}if(!we.proceed){Kt.current=null,on.current.delete(te),await B.reject();return}P={sessionId:we.sessionId,accountPatch:we.accountPatch,nonce:we.nonce}}catch(we){Ee(`onClick:runBeforeButtonClick rejected msg=${(we instanceof Error?we.message:String(we)).slice(0,120)}`),Kt.current=null,on.current.delete(te),await B.reject();return}Ft(()=>Nn.current?.("paypal"));let Te=an(),St={generation:Te,surfaceKey:te,...P};Kt.current=St,on.current.set(te,St),pt.current={...I,attempt:Te},await B.resolve(),Z.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Z.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Je.current=Z.startTiming()},createOrder:h==="order"?$("Failed to create PayPal order."):void 0,createSubscription:h==="subscription"?$("Failed to create PayPal subscription."):void 0,createVaultSetupToken:h==="setup_token"?async()=>Ce(await ke("Failed to create PayPal setup token.")):void 0,onApprove:ee,onCancel:()=>{if(Qe())return;let ne=on.current.get(te)??Kt.current;ne&&on.current.delete(ne.surfaceKey),Kt.current=null,Xt("cancelled"),Z.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ke.current=!0,En({generation:ne?.generation,remount:!0,focus:!1})},onError:ne=>{if(Qe()||He.current!==te)return;let B=ne instanceof Error?ne.message:"PayPal failed to render.";if(Ee(`onError rendered=${An} msg=${B.slice(0,120)}`),An){let Y=on.current.get(te)??Kt.current;if(Y&&!zn(Y.generation)||!Y&&mr())return;if(Fr(B)){yt(Y?.generation);return}let{errorCode:P,popupBlocked:Te,providerDeclined:St,terminalReason:we}=La(ne,{inAppBrowser:j.inAppBrowser,handoffObserved:Y!=null&&D.current===Y.generation});if(Te&&O.markBlocked(),Xt(we),St){Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:we}),dt(ne,Y),Ft(()=>kn.current?.(ln("paypal",B))),Y&&on.current.delete(Y.surfaceKey),Kt.current=null,yt(Y?.generation);return}Z.error({errorCode:P,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:we}),Y&&on.current.delete(Y.surfaceKey),Kt.current=null,En({generation:Y?.generation,remount:!0,showRetry:!0,focus:!0}),Dt(ne,{code:"paypal_runtime_failed",popupBlocked:Te,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:me,terminalReason:we});return}S(Fr(B)?"teardown":"pre_ready_callback",B)}}),wt=Be.isEligible();if(Ee(`isEligible=${wt}`),Z.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!wt){V(!1),S("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Mr=!0,Tn=Be,nr=()=>{if(!Yn||At||Qe()||An)return;At=!0,Ee(`container:dims ${In(xn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(gr=new MutationObserver(B=>{if(!Qe()){for(let Y of B)if(Y.type==="childList")Y.addedNodes.forEach(P=>{if(!(P instanceof Element))return;let Te=P.tagName.toLowerCase(),St=(P.getAttribute("title")??"").slice(0,40),we=Te==="iframe"?` ${Pr(P)}`:"";Ee(`child+ ${Te}${St?` title="${St}"`:""}${we} dims=${In(P)}`)});else if(Y.type==="attributes"&&Y.target instanceof Element){let P=Y.target;if(P.tagName.toLowerCase()!=="iframe")continue;let Te=Y.attributeName;(Te==="src"||Te==="srcdoc")&&Ee(`attr~ iframe ${Te}=${Te==="srcdoc"?`[${(P.getAttribute("srcdoc")??"").length}ch]`:Jn(P.getAttribute("src"))} dims=${In(P)}`)}}}),gr.observe(xn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ne=B=>{if(Qe()||An)return;let Y=xn.querySelectorAll("iframe"),P=typeof document<"u"&&"hasStorageAccess"in document;Ee(`watchdog:${B} container=${In(xn)} children=${xn.childElementCount} iframes=${Y.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${P} paypalNetRequests=${Un.value}`),Y.forEach((Te,St)=>{let we=(Te.getAttribute("title")??"").slice(0,40);Ee(` iframe[${St}] ${In(Te)}${we?` title="${we}"`:""} ${Pr(Te)}`);let Cn=st(Te);Cn&&Ee(` ${Cn}`)}),nn.length===0&&Ee(" (no PayPal/zoid window errors captured)")};tr.push(setTimeout(()=>ne("3s"),3e3)),tr.push(setTimeout(()=>ne("8s"),8e3)),tr.push(setTimeout(()=>ne("15s"),15e3))},nr(),Ee("render:start");let de=Z.startTiming();Gn=setTimeout(()=>{Qe()||An||(Ee("watchdog:11s retryable render timeout"),S("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Td);let Tt=Be.render(xn);(async()=>{try{if(await Tt,Ee(`render:resolved inactive=${Qe()}`),gn(),Qe()){fr();return}An=!0,V(!0),nt(!1),fe.current?.("ready"),Z.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),Z.performance({stage:"checkout_render",durationMs:Z.elapsed(de),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ne){let B=ne instanceof Error?ne.message:"PayPal failed to render.";Ee(`render:rejected msg=${B.slice(0,120)}`),gn(),S(Fr(B)?"teardown":"render_rejected",B)}})()}).catch(x=>{let ee=x instanceof Error?x.message:"PayPal operation failed.";Ee(`provider:failed msg=${ee.slice(0,120)}`);let $="script_rejected";_&&Fr(ee)?$="teardown":_&&Mr&&($="render_rejected"),S($,ee)})},0);return()=>{Ht=!0,clearTimeout(z),Ar&&clearTimeout(Ar),gn(),Pn.current===ar&&(Pn.current=null),fr(),Je.current=null,pt.current=null}},[K,c,s,m,l,h,me,rt,e,Ye,_e,he,L,Ue,Ee,Xt]);let X=pe?Ui("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:lt?"#fef2f2":"#f3f4f6",border:`1px solid ${lt?"#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=${Ve} failed=${lt})`,Ze.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${pt.join(`
4
- `)}`]}):null;return xe&&!N?$e?Wr("div",{children:se}):null:bi("div",{children:[se,Ee&&Wr(yo,{identity:Ee.identity,methodLabel:Ee.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:dn,onCancel:()=>dn(null)}),bi("div",{"aria-hidden":ut||Ee?!0:void 0,style:ut||Ee?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ia},children:[!de&&!ut&&Wr("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"}}),Wr("div",{ref:Ie,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ia,display:"flex",opacity:de?1:0},"aria-busy":qe||Pe},x)]},x),re&&Wr("button",{ref:U,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Sn,style:Zc,children:"Try PayPal again"})]})}function ka(e){return Wr(ol,{...e})}function al(e){return Wr(ol,{...e})}import{jsx as il,jsxs as sd}from"react/jsx-runtime";function ho({children:e,margin:t,icon:n=!0,styleOverride:r}){return sd("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&&il("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:il("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 ld,resolveSessionCurrency as cd}from"@flopay/shared";function vo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Si=":idempotency-key";function wi(e,t){if(!vo())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 Ii(e,t){if(!vo())return null;try{let n=window.sessionStorage.getItem(e+Si);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 _a(e,t){if(vo())try{wi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Ra(e,t){if(_a(e,t),!!vo())try{Ii(e,t)&&window.sessionStorage.removeItem(e+Si)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ea(e,t,n,r){if(vo())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 Ta(e,t,n){if(vo())try{window.sessionStorage.setItem(e+Si,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 dd(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([s],[l])=>s<l?-1:s>l?1:0)),n=1779033703,r=3144134277,o=1013904242,i=2773480762;for(let s=0;s<t.length;s++){let l=t.charCodeAt(s);n=r^Math.imul(n^l,597399067),r=o^Math.imul(r^l,2869860233),o=i^Math.imul(o^l,951274213),i=n^Math.imul(i^l,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(s=>(s>>>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=>Ci(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Ci(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Ci(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:dd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function sl(e,t=!1){let n=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 ll(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=cd(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??ld(t.items,t.subscriptions)).map(f=>({type:f.type,code:f.code??f.providerItemId??f.providerPlanId??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??o).toUpperCase()})).sort((f,C)=>`${f.code}:${f.type??""}`.localeCompare(`${C.code}:${C.type??""}`)),s=e.products.map(f=>({type:f.type,code:f.code??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??e.currency).toUpperCase()})).sort((f,C)=>`${f.code}:${f.type??""}`.localeCompare(`${C.code}:${C.type??""}`));if(i.length!==s.length)return!1;for(let[f,C]of i.entries()){let h=s[f];if(h===void 0||C.code!==h.code||C.type!==void 0&&C.type!==h.type||C.quantity!==h.quantity||C.totalAmount!==h.totalAmount||C.overrideAmount!==h.overrideAmount||C.currency!==h.currency)return!1}let l=[...t.couponCodes??[]].sort(),p=[...e.coupons??[]].sort();return l.length===p.length&&l.every((f,C)=>f===p[C])}import{resolveBillingApiUrl as ud}from"@flopay/shared";import{useEffect as Nr,useMemo as pd,useRef as cl,useState as dl}from"react";import{jsx as md}from"react/jsx-runtime";function Aa({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,s]=dl(e instanceof Promise?null:e),[l,p]=dl(t instanceof Promise||!t?null:t),f=cl(null),C=cl(null),h=go(r);Nr(()=>{h({class:"lifecycle",name:"checkout.mount"})},[h]),Nr(()=>{i&&h({class:"lifecycle",name:"sdk.initialize.ready"})},[h,i]),Nr(()=>{if(i)return Qt(i)?.subscribe?.(h)},[h,i]),Nr(()=>{if(!(!l||l===i))return Qt(l)?.subscribe?.(h)},[h,i,l]),Nr(()=>{if(!i)return;let _=Qt(i);return f.current=_?.beginCheckout()??_?.now()??0,_?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{_?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Nr(()=>{let _=!1;return e instanceof Promise?e.then(ae=>{_||s(ae)},()=>{_||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{_=!0}},[h,e]),Nr(()=>{let _=!1;if(!t){p(null);return}return t instanceof Promise?t.then(ae=>{_||p(ae)},()=>{_||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{_=!0}},[h,t]),Nr(()=>{if(!i||C.current===i)return;C.current=i;let _=Qt(i);_?.log({name:"checkout.rendered",stage:"checkout_render"}),h({class:"lifecycle",name:"checkout.rendered"}),_?.performance({stage:"checkout_render",durationMs:_.elapsed(f.current??0),durationMode:"machine"})},[h,i]);let m=ud(n?.billingApiUrl),w=pd(()=>({flopay:i,paypalFlopay:l,billingApiUrl:m,emitInstrument:h}),[i,l,m,h]);return md(er.Provider,{value:w,children:o})}var xa="flopay_recent_completion_";function bo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(xa+e,JSON.stringify(t))}catch{}}function ki(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(xa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(xa+e),!1):!0}catch{return!1}}async function Ma(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{loadFloPay as ul,PaymentAPI as Ri}from"@flopay/js";import{classifyPaymentRejection as yd,FloPayError as Pt,isAuthorizationOnlySession as fd,isSetupIntentClientSecret as gd,normalizeCheckoutFailureOutcome as pl}from"@flopay/shared";var Xo="card",hd=1e3,yl=3e5;async function vd(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,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 Pd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:s??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 Zo(e){return new Pt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Ei(e,t){return Object.assign(e,{checkoutMethod:t})}function _r(e,t){let n=e instanceof Pt?e:new Pt(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 _r(n,t)}}function fl(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 bd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function Ti(e){if(typeof document>"u"||typeof window>"u")throw new Pt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Pt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let h=new AbortController,m=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",m);let w=window.setTimeout(()=>h.abort(),n);try{let _=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!_.ok)return{status:"unknown"};let ae=await _.json().catch(()=>null);return Cd(ae)}catch{return{status:"unknown"}}finally{window.clearTimeout(w),e.signal?.removeEventListener("abort",m)}},i,s=()=>e.pollCompletionEndpoint!==!1?o():(i??(i=o()),i),l=document.activeElement instanceof HTMLElement?document.activeElement:null,p=document.createElement("div");p.setAttribute("data-flopay-auto-3ds-overlay","1"),p.setAttribute("role","dialog"),p.setAttribute("aria-modal","true"),p.setAttribute("aria-label","Card authentication"),p.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 f=document.createElement("iframe");f.setAttribute("title","Card authentication"),f.setAttribute("allow","payment"),f.tabIndex=0,f.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(";");let C=null;try{C=new URL(e.billingApiUrl,window.location.href).origin}catch{C=null}try{let h=await new Promise((m,w)=>{let _=!1,ae=0,Y=0,Pe=0,S=!1,G=()=>{window.clearTimeout(ae),window.clearInterval(Y),window.clearTimeout(Pe),window.removeEventListener("message",Fe),f.removeEventListener("load",ce),e.signal?.removeEventListener("abort",Te)},X=async()=>{if(!(_||S)){S=!0;try{let ve=await s();if(_||!bd(ve))return;_=!0,G(),m(ve)}finally{S=!1}}},ce=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(Pe),Pe=window.setTimeout(()=>{X()},250))},Te=()=>{_||(_=!0,G(),w(new Pt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Fe=ve=>{if(ve.source!==f.contentWindow||C&&ve.origin!==C)return;let Ue=ve.data;!Ue||typeof Ue!="object"||Ue.source!=="flopay-vault-3ds-return"||_||(_=!0,G(),m(null))};ae=window.setTimeout(()=>{_||(_=!0,G(),w(new Pt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},yl),e.pollCompletionEndpoint!==!1&&(Y=window.setInterval(()=>{X()},t)),f.addEventListener("load",ce),window.addEventListener("message",Fe),e.signal?.addEventListener("abort",Te),f.src=e.nextActionRedirectUrl,p.appendChild(f),document.body.appendChild(p),f.focus(),e.signal?.aborted&&Te()});return h||await s()}finally{p.parentNode?.removeChild(p),l?.isConnected&&l.focus()}}async function Co(e,t){let n=t.nonce??t.session.clientSecret,r=new Ri(t.billingApiUrl,{telemetry:!1}),o=new AbortController,i=new AbortController,s=()=>{o.abort(t.signal.reason),i.abort(t.signal.reason)};t.signal.aborted?s():t.signal.addEventListener("abort",s,{once:!0});let l=Ti({billingApiUrl:t.billingApiUrl,sessionId:t.sessionId,nonce:n,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1}),p=null,f=()=>(p??(p=r.waitForCheckoutSessionCompletion(t.sessionId,{initialDelayMs:hd,nonce:n,statusUrl:`${t.billingApiUrl.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/status`,continueAfterActionRequired:!0,timeoutMs:yl,signal:i.signal})),p),C=f(),h;try{let w=await Promise.race([l.then(_=>({kind:"challenge",outcome:_})),C.then(_=>({kind:"status",session:_}))]);if(w.kind==="status")o.abort(),h=w.session;else{if(w.outcome.status==="declined")throw gr({type:w.outcome.declineReason??"authorization_declined",message:"Card was declined.",gatewayErrorCode:w.outcome.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});h=await f()}}catch(w){throw t.signal.aborted||w instanceof Error&&w.name==="AbortError"?Zo(w):w}finally{t.signal.removeEventListener("abort",s),o.abort(),i.abort()}let m=h.data.session;if(!Mr(m))throw po(m);return{...Sr(m,t.sessionId),checkoutMethod:"card"}}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"authorized":return{status:"authorized",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 gr(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=xr(o)??o,s=Ei(new Pt(i,"api_error",{code:e?.code??pl(e?.outcome)??pl(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(s.orderId=e.orderId),s}function _i(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ba(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function gl(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Ba(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 l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||Ba(l)))return l;let s=o.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let p=l,f=[p.stripeClientSecret,p.clientSecret];for(let C of f)if(typeof C=="string"&&C.length>0&&(!t?.requirePaymentIntentClientSecret||Ba(C)))return C}}}}async function Sd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=gl(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let l=(await new Ri(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ba(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function So({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),p=t??n.id,f=r??n.clientSecret,C=n.customer?.id??n.accountData?.userId??"",h=n.customer?.email??n.accountData?.email??"",m=n.customer?.firstName??n.accountData?.firstName??"",w=n.customer?.lastName??n.accountData?.lastName??"",_=n.customer?.country??n.accountData?.country??void 0,ae=n.customer?.zip??n.accountData?.zip??void 0,Pe=await new Ri(l,s===!1?{telemetry:!1}:void 0).processPayment(C,{sessionId:p,nonce:f,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:C,email:h,firstName:m,lastName:w,country:_,zip:ae},returnUrl:i??_i(n)});if(Pe.ok){let X=typeof Pe.json=="function"?await Pe.json().catch(()=>null):null;if(fd(n)||X?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof X?.paymentId=="string"?X.paymentId:n.paymentId,sessionId:typeof X?.sessionId=="string"?X.sessionId:p,authorizationExpiresAt:typeof X?.authorizationExpiresAt=="string"?X.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Ko(o),checkoutMethod:ml(o,n)}};let ce=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ce?{paymentIntentId:ce}:{},paymentMethodId:Ko(o),checkoutMethod:ml(o,n)}}}let S;try{S=await Pe.json()}catch(X){throw new Pt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:Pe.status,cause:X})}if(S?.type==="3ds_required"&&typeof S.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:S.nextActionRedirectUrl};if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let X=gl(S);if(!X)throw new Pt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:Pe.status});return{type:S.type,threeDSecureToken:X,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let X=await Sd({billingApiUrl:l,sessionId:p,nonce:f,responseJson:S});if(X)return X;throw Ei(new Pt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let G=new Pt(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:Pe.status});throw Object.assign(G,{telemetryOutcome:yd(Pe.status,S)})}async function Fa(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:p,signal:f}){let C=t?.getRawProvider();if(!C)throw _r(new Pt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Ei(new Pt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=gd(e.threeDSecureToken),m=null,w=e.paymentMethodId,_=await Jo(()=>vd(C,e.threeDSecureToken,h),"card");if(_){if(_.error)throw _r(new Pt(_.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let Y=_.intent;!w&&Y?.payment_method&&(typeof Y.payment_method=="string"?w=Y.payment_method:"id"in Y.payment_method&&(w=Y.payment_method.id??void 0))}let ae=w?await Jo(()=>Pd(C,e.threeDSecureToken,{payment_method:w,return_url:l??_i(s)??window.location.href},h),"card"):null;if(ae){if(ae.error)throw _r(new Pt(ae.error.message??"3DS authentication failed.","api_error",{code:ae.error.code}),"card");m=ae.intent}else{let Y=await Jo(()=>C.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(Y.error)throw _r(new Pt(Y.error.message??"3DS authentication failed.","api_error",{code:Y.error.code}),"card");m=(h?Y.setupIntent:Y.paymentIntent)??null}if(m&&(m.status==="requires_capture"||m.status==="succeeded"||m.status==="processing")){let Y=await So({billingApiUrl:o,sessionId:i,session:s,telemetry:p,tokenizedData:{id:m.id,type:"card",threeDSecureActionResultTokenId:m.id},returnUrl:l});return Y.type==="success"?{...Y.result,paymentIntentId:Y.result.paymentIntentId??m.id,paymentMethodId:Y.result.paymentMethodId??w}:Y.type==="next_action_required"?Co(Y,{billingApiUrl:o,sessionId:i??s.id,session:s,signal:f}):Fa(Y,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:p,signal:f})}throw _r(new Pt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw _r(new Pt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:w}=await Jo(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(w)throw _r(new Pt(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:m}=await Jo(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??_i(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(m)throw _r(new Pt(m.message??"PayPal authorization failed.","api_error",{code:m.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Pt("Unsupported payment redirect state.","api_error")}function Qo(e){if(e instanceof Pt){let r=xr(e.message);return r&&r!==e.message?Object.assign(new Pt(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=xr(t)??t;return new Pt(n,"api_error")}function Ai(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Ar(e.data.session);if(!t&&!n&&!r)throw new Pt("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 ml(e,t){return e?e.isPaypal?"paypal":"card":t&&Ar(t)?"card":void 0}async function xi({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,[s,l]=await Promise.all([ul(e,{billingApiUrl:n,locale:r,telemetry:o}),i?ul(i,{billingApiUrl:n,locale:r,telemetry:o}).catch(f=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",f),null)):Promise.resolve(null)]);if(!s)throw new Pt("The payment provider did not initialize.","authentication_error");let p=null;return i?p=l:t&&(p=s),{flopay:s,paypalFlopay:p}}import{PaymentAPI as wo,PciVaultCardCapture as wd,toStripeAppearance as Id}from"@flopay/js";import{COUNTRY_OPTIONS as kd,classifyPaymentRejection as _d,FloPayError as dr,filterStripeMethodsByCountry as Rd,getPostalCodeExample as Ed,getPostalCodeLabel as qi,getStateFromPostalCode as vl,getStateLabel as Mi,getStateOptions as Td,getStripeMethodDisplayName as Jr,hasVendoredStripeMethodLogo as Ad,isAuthorizationOnlySession as Bi,isAVSFieldVisible as rt,isPostalCodeSupported as xd,isSetupIntentClientSecret as Fi,isValidEmail as cn,isValidPostalCode as Md,needsStripeMethodExplicitConfirm as Pl,normalizeCheckoutFailureOutcome as Bd,partitionStripeMethods as Fd,randomUuidV4 as Dd,resolveAVSConfig as Nd,resolveButtonsLayoutTheme as Ld,resolveStripeMethodBrandVariant as Od,resolveTheme as zd,stripeExpressMethodToOptionKey as bl}from"@flopay/shared";import{ExpressCheckoutElement as Bl,PaymentElement as Ud,Elements as Gr,useElements as Vi,useStripe as Hi}from"@stripe/react-stripe-js";import qd,{useCallback as Ze,useContext as Io,useEffect as gt,useMemo as Ft,useRef as me,useState as le}from"react";var hl={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 Yr,jsx as c,jsxs as ze}from"react/jsx-runtime";var hr="flopay_stripe_resume",Cl="flopay_wallet_resume",Fl="fw1",jd="fw2",Dl=300*1e3,$d=900,Kd=25e3,Vd=25e3,Hd=1e4,Di={},Ni={};function Wi(e){return`${jd}:${e}`}function Da(e){if(typeof window>"u")return!1;try{return localStorage.removeItem(Wi(e)),!0}catch{return!1}}function Na(e,t){if(typeof window>"u")return null;let n=Wi(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>Dl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Da(e),null):o}catch{return Da(e),null}}function Wd(e){if(typeof window>"u")return!1;try{return localStorage.setItem(Wi(e.sessionId),JSON.stringify(e)),!0}catch{return!1}}function Sl(e,t,n){let r=Na(e,t);return!r||r.clientSecret!==n?!1:Da(e)}function Li(e,t,n){if(typeof window>"u")return;Na(e,t)?.clientSecret===n&&Da(e)}function Gd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Oi(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":$o(e.status),o=Gd(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function wl(e,t,n){let r=null;try{return await Promise.race([Js(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},Hd),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Yd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Nl(e){return e instanceof dr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Oa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new wo(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Nl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ea="flopay_paypal_resume",Jd=250,Il="Just a moment \u2014 we are finalizing your order. Please press pay again.",Xd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Gi(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function za({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new wo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Zd(e){return e instanceof dr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function zi(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Ll({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=Vr(n),s=i.firstName?i:Vr(r?.name);return Bn({email:cn(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Qd({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let s=Ll({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return cn(s.email)?s:i(o,s)}var eu=`
3
+ ${Ze.join(`
4
+ `)}`]}):null;return lt&&!ct?pe?to("div",{children:X}):null:Ui("div",{children:[X,Me&&to(So,{identity:Me.identity,methodLabel:Me.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:ze,onCancel:()=>ze(null)}),Ui("div",{"aria-hidden":tt||Me?!0:void 0,style:tt||Me?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ka},children:[!Ve&&!tt&&to("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"}}),to("div",{ref:le,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ka,display:"flex",opacity:Ve?1:0},"aria-busy":T||ue},_e)]},_e),ft&&to("button",{ref:$e,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:pn,style:Ad,children:"Try PayPal again"})]})}function Va(e){return to(Bl,{...e})}function Fl(e){return to(Bl,{...e})}import{jsx as Dl,jsxs as Dd}from"react/jsx-runtime";function _o({children:e,margin:t,icon:n=!0,styleOverride:r}){return Dd("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&&Dl("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Dl("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 Od,resolveSessionCurrency as Nd}from"@flopay/shared";function Ro(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var ji=":idempotency-key";function $i(e,t){if(!Ro())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 Ki(e,t){if(!Ro())return null;try{let n=window.sessionStorage.getItem(e+ji);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function Ha(e,t){if(Ro())try{$i(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Wa(e,t){if(Ha(e,t),!!Ro())try{Ki(e,t)&&window.sessionStorage.removeItem(e+ji)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ga(e,t,n,r){if(Ro())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 Ya(e,t,n){if(Ro())try{window.sessionStorage.setItem(e+ji,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function qi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Ld(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([s],[l])=>s<l?-1:s>l?1:0)),n=1779033703,r=3144134277,o=1013904242,i=2773480762;for(let s=0;s<t.length;s++){let l=t.charCodeAt(s);n=r^Math.imul(n^l,597399067),r=o^Math.imul(r^l,2869860233),o=i^Math.imul(o^l,951274213),i=n^Math.imul(i^l,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(s=>(s>>>0).toString(16).padStart(8,"0")).join("")}function Eo(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=>qi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>qi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>qi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Ld(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Ol(e,t=!1){let n=Eo(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 Nl(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=Nd(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??Od(t.items,t.subscriptions)).map(y=>({type:y.type,code:y.code??y.providerItemId??y.providerPlanId??"",quantity:y.quantity??1,totalAmount:y.totalAmount,overrideAmount:y.overrideAmount??null,currency:(y.currency??o).toUpperCase()})).sort((y,b)=>`${y.code}:${y.type??""}`.localeCompare(`${b.code}:${b.type??""}`)),s=e.products.map(y=>({type:y.type,code:y.code??"",quantity:y.quantity??1,totalAmount:y.totalAmount,overrideAmount:y.overrideAmount??null,currency:(y.currency??e.currency).toUpperCase()})).sort((y,b)=>`${y.code}:${y.type??""}`.localeCompare(`${b.code}:${b.type??""}`));if(i.length!==s.length)return!1;for(let[y,b]of i.entries()){let g=s[y];if(g===void 0||b.code!==g.code||b.type!==void 0&&b.type!==g.type||b.quantity!==g.quantity||b.totalAmount!==g.totalAmount||b.overrideAmount!==g.overrideAmount||b.currency!==g.currency)return!1}let l=[...t.couponCodes??[]].sort(),m=[...e.coupons??[]].sort();return l.length===m.length&&l.every((y,b)=>y===m[b])}import{resolveBillingApiUrl as zd}from"@flopay/shared";import{useEffect as Wr,useMemo as Ud,useRef as Ll,useState as zl}from"react";import{jsx as qd}from"react/jsx-runtime";function Ja({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,s]=zl(e instanceof Promise?null:e),[l,m]=zl(t instanceof Promise||!t?null:t),y=Ll(null),b=Ll(null),g=Io(r);Wr(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),Wr(()=>{i&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,i]),Wr(()=>{if(i)return cn(i)?.subscribe?.(g)},[g,i]),Wr(()=>{if(!(!l||l===i))return cn(l)?.subscribe?.(g)},[g,i,l]),Wr(()=>{if(!i)return;let w=cn(i);return y.current=w?.beginCheckout()??w?.now()??0,w?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{w?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Wr(()=>{let w=!1;return e instanceof Promise?e.then(v=>{w||s(v)},()=>{w||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{w=!0}},[g,e]),Wr(()=>{let w=!1;if(!t){m(null);return}return t instanceof Promise?t.then(v=>{w||m(v)},()=>{w||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{w=!0}},[g,t]),Wr(()=>{if(!i||b.current===i)return;b.current=i;let w=cn(i);w?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),w?.performance({stage:"checkout_render",durationMs:w.elapsed(y.current??0),durationMode:"machine"})},[g,i]);let F=zd(n?.billingApiUrl),M=Ud(()=>({flopay:i,paypalFlopay:l,billingApiUrl:F,emitInstrument:g}),[i,l,F,g]);return qd(Qn.Provider,{value:M,children:o})}var Xa="flopay_recent_completion_";function To(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Xa+e,JSON.stringify(t))}catch{}}function Vi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Xa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Xa+e),!1):!0}catch{return!1}}async function Za(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{loadFloPay as Ul,PaymentAPI as Wi}from"@flopay/js";import{classifyPaymentRejection as jd,FloPayError as kt,isAuthorizationOnlySession as $d,isSetupIntentClientSecret as Kd,normalizeCheckoutFailureOutcome as ql}from"@flopay/shared";var pa="card",Vd=1e3,$l=3e5;async function Hd(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,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 Wd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:s??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 ya(e){return new kt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Gi(e,t){return Object.assign(e,{checkoutMethod:t})}function Or(e,t){let n=e instanceof kt?e:new kt(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 ua(e,t){try{return await e()}catch(n){throw Or(n,t)}}function Kl(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 Gd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function Yi(e){if(typeof document>"u"||typeof window>"u")throw new kt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new kt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let g=new AbortController,F=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",F);let M=window.setTimeout(()=>g.abort(),n);try{let w=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!w.ok)return{status:"unknown"};let v=await w.json().catch(()=>null);return Yd(v)}catch{return{status:"unknown"}}finally{window.clearTimeout(M),e.signal?.removeEventListener("abort",F)}},i,s=()=>e.pollCompletionEndpoint!==!1?o():(i??(i=o()),i),l=document.activeElement instanceof HTMLElement?document.activeElement:null,m=document.createElement("div");m.setAttribute("data-flopay-auto-3ds-overlay","1"),m.setAttribute("role","dialog"),m.setAttribute("aria-modal","true"),m.setAttribute("aria-label","Card authentication"),m.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 y=document.createElement("iframe");y.setAttribute("title","Card authentication"),y.setAttribute("allow","payment"),y.tabIndex=0,y.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(";");let b=null;try{b=new URL(e.billingApiUrl,window.location.href).origin}catch{b=null}try{let g=await new Promise((F,M)=>{let w=!1,v=0,U=0,ue=0,E=!1,J=()=>{window.clearTimeout(v),window.clearInterval(U),window.clearTimeout(ue),window.removeEventListener("message",xe),y.removeEventListener("load",se),e.signal?.removeEventListener("abort",G)},K=async()=>{if(!(w||E)){E=!0;try{let Ye=await s();if(w||!Gd(Ye))return;w=!0,J(),F(Ye)}finally{E=!1}}},se=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(ue),ue=window.setTimeout(()=>{K()},250))},G=()=>{w||(w=!0,J(),M(new kt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},xe=Ye=>{if(Ye.source!==y.contentWindow||b&&Ye.origin!==b)return;let be=Ye.data;!be||typeof be!="object"||be.source!=="flopay-vault-3ds-return"||w||(w=!0,J(),F(null))};v=window.setTimeout(()=>{w||(w=!0,J(),M(new kt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},$l),e.pollCompletionEndpoint!==!1&&(U=window.setInterval(()=>{K()},t)),y.addEventListener("load",se),window.addEventListener("message",xe),e.signal?.addEventListener("abort",G),y.src=e.nextActionRedirectUrl,m.appendChild(y),document.body.appendChild(m),y.focus(),e.signal?.aborted&&G()});return g||await s()}finally{m.parentNode?.removeChild(m),l?.isConnected&&l.focus()}}async function Ao(e,t){let n=t.nonce??t.session.clientSecret,r=new Wi(t.billingApiUrl,{telemetry:!1}),o=new AbortController,i=new AbortController,s=()=>{o.abort(t.signal.reason),i.abort(t.signal.reason)};t.signal.aborted?s():t.signal.addEventListener("abort",s,{once:!0});let l=Yi({billingApiUrl:t.billingApiUrl,sessionId:t.sessionId,nonce:n,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1}),m=null,y=()=>(m??(m=r.waitForCheckoutSessionCompletion(t.sessionId,{initialDelayMs:Vd,nonce:n,statusUrl:`${t.billingApiUrl.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/status`,continueAfterActionRequired:!0,timeoutMs:$l,signal:i.signal})),m),b=y(),g;try{let M=await Promise.race([l.then(w=>({kind:"challenge",outcome:w})),b.then(w=>({kind:"status",session:w}))]);if(M.kind==="status")o.abort(),g=M.session;else{if(M.outcome.status==="declined")throw Rr({type:M.outcome.declineReason??"authorization_declined",message:"Card was declined.",gatewayErrorCode:M.outcome.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});g=await y()}}catch(M){throw t.signal.aborted||M instanceof Error&&M.name==="AbortError"?ya(M):M}finally{t.signal.removeEventListener("abort",s),o.abort(),i.abort()}let F=g.data.session;if(!jr(F))throw Co(F);return{...Dr(F,t.sessionId),checkoutMethod:"card"}}function Yd(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"authorized":return{status:"authorized",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 Rr(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=qr(o)??o,s=Gi(new kt(i,"api_error",{code:e?.code??ql(e?.outcome)??ql(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(s.orderId=e.orderId),s}function Hi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Qa(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Vl(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Qa(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 l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||Qa(l)))return l;let s=o.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let m=l,y=[m.stripeClientSecret,m.clientSecret];for(let b of y)if(typeof b=="string"&&b.length>0&&(!t?.requirePaymentIntentClientSecret||Qa(b)))return b}}}}async function Jd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Vl(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let l=(await new Wi(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Qa(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function xo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),m=t??n.id,y=r??n.clientSecret,b=n.customer?.id??n.accountData?.userId??"",g=n.customer?.email??n.accountData?.email??"",F=n.customer?.firstName??n.accountData?.firstName??"",M=n.customer?.lastName??n.accountData?.lastName??"",w=n.customer?.country??n.accountData?.country??void 0,v=n.customer?.zip??n.accountData?.zip??void 0,ue=await new Wi(l,s===!1?{telemetry:!1}:void 0).processPayment(b,{sessionId:m,nonce:y,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:b,email:g,firstName:F,lastName:M,country:w,zip:v},returnUrl:i??Hi(n)});if(ue.ok){let K=typeof ue.json=="function"?await ue.json().catch(()=>null):null;if($d(n)||K?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof K?.paymentId=="string"?K.paymentId:n.paymentId,sessionId:typeof K?.sessionId=="string"?K.sessionId:m,authorizationExpiresAt:typeof K?.authorizationExpiresAt=="string"?K.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:na(o),checkoutMethod:jl(o,n)}};let se=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...se?{paymentIntentId:se}:{},paymentMethodId:na(o),checkoutMethod:jl(o,n)}}}let E;try{E=await ue.json()}catch(K){throw new kt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:ue.status,cause:K})}if(E?.type==="3ds_required"&&typeof E.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:E.nextActionRedirectUrl};if(E?.type==="paypal_redirect_required"||E?.type==="3ds_required"){let K=Vl(E);if(!K)throw new kt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:ue.status});return{type:E.type,threeDSecureToken:K,paymentMethodId:E.paymentMethodId}}if(E?.gatewayErrorCode==="authentication_required"){let K=await Jd({billingApiUrl:l,sessionId:m,nonce:y,responseJson:E});if(K)return K;throw Gi(new kt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let J=new kt(E?.message??"Payment failed. Please try again.","api_error",{code:E?.code??E?.gatewayErrorCode,declineCode:E?.declineCode??E?.gatewayDeclineReason,statusCode:ue.status});throw Object.assign(J,{telemetryOutcome:jd(ue.status,E)})}async function ei(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:m,signal:y}){let b=t?.getRawProvider();if(!b)throw Or(new kt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Gi(new kt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Kd(e.threeDSecureToken),F=null,M=e.paymentMethodId,w=await ua(()=>Hd(b,e.threeDSecureToken,g),"card");if(w){if(w.error)throw Or(new kt(w.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:w.error.code}),"card");let U=w.intent;!M&&U?.payment_method&&(typeof U.payment_method=="string"?M=U.payment_method:"id"in U.payment_method&&(M=U.payment_method.id??void 0))}let v=M?await ua(()=>Wd(b,e.threeDSecureToken,{payment_method:M,return_url:l??Hi(s)??window.location.href},g),"card"):null;if(v){if(v.error)throw Or(new kt(v.error.message??"3DS authentication failed.","api_error",{code:v.error.code}),"card");F=v.intent}else{let U=await ua(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(U.error)throw Or(new kt(U.error.message??"3DS authentication failed.","api_error",{code:U.error.code}),"card");F=(g?U.setupIntent:U.paymentIntent)??null}if(F&&(F.status==="requires_capture"||F.status==="succeeded"||F.status==="processing")){let U=await xo({billingApiUrl:o,sessionId:i,session:s,telemetry:m,tokenizedData:{id:F.id,type:"card",threeDSecureActionResultTokenId:F.id},returnUrl:l});return U.type==="success"?{...U.result,paymentIntentId:U.result.paymentIntentId??F.id,paymentMethodId:U.result.paymentMethodId??M}:U.type==="next_action_required"?Ao(U,{billingApiUrl:o,sessionId:i??s.id,session:s,signal:y}):ei(U,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:m,signal:y})}throw Or(new kt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw Or(new kt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:M}=await ua(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(M)throw Or(new kt(M.message??"PayPal authorization failed.","api_error",{code:M.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:F}=await ua(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??Hi(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(F)throw Or(new kt(F.message??"PayPal authorization failed.","api_error",{code:F.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new kt("Unsupported payment redirect state.","api_error")}function ma(e){if(e instanceof kt){let r=qr(e.message);return r&&r!==e.message?Object.assign(new kt(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=qr(t)??t;return new kt(n,"api_error")}function Ji(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Ur(e.data.session);if(!t&&!n&&!r)throw new kt("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 jl(e,t){return e?e.isPaypal?"paypal":"card":t&&Ur(t)?"card":void 0}async function Xi({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,[s,l]=await Promise.all([Ul(e,{billingApiUrl:n,locale:r,telemetry:o}),i?Ul(i,{billingApiUrl:n,locale:r,telemetry:o}).catch(y=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",y),null)):Promise.resolve(null)]);if(!s)throw new kt("The payment provider did not initialize.","authentication_error");let m=null;return i?m=l:t&&(m=s),{flopay:s,paypalFlopay:m}}import{PaymentAPI as Bo,PciVaultCardCapture as Xd,toStripeAppearance as Zd}from"@flopay/js";import{COUNTRY_OPTIONS as Qd,classifyPaymentRejection as eu,FloPayError as pr,filterStripeMethodsByCountry as tu,getPostalCodeExample as nu,getPostalCodeLabel as is,getStateFromPostalCode as Wl,getStateLabel as Zi,getStateOptions as ru,getStripeMethodDisplayName as oo,hasVendoredStripeMethodLogo as ou,isAuthorizationOnlySession as Qi,isAVSFieldVisible as at,isPostalCodeSupported as au,isSetupIntentClientSecret as es,isValidEmail as hn,isValidPostalCode as iu,needsStripeMethodExplicitConfirm as Gl,normalizeCheckoutFailureOutcome as su,partitionStripeMethods as lu,randomUuidV4 as cu,resolveAVSConfig as du,resolveButtonsLayoutTheme as uu,resolveStripeMethodBrandVariant as pu,resolveTheme as yu,stripeExpressMethodToOptionKey as Yl}from"@flopay/shared";import{ExpressCheckoutElement as lc,PaymentElement as mu,Elements as no,useElements as ds,useStripe as us}from"@stripe/react-stripe-js";import fu,{useCallback as Ge,useContext as Fo,useEffect as bt,useMemo as vt,useRef as re,useState as ae}from"react";function Mo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ti(e,t){if(e)return{error:n=>e.error(Mo(t,n)),log:n=>e.log(Mo(t,n)),performance:n=>e.performance(Mo(t,n)),terminal:n=>e.terminal(Mo(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}var Hl={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 ro,jsx as u,jsxs as Fe}from"react/jsx-runtime";var Er="flopay_stripe_resume",Jl="flopay_wallet_resume",cc="fw1",gu="fw2",dc=300*1e3,hu=900,Pu=25e3,vu=25e3,bu=1e4,uc=["payment_intent","payment_intent_client_secret","redirect_status"],ur={provider:"paypal",paymentMethodCategory:"paypal"},ni={},ts={};function Ut(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function ps(e){return`${gu}:${e}`}function ri(e){return Ut(ps(e))}function oi(e,t){if(typeof window>"u")return null;let n=ps(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>dc||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(ri(e),null):o}catch{return ri(e),null}}function Cu(e){return Ut(ps(e.sessionId),e)}function Xl(e,t,n){let r=oi(e,t);return!r||r.clientSecret!==n?!1:ri(e)}function ns(e,t,n){if(typeof window>"u")return;oi(e,t)?.clientSecret===n&&ri(e)}function wu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function rs(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":ta(e.status),o=wu(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function Zl(e,t,n){let r=null;try{return await Promise.race([Cl(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},bu),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Su(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function pc(e){return e instanceof pr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ai(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Bo(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw pc(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ga="flopay_paypal_resume",fa=new Map;function yc(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(ga);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function ku(){if(typeof window>"u")return!1;let[e,t]=ys();return e?yc(t)!==null:!1}function ys(){let e=new URLSearchParams(window.location.search);return uc.map(t=>e.get(t))}function ms(){let e=new URL(window.location.href);for(let t of uc)e.searchParams.delete(t);return e.toString()}function Iu(){Ut(ga),window.history.replaceState({},"",ms())}var _u=250,Ql="Just a moment \u2014 we are finalizing your order. Please press pay again.",Ru="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function fs(e,t,n,r){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...r?{terminalReason:r}:{}})}async function ii({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Bo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Eu(e){return e instanceof pr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function os(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function mc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=Qr(n),s=i.firstName?i:Qr(r?.name);return Fn({email:hn(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Tu({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let s=mc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return hn(s.email)?s:i(o,s)}var Au=`
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 @@ ${pt.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
- `,La=44,ta=180,kl=`flopay-card-enter ${ta}ms cubic-bezier(0, 0, 0.2, 1) both`,_l=`flopay-card-exit ${ta}ms cubic-bezier(0.4, 0, 0.2, 1) both`,tu=`flopay-buttons-enter ${ta}ms cubic-bezier(0, 0, 0.2, 1) both`,nu=`flopay-buttons-exit ${ta}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function ru(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Yi(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 ou={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function au(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 ji={width:"100%",minHeight:La,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 iu(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Rl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function $i(e){return e==="paypal"?"PayPal":Jr(e)}function su(e,t){let n=`We couldn't open ${$i(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function lu(e){let t=Ed(e);return`Enter a valid ${qi(e)}${t?` (e.g. ${t})`:""}`}function cu(e,t,n){let r=xd(e),o=t.trim(),i=n&&r,s=i&&!o,l=i&&!!o&&!Md(e,o);return{visible:n,supported:r,required:i,empty:s,malformed:l}}function du(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!cn(n);return{required:t,empty:r,malformed:o,value:n}}function El(e,t){return t instanceof dr?t:new dr(t instanceof Error?t.message:`${iu(e)} before-click hook failed.`,"validation_error")}function Ui(){return c("style",{children:eu})}function uu(e){return typeof e=="number"?`${e}px`:e}function Ol(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function zl({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:ze("div",{style:{position:"relative",minHeight:44},children:[c("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"}}),c("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 Tl(e){return e!=="unavailable"&&e!=="load_error"}function Ji(e){return c(mu,{...e})}function Al({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:p,onTechnicalFailure:f,runBeforeButtonClick:C,billingName:h,onBuyerIdentityReady:m,onLoadStateChange:w,placeholderBorderRadius:_}){let ae=Br(),{emitInstrument:Y}=Io(er),Pe=Hi(),S=Vi(),[G,X]=le("loading");gt(()=>{w?.(G)},[G,w]);let[ce,Te]=le(!1),Fe=!cn(n?.trim())||!h?.trim(),{request:ve,collect:Ue,finish:bt}=mo(),ot=me(!1),$e=me(null),De=me(null),[ye,we]=le(0),[Qe,Z]=le(!1),Ie=me(!1),be=me(new Map),{startAttempt:ct,finishAttempt:dt,invalidateAttempt:U,isAttemptInvalidated:V,isAttemptCurrent:de}=Wo((re,Q,L)=>{f?.(re,Q,{...L,popupBlocked:L?.popupBlocked??Ir(Q)}),Z(!0),we(Ae=>Ae+1)});gt(()=>{Qe&&De.current?.focus()},[Qe,ye]);let fe=Ze(()=>{we(re=>re+1)},[]),ut=Ze((re,Q,L)=>{U(L),f?.("paypal",re,{code:Q,popupBlocked:Ir(re)}),Z(!0),fe()},[U,f,fe]),Ne=Ze(()=>{window.setTimeout(()=>{($e.current?.querySelector("iframe")??$e.current)?.focus()},0)},[]);gt(()=>{Ie.current&&(Ie.current=!1,Ne())},[Ne,ye]);let x=Ze(()=>{Z(!1),i?.(null),Ne()},[Ne,i]);gt(()=>{if(!Pe||ot.current)return;let re=new URLSearchParams(window.location.search),Q=re.get("payment_intent"),L=re.get("payment_intent_client_secret"),Ae=re.get("redirect_status");if(!Q||!L)return;ot.current=!0;let xe;try{let qe=localStorage.getItem(ea);if(qe){let ke=JSON.parse(qe);ke.clientSecret===L&&(xe={...ke.accountPatch?{accountPatch:ke.accountPatch}:{},...ke.sessionId?{sessionId:ke.sessionId}:{},...ke.nonce?{nonce:ke.nonce}:{}})}}catch{}try{localStorage.removeItem(ea)}catch{}let Me=new URL(window.location.href);Me.searchParams.delete("payment_intent"),Me.searchParams.delete("payment_intent_client_secret"),Me.searchParams.delete("redirect_status"),window.history.replaceState({},"",Me.toString()),(async()=>{try{if(Te(!0),Ae==="failed"){let Ee="PayPal payment was declined. Please try again.";i?.(Ee),p?.(nn("paypal",Ee));return}let{paymentIntent:qe,error:ke}=await Pe.retrievePaymentIntent(L);if(ke){i?.(ke.message??"Failed to retrieve PayPal payment status.");return}if(qe&&(qe.status==="requires_capture"||qe.status==="succeeded")){let Ee=typeof qe.payment_method=="string"?qe.payment_method:qe.payment_method?.id;o({id:Ee??qe.id,type:"card",threeDSecureActionResultTokenId:qe.id,isPaypal:!0},xe)}else{let Ee="PayPal payment was not completed. Please try again.";i?.(Ee),p?.(nn("paypal",Ee))}}catch(qe){i?.(qe instanceof Error?qe.message:"Failed to complete PayPal payment.")}finally{Te(!1)}})()},[Pe,o,i,p]);let at=Ze(async re=>{if(s||ce){re.reject();return}let Q=C?await C("paypal"):{proceed:!0};if(!Q.proceed){be.current.delete(ye),re.reject();return}let L=ct("paypal");be.current.set(ye,{generation:L,accountPatch:Q.accountPatch,sessionId:Q.sessionId,nonce:Q.nonce}),Z(!1),l?.("paypal"),re.resolve()},[s,l,C,ct,ce,ye]),Ye=Ze(async re=>{if(!Pe||!S)return;let Q=be.current.get(ye);if(Q&&!de(Q.generation)){be.current.delete(ye);return}if(!Q&&V()||Q&&!dt(Q.generation))return;Q||dt();let L=Q??null;if(be.current.delete(ye),!L&&C){let Ee=await C("paypal");if(!Ee.proceed){re.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}L={accountPatch:Ee.accountPatch,sessionId:Ee.sessionId,nonce:Ee.nonce}}let Ae=L?.sessionId??e,xe=L?.nonce??t,Me=await Qd({event:re,prepared:L,email:n,billingName:h,methodLabel:"PayPal",collect:Ue});if(!Me){re.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let qe=Me.email,ke={...L?.accountPatch,...Bn(Me,!0)};try{if(Te(!0),i?.(null),!Ae||!cn(qe))throw new Error("Missing sessionId or email for PayPal payment");await m?.(Me);let Ee=Pe.createPaymentMethod,{error:ee,paymentMethod:dn}=await Ee({type:"paypal"});if(ee){ut(ee,"stripe_paypal_create_payment_method_failed",Q?.generation),re.paymentFailed({reason:"fail"});return}let Yt=await Oa(r,Y,Ae,xe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:dn?.id??null,intentKind:"payment"});if(Yt.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let H=Yt.clientSecret,Je={return_url:window.location.href};if(dn?.id&&(Je.payment_method=dn.id),typeof window<"u")try{localStorage.setItem(ea,JSON.stringify({clientSecret:H,sessionId:Ae,nonce:xe,accountPatch:ke}))}catch{}let{error:$,paymentIntent:K}=await Pe.confirmPayment({clientSecret:H,confirmParams:Je,redirect:"if_required"});if($){if(typeof window<"u")try{localStorage.removeItem(ea)}catch{}if(Ho($)){let u=$.message??"Your payment was declined.";i?.(u),p?.(nn("paypal",u,{code:wr($),declineCode:fo($)})),await za({billingApiUrl:r,sessionId:Ae,nonce:xe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:wr($)??"provider_declined"}})}else ut($,"stripe_paypal_confirm_failed",Q?.generation);return}if(typeof window<"u")try{localStorage.removeItem(ea)}catch{}let ie=typeof K?.payment_method=="string"?K.payment_method:K?.payment_method?.id;o({id:ie??K?.id,type:"card",threeDSecureActionResultTokenId:K?.id,isPaypal:!0},{accountPatch:ke,paymentMethodCategory:"paypal",sessionId:Ae,nonce:xe});return}catch(Ee){ut(Ee,"stripe_paypal_failed",Q?.generation)}finally{Te(!1)}},[Pe,S,e,t,n,h,Ue,m,r,Y,o,i,p,C,ut,dt,de,V,ye]);return ze(Yr,{children:[c(zl,{state:G,placeholderTestId:"flopay-paypal-placeholder",borderRadius:_,children:ze("div",{ref:$e,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Qe&&c("button",{ref:De,type:"button","data-testid":"flopay-paypal-retry-button",onClick:x,style:ji,children:"Try PayPal again"}),ve&&c(yo,{identity:ve.identity,methodLabel:ve.methodLabel,onComplete:bt,onCancel:()=>bt(null)},ve.id),c("div",{style:{display:ve?"none":void 0},children:c(Bl,{onReady:re=>X(Ol(re,["paypal"])),onLoadError:()=>{X("load_error"),Gi(Qt(ae),"paypal","paypal")},onClick:at,onConfirm:Ye,onCancel:()=>{let re=be.current.get(ye);be.current.delete(ye),Qt(ae)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),U(re?.generation),Z(!1),Ie.current=!0,fe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Fe,emailRequired:Fe,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ye)})]})}),ce&&c(fr,{status:"processing"})]})}function xl({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:p,onDecline:f,onTechnicalFailure:C,runBeforeButtonClick:h,billingName:m,onBuyerIdentityReady:w,onLoadStateChange:_,placeholderBorderRadius:ae}){let Y=Br(),{emitInstrument:Pe}=Io(er),S=Hi(),G=Vi(),[X,ce]=le("loading");gt(()=>{_?.(X)},[X,_]);let[Te,Fe]=le(!1),ve=me(!cn(n?.trim())||!m?.trim()).current,{request:Ue,collect:bt,finish:ot}=mo(),$e=me(null),De=me(null),[ye,we]=le(0),[Qe,Z]=le(!1),[Ie,be]=le(()=>Na(e,t)?"blocked":"idle"),[ct,dt]=le("google_pay"),U=me(null),V=me(!0),de=me(!1),fe=me("google_pay"),ut=me("google_pay"),Ne=me(null),x=me(null),at=me(new Set);gt(()=>(V.current=!0,()=>{V.current=!1;for(let $ of at.current)window.clearTimeout($);at.current.clear()}),[]);let Ye=me(new Map),{startAttempt:re,finishAttempt:Q,invalidateAttempt:L,isAttemptInvalidated:Ae,isAttemptCurrent:xe,generationRef:Me}=Wo(($,K,ie)=>{C?.($,K,{...ie,popupBlocked:ie?.popupBlocked??Ir(K)}),dt($),Z(!0),we(u=>u+1)});gt(()=>{Qe&&De.current?.focus()},[Qe,ye]);let qe=Ze(()=>{we($=>$+1)},[]),ke=Ze(($,K,ie,u)=>{L(u),C?.($,K,{code:ie,popupBlocked:Ir(K)}),dt($),Z(!0),qe()},[L,C,qe]),Ee=Ze(()=>{window.setTimeout(()=>{($e.current?.querySelector("iframe")??$e.current)?.focus()},0)},[]);gt(()=>{de.current&&(de.current=!1,Ee())},[Ee,ye]);let ee=Ze(()=>{Z(!1),l?.(null),Ee()},[Ee,l]),dn=Ze(()=>{U.current?.()},[]);gt(()=>{let $=Na(e,t);if(!$)return;let K=!1,ie=!1,u=async()=>{if(!ie){ie=!0,K||be("checking");try{let B=await wl(S,$.clientSecret,at.current);if(K)return;let _e=Oi(B,$.providerObjectId,Fi($.clientSecret));if(_e.kind==="confirmed"){if(!Sl(e,t,$.clientSecret))return;U.current=null,be("idle"),s({id:_e.paymentMethodId,type:"card",threeDSecureActionResultTokenId:_e.intentId},{...$.accountPatch?{accountPatch:$.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(_e.kind==="terminal"){Li(e,t,$.clientSecret),U.current=null,be("idle"),dt($.paymentMethodType),Z(!0),qe();return}be("blocked")}catch{K||be("blocked")}finally{ie=!1}}};return U.current=u,be("blocked"),()=>{K=!0,U.current===u&&(U.current=null)}},[t,s,qe,e,S]);let Yt=Ze(async $=>{let K=!1,ie=je=>{K||(K=!0,$.paymentFailed({reason:"fail",...je?{message:je}:{}}))};if(!S||!G){ie();return}let u=Ye.current.get(ye);if(u&&!xe(u.generation)){Ye.current.delete(ye),ie();return}if(!u&&Ae()){ie();return}if(u&&!Q(u.generation)){ie();return}u||Q();let B=$.expressPaymentType??u?.method??fe.current,_e=u??null,Ke=Rl(B),Re;B==="apple_pay"?Re="apple_pay":B==="google_pay"&&(Re="google_pay");let $t=u?.generation??Me.current,N=Qt(Y),Ct=N?.now()??globalThis.performance?.now()??Date.now(),Et=new AbortController,pt=!1,un=!1,O=null,Ot=e,Cn="processing",pn="other",mn="provider_runtime",_n,Fn=new Promise((je,He)=>{_n=He}),Dn=window.setTimeout(()=>{pt=!0,Et.abort(),_n(Di)},Kd),Jt=async(je,He,St)=>{Cn=je,pn=He,mn=He==="intent_create"||He==="session_claim"?"transport_error":"provider_runtime";let rn=N?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([St,Fn])}finally{let wt=N?.now()??globalThis.performance?.now()??Date.now();N?.performance({stage:je,durationMs:Math.max(0,wt-rn),durationMode:"machine",requestCategory:He,paymentMethodCategory:"wallet",provider:"stripe",...pt?{statusClass:"timeout"}:{}})}};try{if(Fe(!0),l?.(null),!_e&&h){let se=await Jt("processing","other",h(Ke));if(!se.proceed){ie();return}_e={accountPatch:se.accountPatch,sessionId:se.sessionId,nonce:se.nonce}}let je=_e?.sessionId??e;Ot=je;let He=_e?.nonce??t,St=Ne.current??_e?.accountPatch,rn=Ll({event:$,fallbackEmail:St?.email??n,fallbackName:[St?.firstName,St?.lastName].join(" ").trim()||m});if(!cn(rn.email)){ie("Buyer details are required."),bt($i(B),rn).then(se=>{se&&(Ne.current=se)});return}Ne.current=null;let wt={..._e?.accountPatch,...Bn(rn,!0)};await Jt("processing","session_claim",Promise.resolve(w?.(rn)));let{error:$n}=await Jt("tokenization","provider_sdk",G.submit());if($n){ie(),ke(B,$n,"stripe_wallet_submit_failed",u?.generation);return}if(!je)throw new Error("Missing sessionId or email for payment.");let mt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:B,paymentMethodId:null,intentKind:o},Tt=JSON.stringify({sessionId:je,nonce:He??"",request:mt}),zt=x.current,yn=zt?.retryIdentity===Tt?zt.authorizationAttemptId:Dd();x.current={authorizationAttemptId:yn,retryIdentity:Tt};let Ut=await Jt("processing","intent_create",Oa(r,Pe,je,He??"",{...mt,authorizationAttemptId:yn},{signal:Et.signal}));if(Ut.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let At=Ut.clientSecret,Sn=Wd({createdAt:Date.now(),sessionId:je,...He?{nonce:He}:{},clientSecret:At,providerObjectId:Ut.providerObjectId,paymentMethodType:B,accountPatch:wt});window.clearTimeout(Dn),un=!0,N?.performance({stage:"callback",durationMs:Math.max(0,(N?.now()??globalThis.performance?.now()??Date.now())-Ct),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let wn=N?.now()??globalThis.performance?.now()??Date.now(),It={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Re?{walletType:Re}:{},attempt:$t},te=!1,on=null;N?.log({name:"payment.provider_confirmation.started",...It}),O=window.setTimeout(()=>{O!==null&&at.current.delete(O),te=!0;let se=N?.now()??globalThis.performance?.now()??Date.now();N?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...It,operationOutcome:"watchdog_expired",durationMs:Math.max(0,se-wn),statusClass:"timeout",failureCategory:"provider_runtime"}),N?.flush?.().catch(()=>{}),on?.()},Vd),at.current.add(O);let Kn=se=>{O!==null&&(window.clearTimeout(O),at.current.delete(O),O=null);let M=N?.now()??globalThis.performance?.now()??Date.now(),Oe=Math.max(0,M-wn),D=se;return te&&(se==="resolved"?D="resolved_late":se==="returned_error"?D="returned_error_late":D="rejected_late"),N?.log({name:"payment.provider_confirmation.returned",...It,operationOutcome:D}),N?.performance({...It,durationMs:Oe,durationMode:"buyer",operationOutcome:D}),{durationMs:Oe,operationOutcome:D}},Ht=!1,Kt=!1,an=se=>{if(!se||typeof se!="object")return null;let M=se;if(M.error)return null;let Oe=M.setupIntent??M.paymentIntent,D=Oi(Oe??null,void 0,!!M.setupIntent);return D.kind==="confirmed"?D:null},nr=se=>{if(Ht||u&&Me.current!==u.generation)return;let M=an(se);if(!M)return;if(Sn&&!Sl(je,He,At)){Ht=!0;return}let{intentId:Oe,paymentMethodId:D}=M;Ht=!0,Kt=!0,x.current=null,U.current=null,V.current&&(be("idle"),Fe(!1));let kt=`${Fl}:${je}`;if(typeof window<"u")try{localStorage.setItem(kt,JSON.stringify({createdAt:Date.now(),sessionId:je,nonce:He,accountPatch:wt,paymentMethodId:D,providerIntentId:Oe,paymentMethodType:B}))}catch{}try{s({id:D,type:"card",threeDSecureActionResultTokenId:Oe},{accountPatch:wt,paymentMethodCategory:"wallet",sessionId:je,nonce:He})}finally{if(typeof window<"u")try{localStorage.removeItem(kt)}catch{}}},Nn=!1;on=async()=>{if(!(Nn||Ht||Kt)){Nn=!0,V.current&&be("checking");try{let se=await wl(S,At,at.current);if(Ht||Kt)return;let M=Fi(At),Oe=Oi(se,Ut.providerObjectId,M);if(Oe.kind==="confirmed"){nr(M?{setupIntent:se}:{paymentIntent:se});return}if(Oe.kind==="terminal"){if(Kt=!0,Li(je,He,At),x.current=null,U.current=null,!V.current)return;be("idle"),ie(),ke(B,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",u?.generation);return}V.current&&!Kt&&(be("blocked"),Fe(!1))}catch{V.current&&!Kt&&(be("blocked"),Fe(!1))}finally{Nn=!1}}},U.current=on;let Wt,Le;try{let se=await(Fi(At)?S.confirmSetup({elements:G,clientSecret:At,redirect:"if_required"}):S.confirmPayment({elements:G,clientSecret:At,redirect:"if_required"}));if(!se||typeof se!="object"||(Wt=se,!Wt.error&&!an(Wt)))throw Ni;Le=Kn(Wt.error?"returned_error":"resolved")}catch(se){let M=se===Ni,Oe=Kn(M?"returned_error":"rejected");if(N?.error({...M?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:pi(se),...It,operationOutcome:Oe.operationOutcome,durationMs:Oe.durationMs,statusClass:"unknown"}),!V.current||Ht)return;await on?.();return}let fn=Wt.error;if(fn){if(!V.current||Ht)return;if(Ho(fn)){Kt=!0,Li(je,He,At),x.current=null,U.current=null,be("idle");let se=fn.message??"Your payment was declined.";ie(se),l?.(se),f?.(nn(Ke,se,{code:wr(fn),declineCode:fo(fn)})),za({billingApiUrl:r,sessionId:je,nonce:He,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:B,providerDeclineReason:wr(fn)??"provider_declined",...Ut.intentKind==="payment"&&Ut.providerObjectId.startsWith("pi_")?{providerIntentId:Ut.providerObjectId}:{}}})}else N?.error({...pi(fn),...It,operationOutcome:Le.operationOutcome,durationMs:Le.durationMs,statusClass:"unknown"}),await on?.();return}if(nr(Wt),!Ht)throw new Error("Invalid provider returned for APM intent")}catch(je){if(je===Di){let He=N?.now()??globalThis.performance?.now()??Date.now();N?.error({errorCode:Yd(pn),stage:Cn,requestCategory:pn,paymentMethodCategory:"wallet",provider:"stripe",...Re?{walletType:Re}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ot,durationMs:Math.max(0,He-Ct),statusClass:"timeout",failureCategory:mn,attempt:$t}),N?.flush?.().catch(()=>{})}ie(),ke(B,je,je===Di?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",u?.generation)}finally{if(window.clearTimeout(Dn),O!==null&&(window.clearTimeout(O),at.current.delete(O)),!un){let je=N?.now()??globalThis.performance?.now()??Date.now();N?.performance({stage:"callback",durationMs:Math.max(0,je-Ct),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...pt?{statusClass:"timeout"}:{}})}V.current&&Fe(!1)}},[S,G,e,t,n,m,bt,w,r,Pe,o,s,l,f,h,ke,Q,xe,Ae,Me,Y,ye]),H=Ft(()=>{let $=["applePay","googlePay","paypal","link","amazonPay","klarna"],K=new Set(["applePay","googlePay"]),ie=new Set(i.map(bl)),u={};for(let B of $)ie.has(B)?u[B]=K.has(B)?"always":"auto":u[B]="never";return u},[i]),Je=Ft(()=>i.map(bl),[i]);return ze(Yr,{children:[c(zl,{state:X,placeholderTestId:"flopay-wallet-placeholder",borderRadius:ae,children:ze("div",{ref:$e,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Qe&&ze("button",{ref:De,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ee,style:ji,children:["Try ",$i(ct)," again"]}),Ie!=="idle"&&ze("div",{role:"status","aria-live":"polite",children:[c("p",{children:"We are still confirming your payment. Check its status before trying again."}),c("button",{type:"button",onClick:dn,disabled:Ie==="checking",style:ji,children:Ie==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ue&&c(yo,{identity:Ue.identity,methodLabel:Ue.methodLabel,onComplete:ot,onCancel:()=>ot(null)},Ue.id),Ie==="idle"&&c("div",{style:{display:Ue?"none":void 0},children:c(Bl,{onReady:$=>{ce(Ol($,Je))},onLoadError:$=>{ce("load_error"),Gi(Qt(Y),"stripe","wallet")},onClick:async $=>{fe.current=$.expressPaymentType,ut.current=Rl($.expressPaymentType);let K=!0,ie=window.setTimeout(()=>{K=!1,$.reject()},$d),u=h?await h(ut.current):{proceed:!0};if(window.clearTimeout(ie),!K)return;if(!u.proceed){Ye.current.delete(ye),$.reject();return}let B=re($.expressPaymentType);Ye.current.set(ye,{generation:B,method:$.expressPaymentType,accountPatch:u.accountPatch,sessionId:u.sessionId,nonce:u.nonce}),Z(!1),p?.(ut.current),$.resolve()},onConfirm:Yt,onCancel:()=>{let $=Ye.current.get(ye);Ye.current.delete(ye),Qt(Y)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),L($?.generation),x.current=null,Z(!1),de.current=!0,qe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:H,emailRequired:ve,billingAddressRequired:ve,layout:{maxColumns:1,overflow:"never"}}},ye)})]})}),Te&&c(fr,{status:"processing"})]})}function Ul(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function pu({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:s,backgroundColor:l,borderColor:p,textColor:f,borderRadius:C,fontFamily:h}){let m=Od(e,t),w=hl[e],[_,ae]=le(!1),Y=!!w&&!_,Pe=m?.backgroundColor??l??"#ffffff",S=m?.borderColor??p??"#d1d5db",G=m?.textColor??f??"#262833";return c("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&s()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:La,padding:"0 1rem",backgroundColor:Pe,color:G,border:`1px solid ${S}`,borderRadius:C??8,fontSize:"0.95rem",fontWeight:600,fontFamily:h,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?c("span",{style:{margin:"0 auto"},children:`Connecting to ${Jr(e)}\u2026`}):ze(Yr,{children:[ze("span",{style:{display:"inline-flex",alignItems:"center",gap:Ad(e)?8:0},children:[Y?c("img",{src:w,alt:"","aria-hidden":"true",onError:()=>ae(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!Y&&m?.logoSvg?c("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:m.logoSvg}}):null,c("span",{children:Jr(e)})]}),i&&c("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:c("path",{d:"M9 18l6-6-6-6"})})]})})}function Ki({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:p,onDecline:f,onCancel:C,runBeforeButtonClick:h,onButtonClick:m,isProcessing:w,submitButtonColor:_,submitButtonBorderRadius:ae,submitButtonStyle:Y,errorText:Pe}){let S=Br(),{emitInstrument:G}=Io(er),X=Hi(),ce=Vi(),[Te,Fe]=le(!1),ve=me(!1),[Ue,bt]=le(!1),[ot,$e]=le("loading"),[De,ye]=le(""),we=!cn(r?.trim()),Qe=!we||cn(De.trim()),Z=Ze(async()=>{if(!X||!ce||w||ve.current||!Ue)return;ve.current=!0,Fe(!0);let Ie=h?await h("card"):{proceed:!0};if(!Ie.proceed){ve.current=!1,Fe(!1);return}m?.("card");let be=Ie.sessionId??t,ct=Ie.nonce??n,dt=Vr(o?.trim()),U=Bn({email:Ie.accountPatch?.email?.trim()||r?.trim()||De.trim(),firstName:Ie.accountPatch?.firstName?.trim()||dt.firstName,lastName:Ie.accountPatch?.lastName?.trim()||dt.lastName}),V=U.email,de=Bn({...Ie.accountPatch,...U});try{if(p?.(null),!cn(V))throw new Error("A valid email address is required for payment.");await i?.(U);let fe=await ce.submit();if(fe.error){p?.(fe.error.message??"Payment failed.");return}let ut=[U.firstName,U.lastName].filter(Boolean).join(" "),Ne=await X.createPaymentMethod({elements:ce,params:{billing_details:{email:V,...ut?{name:ut}:{}}}});if(Ne.error||!Ne.paymentMethod){p?.(Ne.error?.message??"Failed to create payment method.");return}let x=Ne.paymentMethod;if(!be||!V)throw new Error("Missing sessionId or email for payment.");let at=x.type||e,Ye=await Oa(s,G,be,ct??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:at,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let re=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(hr,JSON.stringify({clientSecret:re,sessionId:be,nonce:ct,accountPatch:de,paymentMethodId:x.id,paymentMethodType:x.type??e,gateway:"stripe"}))}catch{}let{error:Q,paymentIntent:L}=await X.confirmPayment({clientSecret:re,confirmParams:{return_url:window.location.href,payment_method:x.id},redirect:"if_required"});if(Q){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Me=Q.message??"Payment failed.";p?.(Me),f?.(nn("card",Me,{code:Q.code})),await za({billingApiUrl:s,sessionId:be,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Q.code??"provider_declined"}});return}let Ae=L?.status;if(!$o(Ae)){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Me=Ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(Me),f?.(nn("card",Me,{code:Ae??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let xe=typeof L?.payment_method=="string"?L.payment_method:L?.payment_method?.id;l({id:xe??x.id,type:"card",threeDSecureActionResultTokenId:L?.id,gateway:"stripe",paymentMethodType:x.type??e},{accountPatch:de,paymentMethodCategory:"apm",sessionId:be,nonce:ct})}catch(fe){p?.(fe instanceof Error?fe.message:"Payment failed. Please try again.")}finally{ve.current=!1,Fe(!1)}},[X,ce,w,Ue,h,m,t,n,r,o,De,i,s,G,e,l,p,f]);return ze("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[we&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:we&&ze("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:De,onChange:Ie=>ye(Ie.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(Ud,{onReady:()=>$e("ready"),onLoadError:()=>{$e("load_error"),Gi(Qt(S),"stripe","apm")},onChange:Ie=>{bt(!!Ie.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...cn(r?.trim())?{email:r?.trim()}:{}}}}}),c("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Z()},disabled:!Ue||!Qe||Te||w||ot!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:_,color:"white",border:"none",borderRadius:ae,fontSize:"1rem",fontWeight:600,cursor:!Ue||!Qe||Te||w||ot!=="ready"?"not-allowed":"pointer",opacity:!Ue||!Qe||Te||w||ot!=="ready"?.5:1,transition:"opacity 120ms ease-out",...Y??{}},children:Te?"Processing\u2026":`Pay with ${Jr(e)}`}),Pe&&c(ho,{margin:"0.75rem 0 0",children:Pe})]})}function Ml({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:p,onTokenizedBody:f,onErrorChange:C,onButtonClick:h,onDecline:m,runBeforeButtonClick:w,onLoadStateChange:_,isProcessing:ae=!1,submitButtonColor:Y="#4A49FF",submitButtonBorderRadius:Pe=8,submitButtonStyle:S,buttonAppearance:G,themeId:X,onExpandApm:ce,expandedApmMethod:Te}){let{emitInstrument:Fe}=Io(er),[ve,Ue]=le(null),[bt,ot]=le(null),$e=me(!1),{request:De,collect:ye,finish:we}=mo();gt(()=>{s.length>0&&l?_?.("ready"):l||_?.("loading")},[s.length,l,_]);let Qe=Ze(async U=>{if(!l||$e.current||ae)return;$e.current=!0,ot(U);let V=w?await w("card"):{proceed:!0};if(!V.proceed){$e.current=!1,ot(null);return}h?.("card");let de=V.sessionId??e,fe=V.nonce??t,ut=Vr([V.accountPatch?.firstName,V.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ne=Bn({email:V.accountPatch?.email?.trim()||n?.trim(),firstName:V.accountPatch?.firstName?.trim()||ut.firstName,lastName:V.accountPatch?.lastName?.trim()||ut.lastName});if(!cn(Ne.email)){ot(null);let Ye=await ye(Jr(U),Ne);if(!Ye){$e.current=!1;return}Ne=Ye,ot(U)}let x=Ne.email,at=Bn({...V.accountPatch,...Ne});try{if(C?.(null),!de||!cn(x))throw new Error("Missing sessionId or email for payment.");await o?.(Ne);let Ye=await Oa(i,Fe,de,fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:U,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let re=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(hr,JSON.stringify({clientSecret:re,sessionId:de,nonce:fe,accountPatch:at,paymentMethodType:U,gateway:"stripe"}))}catch{}let{error:Q,paymentIntent:L}=await l.confirmPayment({clientSecret:re,confirmParams:{return_url:window.location.href,payment_method_data:{type:U,billing_details:{name:[Ne.firstName,Ne.lastName].filter(Boolean).join(" "),...x?{email:x}:{}}}},redirect:"if_required"});if(Q){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Me=Q.message??"Payment failed.";C?.(Me),m?.(nn("card",Me,{code:Q.code})),await za({billingApiUrl:i,sessionId:de,nonce:fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:U,providerDeclineReason:Q.code??"provider_declined"}});return}let Ae=L?.status;if(!$o(Ae)){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Me=Ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";C?.(Me),m?.(nn("card",Me,{code:Ae??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let xe=typeof L?.payment_method=="string"?L.payment_method:L?.payment_method?.id;f({id:xe??L?.id,type:"card",threeDSecureActionResultTokenId:L?.id,gateway:"stripe",paymentMethodType:U},{accountPatch:at,paymentMethodCategory:"apm",sessionId:de,nonce:fe})}catch(Ye){C?.(Ye instanceof Error?Ye.message:"Payment failed. Please try again.")}finally{$e.current=!1,ot(null)}},[l,ae,w,h,e,t,n,ye,i,Fe,r,o,f,C,m]),[Z,Ie]=le(null),be=ce?Te??null:Z,ct=Ze(U=>{$e.current||ae||be&&be!==U||(Pl(U)?ce?ce(U):Ie(U):Qe(U))},[be,ae,Qe,ce]),dt=Ft(()=>Z?Ul(p,Z):null,[Z,p]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:De?c(yo,{identity:De.identity,methodLabel:De.methodLabel,onComplete:we,onCancel:()=>we(null)},De.id):s.map(U=>{let V=Te===U,de=bt===U,fe=bt!==null&&bt!==U||Te!=null&&Te!==U;return ze(qd.Fragment,{children:[c(pu,{method:U,themeId:X,submitting:de,disabled:fe,highlighted:V,hasNextStep:Pl(U),onClick:()=>ct(U),backgroundColor:G?.backgroundColor,borderColor:G?.borderColor,textColor:G?.textColor,borderRadius:G?.borderRadius,fontFamily:G?.fontFamily}),!ce&&Z===U&&dt&&l&&c(Gr,{stripe:l,options:dt,children:c(Ki,{method:U,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:f,onErrorChange:C,onDecline:m,onCancel:()=>Ie(null),runBeforeButtonClick:w,onButtonClick:h,isProcessing:ae,submitButtonColor:Y,submitButtonBorderRadius:Pe,submitButtonStyle:S})},U)]},U)})})}function mu({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:i,onComplete:s,onError:l,onDecline:p,onTokenizedBody:f,firstName:C,lastName:h,chv:m,className:w,submitLabel:_,isProcessing:ae,error:Y,onErrorChange:Pe,showPayPal:S=!0,showStripe:G=!0,enabledPaymentMethods:X,enabledPaymentMethodCountries:ce,showApplePay:Te=!0,showGooglePay:Fe=!0,layout:ve="default",theme:Ue,buttonsTheme:bt,buttonsStyles:ot,appearance:$e,cardButtonContent:De,cardBackButtonContent:ye,cardTitleContent:we,showSecurityFooter:Qe,onButtonClick:Z,onBeforeButtonClick:Ie,onBuyerIdentityReady:be,enableAVS:ct,cardFieldOrder:dt,cardPreFormSlot:U,avsLayout:V="row",country:de,zip:fe,addressLine1:ut,addressLine2:Ne,city:x,state:at,onCountryChange:Ye,onZipChange:re,avsCheck:Q,checkoutType:L,checkoutLayout:Ae,totalAmount:xe=0,currency:Me="usd",initialCardOpen:qe=!1,directPaypal:ke,isSubscription:Ee=!1,session:ee,dataAttachmentPending:dn=!1,dataAttachmentRequiresIdentity:Yt=!1,debug:H=!1}){let Je=Br(),$=mi(),K=Io(cr),{emitInstrument:ie}=Io(er),u=ee??K.session,B=u?.gateways?.paypal?.providerObjectType??ke?.providerObjectType,_e=dn||K.claimPending===!0,Ke=Yt||K.claimRequiresIdentity===!0,Re=_e&&!Ke,$t=rl(),N=n||$t,[Ct,Et]=le(!1),[pt,un]=le(null),[O,Ot]=le(de??"US"),[Cn,pn]=le(fe??""),[mn,_n]=le(ut??""),[Fn,Dn]=le(Ne??""),[Jt,je]=le(x??""),[He,St]=le(at??""),[rn,wt]=le(""),[$n,mt]=le({}),Tt=me(fe??""),zt=me(de??"US"),yn=me(ut??""),Ut=me(Ne??""),At=me(x??""),Sn=me(at??""),wn=me(""),It=me({});gt(()=>{let a=(b,j,Be,W,st)=>{if(It.current[b])return;let tt=j?.trim();!tt||tt===Be.current||(Be.current=tt,W(tt),st?.(tt))};a("country",de,zt,Ot,Ye),a("zip",fe,Tt,pn,re),a("addressLine1",ut,yn,_n),a("addressLine2",Ne,Ut,Dn),a("city",x,At,je),a("state",at,Sn,St)},[de,fe,ut,Ne,x,at,Ye,re]);let te=Ft(()=>Nd(ct),[ct]),on=te!==null,Kn=Ft(()=>Bi(ee),[ee]),Ht=!!ee?.vault?.html,Kt=!!ee?.gateways?.pcivault,an=ci(ee),Nn=!!(ee?.gateways?.stripe?.enabledPaymentMethods??X)?.includes("card")||Ar(ee),Wt=Ht||Nn||Kt,Le=!!(G&&Wt&&e),[fn,se]=le(()=>ve!=="buttons"||qe?e??null:null),[M,Oe]=le(0),D=ve!=="buttons"||qe||!!e&&fn===e,kt=ee?.captureMethod,xt=me(Je);gt(()=>{xt.current=Je},[Je]);let[Gt,Vn]=le(null);gt(()=>{if(!Le||!e||!D){Vn(null);return}let a=xt.current?xt.current.cardCapture({sessionId:e,captureMethod:kt}):new wd({sessionId:e,captureMethod:kt,billingApiUrl:N,telemetry:r});return Vn({sessionId:e,captureMethod:kt,billingApiUrl:N,telemetry:r,capture:a}),()=>{a.unmount()}},[Le,e,D,kt,N,r]);let ge=Le&&e&&D&&Gt?.sessionId===e&&Gt.captureMethod===kt&&Gt.billingApiUrl===N&&Gt.telemetry===r?Gt.capture:null,sn=Ft(()=>{let a=O,b=te?rt(te.postal_code,a):!1;return cu(a,Cn,b)},[te,O,Cn]),{avsInvalid:Hn,invalidAvsFields:Pr}=Ft(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!Le||!te)return{avsInvalid:!1,invalidAvsFields:a};let b=O,j=(st,tt)=>rt(st,b)&&!tt.trim(),Be={line1:j(te.address_line_1,mn),city:j(te.city,Jt),state:j(te.state,He),zip:sn.empty||sn.malformed};return{avsInvalid:Be.line1||Be.city||Be.state||Be.zip,invalidAvsFields:Be}},[Le,te,O,mn,Jt,He,sn]),[rr,zr]=le(!1),[Ur,or]=le(!1),[Er,Rn]=le(!1),[ar,Dt]=le({line1:!1,city:!1,state:!1}),Ln=me(!1),Wn=me({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Gn=me(!1),yt=Ze(a=>{Wn.current[a]=!0,Gn.current=!0},[]),En=Ze(a=>!Ln.current&&Wn.current[a],[]),Yn=Ze(a=>{En(a)&&Dt(b=>b[a]?b:{...b,[a]:!0})},[En]),[ir,gn]=le(()=>zi(ee?.vault)),[We,hn]=le(qe&&Wt?"card":"buttons"),[ln,On]=le(null),br=We==="expanding"||We==="card",qr=ee?.gateways?.stripe&&!an?"stripe":void 0,Cr=Ze(()=>{ie?.({class:"card_surface",provider:qr})},[qr,ie]),zn=me(null),vn=Ze(a=>{zn.current&&clearTimeout(zn.current),zn.current=setTimeout(()=>{zn.current=null,a()},ta)},[]);gt(()=>()=>{zn.current&&clearTimeout(zn.current)},[]);let Xr=Ze(()=>{Cr(),se(e??null),Oe(a=>a+1),hn("expanding"),vn(()=>hn("card"))},[vn,Cr,e]),Tn=Ze(()=>{hn("collapsing"),vn(()=>hn("buttons"))},[vn]),Tr=Ze(a=>{On(a),hn("apm-expanding"),vn(()=>hn("apm-form"))},[vn]),In=Ze(()=>{hn("apm-collapsing"),vn(()=>{hn("buttons"),On(null)})},[vn]);gt(()=>{ve==="buttons"&&qe&&Wt&&(se(e??null),hn("card"))},[ve,qe,Wt,e]);let[Un,et]=le(null),Jn=me(!1),Xt=me(null),_t=me("idle"),[T,E]=le(!1),F=me(T);F.current=T;let[z,it]=le(()=>ke?.existingOrderId?{orderId:ke.existingOrderId,attempts:1}:null),R=me(z);gt(()=>{R.current=z},[z]);let d=me(null),A=Ft(()=>{if(be||K.claimBuyerIdentity||ee?.buyerIdentified!==!1||!e||!t)return;let a=`${N}|${e}|${t}`;d.current?.key!==a&&(d.current={key:a,claim:uo(new wo(N,{telemetry:!1}),e,t,{...i?{userId:i}:{},...C?{firstName:C}:{},...h?{lastName:h}:{}})});let b=d.current.claim;return async j=>{await b(j)}},[be,K.claimBuyerIdentity,ee?.buyerIdentified,e,t,N,i,C,h]),g=be??K.claimBuyerIdentity??A,P=Y??pt,I=Ft(()=>zd(Ue),[Ue]),v=Ft(()=>{let a=I?.buttonsLayout??Ld(bt);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},[I,bt,ot]),q=$e??I?.appearance,Ve=Ft(()=>Us({appearance:q,buttonsStyles:v,layout:ve}),[q,v,ve]),Nt=K.inlineSessionPatchProcessing??!1,Ce=(ae??Ct)||Nt,ne=N.replace(/\/+$/,""),y=Ft(()=>ui({userId:i,email:o,firstName:C,lastName:h,country:de,zip:fe},$n),[i,o,C,h,de,fe,$n]),k=[y.firstName,y.lastName].filter(a=>!!a?.trim()).join(" "),J=!cn(y.email?.trim()),ue=me(null);Le&&ue.current===null&&(ue.current=J);let Se=Le&&(ue.current??J),pe=Ft(()=>du(rn,Se),[rn,Se]),Ge=pe.empty||pe.malformed,ht=Ft(()=>Je?Je.getRawProvider():null,[Je]),tn=Ft(()=>$?$.getRawProvider():null,[$]),qn=xe||100,Zr=Me.toLowerCase(),Ka=Ft(()=>q?Id(q):null,[q]),Qr=Ka,ss=Ft(()=>{let a=Ka??{},b=a.rules??{};return{...a,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[Ka]),ls=Ft(()=>({...Xs(xe,ee?.captureMethod),currency:Zr,...Qr?{appearance:Qr}:null}),[xe,Zr,ee?.captureMethod,Qr]),cs=Ft(()=>({mode:"payment",amount:qn,currency:Zr,captureMethod:"manual",setupFutureUsage:"off_session",...Qr?{appearance:Qr}:null}),[qn,Zr,Qr]),he=Ze(a=>{un(a),Pe?.(a)},[Pe]),Va=me(""),[ds,Ql]=le(!1),Ha=Ze(()=>{Ql(!0)},[]);gt(()=>{if(!Le||!Se||!g||!ds||Ge||Va.current)return;let a=Bn({email:cn(y.email?.trim())?y.email?.trim():wn.current.trim(),firstName:y.firstName?.trim(),lastName:y.lastName?.trim()});Va.current=JSON.stringify(a),mt(b=>({...b,...a})),Promise.resolve(g(a)).catch(b=>{Va.current="",he(b instanceof Error?b.message:"Failed to attach buyer details.")})},[Le,Se,g,ds,Ge,y.email,y.firstName,y.lastName,he]),gt(()=>{!Le||!ge||ge.setCardFieldOrder?.(dt??null,te==null&&!Se)},[Le,ge,dt,te,Se]),gt(()=>{(We==="expanding"||We==="collapsing"||We==="apm-expanding"||We==="apm-collapsing")&&he(null)},[We,he]);let pr=Ze((a,b,j)=>{p?.(nn(a,b,j))},[p]),eo=Ze((a,b,j)=>{let Be=j?.popupBlocked??Ir(b),W=su(a,Be),st=Hr(j?.code)??wr(b)??"external_payment_method_failed",tt=new dr(W,"api_error",{code:"external_payment_method_failed",param:a});et(null),ve==="buttons"&&(hn("buttons"),On(null)),he(W),l?.(tt),console.error("[FloPay] External payment method failed:",{method:a,code:st,popupBlocked:Be})},[ve,l,he]);gt(()=>{if(!Le||!e){gn(null);return}let a=zi(ee?.vault);if(a){gn(a);return}if(!D){gn(null);return}gn(null);let b=!0;return new wo(ne).getVaultCapture(e,t).then(j=>{if(!b)return;let Be=zi(j);Be?gn(Be):he("Failed to load the secure card form.")}).catch(j=>{b&&he(j instanceof Error?j.message:"Failed to load the secure card form.")}),()=>{b=!1}},[Le,D,M,e,ee?.vault,ne,t,he]);let sr=me({onComplete:s,onError:l,updateError:he,emitDecline:pr,resolvedAccount:y,avsConfig:te,avsCheckProp:Q,sessionId:e,nonce:t,baseUrl:ne,captureMethod:ee?.captureMethod,paymentId:ee?.paymentId,authorizationExpiresAt:ee?.authorizationExpiresAt,serverSideCardGateway:an});sr.current={onComplete:s,onError:l,updateError:he,emitDecline:pr,resolvedAccount:y,avsConfig:te,avsCheckProp:Q,sessionId:e,nonce:t,baseUrl:ne,captureMethod:ee?.captureMethod,paymentId:ee?.paymentId,authorizationExpiresAt:ee?.authorizationExpiresAt,serverSideCardGateway:an};let Wa=me(!1),us=Ze(()=>{let a=sr.current,b=a.resolvedAccount.email?.trim(),j=cn(b)?b:wn.current.trim();if(!cn(j))return null;let Be=a.resolvedAccount.firstName?.trim(),W=a.resolvedAccount.lastName?.trim(),st=zt.current||a.resolvedAccount.country||"US",tt=a.avsConfig?rt(a.avsConfig.state,st):!1,yr=a.avsConfig?rt(a.avsConfig.address_line_1,st):!1,Xe=a.avsConfig?rt(a.avsConfig.postal_code,st):!1,Mt=a.avsConfig?rt(a.avsConfig.city,st):!1,ft=a.avsConfig?rt(a.avsConfig.address_line_2,st):!1,nt=yr&&!tt&&Xe?vl(st,(Tt.current??"").trim()):null,Mn=tt?Sn.current:nt;return{accountData:{userId:a.resolvedAccount.userId??"",email:j,...Be?{firstName:Be}:{},...W?{lastName:W}:{},...Xe&&Tt.current?{zip:Tt.current}:{},...Mt&&At.current?{city:At.current}:{},...Mn?{state:Mn}:{},...yr&&yn.current?{addressLine1:yn.current}:{},...ft&&Ut.current?{addressLine2:Ut.current}:{},country:st},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:rt(a.avsConfig.country,st),postal_code:Xe,address_line_1:yr,address_line_2:ft,city:Mt,state:tt}}:{}}},[]),ps=me(_e);ps.current=_e,gt(()=>{_e||P!==Il||sr.current.updateError(null)},[_e,P]),gt(()=>{!Le||!ge||ge.setSubmitGate?.(Hn||_e||Ge||T)},[Le,ge,Hn,_e,Ge,T]),gt(()=>{if(!Le||!ge)return;Wa.current=!1;let a=null,b=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,_t.current="idle",et(null)},400)},j=ge.on("submitting",()=>{zr(!0),Xt.current&&clearTimeout(Xt.current),_t.current="validation-window",Xt.current=setTimeout(()=>{Xt.current=null,_t.current==="validation-window"&&(_t.current="processing")},Jd),et("processing");let Xe=sr.current;if(!Xe.sessionId||!Xe.nonce)return;let Mt=us();if(!Mt){Xe.updateError("Enter a valid email address."),_t.current="idle",et(null);return}new wo(Xe.baseUrl).patchAccountSnapshot(Xe.sessionId,Xe.nonce,Mt,{telemetryMode:"best_effort"}).catch(ft=>{if(!Zd(ft))return;let nt=ft instanceof Error?ft.message:"Please check your billing address and try again.";Xe.updateError(nt),_t.current="idle",et(null),Xe.onError?.(ft instanceof dr?ft:new dr(nt,"api_error"))})}),Be=ge.on("complete",async Xe=>{if(bo(Xe.sessionId??sr.current.sessionId),_t.current="terminal",E(!1),et("success"),await new Promise(Mn=>setTimeout(Mn,600)),Wa.current)return;Wa.current=!0;let Mt=sr.current,ft=Bi(Mt)||Xe.outcome==="authorized",nt=Mt.serverSideCardGateway?{}:{paymentIntentId:Xe.intentId};sr.current.onComplete?.(ft?{status:"authorized",...nt,paymentId:Xe.paymentId??Mt.paymentId,sessionId:Xe.sessionId??Mt.sessionId,authorizationExpiresAt:Xe.authorizationExpiresAt??Mt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...nt,checkoutMethod:"card"})}),W=ge.on("decline",Xe=>{let Mt=sr.current,ft=Xe.message??"Your payment was declined. Please try another card or contact your bank.";_t.current="terminal",E(!1),Mt.updateError(ft),et("error");let nt=Xe.failureOutcome??Bd(Xe.declineReason)??"authorization_declined";Mt.emitDecline("card",ft,{code:nt,declineCode:nt}),b()}),st=ge.on("error",Xe=>{let Mt=sr.current,ft=Xe.message??"There was a problem processing your payment. Please try again.";_t.current="terminal",E(!1),Mt.updateError(ft),et("error"),Mt.onError?.(new dr(ft,"api_error",{code:Xe.failureOutcome??"capture_failed"})),b()}),tt=ge.on("challenge_dismissed",()=>{Xt.current&&(clearTimeout(Xt.current),Xt.current=null),_t.current="processing",E(!0),et(null)}),yr=ge.on("blocked",()=>{if(F.current){sr.current.updateError(Xd);return}if(!ps.current){zr(!0);return}Ha(),sr.current.updateError(Il)});return()=>{a&&(clearTimeout(a),a=null),Xt.current&&(clearTimeout(Xt.current),Xt.current=null),_t.current="idle",E(!1),et(null),j(),Be(),W(),st(),tt(),yr()}},[Le,ge,Ha,us]);let mr=!!ke?.clientId,To=Array.isArray(X),sa=To&&X.length>0,ec=To&&X.includes("paypal"),{expressMethods:la,paymentElementMethods:Ao}=Ft(()=>Fd(X,{excludePaypal:mr}),[X,mr]),ms=mr||!!$,tc=Ft(()=>ms?la.filter(a=>a!=="paypal"):la,[la,ms]),nc=Ft(()=>{let a=[];return Te&&a.push("apple_pay"),Fe&&a.push("google_pay"),a},[Te,Fe]),to=To?tc:nc,rc=G&&to.length>0,Ga=on?O:de,ca=Ft(()=>{let a=Ga?.trim().toUpperCase();return a?ce?Ao.filter(b=>{let j=ce[b];return!j||j.length===0||j.includes(a)}):Rd(Ao,Ga):Ao},[Ao,Ga,ce]),Ya=Ft(()=>({mode:"payment",amount:qn,currency:Zr,paymentMethodCreation:"manual",appearance:ss}),[qn,Zr,ss]),[ys,fs]=le("loading"),[gs,hs]=le("loading"),[vs,Ps]=le("loading"),[oc,Ja]=le(!1),[bs,Xa]=le("loading"),[Za,ac]=le();gt(()=>{ac(ba())},[]);let da=Za?.inAppBrowser,ua=Za?Ca(Za,ke?.approvalPresentation,B??(Ee?"subscription":"order")):"popup",Cs=S&&(mr||(To?ec:da===!1)),Ss=G&&rc,xo=(!Re||!!K.waitForDataAttachment)&&Cs&&mr,ws=bs==="retrying"||bs==="exhausted",Mo=!Re&&Cs&&!!tn&&(!mr||ws),no=!Re&&Ss&&!!ht,Bo=!Re&&G&&sa&&ca.length>0&&!!ht,ic=xo&&!ws?oc:Mo&&Tl(ys),sc=no&&Tl(gs),lc=Bo&&vs!=="load_error",Is=a=>a==="loading"||a==="ready",ks=xo||Mo&&Is(ys)||no&&Is(gs)||Bo&&vs!=="load_error",pa=me(!1);gt(()=>{if(!pa.current){if(!G&&!S){pa.current=!0;let a=new dr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(a),he(a.message)}else if(!G&&S&&!mr&&!tn){pa.current=!0;let a=new dr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(a),he(a.message)}else if(da!==void 0&&!Re&&!Wt&&!ks){pa.current=!0;let a=new dr("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?.(a),he(a.message)}}},[G,S,mr,tn,da,Re,Wt,ks,l,he]);let _s=me(!1);gt(()=>{if(_s.current||!sa)return;let a=[];Te!==!0&&a.push("showApplePay"),Fe!==!0&&a.push("showGooglePay"),a.length!==0&&(_s.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.`))},[sa,Te,Fe]);let Rs=Ze((a,b)=>K.applyInlineSessionPatch?K.applyInlineSessionPatch(a).then(j=>({error:null,sessionId:j.sessionId||e,nonce:j.session?.clientSecret||t})).catch(j=>{let Be=El(b,j);return he(Be.message),l?.(Be),{error:Be,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[K.applyInlineSessionPatch,t,l,e,he]),lr=Ze(async a=>{if(a!=="card"&&Re&&await K.waitForDataAttachment?.(),!Ie)return{proceed:!0};try{let b=await Ie({method:a,sessionId:e||void 0,createSession:K.inlineSessionDraft});if(b===!1)return{proceed:!1};if(b&&typeof b=="object"){b.account&&mt(Be=>({...Be??{},...b.account}));let j=await Rs(b,a);return j.error?{proceed:!1,accountPatch:b.account}:{proceed:!0,accountPatch:b.account,sessionId:j.sessionId,nonce:j.nonce}}return{proceed:!0}}catch(b){let j=El(a,b);return he(j.message),l?.(j),{proceed:!1}}},[Rs,K.inlineSessionDraft,K.waitForDataAttachment,Re,Ie,l,e,he]),Es=Ze(async(a,b)=>{if(Jn.current)return;Jn.current=!0,Et(!0),et("processing"),he(null);let j=b?.sessionId??e,Be=b?.nonce??t,W=ui(y,b?.accountPatch),st=b?.completionPaymentMethodId??Ko(a),tt=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,yr=ru(a),Xe=()=>{ie?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:yr})};try{let ft=await new wo(ne).processPayment(W.userId??"",{sessionId:j,nonce:Be,paymentMethodCategory:b?.paymentMethodCategory??au(a),tokenizedData:tt,accountData:{...b?.accountPatch,userId:W.userId??"",email:W.email??"",firstName:W.firstName||void 0,lastName:W.lastName||void 0,...te?(()=>{let vt=zt.current,Zn=rt(te.state,vt),kn=rt(te.address_line_1,vt),Zt=rt(te.postal_code,vt),Kr=kn&&!Zn&&Zt?vl(vt,(Tt.current??"").trim()):null,zo=Zn?Sn.current:Kr;return{country:vt,...Zt&&Tt.current?{zip:Tt.current}:{},...rt(te.city,vt)&&At.current?{city:At.current}:{},...zo?{state:zo}:{},...kn&&yn.current?{addressLine1:yn.current}:{},...rt(te.address_line_2,vt)&&Ut.current?{addressLine2:Ut.current}:{}}})():{}},chv:m,avsCheck:Q??!1,checkoutType:L,checkoutLayout:Ae,avsConfig:te?{country:rt(te.country,zt.current),postal_code:rt(te.postal_code,zt.current),address_line_1:rt(te.address_line_1,zt.current),address_line_2:rt(te.address_line_2,zt.current),city:rt(te.city,zt.current),state:rt(te.state,zt.current)}:void 0});if(ft.ok){let vt=ft.status===204?null:await ft.json().catch(()=>null),Zn=Bi(ee)||vt?.status==="authorized";bo(j),et("success"),it(null),await new Promise(Kr=>setTimeout(Kr,600));let kn;typeof vt?.paymentId=="string"?kn=vt.paymentId:ee?.paymentId&&(kn=ee.paymentId);let Zt;typeof vt?.authorizationExpiresAt=="string"?Zt=vt.authorizationExpiresAt:ee?.authorizationExpiresAt&&(Zt=ee.authorizationExpiresAt),s?.(Zn?{status:"authorized",...kn===void 0?{}:{paymentId:kn},sessionId:typeof vt?.sessionId=="string"?vt.sessionId:j,...Zt===void 0?{}:{authorizationExpiresAt:Zt},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:st,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:st,checkoutMethod:a.isPaypal?"paypal":"card"});return}let nt=await ft.json().catch(()=>null);if(nt?.type==="paypal_redirect_required"){let vt=nt.threeDSecureToken,Zn=nt.paymentMethodId||a.id||"";if(!Je||!vt){et("error"),he("PayPal authorization required but no token provided.");return}try{let kn=$?.getRawProvider();if(!kn){he("PayPal is not available.");return}let Zt={return_url:window.location.href};Zn&&(Zt.payment_method=Zn);let{error:Kr}=await kn.confirmPayment({clientSecret:vt,confirmParams:Zt,redirect:"if_required"});if(Kr){et("error");let zo=Kr.message??"PayPal payment failed.";he(zo),pr("paypal",zo,{code:Kr.code})}}catch(kn){et("error"),he(kn instanceof Error?kn.message:"PayPal authorization failed.")}return}if(nt?.type==="paypal_direct_required"){let vt=nt.orderId;if(!vt){et("error"),he("PayPal retry required but no order id provided.");return}let Zn=R.current?.attempts??0;if(Zn>=2){et("error"),he("PayPal payment could not be completed after multiple attempts."),pr("paypal","paypal_direct_required retry limit exceeded");return}Ja(!1),Xa("loading"),it({orderId:vt,attempts:Zn+1}),et(null);return}_d(ft.status,nt)||Xe(),et("error");let Mn=nt?.message??"Payment failed. Please try again.";he(Mn),pr(a.isPaypal?"paypal":"card",Mn,{code:nt?.code??nt?.gatewayErrorCode,declineCode:nt?.declineCode??nt?.gatewayDeclineReason}),await new Promise(vt=>setTimeout(vt,400))}catch(Mt){Nl(Mt)||Xe(),et("error"),he(Mt instanceof Error?Mt.message:"An unexpected error occurred"),await new Promise(ft=>setTimeout(ft,400))}finally{Et(!1),et(null),Jn.current=!1}},[ne,e,t,y,te,Q,L,Ae,m,Je,$,ee,s,he,pr,ie]),An=Ze((a,b)=>{f?f(a):Es(a,b)},[f,Es]),Fo=`${Fl}:${e}`;gt(()=>{if(typeof window>"u")return;let a=localStorage.getItem(Fo);if(!a)return;let b;try{b=JSON.parse(a)}catch{localStorage.removeItem(Fo);return}if(!b||typeof b.createdAt!="number"||Date.now()-b.createdAt<0||Date.now()-b.createdAt>Dl||typeof b.paymentMethodId!="string"||typeof b.providerIntentId!="string"||typeof b.paymentMethodType!="string"||b.sessionId!==e||!t||b.nonce!==t||!to.includes(b.paymentMethodType)){localStorage.removeItem(Fo);return}localStorage.removeItem(Fo),An({id:b.paymentMethodId,type:"card",threeDSecureActionResultTokenId:b.providerIntentId,gateway:"stripe",paymentMethodType:b.paymentMethodType},{...b.accountPatch?{accountPatch:b.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[An,t,e,Fo,to]);let Ts=me(!1);gt(()=>{if(typeof window>"u"||Ts.current)return;let a=new URLSearchParams(window.location.search),b=a.get("payment_intent"),j=a.get("payment_intent_client_secret"),Be=a.get("redirect_status");if(!b||!j||!Je)return;let W=Je.getRawProvider();if(!W)return;let st=nt=>{let Mn=localStorage.getItem(nt);if(!Mn)return null;try{return JSON.parse(Mn)}catch{return localStorage.removeItem(nt),null}},tt=st(hr)??st(Cl),yr;if(tt?.clientSecret){if(tt.clientSecret!==j)return;yr={...tt.accountPatch?{accountPatch:tt.accountPatch}:{},...tt.sessionId?{sessionId:tt.sessionId}:{},...tt.nonce?{nonce:tt.nonce}:{}}}else if(tt?.sessionId&&tt.sessionId!==e)return;Ts.current=!0,localStorage.removeItem(hr),localStorage.removeItem(Cl);let Xe=new URL(window.location.href);Xe.searchParams.delete("payment_intent"),Xe.searchParams.delete("payment_intent_client_secret"),Xe.searchParams.delete("redirect_status"),window.history.replaceState({},"",Xe.toString());let Mt=tt?.paymentMethodType??tt?.tokenType??"card",ft="card";(async()=>{if(Be==="failed"){let Zt="Payment was declined. Please try again.";he(Zt),pr(ft,Zt);return}let{paymentIntent:nt,error:Mn}=await W.retrievePaymentIntent(j);if(Mn){let Zt=Mn.message??"Failed to retrieve payment status.";he(Zt),pr(ft,Zt,{code:Mn.code});return}let vt=nt?.status,Zn=$o(vt);if(!nt||!Zn){let Zt=vt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";he(Zt),pr(ft,Zt,{code:vt??"missing_payment_intent"});return}let kn=typeof nt.payment_method=="string"?nt.payment_method:nt.payment_method?.id;An({id:kn??tt?.paymentMethodId??tt?.tokenId??nt.id,type:"card",threeDSecureActionResultTokenId:nt.id,gateway:tt?.gateway??"stripe",paymentMethodType:Mt},yr)})()},[e,An,Je,he,pr]);let Qa=Ze(a=>{a.preventDefault()},[]);if(!(Le||Je!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Do=ve==="buttons",xn=q?.variables,cc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ei=xn?.colorBackground,dc=ei&&!cc.has(ei)?ei:void 0,No=v.cardInputBorder??(Do?"#e5e7eb":"#A4A4FF"),As=xn?.colorDanger??"#dc2626",qt=a=>Pr[a]&&(ar[a]||rr),ma=Ge&&(Er||rr),Xn=a=>a?As:No,ya=(sn.malformed||sn.empty)&&(Ur||rr),uc=Xn(ya),ti=v.cardFormContainer?.backgroundColor??dc??(Do?"white":"#EDEDFF"),ro=v.cardInputBackground??xn?.colorBackground??"white",ni=io(ye),xs=io(we),oo=v.nameInput,Ms=v.cardInputFontSize??uu(oo?.fontSize)??xn?.fontSizeBase??"16px",Bs=typeof oo?.fontFamily=="string"?oo.fontFamily:xn?.fontFamily??"Poppins, sans-serif",Fs=zs(oo?.fontWeight)??400,pc=v.cardInputColor??(typeof oo?.color=="string"?oo.color:void 0)??xn?.colorText??"#262833",mc=v.cardInputPlaceholderColor??"#9ca3af",Vt=xn?.borderRadius??"8px",jr=xn?.borderRadius??v.cardButton?.borderRadius??Vt,$r=xn?.colorPrimary??"#4A49FF",yc=xn?.colorPrimaryHover??qo($r,.12),ri=xn?.colorText??"#262833",oi={fontSize:Ms,fontFamily:Bs,fontWeight:Fs,color:pc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Lo={marginTop:"0.375rem",...oi,fontSize:"0.75rem",lineHeight:1.4,color:As},fc={"--flopay-input-placeholder-color":mc,"--flopay-input-font-size":Ms,"--flopay-input-font-family":Bs,"--flopay-input-font-weight":String(Fs)},Oo=v.cardFormContainer??{},ai=Oo.padding??(Do?"0":"1rem"),ii=Oo.borderRadius??Vt,gc=ge&&ir?c(si,{capture:ge,html:ir.html,messageToken:ir.messageToken,expectedOrigin:ir.expectedOrigin,theme:Ve,submitLabel:_,onReady:()=>{if(!Se&&!te||typeof document>"u")return;let a=()=>{let j=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(j){Ln.current=!0;try{j.focus()}finally{Ln.current=!1}}};Gn.current||a()},onError:a=>he(a),onValidation:a=>{let b=_t.current;(b==="idle"||b==="validation-window")&&(he(a),a&&_t.current==="validation-window"&&(Xt.current&&(clearTimeout(Xt.current),Xt.current=null),_t.current="idle",et(null)))}}):c("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"}),Ds=ze("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&Cr()},style:{backgroundColor:ti,borderRadius:ii,...Oo,padding:ai,...fc,display:"flex",flexDirection:"column"},children:[c("style",{children:`
25
+ `,ha=44,Pa=180,ec=`flopay-card-enter ${Pa}ms cubic-bezier(0, 0, 0.2, 1) both`,tc=`flopay-card-exit ${Pa}ms cubic-bezier(0.4, 0, 0.2, 1) both`,xu=`flopay-buttons-enter ${Pa}ms cubic-bezier(0, 0, 0.2, 1) both`,Mu=`flopay-buttons-exit ${Pa}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Bu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function gs(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 Fu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Du(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 ss={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 Ou(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function nc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ls(e){return e==="paypal"?"PayPal":oo(e)}function Nu(e){let t=nu(e);return`Enter a valid ${is(e)}${t?` (e.g. ${t})`:""}`}function Lu(e,t,n){let r=au(e),o=t.trim(),i=n&&r,s=i&&!o,l=i&&!!o&&!iu(e,o);return{visible:n,supported:r,required:i,empty:s,malformed:l}}function zu(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!hn(n);return{required:t,empty:r,malformed:o,value:n}}function rc(e,t){return t instanceof pr?t:new pr(t instanceof Error?t.message:`${Ou(e)} before-click hook failed.`,"validation_error")}function as(){return u("style",{children:Au})}function Uu(e){return typeof e=="number"?`${e}px`:e}function fc(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function gc({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:Fe("div",{style:{position:"relative",minHeight:44},children:[u("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"}}),u("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 oc(e){return e!=="unavailable"&&e!=="load_error"}function hs(e){return u(ju,{...e})}function ac({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:m,onTechnicalFailure:y,runBeforeButtonClick:b,billingName:g,onBuyerIdentityReady:F,onLoadStateChange:M,placeholderBorderRadius:w,popupCapabilityOwner:v,externalTelemetryContext:U,presentationMode:ue}){let E=Kr(),{emitInstrument:J}=Fo(Qn),K=us(),se=ds(),G=vt(()=>ti(cn(E),U),[U,E]),[xe,Ye]=ae("loading");bt(()=>{M?.(xe)},[xe,M]);let[be,et]=ae(!1),It=re(!1),pe=!hn(n?.trim())||!g?.trim(),{request:De,collect:_t,finish:Re}=wo(),Oe=re(!1),he=re(null),le=re(null),[Ne,Je]=ae(0),[pt,D]=ae(!1),qe=re(!1),ce=re(new Map),{startAttempt:O,finishAttempt:$e,invalidateAttempt:Ke,isAttemptInvalidated:Ve,isAttemptCurrent:V,generationRef:tt}=la((T,ye,Me)=>{y?.(T,ye,{...Me,popupBlocked:Me?.popupBlocked??$r(ye),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:ue,terminalReason:"overlay_timeout"}),D(!0),Je(L=>L+1)},{onHandoffObserved:()=>{v.markAvailable(),G?.log({name:"provider.popup.opened",stage:"overlay_open",...ur,attempt:tt.current})}});bt(()=>{pt&&le.current?.focus()},[pt,Ne]);let nt=Ge(()=>{Je(T=>T+1)},[]),_e=Ge((T,ye,Me)=>{Ke(Me),y?.("paypal",T,{code:ye,popupBlocked:$r(T),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:ue}),D(!0),nt()},[Ke,y,ue,nt]),Pe=Ge(()=>{window.setTimeout(()=>{(he.current?.querySelector("iframe")??he.current)?.focus()},0)},[]);bt(()=>{qe.current&&(qe.current=!1,Pe())},[Pe,Ne]);let He=Ge(()=>{D(!1),i?.(null),Pe()},[Pe,i]);bt(()=>{if(!K||Oe.current)return;let[T,ye,Me]=ys();if(!T||!ye)return;let L=yc(ye);if(!L)return;Oe.current=!0;let ze=!0,Ct=fa.get(ye);Ct||(Ct=Me==="failed"?Promise.resolve(null):Promise.resolve().then(()=>K.retrievePaymentIntent(ye)),fa.set(ye,Ct));let Ue={accountPatch:L.accountPatch,sessionId:L.sessionId,nonce:L.nonce},c=()=>{G?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...ur,requestCategory:"provider_sdk"})};return G?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...ur}),(async()=>{try{et(!0);let N=await Ct;if(!ze)return;if(N?.error){fa.delete(ye),c(),i?.(N.error.message??"Failed to retrieve PayPal payment status.");return}if(Iu(),fa.delete(ye),Me==="failed"){let j="PayPal payment was declined. Please try again.";G?.terminal({outcome:"payment_declined",...ur,terminalReason:"provider_declined"}),i?.(j),m?.(ln("paypal",j));return}let h=N?.paymentIntent;if(h&&h.id!==T){c(),i?.("Failed to match the returned PayPal payment.");return}if(h&&(h.status==="requires_capture"||h.status==="succeeded")){let j=typeof h.payment_method=="string"?h.payment_method:h.payment_method?.id;o({id:j??h.id,type:"card",threeDSecureActionResultTokenId:h.id,isPaypal:!0},{...Ue,presentationMode:"redirect"})}else{let j="PayPal payment was not completed. Please try again.";G?.terminal({outcome:h?.status==="canceled"?"payment_cancelled":"payment_declined",...ur,terminalReason:h?.status==="canceled"?"cancelled":"provider_declined"}),i?.(j),m?.(ln("paypal",j))}}catch(N){if(!ze)return;fa.delete(ye),c(),i?.(N instanceof Error?N.message:"Failed to complete PayPal payment.")}finally{ze&&et(!1)}})(),()=>{ze=!1,Oe.current=!1}},[K,o,i,m,G]);let ft=Ge(async(T=!1)=>{let ye=b?await b("paypal"):{proceed:!0};if(!ye.proceed)return ce.current.delete(Ne),!1;let Me=O("paypal");return ce.current.set(Ne,{generation:Me,accountPatch:ye.accountPatch,sessionId:ye.sessionId,nonce:ye.nonce}),D(!1),G?.log({name:`provider.${T?"redirect.started":"handoff.requested"}`,stage:T?"redirect":"overlay_open",...ur,attempt:Me}),l?.("paypal"),!0},[l,G,b,O,Ne]),Le=Ge(async T=>{if(s||be||!await ft()){T.reject();return}T.resolve()},[s,ft,be]),en=Ge(async T=>{if(!K||!se)return;let ye=ce.current.get(Ne);if(ye&&!V(ye.generation)){ce.current.delete(Ne);return}if(!ye&&Ve()||ye&&!$e(ye.generation))return;ye||$e();let Me=ye??null;if(ce.current.delete(Ne),!Me&&b){let A=await b("paypal");if(!A.proceed){T.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Me={accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}}let L=Me?.sessionId??e,ze=Me?.nonce??t,Ct=await Tu({event:T,prepared:Me,email:n,billingName:g,methodLabel:"PayPal",collect:_t});if(!Ct){T.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ue=Ct.email,c={...Me?.accountPatch,...Fn(Ct,!0)};try{if(et(!0),i?.(null),!L||!hn(Ue))throw new Error("Missing sessionId or email for PayPal payment");await F?.(Ct);let A=K.createPaymentMethod,{error:N,paymentMethod:h}=await A({type:"paypal"});if(N){_e(N,"stripe_paypal_create_payment_method_failed",ye?.generation),T.paymentFailed({reason:"fail"});return}let j=await ai(r,J,L,ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:h?.id??null,intentKind:"payment"});if(j.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ae=j.clientSecret,me={return_url:ms()};if(h?.id&&(me.payment_method=h.id),!Ut(ga,{clientSecret:Ae,sessionId:L,nonce:ze,accountPatch:c})&&ue==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:Xe,paymentIntent:oe}=await K.confirmPayment({clientSecret:Ae,confirmParams:me,redirect:"if_required"});if(Xe){if(Ut(ga),oa(Xe)){let Rt=Xe.message??"Your payment was declined.";G?.terminal({outcome:"payment_declined",...ur,terminalReason:"provider_declined"}),i?.(Rt),m?.(ln("paypal",Rt,{code:Ir(Xe),declineCode:ko(Xe)})),await ii({billingApiUrl:r,sessionId:L,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ir(Xe)??"provider_declined"}})}else _e(Xe,"stripe_paypal_confirm_failed",ye?.generation);return}Ut(ga);let ct=typeof oe?.payment_method=="string"?oe.payment_method:oe?.payment_method?.id;o({id:ct??oe?.id,type:"card",threeDSecureActionResultTokenId:oe?.id,isPaypal:!0},{accountPatch:c,paymentMethodCategory:"paypal",presentationMode:ue,sessionId:L,nonce:ze});return}catch(A){_e(A,"stripe_paypal_failed",ye?.generation)}finally{et(!1)}},[K,se,e,t,n,g,_t,F,r,J,o,i,m,b,_e,$e,V,Ve,G,ue,Ne]),jt=Ge(async()=>{if(!(It.current||s||be||!K||!se)){It.current=!0,et(!0);try{if(!await ft(!0))return;await en({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{It.current=!1,et(!1)}}},[se,en,s,ft,K,be]),lt=ue==="redirect"?u("button",{type:"button",disabled:s||be,onClick:()=>{jt()},style:{width:"100%",minHeight:ha,border:"1px solid #d1d5db",borderRadius:w??8,background:"#ffc439",color:"#111827",cursor:s||be?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):u(lc,{onReady:T=>Ye(fc(T,["paypal"])),onLoadError:()=>{Ye("load_error"),fs(G,"paypal","paypal","provider_error")},onClick:Le,onConfirm:en,onCancel:()=>{let T=ce.current.get(Ne);ce.current.delete(Ne),G?.terminal({outcome:"payment_cancelled",...ur,terminalReason:"cancelled",...T?{attempt:T.generation}:{}}),Ke(T?.generation),D(!1),qe.current=!0,nt()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:pe,emailRequired:pe,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},Ne),it=Fe(ro,{children:[Fe("div",{ref:he,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[pt&&u("button",{ref:le,type:"button","data-testid":"flopay-paypal-retry-button",onClick:He,style:ss,children:"Try PayPal again"}),De&&u(So,{identity:De.identity,methodLabel:De.methodLabel,onComplete:Re,onCancel:()=>Re(null)},De.id),u("div",{style:{display:De?"none":void 0},children:lt})]}),be&&!De&&u(kr,{status:"processing"})]});return ue==="redirect"?it:u(gc,{state:xe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:it})}function ic({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:m,onDecline:y,onTechnicalFailure:b,runBeforeButtonClick:g,billingName:F,onBuyerIdentityReady:M,onLoadStateChange:w,placeholderBorderRadius:v,popupCapabilityOwner:U,externalTelemetryContext:ue}){let E=Kr(),{emitInstrument:J}=Fo(Qn),K=us(),se=ds(),G=vt(()=>ti(cn(E),ue),[ue,E]),[xe,Ye]=ae("loading");bt(()=>{w?.(xe)},[xe,w]);let[be,et]=ae(!1),It=re(!hn(n?.trim())||!F?.trim()).current,{request:pe,collect:De,finish:_t}=wo(),Re=re(null),Oe=re(null),[he,le]=ae(0),[Ne,Je]=ae(!1),[pt,D]=ae(()=>oi(e,t)?"blocked":"idle"),[qe,ce]=ae("google_pay"),O=re(null),$e=re(!0),Ke=re(!1),Ve=re("google_pay"),V=re("google_pay"),tt=re(null),nt=re(null),_e=re(new Set);bt(()=>($e.current=!0,()=>{$e.current=!1;for(let c of _e.current)window.clearTimeout(c);_e.current.clear()}),[]);let Pe=re(new Map),{startAttempt:He,finishAttempt:ft,invalidateAttempt:Le,isAttemptInvalidated:en,isAttemptCurrent:jt,generationRef:lt}=la((c,A,N)=>{b?.(c,A,{...N,popupBlocked:N?.popupBlocked??$r(A),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ce(c),Je(!0),le(h=>h+1)},{onHandoffObserved:c=>{U.markAvailable(),G?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:lt.current,...c==="apple_pay"||c==="google_pay"?{walletType:c}:{}})}});bt(()=>{Ne&&Oe.current?.focus()},[Ne,he]);let it=Ge(()=>{le(c=>c+1)},[]),T=Ge((c,A,N,h,j=!1)=>{Le(h),b?.(c,A,{code:N,popupBlocked:$r(A),telemetryReported:j,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ce(c),Je(!0),it()},[Le,b,it]),ye=Ge(()=>{window.setTimeout(()=>{(Re.current?.querySelector("iframe")??Re.current)?.focus()},0)},[]);bt(()=>{Ke.current&&(Ke.current=!1,ye())},[ye,he]);let Me=Ge(()=>{Je(!1),l?.(null),ye()},[ye,l]),L=Ge(()=>{O.current?.()},[]);bt(()=>{let c=oi(e,t);if(!c)return;let A=!1,N=!1,h=async()=>{if(!N){N=!0,A||D("checking");try{let j=await Zl(K,c.clientSecret,_e.current);if(A)return;let Ae=rs(j,c.providerObjectId,es(c.clientSecret));if(Ae.kind==="confirmed"){if(!Xl(e,t,c.clientSecret))return;O.current=null,D("idle"),s({id:Ae.paymentMethodId,type:"card",threeDSecureActionResultTokenId:Ae.intentId},{...c.accountPatch?{accountPatch:c.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(Ae.kind==="terminal"){ns(e,t,c.clientSecret),O.current=null,D("idle"),ce(c.paymentMethodType),Je(!0),it();return}D("blocked")}catch{A||D("blocked")}finally{N=!1}}};return O.current=h,D("blocked"),()=>{A=!0,O.current===h&&(O.current=null)}},[t,s,it,e,K]);let ze=Ge(async c=>{let A=!1,N=fe=>{A||(A=!0,c.paymentFailed({reason:"fail",...fe?{message:fe}:{}}))};if(!K||!se){N();return}let h=Pe.current.get(he);if(h&&!jt(h.generation)){Pe.current.delete(he),N();return}if(!h&&en()){N();return}if(h&&!ft(h.generation)){N();return}h||ft();let j=c.expressPaymentType??h?.method??Ve.current,Ae=h??null,me=nc(j),rt;j==="apple_pay"?rt="apple_pay":j==="google_pay"&&(rt="google_pay");let Xe=h?.generation??lt.current,oe=G,ct=oe?.now()??globalThis.performance?.now()??Date.now(),Rt=new AbortController,Pn=!1,Ze=!1,$t=null,Ee=e,Dn="processing",Rn="other",Mt="provider_runtime",kn,On=new Promise((fe,gt)=>{kn=gt}),Nn=window.setTimeout(()=>{Pn=!0,Rt.abort(),kn(ni)},Pu),tn=async(fe,gt,Et)=>{Dn=fe,Rn=gt,Mt=gt==="intent_create"||gt==="session_claim"?"transport_error":"provider_runtime";let vn=oe?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Et,On])}finally{let Bt=oe?.now()??globalThis.performance?.now()??Date.now();oe?.performance({stage:fe,durationMs:Math.max(0,Bt-vn),durationMode:"machine",requestCategory:gt,paymentMethodCategory:"wallet",provider:"stripe",...Pn?{statusClass:"timeout"}:{}})}};try{if(et(!0),l?.(null),!Ae&&g){let Ce=await tn("processing","other",g(me));if(!Ce.proceed){N();return}Ae={accountPatch:Ce.accountPatch,sessionId:Ce.sessionId,nonce:Ce.nonce}}let fe=Ae?.sessionId??e;Ee=fe;let gt=Ae?.nonce??t,Et=tt.current??Ae?.accountPatch,vn=mc({event:c,fallbackEmail:Et?.email??n,fallbackName:[Et?.firstName,Et?.lastName].join(" ").trim()||F});if(!hn(vn.email)){N("Buyer details are required."),De(ls(j),vn).then(Ce=>{Ce&&(tt.current=Ce)});return}tt.current=null;let Bt={...Ae?.accountPatch,...Fn(vn,!0)};await tn("processing","session_claim",Promise.resolve(M?.(vn)));let{error:Kn}=await tn("tokenization","provider_sdk",se.submit());if(Kn){N(),T(j,Kn,"stripe_wallet_submit_failed",h?.generation);return}if(!fe)throw new Error("Missing sessionId or email for payment.");let dn={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:j,paymentMethodId:null,intentKind:o},Kt=JSON.stringify({sessionId:fe,nonce:gt??"",request:dn}),on=nt.current,Vn=on?.retryIdentity===Kt?on.authorizationAttemptId:cu();nt.current={authorizationAttemptId:Vn,retryIdentity:Kt};let un=await tn("processing","intent_create",ai(r,J,fe,gt??"",{...dn,authorizationAttemptId:Vn},{signal:Rt.signal}));if(un.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ht=un.clientSecret,Jt=Cu({createdAt:Date.now(),sessionId:fe,...gt?{nonce:gt}:{},clientSecret:ht,providerObjectId:un.providerObjectId,paymentMethodType:j,accountPatch:Bt});window.clearTimeout(Nn),Ze=!0,oe?.performance({stage:"callback",durationMs:Math.max(0,(oe?.now()??globalThis.performance?.now()??Date.now())-ct),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let pn=oe?.now()??globalThis.performance?.now()??Date.now(),Dt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...rt?{walletType:rt}:{},attempt:Xe},Xt=!1,Vt=null;oe?.log({name:"payment.provider_confirmation.started",...Dt}),$t=window.setTimeout(()=>{$t!==null&&_e.current.delete($t),Xt=!0;let Ce=oe?.now()??globalThis.performance?.now()??Date.now();oe?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Dt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Ce-pn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),oe?.flush?.().catch(()=>{}),Vt?.()},vu),_e.current.add($t);let yn=(Ce,mt)=>{$t!==null&&(window.clearTimeout($t),_e.current.delete($t),$t=null);let X=oe?.now()??globalThis.performance?.now()??Date.now(),I=Math.max(0,X-pn),je=Ce;Xt&&(Ce==="resolved"?je="resolved_late":Ce==="returned_error"?je="returned_error_late":je="rejected_late");let Z=mt??(Ce==="resolved"?"approved":"provider_error");return oe?.log({name:"payment.provider_confirmation.returned",...Dt,operationOutcome:je,terminalReason:Z}),oe?.performance({...Dt,durationMs:I,durationMode:"buyer",operationOutcome:je,terminalReason:Z}),{durationMs:I,operationOutcome:je,terminalReason:Z}},yt=!1,H=!1,Ln=Ce=>{if(!Ce||typeof Ce!="object")return null;let mt=Ce;if(mt.error)return null;let X=mt.setupIntent??mt.paymentIntent,I=rs(X??null,void 0,!!mt.setupIntent);return I.kind==="confirmed"?I:null},zn=Ce=>{if(yt||h&&lt.current!==h.generation)return;let mt=Ln(Ce);if(!mt)return;if(Jt&&!Xl(fe,gt,ht)){yt=!0;return}let{intentId:X,paymentMethodId:I}=mt;yt=!0,H=!0,nt.current=null,O.current=null,$e.current&&(D("idle"),et(!1));let je=`${cc}:${fe}`;Ut(je,{createdAt:Date.now(),sessionId:fe,nonce:gt,accountPatch:Bt,paymentMethodId:I,providerIntentId:X,paymentMethodType:j});try{s({id:I,type:"card",threeDSecureActionResultTokenId:X},{accountPatch:Bt,paymentMethodCategory:"wallet",sessionId:fe,nonce:gt})}finally{Ut(je)}},mr=!1;Vt=async()=>{if(!(mr||yt||H)){mr=!0,$e.current&&D("checking");try{let Ce=await Zl(K,ht,_e.current);if(yt||H)return;let mt=es(ht),X=rs(Ce,un.providerObjectId,mt);if(X.kind==="confirmed"){zn(mt?{setupIntent:Ce}:{paymentIntent:Ce});return}if(X.kind==="terminal"){if(H=!0,ns(fe,gt,ht),nt.current=null,O.current=null,!$e.current)return;D("idle"),N(),T(j,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",h?.generation,!0);return}$e.current&&!H&&(D("blocked"),et(!1))}catch{$e.current&&!H&&(D("blocked"),et(!1))}finally{mr=!1}}},O.current=Vt;let bn,an;try{let Ce=await(es(ht)?K.confirmSetup({elements:se,clientSecret:ht,redirect:"if_required"}):K.confirmPayment({elements:se,clientSecret:ht,redirect:"if_required"}));if(!Ce||typeof Ce!="object"||(bn=Ce,!bn.error&&!Ln(bn)))throw ts;an=yn(bn.error?"returned_error":"resolved",bn.error&&oa(bn.error)?"provider_declined":void 0)}catch(Ce){let mt=Ce===ts,X=yn(mt?"returned_error":"rejected");if(oe?.error({...mt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:Bi(Ce),...Dt,operationOutcome:X.operationOutcome,durationMs:X.durationMs,statusClass:"unknown",terminalReason:X.terminalReason}),!$e.current||yt)return;await Vt?.();return}let En=bn.error;if(En){if(!$e.current||yt)return;if(oa(En)){H=!0,ns(fe,gt,ht),nt.current=null,O.current=null,D("idle");let Ce=En.message??"Your payment was declined.";N(Ce),l?.(Ce),y?.(ln(me,Ce,{code:Ir(En),declineCode:ko(En)})),ii({billingApiUrl:r,sessionId:fe,nonce:gt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:j,providerDeclineReason:Ir(En)??"provider_declined",...un.intentKind==="payment"&&un.providerObjectId.startsWith("pi_")?{providerIntentId:un.providerObjectId}:{}}})}else oe?.error({...Bi(En),...Dt,operationOutcome:an.operationOutcome,durationMs:an.durationMs,statusClass:"unknown",terminalReason:an.terminalReason}),await Vt?.();return}if(zn(bn),!yt)throw new Error("Invalid provider returned for APM intent")}catch(fe){if(fe===ni){let gt=oe?.now()??globalThis.performance?.now()??Date.now();oe?.error({errorCode:Su(Rn),stage:Dn,requestCategory:Rn,paymentMethodCategory:"wallet",provider:"stripe",...rt?{walletType:rt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ee,durationMs:Math.max(0,gt-ct),statusClass:"timeout",failureCategory:Mt,attempt:Xe,terminalReason:"provider_error"}),oe?.flush?.().catch(()=>{})}N(),T(j,fe,fe===ni?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",h?.generation,fe===ni)}finally{if(window.clearTimeout(Nn),$t!==null&&(window.clearTimeout($t),_e.current.delete($t)),!Ze){let fe=oe?.now()??globalThis.performance?.now()??Date.now();oe?.performance({stage:"callback",durationMs:Math.max(0,fe-ct),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Pn?{statusClass:"timeout"}:{}})}$e.current&&et(!1)}},[K,se,e,t,n,F,De,M,r,J,o,s,l,y,g,T,ft,jt,en,lt,G,he]),Ct=vt(()=>{let c=["applePay","googlePay","paypal","link","amazonPay","klarna"],A=new Set(["applePay","googlePay"]),N=new Set(i.map(Yl)),h={};for(let j of c)N.has(j)?h[j]=A.has(j)?"always":"auto":h[j]="never";return h},[i]),Ue=vt(()=>i.map(Yl),[i]);return Fe(ro,{children:[u(gc,{state:xe,placeholderTestId:"flopay-wallet-placeholder",borderRadius:v,children:Fe("div",{ref:Re,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Ne&&Fe("button",{ref:Oe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Me,style:ss,children:["Try ",ls(qe)," again"]}),pt!=="idle"&&Fe("div",{role:"status","aria-live":"polite",children:[u("p",{children:"We are still confirming your payment. Check its status before trying again."}),u("button",{type:"button",onClick:L,disabled:pt==="checking",style:ss,children:pt==="checking"?"Checking payment status\u2026":"Check payment status"})]}),pe&&u(So,{identity:pe.identity,methodLabel:pe.methodLabel,onComplete:_t,onCancel:()=>_t(null)},pe.id),pt==="idle"&&u("div",{style:{display:pe?"none":void 0},children:u(lc,{onReady:c=>{Ye(fc(c,Ue))},onLoadError:c=>{Ye("load_error"),fs(G,"stripe","wallet","provider_error")},onClick:async c=>{Ve.current=c.expressPaymentType,V.current=nc(c.expressPaymentType);let A=!0,N=window.setTimeout(()=>{A=!1,c.reject()},hu),h=g?await g(V.current):{proceed:!0};if(window.clearTimeout(N),!A)return;if(!h.proceed){Pe.current.delete(he),c.reject();return}let j=He(c.expressPaymentType);Pe.current.set(he,{generation:j,method:c.expressPaymentType,accountPatch:h.accountPatch,sessionId:h.sessionId,nonce:h.nonce}),Je(!1),G?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:j,...c.expressPaymentType==="apple_pay"||c.expressPaymentType==="google_pay"?{walletType:c.expressPaymentType}:{}}),m?.(V.current),c.resolve()},onConfirm:ze,onCancel:()=>{let c=Pe.current.get(he);Pe.current.delete(he),G?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...c?{attempt:c.generation}:{}}),Le(c?.generation),nt.current=null,Je(!1),Ke.current=!0,it()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ct,emailRequired:It,billingAddressRequired:It,layout:{maxColumns:1,overflow:"never"}}},he)})]})}),be&&u(kr,{status:"processing"})]})}function hc(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function qu({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:s,backgroundColor:l,borderColor:m,textColor:y,borderRadius:b,fontFamily:g}){let F=pu(e,t),M=Hl[e],[w,v]=ae(!1),U=!!M&&!w,ue=F?.backgroundColor??l??"#ffffff",E=F?.borderColor??m??"#d1d5db",J=F?.textColor??y??"#262833";return u("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&s()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ha,padding:"0 1rem",backgroundColor:ue,color:J,border:`1px solid ${E}`,borderRadius:b??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?u("span",{style:{margin:"0 auto"},children:`Connecting to ${oo(e)}\u2026`}):Fe(ro,{children:[Fe("span",{style:{display:"inline-flex",alignItems:"center",gap:ou(e)?8:0},children:[U?u("img",{src:M,alt:"","aria-hidden":"true",onError:()=>v(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!U&&F?.logoSvg?u("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:F.logoSvg}}):null,u("span",{children:oo(e)})]}),i&&u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:J,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:u("path",{d:"M9 18l6-6-6-6"})})]})})}function cs({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:m,onDecline:y,onCancel:b,runBeforeButtonClick:g,onButtonClick:F,isProcessing:M,submitButtonColor:w,submitButtonBorderRadius:v,submitButtonStyle:U,errorText:ue}){let E=Kr(),{emitInstrument:J}=Fo(Qn),K=us(),se=ds(),[G,xe]=ae(!1),Ye=re(!1),[be,et]=ae(!1),[It,pe]=ae("loading"),[De,_t]=ae(""),Re=!hn(r?.trim()),Oe=!Re||hn(De.trim()),he=Ge(async()=>{if(!K||!se||M||Ye.current||!be)return;Ye.current=!0,xe(!0);let le=g?await g("card"):{proceed:!0};if(!le.proceed){Ye.current=!1,xe(!1);return}F?.("card");let Ne=le.sessionId??t,Je=le.nonce??n,pt=Qr(o?.trim()),D=Fn({email:le.accountPatch?.email?.trim()||r?.trim()||De.trim(),firstName:le.accountPatch?.firstName?.trim()||pt.firstName,lastName:le.accountPatch?.lastName?.trim()||pt.lastName}),qe=D.email,ce=Fn({...le.accountPatch,...D});try{if(m?.(null),!hn(qe))throw new Error("A valid email address is required for payment.");await i?.(D);let O=await se.submit();if(O.error){m?.(O.error.message??"Payment failed.");return}let $e=[D.firstName,D.lastName].filter(Boolean).join(" "),Ke=await K.createPaymentMethod({elements:se,params:{billing_details:{email:qe,...$e?{name:$e}:{}}}});if(Ke.error||!Ke.paymentMethod){m?.(Ke.error?.message??"Failed to create payment method.");return}let Ve=Ke.paymentMethod;if(!Ne||!qe)throw new Error("Missing sessionId or email for payment.");let V=Ve.type||e,tt=await ai(s,J,Ne,Je??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:V,paymentMethodId:null,intentKind:"payment"});if(tt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let nt=tt.clientSecret;Ut(Er,{clientSecret:nt,sessionId:Ne,nonce:Je,accountPatch:ce,paymentMethodId:Ve.id,paymentMethodType:Ve.type??e,gateway:"stripe"});let{error:_e,paymentIntent:Pe}=await K.confirmPayment({clientSecret:nt,confirmParams:{return_url:window.location.href,payment_method:Ve.id},redirect:"if_required"});if(_e){Ut(Er);let Le=_e.message??"Payment failed.";m?.(Le),y?.(ln("card",Le,{code:_e.code})),await ii({billingApiUrl:s,sessionId:Ne,nonce:Je,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:_e.code??"provider_declined"}});return}let He=Pe?.status;if(!ta(He)){Ut(Er);let Le=He==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(Le),y?.(ln("card",Le,{code:He??"missing_payment_intent"}));return}Ut(Er);let ft=typeof Pe?.payment_method=="string"?Pe.payment_method:Pe?.payment_method?.id;l({id:ft??Ve.id,type:"card",threeDSecureActionResultTokenId:Pe?.id,gateway:"stripe",paymentMethodType:Ve.type??e},{accountPatch:ce,paymentMethodCategory:"apm",sessionId:Ne,nonce:Je})}catch(O){m?.(O instanceof Error?O.message:"Payment failed. Please try again.")}finally{Ye.current=!1,xe(!1)}},[K,se,M,be,g,F,t,n,r,o,De,i,s,J,e,l,m,y]);return Fe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Re&&u("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Re&&Fe("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",u("input",{type:"email",autoComplete:"email",required:!0,value:De,onChange:le=>_t(le.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),u(mu,{onReady:()=>pe("ready"),onLoadError:()=>{pe("load_error"),fs(cn(E),"stripe","apm")},onChange:le=>{et(!!le.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...hn(r?.trim())?{email:r?.trim()}:{}}}}}),u("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{he()},disabled:!be||!Oe||G||M||It!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:w,color:"white",border:"none",borderRadius:v,fontSize:"1rem",fontWeight:600,cursor:!be||!Oe||G||M||It!=="ready"?"not-allowed":"pointer",opacity:!be||!Oe||G||M||It!=="ready"?.5:1,transition:"opacity 120ms ease-out",...U??{}},children:G?"Processing\u2026":`Pay with ${oo(e)}`}),ue&&u(_o,{margin:"0.75rem 0 0",children:ue})]})}function sc({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:m,onTokenizedBody:y,onErrorChange:b,onButtonClick:g,onDecline:F,runBeforeButtonClick:M,onLoadStateChange:w,isProcessing:v=!1,submitButtonColor:U="#4A49FF",submitButtonBorderRadius:ue=8,submitButtonStyle:E,buttonAppearance:J,themeId:K,onExpandApm:se,expandedApmMethod:G}){let{emitInstrument:xe}=Fo(Qn),[Ye,be]=ae(null),[et,It]=ae(null),pe=re(!1),{request:De,collect:_t,finish:Re}=wo();bt(()=>{s.length>0&&l?w?.("ready"):l||w?.("loading")},[s.length,l,w]);let Oe=Ge(async D=>{if(!l||pe.current||v)return;pe.current=!0,It(D);let qe=M?await M("card"):{proceed:!0};if(!qe.proceed){pe.current=!1,It(null);return}g?.("card");let ce=qe.sessionId??e,O=qe.nonce??t,$e=Qr([qe.accountPatch?.firstName,qe.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ke=Fn({email:qe.accountPatch?.email?.trim()||n?.trim(),firstName:qe.accountPatch?.firstName?.trim()||$e.firstName,lastName:qe.accountPatch?.lastName?.trim()||$e.lastName});if(!hn(Ke.email)){It(null);let tt=await _t(oo(D),Ke);if(!tt){pe.current=!1;return}Ke=tt,It(D)}let Ve=Ke.email,V=Fn({...qe.accountPatch,...Ke});try{if(b?.(null),!ce||!hn(Ve))throw new Error("Missing sessionId or email for payment.");await o?.(Ke);let tt=await ai(i,xe,ce,O??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:D,paymentMethodId:null,intentKind:"payment"});if(tt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let nt=tt.clientSecret;Ut(Er,{clientSecret:nt,sessionId:ce,nonce:O,accountPatch:V,paymentMethodType:D,gateway:"stripe"});let{error:_e,paymentIntent:Pe}=await l.confirmPayment({clientSecret:nt,confirmParams:{return_url:window.location.href,payment_method_data:{type:D,billing_details:{name:[Ke.firstName,Ke.lastName].filter(Boolean).join(" "),...Ve?{email:Ve}:{}}}},redirect:"if_required"});if(_e){Ut(Er);let Le=_e.message??"Payment failed.";b?.(Le),F?.(ln("card",Le,{code:_e.code})),await ii({billingApiUrl:i,sessionId:ce,nonce:O,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:D,providerDeclineReason:_e.code??"provider_declined"}});return}let He=Pe?.status;if(!ta(He)){Ut(Er);let Le=He==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";b?.(Le),F?.(ln("card",Le,{code:He??"missing_payment_intent"}));return}Ut(Er);let ft=typeof Pe?.payment_method=="string"?Pe.payment_method:Pe?.payment_method?.id;y({id:ft??Pe?.id,type:"card",threeDSecureActionResultTokenId:Pe?.id,gateway:"stripe",paymentMethodType:D},{accountPatch:V,paymentMethodCategory:"apm",sessionId:ce,nonce:O})}catch(tt){b?.(tt instanceof Error?tt.message:"Payment failed. Please try again.")}finally{pe.current=!1,It(null)}},[l,v,M,g,e,t,n,_t,i,xe,r,o,y,b,F]),[he,le]=ae(null),Ne=se?G??null:he,Je=Ge(D=>{pe.current||v||Ne&&Ne!==D||(Gl(D)?se?se(D):le(D):Oe(D))},[Ne,v,Oe,se]),pt=vt(()=>he?hc(m,he):null,[he,m]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:De?u(So,{identity:De.identity,methodLabel:De.methodLabel,onComplete:Re,onCancel:()=>Re(null)},De.id):s.map(D=>{let qe=G===D,ce=et===D,O=et!==null&&et!==D||G!=null&&G!==D;return Fe(fu.Fragment,{children:[u(qu,{method:D,themeId:K,submitting:ce,disabled:O,highlighted:qe,hasNextStep:Gl(D),onClick:()=>Je(D),backgroundColor:J?.backgroundColor,borderColor:J?.borderColor,textColor:J?.textColor,borderRadius:J?.borderRadius,fontFamily:J?.fontFamily}),!se&&he===D&&pt&&l&&u(no,{stripe:l,options:pt,children:u(cs,{method:D,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:y,onErrorChange:b,onDecline:F,onCancel:()=>le(null),runBeforeButtonClick:M,onButtonClick:g,isProcessing:v,submitButtonColor:U,submitButtonBorderRadius:ue,submitButtonStyle:E})},D)]},D)})})}function ju({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:i,onComplete:s,onError:l,onDecline:m,onTokenizedBody:y,firstName:b,lastName:g,chv:F,className:M,submitLabel:w,isProcessing:v,error:U,onErrorChange:ue,showPayPal:E=!0,showStripe:J=!0,walletPresentation:K="auto",enabledPaymentMethods:se,enabledPaymentMethodCountries:G,showApplePay:xe=!0,showGooglePay:Ye=!0,layout:be="default",theme:et,buttonsTheme:It,buttonsStyles:pe,appearance:De,cardButtonContent:_t,cardBackButtonContent:Re,cardTitleContent:Oe,showSecurityFooter:he,onButtonClick:le,onBeforeButtonClick:Ne,onBuyerIdentityReady:Je,enableAVS:pt,cardFieldOrder:D,cardPreFormSlot:qe,avsLayout:ce="row",country:O,zip:$e,addressLine1:Ke,addressLine2:Ve,city:V,state:tt,onCountryChange:nt,onZipChange:_e,avsCheck:Pe,checkoutType:He,checkoutLayout:ft,totalAmount:Le=0,currency:en="usd",initialCardOpen:jt=!1,directPaypal:lt,isSubscription:it=!1,session:T,dataAttachmentPending:ye=!1,dataAttachmentRequiresIdentity:Me=!1,debug:L=!1}){let ze=Kr(),Ct=Di(),Ue=Fo(dr),{emitInstrument:c}=Fo(Qn),A=re(null);A.current||(A.current=ja());let N=A.current,[,h]=ae(0),j=re(null);j.current||(j.current=aa());let Ae=j.current,me=vt(()=>({browser:Ae,capability:N,presentationMode:"popup"}),[Ae,N]),rt=T??Ue.session,Xe=rt?.gateways?.paypal?.providerObjectType??lt?.providerObjectType,oe=ye||Ue.claimPending===!0,ct=Me||Ue.claimRequiresIdentity===!0,Rt=oe&&!ct,Pn=Tl(),Ze=n||Pn,[$t,Ee]=ae(!1),[Dn,Rn]=ae(null),[Mt,kn]=ae(O??""),[On,Nn]=ae($e??""),[tn,fe]=ae(Ke??""),[gt,Et]=ae(Ve??""),[vn,Bt]=ae(V??""),[Kn,dn]=ae(tt??""),[Kt,on]=ae(""),[Vn,un]=ae({}),ht=re($e??""),Jt=re(O??""),pn=re(Ke??""),Dt=re(Ve??""),Xt=re(V??""),Vt=re(tt??""),yn=re(""),yt=re({});bt(()=>{let a=(f,q,Se,W,ge)=>{if(yt.current[f])return;let Yt=q?.trim();!Yt||Yt===Se.current||(Se.current=Yt,W(Yt),ge?.(Yt))};a("country",O,Jt,kn,nt),a("zip",$e,ht,Nn,_e),a("addressLine1",Ke,pn,fe),a("addressLine2",Ve,Dt,Et),a("city",V,Xt,Bt),a("state",tt,Vt,dn)},[O,$e,Ke,Ve,V,tt,nt,_e]);let H=vt(()=>du(pt),[pt]),Ln=H!==null,zn=vt(()=>Qi(T),[T]),mr=!!T?.vault?.html,bn=!!T?.gateways?.pcivault,an=Ai(T),Ce=!!(T?.gateways?.stripe?.enabledPaymentMethods??se)?.includes("card")||Ur(T),mt=mr||Ce||bn,X=!!(J&&mt&&e),[I,je]=ae(()=>be!=="buttons"||jt?e??null:null),[Z,Hn]=ae(0),mn=be!=="buttons"||jt||!!e&&I===e,Ht=T?.captureMethod,Wn=re(ze);bt(()=>{Wn.current=ze},[ze]);let[Qe,Lr]=ae(null);bt(()=>{if(!X||!e||!mn){Lr(null);return}let a=Wn.current?Wn.current.cardCapture({sessionId:e,captureMethod:Ht}):new Xd({sessionId:e,captureMethod:Ht,billingApiUrl:Ze,telemetry:r});return Lr({sessionId:e,captureMethod:Ht,billingApiUrl:Ze,telemetry:r,capture:a}),()=>{a.unmount()}},[X,e,mn,Ht,Ze,r]);let Wt=X&&e&&mn&&Qe?.sessionId===e&&Qe.captureMethod===Ht&&Qe.billingApiUrl===Ze&&Qe.telemetry===r?Qe.capture:null,fn=vt(()=>{let a=Mt,f=H?at(H.postal_code,a):!1;return Lu(a,On,f)},[H,Mt,On]),{avsInvalid:Ar,invalidAvsFields:xr}=vt(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!X||!H)return{avsInvalid:!1,invalidAvsFields:a};let f=Mt,q=(ge,Yt)=>at(ge,f)&&!Yt.trim(),Se={line1:q(H.address_line_1,tn),city:q(H.city,vn),state:q(H.state,Kn),zip:fn.empty||fn.malformed};return{avsInvalid:Se.line1||Se.city||Se.state||Se.zip,invalidAvsFields:Se}},[X,H,Mt,tn,vn,Kn,fn]),[Tn,Zt]=ae(!1),[fr,An]=ae(!1),[Mr,xn]=ae(!1),[gr,hr]=ae({line1:!1,city:!1,state:!1}),tr=re(!1),Gn=re({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Yn=re(!1),At=Ge(a=>{Gn.current[a]=!0,Yn.current=!0},[]),nr=Ge(a=>!tr.current&&Gn.current[a],[]),In=Ge(a=>{nr(a)&&hr(f=>f[a]?f:{...f,[a]:!0})},[nr]),[Jn,Pr]=ae(()=>os(T?.vault)),[st,nn]=ae(jt&&mt?"card":"buttons"),[Qt,Br]=ae(null),Un=st==="expanding"||st==="card",zr=T?.gateways?.stripe&&!an?"stripe":void 0,rr=Ge(()=>{c?.({class:"card_surface",provider:zr})},[zr,c]),or=re(null),gn=Ge(a=>{or.current&&clearTimeout(or.current),or.current=setTimeout(()=>{or.current=null,a()},Pa)},[]);bt(()=>()=>{or.current&&clearTimeout(or.current)},[]);let ar=Ge(()=>{rr(),je(e??null),Hn(a=>a+1),nn("expanding"),gn(()=>nn("card"))},[gn,rr,e]),Fr=Ge(()=>{nn("collapsing"),gn(()=>nn("buttons"))},[gn]),_n=Ge(a=>{Br(a),nn("apm-expanding"),gn(()=>nn("apm-form"))},[gn]),S=Ge(()=>{nn("apm-collapsing"),gn(()=>{nn("buttons"),Br(null)})},[gn]);bt(()=>{be==="buttons"&&jt&&mt&&(je(e??null),nn("card"))},[be,jt,mt,e]);let[R,k]=ae(null),Q=re(!1),ke=re(null),dt=re("idle"),[te,Ie]=ae(!1),z=re(te);z.current=te;let[d,p]=ae(()=>lt?.existingOrderId?{orderId:lt.existingOrderId,attempts:1}:null),_=re(d);bt(()=>{_.current=d},[d]);let x=re(null),ee=vt(()=>{if(Je||Ue.claimBuyerIdentity||T?.buyerIdentified!==!1||!e||!t)return;let a=`${Ze}|${e}|${t}`;x.current?.key!==a&&(x.current={key:a,claim:bo(new Bo(Ze,{telemetry:!1}),e,t,{...i?{userId:i}:{},...b?{firstName:b}:{},...g?{lastName:g}:{}})});let f=x.current.claim;return async q=>{await f(q)}},[Je,Ue.claimBuyerIdentity,T?.buyerIdentified,e,t,Ze,i,b,g]),$=Je??Ue.claimBuyerIdentity??ee,Be=U??Dn,wt=vt(()=>yu(et),[et]),C=vt(()=>{let a=wt?.buttonsLayout??uu(It);return pe?{...a,...pe,cardButton:{...a.cardButton,...pe.cardButton},cardFormContainer:{...a.cardFormContainer,...pe.cardFormContainer},backButton:{...a.backButton,...pe.backButton},backButtonIcon:{...a.backButtonIcon,...pe.backButtonIcon},submitButton:{...a.submitButton,...pe.submitButton},title:{...a.title,...pe.title}}:a},[wt,It,pe]),de=De??wt?.appearance,Tt=vt(()=>ul({appearance:de,buttonsStyles:C,layout:be}),[de,C,be]),ne=Ue.inlineSessionPatchProcessing??!1,B=(v??$t)||ne,Y=Ze.replace(/\/+$/,""),P=vt(()=>Mi({userId:i,email:o,firstName:b,lastName:g,country:O,zip:$e},Vn),[i,o,b,g,O,$e,Vn]),Te=[P.firstName,P.lastName].filter(a=>!!a?.trim()).join(" "),St=!hn(P.email?.trim()),we=re(null);X&&we.current===null&&(we.current=St);let Cn=X&&(we.current??St),vr=vt(()=>zu(Kt,Cn),[Kt,Cn]),ao=vr.empty||vr.malformed,qn=vt(()=>ze?ze.getRawProvider():null,[ze]),Es=vt(()=>Ct?Ct.getRawProvider():null,[Ct]),zo=Le||100,io=en.toLowerCase(),ui=vt(()=>de?Zd(de):null,[de]),so=ui,Ts=vt(()=>{let a=ui??{},f=a.rules??{};return{...a,rules:{...f,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...f[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...f[".AccordionItemContents"]??{}}}}},[ui]),As=vt(()=>({...wl(Le,T?.captureMethod),currency:io,...so?{appearance:so}:null}),[Le,io,T?.captureMethod,so]),xs=vt(()=>({mode:"payment",amount:zo,currency:io,captureMethod:"manual",setupFutureUsage:"off_session",...so?{appearance:so}:null}),[zo,io,so]),ve=Ge(a=>{Rn(a),ue?.(a)},[ue]),pi=re(""),[Ms,Ac]=ae(!1),yi=Ge(()=>{Ac(!0)},[]);bt(()=>{if(!X||!Cn||!$||!Ms||ao||pi.current)return;let a=Fn({email:hn(P.email?.trim())?P.email?.trim():yn.current.trim(),firstName:P.firstName?.trim(),lastName:P.lastName?.trim()});pi.current=JSON.stringify(a),un(f=>({...f,...a})),Promise.resolve($(a)).catch(f=>{pi.current="",ve(f instanceof Error?f.message:"Failed to attach buyer details.")})},[X,Cn,$,Ms,ao,P.email,P.firstName,P.lastName,ve]),bt(()=>{!X||!Wt||Wt.setCardFieldOrder?.(D??null,H==null&&!Cn)},[X,Wt,D,H,Cn]),bt(()=>{(st==="expanding"||st==="collapsing"||st==="apm-expanding"||st==="apm-collapsing")&&ve(null)},[st,ve]);let br=Ge((a,f,q)=>{m?.(ln(a,f,q))},[m]),lo=Ge((a,f,q)=>{let Se=q?.popupBlocked??$r(f);Se&&N.markBlocked()&&h(We=>We+1);let W=Na(ls(a),Se,Ae.inAppBrowser),ge=Ir(f),Yt=(ge?.toLowerCase()==="error"?void 0:ge)??eo(q?.code)??"external_payment_method_failed",lr=new pr(W,"api_error",{code:"external_payment_method_failed",param:a,details:{providerCode:Yt,popupBlocked:Se,inAppBrowser:Ae.inAppBrowser,appFamily:Ae.appFamily,popupCapability:N.current(),presentationMode:q?.presentationMode??"popup"}});q?.telemetryReported||cn(ze)?.error(Mo({...me,presentationMode:q?.presentationMode??"popup"},{errorCode:Se?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:q?.provider??(a==="paypal"?"paypal":"stripe"),paymentMethodCategory:q?.paymentMethodCategory??(a==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:q?.terminalReason??(Se?"popup_blocked":"provider_error")})),k(null),be==="buttons"&&(nn("buttons"),Br(null)),ve(W),l?.(lr),console.error("[FloPay] External payment method failed:",{method:a,code:Yt,popupBlocked:Se})},[Ae,me,ze,be,l,N,ve]);bt(()=>{if(!X||!e){Pr(null);return}let a=os(T?.vault);if(a){Pr(a);return}if(!mn){Pr(null);return}Pr(null);let f=!0;return new Bo(Y).getVaultCapture(e,t).then(q=>{if(!f)return;let Se=os(q);Se?Pr(Se):ve("Failed to load the secure card form.")}).catch(q=>{f&&ve(q instanceof Error?q.message:"Failed to load the secure card form.")}),()=>{f=!1}},[X,mn,Z,e,T?.vault,Y,t,ve]);let ir=re({onComplete:s,onError:l,updateError:ve,emitDecline:br,resolvedAccount:P,avsConfig:H,avsCheckProp:Pe,sessionId:e,nonce:t,baseUrl:Y,captureMethod:T?.captureMethod,paymentId:T?.paymentId,authorizationExpiresAt:T?.authorizationExpiresAt,serverSideCardGateway:an});ir.current={onComplete:s,onError:l,updateError:ve,emitDecline:br,resolvedAccount:P,avsConfig:H,avsCheckProp:Pe,sessionId:e,nonce:t,baseUrl:Y,captureMethod:T?.captureMethod,paymentId:T?.paymentId,authorizationExpiresAt:T?.authorizationExpiresAt,serverSideCardGateway:an};let mi=re(!1),Bs=Ge(()=>{let a=ir.current,f=a.resolvedAccount.email?.trim(),q=hn(f)?f:yn.current.trim();if(!hn(q))return null;let Se=a.resolvedAccount.firstName?.trim(),W=a.resolvedAccount.lastName?.trim(),ge=Jt.current.trim()||a.resolvedAccount.country?.trim()||"",Yt=a.avsConfig?at(a.avsConfig.state,ge):!1,lr=a.avsConfig?at(a.avsConfig.address_line_1,ge):!1,We=a.avsConfig?at(a.avsConfig.postal_code,ge):!1,ut=a.avsConfig?at(a.avsConfig.city,ge):!1,Pt=a.avsConfig?at(a.avsConfig.address_line_2,ge):!1,zt=lr&&!Yt&&We?Wl(ge,(ht.current??"").trim()):null,sn=Yt?Vt.current:zt;return{accountData:{userId:a.resolvedAccount.userId??"",email:q,...Se?{firstName:Se}:{},...W?{lastName:W}:{},...We&&ht.current?{zip:ht.current}:{},...ut&&Xt.current?{city:Xt.current}:{},...sn?{state:sn}:{},...lr&&pn.current?{addressLine1:pn.current}:{},...Pt&&Dt.current?{addressLine2:Dt.current}:{},...ge?{country:ge}:{}},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:at(a.avsConfig.country,ge),postal_code:We,address_line_1:lr,address_line_2:Pt,city:ut,state:Yt}}:{}}},[]),Fs=re(oe);Fs.current=oe,bt(()=>{oe||Be!==Ql||ir.current.updateError(null)},[oe,Be]),bt(()=>{!X||!Wt||Wt.setSubmitGate?.(Ar||oe||ao||te)},[X,Wt,Ar,oe,ao,te]),bt(()=>{if(!X||!Wt)return;mi.current=!1;let a=null,f=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,dt.current="idle",k(null)},400)},q=Wt.on("submitting",()=>{Zt(!0),ke.current&&clearTimeout(ke.current),dt.current="validation-window",ke.current=setTimeout(()=>{ke.current=null,dt.current==="validation-window"&&(dt.current="processing")},_u),k("processing");let We=ir.current;if(!We.sessionId||!We.nonce)return;let ut=Bs();if(!ut){We.updateError("Enter a valid email address."),dt.current="idle",k(null);return}new Bo(We.baseUrl).patchAccountSnapshot(We.sessionId,We.nonce,ut,{telemetryMode:"best_effort"}).catch(Pt=>{if(!Eu(Pt))return;let zt=Pt instanceof Error?Pt.message:"Please check your billing address and try again.";We.updateError(zt),dt.current="idle",k(null),We.onError?.(Pt instanceof pr?Pt:new pr(zt,"api_error"))})}),Se=Wt.on("complete",async We=>{if(To(We.sessionId??ir.current.sessionId),dt.current="terminal",Ie(!1),k("success"),await new Promise(sn=>setTimeout(sn,600)),mi.current)return;mi.current=!0;let ut=ir.current,Pt=Qi(ut)||We.outcome==="authorized",zt=ut.serverSideCardGateway?{}:{paymentIntentId:We.intentId};ir.current.onComplete?.(Pt?{status:"authorized",...zt,paymentId:We.paymentId??ut.paymentId,sessionId:We.sessionId??ut.sessionId,authorizationExpiresAt:We.authorizationExpiresAt??ut.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...zt,checkoutMethod:"card"})}),W=Wt.on("decline",We=>{let ut=ir.current,Pt=We.message??"Your payment was declined. Please try another card or contact your bank.";dt.current="terminal",Ie(!1),ut.updateError(Pt),k("error");let zt=We.failureOutcome??su(We.declineReason)??"authorization_declined";ut.emitDecline("card",Pt,{code:zt,declineCode:zt}),f()}),ge=Wt.on("error",We=>{let ut=ir.current,Pt=We.message??"There was a problem processing your payment. Please try again.";dt.current="terminal",Ie(!1),ut.updateError(Pt),k("error"),ut.onError?.(new pr(Pt,"api_error",{code:We.failureOutcome??"capture_failed"})),f()}),Yt=Wt.on("challenge_dismissed",()=>{ke.current&&(clearTimeout(ke.current),ke.current=null),dt.current="processing",Ie(!0),k(null)}),lr=Wt.on("blocked",()=>{if(z.current){ir.current.updateError(Ru);return}if(!Fs.current){Zt(!0);return}yi(),ir.current.updateError(Ql)});return()=>{a&&(clearTimeout(a),a=null),ke.current&&(clearTimeout(ke.current),ke.current=null),dt.current="idle",Ie(!1),k(null),q(),Se(),W(),ge(),Yt(),lr()}},[X,Wt,yi,Bs]);let Cr=!!lt?.clientId,Uo=Array.isArray(se),ka=Uo&&se.length>0,Ds=Uo&&se.includes("paypal"),Ia=re(null);Ia.current===null&&(Ia.current=ku());let co=Ia.current?"redirect":Al(Ae,K,N.current()),{expressMethods:_a,paymentElementMethods:qo}=vt(()=>lu(se,{excludePaypal:Cr}),[se,Cr]),Os=Cr||!!Ct||Ds&&co==="redirect",xc=vt(()=>Os?_a.filter(a=>a!=="paypal"):_a,[_a,Os]),Mc=vt(()=>{let a=[];return xe&&a.push("apple_pay"),Ye&&a.push("google_pay"),a},[xe,Ye]),uo=Uo?xc:Mc,Bc=J&&uo.length>0,fi=Ln?Mt:O,Ra=vt(()=>{let a=fi?.trim().toUpperCase();return a?G?qo.filter(f=>{let q=G[f];return!q||q.length===0||q.includes(a)}):tu(qo,fi):qo},[qo,fi,G]),gi=vt(()=>({mode:"payment",amount:zo,currency:io,paymentMethodCreation:"manual",appearance:Ts}),[zo,io,Ts]),[Ns,Ls]=ae("loading"),[zs,Us]=ae("loading"),[qs,js]=ae("loading"),[Fc,hi]=ae(!1),[$s,Pi]=ae("loading"),[vi,Dc]=ae();bt(()=>{Dc(aa())},[]);let Ea=vi?.inAppBrowser,Ta=vi?Ua(vi,lt?.approvalPresentation,Xe??(it?"subscription":"order")):"popup",Ks=E&&(Cr||(Uo?Ds:Ea===!1)),Vs=J&&Bc,jo=(!Rt||!!Ue.waitForDataAttachment)&&Ks&&Cr,Hs=$s==="retrying"||$s==="exhausted",$o=null;J&&(Ct?$o=Es:co==="redirect"&&($o=qn));let Ws=vt(()=>({...me,presentationMode:co}),[me,co]),Ko=!Rt&&Ks&&!!$o&&(!Cr||Hs),po=!Rt&&Vs&&!!qn,Vo=!Rt&&J&&ka&&Ra.length>0&&!!qn,Oc=jo&&!Hs?Fc:Ko&&oc(Ns),Nc=po&&oc(zs),Lc=Vo&&qs!=="load_error",Gs=a=>a==="loading"||a==="ready",Ys=jo||Ko&&Gs(Ns)||po&&Gs(zs)||Vo&&qs!=="load_error",Aa=re(!1);bt(()=>{if(!Aa.current){if(!J&&!E){Aa.current=!0;let a=new pr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(a),ve(a.message)}else if(!J&&E&&!Cr){Aa.current=!0;let a=new pr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(a),ve(a.message)}else if(Ea!==void 0&&!Rt&&!mt&&!Ys){Aa.current=!0;let a=new pr("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?.(a),ve(a.message)}}},[J,E,Cr,Ea,Rt,mt,Ys,l,ve]);let Js=re(!1);bt(()=>{if(Js.current||!ka)return;let a=[];xe!==!0&&a.push("showApplePay"),Ye!==!0&&a.push("showGooglePay"),a.length!==0&&(Js.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.`))},[ka,xe,Ye]);let Xs=Ge((a,f)=>Ue.applyInlineSessionPatch?Ue.applyInlineSessionPatch(a).then(q=>({error:null,sessionId:q.sessionId||e,nonce:q.session?.clientSecret||t})).catch(q=>{let Se=rc(f,q);return ve(Se.message),l?.(Se),{error:Se,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ue.applyInlineSessionPatch,t,l,e,ve]),sr=Ge(async a=>{if(a!=="card"&&Rt&&await Ue.waitForDataAttachment?.(),!Ne)return{proceed:!0};try{let f=await Ne({method:a,sessionId:e||void 0,createSession:Ue.inlineSessionDraft});if(f===!1)return{proceed:!1};if(f&&typeof f=="object"){f.account&&un(Se=>({...Se??{},...f.account}));let q=await Xs(f,a);return q.error?{proceed:!1,accountPatch:f.account}:{proceed:!0,accountPatch:f.account,sessionId:q.sessionId,nonce:q.nonce}}return{proceed:!0}}catch(f){let q=rc(a,f);return ve(q.message),l?.(q),{proceed:!1}}},[Xs,Ue.inlineSessionDraft,Ue.waitForDataAttachment,Rt,Ne,l,e,ve]),Zs=Ge(async(a,f)=>{if(Q.current)return;Q.current=!0,Ee(!0),k("processing"),ve(null);let q=f?.sessionId??e,Se=f?.nonce??t,W=Mi(P,f?.accountPatch),ge=f?.completionPaymentMethodId??na(a),Yt=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,lr=Bu(a),We=f?.presentationMode?ti(cn(ze),{...me,presentationMode:f.presentationMode}):void 0,ut=()=>{c?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:lr}),We?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...ur,requestCategory:"process_payment"})};try{let zt=await new Bo(Y).processPayment(W.userId??"",{sessionId:q,nonce:Se,paymentMethodCategory:f?.paymentMethodCategory??Du(a),tokenizedData:Yt,accountData:{...f?.accountPatch,userId:W.userId??"",email:W.email??"",firstName:W.firstName||void 0,lastName:W.lastName||void 0,...H?(()=>{let Ot=Jt.current,wr=at(H.state,Ot),jn=at(H.address_line_1,Ot),Sr=at(H.postal_code,Ot),Zr=jn&&!wr&&Sr?Wl(Ot,(ht.current??"").trim()):null,Xo=wr?Vt.current:Zr;return{country:Ot,...Sr&&ht.current?{zip:ht.current}:{},...at(H.city,Ot)&&Xt.current?{city:Xt.current}:{},...Xo?{state:Xo}:{},...jn&&pn.current?{addressLine1:pn.current}:{},...at(H.address_line_2,Ot)&&Dt.current?{addressLine2:Dt.current}:{}}})():{}},chv:F,avsCheck:Pe??!1,checkoutType:He,checkoutLayout:ft,avsConfig:H?{country:at(H.country,Jt.current),postal_code:at(H.postal_code,Jt.current),address_line_1:at(H.address_line_1,Jt.current),address_line_2:at(H.address_line_2,Jt.current),city:at(H.city,Jt.current),state:at(H.state,Jt.current)}:void 0});if(zt.ok){let Ot=zt.status===204?null:await zt.json().catch(()=>null),wr=Qi(T)||Ot?.status==="authorized";To(q),We?.terminal({outcome:"payment_succeeded",...ur}),k("success"),p(null),await new Promise(Zr=>setTimeout(Zr,600));let jn;typeof Ot?.paymentId=="string"?jn=Ot.paymentId:T?.paymentId&&(jn=T.paymentId);let Sr;typeof Ot?.authorizationExpiresAt=="string"?Sr=Ot.authorizationExpiresAt:T?.authorizationExpiresAt&&(Sr=T.authorizationExpiresAt),s?.(wr?{status:"authorized",...jn===void 0?{}:{paymentId:jn},sessionId:typeof Ot?.sessionId=="string"?Ot.sessionId:q,...Sr===void 0?{}:{authorizationExpiresAt:Sr},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ge,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ge,checkoutMethod:a.isPaypal?"paypal":"card"});return}let sn=await zt.json().catch(()=>null);if(sn?.type==="paypal_redirect_required"){let Ot=sn.threeDSecureToken,wr=sn.paymentMethodId||a.id||"";if(!ze||!Ot){k("error"),ve("PayPal authorization required but no token provided.");return}try{let jn=Ct?.getRawProvider();if(!jn){ve("PayPal is not available.");return}let Sr={return_url:window.location.href};wr&&(Sr.payment_method=wr);let{error:Zr}=await jn.confirmPayment({clientSecret:Ot,confirmParams:Sr,redirect:"if_required"});if(Zr){k("error");let Xo=Zr.message??"PayPal payment failed.";ve(Xo),br("paypal",Xo,{code:Zr.code})}}catch(jn){k("error"),ve(jn instanceof Error?jn.message:"PayPal authorization failed.")}return}if(sn?.type==="paypal_direct_required"){let Ot=sn.orderId;if(!Ot){k("error"),ve("PayPal retry required but no order id provided.");return}let wr=_.current?.attempts??0;if(wr>=2){k("error"),ve("PayPal payment could not be completed after multiple attempts."),br("paypal","paypal_direct_required retry limit exceeded");return}hi(!1),Pi("loading"),p({orderId:Ot,attempts:wr+1}),k(null);return}eu(zt.status,sn)?We?.terminal({outcome:"payment_declined",...ur,terminalReason:"provider_declined"}):ut(),k("error");let cr=sn?.message??"Payment failed. Please try again.";ve(cr),br(a.isPaypal?"paypal":"card",cr,{code:sn?.code??sn?.gatewayErrorCode,declineCode:sn?.declineCode??sn?.gatewayDeclineReason}),await new Promise(Ot=>setTimeout(Ot,400))}catch(Pt){pc(Pt)||ut(),k("error"),ve(Pt instanceof Error?Pt.message:"An unexpected error occurred"),await new Promise(zt=>setTimeout(zt,400))}finally{Ee(!1),k(null),Q.current=!1}},[Y,e,t,P,H,Pe,He,ft,F,ze,Ct,T,s,ve,br,c,me]),Mn=Ge((a,f)=>{y?y(a):Zs(a,f)},[y,Zs]),Ho=`${cc}:${e}`;bt(()=>{if(typeof window>"u")return;let a=localStorage.getItem(Ho);if(!a)return;let f;try{f=JSON.parse(a)}catch{Ut(Ho);return}if(!f||typeof f.createdAt!="number"||Date.now()-f.createdAt<0||Date.now()-f.createdAt>dc||typeof f.paymentMethodId!="string"||typeof f.providerIntentId!="string"||typeof f.paymentMethodType!="string"||f.sessionId!==e||!t||f.nonce!==t||!uo.includes(f.paymentMethodType)){Ut(Ho);return}Ut(Ho),Mn({id:f.paymentMethodId,type:"card",threeDSecureActionResultTokenId:f.providerIntentId,gateway:"stripe",paymentMethodType:f.paymentMethodType},{...f.accountPatch?{accountPatch:f.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Mn,t,e,Ho,uo]);let Qs=re(!1);bt(()=>{if(typeof window>"u"||Qs.current)return;let[a,f,q]=ys();if(!a||!f||Ia.current||!ze)return;let Se=ze.getRawProvider();if(!Se)return;let W=ut=>{let Pt=localStorage.getItem(ut);if(!Pt)return null;try{return JSON.parse(Pt)}catch{return Ut(ut),null}},ge=W(Er)??W(Jl),Yt;if(ge?.clientSecret){if(ge.clientSecret!==f)return;Yt={...ge.accountPatch?{accountPatch:ge.accountPatch}:{},...ge.sessionId?{sessionId:ge.sessionId}:{},...ge.nonce?{nonce:ge.nonce}:{}}}else if(ge?.sessionId&&ge.sessionId!==e)return;Qs.current=!0,Ut(Er),Ut(Jl),window.history.replaceState({},"",ms());let lr=ge?.paymentMethodType??ge?.tokenType??"card",We="card";(async()=>{if(q==="failed"){let cr="Payment was declined. Please try again.";ve(cr),br(We,cr);return}let{paymentIntent:ut,error:Pt}=await Se.retrievePaymentIntent(f);if(Pt){let cr=Pt.message??"Failed to retrieve payment status.";ve(cr),br(We,cr,{code:Pt.code});return}let zt=ut?.status,sn=ta(zt);if(!ut||!sn){let cr=zt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ve(cr),br(We,cr,{code:zt??"missing_payment_intent"});return}let cl=typeof ut.payment_method=="string"?ut.payment_method:ut.payment_method?.id;Mn({id:cl??ge?.paymentMethodId??ge?.tokenId??ut.id,type:"card",threeDSecureActionResultTokenId:ut.id,gateway:ge?.gateway??"stripe",paymentMethodType:lr},Yt)})()},[e,Mn,ze,ve,br]);let bi=Ge(a=>{a.preventDefault()},[]);if(!(X||ze!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Wo=be==="buttons",Bn=de?.variables,zc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ci=Bn?.colorBackground,Uc=Ci&&!zc.has(Ci)?Ci:void 0,Go=C.cardInputBorder??(Wo?"#e5e7eb":"#A4A4FF"),el=Bn?.colorDanger??"#dc2626",Lt=a=>xr[a]&&(gr[a]||Tn),xa=ao&&(Mr||Tn),Xn=a=>a?el:Go,Ma=(fn.malformed||fn.empty)&&(fr||Tn),qc=Xn(Ma),wi=C.cardFormContainer?.backgroundColor??Uc??(Wo?"white":"#EDEDFF"),yo=C.cardInputBackground??Bn?.colorBackground??"white",Si=go(Re),tl=go(Oe),mo=C.nameInput,nl=C.cardInputFontSize??Uu(mo?.fontSize)??Bn?.fontSizeBase??"16px",rl=typeof mo?.fontFamily=="string"?mo.fontFamily:Bn?.fontFamily??"Poppins, sans-serif",ol=dl(mo?.fontWeight)??400,jc=C.cardInputColor??(typeof mo?.color=="string"?mo.color:void 0)??Bn?.colorText??"#262833",$c=C.cardInputPlaceholderColor??"#9ca3af",Gt=Bn?.borderRadius??"8px",Jr=Bn?.borderRadius??C.cardButton?.borderRadius??Gt,Xr=Bn?.colorPrimary??"#4A49FF",Kc=Bn?.colorPrimaryHover??Qo(Xr,.12),ki=Bn?.colorText??"#262833",Ii={fontSize:nl,fontFamily:rl,fontWeight:ol,color:jc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Yo={marginTop:"0.375rem",...Ii,fontSize:"0.75rem",lineHeight:1.4,color:el},Vc={"--flopay-input-placeholder-color":$c,"--flopay-input-font-size":nl,"--flopay-input-font-family":rl,"--flopay-input-font-weight":String(ol)},Jo=C.cardFormContainer??{},_i=Jo.padding??(Wo?"0":"1rem"),Ri=Jo.borderRadius??Gt,Hc=Wt&&Jn?u(Ei,{capture:Wt,html:Jn.html,messageToken:Jn.messageToken,expectedOrigin:Jn.expectedOrigin,theme:Tt,submitLabel:w,onReady:()=>{if(!Cn&&!H||typeof document>"u")return;let a=()=>{let q=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(q){tr.current=!0;try{q.focus()}finally{tr.current=!1}}};Yn.current||a()},onError:a=>ve(a),onValidation:a=>{let f=dt.current;(f==="idle"||f==="validation-window")&&(ve(a),a&&dt.current==="validation-window"&&(ke.current&&(clearTimeout(ke.current),ke.current=null),dt.current="idle",k(null)))}}):u("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"}),al=Fe("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&rr()},style:{backgroundColor:wi,borderRadius:Ri,...Jo,padding:_i,...Vc,display:"flex",flexDirection:"column"},children:[u("style",{children:`
26
26
  .flopay-shared-input::placeholder {
27
27
  color: var(--flopay-input-placeholder-color);
28
28
  opacity: 1;
@@ -30,13 +30,13 @@ ${pt.join(`
30
30
  font-family: var(--flopay-input-font-family);
31
31
  font-weight: var(--flopay-input-font-weight);
32
32
  }
33
- `}),Do&&br&&ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Le?-2:0},children:[ze("button",{type:"button",onClick:Tn,style:{display:"inline-flex",alignItems:"center",gap:ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:v.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...v.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...v.backButtonIcon},children:c("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:c("path",{d:"M15 18l-6-6 6-6"})})}),c(lo,{content:ye})]}),xs?c("div",{style:{flex:1}}):c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...v.title},children:c(jo,{content:we})})]}),!Do&&!xs&&c("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ri,order:Le?-3:0,...v.title},children:c(jo,{content:we})}),Le&&U&&c("div",{style:{order:-2,width:"100%"},children:U}),Le&&Se&&ze("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[c("div",{style:{backgroundColor:ro,border:`1px solid ${Xn(ma)}`,borderRadius:Vt,padding:"10px"},children:c("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:rn,onChange:a=>{yt("email"),wn.current=a.target.value,wt(a.target.value)},onPointerDown:()=>yt("email"),onKeyDown:()=>yt("email"),onBlur:()=>{En("email")&&Rn(!0),Ge||Ha()},disabled:Ce,required:!0,"aria-invalid":ma||void 0,"aria-describedby":ma?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...oi}})}),ma&&c("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Lo,children:pe.empty?"Email address is required":"Enter a valid email address"})]}),te&&c("div",{style:{order:Le?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=O,b=(W=!1)=>({backgroundColor:ro,border:`1px solid ${Xn(W)}`,borderRadius:Vt,marginTop:"0.5rem",padding:"10px"}),j=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...oi}),Be=Td(a);return ze(Yr,{children:[rt(te.address_line_1,a)&&ze(Yr,{children:[c("div",{style:b(qt("line1")),children:c("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:mn,onChange:W=>{yt("line1"),It.current.addressLine1=!0,yn.current=W.target.value,_n(W.target.value)},onPointerDown:()=>yt("line1"),onKeyDown:()=>yt("line1"),onBlur:()=>Yn("line1"),disabled:Ce,required:!0,"aria-invalid":qt("line1")||void 0,"aria-describedby":qt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:j()})}),qt("line1")&&c("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Lo,children:"Street address is required"})]}),rt(te.address_line_2,a)&&c("div",{style:b(),children:c("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:W=>{It.current.addressLine2=!0,Ut.current=W.target.value,Dn(W.target.value)},disabled:Ce,"data-testid":"flopay-address-line2",style:j()})}),(rt(te.city,a)||rt(te.state,a))&&ze("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[rt(te.city,a)&&c("div",{style:{flex:1,backgroundColor:ro,borderTop:`1px solid ${Xn(qt("city"))}`,borderRight:`1px solid ${Xn(qt("city"))}`,borderBottom:`1px solid ${Xn(qt("city"))}`,borderLeft:`1px solid ${Xn(qt("city"))}`,padding:"10px",borderTopLeftRadius:Vt,borderBottomLeftRadius:Vt,...rt(te.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Vt}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Jt,onChange:W=>{yt("city"),It.current.city=!0,At.current=W.target.value,je(W.target.value)},onPointerDown:()=>yt("city"),onKeyDown:()=>yt("city"),onBlur:()=>Yn("city"),disabled:Ce,required:!0,"aria-invalid":qt("city")||void 0,"aria-describedby":qt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:j()})}),rt(te.state,a)&&c("div",{style:{flex:1,backgroundColor:ro,borderTop:`1px solid ${Xn(qt("state"))}`,borderRight:`1px solid ${Xn(qt("state"))}`,borderBottom:`1px solid ${Xn(qt("state"))}`,borderLeft:`1px solid ${Xn(qt("state"))}`,padding:"10px",borderTopRightRadius:Vt,borderBottomRightRadius:Vt,...rt(te.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Xn(qt("state")||qt("city"))}`}:{borderRadius:Vt}},children:Be?ze("select",{id:"flopay-billing-state",name:"billing-state",value:He,onChange:W=>{yt("state"),It.current.state=!0,Sn.current=W.target.value,St(W.target.value)},onPointerDown:()=>yt("state"),onKeyDown:()=>yt("state"),onBlur:()=>Yn("state"),disabled:Ce,autoComplete:"billing address-level1",required:!0,"aria-invalid":qt("state")||void 0,"aria-describedby":qt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...j(),cursor:"pointer"},children:[c("option",{value:"",children:Mi(a)}),Be.map(W=>c("option",{value:W.code,children:W.name},W.code))]}):c("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Mi(a),autoComplete:"billing address-level1",value:He,onChange:W=>{yt("state"),It.current.state=!0,Sn.current=W.target.value,St(W.target.value)},onPointerDown:()=>yt("state"),onKeyDown:()=>yt("state"),onBlur:()=>Yn("state"),disabled:Ce,required:!0,"aria-invalid":qt("state")||void 0,"aria-describedby":qt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:j()})})]}),qt("city")&&c("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Lo,children:"City is required"}),qt("state")&&ze("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Lo,children:[Mi(a)," is required"]}),(rt(te.country,a)||rt(te.postal_code,a))&&ze("div",{style:{display:"flex",flexDirection:V==="column"?"column":"row",gap:V==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[rt(te.country,a)&&c("div",{style:{flex:V==="row"?1:void 0,backgroundColor:ro,borderTop:`1px solid ${No}`,borderRight:`1px solid ${No}`,borderBottom:`1px solid ${No}`,borderLeft:`1px solid ${No}`,padding:"10px",...V==="row"&&rt(te.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:Vt,borderBottomLeftRadius:Vt,borderRight:"none"}:{borderRadius:Vt}},children:c("select",{id:"flopay-billing-country",name:"billing-country",value:O,onChange:W=>{It.current.country=!0,zt.current=W.target.value,Ot(W.target.value),Ye?.(W.target.value),Sn.current="",St("")},disabled:Ce,autoComplete:"billing country","data-testid":"flopay-country",style:{...j(),cursor:"pointer"},children:kd.map(W=>ze("option",{value:W.code,children:[W.flag," ",W.name]},W.code))})}),rt(te.postal_code,a)&&c("div",{style:{flex:V==="row"?1:void 0,backgroundColor:ro,border:`1px solid ${uc}`,padding:"10px",...V==="row"&&rt(te.country,a)?{borderRadius:"0",borderTopRightRadius:Vt,borderBottomRightRadius:Vt}:{borderRadius:Vt}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:qi(O),autoComplete:"billing postal-code",value:Cn,onChange:W=>{yt("zip"),It.current.zip=!0,Tt.current=W.target.value,pn(W.target.value),re?.(W.target.value)},onPointerDown:()=>yt("zip"),onKeyDown:()=>yt("zip"),onBlur:()=>{En("zip")&&or(!0)},disabled:Ce,required:sn.required,"aria-invalid":ya||void 0,"aria-describedby":ya?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:j()})})]}),ya&&c("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Lo,children:sn.empty?`${qi(a)} is required`:lu(a)})]})})()}),Le&&gc,P&&c(ho,{margin:"0.75rem 0",styleOverride:v.errorBanner,children:P})]}),fa={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"},Ns=a=>H?!S||!mr?c("pre",{"data-testid":a,style:fa,children:"FloPay/DirectPayPal-debug - not enabled"}):c("pre",{"data-testid":a,style:fa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${S}`,` directPaypalConfigured=${mr}`,` inAppBrowserDetected=${String(da)}`,` shouldRenderDirectPayPal=${xo}`,` shouldRenderStripePayPal=${Mo}`,` hasPaypalStripeInstance=${!!tn}`].join(`
34
- `)}):null,Ls=a=>H?!G||!ht?c("pre",{"data-testid":a,style:fa,children:"FloPay/Stripe-debug - not enabled"}):c("pre",{"data-testid":a,style:fa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${G}`,` currency=${Me}`,` amountInCents=${qn}`,` enabledPaymentMethods: ${JSON.stringify(X??[])}`,` enabledPaymentMethodsProvided=${To}`,` hasEnabledMethods=${sa}`,` expressMethods: ${JSON.stringify(la)}`,` walletExpressMethods: ${JSON.stringify(to)}`,` paymentElementMethods: ${JSON.stringify(Ao)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(ca)}`,` hasStripeInstance=${!!ht}`,` shouldRenderWallets=${no}`,` shouldRenderPaymentElement=${Bo}`].join(`
35
- `)}):null,Os=We==="apm-expanding"||We==="apm-form"||We==="apm-collapsing",ao;We==="apm-expanding"?ao=kl:We==="apm-collapsing"&&(ao=_l);let ga=ln?Ul(Ya,ln):null;if(ve==="buttons"){let a=We==="buttons"||We==="expanding"||We==="apm-expanding",b=We==="expanding"||We==="card"||We==="collapsing",j=De===void 0?{boxSizing:"border-box",height:La,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Be;We==="expanding"||We==="apm-expanding"?Be=nu:(We==="collapsing"||We==="apm-collapsing")&&(Be=tu);let W;return We==="expanding"?W=kl:We==="collapsing"&&(W=_l),ze("form",{onSubmit:Qa,className:w,noValidate:!0,style:{position:"relative"},children:[c(Ui,{}),Un&&c(fr,{status:Un,errorMessage:P,authorized:Kn}),ze("div",{style:{display:"grid"},children:[ze("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!Be?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!Be?ou:{},...Be?{animation:Be,pointerEvents:"none"}:{}},children:[Ns("flopay-direct-paypal-gate-debug"),Ls("flopay-stripe-gate-debug"),xo&&ke&&ze(Yr,{children:[z&&c("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."}),c(ka,{sessionId:e,nonce:t,billingApiUrl:N,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,clientId:ke.clientId,environment:ke.environment,currency:Me.toUpperCase(),isSubscription:Ee,providerObjectType:B,approvalPresentation:ua==="popup"?void 0:ua,onTokenizedBody:An,onComplete:s,onErrorChange:he,onDecline:p,onTechnicalFailure:eo,onButtonClick:Z,runBeforeButtonClick:lr,isProcessing:Ce,onLoadStateChange:Ja,onInitializationStateChange:Xa,session:u,existingOrderId:z?.orderId,debug:H},z?.orderId??"fresh")]}),Mo&&c(Gr,{stripe:tn,options:cs,children:c(Al,{sessionId:e,nonce:t,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,billingApiUrl:N,onTokenizedBody:An,onErrorChange:he,isProcessing:Ce,onButtonClick:Z,onDecline:p,onTechnicalFailure:eo,runBeforeButtonClick:lr,onLoadStateChange:fs,placeholderBorderRadius:jr})}),no?c(Gr,{stripe:ht,options:ls,children:c(xl,{sessionId:e,nonce:t,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,billingApiUrl:N,intentKind:xe>0?"payment":"setup",expressMethods:to,onTokenizedBody:An,onErrorChange:he,onButtonClick:Z,onDecline:p,onTechnicalFailure:eo,runBeforeButtonClick:lr,onLoadStateChange:hs,placeholderBorderRadius:jr})}):null,!no&&Ss?c("div",{style:{height:La,borderRadius:jr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Bo&&c(Ml,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:g,billingApiUrl:N,paymentElementMethods:ca,stripeInstance:ht,paymentElementBaseOptions:Ya,onTokenizedBody:An,onErrorChange:he,onButtonClick:Z,onDecline:p,runBeforeButtonClick:lr,onLoadStateChange:Ps,isProcessing:Ce,submitButtonColor:$r,submitButtonBorderRadius:Vt,submitButtonStyle:v.submitButton,onExpandApm:Tr,expandedApmMethod:ln,themeId:Ue,buttonAppearance:{backgroundColor:v.cardButton?.backgroundColor,borderColor:v.cardInputBorder,textColor:v.cardButton?.color,borderRadius:jr}}),Le&&c("button",{type:"button",onClick:async()=>{Ce||!(await lr("card")).proceed||(Z?.("card"),Xr())},disabled:Ce,style:{width:"100%",...j,...v.cardButton,...Yi({themeBundle:I,resolvedPrimaryColor:$r,resolvedBorderRadius:Vt,submitButtonStyle:v.submitButton,explicitPrimaryColor:xn?.colorPrimary}),fontSize:v.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ce?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Ce?.6:1},onMouseEnter:st=>{!Ce&&(I||xn?.colorPrimary)&&(st.currentTarget.style.backgroundColor=yc)},onMouseLeave:st=>{(I||xn?.colorPrimary)&&(st.currentTarget.style.backgroundColor=$r)},onMouseDown:st=>{st.currentTarget.style.transform="scale(0.985)"},onMouseUp:st=>{st.currentTarget.style.transform="scale(1)"},children:c(so,{content:De})}),P&&We==="buttons"&&c(ho,{margin:"0.25rem 0",styleOverride:v.errorBanner,children:P})]}),Le&&b&&c("div",{style:{gridArea:"1 / 1",...W?{animation:W}:{},...We==="collapsing"?{pointerEvents:"none"}:{}},children:Ds}),G&&Os&&ln&&ga&&ht&&c("div",{style:{gridArea:"1 / 1",...ao?{animation:ao}:{},...We==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:ti,borderRadius:ii,...Oo,padding:ai},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:In,style:{display:"inline-flex",alignItems:"center",gap:ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:v.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...v.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...v.backButtonIcon},children:c("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:c("path",{d:"M15 18l-6-6 6-6"})})}),c(lo,{content:ye})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:ri,paddingRight:80,...v.title},children:`Pay with ${Jr(ln)}`})]}),c(Gr,{stripe:ht,options:ga,children:c(Ki,{method:ln,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:g,billingApiUrl:N,onTokenizedBody:An,onErrorChange:he,onDecline:p,onCancel:In,runBeforeButtonClick:lr,onButtonClick:Z,isProcessing:Ce,submitButtonColor:$r,submitButtonBorderRadius:Vt,submitButtonStyle:v.submitButton,errorText:P})},ln)]})})]})]})}return Os&&ln&&ga&&ht&&G?ze("form",{onSubmit:Qa,className:w,noValidate:!0,style:{position:"relative"},children:[c(Ui,{}),Un&&c(fr,{status:Un,errorMessage:P,authorized:Kn}),c("div",{style:{...ao?{animation:ao}:{},...We==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:ti,borderRadius:ii,...Oo,padding:ai},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:In,style:{display:"inline-flex",alignItems:"center",gap:ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:v.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...v.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...v.backButtonIcon},children:c("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:c("path",{d:"M15 18l-6-6 6-6"})})}),c(lo,{content:ye})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:ri,paddingRight:80,...v.title},children:`Pay with ${Jr(ln)}`})]}),c(Gr,{stripe:ht,options:ga,children:c(Ki,{method:ln,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:g,billingApiUrl:N,onTokenizedBody:An,onErrorChange:he,onDecline:p,onCancel:In,runBeforeButtonClick:lr,onButtonClick:Z,isProcessing:Ce,submitButtonColor:$r,submitButtonBorderRadius:Vt,submitButtonStyle:v.submitButton,errorText:P})},ln)]})})]}):ze("form",{onSubmit:Qa,className:w,noValidate:!0,style:{position:"relative"},children:[c(Ui,{}),Un&&c(fr,{status:Un,errorMessage:P,authorized:Kn}),ze("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ns("flopay-direct-paypal-gate-debug-default"),Ls("flopay-stripe-gate-debug-default"),xo&&ke&&ze(Yr,{children:[z&&c("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."}),c(ka,{sessionId:e,nonce:t,billingApiUrl:N,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,clientId:ke.clientId,environment:ke.environment,currency:Me.toUpperCase(),isSubscription:Ee,providerObjectType:B,approvalPresentation:ua==="popup"?void 0:ua,onTokenizedBody:An,onComplete:s,onErrorChange:he,onDecline:p,onTechnicalFailure:eo,onButtonClick:Z,runBeforeButtonClick:lr,isProcessing:Ce,onLoadStateChange:Ja,onInitializationStateChange:Xa,session:u,existingOrderId:z?.orderId,debug:H},z?.orderId??"fresh")]}),Mo&&c(Gr,{stripe:tn,options:cs,children:c(Al,{sessionId:e,nonce:t,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,billingApiUrl:N,onTokenizedBody:An,onErrorChange:he,isProcessing:Ce,onButtonClick:Z,onDecline:p,onTechnicalFailure:eo,runBeforeButtonClick:lr,onLoadStateChange:fs,placeholderBorderRadius:jr})}),no&&c(Gr,{stripe:ht,options:ls,children:c(xl,{sessionId:e,nonce:t,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,billingApiUrl:N,intentKind:xe>0?"payment":"setup",expressMethods:to,onTokenizedBody:An,onErrorChange:he,onButtonClick:Z,onDecline:p,onTechnicalFailure:eo,runBeforeButtonClick:lr,onLoadStateChange:hs,placeholderBorderRadius:jr})}),Bo&&c(Ml,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:N,paymentElementMethods:ca,stripeInstance:ht,paymentElementBaseOptions:Ya,onTokenizedBody:An,onErrorChange:he,onButtonClick:Z,onDecline:p,runBeforeButtonClick:lr,onLoadStateChange:Ps,isProcessing:Ce,submitButtonColor:$r,submitButtonBorderRadius:Vt,submitButtonStyle:v.submitButton,themeId:Ue,onExpandApm:Tr,expandedApmMethod:ln,buttonAppearance:{backgroundColor:v.cardButton?.backgroundColor,borderColor:v.cardInputBorder,textColor:v.cardButton?.color,borderRadius:jr}})]}),Le&&(sc||ic||lc)&&ze("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),c("span",{children:"or pay with card"}),c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Le&&Ds]})}import{Fragment as vr,jsx as oe,jsxs as en}from"react/jsx-runtime";var ko=44,rs="flopay_checkout_saved_payment_resume",$a=new Map,qa=new Map;function jl(e,t){t.settled&&t.consumers===0&&$a.get(e)===t&&$a.delete(e)}function Cu(e,t,n){let r=qa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};qa.set(e,i);let s=()=>{qa.get(e)===i&&qa.delete(e)};return o.then(s,s),o}function na(e){return new Promise(t=>setTimeout(t,e))}function ja(e,t,n){let r=wa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Jl,enabled:t!==!1});return r.beginCheckout(n),r}function ra(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Zi(e,t,n,r,o,i){let s=ja(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),ra(s)}function $l(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,o){let i=Gl(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 bn&&t.code==="session_auto_completed"?!1:t instanceof bn&&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 Xl(e,t){let n=e?.data.paypal?.publishableKey;if(n)return{clientId:n,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation,...t?{existingOrderId:t}:{}}}function Qi(e){return!e||e.data.stripe?.publishableKey?!1:!!Xl(e)?.clientId}var Su={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function wu(e){return new yu(Su,{publishableKey:"provider_unavailable",...e})}async function es(e,t){let{publishableKey:n,paypalPublishableKey:r}=Ai(e);return{...await xi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function os(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Iu(){if(!os())return null;try{let e=window.sessionStorage.getItem(rs);return e?JSON.parse(e):null}catch{return null}}function Vl(e){if(os())try{window.sessionStorage.setItem(rs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ts(){if(os())try{window.sessionStorage.removeItem(rs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function ku(){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 Hl(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 ns(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function _u(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Wl(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Ru(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 as({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:s,loading:l,error:p,onComplete:f,onError:C,onInstrument:h,onDecline:m,onCountryChange:w,onZipChange:_,showPayPal:ae=!0,showStripe:Y=!0,enabledPaymentMethods:Pe,showApplePay:S=!0,showGooglePay:G=!0,debug:X=!1,layout:ce,theme:Te,buttonsTheme:Fe,buttonsStyles:ve,cardButtonContent:Ue,cardBackButtonContent:bt,cardTitleContent:ot,showSecurityFooter:$e,onButtonClick:De,onBeforeButtonClick:ye,enableAVS:we,cardFieldOrder:Qe,cardPreFormSlot:Z,avsLayout:Ie,submitLabel:be,className:ct,initialErrorMessage:dt=null,initialPayPalOrderId:U,children:V,checkoutMode:de,confirmLabel:fe,renderConfirmButton:ut,onSessionCompleted:Ne}){let x=vu(r),at=tr(()=>Yl(Te),[Te]),Ye=i??at?.appearance,re=n?"embedded_checkout":"standard_checkout",Q=ns(V,ce),[L,Ae]=jt(null),[xe,Me]=jt(null),qe=Rt(null),ke=Rt(null),Ee=Rt(0),[ee,dn]=jt(null),Yt=Rt(null),[H,Je]=jt(null),$=tr(()=>n?Po(n):"",[n]),K=n?`create:${$}`:`session:${e??""}`,ie=Wl(H),u=Rt(new Set),B=Rt(K),_e=Rt(K);Uo(()=>{_e.current=K,B.current!==K&&(B.current=K,u.current.clear())},[K]);let Ke=Pn(T=>{if(_e.current===K){if(yi.has(T.name)){if(u.current.has(T.name))return;u.current.add(T.name)}Bt(()=>h?.(T))}},[K,h]),Re=go(Ke,K),$t=Rt(!1),N=Pn(T=>{if($t.current)return;let E=T.gateway||!ie?T:{...T,gateway:ie};Ke(E)},[Ke,ie]);ur(()=>{Re({class:"lifecycle",name:"checkout.mount"})},[Re]);let[Ct,Et]=jt(e??""),pt=e??Ct,un=n?"":pt,[O,Ot]=jt(!0),[Cn,pn]=jt(null),[mn,_n]=jt(0),[Fn,Dn]=jt("full"),[Jt,je]=jt(!1),[He,St]=jt(dt),[rn,wt]=jt(null),[$n,mt]=jt(null),[Tt,zt]=jt(!1),[yn,Ut]=jt(void 0),[At,Sn]=jt(""),[wn,It]=jt(!1),[te,on]=jt(!1),[Kn,Ht]=jt(!1),Kt=Rt(null),an=Rt(0),nr=Rt(void 0),[Nn,Wt]=jt("loading"),[Le,fn]=jt(0),se=Rt(!1),M=Rt(!1),Oe=Rt(!1),D=Rt(null),kt=Rt(null),xt=tr(()=>({checkoutMode:de??Fn,layout:_u(V,ce)}),[de,V,Fn,ce]),Gt=Rt(f);Gt.current=f;let Vn=Rt(C);Vn.current=C;let ge=Rt(m);ge.current=m;let sn=Pn(T=>Ma(D,async E=>{try{return await T(E)}catch(F){throw E.aborted?Zo(F):F}}),[]);ur(()=>()=>{D.current?.abort(),D.current=null},[]);let Hn=Pn((T,E)=>{qe.current=T,Me(T),Yt.current=E,dn(E)},[]),Pr=Pn(()=>{let T=ke.current;T&&(ke.current=null,T.destroy())},[]);ur(()=>{Qt(xe)?.setCheckoutContext(xt),ee&&ee!==xe&&Qt(ee)?.setCheckoutContext(xt)},[xe,ee,xt]);let rr=Rt(Ne);rr.current=Ne;let zr=Pn(T=>{Wt(T),!(T!=="exhausted"||Oe.current)&&(Oe.current=!0,Vn.current?.(new bn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Ur=Pn(()=>{Wt("retrying"),fn(T=>T+1)},[]);ur(()=>{Wt("loading"),fn(0),Oe.current=!1},[pt]),ur(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Jl,checkout_type:re,checkout_layout:Q,billing_api_url:x})},[Q,re,x]);let or=tr(()=>n?Po(n,!0):"",[n]),Er=tr(()=>At===or?yn:void 0,[yn,At,or]),Rn=tr(()=>n?di(n,Er):void 0,[n,Er]),ar=de??Rn?.checkoutMode??"full",Dt=tr(()=>Rn?{...Rn,checkoutMode:ar}:void 0,[Rn,ar]);ur(()=>{Ut(void 0),Sn(or),nr.current=void 0,Kt.current=null,Ht(!1)},[or]),ur(()=>{St(dt)},[dt]);let Ln=Pn((T,E,F)=>{Bt(()=>{ge.current?.(nn(T,E,F))})},[]),Wn=Pn(async(T,E)=>{St(null),mt(null),zt(!1),wt("processing");let F=E?.sessionId??T.id,z=T.clientSecret||t,it=Wl(T),R=qe.current??Yt.current,d=Qt(R),A=R?null:ja(x,o,xt),g={log:y=>{d?d.log(y):A?.log(y)},error:y=>{d?d.error(y):A?.error(y)},terminal:y=>{d?d.terminal(y):A?.terminal(y)},performance:y=>{d?d.performance(y):A?.performance(y)},now:()=>d?.now()??A?.now()??0,elapsed:y=>d?.elapsed(y)??Math.max(0,(A?.now()??y)-y)},P=g.now(),I=!!(E?.initialAutoProcessingError||E?.initialAutoProcessingPending),v=!1,q,Ve=()=>{v||(v=!0,I=!0,q=g.now(),g.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),g.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Nt=!1,Ce=()=>{Nt||(Nt=!0,g.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),g.performance({stage:"processing",durationMs:g.elapsed(P),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),q!==void 0&&g.performance({stage:"recovery",durationMs:g.elapsed(q),durationMode:"machine",paymentMethodCategory:"saved"}))};g.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),$t.current=!0;try{g.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{$t.current=!1}Re({class:"lifecycle",name:"payment.processing.started",provider:it}),I&&Ve();let ne;try{let y=fl(E?.initialAutoProcessingError),k=E?.initialAutoProcessingError?.type==="3ds_required"&&!E.initialAutoProcessingError.threeDSecureToken&&E.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:E.initialAutoProcessingError.nextActionRedirectUrl}:null,J,ue=Se=>(Ve(),sn(pe=>Co(Se,{billingApiUrl:x,sessionId:F,nonce:z,session:T,signal:pe})));if(k)J=await ue(k);else if(y)Ve(),y.type==="paypal_redirect_required"&&kt.current?.publishableKey&&Vl({sessionId:F,publishableKey:kt.current.publishableKey,paypalPublishableKey:kt.current.paypalPublishableKey}),J=await sn(Se=>Fa(y,{flopay:qe.current,paypalFlopay:Yt.current,attempt3DS:E?.attempt3DS,billingApiUrl:x,sessionId:F,session:T,telemetry:!1,signal:Se})),y.type==="paypal_redirect_required"&&ts();else if(E?.initialAutoProcessingPending){let Se=E.initialAutoProcessingPending,pe=new Ua(x,{telemetry:!1}),Ge=await sn(qn=>pe.waitForCheckoutSessionCompletion(Se.sessionId,{initialDelayMs:Se.retryAfterMs,nonce:z,statusUrl:Se.statusUrl,signal:qn})),ht=Ge.data.session,tn=Ge.autoProcessingError?.type==="3ds_required"&&Ge.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Ge.autoProcessingError.nextActionRedirectUrl}:null;if(tn)J=await ue(tn);else{if(!Mr(ht))throw po(ht);J=Sr(ht,F)}}else{if(E?.initialAutoProcessingError)throw gr(E.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:E.initialAutoProcessingError.checkoutMethod});if(E?.fromCreateSession)return E?.fallbackToFull&&(Dn("full"),Hl("full")),!1;{let Se=await So({billingApiUrl:x,sessionId:F,session:T,nonce:z,telemetry:!1});Se.type==="success"?J=Se.result:Se.type==="next_action_required"?J=await ue(Se):(Ve(),Se.type==="paypal_redirect_required"&&kt.current?.publishableKey&&Vl({sessionId:F,publishableKey:kt.current.publishableKey,paypalPublishableKey:kt.current.paypalPublishableKey}),J=await sn(pe=>Fa(Se,{flopay:qe.current,paypalFlopay:Yt.current,attempt3DS:E?.attempt3DS,billingApiUrl:x,sessionId:F,session:T,telemetry:!1,signal:pe})),Se.type==="paypal_redirect_required"&&ts())}}F&&bo(F),Ce(),I&&(g.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),g.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),g.terminal({outcome:J.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),zt(J.status==="authorized"),wt("success"),await na(600),ne=()=>Gt.current?.(J)}catch(y){let k=Qo(y);if(k.code==="three_ds_aborted")return!1;let J=k.checkoutMethod??Xo;St(k.message),mt(k.message),zt(!1),E?.fallbackToFull&&(g.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Dn("full"),Hl("full")),Ce();let ue=k.statusCode===void 0?void 0:bu(k.statusCode,"unknown"),Se=ue==="4xx"?{requestCategory:"process_payment",statusClass:ue}:{},pe=ue===void 0||ue==="4xx";if(pe&&(k.telemetryOutcome==="payment_declined"||!!(k.declineCode||k.code?.toLowerCase().includes("declin"))))g.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Se});else if(pe&&(k.telemetryOutcome==="validation_rejected"||k.type==="validation_error"))g.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Se});else{let tn=Gl(y,I?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),qn=k.telemetryRequestCategory??"process_payment";$t.current=!0;try{g.error({...tn,...k.telemetryFailureCategory?{failureCategory:k.telemetryFailureCategory}:{},stage:I?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:qn})}finally{$t.current=!1}Re({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:qn,provider:it})}return Bt(()=>Vn.current?.(k)),Ln(J,k,{code:k.code,declineCode:k.declineCode}),wt("error"),await Promise.allSettled([na(400),E?.ensureProvidersReady?E.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{Ce(),A&&ra(A),wt(null),mt(null)}return Bt(ne),!0},[Ln,Re,t,x,sn,o,xt]);ur(()=>{if(typeof window>"u"||M.current)return;let T=new URLSearchParams(window.location.search),E=T.get("payment_intent_client_secret");if(!E)return;let F=Iu();F&&(M.current=!0,(async()=>{let z,it=0;St(null),mt(null),wt("processing"),je(!0);try{if(T.get("redirect_status")==="failed")throw Object.assign(new bn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:R,paypalFlopay:d}=await xi({publishableKey:F.publishableKey,paypalPublishableKey:F.paypalPublishableKey,billingApiUrl:x,locale:s,telemetry:o});z=Qt(d??R),z?.setCheckoutContext(xt),it=z?.now()??0,z?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),z?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let A=(d??R)?.getRawProvider();if(!A)throw Object.assign(new bn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:g,error:P}=await A.retrievePaymentIntent(E);if(P)throw Object.assign(new bn(P.message??"Failed to retrieve PayPal payment status.","api_error",{code:P.code}),{checkoutMethod:"paypal"});let I=Ys(g?.status);if(!g||I==="failed")throw Object.assign(new bn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let v=typeof g.payment_method=="string"?g.payment_method:g.payment_method?.id,q=I;if(F.sessionId){let Ce=(await new Ua(x,{telemetry:!1}).getUnifiedCheckoutSession(F.sessionId)).data.session;if(Ce&&Ce.status!=="complete"){let ne=await So({billingApiUrl:x,sessionId:F.sessionId,session:Ce,telemetry:!1,tokenizedData:{id:v??g.id,type:"card",threeDSecureActionResultTokenId:g.id,isPaypal:!0}});if(ne.type!=="success")throw Object.assign(new bn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});q=ne.result.status}}F.sessionId&&bo(F.sessionId),z?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),z?.performance({stage:"redirect_resume",durationMs:z.elapsed(it),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),z?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),wt("success"),await na(600),Bt(()=>Gt.current?.({status:q,paymentIntentId:g.id,paymentMethodId:v,checkoutMethod:"paypal"}))}catch(R){let d=Qo(R),A=d.checkoutMethod??"paypal",g=!!(d.declineCode||d.code?.toLowerCase().includes("declin"));if(z)z.performance({stage:"redirect_resume",durationMs:z.elapsed(it),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),g?z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):z.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(g){let P=ja(x,o,xt);P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ra(P)}else Zi(x,o,xt,"REDIRECT_RESUME_FAILED","redirect_resume");St(d.message),mt(d.message),Bt(()=>Vn.current?.(d)),Ln(A,d,{code:d.code,declineCode:d.declineCode}),wt("error"),await na(400)}finally{ts(),ku(),wt(null),mt(null),je(!1)}})())},[Ln,s,x,o,xt]);let Gn=Rt(null),yt=tr(()=>Dt?Po(Dt):"",[Dt]),En=Rt(Dt);En.current=Dt,ur(()=>{Et(e??"")},[e]),ur(()=>{se.current=!1,St(dt),mt(null),zt(!1),wt(null)},[yt,dt,e]);async function Yn(T,E,F){let z=ja(x,o,xt),it=new Ua(x,{telemetry:!1}),R=!1;try{let d=T.idempotencyKey===void 0?void 0:ql(T.idempotencyKey),A=wi(E,F),g=Ii(E,F);A?.canonicalIdentity===F&&g&&g.canonicalIdentity===void 0&&(Ta(E,F,g.idempotencyKey),g={...g,canonicalIdentity:F});let P=d??(g?.canonicalIdentity===F?g.idempotencyKey:void 0),I,v=!1;z.log({name:A?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let q=A?.sid??null,Ve=null,Nt,Ce,ne=!1;if(q)try{Ve=await it.getUnifiedCheckoutSession(q,A?.nonce),A&&A.canonicalIdentity===void 0&&(ll(Ve.data.session,T)?(Ea(E,F,q,A.nonce??Ve.data.session?.clientSecret),g&&g.canonicalIdentity===void 0&&(Ta(E,F,g.idempotencyKey),P??(P=g.idempotencyKey))):(Ra(E,F),g=null,P=d,q=null,Ve=null));let k=Ve?.data.session?.status,J=Ve?.data.session,ue=J?.clientSecret||A?.nonce;if(q&&J?.buyerIdentified===!1&&ue&&(Ce=uo(it,q,ue,T.account)),q&&Ve&&k==="complete"){if(ki(q))return{sid:q,result:Ve};Ra(E,F),q=null,Ve=null,v=!0}}catch{z.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),A?.canonicalIdentity===void 0?(Ra(E,F),P=d):_a(E,F),q=null}if(!q){!d&&(v||!P)&&(P=ql(),I=P),P&&Ta(E,F,P);let k=z.now(),J=0;z.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ue={...T,idempotencyKey:P,avsCheck:!!we,avsConfig:typeof we=="object"?we:void 0,checkoutType:"embedded_checkout",checkoutLayout:ns(V,ce)};Object.defineProperty(ue,fu,{configurable:!1,enumerable:!1,value:{onAttempt:Ge=>{J=Math.max(J,Ge)}}});let Se=()=>{$l(z,"session_create",k,J)},pe=Ge=>{Kl(z,Ge,"session_create",k,J)&&Re({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(hu(ue)){let Ge=await it.createDetachedSession(ue);Ge.claimed.catch(()=>{}),Ve=Ge.shell,q=Ge.sessionId,Ce=Ge.claim;let ht=z.now();z.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Nt=Ge.claimed.then(tn=>{let qn=tn.data.session?.id??Ge.sessionId;return qn&&Ea(E,F,qn,tn.data.session?.clientSecret??Ge.nonce),$l(z,"session_claim",ht),Se(),tn},tn=>{throw _a(E,F),Kl(z,tn,"session_claim",ht,0)&&Re({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),tn}).finally(()=>ra(z)),Nt.catch(()=>{}),R=!0,z.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),z.performance({stage:"session_shell",durationMs:z.now()-k,durationMode:"machine",requestCategory:"session_create",attempt:J,statusClass:"2xx",paymentMethodCategory:"card"})}else Ve=await it.createAndFetchSession(ue),Se()}catch(Ge){throw pe(Ge),Ge}q=Ve.data.session?.id??q??"",q&&!Nt&&Ea(E,F,q,Ve.data.session?.clientSecret)}let y=Ve?.data.session;return!Ce&&q&&y?.buyerIdentified===!1&&y.clientSecret&&(Ce=uo(it,q,y.clientSecret,T.account)),{sid:q??"",result:Ve,sdkGeneratedIdempotencyKey:I,...Nt?{claimed:Nt}:{},...Ce?{claim:Ce}:{},...ne?{claimRequiresIdentity:!0}:{}}}finally{R||ra(z)}}let ir=Rt(Yn);Uo(()=>{ir.current=Yn},[Yn]);let gn=Pn(async(T,E)=>{let F=En.current;if(!F)throw new bn("createSession is required to bootstrap checkout.","validation_error");let z=di(F,T),it=Po(z),R=sl(z),d=$a.get(it);if(!d){let P={canonicalIdentity:it,promise:ir.current(z,R,it),consumers:0,settled:!1};d=P,$a.set(it,P);let I=()=>{P.settled=!0,jl(it,P)};P.promise.then(I,I)}d.consumers+=1;let A=!1,g=()=>{A||(A=!0,d.consumers-=1,jl(it,d))};E?.(g);try{let P=await d.promise;Gn.current=it,T&&(Sn(or),Ut(y=>Hs(y,T)));let{sid:I,result:v,claimed:q,claim:Ve,claimRequiresIdentity:Nt}=P;if(nr.current=Ve,Ht(Nt===!0),Ae(v),v.data.session&&Je(v.data.session),I&&Et(I),q){an.current+=1;let y=an.current;Kt.current=q,on(!0),q.then(k=>{an.current===y&&(Kt.current===q&&(Kt.current=null),Ae(k),k.data.session&&Je(k.data.session),on(!1),Ht(!1))},k=>{an.current===y&&(Kt.current===q&&(Kt.current=null),on(!1),Ht(!1),pn(k instanceof bn?k:new bn(k instanceof Error?k.message:"Failed to create session","api_error")))})}else an.current+=1,Kt.current=null,on(!1),Ht(!1);let{flopay:Ce,paypalFlopay:ne}=await es(v,{billingApiUrl:x,locale:s,telemetry:o});return Hn(Ce,ne),Ot(!1),P}catch(P){throw Gn.current===it&&(Gn.current=null),P}finally{E||g()}},[or,Hn,s,x,o]),We=Rt(Wn);We.current=Wn;let hn=Rt(gn);hn.current=gn;let ln=Pn(async T=>{if(!Ru(T)||wn)return{sessionId:Ct,session:H};It(!0);try{let E=await gn(T);return{sessionId:E.sid,session:E.result.data.session??null}}finally{It(!1)}},[gn,wn,Ct,H]),On=Pn(async T=>{let E=nr.current;if(!E)return;let F=an.current,z=await E(T);an.current===F&&(Ae(z),z.data.session&&Je(z.data.session))},[]),br=Pn(async()=>{await Kt.current},[]),qr=Pn(async()=>(await br(),{proceed:!0}),[br]);ur(()=>{let T=!1,E,F=++Ee.current;Pr(),pn(null),_n(0);let z=()=>{T=!0,Ee.current===F&&(Ee.current+=1,Pr())},it=En.current;if(yt&&it)return Dn(ar),Ot(!1),Gn.current===yt?z:(Je(Ws(it,de)),(async()=>{let A=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),g=ar==="auto"&&!se.current&&!A;g&&(St(null),mt(null),wt("processing"));try{let P=await hn.current(void 0,Ve=>{E=Ve}),I=P.result.data.session??null;kt.current=Ai(P.result);let v=Qi(P.result),q=ki(P.sid||I?.id);if(!T&&g&&I&&!v&&!q){se.current=!0,await Cu(yt,P.sdkGeneratedIdempotencyKey,()=>We.current(I,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:P.result.autoProcessingError,initialAutoProcessingPending:P.result.autoProcessingPending,autoProcessingAttempted:P.result.autoProcessingAttempted,sessionId:P.sid||I.id}));return}!T&&g&&((v||q)&&(se.current=!0),wt(null),mt(null))}catch(P){if(T)return;let I=va(P);if(g&&I==="session_auto_completed"){se.current=!0,wt("success"),await na(600),T||(Bt(()=>{Gt.current?.({status:"succeeded"})}),wt(null),mt(null));return}g&&(wt(null),mt(null));let v=P instanceof bn?P:new bn(P instanceof Error?P.message:"Failed to create session","api_error");pn(v)}finally{E?.(),E=void 0}})(),()=>{z(),E?.()});Ot(!0);async function R(){let A=!1,g=null;try{let P=new Ua(x,{telemetry:!1}),I=await P.getUnifiedCheckoutSession(pt,t);if(g=I,T)return;Ae(I);let v=I.data.session??null;if(Je(v),!v)throw new bn("No session data returned","api_error");let q=v.checkoutMode;if(q==="setup")throw new bn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(v.status==="authorized"){Ot(!1),Bt(()=>{Gt.current?.(Sr(v,pt)),rr.current?.(v.successUrl??"")});return}if(v.status==="complete"){Ot(!1),Bt(()=>{rr.current?.(v.successUrl??"")});return}if(v.status==="expired")throw ha(v);A=!0;let Ve=de??q??"full";Dn(Ve),an.current+=1;let Nt=v.clientSecret||t;nr.current=v.buyerIdentified===!1&&Nt?uo(P,pt,Nt,{...v.customer?.id?{userId:v.customer.id}:{}}):void 0,on(!1),Ht(!1);let Ce=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ne=Qi(I);if(Ve==="auto"&&!se.current&&!Ce&&!ne){se.current=!0;let y=d(I);try{if(await We.current(v,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>y,sessionId:pt||v.id}),T)return;await y,T||Ot(!1);return}catch{if(T)return;await y,T||Ot(!1);return}}await d(I),T||Ot(!1)}catch(P){if(T)return;let I=Vs(P,A);if(A&&Re({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),I){let{errorCode:q,stage:Ve,...Nt}=I;Zi(x,o,xt,q,Ve,Nt)}if(I?.stage==="provider_load"&&(de??g?.data.session?.checkoutMode??"full")==="full"&&Ks(g,ae,Y)){let q=wu({billingApiUrl:x,locale:s,telemetry:o});ke.current=q,Hn(q,null),_n(1),Ot(!1);return}let v=P instanceof bn&&I?.stage!=="provider_load"?P:$s();v!==P&&Bt(()=>Vn.current?.(v)),pn(v),Ot(!1)}}async function d(A){let{flopay:g,paypalFlopay:P,...I}=await es(A,{billingApiUrl:x,locale:s,telemetry:o});kt.current={publishableKey:I.publishableKey,paypalPublishableKey:I.paypalPublishableKey},Hn(g,P),_n(0)}return R(),z},[de,yt,ar,un,t,ae,Y]);let Cr=Pn(async()=>{if(!L||mn!==1)return;let T=Ee.current;_n(2);try{let{flopay:E,paypalFlopay:F}=await es(L,{billingApiUrl:x,locale:s,telemetry:o});if(Ee.current!==T)return;Pr(),Hn(E,F),_n(0)}catch(E){if(Ee.current!==T)return;let{errorCode:F,stage:z,...it}=li(E);Zi(x,o,xt,F,z,it)}},[Pr,Hn,s,mn,x,o,xt,L]),zn=!!(pt&&(H?.clientSecret||t)),vn=Jt||!zn,Xr=Pn(async()=>{if(!(Jt||!zn||!H)){je(!0),St(null);try{await Wn(H,{attempt3DS:!0,fallbackToFull:!0,sessionId:pt||H.id})}finally{je(!1)}}},[pt,Jt,zn,Wn,H]),Tn=Xl(L,U),Tr=Qi(L),In=tr(()=>{if(!(!L||!H||!L.data.stripe?.publishableKey))return{billingApiUrl:x}},[L,H,x]),Un=!!(n&&!V&&ce==="buttons"&&ye&&ar==="full"),et=!!(pt&&(H?.vault?.html||Ar(H))),Jn=tr(()=>({session:H,loading:O,error:Cn,checkoutMode:Fn,inlineSessionDraft:Dt,applyInlineSessionPatch:Un?ln:void 0,inlineSessionPatchProcessing:wn,claimPending:te,claimRequiresIdentity:Kn,claimBuyerIdentity:On,waitForDataAttachment:br}),[H,O,Cn,Fn,Dt,Un,ln,wn,te,Kn,On,br]),Xt=!!n&&ce==="buttons"&&!Tr&&!et&&(!xe||!In),_t=rn?oe(fr,{status:rn,errorMessage:$n,authorized:Tt}):null;if(O&&!et){if(l)return en(vr,{children:[l,_t]});if(ce==="buttons"){let T=at?.buttonsLayout?.cardButton?.borderRadius??at?.appearance.variables?.borderRadius??8,E=F=>oe("div",{style:{height:F,borderRadius:T,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return en(vr,{children:[en("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ae&&E(ko),Y&&(S||G)&&E(ko),Y&&E(ko),oe("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),_t]})}return en(vr,{children:[en("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[oe("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),oe("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),_t]})}return Cn?p?oe(cr.Provider,{value:Jn,children:p(Cn)}):oe(cr.Provider,{value:Jn,children:oe("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Cn.message})}):Xt?en(vr,{children:[oe(cr.Provider,{value:Jn,children:oe(Tu,{onButtonClick:De,showPayPal:ae,showStripe:Y,showApplePay:S,showGooglePay:G,theme:Te,buttonsTheme:Fe,buttonsStyles:ve,cardButtonContent:Ue,cardBackButtonContent:bt,cardTitleContent:ot})}),_t]}):Tr&&H&&Tn?en(vr,{children:[oe(cr.Provider,{value:Jn,children:en("div",{className:ct,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[He&&oe(ho,{icon:!1,children:He}),Nn==="retrying"&&oe("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Nn==="exhausted"&&en("div",{role:"alert",children:[oe("div",{children:"PayPal is temporarily unavailable. Please try again."}),oe("button",{type:"button",onClick:Ur,children:"Retry PayPal"})]}),Nn!=="exhausted"&&oe("div",{"aria-hidden":Nn==="retrying"?!0:void 0,style:Nn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:oe(al,{sessionId:pt,nonce:H.clientSecret||void 0,billingApiUrl:x,email:H.customer?.email||Dt?.account?.email,billingName:[H.customer?.firstName,H.customer?.lastName].filter(Boolean).join(" ")||[Dt?.account?.firstName,Dt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:On,clientId:Tn.clientId,environment:Tn.environment,currency:(H.currency??"usd").toUpperCase(),isSubscription:H.mode==="subscription",providerObjectType:Tn.providerObjectType,approvalPresentation:Tn.approvalPresentation,existingOrderId:Tn.existingOrderId,onComplete:f,onErrorChange:St,onDecline:m,onButtonClick:De,runBeforeButtonClick:qr,onInitializationStateChange:zr,allowAutomaticRetry:Le===0,session:H,telemetry:o,telemetryContext:xt,onInstrument:N,debug:X},`${K}:paypal-init-${Le}`)})]})}),_t]}):Fn==="confirm"?en(vr,{children:[oe(cr.Provider,{value:Jn,children:oe(Aa,{flopay:xe,paypalFlopay:ee,options:In??{billingApiUrl:x},onInstrument:N,children:en("div",{className:ct,children:[He&&oe("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:He}),ut?ut({onConfirm:Xr,isProcessing:vn}):oe("button",{type:"button",onClick:Xr,disabled:vn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:vn?"not-allowed":"pointer",opacity:vn?.6:1},children:Jt?"Processing...":fe??"Confirm Purchase"})]})},K)}),_t]}):(!xe||!In)&&!(et&&Fn==="full")?oe(vr,{children:_t}):en(vr,{children:[oe(cr.Provider,{value:Jn,children:en(Aa,{flopay:xe,paypalFlopay:ee,options:In??{billingApiUrl:x},onInstrument:N,children:[mn===1&&oe("button",{type:"button",onClick:Cr,children:"Retry payment methods"}),V?en(vr,{children:[He&&oe("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:He}),oe(Eu,{sessionId:pt,nonce:H?.clientSecret||void 0,billingApiUrl:x,session:H,submitLabel:be,children:V})]}):oe(Ji,{sessionId:pt,nonce:H?.clientSecret||void 0,telemetry:o,email:H?.customer?.email||Dt?.account?.email,userId:H?.customer?.id||Dt?.account?.userId,firstName:H?.customer?.firstName||Dt?.account?.firstName,lastName:H?.customer?.lastName||Dt?.account?.lastName,totalAmount:H?Math.round(gu(H).total*100):0,currency:H?.currency?.toLowerCase()??"usd",onComplete:f,onError:C,onDecline:m,error:He,onErrorChange:St,showPayPal:ae,showStripe:Y,enabledPaymentMethods:mn?[]:Pe??L?.data.stripe?.enabledPaymentMethods??H?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:L?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:G,layout:ce,theme:Te,buttonsTheme:Fe,buttonsStyles:ve,appearance:Ye,cardButtonContent:Ue,cardBackButtonContent:bt,cardTitleContent:ot,onButtonClick:De,onBeforeButtonClick:ye,onBuyerIdentityReady:On,enableAVS:we,...Qe?{cardFieldOrder:Qe}:{},...Z?{cardPreFormSlot:Z}:{},avsLayout:Ie,country:H?.customer?.country,city:H?.customer?.city,state:H?.customer?.state,onCountryChange:w,onZipChange:_,avsCheck:!!we,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ns(V,ce),className:ct,submitLabel:be,directPaypal:Tn,isSubscription:H?.mode==="subscription",session:H,dataAttachmentPending:te,dataAttachmentRequiresIdentity:Kn,debug:X})]},K)}),_t]})}function Eu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,children:i}){return oe(vr,{children:Xi.Children.map(i,s=>{if(!Xi.isValidElement(s))return s;let l=s.props,p={};return l.sessionId||(p.sessionId=e),!l.nonce&&t&&(p.nonce=t),l.billingApiUrl||(p.billingApiUrl=n),l.submitLabel===void 0&&o!==void 0&&(p.submitLabel=o),r?.customer&&(l.email||(p.email=r.customer.email),l.userId||(p.userId=r.customer.id),l.firstName||(p.firstName=r.customer.firstName),l.lastName||(p.lastName=r.customer.lastName)),Object.keys(p).length===0?s:Xi.cloneElement(s,p)})})}function Tu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:p,cardBackButtonContent:f,cardTitleContent:C}){let[h,m]=jt(!1),w=tr(()=>Yl(i),[i]),_=tr(()=>{let S=w?.buttonsLayout??Pu(s);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},[w,s,l]),ae=w?.buttonsLayout?.cardButton?.borderRadius??w?.appearance.variables?.borderRadius??8,Y=S=>oe("div",{style:{height:S,borderRadius:ae,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),Pe=p===void 0?{boxSizing:"border-box",height:ko,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(h){let S=_.cardInputBorder??"#e5e7eb",G=_.cardInputBackground??"white",X=io(f),ce=io(C);return en("div",{style:{backgroundColor:_.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",..._.cardFormContainer},children:[en("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[en("button",{type:"button",onClick:()=>m(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:X?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",..._.backButton},children:[oe("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",..._.backButtonIcon},children:oe("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:oe("path",{d:"M15 18l-6-6 6-6"})})}),oe(lo,{content:f})]}),ce?oe("div",{style:{flex:1}}):oe("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,..._.title},children:oe(jo,{content:C})})]}),oe("div",{style:{backgroundColor:G,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:oe("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:[oe("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:oe("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),oe("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:oe("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),oe("div",{style:{backgroundColor:G,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:oe("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),oe("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",..._.submitButton,opacity:.5}}),oe("style",{children:`
33
+ `}),Wo&&Un&&Fe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:X?-2:0},children:[Fe("button",{type:"button",onClick:Fr,style:{display:"inline-flex",alignItems:"center",gap:Si?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:C.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...C.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...C.backButtonIcon},children:u("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:u("path",{d:"M15 18l-6-6 6-6"})})}),u(Po,{content:Re})]}),tl?u("div",{style:{flex:1}}):u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:C.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...C.title},children:u(ea,{content:Oe})})]}),!Wo&&!tl&&u("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ki,order:X?-3:0,...C.title},children:u(ea,{content:Oe})}),X&&qe&&u("div",{style:{order:-2,width:"100%"},children:qe}),X&&Cn&&Fe("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[u("div",{style:{backgroundColor:yo,border:`1px solid ${Xn(xa)}`,borderRadius:Gt,padding:"10px"},children:u("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Kt,onChange:a=>{At("email"),yn.current=a.target.value,on(a.target.value)},onPointerDown:()=>At("email"),onKeyDown:()=>At("email"),onBlur:()=>{nr("email")&&xn(!0),ao||yi()},disabled:B,required:!0,"aria-invalid":xa||void 0,"aria-describedby":xa?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ii}})}),xa&&u("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Yo,children:vr.empty?"Email address is required":"Enter a valid email address"})]}),H&&u("div",{style:{order:X?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=Mt,f=(W=!1)=>({backgroundColor:yo,border:`1px solid ${Xn(W)}`,borderRadius:Gt,marginTop:"0.5rem",padding:"10px"}),q=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ii}),Se=ru(a);return Fe(ro,{children:[at(H.address_line_1,a)&&Fe(ro,{children:[u("div",{style:f(Lt("line1")),children:u("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:tn,onChange:W=>{At("line1"),yt.current.addressLine1=!0,pn.current=W.target.value,fe(W.target.value)},onPointerDown:()=>At("line1"),onKeyDown:()=>At("line1"),onBlur:()=>In("line1"),disabled:B,required:!0,"aria-invalid":Lt("line1")||void 0,"aria-describedby":Lt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:q()})}),Lt("line1")&&u("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Yo,children:"Street address is required"})]}),at(H.address_line_2,a)&&u("div",{style:f(),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:gt,onChange:W=>{yt.current.addressLine2=!0,Dt.current=W.target.value,Et(W.target.value)},disabled:B,"data-testid":"flopay-address-line2",style:q()})}),(at(H.city,a)||at(H.state,a))&&Fe("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[at(H.city,a)&&u("div",{style:{flex:1,backgroundColor:yo,borderTop:`1px solid ${Xn(Lt("city"))}`,borderRight:`1px solid ${Xn(Lt("city"))}`,borderBottom:`1px solid ${Xn(Lt("city"))}`,borderLeft:`1px solid ${Xn(Lt("city"))}`,padding:"10px",borderTopLeftRadius:Gt,borderBottomLeftRadius:Gt,...at(H.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Gt}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:vn,onChange:W=>{At("city"),yt.current.city=!0,Xt.current=W.target.value,Bt(W.target.value)},onPointerDown:()=>At("city"),onKeyDown:()=>At("city"),onBlur:()=>In("city"),disabled:B,required:!0,"aria-invalid":Lt("city")||void 0,"aria-describedby":Lt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:q()})}),at(H.state,a)&&u("div",{style:{flex:1,backgroundColor:yo,borderTop:`1px solid ${Xn(Lt("state"))}`,borderRight:`1px solid ${Xn(Lt("state"))}`,borderBottom:`1px solid ${Xn(Lt("state"))}`,borderLeft:`1px solid ${Xn(Lt("state"))}`,padding:"10px",borderTopRightRadius:Gt,borderBottomRightRadius:Gt,...at(H.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Xn(Lt("state")||Lt("city"))}`}:{borderRadius:Gt}},children:Se?Fe("select",{id:"flopay-billing-state",name:"billing-state",value:Kn,onChange:W=>{At("state"),yt.current.state=!0,Vt.current=W.target.value,dn(W.target.value)},onPointerDown:()=>At("state"),onKeyDown:()=>At("state"),onBlur:()=>In("state"),disabled:B,autoComplete:"billing address-level1",required:!0,"aria-invalid":Lt("state")||void 0,"aria-describedby":Lt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...q(),cursor:"pointer"},children:[u("option",{value:"",children:Zi(a)}),Se.map(W=>u("option",{value:W.code,children:W.name},W.code))]}):u("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Zi(a),autoComplete:"billing address-level1",value:Kn,onChange:W=>{At("state"),yt.current.state=!0,Vt.current=W.target.value,dn(W.target.value)},onPointerDown:()=>At("state"),onKeyDown:()=>At("state"),onBlur:()=>In("state"),disabled:B,required:!0,"aria-invalid":Lt("state")||void 0,"aria-describedby":Lt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:q()})})]}),Lt("city")&&u("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Yo,children:"City is required"}),Lt("state")&&Fe("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Yo,children:[Zi(a)," is required"]}),(at(H.country,a)||at(H.postal_code,a))&&Fe("div",{style:{display:"flex",flexDirection:ce==="column"?"column":"row",gap:ce==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[at(H.country,a)&&u("div",{style:{flex:ce==="row"?1:void 0,backgroundColor:yo,borderTop:`1px solid ${Go}`,borderRight:`1px solid ${Go}`,borderBottom:`1px solid ${Go}`,borderLeft:`1px solid ${Go}`,padding:"10px",...ce==="row"&&at(H.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:Gt,borderBottomLeftRadius:Gt,borderRight:"none"}:{borderRadius:Gt}},children:Fe("select",{id:"flopay-billing-country",name:"billing-country",value:Mt,onChange:W=>{yt.current.country=!0,Jt.current=W.target.value,kn(W.target.value),nt?.(W.target.value),Vt.current="",dn("")},disabled:B,autoComplete:"billing country","data-testid":"flopay-country",style:{...q(),cursor:"pointer"},children:[Mt===""?u("option",{value:"",children:"Select country"}):null,Qd.map(W=>Fe("option",{value:W.code,children:[W.flag," ",W.name]},W.code))]})}),at(H.postal_code,a)&&u("div",{style:{flex:ce==="row"?1:void 0,backgroundColor:yo,border:`1px solid ${qc}`,padding:"10px",...ce==="row"&&at(H.country,a)?{borderRadius:"0",borderTopRightRadius:Gt,borderBottomRightRadius:Gt}:{borderRadius:Gt}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:is(Mt),autoComplete:"billing postal-code",value:On,onChange:W=>{At("zip"),yt.current.zip=!0,ht.current=W.target.value,Nn(W.target.value),_e?.(W.target.value)},onPointerDown:()=>At("zip"),onKeyDown:()=>At("zip"),onBlur:()=>{nr("zip")&&An(!0)},disabled:B,required:fn.required,"aria-invalid":Ma||void 0,"aria-describedby":Ma?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:q()})})]}),Ma&&u("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Yo,children:fn.empty?`${is(a)} is required`:Nu(a)})]})})()}),X&&Hc,Be&&u(_o,{margin:"0.75rem 0",styleOverride:C.errorBanner,children:Be})]}),Ba={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"},il=a=>L?!E||!Cr?u("pre",{"data-testid":a,style:Ba,children:"FloPay/DirectPayPal-debug - not enabled"}):u("pre",{"data-testid":a,style:Ba,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${E}`,` directPaypalConfigured=${Cr}`,` inAppBrowserDetected=${String(Ea)}`,` shouldRenderDirectPayPal=${jo}`,` shouldRenderStripePayPal=${Ko}`,` hasPaypalStripeInstance=${!!Es}`].join(`
34
+ `)}):null,sl=a=>L?!J||!qn?u("pre",{"data-testid":a,style:Ba,children:"FloPay/Stripe-debug - not enabled"}):u("pre",{"data-testid":a,style:Ba,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${J}`,` currency=${en}`,` amountInCents=${zo}`,` enabledPaymentMethods: ${JSON.stringify(se??[])}`,` enabledPaymentMethodsProvided=${Uo}`,` hasEnabledMethods=${ka}`,` expressMethods: ${JSON.stringify(_a)}`,` walletExpressMethods: ${JSON.stringify(uo)}`,` paymentElementMethods: ${JSON.stringify(qo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ra)}`,` hasStripeInstance=${!!qn}`,` shouldRenderWallets=${po}`,` shouldRenderPaymentElement=${Vo}`].join(`
35
+ `)}):null,ll=st==="apm-expanding"||st==="apm-form"||st==="apm-collapsing",fo;st==="apm-expanding"?fo=ec:st==="apm-collapsing"&&(fo=tc);let Fa=Qt?hc(gi,Qt):null;if(be==="buttons"){let a=st==="buttons"||st==="expanding"||st==="apm-expanding",f=st==="expanding"||st==="card"||st==="collapsing",q=_t===void 0?{boxSizing:"border-box",height:ha,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Se;st==="expanding"||st==="apm-expanding"?Se=Mu:(st==="collapsing"||st==="apm-collapsing")&&(Se=xu);let W;return st==="expanding"?W=ec:st==="collapsing"&&(W=tc),Fe("form",{onSubmit:bi,className:M,noValidate:!0,style:{position:"relative"},children:[u(as,{}),R&&u(kr,{status:R,errorMessage:Be,authorized:zn}),Fe("div",{style:{display:"grid"},children:[Fe("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!Se?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!Se?Fu:{},...Se?{animation:Se,pointerEvents:"none"}:{}},children:[il("flopay-direct-paypal-gate-debug"),sl("flopay-stripe-gate-debug"),jo&&lt&&Fe(ro,{children:[d&&u("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."}),u(ia.Provider,{value:N,children:u(Va,{sessionId:e,nonce:t,billingApiUrl:Ze,email:P.email,billingName:Te||void 0,onBuyerIdentityReady:$,clientId:lt.clientId,environment:lt.environment,currency:en.toUpperCase(),isSubscription:it,providerObjectType:Xe,approvalPresentation:Ta==="popup"?void 0:Ta,onTokenizedBody:Mn,onComplete:s,onErrorChange:ve,onDecline:m,onTechnicalFailure:lo,onButtonClick:le,runBeforeButtonClick:sr,isProcessing:B,onLoadStateChange:hi,onInitializationStateChange:Pi,session:rt,existingOrderId:d?.orderId,debug:L},d?.orderId??"fresh")})]}),Ko&&u(no,{stripe:$o,options:xs,children:u(ac,{sessionId:e,nonce:t,email:P.email,billingName:Te||void 0,onBuyerIdentityReady:$,billingApiUrl:Ze,onTokenizedBody:Mn,onErrorChange:ve,isProcessing:B,onButtonClick:le,onDecline:m,onTechnicalFailure:lo,runBeforeButtonClick:sr,onLoadStateChange:Ls,placeholderBorderRadius:Jr,popupCapabilityOwner:N,externalTelemetryContext:Ws,presentationMode:co})}),po?u(no,{stripe:qn,options:As,children:u(ic,{sessionId:e,nonce:t,email:P.email,billingName:Te||void 0,onBuyerIdentityReady:$,billingApiUrl:Ze,intentKind:Le>0?"payment":"setup",expressMethods:uo,onTokenizedBody:Mn,onErrorChange:ve,onButtonClick:le,onDecline:m,onTechnicalFailure:lo,runBeforeButtonClick:sr,onLoadStateChange:Us,placeholderBorderRadius:Jr,popupCapabilityOwner:N,externalTelemetryContext:me})}):null,!po&&Vs?u("div",{style:{height:ha,borderRadius:Jr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Vo&&u(sc,{sessionId:e,nonce:t,email:P.email,billingName:[P.firstName,P.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:$,billingApiUrl:Ze,paymentElementMethods:Ra,stripeInstance:qn,paymentElementBaseOptions:gi,onTokenizedBody:Mn,onErrorChange:ve,onButtonClick:le,onDecline:m,runBeforeButtonClick:sr,onLoadStateChange:js,isProcessing:B,submitButtonColor:Xr,submitButtonBorderRadius:Gt,submitButtonStyle:C.submitButton,onExpandApm:_n,expandedApmMethod:Qt,themeId:et,buttonAppearance:{backgroundColor:C.cardButton?.backgroundColor,borderColor:C.cardInputBorder,textColor:C.cardButton?.color,borderRadius:Jr}}),X&&u("button",{type:"button",onClick:async()=>{B||!(await sr("card")).proceed||(le?.("card"),ar())},disabled:B,style:{width:"100%",...q,...C.cardButton,...gs({themeBundle:wt,resolvedPrimaryColor:Xr,resolvedBorderRadius:Gt,submitButtonStyle:C.submitButton,explicitPrimaryColor:Bn?.colorPrimary}),fontSize:C.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:ge=>{!B&&(wt||Bn?.colorPrimary)&&(ge.currentTarget.style.backgroundColor=Kc)},onMouseLeave:ge=>{(wt||Bn?.colorPrimary)&&(ge.currentTarget.style.backgroundColor=Xr)},onMouseDown:ge=>{ge.currentTarget.style.transform="scale(0.985)"},onMouseUp:ge=>{ge.currentTarget.style.transform="scale(1)"},children:u(ho,{content:_t})}),Be&&st==="buttons"&&u(_o,{margin:"0.25rem 0",styleOverride:C.errorBanner,children:Be})]}),X&&f&&u("div",{style:{gridArea:"1 / 1",...W?{animation:W}:{},...st==="collapsing"?{pointerEvents:"none"}:{}},children:al}),J&&ll&&Qt&&Fa&&qn&&u("div",{style:{gridArea:"1 / 1",...fo?{animation:fo}:{},...st==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Fe("div",{style:{backgroundColor:wi,borderRadius:Ri,...Jo,padding:_i},children:[Fe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Fe("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:S,style:{display:"inline-flex",alignItems:"center",gap:Si?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:C.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...C.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...C.backButtonIcon},children:u("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:u("path",{d:"M15 18l-6-6 6-6"})})}),u(Po,{content:Re})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:C.titleFontSize??"1.05rem",color:ki,paddingRight:80,...C.title},children:`Pay with ${oo(Qt)}`})]}),u(no,{stripe:qn,options:Fa,children:u(cs,{method:Qt,sessionId:e,nonce:t,email:P.email,billingName:[P.firstName,P.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:$,billingApiUrl:Ze,onTokenizedBody:Mn,onErrorChange:ve,onDecline:m,onCancel:S,runBeforeButtonClick:sr,onButtonClick:le,isProcessing:B,submitButtonColor:Xr,submitButtonBorderRadius:Gt,submitButtonStyle:C.submitButton,errorText:Be})},Qt)]})})]})]})}return ll&&Qt&&Fa&&qn&&J?Fe("form",{onSubmit:bi,className:M,noValidate:!0,style:{position:"relative"},children:[u(as,{}),R&&u(kr,{status:R,errorMessage:Be,authorized:zn}),u("div",{style:{...fo?{animation:fo}:{},...st==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Fe("div",{style:{backgroundColor:wi,borderRadius:Ri,...Jo,padding:_i},children:[Fe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Fe("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:S,style:{display:"inline-flex",alignItems:"center",gap:Si?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:C.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...C.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...C.backButtonIcon},children:u("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:u("path",{d:"M15 18l-6-6 6-6"})})}),u(Po,{content:Re})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:C.titleFontSize??"1.05rem",color:ki,paddingRight:80,...C.title},children:`Pay with ${oo(Qt)}`})]}),u(no,{stripe:qn,options:Fa,children:u(cs,{method:Qt,sessionId:e,nonce:t,email:P.email,billingName:[P.firstName,P.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:$,billingApiUrl:Ze,onTokenizedBody:Mn,onErrorChange:ve,onDecline:m,onCancel:S,runBeforeButtonClick:sr,onButtonClick:le,isProcessing:B,submitButtonColor:Xr,submitButtonBorderRadius:Gt,submitButtonStyle:C.submitButton,errorText:Be})},Qt)]})})]}):Fe("form",{onSubmit:bi,className:M,noValidate:!0,style:{position:"relative"},children:[u(as,{}),R&&u(kr,{status:R,errorMessage:Be,authorized:zn}),Fe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[il("flopay-direct-paypal-gate-debug-default"),sl("flopay-stripe-gate-debug-default"),jo&&lt&&Fe(ro,{children:[d&&u("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."}),u(ia.Provider,{value:N,children:u(Va,{sessionId:e,nonce:t,billingApiUrl:Ze,email:P.email,billingName:Te||void 0,onBuyerIdentityReady:$,clientId:lt.clientId,environment:lt.environment,currency:en.toUpperCase(),isSubscription:it,providerObjectType:Xe,approvalPresentation:Ta==="popup"?void 0:Ta,onTokenizedBody:Mn,onComplete:s,onErrorChange:ve,onDecline:m,onTechnicalFailure:lo,onButtonClick:le,runBeforeButtonClick:sr,isProcessing:B,onLoadStateChange:hi,onInitializationStateChange:Pi,session:rt,existingOrderId:d?.orderId,debug:L},d?.orderId??"fresh")})]}),Ko&&u(no,{stripe:$o,options:xs,children:u(ac,{sessionId:e,nonce:t,email:P.email,billingName:Te||void 0,onBuyerIdentityReady:$,billingApiUrl:Ze,onTokenizedBody:Mn,onErrorChange:ve,isProcessing:B,onButtonClick:le,onDecline:m,onTechnicalFailure:lo,runBeforeButtonClick:sr,onLoadStateChange:Ls,placeholderBorderRadius:Jr,popupCapabilityOwner:N,externalTelemetryContext:Ws,presentationMode:co})}),po&&u(no,{stripe:qn,options:As,children:u(ic,{sessionId:e,nonce:t,email:P.email,billingName:Te||void 0,onBuyerIdentityReady:$,billingApiUrl:Ze,intentKind:Le>0?"payment":"setup",expressMethods:uo,onTokenizedBody:Mn,onErrorChange:ve,onButtonClick:le,onDecline:m,onTechnicalFailure:lo,runBeforeButtonClick:sr,onLoadStateChange:Us,placeholderBorderRadius:Jr,popupCapabilityOwner:N,externalTelemetryContext:me})}),Vo&&u(sc,{sessionId:e,nonce:t,email:P.email,billingName:[P.firstName,P.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Ze,paymentElementMethods:Ra,stripeInstance:qn,paymentElementBaseOptions:gi,onTokenizedBody:Mn,onErrorChange:ve,onButtonClick:le,onDecline:m,runBeforeButtonClick:sr,onLoadStateChange:js,isProcessing:B,submitButtonColor:Xr,submitButtonBorderRadius:Gt,submitButtonStyle:C.submitButton,themeId:et,onExpandApm:_n,expandedApmMethod:Qt,buttonAppearance:{backgroundColor:C.cardButton?.backgroundColor,borderColor:C.cardInputBorder,textColor:C.cardButton?.color,borderRadius:Jr}})]}),X&&(Nc||Oc||Lc)&&Fe("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),u("span",{children:"or pay with card"}),u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),X&&al]})}import{Fragment as Tr,jsx as ie,jsxs as rn}from"react/jsx-runtime";var Do=44,ks="flopay_checkout_saved_payment_resume",di=new Map,li=new Map;function vc(e,t){t.settled&&t.consumers===0&&di.get(e)===t&&di.delete(e)}function Ju(e,t,n){let r=li.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};li.set(e,i);let s=()=>{li.get(e)===i&&li.delete(e)};return o.then(s,s),o}function va(e){return new Promise(t=>setTimeout(t,e))}function ci(e,t,n){let r=$a({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Rc,enabled:t!==!1});return r.beginCheckout(n),r}function ba(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function vs(e,t,n,r,o,i){let s=ci(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),ba(s)}function bc(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 Cc(e,t,n,r,o){let i=Ic(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 Sn&&t.code==="session_auto_completed"?!1:t instanceof Sn&&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 Ec(e,t){let n=e?.data.paypal?.publishableKey;if(n)return{clientId:n,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation,...t?{existingOrderId:t}:{}}}function bs(e){return!e||e.data.stripe?.publishableKey?!1:!!Ec(e)?.clientId}var Xu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Zu(e){return new $u(Xu,{publishableKey:"provider_unavailable",...e})}async function Cs(e,t){let{publishableKey:n,paypalPublishableKey:r}=Ji(e);return{...await Xi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Is(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Qu(){if(!Is())return null;try{let e=window.sessionStorage.getItem(ks);return e?JSON.parse(e):null}catch{return null}}function wc(e){if(Is())try{window.sessionStorage.setItem(ks,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ws(){if(Is())try{window.sessionStorage.removeItem(ks)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function ep(){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 Sc(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 Ss(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function tp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function kc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function np(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 _s({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:s,loading:l,error:m,onComplete:y,onError:b,onInstrument:g,onDecline:F,onCountryChange:M,onZipChange:w,showPayPal:v=!0,showStripe:U=!0,walletPresentation:ue="auto",enabledPaymentMethods:E,showApplePay:J=!0,showGooglePay:K=!0,debug:se=!1,layout:G,theme:xe,buttonsTheme:Ye,buttonsStyles:be,cardButtonContent:et,cardBackButtonContent:It,cardTitleContent:pe,showSecurityFooter:De,onButtonClick:_t,onBeforeButtonClick:Re,enableAVS:Oe,cardFieldOrder:he,cardPreFormSlot:le,avsLayout:Ne,submitLabel:Je,className:pt,initialErrorMessage:D=null,initialPayPalOrderId:qe,children:ce,checkoutMode:O,confirmLabel:$e,renderConfirmButton:Ke,onSessionCompleted:Ve}){let V=Wu(r),tt=er(()=>_c(xe),[xe]),nt=i??tt?.appearance,_e=n?"embedded_checkout":"standard_checkout",Pe=Ss(ce,G),[He,ft]=qt(null),[Le,en]=qt(null),jt=xt(null),lt=xt(null),it=xt(0),[T,ye]=qt(null),Me=xt(null),[L,ze]=qt(null),Ct=er(()=>n?Eo(n):"",[n]),Ue=n?`create:${Ct}`:`session:${e??""}`,c=kc(L),A=xt(new Set),N=xt(Ue),h=xt(Ue);Zo(()=>{h.current=Ue,N.current!==Ue&&(N.current=Ue,A.current.clear())},[Ue]);let j=wn(S=>{if(h.current===Ue){if(Oi.has(S.name)){if(A.current.has(S.name))return;A.current.add(S.name)}Ft(()=>g?.(S))}},[Ue,g]),Ae=Io(j,Ue),me=xt(!1),rt=wn(S=>{if(me.current)return;let R=S.gateway||!c?S:{...S,gateway:c};j(R)},[j,c]);yr(()=>{Ae({class:"lifecycle",name:"checkout.mount"})},[Ae]);let[Xe,oe]=qt(e??""),ct=e??Xe,Rt=n?"":ct,[Pn,Ze]=qt(!0),[$t,Ee]=qt(null),[Dn,Rn]=qt(0),[Mt,kn]=qt("full"),[On,Nn]=qt(!1),[tn,fe]=qt(D),[gt,Et]=qt(null),[vn,Bt]=qt(null),[Kn,dn]=qt(!1),[Kt,on]=qt(void 0),[Vn,un]=qt(""),[ht,Jt]=qt(!1),[pn,Dt]=qt(!1),[Xt,Vt]=qt(!1),yn=xt(null),yt=xt(0),H=xt(void 0),[Ln,zn]=qt("loading"),[mr,bn]=qt(0),an=xt(!1),En=xt(!1),Ce=xt(!1),mt=xt(null),X=xt(null),I=er(()=>({checkoutMode:O??Mt,layout:tp(ce,G)}),[O,ce,Mt,G]),je=xt(y);je.current=y;let Z=xt(b);Z.current=b;let Hn=xt(F);Hn.current=F;let mn=wn(S=>Za(mt,async R=>{try{return await S(R)}catch(k){throw R.aborted?ya(k):k}}),[]);yr(()=>()=>{mt.current?.abort(),mt.current=null},[]);let Ht=wn((S,R)=>{jt.current=S,en(S),Me.current=R,ye(R)},[]),Wn=wn(()=>{let S=lt.current;S&&(lt.current=null,S.destroy())},[]);yr(()=>{cn(Le)?.setCheckoutContext(I),T&&T!==Le&&cn(T)?.setCheckoutContext(I)},[Le,T,I]);let Qe=xt(Ve);Qe.current=Ve;let Lr=wn(S=>{zn(S),!(S!=="exhausted"||Ce.current)&&(Ce.current=!0,Z.current?.(new Sn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Wt=wn(()=>{zn("retrying"),bn(S=>S+1)},[]);yr(()=>{zn("loading"),bn(0),Ce.current=!1},[ct]),yr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Rc,checkout_type:_e,checkout_layout:Pe,billing_api_url:V})},[Pe,_e,V]);let fn=er(()=>n?Eo(n,!0):"",[n]),Ar=er(()=>Vn===fn?Kt:void 0,[Kt,Vn,fn]),xr=er(()=>n?xi(n,Ar):void 0,[n,Ar]),Tn=O??xr?.checkoutMode??"full",Zt=er(()=>xr?{...xr,checkoutMode:Tn}:void 0,[xr,Tn]);yr(()=>{on(void 0),un(fn),H.current=void 0,yn.current=null,Vt(!1)},[fn]),yr(()=>{fe(D)},[D]);let fr=wn((S,R,k)=>{Ft(()=>{Hn.current?.(ln(S,R,k))})},[]),An=wn(async(S,R)=>{fe(null),Bt(null),dn(!1),Et("processing");let k=R?.sessionId??S.id,Q=S.clientSecret||t,ke=kc(S),dt=jt.current??Me.current,te=cn(dt),Ie=dt?null:ci(V,o,I),z={log:C=>{te?te.log(C):Ie?.log(C)},error:C=>{te?te.error(C):Ie?.error(C)},terminal:C=>{te?te.terminal(C):Ie?.terminal(C)},performance:C=>{te?te.performance(C):Ie?.performance(C)},now:()=>te?.now()??Ie?.now()??0,elapsed:C=>te?.elapsed(C)??Math.max(0,(Ie?.now()??C)-C)},d=z.now(),p=!!(R?.initialAutoProcessingError||R?.initialAutoProcessingPending),_=!1,x,ee=()=>{_||(_=!0,p=!0,x=z.now(),z.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},$=!1,Be=()=>{$||($=!0,z.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),z.performance({stage:"processing",durationMs:z.elapsed(d),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),x!==void 0&&z.performance({stage:"recovery",durationMs:z.elapsed(x),durationMode:"machine",paymentMethodCategory:"saved"}))};z.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),me.current=!0;try{z.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{me.current=!1}Ae({class:"lifecycle",name:"payment.processing.started",provider:ke}),p&&ee();let wt;try{let C=Kl(R?.initialAutoProcessingError),de=R?.initialAutoProcessingError?.type==="3ds_required"&&!R.initialAutoProcessingError.threeDSecureToken&&R.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:R.initialAutoProcessingError.nextActionRedirectUrl}:null,Tt,ne=B=>(ee(),mn(Y=>Ao(B,{billingApiUrl:V,sessionId:k,nonce:Q,session:S,signal:Y})));if(de)Tt=await ne(de);else if(C)ee(),C.type==="paypal_redirect_required"&&X.current?.publishableKey&&wc({sessionId:k,publishableKey:X.current.publishableKey,paypalPublishableKey:X.current.paypalPublishableKey}),Tt=await mn(B=>ei(C,{flopay:jt.current,paypalFlopay:Me.current,attempt3DS:R?.attempt3DS,billingApiUrl:V,sessionId:k,session:S,telemetry:!1,signal:B})),C.type==="paypal_redirect_required"&&ws();else if(R?.initialAutoProcessingPending){let B=R.initialAutoProcessingPending,Y=new si(V,{telemetry:!1}),P=await mn(we=>Y.waitForCheckoutSessionCompletion(B.sessionId,{initialDelayMs:B.retryAfterMs,nonce:Q,statusUrl:B.statusUrl,signal:we})),Te=P.data.session,St=P.autoProcessingError?.type==="3ds_required"&&P.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:P.autoProcessingError.nextActionRedirectUrl}:null;if(St)Tt=await ne(St);else{if(!jr(Te))throw Co(Te);Tt=Dr(Te,k)}}else{if(R?.initialAutoProcessingError)throw Rr(R.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:R.initialAutoProcessingError.checkoutMethod});if(R?.fromCreateSession)return R?.fallbackToFull&&(kn("full"),Sc("full")),!1;{let B=await xo({billingApiUrl:V,sessionId:k,session:S,nonce:Q,telemetry:!1});B.type==="success"?Tt=B.result:B.type==="next_action_required"?Tt=await ne(B):(ee(),B.type==="paypal_redirect_required"&&X.current?.publishableKey&&wc({sessionId:k,publishableKey:X.current.publishableKey,paypalPublishableKey:X.current.paypalPublishableKey}),Tt=await mn(Y=>ei(B,{flopay:jt.current,paypalFlopay:Me.current,attempt3DS:R?.attempt3DS,billingApiUrl:V,sessionId:k,session:S,telemetry:!1,signal:Y})),B.type==="paypal_redirect_required"&&ws())}}k&&To(k),Be(),p&&(z.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),z.terminal({outcome:Tt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),dn(Tt.status==="authorized"),Et("success"),await va(600),wt=()=>je.current?.(Tt)}catch(C){let de=ma(C);if(de.code==="three_ds_aborted")return!1;let Tt=de.checkoutMethod??pa;fe(de.message),Bt(de.message),dn(!1),R?.fallbackToFull&&(z.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),kn("full"),Sc("full")),Be();let ne=de.statusCode===void 0?void 0:Yu(de.statusCode,"unknown"),B=ne==="4xx"?{requestCategory:"process_payment",statusClass:ne}:{},Y=ne===void 0||ne==="4xx";if(Y&&(de.telemetryOutcome==="payment_declined"||!!(de.declineCode||de.code?.toLowerCase().includes("declin"))))z.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...B});else if(Y&&(de.telemetryOutcome==="validation_rejected"||de.type==="validation_error"))z.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...B});else{let St=Ic(C,p?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),we=de.telemetryRequestCategory??"process_payment";me.current=!0;try{z.error({...St,...de.telemetryFailureCategory?{failureCategory:de.telemetryFailureCategory}:{},stage:p?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:we})}finally{me.current=!1}Ae({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:we,provider:ke})}return Ft(()=>Z.current?.(de)),fr(Tt,de,{code:de.code,declineCode:de.declineCode}),Et("error"),await Promise.allSettled([va(400),R?.ensureProvidersReady?R.ensureProvidersReady():Promise.resolve()]),p&&(z.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Be(),Ie&&ba(Ie),Et(null),Bt(null)}return Ft(wt),!0},[fr,Ae,t,V,mn,o,I]);yr(()=>{if(typeof window>"u"||En.current)return;let S=new URLSearchParams(window.location.search),R=S.get("payment_intent_client_secret");if(!R)return;let k=Qu();k&&(En.current=!0,(async()=>{let Q,ke=0;fe(null),Bt(null),Et("processing"),Nn(!0);try{if(S.get("redirect_status")==="failed")throw Object.assign(new Sn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:dt,paypalFlopay:te}=await Xi({publishableKey:k.publishableKey,paypalPublishableKey:k.paypalPublishableKey,billingApiUrl:V,locale:s,telemetry:o});Q=cn(te??dt),Q?.setCheckoutContext(I),ke=Q?.now()??0,Q?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Q?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Ie=(te??dt)?.getRawProvider();if(!Ie)throw Object.assign(new Sn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:z,error:d}=await Ie.retrievePaymentIntent(R);if(d)throw Object.assign(new Sn(d.message??"Failed to retrieve PayPal payment status.","api_error",{code:d.code}),{checkoutMethod:"paypal"});let p=bl(z?.status);if(!z||p==="failed")throw Object.assign(new Sn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let _=typeof z.payment_method=="string"?z.payment_method:z.payment_method?.id,x=p;if(k.sessionId){let Be=(await new si(V,{telemetry:!1}).getUnifiedCheckoutSession(k.sessionId)).data.session;if(Be&&Be.status!=="complete"){let wt=await xo({billingApiUrl:V,sessionId:k.sessionId,session:Be,telemetry:!1,tokenizedData:{id:_??z.id,type:"card",threeDSecureActionResultTokenId:z.id,isPaypal:!0}});if(wt.type!=="success")throw Object.assign(new Sn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});x=wt.result.status}}k.sessionId&&To(k.sessionId),Q?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Q?.performance({stage:"redirect_resume",durationMs:Q.elapsed(ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Q?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Et("success"),await va(600),Ft(()=>je.current?.({status:x,paymentIntentId:z.id,paymentMethodId:_,checkoutMethod:"paypal"}))}catch(dt){let te=ma(dt),Ie=te.checkoutMethod??"paypal",z=!!(te.declineCode||te.code?.toLowerCase().includes("declin"));if(Q)Q.performance({stage:"redirect_resume",durationMs:Q.elapsed(ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),z?Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Q.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(z){let d=ci(V,o,I);d.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ba(d)}else vs(V,o,I,"REDIRECT_RESUME_FAILED","redirect_resume");fe(te.message),Bt(te.message),Ft(()=>Z.current?.(te)),fr(Ie,te,{code:te.code,declineCode:te.declineCode}),Et("error"),await va(400)}finally{ws(),ep(),Et(null),Bt(null),Nn(!1)}})())},[fr,s,V,o,I]);let Mr=xt(null),xn=er(()=>Zt?Eo(Zt):"",[Zt]),gr=xt(Zt);gr.current=Zt,yr(()=>{oe(e??"")},[e]),yr(()=>{an.current=!1,fe(D),Bt(null),dn(!1),Et(null)},[xn,D,e]);async function hr(S,R,k){let Q=ci(V,o,I),ke=new si(V,{telemetry:!1}),dt=!1;try{let te=S.idempotencyKey===void 0?void 0:Pc(S.idempotencyKey),Ie=$i(R,k),z=Ki(R,k);Ie?.canonicalIdentity===k&&z&&z.canonicalIdentity===void 0&&(Ya(R,k,z.idempotencyKey),z={...z,canonicalIdentity:k});let d=te??(z?.canonicalIdentity===k?z.idempotencyKey:void 0),p,_=!1;Q.log({name:Ie?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let x=Ie?.sid??null,ee=null,$,Be,wt=!1;if(x)try{ee=await ke.getUnifiedCheckoutSession(x,Ie?.nonce),Ie&&Ie.canonicalIdentity===void 0&&(Nl(ee.data.session,S)?(Ga(R,k,x,Ie.nonce??ee.data.session?.clientSecret),z&&z.canonicalIdentity===void 0&&(Ya(R,k,z.idempotencyKey),d??(d=z.idempotencyKey))):(Wa(R,k),z=null,d=te,x=null,ee=null));let de=ee?.data.session?.status,Tt=ee?.data.session,ne=Tt?.clientSecret||Ie?.nonce;if(x&&Tt?.buyerIdentified===!1&&ne&&(Be=bo(ke,x,ne,S.account)),x&&ee&&de==="complete"){if(Vi(x))return{sid:x,result:ee};Wa(R,k),x=null,ee=null,_=!0}}catch{Q.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ie?.canonicalIdentity===void 0?(Wa(R,k),d=te):Ha(R,k),x=null}if(!x){!te&&(_||!d)&&(d=Pc(),p=d),d&&Ya(R,k,d);let de=Q.now(),Tt=0;Q.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ne={...S,idempotencyKey:d,avsCheck:!!Oe,avsConfig:typeof Oe=="object"?Oe:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ss(ce,G)};Object.defineProperty(ne,Ku,{configurable:!1,enumerable:!1,value:{onAttempt:P=>{Tt=Math.max(Tt,P)}}});let B=()=>{bc(Q,"session_create",de,Tt)},Y=P=>{Cc(Q,P,"session_create",de,Tt)&&Ae({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(Hu(ne)){let P=await ke.createDetachedSession(ne);P.claimed.catch(()=>{}),ee=P.shell,x=P.sessionId,Be=P.claim;let Te=Q.now();Q.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),$=P.claimed.then(St=>{let we=St.data.session?.id??P.sessionId;return we&&Ga(R,k,we,St.data.session?.clientSecret??P.nonce),bc(Q,"session_claim",Te),B(),St},St=>{throw Ha(R,k),Cc(Q,St,"session_claim",Te,0)&&Ae({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),St}).finally(()=>ba(Q)),$.catch(()=>{}),dt=!0,Q.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Q.performance({stage:"session_shell",durationMs:Q.now()-de,durationMode:"machine",requestCategory:"session_create",attempt:Tt,statusClass:"2xx",paymentMethodCategory:"card"})}else ee=await ke.createAndFetchSession(ne),B()}catch(P){throw Y(P),P}x=ee.data.session?.id??x??"",x&&!$&&Ga(R,k,x,ee.data.session?.clientSecret)}let C=ee?.data.session;return!Be&&x&&C?.buyerIdentified===!1&&C.clientSecret&&(Be=bo(ke,x,C.clientSecret,S.account)),{sid:x??"",result:ee,sdkGeneratedIdempotencyKey:p,...$?{claimed:$}:{},...Be?{claim:Be}:{},...wt?{claimRequiresIdentity:!0}:{}}}finally{dt||ba(Q)}}let tr=xt(hr);Zo(()=>{tr.current=hr},[hr]);let Gn=wn(async(S,R)=>{let k=gr.current;if(!k)throw new Sn("createSession is required to bootstrap checkout.","validation_error");let Q=xi(k,S),ke=Eo(Q),dt=Ol(Q),te=di.get(ke);if(!te){let d={canonicalIdentity:ke,promise:tr.current(Q,dt,ke),consumers:0,settled:!1};te=d,di.set(ke,d);let p=()=>{d.settled=!0,vc(ke,d)};d.promise.then(p,p)}te.consumers+=1;let Ie=!1,z=()=>{Ie||(Ie=!0,te.consumers-=1,vc(ke,te))};R?.(z);try{let d=await te.promise;Mr.current=ke,S&&(un(fn),on(C=>hl(C,S)));let{sid:p,result:_,claimed:x,claim:ee,claimRequiresIdentity:$}=d;if(H.current=ee,Vt($===!0),ft(_),_.data.session&&ze(_.data.session),p&&oe(p),x){yt.current+=1;let C=yt.current;yn.current=x,Dt(!0),x.then(de=>{yt.current===C&&(yn.current===x&&(yn.current=null),ft(de),de.data.session&&ze(de.data.session),Dt(!1),Vt(!1))},de=>{yt.current===C&&(yn.current===x&&(yn.current=null),Dt(!1),Vt(!1),Ee(de instanceof Sn?de:new Sn(de instanceof Error?de.message:"Failed to create session","api_error")))})}else yt.current+=1,yn.current=null,Dt(!1),Vt(!1);let{flopay:Be,paypalFlopay:wt}=await Cs(_,{billingApiUrl:V,locale:s,telemetry:o});return Ht(Be,wt),Ze(!1),d}catch(d){throw Mr.current===ke&&(Mr.current=null),d}finally{R||z()}},[fn,Ht,s,V,o]),Yn=xt(An);Yn.current=An;let At=xt(Gn);At.current=Gn;let nr=wn(async S=>{if(!np(S)||ht)return{sessionId:Xe,session:L};Jt(!0);try{let R=await Gn(S);return{sessionId:R.sid,session:R.result.data.session??null}}finally{Jt(!1)}},[Gn,ht,Xe,L]),In=wn(async S=>{let R=H.current;if(!R)return;let k=yt.current,Q=await R(S);yt.current===k&&(ft(Q),Q.data.session&&ze(Q.data.session))},[]),Jn=wn(async()=>{await yn.current},[]),Pr=wn(async()=>(await Jn(),{proceed:!0}),[Jn]);yr(()=>{let S=!1,R,k=++it.current;Wn(),Ee(null),Rn(0);let Q=()=>{S=!0,it.current===k&&(it.current+=1,Wn())},ke=gr.current;if(xn&&ke)return kn(Tn),Ze(!1),Mr.current===xn?Q:(ze(Pl(ke,O)),(async()=>{let Ie=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),z=Tn==="auto"&&!an.current&&!Ie;z&&(fe(null),Bt(null),Et("processing"));try{let d=await At.current(void 0,ee=>{R=ee}),p=d.result.data.session??null;X.current=Ji(d.result);let _=bs(d.result),x=Vi(d.sid||p?.id);if(!S&&z&&p&&!_&&!x){an.current=!0,await Ju(xn,d.sdkGeneratedIdempotencyKey,()=>Yn.current(p,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:d.result.autoProcessingError,initialAutoProcessingPending:d.result.autoProcessingPending,autoProcessingAttempted:d.result.autoProcessingAttempted,sessionId:d.sid||p.id}));return}!S&&z&&((_||x)&&(an.current=!0),Et(null),Bt(null))}catch(d){if(S)return;let p=Oa(d);if(z&&p==="session_auto_completed"){an.current=!0,Et("success"),await va(600),S||(Ft(()=>{je.current?.({status:"succeeded"})}),Et(null),Bt(null));return}z&&(Et(null),Bt(null));let _=d instanceof Sn?d:new Sn(d instanceof Error?d.message:"Failed to create session","api_error");Ee(_)}finally{R?.(),R=void 0}})(),()=>{Q(),R?.()});Ze(!0);async function dt(){let Ie=!1,z=null;try{let d=new si(V,{telemetry:!1}),p=await d.getUnifiedCheckoutSession(ct,t);if(z=p,S)return;ft(p);let _=p.data.session??null;if(ze(_),!_)throw new Sn("No session data returned","api_error");let x=_.checkoutMode;if(x==="setup")throw new Sn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(_.status==="authorized"){Ze(!1),Ft(()=>{je.current?.(Dr(_,ct)),Qe.current?.(_.successUrl??"")});return}if(_.status==="complete"){Ze(!1),Ft(()=>{Qe.current?.(_.successUrl??"")});return}if(_.status==="expired")throw Da(_);Ie=!0;let ee=O??x??"full";kn(ee),yt.current+=1;let $=_.clientSecret||t;H.current=_.buyerIdentified===!1&&$?bo(d,ct,$,{..._.customer?.id?{userId:_.customer.id}:{}}):void 0,Dt(!1),Vt(!1);let Be=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),wt=bs(p);if(ee==="auto"&&!an.current&&!Be&&!wt){an.current=!0;let C=te(p);try{if(await Yn.current(_,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>C,sessionId:ct||_.id}),S)return;await C,S||Ze(!1);return}catch{if(S)return;await C,S||Ze(!1);return}}await te(p),S||Ze(!1)}catch(d){if(S)return;let p=gl(d,Ie);if(Ie&&Ae({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),p){let{errorCode:x,stage:ee,...$}=p;vs(V,o,I,x,ee,$)}if(p?.stage==="provider_load"&&(O??z?.data.session?.checkoutMode??"full")==="full"&&fl(z,v,U)){let x=Zu({billingApiUrl:V,locale:s,telemetry:o});lt.current=x,Ht(x,null),Rn(1),Ze(!1);return}let _=d instanceof Sn&&p?.stage!=="provider_load"?d:ml();_!==d&&Ft(()=>Z.current?.(_)),Ee(_),Ze(!1)}}async function te(Ie){let{flopay:z,paypalFlopay:d,...p}=await Cs(Ie,{billingApiUrl:V,locale:s,telemetry:o});X.current={publishableKey:p.publishableKey,paypalPublishableKey:p.paypalPublishableKey},Ht(z,d),Rn(0)}return dt(),Q},[O,xn,Tn,Rt,t,v,U]);let st=wn(async()=>{if(!He||Dn!==1)return;let S=it.current;Rn(2);try{let{flopay:R,paypalFlopay:k}=await Cs(He,{billingApiUrl:V,locale:s,telemetry:o});if(it.current!==S)return;Wn(),Ht(R,k),Rn(0)}catch(R){if(it.current!==S)return;let{errorCode:k,stage:Q,...ke}=Ti(R);vs(V,o,I,k,Q,ke)}},[Wn,Ht,s,Dn,V,o,I,He]),nn=!!(ct&&(L?.clientSecret||t)),Qt=On||!nn,Br=wn(async()=>{if(!(On||!nn||!L)){Nn(!0),fe(null);try{await An(L,{attempt3DS:!0,fallbackToFull:!0,sessionId:ct||L.id})}finally{Nn(!1)}}},[ct,On,nn,An,L]),Un=Ec(He,qe),zr=bs(He),rr=er(()=>{if(!(!He||!L||!He.data.stripe?.publishableKey))return{billingApiUrl:V}},[He,L,V]),or=!!(n&&!ce&&G==="buttons"&&Re&&Tn==="full"),gn=!!(ct&&(L?.vault?.html||Ur(L))),ar=er(()=>({session:L,loading:Pn,error:$t,checkoutMode:Mt,inlineSessionDraft:Zt,applyInlineSessionPatch:or?nr:void 0,inlineSessionPatchProcessing:ht,claimPending:pn,claimRequiresIdentity:Xt,claimBuyerIdentity:In,waitForDataAttachment:Jn}),[L,Pn,$t,Mt,Zt,or,nr,ht,pn,Xt,In,Jn]),Fr=!!n&&G==="buttons"&&!zr&&!gn&&(!Le||!rr),_n=gt?ie(kr,{status:gt,errorMessage:vn,authorized:Kn}):null;if(Pn&&!gn){if(l)return rn(Tr,{children:[l,_n]});if(G==="buttons"){let S=tt?.buttonsLayout?.cardButton?.borderRadius??tt?.appearance.variables?.borderRadius??8,R=k=>ie("div",{style:{height:k,borderRadius:S,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return rn(Tr,{children:[rn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[v&&R(Do),U&&(J||K)&&R(Do),U&&R(Do),ie("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),_n]})}return rn(Tr,{children:[rn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ie("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ie("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),_n]})}return $t?m?ie(dr.Provider,{value:ar,children:m($t)}):ie(dr.Provider,{value:ar,children:ie("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:$t.message})}):Fr?rn(Tr,{children:[ie(dr.Provider,{value:ar,children:ie(op,{onButtonClick:_t,showPayPal:v,showStripe:U,showApplePay:J,showGooglePay:K,theme:xe,buttonsTheme:Ye,buttonsStyles:be,cardButtonContent:et,cardBackButtonContent:It,cardTitleContent:pe})}),_n]}):zr&&L&&Un?rn(Tr,{children:[ie(dr.Provider,{value:ar,children:rn("div",{className:pt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[tn&&ie(_o,{icon:!1,children:tn}),Ln==="retrying"&&ie("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ln==="exhausted"&&rn("div",{role:"alert",children:[ie("div",{children:"PayPal is temporarily unavailable. Please try again."}),ie("button",{type:"button",onClick:Wt,children:"Retry PayPal"})]}),Ln!=="exhausted"&&ie("div",{"aria-hidden":Ln==="retrying"?!0:void 0,style:Ln==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ie(Fl,{sessionId:ct,nonce:L.clientSecret||void 0,billingApiUrl:V,email:L.customer?.email||Zt?.account?.email,billingName:[L.customer?.firstName,L.customer?.lastName].filter(Boolean).join(" ")||[Zt?.account?.firstName,Zt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:In,clientId:Un.clientId,environment:Un.environment,currency:(L.currency??"usd").toUpperCase(),isSubscription:L.mode==="subscription",providerObjectType:Un.providerObjectType,approvalPresentation:Un.approvalPresentation,existingOrderId:Un.existingOrderId,onComplete:y,onErrorChange:fe,onDecline:F,onButtonClick:_t,runBeforeButtonClick:Pr,onInitializationStateChange:Lr,allowAutomaticRetry:mr===0,session:L,telemetry:o,telemetryContext:I,onInstrument:rt,debug:se},`${Ue}:paypal-init-${mr}`)})]})}),_n]}):Mt==="confirm"?rn(Tr,{children:[ie(dr.Provider,{value:ar,children:ie(Ja,{flopay:Le,paypalFlopay:T,options:rr??{billingApiUrl:V},onInstrument:rt,children:rn("div",{className:pt,children:[tn&&ie("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:tn}),Ke?Ke({onConfirm:Br,isProcessing:Qt}):ie("button",{type:"button",onClick:Br,disabled:Qt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Qt?"not-allowed":"pointer",opacity:Qt?.6:1},children:On?"Processing...":$e??"Confirm Purchase"})]})},Ue)}),_n]}):(!Le||!rr)&&!(gn&&Mt==="full")?ie(Tr,{children:_n}):rn(Tr,{children:[ie(dr.Provider,{value:ar,children:rn(Ja,{flopay:Le,paypalFlopay:T,options:rr??{billingApiUrl:V},onInstrument:rt,children:[Dn===1&&ie("button",{type:"button",onClick:st,children:"Retry payment methods"}),ce?rn(Tr,{children:[tn&&ie("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:tn}),ie(rp,{sessionId:ct,nonce:L?.clientSecret||void 0,billingApiUrl:V,session:L,submitLabel:Je,walletPresentation:ue,children:ce})]}):ie(hs,{sessionId:ct,nonce:L?.clientSecret||void 0,telemetry:o,email:L?.customer?.email||Zt?.account?.email,userId:L?.customer?.id||Zt?.account?.userId,firstName:L?.customer?.firstName||Zt?.account?.firstName,lastName:L?.customer?.lastName||Zt?.account?.lastName,totalAmount:L?Math.round(Vu(L).total*100):0,currency:L?.currency?.toLowerCase()??"usd",onComplete:y,onError:b,onDecline:F,error:tn,onErrorChange:fe,showPayPal:v,showStripe:U,walletPresentation:ue,enabledPaymentMethods:Dn?[]:E??He?.data.stripe?.enabledPaymentMethods??L?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:He?.data.stripe?.enabledPaymentMethodCountries,showApplePay:J,showGooglePay:K,layout:G,theme:xe,buttonsTheme:Ye,buttonsStyles:be,appearance:nt,cardButtonContent:et,cardBackButtonContent:It,cardTitleContent:pe,onButtonClick:_t,onBeforeButtonClick:Re,onBuyerIdentityReady:In,enableAVS:Oe,...he?{cardFieldOrder:he}:{},...le?{cardPreFormSlot:le}:{},avsLayout:Ne,country:L?.customer?.country,city:L?.customer?.city,state:L?.customer?.state,onCountryChange:M,onZipChange:w,avsCheck:!!Oe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Ss(ce,G),className:pt,submitLabel:Je,directPaypal:Un,isSubscription:L?.mode==="subscription",session:L,dataAttachmentPending:pn,dataAttachmentRequiresIdentity:Xt,debug:se})]},Ue)}),_n]})}function rp({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:i,children:s}){return ie(Tr,{children:Ps.Children.map(s,l=>{if(!Ps.isValidElement(l))return l;let m=l.props,y={};return m.sessionId||(y.sessionId=e),!m.nonce&&t&&(y.nonce=t),m.billingApiUrl||(y.billingApiUrl=n),m.submitLabel===void 0&&o!==void 0&&(y.submitLabel=o),m.walletPresentation===void 0&&(y.walletPresentation=i),r?.customer&&(m.email||(y.email=r.customer.email),m.userId||(y.userId=r.customer.id),m.firstName||(y.firstName=r.customer.firstName),m.lastName||(y.lastName=r.customer.lastName)),Object.keys(y).length===0?l:Ps.cloneElement(l,y)})})}function op({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:m,cardBackButtonContent:y,cardTitleContent:b}){let[g,F]=qt(!1),M=er(()=>_c(i),[i]),w=er(()=>{let E=M?.buttonsLayout??Gu(s);return l?{...E,...l,cardButton:{...E.cardButton,...l.cardButton},cardFormContainer:{...E.cardFormContainer,...l.cardFormContainer},backButton:{...E.backButton,...l.backButton},backButtonIcon:{...E.backButtonIcon,...l.backButtonIcon},submitButton:{...E.submitButton,...l.submitButton},title:{...E.title,...l.title}}:E},[M,s,l]),v=M?.buttonsLayout?.cardButton?.borderRadius??M?.appearance.variables?.borderRadius??8,U=E=>ie("div",{style:{height:E,borderRadius:v,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),ue=m===void 0?{boxSizing:"border-box",height:Do,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(g){let E=w.cardInputBorder??"#e5e7eb",J=w.cardInputBackground??"white",K=go(y),se=go(b);return rn("div",{style:{backgroundColor:w.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...w.cardFormContainer},children:[rn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[rn("button",{type:"button",onClick:()=>F(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:K?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...w.backButton},children:[ie("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...w.backButtonIcon},children:ie("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:ie("path",{d:"M15 18l-6-6 6-6"})})}),ie(Po,{content:y})]}),se?ie("div",{style:{flex:1}}):ie("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...w.title},children:ie(ea,{content:b})})]}),ie("div",{style:{backgroundColor:J,border:`1px solid ${E}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ie("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),rn("div",{style:{display:"flex"},children:[ie("div",{style:{flex:1,backgroundColor:J,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${E}`,borderLeft:`1px solid ${E}`,borderBottomLeftRadius:8,padding:12,height:45},children:ie("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ie("div",{style:{flex:1,backgroundColor:J,borderTop:"none",borderRight:`1px solid ${E}`,borderBottom:`1px solid ${E}`,borderLeft:`1px solid ${E}`,borderBottomRightRadius:8,padding:12,height:45},children:ie("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ie("div",{style:{backgroundColor:J,border:`1px solid ${E}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ie("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ie("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...w.submitButton,opacity:.5}}),ie("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&&Y(ko),n&&(r||o)&&Y(ko),n&&oe("button",{type:"button",onClick:()=>{e?.("card"),m(!0)},style:{width:"100%",...Pe,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:_.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,..._.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:oe(so,{content:p})}),oe("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Ou,jsx as Eo,jsxs as zu}from"react/jsx-runtime";var Bu=44;function Zl(e){return new Promise(t=>setTimeout(t,e))}function Fu(e,t){return e instanceof ia?e:new ia(e instanceof Error?e.message:t,"api_error")}function Du(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Nu(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 Lu({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:s,items:l,subscriptions:p,account:f,successUrl:C,cancelUrl:h,couponCodes:m,tagsData:w,utmMetadata:_,billingApiUrl:ae,locale:Y,theme:Pe,appearance:S,buttonsTheme:G,buttonsStyles:X,onSuccess:ce,onError:Te,onDecline:Fe,children:ve,disabled:Ue=!1,type:bt="button",style:ot,...$e}){let De=oa(()=>Au(ae),[ae]),ye=oa(()=>Nu({createSession:n,clientId:i,products:s,items:l,subscriptions:p,account:f,successUrl:C,cancelUrl:h,couponCodes:m,tagsData:w,utmMetadata:_}),[f,h,i,m,n,s,l,p,C,w,_]),[we,Qe]=aa(!1),[Z,Ie]=aa(null),[be,ct]=aa(null),[dt,U]=aa(!1),[V,de]=aa(null),fe=Ro(!0),ut=Ro(null),Ne=Ro(V),x=Ro(ce),at=Ro(Te),Ye=Ro(Fe),re=Rr(u=>Ma(ut,async B=>{try{return await u(B)}catch(_e){throw B.aborted?Zo(_e):_e}}),[]);_o(()=>{Ne.current=V},[V]),_o(()=>{x.current=ce},[ce]),_o(()=>{at.current=Te},[Te]),_o(()=>{Ye.current=Fe},[Fe]),_o(()=>(fe.current=!0,()=>{fe.current=!1,ut.current?.abort()}),[]),_o(()=>{if(typeof window>"u")return;let u=B=>{B.key==="Escape"&&de(null)};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u)}},[]);let Q=Rr((u,B=Xo)=>{Ye.current?.(nn(B,u,{code:u.code,declineCode:u.declineCode}))},[]),L=Rr(async u=>{fe.current&&(ct(null),U(u.result.status==="authorized"),Ie("success"),await Zl(600),fe.current&&Bt(()=>x.current?.(u)))},[]),Ae=Rr(async(u,B)=>{fe.current&&(at.current?.(u),B?.emitDecline&&Q(u,B.method),ct(u.message),U(!1),Ie("error"),await Zl(400))},[Q]),xe=Rr(async(u,B,_e)=>{let Ke=u.data.session??null;if(!Ke)throw new ia("No session data returned","api_error");let Re=Ke.clientSecret||t;if(Mr(Ke)){await L({result:Sr(Ke,B),session:Ke,sessionId:Ke.id||B,autoCompleted:!1});return}if(Ke.status==="expired")throw ha(Ke);try{if(u.autoProcessingPending){let N=u.autoProcessingPending,Ct=new is(De),Et=await re(O=>Ct.waitForCheckoutSessionCompletion(N.sessionId,{initialDelayMs:N.retryAfterMs,nonce:Re,statusUrl:N.statusUrl,signal:O})),pt=Et.data.session,un=Et.autoProcessingError?.type==="3ds_required"&&Et.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Et.autoProcessingError.nextActionRedirectUrl}:null;if(un&&B&&Re){let O=await re(Ot=>Co(un,{billingApiUrl:De,sessionId:B,nonce:Re,session:Ke,signal:Ot}));await L({result:O,session:Ke,sessionId:Ke.id||B,autoCompleted:!1});return}if(Et.autoProcessingError)throw gr(Et.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Et.autoProcessingError.checkoutMethod});if(!Mr(pt))throw po(pt);await L({result:Sr(pt,B),session:pt,sessionId:pt.id||B,autoCompleted:!1});return}if(u.autoProcessingError){let N=u.autoProcessingError.nextActionRedirectUrl;if(u.autoProcessingError.type==="3ds_required"&&N&&B&&Re){let Ct=await re(O=>Ti({billingApiUrl:De,sessionId:B,nonce:Re,nextActionRedirectUrl:N,signal:O}));if(Ct.status==="declined")throw gr({type:Ct.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ct.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:u.autoProcessingError.checkoutMethod});let un=(await new is(De).waitForCheckoutSessionCompletion(B,{initialDelayMs:0,nonce:Re})).data.session;if(!Mr(un))throw gr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:u.autoProcessingError.checkoutMethod});await L({result:Sr(un,B),session:un,sessionId:un.id||B,autoCompleted:!1});return}throw gr(u.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:u.autoProcessingError.checkoutMethod})}if(_e?.fromCreateSession&&u.autoProcessingAttempted===!0)throw gr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let $t=await So({billingApiUrl:De,sessionId:B??Ke.id,session:Ke,nonce:Re});if($t.type==="next_action_required"&&Re){let N=B??Ke.id,Ct=await re(Et=>Co($t,{billingApiUrl:De,sessionId:N,nonce:Re,session:Ke,signal:Et}));await L({result:Ct,session:Ke,sessionId:Ke.id||N,autoCompleted:!1});return}if($t.type!=="success")throw gr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await L({result:$t.result,session:Ke,sessionId:Ke.id||B,autoCompleted:!1})}catch($t){let N=Qo($t);if(N.code==="three_ds_aborted")return;let Ct=Ke.id||B;await Ae(N,{emitDecline:!0,method:N.checkoutMethod??Xo}),Du(N,Ct)&&Ct&&fe.current&&de({sessionId:Ct,errorMessage:N.message,nonce:Re||void 0,payPalOrderId:N.orderId})}},[t,De,re,Ae,L]),Me=Rr(async u=>{if($e.onClick?.(u),!(u.defaultPrevented||Ue||we)){if(de(null),e&&ye){let B=new ia("Provide either sessionId or create-session props, not both.","validation_error");await Ae(B),fe.current&&(Ie(null),ct(null));return}if(!e&&!ye){let B=new ia("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Ae(B),fe.current&&(Ie(null),ct(null));return}Qe(!0),ct(null),U(!1),Ie("processing");try{let B=new is(De);if(e){let _e=await B.getUnifiedCheckoutSession(e,t);await xe(_e,e);return}try{let _e=await B.createAndFetchSession({...ye});await xe(_e,_e.data.session?.id??null,{fromCreateSession:!0})}catch(_e){if(va(_e)==="session_auto_completed"){await L({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw _e}}catch(B){await Ae(Fu(B,"Automatic payment failed. Please try again."))}finally{fe.current&&(Ie(null),ct(null),Qe(!1))}}},[$e.onClick,ye,Ue,we,t,xe,De,e,Ae,L]),qe=Rr(u=>{let B=Ne.current;de(null),x.current?.({result:u,session:null,sessionId:B?.sessionId??null,autoCompleted:!1})},[]),ke=Rr(u=>{at.current?.(u)},[]),Ee=Rr(u=>{Ye.current?.(u)},[]),ee=oa(()=>Mu(Pe),[Pe]),dn=oa(()=>{let u=ee?.buttonsLayout??xu(G);return X?{...u,...X,cardButton:{...u.cardButton,...X.cardButton}}:u},[ee,G,X]),Yt=oa(()=>{let u=ee?.appearance;return S?u?{...u,...S,variables:{...u.variables,...S.variables}}:S:u},[S,ee]),H=Yt?.variables,Je=H?.colorPrimary??"#4A49FF",$=H?.colorPrimaryHover??qo(Je,.12),K=H?.borderRadius??"8px";return zu(Ou,{children:[Eo("button",{...$e,type:bt,onClick:Me,disabled:Ue||we,"aria-busy":we,style:{width:"100%",...ve===void 0?{boxSizing:"border-box",height:Bu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...dn.cardButton,...Yi({themeBundle:ee,resolvedPrimaryColor:Je,resolvedBorderRadius:K,submitButtonStyle:dn.submitButton,explicitPrimaryColor:H?.colorPrimary}),fontSize:dn.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ue||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:Ue||we?.6:1,...ot},onMouseEnter:u=>{$e.onMouseEnter?.(u),!u.defaultPrevented&&!Ue&&!we&&(ee||H?.colorPrimary)&&(u.currentTarget.style.backgroundColor=$)},onMouseLeave:u=>{$e.onMouseLeave?.(u),!u.defaultPrevented&&(ee||H?.colorPrimary)&&(u.currentTarget.style.backgroundColor=Je)},onMouseDown:u=>{$e.onMouseDown?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(0.985)")},onMouseUp:u=>{$e.onMouseUp?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(1)")},children:Eo(so,{content:ve})}),Z&&Eo(fr,{status:Z,errorMessage:be,authorized:dt}),V&&Eo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:u=>{u.target===u.currentTarget&&de(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:Eo("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:Eo(as,{sessionId:V.sessionId,nonce:V.nonce,checkoutMode:"full",billingApiUrl:De,locale:Y,theme:Pe,...Yt?{appearance:Yt}:{},buttonsTheme:G,buttonsStyles:X,initialErrorMessage:V.errorMessage,initialPayPalOrderId:V.payPalOrderId,cardTitleContent:null,onComplete:qe,onError:ke,onDecline:Ee})})})]})}export{ka as DirectPayPalButton,Lu as FloPayAutomaticPaymentButton,vc as FloPayCardSetup,hc as FloPayCardSetupError,as as FloPayCheckout,Aa as FloPayProvider,Ji as SplitCardForm,si as VaultCardFields,Xm as dropThirdPartyOnlyError,Bc as useCheckout,Br as useFloPay,mi as usePayPalFloPay};
42
+ `})]})}return rn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&U(Do),n&&(r||o)&&U(Do),n&&ie("button",{type:"button",onClick:()=>{e?.("card"),F(!0)},style:{width:"100%",...ue,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:w.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,...w.cardButton},onMouseDown:E=>{E.currentTarget.style.transform="scale(0.985)"},onMouseUp:E=>{E.currentTarget.style.transform="scale(1)"},children:ie(ho,{content:m})}),ie("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as yp,jsx as Lo,jsxs as mp}from"react/jsx-runtime";var lp=44;function Tc(e){return new Promise(t=>setTimeout(t,e))}function cp(e,t){return e instanceof Sa?e:new Sa(e instanceof Error?e.message:t,"api_error")}function dp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function up(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 pp({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:s,items:l,subscriptions:m,account:y,successUrl:b,cancelUrl:g,couponCodes:F,tagsData:M,utmMetadata:w,billingApiUrl:v,locale:U,theme:ue,appearance:E,buttonsTheme:J,buttonsStyles:K,onSuccess:se,onError:G,onDecline:xe,children:Ye,disabled:be=!1,type:et="button",style:It,...pe}){let De=Ca(()=>ap(v),[v]),_t=Ca(()=>up({createSession:n,clientId:i,products:s,items:l,subscriptions:m,account:y,successUrl:b,cancelUrl:g,couponCodes:F,tagsData:M,utmMetadata:w}),[y,g,i,F,n,s,l,m,b,M,w]),[Re,Oe]=wa(!1),[he,le]=wa(null),[Ne,Je]=wa(null),[pt,D]=wa(!1),[qe,ce]=wa(null),O=No(!0),$e=No(null),Ke=No(qe),Ve=No(se),V=No(G),tt=No(xe),nt=Nr(c=>Za($e,async A=>{try{return await c(A)}catch(N){throw A.aborted?ya(N):N}}),[]);Oo(()=>{Ke.current=qe},[qe]),Oo(()=>{Ve.current=se},[se]),Oo(()=>{V.current=G},[G]),Oo(()=>{tt.current=xe},[xe]),Oo(()=>(O.current=!0,()=>{O.current=!1,$e.current?.abort()}),[]),Oo(()=>{if(typeof window>"u")return;let c=A=>{A.key==="Escape"&&ce(null)};return window.addEventListener("keydown",c),()=>{window.removeEventListener("keydown",c)}},[]);let _e=Nr((c,A=pa)=>{tt.current?.(ln(A,c,{code:c.code,declineCode:c.declineCode}))},[]),Pe=Nr(async c=>{O.current&&(Je(null),D(c.result.status==="authorized"),le("success"),await Tc(600),O.current&&Ft(()=>Ve.current?.(c)))},[]),He=Nr(async(c,A)=>{O.current&&(V.current?.(c),A?.emitDecline&&_e(c,A.method),Je(c.message),D(!1),le("error"),await Tc(400))},[_e]),ft=Nr(async(c,A,N)=>{let h=c.data.session??null;if(!h)throw new Sa("No session data returned","api_error");let j=h.clientSecret||t;if(jr(h)){await Pe({result:Dr(h,A),session:h,sessionId:h.id||A,autoCompleted:!1});return}if(h.status==="expired")throw Da(h);try{if(c.autoProcessingPending){let me=c.autoProcessingPending,rt=new Rs(De),Xe=await nt(Rt=>rt.waitForCheckoutSessionCompletion(me.sessionId,{initialDelayMs:me.retryAfterMs,nonce:j,statusUrl:me.statusUrl,signal:Rt})),oe=Xe.data.session,ct=Xe.autoProcessingError?.type==="3ds_required"&&Xe.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Xe.autoProcessingError.nextActionRedirectUrl}:null;if(ct&&A&&j){let Rt=await nt(Pn=>Ao(ct,{billingApiUrl:De,sessionId:A,nonce:j,session:h,signal:Pn}));await Pe({result:Rt,session:h,sessionId:h.id||A,autoCompleted:!1});return}if(Xe.autoProcessingError)throw Rr(Xe.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Xe.autoProcessingError.checkoutMethod});if(!jr(oe))throw Co(oe);await Pe({result:Dr(oe,A),session:oe,sessionId:oe.id||A,autoCompleted:!1});return}if(c.autoProcessingError){let me=c.autoProcessingError.nextActionRedirectUrl;if(c.autoProcessingError.type==="3ds_required"&&me&&A&&j){let rt=await nt(Rt=>Yi({billingApiUrl:De,sessionId:A,nonce:j,nextActionRedirectUrl:me,signal:Rt}));if(rt.status==="declined")throw Rr({type:rt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:rt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:c.autoProcessingError.checkoutMethod});let ct=(await new Rs(De).waitForCheckoutSessionCompletion(A,{initialDelayMs:0,nonce:j})).data.session;if(!jr(ct))throw Rr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:c.autoProcessingError.checkoutMethod});await Pe({result:Dr(ct,A),session:ct,sessionId:ct.id||A,autoCompleted:!1});return}throw Rr(c.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:c.autoProcessingError.checkoutMethod})}if(N?.fromCreateSession&&c.autoProcessingAttempted===!0)throw Rr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ae=await xo({billingApiUrl:De,sessionId:A??h.id,session:h,nonce:j});if(Ae.type==="next_action_required"&&j){let me=A??h.id,rt=await nt(Xe=>Ao(Ae,{billingApiUrl:De,sessionId:me,nonce:j,session:h,signal:Xe}));await Pe({result:rt,session:h,sessionId:h.id||me,autoCompleted:!1});return}if(Ae.type!=="success")throw Rr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Pe({result:Ae.result,session:h,sessionId:h.id||A,autoCompleted:!1})}catch(Ae){let me=ma(Ae);if(me.code==="three_ds_aborted")return;let rt=h.id||A;await He(me,{emitDecline:!0,method:me.checkoutMethod??pa}),dp(me,rt)&&rt&&O.current&&ce({sessionId:rt,errorMessage:me.message,nonce:j||void 0,payPalOrderId:me.orderId})}},[t,De,nt,He,Pe]),Le=Nr(async c=>{if(pe.onClick?.(c),!(c.defaultPrevented||be||Re)){if(ce(null),e&&_t){let A=new Sa("Provide either sessionId or create-session props, not both.","validation_error");await He(A),O.current&&(le(null),Je(null));return}if(!e&&!_t){let A=new Sa("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await He(A),O.current&&(le(null),Je(null));return}Oe(!0),Je(null),D(!1),le("processing");try{let A=new Rs(De);if(e){let N=await A.getUnifiedCheckoutSession(e,t);await ft(N,e);return}try{let N=await A.createAndFetchSession({..._t});await ft(N,N.data.session?.id??null,{fromCreateSession:!0})}catch(N){if(Oa(N)==="session_auto_completed"){await Pe({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw N}}catch(A){await He(cp(A,"Automatic payment failed. Please try again."))}finally{O.current&&(le(null),Je(null),Oe(!1))}}},[pe.onClick,_t,be,Re,t,ft,De,e,He,Pe]),en=Nr(c=>{let A=Ke.current;ce(null),Ve.current?.({result:c,session:null,sessionId:A?.sessionId??null,autoCompleted:!1})},[]),jt=Nr(c=>{V.current?.(c)},[]),lt=Nr(c=>{tt.current?.(c)},[]),it=Ca(()=>sp(ue),[ue]),T=Ca(()=>{let c=it?.buttonsLayout??ip(J);return K?{...c,...K,cardButton:{...c.cardButton,...K.cardButton}}:c},[it,J,K]),ye=Ca(()=>{let c=it?.appearance;return E?c?{...c,...E,variables:{...c.variables,...E.variables}}:E:c},[E,it]),Me=ye?.variables,L=Me?.colorPrimary??"#4A49FF",ze=Me?.colorPrimaryHover??Qo(L,.12),Ct=Me?.borderRadius??"8px";return mp(yp,{children:[Lo("button",{...pe,type:et,onClick:Le,disabled:be||Re,"aria-busy":Re,style:{width:"100%",...Ye===void 0?{boxSizing:"border-box",height:lp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...T.cardButton,...gs({themeBundle:it,resolvedPrimaryColor:L,resolvedBorderRadius:Ct,submitButtonStyle:T.submitButton,explicitPrimaryColor:Me?.colorPrimary}),fontSize:T.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:be||Re?"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:be||Re?.6:1,...It},onMouseEnter:c=>{pe.onMouseEnter?.(c),!c.defaultPrevented&&!be&&!Re&&(it||Me?.colorPrimary)&&(c.currentTarget.style.backgroundColor=ze)},onMouseLeave:c=>{pe.onMouseLeave?.(c),!c.defaultPrevented&&(it||Me?.colorPrimary)&&(c.currentTarget.style.backgroundColor=L)},onMouseDown:c=>{pe.onMouseDown?.(c),c.defaultPrevented||(c.currentTarget.style.transform="scale(0.985)")},onMouseUp:c=>{pe.onMouseUp?.(c),c.defaultPrevented||(c.currentTarget.style.transform="scale(1)")},children:Lo(ho,{content:Ye})}),he&&Lo(kr,{status:he,errorMessage:Ne,authorized:pt}),qe&&Lo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:c=>{c.target===c.currentTarget&&ce(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:Lo("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:Lo(_s,{sessionId:qe.sessionId,nonce:qe.nonce,checkoutMode:"full",billingApiUrl:De,locale:U,theme:ue,...ye?{appearance:ye}:{},buttonsTheme:J,buttonsStyles:K,initialErrorMessage:qe.errorMessage,initialPayPalOrderId:qe.payPalOrderId,cardTitleContent:null,onComplete:en,onError:jt,onDecline:lt})})})]})}export{Va as DirectPayPalButton,pp as FloPayAutomaticPaymentButton,Gc as FloPayCardSetup,Wc as FloPayCardSetupError,_s as FloPayCheckout,Ja as FloPayProvider,hs as SplitCardForm,Ei as VaultCardFields,Bm as dropThirdPartyOnlyError,ud as useCheckout,Kr as useFloPay,Di as usePayPalFloPay};