@flopay/react 1.9.10 → 1.9.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -0
- package/dist/card-setup-entry.cjs +1 -1
- package/dist/card-setup-entry.mjs +1 -1
- package/dist/{chunk-LI3VGXRI.mjs → chunk-M4FGYFX6.mjs} +1 -1
- package/dist/index.cjs +9 -9
- package/dist/index.d.cts +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.mjs +8 -8
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var Ml=Object.create;var ta=Object.defineProperty;var Bl=Object.getOwnPropertyDescriptor;var Fl=Object.getOwnPropertyNames;var Dl=Object.getPrototypeOf,Ll=Object.prototype.hasOwnProperty;var Nl=(e,t)=>{for(var n in t)ta(e,n,{get:t[n],enumerable:!0})},ts=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Fl(t))!Ll.call(e,o)&&o!==n&&ta(e,o,{get:()=>t[o],enumerable:!(r=Bl(t,o))||r.enumerable});return e};var ns=(e,t,n)=>(n=e!=null?Ml(Dl(e)):{},ts(t||!e||!e.__esModule?ta(n,"default",{value:e,enumerable:!0}):n,e)),Ol=e=>ts(ta({},"__esModule",{value:!0}),e);var hd={};Nl(hd,{DirectPayPalButton:()=>Mo,FloPayAutomaticPaymentButton:()=>ll,FloPayCardSetup:()=>pl,FloPayCardSetupError:()=>Vo,FloPayCheckout:()=>Ta,FloPayProvider:()=>Fo,SplitCardForm:()=>Ia,VaultCardFields:()=>mo,dropThirdPartyOnlyError:()=>ml.dropThirdPartyOnlyError,useCheckout:()=>ms,useFloPay:()=>wr,usePayPalFloPay:()=>aa});module.exports=Ol(hd);var ml=require("@flopay/shared");var xa=require("@flopay/js"),Zn=require("@flopay/shared"),We=require("react");var Mt=require("react/jsx-runtime");function zl(){return(0,Mt.jsxs)(Mt.Fragment,{children:[(0,Mt.jsxs)("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:[(0,Mt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Mt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Mt.jsx)("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:(0,Mt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Ul(){return(0,Mt.jsx)(Mt.Fragment,{children:"Go back"})}function ql(){return(0,Mt.jsx)(Mt.Fragment,{children:"Secure card checkout"})}function Xr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Zr({content:e}){return(0,Mt.jsx)(Mt.Fragment,{children:e===void 0?(0,Mt.jsx)(zl,{}):e})}function Qr({content:e}){return(0,Mt.jsx)(Mt.Fragment,{children:e===void 0?(0,Mt.jsx)(Ul,{}):e})}function Ro({content:e}){return(0,Mt.jsx)(Mt.Fragment,{children:e===void 0?(0,Mt.jsx)(ql,{}):e})}var zt=require("@flopay/shared"),$l="Checkout is temporarily unavailable. Please try again later.";function Wa(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof zt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function jl(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 rs(){return new zt.FloPayError($l,"api_error",{code:"CheckoutInitializationFailed"})}function os(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card"))||t&&e?.data.paypal?.publishableKey)}function as(e,t){if(t&&(!(e instanceof zt.FloPayError)||e.type==="authentication_error"))return Wa(e);if(!(e instanceof zt.FloPayError&&jl(e))){if(!t&&!(e instanceof zt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,zt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof zt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof zt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function eo(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let l={...r,...a,email:a.email?.trim()||r.email?.trim()},c=(0,zt.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,zt.isValidEmail)(l.email))return Promise.reject(new zt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let f={};for(let[y,p]of Object.entries(l)){if(c&&y.endsWith("Name")||typeof p!="string")continue;let b=p.trim();b&&(f[y]=b)}return o=e.claimCheckoutSession(t,n,{accountData:f}),o.catch(()=>{}),o}}function is(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 Ga(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 ss(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,l)=>a+(l.overrideAmount??l.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.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((a,l)=>({uuid:`synthetic-${a.type??"item"}-${l}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function Nr(e){if((0,zt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Ya(e,t){return t?{...e,...t}:e}function cn(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var Vl=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function _r(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Vl)if(n.test(t))return r;return e}function Or(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function to(e){return e?.status==="authorized"||e?.status==="complete"}function ls(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function na(e){let t=ls(e);return new zt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ra(e){return e instanceof zt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function oa(e){let t=ls(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new zt.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function _o(e,t){return e==="processing"||(0,zt.isMoneySettledOutcome)(e,t)}function cs(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function ds(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 Ja(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 Eo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Rr=require("@flopay/js"),De=require("@flopay/shared"),C=ns(require("react"),1);var Xa=require("react"),Yn=(0,Xa.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),rr=(0,Xa.createContext)({session:null,loading:!1,error:null});var da=require("@flopay/js"),Ut=require("@flopay/shared"),gs=require("@paypal/paypal-js"),T=require("react");var us=require("@flopay/shared"),or=require("react"),Pr=require("react/jsx-runtime");function Dn(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),l=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...l||t?{lastName:l??""}:{}}}function no(){let[e,t]=(0,or.useState)(null),n=(0,or.useRef)(null),r=(0,or.useRef)(0),o=(0,or.useCallback)((l,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:c}),new Promise(f=>{n.current=f})),[]),a=(0,or.useCallback)(l=>{let c=n.current;n.current=null,t(null),c?.(l)},[]);return(0,or.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function ro({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,c]=(0,or.useState)(e.email?.trim()??""),f=(0,us.isValidEmail)(l.trim());return(0,Pr.jsxs)("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,Pr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Pr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Pr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:y=>c(y.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Pr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Pr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Pr.jsxs)("button",{type:"button",disabled:!f||o,onClick:()=>{n(Dn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function Kl(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 zr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Cr(e){if(typeof e!="object"||e===null)return;let t=e;return zr(t.code)??zr(t.type)??zr(t.name)}function oo(e){if(!(typeof e!="object"||e===null))return zr(e.decline_code)}function To(e){return typeof e!="object"||e===null?!1:zr(e.type)?.toLowerCase()==="card_error"||oo(e)!==void 0}function Sr(e){let t=Kl(e)?.toLowerCase()??"",r=`${Cr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var ps=require("@flopay/shared"),xo=require("react");function wr(){return(0,xo.useContext)(Yn).flopay}function aa(){return(0,xo.useContext)(Yn).paypalFlopay??null}function ms(){return(0,xo.useContext)(rr)}function ys(){return(0,xo.useContext)(Yn).billingApiUrl||(0,ps.resolveBillingApiUrl)()}function ia(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 sa(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var fs=require("@flopay/shared"),qr=require("react");function nt(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}var la=require("react"),Ur=typeof window>"u"?la.useEffect:la.useLayoutEffect;var Hl={"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 Wl(e){return e==="stripe"||e==="paypal"?e:void 0}function Gl(e){let t=Wl(e.provider),n={schemaVersion:fs.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Hl[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 Za=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function ao(e,t){let n=(0,qr.useRef)(e);n.current=e;let r=(0,qr.useRef)(new Set),o=(0,qr.useRef)(t),a=(0,qr.useRef)(t);return Ur(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,qr.useCallback)(l=>{if(a.current!==t)return;let c=Gl(l);if(c){if(Za.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}nt(()=>n.current?.(c))}},[t])}var Yl=Symbol.for("@flopay/js.telemetry.bridge.v1"),Jl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Xl(){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 Zl(e){let t=Xl(),n=(o,a)=>o?o.bind(e):a,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[Jl];return Zl(t?.(e)??{})}function sn(e){if(e)return e[Yl]}var En=require("react");function Ao(e){let t=(0,En.useRef)(0),n=(0,En.useRef)(null),r=(0,En.useRef)(null),o=(0,En.useCallback)((h=r.current)=>{h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),a=(0,En.useCallback)(h=>{o();let w=t.current+1;return t.current=w,n.current=null,r.current={generation:w,method:h,timer:null,yieldedControl:!1},w},[o]),l=(0,En.useCallback)(h=>{let w=r.current;return h!==void 0&&w?.generation!==h?!1:(o(w),r.current=null,(h===void 0||n.current===h)&&(n.current=null),!0)},[o]),c=(0,En.useCallback)(h=>{let w=r.current,B=h??w?.generation??t.current;(h===void 0||w?.generation===h)&&(o(w),r.current=null),n.current=B},[o]),f=(0,En.useCallback)(h=>n.current===(h??t.current),[]),y=(0,En.useCallback)(h=>r.current?.generation===h&&n.current!==h,[]),p=(0,En.useCallback)(()=>{let h=r.current;h&&(h.yieldedControl=!0,o(h))},[o]),b=(0,En.useCallback)(()=>{let h=r.current;!h?.yieldedControl||document.visibilityState!=="visible"||(o(h),h.timer=setTimeout(()=>{h.timer=null,r.current?.generation===h.generation&&(r.current=null,n.current=h.generation,e(h.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[o,e]);return(0,En.useEffect)(()=>{let h=()=>{document.visibilityState==="visible"?b():p()};return document.addEventListener("visibilitychange",h),window.addEventListener("blur",p),window.addEventListener("focus",b),()=>{document.removeEventListener("visibilitychange",h),window.removeEventListener("blur",p),window.removeEventListener("focus",b),o()}},[o,p,b]),{startAttempt:a,finishAttempt:l,invalidateAttempt:c,isAttemptInvalidated:f,isAttemptCurrent:y,generationRef:t}}var Jn=require("react/jsx-runtime"),ua=45,Ql=1e3,ec=11e3,tc=["https://www.paypal.com","https://www.sandbox.paypal.com"],Qa="We couldn't open PayPal. Try again or choose another payment method.",nc={width:"100%",minHeight:ua,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 rc(e){return e.includes("No ack for postMessage init()")&&tc.some(t=>e.includes(t))&&e.includes("10000ms")}var oc={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 ac(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:oc[e.kind]??null}}function ic(e,t){return e==="watchdog_expired"?"paypal_render_timeout":rc(t)?"paypal_init_timeout":"paypal_init_failure"}function sc(e,t=!1){return e?t?`${Qa} Open this page in your system browser, then try again.`:`${Qa} Allow pop-ups for this site, then try again.`:Qa}function lc(e){let t=To(e),n=Sr(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 cc(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 dc(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function hs({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:c,currency:f,isSubscription:y,providerObjectType:p,approvalPresentation:b,onTokenizedBody:h,onComplete:w,onErrorChange:B,onDecline:N,onTechnicalFailure:de,isProcessing:K=!1,onLoadStateChange:I,onInitializationStateChange:re,allowAutomaticRetry:q=!0,onButtonClick:ie,runBeforeButtonClick:se,session:ee,existingOrderId:Oe,telemetry:ue,telemetryContext:Ct,onInstrument:st,debug:Se=!1}){let Re=wr(),he=ao(st,e),te=(0,T.useMemo)(()=>{if(Re)return null;let L=ca({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ut.SDK_VERSION,enabled:ue!==!1});return L.setCheckoutContext(Ct??{}),L.beginCheckout(Ct??{}),L},[n,Re,ue,Ct?.checkoutMode,Ct?.layout]),Te=(0,T.useMemo)(()=>sn(Re),[Re]);(0,T.useEffect)(()=>()=>{te&&te.flush().catch(()=>{}).finally(()=>te.destroy())},[te]);let fe=(0,T.useMemo)(()=>({error:L=>{Te?Te.error(L):te?.error(L),he({class:"technical_error",errorCode:L.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":L.errorCode,requestCategory:L.requestCategory,provider:L.provider})},log:L=>{Te?Te.log(L):te?.log(L),he({class:"lifecycle",name:L.name,provider:L.provider})},performance:L=>{Te?Te.performance(L):te?.performance(L)},terminal:L=>{Te?Te.terminal(L):te?.terminal(L)},startTiming:()=>Te?.now()??te?.now()??0,elapsed:L=>Te?.elapsed(L)??Math.max(0,(te?.now()??L)-L)}),[he,Te,te]),we=(0,T.useRef)(null),xe=(0,T.useRef)(0),Le=(0,T.useRef)(null),_e=(0,T.useRef)(null),_=(0,T.useRef)(null),oe=(0,T.useRef)(!1),[me,J]=(0,T.useState)(!1),[O,Ce]=(0,T.useState)(!1),[Ke,_t]=(0,T.useState)(0),Qe=(0,T.useRef)(0),[Z,X]=(0,T.useState)(!1),$=(0,T.useRef)(!1),ze=(0,T.useRef)(!1),[Je,be]=(0,T.useState)(!1),[Xe,H]=(0,T.useState)(!1),{request:z,collect:rt,finish:D}=no(),j=(0,T.useRef)({sessionId:e,required:!(0,Ut.isValidEmail)(r?.trim()||ee?.customer?.email?.trim())});j.current.sessionId!==e&&(j.current={sessionId:e,required:!(0,Ut.isValidEmail)(r?.trim()||ee?.customer?.email?.trim())});let qe=j.current.required,ve=(0,T.useMemo)(()=>n.replace(/\/+$/,""),[n]),St=ee?.gateways?.paypal?.providerObjectType??p,P=St??(y?"subscription":"order"),[F]=(0,T.useState)(ia),qt=ee?.gateways?.paypal?.approvalPresentation??b,Ae=sa(F,qt==="app_switch"?"app_switch":void 0,P),Et=St==="order"||St==="setup_token",tn=(0,T.useMemo)(()=>JSON.stringify([ve,l,f,c??"",P,Et,Ae,e,Oe??""]),[ve,l,f,c,Oe,P,Et,Ae,e]),et=(0,T.useRef)(tn),nn=et.current!==tn,lt=(0,T.useRef)(Se),Wt=(0,T.useRef)(null),[dn,rn]=(0,T.useState)([]),ke=(0,T.useCallback)(L=>{lt.current&&rn(mt=>[...mt,`${new Date().toISOString().slice(11,23)} ${L}`])},[]);(0,T.useEffect)(()=>{lt.current=Se,Se&&ke("debug:enabled"),Wt.current?.setEnabled(Se)},[ke,Se]);let hn=(0,T.useRef)(h),bn=(0,T.useRef)(w),$e=(0,T.useRef)(B),ct=(0,T.useRef)(N),un=(0,T.useRef)(de),Gt=(0,T.useRef)(ie),pn=(0,T.useRef)(I),$t=(0,T.useRef)(re),wt=(0,T.useRef)(a),Qn=(0,T.useRef)(se),kt=(0,T.useRef)(ee),vn=(0,T.useRef)(r),ht=(0,T.useRef)(o),Yt=(0,T.useRef)(t),dt=(0,T.useRef)(null),Tt=(0,T.useRef)(new Map),Pn=(0,T.useRef)(new Map),Jt=(0,T.useRef)(!1);(0,T.useEffect)(()=>(Jt.current=!0,()=>{Jt.current=!1}),[]),(0,T.useEffect)(()=>{hn.current=h},[h]),(0,T.useEffect)(()=>{wt.current=a},[a]),(0,T.useEffect)(()=>{bn.current=w},[w]),(0,T.useEffect)(()=>{$e.current=B},[B]),(0,T.useEffect)(()=>{ct.current=N},[N]),(0,T.useEffect)(()=>{un.current=de},[de]),(0,T.useEffect)(()=>{Gt.current=ie},[ie]),(0,T.useEffect)(()=>{pn.current=I},[I]),(0,T.useEffect)(()=>{$t.current=re},[re]),(0,T.useEffect)(()=>{Qn.current=se},[se]),(0,T.useEffect)(()=>{kt.current=ee},[ee]),(0,T.useEffect)(()=>{vn.current=r},[r]),(0,T.useEffect)(()=>{ht.current=o},[o]),(0,T.useEffect)(()=>{Yt.current=t},[t]),(0,T.useEffect)(()=>{Qe.current=Ke},[Ke]),(0,T.useEffect)(()=>{Z&&_.current?.focus()},[Z,Ke]);let Cn=(0,T.useCallback)(()=>{window.setTimeout(()=>{_.current?.focus()},0)},[]),ut=(0,T.useCallback)(()=>{J(!1),_t(L=>L+1)},[]),E=(0,T.useCallback)(()=>{X(!1),(we.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??we.current)?.focus?.()},[]);(0,T.useEffect)(()=>{!me||!oe.current||(oe.current=!1,E())},[E,me,Ke]);let xt=(0,T.useCallback)((L,mt)=>{let pe=mt?.popupBlocked??Sr(L),xn=sc(pe,F.inAppBrowser),Sn=un.current;if(Sn){let wn=pe&&F.inAppBrowser?new Ut.FloPayError(xn,"api_error",{code:mt?.code??"paypal_popup_blocked"}):L;Sn("paypal",wn,mt);return}$e.current?.(xn)},[F.inAppBrowser]),ot=(0,T.useCallback)(L=>{let mt=Le.current,pe=_e.current;mt===null||!pe||(fe.log({...pe,name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),fe.performance({...pe,stage:"overlay_return",durationMs:fe.elapsed(mt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),Le.current=null)},[fe]),Xt=(0,T.useCallback)((L,mt,pe)=>{let xn=_e.current;ot("overlay_timeout"),xn&&fe.error({...xn,errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),xt(mt,pe),X(!0),ut(),Cn()},[ot,Cn,xt,ut,fe]),{finishAttempt:on,generationRef:Ln,invalidateAttempt:Tn,isAttemptCurrent:Zt,isAttemptInvalidated:tt,startAttempt:Tr}=Ao(Xt),xr=(0,T.useCallback)(()=>(X(!1),Tr("paypal")),[Tr]),Un=(0,T.useCallback)(L=>{Tn(L?.generation),L?.showRetry&&X(!0),L?.remount&&ut(),L?.focus!==!1&&Cn()},[Cn,Tn,ut]),Ar=L=>{let mt=dt.current;return mt&&Pn.current.set(L,mt),L};(0,T.useEffect)(()=>{et.current!==tn&&(et.current=tn,$.current=!1,ze.current=!1,J(!1),Ce(!1),be(!1),$t.current?.("loading"))},[tn]),(0,T.useEffect)(()=>{nt(()=>pn.current?.(me&&!Je))},[me,Je]);let qn=(0,Ut.normalizeGatewayEnvironment)(c);(0,T.useEffect)(()=>{let L={attempt:Ln.current+1,...F,presentationMode:Ae},mt=()=>_e.current??L,pe={error:v=>fe.error({...v,...mt()}),log:v=>fe.log({...v,...mt()}),performance:v=>fe.performance({...v,...mt()}),terminal:v=>fe.terminal({...v,...mt()}),startTiming:fe.startTiming,elapsed:fe.elapsed},xn=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Sn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(ke(`mount clientId=${xn} env=${c??"(unset)"}\u2192${qn??"live"} ccy=${f} sub=${y}`),ke(`ua=${Sn.slice(0,80)}${Sn.length>80?"\u2026":""}`),!l){ke("FAIL: clientId empty \u2014 gateway misconfigured"),be(!0),pe.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(!we.current){ke("FAIL: containerRef not attached");return}xe.current=pe.startTiming(),pe.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let wn=!1,hr=!1,at=()=>wn||hr,Mr,er=!1,Br=()=>{Mr=(0,Ut.generateIdempotencyKey)(),Mr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),er=!0},$n=null,jn=!1,jt=null,bt=!1,Nn=()=>{!jt||bt||(bt=!0,jt.close().catch(()=>{}))},mn=!1,On=!1,fn=we.current,Ue=null,ln=null,Ft=[],Vn=null,sr=!1,br=!1,Kn=null,An=v=>{if(!v||typeof v.getBoundingClientRect!="function")return"(no rect)";let m=v.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},Mn=v=>{if(!v)return"(empty)";try{let m=new URL(v,typeof window>"u"?"https://localhost":window.location.href),g=m.pathname.toLowerCase();return g.includes("checkcaptcha")||g.includes("captcha")?`CAPTCHA(${m.host}${g})`:g.includes("risk")||g.includes("challenge")?`RISK(${m.host}${g})`:g.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${g}`.slice(0,100)}catch{return v.slice(0,80)}},lr=v=>{let m=v.getAttribute("src"),g=v.getAttribute("srcdoc"),ae=v.getAttribute("name"),Me=v.getAttribute("sandbox"),ce=[];return m&&ce.push(`src=${Mn(m)}`),g&&ce.push(`srcdoc[${g.length}ch]`),!m&&!g&&ce.push("src=(empty) srcdoc=(empty)"),ae&&ce.push(`name=${ae.slice(0,40)}`),Me!==null&&ce.push(`sandbox="${Me.slice(0,40)}"`),ce.join(" ")},Vr=v=>{if(!(v instanceof HTMLIFrameElement))return"";try{let m=v.contentDocument;if(!m)return"cd=null";let g=m.body?.children.length??0,ae=m.body?.innerHTML.length??0,Me=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${g}children,${ae}ch] head[${Me}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},Hn=[],cr=v=>{if(at())return;let m=v.message??String(v.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(ke(`window:error ${m.slice(0,140)}`),Hn.push(m))},gn=v=>{if(at())return;let m=v.reason instanceof Error?v.reason.message:String(v.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(ke(`window:rejection ${m.slice(0,140)}`),Hn.push(m))},yt={value:0},kn=()=>{Ue?.disconnect(),Ue=null,ln?.disconnect(),ln=null;for(let v of Ft.splice(0))clearTimeout(v);br=!1,sr&&typeof window<"u"&&(window.removeEventListener("error",cr),window.removeEventListener("unhandledrejection",gn)),sr=!1},A=()=>{if(!(sr||at()||mn)){if(sr=!0,Hn.length=0,yt.value=0,typeof window<"u"&&(window.addEventListener("error",cr),window.addEventListener("unhandledrejection",gn)),typeof PerformanceObserver<"u")try{ln=new PerformanceObserver(v=>{if(!at())for(let m of v.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;yt.value+=1;let g=Math.round(m.duration);ke(`net ${g}ms ${m.name.slice(0,90)}`)}}),ln.observe({type:"resource",buffered:!0})}catch{}Kn?.()}},x=()=>{Vn&&(clearTimeout(Vn),Vn=null)},U=()=>{kn(),x()},ne={setEnabled:v=>{v?A():kn()}};Wt.current=ne,lt.current&&A();let He=v=>{if(!v)return!1;let m=v.toLowerCase();return m.includes("zoid destroyed")||m.includes("destroyed all components")||m.includes("window closed")||m.includes("detected container element removed")},Ie=v=>{if(at()||He(v))return;let m=_r(v)??v;nt(()=>$e.current?.(m))},ye=(v,m)=>{if(wn||jn)return;jn=!0,hr=!0,U(),Nn();let g=ac({kind:v,generationActive:!0,automaticRetryAllowed:q,automaticRetryUsed:$.current});if(g.action==="retry"){$.current=!0,J(!1),H(!1),Ce(!0),$t.current?.("retrying"),$n=setTimeout(()=>{wn||_t(ae=>ae+1)},Ql);return}if(J(!1),H(!1),Ce(!1),be(!0),g.action!=="ignore"){if($t.current?.("exhausted"),g.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",m);return}g.report&&pe.error({errorCode:g.report.errorCode,stage:g.report.stage,operationOutcome:g.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),ze.current||(ze.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",ic(v,m)))}};be(!1);let le=async(v,m=dt.current)=>{if(at())return;let g=m?.sessionId??e;if(hn.current){await hn.current(v,{sessionId:g,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let ae=pe.startTiming();pe.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Me=()=>{pe.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"processing",durationMs:pe.elapsed(ae),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let ce=kt.current,At=m?.accountPatch?.email??vn.current,In=m?.accountPatch?.userId??ce?.customer?.id??ce?.accountData?.userId??"",vt=m?.accountPatch?.firstName??ce?.customer?.firstName??ce?.accountData?.firstName,Dt=m?.accountPatch?.lastName??ce?.customer?.lastName??ce?.accountData?.lastName,Ee=await new da.PaymentAPI(ve,{telemetry:!1}).processPayment(In,{sessionId:g,nonce:m?.nonce??Yt.current,paymentMethodCategory:"paypal",tokenizedData:v,accountData:{userId:In,email:At??ce?.customer?.email??"",...vt?{firstName:vt}:{},...Dt?{lastName:Dt}:{},country:m?.accountPatch?.country??ce?.customer?.country??ce?.accountData?.country??void 0,zip:m?.accountPatch?.zip??ce?.customer?.zip??ce?.accountData?.zip??void 0}});if(Ee.ok){if(hr||wn&&Jt.current)return;Me(),pe.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),nt(()=>bn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(at())return;let je=await Ee.json().catch(()=>null),Be=je?.message??"PayPal payment failed.",Ne=_r(Be)??Be;Me(),Ee.status===400&&(typeof je?.declineCode=="string"||!Array.isArray(je?.fields))?pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Ee.status===400||Ee.status===422?pe.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):pe.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:dc(Ee.status),failureCategory:Ee.status>=500?"server_error":void 0}),Ie(Ne),nt(()=>ct.current?.(cn("paypal",Ne,{code:je?.code,declineCode:je?.declineCode})));return}catch(ce){if(at())return;Me(),pe.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let At=ce instanceof Error?ce.message:"PayPal payment failed.",In=_r(At)??At;Ie(In),nt(()=>ct.current?.(cn("paypal",In)));return}},W=()=>new Ut.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),M=v=>at()?Promise.reject(W()):Promise.resolve(v),ge=async v=>{if(at())throw W();er||Br();let m=dt.current,g=m?.sessionId??e,ae=m?.nonce??Yt.current;pe.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Me;try{Me=await new da.PaymentAPI(ve,{telemetry:!1}).createSessionIntent(g,ae??"",Et?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Ut.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:P==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Mr})}catch(ce){throw pe.error({...(0,Ut.classifyTelemetryFailure)(ce,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ce}if(at())throw W();if(Me.provider!=="paypal"||Me.providerObjectType!==P)throw new Error(v);return pe.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Me.providerObjectId},k=(v,m)=>{let g=m?.nonce??Yt.current;if(!g)return;let ae=m?.sessionId??e,Me=oo(v)??Cr(v)??"provider_declined";new da.PaymentAPI(ve,{telemetry:!1}).reportSessionIntentDecline(ae,g,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Me}).catch(()=>{})},G=Ke;ke("loadScript:scheduled (deferred 1 tick)");let Ze=null,Vt=setTimeout(()=>{if(wn){ke("loadScript:skipped (cancelled before defer ran)");return}ke("loadScript:start");let v=qn==="live"?"production":qn,m={};P==="subscription"?m={intent:"subscription",vault:!0}:P==="order"&&(m={intent:"capture"}),Ze=(0,gs.loadScript)({clientId:l,currency:f,...m,...v?{environment:v}:{},...v==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let g=!1;Ze.then(ae=>{if(g=!0,ke(`loadScript:resolved inactive=${at()} ns=${!!ae} buttons=${!!ae?.Buttons}`),at())return;if(!ae?.Buttons){ke("FAIL: namespace missing Buttons factory"),ye("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}pe.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"provider_ready",durationMs:pe.elapsed(xe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),pe.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Me=async(Ee,je)=>{if(at()||Qe.current!==G)return;let Be=Ee.vaultSetupToken??Ee.subscriptionID??Ee.orderID??"",Ne=Be?Pn.current.get(Be):Tt.current.get(G);if(!(!Ne||!Zt(Ne.generation))&&on(Ne.generation)){Pn.current.delete(Be),Tt.current.delete(Ne.surfaceKey),ot("approved");try{if(H(!0),nt(()=>$e.current?.(null)),!Be)throw new Ut.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let it=kt.current,Rn=Nr(ht.current??[it?.customer?.firstName,it?.customer?.lastName].filter(Boolean).join(" ")),Ge=Dn({email:Ne.accountPatch?.email?.trim()||vn.current?.trim()||it?.customer?.email?.trim(),firstName:Ne.accountPatch?.firstName?.trim()||Rn.firstName,lastName:Ne.accountPatch?.lastName?.trim()||Rn.lastName});if(!(0,Ut.isValidEmail)(Ge.email)||!(Ge.firstName||Ge.lastName))try{let dr=cc(await je?.order?.get?.());Ge=Dn({email:dr.email||Ge.email,firstName:dr.firstName||Ge.firstName,lastName:dr.lastName||Ge.lastName})}catch{}if((wt.current||qe)&&!(0,Ut.isValidEmail)(Ge.email)){let dr=await rt("PayPal",Ge);if(!dr)return;Ge=dr}(0,Ut.isValidEmail)(Ge.email)&&(Ne.accountPatch=Dn({...Ne.accountPatch,...Ge}),await wt.current?.(Ge));let Q;P==="setup_token"?Q={id:Be,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Ut.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Et?Q={id:Be,isPaypal:!0,gateway:"paypal",paymentMethodType:Ut.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Q={id:Be,isPaypal:!0},await le(Q,Ne)}catch(it){Ie(it instanceof Error?it.message:"PayPal capture failed.")}finally{at()||H(!1)}}},ce=Ee=>{let je=Oe?()=>M(Oe):()=>ge(Ee);return async()=>Ar(await je())},At=ae.Buttons({style:{layout:"horizontal",height:ua,tagline:!1},...Ae==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Ee,je)=>{if(at()){await je.reject();return}Br();let Be=Qn.current,Ne={};if(Be)try{let Ge=await Be("paypal");if(at()){await je.reject();return}if(!Ge.proceed){dt.current=null,Tt.current.delete(G),await je.reject();return}Ne={sessionId:Ge.sessionId,accountPatch:Ge.accountPatch,nonce:Ge.nonce}}catch(Ge){ke(`onClick:runBeforeButtonClick rejected msg=${(Ge instanceof Error?Ge.message:String(Ge)).slice(0,120)}`),dt.current=null,Tt.current.delete(G),await je.reject();return}nt(()=>Gt.current?.("paypal"));let it=xr(),Rn={generation:it,surfaceKey:G,...Ne};dt.current=Rn,Tt.current.set(G,Rn),_e.current={...L,attempt:it},await je.resolve(),pe.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),pe.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Le.current=pe.startTiming()},createOrder:P==="order"?ce("Failed to create PayPal order."):void 0,createSubscription:P==="subscription"?ce("Failed to create PayPal subscription."):void 0,createVaultSetupToken:P==="setup_token"?async()=>Ar(await ge("Failed to create PayPal setup token.")):void 0,onApprove:Me,onCancel:()=>{if(at())return;let Ee=Tt.current.get(G)??dt.current;Ee&&Tt.current.delete(Ee.surfaceKey),dt.current=null,ot("cancelled"),pe.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),oe.current=!0,Un({generation:Ee?.generation,remount:!0,focus:!1})},onError:Ee=>{if(at()||Qe.current!==G)return;let je=Ee instanceof Error?Ee.message:"PayPal failed to render.";if(ke(`onError rendered=${mn} msg=${je.slice(0,120)}`),mn){let Be=Tt.current.get(G)??dt.current;if(Be&&!Zt(Be.generation)||!Be&&tt())return;if(He(je)){on(Be?.generation);return}let{errorCode:Ne,popupBlocked:it,providerDeclined:Rn,terminalReason:Ge}=lc(Ee);if(ot(Ge),Rn){pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ge}),k(Ee,Be),nt(()=>ct.current?.(cn("paypal",je))),Be&&Tt.current.delete(Be.surfaceKey),dt.current=null,on(Be?.generation);return}pe.error({errorCode:Ne,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ge}),Be&&Tt.current.delete(Be.surfaceKey),dt.current=null,Un({generation:Be?.generation,remount:!0,showRetry:!0,focus:!0}),xt(Ee,{code:"paypal_runtime_failed",popupBlocked:it});return}ye(He(je)?"teardown":"pre_ready_callback",je)}}),In=At.isEligible();if(ke(`isEligible=${In}`),pe.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!In){J(!1),ye("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}On=!0,jt=At,Kn=()=>{if(!sr||br||at()||mn)return;br=!0,ke(`container:dims ${An(fn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Ue=new MutationObserver(je=>{if(!at()){for(let Be of je)if(Be.type==="childList")Be.addedNodes.forEach(Ne=>{if(!(Ne instanceof Element))return;let it=Ne.tagName.toLowerCase(),Rn=(Ne.getAttribute("title")??"").slice(0,40),Ge=it==="iframe"?` ${lr(Ne)}`:"";ke(`child+ ${it}${Rn?` title="${Rn}"`:""}${Ge} dims=${An(Ne)}`)});else if(Be.type==="attributes"&&Be.target instanceof Element){let Ne=Be.target;if(Ne.tagName.toLowerCase()!=="iframe")continue;let it=Be.attributeName;(it==="src"||it==="srcdoc")&&ke(`attr~ iframe ${it}=${it==="srcdoc"?`[${(Ne.getAttribute("srcdoc")??"").length}ch]`:Mn(Ne.getAttribute("src"))} dims=${An(Ne)}`)}}}),Ue.observe(fn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ee=je=>{if(at()||mn)return;let Be=fn.querySelectorAll("iframe"),Ne=typeof document<"u"&&"hasStorageAccess"in document;ke(`watchdog:${je} container=${An(fn)} children=${fn.childElementCount} iframes=${Be.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Ne} paypalNetRequests=${yt.value}`),Be.forEach((it,Rn)=>{let Ge=(it.getAttribute("title")??"").slice(0,40);ke(` iframe[${Rn}] ${An(it)}${Ge?` title="${Ge}"`:""} ${lr(it)}`);let Q=Vr(it);Q&&ke(` ${Q}`)}),Hn.length===0&&ke(" (no PayPal/zoid window errors captured)")};Ft.push(setTimeout(()=>Ee("3s"),3e3)),Ft.push(setTimeout(()=>Ee("8s"),8e3)),Ft.push(setTimeout(()=>Ee("15s"),15e3))},Kn(),ke("render:start");let Dt=pe.startTiming();Vn=setTimeout(()=>{at()||mn||(ke("watchdog:11s retryable render timeout"),ye("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},ec);let an=At.render(fn);(async()=>{try{if(await an,ke(`render:resolved inactive=${at()}`),U(),at()){Nn();return}mn=!0,J(!0),Ce(!1),$t.current?.("ready"),pe.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"checkout_render",durationMs:pe.elapsed(Dt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Ee){let je=Ee instanceof Error?Ee.message:"PayPal failed to render.";ke(`render:rejected msg=${je.slice(0,120)}`),U(),ye(He(je)?"teardown":"render_rejected",je)}})()}).catch(ae=>{let Me=ae instanceof Error?ae.message:"PayPal operation failed.";ke(`provider:failed msg=${Me.slice(0,120)}`);let ce="script_rejected";g&&He(Me)?ce="teardown":g&&On&&(ce="render_rejected"),ye(ce,Me)})},0);return()=>{wn=!0,clearTimeout(Vt),$n&&clearTimeout($n),U(),Wt.current===ne&&(Wt.current=null),Nn(),Le.current=null,_e.current=null}},[q,ve,l,f,c,P,Ae,Et,e,Oe,Ke,fe,rt,qe,ke,ot]);let pt=Se?(0,Jn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Je?"#fef2f2":"#f3f4f6",border:`1px solid ${Je?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${me} failed=${Je})`,dn.length===0?`
|
|
1
|
+
"use strict";var Wl=Object.create;var na=Object.defineProperty;var Hl=Object.getOwnPropertyDescriptor;var Gl=Object.getOwnPropertyNames;var Yl=Object.getPrototypeOf,Jl=Object.prototype.hasOwnProperty;var Xl=(e,t)=>{for(var n in t)na(e,n,{get:t[n],enumerable:!0})},ps=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Gl(t))!Jl.call(e,o)&&o!==n&&na(e,o,{get:()=>t[o],enumerable:!(r=Hl(t,o))||r.enumerable});return e};var ms=(e,t,n)=>(n=e!=null?Wl(Yl(e)):{},ps(t||!e||!e.__esModule?na(n,"default",{value:e,enumerable:!0}):n,e)),Zl=e=>ps(na({},"__esModule",{value:!0}),e);var Fd={};Xl(Fd,{DirectPayPalButton:()=>Bo,FloPayAutomaticPaymentButton:()=>Sl,FloPayCardSetup:()=>Rl,FloPayCardSetupError:()=>Ko,FloPayCheckout:()=>Ma,FloPayProvider:()=>Do,SplitCardForm:()=>Ea,VaultCardFields:()=>po,dropThirdPartyOnlyError:()=>_l.dropThirdPartyOnlyError,useCheckout:()=>Is,useFloPay:()=>kr,usePayPalFloPay:()=>ia});module.exports=Zl(Fd);var _l=require("@flopay/shared");var Ba=require("@flopay/js"),Xn=require("@flopay/shared"),et=require("react");var Bt=require("react/jsx-runtime");function Ql(){return(0,Bt.jsxs)(Bt.Fragment,{children:[(0,Bt.jsxs)("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:[(0,Bt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Bt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Bt.jsx)("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:(0,Bt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function ec(){return(0,Bt.jsx)(Bt.Fragment,{children:"Go back"})}function tc(){return(0,Bt.jsx)(Bt.Fragment,{children:"Secure card checkout"})}function Jr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Xr({content:e}){return(0,Bt.jsx)(Bt.Fragment,{children:e===void 0?(0,Bt.jsx)(Ql,{}):e})}function Zr({content:e}){return(0,Bt.jsx)(Bt.Fragment,{children:e===void 0?(0,Bt.jsx)(ec,{}):e})}function _o({content:e}){return(0,Bt.jsx)(Bt.Fragment,{children:e===void 0?(0,Bt.jsx)(tc,{}):e})}var _t=require("@flopay/shared"),nc="Checkout is temporarily unavailable. Please try again later.";function Xa(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof _t.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function rc(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function ys(){return new _t.FloPayError(nc,"api_error",{code:"CheckoutInitializationFailed"})}function fs(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card"))||t&&e?.data.paypal?.publishableKey)}function gs(e,t){if(t&&(!(e instanceof _t.FloPayError)||e.type==="authentication_error"))return Xa(e);if(!(e instanceof _t.FloPayError&&rc(e))){if(!t&&!(e instanceof _t.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,_t.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof _t.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof _t.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Qr(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let l={...r,...a,email:a.email?.trim()||r.email?.trim()},d=(0,_t.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,_t.isValidEmail)(l.email))return Promise.reject(new _t.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[g,y]of Object.entries(l)){if(d&&g.endsWith("Name")||typeof y!="string")continue;let b=y.trim();b&&(m[g]=b)}return o=e.claimCheckoutSession(t,n,{accountData:m}),o.catch(()=>{}),o}}function hs(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Za(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function bs(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,l)=>a+(l.overrideAmount??l.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.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((a,l)=>({uuid:`synthetic-${a.type??"item"}-${l}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function Or(e){if((0,_t.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Qa(e,t){return t?{...e,...t}:e}function nn(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var oc=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function xr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of oc)if(n.test(t))return r;return e}function zr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function eo(e){return e?.status==="authorized"||e?.status==="complete"}function vs(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ra(e){let t=vs(e);return new _t.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function oa(e){return e instanceof _t.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function aa(e){let t=vs(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new _t.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function Eo(e,t){return e==="processing"||(0,_t.isMoneySettledOutcome)(e,t)}function Ps(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Cs(e,t){let n=e;if((0,_t.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:l}=await n.retrieveSetupIntent(t);if(l)throw new _t.FloPayError(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new _t.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function Ss(e,t="automatic"){return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}function ei(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function To(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Rr=require("@flopay/js"),qe=require("@flopay/shared"),C=ms(require("react"),1);var ti=require("react"),Gn=(0,ti.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),ar=(0,ti.createContext)({session:null,loading:!1,error:null});var ua=require("@flopay/js"),Ut=require("@flopay/shared"),Es=require("@paypal/paypal-js"),_=require("react");var ws=require("@flopay/shared"),ir=require("react"),Cr=require("react/jsx-runtime");function Tn(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),l=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...l||t?{lastName:l??""}:{}}}function to(){let[e,t]=(0,ir.useState)(null),n=(0,ir.useRef)(null),r=(0,ir.useRef)(0),o=(0,ir.useCallback)((l,d)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:d}),new Promise(m=>{n.current=m})),[]),a=(0,ir.useCallback)(l=>{let d=n.current;n.current=null,t(null),d?.(l)},[]);return(0,ir.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function no({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,d]=(0,ir.useState)(e.email?.trim()??""),m=(0,ws.isValidEmail)(l.trim());return(0,Cr.jsxs)("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,Cr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Cr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Cr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:g=>d(g.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Cr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Cr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Cr.jsxs)("button",{type:"button",disabled:!m||o,onClick:()=>{n(Tn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function ac(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 Ur(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 Ur(t.code)??Ur(t.type)??Ur(t.name)}function ro(e){if(!(typeof e!="object"||e===null))return Ur(e.decline_code)}function Ao(e){return typeof e!="object"||e===null?!1:Ur(e.type)?.toLowerCase()==="card_error"||ro(e)!==void 0}function wr(e){let t=ac(e)?.toLowerCase()??"",r=`${Sr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var ks=require("@flopay/shared"),xo=require("react");function kr(){return(0,xo.useContext)(Gn).flopay}function ia(){return(0,xo.useContext)(Gn).paypalFlopay??null}function Is(){return(0,xo.useContext)(ar)}function Rs(){return(0,xo.useContext)(Gn).billingApiUrl||(0,ks.resolveBillingApiUrl)()}function sa(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 la(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var _s=require("@flopay/shared"),$r=require("react");function st(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}var ca=require("react"),qr=typeof window>"u"?ca.useEffect:ca.useLayoutEffect;var ic={"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 sc(e){return e==="stripe"||e==="paypal"?e:void 0}function lc(e){let t=sc(e.provider),n={schemaVersion:_s.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=ic[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var ni=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function oo(e,t){let n=(0,$r.useRef)(e);n.current=e;let r=(0,$r.useRef)(new Set),o=(0,$r.useRef)(t),a=(0,$r.useRef)(t);return qr(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,$r.useCallback)(l=>{if(a.current!==t)return;let d=lc(l);if(d){if(ni.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}st(()=>n.current?.(d))}},[t])}var cc=Symbol.for("@flopay/js.telemetry.bridge.v1"),dc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function uc(){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 pc(e){let t=uc(),n=(o,a)=>o?o.bind(e):a,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 da(e){let t=globalThis[dc];return pc(t?.(e)??{})}function Xt(e){if(e)return e[cc]}var Pn=require("react");function Mo(e){let t=(0,Pn.useRef)(0),n=(0,Pn.useRef)(null),r=(0,Pn.useRef)(null),o=(0,Pn.useCallback)((v=r.current)=>{v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),a=(0,Pn.useCallback)(v=>{o();let k=t.current+1;return t.current=k,n.current=null,r.current={generation:k,method:v,timer:null,yieldedControl:!1},k},[o]),l=(0,Pn.useCallback)(v=>{let k=r.current;return v!==void 0&&k?.generation!==v?!1:(o(k),r.current=null,(v===void 0||n.current===v)&&(n.current=null),!0)},[o]),d=(0,Pn.useCallback)(v=>{let k=r.current,B=v??k?.generation??t.current;(v===void 0||k?.generation===v)&&(o(k),r.current=null),n.current=B},[o]),m=(0,Pn.useCallback)(v=>n.current===(v??t.current),[]),g=(0,Pn.useCallback)(v=>r.current?.generation===v&&n.current!==v,[]),y=(0,Pn.useCallback)(()=>{let v=r.current;v&&(v.yieldedControl=!0,o(v))},[o]),b=(0,Pn.useCallback)(()=>{let v=r.current;!v?.yieldedControl||document.visibilityState!=="visible"||(o(v),v.timer=setTimeout(()=>{v.timer=null,r.current?.generation===v.generation&&(r.current=null,n.current=v.generation,e(v.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[o,e]);return(0,Pn.useEffect)(()=>{let v=()=>{document.visibilityState==="visible"?b():y()};return document.addEventListener("visibilitychange",v),window.addEventListener("blur",y),window.addEventListener("focus",b),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("blur",y),window.removeEventListener("focus",b),o()}},[o,y,b]),{startAttempt:a,finishAttempt:l,invalidateAttempt:d,isAttemptInvalidated:m,isAttemptCurrent:g,generationRef:t}}var Yn=require("react/jsx-runtime"),pa=45,mc=1e3,yc=11e3,fc=["https://www.paypal.com","https://www.sandbox.paypal.com"],ri="We couldn't open PayPal. Try again or choose another payment method.",gc={width:"100%",minHeight:pa,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 hc(e){return e.includes("No ack for postMessage init()")&&fc.some(t=>e.includes(t))&&e.includes("10000ms")}var bc={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 vc(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:bc[e.kind]??null}}function Pc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":hc(t)?"paypal_init_timeout":"paypal_init_failure"}function Cc(e,t=!1){return e?t?`${ri} Open this page in your system browser, then try again.`:`${ri} Allow pop-ups for this site, then try again.`:ri}function Sc(e){let t=Ao(e),n=wr(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 wc(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 kc(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Ts({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:d,currency:m,isSubscription:g,providerObjectType:y,approvalPresentation:b,onTokenizedBody:v,onComplete:k,onErrorChange:B,onDecline:L,onTechnicalFailure:he,isProcessing:te=!1,onLoadStateChange:S,onInitializationStateChange:J,allowAutomaticRetry:K=!0,onButtonClick:le,runBeforeButtonClick:Ce,session:j,existingOrderId:Le,telemetry:Ee,telemetryContext:tt,onInstrument:Ct,debug:Fe=!1}){let Me=kr(),pe=oo(Ct,e),Te=(0,_.useMemo)(()=>{if(Me)return null;let T=da({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ut.SDK_VERSION,enabled:Ee!==!1});return T.setCheckoutContext(tt??{}),T.beginCheckout(tt??{}),T},[n,Me,Ee,tt?.checkoutMode,tt?.layout]),me=(0,_.useMemo)(()=>Xt(Me),[Me]);(0,_.useEffect)(()=>()=>{Te&&Te.flush().catch(()=>{}).finally(()=>Te.destroy())},[Te]);let ye=(0,_.useMemo)(()=>({error:T=>{me?me.error(T):Te?.error(T),pe({class:"technical_error",errorCode:T.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":T.errorCode,requestCategory:T.requestCategory,provider:T.provider})},log:T=>{me?me.log(T):Te?.log(T),pe({class:"lifecycle",name:T.name,provider:T.provider})},performance:T=>{me?me.performance(T):Te?.performance(T)},terminal:T=>{me?me.terminal(T):Te?.terminal(T)},startTiming:()=>me?.now()??Te?.now()??0,elapsed:T=>me?.elapsed(T)??Math.max(0,(Te?.now()??T)-T)}),[pe,me,Te]),be=(0,_.useRef)(null),de=(0,_.useRef)(0),He=(0,_.useRef)(null),Ke=(0,_.useRef)(null),w=(0,_.useRef)(null),H=(0,_.useRef)(!1),[fe,ne]=(0,_.useState)(!1),[M,we]=(0,_.useState)(!1),[Oe,pt]=(0,_.useState)(0),Xe=(0,_.useRef)(0),[X,Y]=(0,_.useState)(!1),Z=(0,_.useRef)(!1),Ge=(0,_.useRef)(!1),[nt,Ae]=(0,_.useState)(!1),[ke,Ye]=(0,_.useState)(!1),{request:z,collect:Zt,finish:ie}=to(),St=(0,_.useRef)({sessionId:e,required:!(0,Ut.isValidEmail)(r?.trim()||j?.customer?.email?.trim())});St.current.sessionId!==e&&(St.current={sessionId:e,required:!(0,Ut.isValidEmail)(r?.trim()||j?.customer?.email?.trim())});let wt=St.current.required,rt=(0,_.useMemo)(()=>n.replace(/\/+$/,""),[n]),$e=j?.gateways?.paypal?.providerObjectType??y,f=$e??(g?"subscription":"order"),[A]=(0,_.useState)(sa),Se=j?.gateways?.paypal?.approvalPresentation??b,Ie=la(A,Se==="app_switch"?"app_switch":void 0,f),mt=$e==="order"||$e==="setup_token",At=(0,_.useMemo)(()=>JSON.stringify([rt,l,m,d??"",f,mt,Ie,e,Le??""]),[rt,l,m,d,Le,f,mt,Ie,e]),ze=(0,_.useRef)(At),Ve=ze.current!==At,dt=(0,_.useRef)(Fe),Bn=(0,_.useRef)(null),[rn,Et]=(0,_.useState)([]),se=(0,_.useCallback)(T=>{dt.current&&Et(re=>[...re,`${new Date().toISOString().slice(11,23)} ${T}`])},[]);(0,_.useEffect)(()=>{dt.current=Fe,Fe&&se("debug:enabled"),Bn.current?.setEnabled(Fe)},[se,Fe]);let fn=(0,_.useRef)(v),An=(0,_.useRef)(k),Qt=(0,_.useRef)(B),on=(0,_.useRef)(L),Fn=(0,_.useRef)(he),gn=(0,_.useRef)(le),Cn=(0,_.useRef)(S),qt=(0,_.useRef)(J),ve=(0,_.useRef)(a),ut=(0,_.useRef)(Ce),yt=(0,_.useRef)(j),Sn=(0,_.useRef)(r),xt=(0,_.useRef)(o),Dn=(0,_.useRef)(t),ft=(0,_.useRef)(null),gt=(0,_.useRef)(new Map),cn=(0,_.useRef)(new Map),dn=(0,_.useRef)(!1);(0,_.useEffect)(()=>(dn.current=!0,()=>{dn.current=!1}),[]),(0,_.useEffect)(()=>{fn.current=v},[v]),(0,_.useEffect)(()=>{ve.current=a},[a]),(0,_.useEffect)(()=>{An.current=k},[k]),(0,_.useEffect)(()=>{Qt.current=B},[B]),(0,_.useEffect)(()=>{on.current=L},[L]),(0,_.useEffect)(()=>{Fn.current=he},[he]),(0,_.useEffect)(()=>{gn.current=le},[le]),(0,_.useEffect)(()=>{Cn.current=S},[S]),(0,_.useEffect)(()=>{qt.current=J},[J]),(0,_.useEffect)(()=>{ut.current=Ce},[Ce]),(0,_.useEffect)(()=>{yt.current=j},[j]),(0,_.useEffect)(()=>{Sn.current=r},[r]),(0,_.useEffect)(()=>{xt.current=o},[o]),(0,_.useEffect)(()=>{Dn.current=t},[t]),(0,_.useEffect)(()=>{Xe.current=Oe},[Oe]),(0,_.useEffect)(()=>{X&&w.current?.focus()},[X,Oe]);let Ft=(0,_.useCallback)(()=>{window.setTimeout(()=>{w.current?.focus()},0)},[]),kt=(0,_.useCallback)(()=>{ne(!1),pt(T=>T+1)},[]),Nn=(0,_.useCallback)(()=>{Y(!1),(be.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??be.current)?.focus?.()},[]);(0,_.useEffect)(()=>{!fe||!H.current||(H.current=!1,Nn())},[Nn,fe,Oe]);let Gt=(0,_.useCallback)((T,re)=>{let U=re?.popupBlocked??wr(T),Nt=Cc(U,A.inAppBrowser),Zn=Fn.current;if(Zn){let lt=U&&A.inAppBrowser?new Ut.FloPayError(Nt,"api_error",{code:re?.code??"paypal_popup_blocked"}):T;Zn("paypal",lt,re);return}Qt.current?.(Nt)},[A.inAppBrowser]),$=(0,_.useCallback)(T=>{let re=He.current,U=Ke.current;re===null||!U||(ye.log({...U,name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:T}),ye.performance({...U,stage:"overlay_return",durationMs:ye.elapsed(re),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:T}),He.current=null)},[ye]),dr=(0,_.useCallback)((T,re,U)=>{let Nt=Ke.current;$("overlay_timeout"),Nt&&ye.error({...Nt,errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Gt(re,U),Y(!0),kt(),Ft()},[$,Ft,Gt,kt,ye]),{finishAttempt:Kt,generationRef:hn,invalidateAttempt:Dt,isAttemptCurrent:un,isAttemptInvalidated:Ln,startAttempt:pn}=Mo(dr),We=(0,_.useCallback)(()=>(Y(!1),pn("paypal")),[pn]),wn=(0,_.useCallback)(T=>{Dt(T?.generation),T?.showRetry&&Y(!0),T?.remount&&kt(),T?.focus!==!1&&Ft()},[Ft,Dt,kt]),an=T=>{let re=ft.current;return re&&cn.current.set(T,re),T};(0,_.useEffect)(()=>{ze.current!==At&&(ze.current=At,Z.current=!1,Ge.current=!1,ne(!1),we(!1),Ae(!1),qt.current?.("loading"))},[At]),(0,_.useEffect)(()=>{st(()=>Cn.current?.(fe&&!nt))},[fe,nt]);let mn=(0,Ut.normalizeGatewayEnvironment)(d);(0,_.useEffect)(()=>{let T={attempt:hn.current+1,...A,presentationMode:Ie},re=()=>Ke.current??T,U={error:h=>ye.error({...h,...re()}),log:h=>ye.log({...h,...re()}),performance:h=>ye.performance({...h,...re()}),terminal:h=>ye.terminal({...h,...re()}),startTiming:ye.startTiming,elapsed:ye.elapsed},Nt=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Zn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(se(`mount clientId=${Nt} env=${d??"(unset)"}\u2192${mn??"live"} ccy=${m} sub=${g}`),se(`ua=${Zn.slice(0,80)}${Zn.length>80?"\u2026":""}`),!l){se("FAIL: clientId empty \u2014 gateway misconfigured"),Ae(!0),U.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(!be.current){se("FAIL: containerRef not attached");return}de.current=U.startTiming(),U.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let lt=!1,yn=!1,at=()=>lt||yn,Br,_r=!1,On=()=>{Br=(0,Ut.generateIdempotencyKey)(),Br||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),_r=!0},Er=null,Pr=!1,zn=null,Yt=!1,ur=()=>{!zn||Yt||(Yt=!0,zn.close().catch(()=>{}))},kn=!1,Qn=!1,bn=be.current,er=null,ht=null,Un=[],In=null,Rn=!1,qn=!1,Ze=null,$t=h=>{if(!h||typeof h.getBoundingClientRect!="function")return"(no rect)";let u=h.getBoundingClientRect();return`${Math.round(u.width)}\xD7${Math.round(u.height)}`},Wt=h=>{if(!h)return"(empty)";try{let u=new URL(h,typeof window>"u"?"https://localhost":window.location.href),F=u.pathname.toLowerCase();return F.includes("checkcaptcha")||F.includes("captcha")?`CAPTCHA(${u.host}${F})`:F.includes("risk")||F.includes("challenge")?`RISK(${u.host}${F})`:F.includes("smart/buttons")?`smart-buttons(${u.host})`:`${u.host}${F}`.slice(0,100)}catch{return h.slice(0,80)}},Tr=h=>{let u=h.getAttribute("src"),F=h.getAttribute("srcdoc"),Ne=h.getAttribute("name"),Be=h.getAttribute("sandbox"),R=[];return u&&R.push(`src=${Wt(u)}`),F&&R.push(`srcdoc[${F.length}ch]`),!u&&!F&&R.push("src=(empty) srcdoc=(empty)"),Ne&&R.push(`name=${Ne.slice(0,40)}`),Be!==null&&R.push(`sandbox="${Be.slice(0,40)}"`),R.join(" ")},fo=h=>{if(!(h instanceof HTMLIFrameElement))return"";try{let u=h.contentDocument;if(!u)return"cd=null";let F=u.body?.children.length??0,Ne=u.body?.innerHTML.length??0,Be=u.head?.innerHTML.length??0;return`cd=same-origin readyState=${u.readyState} body[${F}children,${Ne}ch] head[${Be}ch]`}catch(u){return`cd=cross-origin(${u.message.slice(0,30)})`}},pr=[],$n=h=>{if(at())return;let u=h.message??String(h.error??"(no message)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&(se(`window:error ${u.slice(0,140)}`),pr.push(u))},Vn=h=>{if(at())return;let u=h.reason instanceof Error?h.reason.message:String(h.reason??"(no reason)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&(se(`window:rejection ${u.slice(0,140)}`),pr.push(u))},sn={value:0},Fr=()=>{er?.disconnect(),er=null,ht?.disconnect(),ht=null;for(let h of Un.splice(0))clearTimeout(h);qn=!1,Rn&&typeof window<"u"&&(window.removeEventListener("error",$n),window.removeEventListener("unhandledrejection",Vn)),Rn=!1},Ar=()=>{if(!(Rn||at()||kn)){if(Rn=!0,pr.length=0,sn.value=0,typeof window<"u"&&(window.addEventListener("error",$n),window.addEventListener("unhandledrejection",Vn)),typeof PerformanceObserver<"u")try{ht=new PerformanceObserver(h=>{if(!at())for(let u of h.getEntries()){if(!u.name.toLowerCase().includes("paypal"))continue;sn.value+=1;let F=Math.round(u.duration);se(`net ${F}ms ${u.name.slice(0,90)}`)}}),ht.observe({type:"resource",buffered:!0})}catch{}Ze?.()}},tr=()=>{In&&(clearTimeout(In),In=null)},nr=()=>{Fr(),tr()},en={setEnabled:h=>{h?Ar():Fr()}};Bn.current=en,dt.current&&Ar();let P=h=>{if(!h)return!1;let u=h.toLowerCase();return u.includes("zoid destroyed")||u.includes("destroyed all components")||u.includes("window closed")||u.includes("detected container element removed")},D=h=>{if(at()||P(h))return;let u=xr(h)??h;st(()=>Qt.current?.(u))},O=(h,u)=>{if(lt||Pr)return;Pr=!0,yn=!0,nr(),ur();let F=vc({kind:h,generationActive:!0,automaticRetryAllowed:K,automaticRetryUsed:Z.current});if(F.action==="retry"){Z.current=!0,ne(!1),Ye(!1),we(!0),qt.current?.("retrying"),Er=setTimeout(()=>{lt||pt(Ne=>Ne+1)},mc);return}if(ne(!1),Ye(!1),we(!1),Ae(!0),F.action!=="ignore"){if(qt.current?.("exhausted"),F.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",u);return}F.report&&U.error({errorCode:F.report.errorCode,stage:F.report.stage,operationOutcome:F.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),Ge.current||(Ge.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Pc(h,u)))}};Ae(!1);let V=async(h,u=ft.current)=>{if(at())return;let F=u?.sessionId??e;if(fn.current){await fn.current(h,{sessionId:F,accountPatch:u?.accountPatch,nonce:u?.nonce});return}let Ne=U.startTiming();U.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Be=()=>{U.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),U.performance({stage:"processing",durationMs:U.elapsed(Ne),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let R=yt.current,Q=u?.accountPatch?.email??Sn.current,q=u?.accountPatch?.userId??R?.customer?.id??R?.accountData?.userId??"",It=u?.accountPatch?.firstName??R?.customer?.firstName??R?.accountData?.firstName,Lt=u?.accountPatch?.lastName??R?.customer?.lastName??R?.accountData?.lastName,_e=await new ua.PaymentAPI(rt,{telemetry:!1}).processPayment(q,{sessionId:F,nonce:u?.nonce??Dn.current,paymentMethodCategory:"paypal",tokenizedData:h,accountData:{userId:q,email:Q??R?.customer?.email??"",...It?{firstName:It}:{},...Lt?{lastName:Lt}:{},country:u?.accountPatch?.country??R?.customer?.country??R?.accountData?.country??void 0,zip:u?.accountPatch?.zip??R?.customer?.zip??R?.accountData?.zip??void 0}});if(_e.ok){if(yn||lt&&dn.current)return;Be(),U.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),st(()=>An.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(at())return;let ue=await _e.json().catch(()=>null),ge=ue?.message??"PayPal payment failed.",ee=xr(ge)??ge;Be(),_e.status===400&&(typeof ue?.declineCode=="string"||!Array.isArray(ue?.fields))?U.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):_e.status===400||_e.status===422?U.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):U.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:kc(_e.status),failureCategory:_e.status>=500?"server_error":void 0}),D(ee),st(()=>on.current?.(nn("paypal",ee,{code:ue?.code,declineCode:ue?.declineCode})));return}catch(R){if(at())return;Be(),U.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Q=R instanceof Error?R.message:"PayPal payment failed.",q=xr(Q)??Q;D(q),st(()=>on.current?.(nn("paypal",q)));return}},De=()=>new Ut.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),bt=h=>at()?Promise.reject(De()):Promise.resolve(h),xe=async h=>{if(at())throw De();_r||On();let u=ft.current,F=u?.sessionId??e,Ne=u?.nonce??Dn.current;U.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Be;try{Be=await new ua.PaymentAPI(rt,{telemetry:!1}).createSessionIntent(F,Ne??"",mt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Ut.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:f==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Br})}catch(R){throw U.error({...(0,Ut.classifyTelemetryFailure)(R,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),R}if(at())throw De();if(Be.provider!=="paypal"||Be.providerObjectType!==f)throw new Error(h);return U.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Be.providerObjectId},ae=(h,u)=>{let F=u?.nonce??Dn.current;if(!F)return;let Ne=u?.sessionId??e,Be=ro(h)??Sr(h)??"provider_declined";new ua.PaymentAPI(rt,{telemetry:!1}).reportSessionIntentDecline(Ne,F,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Be}).catch(()=>{})},oe=Oe;se("loadScript:scheduled (deferred 1 tick)");let x=null,ce=setTimeout(()=>{if(lt){se("loadScript:skipped (cancelled before defer ran)");return}se("loadScript:start");let h=mn==="live"?"production":mn,u={};f==="subscription"?u={intent:"subscription",vault:!0}:f==="order"&&(u={intent:"capture"}),x=(0,Es.loadScript)({clientId:l,currency:m,...u,...h?{environment:h}:{},...h==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let F=!1;x.then(Ne=>{if(F=!0,se(`loadScript:resolved inactive=${at()} ns=${!!Ne} buttons=${!!Ne?.Buttons}`),at())return;if(!Ne?.Buttons){se("FAIL: namespace missing Buttons factory"),O("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}U.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),U.performance({stage:"provider_ready",durationMs:U.elapsed(de.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),U.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Be=async(_e,ue)=>{if(at()||Xe.current!==oe)return;let ge=_e.vaultSetupToken??_e.subscriptionID??_e.orderID??"",ee=ge?cn.current.get(ge):gt.current.get(oe);if(!(!ee||!un(ee.generation))&&Kt(ee.generation)){cn.current.delete(ge),gt.current.delete(ee.surfaceKey),$("approved");try{if(Ye(!0),st(()=>Qt.current?.(null)),!ge)throw new Ut.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Qe=yt.current,tn=Or(xt.current??[Qe?.customer?.firstName,Qe?.customer?.lastName].filter(Boolean).join(" ")),je=Tn({email:ee.accountPatch?.email?.trim()||Sn.current?.trim()||Qe?.customer?.email?.trim(),firstName:ee.accountPatch?.firstName?.trim()||tn.firstName,lastName:ee.accountPatch?.lastName?.trim()||tn.lastName});if(!(0,Ut.isValidEmail)(je.email)||!(je.firstName||je.lastName))try{let xn=wc(await ue?.order?.get?.());je=Tn({email:xn.email||je.email,firstName:xn.firstName||je.firstName,lastName:xn.lastName||je.lastName})}catch{}if((ve.current||wt)&&!(0,Ut.isValidEmail)(je.email)){let xn=await Zt("PayPal",je);if(!xn)return;je=xn}(0,Ut.isValidEmail)(je.email)&&(ee.accountPatch=Tn({...ee.accountPatch,...je}),await ve.current?.(je));let rr;f==="setup_token"?rr={id:ge,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Ut.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:mt?rr={id:ge,isPaypal:!0,gateway:"paypal",paymentMethodType:Ut.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:rr={id:ge,isPaypal:!0},await V(rr,ee)}catch(Qe){D(Qe instanceof Error?Qe.message:"PayPal capture failed.")}finally{at()||Ye(!1)}}},R=_e=>{let ue=Le?()=>bt(Le):()=>xe(_e);return async()=>an(await ue())},Q=Ne.Buttons({style:{layout:"horizontal",height:pa,tagline:!1},...Ie==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(_e,ue)=>{if(at()){await ue.reject();return}On();let ge=ut.current,ee={};if(ge)try{let je=await ge("paypal");if(at()){await ue.reject();return}if(!je.proceed){ft.current=null,gt.current.delete(oe),await ue.reject();return}ee={sessionId:je.sessionId,accountPatch:je.accountPatch,nonce:je.nonce}}catch(je){se(`onClick:runBeforeButtonClick rejected msg=${(je instanceof Error?je.message:String(je)).slice(0,120)}`),ft.current=null,gt.current.delete(oe),await ue.reject();return}st(()=>gn.current?.("paypal"));let Qe=We(),tn={generation:Qe,surfaceKey:oe,...ee};ft.current=tn,gt.current.set(oe,tn),Ke.current={...T,attempt:Qe},await ue.resolve(),U.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),U.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),He.current=U.startTiming()},createOrder:f==="order"?R("Failed to create PayPal order."):void 0,createSubscription:f==="subscription"?R("Failed to create PayPal subscription."):void 0,createVaultSetupToken:f==="setup_token"?async()=>an(await xe("Failed to create PayPal setup token.")):void 0,onApprove:Be,onCancel:()=>{if(at())return;let _e=gt.current.get(oe)??ft.current;_e&>.current.delete(_e.surfaceKey),ft.current=null,$("cancelled"),U.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),H.current=!0,wn({generation:_e?.generation,remount:!0,focus:!1})},onError:_e=>{if(at()||Xe.current!==oe)return;let ue=_e instanceof Error?_e.message:"PayPal failed to render.";if(se(`onError rendered=${kn} msg=${ue.slice(0,120)}`),kn){let ge=gt.current.get(oe)??ft.current;if(ge&&!un(ge.generation)||!ge&&Ln())return;if(P(ue)){Kt(ge?.generation);return}let{errorCode:ee,popupBlocked:Qe,providerDeclined:tn,terminalReason:je}=Sc(_e);if($(je),tn){U.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:je}),ae(_e,ge),st(()=>on.current?.(nn("paypal",ue))),ge&>.current.delete(ge.surfaceKey),ft.current=null,Kt(ge?.generation);return}U.error({errorCode:ee,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:je}),ge&>.current.delete(ge.surfaceKey),ft.current=null,wn({generation:ge?.generation,remount:!0,showRetry:!0,focus:!0}),Gt(_e,{code:"paypal_runtime_failed",popupBlocked:Qe});return}O(P(ue)?"teardown":"pre_ready_callback",ue)}}),q=Q.isEligible();if(se(`isEligible=${q}`),U.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!q){ne(!1),O("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Qn=!0,zn=Q,Ze=()=>{if(!Rn||qn||at()||kn)return;qn=!0,se(`container:dims ${$t(bn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(er=new MutationObserver(ue=>{if(!at()){for(let ge of ue)if(ge.type==="childList")ge.addedNodes.forEach(ee=>{if(!(ee instanceof Element))return;let Qe=ee.tagName.toLowerCase(),tn=(ee.getAttribute("title")??"").slice(0,40),je=Qe==="iframe"?` ${Tr(ee)}`:"";se(`child+ ${Qe}${tn?` title="${tn}"`:""}${je} dims=${$t(ee)}`)});else if(ge.type==="attributes"&&ge.target instanceof Element){let ee=ge.target;if(ee.tagName.toLowerCase()!=="iframe")continue;let Qe=ge.attributeName;(Qe==="src"||Qe==="srcdoc")&&se(`attr~ iframe ${Qe}=${Qe==="srcdoc"?`[${(ee.getAttribute("srcdoc")??"").length}ch]`:Wt(ee.getAttribute("src"))} dims=${$t(ee)}`)}}}),er.observe(bn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let _e=ue=>{if(at()||kn)return;let ge=bn.querySelectorAll("iframe"),ee=typeof document<"u"&&"hasStorageAccess"in document;se(`watchdog:${ue} container=${$t(bn)} children=${bn.childElementCount} iframes=${ge.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${ee} paypalNetRequests=${sn.value}`),ge.forEach((Qe,tn)=>{let je=(Qe.getAttribute("title")??"").slice(0,40);se(` iframe[${tn}] ${$t(Qe)}${je?` title="${je}"`:""} ${Tr(Qe)}`);let rr=fo(Qe);rr&&se(` ${rr}`)}),pr.length===0&&se(" (no PayPal/zoid window errors captured)")};Un.push(setTimeout(()=>_e("3s"),3e3)),Un.push(setTimeout(()=>_e("8s"),8e3)),Un.push(setTimeout(()=>_e("15s"),15e3))},Ze(),se("render:start");let Lt=U.startTiming();In=setTimeout(()=>{at()||kn||(se("watchdog:11s retryable render timeout"),O("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},yc);let jn=Q.render(bn);(async()=>{try{if(await jn,se(`render:resolved inactive=${at()}`),nr(),at()){ur();return}kn=!0,ne(!0),we(!1),qt.current?.("ready"),U.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),U.performance({stage:"checkout_render",durationMs:U.elapsed(Lt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(_e){let ue=_e instanceof Error?_e.message:"PayPal failed to render.";se(`render:rejected msg=${ue.slice(0,120)}`),nr(),O(P(ue)?"teardown":"render_rejected",ue)}})()}).catch(Ne=>{let Be=Ne instanceof Error?Ne.message:"PayPal operation failed.";se(`provider:failed msg=${Be.slice(0,120)}`);let R="script_rejected";F&&P(Be)?R="teardown":F&&Qn&&(R="render_rejected"),O(R,Be)})},0);return()=>{lt=!0,clearTimeout(ce),Er&&clearTimeout(Er),nr(),Bn.current===en&&(Bn.current=null),ur(),He.current=null,Ke.current=null}},[K,rt,l,m,d,f,Ie,mt,e,Le,Oe,ye,Zt,wt,se,$]);let Re=Fe?(0,Yn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:nt?"#fef2f2":"#f3f4f6",border:`1px solid ${nt?"#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=${fe} failed=${nt})`,rn.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return
|
|
3
|
+
${rn.join(`
|
|
4
|
+
`)}`]}):null;return nt&&!Ve?Fe?(0,Yn.jsx)("div",{children:Re}):null:(0,Yn.jsxs)("div",{children:[Re,z&&(0,Yn.jsx)(no,{identity:z.identity,methodLabel:z.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:ie,onCancel:()=>ie(null)}),(0,Yn.jsxs)("div",{"aria-hidden":M||z?!0:void 0,style:M||z?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:pa},children:[!fe&&!M&&(0,Yn.jsx)("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"}}),(0,Yn.jsx)("div",{ref:be,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:pa,display:"flex",opacity:fe?1:0},"aria-busy":ke||te},Oe)]},Oe),X&&(0,Yn.jsx)("button",{ref:w,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Nn,style:gc,children:"Try PayPal again"})]})}function Bo(e){return(0,Yn.jsx)(Ts,{...e})}function As(e){return(0,Yn.jsx)(Ts,{...e})}var Fo=require("react/jsx-runtime");function ao({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,Fo.jsxs)("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&&(0,Fo.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Fo.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var ma=require("@flopay/shared");function io(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var ai=":idempotency-key";function ii(e,t){if(!io())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 si(e,t){if(!io())return null;try{let n=window.sessionStorage.getItem(e+ai);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 ya(e,t){if(io())try{ii(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function fa(e,t){if(ya(e,t),!!io())try{si(e,t)&&window.sessionStorage.removeItem(e+ai)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function ga(e,t,n,r){if(io())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 ha(e,t,n){if(io())try{window.sessionStorage.setItem(e+ai,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function oi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Ic(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([l],[d])=>l<d?-1:l>d?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let l=0;l<t.length;l++){let d=t.charCodeAt(l);n=r^Math.imul(n^d,597399067),r=o^Math.imul(r^d,2869860233),o=a^Math.imul(o^d,951274213),a=n^Math.imul(a^d,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(a^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),a=Math.imul(r^a>>>19,2716044179),n^=r^o^a,r^=n,o^=n,a^=n,[n,r,o,a].map(l=>(l>>>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=>oi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>oi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>oi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Ic(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function xs(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 Ms(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=(0,ma.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,ma.foldIntoProducts)(t.items,t.subscriptions)).map(g=>({type:g.type,code:g.code??g.providerItemId??g.providerPlanId??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??o).toUpperCase()})).sort((g,y)=>`${g.code}:${g.type??""}`.localeCompare(`${y.code}:${y.type??""}`)),l=e.products.map(g=>({type:g.type,code:g.code??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??e.currency).toUpperCase()})).sort((g,y)=>`${g.code}:${g.type??""}`.localeCompare(`${y.code}:${y.type??""}`));if(a.length!==l.length)return!1;for(let[g,y]of a.entries()){let b=l[g];if(b===void 0||y.code!==b.code||y.type!==void 0&&y.type!==b.type||y.quantity!==b.quantity||y.totalAmount!==b.totalAmount||y.overrideAmount!==b.overrideAmount||y.currency!==b.currency)return!1}let d=[...t.couponCodes??[]].sort(),m=[...e.coupons??[]].sort();return d.length===m.length&&d.every((g,y)=>g===m[y])}var Ht=require("react/jsx-runtime");var Rc={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function Jn({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:l="You will be automatically redirected, do not close or navigate away from this window.",theme:d=Rc}){let m={fontSize:13,color:d.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,Ht.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,Ht.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...d.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,Ht.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,Ht.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,Ht.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:d.spinnerTrackColor,strokeWidth:"3"}),(0,Ht.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:d.spinnerAccentColor})]}),e==="success"&&(0,Ht.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,Ht.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,Ht.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,Ht.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,Ht.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,Ht.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,Ht.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,Ht.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,Ht.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:d.labelColors[e]},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&a]}),e==="success"&&l!==null&&(0,Ht.jsx)("p",{style:m,children:l}),e==="error"&&t&&(0,Ht.jsx)("p",{style:m,children:t}),(0,Ht.jsx)("style",{children:`
|
|
5
5
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
6
6
|
@keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
|
|
7
7
|
@keyframes flopay-draw { to { stroke-dashoffset: 0; } }
|
|
8
8
|
@keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
|
|
9
|
-
`})]})})}var Cs=require("@flopay/shared"),yn=require("react");var Ss=require("react/jsx-runtime");function Fo({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=(0,yn.useState)(e instanceof Promise?null:e),[c,f]=(0,yn.useState)(t instanceof Promise||!t?null:t),y=(0,yn.useRef)(null),p=(0,yn.useRef)(null),b=ao(r);(0,yn.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,yn.useEffect)(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),(0,yn.useEffect)(()=>{if(a)return sn(a)?.subscribe?.(b)},[b,a]),(0,yn.useEffect)(()=>{if(!(!c||c===a))return sn(c)?.subscribe?.(b)},[b,a,c]),(0,yn.useEffect)(()=>{if(!a)return;let B=sn(a);return y.current=B?.beginCheckout()??B?.now()??0,B?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{B?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,yn.useEffect)(()=>{let B=!1;return e instanceof Promise?e.then(N=>{B||l(N)},()=>{B||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{B=!0}},[b,e]),(0,yn.useEffect)(()=>{let B=!1;if(!t){f(null);return}return t instanceof Promise?t.then(N=>{B||f(N)},()=>{B||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):f(t),()=>{B=!0}},[b,t]),(0,yn.useEffect)(()=>{if(!a||p.current===a)return;p.current=a;let B=sn(a);B?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),B?.performance({stage:"checkout_render",durationMs:B.elapsed(y.current??0),durationMode:"machine"})},[b,a]);let h=(0,Cs.resolveBillingApiUrl)(n?.billingApiUrl),w=(0,yn.useMemo)(()=>({flopay:a,paypalFlopay:c,billingApiUrl:h,emitInstrument:b}),[a,c,h,b]);return(0,Ss.jsx)(Yn.Provider,{value:w,children:o})}var ha="flopay_recent_completion_";function co(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ha+e,JSON.stringify(t))}catch{}}function oi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ha+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ha+e),!1):!0}catch{return!1}}var uo=require("@flopay/js"),Ve=require("@flopay/shared");var Lo="card";async function mc(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:a??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 yc(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function ii(e,t){return Object.assign(e,{checkoutMethod:t})}function kr(e,t){let n=e instanceof Ve.FloPayError?e:new Ve.FloPayError(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 Do(e,t){try{return await e()}catch(n){throw kr(n,t)}}function ks(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 fc(e){return e.status==="succeeded"||e.status==="declined"}async function Is(e){if(typeof document>"u"||typeof window>"u")throw new Ve.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ve.FloPayError("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`,a=async()=>{let p=new AbortController,b=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",b);let h=window.setTimeout(()=>p.abort(),r);try{let w=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:p.signal});if(!w.ok)return{status:"unknown"};let B=await w.json().catch(()=>null);return gc(B)}catch{return{status:"unknown"}}finally{window.clearTimeout(h),e.signal?.removeEventListener("abort",b)}},l=document.activeElement instanceof HTMLElement?document.activeElement:null,c=document.createElement("div");c.setAttribute("data-flopay-auto-3ds-overlay","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let 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(";"),f.src=e.nextActionRedirectUrl,c.appendChild(f),document.body.appendChild(c),f.focus();let y=null;try{y=new URL(e.billingApiUrl,window.location.href).origin}catch{y=null}try{let p=await new Promise((b,h)=>{let w=!1,B=0,N=0,de=0,K=!1,I=()=>{window.clearTimeout(B),window.clearInterval(N),window.clearTimeout(de),window.removeEventListener("message",se),f.removeEventListener("load",q),e.signal?.removeEventListener("abort",ie)},re=async()=>{if(!(w||K)){K=!0;try{let ee=await a();if(w||!fc(ee))return;w=!0,I(),b(ee)}finally{K=!1}}},q=()=>{window.clearTimeout(de),de=window.setTimeout(()=>{re()},250)},ie=()=>{w||(w=!0,I(),h(new Ve.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},se=ee=>{if(ee.source!==f.contentWindow||y&&ee.origin!==y)return;let Oe=ee.data;!Oe||typeof Oe!="object"||Oe.source!=="flopay-vault-3ds-return"||w||(w=!0,I(),b(null))};B=window.setTimeout(()=>{w||(w=!0,I(),h(new Ve.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),N=window.setInterval(()=>{re()},n),f.addEventListener("load",q),window.addEventListener("message",se),e.signal?.addEventListener("abort",ie),e.signal?.aborted&&ie()});return p||await a()}finally{c.parentNode?.removeChild(c),l?.isConnected&&l.focus()}}function gc(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Er(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,a=_r(o)??o;return ii(new Ve.FloPayError(a,"api_error",{code:(0,Ve.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ve.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function ai(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ba(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Rs(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ba(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let c of a)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||ba(c)))return c;let l=o.gateways;if(l&&typeof l=="object"){let c=l.stripe;if(c&&typeof c=="object"){let f=c,y=[f.stripeClientSecret,f.clientSecret];for(let p of y)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||ba(p)))return p}}}}async function hc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Rs(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let c=(await new uo.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ba(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function po({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let c=e.replace(/\/+$/,""),f=t??n.id,y=r??n.clientSecret,p=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",h=n.customer?.firstName??n.accountData?.firstName??"",w=n.customer?.lastName??n.accountData?.lastName??"",B=n.customer?.country??n.accountData?.country??void 0,N=n.customer?.zip??n.accountData?.zip??void 0,K=await new uo.PaymentAPI(c,l===!1?{telemetry:!1}:void 0).processPayment(p,{sessionId:f,nonce:y,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:p,email:b,firstName:h,lastName:w,country:B,zip:N},returnUrl:a??ai(n)});if(K.ok){let q=typeof K.json=="function"?await K.json().catch(()=>null):null;return(0,Ve.isAuthorizationOnlySession)(n)||q?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof q?.paymentId=="string"?q.paymentId:n.paymentId,sessionId:typeof q?.sessionId=="string"?q.sessionId:f,authorizationExpiresAt:typeof q?.authorizationExpiresAt=="string"?q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Eo(o),checkoutMethod:ws(o)}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Eo(o),checkoutMethod:ws(o)}}}let I;try{I=await K.json()}catch(q){throw new Ve.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:K.status,cause:q})}if(I?.type==="paypal_redirect_required"||I?.type==="3ds_required"){let q=Rs(I);if(!q)throw new Ve.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:K.status});return{type:I.type,threeDSecureToken:q,paymentMethodId:I.paymentMethodId}}if(I?.gatewayErrorCode==="authentication_required"){let q=await hc({billingApiUrl:c,sessionId:f,nonce:y,responseJson:I});if(q)return q;throw ii(new Ve.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let re=new Ve.FloPayError(I?.message??"Payment failed. Please try again.","api_error",{code:I?.code??I?.gatewayErrorCode,declineCode:I?.declineCode??I?.gatewayDeclineReason,statusCode:K.status});throw Object.assign(re,{telemetryOutcome:(0,Ve.classifyPaymentRejection)(K.status,I)})}async function va(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:c,telemetry:f}){let y=t?.getRawProvider();if(!y)throw kr(new Ve.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw ii(new Ve.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let p=(0,Ve.isSetupIntentClientSecret)(e.threeDSecureToken),b=null,h=e.paymentMethodId,w=await Do(()=>mc(y,e.threeDSecureToken,p),"card");if(w){if(w.error)throw kr(new Ve.FloPayError(w.error.message??`Failed to retrieve 3DS ${p?"setup":"payment"} status.`,"api_error",{code:w.error.code}),"card");let N=w.intent;!h&&N?.payment_method&&(typeof N.payment_method=="string"?h=N.payment_method:"id"in N.payment_method&&(h=N.payment_method.id??void 0))}let B=h?await Do(()=>yc(y,e.threeDSecureToken,{payment_method:h,return_url:c??ai(l)??window.location.href},p),"card"):null;if(B){if(B.error)throw kr(new Ve.FloPayError(B.error.message??"3DS authentication failed.","api_error",{code:B.error.code}),"card");b=B.intent}else{let N=await Do(()=>y.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(N.error)throw kr(new Ve.FloPayError(N.error.message??"3DS authentication failed.","api_error",{code:N.error.code}),"card");b=(p?N.setupIntent:N.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let N=await po({billingApiUrl:o,sessionId:a,session:l,telemetry:f,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:c});return N.type==="success"?{...N.result,paymentIntentId:N.result.paymentIntentId??b.id,paymentMethodId:N.result.paymentMethodId??h}:va(N,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:c,telemetry:f})}throw kr(new Ve.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let p=(n??t)?.getRawProvider();if(!p)throw kr(new Ve.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:h}=await Do(()=>p.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(h)throw kr(new Ve.FloPayError(h.message??"PayPal authorization failed.","api_error",{code:h.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await Do(()=>p.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??ai(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw kr(new Ve.FloPayError(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ve.FloPayError("Unsupported payment redirect state.","api_error")}function No(e){if(e instanceof Ve.FloPayError){let r=_r(e.message);return r&&r!==e.message?Object.assign(new Ve.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=_r(t)??t;return new Ve.FloPayError(n,"api_error")}function si(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ve.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function ws(e){if(e)return e.isPaypal?"paypal":"card"}async function li({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=t&&t!==e?t:void 0,[l,c]=await Promise.all([(0,uo.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,uo.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(y=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",y),null)):Promise.resolve(null)]);if(!l)throw new Ve.FloPayError("The payment provider did not initialize.","authentication_error");let f=null;return a?f=c:t&&(f=l),{flopay:l,paypalFlopay:f}}var Ir=require("@flopay/js"),u=require("@flopay/shared"),Ht=require("@stripe/react-stripe-js"),s=ns(require("react"),1);var _s={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"};var mr=require("react");function Es(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(l=>l.startsWith("background")),a={};for(let[l,c]of Object.entries(e))l in n||o&&l.startsWith("background")||(a[l]=c);for(let l of r)a[l]=n[l];return a}var bc=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function vc(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return bc.has(t.charAt(0).toLowerCase()+t.slice(1))}function Pc(e,t){return typeof t=="number"&&t!==0&&!vc(e)?`${t}px`:String(t).trim()}function Ts(e,t){if(e.style.cssText="",!!t){for(let[n,r]of Object.entries(t))if(!(r==null||r==="")){if(n.startsWith("--")){e.style.setProperty(n,String(r));continue}e.style[n]=Pc(n,r)}}}var xs=require("react/jsx-runtime");function mo({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:a,onReady:l,onError:c,onValidation:f}){let y=(0,mr.useRef)(null),p=(0,mr.useRef)(l),b=(0,mr.useRef)(c),h=(0,mr.useRef)(f);p.current=l,b.current=c,h.current=f;let w=(0,mr.useRef)(o);w.current=o;let B=(0,mr.useRef)(null);return(0,mr.useEffect)(()=>{let N=y.current;if(!N)return;let de=!0,K=!1,I=()=>{!de||K||(K=!0,p.current?.())},re=e.on("ready",()=>{I()}),q=e.on("error",ee=>{b.current?.(ee.message??"There was a problem loading the secure card form.")}),ie=e.on("validation",ee=>{h.current?.(ee.message??null)}),se={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...w.current?{theme:w.current}:{}};return B.current=w.current??null,e.mount(N,se).then(()=>{I()}).catch(ee=>{de&&b.current?.(ee instanceof Error?ee.message:"Failed to load the secure card form.")}),()=>{de=!1,re(),q(),ie(),e.unmount()}},[e,t,n,r]),Ur(()=>{let N=y.current;N&&Ts(N,a)},[a]),(0,mr.useEffect)(()=>{o!==void 0&&(o===null&&B.current===null||(B.current=o,e.applyTheme?.(o)))},[e,o]),(0,xs.jsx)("div",{ref:y,"data-testid":"flopay-vault-card-fields"})}var Ms=/^#([0-9a-f]{6})$/i,Cc=/^#([0-9a-f]{3})$/i,Bs=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Fs=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+|1\.0+)\s*\)$/i,Sc=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,wc=/^(-?\d+(?:\.\d+)?)(?:px)?$/,kc=/^(-?\d+(?:\.\d+)?)em$/,Ic=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,Rc=/^[a-z][a-z0-9 -]{0,31}$/i,_c=new Set(["none","uppercase","lowercase","capitalize"]);function Ds(e){if(typeof e!="string")return null;let t=e.trim(),n=Ms.exec(t);if(n){let p=Number.parseInt(n[1],16);return{r:p>>16&255,g:p>>8&255,b:p&255,a:null}}let r=Cc.exec(t);if(r){let[p,b,h]=r[1].split("").map(w=>Number.parseInt(w+w,16));return{r:p,g:b,b:h,a:null}}let o=Bs.exec(t),a=o?null:Fs.exec(t),l=o??a;if(!l)return null;let c=Number(l[1]),f=Number(l[2]),y=Number(l[3]);return c>255||f>255||y>255?null:{r:c,g:f,b:y,a:a?Number(a[4]):null}}function Ls({r:e,g:t,b:n,a:r}){return r===null?`#${(1<<24|e<<16|t<<8|n).toString(16).slice(1)}`:`rgba(${e},${t},${n},${r})`}function Oo(e){if(typeof e!="string")return;let t=e.trim();if(Ms.test(t)||Bs.test(t))return t;let n=Fs.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=Ds(t);return r?Ls(r):void 0}function Pa(e,t=.12){let n=Ds(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Ls({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function zo(e,t){let n=[],r=0,o="";for(let a of e){if(a==="("&&(r+=1),a===")"&&(r-=1),a===t&&r===0){o.trim()&&n.push(o.trim()),o="";continue}o+=a}return o.trim()&&n.push(o.trim()),n}function $r(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=wc.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Ec(e,t,n){if(typeof e!="string")return;let r=kc.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Tc(e){let t=zo(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=zo(o," "),l=Oo(a[0]);if(!l)return;let c=r/(t.length-1)*100,f=a[1]===void 0?c:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),y=n[n.length-1]?.position??-1;if(!Number.isFinite(f)||f<0||f>100||f<y)return;n.push({color:l,position:f})}return{type:"linearGradient",angle:0,stops:n}}function xc(e){if(typeof e!="string")return;let t=e.trim(),n=Oo(t);if(n)return{type:"solid",color:n};let r=Sc.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=Tc(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function Ac(e){return e.type==="solid"?{type:"solid",color:Pa(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:Pa(t.color)}))}}function Mc(e){let t=!1,n,r=[];for(let f of zo(e," ")){if(f.toLowerCase()==="inset"){t=!0;continue}let y=Oo(f);if(y){n=y;continue}let p=$r(f,-128,128);if(p===void 0)return;r.push(p)}if(!n||r.length<2||r.length>4)return;let[o,a,l=0,c=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||l>128||Math.abs(c)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:l,spread:c}}function Bc(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=zo(t,",").map(Mc);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function As(e){if(typeof e!="string")return;let t=zo(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>Rc.test(n)).slice(0,4);return t.length>0?t:void 0}function Fc(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=$r(t[0],0,64),r=$r(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function Dc(e){if(e==="bold")return 700;if(e==="normal")return 400;let t=Number(e);return Number.isInteger(t)&&t>=100&&t<=900?t:void 0}function Ns({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=xc(r.background??r.backgroundColor),l=Oo(o?.colorPrimaryHover),c=l?{type:"solid",color:l}:a&&Ac(a),f={fontFamilies:As(r.fontFamily)??As(n),fontSize:$r(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:Dc(r.fontWeight)??600,letterSpacing:Ec(r.letterSpacing,-.1,.5)??.01,lineHeight:$r(r.lineHeight,.8,2)??1,textTransform:_c.has(String(r.textTransform))?r.textTransform:"uppercase"},y=Fc(r.padding),p=Bc(r.boxShadow),b=$r(r.borderRadius,0,9999),h=typeof r.backdropFilter=="string"?$r(Ic.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Oo(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...c?{hoverBackground:c}:{},typography:f,...y?{spacing:y}:{},...p?{shadow:p}:{},...b===void 0?{}:{borderRadius:b},disabledOpacity:e?.theme==="night"?.8:.6,...h===void 0?{}:{backdropBlur:h}}}function yo(e,t=.12){let n=e.trim(),r=/^[0-9a-fA-F]{6}$/.test(n)?`#${n}`:n;return/^#[0-9a-fA-F]{6}$/.test(r)?Pa(r,t):e}function ci(e){if(typeof e=="number"||typeof e=="string")return e}function Ca({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=b=>typeof b=="string"&&b?b:void 0,a=t.submitButton,l=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",c=n==="buttons",f=t.nameInput,y=o(f?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",p=Ns({appearance:e,buttonsStyles:t,fontFamily:y});return{primaryColor:l,primaryHoverColor:o(r?.colorPrimaryHover)??yo(l,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(f?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(c?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:y,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(ci(f?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...p?{submitButton:p}:{}}}var d=require("react/jsx-runtime"),yr="flopay_stripe_resume",Os="flopay_wallet_resume",Gs="fw1",Lc=300*1e3,Nc=900,Oc=25e3,zc=25e3,di={},ui={};function Uc(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Ys(e){return e instanceof u.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function wa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Ir.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Ys(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Uo="flopay_paypal_resume",qc=250,zs="Just a moment \u2014 we are finalizing your order. Please press pay again.";function gi(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ka({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Ir.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function $c(e){return e instanceof u.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function pi(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Js({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=Nr(n),l=a.firstName?a:Nr(r?.name);return Dn({email:(0,u.isValidEmail)(o)?o:r?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function jc({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=Js({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,u.isValidEmail)(l.email)?l:a(o,l)}var Vc=`
|
|
9
|
+
`})]})})}var Bs=require("@flopay/shared"),ln=require("react");var Fs=require("react/jsx-runtime");function Do({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=(0,ln.useState)(e instanceof Promise?null:e),[d,m]=(0,ln.useState)(t instanceof Promise||!t?null:t),g=(0,ln.useRef)(null),y=(0,ln.useRef)(null),b=oo(r);(0,ln.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,ln.useEffect)(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),(0,ln.useEffect)(()=>{if(a)return Xt(a)?.subscribe?.(b)},[b,a]),(0,ln.useEffect)(()=>{if(!(!d||d===a))return Xt(d)?.subscribe?.(b)},[b,a,d]),(0,ln.useEffect)(()=>{if(!a)return;let B=Xt(a);return g.current=B?.beginCheckout()??B?.now()??0,B?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{B?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,ln.useEffect)(()=>{let B=!1;return e instanceof Promise?e.then(L=>{B||l(L)},()=>{B||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{B=!0}},[b,e]),(0,ln.useEffect)(()=>{let B=!1;if(!t){m(null);return}return t instanceof Promise?t.then(L=>{B||m(L)},()=>{B||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{B=!0}},[b,t]),(0,ln.useEffect)(()=>{if(!a||y.current===a)return;y.current=a;let B=Xt(a);B?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),B?.performance({stage:"checkout_render",durationMs:B.elapsed(g.current??0),durationMode:"machine"})},[b,a]);let v=(0,Bs.resolveBillingApiUrl)(n?.billingApiUrl),k=(0,ln.useMemo)(()=>({flopay:a,paypalFlopay:d,billingApiUrl:v,emitInstrument:b}),[a,d,v,b]);return(0,Fs.jsx)(Gn.Provider,{value:k,children:o})}var ba="flopay_recent_completion_";function lo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ba+e,JSON.stringify(t))}catch{}}function li(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ba+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ba+e),!1):!0}catch{return!1}}var co=require("@flopay/js"),Je=require("@flopay/shared");var Lo="card";async function _c(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:a??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 Ec(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function di(e,t){return Object.assign(e,{checkoutMethod:t})}function Ir(e,t){let n=e instanceof Je.FloPayError?e:new Je.FloPayError(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 No(e,t){try{return await e()}catch(n){throw Ir(n,t)}}function Ns(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 Tc(e){return e.status==="succeeded"||e.status==="declined"}async function Ls(e){if(typeof document>"u"||typeof window>"u")throw new Je.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Je.FloPayError("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`,a=async()=>{let y=new AbortController,b=()=>y.abort();e.signal?.aborted?y.abort():e.signal?.addEventListener("abort",b);let v=window.setTimeout(()=>y.abort(),r);try{let k=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:y.signal});if(!k.ok)return{status:"unknown"};let B=await k.json().catch(()=>null);return Ac(B)}catch{return{status:"unknown"}}finally{window.clearTimeout(v),e.signal?.removeEventListener("abort",b)}},l=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.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 m=document.createElement("iframe");m.setAttribute("title","Card authentication"),m.setAttribute("allow","payment"),m.tabIndex=0,m.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(";"),m.src=e.nextActionRedirectUrl,d.appendChild(m),document.body.appendChild(d),m.focus();let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let y=await new Promise((b,v)=>{let k=!1,B=0,L=0,he=0,te=!1,S=()=>{window.clearTimeout(B),window.clearInterval(L),window.clearTimeout(he),window.removeEventListener("message",Ce),m.removeEventListener("load",K),e.signal?.removeEventListener("abort",le)},J=async()=>{if(!(k||te)){te=!0;try{let j=await a();if(k||!Tc(j))return;k=!0,S(),b(j)}finally{te=!1}}},K=()=>{window.clearTimeout(he),he=window.setTimeout(()=>{J()},250)},le=()=>{k||(k=!0,S(),v(new Je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Ce=j=>{if(j.source!==m.contentWindow||g&&j.origin!==g)return;let Le=j.data;!Le||typeof Le!="object"||Le.source!=="flopay-vault-3ds-return"||k||(k=!0,S(),b(null))};B=window.setTimeout(()=>{k||(k=!0,S(),v(new Je.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),L=window.setInterval(()=>{J()},n),m.addEventListener("load",K),window.addEventListener("message",Ce),e.signal?.addEventListener("abort",le),e.signal?.aborted&&le()});return y||await a()}finally{d.parentNode?.removeChild(d),l?.isConnected&&l.focus()}}function Ac(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Mr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=xr(o)??o;return di(new Je.FloPayError(a,"api_error",{code:(0,Je.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Je.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function ci(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function va(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Os(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||va(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let d of a)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||va(d)))return d;let l=o.gateways;if(l&&typeof l=="object"){let d=l.stripe;if(d&&typeof d=="object"){let m=d,g=[m.stripeClientSecret,m.clientSecret];for(let y of g)if(typeof y=="string"&&y.length>0&&(!t?.requirePaymentIntentClientSecret||va(y)))return y}}}}async function xc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Os(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new co.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(va(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function uo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let d=e.replace(/\/+$/,""),m=t??n.id,g=r??n.clientSecret,y=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",v=n.customer?.firstName??n.accountData?.firstName??"",k=n.customer?.lastName??n.accountData?.lastName??"",B=n.customer?.country??n.accountData?.country??void 0,L=n.customer?.zip??n.accountData?.zip??void 0,te=await new co.PaymentAPI(d,l===!1?{telemetry:!1}:void 0).processPayment(y,{sessionId:m,nonce:g,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:y,email:b,firstName:v,lastName:k,country:B,zip:L},returnUrl:a??ci(n)});if(te.ok){let K=typeof te.json=="function"?await te.json().catch(()=>null):null;return(0,Je.isAuthorizationOnlySession)(n)||K?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof K?.paymentId=="string"?K.paymentId:n.paymentId,sessionId:typeof K?.sessionId=="string"?K.sessionId:m,authorizationExpiresAt:typeof K?.authorizationExpiresAt=="string"?K.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:To(o),checkoutMethod:Ds(o)}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:To(o),checkoutMethod:Ds(o)}}}let S;try{S=await te.json()}catch(K){throw new Je.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:te.status,cause:K})}if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let K=Os(S);if(!K)throw new Je.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:te.status});return{type:S.type,threeDSecureToken:K,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let K=await xc({billingApiUrl:d,sessionId:m,nonce:g,responseJson:S});if(K)return K;throw di(new Je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let J=new Je.FloPayError(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:te.status});throw Object.assign(J,{telemetryOutcome:(0,Je.classifyPaymentRejection)(te.status,S)})}async function Pa(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:d,telemetry:m}){let g=t?.getRawProvider();if(!g)throw Ir(new Je.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw di(new Je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let y=(0,Je.isSetupIntentClientSecret)(e.threeDSecureToken),b=null,v=e.paymentMethodId,k=await No(()=>_c(g,e.threeDSecureToken,y),"card");if(k){if(k.error)throw Ir(new Je.FloPayError(k.error.message??`Failed to retrieve 3DS ${y?"setup":"payment"} status.`,"api_error",{code:k.error.code}),"card");let L=k.intent;!v&&L?.payment_method&&(typeof L.payment_method=="string"?v=L.payment_method:"id"in L.payment_method&&(v=L.payment_method.id??void 0))}let B=v?await No(()=>Ec(g,e.threeDSecureToken,{payment_method:v,return_url:d??ci(l)??window.location.href},y),"card"):null;if(B){if(B.error)throw Ir(new Je.FloPayError(B.error.message??"3DS authentication failed.","api_error",{code:B.error.code}),"card");b=B.intent}else{let L=await No(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(L.error)throw Ir(new Je.FloPayError(L.error.message??"3DS authentication failed.","api_error",{code:L.error.code}),"card");b=(y?L.setupIntent:L.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let L=await uo({billingApiUrl:o,sessionId:a,session:l,telemetry:m,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:d});return L.type==="success"?{...L.result,paymentIntentId:L.result.paymentIntentId??b.id,paymentMethodId:L.result.paymentMethodId??v}:Pa(L,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:d,telemetry:m})}throw Ir(new Je.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let y=(n??t)?.getRawProvider();if(!y)throw Ir(new Je.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:v}=await No(()=>y.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(v)throw Ir(new Je.FloPayError(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await No(()=>y.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??ci(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw Ir(new Je.FloPayError(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Je.FloPayError("Unsupported payment redirect state.","api_error")}function Oo(e){if(e instanceof Je.FloPayError){let r=xr(e.message);return r&&r!==e.message?Object.assign(new Je.FloPayError(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=xr(t)??t;return new Je.FloPayError(n,"api_error")}function ui(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html;if(!t&&!n&&!r)throw new Je.FloPayError("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 Ds(e){if(e)return e.isPaypal?"paypal":"card"}async function pi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=t&&t!==e?t:void 0,[l,d]=await Promise.all([(0,co.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,co.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(g=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",g),null)):Promise.resolve(null)]);if(!l)throw new Je.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return a?m=d:t&&(m=l),{flopay:l,paypalFlopay:m}}var sr=require("@flopay/js"),p=require("@flopay/shared"),jt=require("@stripe/react-stripe-js"),s=ms(require("react"),1);var zs={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"};var gr=require("react");function Us(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(l=>l.startsWith("background")),a={};for(let[l,d]of Object.entries(e))l in n||o&&l.startsWith("background")||(a[l]=d);for(let l of r)a[l]=n[l];return a}var Mc=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function Bc(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Mc.has(t.charAt(0).toLowerCase()+t.slice(1))}function Fc(e,t){return typeof t=="number"&&t!==0&&!Bc(e)?`${t}px`:String(t).trim()}function qs(e,t){if(e.style.cssText="",!!t){for(let[n,r]of Object.entries(t))if(!(r==null||r==="")){if(n.startsWith("--")){e.style.setProperty(n,String(r));continue}e.style[n]=Fc(n,r)}}}var $s=require("react/jsx-runtime");function po({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:a,onReady:l,onError:d,onValidation:m}){let g=(0,gr.useRef)(null),y=(0,gr.useRef)(l),b=(0,gr.useRef)(d),v=(0,gr.useRef)(m);y.current=l,b.current=d,v.current=m;let k=(0,gr.useRef)(o);k.current=o;let B=(0,gr.useRef)(null);return(0,gr.useEffect)(()=>{let L=g.current;if(!L)return;let he=!0,te=!1,S=()=>{!he||te||(te=!0,y.current?.())},J=e.on("ready",()=>{S()}),K=e.on("error",j=>{b.current?.(j.message??"There was a problem loading the secure card form.")}),le=e.on("validation",j=>{v.current?.(j.message??null)}),Ce={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...k.current?{theme:k.current}:{}};return B.current=k.current??null,e.mount(L,Ce).then(()=>{S()}).catch(j=>{he&&b.current?.(j instanceof Error?j.message:"Failed to load the secure card form.")}),()=>{he=!1,J(),K(),le(),e.unmount()}},[e,t,n,r]),qr(()=>{let L=g.current;L&&qs(L,a)},[a]),(0,gr.useEffect)(()=>{o!==void 0&&(o===null&&B.current===null||(B.current=o,e.applyTheme?.(o)))},[e,o]),(0,$s.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields"})}var js=/^#([0-9a-f]{6})$/i,Dc=/^#([0-9a-f]{3})$/i,Ks=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Ws=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+|1\.0+)\s*\)$/i,Nc=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,Lc=/^(-?\d+(?:\.\d+)?)(?:px)?$/,Oc=/^(-?\d+(?:\.\d+)?)em$/,zc=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,Uc=/^[a-z][a-z0-9 -]{0,31}$/i,qc=new Set(["none","uppercase","lowercase","capitalize"]);function Hs(e){if(typeof e!="string")return null;let t=e.trim(),n=js.exec(t);if(n){let y=Number.parseInt(n[1],16);return{r:y>>16&255,g:y>>8&255,b:y&255,a:null}}let r=Dc.exec(t);if(r){let[y,b,v]=r[1].split("").map(k=>Number.parseInt(k+k,16));return{r:y,g:b,b:v,a:null}}let o=Ks.exec(t),a=o?null:Ws.exec(t),l=o??a;if(!l)return null;let d=Number(l[1]),m=Number(l[2]),g=Number(l[3]);return d>255||m>255||g>255?null:{r:d,g:m,b:g,a:a?Number(a[4]):null}}function Gs({r:e,g:t,b:n,a:r}){return r===null?`#${(1<<24|e<<16|t<<8|n).toString(16).slice(1)}`:`rgba(${e},${t},${n},${r})`}function zo(e){if(typeof e!="string")return;let t=e.trim();if(js.test(t)||Ks.test(t))return t;let n=Ws.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=Hs(t);return r?Gs(r):void 0}function Ca(e,t=.12){let n=Hs(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Gs({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function Uo(e,t){let n=[],r=0,o="";for(let a of e){if(a==="("&&(r+=1),a===")"&&(r-=1),a===t&&r===0){o.trim()&&n.push(o.trim()),o="";continue}o+=a}return o.trim()&&n.push(o.trim()),n}function Vr(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=Lc.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function $c(e,t,n){if(typeof e!="string")return;let r=Oc.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Vc(e){let t=Uo(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=Uo(o," "),l=zo(a[0]);if(!l)return;let d=r/(t.length-1)*100,m=a[1]===void 0?d:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),g=n[n.length-1]?.position??-1;if(!Number.isFinite(m)||m<0||m>100||m<g)return;n.push({color:l,position:m})}return{type:"linearGradient",angle:0,stops:n}}function jc(e){if(typeof e!="string")return;let t=e.trim(),n=zo(t);if(n)return{type:"solid",color:n};let r=Nc.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=Vc(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function Kc(e){return e.type==="solid"?{type:"solid",color:Ca(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:Ca(t.color)}))}}function Wc(e){let t=!1,n,r=[];for(let m of Uo(e," ")){if(m.toLowerCase()==="inset"){t=!0;continue}let g=zo(m);if(g){n=g;continue}let y=Vr(m,-128,128);if(y===void 0)return;r.push(y)}if(!n||r.length<2||r.length>4)return;let[o,a,l=0,d=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||l>128||Math.abs(d)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:l,spread:d}}function Hc(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=Uo(t,",").map(Wc);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function Vs(e){if(typeof e!="string")return;let t=Uo(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>Uc.test(n)).slice(0,4);return t.length>0?t:void 0}function Gc(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=Vr(t[0],0,64),r=Vr(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function Yc(e){if(e==="bold")return 700;if(e==="normal")return 400;let t=Number(e);return Number.isInteger(t)&&t>=100&&t<=900?t:void 0}function Ys({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=jc(r.background??r.backgroundColor),l=zo(o?.colorPrimaryHover),d=l?{type:"solid",color:l}:a&&Kc(a),m={fontFamilies:Vs(r.fontFamily)??Vs(n),fontSize:Vr(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:Yc(r.fontWeight)??600,letterSpacing:$c(r.letterSpacing,-.1,.5)??.01,lineHeight:Vr(r.lineHeight,.8,2)??1,textTransform:qc.has(String(r.textTransform))?r.textTransform:"uppercase"},g=Gc(r.padding),y=Hc(r.boxShadow),b=Vr(r.borderRadius,0,9999),v=typeof r.backdropFilter=="string"?Vr(zc.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:zo(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...d?{hoverBackground:d}:{},typography:m,...g?{spacing:g}:{},...y?{shadow:y}:{},...b===void 0?{}:{borderRadius:b},disabledOpacity:e?.theme==="night"?.8:.6,...v===void 0?{}:{backdropBlur:v}}}function mo(e,t=.12){let n=e.trim(),r=/^[0-9a-fA-F]{6}$/.test(n)?`#${n}`:n;return/^#[0-9a-fA-F]{6}$/.test(r)?Ca(r,t):e}function mi(e){if(typeof e=="number"||typeof e=="string")return e}function Sa({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=b=>typeof b=="string"&&b?b:void 0,a=t.submitButton,l=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",d=n==="buttons",m=t.nameInput,g=o(m?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",y=Ys({appearance:e,buttonsStyles:t,fontFamily:g});return{primaryColor:l,primaryHoverColor:o(r?.colorPrimaryHover)??mo(l,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(m?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(d?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:g,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(mi(m?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...y?{submitButton:y}:{}}}var c=require("react/jsx-runtime"),hr="flopay_stripe_resume",Js="flopay_wallet_resume",ll="fw1",Jc="fw2",cl=300*1e3,Xc=900,Zc=25e3,Qc=25e3,ed=1e4,yi={},fi={};function wi(e){return`${Jc}:${e}`}function wa(e){if(typeof window>"u")return!1;try{return localStorage.removeItem(wi(e)),!0}catch{return!1}}function ka(e,t){if(typeof window>"u")return null;let n=wi(e);try{let r=localStorage.getItem(n);if(!r)return null;let o=JSON.parse(r);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>cl||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 td(e){if(typeof window>"u")return!1;try{return localStorage.setItem(wi(e.sessionId),JSON.stringify(e)),!0}catch{return!1}}function Xs(e,t,n){let r=ka(e,t);return!r||r.clientSecret!==n?!1:wa(e)}function gi(e,t,n){if(typeof window>"u")return;ka(e,t)?.clientSecret===n&&wa(e)}function nd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function hi(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":Eo(e.status),o=nd(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function Zs(e,t,n){let r=null;try{return await Promise.race([Cs(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},ed),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function rd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function dl(e){return e instanceof p.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Ra(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new sr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw dl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var qo="flopay_paypal_resume",od=250,Qs="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ki(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function _a({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new sr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function ad(e){return e instanceof p.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function bi(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function ul({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=Or(n),l=a.firstName?a:Or(r?.name);return Tn({email:(0,p.isValidEmail)(o)?o:r?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function id({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=ul({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,p.isValidEmail)(l.email)?l:a(o,l)}var sd=`
|
|
10
10
|
.paypal-buttons { margin: 0 !important; vertical-align: top !important; }
|
|
11
11
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
12
12
|
@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
@@ -27,7 +27,7 @@ ${dn.join(`
|
|
|
27
27
|
0% { opacity: 1; transform: translateX(0) scale(1); }
|
|
28
28
|
100% { opacity: 0; transform: translateX(16px) scale(0.97); }
|
|
29
29
|
}
|
|
30
|
-
`,Sa=44,qo=280,Us=`flopay-card-enter ${qo}ms cubic-bezier(0, 0, 0.2, 1) both`,qs=`flopay-card-exit ${qo}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Kc=`flopay-buttons-enter ${qo}ms cubic-bezier(0, 0, 0.2, 1) both`,Hc=`flopay-buttons-exit ${qo}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Wc(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function hi(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 Gc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Yc(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 Xs={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 Jc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function $s(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function yi(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function Xc(e,t){let n=`We couldn't open ${yi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Zc(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Qc(e,t,n){let r=(0,u.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,l=a&&!o,c=a&&!!o&&!(0,u.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:c}}function ed(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,u.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function js(e,t){return t instanceof u.FloPayError?t:new u.FloPayError(t instanceof Error?t.message:`${Jc(e)} before-click hook failed.`,"validation_error")}function mi(){return(0,d.jsx)("style",{children:Vc})}function td(e){return typeof e=="number"?`${e}px`:e}function Zs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Qs({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,d.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,d.jsx)("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"}}),(0,d.jsx)("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 Vs(e){return e!=="unavailable"&&e!=="load_error"}function Ia(e){return(0,d.jsx)(rd,{...e})}function Ks({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:c,onDecline:f,onTechnicalFailure:y,runBeforeButtonClick:p,billingName:b,onBuyerIdentityReady:h,onLoadStateChange:w,placeholderBorderRadius:B}){let N=wr(),{emitInstrument:de}=(0,s.useContext)(Yn),K=(0,Ht.useStripe)(),I=(0,Ht.useElements)(),[re,q]=(0,s.useState)("loading");(0,s.useEffect)(()=>{w?.(re)},[re,w]);let[ie,se]=(0,s.useState)(!1),ee=!(0,u.isValidEmail)(n?.trim())||!b?.trim(),{request:Oe,collect:ue,finish:Ct}=no(),st=(0,s.useRef)(!1),Se=(0,s.useRef)(null),Re=(0,s.useRef)(null),[he,te]=(0,s.useState)(0),[Te,fe]=(0,s.useState)(!1),we=(0,s.useRef)(!1),xe=(0,s.useRef)(new Map),{startAttempt:Le,finishAttempt:_e,invalidateAttempt:_,isAttemptInvalidated:oe,isAttemptCurrent:me}=Ao((Z,X,$)=>{y?.(Z,X,{...$,popupBlocked:$?.popupBlocked??Sr(X)}),fe(!0),te(ze=>ze+1)});(0,s.useEffect)(()=>{Te&&Re.current?.focus()},[Te,he]);let J=(0,s.useCallback)(()=>{te(Z=>Z+1)},[]),O=(0,s.useCallback)((Z,X,$)=>{_($),y?.("paypal",Z,{code:X,popupBlocked:Sr(Z)}),fe(!0),J()},[_,y,J]),Ce=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Se.current?.querySelector("iframe")??Se.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{we.current&&(we.current=!1,Ce())},[Ce,he]);let Ke=(0,s.useCallback)(()=>{fe(!1),a?.(null),Ce()},[Ce,a]);(0,s.useEffect)(()=>{if(!K||st.current)return;let Z=new URLSearchParams(window.location.search),X=Z.get("payment_intent"),$=Z.get("payment_intent_client_secret"),ze=Z.get("redirect_status");if(!X||!$)return;st.current=!0;let Je;try{let Xe=localStorage.getItem(Uo);if(Xe){let H=JSON.parse(Xe);H.clientSecret===$&&(Je={...H.accountPatch?{accountPatch:H.accountPatch}:{},...H.sessionId?{sessionId:H.sessionId}:{},...H.nonce?{nonce:H.nonce}:{}})}}catch{}try{localStorage.removeItem(Uo)}catch{}let be=new URL(window.location.href);be.searchParams.delete("payment_intent"),be.searchParams.delete("payment_intent_client_secret"),be.searchParams.delete("redirect_status"),window.history.replaceState({},"",be.toString()),(async()=>{try{if(se(!0),ze==="failed"){let z="PayPal payment was declined. Please try again.";a?.(z),f?.(cn("paypal",z));return}let{paymentIntent:Xe,error:H}=await K.retrievePaymentIntent($);if(H){a?.(H.message??"Failed to retrieve PayPal payment status.");return}if(Xe&&(Xe.status==="requires_capture"||Xe.status==="succeeded")){let z=typeof Xe.payment_method=="string"?Xe.payment_method:Xe.payment_method?.id;o({id:z??Xe.id,type:"card",threeDSecureActionResultTokenId:Xe.id,isPaypal:!0},Je)}else{let z="PayPal payment was not completed. Please try again.";a?.(z),f?.(cn("paypal",z))}}catch(Xe){a?.(Xe instanceof Error?Xe.message:"Failed to complete PayPal payment.")}finally{se(!1)}})()},[K,o,a,f]);let _t=(0,s.useCallback)(async Z=>{if(l||ie){Z.reject();return}let X=p?await p("paypal"):{proceed:!0};if(!X.proceed){xe.current.delete(he),Z.reject();return}let $=Le("paypal");xe.current.set(he,{generation:$,accountPatch:X.accountPatch,sessionId:X.sessionId,nonce:X.nonce}),fe(!1),c?.("paypal"),Z.resolve()},[l,c,p,Le,ie,he]),Qe=(0,s.useCallback)(async Z=>{if(!K||!I)return;let X=xe.current.get(he);if(X&&!me(X.generation)){xe.current.delete(he);return}if(!X&&oe()||X&&!_e(X.generation))return;X||_e();let $=X??null;if(xe.current.delete(he),!$&&p){let z=await p("paypal");if(!z.proceed){Z.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}$={accountPatch:z.accountPatch,sessionId:z.sessionId,nonce:z.nonce}}let ze=$?.sessionId??e,Je=$?.nonce??t,be=await jc({event:Z,prepared:$,email:n,billingName:b,methodLabel:"PayPal",collect:ue});if(!be){Z.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Xe=be.email,H={...$?.accountPatch,...Dn(be,!0)};try{if(se(!0),a?.(null),!ze||!(0,u.isValidEmail)(Xe))throw new Error("Missing sessionId or email for PayPal payment");await h?.(be);let z=K.createPaymentMethod,{error:rt,paymentMethod:D}=await z({type:"paypal"});if(rt){O(rt,"stripe_paypal_create_payment_method_failed",X?.generation),Z.paymentFailed({reason:"fail"});return}let j=await wa(r,de,ze,Je??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:D?.id??null,intentKind:"payment"});if(j.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let qe=j.clientSecret,ve={return_url:window.location.href};if(D?.id&&(ve.payment_method=D.id),typeof window<"u")try{localStorage.setItem(Uo,JSON.stringify({clientSecret:qe,sessionId:ze,nonce:Je,accountPatch:H}))}catch{}let{error:Bt,paymentIntent:St}=await K.confirmPayment({clientSecret:qe,confirmParams:ve,redirect:"if_required"});if(Bt){if(typeof window<"u")try{localStorage.removeItem(Uo)}catch{}if(To(Bt)){let F=Bt.message??"Your payment was declined.";a?.(F),f?.(cn("paypal",F,{code:Cr(Bt),declineCode:oo(Bt)})),await ka({billingApiUrl:r,sessionId:ze,nonce:Je,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Cr(Bt)??"provider_declined"}})}else O(Bt,"stripe_paypal_confirm_failed",X?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Uo)}catch{}let P=typeof St?.payment_method=="string"?St.payment_method:St?.payment_method?.id;o({id:P??St?.id,type:"card",threeDSecureActionResultTokenId:St?.id,isPaypal:!0},{accountPatch:H,paymentMethodCategory:"paypal",sessionId:ze,nonce:Je});return}catch(z){O(z,"stripe_paypal_failed",X?.generation)}finally{se(!1)}},[K,I,e,t,n,b,ue,h,r,de,o,a,f,p,O,_e,me,oe,he]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Qs,{state:re,placeholderTestId:"flopay-paypal-placeholder",borderRadius:B,children:(0,d.jsxs)("div",{ref:Se,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Te&&(0,d.jsx)("button",{ref:Re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ke,style:Xs,children:"Try PayPal again"}),Oe&&(0,d.jsx)(ro,{identity:Oe.identity,methodLabel:Oe.methodLabel,onComplete:Ct,onCancel:()=>Ct(null)},Oe.id),(0,d.jsx)("div",{style:{display:Oe?"none":void 0},children:(0,d.jsx)(Ht.ExpressCheckoutElement,{onReady:Z=>q(Zs(Z,["paypal"])),onLoadError:()=>{q("load_error"),gi(sn(N),"paypal","paypal")},onClick:_t,onConfirm:Qe,onCancel:()=>{let Z=xe.current.get(he);xe.current.delete(he),sn(N)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),_(Z?.generation),fe(!1),we.current=!0,J()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ee,emailRequired:ee,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},he)})]})}),ie&&(0,d.jsx)(Xn,{status:"processing"})]})}function Hs({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:c,onButtonClick:f,onDecline:y,onTechnicalFailure:p,runBeforeButtonClick:b,billingName:h,onBuyerIdentityReady:w,onLoadStateChange:B,placeholderBorderRadius:N}){let de=wr(),{emitInstrument:K}=(0,s.useContext)(Yn),I=(0,Ht.useStripe)(),re=(0,Ht.useElements)(),[q,ie]=(0,s.useState)("loading");(0,s.useEffect)(()=>{B?.(q)},[q,B]);let[se,ee]=(0,s.useState)(!1),Oe=(0,s.useRef)(!(0,u.isValidEmail)(n?.trim())||!h?.trim()).current,{request:ue,collect:Ct,finish:st}=no(),Se=(0,s.useRef)(null),Re=(0,s.useRef)(null),[he,te]=(0,s.useState)(0),[Te,fe]=(0,s.useState)(!1),[we,xe]=(0,s.useState)("google_pay"),Le=(0,s.useRef)(!1),_e=(0,s.useRef)("google_pay"),_=(0,s.useRef)("google_pay"),oe=(0,s.useRef)(null),me=(0,s.useRef)(new Set);(0,s.useEffect)(()=>()=>{for(let z of me.current)window.clearTimeout(z);me.current.clear()},[]);let J=(0,s.useRef)(new Map),{startAttempt:O,finishAttempt:Ce,invalidateAttempt:Ke,isAttemptInvalidated:_t,isAttemptCurrent:Qe,generationRef:Z}=Ao((z,rt,D)=>{p?.(z,rt,{...D,popupBlocked:D?.popupBlocked??Sr(rt)}),xe(z),fe(!0),te(j=>j+1)});(0,s.useEffect)(()=>{Te&&Re.current?.focus()},[Te,he]);let X=(0,s.useCallback)(()=>{te(z=>z+1)},[]),$=(0,s.useCallback)((z,rt,D,j)=>{Ke(j),p?.(z,rt,{code:D,popupBlocked:Sr(rt)}),xe(z),fe(!0),X()},[Ke,p,X]),ze=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Se.current?.querySelector("iframe")??Se.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{Le.current&&(Le.current=!1,ze())},[ze,he]);let Je=(0,s.useCallback)(()=>{fe(!1),c?.(null),ze()},[ze,c]),be=(0,s.useCallback)(async z=>{let rt=!1,D=$e=>{rt||(rt=!0,z.paymentFailed({reason:"fail",...$e?{message:$e}:{}}))};if(!I||!re){D();return}let j=J.current.get(he);if(j&&!Qe(j.generation)){J.current.delete(he),D();return}if(!j&&_t()){D();return}if(j&&!Ce(j.generation)){D();return}j||Ce();let qe=z.expressPaymentType??j?.method??_e.current,ve=j??null,Bt=$s(qe),St;qe==="apple_pay"?St="apple_pay":qe==="google_pay"&&(St="google_pay");let P=j?.generation??Z.current,F=sn(de),qt=F?.now()??globalThis.performance?.now()??Date.now(),Ae=new AbortController,Et=!1,tn=!1,et=null,nn=e,lt="processing",Wt="other",dn="provider_runtime",rn,ke=new Promise(($e,ct)=>{rn=ct}),hn=window.setTimeout(()=>{Et=!0,Ae.abort(),rn(di)},Oc),bn=async($e,ct,un)=>{lt=$e,Wt=ct,dn=ct==="intent_create"||ct==="session_claim"?"transport_error":"provider_runtime";let Gt=F?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([un,ke])}finally{let pn=F?.now()??globalThis.performance?.now()??Date.now();F?.performance({stage:$e,durationMs:Math.max(0,pn-Gt),durationMode:"machine",requestCategory:ct,paymentMethodCategory:"wallet",provider:"stripe",...Et?{statusClass:"timeout"}:{}})}};try{if(ee(!0),c?.(null),!ve&&b){let E=await bn("processing","other",b(Bt));if(!E.proceed){D();return}ve={accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}}let $e=ve?.sessionId??e;nn=$e;let ct=ve?.nonce??t,un=oe.current??ve?.accountPatch,Gt=Js({event:z,fallbackEmail:un?.email??n,fallbackName:[un?.firstName,un?.lastName].join(" ").trim()||h});if(!(0,u.isValidEmail)(Gt.email)){D("Buyer details are required."),Ct(yi(qe),Gt).then(E=>{E&&(oe.current=E)});return}oe.current=null;let pn={...ve?.accountPatch,...Dn(Gt,!0)};await bn("processing","session_claim",Promise.resolve(w?.(Gt)));let{error:$t}=await bn("tokenization","provider_sdk",re.submit());if($t){D(),$(qe,$t,"stripe_wallet_submit_failed",j?.generation);return}if(!$e)throw new Error("Missing sessionId or email for payment.");let wt=await bn("processing","intent_create",wa(r,K,$e,ct??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:qe,paymentMethodId:null,intentKind:o},{signal:Ae.signal}));if(wt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Qn=wt.clientSecret;window.clearTimeout(hn),tn=!0,F?.performance({stage:"callback",durationMs:Math.max(0,(F?.now()??globalThis.performance?.now()??Date.now())-qt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let kt=F?.now()??globalThis.performance?.now()??Date.now(),vn={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...St?{walletType:St}:{},attempt:P},ht=!1;F?.log({name:"payment.provider_confirmation.started",...vn}),et=window.setTimeout(()=>{et!==null&&me.current.delete(et),ht=!0;let E=F?.now()??globalThis.performance?.now()??Date.now();F?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...vn,operationOutcome:"watchdog_expired",checkoutSessionId:$e,durationMs:Math.max(0,E-kt),statusClass:"timeout",failureCategory:"provider_runtime"}),F?.flush?.().catch(()=>{})},zc),me.current.add(et);let Yt=E=>{et!==null&&(window.clearTimeout(et),me.current.delete(et),et=null);let xt=F?.now()??globalThis.performance?.now()??Date.now(),ot=Math.max(0,xt-kt),Xt=E;return ht&&(E==="resolved"?Xt="resolved_late":E==="returned_error"?Xt="returned_error_late":Xt="rejected_late"),F?.log({name:"payment.provider_confirmation.returned",...vn,operationOutcome:Xt}),F?.performance({...vn,durationMs:ot,durationMode:"buyer",operationOutcome:Xt}),{durationMs:ot,operationOutcome:Xt}},dt=!1,Tt=E=>{if(!E||typeof E!="object")return null;let xt=E;if(xt.error)return null;let ot=xt.setupIntent??xt.paymentIntent,Xt=ot?.id,on=ot?.status,Ln=xt.setupIntent?on==="succeeded":_o(typeof on=="string"?on:void 0),Tn=ot?.payment_method,Zt=null;return typeof Tn=="string"?Zt=Tn:typeof Tn?.id=="string"&&(Zt=Tn.id),!Ln||typeof Xt!="string"||!Zt?null:{intentId:Xt,paymentMethodId:Zt}},Pn=E=>{if(dt||j&&Z.current!==j.generation)return;let xt=Tt(E);if(!xt)return;let{intentId:ot,paymentMethodId:Xt}=xt;dt=!0;let on=`${Gs}:${$e}`;if(typeof window<"u")try{localStorage.setItem(on,JSON.stringify({createdAt:Date.now(),sessionId:$e,nonce:ct,accountPatch:pn,paymentMethodId:Xt,providerIntentId:ot,paymentMethodType:qe}))}catch{}try{l({id:Xt,type:"card",threeDSecureActionResultTokenId:ot},{accountPatch:pn,paymentMethodCategory:"wallet",sessionId:$e,nonce:ct})}finally{if(typeof window<"u")try{localStorage.removeItem(on)}catch{}}},Jt,Cn;try{let E=await((0,u.isSetupIntentClientSecret)(Qn)?I.confirmSetup({elements:re,clientSecret:Qn,redirect:"if_required"}):I.confirmPayment({elements:re,clientSecret:Qn,redirect:"if_required"}));if(!E||typeof E!="object"||(Jt=E,!Jt.error&&!Tt(Jt)))throw ui;Cn=Yt(Jt.error?"returned_error":"resolved")}catch(E){let xt=E===ui,ot=Yt(xt?"returned_error":"rejected");throw F?.error({...xt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:Ja(E),...vn,operationOutcome:ot.operationOutcome,checkoutSessionId:$e,durationMs:ot.durationMs,statusClass:"unknown"}),E}let ut=Jt.error;if(ut){if(To(ut)){let E=ut.message??"Your payment was declined.";D(E),c?.(E),y?.(cn(Bt,E,{code:Cr(ut),declineCode:oo(ut)})),ka({billingApiUrl:r,sessionId:$e,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:qe,providerDeclineReason:Cr(ut)??"provider_declined",...wt.intentKind==="payment"&&wt.providerObjectId.startsWith("pi_")?{providerIntentId:wt.providerObjectId}:{}}})}else F?.error({...Ja(ut),...vn,operationOutcome:Cn.operationOutcome,checkoutSessionId:$e,durationMs:Cn.durationMs,statusClass:"unknown"}),D(),$(qe,ut,"stripe_wallet_confirm_failed",j?.generation);return}if(Pn(Jt),!dt)throw new Error("Invalid provider returned for APM intent")}catch($e){if($e===di){let ct=F?.now()??globalThis.performance?.now()??Date.now();F?.error({errorCode:Uc(Wt),stage:lt,requestCategory:Wt,paymentMethodCategory:"wallet",provider:"stripe",...St?{walletType:St}:{},operationOutcome:"watchdog_expired",checkoutSessionId:nn,durationMs:Math.max(0,ct-qt),statusClass:"timeout",failureCategory:dn,attempt:P}),F?.flush?.().catch(()=>{})}D(),$(qe,$e,$e===di?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",j?.generation)}finally{if(window.clearTimeout(hn),et!==null&&(window.clearTimeout(et),me.current.delete(et)),!tn){let $e=F?.now()??globalThis.performance?.now()??Date.now();F?.performance({stage:"callback",durationMs:Math.max(0,$e-qt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Et?{statusClass:"timeout"}:{}})}ee(!1)}},[I,re,e,t,n,h,Ct,w,r,K,o,l,c,y,b,$,Ce,Qe,_t,Z,de,he]),Xe=(0,s.useMemo)(()=>{let z=["applePay","googlePay","paypal","link","amazonPay","klarna"],rt=new Set(["applePay","googlePay"]),D=new Set(a.map(u.stripeExpressMethodToOptionKey)),j={};for(let qe of z)D.has(qe)?j[qe]=rt.has(qe)?"always":"auto":j[qe]="never";return j},[a]),H=(0,s.useMemo)(()=>a.map(u.stripeExpressMethodToOptionKey),[a]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Qs,{state:q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:N,children:(0,d.jsxs)("div",{ref:Se,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Te&&(0,d.jsxs)("button",{ref:Re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Je,style:Xs,children:["Try ",yi(we)," again"]}),ue&&(0,d.jsx)(ro,{identity:ue.identity,methodLabel:ue.methodLabel,onComplete:st,onCancel:()=>st(null)},ue.id),(0,d.jsx)("div",{style:{display:ue?"none":void 0},children:(0,d.jsx)(Ht.ExpressCheckoutElement,{onReady:z=>{ie(Zs(z,H))},onLoadError:z=>{ie("load_error"),gi(sn(de),"stripe","wallet")},onClick:async z=>{_e.current=z.expressPaymentType,_.current=$s(z.expressPaymentType);let rt=!0,D=window.setTimeout(()=>{rt=!1,z.reject()},Nc),j=b?await b(_.current):{proceed:!0};if(window.clearTimeout(D),!rt)return;if(!j.proceed){J.current.delete(he),z.reject();return}let qe=O(z.expressPaymentType);J.current.set(he,{generation:qe,method:z.expressPaymentType,accountPatch:j.accountPatch,sessionId:j.sessionId,nonce:j.nonce}),fe(!1),f?.(_.current),z.resolve()},onConfirm:be,onCancel:()=>{let z=J.current.get(he);J.current.delete(he),sn(de)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Ke(z?.generation),fe(!1),Le.current=!0,X()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Xe,emailRequired:Oe,billingAddressRequired:Oe,layout:{maxColumns:1,overflow:"never"}}},he)})]})}),se&&(0,d.jsx)(Xn,{status:"processing"})]})}function el(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function nd({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:c,borderColor:f,textColor:y,borderRadius:p,fontFamily:b}){let h=(0,u.resolveStripeMethodBrandVariant)(e,t),w=_s[e],[B,N]=(0,s.useState)(!1),de=!!w&&!B,K=h?.backgroundColor??c??"#ffffff",I=h?.borderColor??f??"#d1d5db",re=h?.textColor??y??"#262833";return(0,d.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&l()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Sa,padding:"0 1rem",backgroundColor:K,color:re,border:`1px solid ${I}`,borderRadius:p??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,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?(0,d.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,u.getStripeMethodDisplayName)(e)}\u2026`}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,u.hasVendoredStripeMethodLogo)(e)?8:0},children:[de?(0,d.jsx)("img",{src:w,alt:"","aria-hidden":"true",onError:()=>N(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!de&&h?.logoSvg?(0,d.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:h.logoSvg}}):null,(0,d.jsx)("span",{children:(0,u.getStripeMethodDisplayName)(e)})]}),a&&(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:re,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:(0,d.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function fi({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:c,onErrorChange:f,onDecline:y,onCancel:p,runBeforeButtonClick:b,onButtonClick:h,isProcessing:w,submitButtonColor:B,submitButtonBorderRadius:N,submitButtonStyle:de,errorText:K}){let I=wr(),{emitInstrument:re}=(0,s.useContext)(Yn),q=(0,Ht.useStripe)(),ie=(0,Ht.useElements)(),[se,ee]=(0,s.useState)(!1),Oe=(0,s.useRef)(!1),[ue,Ct]=(0,s.useState)(!1),[st,Se]=(0,s.useState)("loading"),[Re,he]=(0,s.useState)(""),te=!(0,u.isValidEmail)(r?.trim()),Te=!te||(0,u.isValidEmail)(Re.trim()),fe=(0,s.useCallback)(async()=>{if(!q||!ie||w||Oe.current||!ue)return;Oe.current=!0,ee(!0);let we=b?await b("card"):{proceed:!0};if(!we.proceed){Oe.current=!1,ee(!1);return}h?.("card");let xe=we.sessionId??t,Le=we.nonce??n,_e=Nr(o?.trim()),_=Dn({email:we.accountPatch?.email?.trim()||r?.trim()||Re.trim(),firstName:we.accountPatch?.firstName?.trim()||_e.firstName,lastName:we.accountPatch?.lastName?.trim()||_e.lastName}),oe=_.email,me=Dn({...we.accountPatch,..._});try{if(f?.(null),!(0,u.isValidEmail)(oe))throw new Error("A valid email address is required for payment.");await a?.(_);let J=await ie.submit();if(J.error){f?.(J.error.message??"Payment failed.");return}let O=[_.firstName,_.lastName].filter(Boolean).join(" "),Ce=await q.createPaymentMethod({elements:ie,params:{billing_details:{email:oe,...O?{name:O}:{}}}});if(Ce.error||!Ce.paymentMethod){f?.(Ce.error?.message??"Failed to create payment method.");return}let Ke=Ce.paymentMethod;if(!xe||!oe)throw new Error("Missing sessionId or email for payment.");let _t=Ke.type||e,Qe=await wa(l,re,xe,Le??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_t,paymentMethodId:null,intentKind:"payment"});if(Qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Z=Qe.clientSecret;if(typeof window<"u")try{localStorage.setItem(yr,JSON.stringify({clientSecret:Z,sessionId:xe,nonce:Le,accountPatch:me,paymentMethodId:Ke.id,paymentMethodType:Ke.type??e,gateway:"stripe"}))}catch{}let{error:X,paymentIntent:$}=await q.confirmPayment({clientSecret:Z,confirmParams:{return_url:window.location.href,payment_method:Ke.id},redirect:"if_required"});if(X){if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let be=X.message??"Payment failed.";f?.(be),y?.(cn("card",be,{code:X.code})),await ka({billingApiUrl:l,sessionId:xe,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:X.code??"provider_declined"}});return}let ze=$?.status;if(!_o(ze)){if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let be=ze==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(be),y?.(cn("card",be,{code:ze??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let Je=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;c({id:Je??Ke.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:Ke.type??e},{accountPatch:me,paymentMethodCategory:"apm",sessionId:xe,nonce:Le})}catch(J){f?.(J instanceof Error?J.message:"Payment failed. Please try again.")}finally{Oe.current=!1,ee(!1)}},[q,ie,w,ue,b,h,t,n,r,o,Re,a,l,re,e,c,f,y]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[te&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:te&&(0,d.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,d.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Re,onChange:we=>he(we.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(Ht.PaymentElement,{onReady:()=>Se("ready"),onLoadError:()=>{Se("load_error"),gi(sn(I),"stripe","apm")},onChange:we=>{Ct(!!we.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,u.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,d.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{fe()},disabled:!ue||!Te||se||w||st!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:B,color:"white",border:"none",borderRadius:N,fontSize:"1rem",fontWeight:600,cursor:!ue||!Te||se||w||st!=="ready"?"not-allowed":"pointer",opacity:!ue||!Te||se||w||st!=="ready"?.5:1,transition:"opacity 120ms ease-out",...de??{}},children:se?"Processing\u2026":`Pay with ${(0,u.getStripeMethodDisplayName)(e)}`}),K&&(0,d.jsx)(io,{margin:"0.75rem 0 0",children:K})]})}function Ws({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:c,paymentElementBaseOptions:f,onTokenizedBody:y,onErrorChange:p,onButtonClick:b,onDecline:h,runBeforeButtonClick:w,onLoadStateChange:B,isProcessing:N=!1,submitButtonColor:de="#4A49FF",submitButtonBorderRadius:K=8,submitButtonStyle:I,buttonAppearance:re,themeId:q,onExpandApm:ie,expandedApmMethod:se}){let{emitInstrument:ee}=(0,s.useContext)(Yn),[Oe,ue]=(0,s.useState)(null),[Ct,st]=(0,s.useState)(null),Se=(0,s.useRef)(!1),{request:Re,collect:he,finish:te}=no();(0,s.useEffect)(()=>{l.length>0&&c?B?.("ready"):c||B?.("loading")},[l.length,c,B]);let Te=(0,s.useCallback)(async _=>{if(!c||Se.current||N)return;Se.current=!0,st(_);let oe=w?await w("card"):{proceed:!0};if(!oe.proceed){Se.current=!1,st(null);return}b?.("card");let me=oe.sessionId??e,J=oe.nonce??t,O=Nr([oe.accountPatch?.firstName,oe.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ce=Dn({email:oe.accountPatch?.email?.trim()||n?.trim(),firstName:oe.accountPatch?.firstName?.trim()||O.firstName,lastName:oe.accountPatch?.lastName?.trim()||O.lastName});if(!(0,u.isValidEmail)(Ce.email)){st(null);let Qe=await he((0,u.getStripeMethodDisplayName)(_),Ce);if(!Qe){Se.current=!1;return}Ce=Qe,st(_)}let Ke=Ce.email,_t=Dn({...oe.accountPatch,...Ce});try{if(p?.(null),!me||!(0,u.isValidEmail)(Ke))throw new Error("Missing sessionId or email for payment.");await o?.(Ce);let Qe=await wa(a,ee,me,J??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,paymentMethodId:null,intentKind:"payment"});if(Qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Z=Qe.clientSecret;if(typeof window<"u")try{localStorage.setItem(yr,JSON.stringify({clientSecret:Z,sessionId:me,nonce:J,accountPatch:_t,paymentMethodType:_,gateway:"stripe"}))}catch{}let{error:X,paymentIntent:$}=await c.confirmPayment({clientSecret:Z,confirmParams:{return_url:window.location.href,payment_method_data:{type:_,billing_details:{name:[Ce.firstName,Ce.lastName].filter(Boolean).join(" "),...Ke?{email:Ke}:{}}}},redirect:"if_required"});if(X){if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let be=X.message??"Payment failed.";p?.(be),h?.(cn("card",be,{code:X.code})),await ka({billingApiUrl:a,sessionId:me,nonce:J,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,providerDeclineReason:X.code??"provider_declined"}});return}let ze=$?.status;if(!_o(ze)){if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let be=ze==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(be),h?.(cn("card",be,{code:ze??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let Je=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;y({id:Je??$?.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:_},{accountPatch:_t,paymentMethodCategory:"apm",sessionId:me,nonce:J})}catch(Qe){p?.(Qe instanceof Error?Qe.message:"Payment failed. Please try again.")}finally{Se.current=!1,st(null)}},[c,N,w,b,e,t,n,he,a,ee,r,o,y,p,h]),[fe,we]=(0,s.useState)(null),xe=ie?se??null:fe,Le=(0,s.useCallback)(_=>{Se.current||N||xe&&xe!==_||((0,u.needsStripeMethodExplicitConfirm)(_)?ie?ie(_):we(_):Te(_))},[xe,N,Te,ie]),_e=(0,s.useMemo)(()=>fe?el(f,fe):null,[fe,f]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Re?(0,d.jsx)(ro,{identity:Re.identity,methodLabel:Re.methodLabel,onComplete:te,onCancel:()=>te(null)},Re.id):l.map(_=>{let oe=se===_,me=Ct===_,J=Ct!==null&&Ct!==_||se!=null&&se!==_;return(0,d.jsxs)(s.default.Fragment,{children:[(0,d.jsx)(nd,{method:_,themeId:q,submitting:me,disabled:J,highlighted:oe,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(_),onClick:()=>Le(_),backgroundColor:re?.backgroundColor,borderColor:re?.borderColor,textColor:re?.textColor,borderRadius:re?.borderRadius,fontFamily:re?.fontFamily}),!ie&&fe===_&&_e&&c&&(0,d.jsx)(Ht.Elements,{stripe:c,options:_e,children:(0,d.jsx)(fi,{method:_,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:y,onErrorChange:p,onDecline:h,onCancel:()=>we(null),runBeforeButtonClick:w,onButtonClick:b,isProcessing:N,submitButtonColor:de,submitButtonBorderRadius:K,submitButtonStyle:I})},_)]},_)})})}function rd({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:l,onDecline:c,onTokenizedBody:f,firstName:y,lastName:p,chv:b,className:h,isProcessing:w,error:B,onErrorChange:N,showPayPal:de=!0,showStripe:K=!0,enabledPaymentMethods:I,enabledPaymentMethodCountries:re,showApplePay:q=!0,showGooglePay:ie=!0,layout:se="default",theme:ee,buttonsTheme:Oe,buttonsStyles:ue,appearance:Ct,cardButtonContent:st,cardBackButtonContent:Se,cardTitleContent:Re,showSecurityFooter:he,onButtonClick:te,onBeforeButtonClick:Te,onBuyerIdentityReady:fe,enableAVS:we,cardFieldOrder:xe,cardPreFormSlot:Le,avsLayout:_e="row",country:_,zip:oe,addressLine1:me,addressLine2:J,city:O,state:Ce,onCountryChange:Ke,onZipChange:_t,avsCheck:Qe,checkoutType:Z,checkoutLayout:X,totalAmount:$=0,currency:ze="usd",initialCardOpen:Je=!1,directPaypal:be,isSubscription:Xe=!1,session:H,dataAttachmentPending:z=!1,dataAttachmentRequiresIdentity:rt=!1,debug:D=!1}){let j=wr(),qe=aa(),ve=(0,s.useContext)(rr),{emitInstrument:Bt}=(0,s.useContext)(Yn),St=H??ve.session,P=St?.gateways?.paypal?.providerObjectType??be?.providerObjectType,F=z||ve.claimPending===!0,qt=rt||ve.claimRequiresIdentity===!0,Ae=F&&!qt,Et=ys(),[tn,et]=(0,s.useState)(!1),[nn,lt]=(0,s.useState)(null),[Wt,dn]=(0,s.useState)(_??"US"),[rn,ke]=(0,s.useState)(oe??""),[hn,bn]=(0,s.useState)(me??""),[$e,ct]=(0,s.useState)(J??""),[un,Gt]=(0,s.useState)(O??""),[pn,$t]=(0,s.useState)(Ce??""),[wt,Qn]=(0,s.useState)(""),[kt,vn]=(0,s.useState)({}),ht=(0,s.useRef)(oe??""),Yt=(0,s.useRef)(_??"US"),dt=(0,s.useRef)(me??""),Tt=(0,s.useRef)(J??""),Pn=(0,s.useRef)(O??""),Jt=(0,s.useRef)(Ce??""),Cn=(0,s.useRef)(""),ut=(0,s.useRef)({});(0,s.useEffect)(()=>{let i=(S,V,Fe,Y,Pe)=>{if(ut.current[S])return;let Qt=V?.trim();!Qt||Qt===Fe.current||(Fe.current=Qt,Y(Qt),Pe?.(Qt))};i("country",_,Yt,dn,Ke),i("zip",oe,ht,ke,_t),i("addressLine1",me,dt,bn),i("addressLine2",J,Tt,ct),i("city",O,Pn,Gt),i("state",Ce,Jt,$t)},[_,oe,me,J,O,Ce,Ke,_t]);let E=(0,s.useMemo)(()=>(0,u.resolveAVSConfig)(we),[we]),xt=E!==null,ot=(0,s.useMemo)(()=>(0,u.isAuthorizationOnlySession)(H),[H]),Xt=!!H?.vault?.html,on=!!H?.gateways?.pcivault,Tn=!!(H?.gateways?.stripe?.enabledPaymentMethods??I)?.includes("card"),Zt=Xt||Tn||on,tt=!!(K&&Zt&&j&&e),[Tr,xr]=(0,s.useState)(()=>se!=="buttons"||Je?e??null:null),[Un,Ar]=(0,s.useState)(0),qn=se!=="buttons"||Je||!!e&&Tr===e,pt=(0,s.useMemo)(()=>!j||!tt||!e||!qn?null:j.cardCapture({sessionId:e,captureMethod:H?.captureMethod}),[j,tt,e,qn,H?.captureMethod]),L=(0,s.useMemo)(()=>{let i=Wt,S=E?(0,u.isAVSFieldVisible)(E.postal_code,i):!1;return Qc(i,rn,S)},[E,Wt,rn]),{avsInvalid:mt,invalidAvsFields:pe}=(0,s.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!tt||!E)return{avsInvalid:!1,invalidAvsFields:i};let S=Wt,V=(Pe,Qt)=>(0,u.isAVSFieldVisible)(Pe,S)&&!Qt.trim(),Fe={line1:V(E.address_line_1,hn),city:V(E.city,un),state:V(E.state,pn),zip:L.empty||L.malformed};return{avsInvalid:Fe.line1||Fe.city||Fe.state||Fe.zip,invalidAvsFields:Fe}},[tt,E,Wt,hn,un,pn,L]),[xn,Sn]=(0,s.useState)(!1),[wn,hr]=(0,s.useState)(!1),[at,Mr]=(0,s.useState)(!1),[er,Br]=(0,s.useState)({line1:!1,city:!1,state:!1}),$n=(0,s.useRef)(!1),jn=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),jt=(0,s.useRef)(!1),bt=(0,s.useCallback)(i=>{jn.current[i]=!0,jt.current=!0},[]),Nn=(0,s.useCallback)(i=>!$n.current&&jn.current[i],[]),mn=(0,s.useCallback)(i=>{Nn(i)&&Br(S=>S[i]?S:{...S,[i]:!0})},[Nn]),[On,fn]=(0,s.useState)(()=>pi(H?.vault)),[Ue,ln]=(0,s.useState)(Je&&Zt?"card":"buttons"),[Ft,Vn]=(0,s.useState)(null),sr=Ue==="expanding"||Ue==="card",br=H?.gateways?.stripe?"stripe":void 0,Kn=(0,s.useCallback)(()=>{Bt?.({class:"card_surface",provider:br})},[br,Bt]),An=(0,s.useRef)(null),Mn=(0,s.useCallback)(i=>{An.current&&clearTimeout(An.current),An.current=setTimeout(()=>{An.current=null,i()},qo)},[]);(0,s.useEffect)(()=>()=>{An.current&&clearTimeout(An.current)},[]);let lr=(0,s.useCallback)(()=>{Kn(),xr(e??null),Ar(i=>i+1),ln("expanding"),Mn(()=>ln("card"))},[Mn,Kn,e]),Vr=(0,s.useCallback)(()=>{ln("collapsing"),Mn(()=>ln("buttons"))},[Mn]),Hn=(0,s.useCallback)(i=>{Vn(i),ln("apm-expanding"),Mn(()=>ln("apm-form"))},[Mn]),cr=(0,s.useCallback)(()=>{ln("apm-collapsing"),Mn(()=>{ln("buttons"),Vn(null)})},[Mn]);(0,s.useEffect)(()=>{se==="buttons"&&Je&&Zt&&(xr(e??null),ln("card"))},[se,Je,Zt,e]);let[gn,yt]=(0,s.useState)(null),kn=(0,s.useRef)(!1),A=(0,s.useRef)(null),x=(0,s.useRef)("idle"),[U,ne]=(0,s.useState)(null),He=(0,s.useRef)(U);(0,s.useEffect)(()=>{He.current=U},[U]);let Ie=n||Et,ye=(0,s.useRef)(null),le=(0,s.useMemo)(()=>{if(fe||ve.claimBuyerIdentity||H?.buyerIdentified!==!1||!e||!t)return;let i=`${Ie}|${e}|${t}`;ye.current?.key!==i&&(ye.current={key:i,claim:eo(new Ir.PaymentAPI(Ie,{telemetry:!1}),e,t,{...o?{userId:o}:{},...y?{firstName:y}:{},...p?{lastName:p}:{}})});let S=ye.current.claim;return async V=>{await S(V)}},[fe,ve.claimBuyerIdentity,H?.buyerIdentified,e,t,Ie,o,y,p]),W=fe??ve.claimBuyerIdentity??le,M=B??nn,ge=(0,s.useMemo)(()=>(0,u.resolveTheme)(ee),[ee]),k=(0,s.useMemo)(()=>{let i=ge?.buttonsLayout??(0,u.resolveButtonsLayoutTheme)(Oe);return ue?{...i,...ue,cardButton:{...i.cardButton,...ue.cardButton},cardFormContainer:{...i.cardFormContainer,...ue.cardFormContainer},backButton:{...i.backButton,...ue.backButton},backButtonIcon:{...i.backButtonIcon,...ue.backButtonIcon},submitButton:{...i.submitButton,...ue.submitButton},title:{...i.title,...ue.title}}:i},[ge,Oe,ue]),G=Ct??ge?.appearance,Ze=(0,s.useMemo)(()=>Ca({appearance:G,buttonsStyles:k,layout:se}),[G,k,se]),Vt=ve.inlineSessionPatchProcessing??!1,v=(w??tn)||Vt,m=Ie.replace(/\/+$/,""),g=(0,s.useMemo)(()=>Ya({userId:o,email:r,firstName:y,lastName:p,country:_,zip:oe},kt),[o,r,y,p,_,oe,kt]),ae=[g.firstName,g.lastName].filter(i=>!!i?.trim()).join(" "),Me=!(0,u.isValidEmail)(g.email?.trim()),ce=(0,s.useRef)(null);tt&&ce.current===null&&(ce.current=Me);let At=tt&&(ce.current??Me),In=(0,s.useMemo)(()=>ed(wt,At),[wt,At]),vt=In.empty||In.malformed,Dt=(0,s.useMemo)(()=>j?j.getRawProvider():null,[j]),an=(0,s.useMemo)(()=>qe?qe.getRawProvider():null,[qe]),Ee=$||100,je=ze.toLowerCase(),Be=(0,s.useMemo)(()=>G?(0,Ir.toStripeAppearance)(G):null,[G]),Ne=Be,it=(0,s.useMemo)(()=>{let i=Be??{},S=i.rules??{};return{...i,rules:{...S,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...S[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...S[".AccordionItemContents"]??{}}}}},[Be]),Rn=(0,s.useMemo)(()=>({...ds($,H?.captureMethod),currency:je,...Ne?{appearance:Ne}:null}),[$,je,H?.captureMethod,Ne]),Ge=(0,s.useMemo)(()=>({mode:"payment",amount:Ee,currency:je,captureMethod:"manual",setupFutureUsage:"off_session",...Ne?{appearance:Ne}:null}),[Ee,je,Ne]),Q=(0,s.useCallback)(i=>{lt(i),N?.(i)},[N]),dr=(0,s.useRef)(""),[Ri,yl]=(0,s.useState)(!1),Ma=(0,s.useCallback)(()=>{yl(!0)},[]);(0,s.useEffect)(()=>{if(!tt||!At||!W||!Ri||vt||dr.current)return;let i=Dn({email:(0,u.isValidEmail)(g.email?.trim())?g.email?.trim():Cn.current.trim(),firstName:g.firstName?.trim(),lastName:g.lastName?.trim()});dr.current=JSON.stringify(i),vn(S=>({...S,...i})),Promise.resolve(W(i)).catch(S=>{dr.current="",Q(S instanceof Error?S.message:"Failed to attach buyer details.")})},[tt,At,W,Ri,vt,g.email,g.firstName,g.lastName,Q]),(0,s.useEffect)(()=>{!tt||!pt||pt.setCardFieldOrder?.(xe??null,E==null&&!At)},[tt,pt,xe,E,At]),(0,s.useEffect)(()=>{(Ue==="expanding"||Ue==="collapsing"||Ue==="apm-expanding"||Ue==="apm-collapsing")&&Q(null)},[Ue,Q]);let tr=(0,s.useCallback)((i,S,V)=>{c?.(cn(i,S,V))},[c]),Kr=(0,s.useCallback)((i,S,V)=>{let Fe=V?.popupBlocked??Sr(S),Y=Xc(i,Fe),Pe=zr(V?.code)??Cr(S)??"external_payment_method_failed",Qt=new u.FloPayError(Y,"api_error",{code:"external_payment_method_failed",param:i});yt(null),se==="buttons"&&(ln("buttons"),Vn(null)),Q(Y),l?.(Qt),console.error("[FloPay] External payment method failed:",{method:i,code:Pe,popupBlocked:Fe})},[se,l,Q]);(0,s.useEffect)(()=>{if(!tt||!e){fn(null);return}let i=pi(H?.vault);if(i){fn(i);return}if(!qn){fn(null);return}fn(null);let S=!0;return new Ir.PaymentAPI(m).getVaultCapture(e,t).then(V=>{if(!S)return;let Fe=pi(V);Fe?fn(Fe):Q("Failed to load the secure card form.")}).catch(V=>{S&&Q(V instanceof Error?V.message:"Failed to load the secure card form.")}),()=>{S=!1}},[tt,qn,Un,e,H?.vault,m,t,Q]);let ur=(0,s.useRef)({onComplete:a,onError:l,updateError:Q,emitDecline:tr,resolvedAccount:g,avsConfig:E,avsCheckProp:Qe,sessionId:e,nonce:t,baseUrl:m,captureMethod:H?.captureMethod,paymentId:H?.paymentId,authorizationExpiresAt:H?.authorizationExpiresAt});ur.current={onComplete:a,onError:l,updateError:Q,emitDecline:tr,resolvedAccount:g,avsConfig:E,avsCheckProp:Qe,sessionId:e,nonce:t,baseUrl:m,captureMethod:H?.captureMethod,paymentId:H?.paymentId,authorizationExpiresAt:H?.authorizationExpiresAt};let Ba=(0,s.useRef)(!1),_i=(0,s.useCallback)(()=>{let i=ur.current,S=i.resolvedAccount.email?.trim(),V=(0,u.isValidEmail)(S)?S:Cn.current.trim();if(!(0,u.isValidEmail)(V))return null;let Fe=i.resolvedAccount.firstName?.trim(),Y=i.resolvedAccount.lastName?.trim(),Pe=Yt.current||i.resolvedAccount.country||"US",Qt=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.state,Pe):!1,Ye=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.address_line_1,Pe):!1,Nt=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.postal_code,Pe):!1,Pt=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.city,Pe):!1,It=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.address_line_2,Pe):!1,Rt=Ye&&!Qt&&Nt?(0,u.getStateFromPostalCode)(Pe,(ht.current??"").trim()):null,vr=Qt?Jt.current:Rt;return{accountData:{userId:i.resolvedAccount.userId??"",email:V,...Fe?{firstName:Fe}:{},...Y?{lastName:Y}:{},...Nt&&ht.current?{zip:ht.current}:{},...Pt&&Pn.current?{city:Pn.current}:{},...vr?{state:vr}:{},...Ye&&dt.current?{addressLine1:dt.current}:{},...It&&Tt.current?{addressLine2:Tt.current}:{},country:Pe},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,u.isAVSFieldVisible)(i.avsConfig.country,Pe),postal_code:Nt,address_line_1:Ye,address_line_2:It,city:Pt,state:Qt}}:{}}},[]),Ei=(0,s.useRef)(F);Ei.current=F,(0,s.useEffect)(()=>{F||M!==zs||ur.current.updateError(null)},[F,M]),(0,s.useEffect)(()=>{!tt||!pt||pt.setSubmitGate?.(mt||F||vt)},[tt,pt,mt,F,vt]),(0,s.useEffect)(()=>{if(!tt||!pt)return;Ba.current=!1;let i=null,S=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,x.current="idle",yt(null)},1500)},V=pt.on("submitting",()=>{Sn(!0),A.current&&clearTimeout(A.current),x.current="validation-window",A.current=setTimeout(()=>{A.current=null,x.current==="validation-window"&&(x.current="processing")},qc),yt("processing");let Ye=ur.current;if(!Ye.sessionId||!Ye.nonce)return;let Nt=_i();if(!Nt){Ye.updateError("Enter a valid email address."),x.current="idle",yt(null);return}new Ir.PaymentAPI(Ye.baseUrl).patchAccountSnapshot(Ye.sessionId,Ye.nonce,Nt,{telemetryMode:"best_effort"}).catch(Pt=>{if(!$c(Pt))return;let It=Pt instanceof Error?Pt.message:"Please check your billing address and try again.";Ye.updateError(It),x.current="idle",yt(null),Ye.onError?.(Pt instanceof u.FloPayError?Pt:new u.FloPayError(It,"api_error"))})}),Fe=pt.on("complete",async Ye=>{if(co(Ye.sessionId??ur.current.sessionId),x.current="terminal",yt("success"),await new Promise(It=>setTimeout(It,1200)),Ba.current)return;Ba.current=!0;let Nt=ur.current,Pt=(0,u.isAuthorizationOnlySession)(Nt)||Ye.outcome==="authorized";ur.current.onComplete?.(Pt?{status:"authorized",paymentIntentId:Ye.intentId,paymentId:Ye.paymentId??Nt.paymentId,sessionId:Ye.sessionId??Nt.sessionId,authorizationExpiresAt:Ye.authorizationExpiresAt??Nt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ye.intentId,checkoutMethod:"card"})}),Y=pt.on("decline",Ye=>{let Nt=ur.current,Pt=Ye.message??"Your payment was declined. Please try another card or contact your bank.";x.current="terminal",Nt.updateError(Pt),yt("error");let It=Ye.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(Ye.declineReason)??"authorization_declined";Nt.emitDecline("card",Pt,{code:It,declineCode:It}),S()}),Pe=pt.on("error",Ye=>{let Nt=ur.current,Pt=Ye.message??"There was a problem processing your payment. Please try again.";x.current="terminal",Nt.updateError(Pt),yt("error"),Nt.onError?.(new u.FloPayError(Pt,"api_error",{code:Ye.failureOutcome??"capture_failed"})),S()}),Qt=pt.on("blocked",()=>{if(!Ei.current){Sn(!0);return}Ma(),ur.current.updateError(zs)});return()=>{i&&(clearTimeout(i),i=null),A.current&&(clearTimeout(A.current),A.current=null),x.current="idle",yt(null),V(),Fe(),Y(),Pe(),Qt()}},[tt,pt,Ma,_i]);let pr=!!be?.clientId,fo=Array.isArray(I),Ko=fo&&I.length>0,fl=fo&&I.includes("paypal"),{expressMethods:Ho,paymentElementMethods:go}=(0,s.useMemo)(()=>(0,u.partitionStripeMethods)(I,{excludePaypal:pr}),[I,pr]),Ti=pr||!!qe,gl=(0,s.useMemo)(()=>Ti?Ho.filter(i=>i!=="paypal"):Ho,[Ho,Ti]),hl=(0,s.useMemo)(()=>{let i=[];return q&&i.push("apple_pay"),ie&&i.push("google_pay"),i},[q,ie]),Hr=fo?gl:hl,bl=K&&Hr.length>0,Fa=xt?Wt:_,Wo=(0,s.useMemo)(()=>{let i=Fa?.trim().toUpperCase();return i?re?go.filter(S=>{let V=re[S];return!V||V.length===0||V.includes(i)}):(0,u.filterStripeMethodsByCountry)(go,Fa):go},[go,Fa,re]),Da=(0,s.useMemo)(()=>({mode:"payment",amount:Ee,currency:je,paymentMethodCreation:"manual",appearance:it}),[Ee,je,it]),[xi,Ai]=(0,s.useState)("loading"),[Mi,Bi]=(0,s.useState)("loading"),[Fi,Di]=(0,s.useState)("loading"),[vl,La]=(0,s.useState)(!1),[Li,Na]=(0,s.useState)("loading"),[Oa,Pl]=(0,s.useState)();(0,s.useEffect)(()=>{Pl(ia())},[]);let Go=Oa?.inAppBrowser,Yo=Oa?sa(Oa,be?.approvalPresentation,P??(Xe?"subscription":"order")):"popup",Ni=de&&(pr||(fo?fl:Go===!1)),Oi=K&&bl,ho=!Ae&&Ni&&pr,zi=Li==="retrying"||Li==="exhausted",bo=!Ae&&Ni&&!!an&&(!pr||zi),Wr=!Ae&&Oi&&!!Dt,vo=!Ae&&K&&Ko&&Wo.length>0&&!!Dt,Cl=ho&&!zi?vl:bo&&Vs(xi),Sl=Wr&&Vs(Mi),wl=vo&&Fi!=="load_error",Ui=i=>i==="loading"||i==="ready",qi=ho||bo&&Ui(xi)||Wr&&Ui(Mi)||vo&&Fi!=="load_error",Jo=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!Jo.current){if(!K&&!de){Jo.current=!0;let i=new u.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(i),Q(i.message)}else if(!K&&de&&!pr&&!an){Jo.current=!0;let i=new u.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(i),Q(i.message)}else if(Go!==void 0&&!Ae&&!Zt&&!qi){Jo.current=!0;let i=new u.FloPayError("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?.(i),Q(i.message)}}},[K,de,pr,an,Go,Ae,Zt,qi,l,Q]);let $i=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if($i.current||!Ko)return;let i=[];q!==!0&&i.push("showApplePay"),ie!==!0&&i.push("showGooglePay"),i.length!==0&&($i.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Ko,q,ie]);let ji=(0,s.useCallback)((i,S)=>ve.applyInlineSessionPatch?ve.applyInlineSessionPatch(i).then(V=>({error:null,sessionId:V.sessionId||e,nonce:V.session?.clientSecret||t})).catch(V=>{let Fe=js(S,V);return Q(Fe.message),l?.(Fe),{error:Fe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ve.applyInlineSessionPatch,t,l,e,Q]),nr=(0,s.useCallback)(async i=>{if(!Te)return{proceed:!0};try{let S=await Te({method:i,sessionId:e||void 0,createSession:ve.inlineSessionDraft});if(S===!1)return{proceed:!1};if(S&&typeof S=="object"){S.account&&vn(Fe=>({...Fe??{},...S.account}));let V=await ji(S,i);return V.error?{proceed:!1,accountPatch:S.account}:{proceed:!0,accountPatch:S.account,sessionId:V.sessionId,nonce:V.nonce}}return{proceed:!0}}catch(S){let V=js(i,S);return Q(V.message),l?.(V),{proceed:!1}}},[ji,ve.inlineSessionDraft,Te,l,e,Q]),Vi=(0,s.useCallback)(async(i,S)=>{if(kn.current)return;kn.current=!0,et(!0),yt("processing"),Q(null);let V=S?.sessionId??e,Fe=S?.nonce??t,Y=Ya(g,S?.accountPatch),Pe=S?.completionPaymentMethodId??Eo(i),Qt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,Ye=Wc(i),Nt=()=>{Bt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Ye})};try{let It=await new Ir.PaymentAPI(m).processPayment(Y.userId??"",{sessionId:V,nonce:Fe,paymentMethodCategory:S?.paymentMethodCategory??Yc(i),tokenizedData:Qt,accountData:{...S?.accountPatch,userId:Y.userId??"",email:Y.email??"",firstName:Y.firstName||void 0,lastName:Y.lastName||void 0,...E?(()=>{let ft=Yt.current,Gn=(0,u.isAVSFieldVisible)(E.state,ft),_n=(0,u.isAVSFieldVisible)(E.address_line_1,ft),Ot=(0,u.isAVSFieldVisible)(E.postal_code,ft),Lr=_n&&!Gn&&Ot?(0,u.getStateFromPostalCode)(ft,(ht.current??"").trim()):null,Io=Gn?Jt.current:Lr;return{country:ft,...Ot&&ht.current?{zip:ht.current}:{},...(0,u.isAVSFieldVisible)(E.city,ft)&&Pn.current?{city:Pn.current}:{},...Io?{state:Io}:{},..._n&&dt.current?{addressLine1:dt.current}:{},...(0,u.isAVSFieldVisible)(E.address_line_2,ft)&&Tt.current?{addressLine2:Tt.current}:{}}})():{}},chv:b,avsCheck:Qe??!1,checkoutType:Z,checkoutLayout:X,avsConfig:E?{country:(0,u.isAVSFieldVisible)(E.country,Yt.current),postal_code:(0,u.isAVSFieldVisible)(E.postal_code,Yt.current),address_line_1:(0,u.isAVSFieldVisible)(E.address_line_1,Yt.current),address_line_2:(0,u.isAVSFieldVisible)(E.address_line_2,Yt.current),city:(0,u.isAVSFieldVisible)(E.city,Yt.current),state:(0,u.isAVSFieldVisible)(E.state,Yt.current)}:void 0});if(It.ok){let ft=It.status===204?null:await It.json().catch(()=>null),Gn=(0,u.isAuthorizationOnlySession)(H)||ft?.status==="authorized";co(V),yt("success"),ne(null),await new Promise(Lr=>setTimeout(Lr,1200));let _n;typeof ft?.paymentId=="string"?_n=ft.paymentId:H?.paymentId&&(_n=H.paymentId);let Ot;typeof ft?.authorizationExpiresAt=="string"?Ot=ft.authorizationExpiresAt:H?.authorizationExpiresAt&&(Ot=H.authorizationExpiresAt),a?.(Gn?{status:"authorized",..._n===void 0?{}:{paymentId:_n},sessionId:typeof ft?.sessionId=="string"?ft.sessionId:V,...Ot===void 0?{}:{authorizationExpiresAt:Ot},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Pe,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Pe,checkoutMethod:i.isPaypal?"paypal":"card"});return}let Rt=await It.json().catch(()=>null);if(Rt?.type==="paypal_redirect_required"){let ft=Rt.threeDSecureToken,Gn=Rt.paymentMethodId||i.id||"";if(!j||!ft){yt("error"),Q("PayPal authorization required but no token provided.");return}try{let _n=qe?.getRawProvider();if(!_n){Q("PayPal is not available.");return}let Ot={return_url:window.location.href};Gn&&(Ot.payment_method=Gn);let{error:Lr}=await _n.confirmPayment({clientSecret:ft,confirmParams:Ot,redirect:"if_required"});if(Lr){yt("error");let Io=Lr.message??"PayPal payment failed.";Q(Io),tr("paypal",Io,{code:Lr.code})}}catch(_n){yt("error"),Q(_n instanceof Error?_n.message:"PayPal authorization failed.")}return}if(Rt?.type==="paypal_direct_required"){let ft=Rt.orderId;if(!ft){yt("error"),Q("PayPal retry required but no order id provided.");return}let Gn=He.current?.attempts??0;if(Gn>=2){yt("error"),Q("PayPal payment could not be completed after multiple attempts."),tr("paypal","paypal_direct_required retry limit exceeded");return}La(!1),Na("loading"),ne({orderId:ft,attempts:Gn+1}),yt(null);return}(0,u.classifyPaymentRejection)(It.status,Rt)||Nt(),yt("error");let vr=Rt?.message??"Payment failed. Please try again.";Q(vr),tr(i.isPaypal?"paypal":"card",vr,{code:Rt?.code??Rt?.gatewayErrorCode,declineCode:Rt?.declineCode??Rt?.gatewayDeclineReason}),await new Promise(ft=>setTimeout(ft,1500))}catch(Pt){Ys(Pt)||Nt(),yt("error"),Q(Pt instanceof Error?Pt.message:"An unexpected error occurred"),await new Promise(It=>setTimeout(It,1500))}finally{et(!1),yt(null),kn.current=!1}},[m,e,t,g,E,Qe,Z,X,b,j,qe,H,a,Q,tr,Bt]),Bn=(0,s.useCallback)((i,S)=>{f?f(i):Vi(i,S)},[f,Vi]),Po=`${Gs}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(Po);if(!i)return;let S;try{S=JSON.parse(i)}catch{localStorage.removeItem(Po);return}if(!S||typeof S.createdAt!="number"||Date.now()-S.createdAt<0||Date.now()-S.createdAt>Lc||typeof S.paymentMethodId!="string"||typeof S.providerIntentId!="string"||typeof S.paymentMethodType!="string"||S.sessionId!==e||!t||S.nonce!==t||!Hr.includes(S.paymentMethodType)){localStorage.removeItem(Po);return}localStorage.removeItem(Po),Bn({id:S.paymentMethodId,type:"card",threeDSecureActionResultTokenId:S.providerIntentId,gateway:"stripe",paymentMethodType:S.paymentMethodType},{...S.accountPatch?{accountPatch:S.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Bn,t,e,Po,Hr]);let Ki=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||Ki.current)return;let i=new URLSearchParams(window.location.search),S=i.get("payment_intent"),V=i.get("payment_intent_client_secret"),Fe=i.get("redirect_status");if(!S||!V)return;let Y=It=>{let Rt=localStorage.getItem(It);if(!Rt)return null;try{return JSON.parse(Rt)}catch{return localStorage.removeItem(It),null}},Pe=Y(yr)??Y(Os),Qt;if(Pe?.clientSecret){if(Pe.clientSecret!==V)return;Qt={...Pe.accountPatch?{accountPatch:Pe.accountPatch}:{},...Pe.sessionId?{sessionId:Pe.sessionId}:{},...Pe.nonce?{nonce:Pe.nonce}:{}}}else if(Pe?.sessionId&&Pe.sessionId!==e)return;Ki.current=!0,localStorage.removeItem(yr),localStorage.removeItem(Os);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 Nt=Pe?.paymentMethodType??Pe?.tokenType??"card",Pt="card";(async()=>{let It=j?.getRawProvider();if(!It){let Ot="Payment is not available \u2014 please refresh and try again.";Q(Ot),tr(Pt,Ot);return}if(Fe==="failed"){let Ot="Payment was declined. Please try again.";Q(Ot),tr(Pt,Ot);return}let{paymentIntent:Rt,error:vr}=await It.retrievePaymentIntent(V);if(vr){let Ot=vr.message??"Failed to retrieve payment status.";Q(Ot),tr(Pt,Ot,{code:vr.code});return}let ft=Rt?.status,Gn=_o(ft);if(!Rt||!Gn){let Ot=ft==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Q(Ot),tr(Pt,Ot,{code:ft??"missing_payment_intent"});return}let _n=typeof Rt.payment_method=="string"?Rt.payment_method:Rt.payment_method?.id;Bn({id:_n??Pe?.paymentMethodId??Pe?.tokenId??Rt.id,type:"card",threeDSecureActionResultTokenId:Rt.id,gateway:Pe?.gateway??"stripe",paymentMethodType:Nt},Qt)})()},[e,Bn,j,Q,tr]);let za=(0,s.useCallback)(i=>{i.preventDefault()},[]);if(!(j!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Co=se==="buttons",Fn=G?.variables,kl=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ua=Fn?.colorBackground,Il=Ua&&!kl.has(Ua)?Ua:void 0,So=k.cardInputBorder??(Co?"#e5e7eb":"#A4A4FF"),Hi=Fn?.colorDanger??"#dc2626",Lt=i=>pe[i]&&(er[i]||xn),Xo=vt&&(at||xn),Wn=i=>i?Hi:So,Zo=(L.malformed||L.empty)&&(wn||xn),Rl=Wn(Zo),qa=k.cardFormContainer?.backgroundColor??Il??(Co?"white":"#EDEDFF"),Gr=k.cardInputBackground??Fn?.colorBackground??"white",$a=Xr(Se),Wi=Xr(Re),Yr=k.nameInput,Gi=k.cardInputFontSize??td(Yr?.fontSize)??Fn?.fontSizeBase??"16px",Yi=typeof Yr?.fontFamily=="string"?Yr.fontFamily:Fn?.fontFamily??"Poppins, sans-serif",Ji=ci(Yr?.fontWeight)??400,_l=k.cardInputColor??(typeof Yr?.color=="string"?Yr.color:void 0)??Fn?.colorText??"#262833",El=k.cardInputPlaceholderColor??"#9ca3af",Kt=Fn?.borderRadius??"8px",Fr=Fn?.borderRadius??k.cardButton?.borderRadius??Kt,Dr=Fn?.colorPrimary??"#4A49FF",Tl=Fn?.colorPrimaryHover??yo(Dr,.12),ja=Fn?.colorText??"#262833",Va={fontSize:Gi,fontFamily:Yi,fontWeight:Ji,color:_l,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},wo={marginTop:"0.375rem",...Va,fontSize:"0.75rem",lineHeight:1.4,color:Hi},xl={"--flopay-input-placeholder-color":El,"--flopay-input-font-size":Gi,"--flopay-input-font-family":Yi,"--flopay-input-font-weight":String(Ji)},ko=k.cardFormContainer??{},Ka=ko.padding??(Co?"0":"1rem"),Ha=ko.borderRadius??Kt,Al=pt&&On?(0,d.jsx)(mo,{capture:pt,html:On.html,messageToken:On.messageToken,expectedOrigin:On.expectedOrigin,theme:Ze,onReady:()=>{if(!At&&!E||typeof document>"u")return;let i=()=>{let V=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(V){$n.current=!0;try{V.focus()}finally{$n.current=!1}}};jt.current||i()},onError:i=>Q(i),onValidation:i=>{let S=x.current;(S==="idle"||S==="validation-window")&&(Q(i),i&&x.current==="validation-window"&&(A.current&&(clearTimeout(A.current),A.current=null),x.current="idle",yt(null)))}}):(0,d.jsx)("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"}),Xi=(0,d.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&Kn()},style:{backgroundColor:qa,borderRadius:Ha,...ko,padding:Ka,...xl,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
|
|
30
|
+
`,Ia=44,$o=180,el=`flopay-card-enter ${$o}ms cubic-bezier(0, 0, 0.2, 1) both`,tl=`flopay-card-exit ${$o}ms cubic-bezier(0.4, 0, 0.2, 1) both`,ld=`flopay-buttons-enter ${$o}ms cubic-bezier(0, 0, 0.2, 1) both`,cd=`flopay-buttons-exit ${$o}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function dd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Ii(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 ud={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function pd(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 Pi={width:"100%",minHeight:Ia,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function md(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function nl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ci(e){return e==="paypal"?"PayPal":(0,p.getStripeMethodDisplayName)(e)}function yd(e,t){let n=`We couldn't open ${Ci(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function fd(e){let t=(0,p.getPostalCodeExample)(e);return`Enter a valid ${(0,p.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function gd(e,t,n){let r=(0,p.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,l=a&&!o,d=a&&!!o&&!(0,p.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:d}}function hd(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,p.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function rl(e,t){return t instanceof p.FloPayError?t:new p.FloPayError(t instanceof Error?t.message:`${md(e)} before-click hook failed.`,"validation_error")}function vi(){return(0,c.jsx)("style",{children:sd})}function bd(e){return typeof e=="number"?`${e}px`:e}function pl(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function ml({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,c.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,c.jsx)("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"}}),(0,c.jsx)("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 ol(e){return e!=="unavailable"&&e!=="load_error"}function Ea(e){return(0,c.jsx)(Pd,{...e})}function al({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:d,onDecline:m,onTechnicalFailure:g,runBeforeButtonClick:y,billingName:b,onBuyerIdentityReady:v,onLoadStateChange:k,placeholderBorderRadius:B}){let L=kr(),{emitInstrument:he}=(0,s.useContext)(Gn),te=(0,jt.useStripe)(),S=(0,jt.useElements)(),[J,K]=(0,s.useState)("loading");(0,s.useEffect)(()=>{k?.(J)},[J,k]);let[le,Ce]=(0,s.useState)(!1),j=!(0,p.isValidEmail)(n?.trim())||!b?.trim(),{request:Le,collect:Ee,finish:tt}=to(),Ct=(0,s.useRef)(!1),Fe=(0,s.useRef)(null),Me=(0,s.useRef)(null),[pe,Te]=(0,s.useState)(0),[me,ye]=(0,s.useState)(!1),be=(0,s.useRef)(!1),de=(0,s.useRef)(new Map),{startAttempt:He,finishAttempt:Ke,invalidateAttempt:w,isAttemptInvalidated:H,isAttemptCurrent:fe}=Mo((X,Y,Z)=>{g?.(X,Y,{...Z,popupBlocked:Z?.popupBlocked??wr(Y)}),ye(!0),Te(Ge=>Ge+1)});(0,s.useEffect)(()=>{me&&Me.current?.focus()},[me,pe]);let ne=(0,s.useCallback)(()=>{Te(X=>X+1)},[]),M=(0,s.useCallback)((X,Y,Z)=>{w(Z),g?.("paypal",X,{code:Y,popupBlocked:wr(X)}),ye(!0),ne()},[w,g,ne]),we=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Fe.current?.querySelector("iframe")??Fe.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{be.current&&(be.current=!1,we())},[we,pe]);let Oe=(0,s.useCallback)(()=>{ye(!1),a?.(null),we()},[we,a]);(0,s.useEffect)(()=>{if(!te||Ct.current)return;let X=new URLSearchParams(window.location.search),Y=X.get("payment_intent"),Z=X.get("payment_intent_client_secret"),Ge=X.get("redirect_status");if(!Y||!Z)return;Ct.current=!0;let nt;try{let ke=localStorage.getItem(qo);if(ke){let Ye=JSON.parse(ke);Ye.clientSecret===Z&&(nt={...Ye.accountPatch?{accountPatch:Ye.accountPatch}:{},...Ye.sessionId?{sessionId:Ye.sessionId}:{},...Ye.nonce?{nonce:Ye.nonce}:{}})}}catch{}try{localStorage.removeItem(qo)}catch{}let Ae=new URL(window.location.href);Ae.searchParams.delete("payment_intent"),Ae.searchParams.delete("payment_intent_client_secret"),Ae.searchParams.delete("redirect_status"),window.history.replaceState({},"",Ae.toString()),(async()=>{try{if(Ce(!0),Ge==="failed"){let z="PayPal payment was declined. Please try again.";a?.(z),m?.(nn("paypal",z));return}let{paymentIntent:ke,error:Ye}=await te.retrievePaymentIntent(Z);if(Ye){a?.(Ye.message??"Failed to retrieve PayPal payment status.");return}if(ke&&(ke.status==="requires_capture"||ke.status==="succeeded")){let z=typeof ke.payment_method=="string"?ke.payment_method:ke.payment_method?.id;o({id:z??ke.id,type:"card",threeDSecureActionResultTokenId:ke.id,isPaypal:!0},nt)}else{let z="PayPal payment was not completed. Please try again.";a?.(z),m?.(nn("paypal",z))}}catch(ke){a?.(ke instanceof Error?ke.message:"Failed to complete PayPal payment.")}finally{Ce(!1)}})()},[te,o,a,m]);let pt=(0,s.useCallback)(async X=>{if(l||le){X.reject();return}let Y=y?await y("paypal"):{proceed:!0};if(!Y.proceed){de.current.delete(pe),X.reject();return}let Z=He("paypal");de.current.set(pe,{generation:Z,accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}),ye(!1),d?.("paypal"),X.resolve()},[l,d,y,He,le,pe]),Xe=(0,s.useCallback)(async X=>{if(!te||!S)return;let Y=de.current.get(pe);if(Y&&!fe(Y.generation)){de.current.delete(pe);return}if(!Y&&H()||Y&&!Ke(Y.generation))return;Y||Ke();let Z=Y??null;if(de.current.delete(pe),!Z&&y){let z=await y("paypal");if(!z.proceed){X.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Z={accountPatch:z.accountPatch,sessionId:z.sessionId,nonce:z.nonce}}let Ge=Z?.sessionId??e,nt=Z?.nonce??t,Ae=await id({event:X,prepared:Z,email:n,billingName:b,methodLabel:"PayPal",collect:Ee});if(!Ae){X.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let ke=Ae.email,Ye={...Z?.accountPatch,...Tn(Ae,!0)};try{if(Ce(!0),a?.(null),!Ge||!(0,p.isValidEmail)(ke))throw new Error("Missing sessionId or email for PayPal payment");await v?.(Ae);let z=te.createPaymentMethod,{error:Zt,paymentMethod:ie}=await z({type:"paypal"});if(Zt){M(Zt,"stripe_paypal_create_payment_method_failed",Y?.generation),X.paymentFailed({reason:"fail"});return}let St=await Ra(r,he,Ge,nt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ie?.id??null,intentKind:"payment"});if(St.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let wt=St.clientSecret,rt={return_url:window.location.href};if(ie?.id&&(rt.payment_method=ie.id),typeof window<"u")try{localStorage.setItem(qo,JSON.stringify({clientSecret:wt,sessionId:Ge,nonce:nt,accountPatch:Ye}))}catch{}let{error:N,paymentIntent:$e}=await te.confirmPayment({clientSecret:wt,confirmParams:rt,redirect:"if_required"});if(N){if(typeof window<"u")try{localStorage.removeItem(qo)}catch{}if(Ao(N)){let A=N.message??"Your payment was declined.";a?.(A),m?.(nn("paypal",A,{code:Sr(N),declineCode:ro(N)})),await _a({billingApiUrl:r,sessionId:Ge,nonce:nt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Sr(N)??"provider_declined"}})}else M(N,"stripe_paypal_confirm_failed",Y?.generation);return}if(typeof window<"u")try{localStorage.removeItem(qo)}catch{}let f=typeof $e?.payment_method=="string"?$e.payment_method:$e?.payment_method?.id;o({id:f??$e?.id,type:"card",threeDSecureActionResultTokenId:$e?.id,isPaypal:!0},{accountPatch:Ye,paymentMethodCategory:"paypal",sessionId:Ge,nonce:nt});return}catch(z){M(z,"stripe_paypal_failed",Y?.generation)}finally{Ce(!1)}},[te,S,e,t,n,b,Ee,v,r,he,o,a,m,y,M,Ke,fe,H,pe]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(ml,{state:J,placeholderTestId:"flopay-paypal-placeholder",borderRadius:B,children:(0,c.jsxs)("div",{ref:Fe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[me&&(0,c.jsx)("button",{ref:Me,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Oe,style:Pi,children:"Try PayPal again"}),Le&&(0,c.jsx)(no,{identity:Le.identity,methodLabel:Le.methodLabel,onComplete:tt,onCancel:()=>tt(null)},Le.id),(0,c.jsx)("div",{style:{display:Le?"none":void 0},children:(0,c.jsx)(jt.ExpressCheckoutElement,{onReady:X=>K(pl(X,["paypal"])),onLoadError:()=>{K("load_error"),ki(Xt(L),"paypal","paypal")},onClick:pt,onConfirm:Xe,onCancel:()=>{let X=de.current.get(pe);de.current.delete(pe),Xt(L)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),w(X?.generation),ye(!1),be.current=!0,ne()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:j,emailRequired:j,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},pe)})]})}),le&&(0,c.jsx)(Jn,{status:"processing"})]})}function il({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:d,onButtonClick:m,onDecline:g,onTechnicalFailure:y,runBeforeButtonClick:b,billingName:v,onBuyerIdentityReady:k,onLoadStateChange:B,placeholderBorderRadius:L}){let he=kr(),{emitInstrument:te}=(0,s.useContext)(Gn),S=(0,jt.useStripe)(),J=(0,jt.useElements)(),[K,le]=(0,s.useState)("loading");(0,s.useEffect)(()=>{B?.(K)},[K,B]);let[Ce,j]=(0,s.useState)(!1),Le=(0,s.useRef)(!(0,p.isValidEmail)(n?.trim())||!v?.trim()).current,{request:Ee,collect:tt,finish:Ct}=to(),Fe=(0,s.useRef)(null),Me=(0,s.useRef)(null),[pe,Te]=(0,s.useState)(0),[me,ye]=(0,s.useState)(!1),[be,de]=(0,s.useState)(()=>ka(e,t)?"blocked":"idle"),[He,Ke]=(0,s.useState)("google_pay"),w=(0,s.useRef)(null),H=(0,s.useRef)(!0),fe=(0,s.useRef)(!1),ne=(0,s.useRef)("google_pay"),M=(0,s.useRef)("google_pay"),we=(0,s.useRef)(null),Oe=(0,s.useRef)(null),pt=(0,s.useRef)(new Set);(0,s.useEffect)(()=>(H.current=!0,()=>{H.current=!1;for(let N of pt.current)window.clearTimeout(N);pt.current.clear()}),[]);let Xe=(0,s.useRef)(new Map),{startAttempt:X,finishAttempt:Y,invalidateAttempt:Z,isAttemptInvalidated:Ge,isAttemptCurrent:nt,generationRef:Ae}=Mo((N,$e,f)=>{y?.(N,$e,{...f,popupBlocked:f?.popupBlocked??wr($e)}),Ke(N),ye(!0),Te(A=>A+1)});(0,s.useEffect)(()=>{me&&Me.current?.focus()},[me,pe]);let ke=(0,s.useCallback)(()=>{Te(N=>N+1)},[]),Ye=(0,s.useCallback)((N,$e,f,A)=>{Z(A),y?.(N,$e,{code:f,popupBlocked:wr($e)}),Ke(N),ye(!0),ke()},[Z,y,ke]),z=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Fe.current?.querySelector("iframe")??Fe.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{fe.current&&(fe.current=!1,z())},[z,pe]);let Zt=(0,s.useCallback)(()=>{ye(!1),d?.(null),z()},[z,d]),ie=(0,s.useCallback)(()=>{w.current?.()},[]);(0,s.useEffect)(()=>{let N=ka(e,t);if(!N)return;let $e=!1,f=!1,A=async()=>{if(!f){f=!0,$e||de("checking");try{let Se=await Zs(S,N.clientSecret,pt.current);if($e)return;let Ie=hi(Se,N.providerObjectId,(0,p.isSetupIntentClientSecret)(N.clientSecret));if(Ie.kind==="confirmed"){if(!Xs(e,t,N.clientSecret))return;w.current=null,de("idle"),l({id:Ie.paymentMethodId,type:"card",threeDSecureActionResultTokenId:Ie.intentId},{...N.accountPatch?{accountPatch:N.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(Ie.kind==="terminal"){gi(e,t,N.clientSecret),w.current=null,de("idle"),Ke(N.paymentMethodType),ye(!0),ke();return}de("blocked")}catch{$e||de("blocked")}finally{f=!1}}};return w.current=A,de("blocked"),()=>{$e=!0,w.current===A&&(w.current=null)}},[t,l,ke,e,S]);let St=(0,s.useCallback)(async N=>{let $e=!1,f=ve=>{$e||($e=!0,N.paymentFailed({reason:"fail",...ve?{message:ve}:{}}))};if(!S||!J){f();return}let A=Xe.current.get(pe);if(A&&!nt(A.generation)){Xe.current.delete(pe),f();return}if(!A&&Ge()){f();return}if(A&&!Y(A.generation)){f();return}A||Y();let Se=N.expressPaymentType??A?.method??ne.current,Ie=A??null,mt=nl(Se),At;Se==="apple_pay"?At="apple_pay":Se==="google_pay"&&(At="google_pay");let ze=A?.generation??Ae.current,Ve=Xt(he),dt=Ve?.now()??globalThis.performance?.now()??Date.now(),Bn=new AbortController,rn=!1,Et=!1,se=null,fn=e,An="processing",Qt="other",on="provider_runtime",Fn,gn=new Promise((ve,ut)=>{Fn=ut}),Cn=window.setTimeout(()=>{rn=!0,Bn.abort(),Fn(yi)},Zc),qt=async(ve,ut,yt)=>{An=ve,Qt=ut,on=ut==="intent_create"||ut==="session_claim"?"transport_error":"provider_runtime";let Sn=Ve?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([yt,gn])}finally{let xt=Ve?.now()??globalThis.performance?.now()??Date.now();Ve?.performance({stage:ve,durationMs:Math.max(0,xt-Sn),durationMode:"machine",requestCategory:ut,paymentMethodCategory:"wallet",provider:"stripe",...rn?{statusClass:"timeout"}:{}})}};try{if(j(!0),d?.(null),!Ie&&b){let Re=await qt("processing","other",b(mt));if(!Re.proceed){f();return}Ie={accountPatch:Re.accountPatch,sessionId:Re.sessionId,nonce:Re.nonce}}let ve=Ie?.sessionId??e;fn=ve;let ut=Ie?.nonce??t,yt=we.current??Ie?.accountPatch,Sn=ul({event:N,fallbackEmail:yt?.email??n,fallbackName:[yt?.firstName,yt?.lastName].join(" ").trim()||v});if(!(0,p.isValidEmail)(Sn.email)){f("Buyer details are required."),tt(Ci(Se),Sn).then(Re=>{Re&&(we.current=Re)});return}we.current=null;let xt={...Ie?.accountPatch,...Tn(Sn,!0)};await qt("processing","session_claim",Promise.resolve(k?.(Sn)));let{error:Dn}=await qt("tokenization","provider_sdk",J.submit());if(Dn){f(),Ye(Se,Dn,"stripe_wallet_submit_failed",A?.generation);return}if(!ve)throw new Error("Missing sessionId or email for payment.");let ft={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Se,paymentMethodId:null,intentKind:o},gt=JSON.stringify({sessionId:ve,nonce:ut??"",request:ft}),cn=Oe.current,dn=cn?.retryIdentity===gt?cn.authorizationAttemptId:(0,p.randomUuidV4)();Oe.current={authorizationAttemptId:dn,retryIdentity:gt};let Ft=await qt("processing","intent_create",Ra(r,te,ve,ut??"",{...ft,authorizationAttemptId:dn},{signal:Bn.signal}));if(Ft.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let kt=Ft.clientSecret,Nn=td({createdAt:Date.now(),sessionId:ve,...ut?{nonce:ut}:{},clientSecret:kt,providerObjectId:Ft.providerObjectId,paymentMethodType:Se,accountPatch:xt});window.clearTimeout(Cn),Et=!0,Ve?.performance({stage:"callback",durationMs:Math.max(0,(Ve?.now()??globalThis.performance?.now()??Date.now())-dt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Gt=Ve?.now()??globalThis.performance?.now()??Date.now(),$={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...At?{walletType:At}:{},attempt:ze},dr=!1,Kt=null;Ve?.log({name:"payment.provider_confirmation.started",...$}),se=window.setTimeout(()=>{se!==null&&pt.current.delete(se),dr=!0;let Re=Ve?.now()??globalThis.performance?.now()??Date.now();Ve?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...$,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Re-Gt),statusClass:"timeout",failureCategory:"provider_runtime"}),Ve?.flush?.().catch(()=>{}),Kt?.()},Qc),pt.current.add(se);let hn=Re=>{se!==null&&(window.clearTimeout(se),pt.current.delete(se),se=null);let T=Ve?.now()??globalThis.performance?.now()??Date.now(),re=Math.max(0,T-Gt),U=Re;return dr&&(Re==="resolved"?U="resolved_late":Re==="returned_error"?U="returned_error_late":U="rejected_late"),Ve?.log({name:"payment.provider_confirmation.returned",...$,operationOutcome:U}),Ve?.performance({...$,durationMs:re,durationMode:"buyer",operationOutcome:U}),{durationMs:re,operationOutcome:U}},Dt=!1,un=!1,Ln=Re=>{if(!Re||typeof Re!="object")return null;let T=Re;if(T.error)return null;let re=T.setupIntent??T.paymentIntent,U=hi(re??null,void 0,!!T.setupIntent);return U.kind==="confirmed"?U:null},pn=Re=>{if(Dt||A&&Ae.current!==A.generation)return;let T=Ln(Re);if(!T)return;if(Nn&&!Xs(ve,ut,kt)){Dt=!0;return}let{intentId:re,paymentMethodId:U}=T;Dt=!0,un=!0,Oe.current=null,w.current=null,H.current&&(de("idle"),j(!1));let Nt=`${ll}:${ve}`;if(typeof window<"u")try{localStorage.setItem(Nt,JSON.stringify({createdAt:Date.now(),sessionId:ve,nonce:ut,accountPatch:xt,paymentMethodId:U,providerIntentId:re,paymentMethodType:Se}))}catch{}try{l({id:U,type:"card",threeDSecureActionResultTokenId:re},{accountPatch:xt,paymentMethodCategory:"wallet",sessionId:ve,nonce:ut})}finally{if(typeof window<"u")try{localStorage.removeItem(Nt)}catch{}}},We=!1;Kt=async()=>{if(!(We||Dt||un)){We=!0,H.current&&de("checking");try{let Re=await Zs(S,kt,pt.current);if(Dt||un)return;let T=(0,p.isSetupIntentClientSecret)(kt),re=hi(Re,Ft.providerObjectId,T);if(re.kind==="confirmed"){pn(T?{setupIntent:Re}:{paymentIntent:Re});return}if(re.kind==="terminal"){if(un=!0,gi(ve,ut,kt),Oe.current=null,w.current=null,!H.current)return;de("idle"),f(),Ye(Se,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",A?.generation);return}H.current&&!un&&(de("blocked"),j(!1))}catch{H.current&&!un&&(de("blocked"),j(!1))}finally{We=!1}}},w.current=Kt;let wn,an;try{let Re=await((0,p.isSetupIntentClientSecret)(kt)?S.confirmSetup({elements:J,clientSecret:kt,redirect:"if_required"}):S.confirmPayment({elements:J,clientSecret:kt,redirect:"if_required"}));if(!Re||typeof Re!="object"||(wn=Re,!wn.error&&!Ln(wn)))throw fi;an=hn(wn.error?"returned_error":"resolved")}catch(Re){let T=Re===fi,re=hn(T?"returned_error":"rejected");if(Ve?.error({...T?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:ei(Re),...$,operationOutcome:re.operationOutcome,durationMs:re.durationMs,statusClass:"unknown"}),!H.current||Dt)return;await Kt?.();return}let mn=wn.error;if(mn){if(!H.current||Dt)return;if(Ao(mn)){un=!0,gi(ve,ut,kt),Oe.current=null,w.current=null,de("idle");let Re=mn.message??"Your payment was declined.";f(Re),d?.(Re),g?.(nn(mt,Re,{code:Sr(mn),declineCode:ro(mn)})),_a({billingApiUrl:r,sessionId:ve,nonce:ut,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Se,providerDeclineReason:Sr(mn)??"provider_declined",...Ft.intentKind==="payment"&&Ft.providerObjectId.startsWith("pi_")?{providerIntentId:Ft.providerObjectId}:{}}})}else Ve?.error({...ei(mn),...$,operationOutcome:an.operationOutcome,durationMs:an.durationMs,statusClass:"unknown"}),await Kt?.();return}if(pn(wn),!Dt)throw new Error("Invalid provider returned for APM intent")}catch(ve){if(ve===yi){let ut=Ve?.now()??globalThis.performance?.now()??Date.now();Ve?.error({errorCode:rd(Qt),stage:An,requestCategory:Qt,paymentMethodCategory:"wallet",provider:"stripe",...At?{walletType:At}:{},operationOutcome:"watchdog_expired",checkoutSessionId:fn,durationMs:Math.max(0,ut-dt),statusClass:"timeout",failureCategory:on,attempt:ze}),Ve?.flush?.().catch(()=>{})}f(),Ye(Se,ve,ve===yi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",A?.generation)}finally{if(window.clearTimeout(Cn),se!==null&&(window.clearTimeout(se),pt.current.delete(se)),!Et){let ve=Ve?.now()??globalThis.performance?.now()??Date.now();Ve?.performance({stage:"callback",durationMs:Math.max(0,ve-dt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...rn?{statusClass:"timeout"}:{}})}H.current&&j(!1)}},[S,J,e,t,n,v,tt,k,r,te,o,l,d,g,b,Ye,Y,nt,Ge,Ae,he,pe]),wt=(0,s.useMemo)(()=>{let N=["applePay","googlePay","paypal","link","amazonPay","klarna"],$e=new Set(["applePay","googlePay"]),f=new Set(a.map(p.stripeExpressMethodToOptionKey)),A={};for(let Se of N)f.has(Se)?A[Se]=$e.has(Se)?"always":"auto":A[Se]="never";return A},[a]),rt=(0,s.useMemo)(()=>a.map(p.stripeExpressMethodToOptionKey),[a]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(ml,{state:K,placeholderTestId:"flopay-wallet-placeholder",borderRadius:L,children:(0,c.jsxs)("div",{ref:Fe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[me&&(0,c.jsxs)("button",{ref:Me,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Zt,style:Pi,children:["Try ",Ci(He)," again"]}),be!=="idle"&&(0,c.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,c.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,c.jsx)("button",{type:"button",onClick:ie,disabled:be==="checking",style:Pi,children:be==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ee&&(0,c.jsx)(no,{identity:Ee.identity,methodLabel:Ee.methodLabel,onComplete:Ct,onCancel:()=>Ct(null)},Ee.id),be==="idle"&&(0,c.jsx)("div",{style:{display:Ee?"none":void 0},children:(0,c.jsx)(jt.ExpressCheckoutElement,{onReady:N=>{le(pl(N,rt))},onLoadError:N=>{le("load_error"),ki(Xt(he),"stripe","wallet")},onClick:async N=>{ne.current=N.expressPaymentType,M.current=nl(N.expressPaymentType);let $e=!0,f=window.setTimeout(()=>{$e=!1,N.reject()},Xc),A=b?await b(M.current):{proceed:!0};if(window.clearTimeout(f),!$e)return;if(!A.proceed){Xe.current.delete(pe),N.reject();return}let Se=X(N.expressPaymentType);Xe.current.set(pe,{generation:Se,method:N.expressPaymentType,accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}),ye(!1),m?.(M.current),N.resolve()},onConfirm:St,onCancel:()=>{let N=Xe.current.get(pe);Xe.current.delete(pe),Xt(he)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Z(N?.generation),Oe.current=null,ye(!1),fe.current=!0,ke()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:wt,emailRequired:Le,billingAddressRequired:Le,layout:{maxColumns:1,overflow:"never"}}},pe)})]})}),Ce&&(0,c.jsx)(Jn,{status:"processing"})]})}function yl(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function vd({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:d,borderColor:m,textColor:g,borderRadius:y,fontFamily:b}){let v=(0,p.resolveStripeMethodBrandVariant)(e,t),k=zs[e],[B,L]=(0,s.useState)(!1),he=!!k&&!B,te=v?.backgroundColor??d??"#ffffff",S=v?.borderColor??m??"#d1d5db",J=v?.textColor??g??"#262833";return(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&l()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Ia,padding:"0 1rem",backgroundColor:te,color:J,border:`1px solid ${S}`,borderRadius:y??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,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?(0,c.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,p.getStripeMethodDisplayName)(e)}\u2026`}):(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,p.hasVendoredStripeMethodLogo)(e)?8:0},children:[he?(0,c.jsx)("img",{src:k,alt:"","aria-hidden":"true",onError:()=>L(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!he&&v?.logoSvg?(0,c.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:v.logoSvg}}):null,(0,c.jsx)("span",{children:(0,p.getStripeMethodDisplayName)(e)})]}),a&&(0,c.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:J,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,c.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Si({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:d,onErrorChange:m,onDecline:g,onCancel:y,runBeforeButtonClick:b,onButtonClick:v,isProcessing:k,submitButtonColor:B,submitButtonBorderRadius:L,submitButtonStyle:he,errorText:te}){let S=kr(),{emitInstrument:J}=(0,s.useContext)(Gn),K=(0,jt.useStripe)(),le=(0,jt.useElements)(),[Ce,j]=(0,s.useState)(!1),Le=(0,s.useRef)(!1),[Ee,tt]=(0,s.useState)(!1),[Ct,Fe]=(0,s.useState)("loading"),[Me,pe]=(0,s.useState)(""),Te=!(0,p.isValidEmail)(r?.trim()),me=!Te||(0,p.isValidEmail)(Me.trim()),ye=(0,s.useCallback)(async()=>{if(!K||!le||k||Le.current||!Ee)return;Le.current=!0,j(!0);let be=b?await b("card"):{proceed:!0};if(!be.proceed){Le.current=!1,j(!1);return}v?.("card");let de=be.sessionId??t,He=be.nonce??n,Ke=Or(o?.trim()),w=Tn({email:be.accountPatch?.email?.trim()||r?.trim()||Me.trim(),firstName:be.accountPatch?.firstName?.trim()||Ke.firstName,lastName:be.accountPatch?.lastName?.trim()||Ke.lastName}),H=w.email,fe=Tn({...be.accountPatch,...w});try{if(m?.(null),!(0,p.isValidEmail)(H))throw new Error("A valid email address is required for payment.");await a?.(w);let ne=await le.submit();if(ne.error){m?.(ne.error.message??"Payment failed.");return}let M=[w.firstName,w.lastName].filter(Boolean).join(" "),we=await K.createPaymentMethod({elements:le,params:{billing_details:{email:H,...M?{name:M}:{}}}});if(we.error||!we.paymentMethod){m?.(we.error?.message??"Failed to create payment method.");return}let Oe=we.paymentMethod;if(!de||!H)throw new Error("Missing sessionId or email for payment.");let pt=Oe.type||e,Xe=await Ra(l,J,de,He??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:pt,paymentMethodId:null,intentKind:"payment"});if(Xe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let X=Xe.clientSecret;if(typeof window<"u")try{localStorage.setItem(hr,JSON.stringify({clientSecret:X,sessionId:de,nonce:He,accountPatch:fe,paymentMethodId:Oe.id,paymentMethodType:Oe.type??e,gateway:"stripe"}))}catch{}let{error:Y,paymentIntent:Z}=await K.confirmPayment({clientSecret:X,confirmParams:{return_url:window.location.href,payment_method:Oe.id},redirect:"if_required"});if(Y){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Ae=Y.message??"Payment failed.";m?.(Ae),g?.(nn("card",Ae,{code:Y.code})),await _a({billingApiUrl:l,sessionId:de,nonce:He,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Y.code??"provider_declined"}});return}let Ge=Z?.status;if(!Eo(Ge)){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Ae=Ge==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(Ae),g?.(nn("card",Ae,{code:Ge??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let nt=typeof Z?.payment_method=="string"?Z.payment_method:Z?.payment_method?.id;d({id:nt??Oe.id,type:"card",threeDSecureActionResultTokenId:Z?.id,gateway:"stripe",paymentMethodType:Oe.type??e},{accountPatch:fe,paymentMethodCategory:"apm",sessionId:de,nonce:He})}catch(ne){m?.(ne instanceof Error?ne.message:"Payment failed. Please try again.")}finally{Le.current=!1,j(!1)}},[K,le,k,Ee,b,v,t,n,r,o,Me,a,l,J,e,d,m,g]);return(0,c.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Te&&(0,c.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Te&&(0,c.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,c.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Me,onChange:be=>pe(be.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,c.jsx)(jt.PaymentElement,{onReady:()=>Fe("ready"),onLoadError:()=>{Fe("load_error"),ki(Xt(S),"stripe","apm")},onChange:be=>{tt(!!be.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,p.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{ye()},disabled:!Ee||!me||Ce||k||Ct!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:B,color:"white",border:"none",borderRadius:L,fontSize:"1rem",fontWeight:600,cursor:!Ee||!me||Ce||k||Ct!=="ready"?"not-allowed":"pointer",opacity:!Ee||!me||Ce||k||Ct!=="ready"?.5:1,transition:"opacity 120ms ease-out",...he??{}},children:Ce?"Processing\u2026":`Pay with ${(0,p.getStripeMethodDisplayName)(e)}`}),te&&(0,c.jsx)(ao,{margin:"0.75rem 0 0",children:te})]})}function sl({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:d,paymentElementBaseOptions:m,onTokenizedBody:g,onErrorChange:y,onButtonClick:b,onDecline:v,runBeforeButtonClick:k,onLoadStateChange:B,isProcessing:L=!1,submitButtonColor:he="#4A49FF",submitButtonBorderRadius:te=8,submitButtonStyle:S,buttonAppearance:J,themeId:K,onExpandApm:le,expandedApmMethod:Ce}){let{emitInstrument:j}=(0,s.useContext)(Gn),[Le,Ee]=(0,s.useState)(null),[tt,Ct]=(0,s.useState)(null),Fe=(0,s.useRef)(!1),{request:Me,collect:pe,finish:Te}=to();(0,s.useEffect)(()=>{l.length>0&&d?B?.("ready"):d||B?.("loading")},[l.length,d,B]);let me=(0,s.useCallback)(async w=>{if(!d||Fe.current||L)return;Fe.current=!0,Ct(w);let H=k?await k("card"):{proceed:!0};if(!H.proceed){Fe.current=!1,Ct(null);return}b?.("card");let fe=H.sessionId??e,ne=H.nonce??t,M=Or([H.accountPatch?.firstName,H.accountPatch?.lastName].filter(Boolean).join(" ")||r),we=Tn({email:H.accountPatch?.email?.trim()||n?.trim(),firstName:H.accountPatch?.firstName?.trim()||M.firstName,lastName:H.accountPatch?.lastName?.trim()||M.lastName});if(!(0,p.isValidEmail)(we.email)){Ct(null);let Xe=await pe((0,p.getStripeMethodDisplayName)(w),we);if(!Xe){Fe.current=!1;return}we=Xe,Ct(w)}let Oe=we.email,pt=Tn({...H.accountPatch,...we});try{if(y?.(null),!fe||!(0,p.isValidEmail)(Oe))throw new Error("Missing sessionId or email for payment.");await o?.(we);let Xe=await Ra(a,j,fe,ne??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:w,paymentMethodId:null,intentKind:"payment"});if(Xe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let X=Xe.clientSecret;if(typeof window<"u")try{localStorage.setItem(hr,JSON.stringify({clientSecret:X,sessionId:fe,nonce:ne,accountPatch:pt,paymentMethodType:w,gateway:"stripe"}))}catch{}let{error:Y,paymentIntent:Z}=await d.confirmPayment({clientSecret:X,confirmParams:{return_url:window.location.href,payment_method_data:{type:w,billing_details:{name:[we.firstName,we.lastName].filter(Boolean).join(" "),...Oe?{email:Oe}:{}}}},redirect:"if_required"});if(Y){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Ae=Y.message??"Payment failed.";y?.(Ae),v?.(nn("card",Ae,{code:Y.code})),await _a({billingApiUrl:a,sessionId:fe,nonce:ne,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:w,providerDeclineReason:Y.code??"provider_declined"}});return}let Ge=Z?.status;if(!Eo(Ge)){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Ae=Ge==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.(Ae),v?.(nn("card",Ae,{code:Ge??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let nt=typeof Z?.payment_method=="string"?Z.payment_method:Z?.payment_method?.id;g({id:nt??Z?.id,type:"card",threeDSecureActionResultTokenId:Z?.id,gateway:"stripe",paymentMethodType:w},{accountPatch:pt,paymentMethodCategory:"apm",sessionId:fe,nonce:ne})}catch(Xe){y?.(Xe instanceof Error?Xe.message:"Payment failed. Please try again.")}finally{Fe.current=!1,Ct(null)}},[d,L,k,b,e,t,n,pe,a,j,r,o,g,y,v]),[ye,be]=(0,s.useState)(null),de=le?Ce??null:ye,He=(0,s.useCallback)(w=>{Fe.current||L||de&&de!==w||((0,p.needsStripeMethodExplicitConfirm)(w)?le?le(w):be(w):me(w))},[de,L,me,le]),Ke=(0,s.useMemo)(()=>ye?yl(m,ye):null,[ye,m]);return(0,c.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Me?(0,c.jsx)(no,{identity:Me.identity,methodLabel:Me.methodLabel,onComplete:Te,onCancel:()=>Te(null)},Me.id):l.map(w=>{let H=Ce===w,fe=tt===w,ne=tt!==null&&tt!==w||Ce!=null&&Ce!==w;return(0,c.jsxs)(s.default.Fragment,{children:[(0,c.jsx)(vd,{method:w,themeId:K,submitting:fe,disabled:ne,highlighted:H,hasNextStep:(0,p.needsStripeMethodExplicitConfirm)(w),onClick:()=>He(w),backgroundColor:J?.backgroundColor,borderColor:J?.borderColor,textColor:J?.textColor,borderRadius:J?.borderRadius,fontFamily:J?.fontFamily}),!le&&ye===w&&Ke&&d&&(0,c.jsx)(jt.Elements,{stripe:d,options:Ke,children:(0,c.jsx)(Si,{method:w,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:g,onErrorChange:y,onDecline:v,onCancel:()=>be(null),runBeforeButtonClick:k,onButtonClick:b,isProcessing:L,submitButtonColor:he,submitButtonBorderRadius:te,submitButtonStyle:S})},w)]},w)})})}function Pd({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:l,onError:d,onDecline:m,onTokenizedBody:g,firstName:y,lastName:b,chv:v,className:k,isProcessing:B,error:L,onErrorChange:he,showPayPal:te=!0,showStripe:S=!0,enabledPaymentMethods:J,enabledPaymentMethodCountries:K,showApplePay:le=!0,showGooglePay:Ce=!0,layout:j="default",theme:Le,buttonsTheme:Ee,buttonsStyles:tt,appearance:Ct,cardButtonContent:Fe,cardBackButtonContent:Me,cardTitleContent:pe,showSecurityFooter:Te,onButtonClick:me,onBeforeButtonClick:ye,onBuyerIdentityReady:be,enableAVS:de,cardFieldOrder:He,cardPreFormSlot:Ke,avsLayout:w="row",country:H,zip:fe,addressLine1:ne,addressLine2:M,city:we,state:Oe,onCountryChange:pt,onZipChange:Xe,avsCheck:X,checkoutType:Y,checkoutLayout:Z,totalAmount:Ge=0,currency:nt="usd",initialCardOpen:Ae=!1,directPaypal:ke,isSubscription:Ye=!1,session:z,dataAttachmentPending:Zt=!1,dataAttachmentRequiresIdentity:ie=!1,debug:St=!1}){let wt=kr(),rt=ia(),N=(0,s.useContext)(ar),{emitInstrument:$e}=(0,s.useContext)(Gn),f=z??N.session,A=f?.gateways?.paypal?.providerObjectType??ke?.providerObjectType,Se=Zt||N.claimPending===!0,Ie=ie||N.claimRequiresIdentity===!0,mt=Se&&!Ie,At=Rs(),ze=n||At,[Ve,dt]=(0,s.useState)(!1),[Bn,rn]=(0,s.useState)(null),[Et,se]=(0,s.useState)(H??"US"),[fn,An]=(0,s.useState)(fe??""),[Qt,on]=(0,s.useState)(ne??""),[Fn,gn]=(0,s.useState)(M??""),[Cn,qt]=(0,s.useState)(we??""),[ve,ut]=(0,s.useState)(Oe??""),[yt,Sn]=(0,s.useState)(""),[xt,Dn]=(0,s.useState)({}),ft=(0,s.useRef)(fe??""),gt=(0,s.useRef)(H??"US"),cn=(0,s.useRef)(ne??""),dn=(0,s.useRef)(M??""),Ft=(0,s.useRef)(we??""),kt=(0,s.useRef)(Oe??""),Nn=(0,s.useRef)(""),Gt=(0,s.useRef)({});(0,s.useEffect)(()=>{let i=(I,W,Ue,G,ct)=>{if(Gt.current[I])return;let ot=W?.trim();!ot||ot===Ue.current||(Ue.current=ot,G(ot),ct?.(ot))};i("country",H,gt,se,pt),i("zip",fe,ft,An,Xe),i("addressLine1",ne,cn,on),i("addressLine2",M,dn,gn),i("city",we,Ft,qt),i("state",Oe,kt,ut)},[H,fe,ne,M,we,Oe,pt,Xe]);let $=(0,s.useMemo)(()=>(0,p.resolveAVSConfig)(de),[de]),dr=$!==null,Kt=(0,s.useMemo)(()=>(0,p.isAuthorizationOnlySession)(z),[z]),hn=!!z?.vault?.html,Dt=!!z?.gateways?.pcivault,Ln=!!(z?.gateways?.stripe?.enabledPaymentMethods??J)?.includes("card"),pn=hn||Ln||Dt,We=!!(S&&pn&&e),[wn,an]=(0,s.useState)(()=>j!=="buttons"||Ae?e??null:null),[mn,Re]=(0,s.useState)(0),T=j!=="buttons"||Ae||!!e&&wn===e,re=z?.captureMethod,U=(0,s.useRef)(wt);(0,s.useEffect)(()=>{U.current=wt},[wt]);let[Nt,Zn]=(0,s.useState)(null);(0,s.useEffect)(()=>{if(!We||!e||!T){Zn(null);return}let i=U.current?U.current.cardCapture({sessionId:e,captureMethod:re}):new sr.PciVaultCardCapture({sessionId:e,captureMethod:re,billingApiUrl:ze,telemetry:r});return Zn({sessionId:e,captureMethod:re,billingApiUrl:ze,telemetry:r,capture:i}),()=>{i.unmount()}},[We,e,T,re,ze,r]);let lt=We&&e&&T&&Nt?.sessionId===e&&Nt.captureMethod===re&&Nt.billingApiUrl===ze&&Nt.telemetry===r?Nt.capture:null,yn=(0,s.useMemo)(()=>{let i=Et,I=$?(0,p.isAVSFieldVisible)($.postal_code,i):!1;return gd(i,fn,I)},[$,Et,fn]),{avsInvalid:at,invalidAvsFields:Br}=(0,s.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!We||!$)return{avsInvalid:!1,invalidAvsFields:i};let I=Et,W=(ct,ot)=>(0,p.isAVSFieldVisible)(ct,I)&&!ot.trim(),Ue={line1:W($.address_line_1,Qt),city:W($.city,Cn),state:W($.state,ve),zip:yn.empty||yn.malformed};return{avsInvalid:Ue.line1||Ue.city||Ue.state||Ue.zip,invalidAvsFields:Ue}},[We,$,Et,Qt,Cn,ve,yn]),[_r,On]=(0,s.useState)(!1),[Er,Pr]=(0,s.useState)(!1),[zn,Yt]=(0,s.useState)(!1),[ur,kn]=(0,s.useState)({line1:!1,city:!1,state:!1}),Qn=(0,s.useRef)(!1),bn=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),er=(0,s.useRef)(!1),ht=(0,s.useCallback)(i=>{bn.current[i]=!0,er.current=!0},[]),Un=(0,s.useCallback)(i=>!Qn.current&&bn.current[i],[]),In=(0,s.useCallback)(i=>{Un(i)&&kn(I=>I[i]?I:{...I,[i]:!0})},[Un]),[Rn,qn]=(0,s.useState)(()=>bi(z?.vault)),[Ze,$t]=(0,s.useState)(Ae&&pn?"card":"buttons"),[Wt,Tr]=(0,s.useState)(null),fo=Ze==="expanding"||Ze==="card",pr=z?.gateways?.stripe?"stripe":void 0,$n=(0,s.useCallback)(()=>{$e?.({class:"card_surface",provider:pr})},[pr,$e]),Vn=(0,s.useRef)(null),sn=(0,s.useCallback)(i=>{Vn.current&&clearTimeout(Vn.current),Vn.current=setTimeout(()=>{Vn.current=null,i()},$o)},[]);(0,s.useEffect)(()=>()=>{Vn.current&&clearTimeout(Vn.current)},[]);let Fr=(0,s.useCallback)(()=>{$n(),an(e??null),Re(i=>i+1),$t("expanding"),sn(()=>$t("card"))},[sn,$n,e]),Ar=(0,s.useCallback)(()=>{$t("collapsing"),sn(()=>$t("buttons"))},[sn]),tr=(0,s.useCallback)(i=>{Tr(i),$t("apm-expanding"),sn(()=>$t("apm-form"))},[sn]),nr=(0,s.useCallback)(()=>{$t("apm-collapsing"),sn(()=>{$t("buttons"),Tr(null)})},[sn]);(0,s.useEffect)(()=>{j==="buttons"&&Ae&&pn&&(an(e??null),$t("card"))},[j,Ae,pn,e]);let[en,P]=(0,s.useState)(null),D=(0,s.useRef)(!1),O=(0,s.useRef)(null),V=(0,s.useRef)("idle"),[De,bt]=(0,s.useState)(null),xe=(0,s.useRef)(De);(0,s.useEffect)(()=>{xe.current=De},[De]);let ae=(0,s.useRef)(null),oe=(0,s.useMemo)(()=>{if(be||N.claimBuyerIdentity||z?.buyerIdentified!==!1||!e||!t)return;let i=`${ze}|${e}|${t}`;ae.current?.key!==i&&(ae.current={key:i,claim:Qr(new sr.PaymentAPI(ze,{telemetry:!1}),e,t,{...a?{userId:a}:{},...y?{firstName:y}:{},...b?{lastName:b}:{}})});let I=ae.current.claim;return async W=>{await I(W)}},[be,N.claimBuyerIdentity,z?.buyerIdentified,e,t,ze,a,y,b]),x=be??N.claimBuyerIdentity??oe,ce=L??Bn,h=(0,s.useMemo)(()=>(0,p.resolveTheme)(Le),[Le]),u=(0,s.useMemo)(()=>{let i=h?.buttonsLayout??(0,p.resolveButtonsLayoutTheme)(Ee);return tt?{...i,...tt,cardButton:{...i.cardButton,...tt.cardButton},cardFormContainer:{...i.cardFormContainer,...tt.cardFormContainer},backButton:{...i.backButton,...tt.backButton},backButtonIcon:{...i.backButtonIcon,...tt.backButtonIcon},submitButton:{...i.submitButton,...tt.submitButton},title:{...i.title,...tt.title}}:i},[h,Ee,tt]),F=Ct??h?.appearance,Ne=(0,s.useMemo)(()=>Sa({appearance:F,buttonsStyles:u,layout:j}),[F,u,j]),Be=N.inlineSessionPatchProcessing??!1,R=(B??Ve)||Be,Q=ze.replace(/\/+$/,""),q=(0,s.useMemo)(()=>Qa({userId:a,email:o,firstName:y,lastName:b,country:H,zip:fe},xt),[a,o,y,b,H,fe,xt]),It=[q.firstName,q.lastName].filter(i=>!!i?.trim()).join(" "),Lt=!(0,p.isValidEmail)(q.email?.trim()),jn=(0,s.useRef)(null);We&&jn.current===null&&(jn.current=Lt);let _e=We&&(jn.current??Lt),ue=(0,s.useMemo)(()=>hd(yt,_e),[yt,_e]),ge=ue.empty||ue.malformed,ee=(0,s.useMemo)(()=>wt?wt.getRawProvider():null,[wt]),Qe=(0,s.useMemo)(()=>rt?rt.getRawProvider():null,[rt]),tn=Ge||100,je=nt.toLowerCase(),rr=(0,s.useMemo)(()=>F?(0,sr.toStripeAppearance)(F):null,[F]),xn=rr,Fi=(0,s.useMemo)(()=>{let i=rr??{},I=i.rules??{};return{...i,rules:{...I,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...I[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...I[".AccordionItemContents"]??{}}}}},[rr]),Di=(0,s.useMemo)(()=>({...Ss(Ge,z?.captureMethod),currency:je,...xn?{appearance:xn}:null}),[Ge,je,z?.captureMethod,xn]),Ni=(0,s.useMemo)(()=>({mode:"payment",amount:tn,currency:je,captureMethod:"manual",setupFutureUsage:"off_session",...xn?{appearance:xn}:null}),[tn,je,xn]),Pe=(0,s.useCallback)(i=>{rn(i),he?.(i)},[he]),Da=(0,s.useRef)(""),[Li,El]=(0,s.useState)(!1),Na=(0,s.useCallback)(()=>{El(!0)},[]);(0,s.useEffect)(()=>{if(!We||!_e||!x||!Li||ge||Da.current)return;let i=Tn({email:(0,p.isValidEmail)(q.email?.trim())?q.email?.trim():Nn.current.trim(),firstName:q.firstName?.trim(),lastName:q.lastName?.trim()});Da.current=JSON.stringify(i),Dn(I=>({...I,...i})),Promise.resolve(x(i)).catch(I=>{Da.current="",Pe(I instanceof Error?I.message:"Failed to attach buyer details.")})},[We,_e,x,Li,ge,q.email,q.firstName,q.lastName,Pe]),(0,s.useEffect)(()=>{!We||!lt||lt.setCardFieldOrder?.(He??null,$==null&&!_e)},[We,lt,He,$,_e]),(0,s.useEffect)(()=>{(Ze==="expanding"||Ze==="collapsing"||Ze==="apm-expanding"||Ze==="apm-collapsing")&&Pe(null)},[Ze,Pe]);let mr=(0,s.useCallback)((i,I,W)=>{m?.(nn(i,I,W))},[m]),jr=(0,s.useCallback)((i,I,W)=>{let Ue=W?.popupBlocked??wr(I),G=yd(i,Ue),ct=Ur(W?.code)??Sr(I)??"external_payment_method_failed",ot=new p.FloPayError(G,"api_error",{code:"external_payment_method_failed",param:i});P(null),j==="buttons"&&($t("buttons"),Tr(null)),Pe(G),d?.(ot),console.error("[FloPay] External payment method failed:",{method:i,code:ct,popupBlocked:Ue})},[j,d,Pe]);(0,s.useEffect)(()=>{if(!We||!e){qn(null);return}let i=bi(z?.vault);if(i){qn(i);return}if(!T){qn(null);return}qn(null);let I=!0;return new sr.PaymentAPI(Q).getVaultCapture(e,t).then(W=>{if(!I)return;let Ue=bi(W);Ue?qn(Ue):Pe("Failed to load the secure card form.")}).catch(W=>{I&&Pe(W instanceof Error?W.message:"Failed to load the secure card form.")}),()=>{I=!1}},[We,T,mn,e,z?.vault,Q,t,Pe]);let yr=(0,s.useRef)({onComplete:l,onError:d,updateError:Pe,emitDecline:mr,resolvedAccount:q,avsConfig:$,avsCheckProp:X,sessionId:e,nonce:t,baseUrl:Q,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt});yr.current={onComplete:l,onError:d,updateError:Pe,emitDecline:mr,resolvedAccount:q,avsConfig:$,avsCheckProp:X,sessionId:e,nonce:t,baseUrl:Q,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt};let La=(0,s.useRef)(!1),Oi=(0,s.useCallback)(()=>{let i=yr.current,I=i.resolvedAccount.email?.trim(),W=(0,p.isValidEmail)(I)?I:Nn.current.trim();if(!(0,p.isValidEmail)(W))return null;let Ue=i.resolvedAccount.firstName?.trim(),G=i.resolvedAccount.lastName?.trim(),ct=gt.current||i.resolvedAccount.country||"US",ot=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.state,ct):!1,it=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.address_line_1,ct):!1,Rt=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.postal_code,ct):!1,Mt=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.city,ct):!1,zt=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.address_line_2,ct):!1,Tt=it&&!ot&&Rt?(0,p.getStateFromPostalCode)(ct,(ft.current??"").trim()):null,Wn=ot?kt.current:Tt;return{accountData:{userId:i.resolvedAccount.userId??"",email:W,...Ue?{firstName:Ue}:{},...G?{lastName:G}:{},...Rt&&ft.current?{zip:ft.current}:{},...Mt&&Ft.current?{city:Ft.current}:{},...Wn?{state:Wn}:{},...it&&cn.current?{addressLine1:cn.current}:{},...zt&&dn.current?{addressLine2:dn.current}:{},country:ct},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,p.isAVSFieldVisible)(i.avsConfig.country,ct),postal_code:Rt,address_line_1:it,address_line_2:zt,city:Mt,state:ot}}:{}}},[]),zi=(0,s.useRef)(Se);zi.current=Se,(0,s.useEffect)(()=>{Se||ce!==Qs||yr.current.updateError(null)},[Se,ce]),(0,s.useEffect)(()=>{!We||!lt||lt.setSubmitGate?.(at||Se||ge)},[We,lt,at,Se,ge]),(0,s.useEffect)(()=>{if(!We||!lt)return;La.current=!1;let i=null,I=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,V.current="idle",P(null)},400)},W=lt.on("submitting",()=>{On(!0),O.current&&clearTimeout(O.current),V.current="validation-window",O.current=setTimeout(()=>{O.current=null,V.current==="validation-window"&&(V.current="processing")},od),P("processing");let it=yr.current;if(!it.sessionId||!it.nonce)return;let Rt=Oi();if(!Rt){it.updateError("Enter a valid email address."),V.current="idle",P(null);return}new sr.PaymentAPI(it.baseUrl).patchAccountSnapshot(it.sessionId,it.nonce,Rt,{telemetryMode:"best_effort"}).catch(Mt=>{if(!ad(Mt))return;let zt=Mt instanceof Error?Mt.message:"Please check your billing address and try again.";it.updateError(zt),V.current="idle",P(null),it.onError?.(Mt instanceof p.FloPayError?Mt:new p.FloPayError(zt,"api_error"))})}),Ue=lt.on("complete",async it=>{if(lo(it.sessionId??yr.current.sessionId),V.current="terminal",P("success"),await new Promise(zt=>setTimeout(zt,600)),La.current)return;La.current=!0;let Rt=yr.current,Mt=(0,p.isAuthorizationOnlySession)(Rt)||it.outcome==="authorized";yr.current.onComplete?.(Mt?{status:"authorized",paymentIntentId:it.intentId,paymentId:it.paymentId??Rt.paymentId,sessionId:it.sessionId??Rt.sessionId,authorizationExpiresAt:it.authorizationExpiresAt??Rt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:it.intentId,checkoutMethod:"card"})}),G=lt.on("decline",it=>{let Rt=yr.current,Mt=it.message??"Your payment was declined. Please try another card or contact your bank.";V.current="terminal",Rt.updateError(Mt),P("error");let zt=it.failureOutcome??(0,p.normalizeCheckoutFailureOutcome)(it.declineReason)??"authorization_declined";Rt.emitDecline("card",Mt,{code:zt,declineCode:zt}),I()}),ct=lt.on("error",it=>{let Rt=yr.current,Mt=it.message??"There was a problem processing your payment. Please try again.";V.current="terminal",Rt.updateError(Mt),P("error"),Rt.onError?.(new p.FloPayError(Mt,"api_error",{code:it.failureOutcome??"capture_failed"})),I()}),ot=lt.on("blocked",()=>{if(!zi.current){On(!0);return}Na(),yr.current.updateError(Qs)});return()=>{i&&(clearTimeout(i),i=null),O.current&&(clearTimeout(O.current),O.current=null),V.current="idle",P(null),W(),Ue(),G(),ct(),ot()}},[We,lt,Na,Oi]);let fr=!!ke?.clientId,go=Array.isArray(J),Wo=go&&J.length>0,Tl=go&&J.includes("paypal"),{expressMethods:Ho,paymentElementMethods:ho}=(0,s.useMemo)(()=>(0,p.partitionStripeMethods)(J,{excludePaypal:fr}),[J,fr]),Ui=fr||!!rt,Al=(0,s.useMemo)(()=>Ui?Ho.filter(i=>i!=="paypal"):Ho,[Ho,Ui]),xl=(0,s.useMemo)(()=>{let i=[];return le&&i.push("apple_pay"),Ce&&i.push("google_pay"),i},[le,Ce]),Kr=go?Al:xl,Ml=S&&Kr.length>0,Oa=dr?Et:H,Go=(0,s.useMemo)(()=>{let i=Oa?.trim().toUpperCase();return i?K?ho.filter(I=>{let W=K[I];return!W||W.length===0||W.includes(i)}):(0,p.filterStripeMethodsByCountry)(ho,Oa):ho},[ho,Oa,K]),za=(0,s.useMemo)(()=>({mode:"payment",amount:tn,currency:je,paymentMethodCreation:"manual",appearance:Fi}),[tn,je,Fi]),[qi,$i]=(0,s.useState)("loading"),[Vi,ji]=(0,s.useState)("loading"),[Ki,Wi]=(0,s.useState)("loading"),[Bl,Ua]=(0,s.useState)(!1),[Hi,qa]=(0,s.useState)("loading"),[$a,Fl]=(0,s.useState)();(0,s.useEffect)(()=>{Fl(sa())},[]);let Yo=$a?.inAppBrowser,Jo=$a?la($a,ke?.approvalPresentation,A??(Ye?"subscription":"order")):"popup",Gi=te&&(fr||(go?Tl:Yo===!1)),Yi=S&&Ml,bo=(!mt||!!N.waitForDataAttachment)&&Gi&&fr,Ji=Hi==="retrying"||Hi==="exhausted",vo=!mt&&Gi&&!!Qe&&(!fr||Ji),Wr=!mt&&Yi&&!!ee,Po=!mt&&S&&Wo&&Go.length>0&&!!ee,Dl=bo&&!Ji?Bl:vo&&ol(qi),Nl=Wr&&ol(Vi),Ll=Po&&Ki!=="load_error",Xi=i=>i==="loading"||i==="ready",Zi=bo||vo&&Xi(qi)||Wr&&Xi(Vi)||Po&&Ki!=="load_error",Xo=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!Xo.current){if(!S&&!te){Xo.current=!0;let i=new p.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(i),Pe(i.message)}else if(!S&&te&&!fr&&!Qe){Xo.current=!0;let i=new p.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(i),Pe(i.message)}else if(Yo!==void 0&&!mt&&!pn&&!Zi){Xo.current=!0;let i=new p.FloPayError("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"});d?.(i),Pe(i.message)}}},[S,te,fr,Qe,Yo,mt,pn,Zi,d,Pe]);let Qi=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(Qi.current||!Wo)return;let i=[];le!==!0&&i.push("showApplePay"),Ce!==!0&&i.push("showGooglePay"),i.length!==0&&(Qi.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Wo,le,Ce]);let es=(0,s.useCallback)((i,I)=>N.applyInlineSessionPatch?N.applyInlineSessionPatch(i).then(W=>({error:null,sessionId:W.sessionId||e,nonce:W.session?.clientSecret||t})).catch(W=>{let Ue=rl(I,W);return Pe(Ue.message),d?.(Ue),{error:Ue,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[N.applyInlineSessionPatch,t,d,e,Pe]),or=(0,s.useCallback)(async i=>{if(i!=="card"&&mt&&await N.waitForDataAttachment?.(),!ye)return{proceed:!0};try{let I=await ye({method:i,sessionId:e||void 0,createSession:N.inlineSessionDraft});if(I===!1)return{proceed:!1};if(I&&typeof I=="object"){I.account&&Dn(Ue=>({...Ue??{},...I.account}));let W=await es(I,i);return W.error?{proceed:!1,accountPatch:I.account}:{proceed:!0,accountPatch:I.account,sessionId:W.sessionId,nonce:W.nonce}}return{proceed:!0}}catch(I){let W=rl(i,I);return Pe(W.message),d?.(W),{proceed:!1}}},[es,N.inlineSessionDraft,N.waitForDataAttachment,mt,ye,d,e,Pe]),ts=(0,s.useCallback)(async(i,I)=>{if(D.current)return;D.current=!0,dt(!0),P("processing"),Pe(null);let W=I?.sessionId??e,Ue=I?.nonce??t,G=Qa(q,I?.accountPatch),ct=I?.completionPaymentMethodId??To(i),ot=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,it=dd(i),Rt=()=>{$e?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:it})};try{let zt=await new sr.PaymentAPI(Q).processPayment(G.userId??"",{sessionId:W,nonce:Ue,paymentMethodCategory:I?.paymentMethodCategory??pd(i),tokenizedData:ot,accountData:{...I?.accountPatch,userId:G.userId??"",email:G.email??"",firstName:G.firstName||void 0,lastName:G.lastName||void 0,...$?(()=>{let vt=gt.current,Hn=(0,p.isAVSFieldVisible)($.state,vt),vn=(0,p.isAVSFieldVisible)($.address_line_1,vt),Jt=(0,p.isAVSFieldVisible)($.postal_code,vt),Lr=vn&&!Hn&&Jt?(0,p.getStateFromPostalCode)(vt,(ft.current??"").trim()):null,Ro=Hn?kt.current:Lr;return{country:vt,...Jt&&ft.current?{zip:ft.current}:{},...(0,p.isAVSFieldVisible)($.city,vt)&&Ft.current?{city:Ft.current}:{},...Ro?{state:Ro}:{},...vn&&cn.current?{addressLine1:cn.current}:{},...(0,p.isAVSFieldVisible)($.address_line_2,vt)&&dn.current?{addressLine2:dn.current}:{}}})():{}},chv:v,avsCheck:X??!1,checkoutType:Y,checkoutLayout:Z,avsConfig:$?{country:(0,p.isAVSFieldVisible)($.country,gt.current),postal_code:(0,p.isAVSFieldVisible)($.postal_code,gt.current),address_line_1:(0,p.isAVSFieldVisible)($.address_line_1,gt.current),address_line_2:(0,p.isAVSFieldVisible)($.address_line_2,gt.current),city:(0,p.isAVSFieldVisible)($.city,gt.current),state:(0,p.isAVSFieldVisible)($.state,gt.current)}:void 0});if(zt.ok){let vt=zt.status===204?null:await zt.json().catch(()=>null),Hn=(0,p.isAuthorizationOnlySession)(z)||vt?.status==="authorized";lo(W),P("success"),bt(null),await new Promise(Lr=>setTimeout(Lr,600));let vn;typeof vt?.paymentId=="string"?vn=vt.paymentId:z?.paymentId&&(vn=z.paymentId);let Jt;typeof vt?.authorizationExpiresAt=="string"?Jt=vt.authorizationExpiresAt:z?.authorizationExpiresAt&&(Jt=z.authorizationExpiresAt),l?.(Hn?{status:"authorized",...vn===void 0?{}:{paymentId:vn},sessionId:typeof vt?.sessionId=="string"?vt.sessionId:W,...Jt===void 0?{}:{authorizationExpiresAt:Jt},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:ct,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:ct,checkoutMethod:i.isPaypal?"paypal":"card"});return}let Tt=await zt.json().catch(()=>null);if(Tt?.type==="paypal_redirect_required"){let vt=Tt.threeDSecureToken,Hn=Tt.paymentMethodId||i.id||"";if(!wt||!vt){P("error"),Pe("PayPal authorization required but no token provided.");return}try{let vn=rt?.getRawProvider();if(!vn){Pe("PayPal is not available.");return}let Jt={return_url:window.location.href};Hn&&(Jt.payment_method=Hn);let{error:Lr}=await vn.confirmPayment({clientSecret:vt,confirmParams:Jt,redirect:"if_required"});if(Lr){P("error");let Ro=Lr.message??"PayPal payment failed.";Pe(Ro),mr("paypal",Ro,{code:Lr.code})}}catch(vn){P("error"),Pe(vn instanceof Error?vn.message:"PayPal authorization failed.")}return}if(Tt?.type==="paypal_direct_required"){let vt=Tt.orderId;if(!vt){P("error"),Pe("PayPal retry required but no order id provided.");return}let Hn=xe.current?.attempts??0;if(Hn>=2){P("error"),Pe("PayPal payment could not be completed after multiple attempts."),mr("paypal","paypal_direct_required retry limit exceeded");return}Ua(!1),qa("loading"),bt({orderId:vt,attempts:Hn+1}),P(null);return}(0,p.classifyPaymentRejection)(zt.status,Tt)||Rt(),P("error");let Wn=Tt?.message??"Payment failed. Please try again.";Pe(Wn),mr(i.isPaypal?"paypal":"card",Wn,{code:Tt?.code??Tt?.gatewayErrorCode,declineCode:Tt?.declineCode??Tt?.gatewayDeclineReason}),await new Promise(vt=>setTimeout(vt,400))}catch(Mt){dl(Mt)||Rt(),P("error"),Pe(Mt instanceof Error?Mt.message:"An unexpected error occurred"),await new Promise(zt=>setTimeout(zt,400))}finally{dt(!1),P(null),D.current=!1}},[Q,e,t,q,$,X,Y,Z,v,wt,rt,z,l,Pe,mr,$e]),_n=(0,s.useCallback)((i,I)=>{g?g(i):ts(i,I)},[g,ts]),Co=`${ll}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(Co);if(!i)return;let I;try{I=JSON.parse(i)}catch{localStorage.removeItem(Co);return}if(!I||typeof I.createdAt!="number"||Date.now()-I.createdAt<0||Date.now()-I.createdAt>cl||typeof I.paymentMethodId!="string"||typeof I.providerIntentId!="string"||typeof I.paymentMethodType!="string"||I.sessionId!==e||!t||I.nonce!==t||!Kr.includes(I.paymentMethodType)){localStorage.removeItem(Co);return}localStorage.removeItem(Co),_n({id:I.paymentMethodId,type:"card",threeDSecureActionResultTokenId:I.providerIntentId,gateway:"stripe",paymentMethodType:I.paymentMethodType},{...I.accountPatch?{accountPatch:I.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[_n,t,e,Co,Kr]);let ns=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||ns.current)return;let i=new URLSearchParams(window.location.search),I=i.get("payment_intent"),W=i.get("payment_intent_client_secret"),Ue=i.get("redirect_status");if(!I||!W||!wt)return;let G=wt.getRawProvider();if(!G)return;let ct=Tt=>{let Wn=localStorage.getItem(Tt);if(!Wn)return null;try{return JSON.parse(Wn)}catch{return localStorage.removeItem(Tt),null}},ot=ct(hr)??ct(Js),it;if(ot?.clientSecret){if(ot.clientSecret!==W)return;it={...ot.accountPatch?{accountPatch:ot.accountPatch}:{},...ot.sessionId?{sessionId:ot.sessionId}:{},...ot.nonce?{nonce:ot.nonce}:{}}}else if(ot?.sessionId&&ot.sessionId!==e)return;ns.current=!0,localStorage.removeItem(hr),localStorage.removeItem(Js);let Rt=new URL(window.location.href);Rt.searchParams.delete("payment_intent"),Rt.searchParams.delete("payment_intent_client_secret"),Rt.searchParams.delete("redirect_status"),window.history.replaceState({},"",Rt.toString());let Mt=ot?.paymentMethodType??ot?.tokenType??"card",zt="card";(async()=>{if(Ue==="failed"){let Jt="Payment was declined. Please try again.";Pe(Jt),mr(zt,Jt);return}let{paymentIntent:Tt,error:Wn}=await G.retrievePaymentIntent(W);if(Wn){let Jt=Wn.message??"Failed to retrieve payment status.";Pe(Jt),mr(zt,Jt,{code:Wn.code});return}let vt=Tt?.status,Hn=Eo(vt);if(!Tt||!Hn){let Jt=vt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Pe(Jt),mr(zt,Jt,{code:vt??"missing_payment_intent"});return}let vn=typeof Tt.payment_method=="string"?Tt.payment_method:Tt.payment_method?.id;_n({id:vn??ot?.paymentMethodId??ot?.tokenId??Tt.id,type:"card",threeDSecureActionResultTokenId:Tt.id,gateway:ot?.gateway??"stripe",paymentMethodType:Mt},it)})()},[e,_n,wt,Pe,mr]);let Va=(0,s.useCallback)(i=>{i.preventDefault()},[]);if(!(We||wt!==null))return(0,c.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let So=j==="buttons",En=F?.variables,Ol=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ja=En?.colorBackground,zl=ja&&!Ol.has(ja)?ja:void 0,wo=u.cardInputBorder??(So?"#e5e7eb":"#A4A4FF"),rs=En?.colorDanger??"#dc2626",Ot=i=>Br[i]&&(ur[i]||_r),Zo=ge&&(zn||_r),Kn=i=>i?rs:wo,Qo=(yn.malformed||yn.empty)&&(Er||_r),Ul=Kn(Qo),Ka=u.cardFormContainer?.backgroundColor??zl??(So?"white":"#EDEDFF"),Hr=u.cardInputBackground??En?.colorBackground??"white",Wa=Jr(Me),os=Jr(pe),Gr=u.nameInput,as=u.cardInputFontSize??bd(Gr?.fontSize)??En?.fontSizeBase??"16px",is=typeof Gr?.fontFamily=="string"?Gr.fontFamily:En?.fontFamily??"Poppins, sans-serif",ss=mi(Gr?.fontWeight)??400,ql=u.cardInputColor??(typeof Gr?.color=="string"?Gr.color:void 0)??En?.colorText??"#262833",$l=u.cardInputPlaceholderColor??"#9ca3af",Vt=En?.borderRadius??"8px",Dr=En?.borderRadius??u.cardButton?.borderRadius??Vt,Nr=En?.colorPrimary??"#4A49FF",Vl=En?.colorPrimaryHover??mo(Nr,.12),Ha=En?.colorText??"#262833",Ga={fontSize:as,fontFamily:is,fontWeight:ss,color:ql,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ko={marginTop:"0.375rem",...Ga,fontSize:"0.75rem",lineHeight:1.4,color:rs},jl={"--flopay-input-placeholder-color":$l,"--flopay-input-font-size":as,"--flopay-input-font-family":is,"--flopay-input-font-weight":String(ss)},Io=u.cardFormContainer??{},Ya=Io.padding??(So?"0":"1rem"),Ja=Io.borderRadius??Vt,Kl=lt&&Rn?(0,c.jsx)(po,{capture:lt,html:Rn.html,messageToken:Rn.messageToken,expectedOrigin:Rn.expectedOrigin,theme:Ne,onReady:()=>{if(!_e&&!$||typeof document>"u")return;let i=()=>{let W=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(W){Qn.current=!0;try{W.focus()}finally{Qn.current=!1}}};er.current||i()},onError:i=>Pe(i),onValidation:i=>{let I=V.current;(I==="idle"||I==="validation-window")&&(Pe(i),i&&V.current==="validation-window"&&(O.current&&(clearTimeout(O.current),O.current=null),V.current="idle",P(null)))}}):(0,c.jsx)("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"}),ls=(0,c.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&$n()},style:{backgroundColor:Ka,borderRadius:Ja,...Io,padding:Ya,...jl,display:"flex",flexDirection:"column"},children:[(0,c.jsx)("style",{children:`
|
|
31
31
|
.flopay-shared-input::placeholder {
|
|
32
32
|
color: var(--flopay-input-placeholder-color);
|
|
33
33
|
opacity: 1;
|
|
@@ -35,13 +35,13 @@ ${dn.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),
|
|
39
|
-
`)}):null,
|
|
40
|
-
`)}):null,es=Ue==="apm-expanding"||Ue==="apm-form"||Ue==="apm-collapsing",Jr;Ue==="apm-expanding"?Jr=Us:Ue==="apm-collapsing"&&(Jr=qs);let ea=Ft?el(Da,Ft):null;if(se==="buttons"){let i=Ue==="buttons"||Ue==="expanding"||Ue==="apm-expanding",S=Ue==="expanding"||Ue==="card"||Ue==="collapsing",V=st===void 0?{boxSizing:"border-box",height:Sa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Fe;Ue==="expanding"||Ue==="apm-expanding"?Fe=Hc:(Ue==="collapsing"||Ue==="apm-collapsing")&&(Fe=Kc);let Y;return Ue==="expanding"?Y=Us:Ue==="collapsing"&&(Y=qs),(0,d.jsxs)("form",{onSubmit:za,className:h,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(mi,{}),gn&&(0,d.jsx)(Xn,{status:gn,errorMessage:M,authorized:ot}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Fe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Fe?Gc:{},...Fe?{animation:Fe,pointerEvents:"none"}:{}},children:[Zi("flopay-direct-paypal-gate-debug"),Qi("flopay-stripe-gate-debug"),ho&&be&&(0,d.jsxs)(d.Fragment,{children:[U&&(0,d.jsx)("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."}),(0,d.jsx)(Mo,{sessionId:e,nonce:t,billingApiUrl:Ie,email:g.email,billingName:ae||void 0,onBuyerIdentityReady:W,clientId:be.clientId,environment:be.environment,currency:ze.toUpperCase(),isSubscription:Xe,providerObjectType:P,approvalPresentation:Yo==="popup"?void 0:Yo,onTokenizedBody:Bn,onComplete:a,onErrorChange:Q,onDecline:c,onTechnicalFailure:Kr,onButtonClick:te,runBeforeButtonClick:nr,isProcessing:v,onLoadStateChange:La,onInitializationStateChange:Na,session:St,existingOrderId:U?.orderId,debug:D},U?.orderId??"fresh")]}),bo&&(0,d.jsx)(Ht.Elements,{stripe:an,options:Ge,children:(0,d.jsx)(Ks,{sessionId:e,nonce:t,email:g.email,billingName:ae||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,onTokenizedBody:Bn,onErrorChange:Q,isProcessing:v,onButtonClick:te,onDecline:c,onTechnicalFailure:Kr,runBeforeButtonClick:nr,onLoadStateChange:Ai,placeholderBorderRadius:Fr})}),Wr?(0,d.jsx)(Ht.Elements,{stripe:Dt,options:Rn,children:(0,d.jsx)(Hs,{sessionId:e,nonce:t,email:g.email,billingName:ae||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,intentKind:$>0?"payment":"setup",expressMethods:Hr,onTokenizedBody:Bn,onErrorChange:Q,onButtonClick:te,onDecline:c,onTechnicalFailure:Kr,runBeforeButtonClick:nr,onLoadStateChange:Bi,placeholderBorderRadius:Fr})}):null,!Wr&&Oi?(0,d.jsx)("div",{style:{height:Sa,borderRadius:Fr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,vo&&(0,d.jsx)(Ws,{sessionId:e,nonce:t,email:g.email,billingName:[g.firstName,g.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,paymentElementMethods:Wo,stripeInstance:Dt,paymentElementBaseOptions:Da,onTokenizedBody:Bn,onErrorChange:Q,onButtonClick:te,onDecline:c,runBeforeButtonClick:nr,onLoadStateChange:Di,isProcessing:v,submitButtonColor:Dr,submitButtonBorderRadius:Kt,submitButtonStyle:k.submitButton,onExpandApm:Hn,expandedApmMethod:Ft,themeId:ee,buttonAppearance:{backgroundColor:k.cardButton?.backgroundColor,borderColor:k.cardInputBorder,textColor:k.cardButton?.color,borderRadius:Fr}}),tt&&(0,d.jsx)("button",{type:"button",onClick:async()=>{v||!(await nr("card")).proceed||(te?.("card"),lr())},disabled:v,style:{width:"100%",...V,...k.cardButton,...hi({themeBundle:ge,resolvedPrimaryColor:Dr,resolvedBorderRadius:Kt,submitButtonStyle:k.submitButton,explicitPrimaryColor:Fn?.colorPrimary}),fontSize:k.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:v?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:v?.6:1},onMouseEnter:Pe=>{!v&&(ge||Fn?.colorPrimary)&&(Pe.currentTarget.style.backgroundColor=Tl)},onMouseLeave:Pe=>{(ge||Fn?.colorPrimary)&&(Pe.currentTarget.style.backgroundColor=Dr)},onMouseDown:Pe=>{Pe.currentTarget.style.transform="scale(0.985)"},onMouseUp:Pe=>{Pe.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(Zr,{content:st})}),M&&Ue==="buttons"&&(0,d.jsx)(io,{margin:"0.25rem 0",styleOverride:k.errorBanner,children:M})]}),tt&&S&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Y?{animation:Y}:{},...Ue==="collapsing"?{pointerEvents:"none"}:{}},children:Xi}),K&&es&&Ft&&ea&&Dt&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Jr?{animation:Jr}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:qa,borderRadius:Ha,...ko,padding:Ka},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:cr,style:{display:"inline-flex",alignItems:"center",gap:$a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:k.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...k.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...k.backButtonIcon},children:(0,d.jsx)("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:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Qr,{content:Se})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:k.titleFontSize??"1.05rem",color:ja,paddingRight:80,...k.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Ft)}`})]}),(0,d.jsx)(Ht.Elements,{stripe:Dt,options:ea,children:(0,d.jsx)(fi,{method:Ft,sessionId:e,nonce:t,email:g.email,billingName:[g.firstName,g.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,onTokenizedBody:Bn,onErrorChange:Q,onDecline:c,onCancel:cr,runBeforeButtonClick:nr,onButtonClick:te,isProcessing:v,submitButtonColor:Dr,submitButtonBorderRadius:Kt,submitButtonStyle:k.submitButton,errorText:M})},Ft)]})})]})]})}return es&&Ft&&ea&&Dt&&K?(0,d.jsxs)("form",{onSubmit:za,className:h,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(mi,{}),gn&&(0,d.jsx)(Xn,{status:gn,errorMessage:M,authorized:ot}),(0,d.jsx)("div",{style:{...Jr?{animation:Jr}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:qa,borderRadius:Ha,...ko,padding:Ka},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:cr,style:{display:"inline-flex",alignItems:"center",gap:$a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:k.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...k.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...k.backButtonIcon},children:(0,d.jsx)("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:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Qr,{content:Se})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:k.titleFontSize??"1.05rem",color:ja,paddingRight:80,...k.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Ft)}`})]}),(0,d.jsx)(Ht.Elements,{stripe:Dt,options:ea,children:(0,d.jsx)(fi,{method:Ft,sessionId:e,nonce:t,email:g.email,billingName:[g.firstName,g.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,onTokenizedBody:Bn,onErrorChange:Q,onDecline:c,onCancel:cr,runBeforeButtonClick:nr,onButtonClick:te,isProcessing:v,submitButtonColor:Dr,submitButtonBorderRadius:Kt,submitButtonStyle:k.submitButton,errorText:M})},Ft)]})})]}):(0,d.jsxs)("form",{onSubmit:za,className:h,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(mi,{}),gn&&(0,d.jsx)(Xn,{status:gn,errorMessage:M,authorized:ot}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Zi("flopay-direct-paypal-gate-debug-default"),Qi("flopay-stripe-gate-debug-default"),ho&&be&&(0,d.jsxs)(d.Fragment,{children:[U&&(0,d.jsx)("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."}),(0,d.jsx)(Mo,{sessionId:e,nonce:t,billingApiUrl:Ie,email:g.email,billingName:ae||void 0,onBuyerIdentityReady:W,clientId:be.clientId,environment:be.environment,currency:ze.toUpperCase(),isSubscription:Xe,providerObjectType:P,approvalPresentation:Yo==="popup"?void 0:Yo,onTokenizedBody:Bn,onComplete:a,onErrorChange:Q,onDecline:c,onTechnicalFailure:Kr,onButtonClick:te,runBeforeButtonClick:nr,isProcessing:v,onLoadStateChange:La,onInitializationStateChange:Na,session:St,existingOrderId:U?.orderId,debug:D},U?.orderId??"fresh")]}),bo&&(0,d.jsx)(Ht.Elements,{stripe:an,options:Ge,children:(0,d.jsx)(Ks,{sessionId:e,nonce:t,email:g.email,billingName:ae||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,onTokenizedBody:Bn,onErrorChange:Q,isProcessing:v,onButtonClick:te,onDecline:c,onTechnicalFailure:Kr,runBeforeButtonClick:nr,onLoadStateChange:Ai,placeholderBorderRadius:Fr})}),Wr&&(0,d.jsx)(Ht.Elements,{stripe:Dt,options:Rn,children:(0,d.jsx)(Hs,{sessionId:e,nonce:t,email:g.email,billingName:ae||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,intentKind:$>0?"payment":"setup",expressMethods:Hr,onTokenizedBody:Bn,onErrorChange:Q,onButtonClick:te,onDecline:c,onTechnicalFailure:Kr,runBeforeButtonClick:nr,onLoadStateChange:Bi,placeholderBorderRadius:Fr})}),vo&&(0,d.jsx)(Ws,{sessionId:e,nonce:t,email:g.email,billingName:[g.firstName,g.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Ie,paymentElementMethods:Wo,stripeInstance:Dt,paymentElementBaseOptions:Da,onTokenizedBody:Bn,onErrorChange:Q,onButtonClick:te,onDecline:c,runBeforeButtonClick:nr,onLoadStateChange:Di,isProcessing:v,submitButtonColor:Dr,submitButtonBorderRadius:Kt,submitButtonStyle:k.submitButton,themeId:ee,onExpandApm:Hn,expandedApmMethod:Ft,buttonAppearance:{backgroundColor:k.cardButton?.backgroundColor,borderColor:k.cardInputBorder,textColor:k.cardButton?.color,borderRadius:Fr}})]}),tt&&(Sl||Cl||wl)&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,d.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,d.jsx)("span",{children:"or pay with card"}),(0,d.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),tt&&Xi]})}var R=require("react/jsx-runtime"),jr=44,ki="flopay_checkout_saved_payment_resume",Ea=new Map,Ra=new Map;function tl(e,t){t.settled&&t.consumers===0&&Ea.get(e)===t&&Ea.delete(e)}function od(e,t,n){let r=Ra.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Ra.set(e,a);let l=()=>{Ra.get(e)===a&&Ra.delete(e)};return o.then(l,l),o}function $o(e){return new Promise(t=>setTimeout(t,e))}function _a(e,t,n){let r=ca({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:De.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function jo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function bi(e,t,n,r,o,a){let l=_a(e,t,n);l.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),jo(l)}function nl(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 rl(e,t,n,r,o){let a=(0,De.classifyTelemetryFailure)(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:a.statusClass}),t instanceof De.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof De.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):a.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...a,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function wi(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 vi(e){return!e||e.data.stripe?.publishableKey?!1:!!wi(e)?.clientId}var ad={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function id(e){return new Rr.FloPay(ad,{publishableKey:"provider_unavailable",...e})}async function Pi(e,t){let{publishableKey:n,paypalPublishableKey:r}=si(e);return{...await li({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Ii(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function sd(){if(!Ii())return null;try{let e=window.sessionStorage.getItem(ki);return e?JSON.parse(e):null}catch{return null}}function ol(e){if(Ii())try{window.sessionStorage.setItem(ki,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ci(){if(Ii())try{window.sessionStorage.removeItem(ki)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function ld(){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 al(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 Si(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function cd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function il(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function dd(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 Ta({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:c,error:f,onComplete:y,onError:p,onInstrument:b,onDecline:h,onCountryChange:w,onZipChange:B,showPayPal:N=!0,showStripe:de=!0,enabledPaymentMethods:K,showApplePay:I=!0,showGooglePay:re=!0,debug:q=!1,layout:ie,theme:se,buttonsTheme:ee,buttonsStyles:Oe,cardButtonContent:ue,cardBackButtonContent:Ct,cardTitleContent:st,showSecurityFooter:Se,onButtonClick:Re,onBeforeButtonClick:he,enableAVS:te,cardFieldOrder:Te,cardPreFormSlot:fe,avsLayout:we,className:xe,initialErrorMessage:Le=null,children:_e,checkoutMode:_,confirmLabel:oe,renderConfirmButton:me,onSessionCompleted:J}){let O=(0,De.resolveBillingApiUrl)(r),Ce=(0,C.useMemo)(()=>(0,De.resolveTheme)(se),[se]),Ke=a??Ce?.appearance,_t=n?"embedded_checkout":"standard_checkout",Qe=Si(_e,ie),[Z,X]=(0,C.useState)(null),[$,ze]=(0,C.useState)(null),Je=(0,C.useRef)(null),be=(0,C.useRef)(null),Xe=(0,C.useRef)(0),[H,z]=(0,C.useState)(null),rt=(0,C.useRef)(null),[D,j]=(0,C.useState)(null),qe=(0,C.useMemo)(()=>n?lo(n):"",[n]),ve=n?`create:${qe}`:`session:${e??""}`,Bt=il(D),St=(0,C.useRef)(new Set),P=(0,C.useRef)(ve),F=(0,C.useRef)(ve);Ur(()=>{F.current=ve,P.current!==ve&&(P.current=ve,St.current.clear())},[ve]);let qt=(0,C.useCallback)(A=>{if(F.current===ve){if(Za.has(A.name)){if(St.current.has(A.name))return;St.current.add(A.name)}nt(()=>b?.(A))}},[ve,b]),Ae=ao(qt,ve),Et=(0,C.useRef)(!1),tn=(0,C.useCallback)(A=>{if(Et.current)return;let x=A.gateway||!Bt?A:{...A,gateway:Bt};qt(x)},[qt,Bt]);(0,C.useEffect)(()=>{Ae({class:"lifecycle",name:"checkout.mount"})},[Ae]);let[et,nn]=(0,C.useState)(e??""),lt=e??et,Wt=n?"":lt,[dn,rn]=(0,C.useState)(!0),[ke,hn]=(0,C.useState)(null),[bn,$e]=(0,C.useState)(0),[ct,un]=(0,C.useState)("full"),[Gt,pn]=(0,C.useState)(!1),[$t,wt]=(0,C.useState)(Le),[Qn,kt]=(0,C.useState)(null),[vn,ht]=(0,C.useState)(null),[Yt,dt]=(0,C.useState)(!1),[Tt,Pn]=(0,C.useState)(void 0),[Jt,Cn]=(0,C.useState)(""),[ut,E]=(0,C.useState)(!1),[xt,ot]=(0,C.useState)(!1),[Xt,on]=(0,C.useState)(!1),Ln=(0,C.useRef)(0),Tn=(0,C.useRef)(void 0),[Zt,tt]=(0,C.useState)("loading"),[Tr,xr]=(0,C.useState)(0),Un=(0,C.useRef)(!1),Ar=(0,C.useRef)(!1),qn=(0,C.useRef)(!1),pt=(0,C.useRef)(null),L=(0,C.useMemo)(()=>({checkoutMode:_??ct,layout:cd(_e,ie)}),[_,_e,ct,ie]),mt=(0,C.useRef)(y);mt.current=y;let pe=(0,C.useRef)(p);pe.current=p;let xn=(0,C.useRef)(h);xn.current=h;let Sn=(0,C.useCallback)((A,x)=>{Je.current=A,ze(A),rt.current=x,z(x)},[]),wn=(0,C.useCallback)(()=>{let A=be.current;A&&(be.current=null,A.destroy())},[]);(0,C.useEffect)(()=>{sn($)?.setCheckoutContext(L),H&&H!==$&&sn(H)?.setCheckoutContext(L)},[$,H,L]);let hr=(0,C.useRef)(J);hr.current=J;let at=(0,C.useCallback)(A=>{tt(A),!(A!=="exhausted"||qn.current)&&(qn.current=!0,pe.current?.(new De.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Mr=(0,C.useCallback)(()=>{tt("retrying"),xr(A=>A+1)},[]);(0,C.useEffect)(()=>{tt("loading"),xr(0),qn.current=!1},[lt]),(0,C.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:De.SDK_VERSION,checkout_type:_t,checkout_layout:Qe,billing_api_url:O})},[Qe,_t,O]);let er=(0,C.useMemo)(()=>n?lo(n,!0):"",[n]),Br=(0,C.useMemo)(()=>Jt===er?Tt:void 0,[Tt,Jt,er]),$n=(0,C.useMemo)(()=>n?Ga(n,Br):void 0,[n,Br]),jn=_??$n?.checkoutMode??"full",jt=(0,C.useMemo)(()=>$n?{...$n,checkoutMode:jn}:void 0,[$n,jn]);(0,C.useEffect)(()=>{Pn(void 0),Cn(er),Tn.current=void 0,on(!1)},[er]),(0,C.useEffect)(()=>{wt(Le)},[Le]);let bt=(0,C.useCallback)((A,x,U)=>{nt(()=>{xn.current?.(cn(A,x,U))})},[]),Nn=(0,C.useCallback)(async(A,x)=>{wt(null),ht(null),dt(!1),kt("processing");let U=x?.sessionId??A.id,ne=il(A),He=Je.current??rt.current,Ie=sn(He),ye=He?null:_a(O,o,L),le={log:m=>{Ie?Ie.log(m):ye?.log(m)},error:m=>{Ie?Ie.error(m):ye?.error(m)},terminal:m=>{Ie?Ie.terminal(m):ye?.terminal(m)},performance:m=>{Ie?Ie.performance(m):ye?.performance(m)},now:()=>Ie?.now()??ye?.now()??0,elapsed:m=>Ie?.elapsed(m)??Math.max(0,(ye?.now()??m)-m)},W=le.now(),M=!!(x?.initialAutoProcessingError||x?.initialAutoProcessingPending),ge=!1,k,G=()=>{ge||(ge=!0,M=!0,k=le.now(),le.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),le.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ze=!1,Vt=()=>{Ze||(Ze=!0,le.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),le.performance({stage:"processing",durationMs:le.elapsed(W),durationMode:"machine",paymentMethodCategory:"saved"}),k!==void 0&&le.performance({stage:"recovery",durationMs:le.elapsed(k),durationMode:"machine",paymentMethodCategory:"saved"}))};le.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Et.current=!0;try{le.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Et.current=!1}Ae({class:"lifecycle",name:"payment.processing.started",provider:ne}),M&&G();let v;try{let m=ks(x?.initialAutoProcessingError),g;if(m)G(),m.type==="paypal_redirect_required"&&pt.current?.publishableKey&&ol({sessionId:U,publishableKey:pt.current.publishableKey,paypalPublishableKey:pt.current.paypalPublishableKey}),g=await va(m,{flopay:Je.current,paypalFlopay:rt.current,attempt3DS:x?.attempt3DS,billingApiUrl:O,sessionId:U,session:A,telemetry:!1}),m.type==="paypal_redirect_required"&&Ci();else if(x?.initialAutoProcessingPending){let ce=(await new Rr.PaymentAPI(O,{telemetry:!1}).waitForCheckoutSessionCompletion(x.initialAutoProcessingPending.sessionId,{initialDelayMs:x.initialAutoProcessingPending.retryAfterMs})).data.session;if(!to(ce))throw oa(ce);g=Or(ce,U)}else{if(x?.initialAutoProcessingError)throw Er(x.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:x.initialAutoProcessingError.checkoutMethod});if(x?.fromCreateSession)return x?.fallbackToFull&&(un("full"),al("full")),!1;{let ae=await po({billingApiUrl:O,sessionId:U,session:A,telemetry:!1});ae.type==="success"?g=ae.result:(G(),ae.type==="paypal_redirect_required"&&pt.current?.publishableKey&&ol({sessionId:U,publishableKey:pt.current.publishableKey,paypalPublishableKey:pt.current.paypalPublishableKey}),g=await va(ae,{flopay:Je.current,paypalFlopay:rt.current,attempt3DS:x?.attempt3DS,billingApiUrl:O,sessionId:U,session:A,telemetry:!1}),ae.type==="paypal_redirect_required"&&Ci())}}U&&co(U),Vt(),M&&(le.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),le.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),le.terminal({outcome:g.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),dt(g.status==="authorized"),kt("success"),await $o(1200),v=()=>mt.current?.(g)}catch(m){let g=No(m),ae=g.checkoutMethod??Lo;wt(g.message),ht(g.message),dt(!1),x?.fallbackToFull&&(le.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),un("full"),al("full")),Vt();let Me=g.statusCode===void 0?void 0:(0,De.telemetryStatusClass)(g.statusCode,"unknown"),ce=Me==="4xx"?{requestCategory:"process_payment",statusClass:Me}:{},At=Me===void 0||Me==="4xx";if(At&&(g.telemetryOutcome==="payment_declined"||!!(g.declineCode||g.code?.toLowerCase().includes("declin"))))le.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...ce});else if(At&&(g.telemetryOutcome==="validation_rejected"||g.type==="validation_error"))le.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...ce});else{let Dt=(0,De.classifyTelemetryFailure)(m,M?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),an=g.telemetryRequestCategory??"process_payment";Et.current=!0;try{le.error({...Dt,...g.telemetryFailureCategory?{failureCategory:g.telemetryFailureCategory}:{},stage:M?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:an})}finally{Et.current=!1}Ae({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:an,provider:ne})}return nt(()=>pe.current?.(g)),bt(ae,g,{code:g.code,declineCode:g.declineCode}),kt("error"),await Promise.allSettled([$o(1500),x?.ensureProvidersReady?x.ensureProvidersReady():Promise.resolve()]),M&&(le.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),le.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Vt(),ye&&jo(ye),kt(null),ht(null)}return nt(v),!0},[bt,Ae,O,o,L]);(0,C.useEffect)(()=>{if(typeof window>"u"||Ar.current)return;let A=new URLSearchParams(window.location.search),x=A.get("payment_intent_client_secret");if(!x)return;let U=sd();U&&(Ar.current=!0,(async()=>{let ne,He=0;wt(null),ht(null),kt("processing"),pn(!0);try{if(A.get("redirect_status")==="failed")throw Object.assign(new De.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Ie,paypalFlopay:ye}=await li({publishableKey:U.publishableKey,paypalPublishableKey:U.paypalPublishableKey,billingApiUrl:O,locale:l,telemetry:o});ne=sn(ye??Ie),ne?.setCheckoutContext(L),He=ne?.now()??0,ne?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ne?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let le=(ye??Ie)?.getRawProvider();if(!le)throw Object.assign(new De.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:W,error:M}=await le.retrievePaymentIntent(x);if(M)throw Object.assign(new De.FloPayError(M.message??"Failed to retrieve PayPal payment status.","api_error",{code:M.code}),{checkoutMethod:"paypal"});let ge=cs(W?.status);if(!W||ge==="failed")throw Object.assign(new De.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let k=typeof W.payment_method=="string"?W.payment_method:W.payment_method?.id,G=ge;if(U.sessionId){let v=(await new Rr.PaymentAPI(O,{telemetry:!1}).getUnifiedCheckoutSession(U.sessionId)).data.session;if(v&&v.status!=="complete"){let m=await po({billingApiUrl:O,sessionId:U.sessionId,session:v,telemetry:!1,tokenizedData:{id:k??W.id,type:"card",threeDSecureActionResultTokenId:W.id,isPaypal:!0}});if(m.type!=="success")throw Object.assign(new De.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});G=m.result.status}}U.sessionId&&co(U.sessionId),ne?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ne?.performance({stage:"redirect_resume",durationMs:ne.elapsed(He),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ne?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),kt("success"),await $o(1200),nt(()=>mt.current?.({status:G,paymentIntentId:W.id,paymentMethodId:k,checkoutMethod:"paypal"}))}catch(Ie){let ye=No(Ie),le=ye.checkoutMethod??"paypal",W=!!(ye.declineCode||ye.code?.toLowerCase().includes("declin"));if(ne)ne.performance({stage:"redirect_resume",durationMs:ne.elapsed(He),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),W?ne.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ne.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(W){let M=_a(O,o,L);M.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),jo(M)}else bi(O,o,L,"REDIRECT_RESUME_FAILED","redirect_resume");wt(ye.message),ht(ye.message),nt(()=>pe.current?.(ye)),bt(le,ye,{code:ye.code,declineCode:ye.declineCode}),kt("error"),await $o(1500)}finally{Ci(),ld(),kt(null),ht(null),pn(!1)}})())},[bt,l,O,o,L]);let mn=(0,C.useRef)(null),On=(0,C.useMemo)(()=>jt?lo(jt):"",[jt]),fn=(0,C.useRef)(jt);fn.current=jt,(0,C.useEffect)(()=>{nn(e??"")},[e]),(0,C.useEffect)(()=>{Un.current=!1,wt(Le),ht(null),dt(!1),kt(null)},[On,Le,e]);async function Ue(A,x,U){let ne=_a(O,o,L),He=new Rr.PaymentAPI(O,{telemetry:!1}),Ie=!1;try{let ye=A.idempotencyKey===void 0?void 0:(0,De.resolveIdempotencyKey)(A.idempotencyKey),le=ni(x,U),W=ri(x,U);le?.canonicalIdentity===U&&W&&W.canonicalIdentity===void 0&&(ga(x,U,W.idempotencyKey),W={...W,canonicalIdentity:U});let M=ye??(W?.canonicalIdentity===U?W.idempotencyKey:void 0),ge,k=!1;ne.log({name:le?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let G=le?.sid??null,Ze=null,Vt,v,m=!1;if(G)try{Ze=await He.getUnifiedCheckoutSession(G,le?.nonce),le&&le.canonicalIdentity===void 0&&(Ps(Ze.data.session,A)?(fa(x,U,G,le.nonce??Ze.data.session?.clientSecret),W&&W.canonicalIdentity===void 0&&(ga(x,U,W.idempotencyKey),M??(M=W.idempotencyKey))):(ya(x,U),W=null,M=ye,G=null,Ze=null));let ae=Ze?.data.session?.status,Me=Ze?.data.session,ce=Me?.clientSecret||le?.nonce;if(G&&Me?.buyerIdentified===!1&&ce&&(v=eo(He,G,ce,A.account)),G&&Ze&&ae==="complete"){if(oi(G))return{sid:G,result:Ze};ya(x,U),G=null,Ze=null,k=!0}}catch{ne.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),le?.canonicalIdentity===void 0?(ya(x,U),M=ye):ma(x,U),G=null}if(!G){!ye&&(k||!M)&&(M=(0,De.resolveIdempotencyKey)(),ge=M),M&&ga(x,U,M);let ae=ne.now(),Me=0;ne.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ce={...A,idempotencyKey:M,avsCheck:!!te,avsConfig:typeof te=="object"?te:void 0,checkoutType:"embedded_checkout",checkoutLayout:Si(_e,ie)};Object.defineProperty(ce,Rr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:vt=>{Me=Math.max(Me,vt)}}});let At=()=>{nl(ne,"session_create",ae,Me)},In=vt=>{rl(ne,vt,"session_create",ae,Me)&&Ae({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,De.isDetachedSessionEligible)(ce)){let vt=await He.createDetachedSession(ce);vt.claimed.catch(()=>{}),Ze=vt.shell,G=vt.sessionId,v=vt.claim;let Dt=ne.now();ne.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Vt=vt.claimed.then(an=>{let Ee=an.data.session?.id??vt.sessionId;return Ee&&fa(x,U,Ee,an.data.session?.clientSecret??vt.nonce),nl(ne,"session_claim",Dt),At(),an},an=>{throw ma(x,U),rl(ne,an,"session_claim",Dt,0)&&Ae({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),an}).finally(()=>jo(ne)),Vt.catch(()=>{}),Ie=!0,ne.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),ne.performance({stage:"session_shell",durationMs:ne.now()-ae,durationMode:"machine",requestCategory:"session_create",attempt:Me,statusClass:"2xx",paymentMethodCategory:"card"})}else Ze=await He.createAndFetchSession(ce),At()}catch(vt){throw In(vt),vt}G=Ze.data.session?.id??G??"",G&&!Vt&&fa(x,U,G,Ze.data.session?.clientSecret)}let g=Ze?.data.session;return!v&&G&&g?.buyerIdentified===!1&&g.clientSecret&&(v=eo(He,G,g.clientSecret,A.account)),{sid:G??"",result:Ze,sdkGeneratedIdempotencyKey:ge,...Vt?{claimed:Vt}:{},...v?{claim:v}:{},...m?{claimRequiresIdentity:!0}:{}}}finally{Ie||jo(ne)}}let ln=(0,C.useRef)(Ue);Ur(()=>{ln.current=Ue},[Ue]);let Ft=(0,C.useCallback)(async(A,x)=>{let U=fn.current;if(!U)throw new De.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ne=Ga(U,A),He=lo(ne),Ie=vs(ne),ye=Ea.get(He);if(!ye){let M={canonicalIdentity:He,promise:ln.current(ne,Ie,He),consumers:0,settled:!1};ye=M,Ea.set(He,M);let ge=()=>{M.settled=!0,tl(He,M)};M.promise.then(ge,ge)}ye.consumers+=1;let le=!1,W=()=>{le||(le=!0,ye.consumers-=1,tl(He,ye))};x?.(W);try{let M=await ye.promise;mn.current=He,A&&(Cn(er),Pn(g=>is(g,A)));let{sid:ge,result:k,claimed:G,claim:Ze,claimRequiresIdentity:Vt}=M;if(Tn.current=Ze,on(Vt===!0),X(k),k.data.session&&j(k.data.session),ge&&nn(ge),G){Ln.current+=1;let g=Ln.current;ot(!0),G.then(ae=>{Ln.current===g&&(X(ae),ae.data.session&&j(ae.data.session),ot(!1),on(!1))},ae=>{Ln.current===g&&(ot(!1),on(!1),hn(ae instanceof De.FloPayError?ae:new De.FloPayError(ae instanceof Error?ae.message:"Failed to create session","api_error")))})}else Ln.current+=1,ot(!1),on(!1);let{flopay:v,paypalFlopay:m}=await Pi(k,{billingApiUrl:O,locale:l,telemetry:o});return Sn(v,m),rn(!1),M}catch(M){throw mn.current===He&&(mn.current=null),M}finally{x||W()}},[er,Sn,l,O,o]),Vn=(0,C.useRef)(Nn);Vn.current=Nn;let sr=(0,C.useRef)(Ft);sr.current=Ft;let br=(0,C.useCallback)(async A=>{if(!dd(A)||ut)return{sessionId:et,session:D};E(!0);try{let x=await Ft(A);return{sessionId:x.sid,session:x.result.data.session??null}}finally{E(!1)}},[Ft,ut,et,D]),Kn=(0,C.useCallback)(async A=>{let x=Tn.current;if(!x)return;let U=Ln.current,ne=await x(A);Ln.current===U&&(X(ne),ne.data.session&&j(ne.data.session))},[]);(0,C.useEffect)(()=>{let A=!1,x,U=++Xe.current;wn(),hn(null),$e(0);let ne=()=>{A=!0,Xe.current===U&&(Xe.current+=1,wn())},He=fn.current;if(On&&He)return un(jn),rn(!1),mn.current===On?ne:(j(ss(He,_)),(async()=>{let le=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),W=jn==="auto"&&!Un.current&&!le;W&&(wt(null),ht(null),kt("processing"));try{let M=await sr.current(void 0,Ze=>{x=Ze}),ge=M.result.data.session??null;pt.current=si(M.result);let k=vi(M.result),G=oi(M.sid||ge?.id);if(!A&&W&&ge&&!k&&!G){Un.current=!0,await od(On,M.sdkGeneratedIdempotencyKey,()=>Vn.current(ge,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:M.result.autoProcessingError,initialAutoProcessingPending:M.result.autoProcessingPending,autoProcessingAttempted:M.result.autoProcessingAttempted,sessionId:M.sid||ge.id}));return}!A&&W&&((k||G)&&(Un.current=!0),kt(null),ht(null))}catch(M){if(A)return;let ge=ra(M);if(W&&ge==="session_auto_completed"){Un.current=!0,kt("success"),await $o(1200),A||(nt(()=>{mt.current?.({status:"succeeded"})}),kt(null),ht(null));return}W&&(kt(null),ht(null));let k=M instanceof De.FloPayError?M:new De.FloPayError(M instanceof Error?M.message:"Failed to create session","api_error");hn(k)}finally{x?.(),x=void 0}})(),()=>{ne(),x?.()});rn(!0);async function Ie(){let le=!1,W=null;try{let M=new Rr.PaymentAPI(O,{telemetry:!1}),ge=await M.getUnifiedCheckoutSession(lt,t);if(W=ge,A)return;X(ge);let k=ge.data.session??null;if(j(k),!k)throw new De.FloPayError("No session data returned","api_error");let G=k.checkoutMode;if(G==="setup")throw new De.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(k.status==="authorized"){rn(!1),nt(()=>{mt.current?.(Or(k,lt)),hr.current?.(k.successUrl??"")});return}if(k.status==="complete"){rn(!1),nt(()=>{hr.current?.(k.successUrl??"")});return}if(k.status==="expired")throw na(k);le=!0;let Ze=_??G??"full";un(Ze),Ln.current+=1;let Vt=k.clientSecret||t;Tn.current=k.buyerIdentified===!1&&Vt?eo(M,lt,Vt,{...k.customer?.id?{userId:k.customer.id}:{}}):void 0,ot(!1),on(!1);let v=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),m=vi(ge);if(Ze==="auto"&&!Un.current&&!v&&!m){Un.current=!0;let g=ye(ge);try{if(await Vn.current(k,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>g,sessionId:lt||k.id}),A)return;await g,A||rn(!1);return}catch{if(A)return;await g,A||rn(!1);return}}await ye(ge),A||rn(!1)}catch(M){if(A)return;let ge=as(M,le);if(le&&Ae({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ge){let{errorCode:G,stage:Ze,...Vt}=ge;bi(O,o,L,G,Ze,Vt)}if(ge?.stage==="provider_load"&&(_??W?.data.session?.checkoutMode??"full")==="full"&&os(W,N,de)){let G=id({billingApiUrl:O,locale:l,telemetry:o});be.current=G,Sn(G,null),$e(1),rn(!1);return}let k=M instanceof De.FloPayError&&ge?.stage!=="provider_load"?M:rs();k!==M&&nt(()=>pe.current?.(k)),hn(k),rn(!1)}}async function ye(le){let{flopay:W,paypalFlopay:M,...ge}=await Pi(le,{billingApiUrl:O,locale:l,telemetry:o});pt.current={publishableKey:ge.publishableKey,paypalPublishableKey:ge.paypalPublishableKey},Sn(W,M),$e(0)}return Ie(),ne},[_,On,jn,Wt,t,N,de]);let An=(0,C.useCallback)(async()=>{if(!Z||bn!==1)return;let A=Xe.current;$e(2);try{let{flopay:x,paypalFlopay:U}=await Pi(Z,{billingApiUrl:O,locale:l,telemetry:o});if(Xe.current!==A)return;wn(),Sn(x,U),$e(0)}catch(x){if(Xe.current!==A)return;let{errorCode:U,stage:ne,...He}=Wa(x);bi(O,o,L,U,ne,He)}},[wn,Sn,l,bn,O,o,L,Z]),Mn=(0,C.useCallback)(async()=>{if(!(Gt||!D)){pn(!0),wt(null);try{await Nn(D,{attempt3DS:!0,fallbackToFull:!0,sessionId:lt||D.id})}finally{pn(!1)}}},[lt,Gt,Nn,D]),lr=wi(Z),Vr=vi(Z),Hn=(0,C.useMemo)(()=>{if(!(!Z||!D||!Z.data.stripe?.publishableKey))return{billingApiUrl:O}},[Z,D,O]),cr=!!(n&&!_e&&ie==="buttons"&&he&&jn==="full"),gn=(0,C.useMemo)(()=>({session:D,loading:dn,error:ke,checkoutMode:ct,inlineSessionDraft:jt,applyInlineSessionPatch:cr?br:void 0,inlineSessionPatchProcessing:ut,claimPending:xt,claimRequiresIdentity:Xt,claimBuyerIdentity:Kn}),[D,dn,ke,ct,jt,cr,br,ut,xt,Xt,Kn]),yt=!!n&&ie==="buttons"&&!Vr&&(!$||!Hn),kn=Qn?(0,R.jsx)(Xn,{status:Qn,errorMessage:vn,authorized:Yt}):null;if(dn){if(c)return(0,R.jsxs)(R.Fragment,{children:[c,kn]});if(ie==="buttons"){let A=Ce?.buttonsLayout?.cardButton?.borderRadius??Ce?.appearance.variables?.borderRadius??8,x=U=>(0,R.jsx)("div",{style:{height:U,borderRadius:A,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[N&&x(jr),de&&(I||re)&&x(jr),de&&x(jr),(0,R.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),kn]})}return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,R.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,R.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),kn]})}return ke?f?(0,R.jsx)(rr.Provider,{value:gn,children:f(ke)}):(0,R.jsx)(rr.Provider,{value:gn,children:(0,R.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:ke.message})}):yt?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(rr.Provider,{value:gn,children:(0,R.jsx)(pd,{onButtonClick:Re,showPayPal:N,showStripe:de,showApplePay:I,showGooglePay:re,theme:se,buttonsTheme:ee,buttonsStyles:Oe,cardButtonContent:ue,cardBackButtonContent:Ct,cardTitleContent:st})}),kn]}):Vr&&D&&lr?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(rr.Provider,{value:gn,children:(0,R.jsxs)("div",{className:xe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[$t&&(0,R.jsx)(io,{icon:!1,children:$t}),Zt==="retrying"&&(0,R.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Zt==="exhausted"&&(0,R.jsxs)("div",{role:"alert",children:[(0,R.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,R.jsx)("button",{type:"button",onClick:Mr,children:"Retry PayPal"})]}),xt?c??(0,R.jsx)("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:jr,borderRadius:8,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"},children:(0,R.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):Zt!=="exhausted"&&(0,R.jsx)("div",{"aria-hidden":Zt==="retrying"?!0:void 0,style:Zt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,R.jsx)(bs,{sessionId:lt,nonce:D.clientSecret||void 0,billingApiUrl:O,email:D.customer?.email||jt?.account?.email,billingName:[D.customer?.firstName,D.customer?.lastName].filter(Boolean).join(" ")||[jt?.account?.firstName,jt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Kn,clientId:lr.clientId,environment:lr.environment,currency:(D.currency??"usd").toUpperCase(),isSubscription:D.mode==="subscription",providerObjectType:lr.providerObjectType,approvalPresentation:lr.approvalPresentation,onComplete:y,onErrorChange:wt,onDecline:h,onButtonClick:Re,onInitializationStateChange:at,allowAutomaticRetry:Tr===0,session:D,telemetry:o,telemetryContext:L,onInstrument:tn,debug:q},`${ve}:paypal-init-${Tr}`)})]})}),kn]}):!$||!Hn?(0,R.jsx)(R.Fragment,{children:kn}):ct==="confirm"?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(rr.Provider,{value:gn,children:(0,R.jsx)(Fo,{flopay:$,paypalFlopay:H,options:Hn,onInstrument:tn,children:(0,R.jsxs)("div",{className:xe,children:[$t&&(0,R.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:$t}),me?me({onConfirm:Mn,isProcessing:Gt}):(0,R.jsx)("button",{type:"button",onClick:Mn,disabled:Gt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Gt?"not-allowed":"pointer",opacity:Gt?.6:1},children:Gt?"Processing...":oe??"Confirm Purchase"})]})},ve)}),kn]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(rr.Provider,{value:gn,children:(0,R.jsxs)(Fo,{flopay:$,paypalFlopay:H,options:Hn,onInstrument:tn,children:[bn===1&&(0,R.jsx)("button",{type:"button",onClick:An,children:"Retry payment methods"}),_e?(0,R.jsxs)(R.Fragment,{children:[$t&&(0,R.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:$t}),(0,R.jsx)(ud,{sessionId:lt,nonce:D?.clientSecret||void 0,billingApiUrl:O,session:D,children:_e})]}):(0,R.jsx)(Ia,{sessionId:lt,nonce:D?.clientSecret||void 0,email:D?.customer?.email||jt?.account?.email,userId:D?.customer?.id||jt?.account?.userId,firstName:D?.customer?.firstName||jt?.account?.firstName,lastName:D?.customer?.lastName||jt?.account?.lastName,totalAmount:D?Math.round((0,De.buildCheckoutDisplayData)(D).total*100):0,currency:D?.currency?.toLowerCase()??"usd",onComplete:y,onError:p,onDecline:h,error:$t,onErrorChange:wt,showPayPal:N,showStripe:de,enabledPaymentMethods:bn?[]:K??Z?.data.stripe?.enabledPaymentMethods??D?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Z?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:re,layout:ie,theme:se,buttonsTheme:ee,buttonsStyles:Oe,appearance:Ke,cardButtonContent:ue,cardBackButtonContent:Ct,cardTitleContent:st,onButtonClick:Re,onBeforeButtonClick:he,onBuyerIdentityReady:Kn,enableAVS:te,...Te?{cardFieldOrder:Te}:{},...fe?{cardPreFormSlot:fe}:{},avsLayout:we,country:D?.customer?.country,city:D?.customer?.city,state:D?.customer?.state,onCountryChange:w,onZipChange:B,avsCheck:!!te,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Si(_e,ie),className:xe,directPaypal:wi(Z),isSubscription:D?.mode==="subscription",session:D,dataAttachmentPending:xt,dataAttachmentRequiresIdentity:Xt,debug:q})]},ve)}),kn]})}function ud({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,R.jsx)(R.Fragment,{children:C.default.Children.map(o,a=>{if(!C.default.isValidElement(a))return a;let l=a.props,c={};return l.sessionId||(c.sessionId=e),!l.nonce&&t&&(c.nonce=t),l.billingApiUrl||(c.billingApiUrl=n),r?.customer&&(l.email||(c.email=r.customer.email),l.userId||(c.userId=r.customer.id),l.firstName||(c.firstName=r.customer.firstName),l.lastName||(c.lastName=r.customer.lastName)),Object.keys(c).length===0?a:C.default.cloneElement(a,c)})})}function pd({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:c,cardButtonContent:f,cardBackButtonContent:y,cardTitleContent:p}){let[b,h]=(0,C.useState)(!1),w=(0,C.useMemo)(()=>(0,De.resolveTheme)(a),[a]),B=(0,C.useMemo)(()=>{let I=w?.buttonsLayout??(0,De.resolveButtonsLayoutTheme)(l);return c?{...I,...c,cardButton:{...I.cardButton,...c.cardButton},cardFormContainer:{...I.cardFormContainer,...c.cardFormContainer},backButton:{...I.backButton,...c.backButton},backButtonIcon:{...I.backButtonIcon,...c.backButtonIcon},submitButton:{...I.submitButton,...c.submitButton},title:{...I.title,...c.title}}:I},[w,l,c]),N=w?.buttonsLayout?.cardButton?.borderRadius??w?.appearance.variables?.borderRadius??8,de=I=>(0,R.jsx)("div",{style:{height:I,borderRadius:N,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),K=f===void 0?{boxSizing:"border-box",height:jr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let I=B.cardInputBorder??"#e5e7eb",re=B.cardInputBackground??"white",q=Xr(y),ie=Xr(p);return(0,R.jsxs)("div",{style:{backgroundColor:B.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...B.cardFormContainer},children:[(0,R.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,R.jsxs)("button",{type:"button",onClick:()=>h(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...B.backButton},children:[(0,R.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...B.backButtonIcon},children:(0,R.jsx)("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:(0,R.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,R.jsx)(Qr,{content:y})]}),ie?(0,R.jsx)("div",{style:{flex:1}}):(0,R.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...B.title},children:(0,R.jsx)(Ro,{content:p})})]}),(0,R.jsx)("div",{style:{backgroundColor:re,border:`1px solid ${I}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsxs)("div",{style:{display:"flex"},children:[(0,R.jsx)("div",{style:{flex:1,backgroundColor:re,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsx)("div",{style:{flex:1,backgroundColor:re,borderTop:"none",borderRight:`1px solid ${I}`,borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,R.jsx)("div",{style:{backgroundColor:re,border:`1px solid ${I}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...B.submitButton,opacity:.5}}),(0,R.jsx)("style",{children:`
|
|
38
|
+
`}),So&&fo&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:We?-2:0},children:[(0,c.jsxs)("button",{type:"button",onClick:Ar,style:{display:"inline-flex",alignItems:"center",gap:Wa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:u.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...u.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...u.backButtonIcon},children:(0,c.jsx)("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:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(Zr,{content:Me})]}),os?(0,c.jsx)("div",{style:{flex:1}}):(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:u.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...u.title},children:(0,c.jsx)(_o,{content:pe})})]}),!So&&!os&&(0,c.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ha,order:We?-3:0,...u.title},children:(0,c.jsx)(_o,{content:pe})}),We&&Ke&&(0,c.jsx)("div",{style:{order:-2,width:"100%"},children:Ke}),We&&_e&&(0,c.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,c.jsx)("div",{style:{backgroundColor:Hr,border:`1px solid ${Kn(Zo)}`,borderRadius:Vt,padding:"10px"},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:yt,onChange:i=>{ht("email"),Nn.current=i.target.value,Sn(i.target.value)},onPointerDown:()=>ht("email"),onKeyDown:()=>ht("email"),onBlur:()=>{Un("email")&&Yt(!0),ge||Na()},disabled:R,required:!0,"aria-invalid":Zo||void 0,"aria-describedby":Zo?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ga}})}),Zo&&(0,c.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ko,children:ue.empty?"Email address is required":"Enter a valid email address"})]}),$&&(0,c.jsx)("div",{style:{order:We?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Et,I=(G=!1)=>({backgroundColor:Hr,border:`1px solid ${Kn(G)}`,borderRadius:Vt,marginTop:"0.5rem",padding:"10px"}),W=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ga}),Ue=(0,p.getStateOptions)(i);return(0,c.jsxs)(c.Fragment,{children:[(0,p.isAVSFieldVisible)($.address_line_1,i)&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("div",{style:I(Ot("line1")),children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Qt,onChange:G=>{ht("line1"),Gt.current.addressLine1=!0,cn.current=G.target.value,on(G.target.value)},onPointerDown:()=>ht("line1"),onKeyDown:()=>ht("line1"),onBlur:()=>In("line1"),disabled:R,required:!0,"aria-invalid":Ot("line1")||void 0,"aria-describedby":Ot("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:W()})}),Ot("line1")&&(0,c.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ko,children:"Street address is required"})]}),(0,p.isAVSFieldVisible)($.address_line_2,i)&&(0,c.jsx)("div",{style:I(),children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Fn,onChange:G=>{Gt.current.addressLine2=!0,dn.current=G.target.value,gn(G.target.value)},disabled:R,"data-testid":"flopay-address-line2",style:W()})}),((0,p.isAVSFieldVisible)($.city,i)||(0,p.isAVSFieldVisible)($.state,i))&&(0,c.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,p.isAVSFieldVisible)($.city,i)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Hr,borderTop:`1px solid ${Kn(Ot("city"))}`,borderRight:`1px solid ${Kn(Ot("city"))}`,borderBottom:`1px solid ${Kn(Ot("city"))}`,borderLeft:`1px solid ${Kn(Ot("city"))}`,padding:"10px",borderTopLeftRadius:Vt,borderBottomLeftRadius:Vt,...(0,p.isAVSFieldVisible)($.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Vt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Cn,onChange:G=>{ht("city"),Gt.current.city=!0,Ft.current=G.target.value,qt(G.target.value)},onPointerDown:()=>ht("city"),onKeyDown:()=>ht("city"),onBlur:()=>In("city"),disabled:R,required:!0,"aria-invalid":Ot("city")||void 0,"aria-describedby":Ot("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:W()})}),(0,p.isAVSFieldVisible)($.state,i)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Hr,borderTop:`1px solid ${Kn(Ot("state"))}`,borderRight:`1px solid ${Kn(Ot("state"))}`,borderBottom:`1px solid ${Kn(Ot("state"))}`,borderLeft:`1px solid ${Kn(Ot("state"))}`,padding:"10px",borderTopRightRadius:Vt,borderBottomRightRadius:Vt,...(0,p.isAVSFieldVisible)($.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Kn(Ot("state")||Ot("city"))}`}:{borderRadius:Vt}},children:Ue?(0,c.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:ve,onChange:G=>{ht("state"),Gt.current.state=!0,kt.current=G.target.value,ut(G.target.value)},onPointerDown:()=>ht("state"),onKeyDown:()=>ht("state"),onBlur:()=>In("state"),disabled:R,autoComplete:"billing address-level1",required:!0,"aria-invalid":Ot("state")||void 0,"aria-describedby":Ot("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...W(),cursor:"pointer"},children:[(0,c.jsx)("option",{value:"",children:(0,p.getStateLabel)(i)}),Ue.map(G=>(0,c.jsx)("option",{value:G.code,children:G.name},G.code))]}):(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,p.getStateLabel)(i),autoComplete:"billing address-level1",value:ve,onChange:G=>{ht("state"),Gt.current.state=!0,kt.current=G.target.value,ut(G.target.value)},onPointerDown:()=>ht("state"),onKeyDown:()=>ht("state"),onBlur:()=>In("state"),disabled:R,required:!0,"aria-invalid":Ot("state")||void 0,"aria-describedby":Ot("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:W()})})]}),Ot("city")&&(0,c.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ko,children:"City is required"}),Ot("state")&&(0,c.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ko,children:[(0,p.getStateLabel)(i)," is required"]}),((0,p.isAVSFieldVisible)($.country,i)||(0,p.isAVSFieldVisible)($.postal_code,i))&&(0,c.jsxs)("div",{style:{display:"flex",flexDirection:w==="column"?"column":"row",gap:w==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,p.isAVSFieldVisible)($.country,i)&&(0,c.jsx)("div",{style:{flex:w==="row"?1:void 0,backgroundColor:Hr,borderTop:`1px solid ${wo}`,borderRight:`1px solid ${wo}`,borderBottom:`1px solid ${wo}`,borderLeft:`1px solid ${wo}`,padding:"10px",...w==="row"&&(0,p.isAVSFieldVisible)($.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:Vt,borderBottomLeftRadius:Vt,borderRight:"none"}:{borderRadius:Vt}},children:(0,c.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Et,onChange:G=>{Gt.current.country=!0,gt.current=G.target.value,se(G.target.value),pt?.(G.target.value),kt.current="",ut("")},disabled:R,autoComplete:"billing country","data-testid":"flopay-country",style:{...W(),cursor:"pointer"},children:p.COUNTRY_OPTIONS.map(G=>(0,c.jsxs)("option",{value:G.code,children:[G.flag," ",G.name]},G.code))})}),(0,p.isAVSFieldVisible)($.postal_code,i)&&(0,c.jsx)("div",{style:{flex:w==="row"?1:void 0,backgroundColor:Hr,border:`1px solid ${Ul}`,padding:"10px",...w==="row"&&(0,p.isAVSFieldVisible)($.country,i)?{borderRadius:"0",borderTopRightRadius:Vt,borderBottomRightRadius:Vt}:{borderRadius:Vt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,p.getPostalCodeLabel)(Et),autoComplete:"billing postal-code",value:fn,onChange:G=>{ht("zip"),Gt.current.zip=!0,ft.current=G.target.value,An(G.target.value),Xe?.(G.target.value)},onPointerDown:()=>ht("zip"),onKeyDown:()=>ht("zip"),onBlur:()=>{Un("zip")&&Pr(!0)},disabled:R,required:yn.required,"aria-invalid":Qo||void 0,"aria-describedby":Qo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:W()})})]}),Qo&&(0,c.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ko,children:yn.empty?`${(0,p.getPostalCodeLabel)(i)} is required`:fd(i)})]})})()}),We&&Kl,ce&&(0,c.jsx)(ao,{margin:"0.75rem 0",styleOverride:u.errorBanner,children:ce})]}),ea={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"},cs=i=>St?!te||!fr?(0,c.jsx)("pre",{"data-testid":i,style:ea,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":i,style:ea,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${te}`,` directPaypalConfigured=${fr}`,` inAppBrowserDetected=${String(Yo)}`,` shouldRenderDirectPayPal=${bo}`,` shouldRenderStripePayPal=${vo}`,` hasPaypalStripeInstance=${!!Qe}`].join(`
|
|
39
|
+
`)}):null,ds=i=>St?!S||!ee?(0,c.jsx)("pre",{"data-testid":i,style:ea,children:"FloPay/Stripe-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":i,style:ea,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${S}`,` currency=${nt}`,` amountInCents=${tn}`,` enabledPaymentMethods: ${JSON.stringify(J??[])}`,` enabledPaymentMethodsProvided=${go}`,` hasEnabledMethods=${Wo}`,` expressMethods: ${JSON.stringify(Ho)}`,` walletExpressMethods: ${JSON.stringify(Kr)}`,` paymentElementMethods: ${JSON.stringify(ho)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Go)}`,` hasStripeInstance=${!!ee}`,` shouldRenderWallets=${Wr}`,` shouldRenderPaymentElement=${Po}`].join(`
|
|
40
|
+
`)}):null,us=Ze==="apm-expanding"||Ze==="apm-form"||Ze==="apm-collapsing",Yr;Ze==="apm-expanding"?Yr=el:Ze==="apm-collapsing"&&(Yr=tl);let ta=Wt?yl(za,Wt):null;if(j==="buttons"){let i=Ze==="buttons"||Ze==="expanding"||Ze==="apm-expanding",I=Ze==="expanding"||Ze==="card"||Ze==="collapsing",W=Fe===void 0?{boxSizing:"border-box",height:Ia,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ue;Ze==="expanding"||Ze==="apm-expanding"?Ue=cd:(Ze==="collapsing"||Ze==="apm-collapsing")&&(Ue=ld);let G;return Ze==="expanding"?G=el:Ze==="collapsing"&&(G=tl),(0,c.jsxs)("form",{onSubmit:Va,className:k,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(vi,{}),en&&(0,c.jsx)(Jn,{status:en,errorMessage:ce,authorized:Kt}),(0,c.jsxs)("div",{style:{display:"grid"},children:[(0,c.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Ue?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Ue?ud:{},...Ue?{animation:Ue,pointerEvents:"none"}:{}},children:[cs("flopay-direct-paypal-gate-debug"),ds("flopay-stripe-gate-debug"),bo&&ke&&(0,c.jsxs)(c.Fragment,{children:[De&&(0,c.jsx)("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."}),(0,c.jsx)(Bo,{sessionId:e,nonce:t,billingApiUrl:ze,email:q.email,billingName:It||void 0,onBuyerIdentityReady:x,clientId:ke.clientId,environment:ke.environment,currency:nt.toUpperCase(),isSubscription:Ye,providerObjectType:A,approvalPresentation:Jo==="popup"?void 0:Jo,onTokenizedBody:_n,onComplete:l,onErrorChange:Pe,onDecline:m,onTechnicalFailure:jr,onButtonClick:me,runBeforeButtonClick:or,isProcessing:R,onLoadStateChange:Ua,onInitializationStateChange:qa,session:f,existingOrderId:De?.orderId,debug:St},De?.orderId??"fresh")]}),vo&&(0,c.jsx)(jt.Elements,{stripe:Qe,options:Ni,children:(0,c.jsx)(al,{sessionId:e,nonce:t,email:q.email,billingName:It||void 0,onBuyerIdentityReady:x,billingApiUrl:ze,onTokenizedBody:_n,onErrorChange:Pe,isProcessing:R,onButtonClick:me,onDecline:m,onTechnicalFailure:jr,runBeforeButtonClick:or,onLoadStateChange:$i,placeholderBorderRadius:Dr})}),Wr?(0,c.jsx)(jt.Elements,{stripe:ee,options:Di,children:(0,c.jsx)(il,{sessionId:e,nonce:t,email:q.email,billingName:It||void 0,onBuyerIdentityReady:x,billingApiUrl:ze,intentKind:Ge>0?"payment":"setup",expressMethods:Kr,onTokenizedBody:_n,onErrorChange:Pe,onButtonClick:me,onDecline:m,onTechnicalFailure:jr,runBeforeButtonClick:or,onLoadStateChange:ji,placeholderBorderRadius:Dr})}):null,!Wr&&Yi?(0,c.jsx)("div",{style:{height:Ia,borderRadius:Dr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Po&&(0,c.jsx)(sl,{sessionId:e,nonce:t,email:q.email,billingName:[q.firstName,q.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:x,billingApiUrl:ze,paymentElementMethods:Go,stripeInstance:ee,paymentElementBaseOptions:za,onTokenizedBody:_n,onErrorChange:Pe,onButtonClick:me,onDecline:m,runBeforeButtonClick:or,onLoadStateChange:Wi,isProcessing:R,submitButtonColor:Nr,submitButtonBorderRadius:Vt,submitButtonStyle:u.submitButton,onExpandApm:tr,expandedApmMethod:Wt,themeId:Le,buttonAppearance:{backgroundColor:u.cardButton?.backgroundColor,borderColor:u.cardInputBorder,textColor:u.cardButton?.color,borderRadius:Dr}}),We&&(0,c.jsx)("button",{type:"button",onClick:async()=>{R||!(await or("card")).proceed||(me?.("card"),Fr())},disabled:R,style:{width:"100%",...W,...u.cardButton,...Ii({themeBundle:h,resolvedPrimaryColor:Nr,resolvedBorderRadius:Vt,submitButtonStyle:u.submitButton,explicitPrimaryColor:En?.colorPrimary}),fontSize:u.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:R?"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:R?.6:1},onMouseEnter:ct=>{!R&&(h||En?.colorPrimary)&&(ct.currentTarget.style.backgroundColor=Vl)},onMouseLeave:ct=>{(h||En?.colorPrimary)&&(ct.currentTarget.style.backgroundColor=Nr)},onMouseDown:ct=>{ct.currentTarget.style.transform="scale(0.985)"},onMouseUp:ct=>{ct.currentTarget.style.transform="scale(1)"},children:(0,c.jsx)(Xr,{content:Fe})}),ce&&Ze==="buttons"&&(0,c.jsx)(ao,{margin:"0.25rem 0",styleOverride:u.errorBanner,children:ce})]}),We&&I&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...G?{animation:G}:{},...Ze==="collapsing"?{pointerEvents:"none"}:{}},children:ls}),S&&us&&Wt&&ta&&ee&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...Yr?{animation:Yr}:{},...Ze==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Ka,borderRadius:Ja,...Io,padding:Ya},children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,c.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:nr,style:{display:"inline-flex",alignItems:"center",gap:Wa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:u.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...u.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...u.backButtonIcon},children:(0,c.jsx)("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:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(Zr,{content:Me})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:u.titleFontSize??"1.05rem",color:Ha,paddingRight:80,...u.title},children:`Pay with ${(0,p.getStripeMethodDisplayName)(Wt)}`})]}),(0,c.jsx)(jt.Elements,{stripe:ee,options:ta,children:(0,c.jsx)(Si,{method:Wt,sessionId:e,nonce:t,email:q.email,billingName:[q.firstName,q.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:x,billingApiUrl:ze,onTokenizedBody:_n,onErrorChange:Pe,onDecline:m,onCancel:nr,runBeforeButtonClick:or,onButtonClick:me,isProcessing:R,submitButtonColor:Nr,submitButtonBorderRadius:Vt,submitButtonStyle:u.submitButton,errorText:ce})},Wt)]})})]})]})}return us&&Wt&&ta&&ee&&S?(0,c.jsxs)("form",{onSubmit:Va,className:k,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(vi,{}),en&&(0,c.jsx)(Jn,{status:en,errorMessage:ce,authorized:Kt}),(0,c.jsx)("div",{style:{...Yr?{animation:Yr}:{},...Ze==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Ka,borderRadius:Ja,...Io,padding:Ya},children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,c.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:nr,style:{display:"inline-flex",alignItems:"center",gap:Wa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:u.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...u.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...u.backButtonIcon},children:(0,c.jsx)("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:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(Zr,{content:Me})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:u.titleFontSize??"1.05rem",color:Ha,paddingRight:80,...u.title},children:`Pay with ${(0,p.getStripeMethodDisplayName)(Wt)}`})]}),(0,c.jsx)(jt.Elements,{stripe:ee,options:ta,children:(0,c.jsx)(Si,{method:Wt,sessionId:e,nonce:t,email:q.email,billingName:[q.firstName,q.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:x,billingApiUrl:ze,onTokenizedBody:_n,onErrorChange:Pe,onDecline:m,onCancel:nr,runBeforeButtonClick:or,onButtonClick:me,isProcessing:R,submitButtonColor:Nr,submitButtonBorderRadius:Vt,submitButtonStyle:u.submitButton,errorText:ce})},Wt)]})})]}):(0,c.jsxs)("form",{onSubmit:Va,className:k,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(vi,{}),en&&(0,c.jsx)(Jn,{status:en,errorMessage:ce,authorized:Kt}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[cs("flopay-direct-paypal-gate-debug-default"),ds("flopay-stripe-gate-debug-default"),bo&&ke&&(0,c.jsxs)(c.Fragment,{children:[De&&(0,c.jsx)("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."}),(0,c.jsx)(Bo,{sessionId:e,nonce:t,billingApiUrl:ze,email:q.email,billingName:It||void 0,onBuyerIdentityReady:x,clientId:ke.clientId,environment:ke.environment,currency:nt.toUpperCase(),isSubscription:Ye,providerObjectType:A,approvalPresentation:Jo==="popup"?void 0:Jo,onTokenizedBody:_n,onComplete:l,onErrorChange:Pe,onDecline:m,onTechnicalFailure:jr,onButtonClick:me,runBeforeButtonClick:or,isProcessing:R,onLoadStateChange:Ua,onInitializationStateChange:qa,session:f,existingOrderId:De?.orderId,debug:St},De?.orderId??"fresh")]}),vo&&(0,c.jsx)(jt.Elements,{stripe:Qe,options:Ni,children:(0,c.jsx)(al,{sessionId:e,nonce:t,email:q.email,billingName:It||void 0,onBuyerIdentityReady:x,billingApiUrl:ze,onTokenizedBody:_n,onErrorChange:Pe,isProcessing:R,onButtonClick:me,onDecline:m,onTechnicalFailure:jr,runBeforeButtonClick:or,onLoadStateChange:$i,placeholderBorderRadius:Dr})}),Wr&&(0,c.jsx)(jt.Elements,{stripe:ee,options:Di,children:(0,c.jsx)(il,{sessionId:e,nonce:t,email:q.email,billingName:It||void 0,onBuyerIdentityReady:x,billingApiUrl:ze,intentKind:Ge>0?"payment":"setup",expressMethods:Kr,onTokenizedBody:_n,onErrorChange:Pe,onButtonClick:me,onDecline:m,onTechnicalFailure:jr,runBeforeButtonClick:or,onLoadStateChange:ji,placeholderBorderRadius:Dr})}),Po&&(0,c.jsx)(sl,{sessionId:e,nonce:t,email:q.email,billingName:[q.firstName,q.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:ze,paymentElementMethods:Go,stripeInstance:ee,paymentElementBaseOptions:za,onTokenizedBody:_n,onErrorChange:Pe,onButtonClick:me,onDecline:m,runBeforeButtonClick:or,onLoadStateChange:Wi,isProcessing:R,submitButtonColor:Nr,submitButtonBorderRadius:Vt,submitButtonStyle:u.submitButton,themeId:Le,onExpandApm:tr,expandedApmMethod:Wt,buttonAppearance:{backgroundColor:u.cardButton?.backgroundColor,borderColor:u.cardInputBorder,textColor:u.cardButton?.color,borderRadius:Dr}})]}),We&&(Nl||Dl||Ll)&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,c.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,c.jsx)("span",{children:"or pay with card"}),(0,c.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),We&&ls]})}var E=require("react/jsx-runtime"),yo=44,Mi="flopay_checkout_saved_payment_resume",xa=new Map,Ta=new Map;function fl(e,t){t.settled&&t.consumers===0&&xa.get(e)===t&&xa.delete(e)}function Cd(e,t,n){let r=Ta.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Ta.set(e,a);let l=()=>{Ta.get(e)===a&&Ta.delete(e)};return o.then(l,l),o}function Vo(e){return new Promise(t=>setTimeout(t,e))}function Aa(e,t,n){let r=da({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:qe.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function jo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ri(e,t,n,r,o,a){let l=Aa(e,t,n);l.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),jo(l)}function gl(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 hl(e,t,n,r,o){let a=(0,qe.classifyTelemetryFailure)(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:a.statusClass}),t instanceof qe.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof qe.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):a.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...a,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function xi(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 _i(e){return!e||e.data.stripe?.publishableKey?!1:!!xi(e)?.clientId}var Sd={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function wd(e){return new Rr.FloPay(Sd,{publishableKey:"provider_unavailable",...e})}async function Ei(e,t){let{publishableKey:n,paypalPublishableKey:r}=ui(e);return{...await pi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Bi(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function kd(){if(!Bi())return null;try{let e=window.sessionStorage.getItem(Mi);return e?JSON.parse(e):null}catch{return null}}function bl(e){if(Bi())try{window.sessionStorage.setItem(Mi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ti(){if(Bi())try{window.sessionStorage.removeItem(Mi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Id(){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 vl(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 Ai(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Rd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Pl(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function _d(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 Ma({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:d,error:m,onComplete:g,onError:y,onInstrument:b,onDecline:v,onCountryChange:k,onZipChange:B,showPayPal:L=!0,showStripe:he=!0,enabledPaymentMethods:te,showApplePay:S=!0,showGooglePay:J=!0,debug:K=!1,layout:le,theme:Ce,buttonsTheme:j,buttonsStyles:Le,cardButtonContent:Ee,cardBackButtonContent:tt,cardTitleContent:Ct,showSecurityFooter:Fe,onButtonClick:Me,onBeforeButtonClick:pe,enableAVS:Te,cardFieldOrder:me,cardPreFormSlot:ye,avsLayout:be,className:de,initialErrorMessage:He=null,children:Ke,checkoutMode:w,confirmLabel:H,renderConfirmButton:fe,onSessionCompleted:ne}){let M=(0,qe.resolveBillingApiUrl)(r),we=(0,C.useMemo)(()=>(0,qe.resolveTheme)(Ce),[Ce]),Oe=a??we?.appearance,pt=n?"embedded_checkout":"standard_checkout",Xe=Ai(Ke,le),[X,Y]=(0,C.useState)(null),[Z,Ge]=(0,C.useState)(null),nt=(0,C.useRef)(null),Ae=(0,C.useRef)(null),ke=(0,C.useRef)(0),[Ye,z]=(0,C.useState)(null),Zt=(0,C.useRef)(null),[ie,St]=(0,C.useState)(null),wt=(0,C.useMemo)(()=>n?so(n):"",[n]),rt=n?`create:${wt}`:`session:${e??""}`,N=Pl(ie),$e=(0,C.useRef)(new Set),f=(0,C.useRef)(rt),A=(0,C.useRef)(rt);qr(()=>{A.current=rt,f.current!==rt&&(f.current=rt,$e.current.clear())},[rt]);let Se=(0,C.useCallback)(P=>{if(A.current===rt){if(ni.has(P.name)){if($e.current.has(P.name))return;$e.current.add(P.name)}st(()=>b?.(P))}},[rt,b]),Ie=oo(Se,rt),mt=(0,C.useRef)(!1),At=(0,C.useCallback)(P=>{if(mt.current)return;let D=P.gateway||!N?P:{...P,gateway:N};Se(D)},[Se,N]);(0,C.useEffect)(()=>{Ie({class:"lifecycle",name:"checkout.mount"})},[Ie]);let[ze,Ve]=(0,C.useState)(e??""),dt=e??ze,Bn=n?"":dt,[rn,Et]=(0,C.useState)(!0),[se,fn]=(0,C.useState)(null),[An,Qt]=(0,C.useState)(0),[on,Fn]=(0,C.useState)("full"),[gn,Cn]=(0,C.useState)(!1),[qt,ve]=(0,C.useState)(He),[ut,yt]=(0,C.useState)(null),[Sn,xt]=(0,C.useState)(null),[Dn,ft]=(0,C.useState)(!1),[gt,cn]=(0,C.useState)(void 0),[dn,Ft]=(0,C.useState)(""),[kt,Nn]=(0,C.useState)(!1),[Gt,$]=(0,C.useState)(!1),[dr,Kt]=(0,C.useState)(!1),hn=(0,C.useRef)(null),Dt=(0,C.useRef)(0),un=(0,C.useRef)(void 0),[Ln,pn]=(0,C.useState)("loading"),[We,wn]=(0,C.useState)(0),an=(0,C.useRef)(!1),mn=(0,C.useRef)(!1),Re=(0,C.useRef)(!1),T=(0,C.useRef)(null),re=(0,C.useMemo)(()=>({checkoutMode:w??on,layout:Rd(Ke,le)}),[w,Ke,on,le]),U=(0,C.useRef)(g);U.current=g;let Nt=(0,C.useRef)(y);Nt.current=y;let Zn=(0,C.useRef)(v);Zn.current=v;let lt=(0,C.useCallback)((P,D)=>{nt.current=P,Ge(P),Zt.current=D,z(D)},[]),yn=(0,C.useCallback)(()=>{let P=Ae.current;P&&(Ae.current=null,P.destroy())},[]);(0,C.useEffect)(()=>{Xt(Z)?.setCheckoutContext(re),Ye&&Ye!==Z&&Xt(Ye)?.setCheckoutContext(re)},[Z,Ye,re]);let at=(0,C.useRef)(ne);at.current=ne;let Br=(0,C.useCallback)(P=>{pn(P),!(P!=="exhausted"||Re.current)&&(Re.current=!0,Nt.current?.(new qe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),_r=(0,C.useCallback)(()=>{pn("retrying"),wn(P=>P+1)},[]);(0,C.useEffect)(()=>{pn("loading"),wn(0),Re.current=!1},[dt]),(0,C.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:qe.SDK_VERSION,checkout_type:pt,checkout_layout:Xe,billing_api_url:M})},[Xe,pt,M]);let On=(0,C.useMemo)(()=>n?so(n,!0):"",[n]),Er=(0,C.useMemo)(()=>dn===On?gt:void 0,[gt,dn,On]),Pr=(0,C.useMemo)(()=>n?Za(n,Er):void 0,[n,Er]),zn=w??Pr?.checkoutMode??"full",Yt=(0,C.useMemo)(()=>Pr?{...Pr,checkoutMode:zn}:void 0,[Pr,zn]);(0,C.useEffect)(()=>{cn(void 0),Ft(On),un.current=void 0,hn.current=null,Kt(!1)},[On]),(0,C.useEffect)(()=>{ve(He)},[He]);let ur=(0,C.useCallback)((P,D,O)=>{st(()=>{Zn.current?.(nn(P,D,O))})},[]),kn=(0,C.useCallback)(async(P,D)=>{ve(null),xt(null),ft(!1),yt("processing");let O=D?.sessionId??P.id,V=Pl(P),De=nt.current??Zt.current,bt=Xt(De),xe=De?null:Aa(M,o,re),ae={log:R=>{bt?bt.log(R):xe?.log(R)},error:R=>{bt?bt.error(R):xe?.error(R)},terminal:R=>{bt?bt.terminal(R):xe?.terminal(R)},performance:R=>{bt?bt.performance(R):xe?.performance(R)},now:()=>bt?.now()??xe?.now()??0,elapsed:R=>bt?.elapsed(R)??Math.max(0,(xe?.now()??R)-R)},oe=ae.now(),x=!!(D?.initialAutoProcessingError||D?.initialAutoProcessingPending),ce=!1,h,u=()=>{ce||(ce=!0,x=!0,h=ae.now(),ae.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),ae.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},F=!1,Ne=()=>{F||(F=!0,ae.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),ae.performance({stage:"processing",durationMs:ae.elapsed(oe),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),h!==void 0&&ae.performance({stage:"recovery",durationMs:ae.elapsed(h),durationMode:"machine",paymentMethodCategory:"saved"}))};ae.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),mt.current=!0;try{ae.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{mt.current=!1}Ie({class:"lifecycle",name:"payment.processing.started",provider:V}),x&&u();let Be;try{let R=Ns(D?.initialAutoProcessingError),Q;if(R)u(),R.type==="paypal_redirect_required"&&T.current?.publishableKey&&bl({sessionId:O,publishableKey:T.current.publishableKey,paypalPublishableKey:T.current.paypalPublishableKey}),Q=await Pa(R,{flopay:nt.current,paypalFlopay:Zt.current,attempt3DS:D?.attempt3DS,billingApiUrl:M,sessionId:O,session:P,telemetry:!1}),R.type==="paypal_redirect_required"&&Ti();else if(D?.initialAutoProcessingPending){let Lt=(await new Rr.PaymentAPI(M,{telemetry:!1}).waitForCheckoutSessionCompletion(D.initialAutoProcessingPending.sessionId,{initialDelayMs:D.initialAutoProcessingPending.retryAfterMs})).data.session;if(!eo(Lt))throw aa(Lt);Q=zr(Lt,O)}else{if(D?.initialAutoProcessingError)throw Mr(D.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:D.initialAutoProcessingError.checkoutMethod});if(D?.fromCreateSession)return D?.fallbackToFull&&(Fn("full"),vl("full")),!1;{let q=await uo({billingApiUrl:M,sessionId:O,session:P,telemetry:!1});q.type==="success"?Q=q.result:(u(),q.type==="paypal_redirect_required"&&T.current?.publishableKey&&bl({sessionId:O,publishableKey:T.current.publishableKey,paypalPublishableKey:T.current.paypalPublishableKey}),Q=await Pa(q,{flopay:nt.current,paypalFlopay:Zt.current,attempt3DS:D?.attempt3DS,billingApiUrl:M,sessionId:O,session:P,telemetry:!1}),q.type==="paypal_redirect_required"&&Ti())}}O&&lo(O),Ne(),x&&(ae.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),ae.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),ae.terminal({outcome:Q.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),ft(Q.status==="authorized"),yt("success"),await Vo(600),Be=()=>U.current?.(Q)}catch(R){let Q=Oo(R),q=Q.checkoutMethod??Lo;ve(Q.message),xt(Q.message),ft(!1),D?.fallbackToFull&&(ae.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Fn("full"),vl("full")),Ne();let It=Q.statusCode===void 0?void 0:(0,qe.telemetryStatusClass)(Q.statusCode,"unknown"),Lt=It==="4xx"?{requestCategory:"process_payment",statusClass:It}:{},jn=It===void 0||It==="4xx";if(jn&&(Q.telemetryOutcome==="payment_declined"||!!(Q.declineCode||Q.code?.toLowerCase().includes("declin"))))ae.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Lt});else if(jn&&(Q.telemetryOutcome==="validation_rejected"||Q.type==="validation_error"))ae.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Lt});else{let ge=(0,qe.classifyTelemetryFailure)(R,x?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),ee=Q.telemetryRequestCategory??"process_payment";mt.current=!0;try{ae.error({...ge,...Q.telemetryFailureCategory?{failureCategory:Q.telemetryFailureCategory}:{},stage:x?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:ee})}finally{mt.current=!1}Ie({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:ee,provider:V})}return st(()=>Nt.current?.(Q)),ur(q,Q,{code:Q.code,declineCode:Q.declineCode}),yt("error"),await Promise.allSettled([Vo(400),D?.ensureProvidersReady?D.ensureProvidersReady():Promise.resolve()]),x&&(ae.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),ae.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ne(),xe&&jo(xe),yt(null),xt(null)}return st(Be),!0},[ur,Ie,M,o,re]);(0,C.useEffect)(()=>{if(typeof window>"u"||mn.current)return;let P=new URLSearchParams(window.location.search),D=P.get("payment_intent_client_secret");if(!D)return;let O=kd();O&&(mn.current=!0,(async()=>{let V,De=0;ve(null),xt(null),yt("processing"),Cn(!0);try{if(P.get("redirect_status")==="failed")throw Object.assign(new qe.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:bt,paypalFlopay:xe}=await pi({publishableKey:O.publishableKey,paypalPublishableKey:O.paypalPublishableKey,billingApiUrl:M,locale:l,telemetry:o});V=Xt(xe??bt),V?.setCheckoutContext(re),De=V?.now()??0,V?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),V?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let ae=(xe??bt)?.getRawProvider();if(!ae)throw Object.assign(new qe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:oe,error:x}=await ae.retrievePaymentIntent(D);if(x)throw Object.assign(new qe.FloPayError(x.message??"Failed to retrieve PayPal payment status.","api_error",{code:x.code}),{checkoutMethod:"paypal"});let ce=Ps(oe?.status);if(!oe||ce==="failed")throw Object.assign(new qe.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let h=typeof oe.payment_method=="string"?oe.payment_method:oe.payment_method?.id,u=ce;if(O.sessionId){let Be=(await new Rr.PaymentAPI(M,{telemetry:!1}).getUnifiedCheckoutSession(O.sessionId)).data.session;if(Be&&Be.status!=="complete"){let R=await uo({billingApiUrl:M,sessionId:O.sessionId,session:Be,telemetry:!1,tokenizedData:{id:h??oe.id,type:"card",threeDSecureActionResultTokenId:oe.id,isPaypal:!0}});if(R.type!=="success")throw Object.assign(new qe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});u=R.result.status}}O.sessionId&&lo(O.sessionId),V?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),V?.performance({stage:"redirect_resume",durationMs:V.elapsed(De),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),V?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),yt("success"),await Vo(600),st(()=>U.current?.({status:u,paymentIntentId:oe.id,paymentMethodId:h,checkoutMethod:"paypal"}))}catch(bt){let xe=Oo(bt),ae=xe.checkoutMethod??"paypal",oe=!!(xe.declineCode||xe.code?.toLowerCase().includes("declin"));if(V)V.performance({stage:"redirect_resume",durationMs:V.elapsed(De),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),oe?V.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):V.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(oe){let x=Aa(M,o,re);x.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),jo(x)}else Ri(M,o,re,"REDIRECT_RESUME_FAILED","redirect_resume");ve(xe.message),xt(xe.message),st(()=>Nt.current?.(xe)),ur(ae,xe,{code:xe.code,declineCode:xe.declineCode}),yt("error"),await Vo(400)}finally{Ti(),Id(),yt(null),xt(null),Cn(!1)}})())},[ur,l,M,o,re]);let Qn=(0,C.useRef)(null),bn=(0,C.useMemo)(()=>Yt?so(Yt):"",[Yt]),er=(0,C.useRef)(Yt);er.current=Yt,(0,C.useEffect)(()=>{Ve(e??"")},[e]),(0,C.useEffect)(()=>{an.current=!1,ve(He),xt(null),ft(!1),yt(null)},[bn,He,e]);async function ht(P,D,O){let V=Aa(M,o,re),De=new Rr.PaymentAPI(M,{telemetry:!1}),bt=!1;try{let xe=P.idempotencyKey===void 0?void 0:(0,qe.resolveIdempotencyKey)(P.idempotencyKey),ae=ii(D,O),oe=si(D,O);ae?.canonicalIdentity===O&&oe&&oe.canonicalIdentity===void 0&&(ha(D,O,oe.idempotencyKey),oe={...oe,canonicalIdentity:O});let x=xe??(oe?.canonicalIdentity===O?oe.idempotencyKey:void 0),ce,h=!1;V.log({name:ae?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let u=ae?.sid??null,F=null,Ne,Be,R=!1;if(u)try{F=await De.getUnifiedCheckoutSession(u,ae?.nonce),ae&&ae.canonicalIdentity===void 0&&(Ms(F.data.session,P)?(ga(D,O,u,ae.nonce??F.data.session?.clientSecret),oe&&oe.canonicalIdentity===void 0&&(ha(D,O,oe.idempotencyKey),x??(x=oe.idempotencyKey))):(fa(D,O),oe=null,x=xe,u=null,F=null));let q=F?.data.session?.status,It=F?.data.session,Lt=It?.clientSecret||ae?.nonce;if(u&&It?.buyerIdentified===!1&&Lt&&(Be=Qr(De,u,Lt,P.account)),u&&F&&q==="complete"){if(li(u))return{sid:u,result:F};fa(D,O),u=null,F=null,h=!0}}catch{V.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),ae?.canonicalIdentity===void 0?(fa(D,O),x=xe):ya(D,O),u=null}if(!u){!xe&&(h||!x)&&(x=(0,qe.resolveIdempotencyKey)(),ce=x),x&&ha(D,O,x);let q=V.now(),It=0;V.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Lt={...P,idempotencyKey:x,avsCheck:!!Te,avsConfig:typeof Te=="object"?Te:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ai(Ke,le)};Object.defineProperty(Lt,Rr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ue=>{It=Math.max(It,ue)}}});let jn=()=>{gl(V,"session_create",q,It)},_e=ue=>{hl(V,ue,"session_create",q,It)&&Ie({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,qe.isDetachedSessionEligible)(Lt)){let ue=await De.createDetachedSession(Lt);ue.claimed.catch(()=>{}),F=ue.shell,u=ue.sessionId,Be=ue.claim;let ge=V.now();V.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Ne=ue.claimed.then(ee=>{let Qe=ee.data.session?.id??ue.sessionId;return Qe&&ga(D,O,Qe,ee.data.session?.clientSecret??ue.nonce),gl(V,"session_claim",ge),jn(),ee},ee=>{throw ya(D,O),hl(V,ee,"session_claim",ge,0)&&Ie({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),ee}).finally(()=>jo(V)),Ne.catch(()=>{}),bt=!0,V.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),V.performance({stage:"session_shell",durationMs:V.now()-q,durationMode:"machine",requestCategory:"session_create",attempt:It,statusClass:"2xx",paymentMethodCategory:"card"})}else F=await De.createAndFetchSession(Lt),jn()}catch(ue){throw _e(ue),ue}u=F.data.session?.id??u??"",u&&!Ne&&ga(D,O,u,F.data.session?.clientSecret)}let Q=F?.data.session;return!Be&&u&&Q?.buyerIdentified===!1&&Q.clientSecret&&(Be=Qr(De,u,Q.clientSecret,P.account)),{sid:u??"",result:F,sdkGeneratedIdempotencyKey:ce,...Ne?{claimed:Ne}:{},...Be?{claim:Be}:{},...R?{claimRequiresIdentity:!0}:{}}}finally{bt||jo(V)}}let Un=(0,C.useRef)(ht);qr(()=>{Un.current=ht},[ht]);let In=(0,C.useCallback)(async(P,D)=>{let O=er.current;if(!O)throw new qe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let V=Za(O,P),De=so(V),bt=xs(V),xe=xa.get(De);if(!xe){let x={canonicalIdentity:De,promise:Un.current(V,bt,De),consumers:0,settled:!1};xe=x,xa.set(De,x);let ce=()=>{x.settled=!0,fl(De,x)};x.promise.then(ce,ce)}xe.consumers+=1;let ae=!1,oe=()=>{ae||(ae=!0,xe.consumers-=1,fl(De,xe))};D?.(oe);try{let x=await xe.promise;Qn.current=De,P&&(Ft(On),cn(Q=>hs(Q,P)));let{sid:ce,result:h,claimed:u,claim:F,claimRequiresIdentity:Ne}=x;if(un.current=F,Kt(Ne===!0),Y(h),h.data.session&&St(h.data.session),ce&&Ve(ce),u){Dt.current+=1;let Q=Dt.current;hn.current=u,$(!0),u.then(q=>{Dt.current===Q&&(hn.current===u&&(hn.current=null),Y(q),q.data.session&&St(q.data.session),$(!1),Kt(!1))},q=>{Dt.current===Q&&(hn.current===u&&(hn.current=null),$(!1),Kt(!1),fn(q instanceof qe.FloPayError?q:new qe.FloPayError(q instanceof Error?q.message:"Failed to create session","api_error")))})}else Dt.current+=1,hn.current=null,$(!1),Kt(!1);let{flopay:Be,paypalFlopay:R}=await Ei(h,{billingApiUrl:M,locale:l,telemetry:o});return lt(Be,R),Et(!1),x}catch(x){throw Qn.current===De&&(Qn.current=null),x}finally{D||oe()}},[On,lt,l,M,o]),Rn=(0,C.useRef)(kn);Rn.current=kn;let qn=(0,C.useRef)(In);qn.current=In;let Ze=(0,C.useCallback)(async P=>{if(!_d(P)||kt)return{sessionId:ze,session:ie};Nn(!0);try{let D=await In(P);return{sessionId:D.sid,session:D.result.data.session??null}}finally{Nn(!1)}},[In,kt,ze,ie]),$t=(0,C.useCallback)(async P=>{let D=un.current;if(!D)return;let O=Dt.current,V=await D(P);Dt.current===O&&(Y(V),V.data.session&&St(V.data.session))},[]),Wt=(0,C.useCallback)(async()=>{await hn.current},[]),Tr=(0,C.useCallback)(async()=>(await Wt(),{proceed:!0}),[Wt]);(0,C.useEffect)(()=>{let P=!1,D,O=++ke.current;yn(),fn(null),Qt(0);let V=()=>{P=!0,ke.current===O&&(ke.current+=1,yn())},De=er.current;if(bn&&De)return Fn(zn),Et(!1),Qn.current===bn?V:(St(bs(De,w)),(async()=>{let ae=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),oe=zn==="auto"&&!an.current&&!ae;oe&&(ve(null),xt(null),yt("processing"));try{let x=await qn.current(void 0,F=>{D=F}),ce=x.result.data.session??null;T.current=ui(x.result);let h=_i(x.result),u=li(x.sid||ce?.id);if(!P&&oe&&ce&&!h&&!u){an.current=!0,await Cd(bn,x.sdkGeneratedIdempotencyKey,()=>Rn.current(ce,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:x.result.autoProcessingError,initialAutoProcessingPending:x.result.autoProcessingPending,autoProcessingAttempted:x.result.autoProcessingAttempted,sessionId:x.sid||ce.id}));return}!P&&oe&&((h||u)&&(an.current=!0),yt(null),xt(null))}catch(x){if(P)return;let ce=oa(x);if(oe&&ce==="session_auto_completed"){an.current=!0,yt("success"),await Vo(600),P||(st(()=>{U.current?.({status:"succeeded"})}),yt(null),xt(null));return}oe&&(yt(null),xt(null));let h=x instanceof qe.FloPayError?x:new qe.FloPayError(x instanceof Error?x.message:"Failed to create session","api_error");fn(h)}finally{D?.(),D=void 0}})(),()=>{V(),D?.()});Et(!0);async function bt(){let ae=!1,oe=null;try{let x=new Rr.PaymentAPI(M,{telemetry:!1}),ce=await x.getUnifiedCheckoutSession(dt,t);if(oe=ce,P)return;Y(ce);let h=ce.data.session??null;if(St(h),!h)throw new qe.FloPayError("No session data returned","api_error");let u=h.checkoutMode;if(u==="setup")throw new qe.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(h.status==="authorized"){Et(!1),st(()=>{U.current?.(zr(h,dt)),at.current?.(h.successUrl??"")});return}if(h.status==="complete"){Et(!1),st(()=>{at.current?.(h.successUrl??"")});return}if(h.status==="expired")throw ra(h);ae=!0;let F=w??u??"full";Fn(F),Dt.current+=1;let Ne=h.clientSecret||t;un.current=h.buyerIdentified===!1&&Ne?Qr(x,dt,Ne,{...h.customer?.id?{userId:h.customer.id}:{}}):void 0,$(!1),Kt(!1);let Be=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),R=_i(ce);if(F==="auto"&&!an.current&&!Be&&!R){an.current=!0;let Q=xe(ce);try{if(await Rn.current(h,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Q,sessionId:dt||h.id}),P)return;await Q,P||Et(!1);return}catch{if(P)return;await Q,P||Et(!1);return}}await xe(ce),P||Et(!1)}catch(x){if(P)return;let ce=gs(x,ae);if(ae&&Ie({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ce){let{errorCode:u,stage:F,...Ne}=ce;Ri(M,o,re,u,F,Ne)}if(ce?.stage==="provider_load"&&(w??oe?.data.session?.checkoutMode??"full")==="full"&&fs(oe,L,he)){let u=wd({billingApiUrl:M,locale:l,telemetry:o});Ae.current=u,lt(u,null),Qt(1),Et(!1);return}let h=x instanceof qe.FloPayError&&ce?.stage!=="provider_load"?x:ys();h!==x&&st(()=>Nt.current?.(h)),fn(h),Et(!1)}}async function xe(ae){let{flopay:oe,paypalFlopay:x,...ce}=await Ei(ae,{billingApiUrl:M,locale:l,telemetry:o});T.current={publishableKey:ce.publishableKey,paypalPublishableKey:ce.paypalPublishableKey},lt(oe,x),Qt(0)}return bt(),V},[w,bn,zn,Bn,t,L,he]);let fo=(0,C.useCallback)(async()=>{if(!X||An!==1)return;let P=ke.current;Qt(2);try{let{flopay:D,paypalFlopay:O}=await Ei(X,{billingApiUrl:M,locale:l,telemetry:o});if(ke.current!==P)return;yn(),lt(D,O),Qt(0)}catch(D){if(ke.current!==P)return;let{errorCode:O,stage:V,...De}=Xa(D);Ri(M,o,re,O,V,De)}},[yn,lt,l,An,M,o,re,X]),pr=(0,C.useCallback)(async()=>{if(!(gn||!ie)){Cn(!0),ve(null);try{await kn(ie,{attempt3DS:!0,fallbackToFull:!0,sessionId:dt||ie.id})}finally{Cn(!1)}}},[dt,gn,kn,ie]),$n=xi(X),Vn=_i(X),sn=(0,C.useMemo)(()=>{if(!(!X||!ie||!X.data.stripe?.publishableKey))return{billingApiUrl:M}},[X,ie,M]),Fr=!!(n&&!Ke&&le==="buttons"&&pe&&zn==="full"),Ar=!!(dt&&ie?.vault?.html),tr=(0,C.useMemo)(()=>({session:ie,loading:rn,error:se,checkoutMode:on,inlineSessionDraft:Yt,applyInlineSessionPatch:Fr?Ze:void 0,inlineSessionPatchProcessing:kt,claimPending:Gt,claimRequiresIdentity:dr,claimBuyerIdentity:$t,waitForDataAttachment:Wt}),[ie,rn,se,on,Yt,Fr,Ze,kt,Gt,dr,$t,Wt]),nr=!!n&&le==="buttons"&&!Vn&&!Ar&&(!Z||!sn),en=ut?(0,E.jsx)(Jn,{status:ut,errorMessage:Sn,authorized:Dn}):null;if(rn&&!Ar){if(d)return(0,E.jsxs)(E.Fragment,{children:[d,en]});if(le==="buttons"){let P=we?.buttonsLayout?.cardButton?.borderRadius??we?.appearance.variables?.borderRadius??8,D=O=>(0,E.jsx)("div",{style:{height:O,borderRadius:P,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,E.jsxs)(E.Fragment,{children:[(0,E.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[L&&D(yo),he&&(S||J)&&D(yo),he&&D(yo),(0,E.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),en]})}return(0,E.jsxs)(E.Fragment,{children:[(0,E.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,E.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,E.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),en]})}return se?m?(0,E.jsx)(ar.Provider,{value:tr,children:m(se)}):(0,E.jsx)(ar.Provider,{value:tr,children:(0,E.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:se.message})}):nr?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ar.Provider,{value:tr,children:(0,E.jsx)(Td,{onButtonClick:Me,showPayPal:L,showStripe:he,showApplePay:S,showGooglePay:J,theme:Ce,buttonsTheme:j,buttonsStyles:Le,cardButtonContent:Ee,cardBackButtonContent:tt,cardTitleContent:Ct})}),en]}):Vn&&ie&&$n?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ar.Provider,{value:tr,children:(0,E.jsxs)("div",{className:de,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[qt&&(0,E.jsx)(ao,{icon:!1,children:qt}),Ln==="retrying"&&(0,E.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ln==="exhausted"&&(0,E.jsxs)("div",{role:"alert",children:[(0,E.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,E.jsx)("button",{type:"button",onClick:_r,children:"Retry PayPal"})]}),Ln!=="exhausted"&&(0,E.jsx)("div",{"aria-hidden":Ln==="retrying"?!0:void 0,style:Ln==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,E.jsx)(As,{sessionId:dt,nonce:ie.clientSecret||void 0,billingApiUrl:M,email:ie.customer?.email||Yt?.account?.email,billingName:[ie.customer?.firstName,ie.customer?.lastName].filter(Boolean).join(" ")||[Yt?.account?.firstName,Yt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:$t,clientId:$n.clientId,environment:$n.environment,currency:(ie.currency??"usd").toUpperCase(),isSubscription:ie.mode==="subscription",providerObjectType:$n.providerObjectType,approvalPresentation:$n.approvalPresentation,onComplete:g,onErrorChange:ve,onDecline:v,onButtonClick:Me,runBeforeButtonClick:Tr,onInitializationStateChange:Br,allowAutomaticRetry:We===0,session:ie,telemetry:o,telemetryContext:re,onInstrument:At,debug:K},`${rt}:paypal-init-${We}`)})]})}),en]}):(!Z||!sn)&&!(Ar&&on==="full")?(0,E.jsx)(E.Fragment,{children:en}):on==="confirm"?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ar.Provider,{value:tr,children:(0,E.jsx)(Do,{flopay:Z,paypalFlopay:Ye,options:sn??{billingApiUrl:M},onInstrument:At,children:(0,E.jsxs)("div",{className:de,children:[qt&&(0,E.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:qt}),fe?fe({onConfirm:pr,isProcessing:gn}):(0,E.jsx)("button",{type:"button",onClick:pr,disabled:gn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:gn?"not-allowed":"pointer",opacity:gn?.6:1},children:gn?"Processing...":H??"Confirm Purchase"})]})},rt)}),en]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ar.Provider,{value:tr,children:(0,E.jsxs)(Do,{flopay:Z,paypalFlopay:Ye,options:sn??{billingApiUrl:M},onInstrument:At,children:[An===1&&(0,E.jsx)("button",{type:"button",onClick:fo,children:"Retry payment methods"}),Ke?(0,E.jsxs)(E.Fragment,{children:[qt&&(0,E.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:qt}),(0,E.jsx)(Ed,{sessionId:dt,nonce:ie?.clientSecret||void 0,billingApiUrl:M,session:ie,children:Ke})]}):(0,E.jsx)(Ea,{sessionId:dt,nonce:ie?.clientSecret||void 0,telemetry:o,email:ie?.customer?.email||Yt?.account?.email,userId:ie?.customer?.id||Yt?.account?.userId,firstName:ie?.customer?.firstName||Yt?.account?.firstName,lastName:ie?.customer?.lastName||Yt?.account?.lastName,totalAmount:ie?Math.round((0,qe.buildCheckoutDisplayData)(ie).total*100):0,currency:ie?.currency?.toLowerCase()??"usd",onComplete:g,onError:y,onDecline:v,error:qt,onErrorChange:ve,showPayPal:L,showStripe:he,enabledPaymentMethods:An?[]:te??X?.data.stripe?.enabledPaymentMethods??ie?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:X?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:J,layout:le,theme:Ce,buttonsTheme:j,buttonsStyles:Le,appearance:Oe,cardButtonContent:Ee,cardBackButtonContent:tt,cardTitleContent:Ct,onButtonClick:Me,onBeforeButtonClick:pe,onBuyerIdentityReady:$t,enableAVS:Te,...me?{cardFieldOrder:me}:{},...ye?{cardPreFormSlot:ye}:{},avsLayout:be,country:ie?.customer?.country,city:ie?.customer?.city,state:ie?.customer?.state,onCountryChange:k,onZipChange:B,avsCheck:!!Te,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Ai(Ke,le),className:de,directPaypal:xi(X),isSubscription:ie?.mode==="subscription",session:ie,dataAttachmentPending:Gt,dataAttachmentRequiresIdentity:dr,debug:K})]},rt)}),en]})}function Ed({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,E.jsx)(E.Fragment,{children:C.default.Children.map(o,a=>{if(!C.default.isValidElement(a))return a;let l=a.props,d={};return l.sessionId||(d.sessionId=e),!l.nonce&&t&&(d.nonce=t),l.billingApiUrl||(d.billingApiUrl=n),r?.customer&&(l.email||(d.email=r.customer.email),l.userId||(d.userId=r.customer.id),l.firstName||(d.firstName=r.customer.firstName),l.lastName||(d.lastName=r.customer.lastName)),Object.keys(d).length===0?a:C.default.cloneElement(a,d)})})}function Td({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:d,cardButtonContent:m,cardBackButtonContent:g,cardTitleContent:y}){let[b,v]=(0,C.useState)(!1),k=(0,C.useMemo)(()=>(0,qe.resolveTheme)(a),[a]),B=(0,C.useMemo)(()=>{let S=k?.buttonsLayout??(0,qe.resolveButtonsLayoutTheme)(l);return d?{...S,...d,cardButton:{...S.cardButton,...d.cardButton},cardFormContainer:{...S.cardFormContainer,...d.cardFormContainer},backButton:{...S.backButton,...d.backButton},backButtonIcon:{...S.backButtonIcon,...d.backButtonIcon},submitButton:{...S.submitButton,...d.submitButton},title:{...S.title,...d.title}}:S},[k,l,d]),L=k?.buttonsLayout?.cardButton?.borderRadius??k?.appearance.variables?.borderRadius??8,he=S=>(0,E.jsx)("div",{style:{height:S,borderRadius:L,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),te=m===void 0?{boxSizing:"border-box",height:yo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let S=B.cardInputBorder??"#e5e7eb",J=B.cardInputBackground??"white",K=Jr(g),le=Jr(y);return(0,E.jsxs)("div",{style:{backgroundColor:B.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...B.cardFormContainer},children:[(0,E.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,E.jsxs)("button",{type:"button",onClick:()=>v(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:K?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...B.backButton},children:[(0,E.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...B.backButtonIcon},children:(0,E.jsx)("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:(0,E.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,E.jsx)(Zr,{content:g})]}),le?(0,E.jsx)("div",{style:{flex:1}}):(0,E.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...B.title},children:(0,E.jsx)(_o,{content:y})})]}),(0,E.jsx)("div",{style:{backgroundColor:J,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,E.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,E.jsxs)("div",{style:{display:"flex"},children:[(0,E.jsx)("div",{style:{flex:1,backgroundColor:J,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,E.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,E.jsx)("div",{style:{flex:1,backgroundColor:J,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,E.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,E.jsx)("div",{style:{backgroundColor:J,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,E.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,E.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...B.submitButton,opacity:.5}}),(0,E.jsx)("style",{children:`
|
|
41
41
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
42
42
|
@keyframes flopay-interim-expand {
|
|
43
43
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
44
44
|
40% { opacity: 1; }
|
|
45
45
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
46
46
|
}
|
|
47
|
-
`})]})}return(0,R.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&de(jr),n&&(r||o)&&de(jr),n&&(0,R.jsx)("button",{type:"button",onClick:()=>{e?.("card"),h(!0)},style:{width:"100%",...K,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:B.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,...B.cardButton},onMouseDown:I=>{I.currentTarget.style.transform="scale(0.985)"},onMouseUp:I=>{I.currentTarget.style.transform="scale(1)"},children:(0,R.jsx)(Zr,{content:f})}),(0,R.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var ir=require("react/jsx-runtime"),md=44;function sl(e){return new Promise(t=>setTimeout(t,e))}function yd(e,t){return e instanceof Zn.FloPayError?e:new Zn.FloPayError(e instanceof Error?e.message:t,"api_error")}function fd(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function gd(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 ll({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:c,subscriptions:f,account:y,successUrl:p,cancelUrl:b,couponCodes:h,tagsData:w,utmMetadata:B,billingApiUrl:N,locale:de,theme:K,appearance:I,buttonsTheme:re,buttonsStyles:q,onSuccess:ie,onError:se,onDecline:ee,children:Oe,disabled:ue=!1,type:Ct="button",style:st,...Se}){let Re=(0,We.useMemo)(()=>(0,Zn.resolveBillingApiUrl)(N),[N]),he=(0,We.useMemo)(()=>gd({createSession:n,clientId:a,products:l,items:c,subscriptions:f,account:y,successUrl:p,cancelUrl:b,couponCodes:h,tagsData:w,utmMetadata:B}),[y,b,a,h,n,l,c,f,p,w,B]),[te,Te]=(0,We.useState)(!1),[fe,we]=(0,We.useState)(null),[xe,Le]=(0,We.useState)(null),[_e,_]=(0,We.useState)(!1),[oe,me]=(0,We.useState)(null),J=(0,We.useRef)(!0),O=(0,We.useRef)(null),Ce=(0,We.useRef)(oe),Ke=(0,We.useRef)(ie),_t=(0,We.useRef)(se),Qe=(0,We.useRef)(ee);(0,We.useEffect)(()=>{Ce.current=oe},[oe]),(0,We.useEffect)(()=>{Ke.current=ie},[ie]),(0,We.useEffect)(()=>{_t.current=se},[se]),(0,We.useEffect)(()=>{Qe.current=ee},[ee]),(0,We.useEffect)(()=>(J.current=!0,()=>{J.current=!1,O.current?.abort()}),[]),(0,We.useEffect)(()=>{if(typeof window>"u")return;let P=F=>{F.key==="Escape"&&me(null)};return window.addEventListener("keydown",P),()=>{window.removeEventListener("keydown",P)}},[]);let Z=(0,We.useCallback)((P,F=Lo)=>{Qe.current?.(cn(F,P,{code:P.code,declineCode:P.declineCode}))},[]),X=(0,We.useCallback)(async P=>{J.current&&(Le(null),_(P.result.status==="authorized"),we("success"),await sl(1200),J.current&&nt(()=>Ke.current?.(P)))},[]),$=(0,We.useCallback)(async(P,F)=>{J.current&&(_t.current?.(P),F?.emitDecline&&Z(P,F.method),Le(P.message),_(!1),we("error"),await sl(1500))},[Z]),ze=(0,We.useCallback)(async(P,F,qt)=>{let Ae=P.data.session??null;if(!Ae)throw new Zn.FloPayError("No session data returned","api_error");let Et=Ae.clientSecret||t;if(to(Ae)){await X({result:Or(Ae,F),session:Ae,sessionId:Ae.id||F,autoCompleted:!1});return}if(Ae.status==="expired")throw na(Ae);try{if(P.autoProcessingPending){let lt=(await new xa.PaymentAPI(Re).waitForCheckoutSessionCompletion(P.autoProcessingPending.sessionId,{initialDelayMs:P.autoProcessingPending.retryAfterMs})).data.session;if(!to(lt))throw oa(lt);await X({result:Or(lt,F),session:lt,sessionId:lt.id||F,autoCompleted:!1});return}if(P.autoProcessingError){if(P.autoProcessingError.type==="3ds_required"&&P.autoProcessingError.nextActionRedirectUrl&&F&&Et){let et=new AbortController;O.current=et;let nn;try{nn=await Is({billingApiUrl:Re,sessionId:F,nonce:Et,nextActionRedirectUrl:P.autoProcessingError.nextActionRedirectUrl,signal:et.signal})}finally{O.current===et&&(O.current=null)}if(nn.status==="declined")throw Er({type:nn.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:nn.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:P.autoProcessingError.checkoutMethod});let dn=(await new xa.PaymentAPI(Re).waitForCheckoutSessionCompletion(F,{initialDelayMs:0,nonce:Et})).data.session;if(!to(dn))throw Er({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:P.autoProcessingError.checkoutMethod});await X({result:Or(dn,F),session:dn,sessionId:dn.id||F,autoCompleted:!1});return}throw Er(P.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:P.autoProcessingError.checkoutMethod})}if(qt?.fromCreateSession&&P.autoProcessingAttempted===!0)throw Er({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let tn=await po({billingApiUrl:Re,sessionId:F??Ae.id,session:Ae,nonce:Et});if(tn.type!=="success")throw Er({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await X({result:tn.result,session:Ae,sessionId:Ae.id||F,autoCompleted:!1})}catch(tn){let et=No(tn),nn=Ae.id||F;await $(et,{emitDecline:!0,method:et.checkoutMethod??Lo}),fd(et,nn)&&nn&&J.current&&me({sessionId:nn,errorMessage:et.message,nonce:Et||void 0})}},[t,Re,$,X]),Je=(0,We.useCallback)(async P=>{if(Se.onClick?.(P),!(P.defaultPrevented||ue||te)){if(me(null),e&&he){let F=new Zn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await $(F),J.current&&(we(null),Le(null));return}if(!e&&!he){let F=new Zn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $(F),J.current&&(we(null),Le(null));return}Te(!0),Le(null),_(!1),we("processing");try{let F=new xa.PaymentAPI(Re);if(e){let qt=await F.getUnifiedCheckoutSession(e,t);await ze(qt,e);return}try{let qt=await F.createAndFetchSession({...he});await ze(qt,qt.data.session?.id??null,{fromCreateSession:!0})}catch(qt){if(ra(qt)==="session_auto_completed"){await X({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw qt}}catch(F){await $(yd(F,"Automatic payment failed. Please try again."))}finally{J.current&&(we(null),Le(null),Te(!1))}}},[Se.onClick,he,ue,te,t,ze,Re,e,$,X]),be=(0,We.useCallback)(P=>{let F=Ce.current;me(null),Ke.current?.({result:P,session:null,sessionId:F?.sessionId??null,autoCompleted:!1})},[]),Xe=(0,We.useCallback)(P=>{_t.current?.(P)},[]),H=(0,We.useCallback)(P=>{Qe.current?.(P)},[]),z=(0,We.useMemo)(()=>(0,Zn.resolveTheme)(K),[K]),rt=(0,We.useMemo)(()=>{let P=z?.buttonsLayout??(0,Zn.resolveButtonsLayoutTheme)(re);return q?{...P,...q,cardButton:{...P.cardButton,...q.cardButton}}:P},[z,re,q]),D=(0,We.useMemo)(()=>{let P=z?.appearance;return I?P?{...P,...I,variables:{...P.variables,...I.variables}}:I:P},[I,z]),j=D?.variables,qe=j?.colorPrimary??"#4A49FF",ve=j?.colorPrimaryHover??yo(qe,.12),Bt=j?.borderRadius??"8px";return(0,ir.jsxs)(ir.Fragment,{children:[(0,ir.jsx)("button",{...Se,type:Ct,onClick:Je,disabled:ue||te,"aria-busy":te,style:{width:"100%",...Oe===void 0?{boxSizing:"border-box",height:md,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...rt.cardButton,...hi({themeBundle:z,resolvedPrimaryColor:qe,resolvedBorderRadius:Bt,submitButtonStyle:rt.submitButton,explicitPrimaryColor:j?.colorPrimary}),fontSize:rt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ue||te?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ue||te?.6:1,...st},onMouseEnter:P=>{Se.onMouseEnter?.(P),!P.defaultPrevented&&!ue&&!te&&(z||j?.colorPrimary)&&(P.currentTarget.style.backgroundColor=ve)},onMouseLeave:P=>{Se.onMouseLeave?.(P),!P.defaultPrevented&&(z||j?.colorPrimary)&&(P.currentTarget.style.backgroundColor=qe)},onMouseDown:P=>{Se.onMouseDown?.(P),P.defaultPrevented||(P.currentTarget.style.transform="scale(0.985)")},onMouseUp:P=>{Se.onMouseUp?.(P),P.defaultPrevented||(P.currentTarget.style.transform="scale(1)")},children:(0,ir.jsx)(Zr,{content:Oe})}),fe&&(0,ir.jsx)(Xn,{status:fe,errorMessage:xe,authorized:_e}),oe&&(0,ir.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:P=>{P.target===P.currentTarget&&me(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:(0,ir.jsx)("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:(0,ir.jsx)(Ta,{sessionId:oe.sessionId,nonce:oe.nonce,checkoutMode:"full",billingApiUrl:Re,locale:de,theme:K,...D?{appearance:D}:{},buttonsTheme:re,buttonsStyles:q,initialErrorMessage:oe.errorMessage,cardTitleContent:null,onComplete:be,onError:Xe,onDecline:H})})})]})}var Aa=require("@flopay/js/card-setup"),zn=require("@flopay/shared"),gt=require("react");var cl={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function dl(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?cl.dark:cl.light,a=t.colorText??(r?"#F1F5F9":"#262833"),l=e.appearance.rules?.[".Label"];return{panel:{...n.background===void 0?{}:{background:n.background},...n.backgroundColor===void 0?{}:{backgroundColor:n.backgroundColor},...n.border===void 0?{}:{border:n.border},...n.borderRadius===void 0?{}:{borderRadius:n.borderRadius},...n.boxShadow===void 0?{}:{boxShadow:n.boxShadow},color:a,...t.fontFamily?{fontFamily:t.fontFamily}:{}},spinnerTrackColor:e.buttonsLayout.cardInputBorder??(r?"#374151":"#e5e7eb"),spinnerAccentColor:t.colorPrimary??"#4A49FF",labelColors:{processing:a,success:o.success,error:o.error},noteColor:l?.color??a}}var gr=require("react/jsx-runtime"),Vo=class extends zn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function ul(e,t={}){let n=e instanceof zn.FloPayError?e:void 0,r=n?.statusCode,o=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof r=="number"&&r>=500||n?.code==="vault_capture_timeout"||!n);return new Vo(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:o,...n?.param?{param:n.param}:{},...r===void 0?{}:{statusCode:r}})}function pl({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:l=null,onReady:c,onComplete:f,onDecline:y,onCancel:p,onValidation:b,onError:h}){let[w,B]=(0,gt.useState)(null),[N,de]=(0,gt.useState)(null),[K,I]=(0,gt.useState)(null),[re,q]=(0,gt.useState)(null),[ie,se]=(0,gt.useState)(null),ee=(0,gt.useRef)(!1),Oe=(0,gt.useRef)(!1),ue=(0,gt.useMemo)(()=>typeof o=="object"?void 0:(0,zn.resolveTheme)(o),[o]),Ct=(0,gt.useMemo)(()=>typeof o=="object"?o:ue?Ca({appearance:ue.appearance,buttonsStyles:ue.buttonsLayout,layout:"default"}):null,[ue,o]),st=(0,gt.useMemo)(()=>Es(ue?.buttonsLayout.cardFormContainer,a),[ue,a]),Se=(0,gt.useMemo)(()=>ue?dl(ue):void 0,[ue]),Re=(0,gt.useRef)(c),he=(0,gt.useRef)(h),te=(0,gt.useRef)(f),Te=(0,gt.useRef)(y),fe=(0,gt.useRef)(p),we=(0,gt.useRef)(b),xe=(0,gt.useRef)(!1),Le=(0,gt.useRef)(!1),_e=(0,gt.useRef)(0);return Re.current=c,he.current=h,te.current=f,Te.current=y,fe.current=p,we.current=b,(0,gt.useEffect)(()=>{let _=_e.current+1;return _e.current=_,()=>{queueMicrotask(()=>{_e.current===_&&(xe.current||Le.current||(Le.current=!0,nt(()=>{fe.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,gt.useEffect)(()=>{let _=!0,oe=new Aa.PaymentAPI((0,zn.resolveBillingApiUrl)(n),{telemetry:r});return B(null),de(null),I(null),xe.current=!1,Le.current=!1,(async()=>{try{if(!e.trim())throw new zn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new zn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let me=await oe.getUnifiedCheckoutSession(e,t);if(!_)return;let J=me.data.session;if(!J||!(0,zn.isCardSetupCheckoutSession)(J))throw new zn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let O=J.vault;if(O?.html?.trim()||(O=await oe.getVaultCapture(e,t)),!O.html?.trim())throw new zn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!_)return;de(O),B(new Aa.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(me){if(!_)return;let J=ul(me);xe.current=!0,I(J),nt(()=>he.current?.(J))}})(),()=>{_=!1,oe.destroy()}},[n,t,e,r]),(0,gt.useEffect)(()=>{if(!w)return;let _=!1;Oe.current=!1,ee.current=!1;let oe=w.on("submitting",()=>{ee.current=!0,se(null),q("processing")}),me=w.on("complete",O=>{xe.current=!0,ee.current=!1,q("success"),(async()=>(await new Promise(Ce=>setTimeout(Ce,1200)),!Oe.current&&(Oe.current=!0,nt(()=>{te.current?.({status:"succeeded",sessionId:e,...O.paymentMethod?{paymentMethod:O.paymentMethod}:{}})}),_||q(null))))()}),J=w.on("decline",O=>{xe.current=!0,ee.current=!1,se(O.message??null),q("error"),nt(()=>{Te.current?.({status:"declined",sessionId:e,...O.declineReason?{reason:O.declineReason}:{},...O.message?{message:O.message}:{}})}),(async()=>(await new Promise(Ce=>setTimeout(Ce,1500)),_||q(null)))()});return()=>{_=!0,oe(),me(),J()}},[w,e]),K?(0,gr.jsx)("div",{role:"alert",children:K.message}):!w||!N?.html?(0,gr.jsx)(gr.Fragment,{children:l}):(0,gr.jsxs)(gr.Fragment,{children:[re&&(0,gr.jsx)(Xn,{status:re,errorMessage:ie,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...Se?{theme:Se}:{}}),(0,gr.jsx)(mo,{capture:w,html:N.html,messageToken:N.messageToken,expectedOrigin:N.expectedOrigin,theme:Ct,containerStyle:st,onReady:()=>{nt(()=>Re.current?.())},onValidation:_=>{nt(()=>we.current?.(_))},onError:_=>{if(!_)return;ee.current&&(ee.current=!1,se(_),q("error"),setTimeout(()=>q(null),1500));let oe=ul(new Error(_),{code:"card_setup_widget_failed",retryable:!0});nt(()=>he.current?.(oe))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}return(0,E.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&he(yo),n&&(r||o)&&he(yo),n&&(0,E.jsx)("button",{type:"button",onClick:()=>{e?.("card"),v(!0)},style:{width:"100%",...te,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:B.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,...B.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:(0,E.jsx)(Xr,{content:m})}),(0,E.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var cr=require("react/jsx-runtime"),Ad=44;function Cl(e){return new Promise(t=>setTimeout(t,e))}function xd(e,t){return e instanceof Xn.FloPayError?e:new Xn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Md(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Bd(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 Sl({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:d,subscriptions:m,account:g,successUrl:y,cancelUrl:b,couponCodes:v,tagsData:k,utmMetadata:B,billingApiUrl:L,locale:he,theme:te,appearance:S,buttonsTheme:J,buttonsStyles:K,onSuccess:le,onError:Ce,onDecline:j,children:Le,disabled:Ee=!1,type:tt="button",style:Ct,...Fe}){let Me=(0,et.useMemo)(()=>(0,Xn.resolveBillingApiUrl)(L),[L]),pe=(0,et.useMemo)(()=>Bd({createSession:n,clientId:a,products:l,items:d,subscriptions:m,account:g,successUrl:y,cancelUrl:b,couponCodes:v,tagsData:k,utmMetadata:B}),[g,b,a,v,n,l,d,m,y,k,B]),[Te,me]=(0,et.useState)(!1),[ye,be]=(0,et.useState)(null),[de,He]=(0,et.useState)(null),[Ke,w]=(0,et.useState)(!1),[H,fe]=(0,et.useState)(null),ne=(0,et.useRef)(!0),M=(0,et.useRef)(null),we=(0,et.useRef)(H),Oe=(0,et.useRef)(le),pt=(0,et.useRef)(Ce),Xe=(0,et.useRef)(j);(0,et.useEffect)(()=>{we.current=H},[H]),(0,et.useEffect)(()=>{Oe.current=le},[le]),(0,et.useEffect)(()=>{pt.current=Ce},[Ce]),(0,et.useEffect)(()=>{Xe.current=j},[j]),(0,et.useEffect)(()=>(ne.current=!0,()=>{ne.current=!1,M.current?.abort()}),[]),(0,et.useEffect)(()=>{if(typeof window>"u")return;let f=A=>{A.key==="Escape"&&fe(null)};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f)}},[]);let X=(0,et.useCallback)((f,A=Lo)=>{Xe.current?.(nn(A,f,{code:f.code,declineCode:f.declineCode}))},[]),Y=(0,et.useCallback)(async f=>{ne.current&&(He(null),w(f.result.status==="authorized"),be("success"),await Cl(600),ne.current&&st(()=>Oe.current?.(f)))},[]),Z=(0,et.useCallback)(async(f,A)=>{ne.current&&(pt.current?.(f),A?.emitDecline&&X(f,A.method),He(f.message),w(!1),be("error"),await Cl(400))},[X]),Ge=(0,et.useCallback)(async(f,A,Se)=>{let Ie=f.data.session??null;if(!Ie)throw new Xn.FloPayError("No session data returned","api_error");let mt=Ie.clientSecret||t;if(eo(Ie)){await Y({result:zr(Ie,A),session:Ie,sessionId:Ie.id||A,autoCompleted:!1});return}if(Ie.status==="expired")throw ra(Ie);try{if(f.autoProcessingPending){let dt=(await new Ba.PaymentAPI(Me).waitForCheckoutSessionCompletion(f.autoProcessingPending.sessionId,{initialDelayMs:f.autoProcessingPending.retryAfterMs})).data.session;if(!eo(dt))throw aa(dt);await Y({result:zr(dt,A),session:dt,sessionId:dt.id||A,autoCompleted:!1});return}if(f.autoProcessingError){if(f.autoProcessingError.type==="3ds_required"&&f.autoProcessingError.nextActionRedirectUrl&&A&&mt){let ze=new AbortController;M.current=ze;let Ve;try{Ve=await Ls({billingApiUrl:Me,sessionId:A,nonce:mt,nextActionRedirectUrl:f.autoProcessingError.nextActionRedirectUrl,signal:ze.signal})}finally{M.current===ze&&(M.current=null)}if(Ve.status==="declined")throw Mr({type:Ve.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ve.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:f.autoProcessingError.checkoutMethod});let rn=(await new Ba.PaymentAPI(Me).waitForCheckoutSessionCompletion(A,{initialDelayMs:0,nonce:mt})).data.session;if(!eo(rn))throw Mr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:f.autoProcessingError.checkoutMethod});await Y({result:zr(rn,A),session:rn,sessionId:rn.id||A,autoCompleted:!1});return}throw Mr(f.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:f.autoProcessingError.checkoutMethod})}if(Se?.fromCreateSession&&f.autoProcessingAttempted===!0)throw Mr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let At=await uo({billingApiUrl:Me,sessionId:A??Ie.id,session:Ie,nonce:mt});if(At.type!=="success")throw Mr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Y({result:At.result,session:Ie,sessionId:Ie.id||A,autoCompleted:!1})}catch(At){let ze=Oo(At),Ve=Ie.id||A;await Z(ze,{emitDecline:!0,method:ze.checkoutMethod??Lo}),Md(ze,Ve)&&Ve&&ne.current&&fe({sessionId:Ve,errorMessage:ze.message,nonce:mt||void 0})}},[t,Me,Z,Y]),nt=(0,et.useCallback)(async f=>{if(Fe.onClick?.(f),!(f.defaultPrevented||Ee||Te)){if(fe(null),e&&pe){let A=new Xn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Z(A),ne.current&&(be(null),He(null));return}if(!e&&!pe){let A=new Xn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Z(A),ne.current&&(be(null),He(null));return}me(!0),He(null),w(!1),be("processing");try{let A=new Ba.PaymentAPI(Me);if(e){let Se=await A.getUnifiedCheckoutSession(e,t);await Ge(Se,e);return}try{let Se=await A.createAndFetchSession({...pe});await Ge(Se,Se.data.session?.id??null,{fromCreateSession:!0})}catch(Se){if(oa(Se)==="session_auto_completed"){await Y({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Se}}catch(A){await Z(xd(A,"Automatic payment failed. Please try again."))}finally{ne.current&&(be(null),He(null),me(!1))}}},[Fe.onClick,pe,Ee,Te,t,Ge,Me,e,Z,Y]),Ae=(0,et.useCallback)(f=>{let A=we.current;fe(null),Oe.current?.({result:f,session:null,sessionId:A?.sessionId??null,autoCompleted:!1})},[]),ke=(0,et.useCallback)(f=>{pt.current?.(f)},[]),Ye=(0,et.useCallback)(f=>{Xe.current?.(f)},[]),z=(0,et.useMemo)(()=>(0,Xn.resolveTheme)(te),[te]),Zt=(0,et.useMemo)(()=>{let f=z?.buttonsLayout??(0,Xn.resolveButtonsLayoutTheme)(J);return K?{...f,...K,cardButton:{...f.cardButton,...K.cardButton}}:f},[z,J,K]),ie=(0,et.useMemo)(()=>{let f=z?.appearance;return S?f?{...f,...S,variables:{...f.variables,...S.variables}}:S:f},[S,z]),St=ie?.variables,wt=St?.colorPrimary??"#4A49FF",rt=St?.colorPrimaryHover??mo(wt,.12),N=St?.borderRadius??"8px";return(0,cr.jsxs)(cr.Fragment,{children:[(0,cr.jsx)("button",{...Fe,type:tt,onClick:nt,disabled:Ee||Te,"aria-busy":Te,style:{width:"100%",...Le===void 0?{boxSizing:"border-box",height:Ad,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Zt.cardButton,...Ii({themeBundle:z,resolvedPrimaryColor:wt,resolvedBorderRadius:N,submitButtonStyle:Zt.submitButton,explicitPrimaryColor:St?.colorPrimary}),fontSize:Zt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ee||Te?"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:Ee||Te?.6:1,...Ct},onMouseEnter:f=>{Fe.onMouseEnter?.(f),!f.defaultPrevented&&!Ee&&!Te&&(z||St?.colorPrimary)&&(f.currentTarget.style.backgroundColor=rt)},onMouseLeave:f=>{Fe.onMouseLeave?.(f),!f.defaultPrevented&&(z||St?.colorPrimary)&&(f.currentTarget.style.backgroundColor=wt)},onMouseDown:f=>{Fe.onMouseDown?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(0.985)")},onMouseUp:f=>{Fe.onMouseUp?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(1)")},children:(0,cr.jsx)(Xr,{content:Le})}),ye&&(0,cr.jsx)(Jn,{status:ye,errorMessage:de,authorized:Ke}),H&&(0,cr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:f=>{f.target===f.currentTarget&&fe(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:(0,cr.jsx)("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:(0,cr.jsx)(Ma,{sessionId:H.sessionId,nonce:H.nonce,checkoutMode:"full",billingApiUrl:Me,locale:he,theme:te,...ie?{appearance:ie}:{},buttonsTheme:J,buttonsStyles:K,initialErrorMessage:H.errorMessage,cardTitleContent:null,onComplete:Ae,onError:ke,onDecline:Ye})})})]})}var Fa=require("@flopay/js/card-setup"),Mn=require("@flopay/shared"),Pt=require("react");var wl={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function kl(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?wl.dark:wl.light,a=t.colorText??(r?"#F1F5F9":"#262833"),l=e.appearance.rules?.[".Label"];return{panel:{...n.background===void 0?{}:{background:n.background},...n.backgroundColor===void 0?{}:{backgroundColor:n.backgroundColor},...n.border===void 0?{}:{border:n.border},...n.borderRadius===void 0?{}:{borderRadius:n.borderRadius},...n.boxShadow===void 0?{}:{boxShadow:n.boxShadow},color:a,...t.fontFamily?{fontFamily:t.fontFamily}:{}},spinnerTrackColor:e.buttonsLayout.cardInputBorder??(r?"#374151":"#e5e7eb"),spinnerAccentColor:t.colorPrimary??"#4A49FF",labelColors:{processing:a,success:o.success,error:o.error},noteColor:l?.color??a}}var vr=require("react/jsx-runtime"),Ko=class extends Mn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Il(e,t={}){let n=e instanceof Mn.FloPayError?e:void 0,r=n?.statusCode,o=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof r=="number"&&r>=500||n?.code==="vault_capture_timeout"||!n);return new Ko(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:o,...n?.param?{param:n.param}:{},...r===void 0?{}:{statusCode:r}})}function Rl({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:l=null,onReady:d,onComplete:m,onDecline:g,onCancel:y,onValidation:b,onError:v}){let[k,B]=(0,Pt.useState)(null),[L,he]=(0,Pt.useState)(null),[te,S]=(0,Pt.useState)(null),[J,K]=(0,Pt.useState)(null),[le,Ce]=(0,Pt.useState)(null),j=(0,Pt.useRef)(!1),Le=(0,Pt.useRef)(!1),Ee=(0,Pt.useMemo)(()=>typeof o=="object"?void 0:(0,Mn.resolveTheme)(o),[o]),tt=(0,Pt.useMemo)(()=>typeof o=="object"?o:Ee?Sa({appearance:Ee.appearance,buttonsStyles:Ee.buttonsLayout,layout:"default"}):null,[Ee,o]),Ct=(0,Pt.useMemo)(()=>Us(Ee?.buttonsLayout.cardFormContainer,a),[Ee,a]),Fe=(0,Pt.useMemo)(()=>Ee?kl(Ee):void 0,[Ee]),Me=(0,Pt.useRef)(d),pe=(0,Pt.useRef)(v),Te=(0,Pt.useRef)(m),me=(0,Pt.useRef)(g),ye=(0,Pt.useRef)(y),be=(0,Pt.useRef)(b),de=(0,Pt.useRef)(!1),He=(0,Pt.useRef)(!1),Ke=(0,Pt.useRef)(0);return Me.current=d,pe.current=v,Te.current=m,me.current=g,ye.current=y,be.current=b,(0,Pt.useEffect)(()=>{let w=Ke.current+1;return Ke.current=w,()=>{queueMicrotask(()=>{Ke.current===w&&(de.current||He.current||(He.current=!0,st(()=>{ye.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Pt.useEffect)(()=>{let w=!0,H=new Fa.PaymentAPI((0,Mn.resolveBillingApiUrl)(n),{telemetry:r});return B(null),he(null),S(null),de.current=!1,He.current=!1,(async()=>{try{if(!e.trim())throw new Mn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Mn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let fe=await H.getUnifiedCheckoutSession(e,t);if(!w)return;let ne=fe.data.session;if(!ne||!(0,Mn.isCardSetupCheckoutSession)(ne))throw new Mn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let M=ne.vault;if(M?.html?.trim()||(M=await H.getVaultCapture(e,t)),!M.html?.trim())throw new Mn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!w)return;he(M),B(new Fa.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(fe){if(!w)return;let ne=Il(fe);de.current=!0,S(ne),st(()=>pe.current?.(ne))}})(),()=>{w=!1,H.destroy()}},[n,t,e,r]),(0,Pt.useEffect)(()=>{if(!k)return;let w=!1;Le.current=!1,j.current=!1;let H=k.on("submitting",()=>{j.current=!0,Ce(null),K("processing")}),fe=k.on("complete",M=>{de.current=!0,j.current=!1,K("success"),(async()=>(await new Promise(we=>setTimeout(we,600)),!Le.current&&(Le.current=!0,st(()=>{Te.current?.({status:"succeeded",sessionId:e,...M.paymentMethod?{paymentMethod:M.paymentMethod}:{}})}),w||K(null))))()}),ne=k.on("decline",M=>{de.current=!0,j.current=!1,Ce(M.message??null),K("error"),st(()=>{me.current?.({status:"declined",sessionId:e,...M.declineReason?{reason:M.declineReason}:{},...M.message?{message:M.message}:{}})}),(async()=>(await new Promise(we=>setTimeout(we,400)),w||K(null)))()});return()=>{w=!0,H(),fe(),ne()}},[k,e]),te?(0,vr.jsx)("div",{role:"alert",children:te.message}):!k||!L?.html?(0,vr.jsx)(vr.Fragment,{children:l}):(0,vr.jsxs)(vr.Fragment,{children:[J&&(0,vr.jsx)(Jn,{status:J,errorMessage:le,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...Fe?{theme:Fe}:{}}),(0,vr.jsx)(po,{capture:k,html:L.html,messageToken:L.messageToken,expectedOrigin:L.expectedOrigin,theme:tt,containerStyle:Ct,onReady:()=>{st(()=>Me.current?.())},onValidation:w=>{st(()=>be.current?.(w))},onError:w=>{if(!w)return;j.current&&(j.current=!1,Ce(w),K("error"),setTimeout(()=>K(null),400));let H=Il(new Error(w),{code:"card_setup_widget_failed",retryable:!0});st(()=>pe.current?.(H))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|