@flopay/react 1.9.20 → 1.9.22
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/README.md +13 -4
- package/dist/index.cjs +9 -9
- package/dist/index.d.cts +14 -4
- package/dist/index.d.ts +14 -4
- package/dist/index.mjs +8 -8
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as Rt,b as yr,c as Oo,d as oi,e as zo,f as Ds,g as Ns,h as mc,i as yc}from"./chunk-CSBYK62Y.mjs";import{dropThirdPartyOnlyError as $m}from"@flopay/shared";import{PaymentAPI as ns}from"@flopay/js";import{FloPayError as ra,resolveBillingApiUrl as ku,resolveButtonsLayoutTheme as _u,resolveTheme as Ru}from"@flopay/shared";import{useCallback as xr,useEffect as wo,useMemo as ta,useRef as Io,useState as na}from"react";import{Fragment as so,jsx as Hn,jsxs as Ls}from"react/jsx-runtime";function fc(){return Ls(so,{children:[Ls("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:[Hn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Hn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Hn("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:Hn("path",{d:"M9 18l6-6-6-6"})})]})}function gc(){return Hn(so,{children:"Go back"})}function hc(){return Hn(so,{children:"Secure card checkout"})}function oo(e){return e!==void 0&&(e===""||e===null||e===!1)}function ao({content:e}){return Hn(so,{children:e===void 0?Hn(fc,{}):e})}function io({content:e}){return Hn(so,{children:e===void 0?Hn(gc,{}):e})}function Uo({content:e}){return Hn(so,{children:e===void 0?Hn(hc,{}):e})}import{classifyTelemetryFailure as vc,FloPayError as qn,isCardHolderNamePlaceholder as Os,isMoneySettledOutcome as Pc,isSetupIntentClientSecret as bc,isValidEmail as Cc}from"@flopay/shared";var Sc="Checkout is temporarily unavailable. Please try again later.";function ai(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof qn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function wc(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 zs(){return new qn(Sc,"api_error",{code:"CheckoutInitializationFailed"})}function ii(e){return!!e?.gateways?.worldpayCorporateGateway}function Ur(e){return e?.status==="open"&&ii(e)}function Us(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 qs(e,t){if(t&&(!(e instanceof qn)||e.type==="authentication_error"))return ai(e);if(!(e instanceof qn&&wc(e))){if(!t&&!(e instanceof qn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...vc(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof qn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof qn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function lo(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let s={...r,...i,email:i.email?.trim()||r.email?.trim()},l=Os(s.firstName,s.lastName);if(!Cc(s.email))return Promise.reject(new qn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[v,g]of Object.entries(s)){if(l&&v.endsWith("Name")||typeof g!="string")continue;let h=g.trim();h&&(p[v]=h)}return o=e.claimCheckoutSession(t,n,{accountData:p}),o.catch(()=>{}),o}}function js(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 si(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 $s(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(Os(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function li(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 Ic=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Ir(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Ic)if(n.test(t))return r;return e}function jr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function co(e){return e?.status==="authorized"||e?.status==="complete"}function Ks(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ya(e){let t=Ks(e);return new qn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function fa(e){return e instanceof qn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function ga(e){let t=Ks(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new qn(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function qo(e,t){return e==="processing"||Pc(e,t)}function Vs(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Ws(e,t){let n=e;if(bc(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new qn(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 qn(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function Hs(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 ci(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 jo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as cu,PaymentAPI as La,SESSION_CREATE_TELEMETRY as du}from"@flopay/js";import{buildCheckoutDisplayData as uu,classifyTelemetryFailure as Vl,FloPayError as mn,isDetachedSessionEligible as pu,resolveBillingApiUrl as mu,resolveButtonsLayoutTheme as yu,resolveIdempotencyKey as Ol,resolveTheme as Wl,SDK_VERSION as Hl,telemetryStatusClass as fu}from"@flopay/shared";import Wi,{useCallback as wn,useEffect as gr,useMemo as Yn,useRef as Tt,useState as Ot}from"react";import{createContext as Gs}from"react";var Gn=Gs({flopay:null,paypalFlopay:null,billingApiUrl:""}),ar=Gs({session:null,loading:!1,error:null});import{PaymentAPI as mi}from"@flopay/js";import{classifyTelemetryFailure as Uc,FloPayError as yi,generateIdempotencyKey as qc,isValidEmail as Wo,normalizeGatewayEnvironment as jc,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as fi,SDK_VERSION as $c}from"@flopay/shared";import{loadScript as Kc}from"@paypal/paypal-js";import{useCallback as Cr,useEffect as At,useMemo as Ho,useRef as it,useState as Rr}from"react";import{isValidEmail as kc}from"@flopay/shared";import{useCallback as Ys,useEffect as _c,useRef as Js,useState as Zs}from"react";import{jsx as Xs,jsxs as $o}from"react/jsx-runtime";function Dn(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 uo(){let[e,t]=Zs(null),n=Js(null),r=Js(0),o=Ys((s,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:l}),new Promise(p=>{n.current=p})),[]),i=Ys(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return _c(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function po({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=Zs(e.email?.trim()??""),p=kc(s.trim());return $o("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:[$o("div",{style:{fontWeight:700},children:["Continue with ",t]}),$o("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Xs("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:v=>l(v.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),$o("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Xs("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),$o("button",{type:"button",disabled:!p||o,onClick:()=>{n(Dn({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function Rc(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function $r(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Pr(e){if(typeof e!="object"||e===null)return;let t=e;return $r(t.code)??$r(t.type)??$r(t.name)}function mo(e){if(!(typeof e!="object"||e===null))return $r(e.decline_code)}function Ko(e){return typeof e!="object"||e===null?!1:$r(e.type)?.toLowerCase()==="card_error"||mo(e)!==void 0}function br(e){let t=Rc(e)?.toLowerCase()??"",r=`${Pr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Ec}from"@flopay/shared";import{useContext as ha}from"react";function kr(){return ha(Gn).flopay}function di(){return ha(Gn).paypalFlopay??null}function Tc(){return ha(ar)}function Qs(){return ha(Gn).billingApiUrl||Ec()}function va(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 Pa(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}import{FLO_INSTRUMENT_SCHEMA_VERSION as Ac}from"@flopay/shared";import{useCallback as Mc,useRef as ba}from"react";var xc={"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 Bc(e){return e==="stripe"||e==="paypal"?e:void 0}function Fc(e){let t=Bc(e.provider),n={schemaVersion:Ac,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=xc[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 ui=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function yo(e,t){let n=ba(e);n.current=e;let r=ba(new Set),o=ba(t),i=ba(t);return Oo(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Mc(s=>{if(i.current!==t)return;let l=Fc(s);if(l){if(ui.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}Rt(()=>n.current?.(l))}},[t])}var Dc=Symbol.for("@flopay/js.telemetry.bridge.v1"),Nc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Lc(){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 Oc(e){let t=Lc(),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 Ca(e){let t=globalThis[Nc];return Oc(t?.(e)??{})}function Qt(e){if(e)return e[Dc]}import{useCallback as _r,useEffect as zc,useRef as pi}from"react";function Vo(e){let t=pi(0),n=pi(null),r=pi(null),o=_r((y=r.current)=>{y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),i=_r(y=>{o();let _=t.current+1;return t.current=_,n.current=null,r.current={generation:_,method:y,timer:null,yieldedControl:!1},_},[o]),s=_r(y=>{let _=r.current;return y!==void 0&&_?.generation!==y?!1:(o(_),r.current=null,(y===void 0||n.current===y)&&(n.current=null),!0)},[o]),l=_r(y=>{let _=r.current,M=y??_?.generation??t.current;(y===void 0||_?.generation===y)&&(o(_),r.current=null),n.current=M},[o]),p=_r(y=>n.current===(y??t.current),[]),v=_r(y=>r.current?.generation===y&&n.current!==y,[]),g=_r(()=>{let y=r.current;y&&(y.yieldedControl=!0,o(y))},[o]),h=_r(()=>{let y=r.current;!y?.yieldedControl||document.visibilityState!=="visible"||(o(y),y.timer=setTimeout(()=>{y.timer=null,r.current?.generation===y.generation&&(r.current=null,n.current=y.generation,e(y.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[o,e]);return zc(()=>{let y=()=>{document.visibilityState==="visible"?h():g()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",g),window.addEventListener("focus",h),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",g),window.removeEventListener("focus",h),o()}},[o,g,h]),{startAttempt:i,finishAttempt:s,invalidateAttempt:l,isAttemptInvalidated:p,isAttemptCurrent:v,generationRef:t}}import{jsx as Kr,jsxs as hi}from"react/jsx-runtime";var Sa=45,Vc=1e3,Wc=11e3,Hc=["https://www.paypal.com","https://www.sandbox.paypal.com"],gi="We couldn't open PayPal. Try again or choose another payment method.",Gc={width:"100%",minHeight:Sa,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 Yc(e){return e.includes("No ack for postMessage init()")&&Hc.some(t=>e.includes(t))&&e.includes("10000ms")}var Jc={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 Xc(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Jc[e.kind]??null}}function Zc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Yc(t)?"paypal_init_timeout":"paypal_init_failure"}function Qc(e,t=!1){return e?t?`${gi} Open this page in your system browser, then try again.`:`${gi} Allow pop-ups for this site, then try again.`:gi}function ed(e){let t=Ko(e),n=br(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 td(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 nd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function el({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:s,environment:l,currency:p,isSubscription:v,providerObjectType:g,approvalPresentation:h,onTokenizedBody:y,onComplete:_,onErrorChange:M,onDecline:U,onTechnicalFailure:qe,isProcessing:ge=!1,onLoadStateChange:S,onInitializationStateChange:W,allowAutomaticRetry:Y=!0,onButtonClick:de,runBeforeButtonClick:Le,session:Se,existingOrderId:Re,telemetry:Ge,telemetryContext:St,onInstrument:tt,debug:je=!1}){let $e=kr(),ue=yo(tt,e),we=Ho(()=>{if($e)return null;let E=Ca({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:$c,enabled:Ge!==!1});return E.setCheckoutContext(St??{}),E.beginCheckout(St??{}),E},[n,$e,Ge,St?.checkoutMode,St?.layout]),Xe=Ho(()=>Qt($e),[$e]);At(()=>()=>{we&&we.flush().catch(()=>{}).finally(()=>we.destroy())},[we]);let ee=Ho(()=>({error:E=>{Xe?Xe.error(E):we?.error(E),ue({class:"technical_error",errorCode:E.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":E.errorCode,requestCategory:E.requestCategory,provider:E.provider})},log:E=>{Xe?Xe.log(E):we?.log(E),ue({class:"lifecycle",name:E.name,provider:E.provider})},performance:E=>{Xe?Xe.performance(E):we?.performance(E)},terminal:E=>{Xe?Xe.terminal(E):we?.terminal(E)},startTiming:()=>Xe?.now()??we?.now()??0,elapsed:E=>Xe?.elapsed(E)??Math.max(0,(we?.now()??E)-E)}),[ue,Xe,we]),Ie=it(null),he=it(0),st=it(null),lt=it(null),T=it(null),$=it(!1),[Ee,ie]=Rr(!1),[rt,A]=Rr(!1),[Te,dt]=Rr(0),We=it(0),[se,x]=Rr(!1),Q=it(!1),Me=it(!1),[ot,ke]=Rr(!1),[Ke,_e]=Rr(!1),{request:le,collect:ve,finish:Vt}=uo(),H=it({sessionId:e,required:!Wo(r?.trim()||Se?.customer?.email?.trim())});H.current.sessionId!==e&&(H.current={sessionId:e,required:!Wo(r?.trim()||Se?.customer?.email?.trim())});let Mt=H.current.required,mt=Ho(()=>n.replace(/\/+$/,""),[n]),ne=Se?.gateways?.paypal?.providerObjectType??g,u=ne??(v?"subscription":"order"),[w]=Rr(va),xe=Se?.gateways?.paypal?.approvalPresentation??h,me=Pa(w,xe==="app_switch"?"app_switch":void 0,u),Ct=ne==="order"||ne==="setup_token",nt=Ho(()=>JSON.stringify([mt,s,p,l??"",u,Ct,me,e,Re??""]),[mt,s,p,l,Re,u,Ct,me,e]),xt=it(nt),K=xt.current!==nt,Wt=it(je),wt=it(null),[yn,sr]=Rr([]),N=Cr(E=>{Wt.current&&sr(be=>[...be,`${new Date().toISOString().slice(11,23)} ${E}`])},[]);At(()=>{Wt.current=je,je&&N("debug:enabled"),wt.current?.setEnabled(je)},[N,je]);let fn=it(y),In=it(_),cn=it(M),rn=it(U),gn=it(qe),Jn=it(de),dn=it(S),Ht=it(W),Ae=it(i),Oe=it(Le),on=it(Se),ut=it(r),jn=it(o),Bt=it(t),Gt=it(null),gt=it(new Map),$t=it(new Map),un=it(!1);At(()=>(un.current=!0,()=>{un.current=!1}),[]),At(()=>{fn.current=y},[y]),At(()=>{Ae.current=i},[i]),At(()=>{In.current=_},[_]),At(()=>{cn.current=M},[M]),At(()=>{rn.current=U},[U]),At(()=>{gn.current=qe},[qe]),At(()=>{Jn.current=de},[de]),At(()=>{dn.current=S},[S]),At(()=>{Ht.current=W},[W]),At(()=>{Oe.current=Le},[Le]),At(()=>{on.current=Se},[Se]),At(()=>{ut.current=r},[r]),At(()=>{jn.current=o},[o]),At(()=>{Bt.current=t},[t]),At(()=>{We.current=Te},[Te]),At(()=>{se&&T.current?.focus()},[se,Te]);let Ft=Cr(()=>{window.setTimeout(()=>{T.current?.focus()},0)},[]),It=Cr(()=>{ie(!1),dt(E=>E+1)},[]),an=Cr(()=>{x(!1),(Ie.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Ie.current)?.focus?.()},[]);At(()=>{!Ee||!$.current||($.current=!1,an())},[an,Ee,Te]);let Nn=Cr((E,be)=>{let I=be?.popupBlocked??br(E),Nt=Qc(I,w.inAppBrowser),Pn=gn.current;if(Pn){let sn=I&&w.inAppBrowser?new yi(Nt,"api_error",{code:be?.code??"paypal_popup_blocked"}):E;Pn("paypal",sn,be);return}cn.current?.(Nt)},[w.inAppBrowser]),vt=Cr(E=>{let be=st.current,I=lt.current;be===null||!I||(ee.log({...I,name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:E}),ee.performance({...I,stage:"overlay_return",durationMs:ee.elapsed(be),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:E}),st.current=null)},[ee]),J=Cr((E,be,I)=>{let Nt=lt.current;vt("overlay_timeout"),Nt&&ee.error({...Nt,errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Nn(be,I),x(!0),It(),Ft()},[vt,Ft,Nn,It,ee]),{finishAttempt:hn,generationRef:vn,invalidateAttempt:Dt,isAttemptCurrent:zt,isAttemptInvalidated:Ln,startAttempt:$n}=Vo(J),Xn=Cr(()=>(x(!1),$n("paypal")),[$n]),Yt=Cr(E=>{Dt(E?.generation),E?.showRetry&&x(!0),E?.remount&&It(),E?.focus!==!1&&Ft()},[Ft,Dt,It]),ze=E=>{let be=Gt.current;return be&&$t.current.set(E,be),E};At(()=>{xt.current!==nt&&(xt.current=nt,Q.current=!1,Me.current=!1,ie(!1),A(!1),ke(!1),Ht.current?.("loading"))},[nt]),At(()=>{Rt(()=>dn.current?.(Ee&&!ot))},[Ee,ot]);let Ut=jc(l);At(()=>{let E={attempt:vn.current+1,...w,presentationMode:me},be=()=>lt.current??E,I={error:m=>ee.error({...m,...be()}),log:m=>ee.log({...m,...be()}),performance:m=>ee.performance({...m,...be()}),terminal:m=>ee.terminal({...m,...be()}),startTiming:ee.startTiming,elapsed:ee.elapsed},Nt=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",Pn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(N(`mount clientId=${Nt} env=${l??"(unset)"}\u2192${Ut??"live"} ccy=${p} sub=${v}`),N(`ua=${Pn.slice(0,80)}${Pn.length>80?"\u2026":""}`),!s){N("FAIL: clientId empty \u2014 gateway misconfigured"),ke(!0),I.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){N("FAIL: containerRef not attached");return}he.current=I.startTiming(),I.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let sn=!1,On=!1,ae=()=>sn||On,bn,Br=!1,Gr=()=>{bn=qc(),bn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Br=!0},kn=null,wr=!1,lr=null,Zn=!1,Kt=()=>{!lr||Zn||(Zn=!0,lr.close().catch(()=>{}))},_n=!1,vr=!1,zn=Ie.current,Rn=null,Qn=null,er=[],Pt=null,Cn=!1,Kn=!1,tr=null,En=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let d=m.getBoundingClientRect();return`${Math.round(d.width)}\xD7${Math.round(d.height)}`},Ve=m=>{if(!m)return"(empty)";try{let d=new URL(m,typeof window>"u"?"https://localhost":window.location.href),C=d.pathname.toLowerCase();return C.includes("checkcaptcha")||C.includes("captcha")?`CAPTCHA(${d.host}${C})`:C.includes("risk")||C.includes("challenge")?`RISK(${d.host}${C})`:C.includes("smart/buttons")?`smart-buttons(${d.host})`:`${d.host}${C}`.slice(0,100)}catch{return m.slice(0,80)}},tn=m=>{let d=m.getAttribute("src"),C=m.getAttribute("srcdoc"),L=m.getAttribute("name"),te=m.getAttribute("sandbox"),V=[];return d&&V.push(`src=${Ve(d)}`),C&&V.push(`srcdoc[${C.length}ch]`),!d&&!C&&V.push("src=(empty) srcdoc=(empty)"),L&&V.push(`name=${L.slice(0,40)}`),te!==null&&V.push(`sandbox="${te.slice(0,40)}"`),V.join(" ")},pn=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let d=m.contentDocument;if(!d)return"cd=null";let C=d.body?.children.length??0,L=d.body?.innerHTML.length??0,te=d.head?.innerHTML.length??0;return`cd=same-origin readyState=${d.readyState} body[${C}children,${L}ch] head[${te}ch]`}catch(d){return`cd=cross-origin(${d.message.slice(0,30)})`}},cr=[],Fr=m=>{if(ae())return;let d=m.message??String(m.error??"(no message)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(N(`window:error ${d.slice(0,140)}`),cr.push(d))},nr=m=>{if(ae())return;let d=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(N(`window:rejection ${d.slice(0,140)}`),cr.push(d))},dr={value:0},Tn=()=>{Rn?.disconnect(),Rn=null,Qn?.disconnect(),Qn=null;for(let m of er.splice(0))clearTimeout(m);Kn=!1,Cn&&typeof window<"u"&&(window.removeEventListener("error",Fr),window.removeEventListener("unhandledrejection",nr)),Cn=!1},An=()=>{if(!(Cn||ae()||_n)){if(Cn=!0,cr.length=0,dr.value=0,typeof window<"u"&&(window.addEventListener("error",Fr),window.addEventListener("unhandledrejection",nr)),typeof PerformanceObserver<"u")try{Qn=new PerformanceObserver(m=>{if(!ae())for(let d of m.getEntries()){if(!d.name.toLowerCase().includes("paypal"))continue;dr.value+=1;let C=Math.round(d.duration);N(`net ${C}ms ${d.name.slice(0,90)}`)}}),Qn.observe({type:"resource",buffered:!0})}catch{}tr?.()}},Dr=()=>{Pt&&(clearTimeout(Pt),Pt=null)},Un=()=>{Tn(),Dr()},Nr={setEnabled:m=>{m?An():Tn()}};wt.current=Nr,Wt.current&&An();let Jt=m=>{if(!m)return!1;let d=m.toLowerCase();return d.includes("zoid destroyed")||d.includes("destroyed all components")||d.includes("window closed")||d.includes("detected container element removed")},k=m=>{if(ae()||Jt(m))return;let d=Ir(m)??m;Rt(()=>cn.current?.(d))},f=(m,d)=>{if(sn||wr)return;wr=!0,On=!0,Un(),Kt();let C=Xc({kind:m,generationActive:!0,automaticRetryAllowed:Y,automaticRetryUsed:Q.current});if(C.action==="retry"){Q.current=!0,ie(!1),_e(!1),A(!0),Ht.current?.("retrying"),kn=setTimeout(()=>{sn||dt(L=>L+1)},Vc);return}if(ie(!1),_e(!1),A(!1),ke(!0),C.action!=="ignore"){if(Ht.current?.("exhausted"),C.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",d);return}C.report&&I.error({errorCode:C.report.errorCode,stage:C.report.stage,operationOutcome:C.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),Me.current||(Me.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Zc(m,d)))}};ke(!1);let G=async(m,d=Gt.current)=>{if(ae())return;let C=d?.sessionId??e;if(fn.current){await fn.current(m,{sessionId:C,accountPatch:d?.accountPatch,nonce:d?.nonce});return}let L=I.startTiming();I.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let te=()=>{I.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),I.performance({stage:"processing",durationMs:I.elapsed(L),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let V=on.current,b=d?.accountPatch?.email??ut.current,Z=d?.accountPatch?.userId??V?.customer?.id??V?.accountData?.userId??"",pt=d?.accountPatch?.firstName??V?.customer?.firstName??V?.accountData?.firstName,qt=d?.accountPatch?.lastName??V?.customer?.lastName??V?.accountData?.lastName,fe=await new mi(mt,{telemetry:!1}).processPayment(Z,{sessionId:C,nonce:d?.nonce??Bt.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:Z,email:b??V?.customer?.email??"",...pt?{firstName:pt}:{},...qt?{lastName:qt}:{},country:d?.accountPatch?.country??V?.customer?.country??V?.accountData?.country??void 0,zip:d?.accountPatch?.zip??V?.customer?.zip??V?.accountData?.zip??void 0}});if(fe.ok){if(On||sn&&un.current)return;te(),I.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Rt(()=>In.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ae())return;let D=await fe.json().catch(()=>null),q=D?.message??"PayPal payment failed.",Fe=Ir(q)??q;te(),fe.status===400&&(typeof D?.declineCode=="string"||!Array.isArray(D?.fields))?I.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):fe.status===400||fe.status===422?I.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):I.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:nd(fe.status),failureCategory:fe.status>=500?"server_error":void 0}),k(Fe),Rt(()=>rn.current?.(nn("paypal",Fe,{code:D?.code,declineCode:D?.declineCode})));return}catch(V){if(ae())return;te(),I.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let b=V instanceof Error?V.message:"PayPal payment failed.",Z=Ir(b)??b;k(Z),Rt(()=>rn.current?.(nn("paypal",Z)));return}},B=()=>new yi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ce=m=>ae()?Promise.reject(B()):Promise.resolve(m),ct=async m=>{if(ae())throw B();Br||Gr();let d=Gt.current,C=d?.sessionId??e,L=d?.nonce??Bt.current;I.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let te;try{te=await new mi(mt,{telemetry:!1}).createSessionIntent(C,L??"",Ct?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:fi,paymentMethodId:null,intentKind:u==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:bn})}catch(V){throw I.error({...Uc(V,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),V}if(ae())throw B();if(te.provider!=="paypal"||te.providerObjectType!==u)throw new Error(m);return I.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),te.providerObjectId},ye=(m,d)=>{let C=d?.nonce??Bt.current;if(!C)return;let L=d?.sessionId??e,te=mo(m)??Pr(m)??"provider_declined";new mi(mt,{telemetry:!1}).reportSessionIntentDecline(L,C,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:te}).catch(()=>{})},z=Te;N("loadScript:scheduled (deferred 1 tick)");let X=null,F=setTimeout(()=>{if(sn){N("loadScript:skipped (cancelled before defer ran)");return}N("loadScript:start");let m=Ut==="live"?"production":Ut,d={};u==="subscription"?d={intent:"subscription",vault:!0}:u==="order"&&(d={intent:"capture"}),X=Kc({clientId:s,currency:p,...d,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let C=!1;X.then(L=>{if(C=!0,N(`loadScript:resolved inactive=${ae()} ns=${!!L} buttons=${!!L?.Buttons}`),ae())return;if(!L?.Buttons){N("FAIL: namespace missing Buttons factory"),f("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}I.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),I.performance({stage:"provider_ready",durationMs:I.elapsed(he.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),I.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let te=async(fe,D)=>{if(ae()||We.current!==z)return;let q=fe.vaultSetupToken??fe.subscriptionID??fe.orderID??"",Fe=q?$t.current.get(q):gt.current.get(z);if(!(!Fe||!zt(Fe.generation))&&hn(Fe.generation)){$t.current.delete(q),gt.current.delete(Fe.surfaceKey),vt("approved");try{if(_e(!0),Rt(()=>cn.current?.(null)),!q)throw new yi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let De=on.current,kt=qr(jn.current??[De?.customer?.firstName,De?.customer?.lastName].filter(Boolean).join(" ")),He=Dn({email:Fe.accountPatch?.email?.trim()||ut.current?.trim()||De?.customer?.email?.trim(),firstName:Fe.accountPatch?.firstName?.trim()||kt.firstName,lastName:Fe.accountPatch?.lastName?.trim()||kt.lastName});if(!Wo(He.email)||!(He.firstName||He.lastName))try{let Xt=td(await D?.order?.get?.());He=Dn({email:Xt.email||He.email,firstName:Xt.firstName||He.firstName,lastName:Xt.lastName||He.lastName})}catch{}if((Ae.current||Mt)&&!Wo(He.email)){let Xt=await ve("PayPal",He);if(!Xt)return;He=Xt}Wo(He.email)&&(Fe.accountPatch=Dn({...Fe.accountPatch,...He}),await Ae.current?.(He));let Mn;u==="setup_token"?Mn={id:q,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:fi}:Ct?Mn={id:q,isPaypal:!0,gateway:"paypal",paymentMethodType:fi}:Mn={id:q,isPaypal:!0},await G(Mn,Fe)}catch(De){k(De instanceof Error?De.message:"PayPal capture failed.")}finally{ae()||_e(!1)}}},V=fe=>{let D=Re?()=>Ce(Re):()=>ct(fe);return async()=>ze(await D())},b=L.Buttons({style:{layout:"horizontal",height:Sa,tagline:!1},...me==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(fe,D)=>{if(ae()){await D.reject();return}Gr();let q=Oe.current,Fe={};if(q)try{let He=await q("paypal");if(ae()){await D.reject();return}if(!He.proceed){Gt.current=null,gt.current.delete(z),await D.reject();return}Fe={sessionId:He.sessionId,accountPatch:He.accountPatch,nonce:He.nonce}}catch(He){N(`onClick:runBeforeButtonClick rejected msg=${(He instanceof Error?He.message:String(He)).slice(0,120)}`),Gt.current=null,gt.current.delete(z),await D.reject();return}Rt(()=>Jn.current?.("paypal"));let De=Xn(),kt={generation:De,surfaceKey:z,...Fe};Gt.current=kt,gt.current.set(z,kt),lt.current={...E,attempt:De},await D.resolve(),I.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),I.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),st.current=I.startTiming()},createOrder:u==="order"?V("Failed to create PayPal order."):void 0,createSubscription:u==="subscription"?V("Failed to create PayPal subscription."):void 0,createVaultSetupToken:u==="setup_token"?async()=>ze(await ct("Failed to create PayPal setup token.")):void 0,onApprove:te,onCancel:()=>{if(ae())return;let fe=gt.current.get(z)??Gt.current;fe&>.current.delete(fe.surfaceKey),Gt.current=null,vt("cancelled"),I.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),$.current=!0,Yt({generation:fe?.generation,remount:!0,focus:!1})},onError:fe=>{if(ae()||We.current!==z)return;let D=fe instanceof Error?fe.message:"PayPal failed to render.";if(N(`onError rendered=${_n} msg=${D.slice(0,120)}`),_n){let q=gt.current.get(z)??Gt.current;if(q&&!zt(q.generation)||!q&&Ln())return;if(Jt(D)){hn(q?.generation);return}let{errorCode:Fe,popupBlocked:De,providerDeclined:kt,terminalReason:He}=ed(fe);if(vt(He),kt){I.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:He}),ye(fe,q),Rt(()=>rn.current?.(nn("paypal",D))),q&>.current.delete(q.surfaceKey),Gt.current=null,hn(q?.generation);return}I.error({errorCode:Fe,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:He}),q&>.current.delete(q.surfaceKey),Gt.current=null,Yt({generation:q?.generation,remount:!0,showRetry:!0,focus:!0}),Nn(fe,{code:"paypal_runtime_failed",popupBlocked:De});return}f(Jt(D)?"teardown":"pre_ready_callback",D)}}),Z=b.isEligible();if(N(`isEligible=${Z}`),I.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Z){ie(!1),f("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}vr=!0,lr=b,tr=()=>{if(!Cn||Kn||ae()||_n)return;Kn=!0,N(`container:dims ${En(zn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Rn=new MutationObserver(D=>{if(!ae()){for(let q of D)if(q.type==="childList")q.addedNodes.forEach(Fe=>{if(!(Fe instanceof Element))return;let De=Fe.tagName.toLowerCase(),kt=(Fe.getAttribute("title")??"").slice(0,40),He=De==="iframe"?` ${tn(Fe)}`:"";N(`child+ ${De}${kt?` title="${kt}"`:""}${He} dims=${En(Fe)}`)});else if(q.type==="attributes"&&q.target instanceof Element){let Fe=q.target;if(Fe.tagName.toLowerCase()!=="iframe")continue;let De=q.attributeName;(De==="src"||De==="srcdoc")&&N(`attr~ iframe ${De}=${De==="srcdoc"?`[${(Fe.getAttribute("srcdoc")??"").length}ch]`:Ve(Fe.getAttribute("src"))} dims=${En(Fe)}`)}}}),Rn.observe(zn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let fe=D=>{if(ae()||_n)return;let q=zn.querySelectorAll("iframe"),Fe=typeof document<"u"&&"hasStorageAccess"in document;N(`watchdog:${D} container=${En(zn)} children=${zn.childElementCount} iframes=${q.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Fe} paypalNetRequests=${dr.value}`),q.forEach((De,kt)=>{let He=(De.getAttribute("title")??"").slice(0,40);N(` iframe[${kt}] ${En(De)}${He?` title="${He}"`:""} ${tn(De)}`);let Mn=pn(De);Mn&&N(` ${Mn}`)}),cr.length===0&&N(" (no PayPal/zoid window errors captured)")};er.push(setTimeout(()=>fe("3s"),3e3)),er.push(setTimeout(()=>fe("8s"),8e3)),er.push(setTimeout(()=>fe("15s"),15e3))},tr(),N("render:start");let qt=I.startTiming();Pt=setTimeout(()=>{ae()||_n||(N("watchdog:11s retryable render timeout"),f("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Wc);let Be=b.render(zn);(async()=>{try{if(await Be,N(`render:resolved inactive=${ae()}`),Un(),ae()){Kt();return}_n=!0,ie(!0),A(!1),Ht.current?.("ready"),I.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),I.performance({stage:"checkout_render",durationMs:I.elapsed(qt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(fe){let D=fe instanceof Error?fe.message:"PayPal failed to render.";N(`render:rejected msg=${D.slice(0,120)}`),Un(),f(Jt(D)?"teardown":"render_rejected",D)}})()}).catch(L=>{let te=L instanceof Error?L.message:"PayPal operation failed.";N(`provider:failed msg=${te.slice(0,120)}`);let V="script_rejected";C&&Jt(te)?V="teardown":C&&vr&&(V="render_rejected"),f(V,te)})},0);return()=>{sn=!0,clearTimeout(F),kn&&clearTimeout(kn),Un(),wt.current===Nr&&(wt.current=null),Kt(),st.current=null,lt.current=null}},[Y,mt,s,p,l,u,me,Ct,e,Re,Te,ee,ve,Mt,N,vt]);let Pe=je?hi("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ot?"#fef2f2":"#f3f4f6",border:`1px solid ${ot?"#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=${Ee} failed=${ot})`,yn.length===0?`
|
|
1
|
+
import{a as Ft,b as wr,c as Ho,d as bi,e as Wo,f as Js,g as Xs,h as xc,i as Mc}from"./chunk-CSBYK62Y.mjs";import{dropThirdPartyOnlyError as mm}from"@flopay/shared";import{PaymentAPI as hs}from"@flopay/js";import{FloPayError as fa,resolveBillingApiUrl as qu,resolveButtonsLayoutTheme as ju,resolveTheme as $u}from"@flopay/shared";import{useCallback as xr,useEffect as xo,useMemo as ya,useRef as Mo,useState as ma}from"react";import{Fragment as mo,jsx as rr,jsxs as Zs}from"react/jsx-runtime";function Bc(){return Zs(mo,{children:[Zs("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:[rr("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),rr("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",rr("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:rr("path",{d:"M9 18l6-6-6-6"})})]})}function Fc(){return rr(mo,{children:"Go back"})}function Dc(){return rr(mo,{children:"Secure card checkout"})}function uo(e){return e!==void 0&&(e===""||e===null||e===!1)}function po({content:e}){return rr(mo,{children:e===void 0?rr(Bc,{}):e})}function yo({content:e}){return rr(mo,{children:e===void 0?rr(Fc,{}):e})}function Go({content:e}){return rr(mo,{children:e===void 0?rr(Dc,{}):e})}import{classifyTelemetryFailure as Oc,FloPayError as Vn,isCardHolderNamePlaceholder as Qs,isMoneySettledOutcome as Nc,isSetupIntentClientSecret as Lc,isValidEmail as zc}from"@flopay/shared";var Uc="Checkout is temporarily unavailable. Please try again later.";function Pi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Vn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function qc(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 el(){return new Vn(Uc,"api_error",{code:"CheckoutInitializationFailed"})}function Ci(e){return!!e?.gateways?.worldpayCorporateGateway}function Mr(e){return e?.status==="open"&&Ci(e)}function tl(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")||Mr(r))||t&&e?.data.paypal?.publishableKey)}function nl(e,t){if(t&&(!(e instanceof Vn)||e.type==="authentication_error"))return Pi(e);if(!(e instanceof Vn&&qc(e))){if(!t&&!(e instanceof Vn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...Oc(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Vn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Vn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function fo(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let s={...r,...i,email:i.email?.trim()||r.email?.trim()},l=Qs(s.firstName,s.lastName);if(!zc(s.email))return Promise.reject(new Vn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[f,b]of Object.entries(s)){if(l&&f.endsWith("Name")||typeof b!="string")continue;let g=b.trim();g&&(y[f]=g)}return o=e.claimCheckoutSession(t,n,{accountData:y}),o.catch(()=>{}),o}}function rl(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 wi(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 ol(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 Yr(e){if(Qs(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Si(e,t){return t?{...e,...t}:e}function dn(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 jc=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Br(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of jc)if(n.test(t))return r;return e}function Tr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Fr(e){return e?.status==="authorized"||e?.status==="complete"}function al(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function _a(e){let t=al(e);return new Vn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Ra(e){return e instanceof Vn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function go(e){let t=al(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new Vn(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function Yo(e,t){return e==="processing"||Nc(e,t)}function il(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function sl(e,t){let n=e;if(Lc(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new Vn(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 Vn(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function ll(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 ki(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 Jo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Iu,PaymentAPI as Za,SESSION_CREATE_TELEMETRY as _u}from"@flopay/js";import{buildCheckoutDisplayData as Ru,classifyTelemetryFailure as lc,FloPayError as Sn,isDetachedSessionEligible as Eu,resolveBillingApiUrl as Tu,resolveButtonsLayoutTheme as Au,resolveIdempotencyKey as tc,resolveTheme as cc,SDK_VERSION as dc,telemetryStatusClass as xu}from"@flopay/shared";import ls,{useCallback as wn,useEffect as yr,useMemo as ar,useRef as At,useState as zt}from"react";import{createContext as cl}from"react";var or=cl({flopay:null,paypalFlopay:null,billingApiUrl:""}),ur=cl({session:null,loading:!1,error:null});import{PaymentAPI as Ei}from"@flopay/js";import{classifyTelemetryFailure as id,FloPayError as Ti,generateIdempotencyKey as sd,isValidEmail as ra,normalizeGatewayEnvironment as ld,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Ai,SDK_VERSION as cd}from"@flopay/shared";import{loadScript as dd}from"@paypal/paypal-js";import{useCallback as kr,useContext as ud,useEffect as Ot,useMemo as oa,useRef as ot,useState as Lr}from"react";import{isValidEmail as $c}from"@flopay/shared";import{useCallback as dl,useEffect as Kc,useRef as ul,useState as yl}from"react";import{jsx as pl,jsxs as Xo}from"react/jsx-runtime";function On(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 ho(){let[e,t]=yl(null),n=ul(null),r=ul(0),o=dl((s,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:l}),new Promise(y=>{n.current=y})),[]),i=dl(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return Kc(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function vo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=yl(e.email?.trim()??""),y=$c(s.trim());return Xo("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:[Xo("div",{style:{fontWeight:700},children:["Continue with ",t]}),Xo("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",pl("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}})]}),Xo("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&pl("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Xo("button",{type:"button",disabled:!y||o,onClick:()=>{n(On({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Vc=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),Hc=["https://www.paypal.com","https://www.sandbox.paypal.com"];function Ea(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 ml(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Jr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Sr(e){if(typeof e!="object"||e===null)return;let t=e;return Jr(t.code)??Jr(t.type)??Jr(t.name)}function bo(e){if(!(typeof e!="object"||e===null))return Jr(e.decline_code)}function Zo(e){return typeof e!="object"||e===null?!1:Jr(e.type)?.toLowerCase()==="card_error"||bo(e)!==void 0}function Wc(e){let t=ml(e)?.toLowerCase()??"",n=Sr(e)?.toLowerCase()??"";return Vc.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 Ii(e){if(Sr(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=ml(e)??"";return n.includes("No ack for postMessage init()")&&Hc.some(r=>n.includes(r))&&n.includes("10000ms")}function Ta(e,t){if(Zo(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=Wc(e)||t.inAppBrowser&&!t.handoffObserved&&Ii(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function Dr(e){return Ta(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}import{resolveBillingApiUrl as Gc}from"@flopay/shared";import{useContext as Aa}from"react";function Or(){return Aa(or).flopay}function _i(){return Aa(or).paypalFlopay??null}function Yc(){return Aa(ur)}function fl(){return Aa(or).billingApiUrl||Gc()}function Qo(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 xa(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}import{FLO_INSTRUMENT_SCHEMA_VERSION as Jc}from"@flopay/shared";import{useCallback as Xc,useRef as Ma}from"react";var Zc={"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 Qc(e){return e==="stripe"||e==="paypal"?e:void 0}function ed(e){let t=Qc(e.provider),n={schemaVersion:Jc,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Zc[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 Ri=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Po(e,t){let n=Ma(e);n.current=e;let r=Ma(new Set),o=Ma(t),i=Ma(t);return Ho(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Xc(s=>{if(i.current!==t)return;let l=ed(s);if(l){if(Ri.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}Ft(()=>n.current?.(l))}},[t])}import{createContext as td}from"react";var ea=td(null);function Ba(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var nd=Symbol.for("@flopay/js.telemetry.bridge.v1"),rd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function od(){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 ad(e){let t=od(),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 Fa(e){let t=globalThis[rd];return ad(t?.(e)??{})}function mn(e){if(e)return e[nd]}import{useCallback as Nr,useEffect as gl,useRef as ta}from"react";function na(e,t){let n=ta(0),r=ta(null),o=ta(null),i=ta(e),s=ta(t?.onHandoffObserved);gl(()=>{i.current=e,s.current=t?.onHandoffObserved},[e,t?.onHandoffObserved]);let l=Nr((v=o.current)=>{v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),y=Nr(v=>{l();let q=n.current+1;return n.current=q,r.current=null,o.current={generation:q,method:v,timer:null,yieldedControl:!1},q},[l]),f=Nr(v=>{let q=o.current;return v!==void 0&&q?.generation!==v?!1:(l(q),o.current=null,(v===void 0||r.current===v)&&(r.current=null),!0)},[l]),b=Nr(v=>{let q=o.current,Re=v??q?.generation??n.current;(v===void 0||q?.generation===v)&&(l(q),o.current=null),r.current=Re},[l]),g=Nr(v=>r.current===(v??n.current),[]),M=Nr(v=>o.current?.generation===v&&r.current!==v,[]),R=Nr(()=>{let v=o.current;v&&(l(v),!v.yieldedControl&&(v.yieldedControl=!0,s.current?.(v.method)))},[l]),C=Nr(()=>{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 gl(()=>{let v=()=>{document.visibilityState==="visible"?C():R()};return document.addEventListener("visibilitychange",v),window.addEventListener("blur",R),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("blur",R),window.removeEventListener("focus",C),l()}},[l,R,C]),{startAttempt:y,finishAttempt:f,invalidateAttempt:b,isAttemptInvalidated:g,isAttemptCurrent:M,generationRef:n}}import{jsx as Xr,jsxs as xi}from"react/jsx-runtime";var Da=45,pd=1e3,yd=11e3,md={width:"100%",minHeight:Da,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"},fd={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 gd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:fd[e.kind]??null}}function hl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Ii(t)?"paypal_init_timeout":"paypal_init_failure"}function hd(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 vd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function vl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:s,environment:l,currency:y,isSubscription:f,providerObjectType:b,approvalPresentation:g,onTokenizedBody:M,onComplete:R,onErrorChange:C,onDecline:v,onTechnicalFailure:q,isProcessing:Re=!1,onLoadStateChange:I,onInitializationStateChange:G,allowAutomaticRetry:Y=!0,onButtonClick:re,runBeforeButtonClick:ve,session:Le,existingOrderId:Ce,telemetry:$e,telemetryContext:vt,onInstrument:Ke,debug:Ne=!1}){let Me=Or(),wt=Po(Ke,e),fe=oa(()=>{if(Me)return null;let x=Fa({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:cd,enabled:$e!==!1});return x.setCheckoutContext(vt??{}),x.beginCheckout(vt??{}),x},[n,Me,$e,vt?.checkoutMode,vt?.layout]),ut=oa(()=>mn(Me),[Me]);Ot(()=>()=>{fe&&fe.flush().catch(()=>{}).finally(()=>fe.destroy())},[fe]);let O=oa(()=>({error:x=>{ut?ut.error(x):fe?.error(x),wt({class:"technical_error",errorCode:x.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":x.errorCode,requestCategory:x.requestCategory,provider:x.provider})},log:x=>{ut?ut.log(x):fe?.log(x),wt({class:"lifecycle",name:x.name,provider:x.provider})},performance:x=>{ut?ut.performance(x):fe?.performance(x)},terminal:x=>{ut?ut.terminal(x):fe?.terminal(x)},startTiming:()=>ut?.now()??fe?.now()??0,elapsed:x=>ut?.elapsed(x)??Math.max(0,(fe?.now()??x)-x)}),[wt,ut,fe]),Ae=ot(null),yt=ot(0),Be=ot(null),it=ot(null),N=ot(null),ue=ud(ea),ge=ot(null);ge.current||(ge.current=Ba());let K=ue??ge.current,Ge=ot(null),Ve=ot(!1),[L,st]=Lr(!1),[Ye,He]=Lr(!1),[Ee,le]=Lr(0),mt=ot(0),[Q,oe]=Lr(!1),Fe=ot(!1),Je=ot(!1),[lt,z]=Lr(!1),[pt,Xe]=Lr(!1),{request:_,collect:ct,finish:Jt}=ho(),xe=ot({sessionId:e,required:!ra(r?.trim()||Le?.customer?.email?.trim())});xe.current.sessionId!==e&&(xe.current={sessionId:e,required:!ra(r?.trim()||Le?.customer?.email?.trim())});let un=xe.current.required,c=oa(()=>n.replace(/\/+$/,""),[n]),ne=Le?.gateways?.paypal?.providerObjectType??b,k=ne??(f?"subscription":"order"),[$]=Lr(Qo),ft=Le?.gateways?.paypal?.approvalPresentation??g,ze=xa($,ft==="app_switch"?"app_switch":void 0,k),Ue=ne==="order"||ne==="setup_token",xt=oa(()=>JSON.stringify([c,s,y,l??"",k,Ue,ze,e,Ce??""]),[c,s,y,l,Ce,k,Ue,ze,e]),ee=ot(xt),pn=ee.current!==xt,We=ot(Ne),Dt=ot(null),[Rn,Kt]=Lr([]),Te=kr(x=>{We.current&&Kt(qe=>[...qe,`${new Date().toISOString().slice(11,23)} ${x}`])},[]);Ot(()=>{We.current=Ne,Ne&&Te("debug:enabled"),Dt.current?.setEnabled(Ne)},[Te,Ne]);let Ut=ot(M),gn=ot(R),hn=ot(C),kn=ot(v),Nn=ot(q),vn=ot(re),Vt=ot(I),De=ot(G),we=ot(i),Ln=ot(ve),St=ot(Le),bn=ot(r),En=ot(o),Hn=ot(t),Ht=ot(null),Xt=ot(new Map),ln=ot(new Map),kt=ot(!1);Ot(()=>(kt.current=!0,()=>{kt.current=!1}),[]),Ot(()=>{Ut.current=M},[M]),Ot(()=>{we.current=i},[i]),Ot(()=>{gn.current=R},[R]),Ot(()=>{hn.current=C},[C]),Ot(()=>{kn.current=v},[v]),Ot(()=>{Nn.current=q},[q]),Ot(()=>{vn.current=re},[re]),Ot(()=>{Vt.current=I},[I]),Ot(()=>{De.current=G},[G]),Ot(()=>{Ln.current=ve},[ve]),Ot(()=>{St.current=Le},[Le]),Ot(()=>{bn.current=r},[r]),Ot(()=>{En.current=o},[o]),Ot(()=>{Hn.current=t},[t]),Ot(()=>{mt.current=Ee},[Ee]),Ot(()=>{Q&&Ge.current?.focus()},[Q,Ee]);let Mt=kr(()=>{window.setTimeout(()=>{Ge.current?.focus()},0)},[]),yn=kr(()=>{st(!1),le(x=>x+1)},[]),Zt=kr(()=>{oe(!1),(Ae.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Ae.current)?.focus?.()},[]);Ot(()=>{!L||!Ve.current||(Ve.current=!1,Zt())},[Zt,L,Ee]);let qt=kr((x,qe)=>{let te=qe?.popupBlocked??Dr(x);te&&K.markBlocked();let tn=Ea("PayPal",te,$.inAppBrowser),Pn=Nn.current;if(Pn){let nn=te&&$.inAppBrowser?new Ti(tn,"api_error",{code:qe?.code??"paypal_popup_blocked"}):x;Pn("paypal",nn,qe);return}hn.current?.(tn)},[K,$.inAppBrowser]),Wt=kr(x=>{let qe=Be.current,te=it.current;qe===null||!te||(O.log({...te,popupCapability:K.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:x}),O.performance({...te,popupCapability:K.current(),stage:"overlay_return",durationMs:O.elapsed(qe),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:x}),Be.current=null)},[K,O]),Tt=kr((x,qe,te)=>{let tn=it.current;Wt("overlay_timeout"),tn&&O.error({...tn,popupCapability:K.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),qt(qe,{...te,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ze,terminalReason:"overlay_timeout"}),oe(!0),yn(),Mt()},[Wt,Mt,qt,K,ze,yn,O]),X=kr(()=>{K.markAvailable();let x=it.current;x&&(N.current=x.attempt,O.log({...x,popupCapability:K.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[K,O]),{finishAttempt:Qt,generationRef:en,invalidateAttempt:ir,isAttemptCurrent:mr,isAttemptInvalidated:Wn,startAttempt:Gt}=na(Tt,{onHandoffObserved:X}),sr=kr(()=>(oe(!1),Gt("paypal")),[Gt]),jt=kr(x=>{ir(x?.generation),x?.showRetry&&oe(!0),x?.remount&&yn(),x?.focus!==!1&&Mt()},[Mt,ir,yn]),A=x=>{let qe=Ht.current;return qe&&ln.current.set(x,qe),x};Ot(()=>{ee.current!==xt&&(ee.current=xt,Fe.current=!1,Je.current=!1,st(!1),He(!1),z(!1),De.current?.("loading"))},[xt]),Ot(()=>{Ft(()=>Vt.current?.(L&&!lt))},[L,lt]);let gt=ld(l);Ot(()=>{let x={attempt:en.current+1,inAppBrowser:$.inAppBrowser,appFamily:$.appFamily,popupCapability:K.current(),presentationMode:ze},qe=()=>({...it.current??x,popupCapability:K.current()}),te={error:p=>O.error({...p,...qe()}),log:p=>O.log({...p,...qe()}),performance:p=>O.performance({...p,...qe()}),terminal:p=>O.terminal({...p,...qe()}),startTiming:O.startTiming,elapsed:O.elapsed},tn=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",Pn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Te(`mount clientId=${tn} env=${l??"(unset)"}\u2192${gt??"live"} ccy=${y} sub=${f}`),Te(`ua=${Pn.slice(0,80)}${Pn.length>80?"\u2026":""}`),!s){Te("FAIL: clientId empty \u2014 gateway misconfigured"),z(!0),te.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Ae.current){Te("FAIL: containerRef not attached");return}yt.current=te.startTiming(),te.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let nn=!1,fr=!1,he=()=>nn||fr,zn,Gn=!1,jr=()=>{zn=sd(),zn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Gn=!0},Yn=null,Jn=!1,Yt=null,Er=!1,gr=()=>{!Yt||Er||(Er=!0,Yt.close().catch(()=>{}))},Tn=!1,hr=!1,Xn=Ae.current,Zn=null,vr=null,Qn=[],It=null,Un=!1,lr=!1,qn=null,Cn=p=>{if(!p||typeof p.getBoundingClientRect!="function")return"(no rect)";let u=p.getBoundingClientRect();return`${Math.round(u.width)}\xD7${Math.round(u.height)}`},nt=p=>{if(!p)return"(empty)";try{let u=new URL(p,typeof window>"u"?"https://localhost":window.location.href),P=u.pathname.toLowerCase();return P.includes("checkcaptcha")||P.includes("captcha")?`CAPTCHA(${u.host}${P})`:P.includes("risk")||P.includes("challenge")?`RISK(${u.host}${P})`:P.includes("smart/buttons")?`smart-buttons(${u.host})`:`${u.host}${P}`.slice(0,100)}catch{return p.slice(0,80)}},In=p=>{let u=p.getAttribute("src"),P=p.getAttribute("srcdoc"),B=p.getAttribute("name"),ie=p.getAttribute("sandbox"),Z=[];return u&&Z.push(`src=${nt(u)}`),P&&Z.push(`srcdoc[${P.length}ch]`),!u&&!P&&Z.push("src=(empty) srcdoc=(empty)"),B&&Z.push(`name=${B.slice(0,40)}`),ie!==null&&Z.push(`sandbox="${ie.slice(0,40)}"`),Z.join(" ")},cn=p=>{if(!(p instanceof HTMLIFrameElement))return"";try{let u=p.contentDocument;if(!u)return"cd=null";let P=u.body?.children.length??0,B=u.body?.innerHTML.length??0,ie=u.head?.innerHTML.length??0;return`cd=same-origin readyState=${u.readyState} body[${P}children,${B}ch] head[${ie}ch]`}catch(u){return`cd=cross-origin(${u.message.slice(0,30)})`}},jn=[],$r=p=>{if(he())return;let u=p.message??String(p.error??"(no message)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&(Te(`window:error ${u.slice(0,140)}`),jn.push(u))},$n=p=>{if(he())return;let u=p.reason instanceof Error?p.reason.message:String(p.reason??"(no reason)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&(Te(`window:rejection ${u.slice(0,140)}`),jn.push(u))},br={value:0},An=()=>{Zn?.disconnect(),Zn=null,vr?.disconnect(),vr=null;for(let p of Qn.splice(0))clearTimeout(p);lr=!1,Un&&typeof window<"u"&&(window.removeEventListener("error",$r),window.removeEventListener("unhandledrejection",$n)),Un=!1},xn=()=>{if(!(Un||he()||Tn)){if(Un=!0,jn.length=0,br.value=0,typeof window<"u"&&(window.addEventListener("error",$r),window.addEventListener("unhandledrejection",$n)),typeof PerformanceObserver<"u")try{vr=new PerformanceObserver(p=>{if(!he())for(let u of p.getEntries()){if(!u.name.toLowerCase().includes("paypal"))continue;br.value+=1;let P=Math.round(u.duration);Te(`net ${P}ms ${u.name.slice(0,90)}`)}}),vr.observe({type:"resource",buffered:!0})}catch{}qn?.()}},Kr=()=>{It&&(clearTimeout(It),It=null)},Kn=()=>{An(),Kr()},Vr={setEnabled:p=>{p?xn():An()}};Dt.current=Vr,We.current&&xn();let rn=p=>{if(!p)return!1;let u=p.toLowerCase();return u.includes("zoid destroyed")||u.includes("destroyed all components")||u.includes("window closed")||u.includes("detected container element removed")},S=p=>{if(he()||rn(p))return;let u=Br(p)??p;Ft(()=>hn.current?.(u))},m=(p,u)=>{if(nn||Jn)return;Jn=!0,fr=!0,Kn(),gr();let P=gd({kind:p,generationActive:!0,automaticRetryAllowed:Y,automaticRetryUsed:Fe.current});if(P.action==="retry"){Fe.current=!0,st(!1),Xe(!1),He(!0),De.current?.("retrying"),Yn=setTimeout(()=>{nn||le(B=>B+1)},pd);return}if(st(!1),Xe(!1),He(!1),z(!0),P.action!=="ignore"){if(De.current?.("exhausted"),P.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",u);return}if(P.report){let B=Ta({code:hl(p,u),message:u},{inAppBrowser:$.inAppBrowser,handoffObserved:!1});B.popupBlocked&&K.markBlocked(),te.error({errorCode:B.popupBlocked?B.errorCode:P.report.errorCode,stage:P.report.stage,operationOutcome:P.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:B.terminalReason})}Je.current||(Je.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",hl(p,u)))}};z(!1);let W=async(p,u=Ht.current)=>{if(he())return;let P=u?.sessionId??e;if(Ut.current){await Ut.current(p,{sessionId:P,accountPatch:u?.accountPatch,nonce:u?.nonce});return}let B=te.startTiming();te.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ie=()=>{te.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"processing",durationMs:te.elapsed(B),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Z=St.current,j=u?.accountPatch?.email??bn.current,ae=u?.accountPatch?.userId??Z?.customer?.id??Z?.accountData?.userId??"",Se=u?.accountPatch?.firstName??Z?.customer?.firstName??Z?.accountData?.firstName,bt=u?.accountPatch?.lastName??Z?.customer?.lastName??Z?.accountData?.lastName,H=await new Ei(c,{telemetry:!1}).processPayment(ae,{sessionId:P,nonce:u?.nonce??Hn.current,paymentMethodCategory:"paypal",tokenizedData:p,accountData:{userId:ae,email:j??Z?.customer?.email??"",...Se?{firstName:Se}:{},...bt?{lastName:bt}:{},country:u?.accountPatch?.country??Z?.customer?.country??Z?.accountData?.country??void 0,zip:u?.accountPatch?.zip??Z?.customer?.zip??Z?.accountData?.zip??void 0}});if(H.ok){if(fr||nn&&kt.current)return;ie(),te.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Ft(()=>gn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(he())return;let T=await H.json().catch(()=>null),U=T?.message??"PayPal payment failed.",ke=Br(U)??U;ie(),H.status===400&&(typeof T?.declineCode=="string"||!Array.isArray(T?.fields))?te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):H.status===400||H.status===422?te.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):te.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:vd(H.status),failureCategory:H.status>=500?"server_error":void 0}),S(ke),Ft(()=>kn.current?.(dn("paypal",ke,{code:T?.code,declineCode:T?.declineCode})));return}catch(Z){if(he())return;ie(),te.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let j=Z instanceof Error?Z.message:"PayPal payment failed.",ae=Br(j)??j;S(ae),Ft(()=>kn.current?.(dn("paypal",ae)));return}},F=()=>new Ti("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),be=p=>he()?Promise.reject(F()):Promise.resolve(p),Nt=async p=>{if(he())throw F();Gn||jr();let u=Ht.current,P=u?.sessionId??e,B=u?.nonce??Hn.current;te.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ie;try{ie=await new Ei(c,{telemetry:!1}).createSessionIntent(P,B??"",Ue?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Ai,paymentMethodId:null,intentKind:k==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:zn})}catch(Z){throw te.error({...id(Z,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Z}if(he())throw F();if(ie.provider!=="paypal"||ie.providerObjectType!==k)throw new Error(p);return te.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ie.providerObjectId},ye=(p,u)=>{let P=u?.nonce??Hn.current;if(!P)return;let B=u?.sessionId??e,ie=bo(p)??Sr(p)??"provider_declined";new Ei(c,{telemetry:!1}).reportSessionIntentDecline(B,P,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ie}).catch(()=>{})},pe=Ee;Te("loadScript:scheduled (deferred 1 tick)");let E=null,V=setTimeout(()=>{if(nn){Te("loadScript:skipped (cancelled before defer ran)");return}Te("loadScript:start");let p=gt==="live"?"production":gt,u={};k==="subscription"?u={intent:"subscription",vault:!0}:k==="order"&&(u={intent:"capture"}),E=dd({clientId:s,currency:y,...u,...p?{environment:p}:{},...p==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let P=!1;E.then(B=>{if(P=!0,Te(`loadScript:resolved inactive=${he()} ns=${!!B} buttons=${!!B?.Buttons}`),he())return;if(!B?.Buttons){Te("FAIL: namespace missing Buttons factory"),m("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}te.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"provider_ready",durationMs:te.elapsed(yt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),te.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let ie=async(H,T)=>{if(he()||mt.current!==pe)return;let U=H.vaultSetupToken??H.subscriptionID??H.orderID??"",ke=U?ln.current.get(U):Xt.current.get(pe);if(!(!ke||!mr(ke.generation))&&Qt(ke.generation)){ln.current.delete(U),Xt.current.delete(ke.surfaceKey),Wt("approved");try{if(Xe(!0),Ft(()=>hn.current?.(null)),!U)throw new Ti("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ie=St.current,ht=Yr(En.current??[Ie?.customer?.firstName,Ie?.customer?.lastName].filter(Boolean).join(" ")),je=On({email:ke.accountPatch?.email?.trim()||bn.current?.trim()||Ie?.customer?.email?.trim(),firstName:ke.accountPatch?.firstName?.trim()||ht.firstName,lastName:ke.accountPatch?.lastName?.trim()||ht.lastName});if(!ra(je.email)||!(je.firstName||je.lastName))try{let on=hd(await T?.order?.get?.());je=On({email:on.email||je.email,firstName:on.firstName||je.firstName,lastName:on.lastName||je.lastName})}catch{}if((we.current||un)&&!ra(je.email)){let on=await ct("PayPal",je);if(!on)return;je=on}ra(je.email)&&(ke.accountPatch=On({...ke.accountPatch,...je}),await we.current?.(je));let Mn;k==="setup_token"?Mn={id:U,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Ai}:Ue?Mn={id:U,isPaypal:!0,gateway:"paypal",paymentMethodType:Ai}:Mn={id:U,isPaypal:!0},await W(Mn,ke)}catch(Ie){S(Ie instanceof Error?Ie.message:"PayPal capture failed.")}finally{he()||Xe(!1)}}},Z=H=>{let T=Ce?()=>be(Ce):()=>Nt(H);return async()=>A(await T())},j=B.Buttons({style:{layout:"horizontal",height:Da,tagline:!1},...ze==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(H,T)=>{if(he()){await T.reject();return}jr();let U=Ln.current,ke={};if(U)try{let je=await U("paypal");if(he()){await T.reject();return}if(!je.proceed){Ht.current=null,Xt.current.delete(pe),await T.reject();return}ke={sessionId:je.sessionId,accountPatch:je.accountPatch,nonce:je.nonce}}catch(je){Te(`onClick:runBeforeButtonClick rejected msg=${(je instanceof Error?je.message:String(je)).slice(0,120)}`),Ht.current=null,Xt.current.delete(pe),await T.reject();return}Ft(()=>vn.current?.("paypal"));let Ie=sr(),ht={generation:Ie,surfaceKey:pe,...ke};Ht.current=ht,Xt.current.set(pe,ht),it.current={...x,attempt:Ie},await T.resolve(),te.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Be.current=te.startTiming()},createOrder:k==="order"?Z("Failed to create PayPal order."):void 0,createSubscription:k==="subscription"?Z("Failed to create PayPal subscription."):void 0,createVaultSetupToken:k==="setup_token"?async()=>A(await Nt("Failed to create PayPal setup token.")):void 0,onApprove:ie,onCancel:()=>{if(he())return;let H=Xt.current.get(pe)??Ht.current;H&&Xt.current.delete(H.surfaceKey),Ht.current=null,Wt("cancelled"),te.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ve.current=!0,jt({generation:H?.generation,remount:!0,focus:!1})},onError:H=>{if(he()||mt.current!==pe)return;let T=H instanceof Error?H.message:"PayPal failed to render.";if(Te(`onError rendered=${Tn} msg=${T.slice(0,120)}`),Tn){let U=Xt.current.get(pe)??Ht.current;if(U&&!mr(U.generation)||!U&&Wn())return;if(rn(T)){Qt(U?.generation);return}let{errorCode:ke,popupBlocked:Ie,providerDeclined:ht,terminalReason:je}=Ta(H,{inAppBrowser:$.inAppBrowser,handoffObserved:U!=null&&N.current===U.generation});if(Ie&&K.markBlocked(),Wt(je),ht){te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:je}),ye(H,U),Ft(()=>kn.current?.(dn("paypal",T))),U&&Xt.current.delete(U.surfaceKey),Ht.current=null,Qt(U?.generation);return}te.error({errorCode:ke,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:je}),U&&Xt.current.delete(U.surfaceKey),Ht.current=null,jt({generation:U?.generation,remount:!0,showRetry:!0,focus:!0}),qt(H,{code:"paypal_runtime_failed",popupBlocked:Ie,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ze,terminalReason:je});return}m(rn(T)?"teardown":"pre_ready_callback",T)}}),ae=j.isEligible();if(Te(`isEligible=${ae}`),te.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ae){st(!1),m("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}hr=!0,Yt=j,qn=()=>{if(!Un||lr||he()||Tn)return;lr=!0,Te(`container:dims ${Cn(Xn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Zn=new MutationObserver(T=>{if(!he()){for(let U of T)if(U.type==="childList")U.addedNodes.forEach(ke=>{if(!(ke instanceof Element))return;let Ie=ke.tagName.toLowerCase(),ht=(ke.getAttribute("title")??"").slice(0,40),je=Ie==="iframe"?` ${In(ke)}`:"";Te(`child+ ${Ie}${ht?` title="${ht}"`:""}${je} dims=${Cn(ke)}`)});else if(U.type==="attributes"&&U.target instanceof Element){let ke=U.target;if(ke.tagName.toLowerCase()!=="iframe")continue;let Ie=U.attributeName;(Ie==="src"||Ie==="srcdoc")&&Te(`attr~ iframe ${Ie}=${Ie==="srcdoc"?`[${(ke.getAttribute("srcdoc")??"").length}ch]`:nt(ke.getAttribute("src"))} dims=${Cn(ke)}`)}}}),Zn.observe(Xn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let H=T=>{if(he()||Tn)return;let U=Xn.querySelectorAll("iframe"),ke=typeof document<"u"&&"hasStorageAccess"in document;Te(`watchdog:${T} container=${Cn(Xn)} children=${Xn.childElementCount} iframes=${U.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${ke} paypalNetRequests=${br.value}`),U.forEach((Ie,ht)=>{let je=(Ie.getAttribute("title")??"").slice(0,40);Te(` iframe[${ht}] ${Cn(Ie)}${je?` title="${je}"`:""} ${In(Ie)}`);let Mn=cn(Ie);Mn&&Te(` ${Mn}`)}),jn.length===0&&Te(" (no PayPal/zoid window errors captured)")};Qn.push(setTimeout(()=>H("3s"),3e3)),Qn.push(setTimeout(()=>H("8s"),8e3)),Qn.push(setTimeout(()=>H("15s"),15e3))},qn(),Te("render:start");let bt=te.startTiming();It=setTimeout(()=>{he()||Tn||(Te("watchdog:11s retryable render timeout"),m("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},yd);let _e=j.render(Xn);(async()=>{try{if(await _e,Te(`render:resolved inactive=${he()}`),Kn(),he()){gr();return}Tn=!0,st(!0),He(!1),De.current?.("ready"),te.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"checkout_render",durationMs:te.elapsed(bt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(H){let T=H instanceof Error?H.message:"PayPal failed to render.";Te(`render:rejected msg=${T.slice(0,120)}`),Kn(),m(rn(T)?"teardown":"render_rejected",T)}})()}).catch(B=>{let ie=B instanceof Error?B.message:"PayPal operation failed.";Te(`provider:failed msg=${ie.slice(0,120)}`);let Z="script_rejected";P&&rn(ie)?Z="teardown":P&&hr&&(Z="render_rejected"),m(Z,ie)})},0);return()=>{nn=!0,clearTimeout(V),Yn&&clearTimeout(Yn),Kn(),Dt.current===Vr&&(Dt.current=null),gr(),Be.current=null,it.current=null}},[Y,c,s,y,l,k,ze,Ue,e,Ce,Ee,O,ct,un,Te,Wt]);let Ze=Ne?xi("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=${L} failed=${lt})`,Rn.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return ot&&!K?je?Kr("div",{children:Pe}):null:hi("div",{children:[Pe,le&&Kr(po,{identity:le.identity,methodLabel:le.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Vt,onCancel:()=>Vt(null)}),hi("div",{"aria-hidden":rt||le?!0:void 0,style:rt||le?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Sa},children:[!Ee&&!rt&&Kr("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"}}),Kr("div",{ref:Ie,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Sa,display:"flex",opacity:Ee?1:0},"aria-busy":Ke||ge},Te)]},Te),se&&Kr("button",{ref:T,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:an,style:Gc,children:"Try PayPal again"})]})}function wa(e){return Kr(el,{...e})}function tl(e){return Kr(el,{...e})}import{jsx as nl,jsxs as rd}from"react/jsx-runtime";function fo({children:e,margin:t,icon:n=!0,styleOverride:r}){return rd("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&&nl("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:nl("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 ad}from"@flopay/shared";function go(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Pi=":idempotency-key";function bi(e,t){if(!go())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 Ci(e,t){if(!go())return null;try{let n=window.sessionStorage.getItem(e+Pi);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function Ia(e,t){if(go())try{bi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ka(e,t){if(Ia(e,t),!!go())try{Ci(e,t)&&window.sessionStorage.removeItem(e+Pi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function _a(e,t,n,r){if(go())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 Ra(e,t,n){if(go())try{window.sessionStorage.setItem(e+Pi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function vi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function id(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 ho(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=>vi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>vi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>vi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:id(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function rl(e,t=!1){let n=ho(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 ol(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=ad(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(v=>({type:v.type,code:v.code??v.providerItemId??v.providerPlanId??"",quantity:v.quantity??1,totalAmount:v.totalAmount,overrideAmount:v.overrideAmount??null,currency:(v.currency??o).toUpperCase()})).sort((v,g)=>`${v.code}:${v.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),s=e.products.map(v=>({type:v.type,code:v.code??"",quantity:v.quantity??1,totalAmount:v.totalAmount,overrideAmount:v.overrideAmount??null,currency:(v.currency??e.currency).toUpperCase()})).sort((v,g)=>`${v.code}:${v.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(i.length!==s.length)return!1;for(let[v,g]of i.entries()){let h=s[v];if(h===void 0||g.code!==h.code||g.type!==void 0&&g.type!==h.type||g.quantity!==h.quantity||g.totalAmount!==h.totalAmount||g.overrideAmount!==h.overrideAmount||g.currency!==h.currency)return!1}let l=[...t.couponCodes??[]].sort(),p=[...e.coupons??[]].sort();return l.length===p.length&&l.every((v,g)=>v===p[g])}import{resolveBillingApiUrl as sd}from"@flopay/shared";import{useEffect as Er,useMemo as ld,useRef as al,useState as il}from"react";import{jsx as cd}from"react/jsx-runtime";function Ea({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,s]=il(e instanceof Promise?null:e),[l,p]=il(t instanceof Promise||!t?null:t),v=al(null),g=al(null),h=yo(r);Er(()=>{h({class:"lifecycle",name:"checkout.mount"})},[h]),Er(()=>{i&&h({class:"lifecycle",name:"sdk.initialize.ready"})},[h,i]),Er(()=>{if(i)return Qt(i)?.subscribe?.(h)},[h,i]),Er(()=>{if(!(!l||l===i))return Qt(l)?.subscribe?.(h)},[h,i,l]),Er(()=>{if(!i)return;let M=Qt(i);return v.current=M?.beginCheckout()??M?.now()??0,M?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{M?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Er(()=>{let M=!1;return e instanceof Promise?e.then(U=>{M||s(U)},()=>{M||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{M=!0}},[h,e]),Er(()=>{let M=!1;if(!t){p(null);return}return t instanceof Promise?t.then(U=>{M||p(U)},()=>{M||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{M=!0}},[h,t]),Er(()=>{if(!i||g.current===i)return;g.current=i;let M=Qt(i);M?.log({name:"checkout.rendered",stage:"checkout_render"}),h({class:"lifecycle",name:"checkout.rendered"}),M?.performance({stage:"checkout_render",durationMs:M.elapsed(v.current??0),durationMode:"machine"})},[h,i]);let y=sd(n?.billingApiUrl),_=ld(()=>({flopay:i,paypalFlopay:l,billingApiUrl:y,emitInstrument:h}),[i,l,y,h]);return cd(Gn.Provider,{value:_,children:o})}var Ta="flopay_recent_completion_";function vo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Ta+e,JSON.stringify(t))}catch{}}function Si(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Ta+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Ta+e),!1):!0}catch{return!1}}import{loadFloPay as sl,PaymentAPI as dl}from"@flopay/js";import{classifyPaymentRejection as dd,FloPayError as bt,isAuthorizationOnlySession as ud,isSetupIntentClientSecret as pd,normalizeCheckoutFailureOutcome as ll}from"@flopay/shared";var Yo="card";async function md(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 yd(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 Ii(e,t){return Object.assign(e,{checkoutMethod:t})}function Sr(e,t){let n=e instanceof bt?e:new bt(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Go(e,t){try{return await e()}catch(n){throw Sr(n,t)}}function ul(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 fd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function pl(e){if(typeof document>"u"||typeof window>"u")throw new bt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new bt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let g=new AbortController,h=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",h);let y=window.setTimeout(()=>g.abort(),r);try{let _=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!_.ok)return{status:"unknown"};let M=await _.json().catch(()=>null);return gd(M)}catch{return{status:"unknown"}}finally{window.clearTimeout(y),e.signal?.removeEventListener("abort",h)}},s=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let p=document.createElement("iframe");p.setAttribute("title","Card authentication"),p.setAttribute("allow","payment"),p.tabIndex=0,p.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(";"),p.src=e.nextActionRedirectUrl,l.appendChild(p),document.body.appendChild(l),p.focus();let v=null;try{v=new URL(e.billingApiUrl,window.location.href).origin}catch{v=null}try{let g=await new Promise((h,y)=>{let _=!1,M=0,U=0,qe=0,ge=!1,S=()=>{window.clearTimeout(M),window.clearInterval(U),window.clearTimeout(qe),window.removeEventListener("message",Le),p.removeEventListener("load",Y),e.signal?.removeEventListener("abort",de)},W=async()=>{if(!(_||ge)){ge=!0;try{let Se=await i();if(_||!fd(Se))return;_=!0,S(),h(Se)}finally{ge=!1}}},Y=()=>{window.clearTimeout(qe),qe=window.setTimeout(()=>{W()},250)},de=()=>{_||(_=!0,S(),y(new bt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Le=Se=>{if(Se.source!==p.contentWindow||v&&Se.origin!==v)return;let Re=Se.data;!Re||typeof Re!="object"||Re.source!=="flopay-vault-3ds-return"||_||(_=!0,S(),h(null))};M=window.setTimeout(()=>{_||(_=!0,S(),y(new bt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),U=window.setInterval(()=>{W()},n),p.addEventListener("load",Y),window.addEventListener("message",Le),e.signal?.addEventListener("abort",de),e.signal?.aborted&&de()});return g||await i()}finally{l.parentNode?.removeChild(l),s?.isConnected&&s.focus()}}function gd(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 Tr(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=Ir(o)??o;return Ii(new bt(i,"api_error",{code:ll(e?.outcome)??ll(e?.type)??e?.gatewayErrorCode}),r)}function wi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Aa(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ml(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Aa(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||Aa(l)))return l;let s=o.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let p=l,v=[p.stripeClientSecret,p.clientSecret];for(let g of v)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||Aa(g)))return g}}}}async function hd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ml(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 dl(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Aa(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Po({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),p=t??n.id,v=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",h=n.customer?.email??n.accountData?.email??"",y=n.customer?.firstName??n.accountData?.firstName??"",_=n.customer?.lastName??n.accountData?.lastName??"",M=n.customer?.country??n.accountData?.country??void 0,U=n.customer?.zip??n.accountData?.zip??void 0,ge=await new dl(l,s===!1?{telemetry:!1}:void 0).processPayment(g,{sessionId:p,nonce:v,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:g,email:h,firstName:y,lastName:_,country:M,zip:U},returnUrl:i??wi(n)});if(ge.ok){let Y=typeof ge.json=="function"?await ge.json().catch(()=>null):null;return ud(n)||Y?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof Y?.paymentId=="string"?Y.paymentId:n.paymentId,sessionId:typeof Y?.sessionId=="string"?Y.sessionId:p,authorizationExpiresAt:typeof Y?.authorizationExpiresAt=="string"?Y.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:jo(o),checkoutMethod:cl(o)}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:jo(o),checkoutMethod:cl(o)}}}let S;try{S=await ge.json()}catch(Y){throw new bt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:ge.status,cause:Y})}if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let Y=ml(S);if(!Y)throw new bt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:ge.status});return{type:S.type,threeDSecureToken:Y,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let Y=await hd({billingApiUrl:l,sessionId:p,nonce:v,responseJson:S});if(Y)return Y;throw Ii(new bt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let W=new bt(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:ge.status});throw Object.assign(W,{telemetryOutcome:dd(ge.status,S)})}async function Ma(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:p}){let v=t?.getRawProvider();if(!v)throw Sr(new bt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Ii(new bt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=pd(e.threeDSecureToken),h=null,y=e.paymentMethodId,_=await Go(()=>md(v,e.threeDSecureToken,g),"card");if(_){if(_.error)throw Sr(new bt(_.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let U=_.intent;!y&&U?.payment_method&&(typeof U.payment_method=="string"?y=U.payment_method:"id"in U.payment_method&&(y=U.payment_method.id??void 0))}let M=y?await Go(()=>yd(v,e.threeDSecureToken,{payment_method:y,return_url:l??wi(s)??window.location.href},g),"card"):null;if(M){if(M.error)throw Sr(new bt(M.error.message??"3DS authentication failed.","api_error",{code:M.error.code}),"card");h=M.intent}else{let U=await Go(()=>v.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(U.error)throw Sr(new bt(U.error.message??"3DS authentication failed.","api_error",{code:U.error.code}),"card");h=(g?U.setupIntent:U.paymentIntent)??null}if(h&&(h.status==="requires_capture"||h.status==="succeeded"||h.status==="processing")){let U=await Po({billingApiUrl:o,sessionId:i,session:s,telemetry:p,tokenizedData:{id:h.id,type:"card",threeDSecureActionResultTokenId:h.id},returnUrl:l});return U.type==="success"?{...U.result,paymentIntentId:U.result.paymentIntentId??h.id,paymentMethodId:U.result.paymentMethodId??y}:Ma(U,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:p})}throw Sr(new bt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw Sr(new bt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:y}=await Go(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(y)throw Sr(new bt(y.message??"PayPal authorization failed.","api_error",{code:y.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:h}=await Go(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??wi(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(h)throw Sr(new bt(h.message??"PayPal authorization failed.","api_error",{code:h.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new bt("Unsupported payment redirect state.","api_error")}function Jo(e){if(e instanceof bt){let r=Ir(e.message);return r&&r!==e.message?Object.assign(new bt(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Ir(t)??t;return new bt(n,"api_error")}function ki(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 bt("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function cl(e){if(e)return e.isPaypal?"paypal":"card"}async function _i({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([sl(e,{billingApiUrl:n,locale:r,telemetry:o}),i?sl(i,{billingApiUrl:n,locale:r,telemetry:o}).catch(v=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",v),null)):Promise.resolve(null)]);if(!s)throw new bt("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 bo,PciVaultCardCapture as vd,toStripeAppearance as Pd}from"@flopay/js";import{COUNTRY_OPTIONS as bd,classifyPaymentRejection as Cd,FloPayError as ir,filterStripeMethodsByCountry as Sd,getPostalCodeExample as wd,getPostalCodeLabel as Ni,getStateFromPostalCode as fl,getStateLabel as Ri,getStateOptions as Id,getStripeMethodDisplayName as Hr,hasVendoredStripeMethodLogo as kd,isAuthorizationOnlySession as Ei,isAVSFieldVisible as et,isPostalCodeSupported as _d,isSetupIntentClientSecret as Ti,isValidEmail as ln,isValidPostalCode as Rd,needsStripeMethodExplicitConfirm as gl,normalizeCheckoutFailureOutcome as Ed,partitionStripeMethods as Td,randomUuidV4 as Ad,resolveAVSConfig as Md,resolveButtonsLayoutTheme as xd,resolveStripeMethodBrandVariant as Bd,resolveTheme as Fd,stripeExpressMethodToOptionKey as hl}from"@flopay/shared";import{ExpressCheckoutElement as Al,PaymentElement as Dd,Elements as Vr,useElements as Ui,useStripe as qi}from"@stripe/react-stripe-js";import Nd,{useCallback as Je,useContext as Co,useEffect as ft,useMemo as Et,useRef as ce,useState as oe}from"react";var yl={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 Wr,jsx as c,jsxs as Ue}from"react/jsx-runtime";var fr="flopay_stripe_resume",vl="flopay_wallet_resume",Ml="fw1",Ld="fw2",xl=300*1e3,Od=900,zd=25e3,Ud=25e3,qd=1e4,Ai={},Mi={};function ji(e){return`${Ld}:${e}`}function xa(e){if(typeof window>"u")return!1;try{return localStorage.removeItem(ji(e)),!0}catch{return!1}}function Ba(e,t){if(typeof window>"u")return null;let n=ji(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>xl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(xa(e),null):o}catch{return xa(e),null}}function jd(e){if(typeof window>"u")return!1;try{return localStorage.setItem(ji(e.sessionId),JSON.stringify(e)),!0}catch{return!1}}function Pl(e,t,n){let r=Ba(e,t);return!r||r.clientSecret!==n?!1:xa(e)}function xi(e,t,n){if(typeof window>"u")return;Ba(e,t)?.clientSecret===n&&xa(e)}function $d(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Bi(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":qo(e.status),o=$d(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function bl(e,t,n){let r=null;try{return await Promise.race([Ws(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},qd),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Kd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Bl(e){return e instanceof ir&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Da(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 Bl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Xo="flopay_paypal_resume",Vd=250,Cl="Just a moment \u2014 we are finalizing your order. Please press pay again.",Wd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function $i(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Na({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new bo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Hd(e){return e instanceof ir&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Fi(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Fl({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=qr(n),s=i.firstName?i:qr(r?.name);return Dn({email:ln(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Gd({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let s=Fl({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return ln(s.email)?s:i(o,s)}var Yd=`
|
|
3
|
+
${Rn.join(`
|
|
4
|
+
`)}`]}):null;return lt&&!pn?Ne?Xr("div",{children:Ze}):null:xi("div",{children:[Ze,_&&Xr(vo,{identity:_.identity,methodLabel:_.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Jt,onCancel:()=>Jt(null)}),xi("div",{"aria-hidden":Ye||_?!0:void 0,style:Ye||_?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Da},children:[!L&&!Ye&&Xr("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"}}),Xr("div",{ref:Ae,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Da,display:"flex",opacity:L?1:0},"aria-busy":pt||Re},Ee)]},Ee),Q&&Xr("button",{ref:Ge,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Zt,style:md,children:"Try PayPal again"})]})}function Oa(e){return Xr(vl,{...e})}function bl(e){return Xr(vl,{...e})}import{jsx as Pl,jsxs as bd}from"react/jsx-runtime";function Co({children:e,margin:t,icon:n=!0,styleOverride:r}){return bd("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&&Pl("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Pl("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 Pd,resolveSessionCurrency as Cd}from"@flopay/shared";function wo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Bi=":idempotency-key";function Fi(e,t){if(!wo())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 Di(e,t){if(!wo())return null;try{let n=window.sessionStorage.getItem(e+Bi);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 Na(e,t){if(wo())try{Fi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function La(e,t){if(Na(e,t),!!wo())try{Di(e,t)&&window.sessionStorage.removeItem(e+Bi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function za(e,t,n,r){if(wo())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 Ua(e,t,n){if(wo())try{window.sessionStorage.setItem(e+Bi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Mi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function wd(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 So(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=>Mi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Mi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Mi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:wd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Cl(e,t=!1){let n=So(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 wl(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??Pd(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,b)=>`${f.code}:${f.type??""}`.localeCompare(`${b.code}:${b.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,b)=>`${f.code}:${f.type??""}`.localeCompare(`${b.code}:${b.type??""}`));if(i.length!==s.length)return!1;for(let[f,b]of i.entries()){let g=s[f];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(),y=[...e.coupons??[]].sort();return l.length===y.length&&l.every((f,b)=>f===y[b])}import{resolveBillingApiUrl as Sd}from"@flopay/shared";import{useEffect as zr,useMemo as kd,useRef as Sl,useState as kl}from"react";import{jsx as Id}from"react/jsx-runtime";function qa({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,s]=kl(e instanceof Promise?null:e),[l,y]=kl(t instanceof Promise||!t?null:t),f=Sl(null),b=Sl(null),g=Po(r);zr(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),zr(()=>{i&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,i]),zr(()=>{if(i)return mn(i)?.subscribe?.(g)},[g,i]),zr(()=>{if(!(!l||l===i))return mn(l)?.subscribe?.(g)},[g,i,l]),zr(()=>{if(!i)return;let C=mn(i);return f.current=C?.beginCheckout()??C?.now()??0,C?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{C?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),zr(()=>{let C=!1;return e instanceof Promise?e.then(v=>{C||s(v)},()=>{C||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{C=!0}},[g,e]),zr(()=>{let C=!1;if(!t){y(null);return}return t instanceof Promise?t.then(v=>{C||y(v)},()=>{C||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{C=!0}},[g,t]),zr(()=>{if(!i||b.current===i)return;b.current=i;let C=mn(i);C?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),C?.performance({stage:"checkout_render",durationMs:C.elapsed(f.current??0),durationMode:"machine"})},[g,i]);let M=Sd(n?.billingApiUrl),R=kd(()=>({flopay:i,paypalFlopay:l,billingApiUrl:M,emitInstrument:g}),[i,l,M,g]);return Id(or.Provider,{value:R,children:o})}var ja="flopay_recent_completion_";function ko(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ja+e,JSON.stringify(t))}catch{}}function Oi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ja+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ja+e),!1):!0}catch{return!1}}async function $a(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 Il,PaymentAPI as Li}from"@flopay/js";import{classifyPaymentRejection as _d,FloPayError as Rt,isAuthorizationOnlySession as Rd,isSetupIntentClientSecret as Ed,normalizeCheckoutFailureOutcome as _l}from"@flopay/shared";var ia="card",Td=1e3,El=3e5;async function Ad(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 xd(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 sa(e){return new Rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function zi(e,t){return Object.assign(e,{checkoutMethod:t})}function Ar(e,t){let n=e instanceof Rt?e:new Rt(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function aa(e,t){try{return await e()}catch(n){throw Ar(n,t)}}function Tl(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 Md(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function Ui(e){if(typeof document>"u"||typeof window>"u")throw new Rt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let g=new AbortController,M=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",M);let R=window.setTimeout(()=>g.abort(),n);try{let C=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!C.ok)return{status:"unknown"};let v=await C.json().catch(()=>null);return Bd(v)}catch{return{status:"unknown"}}finally{window.clearTimeout(R),e.signal?.removeEventListener("abort",M)}},i,s=()=>e.pollCompletionEndpoint!==!1?o():(i??(i=o()),i),l=document.activeElement instanceof HTMLElement?document.activeElement:null,y=document.createElement("div");y.setAttribute("data-flopay-auto-3ds-overlay","1"),y.setAttribute("role","dialog"),y.setAttribute("aria-modal","true"),y.setAttribute("aria-label","Card authentication"),y.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 b=null;try{b=new URL(e.billingApiUrl,window.location.href).origin}catch{b=null}try{let g=await new Promise((M,R)=>{let C=!1,v=0,q=0,Re=0,I=!1,G=()=>{window.clearTimeout(v),window.clearInterval(q),window.clearTimeout(Re),window.removeEventListener("message",Le),f.removeEventListener("load",re),e.signal?.removeEventListener("abort",ve)},Y=async()=>{if(!(C||I)){I=!0;try{let Ce=await s();if(C||!Md(Ce))return;C=!0,G(),M(Ce)}finally{I=!1}}},re=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(Re),Re=window.setTimeout(()=>{Y()},250))},ve=()=>{C||(C=!0,G(),R(new Rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Le=Ce=>{if(Ce.source!==f.contentWindow||b&&Ce.origin!==b)return;let $e=Ce.data;!$e||typeof $e!="object"||$e.source!=="flopay-vault-3ds-return"||C||(C=!0,G(),M(null))};v=window.setTimeout(()=>{C||(C=!0,G(),R(new Rt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},El),e.pollCompletionEndpoint!==!1&&(q=window.setInterval(()=>{Y()},t)),f.addEventListener("load",re),window.addEventListener("message",Le),e.signal?.addEventListener("abort",ve),f.src=e.nextActionRedirectUrl,y.appendChild(f),document.body.appendChild(y),f.focus(),e.signal?.aborted&&ve()});return g||await s()}finally{y.parentNode?.removeChild(y),l?.isConnected&&l.focus()}}async function Io(e,t){let n=t.nonce??t.session.clientSecret,r=new Li(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=Ui({billingApiUrl:t.billingApiUrl,sessionId:t.sessionId,nonce:n,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1}),y=null,f=()=>(y??(y=r.waitForCheckoutSessionCompletion(t.sessionId,{initialDelayMs:Td,nonce:n,statusUrl:`${t.billingApiUrl.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/status`,continueAfterActionRequired:!0,timeoutMs:El,signal:i.signal})),y),b=f(),g;try{let R=await Promise.race([l.then(C=>({kind:"challenge",outcome:C})),b.then(C=>({kind:"status",session:C}))]);if(R.kind==="status")o.abort(),g=R.session;else{if(R.outcome.status==="declined")throw Ir({type:R.outcome.declineReason??"authorization_declined",message:"Card was declined.",gatewayErrorCode:R.outcome.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});g=await f()}}catch(R){throw t.signal.aborted||R instanceof Error&&R.name==="AbortError"?sa(R):R}finally{t.signal.removeEventListener("abort",s),o.abort(),i.abort()}let M=g.data.session;if(!Fr(M))throw go(M);return{...Tr(M,t.sessionId),checkoutMethod:"card"}}function Bd(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 Ir(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=Br(o)??o,s=zi(new Rt(i,"api_error",{code:e?.code??_l(e?.outcome)??_l(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(s.orderId=e.orderId),s}function Ni(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ka(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Al(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Ka(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,i=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||Ka(l)))return l;let s=o.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let y=l,f=[y.stripeClientSecret,y.clientSecret];for(let b of f)if(typeof b=="string"&&b.length>0&&(!t?.requirePaymentIntentClientSecret||Ka(b)))return b}}}}async function Fd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Al(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 Li(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ka(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function _o({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),y=t??n.id,f=r??n.clientSecret,b=n.customer?.id??n.accountData?.userId??"",g=n.customer?.email??n.accountData?.email??"",M=n.customer?.firstName??n.accountData?.firstName??"",R=n.customer?.lastName??n.accountData?.lastName??"",C=n.customer?.country??n.accountData?.country??void 0,v=n.customer?.zip??n.accountData?.zip??void 0,Re=await new Li(l,s===!1?{telemetry:!1}:void 0).processPayment(b,{sessionId:y,nonce:f,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:b,email:g,firstName:M,lastName:R,country:C,zip:v},returnUrl:i??Ni(n)});if(Re.ok){let Y=typeof Re.json=="function"?await Re.json().catch(()=>null):null;if(Rd(n)||Y?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof Y?.paymentId=="string"?Y.paymentId:n.paymentId,sessionId:typeof Y?.sessionId=="string"?Y.sessionId:y,authorizationExpiresAt:typeof Y?.authorizationExpiresAt=="string"?Y.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Jo(o),checkoutMethod:Rl(o,n)}};let re=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...re?{paymentIntentId:re}:{},paymentMethodId:Jo(o),checkoutMethod:Rl(o,n)}}}let I;try{I=await Re.json()}catch(Y){throw new Rt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:Re.status,cause:Y})}if(I?.type==="3ds_required"&&typeof I.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:I.nextActionRedirectUrl};if(I?.type==="paypal_redirect_required"||I?.type==="3ds_required"){let Y=Al(I);if(!Y)throw new Rt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:Re.status});return{type:I.type,threeDSecureToken:Y,paymentMethodId:I.paymentMethodId}}if(I?.gatewayErrorCode==="authentication_required"){let Y=await Fd({billingApiUrl:l,sessionId:y,nonce:f,responseJson:I});if(Y)return Y;throw zi(new Rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let G=new Rt(I?.message??"Payment failed. Please try again.","api_error",{code:I?.code??I?.gatewayErrorCode,declineCode:I?.declineCode??I?.gatewayDeclineReason,statusCode:Re.status});throw Object.assign(G,{telemetryOutcome:_d(Re.status,I)})}async function Va(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:y,signal:f}){let b=t?.getRawProvider();if(!b)throw Ar(new Rt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw zi(new Rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Ed(e.threeDSecureToken),M=null,R=e.paymentMethodId,C=await aa(()=>Ad(b,e.threeDSecureToken,g),"card");if(C){if(C.error)throw Ar(new Rt(C.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:C.error.code}),"card");let q=C.intent;!R&&q?.payment_method&&(typeof q.payment_method=="string"?R=q.payment_method:"id"in q.payment_method&&(R=q.payment_method.id??void 0))}let v=R?await aa(()=>xd(b,e.threeDSecureToken,{payment_method:R,return_url:l??Ni(s)??window.location.href},g),"card"):null;if(v){if(v.error)throw Ar(new Rt(v.error.message??"3DS authentication failed.","api_error",{code:v.error.code}),"card");M=v.intent}else{let q=await aa(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(q.error)throw Ar(new Rt(q.error.message??"3DS authentication failed.","api_error",{code:q.error.code}),"card");M=(g?q.setupIntent:q.paymentIntent)??null}if(M&&(M.status==="requires_capture"||M.status==="succeeded"||M.status==="processing")){let q=await _o({billingApiUrl:o,sessionId:i,session:s,telemetry:y,tokenizedData:{id:M.id,type:"card",threeDSecureActionResultTokenId:M.id},returnUrl:l});return q.type==="success"?{...q.result,paymentIntentId:q.result.paymentIntentId??M.id,paymentMethodId:q.result.paymentMethodId??R}:q.type==="next_action_required"?Io(q,{billingApiUrl:o,sessionId:i??s.id,session:s,signal:f}):Va(q,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:y,signal:f})}throw Ar(new Rt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw Ar(new Rt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:R}=await aa(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(R)throw Ar(new Rt(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:M}=await aa(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??Ni(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(M)throw Ar(new Rt(M.message??"PayPal authorization failed.","api_error",{code:M.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Rt("Unsupported payment redirect state.","api_error")}function la(e){if(e instanceof Rt){let r=Br(e.message);return r&&r!==e.message?Object.assign(new Rt(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=Br(t)??t;return new Rt(n,"api_error")}function qi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Mr(e.data.session);if(!t&&!n&&!r)throw new Rt("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 Rl(e,t){return e?e.isPaypal?"paypal":"card":t&&Mr(t)?"card":void 0}async function ji({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([Il(e,{billingApiUrl:n,locale:r,telemetry:o}),i?Il(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 Rt("The payment provider did not initialize.","authentication_error");let y=null;return i?y=l:t&&(y=s),{flopay:s,paypalFlopay:y}}import{PaymentAPI as Eo,PciVaultCardCapture as Dd,toStripeAppearance as Od}from"@flopay/js";import{COUNTRY_OPTIONS as Nd,classifyPaymentRejection as Ld,FloPayError as pr,filterStripeMethodsByCountry as zd,getPostalCodeExample as Ud,getPostalCodeLabel as Zi,getStateFromPostalCode as Ml,getStateLabel as Ki,getStateOptions as qd,getStripeMethodDisplayName as eo,hasVendoredStripeMethodLogo as jd,isAuthorizationOnlySession as Vi,isAVSFieldVisible as at,isPostalCodeSupported as $d,isSetupIntentClientSecret as Hi,isValidEmail as fn,isValidPostalCode as Kd,needsStripeMethodExplicitConfirm as Bl,normalizeCheckoutFailureOutcome as Vd,partitionStripeMethods as Hd,randomUuidV4 as Wd,resolveAVSConfig as Gd,resolveButtonsLayoutTheme as Yd,resolveStripeMethodBrandVariant as Jd,resolveTheme as Xd,stripeExpressMethodToOptionKey as Fl}from"@flopay/shared";import{ExpressCheckoutElement as Wl,PaymentElement as Zd,Elements as Zr,useElements as ns,useStripe as rs}from"@stripe/react-stripe-js";import Qd,{useCallback as tt,useContext as To,useEffect as Ct,useMemo as Et,useRef as de,useState as ce}from"react";function Ro(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function $i(e,t){if(e)return{error:n=>e.error(Ro(t,n)),log:n=>e.log(Ro(t,n)),performance:n=>e.performance(Ro(t,n)),terminal:n=>e.terminal(Ro(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 xl={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 Qr,jsx as d,jsxs as Oe}from"react/jsx-runtime";var _r="flopay_stripe_resume",Dl="flopay_wallet_resume",Gl="fw1",eu="fw2",Yl=300*1e3,tu=900,nu=25e3,ru=25e3,ou=1e4,Ha={},Wi={};function os(e){return`${eu}:${e}`}function Wa(e){if(typeof window>"u")return!1;try{return localStorage.removeItem(os(e)),!0}catch{return!1}}function Ga(e,t){if(typeof window>"u")return null;let n=os(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>Yl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Wa(e),null):o}catch{return Wa(e),null}}function au(e){if(typeof window>"u")return!1;try{return localStorage.setItem(os(e.sessionId),JSON.stringify(e)),!0}catch{return!1}}function Ol(e,t,n){let r=Ga(e,t);return!r||r.clientSecret!==n?!1:Wa(e)}function Gi(e,t,n){if(typeof window>"u")return;Ga(e,t)?.clientSecret===n&&Wa(e)}function iu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Yi(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":Yo(e.status),o=iu(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function Nl(e,t,n){let r=null;try{return await Promise.race([sl(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},ou),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 Jl(e){return e instanceof pr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Ja(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Eo(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Jl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ca="flopay_paypal_resume",lu=250,Ll="Just a moment \u2014 we are finalizing your order. Please press pay again.",cu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function as(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 Xa({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Eo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function du(e){return e instanceof pr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ji(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Xl({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=Yr(n),s=i.firstName?i:Yr(r?.name);return On({email:fn(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function uu({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let s=Xl({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return fn(s.email)?s:i(o,s)}var pu=`
|
|
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 @@ ${yn.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
|
-
`,Fa=44,Zo=180,Sl=`flopay-card-enter ${Zo}ms cubic-bezier(0, 0, 0.2, 1) both`,wl=`flopay-card-exit ${Zo}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Jd=`flopay-buttons-enter ${Zo}ms cubic-bezier(0, 0, 0.2, 1) both`,Xd=`flopay-buttons-exit ${Zo}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Zd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Ki(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 Qd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function eu(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 Li={width:"100%",minHeight:Fa,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 tu(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Il(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Oi(e){return e==="paypal"?"PayPal":Hr(e)}function nu(e,t){let n=`We couldn't open ${Oi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function ru(e){let t=wd(e);return`Enter a valid ${Ni(e)}${t?` (e.g. ${t})`:""}`}function ou(e,t,n){let r=_d(e),o=t.trim(),i=n&&r,s=i&&!o,l=i&&!!o&&!Rd(e,o);return{visible:n,supported:r,required:i,empty:s,malformed:l}}function au(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!ln(n);return{required:t,empty:r,malformed:o,value:n}}function kl(e,t){return t instanceof ir?t:new ir(t instanceof Error?t.message:`${tu(e)} before-click hook failed.`,"validation_error")}function Di(){return c("style",{children:Yd})}function iu(e){return typeof e=="number"?`${e}px`:e}function Dl(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Nl({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:Ue("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 _l(e){return e!=="unavailable"&&e!=="load_error"}function Vi(e){return c(lu,{...e})}function Rl({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:p,onTechnicalFailure:v,runBeforeButtonClick:g,billingName:h,onBuyerIdentityReady:y,onLoadStateChange:_,placeholderBorderRadius:M}){let U=kr(),{emitInstrument:qe}=Co(Gn),ge=qi(),S=Ui(),[W,Y]=oe("loading");ft(()=>{_?.(W)},[W,_]);let[de,Le]=oe(!1),Se=!ln(n?.trim())||!h?.trim(),{request:Re,collect:Ge,finish:St}=uo(),tt=ce(!1),je=ce(null),$e=ce(null),[ue,we]=oe(0),[Xe,ee]=oe(!1),Ie=ce(!1),he=ce(new Map),{startAttempt:st,finishAttempt:lt,invalidateAttempt:T,isAttemptInvalidated:$,isAttemptCurrent:Ee}=Vo((se,x,Q)=>{v?.(se,x,{...Q,popupBlocked:Q?.popupBlocked??br(x)}),ee(!0),we(Me=>Me+1)});ft(()=>{Xe&&$e.current?.focus()},[Xe,ue]);let ie=Je(()=>{we(se=>se+1)},[]),rt=Je((se,x,Q)=>{T(Q),v?.("paypal",se,{code:x,popupBlocked:br(se)}),ee(!0),ie()},[T,v,ie]),A=Je(()=>{window.setTimeout(()=>{(je.current?.querySelector("iframe")??je.current)?.focus()},0)},[]);ft(()=>{Ie.current&&(Ie.current=!1,A())},[A,ue]);let Te=Je(()=>{ee(!1),i?.(null),A()},[A,i]);ft(()=>{if(!ge||tt.current)return;let se=new URLSearchParams(window.location.search),x=se.get("payment_intent"),Q=se.get("payment_intent_client_secret"),Me=se.get("redirect_status");if(!x||!Q)return;tt.current=!0;let ot;try{let Ke=localStorage.getItem(Xo);if(Ke){let _e=JSON.parse(Ke);_e.clientSecret===Q&&(ot={..._e.accountPatch?{accountPatch:_e.accountPatch}:{},..._e.sessionId?{sessionId:_e.sessionId}:{},..._e.nonce?{nonce:_e.nonce}:{}})}}catch{}try{localStorage.removeItem(Xo)}catch{}let ke=new URL(window.location.href);ke.searchParams.delete("payment_intent"),ke.searchParams.delete("payment_intent_client_secret"),ke.searchParams.delete("redirect_status"),window.history.replaceState({},"",ke.toString()),(async()=>{try{if(Le(!0),Me==="failed"){let le="PayPal payment was declined. Please try again.";i?.(le),p?.(nn("paypal",le));return}let{paymentIntent:Ke,error:_e}=await ge.retrievePaymentIntent(Q);if(_e){i?.(_e.message??"Failed to retrieve PayPal payment status.");return}if(Ke&&(Ke.status==="requires_capture"||Ke.status==="succeeded")){let le=typeof Ke.payment_method=="string"?Ke.payment_method:Ke.payment_method?.id;o({id:le??Ke.id,type:"card",threeDSecureActionResultTokenId:Ke.id,isPaypal:!0},ot)}else{let le="PayPal payment was not completed. Please try again.";i?.(le),p?.(nn("paypal",le))}}catch(Ke){i?.(Ke instanceof Error?Ke.message:"Failed to complete PayPal payment.")}finally{Le(!1)}})()},[ge,o,i,p]);let dt=Je(async se=>{if(s||de){se.reject();return}let x=g?await g("paypal"):{proceed:!0};if(!x.proceed){he.current.delete(ue),se.reject();return}let Q=st("paypal");he.current.set(ue,{generation:Q,accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}),ee(!1),l?.("paypal"),se.resolve()},[s,l,g,st,de,ue]),We=Je(async se=>{if(!ge||!S)return;let x=he.current.get(ue);if(x&&!Ee(x.generation)){he.current.delete(ue);return}if(!x&&$()||x&&!lt(x.generation))return;x||lt();let Q=x??null;if(he.current.delete(ue),!Q&&g){let le=await g("paypal");if(!le.proceed){se.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Q={accountPatch:le.accountPatch,sessionId:le.sessionId,nonce:le.nonce}}let Me=Q?.sessionId??e,ot=Q?.nonce??t,ke=await Gd({event:se,prepared:Q,email:n,billingName:h,methodLabel:"PayPal",collect:Ge});if(!ke){se.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ke=ke.email,_e={...Q?.accountPatch,...Dn(ke,!0)};try{if(Le(!0),i?.(null),!Me||!ln(Ke))throw new Error("Missing sessionId or email for PayPal payment");await y?.(ke);let le=ge.createPaymentMethod,{error:ve,paymentMethod:Vt}=await le({type:"paypal"});if(ve){rt(ve,"stripe_paypal_create_payment_method_failed",x?.generation),se.paymentFailed({reason:"fail"});return}let H=await Da(r,qe,Me,ot??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Vt?.id??null,intentKind:"payment"});if(H.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Mt=H.clientSecret,mt={return_url:window.location.href};if(Vt?.id&&(mt.payment_method=Vt.id),typeof window<"u")try{localStorage.setItem(Xo,JSON.stringify({clientSecret:Mt,sessionId:Me,nonce:ot,accountPatch:_e}))}catch{}let{error:R,paymentIntent:ne}=await ge.confirmPayment({clientSecret:Mt,confirmParams:mt,redirect:"if_required"});if(R){if(typeof window<"u")try{localStorage.removeItem(Xo)}catch{}if(Ko(R)){let w=R.message??"Your payment was declined.";i?.(w),p?.(nn("paypal",w,{code:Pr(R),declineCode:mo(R)})),await Na({billingApiUrl:r,sessionId:Me,nonce:ot,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Pr(R)??"provider_declined"}})}else rt(R,"stripe_paypal_confirm_failed",x?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Xo)}catch{}let u=typeof ne?.payment_method=="string"?ne.payment_method:ne?.payment_method?.id;o({id:u??ne?.id,type:"card",threeDSecureActionResultTokenId:ne?.id,isPaypal:!0},{accountPatch:_e,paymentMethodCategory:"paypal",sessionId:Me,nonce:ot});return}catch(le){rt(le,"stripe_paypal_failed",x?.generation)}finally{Le(!1)}},[ge,S,e,t,n,h,Ge,y,r,qe,o,i,p,g,rt,lt,Ee,$,ue]);return Ue(Wr,{children:[c(Nl,{state:W,placeholderTestId:"flopay-paypal-placeholder",borderRadius:M,children:Ue("div",{ref:je,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Xe&&c("button",{ref:$e,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Te,style:Li,children:"Try PayPal again"}),Re&&c(po,{identity:Re.identity,methodLabel:Re.methodLabel,onComplete:St,onCancel:()=>St(null)},Re.id),c("div",{style:{display:Re?"none":void 0},children:c(Al,{onReady:se=>Y(Dl(se,["paypal"])),onLoadError:()=>{Y("load_error"),$i(Qt(U),"paypal","paypal")},onClick:dt,onConfirm:We,onCancel:()=>{let se=he.current.get(ue);he.current.delete(ue),Qt(U)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),T(se?.generation),ee(!1),Ie.current=!0,ie()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Se,emailRequired:Se,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ue)})]})}),de&&c(yr,{status:"processing"})]})}function El({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:p,onDecline:v,onTechnicalFailure:g,runBeforeButtonClick:h,billingName:y,onBuyerIdentityReady:_,onLoadStateChange:M,placeholderBorderRadius:U}){let qe=kr(),{emitInstrument:ge}=Co(Gn),S=qi(),W=Ui(),[Y,de]=oe("loading");ft(()=>{M?.(Y)},[Y,M]);let[Le,Se]=oe(!1),Re=ce(!ln(n?.trim())||!y?.trim()).current,{request:Ge,collect:St,finish:tt}=uo(),je=ce(null),$e=ce(null),[ue,we]=oe(0),[Xe,ee]=oe(!1),[Ie,he]=oe(()=>Ba(e,t)?"blocked":"idle"),[st,lt]=oe("google_pay"),T=ce(null),$=ce(!0),Ee=ce(!1),ie=ce("google_pay"),rt=ce("google_pay"),A=ce(null),Te=ce(null),dt=ce(new Set);ft(()=>($.current=!0,()=>{$.current=!1;for(let R of dt.current)window.clearTimeout(R);dt.current.clear()}),[]);let We=ce(new Map),{startAttempt:se,finishAttempt:x,invalidateAttempt:Q,isAttemptInvalidated:Me,isAttemptCurrent:ot,generationRef:ke}=Vo((R,ne,u)=>{g?.(R,ne,{...u,popupBlocked:u?.popupBlocked??br(ne)}),lt(R),ee(!0),we(w=>w+1)});ft(()=>{Xe&&$e.current?.focus()},[Xe,ue]);let Ke=Je(()=>{we(R=>R+1)},[]),_e=Je((R,ne,u,w)=>{Q(w),g?.(R,ne,{code:u,popupBlocked:br(ne)}),lt(R),ee(!0),Ke()},[Q,g,Ke]),le=Je(()=>{window.setTimeout(()=>{(je.current?.querySelector("iframe")??je.current)?.focus()},0)},[]);ft(()=>{Ee.current&&(Ee.current=!1,le())},[le,ue]);let ve=Je(()=>{ee(!1),l?.(null),le()},[le,l]),Vt=Je(()=>{T.current?.()},[]);ft(()=>{let R=Ba(e,t);if(!R)return;let ne=!1,u=!1,w=async()=>{if(!u){u=!0,ne||he("checking");try{let xe=await bl(S,R.clientSecret,dt.current);if(ne)return;let me=Bi(xe,R.providerObjectId,Ti(R.clientSecret));if(me.kind==="confirmed"){if(!Pl(e,t,R.clientSecret))return;T.current=null,he("idle"),s({id:me.paymentMethodId,type:"card",threeDSecureActionResultTokenId:me.intentId},{...R.accountPatch?{accountPatch:R.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(me.kind==="terminal"){xi(e,t,R.clientSecret),T.current=null,he("idle"),lt(R.paymentMethodType),ee(!0),Ke();return}he("blocked")}catch{ne||he("blocked")}finally{u=!1}}};return T.current=w,he("blocked"),()=>{ne=!0,T.current===w&&(T.current=null)}},[t,s,Ke,e,S]);let H=Je(async R=>{let ne=!1,u=Ae=>{ne||(ne=!0,R.paymentFailed({reason:"fail",...Ae?{message:Ae}:{}}))};if(!S||!W){u();return}let w=We.current.get(ue);if(w&&!ot(w.generation)){We.current.delete(ue),u();return}if(!w&&Me()){u();return}if(w&&!x(w.generation)){u();return}w||x();let xe=R.expressPaymentType??w?.method??ie.current,me=w??null,Ct=Il(xe),nt;xe==="apple_pay"?nt="apple_pay":xe==="google_pay"&&(nt="google_pay");let xt=w?.generation??ke.current,K=Qt(qe),Wt=K?.now()??globalThis.performance?.now()??Date.now(),wt=new AbortController,yn=!1,sr=!1,N=null,fn=e,In="processing",cn="other",rn="provider_runtime",gn,Jn=new Promise((Ae,Oe)=>{gn=Oe}),dn=window.setTimeout(()=>{yn=!0,wt.abort(),gn(Ai)},zd),Ht=async(Ae,Oe,on)=>{In=Ae,cn=Oe,rn=Oe==="intent_create"||Oe==="session_claim"?"transport_error":"provider_runtime";let ut=K?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([on,Jn])}finally{let jn=K?.now()??globalThis.performance?.now()??Date.now();K?.performance({stage:Ae,durationMs:Math.max(0,jn-ut),durationMode:"machine",requestCategory:Oe,paymentMethodCategory:"wallet",provider:"stripe",...yn?{statusClass:"timeout"}:{}})}};try{if(Se(!0),l?.(null),!me&&h){let Pe=await Ht("processing","other",h(Ct));if(!Pe.proceed){u();return}me={accountPatch:Pe.accountPatch,sessionId:Pe.sessionId,nonce:Pe.nonce}}let Ae=me?.sessionId??e;fn=Ae;let Oe=me?.nonce??t,on=A.current??me?.accountPatch,ut=Fl({event:R,fallbackEmail:on?.email??n,fallbackName:[on?.firstName,on?.lastName].join(" ").trim()||y});if(!ln(ut.email)){u("Buyer details are required."),St(Oi(xe),ut).then(Pe=>{Pe&&(A.current=Pe)});return}A.current=null;let jn={...me?.accountPatch,...Dn(ut,!0)};await Ht("processing","session_claim",Promise.resolve(_?.(ut)));let{error:Bt}=await Ht("tokenization","provider_sdk",W.submit());if(Bt){u(),_e(xe,Bt,"stripe_wallet_submit_failed",w?.generation);return}if(!Ae)throw new Error("Missing sessionId or email for payment.");let Gt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:xe,paymentMethodId:null,intentKind:o},gt=JSON.stringify({sessionId:Ae,nonce:Oe??"",request:Gt}),$t=Te.current,un=$t?.retryIdentity===gt?$t.authorizationAttemptId:Ad();Te.current={authorizationAttemptId:un,retryIdentity:gt};let Ft=await Ht("processing","intent_create",Da(r,ge,Ae,Oe??"",{...Gt,authorizationAttemptId:un},{signal:wt.signal}));if(Ft.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let It=Ft.clientSecret,an=jd({createdAt:Date.now(),sessionId:Ae,...Oe?{nonce:Oe}:{},clientSecret:It,providerObjectId:Ft.providerObjectId,paymentMethodType:xe,accountPatch:jn});window.clearTimeout(dn),sr=!0,K?.performance({stage:"callback",durationMs:Math.max(0,(K?.now()??globalThis.performance?.now()??Date.now())-Wt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Nn=K?.now()??globalThis.performance?.now()??Date.now(),vt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...nt?{walletType:nt}:{},attempt:xt},J=!1,hn=null;K?.log({name:"payment.provider_confirmation.started",...vt}),N=window.setTimeout(()=>{N!==null&&dt.current.delete(N),J=!0;let Pe=K?.now()??globalThis.performance?.now()??Date.now();K?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...vt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Pe-Nn),statusClass:"timeout",failureCategory:"provider_runtime"}),K?.flush?.().catch(()=>{}),hn?.()},Ud),dt.current.add(N);let vn=Pe=>{N!==null&&(window.clearTimeout(N),dt.current.delete(N),N=null);let E=K?.now()??globalThis.performance?.now()??Date.now(),be=Math.max(0,E-Nn),I=Pe;return J&&(Pe==="resolved"?I="resolved_late":Pe==="returned_error"?I="returned_error_late":I="rejected_late"),K?.log({name:"payment.provider_confirmation.returned",...vt,operationOutcome:I}),K?.performance({...vt,durationMs:be,durationMode:"buyer",operationOutcome:I}),{durationMs:be,operationOutcome:I}},Dt=!1,zt=!1,Ln=Pe=>{if(!Pe||typeof Pe!="object")return null;let E=Pe;if(E.error)return null;let be=E.setupIntent??E.paymentIntent,I=Bi(be??null,void 0,!!E.setupIntent);return I.kind==="confirmed"?I:null},$n=Pe=>{if(Dt||w&&ke.current!==w.generation)return;let E=Ln(Pe);if(!E)return;if(an&&!Pl(Ae,Oe,It)){Dt=!0;return}let{intentId:be,paymentMethodId:I}=E;Dt=!0,zt=!0,Te.current=null,T.current=null,$.current&&(he("idle"),Se(!1));let Nt=`${Ml}:${Ae}`;if(typeof window<"u")try{localStorage.setItem(Nt,JSON.stringify({createdAt:Date.now(),sessionId:Ae,nonce:Oe,accountPatch:jn,paymentMethodId:I,providerIntentId:be,paymentMethodType:xe}))}catch{}try{s({id:I,type:"card",threeDSecureActionResultTokenId:be},{accountPatch:jn,paymentMethodCategory:"wallet",sessionId:Ae,nonce:Oe})}finally{if(typeof window<"u")try{localStorage.removeItem(Nt)}catch{}}},Xn=!1;hn=async()=>{if(!(Xn||Dt||zt)){Xn=!0,$.current&&he("checking");try{let Pe=await bl(S,It,dt.current);if(Dt||zt)return;let E=Ti(It),be=Bi(Pe,Ft.providerObjectId,E);if(be.kind==="confirmed"){$n(E?{setupIntent:Pe}:{paymentIntent:Pe});return}if(be.kind==="terminal"){if(zt=!0,xi(Ae,Oe,It),Te.current=null,T.current=null,!$.current)return;he("idle"),u(),_e(xe,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",w?.generation);return}$.current&&!zt&&(he("blocked"),Se(!1))}catch{$.current&&!zt&&(he("blocked"),Se(!1))}finally{Xn=!1}}},T.current=hn;let Yt,ze;try{let Pe=await(Ti(It)?S.confirmSetup({elements:W,clientSecret:It,redirect:"if_required"}):S.confirmPayment({elements:W,clientSecret:It,redirect:"if_required"}));if(!Pe||typeof Pe!="object"||(Yt=Pe,!Yt.error&&!Ln(Yt)))throw Mi;ze=vn(Yt.error?"returned_error":"resolved")}catch(Pe){let E=Pe===Mi,be=vn(E?"returned_error":"rejected");if(K?.error({...E?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:ci(Pe),...vt,operationOutcome:be.operationOutcome,durationMs:be.durationMs,statusClass:"unknown"}),!$.current||Dt)return;await hn?.();return}let Ut=Yt.error;if(Ut){if(!$.current||Dt)return;if(Ko(Ut)){zt=!0,xi(Ae,Oe,It),Te.current=null,T.current=null,he("idle");let Pe=Ut.message??"Your payment was declined.";u(Pe),l?.(Pe),v?.(nn(Ct,Pe,{code:Pr(Ut),declineCode:mo(Ut)})),Na({billingApiUrl:r,sessionId:Ae,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:xe,providerDeclineReason:Pr(Ut)??"provider_declined",...Ft.intentKind==="payment"&&Ft.providerObjectId.startsWith("pi_")?{providerIntentId:Ft.providerObjectId}:{}}})}else K?.error({...ci(Ut),...vt,operationOutcome:ze.operationOutcome,durationMs:ze.durationMs,statusClass:"unknown"}),await hn?.();return}if($n(Yt),!Dt)throw new Error("Invalid provider returned for APM intent")}catch(Ae){if(Ae===Ai){let Oe=K?.now()??globalThis.performance?.now()??Date.now();K?.error({errorCode:Kd(cn),stage:In,requestCategory:cn,paymentMethodCategory:"wallet",provider:"stripe",...nt?{walletType:nt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:fn,durationMs:Math.max(0,Oe-Wt),statusClass:"timeout",failureCategory:rn,attempt:xt}),K?.flush?.().catch(()=>{})}u(),_e(xe,Ae,Ae===Ai?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",w?.generation)}finally{if(window.clearTimeout(dn),N!==null&&(window.clearTimeout(N),dt.current.delete(N)),!sr){let Ae=K?.now()??globalThis.performance?.now()??Date.now();K?.performance({stage:"callback",durationMs:Math.max(0,Ae-Wt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...yn?{statusClass:"timeout"}:{}})}$.current&&Se(!1)}},[S,W,e,t,n,y,St,_,r,ge,o,s,l,v,h,_e,x,ot,Me,ke,qe,ue]),Mt=Et(()=>{let R=["applePay","googlePay","paypal","link","amazonPay","klarna"],ne=new Set(["applePay","googlePay"]),u=new Set(i.map(hl)),w={};for(let xe of R)u.has(xe)?w[xe]=ne.has(xe)?"always":"auto":w[xe]="never";return w},[i]),mt=Et(()=>i.map(hl),[i]);return Ue(Wr,{children:[c(Nl,{state:Y,placeholderTestId:"flopay-wallet-placeholder",borderRadius:U,children:Ue("div",{ref:je,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Xe&&Ue("button",{ref:$e,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ve,style:Li,children:["Try ",Oi(st)," again"]}),Ie!=="idle"&&Ue("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:Vt,disabled:Ie==="checking",style:Li,children:Ie==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ge&&c(po,{identity:Ge.identity,methodLabel:Ge.methodLabel,onComplete:tt,onCancel:()=>tt(null)},Ge.id),Ie==="idle"&&c("div",{style:{display:Ge?"none":void 0},children:c(Al,{onReady:R=>{de(Dl(R,mt))},onLoadError:R=>{de("load_error"),$i(Qt(qe),"stripe","wallet")},onClick:async R=>{ie.current=R.expressPaymentType,rt.current=Il(R.expressPaymentType);let ne=!0,u=window.setTimeout(()=>{ne=!1,R.reject()},Od),w=h?await h(rt.current):{proceed:!0};if(window.clearTimeout(u),!ne)return;if(!w.proceed){We.current.delete(ue),R.reject();return}let xe=se(R.expressPaymentType);We.current.set(ue,{generation:xe,method:R.expressPaymentType,accountPatch:w.accountPatch,sessionId:w.sessionId,nonce:w.nonce}),ee(!1),p?.(rt.current),R.resolve()},onConfirm:H,onCancel:()=>{let R=We.current.get(ue);We.current.delete(ue),Qt(qe)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Q(R?.generation),Te.current=null,ee(!1),Ee.current=!0,Ke()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Mt,emailRequired:Re,billingAddressRequired:Re,layout:{maxColumns:1,overflow:"never"}}},ue)})]})}),Le&&c(yr,{status:"processing"})]})}function Ll(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function su({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:s,backgroundColor:l,borderColor:p,textColor:v,borderRadius:g,fontFamily:h}){let y=Bd(e,t),_=yl[e],[M,U]=oe(!1),qe=!!_&&!M,ge=y?.backgroundColor??l??"#ffffff",S=y?.borderColor??p??"#d1d5db",W=y?.textColor??v??"#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:Fa,padding:"0 1rem",backgroundColor:ge,color:W,border:`1px solid ${S}`,borderRadius:g??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 ${Hr(e)}\u2026`}):Ue(Wr,{children:[Ue("span",{style:{display:"inline-flex",alignItems:"center",gap:kd(e)?8:0},children:[qe?c("img",{src:_,alt:"","aria-hidden":"true",onError:()=>U(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!qe&&y?.logoSvg?c("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:y.logoSvg}}):null,c("span",{children:Hr(e)})]}),i&&c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:W,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:c("path",{d:"M9 18l6-6-6-6"})})]})})}function zi({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:p,onDecline:v,onCancel:g,runBeforeButtonClick:h,onButtonClick:y,isProcessing:_,submitButtonColor:M,submitButtonBorderRadius:U,submitButtonStyle:qe,errorText:ge}){let S=kr(),{emitInstrument:W}=Co(Gn),Y=qi(),de=Ui(),[Le,Se]=oe(!1),Re=ce(!1),[Ge,St]=oe(!1),[tt,je]=oe("loading"),[$e,ue]=oe(""),we=!ln(r?.trim()),Xe=!we||ln($e.trim()),ee=Je(async()=>{if(!Y||!de||_||Re.current||!Ge)return;Re.current=!0,Se(!0);let Ie=h?await h("card"):{proceed:!0};if(!Ie.proceed){Re.current=!1,Se(!1);return}y?.("card");let he=Ie.sessionId??t,st=Ie.nonce??n,lt=qr(o?.trim()),T=Dn({email:Ie.accountPatch?.email?.trim()||r?.trim()||$e.trim(),firstName:Ie.accountPatch?.firstName?.trim()||lt.firstName,lastName:Ie.accountPatch?.lastName?.trim()||lt.lastName}),$=T.email,Ee=Dn({...Ie.accountPatch,...T});try{if(p?.(null),!ln($))throw new Error("A valid email address is required for payment.");await i?.(T);let ie=await de.submit();if(ie.error){p?.(ie.error.message??"Payment failed.");return}let rt=[T.firstName,T.lastName].filter(Boolean).join(" "),A=await Y.createPaymentMethod({elements:de,params:{billing_details:{email:$,...rt?{name:rt}:{}}}});if(A.error||!A.paymentMethod){p?.(A.error?.message??"Failed to create payment method.");return}let Te=A.paymentMethod;if(!he||!$)throw new Error("Missing sessionId or email for payment.");let dt=Te.type||e,We=await Da(s,W,he,st??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:dt,paymentMethodId:null,intentKind:"payment"});if(We.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let se=We.clientSecret;if(typeof window<"u")try{localStorage.setItem(fr,JSON.stringify({clientSecret:se,sessionId:he,nonce:st,accountPatch:Ee,paymentMethodId:Te.id,paymentMethodType:Te.type??e,gateway:"stripe"}))}catch{}let{error:x,paymentIntent:Q}=await Y.confirmPayment({clientSecret:se,confirmParams:{return_url:window.location.href,payment_method:Te.id},redirect:"if_required"});if(x){if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let ke=x.message??"Payment failed.";p?.(ke),v?.(nn("card",ke,{code:x.code})),await Na({billingApiUrl:s,sessionId:he,nonce:st,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:x.code??"provider_declined"}});return}let Me=Q?.status;if(!qo(Me)){if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let ke=Me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(ke),v?.(nn("card",ke,{code:Me??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let ot=typeof Q?.payment_method=="string"?Q.payment_method:Q?.payment_method?.id;l({id:ot??Te.id,type:"card",threeDSecureActionResultTokenId:Q?.id,gateway:"stripe",paymentMethodType:Te.type??e},{accountPatch:Ee,paymentMethodCategory:"apm",sessionId:he,nonce:st})}catch(ie){p?.(ie instanceof Error?ie.message:"Payment failed. Please try again.")}finally{Re.current=!1,Se(!1)}},[Y,de,_,Ge,h,y,t,n,r,o,$e,i,s,W,e,l,p,v]);return Ue("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&&Ue("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:$e,onChange:Ie=>ue(Ie.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(Dd,{onReady:()=>je("ready"),onLoadError:()=>{je("load_error"),$i(Qt(S),"stripe","apm")},onChange:Ie=>{St(!!Ie.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...ln(r?.trim())?{email:r?.trim()}:{}}}}}),c("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{ee()},disabled:!Ge||!Xe||Le||_||tt!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:M,color:"white",border:"none",borderRadius:U,fontSize:"1rem",fontWeight:600,cursor:!Ge||!Xe||Le||_||tt!=="ready"?"not-allowed":"pointer",opacity:!Ge||!Xe||Le||_||tt!=="ready"?.5:1,transition:"opacity 120ms ease-out",...qe??{}},children:Le?"Processing\u2026":`Pay with ${Hr(e)}`}),ge&&c(fo,{margin:"0.75rem 0 0",children:ge})]})}function Tl({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:p,onTokenizedBody:v,onErrorChange:g,onButtonClick:h,onDecline:y,runBeforeButtonClick:_,onLoadStateChange:M,isProcessing:U=!1,submitButtonColor:qe="#4A49FF",submitButtonBorderRadius:ge=8,submitButtonStyle:S,buttonAppearance:W,themeId:Y,onExpandApm:de,expandedApmMethod:Le}){let{emitInstrument:Se}=Co(Gn),[Re,Ge]=oe(null),[St,tt]=oe(null),je=ce(!1),{request:$e,collect:ue,finish:we}=uo();ft(()=>{s.length>0&&l?M?.("ready"):l||M?.("loading")},[s.length,l,M]);let Xe=Je(async T=>{if(!l||je.current||U)return;je.current=!0,tt(T);let $=_?await _("card"):{proceed:!0};if(!$.proceed){je.current=!1,tt(null);return}h?.("card");let Ee=$.sessionId??e,ie=$.nonce??t,rt=qr([$.accountPatch?.firstName,$.accountPatch?.lastName].filter(Boolean).join(" ")||r),A=Dn({email:$.accountPatch?.email?.trim()||n?.trim(),firstName:$.accountPatch?.firstName?.trim()||rt.firstName,lastName:$.accountPatch?.lastName?.trim()||rt.lastName});if(!ln(A.email)){tt(null);let We=await ue(Hr(T),A);if(!We){je.current=!1;return}A=We,tt(T)}let Te=A.email,dt=Dn({...$.accountPatch,...A});try{if(g?.(null),!Ee||!ln(Te))throw new Error("Missing sessionId or email for payment.");await o?.(A);let We=await Da(i,Se,Ee,ie??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,paymentMethodId:null,intentKind:"payment"});if(We.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let se=We.clientSecret;if(typeof window<"u")try{localStorage.setItem(fr,JSON.stringify({clientSecret:se,sessionId:Ee,nonce:ie,accountPatch:dt,paymentMethodType:T,gateway:"stripe"}))}catch{}let{error:x,paymentIntent:Q}=await l.confirmPayment({clientSecret:se,confirmParams:{return_url:window.location.href,payment_method_data:{type:T,billing_details:{name:[A.firstName,A.lastName].filter(Boolean).join(" "),...Te?{email:Te}:{}}}},redirect:"if_required"});if(x){if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let ke=x.message??"Payment failed.";g?.(ke),y?.(nn("card",ke,{code:x.code})),await Na({billingApiUrl:i,sessionId:Ee,nonce:ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,providerDeclineReason:x.code??"provider_declined"}});return}let Me=Q?.status;if(!qo(Me)){if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let ke=Me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(ke),y?.(nn("card",ke,{code:Me??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let ot=typeof Q?.payment_method=="string"?Q.payment_method:Q?.payment_method?.id;v({id:ot??Q?.id,type:"card",threeDSecureActionResultTokenId:Q?.id,gateway:"stripe",paymentMethodType:T},{accountPatch:dt,paymentMethodCategory:"apm",sessionId:Ee,nonce:ie})}catch(We){g?.(We instanceof Error?We.message:"Payment failed. Please try again.")}finally{je.current=!1,tt(null)}},[l,U,_,h,e,t,n,ue,i,Se,r,o,v,g,y]),[ee,Ie]=oe(null),he=de?Le??null:ee,st=Je(T=>{je.current||U||he&&he!==T||(gl(T)?de?de(T):Ie(T):Xe(T))},[he,U,Xe,de]),lt=Et(()=>ee?Ll(p,ee):null,[ee,p]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:$e?c(po,{identity:$e.identity,methodLabel:$e.methodLabel,onComplete:we,onCancel:()=>we(null)},$e.id):s.map(T=>{let $=Le===T,Ee=St===T,ie=St!==null&&St!==T||Le!=null&&Le!==T;return Ue(Nd.Fragment,{children:[c(su,{method:T,themeId:Y,submitting:Ee,disabled:ie,highlighted:$,hasNextStep:gl(T),onClick:()=>st(T),backgroundColor:W?.backgroundColor,borderColor:W?.borderColor,textColor:W?.textColor,borderRadius:W?.borderRadius,fontFamily:W?.fontFamily}),!de&&ee===T&<&&l&&c(Vr,{stripe:l,options:lt,children:c(zi,{method:T,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:v,onErrorChange:g,onDecline:y,onCancel:()=>Ie(null),runBeforeButtonClick:_,onButtonClick:h,isProcessing:U,submitButtonColor:qe,submitButtonBorderRadius:ge,submitButtonStyle:S})},T)]},T)})})}function lu({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:i,onComplete:s,onError:l,onDecline:p,onTokenizedBody:v,firstName:g,lastName:h,chv:y,className:_,submitLabel:M,isProcessing:U,error:qe,onErrorChange:ge,showPayPal:S=!0,showStripe:W=!0,enabledPaymentMethods:Y,enabledPaymentMethodCountries:de,showApplePay:Le=!0,showGooglePay:Se=!0,layout:Re="default",theme:Ge,buttonsTheme:St,buttonsStyles:tt,appearance:je,cardButtonContent:$e,cardBackButtonContent:ue,cardTitleContent:we,showSecurityFooter:Xe,onButtonClick:ee,onBeforeButtonClick:Ie,onBuyerIdentityReady:he,enableAVS:st,cardFieldOrder:lt,cardPreFormSlot:T,avsLayout:$="row",country:Ee,zip:ie,addressLine1:rt,addressLine2:A,city:Te,state:dt,onCountryChange:We,onZipChange:se,avsCheck:x,checkoutType:Q,checkoutLayout:Me,totalAmount:ot=0,currency:ke="usd",initialCardOpen:Ke=!1,directPaypal:_e,isSubscription:le=!1,session:ve,dataAttachmentPending:Vt=!1,dataAttachmentRequiresIdentity:H=!1,debug:Mt=!1}){let mt=kr(),R=di(),ne=Co(ar),{emitInstrument:u}=Co(Gn),w=ve??ne.session,xe=w?.gateways?.paypal?.providerObjectType??_e?.providerObjectType,me=Vt||ne.claimPending===!0,Ct=H||ne.claimRequiresIdentity===!0,nt=me&&!Ct,xt=Qs(),K=n||xt,[Wt,wt]=oe(!1),[yn,sr]=oe(null),[N,fn]=oe(Ee??"US"),[In,cn]=oe(ie??""),[rn,gn]=oe(rt??""),[Jn,dn]=oe(A??""),[Ht,Ae]=oe(Te??""),[Oe,on]=oe(dt??""),[ut,jn]=oe(""),[Bt,Gt]=oe({}),gt=ce(ie??""),$t=ce(Ee??"US"),un=ce(rt??""),Ft=ce(A??""),It=ce(Te??""),an=ce(dt??""),Nn=ce(""),vt=ce({});ft(()=>{let a=(P,O,Ne,j,at)=>{if(vt.current[P])return;let Ze=O?.trim();!Ze||Ze===Ne.current||(Ne.current=Ze,j(Ze),at?.(Ze))};a("country",Ee,$t,fn,We),a("zip",ie,gt,cn,se),a("addressLine1",rt,un,gn),a("addressLine2",A,Ft,dn),a("city",Te,It,Ae),a("state",dt,an,on)},[Ee,ie,rt,A,Te,dt,We,se]);let J=Et(()=>Md(st),[st]),hn=J!==null,vn=Et(()=>Ei(ve),[ve]),Dt=!!ve?.vault?.html,zt=!!ve?.gateways?.pcivault,Ln=ii(ve),Xn=!!(ve?.gateways?.stripe?.enabledPaymentMethods??Y)?.includes("card")||Ur(ve),Yt=Dt||Xn||zt,ze=!!(W&&Yt&&e),[Ut,Pe]=oe(()=>Re!=="buttons"||Ke?e??null:null),[E,be]=oe(0),I=Re!=="buttons"||Ke||!!e&&Ut===e,Nt=ve?.captureMethod,Pn=ce(mt);ft(()=>{Pn.current=mt},[mt]);let[sn,On]=oe(null);ft(()=>{if(!ze||!e||!I){On(null);return}let a=Pn.current?Pn.current.cardCapture({sessionId:e,captureMethod:Nt}):new vd({sessionId:e,captureMethod:Nt,billingApiUrl:K,telemetry:r});return On({sessionId:e,captureMethod:Nt,billingApiUrl:K,telemetry:r,capture:a}),()=>{a.unmount()}},[ze,e,I,Nt,K,r]);let ae=ze&&e&&I&&sn?.sessionId===e&&sn.captureMethod===Nt&&sn.billingApiUrl===K&&sn.telemetry===r?sn.capture:null,bn=Et(()=>{let a=N,P=J?et(J.postal_code,a):!1;return ou(a,In,P)},[J,N,In]),{avsInvalid:Br,invalidAvsFields:Gr}=Et(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!ze||!J)return{avsInvalid:!1,invalidAvsFields:a};let P=N,O=(at,Ze)=>et(at,P)&&!Ze.trim(),Ne={line1:O(J.address_line_1,rn),city:O(J.city,Ht),state:O(J.state,Oe),zip:bn.empty||bn.malformed};return{avsInvalid:Ne.line1||Ne.city||Ne.state||Ne.zip,invalidAvsFields:Ne}},[ze,J,N,rn,Ht,Oe,bn]),[kn,wr]=oe(!1),[lr,Zn]=oe(!1),[Kt,_n]=oe(!1),[vr,zn]=oe({line1:!1,city:!1,state:!1}),Rn=ce(!1),Qn=ce({email:!1,line1:!1,city:!1,state:!1,zip:!1}),er=ce(!1),Pt=Je(a=>{Qn.current[a]=!0,er.current=!0},[]),Cn=Je(a=>!Rn.current&&Qn.current[a],[]),Kn=Je(a=>{Cn(a)&&zn(P=>P[a]?P:{...P,[a]:!0})},[Cn]),[tr,En]=oe(()=>Fi(ve?.vault)),[Ve,tn]=oe(Ke&&Yt?"card":"buttons"),[pn,cr]=oe(null),Fr=Ve==="expanding"||Ve==="card",nr=ve?.gateways?.stripe&&!Ln?"stripe":void 0,dr=Je(()=>{u?.({class:"card_surface",provider:nr})},[nr,u]),Tn=ce(null),An=Je(a=>{Tn.current&&clearTimeout(Tn.current),Tn.current=setTimeout(()=>{Tn.current=null,a()},Zo)},[]);ft(()=>()=>{Tn.current&&clearTimeout(Tn.current)},[]);let Dr=Je(()=>{dr(),Pe(e??null),be(a=>a+1),tn("expanding"),An(()=>tn("card"))},[An,dr,e]),Un=Je(()=>{tn("collapsing"),An(()=>tn("buttons"))},[An]),Nr=Je(a=>{cr(a),tn("apm-expanding"),An(()=>tn("apm-form"))},[An]),Jt=Je(()=>{tn("apm-collapsing"),An(()=>{tn("buttons"),cr(null)})},[An]);ft(()=>{Re==="buttons"&&Ke&&Yt&&(Pe(e??null),tn("card"))},[Re,Ke,Yt,e]);let[k,f]=oe(null),G=ce(!1),B=ce(null),Ce=ce("idle"),[ct,ye]=oe(!1),z=ce(ct);z.current=ct;let[X,F]=oe(null),m=ce(X);ft(()=>{m.current=X},[X]);let d=ce(null),C=Et(()=>{if(he||ne.claimBuyerIdentity||ve?.buyerIdentified!==!1||!e||!t)return;let a=`${K}|${e}|${t}`;d.current?.key!==a&&(d.current={key:a,claim:lo(new bo(K,{telemetry:!1}),e,t,{...i?{userId:i}:{},...g?{firstName:g}:{},...h?{lastName:h}:{}})});let P=d.current.claim;return async O=>{await P(O)}},[he,ne.claimBuyerIdentity,ve?.buyerIdentified,e,t,K,i,g,h]),L=he??ne.claimBuyerIdentity??C,te=qe??yn,V=Et(()=>Fd(Ge),[Ge]),b=Et(()=>{let a=V?.buttonsLayout??xd(St);return tt?{...a,...tt,cardButton:{...a.cardButton,...tt.cardButton},cardFormContainer:{...a.cardFormContainer,...tt.cardFormContainer},backButton:{...a.backButton,...tt.backButton},backButtonIcon:{...a.backButtonIcon,...tt.backButtonIcon},submitButton:{...a.submitButton,...tt.submitButton},title:{...a.title,...tt.title}}:a},[V,St,tt]),Z=je??V?.appearance,pt=Et(()=>Ns({appearance:Z,buttonsStyles:b,layout:Re}),[Z,b,Re]),qt=ne.inlineSessionPatchProcessing??!1,Be=(U??Wt)||qt,fe=K.replace(/\/+$/,""),D=Et(()=>li({userId:i,email:o,firstName:g,lastName:h,country:Ee,zip:ie},Bt),[i,o,g,h,Ee,ie,Bt]),q=[D.firstName,D.lastName].filter(a=>!!a?.trim()).join(" "),Fe=!ln(D.email?.trim()),De=ce(null);ze&&De.current===null&&(De.current=Fe);let kt=ze&&(De.current??Fe),He=Et(()=>au(ut,kt),[ut,kt]),Mn=He.empty||He.malformed,Xt=Et(()=>mt?mt.getRawProvider():null,[mt]),Yr=Et(()=>R?R.getRawProvider():null,[R]),_o=ot||100,Jr=ke.toLowerCase(),qa=Et(()=>Z?Pd(Z):null,[Z]),Xr=qa,rs=Et(()=>{let a=qa??{},P=a.rules??{};return{...a,rules:{...P,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...P[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...P[".AccordionItemContents"]??{}}}}},[qa]),os=Et(()=>({...Hs(ot,ve?.captureMethod),currency:Jr,...Xr?{appearance:Xr}:null}),[ot,Jr,ve?.captureMethod,Xr]),as=Et(()=>({mode:"payment",amount:_o,currency:Jr,captureMethod:"manual",setupFutureUsage:"off_session",...Xr?{appearance:Xr}:null}),[_o,Jr,Xr]),pe=Je(a=>{sr(a),ge?.(a)},[ge]),ja=ce(""),[is,Yl]=oe(!1),$a=Je(()=>{Yl(!0)},[]);ft(()=>{if(!ze||!kt||!L||!is||Mn||ja.current)return;let a=Dn({email:ln(D.email?.trim())?D.email?.trim():Nn.current.trim(),firstName:D.firstName?.trim(),lastName:D.lastName?.trim()});ja.current=JSON.stringify(a),Gt(P=>({...P,...a})),Promise.resolve(L(a)).catch(P=>{ja.current="",pe(P instanceof Error?P.message:"Failed to attach buyer details.")})},[ze,kt,L,is,Mn,D.email,D.firstName,D.lastName,pe]),ft(()=>{!ze||!ae||ae.setCardFieldOrder?.(lt??null,J==null&&!kt)},[ze,ae,lt,J,kt]),ft(()=>{(Ve==="expanding"||Ve==="collapsing"||Ve==="apm-expanding"||Ve==="apm-collapsing")&&pe(null)},[Ve,pe]);let ur=Je((a,P,O)=>{p?.(nn(a,P,O))},[p]),Zr=Je((a,P,O)=>{let Ne=O?.popupBlocked??br(P),j=nu(a,Ne),at=$r(O?.code)??Pr(P)??"external_payment_method_failed",Ze=new ir(j,"api_error",{code:"external_payment_method_failed",param:a});f(null),Re==="buttons"&&(tn("buttons"),cr(null)),pe(j),l?.(Ze),console.error("[FloPay] External payment method failed:",{method:a,code:at,popupBlocked:Ne})},[Re,l,pe]);ft(()=>{if(!ze||!e){En(null);return}let a=Fi(ve?.vault);if(a){En(a);return}if(!I){En(null);return}En(null);let P=!0;return new bo(fe).getVaultCapture(e,t).then(O=>{if(!P)return;let Ne=Fi(O);Ne?En(Ne):pe("Failed to load the secure card form.")}).catch(O=>{P&&pe(O instanceof Error?O.message:"Failed to load the secure card form.")}),()=>{P=!1}},[ze,I,E,e,ve?.vault,fe,t,pe]);let rr=ce({onComplete:s,onError:l,updateError:pe,emitDecline:ur,resolvedAccount:D,avsConfig:J,avsCheckProp:x,sessionId:e,nonce:t,baseUrl:fe,captureMethod:ve?.captureMethod,paymentId:ve?.paymentId,authorizationExpiresAt:ve?.authorizationExpiresAt,serverSideCardGateway:Ln});rr.current={onComplete:s,onError:l,updateError:pe,emitDecline:ur,resolvedAccount:D,avsConfig:J,avsCheckProp:x,sessionId:e,nonce:t,baseUrl:fe,captureMethod:ve?.captureMethod,paymentId:ve?.paymentId,authorizationExpiresAt:ve?.authorizationExpiresAt,serverSideCardGateway:Ln};let Ka=ce(!1),ss=Je(()=>{let a=rr.current,P=a.resolvedAccount.email?.trim(),O=ln(P)?P:Nn.current.trim();if(!ln(O))return null;let Ne=a.resolvedAccount.firstName?.trim(),j=a.resolvedAccount.lastName?.trim(),at=$t.current||a.resolvedAccount.country||"US",Ze=a.avsConfig?et(a.avsConfig.state,at):!1,mr=a.avsConfig?et(a.avsConfig.address_line_1,at):!1,Ye=a.avsConfig?et(a.avsConfig.postal_code,at):!1,_t=a.avsConfig?et(a.avsConfig.city,at):!1,yt=a.avsConfig?et(a.avsConfig.address_line_2,at):!1,Qe=mr&&!Ze&&Ye?fl(at,(gt.current??"").trim()):null,Fn=Ze?an.current:Qe;return{accountData:{userId:a.resolvedAccount.userId??"",email:O,...Ne?{firstName:Ne}:{},...j?{lastName:j}:{},...Ye&>.current?{zip:gt.current}:{},..._t&&It.current?{city:It.current}:{},...Fn?{state:Fn}:{},...mr&&un.current?{addressLine1:un.current}:{},...yt&&Ft.current?{addressLine2:Ft.current}:{},country:at},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:et(a.avsConfig.country,at),postal_code:Ye,address_line_1:mr,address_line_2:yt,city:_t,state:Ze}}:{}}},[]),ls=ce(me);ls.current=me,ft(()=>{me||te!==Cl||rr.current.updateError(null)},[me,te]),ft(()=>{!ze||!ae||ae.setSubmitGate?.(Br||me||Mn||ct)},[ze,ae,Br,me,Mn,ct]),ft(()=>{if(!ze||!ae)return;Ka.current=!1;let a=null,P=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,Ce.current="idle",f(null)},400)},O=ae.on("submitting",()=>{wr(!0),B.current&&clearTimeout(B.current),Ce.current="validation-window",B.current=setTimeout(()=>{B.current=null,Ce.current==="validation-window"&&(Ce.current="processing")},Vd),f("processing");let Ye=rr.current;if(!Ye.sessionId||!Ye.nonce)return;let _t=ss();if(!_t){Ye.updateError("Enter a valid email address."),Ce.current="idle",f(null);return}new bo(Ye.baseUrl).patchAccountSnapshot(Ye.sessionId,Ye.nonce,_t,{telemetryMode:"best_effort"}).catch(yt=>{if(!Hd(yt))return;let Qe=yt instanceof Error?yt.message:"Please check your billing address and try again.";Ye.updateError(Qe),Ce.current="idle",f(null),Ye.onError?.(yt instanceof ir?yt:new ir(Qe,"api_error"))})}),Ne=ae.on("complete",async Ye=>{if(vo(Ye.sessionId??rr.current.sessionId),Ce.current="terminal",ye(!1),f("success"),await new Promise(Fn=>setTimeout(Fn,600)),Ka.current)return;Ka.current=!0;let _t=rr.current,yt=Ei(_t)||Ye.outcome==="authorized",Qe=_t.serverSideCardGateway?{}:{paymentIntentId:Ye.intentId};rr.current.onComplete?.(yt?{status:"authorized",...Qe,paymentId:Ye.paymentId??_t.paymentId,sessionId:Ye.sessionId??_t.sessionId,authorizationExpiresAt:Ye.authorizationExpiresAt??_t.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Qe,checkoutMethod:"card"})}),j=ae.on("decline",Ye=>{let _t=rr.current,yt=Ye.message??"Your payment was declined. Please try another card or contact your bank.";Ce.current="terminal",ye(!1),_t.updateError(yt),f("error");let Qe=Ye.failureOutcome??Ed(Ye.declineReason)??"authorization_declined";_t.emitDecline("card",yt,{code:Qe,declineCode:Qe}),P()}),at=ae.on("error",Ye=>{let _t=rr.current,yt=Ye.message??"There was a problem processing your payment. Please try again.";Ce.current="terminal",ye(!1),_t.updateError(yt),f("error"),_t.onError?.(new ir(yt,"api_error",{code:Ye.failureOutcome??"capture_failed"})),P()}),Ze=ae.on("challenge_dismissed",()=>{B.current&&(clearTimeout(B.current),B.current=null),Ce.current="processing",ye(!0),f(null)}),mr=ae.on("blocked",()=>{if(z.current){rr.current.updateError(Wd);return}if(!ls.current){wr(!0);return}$a(),rr.current.updateError(Cl)});return()=>{a&&(clearTimeout(a),a=null),B.current&&(clearTimeout(B.current),B.current=null),Ce.current="idle",ye(!1),f(null),O(),Ne(),j(),at(),Ze(),mr()}},[ze,ae,$a,ss]);let pr=!!_e?.clientId,Ro=Array.isArray(Y),oa=Ro&&Y.length>0,Jl=Ro&&Y.includes("paypal"),{expressMethods:aa,paymentElementMethods:Eo}=Et(()=>Td(Y,{excludePaypal:pr}),[Y,pr]),cs=pr||!!R,Xl=Et(()=>cs?aa.filter(a=>a!=="paypal"):aa,[aa,cs]),Zl=Et(()=>{let a=[];return Le&&a.push("apple_pay"),Se&&a.push("google_pay"),a},[Le,Se]),Qr=Ro?Xl:Zl,Ql=W&&Qr.length>0,Va=hn?N:Ee,ia=Et(()=>{let a=Va?.trim().toUpperCase();return a?de?Eo.filter(P=>{let O=de[P];return!O||O.length===0||O.includes(a)}):Sd(Eo,Va):Eo},[Eo,Va,de]),Wa=Et(()=>({mode:"payment",amount:_o,currency:Jr,paymentMethodCreation:"manual",appearance:rs}),[_o,Jr,rs]),[ds,us]=oe("loading"),[ps,ms]=oe("loading"),[ys,fs]=oe("loading"),[ec,Ha]=oe(!1),[gs,Ga]=oe("loading"),[Ya,tc]=oe();ft(()=>{tc(va())},[]);let sa=Ya?.inAppBrowser,la=Ya?Pa(Ya,_e?.approvalPresentation,xe??(le?"subscription":"order")):"popup",hs=S&&(pr||(Ro?Jl:sa===!1)),vs=W&&Ql,To=(!nt||!!ne.waitForDataAttachment)&&hs&&pr,Ps=gs==="retrying"||gs==="exhausted",Ao=!nt&&hs&&!!Yr&&(!pr||Ps),eo=!nt&&vs&&!!Xt,Mo=!nt&&W&&oa&&ia.length>0&&!!Xt,nc=To&&!Ps?ec:Ao&&_l(ds),rc=eo&&_l(ps),oc=Mo&&ys!=="load_error",bs=a=>a==="loading"||a==="ready",Cs=To||Ao&&bs(ds)||eo&&bs(ps)||Mo&&ys!=="load_error",ca=ce(!1);ft(()=>{if(!ca.current){if(!W&&!S){ca.current=!0;let a=new ir("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(a),pe(a.message)}else if(!W&&S&&!pr&&!Yr){ca.current=!0;let a=new ir("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(a),pe(a.message)}else if(sa!==void 0&&!nt&&!Yt&&!Cs){ca.current=!0;let a=new ir("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});l?.(a),pe(a.message)}}},[W,S,pr,Yr,sa,nt,Yt,Cs,l,pe]);let Ss=ce(!1);ft(()=>{if(Ss.current||!oa)return;let a=[];Le!==!0&&a.push("showApplePay"),Se!==!0&&a.push("showGooglePay"),a.length!==0&&(Ss.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.`))},[oa,Le,Se]);let ws=Je((a,P)=>ne.applyInlineSessionPatch?ne.applyInlineSessionPatch(a).then(O=>({error:null,sessionId:O.sessionId||e,nonce:O.session?.clientSecret||t})).catch(O=>{let Ne=kl(P,O);return pe(Ne.message),l?.(Ne),{error:Ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ne.applyInlineSessionPatch,t,l,e,pe]),or=Je(async a=>{if(a!=="card"&&nt&&await ne.waitForDataAttachment?.(),!Ie)return{proceed:!0};try{let P=await Ie({method:a,sessionId:e||void 0,createSession:ne.inlineSessionDraft});if(P===!1)return{proceed:!1};if(P&&typeof P=="object"){P.account&&Gt(Ne=>({...Ne??{},...P.account}));let O=await ws(P,a);return O.error?{proceed:!1,accountPatch:P.account}:{proceed:!0,accountPatch:P.account,sessionId:O.sessionId,nonce:O.nonce}}return{proceed:!0}}catch(P){let O=kl(a,P);return pe(O.message),l?.(O),{proceed:!1}}},[ws,ne.inlineSessionDraft,ne.waitForDataAttachment,nt,Ie,l,e,pe]),Is=Je(async(a,P)=>{if(G.current)return;G.current=!0,wt(!0),f("processing"),pe(null);let O=P?.sessionId??e,Ne=P?.nonce??t,j=li(D,P?.accountPatch),at=P?.completionPaymentMethodId??jo(a),Ze=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,mr=Zd(a),Ye=()=>{u?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:mr})};try{let yt=await new bo(fe).processPayment(j.userId??"",{sessionId:O,nonce:Ne,paymentMethodCategory:P?.paymentMethodCategory??eu(a),tokenizedData:Ze,accountData:{...P?.accountPatch,userId:j.userId??"",email:j.email??"",firstName:j.firstName||void 0,lastName:j.lastName||void 0,...J?(()=>{let ht=$t.current,Wn=et(J.state,ht),Sn=et(J.address_line_1,ht),Zt=et(J.postal_code,ht),zr=Sn&&!Wn&&Zt?fl(ht,(gt.current??"").trim()):null,Lo=Wn?an.current:zr;return{country:ht,...Zt&>.current?{zip:gt.current}:{},...et(J.city,ht)&&It.current?{city:It.current}:{},...Lo?{state:Lo}:{},...Sn&&un.current?{addressLine1:un.current}:{},...et(J.address_line_2,ht)&&Ft.current?{addressLine2:Ft.current}:{}}})():{}},chv:y,avsCheck:x??!1,checkoutType:Q,checkoutLayout:Me,avsConfig:J?{country:et(J.country,$t.current),postal_code:et(J.postal_code,$t.current),address_line_1:et(J.address_line_1,$t.current),address_line_2:et(J.address_line_2,$t.current),city:et(J.city,$t.current),state:et(J.state,$t.current)}:void 0});if(yt.ok){let ht=yt.status===204?null:await yt.json().catch(()=>null),Wn=Ei(ve)||ht?.status==="authorized";vo(O),f("success"),F(null),await new Promise(zr=>setTimeout(zr,600));let Sn;typeof ht?.paymentId=="string"?Sn=ht.paymentId:ve?.paymentId&&(Sn=ve.paymentId);let Zt;typeof ht?.authorizationExpiresAt=="string"?Zt=ht.authorizationExpiresAt:ve?.authorizationExpiresAt&&(Zt=ve.authorizationExpiresAt),s?.(Wn?{status:"authorized",...Sn===void 0?{}:{paymentId:Sn},sessionId:typeof ht?.sessionId=="string"?ht.sessionId:O,...Zt===void 0?{}:{authorizationExpiresAt:Zt},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:at,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:at,checkoutMethod:a.isPaypal?"paypal":"card"});return}let Qe=await yt.json().catch(()=>null);if(Qe?.type==="paypal_redirect_required"){let ht=Qe.threeDSecureToken,Wn=Qe.paymentMethodId||a.id||"";if(!mt||!ht){f("error"),pe("PayPal authorization required but no token provided.");return}try{let Sn=R?.getRawProvider();if(!Sn){pe("PayPal is not available.");return}let Zt={return_url:window.location.href};Wn&&(Zt.payment_method=Wn);let{error:zr}=await Sn.confirmPayment({clientSecret:ht,confirmParams:Zt,redirect:"if_required"});if(zr){f("error");let Lo=zr.message??"PayPal payment failed.";pe(Lo),ur("paypal",Lo,{code:zr.code})}}catch(Sn){f("error"),pe(Sn instanceof Error?Sn.message:"PayPal authorization failed.")}return}if(Qe?.type==="paypal_direct_required"){let ht=Qe.orderId;if(!ht){f("error"),pe("PayPal retry required but no order id provided.");return}let Wn=m.current?.attempts??0;if(Wn>=2){f("error"),pe("PayPal payment could not be completed after multiple attempts."),ur("paypal","paypal_direct_required retry limit exceeded");return}Ha(!1),Ga("loading"),F({orderId:ht,attempts:Wn+1}),f(null);return}Cd(yt.status,Qe)||Ye(),f("error");let Fn=Qe?.message??"Payment failed. Please try again.";pe(Fn),ur(a.isPaypal?"paypal":"card",Fn,{code:Qe?.code??Qe?.gatewayErrorCode,declineCode:Qe?.declineCode??Qe?.gatewayDeclineReason}),await new Promise(ht=>setTimeout(ht,400))}catch(_t){Bl(_t)||Ye(),f("error"),pe(_t instanceof Error?_t.message:"An unexpected error occurred"),await new Promise(yt=>setTimeout(yt,400))}finally{wt(!1),f(null),G.current=!1}},[fe,e,t,D,J,x,Q,Me,y,mt,R,ve,s,pe,ur,u]),xn=Je((a,P)=>{v?v(a):Is(a,P)},[v,Is]),xo=`${Ml}:${e}`;ft(()=>{if(typeof window>"u")return;let a=localStorage.getItem(xo);if(!a)return;let P;try{P=JSON.parse(a)}catch{localStorage.removeItem(xo);return}if(!P||typeof P.createdAt!="number"||Date.now()-P.createdAt<0||Date.now()-P.createdAt>xl||typeof P.paymentMethodId!="string"||typeof P.providerIntentId!="string"||typeof P.paymentMethodType!="string"||P.sessionId!==e||!t||P.nonce!==t||!Qr.includes(P.paymentMethodType)){localStorage.removeItem(xo);return}localStorage.removeItem(xo),xn({id:P.paymentMethodId,type:"card",threeDSecureActionResultTokenId:P.providerIntentId,gateway:"stripe",paymentMethodType:P.paymentMethodType},{...P.accountPatch?{accountPatch:P.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[xn,t,e,xo,Qr]);let ks=ce(!1);ft(()=>{if(typeof window>"u"||ks.current)return;let a=new URLSearchParams(window.location.search),P=a.get("payment_intent"),O=a.get("payment_intent_client_secret"),Ne=a.get("redirect_status");if(!P||!O||!mt)return;let j=mt.getRawProvider();if(!j)return;let at=Qe=>{let Fn=localStorage.getItem(Qe);if(!Fn)return null;try{return JSON.parse(Fn)}catch{return localStorage.removeItem(Qe),null}},Ze=at(fr)??at(vl),mr;if(Ze?.clientSecret){if(Ze.clientSecret!==O)return;mr={...Ze.accountPatch?{accountPatch:Ze.accountPatch}:{},...Ze.sessionId?{sessionId:Ze.sessionId}:{},...Ze.nonce?{nonce:Ze.nonce}:{}}}else if(Ze?.sessionId&&Ze.sessionId!==e)return;ks.current=!0,localStorage.removeItem(fr),localStorage.removeItem(vl);let Ye=new URL(window.location.href);Ye.searchParams.delete("payment_intent"),Ye.searchParams.delete("payment_intent_client_secret"),Ye.searchParams.delete("redirect_status"),window.history.replaceState({},"",Ye.toString());let _t=Ze?.paymentMethodType??Ze?.tokenType??"card",yt="card";(async()=>{if(Ne==="failed"){let Zt="Payment was declined. Please try again.";pe(Zt),ur(yt,Zt);return}let{paymentIntent:Qe,error:Fn}=await j.retrievePaymentIntent(O);if(Fn){let Zt=Fn.message??"Failed to retrieve payment status.";pe(Zt),ur(yt,Zt,{code:Fn.code});return}let ht=Qe?.status,Wn=qo(ht);if(!Qe||!Wn){let Zt=ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";pe(Zt),ur(yt,Zt,{code:ht??"missing_payment_intent"});return}let Sn=typeof Qe.payment_method=="string"?Qe.payment_method:Qe.payment_method?.id;xn({id:Sn??Ze?.paymentMethodId??Ze?.tokenId??Qe.id,type:"card",threeDSecureActionResultTokenId:Qe.id,gateway:Ze?.gateway??"stripe",paymentMethodType:_t},mr)})()},[e,xn,mt,pe,ur]);let Ja=Je(a=>{a.preventDefault()},[]);if(!(ze||mt!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Bo=Re==="buttons",Bn=Z?.variables,ac=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Xa=Bn?.colorBackground,ic=Xa&&!ac.has(Xa)?Xa:void 0,Fo=b.cardInputBorder??(Bo?"#e5e7eb":"#A4A4FF"),_s=Bn?.colorDanger??"#dc2626",Lt=a=>Gr[a]&&(vr[a]||kn),da=Mn&&(Kt||kn),Vn=a=>a?_s:Fo,ua=(bn.malformed||bn.empty)&&(lr||kn),sc=Vn(ua),Za=b.cardFormContainer?.backgroundColor??ic??(Bo?"white":"#EDEDFF"),to=b.cardInputBackground??Bn?.colorBackground??"white",Qa=oo(ue),Rs=oo(we),no=b.nameInput,Es=b.cardInputFontSize??iu(no?.fontSize)??Bn?.fontSizeBase??"16px",Ts=typeof no?.fontFamily=="string"?no.fontFamily:Bn?.fontFamily??"Poppins, sans-serif",As=Ds(no?.fontWeight)??400,lc=b.cardInputColor??(typeof no?.color=="string"?no.color:void 0)??Bn?.colorText??"#262833",cc=b.cardInputPlaceholderColor??"#9ca3af",jt=Bn?.borderRadius??"8px",Lr=Bn?.borderRadius??b.cardButton?.borderRadius??jt,Or=Bn?.colorPrimary??"#4A49FF",dc=Bn?.colorPrimaryHover??zo(Or,.12),ei=Bn?.colorText??"#262833",ti={fontSize:Es,fontFamily:Ts,fontWeight:As,color:lc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Do={marginTop:"0.375rem",...ti,fontSize:"0.75rem",lineHeight:1.4,color:_s},uc={"--flopay-input-placeholder-color":cc,"--flopay-input-font-size":Es,"--flopay-input-font-family":Ts,"--flopay-input-font-weight":String(As)},No=b.cardFormContainer??{},ni=No.padding??(Bo?"0":"1rem"),ri=No.borderRadius??jt,pc=ae&&tr?c(oi,{capture:ae,html:tr.html,messageToken:tr.messageToken,expectedOrigin:tr.expectedOrigin,theme:pt,submitLabel:M,onReady:()=>{if(!kt&&!J||typeof document>"u")return;let a=()=>{let O=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(O){Rn.current=!0;try{O.focus()}finally{Rn.current=!1}}};er.current||a()},onError:a=>pe(a),onValidation:a=>{let P=Ce.current;(P==="idle"||P==="validation-window")&&(pe(a),a&&Ce.current==="validation-window"&&(B.current&&(clearTimeout(B.current),B.current=null),Ce.current="idle",f(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"}),Ms=Ue("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&dr()},style:{backgroundColor:Za,borderRadius:ri,...No,padding:ni,...uc,display:"flex",flexDirection:"column"},children:[c("style",{children:`
|
|
25
|
+
`,Ya=44,da=180,zl=`flopay-card-enter ${da}ms cubic-bezier(0, 0, 0.2, 1) both`,Ul=`flopay-card-exit ${da}ms cubic-bezier(0.4, 0, 0.2, 1) both`,yu=`flopay-buttons-enter ${da}ms cubic-bezier(0, 0, 0.2, 1) both`,mu=`flopay-buttons-exit ${da}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function fu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function is(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 gu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function hu(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 Qi={width:"100%",minHeight:Ya,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 vu(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ql(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function es(e){return e==="paypal"?"PayPal":eo(e)}function bu(e){let t=Ud(e);return`Enter a valid ${Zi(e)}${t?` (e.g. ${t})`:""}`}function Pu(e,t,n){let r=$d(e),o=t.trim(),i=n&&r,s=i&&!o,l=i&&!!o&&!Kd(e,o);return{visible:n,supported:r,required:i,empty:s,malformed:l}}function Cu(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!fn(n);return{required:t,empty:r,malformed:o,value:n}}function jl(e,t){return t instanceof pr?t:new pr(t instanceof Error?t.message:`${vu(e)} before-click hook failed.`,"validation_error")}function Xi(){return d("style",{children:pu})}function wu(e){return typeof e=="number"?`${e}px`:e}function Zl(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Ql({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:Oe("div",{style:{position:"relative",minHeight:44},children:[d("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),d("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function $l(e){return e!=="unavailable"&&e!=="load_error"}function ss(e){return d(ku,{...e})}function Kl({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:y,onTechnicalFailure:f,runBeforeButtonClick:b,billingName:g,onBuyerIdentityReady:M,onLoadStateChange:R,placeholderBorderRadius:C,popupCapabilityOwner:v,externalTelemetryContext:q}){let Re=Or(),{emitInstrument:I}=To(or),G=rs(),Y=ns(),re=Et(()=>$i(mn(Re),q),[q,Re]),[ve,Le]=ce("loading");Ct(()=>{R?.(ve)},[ve,R]);let[Ce,$e]=ce(!1),vt=!fn(n?.trim())||!g?.trim(),{request:Ke,collect:Ne,finish:Me}=ho(),wt=de(!1),fe=de(null),ut=de(null),[O,Ae]=ce(0),[yt,Be]=ce(!1),it=de(!1),N=de(new Map),{startAttempt:ue,finishAttempt:ge,invalidateAttempt:K,isAttemptInvalidated:Ge,isAttemptCurrent:Ve,generationRef:L}=na((Q,oe,Fe)=>{f?.(Q,oe,{...Fe,popupBlocked:Fe?.popupBlocked??Dr(oe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:"popup",terminalReason:"overlay_timeout"}),Be(!0),Ae(Je=>Je+1)},{onHandoffObserved:()=>{v.markAvailable(),re?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal",attempt:L.current})}});Ct(()=>{yt&&ut.current?.focus()},[yt,O]);let st=tt(()=>{Ae(Q=>Q+1)},[]),Ye=tt((Q,oe,Fe)=>{K(Fe),f?.("paypal",Q,{code:oe,popupBlocked:Dr(Q),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:"popup"}),Be(!0),st()},[K,f,st]),He=tt(()=>{window.setTimeout(()=>{(fe.current?.querySelector("iframe")??fe.current)?.focus()},0)},[]);Ct(()=>{it.current&&(it.current=!1,He())},[He,O]);let Ee=tt(()=>{Be(!1),i?.(null),He()},[He,i]);Ct(()=>{if(!G||wt.current)return;let Q=new URLSearchParams(window.location.search),oe=Q.get("payment_intent"),Fe=Q.get("payment_intent_client_secret"),Je=Q.get("redirect_status");if(!oe||!Fe)return;wt.current=!0;let lt;try{let pt=localStorage.getItem(ca);if(pt){let Xe=JSON.parse(pt);Xe.clientSecret===Fe&&(lt={...Xe.accountPatch?{accountPatch:Xe.accountPatch}:{},...Xe.sessionId?{sessionId:Xe.sessionId}:{},...Xe.nonce?{nonce:Xe.nonce}:{}})}}catch{}try{localStorage.removeItem(ca)}catch{}let z=new URL(window.location.href);z.searchParams.delete("payment_intent"),z.searchParams.delete("payment_intent_client_secret"),z.searchParams.delete("redirect_status"),window.history.replaceState({},"",z.toString()),(async()=>{try{if($e(!0),Je==="failed"){let _="PayPal payment was declined. Please try again.";i?.(_),y?.(dn("paypal",_));return}let{paymentIntent:pt,error:Xe}=await G.retrievePaymentIntent(Fe);if(Xe){i?.(Xe.message??"Failed to retrieve PayPal payment status.");return}if(pt&&(pt.status==="requires_capture"||pt.status==="succeeded")){let _=typeof pt.payment_method=="string"?pt.payment_method:pt.payment_method?.id;o({id:_??pt.id,type:"card",threeDSecureActionResultTokenId:pt.id,isPaypal:!0},lt)}else{let _="PayPal payment was not completed. Please try again.";i?.(_),y?.(dn("paypal",_))}}catch(pt){i?.(pt instanceof Error?pt.message:"Failed to complete PayPal payment.")}finally{$e(!1)}})()},[G,o,i,y]);let le=tt(async Q=>{if(s||Ce){Q.reject();return}let oe=b?await b("paypal"):{proceed:!0};if(!oe.proceed){N.current.delete(O),Q.reject();return}let Fe=ue("paypal");N.current.set(O,{generation:Fe,accountPatch:oe.accountPatch,sessionId:oe.sessionId,nonce:oe.nonce}),Be(!1),re?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal",attempt:Fe}),l?.("paypal"),Q.resolve()},[s,l,re,b,ue,Ce,O]),mt=tt(async Q=>{if(!G||!Y)return;let oe=N.current.get(O);if(oe&&!Ve(oe.generation)){N.current.delete(O);return}if(!oe&&Ge()||oe&&!ge(oe.generation))return;oe||ge();let Fe=oe??null;if(N.current.delete(O),!Fe&&b){let _=await b("paypal");if(!_.proceed){Q.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Fe={accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}}let Je=Fe?.sessionId??e,lt=Fe?.nonce??t,z=await uu({event:Q,prepared:Fe,email:n,billingName:g,methodLabel:"PayPal",collect:Ne});if(!z){Q.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let pt=z.email,Xe={...Fe?.accountPatch,...On(z,!0)};try{if($e(!0),i?.(null),!Je||!fn(pt))throw new Error("Missing sessionId or email for PayPal payment");await M?.(z);let _=G.createPaymentMethod,{error:ct,paymentMethod:Jt}=await _({type:"paypal"});if(ct){Ye(ct,"stripe_paypal_create_payment_method_failed",oe?.generation),Q.paymentFailed({reason:"fail"});return}let xe=await Ja(r,I,Je,lt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Jt?.id??null,intentKind:"payment"});if(xe.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let un=xe.clientSecret,c={return_url:window.location.href};if(Jt?.id&&(c.payment_method=Jt.id),typeof window<"u")try{localStorage.setItem(ca,JSON.stringify({clientSecret:un,sessionId:Je,nonce:lt,accountPatch:Xe}))}catch{}let{error:w,paymentIntent:ne}=await G.confirmPayment({clientSecret:un,confirmParams:c,redirect:"if_required"});if(w){if(typeof window<"u")try{localStorage.removeItem(ca)}catch{}if(Zo(w)){let $=w.message??"Your payment was declined.";i?.($),y?.(dn("paypal",$,{code:Sr(w),declineCode:bo(w)})),await Xa({billingApiUrl:r,sessionId:Je,nonce:lt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Sr(w)??"provider_declined"}})}else Ye(w,"stripe_paypal_confirm_failed",oe?.generation);return}if(typeof window<"u")try{localStorage.removeItem(ca)}catch{}let k=typeof ne?.payment_method=="string"?ne.payment_method:ne?.payment_method?.id;o({id:k??ne?.id,type:"card",threeDSecureActionResultTokenId:ne?.id,isPaypal:!0},{accountPatch:Xe,paymentMethodCategory:"paypal",sessionId:Je,nonce:lt});return}catch(_){Ye(_,"stripe_paypal_failed",oe?.generation)}finally{$e(!1)}},[G,Y,e,t,n,g,Ne,M,r,I,o,i,y,b,Ye,ge,Ve,Ge,O]);return Oe(Qr,{children:[d(Ql,{state:ve,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:Oe("div",{ref:fe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[yt&&d("button",{ref:ut,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ee,style:Qi,children:"Try PayPal again"}),Ke&&d(vo,{identity:Ke.identity,methodLabel:Ke.methodLabel,onComplete:Me,onCancel:()=>Me(null)},Ke.id),d("div",{style:{display:Ke?"none":void 0},children:d(Wl,{onReady:Q=>Le(Zl(Q,["paypal"])),onLoadError:()=>{Le("load_error"),as(re,"paypal","paypal","provider_error")},onClick:le,onConfirm:mt,onCancel:()=>{let Q=N.current.get(O);N.current.delete(O),re?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"cancelled",...Q?{attempt:Q.generation}:{}}),K(Q?.generation),Be(!1),it.current=!0,st()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:vt,emailRequired:vt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},O)})]})}),Ce&&d(wr,{status:"processing"})]})}function Vl({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:y,onDecline:f,onTechnicalFailure:b,runBeforeButtonClick:g,billingName:M,onBuyerIdentityReady:R,onLoadStateChange:C,placeholderBorderRadius:v,popupCapabilityOwner:q,externalTelemetryContext:Re}){let I=Or(),{emitInstrument:G}=To(or),Y=rs(),re=ns(),ve=Et(()=>$i(mn(I),Re),[Re,I]),[Le,Ce]=ce("loading");Ct(()=>{C?.(Le)},[Le,C]);let[$e,vt]=ce(!1),Ke=de(!fn(n?.trim())||!M?.trim()).current,{request:Ne,collect:Me,finish:wt}=ho(),fe=de(null),ut=de(null),[O,Ae]=ce(0),[yt,Be]=ce(!1),[it,N]=ce(()=>Ga(e,t)?"blocked":"idle"),[ue,ge]=ce("google_pay"),K=de(null),Ge=de(!0),Ve=de(!1),L=de("google_pay"),st=de("google_pay"),Ye=de(null),He=de(null),Ee=de(new Set);Ct(()=>(Ge.current=!0,()=>{Ge.current=!1;for(let c of Ee.current)window.clearTimeout(c);Ee.current.clear()}),[]);let le=de(new Map),{startAttempt:mt,finishAttempt:Q,invalidateAttempt:oe,isAttemptInvalidated:Fe,isAttemptCurrent:Je,generationRef:lt}=na((c,w,ne)=>{b?.(c,w,{...ne,popupBlocked:ne?.popupBlocked??Dr(w),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ge(c),Be(!0),Ae(k=>k+1)},{onHandoffObserved:c=>{q.markAvailable(),ve?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:lt.current,...c==="apple_pay"||c==="google_pay"?{walletType:c}:{}})}});Ct(()=>{yt&&ut.current?.focus()},[yt,O]);let z=tt(()=>{Ae(c=>c+1)},[]),pt=tt((c,w,ne,k,$=!1)=>{oe(k),b?.(c,w,{code:ne,popupBlocked:Dr(w),telemetryReported:$,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ge(c),Be(!0),z()},[oe,b,z]),Xe=tt(()=>{window.setTimeout(()=>{(fe.current?.querySelector("iframe")??fe.current)?.focus()},0)},[]);Ct(()=>{Ve.current&&(Ve.current=!1,Xe())},[Xe,O]);let _=tt(()=>{Be(!1),l?.(null),Xe()},[Xe,l]),ct=tt(()=>{K.current?.()},[]);Ct(()=>{let c=Ga(e,t);if(!c)return;let w=!1,ne=!1,k=async()=>{if(!ne){ne=!0,w||N("checking");try{let $=await Nl(Y,c.clientSecret,Ee.current);if(w)return;let ft=Yi($,c.providerObjectId,Hi(c.clientSecret));if(ft.kind==="confirmed"){if(!Ol(e,t,c.clientSecret))return;K.current=null,N("idle"),s({id:ft.paymentMethodId,type:"card",threeDSecureActionResultTokenId:ft.intentId},{...c.accountPatch?{accountPatch:c.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(ft.kind==="terminal"){Gi(e,t,c.clientSecret),K.current=null,N("idle"),ge(c.paymentMethodType),Be(!0),z();return}N("blocked")}catch{w||N("blocked")}finally{ne=!1}}};return K.current=k,N("blocked"),()=>{w=!0,K.current===k&&(K.current=null)}},[t,s,z,e,Y]);let Jt=tt(async c=>{let w=!1,ne=De=>{w||(w=!0,c.paymentFailed({reason:"fail",...De?{message:De}:{}}))};if(!Y||!re){ne();return}let k=le.current.get(O);if(k&&!Je(k.generation)){le.current.delete(O),ne();return}if(!k&&Fe()){ne();return}if(k&&!Q(k.generation)){ne();return}k||Q();let $=c.expressPaymentType??k?.method??L.current,ft=k??null,ze=ql($),Ue;$==="apple_pay"?Ue="apple_pay":$==="google_pay"&&(Ue="google_pay");let xt=k?.generation??lt.current,ee=ve,pn=ee?.now()??globalThis.performance?.now()??Date.now(),We=new AbortController,Dt=!1,Rn=!1,Kt=null,Te=e,Ut="processing",gn="other",hn="provider_runtime",kn,Nn=new Promise((De,we)=>{kn=we}),vn=window.setTimeout(()=>{Dt=!0,We.abort(),kn(Ha)},nu),Vt=async(De,we,Ln)=>{Ut=De,gn=we,hn=we==="intent_create"||we==="session_claim"?"transport_error":"provider_runtime";let St=ee?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Ln,Nn])}finally{let bn=ee?.now()??globalThis.performance?.now()??Date.now();ee?.performance({stage:De,durationMs:Math.max(0,bn-St),durationMode:"machine",requestCategory:we,paymentMethodCategory:"wallet",provider:"stripe",...Dt?{statusClass:"timeout"}:{}})}};try{if(vt(!0),l?.(null),!ft&&g){let A=await Vt("processing","other",g(ze));if(!A.proceed){ne();return}ft={accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}}let De=ft?.sessionId??e;Te=De;let we=ft?.nonce??t,Ln=Ye.current??ft?.accountPatch,St=Xl({event:c,fallbackEmail:Ln?.email??n,fallbackName:[Ln?.firstName,Ln?.lastName].join(" ").trim()||M});if(!fn(St.email)){ne("Buyer details are required."),Me(es($),St).then(A=>{A&&(Ye.current=A)});return}Ye.current=null;let bn={...ft?.accountPatch,...On(St,!0)};await Vt("processing","session_claim",Promise.resolve(R?.(St)));let{error:En}=await Vt("tokenization","provider_sdk",re.submit());if(En){ne(),pt($,En,"stripe_wallet_submit_failed",k?.generation);return}if(!De)throw new Error("Missing sessionId or email for payment.");let Hn={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:$,paymentMethodId:null,intentKind:o},Ht=JSON.stringify({sessionId:De,nonce:we??"",request:Hn}),Xt=He.current,ln=Xt?.retryIdentity===Ht?Xt.authorizationAttemptId:Wd();He.current={authorizationAttemptId:ln,retryIdentity:Ht};let kt=await Vt("processing","intent_create",Ja(r,G,De,we??"",{...Hn,authorizationAttemptId:ln},{signal:We.signal}));if(kt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Mt=kt.clientSecret,yn=au({createdAt:Date.now(),sessionId:De,...we?{nonce:we}:{},clientSecret:Mt,providerObjectId:kt.providerObjectId,paymentMethodType:$,accountPatch:bn});window.clearTimeout(vn),Rn=!0,ee?.performance({stage:"callback",durationMs:Math.max(0,(ee?.now()??globalThis.performance?.now()??Date.now())-pn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Zt=ee?.now()??globalThis.performance?.now()??Date.now(),qt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Ue?{walletType:Ue}:{},attempt:xt},Wt=!1,Tt=null;ee?.log({name:"payment.provider_confirmation.started",...qt}),Kt=window.setTimeout(()=>{Kt!==null&&Ee.current.delete(Kt),Wt=!0;let A=ee?.now()??globalThis.performance?.now()??Date.now();ee?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...qt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,A-Zt),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),ee?.flush?.().catch(()=>{}),Tt?.()},ru),Ee.current.add(Kt);let X=(A,gt)=>{Kt!==null&&(window.clearTimeout(Kt),Ee.current.delete(Kt),Kt=null);let Ze=ee?.now()??globalThis.performance?.now()??Date.now(),x=Math.max(0,Ze-Zt),qe=A;Wt&&(A==="resolved"?qe="resolved_late":A==="returned_error"?qe="returned_error_late":qe="rejected_late");let te=gt??(A==="resolved"?"approved":"provider_error");return ee?.log({name:"payment.provider_confirmation.returned",...qt,operationOutcome:qe,terminalReason:te}),ee?.performance({...qt,durationMs:x,durationMode:"buyer",operationOutcome:qe,terminalReason:te}),{durationMs:x,operationOutcome:qe,terminalReason:te}},Qt=!1,en=!1,ir=A=>{if(!A||typeof A!="object")return null;let gt=A;if(gt.error)return null;let Ze=gt.setupIntent??gt.paymentIntent,x=Yi(Ze??null,void 0,!!gt.setupIntent);return x.kind==="confirmed"?x:null},mr=A=>{if(Qt||k&<.current!==k.generation)return;let gt=ir(A);if(!gt)return;if(yn&&!Ol(De,we,Mt)){Qt=!0;return}let{intentId:Ze,paymentMethodId:x}=gt;Qt=!0,en=!0,He.current=null,K.current=null,Ge.current&&(N("idle"),vt(!1));let qe=`${Gl}:${De}`;if(typeof window<"u")try{localStorage.setItem(qe,JSON.stringify({createdAt:Date.now(),sessionId:De,nonce:we,accountPatch:bn,paymentMethodId:x,providerIntentId:Ze,paymentMethodType:$}))}catch{}try{s({id:x,type:"card",threeDSecureActionResultTokenId:Ze},{accountPatch:bn,paymentMethodCategory:"wallet",sessionId:De,nonce:we})}finally{if(typeof window<"u")try{localStorage.removeItem(qe)}catch{}}},Wn=!1;Tt=async()=>{if(!(Wn||Qt||en)){Wn=!0,Ge.current&&N("checking");try{let A=await Nl(Y,Mt,Ee.current);if(Qt||en)return;let gt=Hi(Mt),Ze=Yi(A,kt.providerObjectId,gt);if(Ze.kind==="confirmed"){mr(gt?{setupIntent:A}:{paymentIntent:A});return}if(Ze.kind==="terminal"){if(en=!0,Gi(De,we,Mt),He.current=null,K.current=null,!Ge.current)return;N("idle"),ne(),pt($,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",k?.generation,!0);return}Ge.current&&!en&&(N("blocked"),vt(!1))}catch{Ge.current&&!en&&(N("blocked"),vt(!1))}finally{Wn=!1}}},K.current=Tt;let Gt,sr;try{let A=await(Hi(Mt)?Y.confirmSetup({elements:re,clientSecret:Mt,redirect:"if_required"}):Y.confirmPayment({elements:re,clientSecret:Mt,redirect:"if_required"}));if(!A||typeof A!="object"||(Gt=A,!Gt.error&&!ir(Gt)))throw Wi;sr=X(Gt.error?"returned_error":"resolved",Gt.error&&Zo(Gt.error)?"provider_declined":void 0)}catch(A){let gt=A===Wi,Ze=X(gt?"returned_error":"rejected");if(ee?.error({...gt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:ki(A),...qt,operationOutcome:Ze.operationOutcome,durationMs:Ze.durationMs,statusClass:"unknown",terminalReason:Ze.terminalReason}),!Ge.current||Qt)return;await Tt?.();return}let jt=Gt.error;if(jt){if(!Ge.current||Qt)return;if(Zo(jt)){en=!0,Gi(De,we,Mt),He.current=null,K.current=null,N("idle");let A=jt.message??"Your payment was declined.";ne(A),l?.(A),f?.(dn(ze,A,{code:Sr(jt),declineCode:bo(jt)})),Xa({billingApiUrl:r,sessionId:De,nonce:we,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:$,providerDeclineReason:Sr(jt)??"provider_declined",...kt.intentKind==="payment"&&kt.providerObjectId.startsWith("pi_")?{providerIntentId:kt.providerObjectId}:{}}})}else ee?.error({...ki(jt),...qt,operationOutcome:sr.operationOutcome,durationMs:sr.durationMs,statusClass:"unknown",terminalReason:sr.terminalReason}),await Tt?.();return}if(mr(Gt),!Qt)throw new Error("Invalid provider returned for APM intent")}catch(De){if(De===Ha){let we=ee?.now()??globalThis.performance?.now()??Date.now();ee?.error({errorCode:su(gn),stage:Ut,requestCategory:gn,paymentMethodCategory:"wallet",provider:"stripe",...Ue?{walletType:Ue}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Te,durationMs:Math.max(0,we-pn),statusClass:"timeout",failureCategory:hn,attempt:xt,terminalReason:"provider_error"}),ee?.flush?.().catch(()=>{})}ne(),pt($,De,De===Ha?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",k?.generation,De===Ha)}finally{if(window.clearTimeout(vn),Kt!==null&&(window.clearTimeout(Kt),Ee.current.delete(Kt)),!Rn){let De=ee?.now()??globalThis.performance?.now()??Date.now();ee?.performance({stage:"callback",durationMs:Math.max(0,De-pn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Dt?{statusClass:"timeout"}:{}})}Ge.current&&vt(!1)}},[Y,re,e,t,n,M,Me,R,r,G,o,s,l,f,g,pt,Q,Je,Fe,lt,ve,O]),xe=Et(()=>{let c=["applePay","googlePay","paypal","link","amazonPay","klarna"],w=new Set(["applePay","googlePay"]),ne=new Set(i.map(Fl)),k={};for(let $ of c)ne.has($)?k[$]=w.has($)?"always":"auto":k[$]="never";return k},[i]),un=Et(()=>i.map(Fl),[i]);return Oe(Qr,{children:[d(Ql,{state:Le,placeholderTestId:"flopay-wallet-placeholder",borderRadius:v,children:Oe("div",{ref:fe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[yt&&Oe("button",{ref:ut,type:"button","data-testid":"flopay-wallet-retry-button",onClick:_,style:Qi,children:["Try ",es(ue)," again"]}),it!=="idle"&&Oe("div",{role:"status","aria-live":"polite",children:[d("p",{children:"We are still confirming your payment. Check its status before trying again."}),d("button",{type:"button",onClick:ct,disabled:it==="checking",style:Qi,children:it==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ne&&d(vo,{identity:Ne.identity,methodLabel:Ne.methodLabel,onComplete:wt,onCancel:()=>wt(null)},Ne.id),it==="idle"&&d("div",{style:{display:Ne?"none":void 0},children:d(Wl,{onReady:c=>{Ce(Zl(c,un))},onLoadError:c=>{Ce("load_error"),as(ve,"stripe","wallet","provider_error")},onClick:async c=>{L.current=c.expressPaymentType,st.current=ql(c.expressPaymentType);let w=!0,ne=window.setTimeout(()=>{w=!1,c.reject()},tu),k=g?await g(st.current):{proceed:!0};if(window.clearTimeout(ne),!w)return;if(!k.proceed){le.current.delete(O),c.reject();return}let $=mt(c.expressPaymentType);le.current.set(O,{generation:$,method:c.expressPaymentType,accountPatch:k.accountPatch,sessionId:k.sessionId,nonce:k.nonce}),Be(!1),ve?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:$,...c.expressPaymentType==="apple_pay"||c.expressPaymentType==="google_pay"?{walletType:c.expressPaymentType}:{}}),y?.(st.current),c.resolve()},onConfirm:Jt,onCancel:()=>{let c=le.current.get(O);le.current.delete(O),ve?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...c?{attempt:c.generation}:{}}),oe(c?.generation),He.current=null,Be(!1),Ve.current=!0,z()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:xe,emailRequired:Ke,billingAddressRequired:Ke,layout:{maxColumns:1,overflow:"never"}}},O)})]})}),$e&&d(wr,{status:"processing"})]})}function ec(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function Su({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:s,backgroundColor:l,borderColor:y,textColor:f,borderRadius:b,fontFamily:g}){let M=Jd(e,t),R=xl[e],[C,v]=ce(!1),q=!!R&&!C,Re=M?.backgroundColor??l??"#ffffff",I=M?.borderColor??y??"#d1d5db",G=M?.textColor??f??"#262833";return d("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:Ya,padding:"0 1rem",backgroundColor:Re,color:G,border:`1px solid ${I}`,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?d("span",{style:{margin:"0 auto"},children:`Connecting to ${eo(e)}\u2026`}):Oe(Qr,{children:[Oe("span",{style:{display:"inline-flex",alignItems:"center",gap:jd(e)?8:0},children:[q?d("img",{src:R,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,!q&&M?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:M.logoSvg}}):null,d("span",{children:eo(e)})]}),i&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:G,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:d("path",{d:"M9 18l6-6-6-6"})})]})})}function ts({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:y,onDecline:f,onCancel:b,runBeforeButtonClick:g,onButtonClick:M,isProcessing:R,submitButtonColor:C,submitButtonBorderRadius:v,submitButtonStyle:q,errorText:Re}){let I=Or(),{emitInstrument:G}=To(or),Y=rs(),re=ns(),[ve,Le]=ce(!1),Ce=de(!1),[$e,vt]=ce(!1),[Ke,Ne]=ce("loading"),[Me,wt]=ce(""),fe=!fn(r?.trim()),ut=!fe||fn(Me.trim()),O=tt(async()=>{if(!Y||!re||R||Ce.current||!$e)return;Ce.current=!0,Le(!0);let Ae=g?await g("card"):{proceed:!0};if(!Ae.proceed){Ce.current=!1,Le(!1);return}M?.("card");let yt=Ae.sessionId??t,Be=Ae.nonce??n,it=Yr(o?.trim()),N=On({email:Ae.accountPatch?.email?.trim()||r?.trim()||Me.trim(),firstName:Ae.accountPatch?.firstName?.trim()||it.firstName,lastName:Ae.accountPatch?.lastName?.trim()||it.lastName}),ue=N.email,ge=On({...Ae.accountPatch,...N});try{if(y?.(null),!fn(ue))throw new Error("A valid email address is required for payment.");await i?.(N);let K=await re.submit();if(K.error){y?.(K.error.message??"Payment failed.");return}let Ge=[N.firstName,N.lastName].filter(Boolean).join(" "),Ve=await Y.createPaymentMethod({elements:re,params:{billing_details:{email:ue,...Ge?{name:Ge}:{}}}});if(Ve.error||!Ve.paymentMethod){y?.(Ve.error?.message??"Failed to create payment method.");return}let L=Ve.paymentMethod;if(!yt||!ue)throw new Error("Missing sessionId or email for payment.");let st=L.type||e,Ye=await Ja(s,G,yt,Be??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:st,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let He=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(_r,JSON.stringify({clientSecret:He,sessionId:yt,nonce:Be,accountPatch:ge,paymentMethodId:L.id,paymentMethodType:L.type??e,gateway:"stripe"}))}catch{}let{error:Ee,paymentIntent:le}=await Y.confirmPayment({clientSecret:He,confirmParams:{return_url:window.location.href,payment_method:L.id},redirect:"if_required"});if(Ee){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let oe=Ee.message??"Payment failed.";y?.(oe),f?.(dn("card",oe,{code:Ee.code})),await Xa({billingApiUrl:s,sessionId:yt,nonce:Be,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ee.code??"provider_declined"}});return}let mt=le?.status;if(!Yo(mt)){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let oe=mt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.(oe),f?.(dn("card",oe,{code:mt??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let Q=typeof le?.payment_method=="string"?le.payment_method:le?.payment_method?.id;l({id:Q??L.id,type:"card",threeDSecureActionResultTokenId:le?.id,gateway:"stripe",paymentMethodType:L.type??e},{accountPatch:ge,paymentMethodCategory:"apm",sessionId:yt,nonce:Be})}catch(K){y?.(K instanceof Error?K.message:"Payment failed. Please try again.")}finally{Ce.current=!1,Le(!1)}},[Y,re,R,$e,g,M,t,n,r,o,Me,i,s,G,e,l,y,f]);return Oe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[fe&&d("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:fe&&Oe("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",d("input",{type:"email",autoComplete:"email",required:!0,value:Me,onChange:Ae=>wt(Ae.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),d(Zd,{onReady:()=>Ne("ready"),onLoadError:()=>{Ne("load_error"),as(mn(I),"stripe","apm")},onChange:Ae=>{vt(!!Ae.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...fn(r?.trim())?{email:r?.trim()}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{O()},disabled:!$e||!ut||ve||R||Ke!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:C,color:"white",border:"none",borderRadius:v,fontSize:"1rem",fontWeight:600,cursor:!$e||!ut||ve||R||Ke!=="ready"?"not-allowed":"pointer",opacity:!$e||!ut||ve||R||Ke!=="ready"?.5:1,transition:"opacity 120ms ease-out",...q??{}},children:ve?"Processing\u2026":`Pay with ${eo(e)}`}),Re&&d(Co,{margin:"0.75rem 0 0",children:Re})]})}function Hl({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:y,onTokenizedBody:f,onErrorChange:b,onButtonClick:g,onDecline:M,runBeforeButtonClick:R,onLoadStateChange:C,isProcessing:v=!1,submitButtonColor:q="#4A49FF",submitButtonBorderRadius:Re=8,submitButtonStyle:I,buttonAppearance:G,themeId:Y,onExpandApm:re,expandedApmMethod:ve}){let{emitInstrument:Le}=To(or),[Ce,$e]=ce(null),[vt,Ke]=ce(null),Ne=de(!1),{request:Me,collect:wt,finish:fe}=ho();Ct(()=>{s.length>0&&l?C?.("ready"):l||C?.("loading")},[s.length,l,C]);let ut=tt(async N=>{if(!l||Ne.current||v)return;Ne.current=!0,Ke(N);let ue=R?await R("card"):{proceed:!0};if(!ue.proceed){Ne.current=!1,Ke(null);return}g?.("card");let ge=ue.sessionId??e,K=ue.nonce??t,Ge=Yr([ue.accountPatch?.firstName,ue.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ve=On({email:ue.accountPatch?.email?.trim()||n?.trim(),firstName:ue.accountPatch?.firstName?.trim()||Ge.firstName,lastName:ue.accountPatch?.lastName?.trim()||Ge.lastName});if(!fn(Ve.email)){Ke(null);let Ye=await wt(eo(N),Ve);if(!Ye){Ne.current=!1;return}Ve=Ye,Ke(N)}let L=Ve.email,st=On({...ue.accountPatch,...Ve});try{if(b?.(null),!ge||!fn(L))throw new Error("Missing sessionId or email for payment.");await o?.(Ve);let Ye=await Ja(i,Le,ge,K??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:N,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let He=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(_r,JSON.stringify({clientSecret:He,sessionId:ge,nonce:K,accountPatch:st,paymentMethodType:N,gateway:"stripe"}))}catch{}let{error:Ee,paymentIntent:le}=await l.confirmPayment({clientSecret:He,confirmParams:{return_url:window.location.href,payment_method_data:{type:N,billing_details:{name:[Ve.firstName,Ve.lastName].filter(Boolean).join(" "),...L?{email:L}:{}}}},redirect:"if_required"});if(Ee){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let oe=Ee.message??"Payment failed.";b?.(oe),M?.(dn("card",oe,{code:Ee.code})),await Xa({billingApiUrl:i,sessionId:ge,nonce:K,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:N,providerDeclineReason:Ee.code??"provider_declined"}});return}let mt=le?.status;if(!Yo(mt)){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let oe=mt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";b?.(oe),M?.(dn("card",oe,{code:mt??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let Q=typeof le?.payment_method=="string"?le.payment_method:le?.payment_method?.id;f({id:Q??le?.id,type:"card",threeDSecureActionResultTokenId:le?.id,gateway:"stripe",paymentMethodType:N},{accountPatch:st,paymentMethodCategory:"apm",sessionId:ge,nonce:K})}catch(Ye){b?.(Ye instanceof Error?Ye.message:"Payment failed. Please try again.")}finally{Ne.current=!1,Ke(null)}},[l,v,R,g,e,t,n,wt,i,Le,r,o,f,b,M]),[O,Ae]=ce(null),yt=re?ve??null:O,Be=tt(N=>{Ne.current||v||yt&&yt!==N||(Bl(N)?re?re(N):Ae(N):ut(N))},[yt,v,ut,re]),it=Et(()=>O?ec(y,O):null,[O,y]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Me?d(vo,{identity:Me.identity,methodLabel:Me.methodLabel,onComplete:fe,onCancel:()=>fe(null)},Me.id):s.map(N=>{let ue=ve===N,ge=vt===N,K=vt!==null&&vt!==N||ve!=null&&ve!==N;return Oe(Qd.Fragment,{children:[d(Su,{method:N,themeId:Y,submitting:ge,disabled:K,highlighted:ue,hasNextStep:Bl(N),onClick:()=>Be(N),backgroundColor:G?.backgroundColor,borderColor:G?.borderColor,textColor:G?.textColor,borderRadius:G?.borderRadius,fontFamily:G?.fontFamily}),!re&&O===N&&it&&l&&d(Zr,{stripe:l,options:it,children:d(ts,{method:N,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:f,onErrorChange:b,onDecline:M,onCancel:()=>Ae(null),runBeforeButtonClick:R,onButtonClick:g,isProcessing:v,submitButtonColor:q,submitButtonBorderRadius:Re,submitButtonStyle:I})},N)]},N)})})}function ku({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:i,onComplete:s,onError:l,onDecline:y,onTokenizedBody:f,firstName:b,lastName:g,chv:M,className:R,submitLabel:C,isProcessing:v,error:q,onErrorChange:Re,showPayPal:I=!0,showStripe:G=!0,enabledPaymentMethods:Y,enabledPaymentMethodCountries:re,showApplePay:ve=!0,showGooglePay:Le=!0,layout:Ce="default",theme:$e,buttonsTheme:vt,buttonsStyles:Ke,appearance:Ne,cardButtonContent:Me,cardBackButtonContent:wt,cardTitleContent:fe,showSecurityFooter:ut,onButtonClick:O,onBeforeButtonClick:Ae,onBuyerIdentityReady:yt,enableAVS:Be,cardFieldOrder:it,cardPreFormSlot:N,avsLayout:ue="row",country:ge,zip:K,addressLine1:Ge,addressLine2:Ve,city:L,state:st,onCountryChange:Ye,onZipChange:He,avsCheck:Ee,checkoutType:le,checkoutLayout:mt,totalAmount:Q=0,currency:oe="usd",initialCardOpen:Fe=!1,directPaypal:Je,isSubscription:lt=!1,session:z,dataAttachmentPending:pt=!1,dataAttachmentRequiresIdentity:Xe=!1,debug:_=!1}){let ct=Or(),Jt=_i(),xe=To(ur),{emitInstrument:un}=To(or),c=de(null);c.current||(c.current=Ba());let w=c.current,ne=de(null);ne.current||(ne.current=Qo());let k=ne.current,$=Et(()=>({browser:k,capability:w,presentationMode:"popup"}),[k,w]),ft=z??xe.session,ze=ft?.gateways?.paypal?.providerObjectType??Je?.providerObjectType,Ue=pt||xe.claimPending===!0,xt=Xe||xe.claimRequiresIdentity===!0,ee=Ue&&!xt,pn=fl(),We=n||pn,[Dt,Rn]=ce(!1),[Kt,Te]=ce(null),[Ut,gn]=ce(ge??"US"),[hn,kn]=ce(K??""),[Nn,vn]=ce(Ge??""),[Vt,De]=ce(Ve??""),[we,Ln]=ce(L??""),[St,bn]=ce(st??""),[En,Hn]=ce(""),[Ht,Xt]=ce({}),ln=de(K??""),kt=de(ge??"US"),Mt=de(Ge??""),yn=de(Ve??""),Zt=de(L??""),qt=de(st??""),Wt=de(""),Tt=de({});Ct(()=>{let a=(h,D,Pe,J,dt)=>{if(Tt.current[h])return;let Qe=D?.trim();!Qe||Qe===Pe.current||(Pe.current=Qe,J(Qe),dt?.(Qe))};a("country",ge,kt,gn,Ye),a("zip",K,ln,kn,He),a("addressLine1",Ge,Mt,vn),a("addressLine2",Ve,yn,De),a("city",L,Zt,Ln),a("state",st,qt,bn)},[ge,K,Ge,Ve,L,st,Ye,He]);let X=Et(()=>Gd(Be),[Be]),Qt=X!==null,en=Et(()=>Vi(z),[z]),ir=!!z?.vault?.html,mr=!!z?.gateways?.pcivault,Wn=Ci(z),sr=!!(z?.gateways?.stripe?.enabledPaymentMethods??Y)?.includes("card")||Mr(z),jt=ir||sr||mr,A=!!(G&&jt&&e),[gt,Ze]=ce(()=>Ce!=="buttons"||Fe?e??null:null),[x,qe]=ce(0),te=Ce!=="buttons"||Fe||!!e&>===e,tn=z?.captureMethod,Pn=de(ct);Ct(()=>{Pn.current=ct},[ct]);let[nn,fr]=ce(null);Ct(()=>{if(!A||!e||!te){fr(null);return}let a=Pn.current?Pn.current.cardCapture({sessionId:e,captureMethod:tn}):new Dd({sessionId:e,captureMethod:tn,billingApiUrl:We,telemetry:r});return fr({sessionId:e,captureMethod:tn,billingApiUrl:We,telemetry:r,capture:a}),()=>{a.unmount()}},[A,e,te,tn,We,r]);let he=A&&e&&te&&nn?.sessionId===e&&nn.captureMethod===tn&&nn.billingApiUrl===We&&nn.telemetry===r?nn.capture:null,zn=Et(()=>{let a=Ut,h=X?at(X.postal_code,a):!1;return Pu(a,hn,h)},[X,Ut,hn]),{avsInvalid:Gn,invalidAvsFields:jr}=Et(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!A||!X)return{avsInvalid:!1,invalidAvsFields:a};let h=Ut,D=(dt,Qe)=>at(dt,h)&&!Qe.trim(),Pe={line1:D(X.address_line_1,Nn),city:D(X.city,we),state:D(X.state,St),zip:zn.empty||zn.malformed};return{avsInvalid:Pe.line1||Pe.city||Pe.state||Pe.zip,invalidAvsFields:Pe}},[A,X,Ut,Nn,we,St,zn]),[Yn,Jn]=ce(!1),[Yt,Er]=ce(!1),[gr,Tn]=ce(!1),[hr,Xn]=ce({line1:!1,city:!1,state:!1}),Zn=de(!1),vr=de({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Qn=de(!1),It=tt(a=>{vr.current[a]=!0,Qn.current=!0},[]),Un=tt(a=>!Zn.current&&vr.current[a],[]),lr=tt(a=>{Un(a)&&Xn(h=>h[a]?h:{...h,[a]:!0})},[Un]),[qn,Cn]=ce(()=>Ji(z?.vault)),[nt,In]=ce(Fe&&jt?"card":"buttons"),[cn,jn]=ce(null),$r=nt==="expanding"||nt==="card",$n=z?.gateways?.stripe&&!Wn?"stripe":void 0,br=tt(()=>{un?.({class:"card_surface",provider:$n})},[$n,un]),An=de(null),xn=tt(a=>{An.current&&clearTimeout(An.current),An.current=setTimeout(()=>{An.current=null,a()},da)},[]);Ct(()=>()=>{An.current&&clearTimeout(An.current)},[]);let Kr=tt(()=>{br(),Ze(e??null),qe(a=>a+1),In("expanding"),xn(()=>In("card"))},[xn,br,e]),Kn=tt(()=>{In("collapsing"),xn(()=>In("buttons"))},[xn]),Vr=tt(a=>{jn(a),In("apm-expanding"),xn(()=>In("apm-form"))},[xn]),rn=tt(()=>{In("apm-collapsing"),xn(()=>{In("buttons"),jn(null)})},[xn]);Ct(()=>{Ce==="buttons"&&Fe&&jt&&(Ze(e??null),In("card"))},[Ce,Fe,jt,e]);let[S,m]=ce(null),W=de(!1),F=de(null),be=de("idle"),[Nt,ye]=ce(!1),pe=de(Nt);pe.current=Nt;let[E,V]=ce(()=>Je?.existingOrderId?{orderId:Je.existingOrderId,attempts:1}:null),p=de(E);Ct(()=>{p.current=E},[E]);let u=de(null),P=Et(()=>{if(yt||xe.claimBuyerIdentity||z?.buyerIdentified!==!1||!e||!t)return;let a=`${We}|${e}|${t}`;u.current?.key!==a&&(u.current={key:a,claim:fo(new Eo(We,{telemetry:!1}),e,t,{...i?{userId:i}:{},...b?{firstName:b}:{},...g?{lastName:g}:{}})});let h=u.current.claim;return async D=>{await h(D)}},[yt,xe.claimBuyerIdentity,z?.buyerIdentified,e,t,We,i,b,g]),B=yt??xe.claimBuyerIdentity??P,ie=q??Kt,Z=Et(()=>Xd($e),[$e]),j=Et(()=>{let a=Z?.buttonsLayout??Yd(vt);return Ke?{...a,...Ke,cardButton:{...a.cardButton,...Ke.cardButton},cardFormContainer:{...a.cardFormContainer,...Ke.cardFormContainer},backButton:{...a.backButton,...Ke.backButton},backButtonIcon:{...a.backButtonIcon,...Ke.backButtonIcon},submitButton:{...a.submitButton,...Ke.submitButton},title:{...a.title,...Ke.title}}:a},[Z,vt,Ke]),ae=Ne??Z?.appearance,Se=Et(()=>Xs({appearance:ae,buttonsStyles:j,layout:Ce}),[ae,j,Ce]),bt=xe.inlineSessionPatchProcessing??!1,_e=(v??Dt)||bt,H=We.replace(/\/+$/,""),T=Et(()=>Si({userId:i,email:o,firstName:b,lastName:g,country:ge,zip:K},Ht),[i,o,b,g,ge,K,Ht]),U=[T.firstName,T.lastName].filter(a=>!!a?.trim()).join(" "),ke=!fn(T.email?.trim()),Ie=de(null);A&&Ie.current===null&&(Ie.current=ke);let ht=A&&(Ie.current??ke),je=Et(()=>Cu(En,ht),[En,ht]),Mn=je.empty||je.malformed,on=Et(()=>ct?ct.getRawProvider():null,[ct]),to=Et(()=>Jt?Jt.getRawProvider():null,[Jt]),Fo=Q||100,no=oe.toLowerCase(),ni=Et(()=>ae?Od(ae):null,[ae]),ro=ni,vs=Et(()=>{let a=ni??{},h=a.rules??{};return{...a,rules:{...h,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...h[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...h[".AccordionItemContents"]??{}}}}},[ni]),bs=Et(()=>({...ll(Q,z?.captureMethod),currency:no,...ro?{appearance:ro}:null}),[Q,no,z?.captureMethod,ro]),Ps=Et(()=>({mode:"payment",amount:Fo,currency:no,captureMethod:"manual",setupFutureUsage:"off_session",...ro?{appearance:ro}:null}),[Fo,no,ro]),me=tt(a=>{Te(a),Re?.(a)},[Re]),ri=de(""),[Cs,yc]=ce(!1),oi=tt(()=>{yc(!0)},[]);Ct(()=>{if(!A||!ht||!B||!Cs||Mn||ri.current)return;let a=On({email:fn(T.email?.trim())?T.email?.trim():Wt.current.trim(),firstName:T.firstName?.trim(),lastName:T.lastName?.trim()});ri.current=JSON.stringify(a),Xt(h=>({...h,...a})),Promise.resolve(B(a)).catch(h=>{ri.current="",me(h instanceof Error?h.message:"Failed to attach buyer details.")})},[A,ht,B,Cs,Mn,T.email,T.firstName,T.lastName,me]),Ct(()=>{!A||!he||he.setCardFieldOrder?.(it??null,X==null&&!ht)},[A,he,it,X,ht]),Ct(()=>{(nt==="expanding"||nt==="collapsing"||nt==="apm-expanding"||nt==="apm-collapsing")&&me(null)},[nt,me]);let Pr=tt((a,h,D)=>{y?.(dn(a,h,D))},[y]),oo=tt((a,h,D)=>{let Pe=D?.popupBlocked??Dr(h);Pe&&w.markBlocked();let J=Ea(es(a),Pe,k.inAppBrowser),dt=Sr(h),Qe=(dt?.toLowerCase()==="error"?void 0:dt)??Jr(D?.code)??"external_payment_method_failed",tr=new pr(J,"api_error",{code:"external_payment_method_failed",param:a,details:{providerCode:Qe,popupBlocked:Pe,inAppBrowser:k.inAppBrowser,appFamily:k.appFamily,popupCapability:w.current(),presentationMode:D?.presentationMode??"popup"}});D?.telemetryReported||mn(ct)?.error(Ro({...$,presentationMode:D?.presentationMode??"popup"},{errorCode:Pe?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:D?.provider??(a==="paypal"?"paypal":"stripe"),paymentMethodCategory:D?.paymentMethodCategory??(a==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:D?.terminalReason??(Pe?"popup_blocked":"provider_error")})),m(null),Ce==="buttons"&&(In("buttons"),jn(null)),me(J),l?.(tr),console.error("[FloPay] External payment method failed:",{method:a,code:Qe,popupBlocked:Pe})},[k,$,ct,Ce,l,w,me]);Ct(()=>{if(!A||!e){Cn(null);return}let a=Ji(z?.vault);if(a){Cn(a);return}if(!te){Cn(null);return}Cn(null);let h=!0;return new Eo(H).getVaultCapture(e,t).then(D=>{if(!h)return;let Pe=Ji(D);Pe?Cn(Pe):me("Failed to load the secure card form.")}).catch(D=>{h&&me(D instanceof Error?D.message:"Failed to load the secure card form.")}),()=>{h=!1}},[A,te,x,e,z?.vault,H,t,me]);let cr=de({onComplete:s,onError:l,updateError:me,emitDecline:Pr,resolvedAccount:T,avsConfig:X,avsCheckProp:Ee,sessionId:e,nonce:t,baseUrl:H,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt,serverSideCardGateway:Wn});cr.current={onComplete:s,onError:l,updateError:me,emitDecline:Pr,resolvedAccount:T,avsConfig:X,avsCheckProp:Ee,sessionId:e,nonce:t,baseUrl:H,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt,serverSideCardGateway:Wn};let ai=de(!1),ws=tt(()=>{let a=cr.current,h=a.resolvedAccount.email?.trim(),D=fn(h)?h:Wt.current.trim();if(!fn(D))return null;let Pe=a.resolvedAccount.firstName?.trim(),J=a.resolvedAccount.lastName?.trim(),dt=kt.current||a.resolvedAccount.country||"US",Qe=a.avsConfig?at(a.avsConfig.state,dt):!1,tr=a.avsConfig?at(a.avsConfig.address_line_1,dt):!1,et=a.avsConfig?at(a.avsConfig.postal_code,dt):!1,Bt=a.avsConfig?at(a.avsConfig.city,dt):!1,Pt=a.avsConfig?at(a.avsConfig.address_line_2,dt):!1,rt=tr&&!Qe&&et?Ml(dt,(ln.current??"").trim()):null,Dn=Qe?qt.current:rt;return{accountData:{userId:a.resolvedAccount.userId??"",email:D,...Pe?{firstName:Pe}:{},...J?{lastName:J}:{},...et&&ln.current?{zip:ln.current}:{},...Bt&&Zt.current?{city:Zt.current}:{},...Dn?{state:Dn}:{},...tr&&Mt.current?{addressLine1:Mt.current}:{},...Pt&&yn.current?{addressLine2:yn.current}:{},country:dt},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:at(a.avsConfig.country,dt),postal_code:et,address_line_1:tr,address_line_2:Pt,city:Bt,state:Qe}}:{}}},[]),Ss=de(Ue);Ss.current=Ue,Ct(()=>{Ue||ie!==Ll||cr.current.updateError(null)},[Ue,ie]),Ct(()=>{!A||!he||he.setSubmitGate?.(Gn||Ue||Mn||Nt)},[A,he,Gn,Ue,Mn,Nt]),Ct(()=>{if(!A||!he)return;ai.current=!1;let a=null,h=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,be.current="idle",m(null)},400)},D=he.on("submitting",()=>{Jn(!0),F.current&&clearTimeout(F.current),be.current="validation-window",F.current=setTimeout(()=>{F.current=null,be.current==="validation-window"&&(be.current="processing")},lu),m("processing");let et=cr.current;if(!et.sessionId||!et.nonce)return;let Bt=ws();if(!Bt){et.updateError("Enter a valid email address."),be.current="idle",m(null);return}new Eo(et.baseUrl).patchAccountSnapshot(et.sessionId,et.nonce,Bt,{telemetryMode:"best_effort"}).catch(Pt=>{if(!du(Pt))return;let rt=Pt instanceof Error?Pt.message:"Please check your billing address and try again.";et.updateError(rt),be.current="idle",m(null),et.onError?.(Pt instanceof pr?Pt:new pr(rt,"api_error"))})}),Pe=he.on("complete",async et=>{if(ko(et.sessionId??cr.current.sessionId),be.current="terminal",ye(!1),m("success"),await new Promise(Dn=>setTimeout(Dn,600)),ai.current)return;ai.current=!0;let Bt=cr.current,Pt=Vi(Bt)||et.outcome==="authorized",rt=Bt.serverSideCardGateway?{}:{paymentIntentId:et.intentId};cr.current.onComplete?.(Pt?{status:"authorized",...rt,paymentId:et.paymentId??Bt.paymentId,sessionId:et.sessionId??Bt.sessionId,authorizationExpiresAt:et.authorizationExpiresAt??Bt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...rt,checkoutMethod:"card"})}),J=he.on("decline",et=>{let Bt=cr.current,Pt=et.message??"Your payment was declined. Please try another card or contact your bank.";be.current="terminal",ye(!1),Bt.updateError(Pt),m("error");let rt=et.failureOutcome??Vd(et.declineReason)??"authorization_declined";Bt.emitDecline("card",Pt,{code:rt,declineCode:rt}),h()}),dt=he.on("error",et=>{let Bt=cr.current,Pt=et.message??"There was a problem processing your payment. Please try again.";be.current="terminal",ye(!1),Bt.updateError(Pt),m("error"),Bt.onError?.(new pr(Pt,"api_error",{code:et.failureOutcome??"capture_failed"})),h()}),Qe=he.on("challenge_dismissed",()=>{F.current&&(clearTimeout(F.current),F.current=null),be.current="processing",ye(!0),m(null)}),tr=he.on("blocked",()=>{if(pe.current){cr.current.updateError(cu);return}if(!Ss.current){Jn(!0);return}oi(),cr.current.updateError(Ll)});return()=>{a&&(clearTimeout(a),a=null),F.current&&(clearTimeout(F.current),F.current=null),be.current="idle",ye(!1),m(null),D(),Pe(),J(),dt(),Qe(),tr()}},[A,he,oi,ws]);let Cr=!!Je?.clientId,Do=Array.isArray(Y),ga=Do&&Y.length>0,mc=Do&&Y.includes("paypal"),{expressMethods:ha,paymentElementMethods:Oo}=Et(()=>Hd(Y,{excludePaypal:Cr}),[Y,Cr]),ks=Cr||!!Jt,fc=Et(()=>ks?ha.filter(a=>a!=="paypal"):ha,[ha,ks]),gc=Et(()=>{let a=[];return ve&&a.push("apple_pay"),Le&&a.push("google_pay"),a},[ve,Le]),ao=Do?fc:gc,hc=G&&ao.length>0,ii=Qt?Ut:ge,va=Et(()=>{let a=ii?.trim().toUpperCase();return a?re?Oo.filter(h=>{let D=re[h];return!D||D.length===0||D.includes(a)}):zd(Oo,ii):Oo},[Oo,ii,re]),si=Et(()=>({mode:"payment",amount:Fo,currency:no,paymentMethodCreation:"manual",appearance:vs}),[Fo,no,vs]),[Is,_s]=ce("loading"),[Rs,Es]=ce("loading"),[Ts,As]=ce("loading"),[vc,li]=ce(!1),[xs,ci]=ce("loading"),[di,bc]=ce();Ct(()=>{bc(Qo())},[]);let ba=di?.inAppBrowser,Pa=di?xa(di,Je?.approvalPresentation,ze??(lt?"subscription":"order")):"popup",Ms=I&&(Cr||(Do?mc:ba===!1)),Bs=G&&hc,No=(!ee||!!xe.waitForDataAttachment)&&Ms&&Cr,Fs=xs==="retrying"||xs==="exhausted",Lo=!ee&&Ms&&!!to&&(!Cr||Fs),io=!ee&&Bs&&!!on,zo=!ee&&G&&ga&&va.length>0&&!!on,Pc=No&&!Fs?vc:Lo&&$l(Is),Cc=io&&$l(Rs),wc=zo&&Ts!=="load_error",Ds=a=>a==="loading"||a==="ready",Os=No||Lo&&Ds(Is)||io&&Ds(Rs)||zo&&Ts!=="load_error",Ca=de(!1);Ct(()=>{if(!Ca.current){if(!G&&!I){Ca.current=!0;let a=new pr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(a),me(a.message)}else if(!G&&I&&!Cr&&!to){Ca.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),me(a.message)}else if(ba!==void 0&&!ee&&!jt&&!Os){Ca.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),me(a.message)}}},[G,I,Cr,to,ba,ee,jt,Os,l,me]);let Ns=de(!1);Ct(()=>{if(Ns.current||!ga)return;let a=[];ve!==!0&&a.push("showApplePay"),Le!==!0&&a.push("showGooglePay"),a.length!==0&&(Ns.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.`))},[ga,ve,Le]);let Ls=tt((a,h)=>xe.applyInlineSessionPatch?xe.applyInlineSessionPatch(a).then(D=>({error:null,sessionId:D.sessionId||e,nonce:D.session?.clientSecret||t})).catch(D=>{let Pe=jl(h,D);return me(Pe.message),l?.(Pe),{error:Pe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[xe.applyInlineSessionPatch,t,l,e,me]),dr=tt(async a=>{if(a!=="card"&&ee&&await xe.waitForDataAttachment?.(),!Ae)return{proceed:!0};try{let h=await Ae({method:a,sessionId:e||void 0,createSession:xe.inlineSessionDraft});if(h===!1)return{proceed:!1};if(h&&typeof h=="object"){h.account&&Xt(Pe=>({...Pe??{},...h.account}));let D=await Ls(h,a);return D.error?{proceed:!1,accountPatch:h.account}:{proceed:!0,accountPatch:h.account,sessionId:D.sessionId,nonce:D.nonce}}return{proceed:!0}}catch(h){let D=jl(a,h);return me(D.message),l?.(D),{proceed:!1}}},[Ls,xe.inlineSessionDraft,xe.waitForDataAttachment,ee,Ae,l,e,me]),zs=tt(async(a,h)=>{if(W.current)return;W.current=!0,Rn(!0),m("processing"),me(null);let D=h?.sessionId??e,Pe=h?.nonce??t,J=Si(T,h?.accountPatch),dt=h?.completionPaymentMethodId??Jo(a),Qe=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,tr=fu(a),et=()=>{un?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:tr})};try{let Pt=await new Eo(H).processPayment(J.userId??"",{sessionId:D,nonce:Pe,paymentMethodCategory:h?.paymentMethodCategory??hu(a),tokenizedData:Qe,accountData:{...h?.accountPatch,userId:J.userId??"",email:J.email??"",firstName:J.firstName||void 0,lastName:J.lastName||void 0,...X?(()=>{let _t=kt.current,nr=at(X.state,_t),_n=at(X.address_line_1,_t),an=at(X.postal_code,_t),Gr=_n&&!nr&&an?Ml(_t,(ln.current??"").trim()):null,Vo=nr?qt.current:Gr;return{country:_t,...an&&ln.current?{zip:ln.current}:{},...at(X.city,_t)&&Zt.current?{city:Zt.current}:{},...Vo?{state:Vo}:{},..._n&&Mt.current?{addressLine1:Mt.current}:{},...at(X.address_line_2,_t)&&yn.current?{addressLine2:yn.current}:{}}})():{}},chv:M,avsCheck:Ee??!1,checkoutType:le,checkoutLayout:mt,avsConfig:X?{country:at(X.country,kt.current),postal_code:at(X.postal_code,kt.current),address_line_1:at(X.address_line_1,kt.current),address_line_2:at(X.address_line_2,kt.current),city:at(X.city,kt.current),state:at(X.state,kt.current)}:void 0});if(Pt.ok){let _t=Pt.status===204?null:await Pt.json().catch(()=>null),nr=Vi(z)||_t?.status==="authorized";ko(D),m("success"),V(null),await new Promise(Gr=>setTimeout(Gr,600));let _n;typeof _t?.paymentId=="string"?_n=_t.paymentId:z?.paymentId&&(_n=z.paymentId);let an;typeof _t?.authorizationExpiresAt=="string"?an=_t.authorizationExpiresAt:z?.authorizationExpiresAt&&(an=z.authorizationExpiresAt),s?.(nr?{status:"authorized",..._n===void 0?{}:{paymentId:_n},sessionId:typeof _t?.sessionId=="string"?_t.sessionId:D,...an===void 0?{}:{authorizationExpiresAt:an},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:dt,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:dt,checkoutMethod:a.isPaypal?"paypal":"card"});return}let rt=await Pt.json().catch(()=>null);if(rt?.type==="paypal_redirect_required"){let _t=rt.threeDSecureToken,nr=rt.paymentMethodId||a.id||"";if(!ct||!_t){m("error"),me("PayPal authorization required but no token provided.");return}try{let _n=Jt?.getRawProvider();if(!_n){me("PayPal is not available.");return}let an={return_url:window.location.href};nr&&(an.payment_method=nr);let{error:Gr}=await _n.confirmPayment({clientSecret:_t,confirmParams:an,redirect:"if_required"});if(Gr){m("error");let Vo=Gr.message??"PayPal payment failed.";me(Vo),Pr("paypal",Vo,{code:Gr.code})}}catch(_n){m("error"),me(_n instanceof Error?_n.message:"PayPal authorization failed.")}return}if(rt?.type==="paypal_direct_required"){let _t=rt.orderId;if(!_t){m("error"),me("PayPal retry required but no order id provided.");return}let nr=p.current?.attempts??0;if(nr>=2){m("error"),me("PayPal payment could not be completed after multiple attempts."),Pr("paypal","paypal_direct_required retry limit exceeded");return}li(!1),ci("loading"),V({orderId:_t,attempts:nr+1}),m(null);return}Ld(Pt.status,rt)||et(),m("error");let Dn=rt?.message??"Payment failed. Please try again.";me(Dn),Pr(a.isPaypal?"paypal":"card",Dn,{code:rt?.code??rt?.gatewayErrorCode,declineCode:rt?.declineCode??rt?.gatewayDeclineReason}),await new Promise(_t=>setTimeout(_t,400))}catch(Bt){Jl(Bt)||et(),m("error"),me(Bt instanceof Error?Bt.message:"An unexpected error occurred"),await new Promise(Pt=>setTimeout(Pt,400))}finally{Rn(!1),m(null),W.current=!1}},[H,e,t,T,X,Ee,le,mt,M,ct,Jt,z,s,me,Pr,un]),Bn=tt((a,h)=>{f?f(a):zs(a,h)},[f,zs]),Uo=`${Gl}:${e}`;Ct(()=>{if(typeof window>"u")return;let a=localStorage.getItem(Uo);if(!a)return;let h;try{h=JSON.parse(a)}catch{localStorage.removeItem(Uo);return}if(!h||typeof h.createdAt!="number"||Date.now()-h.createdAt<0||Date.now()-h.createdAt>Yl||typeof h.paymentMethodId!="string"||typeof h.providerIntentId!="string"||typeof h.paymentMethodType!="string"||h.sessionId!==e||!t||h.nonce!==t||!ao.includes(h.paymentMethodType)){localStorage.removeItem(Uo);return}localStorage.removeItem(Uo),Bn({id:h.paymentMethodId,type:"card",threeDSecureActionResultTokenId:h.providerIntentId,gateway:"stripe",paymentMethodType:h.paymentMethodType},{...h.accountPatch?{accountPatch:h.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Bn,t,e,Uo,ao]);let Us=de(!1);Ct(()=>{if(typeof window>"u"||Us.current)return;let a=new URLSearchParams(window.location.search),h=a.get("payment_intent"),D=a.get("payment_intent_client_secret"),Pe=a.get("redirect_status");if(!h||!D||!ct)return;let J=ct.getRawProvider();if(!J)return;let dt=rt=>{let Dn=localStorage.getItem(rt);if(!Dn)return null;try{return JSON.parse(Dn)}catch{return localStorage.removeItem(rt),null}},Qe=dt(_r)??dt(Dl),tr;if(Qe?.clientSecret){if(Qe.clientSecret!==D)return;tr={...Qe.accountPatch?{accountPatch:Qe.accountPatch}:{},...Qe.sessionId?{sessionId:Qe.sessionId}:{},...Qe.nonce?{nonce:Qe.nonce}:{}}}else if(Qe?.sessionId&&Qe.sessionId!==e)return;Us.current=!0,localStorage.removeItem(_r),localStorage.removeItem(Dl);let et=new URL(window.location.href);et.searchParams.delete("payment_intent"),et.searchParams.delete("payment_intent_client_secret"),et.searchParams.delete("redirect_status"),window.history.replaceState({},"",et.toString());let Bt=Qe?.paymentMethodType??Qe?.tokenType??"card",Pt="card";(async()=>{if(Pe==="failed"){let an="Payment was declined. Please try again.";me(an),Pr(Pt,an);return}let{paymentIntent:rt,error:Dn}=await J.retrievePaymentIntent(D);if(Dn){let an=Dn.message??"Failed to retrieve payment status.";me(an),Pr(Pt,an,{code:Dn.code});return}let _t=rt?.status,nr=Yo(_t);if(!rt||!nr){let an=_t==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";me(an),Pr(Pt,an,{code:_t??"missing_payment_intent"});return}let _n=typeof rt.payment_method=="string"?rt.payment_method:rt.payment_method?.id;Bn({id:_n??Qe?.paymentMethodId??Qe?.tokenId??rt.id,type:"card",threeDSecureActionResultTokenId:rt.id,gateway:Qe?.gateway??"stripe",paymentMethodType:Bt},tr)})()},[e,Bn,ct,me,Pr]);let ui=tt(a=>{a.preventDefault()},[]);if(!(A||ct!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let qo=Ce==="buttons",Fn=ae?.variables,Sc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),pi=Fn?.colorBackground,kc=pi&&!Sc.has(pi)?pi:void 0,jo=j.cardInputBorder??(qo?"#e5e7eb":"#A4A4FF"),qs=Fn?.colorDanger??"#dc2626",Lt=a=>jr[a]&&(hr[a]||Yn),wa=Mn&&(gr||Yn),er=a=>a?qs:jo,Sa=(zn.malformed||zn.empty)&&(Yt||Yn),Ic=er(Sa),yi=j.cardFormContainer?.backgroundColor??kc??(qo?"white":"#EDEDFF"),so=j.cardInputBackground??Fn?.colorBackground??"white",mi=uo(wt),js=uo(fe),lo=j.nameInput,$s=j.cardInputFontSize??wu(lo?.fontSize)??Fn?.fontSizeBase??"16px",Ks=typeof lo?.fontFamily=="string"?lo.fontFamily:Fn?.fontFamily??"Poppins, sans-serif",Vs=Js(lo?.fontWeight)??400,_c=j.cardInputColor??(typeof lo?.color=="string"?lo.color:void 0)??Fn?.colorText??"#262833",Rc=j.cardInputPlaceholderColor??"#9ca3af",$t=Fn?.borderRadius??"8px",Hr=Fn?.borderRadius??j.cardButton?.borderRadius??$t,Wr=Fn?.colorPrimary??"#4A49FF",Ec=Fn?.colorPrimaryHover??Wo(Wr,.12),fi=Fn?.colorText??"#262833",gi={fontSize:$s,fontFamily:Ks,fontWeight:Vs,color:_c,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},$o={marginTop:"0.375rem",...gi,fontSize:"0.75rem",lineHeight:1.4,color:qs},Tc={"--flopay-input-placeholder-color":Rc,"--flopay-input-font-size":$s,"--flopay-input-font-family":Ks,"--flopay-input-font-weight":String(Vs)},Ko=j.cardFormContainer??{},hi=Ko.padding??(qo?"0":"1rem"),vi=Ko.borderRadius??$t,Ac=he&&qn?d(bi,{capture:he,html:qn.html,messageToken:qn.messageToken,expectedOrigin:qn.expectedOrigin,theme:Se,submitLabel:C,onReady:()=>{if(!ht&&!X||typeof document>"u")return;let a=()=>{let D=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(D){Zn.current=!0;try{D.focus()}finally{Zn.current=!1}}};Qn.current||a()},onError:a=>me(a),onValidation:a=>{let h=be.current;(h==="idle"||h==="validation-window")&&(me(a),a&&be.current==="validation-window"&&(F.current&&(clearTimeout(F.current),F.current=null),be.current="idle",m(null)))}}):d("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Hs=Oe("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&br()},style:{backgroundColor:yi,borderRadius:vi,...Ko,padding:hi,...Tc,display:"flex",flexDirection:"column"},children:[d("style",{children:`
|
|
26
26
|
.flopay-shared-input::placeholder {
|
|
27
27
|
color: var(--flopay-input-placeholder-color);
|
|
28
28
|
opacity: 1;
|
|
@@ -30,13 +30,13 @@ ${yn.join(`
|
|
|
30
30
|
font-family: var(--flopay-input-font-family);
|
|
31
31
|
font-weight: var(--flopay-input-font-weight);
|
|
32
32
|
}
|
|
33
|
-
`}),
|
|
34
|
-
`)}):null,
|
|
35
|
-
`)}):null,Fs=Ve==="apm-expanding"||Ve==="apm-form"||Ve==="apm-collapsing",ro;Ve==="apm-expanding"?ro=Sl:Ve==="apm-collapsing"&&(ro=wl);let ma=pn?Ll(Wa,pn):null;if(Re==="buttons"){let a=Ve==="buttons"||Ve==="expanding"||Ve==="apm-expanding",P=Ve==="expanding"||Ve==="card"||Ve==="collapsing",O=$e===void 0?{boxSizing:"border-box",height:Fa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ne;Ve==="expanding"||Ve==="apm-expanding"?Ne=Xd:(Ve==="collapsing"||Ve==="apm-collapsing")&&(Ne=Jd);let j;return Ve==="expanding"?j=Sl:Ve==="collapsing"&&(j=wl),Ue("form",{onSubmit:Ja,className:_,noValidate:!0,style:{position:"relative"},children:[c(Di,{}),k&&c(yr,{status:k,errorMessage:te,authorized:vn}),Ue("div",{style:{display:"grid"},children:[Ue("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!Ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!Ne?Qd:{},...Ne?{animation:Ne,pointerEvents:"none"}:{}},children:[xs("flopay-direct-paypal-gate-debug"),Bs("flopay-stripe-gate-debug"),To&&_e&&Ue(Wr,{children:[X&&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(wa,{sessionId:e,nonce:t,billingApiUrl:K,email:D.email,billingName:q||void 0,onBuyerIdentityReady:L,clientId:_e.clientId,environment:_e.environment,currency:ke.toUpperCase(),isSubscription:le,providerObjectType:xe,approvalPresentation:la==="popup"?void 0:la,onTokenizedBody:xn,onComplete:s,onErrorChange:pe,onDecline:p,onTechnicalFailure:Zr,onButtonClick:ee,runBeforeButtonClick:or,isProcessing:Be,onLoadStateChange:Ha,onInitializationStateChange:Ga,session:w,existingOrderId:X?.orderId,debug:Mt},X?.orderId??"fresh")]}),Ao&&c(Vr,{stripe:Yr,options:as,children:c(Rl,{sessionId:e,nonce:t,email:D.email,billingName:q||void 0,onBuyerIdentityReady:L,billingApiUrl:K,onTokenizedBody:xn,onErrorChange:pe,isProcessing:Be,onButtonClick:ee,onDecline:p,onTechnicalFailure:Zr,runBeforeButtonClick:or,onLoadStateChange:us,placeholderBorderRadius:Lr})}),eo?c(Vr,{stripe:Xt,options:os,children:c(El,{sessionId:e,nonce:t,email:D.email,billingName:q||void 0,onBuyerIdentityReady:L,billingApiUrl:K,intentKind:ot>0?"payment":"setup",expressMethods:Qr,onTokenizedBody:xn,onErrorChange:pe,onButtonClick:ee,onDecline:p,onTechnicalFailure:Zr,runBeforeButtonClick:or,onLoadStateChange:ms,placeholderBorderRadius:Lr})}):null,!eo&&vs?c("div",{style:{height:Fa,borderRadius:Lr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Mo&&c(Tl,{sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:L,billingApiUrl:K,paymentElementMethods:ia,stripeInstance:Xt,paymentElementBaseOptions:Wa,onTokenizedBody:xn,onErrorChange:pe,onButtonClick:ee,onDecline:p,runBeforeButtonClick:or,onLoadStateChange:fs,isProcessing:Be,submitButtonColor:Or,submitButtonBorderRadius:jt,submitButtonStyle:b.submitButton,onExpandApm:Nr,expandedApmMethod:pn,themeId:Ge,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:Lr}}),ze&&c("button",{type:"button",onClick:async()=>{Be||!(await or("card")).proceed||(ee?.("card"),Dr())},disabled:Be,style:{width:"100%",...O,...b.cardButton,...Ki({themeBundle:V,resolvedPrimaryColor:Or,resolvedBorderRadius:jt,submitButtonStyle:b.submitButton,explicitPrimaryColor:Bn?.colorPrimary}),fontSize:b.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Be?"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?.6:1},onMouseEnter:at=>{!Be&&(V||Bn?.colorPrimary)&&(at.currentTarget.style.backgroundColor=dc)},onMouseLeave:at=>{(V||Bn?.colorPrimary)&&(at.currentTarget.style.backgroundColor=Or)},onMouseDown:at=>{at.currentTarget.style.transform="scale(0.985)"},onMouseUp:at=>{at.currentTarget.style.transform="scale(1)"},children:c(ao,{content:$e})}),te&&Ve==="buttons"&&c(fo,{margin:"0.25rem 0",styleOverride:b.errorBanner,children:te})]}),ze&&P&&c("div",{style:{gridArea:"1 / 1",...j?{animation:j}:{},...Ve==="collapsing"?{pointerEvents:"none"}:{}},children:Ms}),W&&Fs&&pn&&ma&&Xt&&c("div",{style:{gridArea:"1 / 1",...ro?{animation:ro}:{},...Ve==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ue("div",{style:{backgroundColor:Za,borderRadius:ri,...No,padding:ni},children:[Ue("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ue("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Jt,style:{display:"inline-flex",alignItems:"center",gap:Qa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.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",...b.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(io,{content:ue})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:ei,paddingRight:80,...b.title},children:`Pay with ${Hr(pn)}`})]}),c(Vr,{stripe:Xt,options:ma,children:c(zi,{method:pn,sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:L,billingApiUrl:K,onTokenizedBody:xn,onErrorChange:pe,onDecline:p,onCancel:Jt,runBeforeButtonClick:or,onButtonClick:ee,isProcessing:Be,submitButtonColor:Or,submitButtonBorderRadius:jt,submitButtonStyle:b.submitButton,errorText:te})},pn)]})})]})]})}return Fs&&pn&&ma&&Xt&&W?Ue("form",{onSubmit:Ja,className:_,noValidate:!0,style:{position:"relative"},children:[c(Di,{}),k&&c(yr,{status:k,errorMessage:te,authorized:vn}),c("div",{style:{...ro?{animation:ro}:{},...Ve==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ue("div",{style:{backgroundColor:Za,borderRadius:ri,...No,padding:ni},children:[Ue("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ue("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Jt,style:{display:"inline-flex",alignItems:"center",gap:Qa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.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",...b.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(io,{content:ue})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:ei,paddingRight:80,...b.title},children:`Pay with ${Hr(pn)}`})]}),c(Vr,{stripe:Xt,options:ma,children:c(zi,{method:pn,sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:L,billingApiUrl:K,onTokenizedBody:xn,onErrorChange:pe,onDecline:p,onCancel:Jt,runBeforeButtonClick:or,onButtonClick:ee,isProcessing:Be,submitButtonColor:Or,submitButtonBorderRadius:jt,submitButtonStyle:b.submitButton,errorText:te})},pn)]})})]}):Ue("form",{onSubmit:Ja,className:_,noValidate:!0,style:{position:"relative"},children:[c(Di,{}),k&&c(yr,{status:k,errorMessage:te,authorized:vn}),Ue("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[xs("flopay-direct-paypal-gate-debug-default"),Bs("flopay-stripe-gate-debug-default"),To&&_e&&Ue(Wr,{children:[X&&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(wa,{sessionId:e,nonce:t,billingApiUrl:K,email:D.email,billingName:q||void 0,onBuyerIdentityReady:L,clientId:_e.clientId,environment:_e.environment,currency:ke.toUpperCase(),isSubscription:le,providerObjectType:xe,approvalPresentation:la==="popup"?void 0:la,onTokenizedBody:xn,onComplete:s,onErrorChange:pe,onDecline:p,onTechnicalFailure:Zr,onButtonClick:ee,runBeforeButtonClick:or,isProcessing:Be,onLoadStateChange:Ha,onInitializationStateChange:Ga,session:w,existingOrderId:X?.orderId,debug:Mt},X?.orderId??"fresh")]}),Ao&&c(Vr,{stripe:Yr,options:as,children:c(Rl,{sessionId:e,nonce:t,email:D.email,billingName:q||void 0,onBuyerIdentityReady:L,billingApiUrl:K,onTokenizedBody:xn,onErrorChange:pe,isProcessing:Be,onButtonClick:ee,onDecline:p,onTechnicalFailure:Zr,runBeforeButtonClick:or,onLoadStateChange:us,placeholderBorderRadius:Lr})}),eo&&c(Vr,{stripe:Xt,options:os,children:c(El,{sessionId:e,nonce:t,email:D.email,billingName:q||void 0,onBuyerIdentityReady:L,billingApiUrl:K,intentKind:ot>0?"payment":"setup",expressMethods:Qr,onTokenizedBody:xn,onErrorChange:pe,onButtonClick:ee,onDecline:p,onTechnicalFailure:Zr,runBeforeButtonClick:or,onLoadStateChange:ms,placeholderBorderRadius:Lr})}),Mo&&c(Tl,{sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:K,paymentElementMethods:ia,stripeInstance:Xt,paymentElementBaseOptions:Wa,onTokenizedBody:xn,onErrorChange:pe,onButtonClick:ee,onDecline:p,runBeforeButtonClick:or,onLoadStateChange:fs,isProcessing:Be,submitButtonColor:Or,submitButtonBorderRadius:jt,submitButtonStyle:b.submitButton,themeId:Ge,onExpandApm:Nr,expandedApmMethod:pn,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:Lr}})]}),ze&&(rc||nc||oc)&&Ue("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"}})]}),ze&&Ms]})}import{Fragment as hr,jsx as re,jsxs as en}from"react/jsx-runtime";var So=44,Qi="flopay_checkout_saved_payment_resume",Ua=new Map,Oa=new Map;function zl(e,t){t.settled&&t.consumers===0&&Ua.get(e)===t&&Ua.delete(e)}function gu(e,t,n){let r=Oa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};Oa.set(e,i);let s=()=>{Oa.get(e)===i&&Oa.delete(e)};return o.then(s,s),o}function Qo(e){return new Promise(t=>setTimeout(t,e))}function za(e,t,n){let r=Ca({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Hl,enabled:t!==!1});return r.beginCheckout(n),r}function ea(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Hi(e,t,n,r,o,i){let s=za(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),ea(s)}function Ul(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 ql(e,t,n,r,o){let i=Vl(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 mn&&t.code==="session_auto_completed"?!1:t instanceof mn&&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 Zi(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation}}function Gi(e){return!e||e.data.stripe?.publishableKey?!1:!!Zi(e)?.clientId}var hu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function vu(e){return new cu(hu,{publishableKey:"provider_unavailable",...e})}async function Yi(e,t){let{publishableKey:n,paypalPublishableKey:r}=ki(e);return{...await _i({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function es(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Pu(){if(!es())return null;try{let e=window.sessionStorage.getItem(Qi);return e?JSON.parse(e):null}catch{return null}}function jl(e){if(es())try{window.sessionStorage.setItem(Qi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ji(){if(es())try{window.sessionStorage.removeItem(Qi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function bu(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function $l(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function Xi(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Cu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Kl(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Su(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 ts({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:s,loading:l,error:p,onComplete:v,onError:g,onInstrument:h,onDecline:y,onCountryChange:_,onZipChange:M,showPayPal:U=!0,showStripe:qe=!0,enabledPaymentMethods:ge,showApplePay:S=!0,showGooglePay:W=!0,debug:Y=!1,layout:de,theme:Le,buttonsTheme:Se,buttonsStyles:Re,cardButtonContent:Ge,cardBackButtonContent:St,cardTitleContent:tt,showSecurityFooter:je,onButtonClick:$e,onBeforeButtonClick:ue,enableAVS:we,cardFieldOrder:Xe,cardPreFormSlot:ee,avsLayout:Ie,submitLabel:he,className:st,initialErrorMessage:lt=null,children:T,checkoutMode:$,confirmLabel:Ee,renderConfirmButton:ie,onSessionCompleted:rt}){let A=mu(r),Te=Yn(()=>Wl(Le),[Le]),dt=i??Te?.appearance,We=n?"embedded_checkout":"standard_checkout",se=Xi(T,de),[x,Q]=Ot(null),[Me,ot]=Ot(null),ke=Tt(null),Ke=Tt(null),_e=Tt(0),[le,ve]=Ot(null),Vt=Tt(null),[H,Mt]=Ot(null),mt=Yn(()=>n?ho(n):"",[n]),R=n?`create:${mt}`:`session:${e??""}`,ne=Kl(H),u=Tt(new Set),w=Tt(R),xe=Tt(R);Oo(()=>{xe.current=R,w.current!==R&&(w.current=R,u.current.clear())},[R]);let me=wn(k=>{if(xe.current===R){if(ui.has(k.name)){if(u.current.has(k.name))return;u.current.add(k.name)}Rt(()=>h?.(k))}},[R,h]),Ct=yo(me,R),nt=Tt(!1),xt=wn(k=>{if(nt.current)return;let f=k.gateway||!ne?k:{...k,gateway:ne};me(f)},[me,ne]);gr(()=>{Ct({class:"lifecycle",name:"checkout.mount"})},[Ct]);let[K,Wt]=Ot(e??""),wt=e??K,yn=n?"":wt,[sr,N]=Ot(!0),[fn,In]=Ot(null),[cn,rn]=Ot(0),[gn,Jn]=Ot("full"),[dn,Ht]=Ot(!1),[Ae,Oe]=Ot(lt),[on,ut]=Ot(null),[jn,Bt]=Ot(null),[Gt,gt]=Ot(!1),[$t,un]=Ot(void 0),[Ft,It]=Ot(""),[an,Nn]=Ot(!1),[vt,J]=Ot(!1),[hn,vn]=Ot(!1),Dt=Tt(null),zt=Tt(0),Ln=Tt(void 0),[$n,Xn]=Ot("loading"),[Yt,ze]=Ot(0),Ut=Tt(!1),Pe=Tt(!1),E=Tt(!1),be=Tt(null),I=Yn(()=>({checkoutMode:$??gn,layout:Cu(T,de)}),[$,T,gn,de]),Nt=Tt(v);Nt.current=v;let Pn=Tt(g);Pn.current=g;let sn=Tt(y);sn.current=y;let On=wn((k,f)=>{ke.current=k,ot(k),Vt.current=f,ve(f)},[]),ae=wn(()=>{let k=Ke.current;k&&(Ke.current=null,k.destroy())},[]);gr(()=>{Qt(Me)?.setCheckoutContext(I),le&&le!==Me&&Qt(le)?.setCheckoutContext(I)},[Me,le,I]);let bn=Tt(rt);bn.current=rt;let Br=wn(k=>{Xn(k),!(k!=="exhausted"||E.current)&&(E.current=!0,Pn.current?.(new mn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Gr=wn(()=>{Xn("retrying"),ze(k=>k+1)},[]);gr(()=>{Xn("loading"),ze(0),E.current=!1},[wt]),gr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Hl,checkout_type:We,checkout_layout:se,billing_api_url:A})},[se,We,A]);let kn=Yn(()=>n?ho(n,!0):"",[n]),wr=Yn(()=>Ft===kn?$t:void 0,[$t,Ft,kn]),lr=Yn(()=>n?si(n,wr):void 0,[n,wr]),Zn=$??lr?.checkoutMode??"full",Kt=Yn(()=>lr?{...lr,checkoutMode:Zn}:void 0,[lr,Zn]);gr(()=>{un(void 0),It(kn),Ln.current=void 0,Dt.current=null,vn(!1)},[kn]),gr(()=>{Oe(lt)},[lt]);let _n=wn((k,f,G)=>{Rt(()=>{sn.current?.(nn(k,f,G))})},[]),vr=wn(async(k,f)=>{Oe(null),Bt(null),gt(!1),ut("processing");let G=f?.sessionId??k.id,B=Kl(k),Ce=ke.current??Vt.current,ct=Qt(Ce),ye=Ce?null:za(A,o,I),z={log:b=>{ct?ct.log(b):ye?.log(b)},error:b=>{ct?ct.error(b):ye?.error(b)},terminal:b=>{ct?ct.terminal(b):ye?.terminal(b)},performance:b=>{ct?ct.performance(b):ye?.performance(b)},now:()=>ct?.now()??ye?.now()??0,elapsed:b=>ct?.elapsed(b)??Math.max(0,(ye?.now()??b)-b)},X=z.now(),F=!!(f?.initialAutoProcessingError||f?.initialAutoProcessingPending),m=!1,d,C=()=>{m||(m=!0,F=!0,d=z.now(),z.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},L=!1,te=()=>{L||(L=!0,z.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),z.performance({stage:"processing",durationMs:z.elapsed(X),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),d!==void 0&&z.performance({stage:"recovery",durationMs:z.elapsed(d),durationMode:"machine",paymentMethodCategory:"saved"}))};z.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),nt.current=!0;try{z.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{nt.current=!1}Ct({class:"lifecycle",name:"payment.processing.started",provider:B}),F&&C();let V;try{let b=ul(f?.initialAutoProcessingError),Z;if(b)C(),b.type==="paypal_redirect_required"&&be.current?.publishableKey&&jl({sessionId:G,publishableKey:be.current.publishableKey,paypalPublishableKey:be.current.paypalPublishableKey}),Z=await Ma(b,{flopay:ke.current,paypalFlopay:Vt.current,attempt3DS:f?.attempt3DS,billingApiUrl:A,sessionId:G,session:k,telemetry:!1}),b.type==="paypal_redirect_required"&&Ji();else if(f?.initialAutoProcessingPending){let Be=(await new La(A,{telemetry:!1}).waitForCheckoutSessionCompletion(f.initialAutoProcessingPending.sessionId,{initialDelayMs:f.initialAutoProcessingPending.retryAfterMs})).data.session;if(!co(Be))throw ga(Be);Z=jr(Be,G)}else{if(f?.initialAutoProcessingError)throw Tr(f.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:f.initialAutoProcessingError.checkoutMethod});if(f?.fromCreateSession)return f?.fallbackToFull&&(Jn("full"),$l("full")),!1;{let pt=await Po({billingApiUrl:A,sessionId:G,session:k,telemetry:!1});pt.type==="success"?Z=pt.result:(C(),pt.type==="paypal_redirect_required"&&be.current?.publishableKey&&jl({sessionId:G,publishableKey:be.current.publishableKey,paypalPublishableKey:be.current.paypalPublishableKey}),Z=await Ma(pt,{flopay:ke.current,paypalFlopay:Vt.current,attempt3DS:f?.attempt3DS,billingApiUrl:A,sessionId:G,session:k,telemetry:!1}),pt.type==="paypal_redirect_required"&&Ji())}}G&&vo(G),te(),F&&(z.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),z.terminal({outcome:Z.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),gt(Z.status==="authorized"),ut("success"),await Qo(600),V=()=>Nt.current?.(Z)}catch(b){let Z=Jo(b),pt=Z.checkoutMethod??Yo;Oe(Z.message),Bt(Z.message),gt(!1),f?.fallbackToFull&&(z.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Jn("full"),$l("full")),te();let qt=Z.statusCode===void 0?void 0:fu(Z.statusCode,"unknown"),Be=qt==="4xx"?{requestCategory:"process_payment",statusClass:qt}:{},fe=qt===void 0||qt==="4xx";if(fe&&(Z.telemetryOutcome==="payment_declined"||!!(Z.declineCode||Z.code?.toLowerCase().includes("declin"))))z.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Be});else if(fe&&(Z.telemetryOutcome==="validation_rejected"||Z.type==="validation_error"))z.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Be});else{let Fe=Vl(b,F?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),De=Z.telemetryRequestCategory??"process_payment";nt.current=!0;try{z.error({...Fe,...Z.telemetryFailureCategory?{failureCategory:Z.telemetryFailureCategory}:{},stage:F?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:De})}finally{nt.current=!1}Ct({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:De,provider:B})}return Rt(()=>Pn.current?.(Z)),_n(pt,Z,{code:Z.code,declineCode:Z.declineCode}),ut("error"),await Promise.allSettled([Qo(400),f?.ensureProvidersReady?f.ensureProvidersReady():Promise.resolve()]),F&&(z.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{te(),ye&&ea(ye),ut(null),Bt(null)}return Rt(V),!0},[_n,Ct,A,o,I]);gr(()=>{if(typeof window>"u"||Pe.current)return;let k=new URLSearchParams(window.location.search),f=k.get("payment_intent_client_secret");if(!f)return;let G=Pu();G&&(Pe.current=!0,(async()=>{let B,Ce=0;Oe(null),Bt(null),ut("processing"),Ht(!0);try{if(k.get("redirect_status")==="failed")throw Object.assign(new mn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ct,paypalFlopay:ye}=await _i({publishableKey:G.publishableKey,paypalPublishableKey:G.paypalPublishableKey,billingApiUrl:A,locale:s,telemetry:o});B=Qt(ye??ct),B?.setCheckoutContext(I),Ce=B?.now()??0,B?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),B?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let z=(ye??ct)?.getRawProvider();if(!z)throw Object.assign(new mn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:X,error:F}=await z.retrievePaymentIntent(f);if(F)throw Object.assign(new mn(F.message??"Failed to retrieve PayPal payment status.","api_error",{code:F.code}),{checkoutMethod:"paypal"});let m=Vs(X?.status);if(!X||m==="failed")throw Object.assign(new mn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let d=typeof X.payment_method=="string"?X.payment_method:X.payment_method?.id,C=m;if(G.sessionId){let V=(await new La(A,{telemetry:!1}).getUnifiedCheckoutSession(G.sessionId)).data.session;if(V&&V.status!=="complete"){let b=await Po({billingApiUrl:A,sessionId:G.sessionId,session:V,telemetry:!1,tokenizedData:{id:d??X.id,type:"card",threeDSecureActionResultTokenId:X.id,isPaypal:!0}});if(b.type!=="success")throw Object.assign(new mn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});C=b.result.status}}G.sessionId&&vo(G.sessionId),B?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),B?.performance({stage:"redirect_resume",durationMs:B.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ut("success"),await Qo(600),Rt(()=>Nt.current?.({status:C,paymentIntentId:X.id,paymentMethodId:d,checkoutMethod:"paypal"}))}catch(ct){let ye=Jo(ct),z=ye.checkoutMethod??"paypal",X=!!(ye.declineCode||ye.code?.toLowerCase().includes("declin"));if(B)B.performance({stage:"redirect_resume",durationMs:B.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),X?B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):B.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(X){let F=za(A,o,I);F.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ea(F)}else Hi(A,o,I,"REDIRECT_RESUME_FAILED","redirect_resume");Oe(ye.message),Bt(ye.message),Rt(()=>Pn.current?.(ye)),_n(z,ye,{code:ye.code,declineCode:ye.declineCode}),ut("error"),await Qo(400)}finally{Ji(),bu(),ut(null),Bt(null),Ht(!1)}})())},[_n,s,A,o,I]);let zn=Tt(null),Rn=Yn(()=>Kt?ho(Kt):"",[Kt]),Qn=Tt(Kt);Qn.current=Kt,gr(()=>{Wt(e??"")},[e]),gr(()=>{Ut.current=!1,Oe(lt),Bt(null),gt(!1),ut(null)},[Rn,lt,e]);async function er(k,f,G){let B=za(A,o,I),Ce=new La(A,{telemetry:!1}),ct=!1;try{let ye=k.idempotencyKey===void 0?void 0:Ol(k.idempotencyKey),z=bi(f,G),X=Ci(f,G);z?.canonicalIdentity===G&&X&&X.canonicalIdentity===void 0&&(Ra(f,G,X.idempotencyKey),X={...X,canonicalIdentity:G});let F=ye??(X?.canonicalIdentity===G?X.idempotencyKey:void 0),m,d=!1;B.log({name:z?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let C=z?.sid??null,L=null,te,V,b=!1;if(C)try{L=await Ce.getUnifiedCheckoutSession(C,z?.nonce),z&&z.canonicalIdentity===void 0&&(ol(L.data.session,k)?(_a(f,G,C,z.nonce??L.data.session?.clientSecret),X&&X.canonicalIdentity===void 0&&(Ra(f,G,X.idempotencyKey),F??(F=X.idempotencyKey))):(ka(f,G),X=null,F=ye,C=null,L=null));let pt=L?.data.session?.status,qt=L?.data.session,Be=qt?.clientSecret||z?.nonce;if(C&&qt?.buyerIdentified===!1&&Be&&(V=lo(Ce,C,Be,k.account)),C&&L&&pt==="complete"){if(Si(C))return{sid:C,result:L};ka(f,G),C=null,L=null,d=!0}}catch{B.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),z?.canonicalIdentity===void 0?(ka(f,G),F=ye):Ia(f,G),C=null}if(!C){!ye&&(d||!F)&&(F=Ol(),m=F),F&&Ra(f,G,F);let pt=B.now(),qt=0;B.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Be={...k,idempotencyKey:F,avsCheck:!!we,avsConfig:typeof we=="object"?we:void 0,checkoutType:"embedded_checkout",checkoutLayout:Xi(T,de)};Object.defineProperty(Be,du,{configurable:!1,enumerable:!1,value:{onAttempt:q=>{qt=Math.max(qt,q)}}});let fe=()=>{Ul(B,"session_create",pt,qt)},D=q=>{ql(B,q,"session_create",pt,qt)&&Ct({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(pu(Be)){let q=await Ce.createDetachedSession(Be);q.claimed.catch(()=>{}),L=q.shell,C=q.sessionId,V=q.claim;let Fe=B.now();B.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),te=q.claimed.then(De=>{let kt=De.data.session?.id??q.sessionId;return kt&&_a(f,G,kt,De.data.session?.clientSecret??q.nonce),Ul(B,"session_claim",Fe),fe(),De},De=>{throw Ia(f,G),ql(B,De,"session_claim",Fe,0)&&Ct({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),De}).finally(()=>ea(B)),te.catch(()=>{}),ct=!0,B.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),B.performance({stage:"session_shell",durationMs:B.now()-pt,durationMode:"machine",requestCategory:"session_create",attempt:qt,statusClass:"2xx",paymentMethodCategory:"card"})}else L=await Ce.createAndFetchSession(Be),fe()}catch(q){throw D(q),q}C=L.data.session?.id??C??"",C&&!te&&_a(f,G,C,L.data.session?.clientSecret)}let Z=L?.data.session;return!V&&C&&Z?.buyerIdentified===!1&&Z.clientSecret&&(V=lo(Ce,C,Z.clientSecret,k.account)),{sid:C??"",result:L,sdkGeneratedIdempotencyKey:m,...te?{claimed:te}:{},...V?{claim:V}:{},...b?{claimRequiresIdentity:!0}:{}}}finally{ct||ea(B)}}let Pt=Tt(er);Oo(()=>{Pt.current=er},[er]);let Cn=wn(async(k,f)=>{let G=Qn.current;if(!G)throw new mn("createSession is required to bootstrap checkout.","validation_error");let B=si(G,k),Ce=ho(B),ct=rl(B),ye=Ua.get(Ce);if(!ye){let F={canonicalIdentity:Ce,promise:Pt.current(B,ct,Ce),consumers:0,settled:!1};ye=F,Ua.set(Ce,F);let m=()=>{F.settled=!0,zl(Ce,F)};F.promise.then(m,m)}ye.consumers+=1;let z=!1,X=()=>{z||(z=!0,ye.consumers-=1,zl(Ce,ye))};f?.(X);try{let F=await ye.promise;zn.current=Ce,k&&(It(kn),un(Z=>js(Z,k)));let{sid:m,result:d,claimed:C,claim:L,claimRequiresIdentity:te}=F;if(Ln.current=L,vn(te===!0),Q(d),d.data.session&&Mt(d.data.session),m&&Wt(m),C){zt.current+=1;let Z=zt.current;Dt.current=C,J(!0),C.then(pt=>{zt.current===Z&&(Dt.current===C&&(Dt.current=null),Q(pt),pt.data.session&&Mt(pt.data.session),J(!1),vn(!1))},pt=>{zt.current===Z&&(Dt.current===C&&(Dt.current=null),J(!1),vn(!1),In(pt instanceof mn?pt:new mn(pt instanceof Error?pt.message:"Failed to create session","api_error")))})}else zt.current+=1,Dt.current=null,J(!1),vn(!1);let{flopay:V,paypalFlopay:b}=await Yi(d,{billingApiUrl:A,locale:s,telemetry:o});return On(V,b),N(!1),F}catch(F){throw zn.current===Ce&&(zn.current=null),F}finally{f||X()}},[kn,On,s,A,o]),Kn=Tt(vr);Kn.current=vr;let tr=Tt(Cn);tr.current=Cn;let En=wn(async k=>{if(!Su(k)||an)return{sessionId:K,session:H};Nn(!0);try{let f=await Cn(k);return{sessionId:f.sid,session:f.result.data.session??null}}finally{Nn(!1)}},[Cn,an,K,H]),Ve=wn(async k=>{let f=Ln.current;if(!f)return;let G=zt.current,B=await f(k);zt.current===G&&(Q(B),B.data.session&&Mt(B.data.session))},[]),tn=wn(async()=>{await Dt.current},[]),pn=wn(async()=>(await tn(),{proceed:!0}),[tn]);gr(()=>{let k=!1,f,G=++_e.current;ae(),In(null),rn(0);let B=()=>{k=!0,_e.current===G&&(_e.current+=1,ae())},Ce=Qn.current;if(Rn&&Ce)return Jn(Zn),N(!1),zn.current===Rn?B:(Mt($s(Ce,$)),(async()=>{let z=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),X=Zn==="auto"&&!Ut.current&&!z;X&&(Oe(null),Bt(null),ut("processing"));try{let F=await tr.current(void 0,L=>{f=L}),m=F.result.data.session??null;be.current=ki(F.result);let d=Gi(F.result),C=Si(F.sid||m?.id);if(!k&&X&&m&&!d&&!C){Ut.current=!0,await gu(Rn,F.sdkGeneratedIdempotencyKey,()=>Kn.current(m,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:F.result.autoProcessingError,initialAutoProcessingPending:F.result.autoProcessingPending,autoProcessingAttempted:F.result.autoProcessingAttempted,sessionId:F.sid||m.id}));return}!k&&X&&((d||C)&&(Ut.current=!0),ut(null),Bt(null))}catch(F){if(k)return;let m=fa(F);if(X&&m==="session_auto_completed"){Ut.current=!0,ut("success"),await Qo(600),k||(Rt(()=>{Nt.current?.({status:"succeeded"})}),ut(null),Bt(null));return}X&&(ut(null),Bt(null));let d=F instanceof mn?F:new mn(F instanceof Error?F.message:"Failed to create session","api_error");In(d)}finally{f?.(),f=void 0}})(),()=>{B(),f?.()});N(!0);async function ct(){let z=!1,X=null;try{let F=new La(A,{telemetry:!1}),m=await F.getUnifiedCheckoutSession(wt,t);if(X=m,k)return;Q(m);let d=m.data.session??null;if(Mt(d),!d)throw new mn("No session data returned","api_error");let C=d.checkoutMode;if(C==="setup")throw new mn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(d.status==="authorized"){N(!1),Rt(()=>{Nt.current?.(jr(d,wt)),bn.current?.(d.successUrl??"")});return}if(d.status==="complete"){N(!1),Rt(()=>{bn.current?.(d.successUrl??"")});return}if(d.status==="expired")throw ya(d);z=!0;let L=$??C??"full";Jn(L),zt.current+=1;let te=d.clientSecret||t;Ln.current=d.buyerIdentified===!1&&te?lo(F,wt,te,{...d.customer?.id?{userId:d.customer.id}:{}}):void 0,J(!1),vn(!1);let V=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),b=Gi(m);if(L==="auto"&&!Ut.current&&!V&&!b){Ut.current=!0;let Z=ye(m);try{if(await Kn.current(d,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Z,sessionId:wt||d.id}),k)return;await Z,k||N(!1);return}catch{if(k)return;await Z,k||N(!1);return}}await ye(m),k||N(!1)}catch(F){if(k)return;let m=qs(F,z);if(z&&Ct({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),m){let{errorCode:C,stage:L,...te}=m;Hi(A,o,I,C,L,te)}if(m?.stage==="provider_load"&&($??X?.data.session?.checkoutMode??"full")==="full"&&Us(X,U,qe)){let C=vu({billingApiUrl:A,locale:s,telemetry:o});Ke.current=C,On(C,null),rn(1),N(!1);return}let d=F instanceof mn&&m?.stage!=="provider_load"?F:zs();d!==F&&Rt(()=>Pn.current?.(d)),In(d),N(!1)}}async function ye(z){let{flopay:X,paypalFlopay:F,...m}=await Yi(z,{billingApiUrl:A,locale:s,telemetry:o});be.current={publishableKey:m.publishableKey,paypalPublishableKey:m.paypalPublishableKey},On(X,F),rn(0)}return ct(),B},[$,Rn,Zn,yn,t,U,qe]);let cr=wn(async()=>{if(!x||cn!==1)return;let k=_e.current;rn(2);try{let{flopay:f,paypalFlopay:G}=await Yi(x,{billingApiUrl:A,locale:s,telemetry:o});if(_e.current!==k)return;ae(),On(f,G),rn(0)}catch(f){if(_e.current!==k)return;let{errorCode:G,stage:B,...Ce}=ai(f);Hi(A,o,I,G,B,Ce)}},[ae,On,s,cn,A,o,I,x]),Fr=wn(async()=>{if(!(dn||!H)){Ht(!0),Oe(null);try{await vr(H,{attempt3DS:!0,fallbackToFull:!0,sessionId:wt||H.id})}finally{Ht(!1)}}},[wt,dn,vr,H]),nr=Zi(x),dr=Gi(x),Tn=Yn(()=>{if(!(!x||!H||!x.data.stripe?.publishableKey))return{billingApiUrl:A}},[x,H,A]),An=!!(n&&!T&&de==="buttons"&&ue&&Zn==="full"),Dr=!!(wt&&(H?.vault?.html||Ur(H))),Un=Yn(()=>({session:H,loading:sr,error:fn,checkoutMode:gn,inlineSessionDraft:Kt,applyInlineSessionPatch:An?En:void 0,inlineSessionPatchProcessing:an,claimPending:vt,claimRequiresIdentity:hn,claimBuyerIdentity:Ve,waitForDataAttachment:tn}),[H,sr,fn,gn,Kt,An,En,an,vt,hn,Ve,tn]),Nr=!!n&&de==="buttons"&&!dr&&!Dr&&(!Me||!Tn),Jt=on?re(yr,{status:on,errorMessage:jn,authorized:Gt}):null;if(sr&&!Dr){if(l)return en(hr,{children:[l,Jt]});if(de==="buttons"){let k=Te?.buttonsLayout?.cardButton?.borderRadius??Te?.appearance.variables?.borderRadius??8,f=G=>re("div",{style:{height:G,borderRadius:k,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return en(hr,{children:[en("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[U&&f(So),qe&&(S||W)&&f(So),qe&&f(So),re("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Jt]})}return en(hr,{children:[en("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[re("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),re("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Jt]})}return fn?p?re(ar.Provider,{value:Un,children:p(fn)}):re(ar.Provider,{value:Un,children:re("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:fn.message})}):Nr?en(hr,{children:[re(ar.Provider,{value:Un,children:re(Iu,{onButtonClick:$e,showPayPal:U,showStripe:qe,showApplePay:S,showGooglePay:W,theme:Le,buttonsTheme:Se,buttonsStyles:Re,cardButtonContent:Ge,cardBackButtonContent:St,cardTitleContent:tt})}),Jt]}):dr&&H&&nr?en(hr,{children:[re(ar.Provider,{value:Un,children:en("div",{className:st,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ae&&re(fo,{icon:!1,children:Ae}),$n==="retrying"&&re("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),$n==="exhausted"&&en("div",{role:"alert",children:[re("div",{children:"PayPal is temporarily unavailable. Please try again."}),re("button",{type:"button",onClick:Gr,children:"Retry PayPal"})]}),$n!=="exhausted"&&re("div",{"aria-hidden":$n==="retrying"?!0:void 0,style:$n==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:re(tl,{sessionId:wt,nonce:H.clientSecret||void 0,billingApiUrl:A,email:H.customer?.email||Kt?.account?.email,billingName:[H.customer?.firstName,H.customer?.lastName].filter(Boolean).join(" ")||[Kt?.account?.firstName,Kt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Ve,clientId:nr.clientId,environment:nr.environment,currency:(H.currency??"usd").toUpperCase(),isSubscription:H.mode==="subscription",providerObjectType:nr.providerObjectType,approvalPresentation:nr.approvalPresentation,onComplete:v,onErrorChange:Oe,onDecline:y,onButtonClick:$e,runBeforeButtonClick:pn,onInitializationStateChange:Br,allowAutomaticRetry:Yt===0,session:H,telemetry:o,telemetryContext:I,onInstrument:xt,debug:Y},`${R}:paypal-init-${Yt}`)})]})}),Jt]}):(!Me||!Tn)&&!(Dr&&gn==="full")?re(hr,{children:Jt}):gn==="confirm"?en(hr,{children:[re(ar.Provider,{value:Un,children:re(Ea,{flopay:Me,paypalFlopay:le,options:Tn??{billingApiUrl:A},onInstrument:xt,children:en("div",{className:st,children:[Ae&&re("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ae}),ie?ie({onConfirm:Fr,isProcessing:dn}):re("button",{type:"button",onClick:Fr,disabled:dn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:dn?"not-allowed":"pointer",opacity:dn?.6:1},children:dn?"Processing...":Ee??"Confirm Purchase"})]})},R)}),Jt]}):en(hr,{children:[re(ar.Provider,{value:Un,children:en(Ea,{flopay:Me,paypalFlopay:le,options:Tn??{billingApiUrl:A},onInstrument:xt,children:[cn===1&&re("button",{type:"button",onClick:cr,children:"Retry payment methods"}),T?en(hr,{children:[Ae&&re("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ae}),re(wu,{sessionId:wt,nonce:H?.clientSecret||void 0,billingApiUrl:A,session:H,submitLabel:he,children:T})]}):re(Vi,{sessionId:wt,nonce:H?.clientSecret||void 0,telemetry:o,email:H?.customer?.email||Kt?.account?.email,userId:H?.customer?.id||Kt?.account?.userId,firstName:H?.customer?.firstName||Kt?.account?.firstName,lastName:H?.customer?.lastName||Kt?.account?.lastName,totalAmount:H?Math.round(uu(H).total*100):0,currency:H?.currency?.toLowerCase()??"usd",onComplete:v,onError:g,onDecline:y,error:Ae,onErrorChange:Oe,showPayPal:U,showStripe:qe,enabledPaymentMethods:cn?[]:ge??x?.data.stripe?.enabledPaymentMethods??H?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:x?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:W,layout:de,theme:Le,buttonsTheme:Se,buttonsStyles:Re,appearance:dt,cardButtonContent:Ge,cardBackButtonContent:St,cardTitleContent:tt,onButtonClick:$e,onBeforeButtonClick:ue,onBuyerIdentityReady:Ve,enableAVS:we,...Xe?{cardFieldOrder:Xe}:{},...ee?{cardPreFormSlot:ee}:{},avsLayout:Ie,country:H?.customer?.country,city:H?.customer?.city,state:H?.customer?.state,onCountryChange:_,onZipChange:M,avsCheck:!!we,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Xi(T,de),className:st,submitLabel:he,directPaypal:Zi(x),isSubscription:H?.mode==="subscription",session:H,dataAttachmentPending:vt,dataAttachmentRequiresIdentity:hn,debug:Y})]},R)}),Jt]})}function wu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,children:i}){return re(hr,{children:Wi.Children.map(i,s=>{if(!Wi.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:Wi.cloneElement(s,p)})})}function Iu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:p,cardBackButtonContent:v,cardTitleContent:g}){let[h,y]=Ot(!1),_=Yn(()=>Wl(i),[i]),M=Yn(()=>{let S=_?.buttonsLayout??yu(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},[_,s,l]),U=_?.buttonsLayout?.cardButton?.borderRadius??_?.appearance.variables?.borderRadius??8,qe=S=>re("div",{style:{height:S,borderRadius:U,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),ge=p===void 0?{boxSizing:"border-box",height:So,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(h){let S=M.cardInputBorder??"#e5e7eb",W=M.cardInputBackground??"white",Y=oo(v),de=oo(g);return en("div",{style:{backgroundColor:M.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...M.cardFormContainer},children:[en("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[en("button",{type:"button",onClick:()=>y(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Y?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...M.backButton},children:[re("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...M.backButtonIcon},children:re("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:re("path",{d:"M15 18l-6-6 6-6"})})}),re(io,{content:v})]}),de?re("div",{style:{flex:1}}):re("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...M.title},children:re(Uo,{content:g})})]}),re("div",{style:{backgroundColor:W,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:re("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:[re("div",{style:{flex:1,backgroundColor:W,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:re("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{flex:1,backgroundColor:W,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:re("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),re("div",{style:{backgroundColor:W,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:re("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...M.submitButton,opacity:.5}}),re("style",{children:`
|
|
33
|
+
`}),qo&&$r&&Oe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:A?-2:0},children:[Oe("button",{type:"button",onClick:Kn,style:{display:"inline-flex",alignItems:"center",gap:mi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:j.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...j.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...j.backButtonIcon},children:d("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(yo,{content:wt})]}),js?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:j.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...j.title},children:d(Go,{content:fe})})]}),!qo&&!js&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:fi,order:A?-3:0,...j.title},children:d(Go,{content:fe})}),A&&N&&d("div",{style:{order:-2,width:"100%"},children:N}),A&&ht&&Oe("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[d("div",{style:{backgroundColor:so,border:`1px solid ${er(wa)}`,borderRadius:$t,padding:"10px"},children:d("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:En,onChange:a=>{It("email"),Wt.current=a.target.value,Hn(a.target.value)},onPointerDown:()=>It("email"),onKeyDown:()=>It("email"),onBlur:()=>{Un("email")&&Tn(!0),Mn||oi()},disabled:_e,required:!0,"aria-invalid":wa||void 0,"aria-describedby":wa?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...gi}})}),wa&&d("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:$o,children:je.empty?"Email address is required":"Enter a valid email address"})]}),X&&d("div",{style:{order:A?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=Ut,h=(J=!1)=>({backgroundColor:so,border:`1px solid ${er(J)}`,borderRadius:$t,marginTop:"0.5rem",padding:"10px"}),D=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...gi}),Pe=qd(a);return Oe(Qr,{children:[at(X.address_line_1,a)&&Oe(Qr,{children:[d("div",{style:h(Lt("line1")),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Nn,onChange:J=>{It("line1"),Tt.current.addressLine1=!0,Mt.current=J.target.value,vn(J.target.value)},onPointerDown:()=>It("line1"),onKeyDown:()=>It("line1"),onBlur:()=>lr("line1"),disabled:_e,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:D()})}),Lt("line1")&&d("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:$o,children:"Street address is required"})]}),at(X.address_line_2,a)&&d("div",{style:h(),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Vt,onChange:J=>{Tt.current.addressLine2=!0,yn.current=J.target.value,De(J.target.value)},disabled:_e,"data-testid":"flopay-address-line2",style:D()})}),(at(X.city,a)||at(X.state,a))&&Oe("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[at(X.city,a)&&d("div",{style:{flex:1,backgroundColor:so,borderTop:`1px solid ${er(Lt("city"))}`,borderRight:`1px solid ${er(Lt("city"))}`,borderBottom:`1px solid ${er(Lt("city"))}`,borderLeft:`1px solid ${er(Lt("city"))}`,padding:"10px",borderTopLeftRadius:$t,borderBottomLeftRadius:$t,...at(X.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:$t}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:we,onChange:J=>{It("city"),Tt.current.city=!0,Zt.current=J.target.value,Ln(J.target.value)},onPointerDown:()=>It("city"),onKeyDown:()=>It("city"),onBlur:()=>lr("city"),disabled:_e,required:!0,"aria-invalid":Lt("city")||void 0,"aria-describedby":Lt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:D()})}),at(X.state,a)&&d("div",{style:{flex:1,backgroundColor:so,borderTop:`1px solid ${er(Lt("state"))}`,borderRight:`1px solid ${er(Lt("state"))}`,borderBottom:`1px solid ${er(Lt("state"))}`,borderLeft:`1px solid ${er(Lt("state"))}`,padding:"10px",borderTopRightRadius:$t,borderBottomRightRadius:$t,...at(X.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${er(Lt("state")||Lt("city"))}`}:{borderRadius:$t}},children:Pe?Oe("select",{id:"flopay-billing-state",name:"billing-state",value:St,onChange:J=>{It("state"),Tt.current.state=!0,qt.current=J.target.value,bn(J.target.value)},onPointerDown:()=>It("state"),onKeyDown:()=>It("state"),onBlur:()=>lr("state"),disabled:_e,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:{...D(),cursor:"pointer"},children:[d("option",{value:"",children:Ki(a)}),Pe.map(J=>d("option",{value:J.code,children:J.name},J.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Ki(a),autoComplete:"billing address-level1",value:St,onChange:J=>{It("state"),Tt.current.state=!0,qt.current=J.target.value,bn(J.target.value)},onPointerDown:()=>It("state"),onKeyDown:()=>It("state"),onBlur:()=>lr("state"),disabled:_e,required:!0,"aria-invalid":Lt("state")||void 0,"aria-describedby":Lt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:D()})})]}),Lt("city")&&d("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:$o,children:"City is required"}),Lt("state")&&Oe("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:$o,children:[Ki(a)," is required"]}),(at(X.country,a)||at(X.postal_code,a))&&Oe("div",{style:{display:"flex",flexDirection:ue==="column"?"column":"row",gap:ue==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[at(X.country,a)&&d("div",{style:{flex:ue==="row"?1:void 0,backgroundColor:so,borderTop:`1px solid ${jo}`,borderRight:`1px solid ${jo}`,borderBottom:`1px solid ${jo}`,borderLeft:`1px solid ${jo}`,padding:"10px",...ue==="row"&&at(X.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:$t,borderBottomLeftRadius:$t,borderRight:"none"}:{borderRadius:$t}},children:d("select",{id:"flopay-billing-country",name:"billing-country",value:Ut,onChange:J=>{Tt.current.country=!0,kt.current=J.target.value,gn(J.target.value),Ye?.(J.target.value),qt.current="",bn("")},disabled:_e,autoComplete:"billing country","data-testid":"flopay-country",style:{...D(),cursor:"pointer"},children:Nd.map(J=>Oe("option",{value:J.code,children:[J.flag," ",J.name]},J.code))})}),at(X.postal_code,a)&&d("div",{style:{flex:ue==="row"?1:void 0,backgroundColor:so,border:`1px solid ${Ic}`,padding:"10px",...ue==="row"&&at(X.country,a)?{borderRadius:"0",borderTopRightRadius:$t,borderBottomRightRadius:$t}:{borderRadius:$t}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Zi(Ut),autoComplete:"billing postal-code",value:hn,onChange:J=>{It("zip"),Tt.current.zip=!0,ln.current=J.target.value,kn(J.target.value),He?.(J.target.value)},onPointerDown:()=>It("zip"),onKeyDown:()=>It("zip"),onBlur:()=>{Un("zip")&&Er(!0)},disabled:_e,required:zn.required,"aria-invalid":Sa||void 0,"aria-describedby":Sa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:D()})})]}),Sa&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:$o,children:zn.empty?`${Zi(a)} is required`:bu(a)})]})})()}),A&&Ac,ie&&d(Co,{margin:"0.75rem 0",styleOverride:j.errorBanner,children:ie})]}),ka={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"},Ws=a=>_?!I||!Cr?d("pre",{"data-testid":a,style:ka,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":a,style:ka,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${I}`,` directPaypalConfigured=${Cr}`,` inAppBrowserDetected=${String(ba)}`,` shouldRenderDirectPayPal=${No}`,` shouldRenderStripePayPal=${Lo}`,` hasPaypalStripeInstance=${!!to}`].join(`
|
|
34
|
+
`)}):null,Gs=a=>_?!G||!on?d("pre",{"data-testid":a,style:ka,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":a,style:ka,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${G}`,` currency=${oe}`,` amountInCents=${Fo}`,` enabledPaymentMethods: ${JSON.stringify(Y??[])}`,` enabledPaymentMethodsProvided=${Do}`,` hasEnabledMethods=${ga}`,` expressMethods: ${JSON.stringify(ha)}`,` walletExpressMethods: ${JSON.stringify(ao)}`,` paymentElementMethods: ${JSON.stringify(Oo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(va)}`,` hasStripeInstance=${!!on}`,` shouldRenderWallets=${io}`,` shouldRenderPaymentElement=${zo}`].join(`
|
|
35
|
+
`)}):null,Ys=nt==="apm-expanding"||nt==="apm-form"||nt==="apm-collapsing",co;nt==="apm-expanding"?co=zl:nt==="apm-collapsing"&&(co=Ul);let Ia=cn?ec(si,cn):null;if(Ce==="buttons"){let a=nt==="buttons"||nt==="expanding"||nt==="apm-expanding",h=nt==="expanding"||nt==="card"||nt==="collapsing",D=Me===void 0?{boxSizing:"border-box",height:Ya,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Pe;nt==="expanding"||nt==="apm-expanding"?Pe=mu:(nt==="collapsing"||nt==="apm-collapsing")&&(Pe=yu);let J;return nt==="expanding"?J=zl:nt==="collapsing"&&(J=Ul),Oe("form",{onSubmit:ui,className:R,noValidate:!0,style:{position:"relative"},children:[d(Xi,{}),S&&d(wr,{status:S,errorMessage:ie,authorized:en}),Oe("div",{style:{display:"grid"},children:[Oe("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!Pe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!Pe?gu:{},...Pe?{animation:Pe,pointerEvents:"none"}:{}},children:[Ws("flopay-direct-paypal-gate-debug"),Gs("flopay-stripe-gate-debug"),No&&Je&&Oe(Qr,{children:[E&&d("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),d(ea.Provider,{value:w,children:d(Oa,{sessionId:e,nonce:t,billingApiUrl:We,email:T.email,billingName:U||void 0,onBuyerIdentityReady:B,clientId:Je.clientId,environment:Je.environment,currency:oe.toUpperCase(),isSubscription:lt,providerObjectType:ze,approvalPresentation:Pa==="popup"?void 0:Pa,onTokenizedBody:Bn,onComplete:s,onErrorChange:me,onDecline:y,onTechnicalFailure:oo,onButtonClick:O,runBeforeButtonClick:dr,isProcessing:_e,onLoadStateChange:li,onInitializationStateChange:ci,session:ft,existingOrderId:E?.orderId,debug:_},E?.orderId??"fresh")})]}),Lo&&d(Zr,{stripe:to,options:Ps,children:d(Kl,{sessionId:e,nonce:t,email:T.email,billingName:U||void 0,onBuyerIdentityReady:B,billingApiUrl:We,onTokenizedBody:Bn,onErrorChange:me,isProcessing:_e,onButtonClick:O,onDecline:y,onTechnicalFailure:oo,runBeforeButtonClick:dr,onLoadStateChange:_s,placeholderBorderRadius:Hr,popupCapabilityOwner:w,externalTelemetryContext:$})}),io?d(Zr,{stripe:on,options:bs,children:d(Vl,{sessionId:e,nonce:t,email:T.email,billingName:U||void 0,onBuyerIdentityReady:B,billingApiUrl:We,intentKind:Q>0?"payment":"setup",expressMethods:ao,onTokenizedBody:Bn,onErrorChange:me,onButtonClick:O,onDecline:y,onTechnicalFailure:oo,runBeforeButtonClick:dr,onLoadStateChange:Es,placeholderBorderRadius:Hr,popupCapabilityOwner:w,externalTelemetryContext:$})}):null,!io&&Bs?d("div",{style:{height:Ya,borderRadius:Hr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,zo&&d(Hl,{sessionId:e,nonce:t,email:T.email,billingName:[T.firstName,T.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:B,billingApiUrl:We,paymentElementMethods:va,stripeInstance:on,paymentElementBaseOptions:si,onTokenizedBody:Bn,onErrorChange:me,onButtonClick:O,onDecline:y,runBeforeButtonClick:dr,onLoadStateChange:As,isProcessing:_e,submitButtonColor:Wr,submitButtonBorderRadius:$t,submitButtonStyle:j.submitButton,onExpandApm:Vr,expandedApmMethod:cn,themeId:$e,buttonAppearance:{backgroundColor:j.cardButton?.backgroundColor,borderColor:j.cardInputBorder,textColor:j.cardButton?.color,borderRadius:Hr}}),A&&d("button",{type:"button",onClick:async()=>{_e||!(await dr("card")).proceed||(O?.("card"),Kr())},disabled:_e,style:{width:"100%",...D,...j.cardButton,...is({themeBundle:Z,resolvedPrimaryColor:Wr,resolvedBorderRadius:$t,submitButtonStyle:j.submitButton,explicitPrimaryColor:Fn?.colorPrimary}),fontSize:j.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:_e?"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:_e?.6:1},onMouseEnter:dt=>{!_e&&(Z||Fn?.colorPrimary)&&(dt.currentTarget.style.backgroundColor=Ec)},onMouseLeave:dt=>{(Z||Fn?.colorPrimary)&&(dt.currentTarget.style.backgroundColor=Wr)},onMouseDown:dt=>{dt.currentTarget.style.transform="scale(0.985)"},onMouseUp:dt=>{dt.currentTarget.style.transform="scale(1)"},children:d(po,{content:Me})}),ie&&nt==="buttons"&&d(Co,{margin:"0.25rem 0",styleOverride:j.errorBanner,children:ie})]}),A&&h&&d("div",{style:{gridArea:"1 / 1",...J?{animation:J}:{},...nt==="collapsing"?{pointerEvents:"none"}:{}},children:Hs}),G&&Ys&&cn&&Ia&&on&&d("div",{style:{gridArea:"1 / 1",...co?{animation:co}:{},...nt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Oe("div",{style:{backgroundColor:yi,borderRadius:vi,...Ko,padding:hi},children:[Oe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Oe("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:rn,style:{display:"inline-flex",alignItems:"center",gap:mi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:j.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...j.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...j.backButtonIcon},children:d("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(yo,{content:wt})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:j.titleFontSize??"1.05rem",color:fi,paddingRight:80,...j.title},children:`Pay with ${eo(cn)}`})]}),d(Zr,{stripe:on,options:Ia,children:d(ts,{method:cn,sessionId:e,nonce:t,email:T.email,billingName:[T.firstName,T.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:B,billingApiUrl:We,onTokenizedBody:Bn,onErrorChange:me,onDecline:y,onCancel:rn,runBeforeButtonClick:dr,onButtonClick:O,isProcessing:_e,submitButtonColor:Wr,submitButtonBorderRadius:$t,submitButtonStyle:j.submitButton,errorText:ie})},cn)]})})]})]})}return Ys&&cn&&Ia&&on&&G?Oe("form",{onSubmit:ui,className:R,noValidate:!0,style:{position:"relative"},children:[d(Xi,{}),S&&d(wr,{status:S,errorMessage:ie,authorized:en}),d("div",{style:{...co?{animation:co}:{},...nt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Oe("div",{style:{backgroundColor:yi,borderRadius:vi,...Ko,padding:hi},children:[Oe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Oe("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:rn,style:{display:"inline-flex",alignItems:"center",gap:mi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:j.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...j.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...j.backButtonIcon},children:d("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(yo,{content:wt})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:j.titleFontSize??"1.05rem",color:fi,paddingRight:80,...j.title},children:`Pay with ${eo(cn)}`})]}),d(Zr,{stripe:on,options:Ia,children:d(ts,{method:cn,sessionId:e,nonce:t,email:T.email,billingName:[T.firstName,T.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:B,billingApiUrl:We,onTokenizedBody:Bn,onErrorChange:me,onDecline:y,onCancel:rn,runBeforeButtonClick:dr,onButtonClick:O,isProcessing:_e,submitButtonColor:Wr,submitButtonBorderRadius:$t,submitButtonStyle:j.submitButton,errorText:ie})},cn)]})})]}):Oe("form",{onSubmit:ui,className:R,noValidate:!0,style:{position:"relative"},children:[d(Xi,{}),S&&d(wr,{status:S,errorMessage:ie,authorized:en}),Oe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ws("flopay-direct-paypal-gate-debug-default"),Gs("flopay-stripe-gate-debug-default"),No&&Je&&Oe(Qr,{children:[E&&d("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),d(ea.Provider,{value:w,children:d(Oa,{sessionId:e,nonce:t,billingApiUrl:We,email:T.email,billingName:U||void 0,onBuyerIdentityReady:B,clientId:Je.clientId,environment:Je.environment,currency:oe.toUpperCase(),isSubscription:lt,providerObjectType:ze,approvalPresentation:Pa==="popup"?void 0:Pa,onTokenizedBody:Bn,onComplete:s,onErrorChange:me,onDecline:y,onTechnicalFailure:oo,onButtonClick:O,runBeforeButtonClick:dr,isProcessing:_e,onLoadStateChange:li,onInitializationStateChange:ci,session:ft,existingOrderId:E?.orderId,debug:_},E?.orderId??"fresh")})]}),Lo&&d(Zr,{stripe:to,options:Ps,children:d(Kl,{sessionId:e,nonce:t,email:T.email,billingName:U||void 0,onBuyerIdentityReady:B,billingApiUrl:We,onTokenizedBody:Bn,onErrorChange:me,isProcessing:_e,onButtonClick:O,onDecline:y,onTechnicalFailure:oo,runBeforeButtonClick:dr,onLoadStateChange:_s,placeholderBorderRadius:Hr,popupCapabilityOwner:w,externalTelemetryContext:$})}),io&&d(Zr,{stripe:on,options:bs,children:d(Vl,{sessionId:e,nonce:t,email:T.email,billingName:U||void 0,onBuyerIdentityReady:B,billingApiUrl:We,intentKind:Q>0?"payment":"setup",expressMethods:ao,onTokenizedBody:Bn,onErrorChange:me,onButtonClick:O,onDecline:y,onTechnicalFailure:oo,runBeforeButtonClick:dr,onLoadStateChange:Es,placeholderBorderRadius:Hr,popupCapabilityOwner:w,externalTelemetryContext:$})}),zo&&d(Hl,{sessionId:e,nonce:t,email:T.email,billingName:[T.firstName,T.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:We,paymentElementMethods:va,stripeInstance:on,paymentElementBaseOptions:si,onTokenizedBody:Bn,onErrorChange:me,onButtonClick:O,onDecline:y,runBeforeButtonClick:dr,onLoadStateChange:As,isProcessing:_e,submitButtonColor:Wr,submitButtonBorderRadius:$t,submitButtonStyle:j.submitButton,themeId:$e,onExpandApm:Vr,expandedApmMethod:cn,buttonAppearance:{backgroundColor:j.cardButton?.backgroundColor,borderColor:j.cardInputBorder,textColor:j.cardButton?.color,borderRadius:Hr}})]}),A&&(Cc||Pc||wc)&&Oe("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),d("span",{children:"or pay with card"}),d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),A&&Hs]})}import{Fragment as Rr,jsx as se,jsxs as sn}from"react/jsx-runtime";var Ao=44,ms="flopay_checkout_saved_payment_resume",ti=new Map,Qa=new Map;function nc(e,t){t.settled&&t.consumers===0&&ti.get(e)===t&&ti.delete(e)}function Mu(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 ua(e){return new Promise(t=>setTimeout(t,e))}function ei(e,t,n){let r=Fa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:dc,enabled:t!==!1});return r.beginCheckout(n),r}function pa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function cs(e,t,n,r,o,i){let s=ei(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),pa(s)}function rc(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 oc(e,t,n,r,o){let i=lc(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 uc(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 ds(e){return!e||e.data.stripe?.publishableKey?!1:!!uc(e)?.clientId}var Bu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Fu(e){return new Iu(Bu,{publishableKey:"provider_unavailable",...e})}async function us(e,t){let{publishableKey:n,paypalPublishableKey:r}=qi(e);return{...await ji({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function fs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Du(){if(!fs())return null;try{let e=window.sessionStorage.getItem(ms);return e?JSON.parse(e):null}catch{return null}}function ac(e){if(fs())try{window.sessionStorage.setItem(ms,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ps(){if(fs())try{window.sessionStorage.removeItem(ms)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Ou(){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 ic(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 ys(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Nu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function sc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Lu(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 gs({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:s,loading:l,error:y,onComplete:f,onError:b,onInstrument:g,onDecline:M,onCountryChange:R,onZipChange:C,showPayPal:v=!0,showStripe:q=!0,enabledPaymentMethods:Re,showApplePay:I=!0,showGooglePay:G=!0,debug:Y=!1,layout:re,theme:ve,buttonsTheme:Le,buttonsStyles:Ce,cardButtonContent:$e,cardBackButtonContent:vt,cardTitleContent:Ke,showSecurityFooter:Ne,onButtonClick:Me,onBeforeButtonClick:wt,enableAVS:fe,cardFieldOrder:ut,cardPreFormSlot:O,avsLayout:Ae,submitLabel:yt,className:Be,initialErrorMessage:it=null,initialPayPalOrderId:N,children:ue,checkoutMode:ge,confirmLabel:K,renderConfirmButton:Ge,onSessionCompleted:Ve}){let L=Tu(r),st=ar(()=>cc(ve),[ve]),Ye=i??st?.appearance,He=n?"embedded_checkout":"standard_checkout",Ee=ys(ue,re),[le,mt]=zt(null),[Q,oe]=zt(null),Fe=At(null),Je=At(null),lt=At(0),[z,pt]=zt(null),Xe=At(null),[_,ct]=zt(null),Jt=ar(()=>n?So(n):"",[n]),xe=n?`create:${Jt}`:`session:${e??""}`,un=sc(_),c=At(new Set),w=At(xe),ne=At(xe);Ho(()=>{ne.current=xe,w.current!==xe&&(w.current=xe,c.current.clear())},[xe]);let k=wn(S=>{if(ne.current===xe){if(Ri.has(S.name)){if(c.current.has(S.name))return;c.current.add(S.name)}Ft(()=>g?.(S))}},[xe,g]),$=Po(k,xe),ft=At(!1),ze=wn(S=>{if(ft.current)return;let m=S.gateway||!un?S:{...S,gateway:un};k(m)},[k,un]);yr(()=>{$({class:"lifecycle",name:"checkout.mount"})},[$]);let[Ue,xt]=zt(e??""),ee=e??Ue,pn=n?"":ee,[We,Dt]=zt(!0),[Rn,Kt]=zt(null),[Te,Ut]=zt(0),[gn,hn]=zt("full"),[kn,Nn]=zt(!1),[vn,Vt]=zt(it),[De,we]=zt(null),[Ln,St]=zt(null),[bn,En]=zt(!1),[Hn,Ht]=zt(void 0),[Xt,ln]=zt(""),[kt,Mt]=zt(!1),[yn,Zt]=zt(!1),[qt,Wt]=zt(!1),Tt=At(null),X=At(0),Qt=At(void 0),[en,ir]=zt("loading"),[mr,Wn]=zt(0),Gt=At(!1),sr=At(!1),jt=At(!1),A=At(null),gt=At(null),Ze=ar(()=>({checkoutMode:ge??gn,layout:Nu(ue,re)}),[ge,ue,gn,re]),x=At(f);x.current=f;let qe=At(b);qe.current=b;let te=At(M);te.current=M;let tn=wn(S=>$a(A,async m=>{try{return await S(m)}catch(W){throw m.aborted?sa(W):W}}),[]);yr(()=>()=>{A.current?.abort(),A.current=null},[]);let Pn=wn((S,m)=>{Fe.current=S,oe(S),Xe.current=m,pt(m)},[]),nn=wn(()=>{let S=Je.current;S&&(Je.current=null,S.destroy())},[]);yr(()=>{mn(Q)?.setCheckoutContext(Ze),z&&z!==Q&&mn(z)?.setCheckoutContext(Ze)},[Q,z,Ze]);let fr=At(Ve);fr.current=Ve;let he=wn(S=>{ir(S),!(S!=="exhausted"||jt.current)&&(jt.current=!0,qe.current?.(new Sn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),zn=wn(()=>{ir("retrying"),Wn(S=>S+1)},[]);yr(()=>{ir("loading"),Wn(0),jt.current=!1},[ee]),yr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:dc,checkout_type:He,checkout_layout:Ee,billing_api_url:L})},[Ee,He,L]);let Gn=ar(()=>n?So(n,!0):"",[n]),jr=ar(()=>Xt===Gn?Hn:void 0,[Hn,Xt,Gn]),Yn=ar(()=>n?wi(n,jr):void 0,[n,jr]),Jn=ge??Yn?.checkoutMode??"full",Yt=ar(()=>Yn?{...Yn,checkoutMode:Jn}:void 0,[Yn,Jn]);yr(()=>{Ht(void 0),ln(Gn),Qt.current=void 0,Tt.current=null,Wt(!1)},[Gn]),yr(()=>{Vt(it)},[it]);let Er=wn((S,m,W)=>{Ft(()=>{te.current?.(dn(S,m,W))})},[]),gr=wn(async(S,m)=>{Vt(null),St(null),En(!1),we("processing");let W=m?.sessionId??S.id,F=S.clientSecret||t,be=sc(S),Nt=Fe.current??Xe.current,ye=mn(Nt),pe=Nt?null:ei(L,o,Ze),E={log:ae=>{ye?ye.log(ae):pe?.log(ae)},error:ae=>{ye?ye.error(ae):pe?.error(ae)},terminal:ae=>{ye?ye.terminal(ae):pe?.terminal(ae)},performance:ae=>{ye?ye.performance(ae):pe?.performance(ae)},now:()=>ye?.now()??pe?.now()??0,elapsed:ae=>ye?.elapsed(ae)??Math.max(0,(pe?.now()??ae)-ae)},V=E.now(),p=!!(m?.initialAutoProcessingError||m?.initialAutoProcessingPending),u=!1,P,B=()=>{u||(u=!0,p=!0,P=E.now(),E.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),E.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ie=!1,Z=()=>{ie||(ie=!0,E.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),E.performance({stage:"processing",durationMs:E.elapsed(V),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),P!==void 0&&E.performance({stage:"recovery",durationMs:E.elapsed(P),durationMode:"machine",paymentMethodCategory:"saved"}))};E.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ft.current=!0;try{E.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ft.current=!1}$({class:"lifecycle",name:"payment.processing.started",provider:be}),p&&B();let j;try{let ae=Tl(m?.initialAutoProcessingError),Se=m?.initialAutoProcessingError?.type==="3ds_required"&&!m.initialAutoProcessingError.threeDSecureToken&&m.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:m.initialAutoProcessingError.nextActionRedirectUrl}:null,bt,_e=H=>(B(),tn(T=>Io(H,{billingApiUrl:L,sessionId:W,nonce:F,session:S,signal:T})));if(Se)bt=await _e(Se);else if(ae)B(),ae.type==="paypal_redirect_required"&>.current?.publishableKey&&ac({sessionId:W,publishableKey:gt.current.publishableKey,paypalPublishableKey:gt.current.paypalPublishableKey}),bt=await tn(H=>Va(ae,{flopay:Fe.current,paypalFlopay:Xe.current,attempt3DS:m?.attempt3DS,billingApiUrl:L,sessionId:W,session:S,telemetry:!1,signal:H})),ae.type==="paypal_redirect_required"&&ps();else if(m?.initialAutoProcessingPending){let H=m.initialAutoProcessingPending,T=new Za(L,{telemetry:!1}),U=await tn(ht=>T.waitForCheckoutSessionCompletion(H.sessionId,{initialDelayMs:H.retryAfterMs,nonce:F,statusUrl:H.statusUrl,signal:ht})),ke=U.data.session,Ie=U.autoProcessingError?.type==="3ds_required"&&U.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:U.autoProcessingError.nextActionRedirectUrl}:null;if(Ie)bt=await _e(Ie);else{if(!Fr(ke))throw go(ke);bt=Tr(ke,W)}}else{if(m?.initialAutoProcessingError)throw Ir(m.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:m.initialAutoProcessingError.checkoutMethod});if(m?.fromCreateSession)return m?.fallbackToFull&&(hn("full"),ic("full")),!1;{let H=await _o({billingApiUrl:L,sessionId:W,session:S,nonce:F,telemetry:!1});H.type==="success"?bt=H.result:H.type==="next_action_required"?bt=await _e(H):(B(),H.type==="paypal_redirect_required"&>.current?.publishableKey&&ac({sessionId:W,publishableKey:gt.current.publishableKey,paypalPublishableKey:gt.current.paypalPublishableKey}),bt=await tn(T=>Va(H,{flopay:Fe.current,paypalFlopay:Xe.current,attempt3DS:m?.attempt3DS,billingApiUrl:L,sessionId:W,session:S,telemetry:!1,signal:T})),H.type==="paypal_redirect_required"&&ps())}}W&&ko(W),Z(),p&&(E.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),E.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),E.terminal({outcome:bt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),En(bt.status==="authorized"),we("success"),await ua(600),j=()=>x.current?.(bt)}catch(ae){let Se=la(ae);if(Se.code==="three_ds_aborted")return!1;let bt=Se.checkoutMethod??ia;Vt(Se.message),St(Se.message),En(!1),m?.fallbackToFull&&(E.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),hn("full"),ic("full")),Z();let _e=Se.statusCode===void 0?void 0:xu(Se.statusCode,"unknown"),H=_e==="4xx"?{requestCategory:"process_payment",statusClass:_e}:{},T=_e===void 0||_e==="4xx";if(T&&(Se.telemetryOutcome==="payment_declined"||!!(Se.declineCode||Se.code?.toLowerCase().includes("declin"))))E.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...H});else if(T&&(Se.telemetryOutcome==="validation_rejected"||Se.type==="validation_error"))E.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...H});else{let Ie=lc(ae,p?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),ht=Se.telemetryRequestCategory??"process_payment";ft.current=!0;try{E.error({...Ie,...Se.telemetryFailureCategory?{failureCategory:Se.telemetryFailureCategory}:{},stage:p?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:ht})}finally{ft.current=!1}$({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:ht,provider:be})}return Ft(()=>qe.current?.(Se)),Er(bt,Se,{code:Se.code,declineCode:Se.declineCode}),we("error"),await Promise.allSettled([ua(400),m?.ensureProvidersReady?m.ensureProvidersReady():Promise.resolve()]),p&&(E.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),E.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Z(),pe&&pa(pe),we(null),St(null)}return Ft(j),!0},[Er,$,t,L,tn,o,Ze]);yr(()=>{if(typeof window>"u"||sr.current)return;let S=new URLSearchParams(window.location.search),m=S.get("payment_intent_client_secret");if(!m)return;let W=Du();W&&(sr.current=!0,(async()=>{let F,be=0;Vt(null),St(null),we("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:Nt,paypalFlopay:ye}=await ji({publishableKey:W.publishableKey,paypalPublishableKey:W.paypalPublishableKey,billingApiUrl:L,locale:s,telemetry:o});F=mn(ye??Nt),F?.setCheckoutContext(Ze),be=F?.now()??0,F?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),F?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let pe=(ye??Nt)?.getRawProvider();if(!pe)throw Object.assign(new Sn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:E,error:V}=await pe.retrievePaymentIntent(m);if(V)throw Object.assign(new Sn(V.message??"Failed to retrieve PayPal payment status.","api_error",{code:V.code}),{checkoutMethod:"paypal"});let p=il(E?.status);if(!E||p==="failed")throw Object.assign(new Sn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let u=typeof E.payment_method=="string"?E.payment_method:E.payment_method?.id,P=p;if(W.sessionId){let Z=(await new Za(L,{telemetry:!1}).getUnifiedCheckoutSession(W.sessionId)).data.session;if(Z&&Z.status!=="complete"){let j=await _o({billingApiUrl:L,sessionId:W.sessionId,session:Z,telemetry:!1,tokenizedData:{id:u??E.id,type:"card",threeDSecureActionResultTokenId:E.id,isPaypal:!0}});if(j.type!=="success")throw Object.assign(new Sn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});P=j.result.status}}W.sessionId&&ko(W.sessionId),F?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),F?.performance({stage:"redirect_resume",durationMs:F.elapsed(be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),F?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),we("success"),await ua(600),Ft(()=>x.current?.({status:P,paymentIntentId:E.id,paymentMethodId:u,checkoutMethod:"paypal"}))}catch(Nt){let ye=la(Nt),pe=ye.checkoutMethod??"paypal",E=!!(ye.declineCode||ye.code?.toLowerCase().includes("declin"));if(F)F.performance({stage:"redirect_resume",durationMs:F.elapsed(be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),E?F.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):F.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(E){let V=ei(L,o,Ze);V.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),pa(V)}else cs(L,o,Ze,"REDIRECT_RESUME_FAILED","redirect_resume");Vt(ye.message),St(ye.message),Ft(()=>qe.current?.(ye)),Er(pe,ye,{code:ye.code,declineCode:ye.declineCode}),we("error"),await ua(400)}finally{ps(),Ou(),we(null),St(null),Nn(!1)}})())},[Er,s,L,o,Ze]);let Tn=At(null),hr=ar(()=>Yt?So(Yt):"",[Yt]),Xn=At(Yt);Xn.current=Yt,yr(()=>{xt(e??"")},[e]),yr(()=>{Gt.current=!1,Vt(it),St(null),En(!1),we(null)},[hr,it,e]);async function Zn(S,m,W){let F=ei(L,o,Ze),be=new Za(L,{telemetry:!1}),Nt=!1;try{let ye=S.idempotencyKey===void 0?void 0:tc(S.idempotencyKey),pe=Fi(m,W),E=Di(m,W);pe?.canonicalIdentity===W&&E&&E.canonicalIdentity===void 0&&(Ua(m,W,E.idempotencyKey),E={...E,canonicalIdentity:W});let V=ye??(E?.canonicalIdentity===W?E.idempotencyKey:void 0),p,u=!1;F.log({name:pe?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let P=pe?.sid??null,B=null,ie,Z,j=!1;if(P)try{B=await be.getUnifiedCheckoutSession(P,pe?.nonce),pe&&pe.canonicalIdentity===void 0&&(wl(B.data.session,S)?(za(m,W,P,pe.nonce??B.data.session?.clientSecret),E&&E.canonicalIdentity===void 0&&(Ua(m,W,E.idempotencyKey),V??(V=E.idempotencyKey))):(La(m,W),E=null,V=ye,P=null,B=null));let Se=B?.data.session?.status,bt=B?.data.session,_e=bt?.clientSecret||pe?.nonce;if(P&&bt?.buyerIdentified===!1&&_e&&(Z=fo(be,P,_e,S.account)),P&&B&&Se==="complete"){if(Oi(P))return{sid:P,result:B};La(m,W),P=null,B=null,u=!0}}catch{F.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),pe?.canonicalIdentity===void 0?(La(m,W),V=ye):Na(m,W),P=null}if(!P){!ye&&(u||!V)&&(V=tc(),p=V),V&&Ua(m,W,V);let Se=F.now(),bt=0;F.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let _e={...S,idempotencyKey:V,avsCheck:!!fe,avsConfig:typeof fe=="object"?fe:void 0,checkoutType:"embedded_checkout",checkoutLayout:ys(ue,re)};Object.defineProperty(_e,_u,{configurable:!1,enumerable:!1,value:{onAttempt:U=>{bt=Math.max(bt,U)}}});let H=()=>{rc(F,"session_create",Se,bt)},T=U=>{oc(F,U,"session_create",Se,bt)&&$({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(Eu(_e)){let U=await be.createDetachedSession(_e);U.claimed.catch(()=>{}),B=U.shell,P=U.sessionId,Z=U.claim;let ke=F.now();F.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ie=U.claimed.then(Ie=>{let ht=Ie.data.session?.id??U.sessionId;return ht&&za(m,W,ht,Ie.data.session?.clientSecret??U.nonce),rc(F,"session_claim",ke),H(),Ie},Ie=>{throw Na(m,W),oc(F,Ie,"session_claim",ke,0)&&$({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Ie}).finally(()=>pa(F)),ie.catch(()=>{}),Nt=!0,F.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),F.performance({stage:"session_shell",durationMs:F.now()-Se,durationMode:"machine",requestCategory:"session_create",attempt:bt,statusClass:"2xx",paymentMethodCategory:"card"})}else B=await be.createAndFetchSession(_e),H()}catch(U){throw T(U),U}P=B.data.session?.id??P??"",P&&!ie&&za(m,W,P,B.data.session?.clientSecret)}let ae=B?.data.session;return!Z&&P&&ae?.buyerIdentified===!1&&ae.clientSecret&&(Z=fo(be,P,ae.clientSecret,S.account)),{sid:P??"",result:B,sdkGeneratedIdempotencyKey:p,...ie?{claimed:ie}:{},...Z?{claim:Z}:{},...j?{claimRequiresIdentity:!0}:{}}}finally{Nt||pa(F)}}let vr=At(Zn);Ho(()=>{vr.current=Zn},[Zn]);let Qn=wn(async(S,m)=>{let W=Xn.current;if(!W)throw new Sn("createSession is required to bootstrap checkout.","validation_error");let F=wi(W,S),be=So(F),Nt=Cl(F),ye=ti.get(be);if(!ye){let V={canonicalIdentity:be,promise:vr.current(F,Nt,be),consumers:0,settled:!1};ye=V,ti.set(be,V);let p=()=>{V.settled=!0,nc(be,V)};V.promise.then(p,p)}ye.consumers+=1;let pe=!1,E=()=>{pe||(pe=!0,ye.consumers-=1,nc(be,ye))};m?.(E);try{let V=await ye.promise;Tn.current=be,S&&(ln(Gn),Ht(ae=>rl(ae,S)));let{sid:p,result:u,claimed:P,claim:B,claimRequiresIdentity:ie}=V;if(Qt.current=B,Wt(ie===!0),mt(u),u.data.session&&ct(u.data.session),p&&xt(p),P){X.current+=1;let ae=X.current;Tt.current=P,Zt(!0),P.then(Se=>{X.current===ae&&(Tt.current===P&&(Tt.current=null),mt(Se),Se.data.session&&ct(Se.data.session),Zt(!1),Wt(!1))},Se=>{X.current===ae&&(Tt.current===P&&(Tt.current=null),Zt(!1),Wt(!1),Kt(Se instanceof Sn?Se:new Sn(Se instanceof Error?Se.message:"Failed to create session","api_error")))})}else X.current+=1,Tt.current=null,Zt(!1),Wt(!1);let{flopay:Z,paypalFlopay:j}=await us(u,{billingApiUrl:L,locale:s,telemetry:o});return Pn(Z,j),Dt(!1),V}catch(V){throw Tn.current===be&&(Tn.current=null),V}finally{m||E()}},[Gn,Pn,s,L,o]),It=At(gr);It.current=gr;let Un=At(Qn);Un.current=Qn;let lr=wn(async S=>{if(!Lu(S)||kt)return{sessionId:Ue,session:_};Mt(!0);try{let m=await Qn(S);return{sessionId:m.sid,session:m.result.data.session??null}}finally{Mt(!1)}},[Qn,kt,Ue,_]),qn=wn(async S=>{let m=Qt.current;if(!m)return;let W=X.current,F=await m(S);X.current===W&&(mt(F),F.data.session&&ct(F.data.session))},[]),Cn=wn(async()=>{await Tt.current},[]),nt=wn(async()=>(await Cn(),{proceed:!0}),[Cn]);yr(()=>{let S=!1,m,W=++lt.current;nn(),Kt(null),Ut(0);let F=()=>{S=!0,lt.current===W&&(lt.current+=1,nn())},be=Xn.current;if(hr&&be)return hn(Jn),Dt(!1),Tn.current===hr?F:(ct(ol(be,ge)),(async()=>{let pe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),E=Jn==="auto"&&!Gt.current&&!pe;E&&(Vt(null),St(null),we("processing"));try{let V=await Un.current(void 0,B=>{m=B}),p=V.result.data.session??null;gt.current=qi(V.result);let u=ds(V.result),P=Oi(V.sid||p?.id);if(!S&&E&&p&&!u&&!P){Gt.current=!0,await Mu(hr,V.sdkGeneratedIdempotencyKey,()=>It.current(p,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:V.result.autoProcessingError,initialAutoProcessingPending:V.result.autoProcessingPending,autoProcessingAttempted:V.result.autoProcessingAttempted,sessionId:V.sid||p.id}));return}!S&&E&&((u||P)&&(Gt.current=!0),we(null),St(null))}catch(V){if(S)return;let p=Ra(V);if(E&&p==="session_auto_completed"){Gt.current=!0,we("success"),await ua(600),S||(Ft(()=>{x.current?.({status:"succeeded"})}),we(null),St(null));return}E&&(we(null),St(null));let u=V instanceof Sn?V:new Sn(V instanceof Error?V.message:"Failed to create session","api_error");Kt(u)}finally{m?.(),m=void 0}})(),()=>{F(),m?.()});Dt(!0);async function Nt(){let pe=!1,E=null;try{let V=new Za(L,{telemetry:!1}),p=await V.getUnifiedCheckoutSession(ee,t);if(E=p,S)return;mt(p);let u=p.data.session??null;if(ct(u),!u)throw new Sn("No session data returned","api_error");let P=u.checkoutMode;if(P==="setup")throw new Sn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(u.status==="authorized"){Dt(!1),Ft(()=>{x.current?.(Tr(u,ee)),fr.current?.(u.successUrl??"")});return}if(u.status==="complete"){Dt(!1),Ft(()=>{fr.current?.(u.successUrl??"")});return}if(u.status==="expired")throw _a(u);pe=!0;let B=ge??P??"full";hn(B),X.current+=1;let ie=u.clientSecret||t;Qt.current=u.buyerIdentified===!1&&ie?fo(V,ee,ie,{...u.customer?.id?{userId:u.customer.id}:{}}):void 0,Zt(!1),Wt(!1);let Z=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),j=ds(p);if(B==="auto"&&!Gt.current&&!Z&&!j){Gt.current=!0;let ae=ye(p);try{if(await It.current(u,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ae,sessionId:ee||u.id}),S)return;await ae,S||Dt(!1);return}catch{if(S)return;await ae,S||Dt(!1);return}}await ye(p),S||Dt(!1)}catch(V){if(S)return;let p=nl(V,pe);if(pe&&$({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),p){let{errorCode:P,stage:B,...ie}=p;cs(L,o,Ze,P,B,ie)}if(p?.stage==="provider_load"&&(ge??E?.data.session?.checkoutMode??"full")==="full"&&tl(E,v,q)){let P=Fu({billingApiUrl:L,locale:s,telemetry:o});Je.current=P,Pn(P,null),Ut(1),Dt(!1);return}let u=V instanceof Sn&&p?.stage!=="provider_load"?V:el();u!==V&&Ft(()=>qe.current?.(u)),Kt(u),Dt(!1)}}async function ye(pe){let{flopay:E,paypalFlopay:V,...p}=await us(pe,{billingApiUrl:L,locale:s,telemetry:o});gt.current={publishableKey:p.publishableKey,paypalPublishableKey:p.paypalPublishableKey},Pn(E,V),Ut(0)}return Nt(),F},[ge,hr,Jn,pn,t,v,q]);let In=wn(async()=>{if(!le||Te!==1)return;let S=lt.current;Ut(2);try{let{flopay:m,paypalFlopay:W}=await us(le,{billingApiUrl:L,locale:s,telemetry:o});if(lt.current!==S)return;nn(),Pn(m,W),Ut(0)}catch(m){if(lt.current!==S)return;let{errorCode:W,stage:F,...be}=Pi(m);cs(L,o,Ze,W,F,be)}},[nn,Pn,s,Te,L,o,Ze,le]),cn=!!(ee&&(_?.clientSecret||t)),jn=kn||!cn,$r=wn(async()=>{if(!(kn||!cn||!_)){Nn(!0),Vt(null);try{await gr(_,{attempt3DS:!0,fallbackToFull:!0,sessionId:ee||_.id})}finally{Nn(!1)}}},[ee,kn,cn,gr,_]),$n=uc(le,N),br=ds(le),An=ar(()=>{if(!(!le||!_||!le.data.stripe?.publishableKey))return{billingApiUrl:L}},[le,_,L]),xn=!!(n&&!ue&&re==="buttons"&&wt&&Jn==="full"),Kr=!!(ee&&(_?.vault?.html||Mr(_))),Kn=ar(()=>({session:_,loading:We,error:Rn,checkoutMode:gn,inlineSessionDraft:Yt,applyInlineSessionPatch:xn?lr:void 0,inlineSessionPatchProcessing:kt,claimPending:yn,claimRequiresIdentity:qt,claimBuyerIdentity:qn,waitForDataAttachment:Cn}),[_,We,Rn,gn,Yt,xn,lr,kt,yn,qt,qn,Cn]),Vr=!!n&&re==="buttons"&&!br&&!Kr&&(!Q||!An),rn=De?se(wr,{status:De,errorMessage:Ln,authorized:bn}):null;if(We&&!Kr){if(l)return sn(Rr,{children:[l,rn]});if(re==="buttons"){let S=st?.buttonsLayout?.cardButton?.borderRadius??st?.appearance.variables?.borderRadius??8,m=W=>se("div",{style:{height:W,borderRadius:S,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return sn(Rr,{children:[sn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[v&&m(Ao),q&&(I||G)&&m(Ao),q&&m(Ao),se("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),rn]})}return sn(Rr,{children:[sn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[se("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),se("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),rn]})}return Rn?y?se(ur.Provider,{value:Kn,children:y(Rn)}):se(ur.Provider,{value:Kn,children:se("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Rn.message})}):Vr?sn(Rr,{children:[se(ur.Provider,{value:Kn,children:se(Uu,{onButtonClick:Me,showPayPal:v,showStripe:q,showApplePay:I,showGooglePay:G,theme:ve,buttonsTheme:Le,buttonsStyles:Ce,cardButtonContent:$e,cardBackButtonContent:vt,cardTitleContent:Ke})}),rn]}):br&&_&&$n?sn(Rr,{children:[se(ur.Provider,{value:Kn,children:sn("div",{className:Be,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[vn&&se(Co,{icon:!1,children:vn}),en==="retrying"&&se("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),en==="exhausted"&&sn("div",{role:"alert",children:[se("div",{children:"PayPal is temporarily unavailable. Please try again."}),se("button",{type:"button",onClick:zn,children:"Retry PayPal"})]}),en!=="exhausted"&&se("div",{"aria-hidden":en==="retrying"?!0:void 0,style:en==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:se(bl,{sessionId:ee,nonce:_.clientSecret||void 0,billingApiUrl:L,email:_.customer?.email||Yt?.account?.email,billingName:[_.customer?.firstName,_.customer?.lastName].filter(Boolean).join(" ")||[Yt?.account?.firstName,Yt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:qn,clientId:$n.clientId,environment:$n.environment,currency:(_.currency??"usd").toUpperCase(),isSubscription:_.mode==="subscription",providerObjectType:$n.providerObjectType,approvalPresentation:$n.approvalPresentation,existingOrderId:$n.existingOrderId,onComplete:f,onErrorChange:Vt,onDecline:M,onButtonClick:Me,runBeforeButtonClick:nt,onInitializationStateChange:he,allowAutomaticRetry:mr===0,session:_,telemetry:o,telemetryContext:Ze,onInstrument:ze,debug:Y},`${xe}:paypal-init-${mr}`)})]})}),rn]}):gn==="confirm"?sn(Rr,{children:[se(ur.Provider,{value:Kn,children:se(qa,{flopay:Q,paypalFlopay:z,options:An??{billingApiUrl:L},onInstrument:ze,children:sn("div",{className:Be,children:[vn&&se("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:vn}),Ge?Ge({onConfirm:$r,isProcessing:jn}):se("button",{type:"button",onClick:$r,disabled:jn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:jn?"not-allowed":"pointer",opacity:jn?.6:1},children:kn?"Processing...":K??"Confirm Purchase"})]})},xe)}),rn]}):(!Q||!An)&&!(Kr&&gn==="full")?se(Rr,{children:rn}):sn(Rr,{children:[se(ur.Provider,{value:Kn,children:sn(qa,{flopay:Q,paypalFlopay:z,options:An??{billingApiUrl:L},onInstrument:ze,children:[Te===1&&se("button",{type:"button",onClick:In,children:"Retry payment methods"}),ue?sn(Rr,{children:[vn&&se("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:vn}),se(zu,{sessionId:ee,nonce:_?.clientSecret||void 0,billingApiUrl:L,session:_,submitLabel:yt,children:ue})]}):se(ss,{sessionId:ee,nonce:_?.clientSecret||void 0,telemetry:o,email:_?.customer?.email||Yt?.account?.email,userId:_?.customer?.id||Yt?.account?.userId,firstName:_?.customer?.firstName||Yt?.account?.firstName,lastName:_?.customer?.lastName||Yt?.account?.lastName,totalAmount:_?Math.round(Ru(_).total*100):0,currency:_?.currency?.toLowerCase()??"usd",onComplete:f,onError:b,onDecline:M,error:vn,onErrorChange:Vt,showPayPal:v,showStripe:q,enabledPaymentMethods:Te?[]:Re??le?.data.stripe?.enabledPaymentMethods??_?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:le?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:G,layout:re,theme:ve,buttonsTheme:Le,buttonsStyles:Ce,appearance:Ye,cardButtonContent:$e,cardBackButtonContent:vt,cardTitleContent:Ke,onButtonClick:Me,onBeforeButtonClick:wt,onBuyerIdentityReady:qn,enableAVS:fe,...ut?{cardFieldOrder:ut}:{},...O?{cardPreFormSlot:O}:{},avsLayout:Ae,country:_?.customer?.country,city:_?.customer?.city,state:_?.customer?.state,onCountryChange:R,onZipChange:C,avsCheck:!!fe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ys(ue,re),className:Be,submitLabel:yt,directPaypal:$n,isSubscription:_?.mode==="subscription",session:_,dataAttachmentPending:yn,dataAttachmentRequiresIdentity:qt,debug:Y})]},xe)}),rn]})}function zu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,children:i}){return se(Rr,{children:ls.Children.map(i,s=>{if(!ls.isValidElement(s))return s;let l=s.props,y={};return l.sessionId||(y.sessionId=e),!l.nonce&&t&&(y.nonce=t),l.billingApiUrl||(y.billingApiUrl=n),l.submitLabel===void 0&&o!==void 0&&(y.submitLabel=o),r?.customer&&(l.email||(y.email=r.customer.email),l.userId||(y.userId=r.customer.id),l.firstName||(y.firstName=r.customer.firstName),l.lastName||(y.lastName=r.customer.lastName)),Object.keys(y).length===0?s:ls.cloneElement(s,y)})})}function Uu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:y,cardBackButtonContent:f,cardTitleContent:b}){let[g,M]=zt(!1),R=ar(()=>cc(i),[i]),C=ar(()=>{let I=R?.buttonsLayout??Au(s);return l?{...I,...l,cardButton:{...I.cardButton,...l.cardButton},cardFormContainer:{...I.cardFormContainer,...l.cardFormContainer},backButton:{...I.backButton,...l.backButton},backButtonIcon:{...I.backButtonIcon,...l.backButtonIcon},submitButton:{...I.submitButton,...l.submitButton},title:{...I.title,...l.title}}:I},[R,s,l]),v=R?.buttonsLayout?.cardButton?.borderRadius??R?.appearance.variables?.borderRadius??8,q=I=>se("div",{style:{height:I,borderRadius:v,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),Re=y===void 0?{boxSizing:"border-box",height:Ao,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(g){let I=C.cardInputBorder??"#e5e7eb",G=C.cardInputBackground??"white",Y=uo(f),re=uo(b);return sn("div",{style:{backgroundColor:C.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...C.cardFormContainer},children:[sn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[sn("button",{type:"button",onClick:()=>M(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Y?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...C.backButton},children:[se("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...C.backButtonIcon},children:se("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:se("path",{d:"M15 18l-6-6 6-6"})})}),se(yo,{content:f})]}),re?se("div",{style:{flex:1}}):se("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...C.title},children:se(Go,{content:b})})]}),se("div",{style:{backgroundColor:G,border:`1px solid ${I}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:se("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),sn("div",{style:{display:"flex"},children:[se("div",{style:{flex:1,backgroundColor:G,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,borderBottomLeftRadius:8,padding:12,height:45},children:se("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),se("div",{style:{flex:1,backgroundColor:G,borderTop:"none",borderRight:`1px solid ${I}`,borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,borderBottomRightRadius:8,padding:12,height:45},children:se("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),se("div",{style:{backgroundColor:G,border:`1px solid ${I}`,borderRadius:8,marginTop:8,padding:12,height:45},children:se("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),se("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...C.submitButton,opacity:.5}}),se("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&&qe(So),n&&(r||o)&&qe(So),n&&re("button",{type:"button",onClick:()=>{e?.("card"),y(!0)},style:{width:"100%",...ge,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:M.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...M.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:re(ao,{content:p})}),re("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Bu,jsx as ko,jsxs as Fu}from"react/jsx-runtime";var Eu=44;function Gl(e){return new Promise(t=>setTimeout(t,e))}function Tu(e,t){return e instanceof ra?e:new ra(e instanceof Error?e.message:t,"api_error")}function Au(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Mu(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 xu({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:s,items:l,subscriptions:p,account:v,successUrl:g,cancelUrl:h,couponCodes:y,tagsData:_,utmMetadata:M,billingApiUrl:U,locale:qe,theme:ge,appearance:S,buttonsTheme:W,buttonsStyles:Y,onSuccess:de,onError:Le,onDecline:Se,children:Re,disabled:Ge=!1,type:St="button",style:tt,...je}){let $e=ta(()=>ku(U),[U]),ue=ta(()=>Mu({createSession:n,clientId:i,products:s,items:l,subscriptions:p,account:v,successUrl:g,cancelUrl:h,couponCodes:y,tagsData:_,utmMetadata:M}),[v,h,i,y,n,s,l,p,g,_,M]),[we,Xe]=na(!1),[ee,Ie]=na(null),[he,st]=na(null),[lt,T]=na(!1),[$,Ee]=na(null),ie=Io(!0),rt=Io(null),A=Io($),Te=Io(de),dt=Io(Le),We=Io(Se);wo(()=>{A.current=$},[$]),wo(()=>{Te.current=de},[de]),wo(()=>{dt.current=Le},[Le]),wo(()=>{We.current=Se},[Se]),wo(()=>(ie.current=!0,()=>{ie.current=!1,rt.current?.abort()}),[]),wo(()=>{if(typeof window>"u")return;let u=w=>{w.key==="Escape"&&Ee(null)};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u)}},[]);let se=xr((u,w=Yo)=>{We.current?.(nn(w,u,{code:u.code,declineCode:u.declineCode}))},[]),x=xr(async u=>{ie.current&&(st(null),T(u.result.status==="authorized"),Ie("success"),await Gl(600),ie.current&&Rt(()=>Te.current?.(u)))},[]),Q=xr(async(u,w)=>{ie.current&&(dt.current?.(u),w?.emitDecline&&se(u,w.method),st(u.message),T(!1),Ie("error"),await Gl(400))},[se]),Me=xr(async(u,w,xe)=>{let me=u.data.session??null;if(!me)throw new ra("No session data returned","api_error");let Ct=me.clientSecret||t;if(co(me)){await x({result:jr(me,w),session:me,sessionId:me.id||w,autoCompleted:!1});return}if(me.status==="expired")throw ya(me);try{if(u.autoProcessingPending){let Wt=(await new ns($e).waitForCheckoutSessionCompletion(u.autoProcessingPending.sessionId,{initialDelayMs:u.autoProcessingPending.retryAfterMs})).data.session;if(!co(Wt))throw ga(Wt);await x({result:jr(Wt,w),session:Wt,sessionId:Wt.id||w,autoCompleted:!1});return}if(u.autoProcessingError){if(u.autoProcessingError.type==="3ds_required"&&u.autoProcessingError.nextActionRedirectUrl&&w&&Ct){let xt=new AbortController;rt.current=xt;let K;try{K=await pl({billingApiUrl:$e,sessionId:w,nonce:Ct,nextActionRedirectUrl:u.autoProcessingError.nextActionRedirectUrl,signal:xt.signal})}finally{rt.current===xt&&(rt.current=null)}if(K.status==="declined")throw Tr({type:K.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:K.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:u.autoProcessingError.checkoutMethod});let yn=(await new ns($e).waitForCheckoutSessionCompletion(w,{initialDelayMs:0,nonce:Ct})).data.session;if(!co(yn))throw Tr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:u.autoProcessingError.checkoutMethod});await x({result:jr(yn,w),session:yn,sessionId:yn.id||w,autoCompleted:!1});return}throw Tr(u.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:u.autoProcessingError.checkoutMethod})}if(xe?.fromCreateSession&&u.autoProcessingAttempted===!0)throw Tr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let nt=await Po({billingApiUrl:$e,sessionId:w??me.id,session:me,nonce:Ct});if(nt.type!=="success")throw Tr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await x({result:nt.result,session:me,sessionId:me.id||w,autoCompleted:!1})}catch(nt){let xt=Jo(nt),K=me.id||w;await Q(xt,{emitDecline:!0,method:xt.checkoutMethod??Yo}),Au(xt,K)&&K&&ie.current&&Ee({sessionId:K,errorMessage:xt.message,nonce:Ct||void 0})}},[t,$e,Q,x]),ot=xr(async u=>{if(je.onClick?.(u),!(u.defaultPrevented||Ge||we)){if(Ee(null),e&&ue){let w=new ra("Provide either sessionId or create-session props, not both.","validation_error");await Q(w),ie.current&&(Ie(null),st(null));return}if(!e&&!ue){let w=new ra("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Q(w),ie.current&&(Ie(null),st(null));return}Xe(!0),st(null),T(!1),Ie("processing");try{let w=new ns($e);if(e){let xe=await w.getUnifiedCheckoutSession(e,t);await Me(xe,e);return}try{let xe=await w.createAndFetchSession({...ue});await Me(xe,xe.data.session?.id??null,{fromCreateSession:!0})}catch(xe){if(fa(xe)==="session_auto_completed"){await x({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw xe}}catch(w){await Q(Tu(w,"Automatic payment failed. Please try again."))}finally{ie.current&&(Ie(null),st(null),Xe(!1))}}},[je.onClick,ue,Ge,we,t,Me,$e,e,Q,x]),ke=xr(u=>{let w=A.current;Ee(null),Te.current?.({result:u,session:null,sessionId:w?.sessionId??null,autoCompleted:!1})},[]),Ke=xr(u=>{dt.current?.(u)},[]),_e=xr(u=>{We.current?.(u)},[]),le=ta(()=>Ru(ge),[ge]),ve=ta(()=>{let u=le?.buttonsLayout??_u(W);return Y?{...u,...Y,cardButton:{...u.cardButton,...Y.cardButton}}:u},[le,W,Y]),Vt=ta(()=>{let u=le?.appearance;return S?u?{...u,...S,variables:{...u.variables,...S.variables}}:S:u},[S,le]),H=Vt?.variables,Mt=H?.colorPrimary??"#4A49FF",mt=H?.colorPrimaryHover??zo(Mt,.12),R=H?.borderRadius??"8px";return Fu(Bu,{children:[ko("button",{...je,type:St,onClick:ot,disabled:Ge||we,"aria-busy":we,style:{width:"100%",...Re===void 0?{boxSizing:"border-box",height:Eu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...ve.cardButton,...Ki({themeBundle:le,resolvedPrimaryColor:Mt,resolvedBorderRadius:R,submitButtonStyle:ve.submitButton,explicitPrimaryColor:H?.colorPrimary}),fontSize:ve.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ge||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:Ge||we?.6:1,...tt},onMouseEnter:u=>{je.onMouseEnter?.(u),!u.defaultPrevented&&!Ge&&!we&&(le||H?.colorPrimary)&&(u.currentTarget.style.backgroundColor=mt)},onMouseLeave:u=>{je.onMouseLeave?.(u),!u.defaultPrevented&&(le||H?.colorPrimary)&&(u.currentTarget.style.backgroundColor=Mt)},onMouseDown:u=>{je.onMouseDown?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(0.985)")},onMouseUp:u=>{je.onMouseUp?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(1)")},children:ko(ao,{content:Re})}),ee&&ko(yr,{status:ee,errorMessage:he,authorized:lt}),$&&ko("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:u=>{u.target===u.currentTarget&&Ee(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:ko("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:ko(ts,{sessionId:$.sessionId,nonce:$.nonce,checkoutMode:"full",billingApiUrl:$e,locale:qe,theme:ge,...Vt?{appearance:Vt}:{},buttonsTheme:W,buttonsStyles:Y,initialErrorMessage:$.errorMessage,cardTitleContent:null,onComplete:ke,onError:Ke,onDecline:_e})})})]})}export{wa as DirectPayPalButton,xu as FloPayAutomaticPaymentButton,yc as FloPayCardSetup,mc as FloPayCardSetupError,ts as FloPayCheckout,Ea as FloPayProvider,Vi as SplitCardForm,oi as VaultCardFields,$m as dropThirdPartyOnlyError,Tc as useCheckout,kr as useFloPay,di as usePayPalFloPay};
|
|
42
|
+
`})]})}return sn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&q(Ao),n&&(r||o)&&q(Ao),n&&se("button",{type:"button",onClick:()=>{e?.("card"),M(!0)},style:{width:"100%",...Re,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:C.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...C.cardButton},onMouseDown:I=>{I.currentTarget.style.transform="scale(0.985)"},onMouseUp:I=>{I.currentTarget.style.transform="scale(1)"},children:se(po,{content:y})}),se("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Yu,jsx as Bo,jsxs as Ju}from"react/jsx-runtime";var Ku=44;function pc(e){return new Promise(t=>setTimeout(t,e))}function Vu(e,t){return e instanceof fa?e:new fa(e instanceof Error?e.message:t,"api_error")}function Hu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Wu(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function Gu({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:s,items:l,subscriptions:y,account:f,successUrl:b,cancelUrl:g,couponCodes:M,tagsData:R,utmMetadata:C,billingApiUrl:v,locale:q,theme:Re,appearance:I,buttonsTheme:G,buttonsStyles:Y,onSuccess:re,onError:ve,onDecline:Le,children:Ce,disabled:$e=!1,type:vt="button",style:Ke,...Ne}){let Me=ya(()=>qu(v),[v]),wt=ya(()=>Wu({createSession:n,clientId:i,products:s,items:l,subscriptions:y,account:f,successUrl:b,cancelUrl:g,couponCodes:M,tagsData:R,utmMetadata:C}),[f,g,i,M,n,s,l,y,b,R,C]),[fe,ut]=ma(!1),[O,Ae]=ma(null),[yt,Be]=ma(null),[it,N]=ma(!1),[ue,ge]=ma(null),K=Mo(!0),Ge=Mo(null),Ve=Mo(ue),L=Mo(re),st=Mo(ve),Ye=Mo(Le),He=xr(c=>$a(Ge,async w=>{try{return await c(w)}catch(ne){throw w.aborted?sa(ne):ne}}),[]);xo(()=>{Ve.current=ue},[ue]),xo(()=>{L.current=re},[re]),xo(()=>{st.current=ve},[ve]),xo(()=>{Ye.current=Le},[Le]),xo(()=>(K.current=!0,()=>{K.current=!1,Ge.current?.abort()}),[]),xo(()=>{if(typeof window>"u")return;let c=w=>{w.key==="Escape"&&ge(null)};return window.addEventListener("keydown",c),()=>{window.removeEventListener("keydown",c)}},[]);let Ee=xr((c,w=ia)=>{Ye.current?.(dn(w,c,{code:c.code,declineCode:c.declineCode}))},[]),le=xr(async c=>{K.current&&(Be(null),N(c.result.status==="authorized"),Ae("success"),await pc(600),K.current&&Ft(()=>L.current?.(c)))},[]),mt=xr(async(c,w)=>{K.current&&(st.current?.(c),w?.emitDecline&&Ee(c,w.method),Be(c.message),N(!1),Ae("error"),await pc(400))},[Ee]),Q=xr(async(c,w,ne)=>{let k=c.data.session??null;if(!k)throw new fa("No session data returned","api_error");let $=k.clientSecret||t;if(Fr(k)){await le({result:Tr(k,w),session:k,sessionId:k.id||w,autoCompleted:!1});return}if(k.status==="expired")throw _a(k);try{if(c.autoProcessingPending){let ze=c.autoProcessingPending,Ue=new hs(Me),xt=await He(We=>Ue.waitForCheckoutSessionCompletion(ze.sessionId,{initialDelayMs:ze.retryAfterMs,nonce:$,statusUrl:ze.statusUrl,signal:We})),ee=xt.data.session,pn=xt.autoProcessingError?.type==="3ds_required"&&xt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:xt.autoProcessingError.nextActionRedirectUrl}:null;if(pn&&w&&$){let We=await He(Dt=>Io(pn,{billingApiUrl:Me,sessionId:w,nonce:$,session:k,signal:Dt}));await le({result:We,session:k,sessionId:k.id||w,autoCompleted:!1});return}if(xt.autoProcessingError)throw Ir(xt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:xt.autoProcessingError.checkoutMethod});if(!Fr(ee))throw go(ee);await le({result:Tr(ee,w),session:ee,sessionId:ee.id||w,autoCompleted:!1});return}if(c.autoProcessingError){let ze=c.autoProcessingError.nextActionRedirectUrl;if(c.autoProcessingError.type==="3ds_required"&&ze&&w&&$){let Ue=await He(We=>Ui({billingApiUrl:Me,sessionId:w,nonce:$,nextActionRedirectUrl:ze,signal:We}));if(Ue.status==="declined")throw Ir({type:Ue.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ue.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:c.autoProcessingError.checkoutMethod});let pn=(await new hs(Me).waitForCheckoutSessionCompletion(w,{initialDelayMs:0,nonce:$})).data.session;if(!Fr(pn))throw Ir({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:c.autoProcessingError.checkoutMethod});await le({result:Tr(pn,w),session:pn,sessionId:pn.id||w,autoCompleted:!1});return}throw Ir(c.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:c.autoProcessingError.checkoutMethod})}if(ne?.fromCreateSession&&c.autoProcessingAttempted===!0)throw Ir({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ft=await _o({billingApiUrl:Me,sessionId:w??k.id,session:k,nonce:$});if(ft.type==="next_action_required"&&$){let ze=w??k.id,Ue=await He(xt=>Io(ft,{billingApiUrl:Me,sessionId:ze,nonce:$,session:k,signal:xt}));await le({result:Ue,session:k,sessionId:k.id||ze,autoCompleted:!1});return}if(ft.type!=="success")throw Ir({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await le({result:ft.result,session:k,sessionId:k.id||w,autoCompleted:!1})}catch(ft){let ze=la(ft);if(ze.code==="three_ds_aborted")return;let Ue=k.id||w;await mt(ze,{emitDecline:!0,method:ze.checkoutMethod??ia}),Hu(ze,Ue)&&Ue&&K.current&&ge({sessionId:Ue,errorMessage:ze.message,nonce:$||void 0,payPalOrderId:ze.orderId})}},[t,Me,He,mt,le]),oe=xr(async c=>{if(Ne.onClick?.(c),!(c.defaultPrevented||$e||fe)){if(ge(null),e&&wt){let w=new fa("Provide either sessionId or create-session props, not both.","validation_error");await mt(w),K.current&&(Ae(null),Be(null));return}if(!e&&!wt){let w=new fa("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await mt(w),K.current&&(Ae(null),Be(null));return}ut(!0),Be(null),N(!1),Ae("processing");try{let w=new hs(Me);if(e){let ne=await w.getUnifiedCheckoutSession(e,t);await Q(ne,e);return}try{let ne=await w.createAndFetchSession({...wt});await Q(ne,ne.data.session?.id??null,{fromCreateSession:!0})}catch(ne){if(Ra(ne)==="session_auto_completed"){await le({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw ne}}catch(w){await mt(Vu(w,"Automatic payment failed. Please try again."))}finally{K.current&&(Ae(null),Be(null),ut(!1))}}},[Ne.onClick,wt,$e,fe,t,Q,Me,e,mt,le]),Fe=xr(c=>{let w=Ve.current;ge(null),L.current?.({result:c,session:null,sessionId:w?.sessionId??null,autoCompleted:!1})},[]),Je=xr(c=>{st.current?.(c)},[]),lt=xr(c=>{Ye.current?.(c)},[]),z=ya(()=>$u(Re),[Re]),pt=ya(()=>{let c=z?.buttonsLayout??ju(G);return Y?{...c,...Y,cardButton:{...c.cardButton,...Y.cardButton}}:c},[z,G,Y]),Xe=ya(()=>{let c=z?.appearance;return I?c?{...c,...I,variables:{...c.variables,...I.variables}}:I:c},[I,z]),_=Xe?.variables,ct=_?.colorPrimary??"#4A49FF",Jt=_?.colorPrimaryHover??Wo(ct,.12),xe=_?.borderRadius??"8px";return Ju(Yu,{children:[Bo("button",{...Ne,type:vt,onClick:oe,disabled:$e||fe,"aria-busy":fe,style:{width:"100%",...Ce===void 0?{boxSizing:"border-box",height:Ku,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...pt.cardButton,...is({themeBundle:z,resolvedPrimaryColor:ct,resolvedBorderRadius:xe,submitButtonStyle:pt.submitButton,explicitPrimaryColor:_?.colorPrimary}),fontSize:pt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:$e||fe?"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:$e||fe?.6:1,...Ke},onMouseEnter:c=>{Ne.onMouseEnter?.(c),!c.defaultPrevented&&!$e&&!fe&&(z||_?.colorPrimary)&&(c.currentTarget.style.backgroundColor=Jt)},onMouseLeave:c=>{Ne.onMouseLeave?.(c),!c.defaultPrevented&&(z||_?.colorPrimary)&&(c.currentTarget.style.backgroundColor=ct)},onMouseDown:c=>{Ne.onMouseDown?.(c),c.defaultPrevented||(c.currentTarget.style.transform="scale(0.985)")},onMouseUp:c=>{Ne.onMouseUp?.(c),c.defaultPrevented||(c.currentTarget.style.transform="scale(1)")},children:Bo(po,{content:Ce})}),O&&Bo(wr,{status:O,errorMessage:yt,authorized:it}),ue&&Bo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:c=>{c.target===c.currentTarget&&ge(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:Bo("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:Bo(gs,{sessionId:ue.sessionId,nonce:ue.nonce,checkoutMode:"full",billingApiUrl:Me,locale:q,theme:Re,...Xe?{appearance:Xe}:{},buttonsTheme:G,buttonsStyles:Y,initialErrorMessage:ue.errorMessage,initialPayPalOrderId:ue.payPalOrderId,cardTitleContent:null,onComplete:Fe,onError:Je,onDecline:lt})})})]})}export{Oa as DirectPayPalButton,Gu as FloPayAutomaticPaymentButton,Mc as FloPayCardSetup,xc as FloPayCardSetupError,gs as FloPayCheckout,qa as FloPayProvider,ss as SplitCardForm,bi as VaultCardFields,mm as dropThirdPartyOnlyError,Yc as useCheckout,Or as useFloPay,_i as usePayPalFloPay};
|