@flopay/react 1.9.14 → 1.9.15
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 +35 -1
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +8 -8
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var Gl=Object.create;var ra=Object.defineProperty;var Yl=Object.getOwnPropertyDescriptor;var Jl=Object.getOwnPropertyNames;var Xl=Object.getPrototypeOf,Zl=Object.prototype.hasOwnProperty;var Ql=(e,t)=>{for(var n in t)ra(e,n,{get:t[n],enumerable:!0})},ys=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Jl(t))!Zl.call(e,o)&&o!==n&&ra(e,o,{get:()=>t[o],enumerable:!(r=Yl(t,o))||r.enumerable});return e};var fs=(e,t,n)=>(n=e!=null?Gl(Xl(e)):{},ys(t||!e||!e.__esModule?ra(n,"default",{value:e,enumerable:!0}):n,e)),ec=e=>ys(ra({},"__esModule",{value:!0}),e);var Ld={};Ql(Ld,{DirectPayPalButton:()=>Fo,FloPayAutomaticPaymentButton:()=>kl,FloPayCardSetup:()=>El,FloPayCardSetupError:()=>Wo,FloPayCheckout:()=>Ba,FloPayProvider:()=>Lo,SplitCardForm:()=>Ta,VaultCardFields:()=>yo,dropThirdPartyOnlyError:()=>Tl.dropThirdPartyOnlyError,useCheckout:()=>_s,useFloPay:()=>wr,usePayPalFloPay:()=>sa});module.exports=ec(Ld);var Tl=require("@flopay/shared");var Fa=require("@flopay/js"),Jn=require("@flopay/shared"),tt=require("react");var Tt=require("react/jsx-runtime");function tc(){return(0,Tt.jsxs)(Tt.Fragment,{children:[(0,Tt.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,Tt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Tt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Tt.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,Tt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function nc(){return(0,Tt.jsx)(Tt.Fragment,{children:"Go back"})}function rc(){return(0,Tt.jsx)(Tt.Fragment,{children:"Secure card checkout"})}function Zr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Qr({content:e}){return(0,Tt.jsx)(Tt.Fragment,{children:e===void 0?(0,Tt.jsx)(tc,{}):e})}function eo({content:e}){return(0,Tt.jsx)(Tt.Fragment,{children:e===void 0?(0,Tt.jsx)(nc,{}):e})}function Eo({content:e}){return(0,Tt.jsx)(Tt.Fragment,{children:e===void 0?(0,Tt.jsx)(rc,{}):e})}var kt=require("@flopay/shared"),oc="Checkout is temporarily unavailable. Please try again later.";function Za(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof kt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function ac(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function gs(){return new kt.FloPayError(oc,"api_error",{code:"CheckoutInitializationFailed"})}function hs(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 bs(e,t){if(t&&(!(e instanceof kt.FloPayError)||e.type==="authentication_error"))return Za(e);if(!(e instanceof kt.FloPayError&&ac(e))){if(!t&&!(e instanceof kt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,kt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof kt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof kt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function to(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,kt.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,kt.isValidEmail)(l.email))return Promise.reject(new kt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let u={};for(let[b,f]of Object.entries(l)){if(d&&b.endsWith("Name")||typeof f!="string")continue;let P=f.trim();P&&(u[b]=P)}return o=e.claimCheckoutSession(t,n,{accountData:u}),o.catch(()=>{}),o}}function vs(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 Qa(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 Ps(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,kt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function ei(e,t){return t?{...e,...t}:e}function rn(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 ic=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Tr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of ic)if(n.test(t))return r;return e}function zr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function no(e){return e?.status==="authorized"||e?.status==="complete"}function Cs(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function oa(e){let t=Cs(e);return new kt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function aa(e){return e instanceof kt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function ia(e){let t=Cs(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new kt.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function To(e,t){return e==="processing"||(0,kt.isMoneySettledOutcome)(e,t)}function Ss(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function ws(e,t){let n=e;if((0,kt.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:l}=await n.retrieveSetupIntent(t);if(l)throw new kt.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 kt.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function ks(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 ti(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 Ao(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Ir=require("@flopay/js"),je=require("@flopay/shared"),C=fs(require("react"),1);var ni=require("react"),Hn=(0,ni.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),nr=(0,ni.createContext)({session:null,loading:!1,error:null});var pa=require("@flopay/js"),zt=require("@flopay/shared"),As=require("@paypal/paypal-js"),_=require("react");var Is=require("@flopay/shared"),rr=require("react"),Pr=require("react/jsx-runtime");function xn(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 ro(){let[e,t]=(0,rr.useState)(null),n=(0,rr.useRef)(null),r=(0,rr.useRef)(0),o=(0,rr.useCallback)((l,d)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:d}),new Promise(u=>{n.current=u})),[]),a=(0,rr.useCallback)(l=>{let d=n.current;n.current=null,t(null),d?.(l)},[]);return(0,rr.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function oo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,d]=(0,rr.useState)(e.email?.trim()??""),u=(0,Is.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:b=>d(b.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:!u||o,onClick:()=>{n(xn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function sc(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 Cr(e){if(typeof e!="object"||e===null)return;let t=e;return Ur(t.code)??Ur(t.type)??Ur(t.name)}function ao(e){if(!(typeof e!="object"||e===null))return Ur(e.decline_code)}function xo(e){return typeof e!="object"||e===null?!1:Ur(e.type)?.toLowerCase()==="card_error"||ao(e)!==void 0}function Sr(e){let t=sc(e)?.toLowerCase()??"",r=`${Cr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var Rs=require("@flopay/shared"),Mo=require("react");function wr(){return(0,Mo.useContext)(Hn).flopay}function sa(){return(0,Mo.useContext)(Hn).paypalFlopay??null}function _s(){return(0,Mo.useContext)(nr)}function Es(){return(0,Mo.useContext)(Hn).billingApiUrl||(0,Rs.resolveBillingApiUrl)()}function la(e){let t=e??(typeof navigator>"u"?"":navigator.userAgent),n=r=>({inAppBrowser:r!=="none",appFamily:r,popupCapability:"unknown"});return t?/FBAN|FBAV|FB_IAB|FBIOS/i.test(t)?n("facebook"):/Instagram/i.test(t)?n("instagram"):/musical_ly|BytedanceWebview|TikTok/i.test(t)?n("tiktok"):/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)?n("other_in_app"):/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)?n("generic_webview"):n("none"):n("none")}function ca(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var Ts=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 da=require("react"),qr=typeof window>"u"?da.useEffect:da.useLayoutEffect;var lc={"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 cc(e){return e==="stripe"||e==="paypal"?e:void 0}function dc(e){let t=cc(e.provider),n={schemaVersion:Ts.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=lc[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var ri=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function io(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=dc(l);if(d){if(ri.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}st(()=>n.current?.(d))}},[t])}var uc=Symbol.for("@flopay/js.telemetry.bridge.v1"),pc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function mc(){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 yc(e){let t=mc(),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 ua(e){let t=globalThis[pc];return yc(t?.(e)??{})}function tn(e){if(e)return e[uc]}var wn=require("react");function Bo(e){let t=(0,wn.useRef)(0),n=(0,wn.useRef)(null),r=(0,wn.useRef)(null),o=(0,wn.useCallback)((v=r.current)=>{v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),a=(0,wn.useCallback)(v=>{o();let I=t.current+1;return t.current=I,n.current=null,r.current={generation:I,method:v,timer:null,yieldedControl:!1},I},[o]),l=(0,wn.useCallback)(v=>{let I=r.current;return v!==void 0&&I?.generation!==v?!1:(o(I),r.current=null,(v===void 0||n.current===v)&&(n.current=null),!0)},[o]),d=(0,wn.useCallback)(v=>{let I=r.current,M=v??I?.generation??t.current;(v===void 0||I?.generation===v)&&(o(I),r.current=null),n.current=M},[o]),u=(0,wn.useCallback)(v=>n.current===(v??t.current),[]),b=(0,wn.useCallback)(v=>r.current?.generation===v&&n.current!==v,[]),f=(0,wn.useCallback)(()=>{let v=r.current;v&&(v.yieldedControl=!0,o(v))},[o]),P=(0,wn.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,wn.useEffect)(()=>{let v=()=>{document.visibilityState==="visible"?P():f()};return document.addEventListener("visibilitychange",v),window.addEventListener("blur",f),window.addEventListener("focus",P),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("blur",f),window.removeEventListener("focus",P),o()}},[o,f,P]),{startAttempt:a,finishAttempt:l,invalidateAttempt:d,isAttemptInvalidated:u,isAttemptCurrent:b,generationRef:t}}var Gn=require("react/jsx-runtime"),ma=45,fc=1e3,gc=11e3,hc=["https://www.paypal.com","https://www.sandbox.paypal.com"],oi="We couldn't open PayPal. Try again or choose another payment method.",bc={width:"100%",minHeight:ma,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 vc(e){return e.includes("No ack for postMessage init()")&&hc.some(t=>e.includes(t))&&e.includes("10000ms")}var Pc={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 Cc(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Pc[e.kind]??null}}function Sc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":vc(t)?"paypal_init_timeout":"paypal_init_failure"}function wc(e,t=!1){return e?t?`${oi} Open this page in your system browser, then try again.`:`${oi} Allow pop-ups for this site, then try again.`:oi}function kc(e){let t=xo(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 Ic(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 Rc(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function xs({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:d,currency:u,isSubscription:b,providerObjectType:f,approvalPresentation:P,onTokenizedBody:v,onComplete:I,onErrorChange:M,onDecline:N,onTechnicalFailure:pe,isProcessing:ae=!1,onLoadStateChange:w,onInitializationStateChange:q,allowAutomaticRetry:O=!0,onButtonClick:le,runBeforeButtonClick:Se,session:ie,existingOrderId:ye,telemetry:he,telemetryContext:dt,onInstrument:Je,debug:be=!1}){let Ue=wr(),ce=io(Je,e),we=(0,_.useMemo)(()=>{if(Ue)return null;let L=ua({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:zt.SDK_VERSION,enabled:he!==!1});return L.setCheckoutContext(dt??{}),L.beginCheckout(dt??{}),L},[n,Ue,he,dt?.checkoutMode,dt?.layout]),Xe=(0,_.useMemo)(()=>tn(Ue),[Ue]);(0,_.useEffect)(()=>()=>{we&&we.flush().catch(()=>{}).finally(()=>we.destroy())},[we]);let Z=(0,_.useMemo)(()=>({error:L=>{Xe?Xe.error(L):we?.error(L),ce({class:"technical_error",errorCode:L.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":L.errorCode,requestCategory:L.requestCategory,provider:L.provider})},log:L=>{Xe?Xe.log(L):we?.log(L),ce({class:"lifecycle",name:L.name,provider:L.provider})},performance:L=>{Xe?Xe.performance(L):we?.performance(L)},terminal:L=>{Xe?Xe.terminal(L):we?.terminal(L)},startTiming:()=>Xe?.now()??we?.now()??0,elapsed:L=>Xe?.elapsed(L)??Math.max(0,(we?.now()??L)-L)}),[ce,Xe,we]),ke=(0,_.useRef)(null),de=(0,_.useRef)(0),nt=(0,_.useRef)(null),rt=(0,_.useRef)(null),R=(0,_.useRef)(null),$=(0,_.useRef)(!1),[fe,Q]=(0,_.useState)(!1),[Ie,F]=(0,_.useState)(!1),[Me,ut]=(0,_.useState)(0),et=(0,_.useRef)(0),[ve,z]=(0,_.useState)(!1),oe=(0,_.useRef)(!1),qe=(0,_.useRef)(!1),[lt,Te]=(0,_.useState)(!1),[Ze,Ae]=(0,_.useState)(!1),{request:Pe,collect:Be,finish:Jt}=ro(),te=(0,_.useRef)({sessionId:e,required:!(0,zt.isValidEmail)(r?.trim()||ie?.customer?.email?.trim())});te.current.sessionId!==e&&(te.current={sessionId:e,required:!(0,zt.isValidEmail)(r?.trim()||ie?.customer?.email?.trim())});let At=te.current.required,mt=(0,_.useMemo)(()=>n.replace(/\/+$/,""),[n]),ue=ie?.gateways?.paypal?.providerObjectType??f,g=ue??(b?"subscription":"order"),[T]=(0,_.useState)(la),$e=ie?.gateways?.paypal?.approvalPresentation??P,_e=ca(T,$e==="app_switch"?"app_switch":void 0,g),St=ue==="order"||ue==="setup_token",at=(0,_.useMemo)(()=>JSON.stringify([mt,l,u,d??"",g,St,_e,e,ye??""]),[mt,l,u,d,ye,g,St,_e,e]),xt=(0,_.useRef)(at),J=xt.current!==at,Xt=(0,_.useRef)(be),It=(0,_.useRef)(null),[fn,sr]=(0,_.useState)([]),j=(0,_.useCallback)(L=>{Xt.current&&sr(ge=>[...ge,`${new Date().toISOString().slice(11,23)} ${L}`])},[]);(0,_.useEffect)(()=>{Xt.current=be,be&&j("debug:enabled"),It.current?.setEnabled(be)},[j,be]);let gn=(0,_.useRef)(v),kn=(0,_.useRef)(I),dn=(0,_.useRef)(M),on=(0,_.useRef)(N),hn=(0,_.useRef)(pe),Xn=(0,_.useRef)(le),un=(0,_.useRef)(w),Zt=(0,_.useRef)(q),ze=(0,_.useRef)(a),Ke=(0,_.useRef)(Se),an=(0,_.useRef)(ie),pt=(0,_.useRef)(r),zn=(0,_.useRef)(o),Mt=(0,_.useRef)(t),Qt=(0,_.useRef)(null),ft=(0,_.useRef)(new Map),jt=(0,_.useRef)(new Map),pn=(0,_.useRef)(!1);(0,_.useEffect)(()=>(pn.current=!0,()=>{pn.current=!1}),[]),(0,_.useEffect)(()=>{gn.current=v},[v]),(0,_.useEffect)(()=>{ze.current=a},[a]),(0,_.useEffect)(()=>{kn.current=I},[I]),(0,_.useEffect)(()=>{dn.current=M},[M]),(0,_.useEffect)(()=>{on.current=N},[N]),(0,_.useEffect)(()=>{hn.current=pe},[pe]),(0,_.useEffect)(()=>{Xn.current=le},[le]),(0,_.useEffect)(()=>{un.current=w},[w]),(0,_.useEffect)(()=>{Zt.current=q},[q]),(0,_.useEffect)(()=>{Ke.current=Se},[Se]),(0,_.useEffect)(()=>{an.current=ie},[ie]),(0,_.useEffect)(()=>{pt.current=r},[r]),(0,_.useEffect)(()=>{zn.current=o},[o]),(0,_.useEffect)(()=>{Mt.current=t},[t]),(0,_.useEffect)(()=>{et.current=Me},[Me]),(0,_.useEffect)(()=>{ve&&R.current?.focus()},[ve,Me]);let Bt=(0,_.useCallback)(()=>{window.setTimeout(()=>{R.current?.focus()},0)},[]),Rt=(0,_.useCallback)(()=>{Q(!1),ut(L=>L+1)},[]),sn=(0,_.useCallback)(()=>{z(!1),(ke.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ke.current)?.focus?.()},[]);(0,_.useEffect)(()=>{!fe||!$.current||($.current=!1,sn())},[sn,fe,Me]);let Mn=(0,_.useCallback)((L,ge)=>{let A=ge?.popupBlocked??Sr(L),Kt=wc(A,T.inAppBrowser),ln=hn.current;if(ln){let In=A&&T.inAppBrowser?new zt.FloPayError(Kt,"api_error",{code:ge?.code??"paypal_popup_blocked"}):L;ln("paypal",In,ge);return}dn.current?.(Kt)},[T.inAppBrowser]),vt=(0,_.useCallback)(L=>{let ge=nt.current,A=rt.current;ge===null||!A||(Z.log({...A,name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),Z.performance({...A,stage:"overlay_return",durationMs:Z.elapsed(ge),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),nt.current=null)},[Z]),ne=(0,_.useCallback)((L,ge,A)=>{let Kt=rt.current;vt("overlay_timeout"),Kt&&Z.error({...Kt,errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Mn(ge,A),z(!0),Rt(),Bt()},[vt,Bt,Mn,Rt,Z]),{finishAttempt:bn,generationRef:vn,invalidateAttempt:Ft,isAttemptCurrent:Ut,isAttemptInvalidated:lr,startAttempt:Bn}=Bo(ne),mn=(0,_.useCallback)(()=>(z(!1),Bn("paypal")),[Bn]),Fe=(0,_.useCallback)(L=>{Ft(L?.generation),L?.showRetry&&z(!0),L?.remount&&Rt(),L?.focus!==!1&&Bt()},[Bt,Ft,Rt]),Zn=L=>{let ge=Qt.current;return ge&&jt.current.set(L,ge),L};(0,_.useEffect)(()=>{xt.current!==at&&(xt.current=at,oe.current=!1,qe.current=!1,Q(!1),F(!1),Te(!1),Zt.current?.("loading"))},[at]),(0,_.useEffect)(()=>{st(()=>un.current?.(fe&&!lt))},[fe,lt]);let Dt=(0,zt.normalizeGatewayEnvironment)(d);(0,_.useEffect)(()=>{let L={attempt:vn.current+1,...T,presentationMode:_e},ge=()=>rt.current??L,A={error:h=>Z.error({...h,...ge()}),log:h=>Z.log({...h,...ge()}),performance:h=>Z.performance({...h,...ge()}),terminal:h=>Z.terminal({...h,...ge()}),startTiming:Z.startTiming,elapsed:Z.elapsed},Kt=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",ln=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(j(`mount clientId=${Kt} env=${d??"(unset)"}\u2192${Dt??"live"} ccy=${u} sub=${b}`),j(`ua=${ln.slice(0,80)}${ln.length>80?"\u2026":""}`),!l){j("FAIL: clientId empty \u2014 gateway misconfigured"),Te(!0),A.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!ke.current){j("FAIL: containerRef not attached");return}de.current=A.startTiming(),A.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let In=!1,Pt=!1,We=()=>In||Pt,cr,jr=!1,Rr=()=>{cr=(0,zt.generateIdempotencyKey)(),cr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),jr=!0},Fn=null,xr=!1,dr=null,Qn=!1,Wt=()=>{!dr||Qn||(Qn=!0,dr.close().catch(()=>{}))},Rn=!1,br=!1,Pn=ke.current,Dn=null,er=null,gt=[],Un=null,Cn=!1,qn=!1,$n=null,Ge=h=>{if(!h||typeof h.getBoundingClientRect!="function")return"(no rect)";let y=h.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},nn=h=>{if(!h)return"(empty)";try{let y=new URL(h,typeof window>"u"?"https://localhost":window.location.href),m=y.pathname.toLowerCase();return m.includes("checkcaptcha")||m.includes("captcha")?`CAPTCHA(${y.host}${m})`:m.includes("risk")||m.includes("challenge")?`RISK(${y.host}${m})`:m.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${m}`.slice(0,100)}catch{return h.slice(0,80)}},Ht=h=>{let y=h.getAttribute("src"),m=h.getAttribute("srcdoc"),X=h.getAttribute("name"),Le=h.getAttribute("sandbox"),se=[];return y&&se.push(`src=${nn(y)}`),m&&se.push(`srcdoc[${m.length}ch]`),!y&&!m&&se.push("src=(empty) srcdoc=(empty)"),X&&se.push(`name=${X.slice(0,40)}`),Le!==null&&se.push(`sandbox="${Le.slice(0,40)}"`),se.join(" ")},Mr=h=>{if(!(h instanceof HTMLIFrameElement))return"";try{let y=h.contentDocument;if(!y)return"cd=null";let m=y.body?.children.length??0,X=y.body?.innerHTML.length??0,Le=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${m}children,${X}ch] head[${Le}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},_r=[],Er=h=>{if(We())return;let y=h.message??String(h.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(j(`window:error ${y.slice(0,140)}`),_r.push(y))},Vn=h=>{if(We())return;let y=h.reason instanceof Error?h.reason.message:String(h.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(j(`window:rejection ${y.slice(0,140)}`),_r.push(y))},Ln={value:0},yn=()=>{Dn?.disconnect(),Dn=null,er?.disconnect(),er=null;for(let h of gt.splice(0))clearTimeout(h);qn=!1,Cn&&typeof window<"u"&&(window.removeEventListener("error",Er),window.removeEventListener("unhandledrejection",Vn)),Cn=!1},Br=()=>{if(!(Cn||We()||Rn)){if(Cn=!0,_r.length=0,Ln.value=0,typeof window<"u"&&(window.addEventListener("error",Er),window.addEventListener("unhandledrejection",Vn)),typeof PerformanceObserver<"u")try{er=new PerformanceObserver(h=>{if(!We())for(let y of h.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;Ln.value+=1;let m=Math.round(y.duration);j(`net ${m}ms ${y.name.slice(0,90)}`)}}),er.observe({type:"resource",buffered:!0})}catch{}$n?.()}},Fr=()=>{Un&&(clearTimeout(Un),Un=null)},_n=()=>{yn(),Fr()},vr={setEnabled:h=>{h?Br():yn()}};It.current=vr,Xt.current&&Br();let qt=h=>{if(!h)return!1;let y=h.toLowerCase();return y.includes("zoid destroyed")||y.includes("destroyed all components")||y.includes("window closed")||y.includes("detected container element removed")},S=h=>{if(We()||qt(h))return;let y=Tr(h)??h;st(()=>dn.current?.(y))},B=(h,y)=>{if(In||xr)return;xr=!0,Pt=!0,_n(),Wt();let m=Cc({kind:h,generationActive:!0,automaticRetryAllowed:O,automaticRetryUsed:oe.current});if(m.action==="retry"){oe.current=!0,Q(!1),Ae(!1),F(!0),Zt.current?.("retrying"),Fn=setTimeout(()=>{In||ut(X=>X+1)},fc);return}if(Q(!1),Ae(!1),F(!1),Te(!0),m.action!=="ignore"){if(Zt.current?.("exhausted"),m.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",y);return}m.report&&A.error({errorCode:m.report.errorCode,stage:m.report.stage,operationOutcome:m.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),qe.current||(qe.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Sc(h,y)))}};Te(!1);let K=async(h,y=Qt.current)=>{if(We())return;let m=y?.sessionId??e;if(gn.current){await gn.current(h,{sessionId:m,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let X=A.startTiming();A.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Le=()=>{A.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"processing",durationMs:A.elapsed(X),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let se=an.current,V=y?.accountPatch?.email??pt.current,re=y?.accountPatch?.userId??se?.customer?.id??se?.accountData?.userId??"",H=y?.accountPatch?.firstName??se?.customer?.firstName??se?.accountData?.firstName,Ct=y?.accountPatch?.lastName??se?.customer?.lastName??se?.accountData?.lastName,Ne=await new pa.PaymentAPI(mt,{telemetry:!1}).processPayment(re,{sessionId:m,nonce:y?.nonce??Mt.current,paymentMethodCategory:"paypal",tokenizedData:h,accountData:{userId:re,email:V??se?.customer?.email??"",...H?{firstName:H}:{},...Ct?{lastName:Ct}:{},country:y?.accountPatch?.country??se?.customer?.country??se?.accountData?.country??void 0,zip:y?.accountPatch?.zip??se?.customer?.zip??se?.accountData?.zip??void 0}});if(Ne.ok){if(Pt||In&&pn.current)return;Le(),A.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),st(()=>kn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(We())return;let Oe=await Ne.json().catch(()=>null),ee=Oe?.message??"PayPal payment failed.",Ee=Tr(ee)??ee;Le(),Ne.status===400&&(typeof Oe?.declineCode=="string"||!Array.isArray(Oe?.fields))?A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Ne.status===400||Ne.status===422?A.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):A.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Rc(Ne.status),failureCategory:Ne.status>=500?"server_error":void 0}),S(Ee),st(()=>on.current?.(rn("paypal",Ee,{code:Oe?.code,declineCode:Oe?.declineCode})));return}catch(se){if(We())return;Le(),A.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let V=se instanceof Error?se.message:"PayPal payment failed.",re=Tr(V)??V;S(re),st(()=>on.current?.(rn("paypal",re)));return}},U=()=>new zt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),He=h=>We()?Promise.reject(U()):Promise.resolve(h),yt=async h=>{if(We())throw U();jr||Rr();let y=Qt.current,m=y?.sessionId??e,X=y?.nonce??Mt.current;A.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Le;try{Le=await new pa.PaymentAPI(mt,{telemetry:!1}).createSessionIntent(m,X??"",St?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:zt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:g==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:cr})}catch(se){throw A.error({...(0,zt.classifyTelemetryFailure)(se,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),se}if(We())throw U();if(Le.provider!=="paypal"||Le.providerObjectType!==g)throw new Error(h);return A.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Le.providerObjectId},De=(h,y)=>{let m=y?.nonce??Mt.current;if(!m)return;let X=y?.sessionId??e,Le=ao(h)??Cr(h)??"provider_declined";new pa.PaymentAPI(mt,{telemetry:!1}).reportSessionIntentDecline(X,m,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Le}).catch(()=>{})},W=Me;j("loadScript:scheduled (deferred 1 tick)");let Ce=null,x=setTimeout(()=>{if(In){j("loadScript:skipped (cancelled before defer ran)");return}j("loadScript:start");let h=Dt==="live"?"production":Dt,y={};g==="subscription"?y={intent:"subscription",vault:!0}:g==="order"&&(y={intent:"capture"}),Ce=(0,As.loadScript)({clientId:l,currency:u,...y,...h?{environment:h}:{},...h==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let m=!1;Ce.then(X=>{if(m=!0,j(`loadScript:resolved inactive=${We()} ns=${!!X} buttons=${!!X?.Buttons}`),We())return;if(!X?.Buttons){j("FAIL: namespace missing Buttons factory"),B("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}A.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"provider_ready",durationMs:A.elapsed(de.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),A.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Le=async(Ne,Oe)=>{if(We()||et.current!==W)return;let ee=Ne.vaultSetupToken??Ne.subscriptionID??Ne.orderID??"",Ee=ee?jt.current.get(ee):ft.current.get(W);if(!(!Ee||!Ut(Ee.generation))&&bn(Ee.generation)){jt.current.delete(ee),ft.current.delete(Ee.surfaceKey),vt("approved");try{if(Ae(!0),st(()=>dn.current?.(null)),!ee)throw new zt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let me=an.current,Lt=Or(zn.current??[me?.customer?.firstName,me?.customer?.lastName].filter(Boolean).join(" ")),Ye=xn({email:Ee.accountPatch?.email?.trim()||pt.current?.trim()||me?.customer?.email?.trim(),firstName:Ee.accountPatch?.firstName?.trim()||Lt.firstName,lastName:Ee.accountPatch?.lastName?.trim()||Lt.lastName});if(!(0,zt.isValidEmail)(Ye.email)||!(Ye.firstName||Ye.lastName))try{let ur=Ic(await Oe?.order?.get?.());Ye=xn({email:ur.email||Ye.email,firstName:ur.firstName||Ye.firstName,lastName:ur.lastName||Ye.lastName})}catch{}if((ze.current||At)&&!(0,zt.isValidEmail)(Ye.email)){let ur=await Be("PayPal",Ye);if(!ur)return;Ye=ur}(0,zt.isValidEmail)(Ye.email)&&(Ee.accountPatch=xn({...Ee.accountPatch,...Ye}),await ze.current?.(Ye));let En;g==="setup_token"?En={id:ee,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:zt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:St?En={id:ee,isPaypal:!0,gateway:"paypal",paymentMethodType:zt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:En={id:ee,isPaypal:!0},await K(En,Ee)}catch(me){S(me instanceof Error?me.message:"PayPal capture failed.")}finally{We()||Ae(!1)}}},se=Ne=>{let Oe=ye?()=>He(ye):()=>yt(Ne);return async()=>Zn(await Oe())},V=X.Buttons({style:{layout:"horizontal",height:ma,tagline:!1},..._e==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Ne,Oe)=>{if(We()){await Oe.reject();return}Rr();let ee=Ke.current,Ee={};if(ee)try{let Ye=await ee("paypal");if(We()){await Oe.reject();return}if(!Ye.proceed){Qt.current=null,ft.current.delete(W),await Oe.reject();return}Ee={sessionId:Ye.sessionId,accountPatch:Ye.accountPatch,nonce:Ye.nonce}}catch(Ye){j(`onClick:runBeforeButtonClick rejected msg=${(Ye instanceof Error?Ye.message:String(Ye)).slice(0,120)}`),Qt.current=null,ft.current.delete(W),await Oe.reject();return}st(()=>Xn.current?.("paypal"));let me=mn(),Lt={generation:me,surfaceKey:W,...Ee};Qt.current=Lt,ft.current.set(W,Lt),rt.current={...L,attempt:me},await Oe.resolve(),A.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),A.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),nt.current=A.startTiming()},createOrder:g==="order"?se("Failed to create PayPal order."):void 0,createSubscription:g==="subscription"?se("Failed to create PayPal subscription."):void 0,createVaultSetupToken:g==="setup_token"?async()=>Zn(await yt("Failed to create PayPal setup token.")):void 0,onApprove:Le,onCancel:()=>{if(We())return;let Ne=ft.current.get(W)??Qt.current;Ne&&ft.current.delete(Ne.surfaceKey),Qt.current=null,vt("cancelled"),A.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),$.current=!0,Fe({generation:Ne?.generation,remount:!0,focus:!1})},onError:Ne=>{if(We()||et.current!==W)return;let Oe=Ne instanceof Error?Ne.message:"PayPal failed to render.";if(j(`onError rendered=${Rn} msg=${Oe.slice(0,120)}`),Rn){let ee=ft.current.get(W)??Qt.current;if(ee&&!Ut(ee.generation)||!ee&&lr())return;if(qt(Oe)){bn(ee?.generation);return}let{errorCode:Ee,popupBlocked:me,providerDeclined:Lt,terminalReason:Ye}=kc(Ne);if(vt(Ye),Lt){A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ye}),De(Ne,ee),st(()=>on.current?.(rn("paypal",Oe))),ee&&ft.current.delete(ee.surfaceKey),Qt.current=null,bn(ee?.generation);return}A.error({errorCode:Ee,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ye}),ee&&ft.current.delete(ee.surfaceKey),Qt.current=null,Fe({generation:ee?.generation,remount:!0,showRetry:!0,focus:!0}),Mn(Ne,{code:"paypal_runtime_failed",popupBlocked:me});return}B(qt(Oe)?"teardown":"pre_ready_callback",Oe)}}),re=V.isEligible();if(j(`isEligible=${re}`),A.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!re){Q(!1),B("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}br=!0,dr=V,$n=()=>{if(!Cn||qn||We()||Rn)return;qn=!0,j(`container:dims ${Ge(Pn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Dn=new MutationObserver(Oe=>{if(!We()){for(let ee of Oe)if(ee.type==="childList")ee.addedNodes.forEach(Ee=>{if(!(Ee instanceof Element))return;let me=Ee.tagName.toLowerCase(),Lt=(Ee.getAttribute("title")??"").slice(0,40),Ye=me==="iframe"?` ${Ht(Ee)}`:"";j(`child+ ${me}${Lt?` title="${Lt}"`:""}${Ye} dims=${Ge(Ee)}`)});else if(ee.type==="attributes"&&ee.target instanceof Element){let Ee=ee.target;if(Ee.tagName.toLowerCase()!=="iframe")continue;let me=ee.attributeName;(me==="src"||me==="srcdoc")&&j(`attr~ iframe ${me}=${me==="srcdoc"?`[${(Ee.getAttribute("srcdoc")??"").length}ch]`:nn(Ee.getAttribute("src"))} dims=${Ge(Ee)}`)}}}),Dn.observe(Pn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ne=Oe=>{if(We()||Rn)return;let ee=Pn.querySelectorAll("iframe"),Ee=typeof document<"u"&&"hasStorageAccess"in document;j(`watchdog:${Oe} container=${Ge(Pn)} children=${Pn.childElementCount} iframes=${ee.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Ee} paypalNetRequests=${Ln.value}`),ee.forEach((me,Lt)=>{let Ye=(me.getAttribute("title")??"").slice(0,40);j(` iframe[${Lt}] ${Ge(me)}${Ye?` title="${Ye}"`:""} ${Ht(me)}`);let En=Mr(me);En&&j(` ${En}`)}),_r.length===0&&j(" (no PayPal/zoid window errors captured)")};gt.push(setTimeout(()=>Ne("3s"),3e3)),gt.push(setTimeout(()=>Ne("8s"),8e3)),gt.push(setTimeout(()=>Ne("15s"),15e3))},$n(),j("render:start");let Ct=A.startTiming();Un=setTimeout(()=>{We()||Rn||(j("watchdog:11s retryable render timeout"),B("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},gc);let Gt=V.render(Pn);(async()=>{try{if(await Gt,j(`render:resolved inactive=${We()}`),_n(),We()){Wt();return}Rn=!0,Q(!0),F(!1),Zt.current?.("ready"),A.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"checkout_render",durationMs:A.elapsed(Ct),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Ne){let Oe=Ne instanceof Error?Ne.message:"PayPal failed to render.";j(`render:rejected msg=${Oe.slice(0,120)}`),_n(),B(qt(Oe)?"teardown":"render_rejected",Oe)}})()}).catch(X=>{let Le=X instanceof Error?X.message:"PayPal operation failed.";j(`provider:failed msg=${Le.slice(0,120)}`);let se="script_rejected";m&&qt(Le)?se="teardown":m&&br&&(se="render_rejected"),B(se,Le)})},0);return()=>{In=!0,clearTimeout(x),Fn&&clearTimeout(Fn),_n(),It.current===vr&&(It.current=null),Wt(),nt.current=null,rt.current=null}},[O,mt,l,u,d,g,_e,St,e,ye,Me,Z,Be,At,j,vt]);let xe=be?(0,Gn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:lt?"#fef2f2":"#f3f4f6",border:`1px solid ${lt?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${fe} failed=${lt})`,fn.length===0?`
|
|
1
|
+
"use strict";var Xl=Object.create;var oa=Object.defineProperty;var Zl=Object.getOwnPropertyDescriptor;var Ql=Object.getOwnPropertyNames;var ec=Object.getPrototypeOf,tc=Object.prototype.hasOwnProperty;var nc=(e,t)=>{for(var n in t)oa(e,n,{get:t[n],enumerable:!0})},hs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ql(t))!tc.call(e,o)&&o!==n&&oa(e,o,{get:()=>t[o],enumerable:!(r=Zl(t,o))||r.enumerable});return e};var bs=(e,t,n)=>(n=e!=null?Xl(ec(e)):{},hs(t||!e||!e.__esModule?oa(n,"default",{value:e,enumerable:!0}):n,e)),rc=e=>hs(oa({},"__esModule",{value:!0}),e);var zd={};nc(zd,{DirectPayPalButton:()=>Do,FloPayAutomaticPaymentButton:()=>_l,FloPayCardSetup:()=>xl,FloPayCardSetupError:()=>Ho,FloPayCheckout:()=>Fa,FloPayProvider:()=>No,SplitCardForm:()=>Aa,VaultCardFields:()=>fo,dropThirdPartyOnlyError:()=>Ml.dropThirdPartyOnlyError,useCheckout:()=>As,useFloPay:()=>Ir,usePayPalFloPay:()=>la});module.exports=rc(zd);var Ml=require("@flopay/shared");var Da=require("@flopay/js"),Xn=require("@flopay/shared"),nt=require("react");var xt=require("react/jsx-runtime");function oc(){return(0,xt.jsxs)(xt.Fragment,{children:[(0,xt.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,xt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,xt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,xt.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,xt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function ac(){return(0,xt.jsx)(xt.Fragment,{children:"Go back"})}function ic(){return(0,xt.jsx)(xt.Fragment,{children:"Secure card checkout"})}function Qr(e){return e!==void 0&&(e===""||e===null||e===!1)}function eo({content:e}){return(0,xt.jsx)(xt.Fragment,{children:e===void 0?(0,xt.jsx)(oc,{}):e})}function to({content:e}){return(0,xt.jsx)(xt.Fragment,{children:e===void 0?(0,xt.jsx)(ac,{}):e})}function To({content:e}){return(0,xt.jsx)(xt.Fragment,{children:e===void 0?(0,xt.jsx)(ic,{}):e})}var It=require("@flopay/shared"),sc="Checkout is temporarily unavailable. Please try again later.";function ei(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof It.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function lc(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function vs(){return new It.FloPayError(sc,"api_error",{code:"CheckoutInitializationFailed"})}function ti(e){return!!e?.gateways?.worldpayCorporateGateway}function Or(e){return e?.status==="open"&&ti(e)}function Ps(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")||Or(r))||t&&e?.data.paypal?.publishableKey)}function Cs(e,t){if(t&&(!(e instanceof It.FloPayError)||e.type==="authentication_error"))return ei(e);if(!(e instanceof It.FloPayError&&lc(e))){if(!t&&!(e instanceof It.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,It.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof It.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof It.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function no(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,It.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,It.isValidEmail)(l.email))return Promise.reject(new It.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let u={};for(let[h,y]of Object.entries(l)){if(d&&h.endsWith("Name")||typeof y!="string")continue;let v=y.trim();v&&(u[h]=v)}return o=e.claimCheckoutSession(t,n,{accountData:u}),o.catch(()=>{}),o}}function Ss(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 ni(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ws(e,t){let n=e.products??[...(e.subscriptions??[]).map(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 zr(e){if((0,It.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function ri(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 cc=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Tr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of cc)if(n.test(t))return r;return e}function Ur(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function ro(e){return e?.status==="authorized"||e?.status==="complete"}function ks(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function aa(e){let t=ks(e);return new It.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ia(e){return e instanceof It.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function sa(e){let t=ks(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new It.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function Ao(e,t){return e==="processing"||(0,It.isMoneySettledOutcome)(e,t)}function Is(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Rs(e,t){let n=e;if((0,It.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:l}=await n.retrieveSetupIntent(t);if(l)throw new It.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 It.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function _s(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 oi(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 xo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var _r=require("@flopay/js"),je=require("@flopay/shared"),S=bs(require("react"),1);var ai=require("react"),Gn=(0,ai.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),ir=(0,ai.createContext)({session:null,loading:!1,error:null});var ma=require("@flopay/js"),zt=require("@flopay/shared"),Bs=require("@paypal/paypal-js"),E=require("react");var Es=require("@flopay/shared"),sr=require("react"),Sr=require("react/jsx-runtime");function Mn(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 oo(){let[e,t]=(0,sr.useState)(null),n=(0,sr.useRef)(null),r=(0,sr.useRef)(0),o=(0,sr.useCallback)((l,d)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:d}),new Promise(u=>{n.current=u})),[]),a=(0,sr.useCallback)(l=>{let d=n.current;n.current=null,t(null),d?.(l)},[]);return(0,sr.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function ao({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,d]=(0,sr.useState)(e.email?.trim()??""),u=(0,Es.isValidEmail)(l.trim());return(0,Sr.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,Sr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Sr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Sr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:h=>d(h.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Sr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Sr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Sr.jsxs)("button",{type:"button",disabled:!u||o,onClick:()=>{n(Mn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function dc(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 qr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function wr(e){if(typeof e!="object"||e===null)return;let t=e;return qr(t.code)??qr(t.type)??qr(t.name)}function io(e){if(!(typeof e!="object"||e===null))return qr(e.decline_code)}function Mo(e){return typeof e!="object"||e===null?!1:qr(e.type)?.toLowerCase()==="card_error"||io(e)!==void 0}function kr(e){let t=dc(e)?.toLowerCase()??"",r=`${wr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var Ts=require("@flopay/shared"),Bo=require("react");function Ir(){return(0,Bo.useContext)(Gn).flopay}function la(){return(0,Bo.useContext)(Gn).paypalFlopay??null}function As(){return(0,Bo.useContext)(ir)}function xs(){return(0,Bo.useContext)(Gn).billingApiUrl||(0,Ts.resolveBillingApiUrl)()}function ca(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 da(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var Ms=require("@flopay/shared"),Vr=require("react");function lt(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 ua=require("react"),$r=typeof window>"u"?ua.useEffect:ua.useLayoutEffect;var uc={"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 pc(e){return e==="stripe"||e==="paypal"?e:void 0}function mc(e){let t=pc(e.provider),n={schemaVersion:Ms.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=uc[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 ii=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function so(e,t){let n=(0,Vr.useRef)(e);n.current=e;let r=(0,Vr.useRef)(new Set),o=(0,Vr.useRef)(t),a=(0,Vr.useRef)(t);return $r(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,Vr.useCallback)(l=>{if(a.current!==t)return;let d=mc(l);if(d){if(ii.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}lt(()=>n.current?.(d))}},[t])}var yc=Symbol.for("@flopay/js.telemetry.bridge.v1"),fc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function gc(){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 hc(e){let t=gc(),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 pa(e){let t=globalThis[fc];return hc(t?.(e)??{})}function en(e){if(e)return e[yc]}var Sn=require("react");function Fo(e){let t=(0,Sn.useRef)(0),n=(0,Sn.useRef)(null),r=(0,Sn.useRef)(null),o=(0,Sn.useCallback)((b=r.current)=>{b?.timer&&(clearTimeout(b.timer),b.timer=null)},[]),a=(0,Sn.useCallback)(b=>{o();let R=t.current+1;return t.current=R,n.current=null,r.current={generation:R,method:b,timer:null,yieldedControl:!1},R},[o]),l=(0,Sn.useCallback)(b=>{let R=r.current;return b!==void 0&&R?.generation!==b?!1:(o(R),r.current=null,(b===void 0||n.current===b)&&(n.current=null),!0)},[o]),d=(0,Sn.useCallback)(b=>{let R=r.current,B=b??R?.generation??t.current;(b===void 0||R?.generation===b)&&(o(R),r.current=null),n.current=B},[o]),u=(0,Sn.useCallback)(b=>n.current===(b??t.current),[]),h=(0,Sn.useCallback)(b=>r.current?.generation===b&&n.current!==b,[]),y=(0,Sn.useCallback)(()=>{let b=r.current;b&&(b.yieldedControl=!0,o(b))},[o]),v=(0,Sn.useCallback)(()=>{let b=r.current;!b?.yieldedControl||document.visibilityState!=="visible"||(o(b),b.timer=setTimeout(()=>{b.timer=null,r.current?.generation===b.generation&&(r.current=null,n.current=b.generation,e(b.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[o,e]);return(0,Sn.useEffect)(()=>{let b=()=>{document.visibilityState==="visible"?v():y()};return document.addEventListener("visibilitychange",b),window.addEventListener("blur",y),window.addEventListener("focus",v),()=>{document.removeEventListener("visibilitychange",b),window.removeEventListener("blur",y),window.removeEventListener("focus",v),o()}},[o,y,v]),{startAttempt:a,finishAttempt:l,invalidateAttempt:d,isAttemptInvalidated:u,isAttemptCurrent:h,generationRef:t}}var Yn=require("react/jsx-runtime"),ya=45,bc=1e3,vc=11e3,Pc=["https://www.paypal.com","https://www.sandbox.paypal.com"],si="We couldn't open PayPal. Try again or choose another payment method.",Cc={width:"100%",minHeight:ya,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Sc(e){return e.includes("No ack for postMessage init()")&&Pc.some(t=>e.includes(t))&&e.includes("10000ms")}var wc={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function kc(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:wc[e.kind]??null}}function Ic(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Sc(t)?"paypal_init_timeout":"paypal_init_failure"}function Rc(e,t=!1){return e?t?`${si} Open this page in your system browser, then try again.`:`${si} Allow pop-ups for this site, then try again.`:si}function _c(e){let t=Mo(e),n=kr(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 Ec(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 Tc(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Fs({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:d,currency:u,isSubscription:h,providerObjectType:y,approvalPresentation:v,onTokenizedBody:b,onComplete:R,onErrorChange:B,onDecline:O,onTechnicalFailure:ue,isProcessing:oe=!1,onLoadStateChange:k,onInitializationStateChange:q,allowAutomaticRetry:z=!0,onButtonClick:se,runBeforeButtonClick:Ce,session:ae,existingOrderId:me,telemetry:fe,telemetryContext:pt,onInstrument:Ge,debug:ge=!1}){let Ue=Ir(),le=so(Ge,e),Se=(0,E.useMemo)(()=>{if(Ue)return null;let L=pa({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:zt.SDK_VERSION,enabled:fe!==!1});return L.setCheckoutContext(pt??{}),L.beginCheckout(pt??{}),L},[n,Ue,fe,pt?.checkoutMode,pt?.layout]),Ye=(0,E.useMemo)(()=>en(Ue),[Ue]);(0,E.useEffect)(()=>()=>{Se&&Se.flush().catch(()=>{}).finally(()=>Se.destroy())},[Se]);let X=(0,E.useMemo)(()=>({error:L=>{Ye?Ye.error(L):Se?.error(L),le({class:"technical_error",errorCode:L.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":L.errorCode,requestCategory:L.requestCategory,provider:L.provider})},log:L=>{Ye?Ye.log(L):Se?.log(L),le({class:"lifecycle",name:L.name,provider:L.provider})},performance:L=>{Ye?Ye.performance(L):Se?.performance(L)},terminal:L=>{Ye?Ye.terminal(L):Se?.terminal(L)},startTiming:()=>Ye?.now()??Se?.now()??0,elapsed:L=>Ye?.elapsed(L)??Math.max(0,(Se?.now()??L)-L)}),[le,Ye,Se]),we=(0,E.useRef)(null),ce=(0,E.useRef)(0),rt=(0,E.useRef)(null),ot=(0,E.useRef)(null),_=(0,E.useRef)(null),$=(0,E.useRef)(!1),[ye,Z]=(0,E.useState)(!1),[ke,F]=(0,E.useState)(!1),[De,mt]=(0,E.useState)(0),et=(0,E.useRef)(0),[he,U]=(0,E.useState)(!1),ne=(0,E.useRef)(!1),qe=(0,E.useRef)(!1),[ct,xe]=(0,E.useState)(!1),[Je,Me]=(0,E.useState)(!1),{request:be,collect:_e,finish:Ht}=oo(),Q=(0,E.useRef)({sessionId:e,required:!(0,zt.isValidEmail)(r?.trim()||ae?.customer?.email?.trim())});Q.current.sessionId!==e&&(Q.current={sessionId:e,required:!(0,zt.isValidEmail)(r?.trim()||ae?.customer?.email?.trim())});let Mt=Q.current.required,ft=(0,E.useMemo)(()=>n.replace(/\/+$/,""),[n]),de=ae?.gateways?.paypal?.providerObjectType??y,f=de??(h?"subscription":"order"),[A]=(0,E.useState)(ca),$e=ae?.gateways?.paypal?.approvalPresentation??v,Re=da(A,$e==="app_switch"?"app_switch":void 0,f),kt=de==="order"||de==="setup_token",st=(0,E.useMemo)(()=>JSON.stringify([ft,l,u,d??"",f,kt,Re,e,me??""]),[ft,l,u,d,me,f,kt,Re,e]),Bt=(0,E.useRef)(st),J=Bt.current!==st,Gt=(0,E.useRef)(ge),Rt=(0,E.useRef)(null),[mn,ur]=(0,E.useState)([]),j=(0,E.useCallback)(L=>{Gt.current&&ur(Te=>[...Te,`${new Date().toISOString().slice(11,23)} ${L}`])},[]);(0,E.useEffect)(()=>{Gt.current=ge,ge&&j("debug:enabled"),Rt.current?.setEnabled(ge)},[j,ge]);let yn=(0,E.useRef)(b),wn=(0,E.useRef)(R),cn=(0,E.useRef)(B),rn=(0,E.useRef)(O),fn=(0,E.useRef)(ue),Zn=(0,E.useRef)(se),dn=(0,E.useRef)(k),Yt=(0,E.useRef)(q),Ne=(0,E.useRef)(a),Ke=(0,E.useRef)(Ce),on=(0,E.useRef)(ae),yt=(0,E.useRef)(r),$n=(0,E.useRef)(o),Ft=(0,E.useRef)(t),Jt=(0,E.useRef)(null),ht=(0,E.useRef)(new Map),jt=(0,E.useRef)(new Map),un=(0,E.useRef)(!1);(0,E.useEffect)(()=>(un.current=!0,()=>{un.current=!1}),[]),(0,E.useEffect)(()=>{yn.current=b},[b]),(0,E.useEffect)(()=>{Ne.current=a},[a]),(0,E.useEffect)(()=>{wn.current=R},[R]),(0,E.useEffect)(()=>{cn.current=B},[B]),(0,E.useEffect)(()=>{rn.current=O},[O]),(0,E.useEffect)(()=>{fn.current=ue},[ue]),(0,E.useEffect)(()=>{Zn.current=se},[se]),(0,E.useEffect)(()=>{dn.current=k},[k]),(0,E.useEffect)(()=>{Yt.current=q},[q]),(0,E.useEffect)(()=>{Ke.current=Ce},[Ce]),(0,E.useEffect)(()=>{on.current=ae},[ae]),(0,E.useEffect)(()=>{yt.current=r},[r]),(0,E.useEffect)(()=>{$n.current=o},[o]),(0,E.useEffect)(()=>{Ft.current=t},[t]),(0,E.useEffect)(()=>{et.current=De},[De]),(0,E.useEffect)(()=>{he&&_.current?.focus()},[he,De]);let Dt=(0,E.useCallback)(()=>{window.setTimeout(()=>{_.current?.focus()},0)},[]),_t=(0,E.useCallback)(()=>{Z(!1),mt(L=>L+1)},[]),an=(0,E.useCallback)(()=>{U(!1),(we.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??we.current)?.focus?.()},[]);(0,E.useEffect)(()=>{!ye||!$.current||($.current=!1,an())},[an,ye,De]);let Bn=(0,E.useCallback)((L,Te)=>{let x=Te?.popupBlocked??kr(L),Nt=Rc(x,A.inAppBrowser),bn=fn.current;if(bn){let sn=x&&A.inAppBrowser?new zt.FloPayError(Nt,"api_error",{code:Te?.code??"paypal_popup_blocked"}):L;bn("paypal",sn,Te);return}cn.current?.(Nt)},[A.inAppBrowser]),Pt=(0,E.useCallback)(L=>{let Te=rt.current,x=ot.current;Te===null||!x||(X.log({...x,name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),X.performance({...x,stage:"overlay_return",durationMs:X.elapsed(Te),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),rt.current=null)},[X]),te=(0,E.useCallback)((L,Te,x)=>{let Nt=ot.current;Pt("overlay_timeout"),Nt&&X.error({...Nt,errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Bn(Te,x),U(!0),_t(),Dt()},[Pt,Dt,Bn,_t,X]),{finishAttempt:gn,generationRef:hn,invalidateAttempt:Lt,isAttemptCurrent:Ut,isAttemptInvalidated:Fn,startAttempt:Vn}=Fo(te),Qn=(0,E.useCallback)(()=>(U(!1),Vn("paypal")),[Vn]),Xt=(0,E.useCallback)(L=>{Lt(L?.generation),L?.showRetry&&U(!0),L?.remount&&_t(),L?.focus!==!1&&Dt()},[Dt,Lt,_t]),We=L=>{let Te=Jt.current;return Te&&jt.current.set(L,Te),L};(0,E.useEffect)(()=>{Bt.current!==st&&(Bt.current=st,ne.current=!1,qe.current=!1,Z(!1),F(!1),xe(!1),Yt.current?.("loading"))},[st]),(0,E.useEffect)(()=>{lt(()=>dn.current?.(ye&&!ct))},[ye,ct]);let qt=(0,zt.normalizeGatewayEnvironment)(d);(0,E.useEffect)(()=>{let L={attempt:hn.current+1,...A,presentationMode:Re},Te=()=>ot.current??L,x={error:g=>X.error({...g,...Te()}),log:g=>X.log({...g,...Te()}),performance:g=>X.performance({...g,...Te()}),terminal:g=>X.terminal({...g,...Te()}),startTiming:X.startTiming,elapsed:X.elapsed},Nt=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",bn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(j(`mount clientId=${Nt} env=${d??"(unset)"}\u2192${qt??"live"} ccy=${u} sub=${h}`),j(`ua=${bn.slice(0,80)}${bn.length>80?"\u2026":""}`),!l){j("FAIL: clientId empty \u2014 gateway misconfigured"),xe(!0),x.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){j("FAIL: containerRef not attached");return}ce.current=x.startTiming(),x.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let sn=!1,Dn=!1,ve=()=>sn||Dn,vn,xr=!1,Kr=()=>{vn=(0,zt.generateIdempotencyKey)(),vn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),xr=!0},kn=null,Er=!1,pr=null,er=!1,Kt=()=>{!pr||er||(er=!0,pr.close().catch(()=>{}))},In=!1,Cr=!1,Ln=we.current,Rn=null,tr=null,nr=[],Ct=null,Pn=!1,jn=!1,rr=null,_n=g=>{if(!g||typeof g.getBoundingClientRect!="function")return"(no rect)";let m=g.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},Xe=g=>{if(!g)return"(empty)";try{let m=new URL(g,typeof window>"u"?"https://localhost":window.location.href),w=m.pathname.toLowerCase();return w.includes("checkcaptcha")||w.includes("captcha")?`CAPTCHA(${m.host}${w})`:w.includes("risk")||w.includes("challenge")?`RISK(${m.host}${w})`:w.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${w}`.slice(0,100)}catch{return g.slice(0,80)}},tn=g=>{let m=g.getAttribute("src"),w=g.getAttribute("srcdoc"),C=g.getAttribute("name"),Pe=g.getAttribute("sandbox"),ie=[];return m&&ie.push(`src=${Xe(m)}`),w&&ie.push(`srcdoc[${w.length}ch]`),!m&&!w&&ie.push("src=(empty) srcdoc=(empty)"),C&&ie.push(`name=${C.slice(0,40)}`),Pe!==null&&ie.push(`sandbox="${Pe.slice(0,40)}"`),ie.join(" ")},pn=g=>{if(!(g instanceof HTMLIFrameElement))return"";try{let m=g.contentDocument;if(!m)return"cd=null";let w=m.body?.children.length??0,C=m.body?.innerHTML.length??0,Pe=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${w}children,${C}ch] head[${Pe}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},mr=[],Mr=g=>{if(ve())return;let m=g.message??String(g.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(j(`window:error ${m.slice(0,140)}`),mr.push(m))},or=g=>{if(ve())return;let m=g.reason instanceof Error?g.reason.message:String(g.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(j(`window:rejection ${m.slice(0,140)}`),mr.push(m))},yr={value:0},En=()=>{Rn?.disconnect(),Rn=null,tr?.disconnect(),tr=null;for(let g of nr.splice(0))clearTimeout(g);jn=!1,Pn&&typeof window<"u"&&(window.removeEventListener("error",Mr),window.removeEventListener("unhandledrejection",or)),Pn=!1},Tn=()=>{if(!(Pn||ve()||In)){if(Pn=!0,mr.length=0,yr.value=0,typeof window<"u"&&(window.addEventListener("error",Mr),window.addEventListener("unhandledrejection",or)),typeof PerformanceObserver<"u")try{tr=new PerformanceObserver(g=>{if(!ve())for(let m of g.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;yr.value+=1;let w=Math.round(m.duration);j(`net ${w}ms ${m.name.slice(0,90)}`)}}),tr.observe({type:"resource",buffered:!0})}catch{}rr?.()}},Br=()=>{Ct&&(clearTimeout(Ct),Ct=null)},Nn=()=>{En(),Br()},Fr={setEnabled:g=>{g?Tn():En()}};Rt.current=Fr,Gt.current&&Tn();let Zt=g=>{if(!g)return!1;let m=g.toLowerCase();return m.includes("zoid destroyed")||m.includes("destroyed all components")||m.includes("window closed")||m.includes("detected container element removed")},M=g=>{if(ve()||Zt(g))return;let m=Tr(g)??g;lt(()=>cn.current?.(m))},P=(g,m)=>{if(sn||Er)return;Er=!0,Dn=!0,Nn(),Kt();let w=kc({kind:g,generationActive:!0,automaticRetryAllowed:z,automaticRetryUsed:ne.current});if(w.action==="retry"){ne.current=!0,Z(!1),Me(!1),F(!0),Yt.current?.("retrying"),kn=setTimeout(()=>{sn||mt(C=>C+1)},bc);return}if(Z(!1),Me(!1),F(!1),xe(!0),w.action!=="ignore"){if(Yt.current?.("exhausted"),w.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",m);return}w.report&&x.error({errorCode:w.report.errorCode,stage:w.report.stage,operationOutcome:w.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),qe.current||(qe.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Ic(g,m)))}};xe(!1);let ee=async(g,m=Jt.current)=>{if(ve())return;let w=m?.sessionId??e;if(yn.current){await yn.current(g,{sessionId:w,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let C=x.startTiming();x.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=()=>{x.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),x.performance({stage:"processing",durationMs:x.elapsed(C),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ie=on.current,Ae=m?.accountPatch?.email??yt.current,N=m?.accountPatch?.userId??ie?.customer?.id??ie?.accountData?.userId??"",at=m?.accountPatch?.firstName??ie?.customer?.firstName??ie?.accountData?.firstName,re=m?.accountPatch?.lastName??ie?.customer?.lastName??ie?.accountData?.lastName,Oe=await new ma.PaymentAPI(ft,{telemetry:!1}).processPayment(N,{sessionId:w,nonce:m?.nonce??Ft.current,paymentMethodCategory:"paypal",tokenizedData:g,accountData:{userId:N,email:Ae??ie?.customer?.email??"",...at?{firstName:at}:{},...re?{lastName:re}:{},country:m?.accountPatch?.country??ie?.customer?.country??ie?.accountData?.country??void 0,zip:m?.accountPatch?.zip??ie?.customer?.zip??ie?.accountData?.zip??void 0}});if(Oe.ok){if(Dn||sn&&un.current)return;Pe(),x.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),lt(()=>wn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ve())return;let Ze=await Oe.json().catch(()=>null),W=Ze?.message??"PayPal payment failed.",ze=Tr(W)??W;Pe(),Oe.status===400&&(typeof Ze?.declineCode=="string"||!Array.isArray(Ze?.fields))?x.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Oe.status===400||Oe.status===422?x.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):x.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Tc(Oe.status),failureCategory:Oe.status>=500?"server_error":void 0}),M(ze),lt(()=>rn.current?.(nn("paypal",ze,{code:Ze?.code,declineCode:Ze?.declineCode})));return}catch(ie){if(ve())return;Pe(),x.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ae=ie instanceof Error?ie.message:"PayPal payment failed.",N=Tr(Ae)??Ae;M(N),lt(()=>rn.current?.(nn("paypal",N)));return}},K=()=>new zt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Be=g=>ve()?Promise.reject(K()):Promise.resolve(g),tt=async g=>{if(ve())throw K();xr||Kr();let m=Jt.current,w=m?.sessionId??e,C=m?.nonce??Ft.current;x.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Pe;try{Pe=await new ma.PaymentAPI(ft,{telemetry:!1}).createSessionIntent(w,C??"",kt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:zt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:f==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:vn})}catch(ie){throw x.error({...(0,zt.classifyTelemetryFailure)(ie,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ie}if(ve())throw K();if(Pe.provider!=="paypal"||Pe.providerObjectType!==f)throw new Error(g);return x.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Pe.providerObjectId},Le=(g,m)=>{let w=m?.nonce??Ft.current;if(!w)return;let C=m?.sessionId??e,Pe=io(g)??wr(g)??"provider_declined";new ma.PaymentAPI(ft,{telemetry:!1}).reportSessionIntentDecline(C,w,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Pe}).catch(()=>{})},G=De;j("loadScript:scheduled (deferred 1 tick)");let pe=null,V=setTimeout(()=>{if(sn){j("loadScript:skipped (cancelled before defer ran)");return}j("loadScript:start");let g=qt==="live"?"production":qt,m={};f==="subscription"?m={intent:"subscription",vault:!0}:f==="order"&&(m={intent:"capture"}),pe=(0,Bs.loadScript)({clientId:l,currency:u,...m,...g?{environment:g}:{},...g==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let w=!1;pe.then(C=>{if(w=!0,j(`loadScript:resolved inactive=${ve()} ns=${!!C} buttons=${!!C?.Buttons}`),ve())return;if(!C?.Buttons){j("FAIL: namespace missing Buttons factory"),P("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}x.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),x.performance({stage:"provider_ready",durationMs:x.elapsed(ce.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),x.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=async(Oe,Ze)=>{if(ve()||et.current!==G)return;let W=Oe.vaultSetupToken??Oe.subscriptionID??Oe.orderID??"",ze=W?jt.current.get(W):ht.current.get(G);if(!(!ze||!Ut(ze.generation))&&gn(ze.generation)){jt.current.delete(W),ht.current.delete(ze.surfaceKey),Pt("approved");try{if(Me(!0),lt(()=>cn.current?.(null)),!W)throw new zt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Fe=on.current,gt=zr($n.current??[Fe?.customer?.firstName,Fe?.customer?.lastName].filter(Boolean).join(" ")),He=Mn({email:ze.accountPatch?.email?.trim()||yt.current?.trim()||Fe?.customer?.email?.trim(),firstName:ze.accountPatch?.firstName?.trim()||gt.firstName,lastName:ze.accountPatch?.lastName?.trim()||gt.lastName});if(!(0,zt.isValidEmail)(He.email)||!(He.firstName||He.lastName))try{let zn=Ec(await Ze?.order?.get?.());He=Mn({email:zn.email||He.email,firstName:zn.firstName||He.firstName,lastName:zn.lastName||He.lastName})}catch{}if((Ne.current||Mt)&&!(0,zt.isValidEmail)(He.email)){let zn=await _e("PayPal",He);if(!zn)return;He=zn}(0,zt.isValidEmail)(He.email)&&(ze.accountPatch=Mn({...ze.accountPatch,...He}),await Ne.current?.(He));let On;f==="setup_token"?On={id:W,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:zt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:kt?On={id:W,isPaypal:!0,gateway:"paypal",paymentMethodType:zt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:On={id:W,isPaypal:!0},await ee(On,ze)}catch(Fe){M(Fe instanceof Error?Fe.message:"PayPal capture failed.")}finally{ve()||Me(!1)}}},ie=Oe=>{let Ze=me?()=>Be(me):()=>tt(Oe);return async()=>We(await Ze())},Ae=C.Buttons({style:{layout:"horizontal",height:ya,tagline:!1},...Re==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Oe,Ze)=>{if(ve()){await Ze.reject();return}Kr();let W=Ke.current,ze={};if(W)try{let He=await W("paypal");if(ve()){await Ze.reject();return}if(!He.proceed){Jt.current=null,ht.current.delete(G),await Ze.reject();return}ze={sessionId:He.sessionId,accountPatch:He.accountPatch,nonce:He.nonce}}catch(He){j(`onClick:runBeforeButtonClick rejected msg=${(He instanceof Error?He.message:String(He)).slice(0,120)}`),Jt.current=null,ht.current.delete(G),await Ze.reject();return}lt(()=>Zn.current?.("paypal"));let Fe=Qn(),gt={generation:Fe,surfaceKey:G,...ze};Jt.current=gt,ht.current.set(G,gt),ot.current={...L,attempt:Fe},await Ze.resolve(),x.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),x.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),rt.current=x.startTiming()},createOrder:f==="order"?ie("Failed to create PayPal order."):void 0,createSubscription:f==="subscription"?ie("Failed to create PayPal subscription."):void 0,createVaultSetupToken:f==="setup_token"?async()=>We(await tt("Failed to create PayPal setup token.")):void 0,onApprove:Pe,onCancel:()=>{if(ve())return;let Oe=ht.current.get(G)??Jt.current;Oe&&ht.current.delete(Oe.surfaceKey),Jt.current=null,Pt("cancelled"),x.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),$.current=!0,Xt({generation:Oe?.generation,remount:!0,focus:!1})},onError:Oe=>{if(ve()||et.current!==G)return;let Ze=Oe instanceof Error?Oe.message:"PayPal failed to render.";if(j(`onError rendered=${In} msg=${Ze.slice(0,120)}`),In){let W=ht.current.get(G)??Jt.current;if(W&&!Ut(W.generation)||!W&&Fn())return;if(Zt(Ze)){gn(W?.generation);return}let{errorCode:ze,popupBlocked:Fe,providerDeclined:gt,terminalReason:He}=_c(Oe);if(Pt(He),gt){x.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:He}),Le(Oe,W),lt(()=>rn.current?.(nn("paypal",Ze))),W&&ht.current.delete(W.surfaceKey),Jt.current=null,gn(W?.generation);return}x.error({errorCode:ze,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:He}),W&&ht.current.delete(W.surfaceKey),Jt.current=null,Xt({generation:W?.generation,remount:!0,showRetry:!0,focus:!0}),Bn(Oe,{code:"paypal_runtime_failed",popupBlocked:Fe});return}P(Zt(Ze)?"teardown":"pre_ready_callback",Ze)}}),N=Ae.isEligible();if(j(`isEligible=${N}`),x.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!N){Z(!1),P("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Cr=!0,pr=Ae,rr=()=>{if(!Pn||jn||ve()||In)return;jn=!0,j(`container:dims ${_n(Ln)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Rn=new MutationObserver(Ze=>{if(!ve()){for(let W of Ze)if(W.type==="childList")W.addedNodes.forEach(ze=>{if(!(ze instanceof Element))return;let Fe=ze.tagName.toLowerCase(),gt=(ze.getAttribute("title")??"").slice(0,40),He=Fe==="iframe"?` ${tn(ze)}`:"";j(`child+ ${Fe}${gt?` title="${gt}"`:""}${He} dims=${_n(ze)}`)});else if(W.type==="attributes"&&W.target instanceof Element){let ze=W.target;if(ze.tagName.toLowerCase()!=="iframe")continue;let Fe=W.attributeName;(Fe==="src"||Fe==="srcdoc")&&j(`attr~ iframe ${Fe}=${Fe==="srcdoc"?`[${(ze.getAttribute("srcdoc")??"").length}ch]`:Xe(ze.getAttribute("src"))} dims=${_n(ze)}`)}}}),Rn.observe(Ln,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Oe=Ze=>{if(ve()||In)return;let W=Ln.querySelectorAll("iframe"),ze=typeof document<"u"&&"hasStorageAccess"in document;j(`watchdog:${Ze} container=${_n(Ln)} children=${Ln.childElementCount} iframes=${W.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${ze} paypalNetRequests=${yr.value}`),W.forEach((Fe,gt)=>{let He=(Fe.getAttribute("title")??"").slice(0,40);j(` iframe[${gt}] ${_n(Fe)}${He?` title="${He}"`:""} ${tn(Fe)}`);let On=pn(Fe);On&&j(` ${On}`)}),mr.length===0&&j(" (no PayPal/zoid window errors captured)")};nr.push(setTimeout(()=>Oe("3s"),3e3)),nr.push(setTimeout(()=>Oe("8s"),8e3)),nr.push(setTimeout(()=>Oe("15s"),15e3))},rr(),j("render:start");let re=x.startTiming();Ct=setTimeout(()=>{ve()||In||(j("watchdog:11s retryable render timeout"),P("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},vc);let Et=Ae.render(Ln);(async()=>{try{if(await Et,j(`render:resolved inactive=${ve()}`),Nn(),ve()){Kt();return}In=!0,Z(!0),F(!1),Yt.current?.("ready"),x.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),x.performance({stage:"checkout_render",durationMs:x.elapsed(re),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Oe){let Ze=Oe instanceof Error?Oe.message:"PayPal failed to render.";j(`render:rejected msg=${Ze.slice(0,120)}`),Nn(),P(Zt(Ze)?"teardown":"render_rejected",Ze)}})()}).catch(C=>{let Pe=C instanceof Error?C.message:"PayPal operation failed.";j(`provider:failed msg=${Pe.slice(0,120)}`);let ie="script_rejected";w&&Zt(Pe)?ie="teardown":w&&Cr&&(ie="render_rejected"),P(ie,Pe)})},0);return()=>{sn=!0,clearTimeout(V),kn&&clearTimeout(kn),Nn(),Rt.current===Fr&&(Rt.current=null),Kt(),rt.current=null,ot.current=null}},[z,ft,l,u,d,f,Re,kt,e,me,De,X,_e,Mt,j,Pt]);let Ee=ge?(0,Yn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ct?"#fef2f2":"#f3f4f6",border:`1px solid ${ct?"#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=${ye} failed=${ct})`,mn.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return
|
|
3
|
+
${mn.join(`
|
|
4
|
+
`)}`]}):null;return ct&&!J?ge?(0,Yn.jsx)("div",{children:Ee}):null:(0,Yn.jsxs)("div",{children:[Ee,be&&(0,Yn.jsx)(ao,{identity:be.identity,methodLabel:be.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Ht,onCancel:()=>Ht(null)}),(0,Yn.jsxs)("div",{"aria-hidden":ke||be?!0:void 0,style:ke||be?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ya},children:[!ye&&!ke&&(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:we,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ya,display:"flex",opacity:ye?1:0},"aria-busy":Je||oe},De)]},De),he&&(0,Yn.jsx)("button",{ref:_,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:an,style:Cc,children:"Try PayPal again"})]})}function Do(e){return(0,Yn.jsx)(Fs,{...e})}function Ds(e){return(0,Yn.jsx)(Fs,{...e})}var Lo=require("react/jsx-runtime");function lo({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,Lo.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,Lo.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Lo.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 fa=require("@flopay/shared");function co(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var ci=":idempotency-key";function di(e,t){if(!co())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 ui(e,t){if(!co())return null;try{let n=window.sessionStorage.getItem(e+ci);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 ga(e,t){if(co())try{di(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ha(e,t){if(ga(e,t),!!co())try{ui(e,t)&&window.sessionStorage.removeItem(e+ci)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function ba(e,t,n,r){if(co())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 va(e,t,n){if(co())try{window.sessionStorage.setItem(e+ci,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function li(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Ac(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 uo(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=>li(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>li(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>li(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Ac(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Ls(e,t=!1){let n=uo(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 Ns(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,fa.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,fa.foldIntoProducts)(t.items,t.subscriptions)).map(h=>({type:h.type,code:h.code??h.providerItemId??h.providerPlanId??"",quantity:h.quantity??1,totalAmount:h.totalAmount,overrideAmount:h.overrideAmount??null,currency:(h.currency??o).toUpperCase()})).sort((h,y)=>`${h.code}:${h.type??""}`.localeCompare(`${y.code}:${y.type??""}`)),l=e.products.map(h=>({type:h.type,code:h.code??"",quantity:h.quantity??1,totalAmount:h.totalAmount,overrideAmount:h.overrideAmount??null,currency:(h.currency??e.currency).toUpperCase()})).sort((h,y)=>`${h.code}:${h.type??""}`.localeCompare(`${y.code}:${y.type??""}`));if(a.length!==l.length)return!1;for(let[h,y]of a.entries()){let v=l[h];if(v===void 0||y.code!==v.code||y.type!==void 0&&y.type!==v.type||y.quantity!==v.quantity||y.totalAmount!==v.totalAmount||y.overrideAmount!==v.overrideAmount||y.currency!==v.currency)return!1}let d=[...t.couponCodes??[]].sort(),u=[...e.coupons??[]].sort();return d.length===u.length&&d.every((h,y)=>h===u[y])}var Wt=require("react/jsx-runtime");var xc={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=xc}){let u={fontSize:13,color:d.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,Wt.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,Wt.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,Wt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,Wt.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,Wt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:d.spinnerTrackColor,strokeWidth:"3"}),(0,Wt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:d.spinnerAccentColor})]}),e==="success"&&(0,Wt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,Wt.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,Wt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,Wt.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,Wt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,Wt.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,Wt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,Wt.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,Wt.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,Wt.jsx)("p",{style:u,children:l}),e==="error"&&t&&(0,Wt.jsx)("p",{style:u,children:t}),(0,Wt.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 Ds=require("@flopay/shared"),cn=require("react");var Ls=require("react/jsx-runtime");function Lo({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=(0,cn.useState)(e instanceof Promise?null:e),[d,u]=(0,cn.useState)(t instanceof Promise||!t?null:t),b=(0,cn.useRef)(null),f=(0,cn.useRef)(null),P=io(r);(0,cn.useEffect)(()=>{P({class:"lifecycle",name:"checkout.mount"})},[P]),(0,cn.useEffect)(()=>{a&&P({class:"lifecycle",name:"sdk.initialize.ready"})},[P,a]),(0,cn.useEffect)(()=>{if(a)return tn(a)?.subscribe?.(P)},[P,a]),(0,cn.useEffect)(()=>{if(!(!d||d===a))return tn(d)?.subscribe?.(P)},[P,a,d]),(0,cn.useEffect)(()=>{if(!a)return;let M=tn(a);return b.current=M?.beginCheckout()??M?.now()??0,M?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{M?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,cn.useEffect)(()=>{let M=!1;return e instanceof Promise?e.then(N=>{M||l(N)},()=>{M||P({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{M=!0}},[P,e]),(0,cn.useEffect)(()=>{let M=!1;if(!t){u(null);return}return t instanceof Promise?t.then(N=>{M||u(N)},()=>{M||P({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):u(t),()=>{M=!0}},[P,t]),(0,cn.useEffect)(()=>{if(!a||f.current===a)return;f.current=a;let M=tn(a);M?.log({name:"checkout.rendered",stage:"checkout_render"}),P({class:"lifecycle",name:"checkout.rendered"}),M?.performance({stage:"checkout_render",durationMs:M.elapsed(b.current??0),durationMode:"machine"})},[P,a]);let v=(0,Ds.resolveBillingApiUrl)(n?.billingApiUrl),I=(0,cn.useMemo)(()=>({flopay:a,paypalFlopay:d,billingApiUrl:v,emitInstrument:P}),[a,d,v,P]);return(0,Ls.jsx)(Hn.Provider,{value:I,children:o})}var va="flopay_recent_completion_";function uo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(va+e,JSON.stringify(t))}catch{}}function ci(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(va+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(va+e),!1):!0}catch{return!1}}var po=require("@flopay/js"),Qe=require("@flopay/shared");var Oo="card";async function Tc(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 Ac(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 ui(e,t){return Object.assign(e,{checkoutMethod:t})}function kr(e,t){let n=e instanceof Qe.FloPayError?e:new Qe.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 kr(n,t)}}function Os(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function xc(e){return e.status==="succeeded"||e.status==="declined"}async function zs(e){if(typeof document>"u"||typeof window>"u")throw new Qe.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Qe.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 f=new AbortController,P=()=>f.abort();e.signal?.aborted?f.abort():e.signal?.addEventListener("abort",P);let v=window.setTimeout(()=>f.abort(),r);try{let I=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:f.signal});if(!I.ok)return{status:"unknown"};let M=await I.json().catch(()=>null);return Mc(M)}catch{return{status:"unknown"}}finally{window.clearTimeout(v),e.signal?.removeEventListener("abort",P)}},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 u=document.createElement("iframe");u.setAttribute("title","Card authentication"),u.setAttribute("allow","payment"),u.tabIndex=0,u.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(";"),u.src=e.nextActionRedirectUrl,d.appendChild(u),document.body.appendChild(d),u.focus();let b=null;try{b=new URL(e.billingApiUrl,window.location.href).origin}catch{b=null}try{let f=await new Promise((P,v)=>{let I=!1,M=0,N=0,pe=0,ae=!1,w=()=>{window.clearTimeout(M),window.clearInterval(N),window.clearTimeout(pe),window.removeEventListener("message",Se),u.removeEventListener("load",O),e.signal?.removeEventListener("abort",le)},q=async()=>{if(!(I||ae)){ae=!0;try{let ie=await a();if(I||!xc(ie))return;I=!0,w(),P(ie)}finally{ae=!1}}},O=()=>{window.clearTimeout(pe),pe=window.setTimeout(()=>{q()},250)},le=()=>{I||(I=!0,w(),v(new Qe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Se=ie=>{if(ie.source!==u.contentWindow||b&&ie.origin!==b)return;let ye=ie.data;!ye||typeof ye!="object"||ye.source!=="flopay-vault-3ds-return"||I||(I=!0,w(),P(null))};M=window.setTimeout(()=>{I||(I=!0,w(),v(new Qe.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),N=window.setInterval(()=>{q()},n),u.addEventListener("load",O),window.addEventListener("message",Se),e.signal?.addEventListener("abort",le),e.signal?.aborted&&le()});return f||await a()}finally{d.parentNode?.removeChild(d),l?.isConnected&&l.focus()}}function Mc(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Ar(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=Tr(o)??o;return ui(new Qe.FloPayError(a,"api_error",{code:(0,Qe.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Qe.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function di(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Pa(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Us(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Pa(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||Pa(d)))return d;let l=o.gateways;if(l&&typeof l=="object"){let d=l.stripe;if(d&&typeof d=="object"){let u=d,b=[u.stripeClientSecret,u.clientSecret];for(let f of b)if(typeof f=="string"&&f.length>0&&(!t?.requirePaymentIntentClientSecret||Pa(f)))return f}}}}async function Bc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Us(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 po.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Pa(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function mo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let d=e.replace(/\/+$/,""),u=t??n.id,b=r??n.clientSecret,f=n.customer?.id??n.accountData?.userId??"",P=n.customer?.email??n.accountData?.email??"",v=n.customer?.firstName??n.accountData?.firstName??"",I=n.customer?.lastName??n.accountData?.lastName??"",M=n.customer?.country??n.accountData?.country??void 0,N=n.customer?.zip??n.accountData?.zip??void 0,ae=await new po.PaymentAPI(d,l===!1?{telemetry:!1}:void 0).processPayment(f,{sessionId:u,nonce:b,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:f,email:P,firstName:v,lastName:I,country:M,zip:N},returnUrl:a??di(n)});if(ae.ok){let O=typeof ae.json=="function"?await ae.json().catch(()=>null):null;return(0,Qe.isAuthorizationOnlySession)(n)||O?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof O?.paymentId=="string"?O.paymentId:n.paymentId,sessionId:typeof O?.sessionId=="string"?O.sessionId:u,authorizationExpiresAt:typeof O?.authorizationExpiresAt=="string"?O.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Ao(o),checkoutMethod:Ns(o)}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Ao(o),checkoutMethod:Ns(o)}}}let w;try{w=await ae.json()}catch(O){throw new Qe.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:ae.status,cause:O})}if(w?.type==="paypal_redirect_required"||w?.type==="3ds_required"){let O=Us(w);if(!O)throw new Qe.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:ae.status});return{type:w.type,threeDSecureToken:O,paymentMethodId:w.paymentMethodId}}if(w?.gatewayErrorCode==="authentication_required"){let O=await Bc({billingApiUrl:d,sessionId:u,nonce:b,responseJson:w});if(O)return O;throw ui(new Qe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let q=new Qe.FloPayError(w?.message??"Payment failed. Please try again.","api_error",{code:w?.code??w?.gatewayErrorCode,declineCode:w?.declineCode??w?.gatewayDeclineReason,statusCode:ae.status});throw Object.assign(q,{telemetryOutcome:(0,Qe.classifyPaymentRejection)(ae.status,w)})}async function Ca(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:d,telemetry:u}){let b=t?.getRawProvider();if(!b)throw kr(new Qe.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw ui(new Qe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let f=(0,Qe.isSetupIntentClientSecret)(e.threeDSecureToken),P=null,v=e.paymentMethodId,I=await No(()=>Tc(b,e.threeDSecureToken,f),"card");if(I){if(I.error)throw kr(new Qe.FloPayError(I.error.message??`Failed to retrieve 3DS ${f?"setup":"payment"} status.`,"api_error",{code:I.error.code}),"card");let N=I.intent;!v&&N?.payment_method&&(typeof N.payment_method=="string"?v=N.payment_method:"id"in N.payment_method&&(v=N.payment_method.id??void 0))}let M=v?await No(()=>Ac(b,e.threeDSecureToken,{payment_method:v,return_url:d??di(l)??window.location.href},f),"card"):null;if(M){if(M.error)throw kr(new Qe.FloPayError(M.error.message??"3DS authentication failed.","api_error",{code:M.error.code}),"card");P=M.intent}else{let N=await No(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(N.error)throw kr(new Qe.FloPayError(N.error.message??"3DS authentication failed.","api_error",{code:N.error.code}),"card");P=(f?N.setupIntent:N.paymentIntent)??null}if(P&&(P.status==="requires_capture"||P.status==="succeeded"||P.status==="processing")){let N=await mo({billingApiUrl:o,sessionId:a,session:l,telemetry:u,tokenizedData:{id:P.id,type:"card",threeDSecureActionResultTokenId:P.id},returnUrl:d});return N.type==="success"?{...N.result,paymentIntentId:N.result.paymentIntentId??P.id,paymentMethodId:N.result.paymentMethodId??v}:Ca(N,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:d,telemetry:u})}throw kr(new Qe.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let f=(n??t)?.getRawProvider();if(!f)throw kr(new Qe.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:v}=await No(()=>f.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(v)throw kr(new Qe.FloPayError(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:P}=await No(()=>f.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??di(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(P)throw kr(new Qe.FloPayError(P.message??"PayPal authorization failed.","api_error",{code:P.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Qe.FloPayError("Unsupported payment redirect state.","api_error")}function zo(e){if(e instanceof Qe.FloPayError){let r=Tr(e.message);return r&&r!==e.message?Object.assign(new Qe.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=Tr(t)??t;return new Qe.FloPayError(n,"api_error")}function pi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html;if(!t&&!n&&!r)throw new Qe.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 Ns(e){if(e)return e.isPaypal?"paypal":"card"}async function mi({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,po.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,po.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(b=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",b),null)):Promise.resolve(null)]);if(!l)throw new Qe.FloPayError("The payment provider did not initialize.","authentication_error");let u=null;return a?u=d:t&&(u=l),{flopay:l,paypalFlopay:u}}var or=require("@flopay/js"),p=require("@flopay/shared"),Vt=require("@stripe/react-stripe-js"),s=fs(require("react"),1);var qs={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var Nn=require("react");function $s(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 Fc=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 Dc(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Fc.has(t.charAt(0).toLowerCase()+t.slice(1))}function Lc(e,t){return typeof t=="number"&&t!==0&&!Dc(e)?`${t}px`:String(t).trim()}function Vs(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]=Lc(n,r)}}}var js=require("react/jsx-runtime"),yi=new WeakSet;function yo({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:l,onReady:d,onError:u,onValidation:b}){let f=(0,Nn.useRef)(null),P=(0,Nn.useRef)(d),v=(0,Nn.useRef)(u),I=(0,Nn.useRef)(b);P.current=d,v.current=u,I.current=b;let M=(0,Nn.useRef)(o);M.current=o;let N=(0,Nn.useRef)(null),pe=a??void 0,ae=(0,Nn.useRef)(pe);ae.current=pe;let w=(0,Nn.useRef)(void 0);return(0,Nn.useEffect)(()=>{let q=f.current;if(!q)return;let O=!0,le=!1,Se=()=>{!O||le||(le=!0,P.current?.())},ie=e.on("ready",()=>{Se()}),ye=e.on("error",be=>{v.current?.(be.message??"There was a problem loading the secure card form.")}),he=e.on("validation",be=>{I.current?.(be.message??null)}),dt=ae.current??(yi.has(e)?null:void 0),Je={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...M.current?{theme:M.current}:{},...dt===void 0?{}:{submitLabel:dt}};return N.current=M.current??null,w.current=ae.current,ae.current!==void 0&&yi.add(e),e.mount(q,Je).then(()=>{Se()}).catch(be=>{O&&v.current?.(be instanceof Error?be.message:"Failed to load the secure card form.")}),()=>{O=!1,ie(),ye(),he(),e.unmount()}},[e,t,n,r]),qr(()=>{let q=f.current;q&&Vs(q,l)},[l]),(0,Nn.useEffect)(()=>{o!==void 0&&(o===null&&N.current===null||(N.current=o,e.applyTheme?.(o)))},[e,o]),(0,Nn.useEffect)(()=>{pe!==w.current&&(w.current=pe,pe!==void 0&&yi.add(e),e.setSubmitLabel?.(pe??null))},[e,pe]),(0,js.jsx)("div",{ref:f,"data-testid":"flopay-vault-card-fields"})}var Ws=/^#([0-9a-f]{6})$/i,Nc=/^#([0-9a-f]{3})$/i,Hs=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Gs=/^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,Oc=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,zc=/^(-?\d+(?:\.\d+)?)(?:px)?$/,Uc=/^(-?\d+(?:\.\d+)?)em$/,qc=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,$c=/^[a-z][a-z0-9 -]{0,31}$/i,Vc=new Set(["none","uppercase","lowercase","capitalize"]);function Ys(e){if(typeof e!="string")return null;let t=e.trim(),n=Ws.exec(t);if(n){let f=Number.parseInt(n[1],16);return{r:f>>16&255,g:f>>8&255,b:f&255,a:null}}let r=Nc.exec(t);if(r){let[f,P,v]=r[1].split("").map(I=>Number.parseInt(I+I,16));return{r:f,g:P,b:v,a:null}}let o=Hs.exec(t),a=o?null:Gs.exec(t),l=o??a;if(!l)return null;let d=Number(l[1]),u=Number(l[2]),b=Number(l[3]);return d>255||u>255||b>255?null:{r:d,g:u,b,a:a?Number(a[4]):null}}function Js({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 Uo(e){if(typeof e!="string")return;let t=e.trim();if(Ws.test(t)||Hs.test(t))return t;let n=Gs.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=Ys(t);return r?Js(r):void 0}function Sa(e,t=.12){let n=Ys(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Js({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function qo(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=zc.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function jc(e,t,n){if(typeof e!="string")return;let r=Uc.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Kc(e){let t=qo(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=qo(o," "),l=Uo(a[0]);if(!l)return;let d=r/(t.length-1)*100,u=a[1]===void 0?d:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),b=n[n.length-1]?.position??-1;if(!Number.isFinite(u)||u<0||u>100||u<b)return;n.push({color:l,position:u})}return{type:"linearGradient",angle:0,stops:n}}function Wc(e){if(typeof e!="string")return;let t=e.trim(),n=Uo(t);if(n)return{type:"solid",color:n};let r=Oc.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=Kc(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function Hc(e){return e.type==="solid"?{type:"solid",color:Sa(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:Sa(t.color)}))}}function Gc(e){let t=!1,n,r=[];for(let u of qo(e," ")){if(u.toLowerCase()==="inset"){t=!0;continue}let b=Uo(u);if(b){n=b;continue}let f=Vr(u,-128,128);if(f===void 0)return;r.push(f)}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 Yc(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=qo(t,",").map(Gc);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function Ks(e){if(typeof e!="string")return;let t=qo(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>$c.test(n)).slice(0,4);return t.length>0?t:void 0}function Jc(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 Xc(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 Xs({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=Wc(r.background??r.backgroundColor),l=Uo(o?.colorPrimaryHover),d=l?{type:"solid",color:l}:a&&Hc(a),u={fontFamilies:Ks(r.fontFamily)??Ks(n),fontSize:Vr(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:Xc(r.fontWeight)??600,letterSpacing:jc(r.letterSpacing,-.1,.5)??.01,lineHeight:Vr(r.lineHeight,.8,2)??1,textTransform:Vc.has(String(r.textTransform))?r.textTransform:"uppercase"},b=Jc(r.padding),f=Yc(r.boxShadow),P=Vr(r.borderRadius,0,9999),v=typeof r.backdropFilter=="string"?Vr(qc.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Uo(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...d?{hoverBackground:d}:{},typography:u,...b?{spacing:b}:{},...f?{shadow:f}:{},...P===void 0?{}:{borderRadius:P},disabledOpacity:e?.theme==="night"?.8:.6,...v===void 0?{}:{backdropBlur:v}}}function fo(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)?Sa(r,t):e}function fi(e){if(typeof e=="number"||typeof e=="string")return e}function wa({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=P=>typeof P=="string"&&P?P:void 0,a=t.submitButton,l=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",d=n==="buttons",u=t.nameInput,b=o(u?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",f=Xs({appearance:e,buttonsStyles:t,fontFamily:b});return{primaryColor:l,primaryHoverColor:o(r?.colorPrimaryHover)??fo(l,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(u?.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:b,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(fi(u?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...f?{submitButton:f}:{}}}var c=require("react/jsx-runtime"),fr="flopay_stripe_resume",Zs="flopay_wallet_resume",dl="fw1",Zc="fw2",ul=300*1e3,Qc=900,ed=25e3,td=25e3,nd=1e4,gi={},hi={};function Ii(e){return`${Zc}:${e}`}function ka(e){if(typeof window>"u")return!1;try{return localStorage.removeItem(Ii(e)),!0}catch{return!1}}function Ia(e,t){if(typeof window>"u")return null;let n=Ii(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>ul||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(ka(e),null):o}catch{return ka(e),null}}function rd(e){if(typeof window>"u")return!1;try{return localStorage.setItem(Ii(e.sessionId),JSON.stringify(e)),!0}catch{return!1}}function Qs(e,t,n){let r=Ia(e,t);return!r||r.clientSecret!==n?!1:ka(e)}function bi(e,t,n){if(typeof window>"u")return;Ia(e,t)?.clientSecret===n&&ka(e)}function od(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function vi(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":To(e.status),o=od(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function el(e,t,n){let r=null;try{return await Promise.race([ws(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},nd),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function ad(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function pl(e){return e instanceof p.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function _a(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new or.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw pl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var $o="flopay_paypal_resume",id=250,tl="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Ri(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Ea({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new or.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function sd(e){return e instanceof p.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 ml({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=Or(n),l=a.firstName?a:Or(r?.name);return xn({email:(0,p.isValidEmail)(o)?o:r?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function ld({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=ml({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 cd=`
|
|
9
|
+
`})]})})}var Os=require("@flopay/shared"),ln=require("react");var zs=require("react/jsx-runtime");function No({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=(0,ln.useState)(e instanceof Promise?null:e),[d,u]=(0,ln.useState)(t instanceof Promise||!t?null:t),h=(0,ln.useRef)(null),y=(0,ln.useRef)(null),v=so(r);(0,ln.useEffect)(()=>{v({class:"lifecycle",name:"checkout.mount"})},[v]),(0,ln.useEffect)(()=>{a&&v({class:"lifecycle",name:"sdk.initialize.ready"})},[v,a]),(0,ln.useEffect)(()=>{if(a)return en(a)?.subscribe?.(v)},[v,a]),(0,ln.useEffect)(()=>{if(!(!d||d===a))return en(d)?.subscribe?.(v)},[v,a,d]),(0,ln.useEffect)(()=>{if(!a)return;let B=en(a);return h.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(O=>{B||l(O)},()=>{B||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{B=!0}},[v,e]),(0,ln.useEffect)(()=>{let B=!1;if(!t){u(null);return}return t instanceof Promise?t.then(O=>{B||u(O)},()=>{B||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):u(t),()=>{B=!0}},[v,t]),(0,ln.useEffect)(()=>{if(!a||y.current===a)return;y.current=a;let B=en(a);B?.log({name:"checkout.rendered",stage:"checkout_render"}),v({class:"lifecycle",name:"checkout.rendered"}),B?.performance({stage:"checkout_render",durationMs:B.elapsed(h.current??0),durationMode:"machine"})},[v,a]);let b=(0,Os.resolveBillingApiUrl)(n?.billingApiUrl),R=(0,ln.useMemo)(()=>({flopay:a,paypalFlopay:d,billingApiUrl:b,emitInstrument:v}),[a,d,b,v]);return(0,zs.jsx)(Gn.Provider,{value:R,children:o})}var Pa="flopay_recent_completion_";function po(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Pa+e,JSON.stringify(t))}catch{}}function pi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Pa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Pa+e),!1):!0}catch{return!1}}var mo=require("@flopay/js"),Qe=require("@flopay/shared");var zo="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 Bc(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 yi(e,t){return Object.assign(e,{checkoutMethod:t})}function Rr(e,t){let n=e instanceof Qe.FloPayError?e:new Qe.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 Oo(e,t){try{return await e()}catch(n){throw Rr(n,t)}}function qs(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 $s(e){if(typeof document>"u"||typeof window>"u")throw new Qe.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Qe.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,v=()=>y.abort();e.signal?.aborted?y.abort():e.signal?.addEventListener("abort",v);let b=window.setTimeout(()=>y.abort(),r);try{let R=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:y.signal});if(!R.ok)return{status:"unknown"};let B=await R.json().catch(()=>null);return Dc(B)}catch{return{status:"unknown"}}finally{window.clearTimeout(b),e.signal?.removeEventListener("abort",v)}},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 u=document.createElement("iframe");u.setAttribute("title","Card authentication"),u.setAttribute("allow","payment"),u.tabIndex=0,u.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(";"),u.src=e.nextActionRedirectUrl,d.appendChild(u),document.body.appendChild(d),u.focus();let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}try{let y=await new Promise((v,b)=>{let R=!1,B=0,O=0,ue=0,oe=!1,k=()=>{window.clearTimeout(B),window.clearInterval(O),window.clearTimeout(ue),window.removeEventListener("message",Ce),u.removeEventListener("load",z),e.signal?.removeEventListener("abort",se)},q=async()=>{if(!(R||oe)){oe=!0;try{let ae=await a();if(R||!Fc(ae))return;R=!0,k(),v(ae)}finally{oe=!1}}},z=()=>{window.clearTimeout(ue),ue=window.setTimeout(()=>{q()},250)},se=()=>{R||(R=!0,k(),b(new Qe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Ce=ae=>{if(ae.source!==u.contentWindow||h&&ae.origin!==h)return;let me=ae.data;!me||typeof me!="object"||me.source!=="flopay-vault-3ds-return"||R||(R=!0,k(),v(null))};B=window.setTimeout(()=>{R||(R=!0,k(),b(new Qe.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),O=window.setInterval(()=>{q()},n),u.addEventListener("load",z),window.addEventListener("message",Ce),e.signal?.addEventListener("abort",se),e.signal?.aborted&&se()});return y||await a()}finally{d.parentNode?.removeChild(d),l?.isConnected&&l.focus()}}function Dc(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Ar(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=Tr(o)??o;return yi(new Qe.FloPayError(a,"api_error",{code:(0,Qe.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Qe.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function mi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ca(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Vs(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Ca(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||Ca(d)))return d;let l=o.gateways;if(l&&typeof l=="object"){let d=l.stripe;if(d&&typeof d=="object"){let u=d,h=[u.stripeClientSecret,u.clientSecret];for(let y of h)if(typeof y=="string"&&y.length>0&&(!t?.requirePaymentIntentClientSecret||Ca(y)))return y}}}}async function Lc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Vs(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 mo.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ca(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function yo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let d=e.replace(/\/+$/,""),u=t??n.id,h=r??n.clientSecret,y=n.customer?.id??n.accountData?.userId??"",v=n.customer?.email??n.accountData?.email??"",b=n.customer?.firstName??n.accountData?.firstName??"",R=n.customer?.lastName??n.accountData?.lastName??"",B=n.customer?.country??n.accountData?.country??void 0,O=n.customer?.zip??n.accountData?.zip??void 0,oe=await new mo.PaymentAPI(d,l===!1?{telemetry:!1}:void 0).processPayment(y,{sessionId:u,nonce:h,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:y,email:v,firstName:b,lastName:R,country:B,zip:O},returnUrl:a??mi(n)});if(oe.ok){let z=typeof oe.json=="function"?await oe.json().catch(()=>null):null;return(0,Qe.isAuthorizationOnlySession)(n)||z?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof z?.paymentId=="string"?z.paymentId:n.paymentId,sessionId:typeof z?.sessionId=="string"?z.sessionId:u,authorizationExpiresAt:typeof z?.authorizationExpiresAt=="string"?z.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:xo(o),checkoutMethod:Us(o)}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:xo(o),checkoutMethod:Us(o)}}}let k;try{k=await oe.json()}catch(z){throw new Qe.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:oe.status,cause:z})}if(k?.type==="paypal_redirect_required"||k?.type==="3ds_required"){let z=Vs(k);if(!z)throw new Qe.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:oe.status});return{type:k.type,threeDSecureToken:z,paymentMethodId:k.paymentMethodId}}if(k?.gatewayErrorCode==="authentication_required"){let z=await Lc({billingApiUrl:d,sessionId:u,nonce:h,responseJson:k});if(z)return z;throw yi(new Qe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let q=new Qe.FloPayError(k?.message??"Payment failed. Please try again.","api_error",{code:k?.code??k?.gatewayErrorCode,declineCode:k?.declineCode??k?.gatewayDeclineReason,statusCode:oe.status});throw Object.assign(q,{telemetryOutcome:(0,Qe.classifyPaymentRejection)(oe.status,k)})}async function Sa(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:d,telemetry:u}){let h=t?.getRawProvider();if(!h)throw Rr(new Qe.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw yi(new Qe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let y=(0,Qe.isSetupIntentClientSecret)(e.threeDSecureToken),v=null,b=e.paymentMethodId,R=await Oo(()=>Mc(h,e.threeDSecureToken,y),"card");if(R){if(R.error)throw Rr(new Qe.FloPayError(R.error.message??`Failed to retrieve 3DS ${y?"setup":"payment"} status.`,"api_error",{code:R.error.code}),"card");let O=R.intent;!b&&O?.payment_method&&(typeof O.payment_method=="string"?b=O.payment_method:"id"in O.payment_method&&(b=O.payment_method.id??void 0))}let B=b?await Oo(()=>Bc(h,e.threeDSecureToken,{payment_method:b,return_url:d??mi(l)??window.location.href},y),"card"):null;if(B){if(B.error)throw Rr(new Qe.FloPayError(B.error.message??"3DS authentication failed.","api_error",{code:B.error.code}),"card");v=B.intent}else{let O=await Oo(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(O.error)throw Rr(new Qe.FloPayError(O.error.message??"3DS authentication failed.","api_error",{code:O.error.code}),"card");v=(y?O.setupIntent:O.paymentIntent)??null}if(v&&(v.status==="requires_capture"||v.status==="succeeded"||v.status==="processing")){let O=await yo({billingApiUrl:o,sessionId:a,session:l,telemetry:u,tokenizedData:{id:v.id,type:"card",threeDSecureActionResultTokenId:v.id},returnUrl:d});return O.type==="success"?{...O.result,paymentIntentId:O.result.paymentIntentId??v.id,paymentMethodId:O.result.paymentMethodId??b}:Sa(O,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:d,telemetry:u})}throw Rr(new Qe.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let y=(n??t)?.getRawProvider();if(!y)throw Rr(new Qe.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:b}=await Oo(()=>y.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(b)throw Rr(new Qe.FloPayError(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:v}=await Oo(()=>y.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??mi(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(v)throw Rr(new Qe.FloPayError(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Qe.FloPayError("Unsupported payment redirect state.","api_error")}function Uo(e){if(e instanceof Qe.FloPayError){let r=Tr(e.message);return r&&r!==e.message?Object.assign(new Qe.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=Tr(t)??t;return new Qe.FloPayError(n,"api_error")}function fi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Or(e.data.session);if(!t&&!n&&!r)throw new Qe.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 Us(e){if(e)return e.isPaypal?"paypal":"card"}async function gi({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,mo.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,mo.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(h=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",h),null)):Promise.resolve(null)]);if(!l)throw new Qe.FloPayError("The payment provider did not initialize.","authentication_error");let u=null;return a?u=d:t&&(u=l),{flopay:l,paypalFlopay:u}}var lr=require("@flopay/js"),p=require("@flopay/shared"),Vt=require("@stripe/react-stripe-js"),s=bs(require("react"),1);var js={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 Un=require("react");function Ks(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 Nc=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 Oc(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Nc.has(t.charAt(0).toLowerCase()+t.slice(1))}function zc(e,t){return typeof t=="number"&&t!==0&&!Oc(e)?`${t}px`:String(t).trim()}function Ws(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]=zc(n,r)}}}var Hs=require("react/jsx-runtime"),hi=new WeakSet;function fo({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:l,onReady:d,onError:u,onValidation:h}){let y=(0,Un.useRef)(null),v=(0,Un.useRef)(d),b=(0,Un.useRef)(u),R=(0,Un.useRef)(h);v.current=d,b.current=u,R.current=h;let B=(0,Un.useRef)(o);B.current=o;let O=(0,Un.useRef)(null),ue=a??void 0,oe=(0,Un.useRef)(ue);oe.current=ue;let k=(0,Un.useRef)(void 0);return(0,Un.useEffect)(()=>{let q=y.current;if(!q)return;let z=!0,se=!1,Ce=()=>{!z||se||(se=!0,v.current?.())},ae=e.on("ready",()=>{Ce()}),me=e.on("error",ge=>{b.current?.(ge.message??"There was a problem loading the secure card form.")}),fe=e.on("validation",ge=>{R.current?.(ge.message??null)}),pt=oe.current??(hi.has(e)?null:void 0),Ge={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...B.current?{theme:B.current}:{},...pt===void 0?{}:{submitLabel:pt}};return O.current=B.current??null,k.current=oe.current,oe.current!==void 0&&hi.add(e),e.mount(q,Ge).then(()=>{Ce()}).catch(ge=>{z&&b.current?.(ge instanceof Error?ge.message:"Failed to load the secure card form.")}),()=>{z=!1,ae(),me(),fe(),e.unmount()}},[e,t,n,r]),$r(()=>{let q=y.current;q&&Ws(q,l)},[l]),(0,Un.useEffect)(()=>{o!==void 0&&(o===null&&O.current===null||(O.current=o,e.applyTheme?.(o)))},[e,o]),(0,Un.useEffect)(()=>{ue!==k.current&&(k.current=ue,ue!==void 0&&hi.add(e),e.setSubmitLabel?.(ue??null))},[e,ue]),(0,Hs.jsx)("div",{ref:y,"data-testid":"flopay-vault-card-fields"})}var Ys=/^#([0-9a-f]{6})$/i,Uc=/^#([0-9a-f]{3})$/i,Js=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Xs=/^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,qc=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,$c=/^(-?\d+(?:\.\d+)?)(?:px)?$/,Vc=/^(-?\d+(?:\.\d+)?)em$/,jc=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,Kc=/^[a-z][a-z0-9 -]{0,31}$/i,Wc=new Set(["none","uppercase","lowercase","capitalize"]);function Zs(e){if(typeof e!="string")return null;let t=e.trim(),n=Ys.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=Uc.exec(t);if(r){let[y,v,b]=r[1].split("").map(R=>Number.parseInt(R+R,16));return{r:y,g:v,b,a:null}}let o=Js.exec(t),a=o?null:Xs.exec(t),l=o??a;if(!l)return null;let d=Number(l[1]),u=Number(l[2]),h=Number(l[3]);return d>255||u>255||h>255?null:{r:d,g:u,b:h,a:a?Number(a[4]):null}}function Qs({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 qo(e){if(typeof e!="string")return;let t=e.trim();if(Ys.test(t)||Js.test(t))return t;let n=Xs.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=Zs(t);return r?Qs(r):void 0}function wa(e,t=.12){let n=Zs(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Qs({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function $o(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 jr(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=$c.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Hc(e,t,n){if(typeof e!="string")return;let r=Vc.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Gc(e){let t=$o(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=$o(o," "),l=qo(a[0]);if(!l)return;let d=r/(t.length-1)*100,u=a[1]===void 0?d:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),h=n[n.length-1]?.position??-1;if(!Number.isFinite(u)||u<0||u>100||u<h)return;n.push({color:l,position:u})}return{type:"linearGradient",angle:0,stops:n}}function Yc(e){if(typeof e!="string")return;let t=e.trim(),n=qo(t);if(n)return{type:"solid",color:n};let r=qc.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=Gc(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function Jc(e){return e.type==="solid"?{type:"solid",color:wa(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:wa(t.color)}))}}function Xc(e){let t=!1,n,r=[];for(let u of $o(e," ")){if(u.toLowerCase()==="inset"){t=!0;continue}let h=qo(u);if(h){n=h;continue}let y=jr(u,-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 Zc(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=$o(t,",").map(Xc);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function Gs(e){if(typeof e!="string")return;let t=$o(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>Kc.test(n)).slice(0,4);return t.length>0?t:void 0}function Qc(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=jr(t[0],0,64),r=jr(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function ed(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 el({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=Yc(r.background??r.backgroundColor),l=qo(o?.colorPrimaryHover),d=l?{type:"solid",color:l}:a&&Jc(a),u={fontFamilies:Gs(r.fontFamily)??Gs(n),fontSize:jr(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:ed(r.fontWeight)??600,letterSpacing:Hc(r.letterSpacing,-.1,.5)??.01,lineHeight:jr(r.lineHeight,.8,2)??1,textTransform:Wc.has(String(r.textTransform))?r.textTransform:"uppercase"},h=Qc(r.padding),y=Zc(r.boxShadow),v=jr(r.borderRadius,0,9999),b=typeof r.backdropFilter=="string"?jr(jc.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:qo(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...d?{hoverBackground:d}:{},typography:u,...h?{spacing:h}:{},...y?{shadow:y}:{},...v===void 0?{}:{borderRadius:v},disabledOpacity:e?.theme==="night"?.8:.6,...b===void 0?{}:{backdropBlur:b}}}function go(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)?wa(r,t):e}function bi(e){if(typeof e=="number"||typeof e=="string")return e}function ka({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=v=>typeof v=="string"&&v?v:void 0,a=t.submitButton,l=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",d=n==="buttons",u=t.nameInput,h=o(u?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",y=el({appearance:e,buttonsStyles:t,fontFamily:h});return{primaryColor:l,primaryHoverColor:o(r?.colorPrimaryHover)??go(l,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(u?.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:h,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(bi(u?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...y?{submitButton:y}:{}}}var c=require("react/jsx-runtime"),br="flopay_stripe_resume",tl="flopay_wallet_resume",ml="fw1",td="fw2",yl=300*1e3,nd=900,rd=25e3,od=25e3,ad=1e4,vi={},Pi={};function Ei(e){return`${td}:${e}`}function Ia(e){if(typeof window>"u")return!1;try{return localStorage.removeItem(Ei(e)),!0}catch{return!1}}function Ra(e,t){if(typeof window>"u")return null;let n=Ei(e);try{let r=localStorage.getItem(n);if(!r)return null;let o=JSON.parse(r);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>yl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Ia(e),null):o}catch{return Ia(e),null}}function id(e){if(typeof window>"u")return!1;try{return localStorage.setItem(Ei(e.sessionId),JSON.stringify(e)),!0}catch{return!1}}function nl(e,t,n){let r=Ra(e,t);return!r||r.clientSecret!==n?!1:Ia(e)}function Ci(e,t,n){if(typeof window>"u")return;Ra(e,t)?.clientSecret===n&&Ia(e)}function sd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Si(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":Ao(e.status),o=sd(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function rl(e,t,n){let r=null;try{return await Promise.race([Rs(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},ad),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function ld(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function fl(e){return e instanceof p.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Ea(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new lr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw fl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Vo="flopay_paypal_resume",cd=250,ol="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Ti(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Ta({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new lr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function dd(e){return e instanceof p.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function wi(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function gl({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=zr(n),l=a.firstName?a:zr(r?.name);return Mn({email:(0,p.isValidEmail)(o)?o:r?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function ud({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=gl({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 pd=`
|
|
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 @@ ${fn.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
|
-
`,Ra=44,Vo=180,nl=`flopay-card-enter ${Vo}ms cubic-bezier(0, 0, 0.2, 1) both`,rl=`flopay-card-exit ${Vo}ms cubic-bezier(0.4, 0, 0.2, 1) both`,dd=`flopay-buttons-enter ${Vo}ms cubic-bezier(0, 0, 0.2, 1) both`,ud=`flopay-buttons-exit ${Vo}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function pd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function _i(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var md={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function yd(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 Si={width:"100%",minHeight:Ra,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function fd(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ol(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function wi(e){return e==="paypal"?"PayPal":(0,p.getStripeMethodDisplayName)(e)}function gd(e,t){let n=`We couldn't open ${wi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function hd(e){let t=(0,p.getPostalCodeExample)(e);return`Enter a valid ${(0,p.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function bd(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 vd(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 al(e,t){return t instanceof p.FloPayError?t:new p.FloPayError(t instanceof Error?t.message:`${fd(e)} before-click hook failed.`,"validation_error")}function Ci(){return(0,c.jsx)("style",{children:cd})}function Pd(e){return typeof e=="number"?`${e}px`:e}function yl(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function fl({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 il(e){return e!=="unavailable"&&e!=="load_error"}function Ta(e){return(0,c.jsx)(Sd,{...e})}function sl({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:d,onDecline:u,onTechnicalFailure:b,runBeforeButtonClick:f,billingName:P,onBuyerIdentityReady:v,onLoadStateChange:I,placeholderBorderRadius:M}){let N=wr(),{emitInstrument:pe}=(0,s.useContext)(Hn),ae=(0,Vt.useStripe)(),w=(0,Vt.useElements)(),[q,O]=(0,s.useState)("loading");(0,s.useEffect)(()=>{I?.(q)},[q,I]);let[le,Se]=(0,s.useState)(!1),ie=!(0,p.isValidEmail)(n?.trim())||!P?.trim(),{request:ye,collect:he,finish:dt}=ro(),Je=(0,s.useRef)(!1),be=(0,s.useRef)(null),Ue=(0,s.useRef)(null),[ce,we]=(0,s.useState)(0),[Xe,Z]=(0,s.useState)(!1),ke=(0,s.useRef)(!1),de=(0,s.useRef)(new Map),{startAttempt:nt,finishAttempt:rt,invalidateAttempt:R,isAttemptInvalidated:$,isAttemptCurrent:fe}=Bo((ve,z,oe)=>{b?.(ve,z,{...oe,popupBlocked:oe?.popupBlocked??Sr(z)}),Z(!0),we(qe=>qe+1)});(0,s.useEffect)(()=>{Xe&&Ue.current?.focus()},[Xe,ce]);let Q=(0,s.useCallback)(()=>{we(ve=>ve+1)},[]),Ie=(0,s.useCallback)((ve,z,oe)=>{R(oe),b?.("paypal",ve,{code:z,popupBlocked:Sr(ve)}),Z(!0),Q()},[R,b,Q]),F=(0,s.useCallback)(()=>{window.setTimeout(()=>{(be.current?.querySelector("iframe")??be.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{ke.current&&(ke.current=!1,F())},[F,ce]);let Me=(0,s.useCallback)(()=>{Z(!1),a?.(null),F()},[F,a]);(0,s.useEffect)(()=>{if(!ae||Je.current)return;let ve=new URLSearchParams(window.location.search),z=ve.get("payment_intent"),oe=ve.get("payment_intent_client_secret"),qe=ve.get("redirect_status");if(!z||!oe)return;Je.current=!0;let lt;try{let Ze=localStorage.getItem($o);if(Ze){let Ae=JSON.parse(Ze);Ae.clientSecret===oe&&(lt={...Ae.accountPatch?{accountPatch:Ae.accountPatch}:{},...Ae.sessionId?{sessionId:Ae.sessionId}:{},...Ae.nonce?{nonce:Ae.nonce}:{}})}}catch{}try{localStorage.removeItem($o)}catch{}let Te=new URL(window.location.href);Te.searchParams.delete("payment_intent"),Te.searchParams.delete("payment_intent_client_secret"),Te.searchParams.delete("redirect_status"),window.history.replaceState({},"",Te.toString()),(async()=>{try{if(Se(!0),qe==="failed"){let Pe="PayPal payment was declined. Please try again.";a?.(Pe),u?.(rn("paypal",Pe));return}let{paymentIntent:Ze,error:Ae}=await ae.retrievePaymentIntent(oe);if(Ae){a?.(Ae.message??"Failed to retrieve PayPal payment status.");return}if(Ze&&(Ze.status==="requires_capture"||Ze.status==="succeeded")){let Pe=typeof Ze.payment_method=="string"?Ze.payment_method:Ze.payment_method?.id;o({id:Pe??Ze.id,type:"card",threeDSecureActionResultTokenId:Ze.id,isPaypal:!0},lt)}else{let Pe="PayPal payment was not completed. Please try again.";a?.(Pe),u?.(rn("paypal",Pe))}}catch(Ze){a?.(Ze instanceof Error?Ze.message:"Failed to complete PayPal payment.")}finally{Se(!1)}})()},[ae,o,a,u]);let ut=(0,s.useCallback)(async ve=>{if(l||le){ve.reject();return}let z=f?await f("paypal"):{proceed:!0};if(!z.proceed){de.current.delete(ce),ve.reject();return}let oe=nt("paypal");de.current.set(ce,{generation:oe,accountPatch:z.accountPatch,sessionId:z.sessionId,nonce:z.nonce}),Z(!1),d?.("paypal"),ve.resolve()},[l,d,f,nt,le,ce]),et=(0,s.useCallback)(async ve=>{if(!ae||!w)return;let z=de.current.get(ce);if(z&&!fe(z.generation)){de.current.delete(ce);return}if(!z&&$()||z&&!rt(z.generation))return;z||rt();let oe=z??null;if(de.current.delete(ce),!oe&&f){let Pe=await f("paypal");if(!Pe.proceed){ve.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}oe={accountPatch:Pe.accountPatch,sessionId:Pe.sessionId,nonce:Pe.nonce}}let qe=oe?.sessionId??e,lt=oe?.nonce??t,Te=await ld({event:ve,prepared:oe,email:n,billingName:P,methodLabel:"PayPal",collect:he});if(!Te){ve.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ze=Te.email,Ae={...oe?.accountPatch,...xn(Te,!0)};try{if(Se(!0),a?.(null),!qe||!(0,p.isValidEmail)(Ze))throw new Error("Missing sessionId or email for PayPal payment");await v?.(Te);let Pe=ae.createPaymentMethod,{error:Be,paymentMethod:Jt}=await Pe({type:"paypal"});if(Be){Ie(Be,"stripe_paypal_create_payment_method_failed",z?.generation),ve.paymentFailed({reason:"fail"});return}let te=await _a(r,pe,qe,lt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Jt?.id??null,intentKind:"payment"});if(te.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let At=te.clientSecret,mt={return_url:window.location.href};if(Jt?.id&&(mt.payment_method=Jt.id),typeof window<"u")try{localStorage.setItem($o,JSON.stringify({clientSecret:At,sessionId:qe,nonce:lt,accountPatch:Ae}))}catch{}let{error:D,paymentIntent:ue}=await ae.confirmPayment({clientSecret:At,confirmParams:mt,redirect:"if_required"});if(D){if(typeof window<"u")try{localStorage.removeItem($o)}catch{}if(xo(D)){let T=D.message??"Your payment was declined.";a?.(T),u?.(rn("paypal",T,{code:Cr(D),declineCode:ao(D)})),await Ea({billingApiUrl:r,sessionId:qe,nonce:lt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Cr(D)??"provider_declined"}})}else Ie(D,"stripe_paypal_confirm_failed",z?.generation);return}if(typeof window<"u")try{localStorage.removeItem($o)}catch{}let g=typeof ue?.payment_method=="string"?ue.payment_method:ue?.payment_method?.id;o({id:g??ue?.id,type:"card",threeDSecureActionResultTokenId:ue?.id,isPaypal:!0},{accountPatch:Ae,paymentMethodCategory:"paypal",sessionId:qe,nonce:lt});return}catch(Pe){Ie(Pe,"stripe_paypal_failed",z?.generation)}finally{Se(!1)}},[ae,w,e,t,n,P,he,v,r,pe,o,a,u,f,Ie,rt,fe,$,ce]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(fl,{state:q,placeholderTestId:"flopay-paypal-placeholder",borderRadius:M,children:(0,c.jsxs)("div",{ref:be,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Xe&&(0,c.jsx)("button",{ref:Ue,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Me,style:Si,children:"Try PayPal again"}),ye&&(0,c.jsx)(oo,{identity:ye.identity,methodLabel:ye.methodLabel,onComplete:dt,onCancel:()=>dt(null)},ye.id),(0,c.jsx)("div",{style:{display:ye?"none":void 0},children:(0,c.jsx)(Vt.ExpressCheckoutElement,{onReady:ve=>O(yl(ve,["paypal"])),onLoadError:()=>{O("load_error"),Ri(tn(N),"paypal","paypal")},onClick:ut,onConfirm:et,onCancel:()=>{let ve=de.current.get(ce);de.current.delete(ce),tn(N)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),R(ve?.generation),Z(!1),ke.current=!0,Q()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ie,emailRequired:ie,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ce)})]})}),le&&(0,c.jsx)(Yn,{status:"processing"})]})}function ll({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:d,onButtonClick:u,onDecline:b,onTechnicalFailure:f,runBeforeButtonClick:P,billingName:v,onBuyerIdentityReady:I,onLoadStateChange:M,placeholderBorderRadius:N}){let pe=wr(),{emitInstrument:ae}=(0,s.useContext)(Hn),w=(0,Vt.useStripe)(),q=(0,Vt.useElements)(),[O,le]=(0,s.useState)("loading");(0,s.useEffect)(()=>{M?.(O)},[O,M]);let[Se,ie]=(0,s.useState)(!1),ye=(0,s.useRef)(!(0,p.isValidEmail)(n?.trim())||!v?.trim()).current,{request:he,collect:dt,finish:Je}=ro(),be=(0,s.useRef)(null),Ue=(0,s.useRef)(null),[ce,we]=(0,s.useState)(0),[Xe,Z]=(0,s.useState)(!1),[ke,de]=(0,s.useState)(()=>Ia(e,t)?"blocked":"idle"),[nt,rt]=(0,s.useState)("google_pay"),R=(0,s.useRef)(null),$=(0,s.useRef)(!0),fe=(0,s.useRef)(!1),Q=(0,s.useRef)("google_pay"),Ie=(0,s.useRef)("google_pay"),F=(0,s.useRef)(null),Me=(0,s.useRef)(null),ut=(0,s.useRef)(new Set);(0,s.useEffect)(()=>($.current=!0,()=>{$.current=!1;for(let D of ut.current)window.clearTimeout(D);ut.current.clear()}),[]);let et=(0,s.useRef)(new Map),{startAttempt:ve,finishAttempt:z,invalidateAttempt:oe,isAttemptInvalidated:qe,isAttemptCurrent:lt,generationRef:Te}=Bo((D,ue,g)=>{f?.(D,ue,{...g,popupBlocked:g?.popupBlocked??Sr(ue)}),rt(D),Z(!0),we(T=>T+1)});(0,s.useEffect)(()=>{Xe&&Ue.current?.focus()},[Xe,ce]);let Ze=(0,s.useCallback)(()=>{we(D=>D+1)},[]),Ae=(0,s.useCallback)((D,ue,g,T)=>{oe(T),f?.(D,ue,{code:g,popupBlocked:Sr(ue)}),rt(D),Z(!0),Ze()},[oe,f,Ze]),Pe=(0,s.useCallback)(()=>{window.setTimeout(()=>{(be.current?.querySelector("iframe")??be.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{fe.current&&(fe.current=!1,Pe())},[Pe,ce]);let Be=(0,s.useCallback)(()=>{Z(!1),d?.(null),Pe()},[Pe,d]),Jt=(0,s.useCallback)(()=>{R.current?.()},[]);(0,s.useEffect)(()=>{let D=Ia(e,t);if(!D)return;let ue=!1,g=!1,T=async()=>{if(!g){g=!0,ue||de("checking");try{let $e=await el(w,D.clientSecret,ut.current);if(ue)return;let _e=vi($e,D.providerObjectId,(0,p.isSetupIntentClientSecret)(D.clientSecret));if(_e.kind==="confirmed"){if(!Qs(e,t,D.clientSecret))return;R.current=null,de("idle"),l({id:_e.paymentMethodId,type:"card",threeDSecureActionResultTokenId:_e.intentId},{...D.accountPatch?{accountPatch:D.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(_e.kind==="terminal"){bi(e,t,D.clientSecret),R.current=null,de("idle"),rt(D.paymentMethodType),Z(!0),Ze();return}de("blocked")}catch{ue||de("blocked")}finally{g=!1}}};return R.current=T,de("blocked"),()=>{ue=!0,R.current===T&&(R.current=null)}},[t,l,Ze,e,w]);let te=(0,s.useCallback)(async D=>{let ue=!1,g=ze=>{ue||(ue=!0,D.paymentFailed({reason:"fail",...ze?{message:ze}:{}}))};if(!w||!q){g();return}let T=et.current.get(ce);if(T&&!lt(T.generation)){et.current.delete(ce),g();return}if(!T&&qe()){g();return}if(T&&!z(T.generation)){g();return}T||z();let $e=D.expressPaymentType??T?.method??Q.current,_e=T??null,St=ol($e),at;$e==="apple_pay"?at="apple_pay":$e==="google_pay"&&(at="google_pay");let xt=T?.generation??Te.current,J=tn(pe),Xt=J?.now()??globalThis.performance?.now()??Date.now(),It=new AbortController,fn=!1,sr=!1,j=null,gn=e,kn="processing",dn="other",on="provider_runtime",hn,Xn=new Promise((ze,Ke)=>{hn=Ke}),un=window.setTimeout(()=>{fn=!0,It.abort(),hn(gi)},ed),Zt=async(ze,Ke,an)=>{kn=ze,dn=Ke,on=Ke==="intent_create"||Ke==="session_claim"?"transport_error":"provider_runtime";let pt=J?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([an,Xn])}finally{let zn=J?.now()??globalThis.performance?.now()??Date.now();J?.performance({stage:ze,durationMs:Math.max(0,zn-pt),durationMode:"machine",requestCategory:Ke,paymentMethodCategory:"wallet",provider:"stripe",...fn?{statusClass:"timeout"}:{}})}};try{if(ie(!0),d?.(null),!_e&&P){let xe=await Zt("processing","other",P(St));if(!xe.proceed){g();return}_e={accountPatch:xe.accountPatch,sessionId:xe.sessionId,nonce:xe.nonce}}let ze=_e?.sessionId??e;gn=ze;let Ke=_e?.nonce??t,an=F.current??_e?.accountPatch,pt=ml({event:D,fallbackEmail:an?.email??n,fallbackName:[an?.firstName,an?.lastName].join(" ").trim()||v});if(!(0,p.isValidEmail)(pt.email)){g("Buyer details are required."),dt(wi($e),pt).then(xe=>{xe&&(F.current=xe)});return}F.current=null;let zn={..._e?.accountPatch,...xn(pt,!0)};await Zt("processing","session_claim",Promise.resolve(I?.(pt)));let{error:Mt}=await Zt("tokenization","provider_sdk",q.submit());if(Mt){g(),Ae($e,Mt,"stripe_wallet_submit_failed",T?.generation);return}if(!ze)throw new Error("Missing sessionId or email for payment.");let Qt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:$e,paymentMethodId:null,intentKind:o},ft=JSON.stringify({sessionId:ze,nonce:Ke??"",request:Qt}),jt=Me.current,pn=jt?.retryIdentity===ft?jt.authorizationAttemptId:(0,p.randomUuidV4)();Me.current={authorizationAttemptId:pn,retryIdentity:ft};let Bt=await Zt("processing","intent_create",_a(r,ae,ze,Ke??"",{...Qt,authorizationAttemptId:pn},{signal:It.signal}));if(Bt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Rt=Bt.clientSecret,sn=rd({createdAt:Date.now(),sessionId:ze,...Ke?{nonce:Ke}:{},clientSecret:Rt,providerObjectId:Bt.providerObjectId,paymentMethodType:$e,accountPatch:zn});window.clearTimeout(un),sr=!0,J?.performance({stage:"callback",durationMs:Math.max(0,(J?.now()??globalThis.performance?.now()??Date.now())-Xt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Mn=J?.now()??globalThis.performance?.now()??Date.now(),vt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...at?{walletType:at}:{},attempt:xt},ne=!1,bn=null;J?.log({name:"payment.provider_confirmation.started",...vt}),j=window.setTimeout(()=>{j!==null&&ut.current.delete(j),ne=!0;let xe=J?.now()??globalThis.performance?.now()??Date.now();J?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...vt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,xe-Mn),statusClass:"timeout",failureCategory:"provider_runtime"}),J?.flush?.().catch(()=>{}),bn?.()},td),ut.current.add(j);let vn=xe=>{j!==null&&(window.clearTimeout(j),ut.current.delete(j),j=null);let L=J?.now()??globalThis.performance?.now()??Date.now(),ge=Math.max(0,L-Mn),A=xe;return ne&&(xe==="resolved"?A="resolved_late":xe==="returned_error"?A="returned_error_late":A="rejected_late"),J?.log({name:"payment.provider_confirmation.returned",...vt,operationOutcome:A}),J?.performance({...vt,durationMs:ge,durationMode:"buyer",operationOutcome:A}),{durationMs:ge,operationOutcome:A}},Ft=!1,Ut=!1,lr=xe=>{if(!xe||typeof xe!="object")return null;let L=xe;if(L.error)return null;let ge=L.setupIntent??L.paymentIntent,A=vi(ge??null,void 0,!!L.setupIntent);return A.kind==="confirmed"?A:null},Bn=xe=>{if(Ft||T&&Te.current!==T.generation)return;let L=lr(xe);if(!L)return;if(sn&&!Qs(ze,Ke,Rt)){Ft=!0;return}let{intentId:ge,paymentMethodId:A}=L;Ft=!0,Ut=!0,Me.current=null,R.current=null,$.current&&(de("idle"),ie(!1));let Kt=`${dl}:${ze}`;if(typeof window<"u")try{localStorage.setItem(Kt,JSON.stringify({createdAt:Date.now(),sessionId:ze,nonce:Ke,accountPatch:zn,paymentMethodId:A,providerIntentId:ge,paymentMethodType:$e}))}catch{}try{l({id:A,type:"card",threeDSecureActionResultTokenId:ge},{accountPatch:zn,paymentMethodCategory:"wallet",sessionId:ze,nonce:Ke})}finally{if(typeof window<"u")try{localStorage.removeItem(Kt)}catch{}}},mn=!1;bn=async()=>{if(!(mn||Ft||Ut)){mn=!0,$.current&&de("checking");try{let xe=await el(w,Rt,ut.current);if(Ft||Ut)return;let L=(0,p.isSetupIntentClientSecret)(Rt),ge=vi(xe,Bt.providerObjectId,L);if(ge.kind==="confirmed"){Bn(L?{setupIntent:xe}:{paymentIntent:xe});return}if(ge.kind==="terminal"){if(Ut=!0,bi(ze,Ke,Rt),Me.current=null,R.current=null,!$.current)return;de("idle"),g(),Ae($e,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",T?.generation);return}$.current&&!Ut&&(de("blocked"),ie(!1))}catch{$.current&&!Ut&&(de("blocked"),ie(!1))}finally{mn=!1}}},R.current=bn;let Fe,Zn;try{let xe=await((0,p.isSetupIntentClientSecret)(Rt)?w.confirmSetup({elements:q,clientSecret:Rt,redirect:"if_required"}):w.confirmPayment({elements:q,clientSecret:Rt,redirect:"if_required"}));if(!xe||typeof xe!="object"||(Fe=xe,!Fe.error&&!lr(Fe)))throw hi;Zn=vn(Fe.error?"returned_error":"resolved")}catch(xe){let L=xe===hi,ge=vn(L?"returned_error":"rejected");if(J?.error({...L?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:ti(xe),...vt,operationOutcome:ge.operationOutcome,durationMs:ge.durationMs,statusClass:"unknown"}),!$.current||Ft)return;await bn?.();return}let Dt=Fe.error;if(Dt){if(!$.current||Ft)return;if(xo(Dt)){Ut=!0,bi(ze,Ke,Rt),Me.current=null,R.current=null,de("idle");let xe=Dt.message??"Your payment was declined.";g(xe),d?.(xe),b?.(rn(St,xe,{code:Cr(Dt),declineCode:ao(Dt)})),Ea({billingApiUrl:r,sessionId:ze,nonce:Ke,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:$e,providerDeclineReason:Cr(Dt)??"provider_declined",...Bt.intentKind==="payment"&&Bt.providerObjectId.startsWith("pi_")?{providerIntentId:Bt.providerObjectId}:{}}})}else J?.error({...ti(Dt),...vt,operationOutcome:Zn.operationOutcome,durationMs:Zn.durationMs,statusClass:"unknown"}),await bn?.();return}if(Bn(Fe),!Ft)throw new Error("Invalid provider returned for APM intent")}catch(ze){if(ze===gi){let Ke=J?.now()??globalThis.performance?.now()??Date.now();J?.error({errorCode:ad(dn),stage:kn,requestCategory:dn,paymentMethodCategory:"wallet",provider:"stripe",...at?{walletType:at}:{},operationOutcome:"watchdog_expired",checkoutSessionId:gn,durationMs:Math.max(0,Ke-Xt),statusClass:"timeout",failureCategory:on,attempt:xt}),J?.flush?.().catch(()=>{})}g(),Ae($e,ze,ze===gi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",T?.generation)}finally{if(window.clearTimeout(un),j!==null&&(window.clearTimeout(j),ut.current.delete(j)),!sr){let ze=J?.now()??globalThis.performance?.now()??Date.now();J?.performance({stage:"callback",durationMs:Math.max(0,ze-Xt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...fn?{statusClass:"timeout"}:{}})}$.current&&ie(!1)}},[w,q,e,t,n,v,dt,I,r,ae,o,l,d,b,P,Ae,z,lt,qe,Te,pe,ce]),At=(0,s.useMemo)(()=>{let D=["applePay","googlePay","paypal","link","amazonPay","klarna"],ue=new Set(["applePay","googlePay"]),g=new Set(a.map(p.stripeExpressMethodToOptionKey)),T={};for(let $e of D)g.has($e)?T[$e]=ue.has($e)?"always":"auto":T[$e]="never";return T},[a]),mt=(0,s.useMemo)(()=>a.map(p.stripeExpressMethodToOptionKey),[a]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(fl,{state:O,placeholderTestId:"flopay-wallet-placeholder",borderRadius:N,children:(0,c.jsxs)("div",{ref:be,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Xe&&(0,c.jsxs)("button",{ref:Ue,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Be,style:Si,children:["Try ",wi(nt)," again"]}),ke!=="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:Jt,disabled:ke==="checking",style:Si,children:ke==="checking"?"Checking payment status\u2026":"Check payment status"})]}),he&&(0,c.jsx)(oo,{identity:he.identity,methodLabel:he.methodLabel,onComplete:Je,onCancel:()=>Je(null)},he.id),ke==="idle"&&(0,c.jsx)("div",{style:{display:he?"none":void 0},children:(0,c.jsx)(Vt.ExpressCheckoutElement,{onReady:D=>{le(yl(D,mt))},onLoadError:D=>{le("load_error"),Ri(tn(pe),"stripe","wallet")},onClick:async D=>{Q.current=D.expressPaymentType,Ie.current=ol(D.expressPaymentType);let ue=!0,g=window.setTimeout(()=>{ue=!1,D.reject()},Qc),T=P?await P(Ie.current):{proceed:!0};if(window.clearTimeout(g),!ue)return;if(!T.proceed){et.current.delete(ce),D.reject();return}let $e=ve(D.expressPaymentType);et.current.set(ce,{generation:$e,method:D.expressPaymentType,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),Z(!1),u?.(Ie.current),D.resolve()},onConfirm:te,onCancel:()=>{let D=et.current.get(ce);et.current.delete(ce),tn(pe)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),oe(D?.generation),Me.current=null,Z(!1),fe.current=!0,Ze()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:At,emailRequired:ye,billingAddressRequired:ye,layout:{maxColumns:1,overflow:"never"}}},ce)})]})}),Se&&(0,c.jsx)(Yn,{status:"processing"})]})}function gl(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function Cd({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:d,borderColor:u,textColor:b,borderRadius:f,fontFamily:P}){let v=(0,p.resolveStripeMethodBrandVariant)(e,t),I=qs[e],[M,N]=(0,s.useState)(!1),pe=!!I&&!M,ae=v?.backgroundColor??d??"#ffffff",w=v?.borderColor??u??"#d1d5db",q=v?.textColor??b??"#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:Ra,padding:"0 1rem",backgroundColor:ae,color:q,border:`1px solid ${w}`,borderRadius:f??8,fontSize:"0.95rem",fontWeight:600,fontFamily:P,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:[pe?(0,c.jsx)("img",{src:I,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,!pe&&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:q,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 ki({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:d,onErrorChange:u,onDecline:b,onCancel:f,runBeforeButtonClick:P,onButtonClick:v,isProcessing:I,submitButtonColor:M,submitButtonBorderRadius:N,submitButtonStyle:pe,errorText:ae}){let w=wr(),{emitInstrument:q}=(0,s.useContext)(Hn),O=(0,Vt.useStripe)(),le=(0,Vt.useElements)(),[Se,ie]=(0,s.useState)(!1),ye=(0,s.useRef)(!1),[he,dt]=(0,s.useState)(!1),[Je,be]=(0,s.useState)("loading"),[Ue,ce]=(0,s.useState)(""),we=!(0,p.isValidEmail)(r?.trim()),Xe=!we||(0,p.isValidEmail)(Ue.trim()),Z=(0,s.useCallback)(async()=>{if(!O||!le||I||ye.current||!he)return;ye.current=!0,ie(!0);let ke=P?await P("card"):{proceed:!0};if(!ke.proceed){ye.current=!1,ie(!1);return}v?.("card");let de=ke.sessionId??t,nt=ke.nonce??n,rt=Or(o?.trim()),R=xn({email:ke.accountPatch?.email?.trim()||r?.trim()||Ue.trim(),firstName:ke.accountPatch?.firstName?.trim()||rt.firstName,lastName:ke.accountPatch?.lastName?.trim()||rt.lastName}),$=R.email,fe=xn({...ke.accountPatch,...R});try{if(u?.(null),!(0,p.isValidEmail)($))throw new Error("A valid email address is required for payment.");await a?.(R);let Q=await le.submit();if(Q.error){u?.(Q.error.message??"Payment failed.");return}let Ie=[R.firstName,R.lastName].filter(Boolean).join(" "),F=await O.createPaymentMethod({elements:le,params:{billing_details:{email:$,...Ie?{name:Ie}:{}}}});if(F.error||!F.paymentMethod){u?.(F.error?.message??"Failed to create payment method.");return}let Me=F.paymentMethod;if(!de||!$)throw new Error("Missing sessionId or email for payment.");let ut=Me.type||e,et=await _a(l,q,de,nt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ut,paymentMethodId:null,intentKind:"payment"});if(et.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ve=et.clientSecret;if(typeof window<"u")try{localStorage.setItem(fr,JSON.stringify({clientSecret:ve,sessionId:de,nonce:nt,accountPatch:fe,paymentMethodId:Me.id,paymentMethodType:Me.type??e,gateway:"stripe"}))}catch{}let{error:z,paymentIntent:oe}=await O.confirmPayment({clientSecret:ve,confirmParams:{return_url:window.location.href,payment_method:Me.id},redirect:"if_required"});if(z){if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let Te=z.message??"Payment failed.";u?.(Te),b?.(rn("card",Te,{code:z.code})),await Ea({billingApiUrl:l,sessionId:de,nonce:nt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:z.code??"provider_declined"}});return}let qe=oe?.status;if(!To(qe)){if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let Te=qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";u?.(Te),b?.(rn("card",Te,{code:qe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let lt=typeof oe?.payment_method=="string"?oe.payment_method:oe?.payment_method?.id;d({id:lt??Me.id,type:"card",threeDSecureActionResultTokenId:oe?.id,gateway:"stripe",paymentMethodType:Me.type??e},{accountPatch:fe,paymentMethodCategory:"apm",sessionId:de,nonce:nt})}catch(Q){u?.(Q instanceof Error?Q.message:"Payment failed. Please try again.")}finally{ye.current=!1,ie(!1)}},[O,le,I,he,P,v,t,n,r,o,Ue,a,l,q,e,d,u,b]);return(0,c.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[we&&(0,c.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:we&&(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:Ue,onChange:ke=>ce(ke.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,c.jsx)(Vt.PaymentElement,{onReady:()=>be("ready"),onLoadError:()=>{be("load_error"),Ri(tn(w),"stripe","apm")},onChange:ke=>{dt(!!ke.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:()=>{Z()},disabled:!he||!Xe||Se||I||Je!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:M,color:"white",border:"none",borderRadius:N,fontSize:"1rem",fontWeight:600,cursor:!he||!Xe||Se||I||Je!=="ready"?"not-allowed":"pointer",opacity:!he||!Xe||Se||I||Je!=="ready"?.5:1,transition:"opacity 120ms ease-out",...pe??{}},children:Se?"Processing\u2026":`Pay with ${(0,p.getStripeMethodDisplayName)(e)}`}),ae&&(0,c.jsx)(so,{margin:"0.75rem 0 0",children:ae})]})}function cl({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:d,paymentElementBaseOptions:u,onTokenizedBody:b,onErrorChange:f,onButtonClick:P,onDecline:v,runBeforeButtonClick:I,onLoadStateChange:M,isProcessing:N=!1,submitButtonColor:pe="#4A49FF",submitButtonBorderRadius:ae=8,submitButtonStyle:w,buttonAppearance:q,themeId:O,onExpandApm:le,expandedApmMethod:Se}){let{emitInstrument:ie}=(0,s.useContext)(Hn),[ye,he]=(0,s.useState)(null),[dt,Je]=(0,s.useState)(null),be=(0,s.useRef)(!1),{request:Ue,collect:ce,finish:we}=ro();(0,s.useEffect)(()=>{l.length>0&&d?M?.("ready"):d||M?.("loading")},[l.length,d,M]);let Xe=(0,s.useCallback)(async R=>{if(!d||be.current||N)return;be.current=!0,Je(R);let $=I?await I("card"):{proceed:!0};if(!$.proceed){be.current=!1,Je(null);return}P?.("card");let fe=$.sessionId??e,Q=$.nonce??t,Ie=Or([$.accountPatch?.firstName,$.accountPatch?.lastName].filter(Boolean).join(" ")||r),F=xn({email:$.accountPatch?.email?.trim()||n?.trim(),firstName:$.accountPatch?.firstName?.trim()||Ie.firstName,lastName:$.accountPatch?.lastName?.trim()||Ie.lastName});if(!(0,p.isValidEmail)(F.email)){Je(null);let et=await ce((0,p.getStripeMethodDisplayName)(R),F);if(!et){be.current=!1;return}F=et,Je(R)}let Me=F.email,ut=xn({...$.accountPatch,...F});try{if(f?.(null),!fe||!(0,p.isValidEmail)(Me))throw new Error("Missing sessionId or email for payment.");await o?.(F);let et=await _a(a,ie,fe,Q??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:R,paymentMethodId:null,intentKind:"payment"});if(et.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ve=et.clientSecret;if(typeof window<"u")try{localStorage.setItem(fr,JSON.stringify({clientSecret:ve,sessionId:fe,nonce:Q,accountPatch:ut,paymentMethodType:R,gateway:"stripe"}))}catch{}let{error:z,paymentIntent:oe}=await d.confirmPayment({clientSecret:ve,confirmParams:{return_url:window.location.href,payment_method_data:{type:R,billing_details:{name:[F.firstName,F.lastName].filter(Boolean).join(" "),...Me?{email:Me}:{}}}},redirect:"if_required"});if(z){if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let Te=z.message??"Payment failed.";f?.(Te),v?.(rn("card",Te,{code:z.code})),await Ea({billingApiUrl:a,sessionId:fe,nonce:Q,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:R,providerDeclineReason:z.code??"provider_declined"}});return}let qe=oe?.status;if(!To(qe)){if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let Te=qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(Te),v?.(rn("card",Te,{code:qe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let lt=typeof oe?.payment_method=="string"?oe.payment_method:oe?.payment_method?.id;b({id:lt??oe?.id,type:"card",threeDSecureActionResultTokenId:oe?.id,gateway:"stripe",paymentMethodType:R},{accountPatch:ut,paymentMethodCategory:"apm",sessionId:fe,nonce:Q})}catch(et){f?.(et instanceof Error?et.message:"Payment failed. Please try again.")}finally{be.current=!1,Je(null)}},[d,N,I,P,e,t,n,ce,a,ie,r,o,b,f,v]),[Z,ke]=(0,s.useState)(null),de=le?Se??null:Z,nt=(0,s.useCallback)(R=>{be.current||N||de&&de!==R||((0,p.needsStripeMethodExplicitConfirm)(R)?le?le(R):ke(R):Xe(R))},[de,N,Xe,le]),rt=(0,s.useMemo)(()=>Z?gl(u,Z):null,[Z,u]);return(0,c.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ue?(0,c.jsx)(oo,{identity:Ue.identity,methodLabel:Ue.methodLabel,onComplete:we,onCancel:()=>we(null)},Ue.id):l.map(R=>{let $=Se===R,fe=dt===R,Q=dt!==null&&dt!==R||Se!=null&&Se!==R;return(0,c.jsxs)(s.default.Fragment,{children:[(0,c.jsx)(Cd,{method:R,themeId:O,submitting:fe,disabled:Q,highlighted:$,hasNextStep:(0,p.needsStripeMethodExplicitConfirm)(R),onClick:()=>nt(R),backgroundColor:q?.backgroundColor,borderColor:q?.borderColor,textColor:q?.textColor,borderRadius:q?.borderRadius,fontFamily:q?.fontFamily}),!le&&Z===R&&rt&&d&&(0,c.jsx)(Vt.Elements,{stripe:d,options:rt,children:(0,c.jsx)(ki,{method:R,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:b,onErrorChange:f,onDecline:v,onCancel:()=>ke(null),runBeforeButtonClick:I,onButtonClick:P,isProcessing:N,submitButtonColor:pe,submitButtonBorderRadius:ae,submitButtonStyle:w})},R)]},R)})})}function Sd({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:l,onError:d,onDecline:u,onTokenizedBody:b,firstName:f,lastName:P,chv:v,className:I,submitLabel:M,isProcessing:N,error:pe,onErrorChange:ae,showPayPal:w=!0,showStripe:q=!0,enabledPaymentMethods:O,enabledPaymentMethodCountries:le,showApplePay:Se=!0,showGooglePay:ie=!0,layout:ye="default",theme:he,buttonsTheme:dt,buttonsStyles:Je,appearance:be,cardButtonContent:Ue,cardBackButtonContent:ce,cardTitleContent:we,showSecurityFooter:Xe,onButtonClick:Z,onBeforeButtonClick:ke,onBuyerIdentityReady:de,enableAVS:nt,cardFieldOrder:rt,cardPreFormSlot:R,avsLayout:$="row",country:fe,zip:Q,addressLine1:Ie,addressLine2:F,city:Me,state:ut,onCountryChange:et,onZipChange:ve,avsCheck:z,checkoutType:oe,checkoutLayout:qe,totalAmount:lt=0,currency:Te="usd",initialCardOpen:Ze=!1,directPaypal:Ae,isSubscription:Pe=!1,session:Be,dataAttachmentPending:Jt=!1,dataAttachmentRequiresIdentity:te=!1,debug:At=!1}){let mt=wr(),D=sa(),ue=(0,s.useContext)(nr),{emitInstrument:g}=(0,s.useContext)(Hn),T=Be??ue.session,$e=T?.gateways?.paypal?.providerObjectType??Ae?.providerObjectType,_e=Jt||ue.claimPending===!0,St=te||ue.claimRequiresIdentity===!0,at=_e&&!St,xt=Es(),J=n||xt,[Xt,It]=(0,s.useState)(!1),[fn,sr]=(0,s.useState)(null),[j,gn]=(0,s.useState)(fe??"US"),[kn,dn]=(0,s.useState)(Q??""),[on,hn]=(0,s.useState)(Ie??""),[Xn,un]=(0,s.useState)(F??""),[Zt,ze]=(0,s.useState)(Me??""),[Ke,an]=(0,s.useState)(ut??""),[pt,zn]=(0,s.useState)(""),[Mt,Qt]=(0,s.useState)({}),ft=(0,s.useRef)(Q??""),jt=(0,s.useRef)(fe??"US"),pn=(0,s.useRef)(Ie??""),Bt=(0,s.useRef)(F??""),Rt=(0,s.useRef)(Me??""),sn=(0,s.useRef)(ut??""),Mn=(0,s.useRef)(""),vt=(0,s.useRef)({});(0,s.useEffect)(()=>{let i=(k,G,Ve,Y,ct)=>{if(vt.current[k])return;let ot=G?.trim();!ot||ot===Ve.current||(Ve.current=ot,Y(ot),ct?.(ot))};i("country",fe,jt,gn,et),i("zip",Q,ft,dn,ve),i("addressLine1",Ie,pn,hn),i("addressLine2",F,Bt,un),i("city",Me,Rt,ze),i("state",ut,sn,an)},[fe,Q,Ie,F,Me,ut,et,ve]);let ne=(0,s.useMemo)(()=>(0,p.resolveAVSConfig)(nt),[nt]),bn=ne!==null,vn=(0,s.useMemo)(()=>(0,p.isAuthorizationOnlySession)(Be),[Be]),Ft=!!Be?.vault?.html,Ut=!!Be?.gateways?.pcivault,Bn=!!(Be?.gateways?.stripe?.enabledPaymentMethods??O)?.includes("card"),mn=Ft||Bn||Ut,Fe=!!(q&&mn&&e),[Zn,Dt]=(0,s.useState)(()=>ye!=="buttons"||Ze?e??null:null),[xe,L]=(0,s.useState)(0),ge=ye!=="buttons"||Ze||!!e&&Zn===e,A=Be?.captureMethod,Kt=(0,s.useRef)(mt);(0,s.useEffect)(()=>{Kt.current=mt},[mt]);let[ln,In]=(0,s.useState)(null);(0,s.useEffect)(()=>{if(!Fe||!e||!ge){In(null);return}let i=Kt.current?Kt.current.cardCapture({sessionId:e,captureMethod:A}):new or.PciVaultCardCapture({sessionId:e,captureMethod:A,billingApiUrl:J,telemetry:r});return In({sessionId:e,captureMethod:A,billingApiUrl:J,telemetry:r,capture:i}),()=>{i.unmount()}},[Fe,e,ge,A,J,r]);let Pt=Fe&&e&&ge&&ln?.sessionId===e&&ln.captureMethod===A&&ln.billingApiUrl===J&&ln.telemetry===r?ln.capture:null,We=(0,s.useMemo)(()=>{let i=j,k=ne?(0,p.isAVSFieldVisible)(ne.postal_code,i):!1;return bd(i,kn,k)},[ne,j,kn]),{avsInvalid:cr,invalidAvsFields:jr}=(0,s.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Fe||!ne)return{avsInvalid:!1,invalidAvsFields:i};let k=j,G=(ct,ot)=>(0,p.isAVSFieldVisible)(ct,k)&&!ot.trim(),Ve={line1:G(ne.address_line_1,on),city:G(ne.city,Zt),state:G(ne.state,Ke),zip:We.empty||We.malformed};return{avsInvalid:Ve.line1||Ve.city||Ve.state||Ve.zip,invalidAvsFields:Ve}},[Fe,ne,j,on,Zt,Ke,We]),[Rr,Fn]=(0,s.useState)(!1),[xr,dr]=(0,s.useState)(!1),[Qn,Wt]=(0,s.useState)(!1),[Rn,br]=(0,s.useState)({line1:!1,city:!1,state:!1}),Pn=(0,s.useRef)(!1),Dn=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),er=(0,s.useRef)(!1),gt=(0,s.useCallback)(i=>{Dn.current[i]=!0,er.current=!0},[]),Un=(0,s.useCallback)(i=>!Pn.current&&Dn.current[i],[]),Cn=(0,s.useCallback)(i=>{Un(i)&&br(k=>k[i]?k:{...k,[i]:!0})},[Un]),[qn,$n]=(0,s.useState)(()=>Pi(Be?.vault)),[Ge,nn]=(0,s.useState)(Ze&&mn?"card":"buttons"),[Ht,Mr]=(0,s.useState)(null),_r=Ge==="expanding"||Ge==="card",Er=Be?.gateways?.stripe?"stripe":void 0,Vn=(0,s.useCallback)(()=>{g?.({class:"card_surface",provider:Er})},[Er,g]),Ln=(0,s.useRef)(null),yn=(0,s.useCallback)(i=>{Ln.current&&clearTimeout(Ln.current),Ln.current=setTimeout(()=>{Ln.current=null,i()},Vo)},[]);(0,s.useEffect)(()=>()=>{Ln.current&&clearTimeout(Ln.current)},[]);let Br=(0,s.useCallback)(()=>{Vn(),Dt(e??null),L(i=>i+1),nn("expanding"),yn(()=>nn("card"))},[yn,Vn,e]),Fr=(0,s.useCallback)(()=>{nn("collapsing"),yn(()=>nn("buttons"))},[yn]),_n=(0,s.useCallback)(i=>{Mr(i),nn("apm-expanding"),yn(()=>nn("apm-form"))},[yn]),vr=(0,s.useCallback)(()=>{nn("apm-collapsing"),yn(()=>{nn("buttons"),Mr(null)})},[yn]);(0,s.useEffect)(()=>{ye==="buttons"&&Ze&&mn&&(Dt(e??null),nn("card"))},[ye,Ze,mn,e]);let[qt,S]=(0,s.useState)(null),B=(0,s.useRef)(!1),K=(0,s.useRef)(null),U=(0,s.useRef)("idle"),[He,yt]=(0,s.useState)(null),De=(0,s.useRef)(He);(0,s.useEffect)(()=>{De.current=He},[He]);let W=(0,s.useRef)(null),Ce=(0,s.useMemo)(()=>{if(de||ue.claimBuyerIdentity||Be?.buyerIdentified!==!1||!e||!t)return;let i=`${J}|${e}|${t}`;W.current?.key!==i&&(W.current={key:i,claim:to(new or.PaymentAPI(J,{telemetry:!1}),e,t,{...a?{userId:a}:{},...f?{firstName:f}:{},...P?{lastName:P}:{}})});let k=W.current.claim;return async G=>{await k(G)}},[de,ue.claimBuyerIdentity,Be?.buyerIdentified,e,t,J,a,f,P]),x=de??ue.claimBuyerIdentity??Ce,h=pe??fn,y=(0,s.useMemo)(()=>(0,p.resolveTheme)(he),[he]),m=(0,s.useMemo)(()=>{let i=y?.buttonsLayout??(0,p.resolveButtonsLayoutTheme)(dt);return Je?{...i,...Je,cardButton:{...i.cardButton,...Je.cardButton},cardFormContainer:{...i.cardFormContainer,...Je.cardFormContainer},backButton:{...i.backButton,...Je.backButton},backButtonIcon:{...i.backButtonIcon,...Je.backButtonIcon},submitButton:{...i.submitButton,...Je.submitButton},title:{...i.title,...Je.title}}:i},[y,dt,Je]),X=be??y?.appearance,Le=(0,s.useMemo)(()=>wa({appearance:X,buttonsStyles:m,layout:ye}),[X,m,ye]),se=ue.inlineSessionPatchProcessing??!1,V=(N??Xt)||se,re=J.replace(/\/+$/,""),H=(0,s.useMemo)(()=>ei({userId:a,email:o,firstName:f,lastName:P,country:fe,zip:Q},Mt),[a,o,f,P,fe,Q,Mt]),Ct=[H.firstName,H.lastName].filter(i=>!!i?.trim()).join(" "),Gt=!(0,p.isValidEmail)(H.email?.trim()),Ne=(0,s.useRef)(null);Fe&&Ne.current===null&&(Ne.current=Gt);let Oe=Fe&&(Ne.current??Gt),ee=(0,s.useMemo)(()=>vd(pt,Oe),[pt,Oe]),Ee=ee.empty||ee.malformed,me=(0,s.useMemo)(()=>mt?mt.getRawProvider():null,[mt]),Lt=(0,s.useMemo)(()=>D?D.getRawProvider():null,[D]),Ye=lt||100,En=Te.toLowerCase(),ur=(0,s.useMemo)(()=>X?(0,or.toStripeAppearance)(X):null,[X]),Kr=ur,Li=(0,s.useMemo)(()=>{let i=ur??{},k=i.rules??{};return{...i,rules:{...k,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...k[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...k[".AccordionItemContents"]??{}}}}},[ur]),Ni=(0,s.useMemo)(()=>({...ks(lt,Be?.captureMethod),currency:En,...Kr?{appearance:Kr}:null}),[lt,En,Be?.captureMethod,Kr]),Oi=(0,s.useMemo)(()=>({mode:"payment",amount:Ye,currency:En,captureMethod:"manual",setupFutureUsage:"off_session",...Kr?{appearance:Kr}:null}),[Ye,En,Kr]),Re=(0,s.useCallback)(i=>{sr(i),ae?.(i)},[ae]),La=(0,s.useRef)(""),[zi,Al]=(0,s.useState)(!1),Na=(0,s.useCallback)(()=>{Al(!0)},[]);(0,s.useEffect)(()=>{if(!Fe||!Oe||!x||!zi||Ee||La.current)return;let i=xn({email:(0,p.isValidEmail)(H.email?.trim())?H.email?.trim():Mn.current.trim(),firstName:H.firstName?.trim(),lastName:H.lastName?.trim()});La.current=JSON.stringify(i),Qt(k=>({...k,...i})),Promise.resolve(x(i)).catch(k=>{La.current="",Re(k instanceof Error?k.message:"Failed to attach buyer details.")})},[Fe,Oe,x,zi,Ee,H.email,H.firstName,H.lastName,Re]),(0,s.useEffect)(()=>{!Fe||!Pt||Pt.setCardFieldOrder?.(rt??null,ne==null&&!Oe)},[Fe,Pt,rt,ne,Oe]),(0,s.useEffect)(()=>{(Ge==="expanding"||Ge==="collapsing"||Ge==="apm-expanding"||Ge==="apm-collapsing")&&Re(null)},[Ge,Re]);let pr=(0,s.useCallback)((i,k,G)=>{u?.(rn(i,k,G))},[u]),Wr=(0,s.useCallback)((i,k,G)=>{let Ve=G?.popupBlocked??Sr(k),Y=gd(i,Ve),ct=Ur(G?.code)??Cr(k)??"external_payment_method_failed",ot=new p.FloPayError(Y,"api_error",{code:"external_payment_method_failed",param:i});S(null),ye==="buttons"&&(nn("buttons"),Mr(null)),Re(Y),d?.(ot),console.error("[FloPay] External payment method failed:",{method:i,code:ct,popupBlocked:Ve})},[ye,d,Re]);(0,s.useEffect)(()=>{if(!Fe||!e){$n(null);return}let i=Pi(Be?.vault);if(i){$n(i);return}if(!ge){$n(null);return}$n(null);let k=!0;return new or.PaymentAPI(re).getVaultCapture(e,t).then(G=>{if(!k)return;let Ve=Pi(G);Ve?$n(Ve):Re("Failed to load the secure card form.")}).catch(G=>{k&&Re(G instanceof Error?G.message:"Failed to load the secure card form.")}),()=>{k=!1}},[Fe,ge,xe,e,Be?.vault,re,t,Re]);let mr=(0,s.useRef)({onComplete:l,onError:d,updateError:Re,emitDecline:pr,resolvedAccount:H,avsConfig:ne,avsCheckProp:z,sessionId:e,nonce:t,baseUrl:re,captureMethod:Be?.captureMethod,paymentId:Be?.paymentId,authorizationExpiresAt:Be?.authorizationExpiresAt});mr.current={onComplete:l,onError:d,updateError:Re,emitDecline:pr,resolvedAccount:H,avsConfig:ne,avsCheckProp:z,sessionId:e,nonce:t,baseUrl:re,captureMethod:Be?.captureMethod,paymentId:Be?.paymentId,authorizationExpiresAt:Be?.authorizationExpiresAt};let Oa=(0,s.useRef)(!1),Ui=(0,s.useCallback)(()=>{let i=mr.current,k=i.resolvedAccount.email?.trim(),G=(0,p.isValidEmail)(k)?k:Mn.current.trim();if(!(0,p.isValidEmail)(G))return null;let Ve=i.resolvedAccount.firstName?.trim(),Y=i.resolvedAccount.lastName?.trim(),ct=jt.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,wt=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.postal_code,ct):!1,Et=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.city,ct):!1,Ot=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.address_line_2,ct):!1,_t=it&&!ot&&wt?(0,p.getStateFromPostalCode)(ct,(ft.current??"").trim()):null,Kn=ot?sn.current:_t;return{accountData:{userId:i.resolvedAccount.userId??"",email:G,...Ve?{firstName:Ve}:{},...Y?{lastName:Y}:{},...wt&&ft.current?{zip:ft.current}:{},...Et&&Rt.current?{city:Rt.current}:{},...Kn?{state:Kn}:{},...it&&pn.current?{addressLine1:pn.current}:{},...Ot&&Bt.current?{addressLine2:Bt.current}:{},country:ct},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,p.isAVSFieldVisible)(i.avsConfig.country,ct),postal_code:wt,address_line_1:it,address_line_2:Ot,city:Et,state:ot}}:{}}},[]),qi=(0,s.useRef)(_e);qi.current=_e,(0,s.useEffect)(()=>{_e||h!==tl||mr.current.updateError(null)},[_e,h]),(0,s.useEffect)(()=>{!Fe||!Pt||Pt.setSubmitGate?.(cr||_e||Ee)},[Fe,Pt,cr,_e,Ee]),(0,s.useEffect)(()=>{if(!Fe||!Pt)return;Oa.current=!1;let i=null,k=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,U.current="idle",S(null)},400)},G=Pt.on("submitting",()=>{Fn(!0),K.current&&clearTimeout(K.current),U.current="validation-window",K.current=setTimeout(()=>{K.current=null,U.current==="validation-window"&&(U.current="processing")},id),S("processing");let it=mr.current;if(!it.sessionId||!it.nonce)return;let wt=Ui();if(!wt){it.updateError("Enter a valid email address."),U.current="idle",S(null);return}new or.PaymentAPI(it.baseUrl).patchAccountSnapshot(it.sessionId,it.nonce,wt,{telemetryMode:"best_effort"}).catch(Et=>{if(!sd(Et))return;let Ot=Et instanceof Error?Et.message:"Please check your billing address and try again.";it.updateError(Ot),U.current="idle",S(null),it.onError?.(Et instanceof p.FloPayError?Et:new p.FloPayError(Ot,"api_error"))})}),Ve=Pt.on("complete",async it=>{if(uo(it.sessionId??mr.current.sessionId),U.current="terminal",S("success"),await new Promise(Ot=>setTimeout(Ot,600)),Oa.current)return;Oa.current=!0;let wt=mr.current,Et=(0,p.isAuthorizationOnlySession)(wt)||it.outcome==="authorized";mr.current.onComplete?.(Et?{status:"authorized",paymentIntentId:it.intentId,paymentId:it.paymentId??wt.paymentId,sessionId:it.sessionId??wt.sessionId,authorizationExpiresAt:it.authorizationExpiresAt??wt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:it.intentId,checkoutMethod:"card"})}),Y=Pt.on("decline",it=>{let wt=mr.current,Et=it.message??"Your payment was declined. Please try another card or contact your bank.";U.current="terminal",wt.updateError(Et),S("error");let Ot=it.failureOutcome??(0,p.normalizeCheckoutFailureOutcome)(it.declineReason)??"authorization_declined";wt.emitDecline("card",Et,{code:Ot,declineCode:Ot}),k()}),ct=Pt.on("error",it=>{let wt=mr.current,Et=it.message??"There was a problem processing your payment. Please try again.";U.current="terminal",wt.updateError(Et),S("error"),wt.onError?.(new p.FloPayError(Et,"api_error",{code:it.failureOutcome??"capture_failed"})),k()}),ot=Pt.on("blocked",()=>{if(!qi.current){Fn(!0);return}Na(),mr.current.updateError(tl)});return()=>{i&&(clearTimeout(i),i=null),K.current&&(clearTimeout(K.current),K.current=null),U.current="idle",S(null),G(),Ve(),Y(),ct(),ot()}},[Fe,Pt,Na,Ui]);let yr=!!Ae?.clientId,ho=Array.isArray(O),Ho=ho&&O.length>0,xl=ho&&O.includes("paypal"),{expressMethods:Go,paymentElementMethods:bo}=(0,s.useMemo)(()=>(0,p.partitionStripeMethods)(O,{excludePaypal:yr}),[O,yr]),$i=yr||!!D,Ml=(0,s.useMemo)(()=>$i?Go.filter(i=>i!=="paypal"):Go,[Go,$i]),Bl=(0,s.useMemo)(()=>{let i=[];return Se&&i.push("apple_pay"),ie&&i.push("google_pay"),i},[Se,ie]),Hr=ho?Ml:Bl,Fl=q&&Hr.length>0,za=bn?j:fe,Yo=(0,s.useMemo)(()=>{let i=za?.trim().toUpperCase();return i?le?bo.filter(k=>{let G=le[k];return!G||G.length===0||G.includes(i)}):(0,p.filterStripeMethodsByCountry)(bo,za):bo},[bo,za,le]),Ua=(0,s.useMemo)(()=>({mode:"payment",amount:Ye,currency:En,paymentMethodCreation:"manual",appearance:Li}),[Ye,En,Li]),[Vi,ji]=(0,s.useState)("loading"),[Ki,Wi]=(0,s.useState)("loading"),[Hi,Gi]=(0,s.useState)("loading"),[Dl,qa]=(0,s.useState)(!1),[Yi,$a]=(0,s.useState)("loading"),[Va,Ll]=(0,s.useState)();(0,s.useEffect)(()=>{Ll(la())},[]);let Jo=Va?.inAppBrowser,Xo=Va?ca(Va,Ae?.approvalPresentation,$e??(Pe?"subscription":"order")):"popup",Ji=w&&(yr||(ho?xl:Jo===!1)),Xi=q&&Fl,vo=(!at||!!ue.waitForDataAttachment)&&Ji&&yr,Zi=Yi==="retrying"||Yi==="exhausted",Po=!at&&Ji&&!!Lt&&(!yr||Zi),Gr=!at&&Xi&&!!me,Co=!at&&q&&Ho&&Yo.length>0&&!!me,Nl=vo&&!Zi?Dl:Po&&il(Vi),Ol=Gr&&il(Ki),zl=Co&&Hi!=="load_error",Qi=i=>i==="loading"||i==="ready",es=vo||Po&&Qi(Vi)||Gr&&Qi(Ki)||Co&&Hi!=="load_error",Zo=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!Zo.current){if(!q&&!w){Zo.current=!0;let i=new p.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(i),Re(i.message)}else if(!q&&w&&!yr&&!Lt){Zo.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),Re(i.message)}else if(Jo!==void 0&&!at&&!mn&&!es){Zo.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),Re(i.message)}}},[q,w,yr,Lt,Jo,at,mn,es,d,Re]);let ts=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(ts.current||!Ho)return;let i=[];Se!==!0&&i.push("showApplePay"),ie!==!0&&i.push("showGooglePay"),i.length!==0&&(ts.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.`))},[Ho,Se,ie]);let ns=(0,s.useCallback)((i,k)=>ue.applyInlineSessionPatch?ue.applyInlineSessionPatch(i).then(G=>({error:null,sessionId:G.sessionId||e,nonce:G.session?.clientSecret||t})).catch(G=>{let Ve=al(k,G);return Re(Ve.message),d?.(Ve),{error:Ve,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ue.applyInlineSessionPatch,t,d,e,Re]),tr=(0,s.useCallback)(async i=>{if(i!=="card"&&at&&await ue.waitForDataAttachment?.(),!ke)return{proceed:!0};try{let k=await ke({method:i,sessionId:e||void 0,createSession:ue.inlineSessionDraft});if(k===!1)return{proceed:!1};if(k&&typeof k=="object"){k.account&&Qt(Ve=>({...Ve??{},...k.account}));let G=await ns(k,i);return G.error?{proceed:!1,accountPatch:k.account}:{proceed:!0,accountPatch:k.account,sessionId:G.sessionId,nonce:G.nonce}}return{proceed:!0}}catch(k){let G=al(i,k);return Re(G.message),d?.(G),{proceed:!1}}},[ns,ue.inlineSessionDraft,ue.waitForDataAttachment,at,ke,d,e,Re]),rs=(0,s.useCallback)(async(i,k)=>{if(B.current)return;B.current=!0,It(!0),S("processing"),Re(null);let G=k?.sessionId??e,Ve=k?.nonce??t,Y=ei(H,k?.accountPatch),ct=k?.completionPaymentMethodId??Ao(i),ot=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,it=pd(i),wt=()=>{g?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:it})};try{let Ot=await new or.PaymentAPI(re).processPayment(Y.userId??"",{sessionId:G,nonce:Ve,paymentMethodCategory:k?.paymentMethodCategory??yd(i),tokenizedData:ot,accountData:{...k?.accountPatch,userId:Y.userId??"",email:Y.email??"",firstName:Y.firstName||void 0,lastName:Y.lastName||void 0,...ne?(()=>{let ht=jt.current,Wn=(0,p.isAVSFieldVisible)(ne.state,ht),Sn=(0,p.isAVSFieldVisible)(ne.address_line_1,ht),en=(0,p.isAVSFieldVisible)(ne.postal_code,ht),Nr=Sn&&!Wn&&en?(0,p.getStateFromPostalCode)(ht,(ft.current??"").trim()):null,_o=Wn?sn.current:Nr;return{country:ht,...en&&ft.current?{zip:ft.current}:{},...(0,p.isAVSFieldVisible)(ne.city,ht)&&Rt.current?{city:Rt.current}:{},..._o?{state:_o}:{},...Sn&&pn.current?{addressLine1:pn.current}:{},...(0,p.isAVSFieldVisible)(ne.address_line_2,ht)&&Bt.current?{addressLine2:Bt.current}:{}}})():{}},chv:v,avsCheck:z??!1,checkoutType:oe,checkoutLayout:qe,avsConfig:ne?{country:(0,p.isAVSFieldVisible)(ne.country,jt.current),postal_code:(0,p.isAVSFieldVisible)(ne.postal_code,jt.current),address_line_1:(0,p.isAVSFieldVisible)(ne.address_line_1,jt.current),address_line_2:(0,p.isAVSFieldVisible)(ne.address_line_2,jt.current),city:(0,p.isAVSFieldVisible)(ne.city,jt.current),state:(0,p.isAVSFieldVisible)(ne.state,jt.current)}:void 0});if(Ot.ok){let ht=Ot.status===204?null:await Ot.json().catch(()=>null),Wn=(0,p.isAuthorizationOnlySession)(Be)||ht?.status==="authorized";uo(G),S("success"),yt(null),await new Promise(Nr=>setTimeout(Nr,600));let Sn;typeof ht?.paymentId=="string"?Sn=ht.paymentId:Be?.paymentId&&(Sn=Be.paymentId);let en;typeof ht?.authorizationExpiresAt=="string"?en=ht.authorizationExpiresAt:Be?.authorizationExpiresAt&&(en=Be.authorizationExpiresAt),l?.(Wn?{status:"authorized",...Sn===void 0?{}:{paymentId:Sn},sessionId:typeof ht?.sessionId=="string"?ht.sessionId:G,...en===void 0?{}:{authorizationExpiresAt:en},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:ct,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:ct,checkoutMethod:i.isPaypal?"paypal":"card"});return}let _t=await Ot.json().catch(()=>null);if(_t?.type==="paypal_redirect_required"){let ht=_t.threeDSecureToken,Wn=_t.paymentMethodId||i.id||"";if(!mt||!ht){S("error"),Re("PayPal authorization required but no token provided.");return}try{let Sn=D?.getRawProvider();if(!Sn){Re("PayPal is not available.");return}let en={return_url:window.location.href};Wn&&(en.payment_method=Wn);let{error:Nr}=await Sn.confirmPayment({clientSecret:ht,confirmParams:en,redirect:"if_required"});if(Nr){S("error");let _o=Nr.message??"PayPal payment failed.";Re(_o),pr("paypal",_o,{code:Nr.code})}}catch(Sn){S("error"),Re(Sn instanceof Error?Sn.message:"PayPal authorization failed.")}return}if(_t?.type==="paypal_direct_required"){let ht=_t.orderId;if(!ht){S("error"),Re("PayPal retry required but no order id provided.");return}let Wn=De.current?.attempts??0;if(Wn>=2){S("error"),Re("PayPal payment could not be completed after multiple attempts."),pr("paypal","paypal_direct_required retry limit exceeded");return}qa(!1),$a("loading"),yt({orderId:ht,attempts:Wn+1}),S(null);return}(0,p.classifyPaymentRejection)(Ot.status,_t)||wt(),S("error");let Kn=_t?.message??"Payment failed. Please try again.";Re(Kn),pr(i.isPaypal?"paypal":"card",Kn,{code:_t?.code??_t?.gatewayErrorCode,declineCode:_t?.declineCode??_t?.gatewayDeclineReason}),await new Promise(ht=>setTimeout(ht,400))}catch(Et){pl(Et)||wt(),S("error"),Re(Et instanceof Error?Et.message:"An unexpected error occurred"),await new Promise(Ot=>setTimeout(Ot,400))}finally{It(!1),S(null),B.current=!1}},[re,e,t,H,ne,z,oe,qe,v,mt,D,Be,l,Re,pr,g]),Tn=(0,s.useCallback)((i,k)=>{b?b(i):rs(i,k)},[b,rs]),So=`${dl}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(So);if(!i)return;let k;try{k=JSON.parse(i)}catch{localStorage.removeItem(So);return}if(!k||typeof k.createdAt!="number"||Date.now()-k.createdAt<0||Date.now()-k.createdAt>ul||typeof k.paymentMethodId!="string"||typeof k.providerIntentId!="string"||typeof k.paymentMethodType!="string"||k.sessionId!==e||!t||k.nonce!==t||!Hr.includes(k.paymentMethodType)){localStorage.removeItem(So);return}localStorage.removeItem(So),Tn({id:k.paymentMethodId,type:"card",threeDSecureActionResultTokenId:k.providerIntentId,gateway:"stripe",paymentMethodType:k.paymentMethodType},{...k.accountPatch?{accountPatch:k.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Tn,t,e,So,Hr]);let os=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||os.current)return;let i=new URLSearchParams(window.location.search),k=i.get("payment_intent"),G=i.get("payment_intent_client_secret"),Ve=i.get("redirect_status");if(!k||!G||!mt)return;let Y=mt.getRawProvider();if(!Y)return;let ct=_t=>{let Kn=localStorage.getItem(_t);if(!Kn)return null;try{return JSON.parse(Kn)}catch{return localStorage.removeItem(_t),null}},ot=ct(fr)??ct(Zs),it;if(ot?.clientSecret){if(ot.clientSecret!==G)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;os.current=!0,localStorage.removeItem(fr),localStorage.removeItem(Zs);let wt=new URL(window.location.href);wt.searchParams.delete("payment_intent"),wt.searchParams.delete("payment_intent_client_secret"),wt.searchParams.delete("redirect_status"),window.history.replaceState({},"",wt.toString());let Et=ot?.paymentMethodType??ot?.tokenType??"card",Ot="card";(async()=>{if(Ve==="failed"){let en="Payment was declined. Please try again.";Re(en),pr(Ot,en);return}let{paymentIntent:_t,error:Kn}=await Y.retrievePaymentIntent(G);if(Kn){let en=Kn.message??"Failed to retrieve payment status.";Re(en),pr(Ot,en,{code:Kn.code});return}let ht=_t?.status,Wn=To(ht);if(!_t||!Wn){let en=ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Re(en),pr(Ot,en,{code:ht??"missing_payment_intent"});return}let Sn=typeof _t.payment_method=="string"?_t.payment_method:_t.payment_method?.id;Tn({id:Sn??ot?.paymentMethodId??ot?.tokenId??_t.id,type:"card",threeDSecureActionResultTokenId:_t.id,gateway:ot?.gateway??"stripe",paymentMethodType:Et},it)})()},[e,Tn,mt,Re,pr]);let ja=(0,s.useCallback)(i=>{i.preventDefault()},[]);if(!(Fe||mt!==null))return(0,c.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let wo=ye==="buttons",An=X?.variables,Ul=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ka=An?.colorBackground,ql=Ka&&!Ul.has(Ka)?Ka:void 0,ko=m.cardInputBorder??(wo?"#e5e7eb":"#A4A4FF"),as=An?.colorDanger??"#dc2626",Nt=i=>jr[i]&&(Rn[i]||Rr),Qo=Ee&&(Qn||Rr),jn=i=>i?as:ko,ea=(We.malformed||We.empty)&&(xr||Rr),$l=jn(ea),Wa=m.cardFormContainer?.backgroundColor??ql??(wo?"white":"#EDEDFF"),Yr=m.cardInputBackground??An?.colorBackground??"white",Ha=Zr(ce),is=Zr(we),Jr=m.nameInput,ss=m.cardInputFontSize??Pd(Jr?.fontSize)??An?.fontSizeBase??"16px",ls=typeof Jr?.fontFamily=="string"?Jr.fontFamily:An?.fontFamily??"Poppins, sans-serif",cs=fi(Jr?.fontWeight)??400,Vl=m.cardInputColor??(typeof Jr?.color=="string"?Jr.color:void 0)??An?.colorText??"#262833",jl=m.cardInputPlaceholderColor??"#9ca3af",$t=An?.borderRadius??"8px",Dr=An?.borderRadius??m.cardButton?.borderRadius??$t,Lr=An?.colorPrimary??"#4A49FF",Kl=An?.colorPrimaryHover??fo(Lr,.12),Ga=An?.colorText??"#262833",Ya={fontSize:ss,fontFamily:ls,fontWeight:cs,color:Vl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Io={marginTop:"0.375rem",...Ya,fontSize:"0.75rem",lineHeight:1.4,color:as},Wl={"--flopay-input-placeholder-color":jl,"--flopay-input-font-size":ss,"--flopay-input-font-family":ls,"--flopay-input-font-weight":String(cs)},Ro=m.cardFormContainer??{},Ja=Ro.padding??(wo?"0":"1rem"),Xa=Ro.borderRadius??$t,Hl=Pt&&qn?(0,c.jsx)(yo,{capture:Pt,html:qn.html,messageToken:qn.messageToken,expectedOrigin:qn.expectedOrigin,theme:Le,submitLabel:M,onReady:()=>{if(!Oe&&!ne||typeof document>"u")return;let i=()=>{let G=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(G){Pn.current=!0;try{G.focus()}finally{Pn.current=!1}}};er.current||i()},onError:i=>Re(i),onValidation:i=>{let k=U.current;(k==="idle"||k==="validation-window")&&(Re(i),i&&U.current==="validation-window"&&(K.current&&(clearTimeout(K.current),K.current=null),U.current="idle",S(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"}),ds=(0,c.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&Vn()},style:{backgroundColor:Wa,borderRadius:Xa,...Ro,padding:Ja,...Wl,display:"flex",flexDirection:"column"},children:[(0,c.jsx)("style",{children:`
|
|
30
|
+
`,_a=44,jo=180,al=`flopay-card-enter ${jo}ms cubic-bezier(0, 0, 0.2, 1) both`,il=`flopay-card-exit ${jo}ms cubic-bezier(0.4, 0, 0.2, 1) both`,md=`flopay-buttons-enter ${jo}ms cubic-bezier(0, 0, 0.2, 1) both`,yd=`flopay-buttons-exit ${jo}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function fd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Ai(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var gd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function hd(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 Ii={width:"100%",minHeight:_a,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function bd(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function sl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ri(e){return e==="paypal"?"PayPal":(0,p.getStripeMethodDisplayName)(e)}function vd(e,t){let n=`We couldn't open ${Ri(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Pd(e){let t=(0,p.getPostalCodeExample)(e);return`Enter a valid ${(0,p.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Cd(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 Sd(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 ll(e,t){return t instanceof p.FloPayError?t:new p.FloPayError(t instanceof Error?t.message:`${bd(e)} before-click hook failed.`,"validation_error")}function ki(){return(0,c.jsx)("style",{children:pd})}function wd(e){return typeof e=="number"?`${e}px`:e}function hl(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function bl({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 cl(e){return e!=="unavailable"&&e!=="load_error"}function Aa(e){return(0,c.jsx)(Id,{...e})}function dl({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:d,onDecline:u,onTechnicalFailure:h,runBeforeButtonClick:y,billingName:v,onBuyerIdentityReady:b,onLoadStateChange:R,placeholderBorderRadius:B}){let O=Ir(),{emitInstrument:ue}=(0,s.useContext)(Gn),oe=(0,Vt.useStripe)(),k=(0,Vt.useElements)(),[q,z]=(0,s.useState)("loading");(0,s.useEffect)(()=>{R?.(q)},[q,R]);let[se,Ce]=(0,s.useState)(!1),ae=!(0,p.isValidEmail)(n?.trim())||!v?.trim(),{request:me,collect:fe,finish:pt}=oo(),Ge=(0,s.useRef)(!1),ge=(0,s.useRef)(null),Ue=(0,s.useRef)(null),[le,Se]=(0,s.useState)(0),[Ye,X]=(0,s.useState)(!1),we=(0,s.useRef)(!1),ce=(0,s.useRef)(new Map),{startAttempt:rt,finishAttempt:ot,invalidateAttempt:_,isAttemptInvalidated:$,isAttemptCurrent:ye}=Fo((he,U,ne)=>{h?.(he,U,{...ne,popupBlocked:ne?.popupBlocked??kr(U)}),X(!0),Se(qe=>qe+1)});(0,s.useEffect)(()=>{Ye&&Ue.current?.focus()},[Ye,le]);let Z=(0,s.useCallback)(()=>{Se(he=>he+1)},[]),ke=(0,s.useCallback)((he,U,ne)=>{_(ne),h?.("paypal",he,{code:U,popupBlocked:kr(he)}),X(!0),Z()},[_,h,Z]),F=(0,s.useCallback)(()=>{window.setTimeout(()=>{(ge.current?.querySelector("iframe")??ge.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{we.current&&(we.current=!1,F())},[F,le]);let De=(0,s.useCallback)(()=>{X(!1),a?.(null),F()},[F,a]);(0,s.useEffect)(()=>{if(!oe||Ge.current)return;let he=new URLSearchParams(window.location.search),U=he.get("payment_intent"),ne=he.get("payment_intent_client_secret"),qe=he.get("redirect_status");if(!U||!ne)return;Ge.current=!0;let ct;try{let Je=localStorage.getItem(Vo);if(Je){let Me=JSON.parse(Je);Me.clientSecret===ne&&(ct={...Me.accountPatch?{accountPatch:Me.accountPatch}:{},...Me.sessionId?{sessionId:Me.sessionId}:{},...Me.nonce?{nonce:Me.nonce}:{}})}}catch{}try{localStorage.removeItem(Vo)}catch{}let xe=new URL(window.location.href);xe.searchParams.delete("payment_intent"),xe.searchParams.delete("payment_intent_client_secret"),xe.searchParams.delete("redirect_status"),window.history.replaceState({},"",xe.toString()),(async()=>{try{if(Ce(!0),qe==="failed"){let be="PayPal payment was declined. Please try again.";a?.(be),u?.(nn("paypal",be));return}let{paymentIntent:Je,error:Me}=await oe.retrievePaymentIntent(ne);if(Me){a?.(Me.message??"Failed to retrieve PayPal payment status.");return}if(Je&&(Je.status==="requires_capture"||Je.status==="succeeded")){let be=typeof Je.payment_method=="string"?Je.payment_method:Je.payment_method?.id;o({id:be??Je.id,type:"card",threeDSecureActionResultTokenId:Je.id,isPaypal:!0},ct)}else{let be="PayPal payment was not completed. Please try again.";a?.(be),u?.(nn("paypal",be))}}catch(Je){a?.(Je instanceof Error?Je.message:"Failed to complete PayPal payment.")}finally{Ce(!1)}})()},[oe,o,a,u]);let mt=(0,s.useCallback)(async he=>{if(l||se){he.reject();return}let U=y?await y("paypal"):{proceed:!0};if(!U.proceed){ce.current.delete(le),he.reject();return}let ne=rt("paypal");ce.current.set(le,{generation:ne,accountPatch:U.accountPatch,sessionId:U.sessionId,nonce:U.nonce}),X(!1),d?.("paypal"),he.resolve()},[l,d,y,rt,se,le]),et=(0,s.useCallback)(async he=>{if(!oe||!k)return;let U=ce.current.get(le);if(U&&!ye(U.generation)){ce.current.delete(le);return}if(!U&&$()||U&&!ot(U.generation))return;U||ot();let ne=U??null;if(ce.current.delete(le),!ne&&y){let be=await y("paypal");if(!be.proceed){he.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ne={accountPatch:be.accountPatch,sessionId:be.sessionId,nonce:be.nonce}}let qe=ne?.sessionId??e,ct=ne?.nonce??t,xe=await ud({event:he,prepared:ne,email:n,billingName:v,methodLabel:"PayPal",collect:fe});if(!xe){he.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Je=xe.email,Me={...ne?.accountPatch,...Mn(xe,!0)};try{if(Ce(!0),a?.(null),!qe||!(0,p.isValidEmail)(Je))throw new Error("Missing sessionId or email for PayPal payment");await b?.(xe);let be=oe.createPaymentMethod,{error:_e,paymentMethod:Ht}=await be({type:"paypal"});if(_e){ke(_e,"stripe_paypal_create_payment_method_failed",U?.generation),he.paymentFailed({reason:"fail"});return}let Q=await Ea(r,ue,qe,ct??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Ht?.id??null,intentKind:"payment"});if(Q.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Mt=Q.clientSecret,ft={return_url:window.location.href};if(Ht?.id&&(ft.payment_method=Ht.id),typeof window<"u")try{localStorage.setItem(Vo,JSON.stringify({clientSecret:Mt,sessionId:qe,nonce:ct,accountPatch:Me}))}catch{}let{error:D,paymentIntent:de}=await oe.confirmPayment({clientSecret:Mt,confirmParams:ft,redirect:"if_required"});if(D){if(typeof window<"u")try{localStorage.removeItem(Vo)}catch{}if(Mo(D)){let A=D.message??"Your payment was declined.";a?.(A),u?.(nn("paypal",A,{code:wr(D),declineCode:io(D)})),await Ta({billingApiUrl:r,sessionId:qe,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:wr(D)??"provider_declined"}})}else ke(D,"stripe_paypal_confirm_failed",U?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Vo)}catch{}let f=typeof de?.payment_method=="string"?de.payment_method:de?.payment_method?.id;o({id:f??de?.id,type:"card",threeDSecureActionResultTokenId:de?.id,isPaypal:!0},{accountPatch:Me,paymentMethodCategory:"paypal",sessionId:qe,nonce:ct});return}catch(be){ke(be,"stripe_paypal_failed",U?.generation)}finally{Ce(!1)}},[oe,k,e,t,n,v,fe,b,r,ue,o,a,u,y,ke,ot,ye,$,le]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(bl,{state:q,placeholderTestId:"flopay-paypal-placeholder",borderRadius:B,children:(0,c.jsxs)("div",{ref:ge,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ye&&(0,c.jsx)("button",{ref:Ue,type:"button","data-testid":"flopay-paypal-retry-button",onClick:De,style:Ii,children:"Try PayPal again"}),me&&(0,c.jsx)(ao,{identity:me.identity,methodLabel:me.methodLabel,onComplete:pt,onCancel:()=>pt(null)},me.id),(0,c.jsx)("div",{style:{display:me?"none":void 0},children:(0,c.jsx)(Vt.ExpressCheckoutElement,{onReady:he=>z(hl(he,["paypal"])),onLoadError:()=>{z("load_error"),Ti(en(O),"paypal","paypal")},onClick:mt,onConfirm:et,onCancel:()=>{let he=ce.current.get(le);ce.current.delete(le),en(O)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),_(he?.generation),X(!1),we.current=!0,Z()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ae,emailRequired:ae,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},le)})]})}),se&&(0,c.jsx)(Jn,{status:"processing"})]})}function ul({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:d,onButtonClick:u,onDecline:h,onTechnicalFailure:y,runBeforeButtonClick:v,billingName:b,onBuyerIdentityReady:R,onLoadStateChange:B,placeholderBorderRadius:O}){let ue=Ir(),{emitInstrument:oe}=(0,s.useContext)(Gn),k=(0,Vt.useStripe)(),q=(0,Vt.useElements)(),[z,se]=(0,s.useState)("loading");(0,s.useEffect)(()=>{B?.(z)},[z,B]);let[Ce,ae]=(0,s.useState)(!1),me=(0,s.useRef)(!(0,p.isValidEmail)(n?.trim())||!b?.trim()).current,{request:fe,collect:pt,finish:Ge}=oo(),ge=(0,s.useRef)(null),Ue=(0,s.useRef)(null),[le,Se]=(0,s.useState)(0),[Ye,X]=(0,s.useState)(!1),[we,ce]=(0,s.useState)(()=>Ra(e,t)?"blocked":"idle"),[rt,ot]=(0,s.useState)("google_pay"),_=(0,s.useRef)(null),$=(0,s.useRef)(!0),ye=(0,s.useRef)(!1),Z=(0,s.useRef)("google_pay"),ke=(0,s.useRef)("google_pay"),F=(0,s.useRef)(null),De=(0,s.useRef)(null),mt=(0,s.useRef)(new Set);(0,s.useEffect)(()=>($.current=!0,()=>{$.current=!1;for(let D of mt.current)window.clearTimeout(D);mt.current.clear()}),[]);let et=(0,s.useRef)(new Map),{startAttempt:he,finishAttempt:U,invalidateAttempt:ne,isAttemptInvalidated:qe,isAttemptCurrent:ct,generationRef:xe}=Fo((D,de,f)=>{y?.(D,de,{...f,popupBlocked:f?.popupBlocked??kr(de)}),ot(D),X(!0),Se(A=>A+1)});(0,s.useEffect)(()=>{Ye&&Ue.current?.focus()},[Ye,le]);let Je=(0,s.useCallback)(()=>{Se(D=>D+1)},[]),Me=(0,s.useCallback)((D,de,f,A)=>{ne(A),y?.(D,de,{code:f,popupBlocked:kr(de)}),ot(D),X(!0),Je()},[ne,y,Je]),be=(0,s.useCallback)(()=>{window.setTimeout(()=>{(ge.current?.querySelector("iframe")??ge.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{ye.current&&(ye.current=!1,be())},[be,le]);let _e=(0,s.useCallback)(()=>{X(!1),d?.(null),be()},[be,d]),Ht=(0,s.useCallback)(()=>{_.current?.()},[]);(0,s.useEffect)(()=>{let D=Ra(e,t);if(!D)return;let de=!1,f=!1,A=async()=>{if(!f){f=!0,de||ce("checking");try{let $e=await rl(k,D.clientSecret,mt.current);if(de)return;let Re=Si($e,D.providerObjectId,(0,p.isSetupIntentClientSecret)(D.clientSecret));if(Re.kind==="confirmed"){if(!nl(e,t,D.clientSecret))return;_.current=null,ce("idle"),l({id:Re.paymentMethodId,type:"card",threeDSecureActionResultTokenId:Re.intentId},{...D.accountPatch?{accountPatch:D.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(Re.kind==="terminal"){Ci(e,t,D.clientSecret),_.current=null,ce("idle"),ot(D.paymentMethodType),X(!0),Je();return}ce("blocked")}catch{de||ce("blocked")}finally{f=!1}}};return _.current=A,ce("blocked"),()=>{de=!0,_.current===A&&(_.current=null)}},[t,l,Je,e,k]);let Q=(0,s.useCallback)(async D=>{let de=!1,f=Ne=>{de||(de=!0,D.paymentFailed({reason:"fail",...Ne?{message:Ne}:{}}))};if(!k||!q){f();return}let A=et.current.get(le);if(A&&!ct(A.generation)){et.current.delete(le),f();return}if(!A&&qe()){f();return}if(A&&!U(A.generation)){f();return}A||U();let $e=D.expressPaymentType??A?.method??Z.current,Re=A??null,kt=sl($e),st;$e==="apple_pay"?st="apple_pay":$e==="google_pay"&&(st="google_pay");let Bt=A?.generation??xe.current,J=en(ue),Gt=J?.now()??globalThis.performance?.now()??Date.now(),Rt=new AbortController,mn=!1,ur=!1,j=null,yn=e,wn="processing",cn="other",rn="provider_runtime",fn,Zn=new Promise((Ne,Ke)=>{fn=Ke}),dn=window.setTimeout(()=>{mn=!0,Rt.abort(),fn(vi)},rd),Yt=async(Ne,Ke,on)=>{wn=Ne,cn=Ke,rn=Ke==="intent_create"||Ke==="session_claim"?"transport_error":"provider_runtime";let yt=J?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([on,Zn])}finally{let $n=J?.now()??globalThis.performance?.now()??Date.now();J?.performance({stage:Ne,durationMs:Math.max(0,$n-yt),durationMode:"machine",requestCategory:Ke,paymentMethodCategory:"wallet",provider:"stripe",...mn?{statusClass:"timeout"}:{}})}};try{if(ae(!0),d?.(null),!Re&&v){let Ee=await Yt("processing","other",v(kt));if(!Ee.proceed){f();return}Re={accountPatch:Ee.accountPatch,sessionId:Ee.sessionId,nonce:Ee.nonce}}let Ne=Re?.sessionId??e;yn=Ne;let Ke=Re?.nonce??t,on=F.current??Re?.accountPatch,yt=gl({event:D,fallbackEmail:on?.email??n,fallbackName:[on?.firstName,on?.lastName].join(" ").trim()||b});if(!(0,p.isValidEmail)(yt.email)){f("Buyer details are required."),pt(Ri($e),yt).then(Ee=>{Ee&&(F.current=Ee)});return}F.current=null;let $n={...Re?.accountPatch,...Mn(yt,!0)};await Yt("processing","session_claim",Promise.resolve(R?.(yt)));let{error:Ft}=await Yt("tokenization","provider_sdk",q.submit());if(Ft){f(),Me($e,Ft,"stripe_wallet_submit_failed",A?.generation);return}if(!Ne)throw new Error("Missing sessionId or email for payment.");let Jt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:$e,paymentMethodId:null,intentKind:o},ht=JSON.stringify({sessionId:Ne,nonce:Ke??"",request:Jt}),jt=De.current,un=jt?.retryIdentity===ht?jt.authorizationAttemptId:(0,p.randomUuidV4)();De.current={authorizationAttemptId:un,retryIdentity:ht};let Dt=await Yt("processing","intent_create",Ea(r,oe,Ne,Ke??"",{...Jt,authorizationAttemptId:un},{signal:Rt.signal}));if(Dt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let _t=Dt.clientSecret,an=id({createdAt:Date.now(),sessionId:Ne,...Ke?{nonce:Ke}:{},clientSecret:_t,providerObjectId:Dt.providerObjectId,paymentMethodType:$e,accountPatch:$n});window.clearTimeout(dn),ur=!0,J?.performance({stage:"callback",durationMs:Math.max(0,(J?.now()??globalThis.performance?.now()??Date.now())-Gt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Bn=J?.now()??globalThis.performance?.now()??Date.now(),Pt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...st?{walletType:st}:{},attempt:Bt},te=!1,gn=null;J?.log({name:"payment.provider_confirmation.started",...Pt}),j=window.setTimeout(()=>{j!==null&&mt.current.delete(j),te=!0;let Ee=J?.now()??globalThis.performance?.now()??Date.now();J?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Pt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Ee-Bn),statusClass:"timeout",failureCategory:"provider_runtime"}),J?.flush?.().catch(()=>{}),gn?.()},od),mt.current.add(j);let hn=Ee=>{j!==null&&(window.clearTimeout(j),mt.current.delete(j),j=null);let L=J?.now()??globalThis.performance?.now()??Date.now(),Te=Math.max(0,L-Bn),x=Ee;return te&&(Ee==="resolved"?x="resolved_late":Ee==="returned_error"?x="returned_error_late":x="rejected_late"),J?.log({name:"payment.provider_confirmation.returned",...Pt,operationOutcome:x}),J?.performance({...Pt,durationMs:Te,durationMode:"buyer",operationOutcome:x}),{durationMs:Te,operationOutcome:x}},Lt=!1,Ut=!1,Fn=Ee=>{if(!Ee||typeof Ee!="object")return null;let L=Ee;if(L.error)return null;let Te=L.setupIntent??L.paymentIntent,x=Si(Te??null,void 0,!!L.setupIntent);return x.kind==="confirmed"?x:null},Vn=Ee=>{if(Lt||A&&xe.current!==A.generation)return;let L=Fn(Ee);if(!L)return;if(an&&!nl(Ne,Ke,_t)){Lt=!0;return}let{intentId:Te,paymentMethodId:x}=L;Lt=!0,Ut=!0,De.current=null,_.current=null,$.current&&(ce("idle"),ae(!1));let Nt=`${ml}:${Ne}`;if(typeof window<"u")try{localStorage.setItem(Nt,JSON.stringify({createdAt:Date.now(),sessionId:Ne,nonce:Ke,accountPatch:$n,paymentMethodId:x,providerIntentId:Te,paymentMethodType:$e}))}catch{}try{l({id:x,type:"card",threeDSecureActionResultTokenId:Te},{accountPatch:$n,paymentMethodCategory:"wallet",sessionId:Ne,nonce:Ke})}finally{if(typeof window<"u")try{localStorage.removeItem(Nt)}catch{}}},Qn=!1;gn=async()=>{if(!(Qn||Lt||Ut)){Qn=!0,$.current&&ce("checking");try{let Ee=await rl(k,_t,mt.current);if(Lt||Ut)return;let L=(0,p.isSetupIntentClientSecret)(_t),Te=Si(Ee,Dt.providerObjectId,L);if(Te.kind==="confirmed"){Vn(L?{setupIntent:Ee}:{paymentIntent:Ee});return}if(Te.kind==="terminal"){if(Ut=!0,Ci(Ne,Ke,_t),De.current=null,_.current=null,!$.current)return;ce("idle"),f(),Me($e,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",A?.generation);return}$.current&&!Ut&&(ce("blocked"),ae(!1))}catch{$.current&&!Ut&&(ce("blocked"),ae(!1))}finally{Qn=!1}}},_.current=gn;let Xt,We;try{let Ee=await((0,p.isSetupIntentClientSecret)(_t)?k.confirmSetup({elements:q,clientSecret:_t,redirect:"if_required"}):k.confirmPayment({elements:q,clientSecret:_t,redirect:"if_required"}));if(!Ee||typeof Ee!="object"||(Xt=Ee,!Xt.error&&!Fn(Xt)))throw Pi;We=hn(Xt.error?"returned_error":"resolved")}catch(Ee){let L=Ee===Pi,Te=hn(L?"returned_error":"rejected");if(J?.error({...L?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:oi(Ee),...Pt,operationOutcome:Te.operationOutcome,durationMs:Te.durationMs,statusClass:"unknown"}),!$.current||Lt)return;await gn?.();return}let qt=Xt.error;if(qt){if(!$.current||Lt)return;if(Mo(qt)){Ut=!0,Ci(Ne,Ke,_t),De.current=null,_.current=null,ce("idle");let Ee=qt.message??"Your payment was declined.";f(Ee),d?.(Ee),h?.(nn(kt,Ee,{code:wr(qt),declineCode:io(qt)})),Ta({billingApiUrl:r,sessionId:Ne,nonce:Ke,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:$e,providerDeclineReason:wr(qt)??"provider_declined",...Dt.intentKind==="payment"&&Dt.providerObjectId.startsWith("pi_")?{providerIntentId:Dt.providerObjectId}:{}}})}else J?.error({...oi(qt),...Pt,operationOutcome:We.operationOutcome,durationMs:We.durationMs,statusClass:"unknown"}),await gn?.();return}if(Vn(Xt),!Lt)throw new Error("Invalid provider returned for APM intent")}catch(Ne){if(Ne===vi){let Ke=J?.now()??globalThis.performance?.now()??Date.now();J?.error({errorCode:ld(cn),stage:wn,requestCategory:cn,paymentMethodCategory:"wallet",provider:"stripe",...st?{walletType:st}:{},operationOutcome:"watchdog_expired",checkoutSessionId:yn,durationMs:Math.max(0,Ke-Gt),statusClass:"timeout",failureCategory:rn,attempt:Bt}),J?.flush?.().catch(()=>{})}f(),Me($e,Ne,Ne===vi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",A?.generation)}finally{if(window.clearTimeout(dn),j!==null&&(window.clearTimeout(j),mt.current.delete(j)),!ur){let Ne=J?.now()??globalThis.performance?.now()??Date.now();J?.performance({stage:"callback",durationMs:Math.max(0,Ne-Gt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...mn?{statusClass:"timeout"}:{}})}$.current&&ae(!1)}},[k,q,e,t,n,b,pt,R,r,oe,o,l,d,h,v,Me,U,ct,qe,xe,ue,le]),Mt=(0,s.useMemo)(()=>{let D=["applePay","googlePay","paypal","link","amazonPay","klarna"],de=new Set(["applePay","googlePay"]),f=new Set(a.map(p.stripeExpressMethodToOptionKey)),A={};for(let $e of D)f.has($e)?A[$e]=de.has($e)?"always":"auto":A[$e]="never";return A},[a]),ft=(0,s.useMemo)(()=>a.map(p.stripeExpressMethodToOptionKey),[a]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(bl,{state:z,placeholderTestId:"flopay-wallet-placeholder",borderRadius:O,children:(0,c.jsxs)("div",{ref:ge,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Ye&&(0,c.jsxs)("button",{ref:Ue,type:"button","data-testid":"flopay-wallet-retry-button",onClick:_e,style:Ii,children:["Try ",Ri(rt)," again"]}),we!=="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:Ht,disabled:we==="checking",style:Ii,children:we==="checking"?"Checking payment status\u2026":"Check payment status"})]}),fe&&(0,c.jsx)(ao,{identity:fe.identity,methodLabel:fe.methodLabel,onComplete:Ge,onCancel:()=>Ge(null)},fe.id),we==="idle"&&(0,c.jsx)("div",{style:{display:fe?"none":void 0},children:(0,c.jsx)(Vt.ExpressCheckoutElement,{onReady:D=>{se(hl(D,ft))},onLoadError:D=>{se("load_error"),Ti(en(ue),"stripe","wallet")},onClick:async D=>{Z.current=D.expressPaymentType,ke.current=sl(D.expressPaymentType);let de=!0,f=window.setTimeout(()=>{de=!1,D.reject()},nd),A=v?await v(ke.current):{proceed:!0};if(window.clearTimeout(f),!de)return;if(!A.proceed){et.current.delete(le),D.reject();return}let $e=he(D.expressPaymentType);et.current.set(le,{generation:$e,method:D.expressPaymentType,accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}),X(!1),u?.(ke.current),D.resolve()},onConfirm:Q,onCancel:()=>{let D=et.current.get(le);et.current.delete(le),en(ue)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),ne(D?.generation),De.current=null,X(!1),ye.current=!0,Je()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Mt,emailRequired:me,billingAddressRequired:me,layout:{maxColumns:1,overflow:"never"}}},le)})]})}),Ce&&(0,c.jsx)(Jn,{status:"processing"})]})}function vl(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function kd({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:d,borderColor:u,textColor:h,borderRadius:y,fontFamily:v}){let b=(0,p.resolveStripeMethodBrandVariant)(e,t),R=js[e],[B,O]=(0,s.useState)(!1),ue=!!R&&!B,oe=b?.backgroundColor??d??"#ffffff",k=b?.borderColor??u??"#d1d5db",q=b?.textColor??h??"#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:_a,padding:"0 1rem",backgroundColor:oe,color:q,border:`1px solid ${k}`,borderRadius:y??8,fontSize:"0.95rem",fontWeight:600,fontFamily:v,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:[ue?(0,c.jsx)("img",{src:R,alt:"","aria-hidden":"true",onError:()=>O(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!ue&&b?.logoSvg?(0,c.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:b.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:q,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 _i({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:d,onErrorChange:u,onDecline:h,onCancel:y,runBeforeButtonClick:v,onButtonClick:b,isProcessing:R,submitButtonColor:B,submitButtonBorderRadius:O,submitButtonStyle:ue,errorText:oe}){let k=Ir(),{emitInstrument:q}=(0,s.useContext)(Gn),z=(0,Vt.useStripe)(),se=(0,Vt.useElements)(),[Ce,ae]=(0,s.useState)(!1),me=(0,s.useRef)(!1),[fe,pt]=(0,s.useState)(!1),[Ge,ge]=(0,s.useState)("loading"),[Ue,le]=(0,s.useState)(""),Se=!(0,p.isValidEmail)(r?.trim()),Ye=!Se||(0,p.isValidEmail)(Ue.trim()),X=(0,s.useCallback)(async()=>{if(!z||!se||R||me.current||!fe)return;me.current=!0,ae(!0);let we=v?await v("card"):{proceed:!0};if(!we.proceed){me.current=!1,ae(!1);return}b?.("card");let ce=we.sessionId??t,rt=we.nonce??n,ot=zr(o?.trim()),_=Mn({email:we.accountPatch?.email?.trim()||r?.trim()||Ue.trim(),firstName:we.accountPatch?.firstName?.trim()||ot.firstName,lastName:we.accountPatch?.lastName?.trim()||ot.lastName}),$=_.email,ye=Mn({...we.accountPatch,..._});try{if(u?.(null),!(0,p.isValidEmail)($))throw new Error("A valid email address is required for payment.");await a?.(_);let Z=await se.submit();if(Z.error){u?.(Z.error.message??"Payment failed.");return}let ke=[_.firstName,_.lastName].filter(Boolean).join(" "),F=await z.createPaymentMethod({elements:se,params:{billing_details:{email:$,...ke?{name:ke}:{}}}});if(F.error||!F.paymentMethod){u?.(F.error?.message??"Failed to create payment method.");return}let De=F.paymentMethod;if(!ce||!$)throw new Error("Missing sessionId or email for payment.");let mt=De.type||e,et=await Ea(l,q,ce,rt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:mt,paymentMethodId:null,intentKind:"payment"});if(et.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let he=et.clientSecret;if(typeof window<"u")try{localStorage.setItem(br,JSON.stringify({clientSecret:he,sessionId:ce,nonce:rt,accountPatch:ye,paymentMethodId:De.id,paymentMethodType:De.type??e,gateway:"stripe"}))}catch{}let{error:U,paymentIntent:ne}=await z.confirmPayment({clientSecret:he,confirmParams:{return_url:window.location.href,payment_method:De.id},redirect:"if_required"});if(U){if(typeof window<"u")try{localStorage.removeItem(br)}catch{}let xe=U.message??"Payment failed.";u?.(xe),h?.(nn("card",xe,{code:U.code})),await Ta({billingApiUrl:l,sessionId:ce,nonce:rt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:U.code??"provider_declined"}});return}let qe=ne?.status;if(!Ao(qe)){if(typeof window<"u")try{localStorage.removeItem(br)}catch{}let xe=qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";u?.(xe),h?.(nn("card",xe,{code:qe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(br)}catch{}let ct=typeof ne?.payment_method=="string"?ne.payment_method:ne?.payment_method?.id;d({id:ct??De.id,type:"card",threeDSecureActionResultTokenId:ne?.id,gateway:"stripe",paymentMethodType:De.type??e},{accountPatch:ye,paymentMethodCategory:"apm",sessionId:ce,nonce:rt})}catch(Z){u?.(Z instanceof Error?Z.message:"Payment failed. Please try again.")}finally{me.current=!1,ae(!1)}},[z,se,R,fe,v,b,t,n,r,o,Ue,a,l,q,e,d,u,h]);return(0,c.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Se&&(0,c.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Se&&(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:Ue,onChange:we=>le(we.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,c.jsx)(Vt.PaymentElement,{onReady:()=>ge("ready"),onLoadError:()=>{ge("load_error"),Ti(en(k),"stripe","apm")},onChange:we=>{pt(!!we.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:()=>{X()},disabled:!fe||!Ye||Ce||R||Ge!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:B,color:"white",border:"none",borderRadius:O,fontSize:"1rem",fontWeight:600,cursor:!fe||!Ye||Ce||R||Ge!=="ready"?"not-allowed":"pointer",opacity:!fe||!Ye||Ce||R||Ge!=="ready"?.5:1,transition:"opacity 120ms ease-out",...ue??{}},children:Ce?"Processing\u2026":`Pay with ${(0,p.getStripeMethodDisplayName)(e)}`}),oe&&(0,c.jsx)(lo,{margin:"0.75rem 0 0",children:oe})]})}function pl({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:d,paymentElementBaseOptions:u,onTokenizedBody:h,onErrorChange:y,onButtonClick:v,onDecline:b,runBeforeButtonClick:R,onLoadStateChange:B,isProcessing:O=!1,submitButtonColor:ue="#4A49FF",submitButtonBorderRadius:oe=8,submitButtonStyle:k,buttonAppearance:q,themeId:z,onExpandApm:se,expandedApmMethod:Ce}){let{emitInstrument:ae}=(0,s.useContext)(Gn),[me,fe]=(0,s.useState)(null),[pt,Ge]=(0,s.useState)(null),ge=(0,s.useRef)(!1),{request:Ue,collect:le,finish:Se}=oo();(0,s.useEffect)(()=>{l.length>0&&d?B?.("ready"):d||B?.("loading")},[l.length,d,B]);let Ye=(0,s.useCallback)(async _=>{if(!d||ge.current||O)return;ge.current=!0,Ge(_);let $=R?await R("card"):{proceed:!0};if(!$.proceed){ge.current=!1,Ge(null);return}v?.("card");let ye=$.sessionId??e,Z=$.nonce??t,ke=zr([$.accountPatch?.firstName,$.accountPatch?.lastName].filter(Boolean).join(" ")||r),F=Mn({email:$.accountPatch?.email?.trim()||n?.trim(),firstName:$.accountPatch?.firstName?.trim()||ke.firstName,lastName:$.accountPatch?.lastName?.trim()||ke.lastName});if(!(0,p.isValidEmail)(F.email)){Ge(null);let et=await le((0,p.getStripeMethodDisplayName)(_),F);if(!et){ge.current=!1;return}F=et,Ge(_)}let De=F.email,mt=Mn({...$.accountPatch,...F});try{if(y?.(null),!ye||!(0,p.isValidEmail)(De))throw new Error("Missing sessionId or email for payment.");await o?.(F);let et=await Ea(a,ae,ye,Z??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,paymentMethodId:null,intentKind:"payment"});if(et.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let he=et.clientSecret;if(typeof window<"u")try{localStorage.setItem(br,JSON.stringify({clientSecret:he,sessionId:ye,nonce:Z,accountPatch:mt,paymentMethodType:_,gateway:"stripe"}))}catch{}let{error:U,paymentIntent:ne}=await d.confirmPayment({clientSecret:he,confirmParams:{return_url:window.location.href,payment_method_data:{type:_,billing_details:{name:[F.firstName,F.lastName].filter(Boolean).join(" "),...De?{email:De}:{}}}},redirect:"if_required"});if(U){if(typeof window<"u")try{localStorage.removeItem(br)}catch{}let xe=U.message??"Payment failed.";y?.(xe),b?.(nn("card",xe,{code:U.code})),await Ta({billingApiUrl:a,sessionId:ye,nonce:Z,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,providerDeclineReason:U.code??"provider_declined"}});return}let qe=ne?.status;if(!Ao(qe)){if(typeof window<"u")try{localStorage.removeItem(br)}catch{}let xe=qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.(xe),b?.(nn("card",xe,{code:qe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(br)}catch{}let ct=typeof ne?.payment_method=="string"?ne.payment_method:ne?.payment_method?.id;h({id:ct??ne?.id,type:"card",threeDSecureActionResultTokenId:ne?.id,gateway:"stripe",paymentMethodType:_},{accountPatch:mt,paymentMethodCategory:"apm",sessionId:ye,nonce:Z})}catch(et){y?.(et instanceof Error?et.message:"Payment failed. Please try again.")}finally{ge.current=!1,Ge(null)}},[d,O,R,v,e,t,n,le,a,ae,r,o,h,y,b]),[X,we]=(0,s.useState)(null),ce=se?Ce??null:X,rt=(0,s.useCallback)(_=>{ge.current||O||ce&&ce!==_||((0,p.needsStripeMethodExplicitConfirm)(_)?se?se(_):we(_):Ye(_))},[ce,O,Ye,se]),ot=(0,s.useMemo)(()=>X?vl(u,X):null,[X,u]);return(0,c.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ue?(0,c.jsx)(ao,{identity:Ue.identity,methodLabel:Ue.methodLabel,onComplete:Se,onCancel:()=>Se(null)},Ue.id):l.map(_=>{let $=Ce===_,ye=pt===_,Z=pt!==null&&pt!==_||Ce!=null&&Ce!==_;return(0,c.jsxs)(s.default.Fragment,{children:[(0,c.jsx)(kd,{method:_,themeId:z,submitting:ye,disabled:Z,highlighted:$,hasNextStep:(0,p.needsStripeMethodExplicitConfirm)(_),onClick:()=>rt(_),backgroundColor:q?.backgroundColor,borderColor:q?.borderColor,textColor:q?.textColor,borderRadius:q?.borderRadius,fontFamily:q?.fontFamily}),!se&&X===_&&ot&&d&&(0,c.jsx)(Vt.Elements,{stripe:d,options:ot,children:(0,c.jsx)(_i,{method:_,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:h,onErrorChange:y,onDecline:b,onCancel:()=>we(null),runBeforeButtonClick:R,onButtonClick:v,isProcessing:O,submitButtonColor:ue,submitButtonBorderRadius:oe,submitButtonStyle:k})},_)]},_)})})}function Id({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:l,onError:d,onDecline:u,onTokenizedBody:h,firstName:y,lastName:v,chv:b,className:R,submitLabel:B,isProcessing:O,error:ue,onErrorChange:oe,showPayPal:k=!0,showStripe:q=!0,enabledPaymentMethods:z,enabledPaymentMethodCountries:se,showApplePay:Ce=!0,showGooglePay:ae=!0,layout:me="default",theme:fe,buttonsTheme:pt,buttonsStyles:Ge,appearance:ge,cardButtonContent:Ue,cardBackButtonContent:le,cardTitleContent:Se,showSecurityFooter:Ye,onButtonClick:X,onBeforeButtonClick:we,onBuyerIdentityReady:ce,enableAVS:rt,cardFieldOrder:ot,cardPreFormSlot:_,avsLayout:$="row",country:ye,zip:Z,addressLine1:ke,addressLine2:F,city:De,state:mt,onCountryChange:et,onZipChange:he,avsCheck:U,checkoutType:ne,checkoutLayout:qe,totalAmount:ct=0,currency:xe="usd",initialCardOpen:Je=!1,directPaypal:Me,isSubscription:be=!1,session:_e,dataAttachmentPending:Ht=!1,dataAttachmentRequiresIdentity:Q=!1,debug:Mt=!1}){let ft=Ir(),D=la(),de=(0,s.useContext)(ir),{emitInstrument:f}=(0,s.useContext)(Gn),A=_e??de.session,$e=A?.gateways?.paypal?.providerObjectType??Me?.providerObjectType,Re=Ht||de.claimPending===!0,kt=Q||de.claimRequiresIdentity===!0,st=Re&&!kt,Bt=xs(),J=n||Bt,[Gt,Rt]=(0,s.useState)(!1),[mn,ur]=(0,s.useState)(null),[j,yn]=(0,s.useState)(ye??"US"),[wn,cn]=(0,s.useState)(Z??""),[rn,fn]=(0,s.useState)(ke??""),[Zn,dn]=(0,s.useState)(F??""),[Yt,Ne]=(0,s.useState)(De??""),[Ke,on]=(0,s.useState)(mt??""),[yt,$n]=(0,s.useState)(""),[Ft,Jt]=(0,s.useState)({}),ht=(0,s.useRef)(Z??""),jt=(0,s.useRef)(ye??"US"),un=(0,s.useRef)(ke??""),Dt=(0,s.useRef)(F??""),_t=(0,s.useRef)(De??""),an=(0,s.useRef)(mt??""),Bn=(0,s.useRef)(""),Pt=(0,s.useRef)({});(0,s.useEffect)(()=>{let i=(I,H,Ve,Y,dt)=>{if(Pt.current[I])return;let it=H?.trim();!it||it===Ve.current||(Ve.current=it,Y(it),dt?.(it))};i("country",ye,jt,yn,et),i("zip",Z,ht,cn,he),i("addressLine1",ke,un,fn),i("addressLine2",F,Dt,dn),i("city",De,_t,Ne),i("state",mt,an,on)},[ye,Z,ke,F,De,mt,et,he]);let te=(0,s.useMemo)(()=>(0,p.resolveAVSConfig)(rt),[rt]),gn=te!==null,hn=(0,s.useMemo)(()=>(0,p.isAuthorizationOnlySession)(_e),[_e]),Lt=!!_e?.vault?.html,Ut=!!_e?.gateways?.pcivault,Fn=ti(_e),Qn=!!(_e?.gateways?.stripe?.enabledPaymentMethods??z)?.includes("card")||Or(_e),Xt=Lt||Qn||Ut,We=!!(q&&Xt&&e),[qt,Ee]=(0,s.useState)(()=>me!=="buttons"||Je?e??null:null),[L,Te]=(0,s.useState)(0),x=me!=="buttons"||Je||!!e&&qt===e,Nt=_e?.captureMethod,bn=(0,s.useRef)(ft);(0,s.useEffect)(()=>{bn.current=ft},[ft]);let[sn,Dn]=(0,s.useState)(null);(0,s.useEffect)(()=>{if(!We||!e||!x){Dn(null);return}let i=bn.current?bn.current.cardCapture({sessionId:e,captureMethod:Nt}):new lr.PciVaultCardCapture({sessionId:e,captureMethod:Nt,billingApiUrl:J,telemetry:r});return Dn({sessionId:e,captureMethod:Nt,billingApiUrl:J,telemetry:r,capture:i}),()=>{i.unmount()}},[We,e,x,Nt,J,r]);let ve=We&&e&&x&&sn?.sessionId===e&&sn.captureMethod===Nt&&sn.billingApiUrl===J&&sn.telemetry===r?sn.capture:null,vn=(0,s.useMemo)(()=>{let i=j,I=te?(0,p.isAVSFieldVisible)(te.postal_code,i):!1;return Cd(i,wn,I)},[te,j,wn]),{avsInvalid:xr,invalidAvsFields:Kr}=(0,s.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!We||!te)return{avsInvalid:!1,invalidAvsFields:i};let I=j,H=(dt,it)=>(0,p.isAVSFieldVisible)(dt,I)&&!it.trim(),Ve={line1:H(te.address_line_1,rn),city:H(te.city,Yt),state:H(te.state,Ke),zip:vn.empty||vn.malformed};return{avsInvalid:Ve.line1||Ve.city||Ve.state||Ve.zip,invalidAvsFields:Ve}},[We,te,j,rn,Yt,Ke,vn]),[kn,Er]=(0,s.useState)(!1),[pr,er]=(0,s.useState)(!1),[Kt,In]=(0,s.useState)(!1),[Cr,Ln]=(0,s.useState)({line1:!1,city:!1,state:!1}),Rn=(0,s.useRef)(!1),tr=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),nr=(0,s.useRef)(!1),Ct=(0,s.useCallback)(i=>{tr.current[i]=!0,nr.current=!0},[]),Pn=(0,s.useCallback)(i=>!Rn.current&&tr.current[i],[]),jn=(0,s.useCallback)(i=>{Pn(i)&&Ln(I=>I[i]?I:{...I,[i]:!0})},[Pn]),[rr,_n]=(0,s.useState)(()=>wi(_e?.vault)),[Xe,tn]=(0,s.useState)(Je&&Xt?"card":"buttons"),[pn,mr]=(0,s.useState)(null),Mr=Xe==="expanding"||Xe==="card",or=_e?.gateways?.stripe&&!Fn?"stripe":void 0,yr=(0,s.useCallback)(()=>{f?.({class:"card_surface",provider:or})},[or,f]),En=(0,s.useRef)(null),Tn=(0,s.useCallback)(i=>{En.current&&clearTimeout(En.current),En.current=setTimeout(()=>{En.current=null,i()},jo)},[]);(0,s.useEffect)(()=>()=>{En.current&&clearTimeout(En.current)},[]);let Br=(0,s.useCallback)(()=>{yr(),Ee(e??null),Te(i=>i+1),tn("expanding"),Tn(()=>tn("card"))},[Tn,yr,e]),Nn=(0,s.useCallback)(()=>{tn("collapsing"),Tn(()=>tn("buttons"))},[Tn]),Fr=(0,s.useCallback)(i=>{mr(i),tn("apm-expanding"),Tn(()=>tn("apm-form"))},[Tn]),Zt=(0,s.useCallback)(()=>{tn("apm-collapsing"),Tn(()=>{tn("buttons"),mr(null)})},[Tn]);(0,s.useEffect)(()=>{me==="buttons"&&Je&&Xt&&(Ee(e??null),tn("card"))},[me,Je,Xt,e]);let[M,P]=(0,s.useState)(null),ee=(0,s.useRef)(!1),K=(0,s.useRef)(null),Be=(0,s.useRef)("idle"),[tt,Le]=(0,s.useState)(null),G=(0,s.useRef)(tt);(0,s.useEffect)(()=>{G.current=tt},[tt]);let pe=(0,s.useRef)(null),V=(0,s.useMemo)(()=>{if(ce||de.claimBuyerIdentity||_e?.buyerIdentified!==!1||!e||!t)return;let i=`${J}|${e}|${t}`;pe.current?.key!==i&&(pe.current={key:i,claim:no(new lr.PaymentAPI(J,{telemetry:!1}),e,t,{...a?{userId:a}:{},...y?{firstName:y}:{},...v?{lastName:v}:{}})});let I=pe.current.claim;return async H=>{await I(H)}},[ce,de.claimBuyerIdentity,_e?.buyerIdentified,e,t,J,a,y,v]),g=ce??de.claimBuyerIdentity??V,m=ue??mn,w=(0,s.useMemo)(()=>(0,p.resolveTheme)(fe),[fe]),C=(0,s.useMemo)(()=>{let i=w?.buttonsLayout??(0,p.resolveButtonsLayoutTheme)(pt);return Ge?{...i,...Ge,cardButton:{...i.cardButton,...Ge.cardButton},cardFormContainer:{...i.cardFormContainer,...Ge.cardFormContainer},backButton:{...i.backButton,...Ge.backButton},backButtonIcon:{...i.backButtonIcon,...Ge.backButtonIcon},submitButton:{...i.submitButton,...Ge.submitButton},title:{...i.title,...Ge.title}}:i},[w,pt,Ge]),Pe=ge??w?.appearance,ie=(0,s.useMemo)(()=>ka({appearance:Pe,buttonsStyles:C,layout:me}),[Pe,C,me]),Ae=de.inlineSessionPatchProcessing??!1,N=(O??Gt)||Ae,at=J.replace(/\/+$/,""),re=(0,s.useMemo)(()=>ri({userId:a,email:o,firstName:y,lastName:v,country:ye,zip:Z},Ft),[a,o,y,v,ye,Z,Ft]),Et=[re.firstName,re.lastName].filter(i=>!!i?.trim()).join(" "),Oe=!(0,p.isValidEmail)(re.email?.trim()),Ze=(0,s.useRef)(null);We&&Ze.current===null&&(Ze.current=Oe);let W=We&&(Ze.current??Oe),ze=(0,s.useMemo)(()=>Sd(yt,W),[yt,W]),Fe=ze.empty||ze.malformed,gt=(0,s.useMemo)(()=>ft?ft.getRawProvider():null,[ft]),He=(0,s.useMemo)(()=>D?D.getRawProvider():null,[D]),On=ct||100,zn=xe.toLowerCase(),Na=(0,s.useMemo)(()=>Pe?(0,lr.toStripeAppearance)(Pe):null,[Pe]),Wr=Na,zi=(0,s.useMemo)(()=>{let i=Na??{},I=i.rules??{};return{...i,rules:{...I,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...I[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...I[".AccordionItemContents"]??{}}}}},[Na]),Ui=(0,s.useMemo)(()=>({..._s(ct,_e?.captureMethod),currency:zn,...Wr?{appearance:Wr}:null}),[ct,zn,_e?.captureMethod,Wr]),qi=(0,s.useMemo)(()=>({mode:"payment",amount:On,currency:zn,captureMethod:"manual",setupFutureUsage:"off_session",...Wr?{appearance:Wr}:null}),[On,zn,Wr]),Ie=(0,s.useCallback)(i=>{ur(i),oe?.(i)},[oe]),Oa=(0,s.useRef)(""),[$i,Bl]=(0,s.useState)(!1),za=(0,s.useCallback)(()=>{Bl(!0)},[]);(0,s.useEffect)(()=>{if(!We||!W||!g||!$i||Fe||Oa.current)return;let i=Mn({email:(0,p.isValidEmail)(re.email?.trim())?re.email?.trim():Bn.current.trim(),firstName:re.firstName?.trim(),lastName:re.lastName?.trim()});Oa.current=JSON.stringify(i),Jt(I=>({...I,...i})),Promise.resolve(g(i)).catch(I=>{Oa.current="",Ie(I instanceof Error?I.message:"Failed to attach buyer details.")})},[We,W,g,$i,Fe,re.email,re.firstName,re.lastName,Ie]),(0,s.useEffect)(()=>{!We||!ve||ve.setCardFieldOrder?.(ot??null,te==null&&!W)},[We,ve,ot,te,W]),(0,s.useEffect)(()=>{(Xe==="expanding"||Xe==="collapsing"||Xe==="apm-expanding"||Xe==="apm-collapsing")&&Ie(null)},[Xe,Ie]);let fr=(0,s.useCallback)((i,I,H)=>{u?.(nn(i,I,H))},[u]),Hr=(0,s.useCallback)((i,I,H)=>{let Ve=H?.popupBlocked??kr(I),Y=vd(i,Ve),dt=qr(H?.code)??wr(I)??"external_payment_method_failed",it=new p.FloPayError(Y,"api_error",{code:"external_payment_method_failed",param:i});P(null),me==="buttons"&&(tn("buttons"),mr(null)),Ie(Y),d?.(it),console.error("[FloPay] External payment method failed:",{method:i,code:dt,popupBlocked:Ve})},[me,d,Ie]);(0,s.useEffect)(()=>{if(!We||!e){_n(null);return}let i=wi(_e?.vault);if(i){_n(i);return}if(!x){_n(null);return}_n(null);let I=!0;return new lr.PaymentAPI(at).getVaultCapture(e,t).then(H=>{if(!I)return;let Ve=wi(H);Ve?_n(Ve):Ie("Failed to load the secure card form.")}).catch(H=>{I&&Ie(H instanceof Error?H.message:"Failed to load the secure card form.")}),()=>{I=!1}},[We,x,L,e,_e?.vault,at,t,Ie]);let gr=(0,s.useRef)({onComplete:l,onError:d,updateError:Ie,emitDecline:fr,resolvedAccount:re,avsConfig:te,avsCheckProp:U,sessionId:e,nonce:t,baseUrl:at,captureMethod:_e?.captureMethod,paymentId:_e?.paymentId,authorizationExpiresAt:_e?.authorizationExpiresAt,serverSideCardGateway:Fn});gr.current={onComplete:l,onError:d,updateError:Ie,emitDecline:fr,resolvedAccount:re,avsConfig:te,avsCheckProp:U,sessionId:e,nonce:t,baseUrl:at,captureMethod:_e?.captureMethod,paymentId:_e?.paymentId,authorizationExpiresAt:_e?.authorizationExpiresAt,serverSideCardGateway:Fn};let Ua=(0,s.useRef)(!1),Vi=(0,s.useCallback)(()=>{let i=gr.current,I=i.resolvedAccount.email?.trim(),H=(0,p.isValidEmail)(I)?I:Bn.current.trim();if(!(0,p.isValidEmail)(H))return null;let Ve=i.resolvedAccount.firstName?.trim(),Y=i.resolvedAccount.lastName?.trim(),dt=jt.current||i.resolvedAccount.country||"US",it=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.state,dt):!1,ut=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.address_line_1,dt):!1,St=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.postal_code,dt):!1,Tt=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.city,dt):!1,At=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.address_line_2,dt):!1,wt=ut&&!it&&St?(0,p.getStateFromPostalCode)(dt,(ht.current??"").trim()):null,Wn=it?an.current:wt;return{accountData:{userId:i.resolvedAccount.userId??"",email:H,...Ve?{firstName:Ve}:{},...Y?{lastName:Y}:{},...St&&ht.current?{zip:ht.current}:{},...Tt&&_t.current?{city:_t.current}:{},...Wn?{state:Wn}:{},...ut&&un.current?{addressLine1:un.current}:{},...At&&Dt.current?{addressLine2:Dt.current}:{},country:dt},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,p.isAVSFieldVisible)(i.avsConfig.country,dt),postal_code:St,address_line_1:ut,address_line_2:At,city:Tt,state:it}}:{}}},[]),ji=(0,s.useRef)(Re);ji.current=Re,(0,s.useEffect)(()=>{Re||m!==ol||gr.current.updateError(null)},[Re,m]),(0,s.useEffect)(()=>{!We||!ve||ve.setSubmitGate?.(xr||Re||Fe)},[We,ve,xr,Re,Fe]),(0,s.useEffect)(()=>{if(!We||!ve)return;Ua.current=!1;let i=null,I=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,Be.current="idle",P(null)},400)},H=ve.on("submitting",()=>{Er(!0),K.current&&clearTimeout(K.current),Be.current="validation-window",K.current=setTimeout(()=>{K.current=null,Be.current==="validation-window"&&(Be.current="processing")},cd),P("processing");let ut=gr.current;if(!ut.sessionId||!ut.nonce)return;let St=Vi();if(!St){ut.updateError("Enter a valid email address."),Be.current="idle",P(null);return}new lr.PaymentAPI(ut.baseUrl).patchAccountSnapshot(ut.sessionId,ut.nonce,St,{telemetryMode:"best_effort"}).catch(Tt=>{if(!dd(Tt))return;let At=Tt instanceof Error?Tt.message:"Please check your billing address and try again.";ut.updateError(At),Be.current="idle",P(null),ut.onError?.(Tt instanceof p.FloPayError?Tt:new p.FloPayError(At,"api_error"))})}),Ve=ve.on("complete",async ut=>{if(po(ut.sessionId??gr.current.sessionId),Be.current="terminal",P("success"),await new Promise(wt=>setTimeout(wt,600)),Ua.current)return;Ua.current=!0;let St=gr.current,Tt=(0,p.isAuthorizationOnlySession)(St)||ut.outcome==="authorized",At=St.serverSideCardGateway?{}:{paymentIntentId:ut.intentId};gr.current.onComplete?.(Tt?{status:"authorized",...At,paymentId:ut.paymentId??St.paymentId,sessionId:ut.sessionId??St.sessionId,authorizationExpiresAt:ut.authorizationExpiresAt??St.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...At,checkoutMethod:"card"})}),Y=ve.on("decline",ut=>{let St=gr.current,Tt=ut.message??"Your payment was declined. Please try another card or contact your bank.";Be.current="terminal",St.updateError(Tt),P("error");let At=ut.failureOutcome??(0,p.normalizeCheckoutFailureOutcome)(ut.declineReason)??"authorization_declined";St.emitDecline("card",Tt,{code:At,declineCode:At}),I()}),dt=ve.on("error",ut=>{let St=gr.current,Tt=ut.message??"There was a problem processing your payment. Please try again.";Be.current="terminal",St.updateError(Tt),P("error"),St.onError?.(new p.FloPayError(Tt,"api_error",{code:ut.failureOutcome??"capture_failed"})),I()}),it=ve.on("blocked",()=>{if(!ji.current){Er(!0);return}za(),gr.current.updateError(ol)});return()=>{i&&(clearTimeout(i),i=null),K.current&&(clearTimeout(K.current),K.current=null),Be.current="idle",P(null),H(),Ve(),Y(),dt(),it()}},[We,ve,za,Vi]);let hr=!!Me?.clientId,bo=Array.isArray(z),Go=bo&&z.length>0,Fl=bo&&z.includes("paypal"),{expressMethods:Yo,paymentElementMethods:vo}=(0,s.useMemo)(()=>(0,p.partitionStripeMethods)(z,{excludePaypal:hr}),[z,hr]),Ki=hr||!!D,Dl=(0,s.useMemo)(()=>Ki?Yo.filter(i=>i!=="paypal"):Yo,[Yo,Ki]),Ll=(0,s.useMemo)(()=>{let i=[];return Ce&&i.push("apple_pay"),ae&&i.push("google_pay"),i},[Ce,ae]),Gr=bo?Dl:Ll,Nl=q&&Gr.length>0,qa=gn?j:ye,Jo=(0,s.useMemo)(()=>{let i=qa?.trim().toUpperCase();return i?se?vo.filter(I=>{let H=se[I];return!H||H.length===0||H.includes(i)}):(0,p.filterStripeMethodsByCountry)(vo,qa):vo},[vo,qa,se]),$a=(0,s.useMemo)(()=>({mode:"payment",amount:On,currency:zn,paymentMethodCreation:"manual",appearance:zi}),[On,zn,zi]),[Wi,Hi]=(0,s.useState)("loading"),[Gi,Yi]=(0,s.useState)("loading"),[Ji,Xi]=(0,s.useState)("loading"),[Ol,Va]=(0,s.useState)(!1),[Zi,ja]=(0,s.useState)("loading"),[Ka,zl]=(0,s.useState)();(0,s.useEffect)(()=>{zl(ca())},[]);let Xo=Ka?.inAppBrowser,Zo=Ka?da(Ka,Me?.approvalPresentation,$e??(be?"subscription":"order")):"popup",Qi=k&&(hr||(bo?Fl:Xo===!1)),es=q&&Nl,Po=(!st||!!de.waitForDataAttachment)&&Qi&&hr,ts=Zi==="retrying"||Zi==="exhausted",Co=!st&&Qi&&!!He&&(!hr||ts),Yr=!st&&es&&!!gt,So=!st&&q&&Go&&Jo.length>0&&!!gt,Ul=Po&&!ts?Ol:Co&&cl(Wi),ql=Yr&&cl(Gi),$l=So&&Ji!=="load_error",ns=i=>i==="loading"||i==="ready",rs=Po||Co&&ns(Wi)||Yr&&ns(Gi)||So&&Ji!=="load_error",Qo=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!Qo.current){if(!q&&!k){Qo.current=!0;let i=new p.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(i),Ie(i.message)}else if(!q&&k&&!hr&&!He){Qo.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),Ie(i.message)}else if(Xo!==void 0&&!st&&!Xt&&!rs){Qo.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),Ie(i.message)}}},[q,k,hr,He,Xo,st,Xt,rs,d,Ie]);let os=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(os.current||!Go)return;let i=[];Ce!==!0&&i.push("showApplePay"),ae!==!0&&i.push("showGooglePay"),i.length!==0&&(os.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.`))},[Go,Ce,ae]);let as=(0,s.useCallback)((i,I)=>de.applyInlineSessionPatch?de.applyInlineSessionPatch(i).then(H=>({error:null,sessionId:H.sessionId||e,nonce:H.session?.clientSecret||t})).catch(H=>{let Ve=ll(I,H);return Ie(Ve.message),d?.(Ve),{error:Ve,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[de.applyInlineSessionPatch,t,d,e,Ie]),ar=(0,s.useCallback)(async i=>{if(i!=="card"&&st&&await de.waitForDataAttachment?.(),!we)return{proceed:!0};try{let I=await we({method:i,sessionId:e||void 0,createSession:de.inlineSessionDraft});if(I===!1)return{proceed:!1};if(I&&typeof I=="object"){I.account&&Jt(Ve=>({...Ve??{},...I.account}));let H=await as(I,i);return H.error?{proceed:!1,accountPatch:I.account}:{proceed:!0,accountPatch:I.account,sessionId:H.sessionId,nonce:H.nonce}}return{proceed:!0}}catch(I){let H=ll(i,I);return Ie(H.message),d?.(H),{proceed:!1}}},[as,de.inlineSessionDraft,de.waitForDataAttachment,st,we,d,e,Ie]),is=(0,s.useCallback)(async(i,I)=>{if(ee.current)return;ee.current=!0,Rt(!0),P("processing"),Ie(null);let H=I?.sessionId??e,Ve=I?.nonce??t,Y=ri(re,I?.accountPatch),dt=I?.completionPaymentMethodId??xo(i),it=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,ut=fd(i),St=()=>{f?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:ut})};try{let At=await new lr.PaymentAPI(at).processPayment(Y.userId??"",{sessionId:H,nonce:Ve,paymentMethodCategory:I?.paymentMethodCategory??hd(i),tokenizedData:it,accountData:{...I?.accountPatch,userId:Y.userId??"",email:Y.email??"",firstName:Y.firstName||void 0,lastName:Y.lastName||void 0,...te?(()=>{let bt=jt.current,Hn=(0,p.isAVSFieldVisible)(te.state,bt),Cn=(0,p.isAVSFieldVisible)(te.address_line_1,bt),Qt=(0,p.isAVSFieldVisible)(te.postal_code,bt),Nr=Cn&&!Hn&&Qt?(0,p.getStateFromPostalCode)(bt,(ht.current??"").trim()):null,Eo=Hn?an.current:Nr;return{country:bt,...Qt&&ht.current?{zip:ht.current}:{},...(0,p.isAVSFieldVisible)(te.city,bt)&&_t.current?{city:_t.current}:{},...Eo?{state:Eo}:{},...Cn&&un.current?{addressLine1:un.current}:{},...(0,p.isAVSFieldVisible)(te.address_line_2,bt)&&Dt.current?{addressLine2:Dt.current}:{}}})():{}},chv:b,avsCheck:U??!1,checkoutType:ne,checkoutLayout:qe,avsConfig:te?{country:(0,p.isAVSFieldVisible)(te.country,jt.current),postal_code:(0,p.isAVSFieldVisible)(te.postal_code,jt.current),address_line_1:(0,p.isAVSFieldVisible)(te.address_line_1,jt.current),address_line_2:(0,p.isAVSFieldVisible)(te.address_line_2,jt.current),city:(0,p.isAVSFieldVisible)(te.city,jt.current),state:(0,p.isAVSFieldVisible)(te.state,jt.current)}:void 0});if(At.ok){let bt=At.status===204?null:await At.json().catch(()=>null),Hn=(0,p.isAuthorizationOnlySession)(_e)||bt?.status==="authorized";po(H),P("success"),Le(null),await new Promise(Nr=>setTimeout(Nr,600));let Cn;typeof bt?.paymentId=="string"?Cn=bt.paymentId:_e?.paymentId&&(Cn=_e.paymentId);let Qt;typeof bt?.authorizationExpiresAt=="string"?Qt=bt.authorizationExpiresAt:_e?.authorizationExpiresAt&&(Qt=_e.authorizationExpiresAt),l?.(Hn?{status:"authorized",...Cn===void 0?{}:{paymentId:Cn},sessionId:typeof bt?.sessionId=="string"?bt.sessionId:H,...Qt===void 0?{}:{authorizationExpiresAt:Qt},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:dt,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:dt,checkoutMethod:i.isPaypal?"paypal":"card"});return}let wt=await At.json().catch(()=>null);if(wt?.type==="paypal_redirect_required"){let bt=wt.threeDSecureToken,Hn=wt.paymentMethodId||i.id||"";if(!ft||!bt){P("error"),Ie("PayPal authorization required but no token provided.");return}try{let Cn=D?.getRawProvider();if(!Cn){Ie("PayPal is not available.");return}let Qt={return_url:window.location.href};Hn&&(Qt.payment_method=Hn);let{error:Nr}=await Cn.confirmPayment({clientSecret:bt,confirmParams:Qt,redirect:"if_required"});if(Nr){P("error");let Eo=Nr.message??"PayPal payment failed.";Ie(Eo),fr("paypal",Eo,{code:Nr.code})}}catch(Cn){P("error"),Ie(Cn instanceof Error?Cn.message:"PayPal authorization failed.")}return}if(wt?.type==="paypal_direct_required"){let bt=wt.orderId;if(!bt){P("error"),Ie("PayPal retry required but no order id provided.");return}let Hn=G.current?.attempts??0;if(Hn>=2){P("error"),Ie("PayPal payment could not be completed after multiple attempts."),fr("paypal","paypal_direct_required retry limit exceeded");return}Va(!1),ja("loading"),Le({orderId:bt,attempts:Hn+1}),P(null);return}(0,p.classifyPaymentRejection)(At.status,wt)||St(),P("error");let Wn=wt?.message??"Payment failed. Please try again.";Ie(Wn),fr(i.isPaypal?"paypal":"card",Wn,{code:wt?.code??wt?.gatewayErrorCode,declineCode:wt?.declineCode??wt?.gatewayDeclineReason}),await new Promise(bt=>setTimeout(bt,400))}catch(Tt){fl(Tt)||St(),P("error"),Ie(Tt instanceof Error?Tt.message:"An unexpected error occurred"),await new Promise(At=>setTimeout(At,400))}finally{Rt(!1),P(null),ee.current=!1}},[at,e,t,re,te,U,ne,qe,b,ft,D,_e,l,Ie,fr,f]),An=(0,s.useCallback)((i,I)=>{h?h(i):is(i,I)},[h,is]),wo=`${ml}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(wo);if(!i)return;let I;try{I=JSON.parse(i)}catch{localStorage.removeItem(wo);return}if(!I||typeof I.createdAt!="number"||Date.now()-I.createdAt<0||Date.now()-I.createdAt>yl||typeof I.paymentMethodId!="string"||typeof I.providerIntentId!="string"||typeof I.paymentMethodType!="string"||I.sessionId!==e||!t||I.nonce!==t||!Gr.includes(I.paymentMethodType)){localStorage.removeItem(wo);return}localStorage.removeItem(wo),An({id:I.paymentMethodId,type:"card",threeDSecureActionResultTokenId:I.providerIntentId,gateway:"stripe",paymentMethodType:I.paymentMethodType},{...I.accountPatch?{accountPatch:I.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[An,t,e,wo,Gr]);let ss=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||ss.current)return;let i=new URLSearchParams(window.location.search),I=i.get("payment_intent"),H=i.get("payment_intent_client_secret"),Ve=i.get("redirect_status");if(!I||!H||!ft)return;let Y=ft.getRawProvider();if(!Y)return;let dt=wt=>{let Wn=localStorage.getItem(wt);if(!Wn)return null;try{return JSON.parse(Wn)}catch{return localStorage.removeItem(wt),null}},it=dt(br)??dt(tl),ut;if(it?.clientSecret){if(it.clientSecret!==H)return;ut={...it.accountPatch?{accountPatch:it.accountPatch}:{},...it.sessionId?{sessionId:it.sessionId}:{},...it.nonce?{nonce:it.nonce}:{}}}else if(it?.sessionId&&it.sessionId!==e)return;ss.current=!0,localStorage.removeItem(br),localStorage.removeItem(tl);let St=new URL(window.location.href);St.searchParams.delete("payment_intent"),St.searchParams.delete("payment_intent_client_secret"),St.searchParams.delete("redirect_status"),window.history.replaceState({},"",St.toString());let Tt=it?.paymentMethodType??it?.tokenType??"card",At="card";(async()=>{if(Ve==="failed"){let Qt="Payment was declined. Please try again.";Ie(Qt),fr(At,Qt);return}let{paymentIntent:wt,error:Wn}=await Y.retrievePaymentIntent(H);if(Wn){let Qt=Wn.message??"Failed to retrieve payment status.";Ie(Qt),fr(At,Qt,{code:Wn.code});return}let bt=wt?.status,Hn=Ao(bt);if(!wt||!Hn){let Qt=bt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ie(Qt),fr(At,Qt,{code:bt??"missing_payment_intent"});return}let Cn=typeof wt.payment_method=="string"?wt.payment_method:wt.payment_method?.id;An({id:Cn??it?.paymentMethodId??it?.tokenId??wt.id,type:"card",threeDSecureActionResultTokenId:wt.id,gateway:it?.gateway??"stripe",paymentMethodType:Tt},ut)})()},[e,An,ft,Ie,fr]);let Wa=(0,s.useCallback)(i=>{i.preventDefault()},[]);if(!(We||ft!==null))return(0,c.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ko=me==="buttons",xn=Pe?.variables,Vl=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ha=xn?.colorBackground,jl=Ha&&!Vl.has(Ha)?Ha:void 0,Io=C.cardInputBorder??(ko?"#e5e7eb":"#A4A4FF"),ls=xn?.colorDanger??"#dc2626",Ot=i=>Kr[i]&&(Cr[i]||kn),ea=Fe&&(Kt||kn),Kn=i=>i?ls:Io,ta=(vn.malformed||vn.empty)&&(pr||kn),Kl=Kn(ta),Ga=C.cardFormContainer?.backgroundColor??jl??(ko?"white":"#EDEDFF"),Jr=C.cardInputBackground??xn?.colorBackground??"white",Ya=Qr(le),cs=Qr(Se),Xr=C.nameInput,ds=C.cardInputFontSize??wd(Xr?.fontSize)??xn?.fontSizeBase??"16px",us=typeof Xr?.fontFamily=="string"?Xr.fontFamily:xn?.fontFamily??"Poppins, sans-serif",ps=bi(Xr?.fontWeight)??400,Wl=C.cardInputColor??(typeof Xr?.color=="string"?Xr.color:void 0)??xn?.colorText??"#262833",Hl=C.cardInputPlaceholderColor??"#9ca3af",$t=xn?.borderRadius??"8px",Dr=xn?.borderRadius??C.cardButton?.borderRadius??$t,Lr=xn?.colorPrimary??"#4A49FF",Gl=xn?.colorPrimaryHover??go(Lr,.12),Ja=xn?.colorText??"#262833",Xa={fontSize:ds,fontFamily:us,fontWeight:ps,color:Wl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ro={marginTop:"0.375rem",...Xa,fontSize:"0.75rem",lineHeight:1.4,color:ls},Yl={"--flopay-input-placeholder-color":Hl,"--flopay-input-font-size":ds,"--flopay-input-font-family":us,"--flopay-input-font-weight":String(ps)},_o=C.cardFormContainer??{},Za=_o.padding??(ko?"0":"1rem"),Qa=_o.borderRadius??$t,Jl=ve&&rr?(0,c.jsx)(fo,{capture:ve,html:rr.html,messageToken:rr.messageToken,expectedOrigin:rr.expectedOrigin,theme:ie,submitLabel:B,onReady:()=>{if(!W&&!te||typeof document>"u")return;let i=()=>{let H=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(H){Rn.current=!0;try{H.focus()}finally{Rn.current=!1}}};nr.current||i()},onError:i=>Ie(i),onValidation:i=>{let I=Be.current;(I==="idle"||I==="validation-window")&&(Ie(i),i&&Be.current==="validation-window"&&(K.current&&(clearTimeout(K.current),K.current=null),Be.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"}),ms=(0,c.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&yr()},style:{backgroundColor:Ga,borderRadius:Qa,..._o,padding:Za,...Yl,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 @@ ${fn.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,ms=Ge==="apm-expanding"||Ge==="apm-form"||Ge==="apm-collapsing",Xr;Ge==="apm-expanding"?Xr=nl:Ge==="apm-collapsing"&&(Xr=rl);let na=Ht?gl(Ua,Ht):null;if(ye==="buttons"){let i=Ge==="buttons"||Ge==="expanding"||Ge==="apm-expanding",k=Ge==="expanding"||Ge==="card"||Ge==="collapsing",G=Ue===void 0?{boxSizing:"border-box",height:Ra,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ve;Ge==="expanding"||Ge==="apm-expanding"?Ve=ud:(Ge==="collapsing"||Ge==="apm-collapsing")&&(Ve=dd);let Y;return Ge==="expanding"?Y=nl:Ge==="collapsing"&&(Y=rl),(0,c.jsxs)("form",{onSubmit:ja,className:I,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Ci,{}),qt&&(0,c.jsx)(Yn,{status:qt,errorMessage:h,authorized:vn}),(0,c.jsxs)("div",{style:{display:"grid"},children:[(0,c.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Ve?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Ve?md:{},...Ve?{animation:Ve,pointerEvents:"none"}:{}},children:[us("flopay-direct-paypal-gate-debug"),ps("flopay-stripe-gate-debug"),vo&&Ae&&(0,c.jsxs)(c.Fragment,{children:[He&&(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)(Fo,{sessionId:e,nonce:t,billingApiUrl:J,email:H.email,billingName:Ct||void 0,onBuyerIdentityReady:x,clientId:Ae.clientId,environment:Ae.environment,currency:Te.toUpperCase(),isSubscription:Pe,providerObjectType:$e,approvalPresentation:Xo==="popup"?void 0:Xo,onTokenizedBody:Tn,onComplete:l,onErrorChange:Re,onDecline:u,onTechnicalFailure:Wr,onButtonClick:Z,runBeforeButtonClick:tr,isProcessing:V,onLoadStateChange:qa,onInitializationStateChange:$a,session:T,existingOrderId:He?.orderId,debug:At},He?.orderId??"fresh")]}),Po&&(0,c.jsx)(Vt.Elements,{stripe:Lt,options:Oi,children:(0,c.jsx)(sl,{sessionId:e,nonce:t,email:H.email,billingName:Ct||void 0,onBuyerIdentityReady:x,billingApiUrl:J,onTokenizedBody:Tn,onErrorChange:Re,isProcessing:V,onButtonClick:Z,onDecline:u,onTechnicalFailure:Wr,runBeforeButtonClick:tr,onLoadStateChange:ji,placeholderBorderRadius:Dr})}),Gr?(0,c.jsx)(Vt.Elements,{stripe:me,options:Ni,children:(0,c.jsx)(ll,{sessionId:e,nonce:t,email:H.email,billingName:Ct||void 0,onBuyerIdentityReady:x,billingApiUrl:J,intentKind:lt>0?"payment":"setup",expressMethods:Hr,onTokenizedBody:Tn,onErrorChange:Re,onButtonClick:Z,onDecline:u,onTechnicalFailure:Wr,runBeforeButtonClick:tr,onLoadStateChange:Wi,placeholderBorderRadius:Dr})}):null,!Gr&&Xi?(0,c.jsx)("div",{style:{height:Ra,borderRadius:Dr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Co&&(0,c.jsx)(cl,{sessionId:e,nonce:t,email:H.email,billingName:[H.firstName,H.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:x,billingApiUrl:J,paymentElementMethods:Yo,stripeInstance:me,paymentElementBaseOptions:Ua,onTokenizedBody:Tn,onErrorChange:Re,onButtonClick:Z,onDecline:u,runBeforeButtonClick:tr,onLoadStateChange:Gi,isProcessing:V,submitButtonColor:Lr,submitButtonBorderRadius:$t,submitButtonStyle:m.submitButton,onExpandApm:_n,expandedApmMethod:Ht,themeId:he,buttonAppearance:{backgroundColor:m.cardButton?.backgroundColor,borderColor:m.cardInputBorder,textColor:m.cardButton?.color,borderRadius:Dr}}),Fe&&(0,c.jsx)("button",{type:"button",onClick:async()=>{V||!(await tr("card")).proceed||(Z?.("card"),Br())},disabled:V,style:{width:"100%",...G,...m.cardButton,..._i({themeBundle:y,resolvedPrimaryColor:Lr,resolvedBorderRadius:$t,submitButtonStyle:m.submitButton,explicitPrimaryColor:An?.colorPrimary}),fontSize:m.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:ct=>{!V&&(y||An?.colorPrimary)&&(ct.currentTarget.style.backgroundColor=Kl)},onMouseLeave:ct=>{(y||An?.colorPrimary)&&(ct.currentTarget.style.backgroundColor=Lr)},onMouseDown:ct=>{ct.currentTarget.style.transform="scale(0.985)"},onMouseUp:ct=>{ct.currentTarget.style.transform="scale(1)"},children:(0,c.jsx)(Qr,{content:Ue})}),h&&Ge==="buttons"&&(0,c.jsx)(so,{margin:"0.25rem 0",styleOverride:m.errorBanner,children:h})]}),Fe&&k&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...Y?{animation:Y}:{},...Ge==="collapsing"?{pointerEvents:"none"}:{}},children:ds}),q&&ms&&Ht&&na&&me&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...Xr?{animation:Xr}:{},...Ge==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Wa,borderRadius:Xa,...Ro,padding:Ja},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:vr,style:{display:"inline-flex",alignItems:"center",gap:Ha?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.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",...m.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)(eo,{content:ce})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:m.titleFontSize??"1.05rem",color:Ga,paddingRight:80,...m.title},children:`Pay with ${(0,p.getStripeMethodDisplayName)(Ht)}`})]}),(0,c.jsx)(Vt.Elements,{stripe:me,options:na,children:(0,c.jsx)(ki,{method:Ht,sessionId:e,nonce:t,email:H.email,billingName:[H.firstName,H.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:x,billingApiUrl:J,onTokenizedBody:Tn,onErrorChange:Re,onDecline:u,onCancel:vr,runBeforeButtonClick:tr,onButtonClick:Z,isProcessing:V,submitButtonColor:Lr,submitButtonBorderRadius:$t,submitButtonStyle:m.submitButton,errorText:h})},Ht)]})})]})]})}return ms&&Ht&&na&&me&&q?(0,c.jsxs)("form",{onSubmit:ja,className:I,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Ci,{}),qt&&(0,c.jsx)(Yn,{status:qt,errorMessage:h,authorized:vn}),(0,c.jsx)("div",{style:{...Xr?{animation:Xr}:{},...Ge==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Wa,borderRadius:Xa,...Ro,padding:Ja},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:vr,style:{display:"inline-flex",alignItems:"center",gap:Ha?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.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",...m.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)(eo,{content:ce})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:m.titleFontSize??"1.05rem",color:Ga,paddingRight:80,...m.title},children:`Pay with ${(0,p.getStripeMethodDisplayName)(Ht)}`})]}),(0,c.jsx)(Vt.Elements,{stripe:me,options:na,children:(0,c.jsx)(ki,{method:Ht,sessionId:e,nonce:t,email:H.email,billingName:[H.firstName,H.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:x,billingApiUrl:J,onTokenizedBody:Tn,onErrorChange:Re,onDecline:u,onCancel:vr,runBeforeButtonClick:tr,onButtonClick:Z,isProcessing:V,submitButtonColor:Lr,submitButtonBorderRadius:$t,submitButtonStyle:m.submitButton,errorText:h})},Ht)]})})]}):(0,c.jsxs)("form",{onSubmit:ja,className:I,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Ci,{}),qt&&(0,c.jsx)(Yn,{status:qt,errorMessage:h,authorized:vn}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[us("flopay-direct-paypal-gate-debug-default"),ps("flopay-stripe-gate-debug-default"),vo&&Ae&&(0,c.jsxs)(c.Fragment,{children:[He&&(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)(Fo,{sessionId:e,nonce:t,billingApiUrl:J,email:H.email,billingName:Ct||void 0,onBuyerIdentityReady:x,clientId:Ae.clientId,environment:Ae.environment,currency:Te.toUpperCase(),isSubscription:Pe,providerObjectType:$e,approvalPresentation:Xo==="popup"?void 0:Xo,onTokenizedBody:Tn,onComplete:l,onErrorChange:Re,onDecline:u,onTechnicalFailure:Wr,onButtonClick:Z,runBeforeButtonClick:tr,isProcessing:V,onLoadStateChange:qa,onInitializationStateChange:$a,session:T,existingOrderId:He?.orderId,debug:At},He?.orderId??"fresh")]}),Po&&(0,c.jsx)(Vt.Elements,{stripe:Lt,options:Oi,children:(0,c.jsx)(sl,{sessionId:e,nonce:t,email:H.email,billingName:Ct||void 0,onBuyerIdentityReady:x,billingApiUrl:J,onTokenizedBody:Tn,onErrorChange:Re,isProcessing:V,onButtonClick:Z,onDecline:u,onTechnicalFailure:Wr,runBeforeButtonClick:tr,onLoadStateChange:ji,placeholderBorderRadius:Dr})}),Gr&&(0,c.jsx)(Vt.Elements,{stripe:me,options:Ni,children:(0,c.jsx)(ll,{sessionId:e,nonce:t,email:H.email,billingName:Ct||void 0,onBuyerIdentityReady:x,billingApiUrl:J,intentKind:lt>0?"payment":"setup",expressMethods:Hr,onTokenizedBody:Tn,onErrorChange:Re,onButtonClick:Z,onDecline:u,onTechnicalFailure:Wr,runBeforeButtonClick:tr,onLoadStateChange:Wi,placeholderBorderRadius:Dr})}),Co&&(0,c.jsx)(cl,{sessionId:e,nonce:t,email:H.email,billingName:[H.firstName,H.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:J,paymentElementMethods:Yo,stripeInstance:me,paymentElementBaseOptions:Ua,onTokenizedBody:Tn,onErrorChange:Re,onButtonClick:Z,onDecline:u,runBeforeButtonClick:tr,onLoadStateChange:Gi,isProcessing:V,submitButtonColor:Lr,submitButtonBorderRadius:$t,submitButtonStyle:m.submitButton,themeId:he,onExpandApm:_n,expandedApmMethod:Ht,buttonAppearance:{backgroundColor:m.cardButton?.backgroundColor,borderColor:m.cardInputBorder,textColor:m.cardButton?.color,borderRadius:Dr}})]}),Fe&&(Ol||Nl||zl)&&(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"}})]}),Fe&&ds]})}var E=require("react/jsx-runtime"),go=44,Fi="flopay_checkout_saved_payment_resume",Ma=new Map,Aa=new Map;function hl(e,t){t.settled&&t.consumers===0&&Ma.get(e)===t&&Ma.delete(e)}function wd(e,t,n){let r=Aa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Aa.set(e,a);let l=()=>{Aa.get(e)===a&&Aa.delete(e)};return o.then(l,l),o}function jo(e){return new Promise(t=>setTimeout(t,e))}function xa(e,t,n){let r=ua({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:je.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Ko(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ei(e,t,n,r,o,a){let l=xa(e,t,n);l.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),Ko(l)}function bl(e,t,n,r){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function vl(e,t,n,r,o){let a=(0,je.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 je.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof je.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 Bi(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 Ti(e){return!e||e.data.stripe?.publishableKey?!1:!!Bi(e)?.clientId}var kd={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Id(e){return new Ir.FloPay(kd,{publishableKey:"provider_unavailable",...e})}async function Ai(e,t){let{publishableKey:n,paypalPublishableKey:r}=pi(e);return{...await mi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Di(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Rd(){if(!Di())return null;try{let e=window.sessionStorage.getItem(Fi);return e?JSON.parse(e):null}catch{return null}}function Pl(e){if(Di())try{window.sessionStorage.setItem(Fi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function xi(){if(Di())try{window.sessionStorage.removeItem(Fi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function _d(){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 Cl(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 Mi(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Ed(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Sl(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Td(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 Ba({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:d,error:u,onComplete:b,onError:f,onInstrument:P,onDecline:v,onCountryChange:I,onZipChange:M,showPayPal:N=!0,showStripe:pe=!0,enabledPaymentMethods:ae,showApplePay:w=!0,showGooglePay:q=!0,debug:O=!1,layout:le,theme:Se,buttonsTheme:ie,buttonsStyles:ye,cardButtonContent:he,cardBackButtonContent:dt,cardTitleContent:Je,showSecurityFooter:be,onButtonClick:Ue,onBeforeButtonClick:ce,enableAVS:we,cardFieldOrder:Xe,cardPreFormSlot:Z,avsLayout:ke,submitLabel:de,className:nt,initialErrorMessage:rt=null,children:R,checkoutMode:$,confirmLabel:fe,renderConfirmButton:Q,onSessionCompleted:Ie}){let F=(0,je.resolveBillingApiUrl)(r),Me=(0,C.useMemo)(()=>(0,je.resolveTheme)(Se),[Se]),ut=a??Me?.appearance,et=n?"embedded_checkout":"standard_checkout",ve=Mi(R,le),[z,oe]=(0,C.useState)(null),[qe,lt]=(0,C.useState)(null),Te=(0,C.useRef)(null),Ze=(0,C.useRef)(null),Ae=(0,C.useRef)(0),[Pe,Be]=(0,C.useState)(null),Jt=(0,C.useRef)(null),[te,At]=(0,C.useState)(null),mt=(0,C.useMemo)(()=>n?co(n):"",[n]),D=n?`create:${mt}`:`session:${e??""}`,ue=Sl(te),g=(0,C.useRef)(new Set),T=(0,C.useRef)(D),$e=(0,C.useRef)(D);qr(()=>{$e.current=D,T.current!==D&&(T.current=D,g.current.clear())},[D]);let _e=(0,C.useCallback)(S=>{if($e.current===D){if(ri.has(S.name)){if(g.current.has(S.name))return;g.current.add(S.name)}st(()=>P?.(S))}},[D,P]),St=io(_e,D),at=(0,C.useRef)(!1),xt=(0,C.useCallback)(S=>{if(at.current)return;let B=S.gateway||!ue?S:{...S,gateway:ue};_e(B)},[_e,ue]);(0,C.useEffect)(()=>{St({class:"lifecycle",name:"checkout.mount"})},[St]);let[J,Xt]=(0,C.useState)(e??""),It=e??J,fn=n?"":It,[sr,j]=(0,C.useState)(!0),[gn,kn]=(0,C.useState)(null),[dn,on]=(0,C.useState)(0),[hn,Xn]=(0,C.useState)("full"),[un,Zt]=(0,C.useState)(!1),[ze,Ke]=(0,C.useState)(rt),[an,pt]=(0,C.useState)(null),[zn,Mt]=(0,C.useState)(null),[Qt,ft]=(0,C.useState)(!1),[jt,pn]=(0,C.useState)(void 0),[Bt,Rt]=(0,C.useState)(""),[sn,Mn]=(0,C.useState)(!1),[vt,ne]=(0,C.useState)(!1),[bn,vn]=(0,C.useState)(!1),Ft=(0,C.useRef)(null),Ut=(0,C.useRef)(0),lr=(0,C.useRef)(void 0),[Bn,mn]=(0,C.useState)("loading"),[Fe,Zn]=(0,C.useState)(0),Dt=(0,C.useRef)(!1),xe=(0,C.useRef)(!1),L=(0,C.useRef)(!1),ge=(0,C.useRef)(null),A=(0,C.useMemo)(()=>({checkoutMode:$??hn,layout:Ed(R,le)}),[$,R,hn,le]),Kt=(0,C.useRef)(b);Kt.current=b;let ln=(0,C.useRef)(f);ln.current=f;let In=(0,C.useRef)(v);In.current=v;let Pt=(0,C.useCallback)((S,B)=>{Te.current=S,lt(S),Jt.current=B,Be(B)},[]),We=(0,C.useCallback)(()=>{let S=Ze.current;S&&(Ze.current=null,S.destroy())},[]);(0,C.useEffect)(()=>{tn(qe)?.setCheckoutContext(A),Pe&&Pe!==qe&&tn(Pe)?.setCheckoutContext(A)},[qe,Pe,A]);let cr=(0,C.useRef)(Ie);cr.current=Ie;let jr=(0,C.useCallback)(S=>{mn(S),!(S!=="exhausted"||L.current)&&(L.current=!0,ln.current?.(new je.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Rr=(0,C.useCallback)(()=>{mn("retrying"),Zn(S=>S+1)},[]);(0,C.useEffect)(()=>{mn("loading"),Zn(0),L.current=!1},[It]),(0,C.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:je.SDK_VERSION,checkout_type:et,checkout_layout:ve,billing_api_url:F})},[ve,et,F]);let Fn=(0,C.useMemo)(()=>n?co(n,!0):"",[n]),xr=(0,C.useMemo)(()=>Bt===Fn?jt:void 0,[jt,Bt,Fn]),dr=(0,C.useMemo)(()=>n?Qa(n,xr):void 0,[n,xr]),Qn=$??dr?.checkoutMode??"full",Wt=(0,C.useMemo)(()=>dr?{...dr,checkoutMode:Qn}:void 0,[dr,Qn]);(0,C.useEffect)(()=>{pn(void 0),Rt(Fn),lr.current=void 0,Ft.current=null,vn(!1)},[Fn]),(0,C.useEffect)(()=>{Ke(rt)},[rt]);let Rn=(0,C.useCallback)((S,B,K)=>{st(()=>{In.current?.(rn(S,B,K))})},[]),br=(0,C.useCallback)(async(S,B)=>{Ke(null),Mt(null),ft(!1),pt("processing");let K=B?.sessionId??S.id,U=Sl(S),He=Te.current??Jt.current,yt=tn(He),De=He?null:xa(F,o,A),W={log:V=>{yt?yt.log(V):De?.log(V)},error:V=>{yt?yt.error(V):De?.error(V)},terminal:V=>{yt?yt.terminal(V):De?.terminal(V)},performance:V=>{yt?yt.performance(V):De?.performance(V)},now:()=>yt?.now()??De?.now()??0,elapsed:V=>yt?.elapsed(V)??Math.max(0,(De?.now()??V)-V)},Ce=W.now(),x=!!(B?.initialAutoProcessingError||B?.initialAutoProcessingPending),h=!1,y,m=()=>{h||(h=!0,x=!0,y=W.now(),W.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),W.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},X=!1,Le=()=>{X||(X=!0,W.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),W.performance({stage:"processing",durationMs:W.elapsed(Ce),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),y!==void 0&&W.performance({stage:"recovery",durationMs:W.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}))};W.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),at.current=!0;try{W.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{at.current=!1}St({class:"lifecycle",name:"payment.processing.started",provider:U}),x&&m();let se;try{let V=Os(B?.initialAutoProcessingError),re;if(V)m(),V.type==="paypal_redirect_required"&&ge.current?.publishableKey&&Pl({sessionId:K,publishableKey:ge.current.publishableKey,paypalPublishableKey:ge.current.paypalPublishableKey}),re=await Ca(V,{flopay:Te.current,paypalFlopay:Jt.current,attempt3DS:B?.attempt3DS,billingApiUrl:F,sessionId:K,session:S,telemetry:!1}),V.type==="paypal_redirect_required"&&xi();else if(B?.initialAutoProcessingPending){let Gt=(await new Ir.PaymentAPI(F,{telemetry:!1}).waitForCheckoutSessionCompletion(B.initialAutoProcessingPending.sessionId,{initialDelayMs:B.initialAutoProcessingPending.retryAfterMs})).data.session;if(!no(Gt))throw ia(Gt);re=zr(Gt,K)}else{if(B?.initialAutoProcessingError)throw Ar(B.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:B.initialAutoProcessingError.checkoutMethod});if(B?.fromCreateSession)return B?.fallbackToFull&&(Xn("full"),Cl("full")),!1;{let H=await mo({billingApiUrl:F,sessionId:K,session:S,telemetry:!1});H.type==="success"?re=H.result:(m(),H.type==="paypal_redirect_required"&&ge.current?.publishableKey&&Pl({sessionId:K,publishableKey:ge.current.publishableKey,paypalPublishableKey:ge.current.paypalPublishableKey}),re=await Ca(H,{flopay:Te.current,paypalFlopay:Jt.current,attempt3DS:B?.attempt3DS,billingApiUrl:F,sessionId:K,session:S,telemetry:!1}),H.type==="paypal_redirect_required"&&xi())}}K&&uo(K),Le(),x&&(W.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),W.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),W.terminal({outcome:re.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),ft(re.status==="authorized"),pt("success"),await jo(600),se=()=>Kt.current?.(re)}catch(V){let re=zo(V),H=re.checkoutMethod??Oo;Ke(re.message),Mt(re.message),ft(!1),B?.fallbackToFull&&(W.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Xn("full"),Cl("full")),Le();let Ct=re.statusCode===void 0?void 0:(0,je.telemetryStatusClass)(re.statusCode,"unknown"),Gt=Ct==="4xx"?{requestCategory:"process_payment",statusClass:Ct}:{},Ne=Ct===void 0||Ct==="4xx";if(Ne&&(re.telemetryOutcome==="payment_declined"||!!(re.declineCode||re.code?.toLowerCase().includes("declin"))))W.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Gt});else if(Ne&&(re.telemetryOutcome==="validation_rejected"||re.type==="validation_error"))W.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Gt});else{let Ee=(0,je.classifyTelemetryFailure)(V,x?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),me=re.telemetryRequestCategory??"process_payment";at.current=!0;try{W.error({...Ee,...re.telemetryFailureCategory?{failureCategory:re.telemetryFailureCategory}:{},stage:x?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:me})}finally{at.current=!1}St({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:me,provider:U})}return st(()=>ln.current?.(re)),Rn(H,re,{code:re.code,declineCode:re.declineCode}),pt("error"),await Promise.allSettled([jo(400),B?.ensureProvidersReady?B.ensureProvidersReady():Promise.resolve()]),x&&(W.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),W.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Le(),De&&Ko(De),pt(null),Mt(null)}return st(se),!0},[Rn,St,F,o,A]);(0,C.useEffect)(()=>{if(typeof window>"u"||xe.current)return;let S=new URLSearchParams(window.location.search),B=S.get("payment_intent_client_secret");if(!B)return;let K=Rd();K&&(xe.current=!0,(async()=>{let U,He=0;Ke(null),Mt(null),pt("processing"),Zt(!0);try{if(S.get("redirect_status")==="failed")throw Object.assign(new je.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:yt,paypalFlopay:De}=await mi({publishableKey:K.publishableKey,paypalPublishableKey:K.paypalPublishableKey,billingApiUrl:F,locale:l,telemetry:o});U=tn(De??yt),U?.setCheckoutContext(A),He=U?.now()??0,U?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),U?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let W=(De??yt)?.getRawProvider();if(!W)throw Object.assign(new je.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:Ce,error:x}=await W.retrievePaymentIntent(B);if(x)throw Object.assign(new je.FloPayError(x.message??"Failed to retrieve PayPal payment status.","api_error",{code:x.code}),{checkoutMethod:"paypal"});let h=Ss(Ce?.status);if(!Ce||h==="failed")throw Object.assign(new je.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let y=typeof Ce.payment_method=="string"?Ce.payment_method:Ce.payment_method?.id,m=h;if(K.sessionId){let se=(await new Ir.PaymentAPI(F,{telemetry:!1}).getUnifiedCheckoutSession(K.sessionId)).data.session;if(se&&se.status!=="complete"){let V=await mo({billingApiUrl:F,sessionId:K.sessionId,session:se,telemetry:!1,tokenizedData:{id:y??Ce.id,type:"card",threeDSecureActionResultTokenId:Ce.id,isPaypal:!0}});if(V.type!=="success")throw Object.assign(new je.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});m=V.result.status}}K.sessionId&&uo(K.sessionId),U?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),U?.performance({stage:"redirect_resume",durationMs:U.elapsed(He),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),U?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),pt("success"),await jo(600),st(()=>Kt.current?.({status:m,paymentIntentId:Ce.id,paymentMethodId:y,checkoutMethod:"paypal"}))}catch(yt){let De=zo(yt),W=De.checkoutMethod??"paypal",Ce=!!(De.declineCode||De.code?.toLowerCase().includes("declin"));if(U)U.performance({stage:"redirect_resume",durationMs:U.elapsed(He),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Ce?U.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):U.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(Ce){let x=xa(F,o,A);x.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ko(x)}else Ei(F,o,A,"REDIRECT_RESUME_FAILED","redirect_resume");Ke(De.message),Mt(De.message),st(()=>ln.current?.(De)),Rn(W,De,{code:De.code,declineCode:De.declineCode}),pt("error"),await jo(400)}finally{xi(),_d(),pt(null),Mt(null),Zt(!1)}})())},[Rn,l,F,o,A]);let Pn=(0,C.useRef)(null),Dn=(0,C.useMemo)(()=>Wt?co(Wt):"",[Wt]),er=(0,C.useRef)(Wt);er.current=Wt,(0,C.useEffect)(()=>{Xt(e??"")},[e]),(0,C.useEffect)(()=>{Dt.current=!1,Ke(rt),Mt(null),ft(!1),pt(null)},[Dn,rt,e]);async function gt(S,B,K){let U=xa(F,o,A),He=new Ir.PaymentAPI(F,{telemetry:!1}),yt=!1;try{let De=S.idempotencyKey===void 0?void 0:(0,je.resolveIdempotencyKey)(S.idempotencyKey),W=si(B,K),Ce=li(B,K);W?.canonicalIdentity===K&&Ce&&Ce.canonicalIdentity===void 0&&(ba(B,K,Ce.idempotencyKey),Ce={...Ce,canonicalIdentity:K});let x=De??(Ce?.canonicalIdentity===K?Ce.idempotencyKey:void 0),h,y=!1;U.log({name:W?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let m=W?.sid??null,X=null,Le,se,V=!1;if(m)try{X=await He.getUnifiedCheckoutSession(m,W?.nonce),W&&W.canonicalIdentity===void 0&&(Fs(X.data.session,S)?(ha(B,K,m,W.nonce??X.data.session?.clientSecret),Ce&&Ce.canonicalIdentity===void 0&&(ba(B,K,Ce.idempotencyKey),x??(x=Ce.idempotencyKey))):(ga(B,K),Ce=null,x=De,m=null,X=null));let H=X?.data.session?.status,Ct=X?.data.session,Gt=Ct?.clientSecret||W?.nonce;if(m&&Ct?.buyerIdentified===!1&&Gt&&(se=to(He,m,Gt,S.account)),m&&X&&H==="complete"){if(ci(m))return{sid:m,result:X};ga(B,K),m=null,X=null,y=!0}}catch{U.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),W?.canonicalIdentity===void 0?(ga(B,K),x=De):fa(B,K),m=null}if(!m){!De&&(y||!x)&&(x=(0,je.resolveIdempotencyKey)(),h=x),x&&ba(B,K,x);let H=U.now(),Ct=0;U.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Gt={...S,idempotencyKey:x,avsCheck:!!we,avsConfig:typeof we=="object"?we:void 0,checkoutType:"embedded_checkout",checkoutLayout:Mi(R,le)};Object.defineProperty(Gt,Ir.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ee=>{Ct=Math.max(Ct,ee)}}});let Ne=()=>{bl(U,"session_create",H,Ct)},Oe=ee=>{vl(U,ee,"session_create",H,Ct)&&St({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,je.isDetachedSessionEligible)(Gt)){let ee=await He.createDetachedSession(Gt);ee.claimed.catch(()=>{}),X=ee.shell,m=ee.sessionId,se=ee.claim;let Ee=U.now();U.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Le=ee.claimed.then(me=>{let Lt=me.data.session?.id??ee.sessionId;return Lt&&ha(B,K,Lt,me.data.session?.clientSecret??ee.nonce),bl(U,"session_claim",Ee),Ne(),me},me=>{throw fa(B,K),vl(U,me,"session_claim",Ee,0)&&St({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),me}).finally(()=>Ko(U)),Le.catch(()=>{}),yt=!0,U.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),U.performance({stage:"session_shell",durationMs:U.now()-H,durationMode:"machine",requestCategory:"session_create",attempt:Ct,statusClass:"2xx",paymentMethodCategory:"card"})}else X=await He.createAndFetchSession(Gt),Ne()}catch(ee){throw Oe(ee),ee}m=X.data.session?.id??m??"",m&&!Le&&ha(B,K,m,X.data.session?.clientSecret)}let re=X?.data.session;return!se&&m&&re?.buyerIdentified===!1&&re.clientSecret&&(se=to(He,m,re.clientSecret,S.account)),{sid:m??"",result:X,sdkGeneratedIdempotencyKey:h,...Le?{claimed:Le}:{},...se?{claim:se}:{},...V?{claimRequiresIdentity:!0}:{}}}finally{yt||Ko(U)}}let Un=(0,C.useRef)(gt);qr(()=>{Un.current=gt},[gt]);let Cn=(0,C.useCallback)(async(S,B)=>{let K=er.current;if(!K)throw new je.FloPayError("createSession is required to bootstrap checkout.","validation_error");let U=Qa(K,S),He=co(U),yt=Bs(U),De=Ma.get(He);if(!De){let x={canonicalIdentity:He,promise:Un.current(U,yt,He),consumers:0,settled:!1};De=x,Ma.set(He,x);let h=()=>{x.settled=!0,hl(He,x)};x.promise.then(h,h)}De.consumers+=1;let W=!1,Ce=()=>{W||(W=!0,De.consumers-=1,hl(He,De))};B?.(Ce);try{let x=await De.promise;Pn.current=He,S&&(Rt(Fn),pn(re=>vs(re,S)));let{sid:h,result:y,claimed:m,claim:X,claimRequiresIdentity:Le}=x;if(lr.current=X,vn(Le===!0),oe(y),y.data.session&&At(y.data.session),h&&Xt(h),m){Ut.current+=1;let re=Ut.current;Ft.current=m,ne(!0),m.then(H=>{Ut.current===re&&(Ft.current===m&&(Ft.current=null),oe(H),H.data.session&&At(H.data.session),ne(!1),vn(!1))},H=>{Ut.current===re&&(Ft.current===m&&(Ft.current=null),ne(!1),vn(!1),kn(H instanceof je.FloPayError?H:new je.FloPayError(H instanceof Error?H.message:"Failed to create session","api_error")))})}else Ut.current+=1,Ft.current=null,ne(!1),vn(!1);let{flopay:se,paypalFlopay:V}=await Ai(y,{billingApiUrl:F,locale:l,telemetry:o});return Pt(se,V),j(!1),x}catch(x){throw Pn.current===He&&(Pn.current=null),x}finally{B||Ce()}},[Fn,Pt,l,F,o]),qn=(0,C.useRef)(br);qn.current=br;let $n=(0,C.useRef)(Cn);$n.current=Cn;let Ge=(0,C.useCallback)(async S=>{if(!Td(S)||sn)return{sessionId:J,session:te};Mn(!0);try{let B=await Cn(S);return{sessionId:B.sid,session:B.result.data.session??null}}finally{Mn(!1)}},[Cn,sn,J,te]),nn=(0,C.useCallback)(async S=>{let B=lr.current;if(!B)return;let K=Ut.current,U=await B(S);Ut.current===K&&(oe(U),U.data.session&&At(U.data.session))},[]),Ht=(0,C.useCallback)(async()=>{await Ft.current},[]),Mr=(0,C.useCallback)(async()=>(await Ht(),{proceed:!0}),[Ht]);(0,C.useEffect)(()=>{let S=!1,B,K=++Ae.current;We(),kn(null),on(0);let U=()=>{S=!0,Ae.current===K&&(Ae.current+=1,We())},He=er.current;if(Dn&&He)return Xn(Qn),j(!1),Pn.current===Dn?U:(At(Ps(He,$)),(async()=>{let W=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ce=Qn==="auto"&&!Dt.current&&!W;Ce&&(Ke(null),Mt(null),pt("processing"));try{let x=await $n.current(void 0,X=>{B=X}),h=x.result.data.session??null;ge.current=pi(x.result);let y=Ti(x.result),m=ci(x.sid||h?.id);if(!S&&Ce&&h&&!y&&!m){Dt.current=!0,await wd(Dn,x.sdkGeneratedIdempotencyKey,()=>qn.current(h,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:x.result.autoProcessingError,initialAutoProcessingPending:x.result.autoProcessingPending,autoProcessingAttempted:x.result.autoProcessingAttempted,sessionId:x.sid||h.id}));return}!S&&Ce&&((y||m)&&(Dt.current=!0),pt(null),Mt(null))}catch(x){if(S)return;let h=aa(x);if(Ce&&h==="session_auto_completed"){Dt.current=!0,pt("success"),await jo(600),S||(st(()=>{Kt.current?.({status:"succeeded"})}),pt(null),Mt(null));return}Ce&&(pt(null),Mt(null));let y=x instanceof je.FloPayError?x:new je.FloPayError(x instanceof Error?x.message:"Failed to create session","api_error");kn(y)}finally{B?.(),B=void 0}})(),()=>{U(),B?.()});j(!0);async function yt(){let W=!1,Ce=null;try{let x=new Ir.PaymentAPI(F,{telemetry:!1}),h=await x.getUnifiedCheckoutSession(It,t);if(Ce=h,S)return;oe(h);let y=h.data.session??null;if(At(y),!y)throw new je.FloPayError("No session data returned","api_error");let m=y.checkoutMode;if(m==="setup")throw new je.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(y.status==="authorized"){j(!1),st(()=>{Kt.current?.(zr(y,It)),cr.current?.(y.successUrl??"")});return}if(y.status==="complete"){j(!1),st(()=>{cr.current?.(y.successUrl??"")});return}if(y.status==="expired")throw oa(y);W=!0;let X=$??m??"full";Xn(X),Ut.current+=1;let Le=y.clientSecret||t;lr.current=y.buyerIdentified===!1&&Le?to(x,It,Le,{...y.customer?.id?{userId:y.customer.id}:{}}):void 0,ne(!1),vn(!1);let se=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),V=Ti(h);if(X==="auto"&&!Dt.current&&!se&&!V){Dt.current=!0;let re=De(h);try{if(await qn.current(y,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>re,sessionId:It||y.id}),S)return;await re,S||j(!1);return}catch{if(S)return;await re,S||j(!1);return}}await De(h),S||j(!1)}catch(x){if(S)return;let h=bs(x,W);if(W&&St({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),h){let{errorCode:m,stage:X,...Le}=h;Ei(F,o,A,m,X,Le)}if(h?.stage==="provider_load"&&($??Ce?.data.session?.checkoutMode??"full")==="full"&&hs(Ce,N,pe)){let m=Id({billingApiUrl:F,locale:l,telemetry:o});Ze.current=m,Pt(m,null),on(1),j(!1);return}let y=x instanceof je.FloPayError&&h?.stage!=="provider_load"?x:gs();y!==x&&st(()=>ln.current?.(y)),kn(y),j(!1)}}async function De(W){let{flopay:Ce,paypalFlopay:x,...h}=await Ai(W,{billingApiUrl:F,locale:l,telemetry:o});ge.current={publishableKey:h.publishableKey,paypalPublishableKey:h.paypalPublishableKey},Pt(Ce,x),on(0)}return yt(),U},[$,Dn,Qn,fn,t,N,pe]);let _r=(0,C.useCallback)(async()=>{if(!z||dn!==1)return;let S=Ae.current;on(2);try{let{flopay:B,paypalFlopay:K}=await Ai(z,{billingApiUrl:F,locale:l,telemetry:o});if(Ae.current!==S)return;We(),Pt(B,K),on(0)}catch(B){if(Ae.current!==S)return;let{errorCode:K,stage:U,...He}=Za(B);Ei(F,o,A,K,U,He)}},[We,Pt,l,dn,F,o,A,z]),Er=(0,C.useCallback)(async()=>{if(!(un||!te)){Zt(!0),Ke(null);try{await br(te,{attempt3DS:!0,fallbackToFull:!0,sessionId:It||te.id})}finally{Zt(!1)}}},[It,un,br,te]),Vn=Bi(z),Ln=Ti(z),yn=(0,C.useMemo)(()=>{if(!(!z||!te||!z.data.stripe?.publishableKey))return{billingApiUrl:F}},[z,te,F]),Br=!!(n&&!R&&le==="buttons"&&ce&&Qn==="full"),Fr=!!(It&&te?.vault?.html),_n=(0,C.useMemo)(()=>({session:te,loading:sr,error:gn,checkoutMode:hn,inlineSessionDraft:Wt,applyInlineSessionPatch:Br?Ge:void 0,inlineSessionPatchProcessing:sn,claimPending:vt,claimRequiresIdentity:bn,claimBuyerIdentity:nn,waitForDataAttachment:Ht}),[te,sr,gn,hn,Wt,Br,Ge,sn,vt,bn,nn,Ht]),vr=!!n&&le==="buttons"&&!Ln&&!Fr&&(!qe||!yn),qt=an?(0,E.jsx)(Yn,{status:an,errorMessage:zn,authorized:Qt}):null;if(sr&&!Fr){if(d)return(0,E.jsxs)(E.Fragment,{children:[d,qt]});if(le==="buttons"){let S=Me?.buttonsLayout?.cardButton?.borderRadius??Me?.appearance.variables?.borderRadius??8,B=K=>(0,E.jsx)("div",{style:{height:K,borderRadius:S,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:[N&&B(go),pe&&(w||q)&&B(go),pe&&B(go),(0,E.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),qt]})}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); } }"})]}),qt]})}return gn?u?(0,E.jsx)(nr.Provider,{value:_n,children:u(gn)}):(0,E.jsx)(nr.Provider,{value:_n,children:(0,E.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:gn.message})}):vr?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(nr.Provider,{value:_n,children:(0,E.jsx)(xd,{onButtonClick:Ue,showPayPal:N,showStripe:pe,showApplePay:w,showGooglePay:q,theme:Se,buttonsTheme:ie,buttonsStyles:ye,cardButtonContent:he,cardBackButtonContent:dt,cardTitleContent:Je})}),qt]}):Ln&&te&&Vn?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(nr.Provider,{value:_n,children:(0,E.jsxs)("div",{className:nt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ze&&(0,E.jsx)(so,{icon:!1,children:ze}),Bn==="retrying"&&(0,E.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Bn==="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:Rr,children:"Retry PayPal"})]}),Bn!=="exhausted"&&(0,E.jsx)("div",{"aria-hidden":Bn==="retrying"?!0:void 0,style:Bn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,E.jsx)(Ms,{sessionId:It,nonce:te.clientSecret||void 0,billingApiUrl:F,email:te.customer?.email||Wt?.account?.email,billingName:[te.customer?.firstName,te.customer?.lastName].filter(Boolean).join(" ")||[Wt?.account?.firstName,Wt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:nn,clientId:Vn.clientId,environment:Vn.environment,currency:(te.currency??"usd").toUpperCase(),isSubscription:te.mode==="subscription",providerObjectType:Vn.providerObjectType,approvalPresentation:Vn.approvalPresentation,onComplete:b,onErrorChange:Ke,onDecline:v,onButtonClick:Ue,runBeforeButtonClick:Mr,onInitializationStateChange:jr,allowAutomaticRetry:Fe===0,session:te,telemetry:o,telemetryContext:A,onInstrument:xt,debug:O},`${D}:paypal-init-${Fe}`)})]})}),qt]}):(!qe||!yn)&&!(Fr&&hn==="full")?(0,E.jsx)(E.Fragment,{children:qt}):hn==="confirm"?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(nr.Provider,{value:_n,children:(0,E.jsx)(Lo,{flopay:qe,paypalFlopay:Pe,options:yn??{billingApiUrl:F},onInstrument:xt,children:(0,E.jsxs)("div",{className:nt,children:[ze&&(0,E.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:ze}),Q?Q({onConfirm:Er,isProcessing:un}):(0,E.jsx)("button",{type:"button",onClick:Er,disabled:un,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:un?"not-allowed":"pointer",opacity:un?.6:1},children:un?"Processing...":fe??"Confirm Purchase"})]})},D)}),qt]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(nr.Provider,{value:_n,children:(0,E.jsxs)(Lo,{flopay:qe,paypalFlopay:Pe,options:yn??{billingApiUrl:F},onInstrument:xt,children:[dn===1&&(0,E.jsx)("button",{type:"button",onClick:_r,children:"Retry payment methods"}),R?(0,E.jsxs)(E.Fragment,{children:[ze&&(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:ze}),(0,E.jsx)(Ad,{sessionId:It,nonce:te?.clientSecret||void 0,billingApiUrl:F,session:te,submitLabel:de,children:R})]}):(0,E.jsx)(Ta,{sessionId:It,nonce:te?.clientSecret||void 0,telemetry:o,email:te?.customer?.email||Wt?.account?.email,userId:te?.customer?.id||Wt?.account?.userId,firstName:te?.customer?.firstName||Wt?.account?.firstName,lastName:te?.customer?.lastName||Wt?.account?.lastName,totalAmount:te?Math.round((0,je.buildCheckoutDisplayData)(te).total*100):0,currency:te?.currency?.toLowerCase()??"usd",onComplete:b,onError:f,onDecline:v,error:ze,onErrorChange:Ke,showPayPal:N,showStripe:pe,enabledPaymentMethods:dn?[]:ae??z?.data.stripe?.enabledPaymentMethods??te?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:z?.data.stripe?.enabledPaymentMethodCountries,showApplePay:w,showGooglePay:q,layout:le,theme:Se,buttonsTheme:ie,buttonsStyles:ye,appearance:ut,cardButtonContent:he,cardBackButtonContent:dt,cardTitleContent:Je,onButtonClick:Ue,onBeforeButtonClick:ce,onBuyerIdentityReady:nn,enableAVS:we,...Xe?{cardFieldOrder:Xe}:{},...Z?{cardPreFormSlot:Z}:{},avsLayout:ke,country:te?.customer?.country,city:te?.customer?.city,state:te?.customer?.state,onCountryChange:I,onZipChange:M,avsCheck:!!we,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Mi(R,le),className:nt,submitLabel:de,directPaypal:Bi(z),isSubscription:te?.mode==="subscription",session:te,dataAttachmentPending:vt,dataAttachmentRequiresIdentity:bn,debug:O})]},D)}),qt]})}function Ad({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,children:a}){return(0,E.jsx)(E.Fragment,{children:C.default.Children.map(a,l=>{if(!C.default.isValidElement(l))return l;let d=l.props,u={};return d.sessionId||(u.sessionId=e),!d.nonce&&t&&(u.nonce=t),d.billingApiUrl||(u.billingApiUrl=n),d.submitLabel===void 0&&o!==void 0&&(u.submitLabel=o),r?.customer&&(d.email||(u.email=r.customer.email),d.userId||(u.userId=r.customer.id),d.firstName||(u.firstName=r.customer.firstName),d.lastName||(u.lastName=r.customer.lastName)),Object.keys(u).length===0?l:C.default.cloneElement(l,u)})})}function xd({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:d,cardButtonContent:u,cardBackButtonContent:b,cardTitleContent:f}){let[P,v]=(0,C.useState)(!1),I=(0,C.useMemo)(()=>(0,je.resolveTheme)(a),[a]),M=(0,C.useMemo)(()=>{let w=I?.buttonsLayout??(0,je.resolveButtonsLayoutTheme)(l);return d?{...w,...d,cardButton:{...w.cardButton,...d.cardButton},cardFormContainer:{...w.cardFormContainer,...d.cardFormContainer},backButton:{...w.backButton,...d.backButton},backButtonIcon:{...w.backButtonIcon,...d.backButtonIcon},submitButton:{...w.submitButton,...d.submitButton},title:{...w.title,...d.title}}:w},[I,l,d]),N=I?.buttonsLayout?.cardButton?.borderRadius??I?.appearance.variables?.borderRadius??8,pe=w=>(0,E.jsx)("div",{style:{height:w,borderRadius:N,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),ae=u===void 0?{boxSizing:"border-box",height:go,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(P){let w=M.cardInputBorder??"#e5e7eb",q=M.cardInputBackground??"white",O=Zr(b),le=Zr(f);return(0,E.jsxs)("div",{style:{backgroundColor:M.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...M.cardFormContainer},children:[(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:O?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...M.backButton},children:[(0,E.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...M.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)(eo,{content:b})]}),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,...M.title},children:(0,E.jsx)(Eo,{content:f})})]}),(0,E.jsx)("div",{style:{backgroundColor:q,border:`1px solid ${w}`,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:q,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,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:q,borderTop:"none",borderRight:`1px solid ${w}`,borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,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:q,border:`1px solid ${w}`,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",...M.submitButton,opacity:.5}}),(0,E.jsx)("style",{children:`
|
|
38
|
+
`}),ko&&Mr&&(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:Nn,style:{display:"inline-flex",alignItems:"center",gap:Ya?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:C.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...C.backButton},"aria-label":"Back to payment methods",children:[(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",...C.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)(to,{content:le})]}),cs?(0,c.jsx)("div",{style:{flex:1}}):(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:C.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...C.title},children:(0,c.jsx)(To,{content:Se})})]}),!ko&&!cs&&(0,c.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ja,order:We?-3:0,...C.title},children:(0,c.jsx)(To,{content:Se})}),We&&_&&(0,c.jsx)("div",{style:{order:-2,width:"100%"},children:_}),We&&W&&(0,c.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,c.jsx)("div",{style:{backgroundColor:Jr,border:`1px solid ${Kn(ea)}`,borderRadius:$t,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=>{Ct("email"),Bn.current=i.target.value,$n(i.target.value)},onPointerDown:()=>Ct("email"),onKeyDown:()=>Ct("email"),onBlur:()=>{Pn("email")&&In(!0),Fe||za()},disabled:N,required:!0,"aria-invalid":ea||void 0,"aria-describedby":ea?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Xa}})}),ea&&(0,c.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Ro,children:ze.empty?"Email address is required":"Enter a valid email address"})]}),te&&(0,c.jsx)("div",{style:{order:We?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=j,I=(Y=!1)=>({backgroundColor:Jr,border:`1px solid ${Kn(Y)}`,borderRadius:$t,marginTop:"0.5rem",padding:"10px"}),H=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Xa}),Ve=(0,p.getStateOptions)(i);return(0,c.jsxs)(c.Fragment,{children:[(0,p.isAVSFieldVisible)(te.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:rn,onChange:Y=>{Ct("line1"),Pt.current.addressLine1=!0,un.current=Y.target.value,fn(Y.target.value)},onPointerDown:()=>Ct("line1"),onKeyDown:()=>Ct("line1"),onBlur:()=>jn("line1"),disabled:N,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:H()})}),Ot("line1")&&(0,c.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Ro,children:"Street address is required"})]}),(0,p.isAVSFieldVisible)(te.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:Zn,onChange:Y=>{Pt.current.addressLine2=!0,Dt.current=Y.target.value,dn(Y.target.value)},disabled:N,"data-testid":"flopay-address-line2",style:H()})}),((0,p.isAVSFieldVisible)(te.city,i)||(0,p.isAVSFieldVisible)(te.state,i))&&(0,c.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,p.isAVSFieldVisible)(te.city,i)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Jr,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:$t,borderBottomLeftRadius:$t,...(0,p.isAVSFieldVisible)(te.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:$t}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Yt,onChange:Y=>{Ct("city"),Pt.current.city=!0,_t.current=Y.target.value,Ne(Y.target.value)},onPointerDown:()=>Ct("city"),onKeyDown:()=>Ct("city"),onBlur:()=>jn("city"),disabled:N,required:!0,"aria-invalid":Ot("city")||void 0,"aria-describedby":Ot("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:H()})}),(0,p.isAVSFieldVisible)(te.state,i)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Jr,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:$t,borderBottomRightRadius:$t,...(0,p.isAVSFieldVisible)(te.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Kn(Ot("state")||Ot("city"))}`}:{borderRadius:$t}},children:Ve?(0,c.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Ke,onChange:Y=>{Ct("state"),Pt.current.state=!0,an.current=Y.target.value,on(Y.target.value)},onPointerDown:()=>Ct("state"),onKeyDown:()=>Ct("state"),onBlur:()=>jn("state"),disabled:N,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:{...H(),cursor:"pointer"},children:[(0,c.jsx)("option",{value:"",children:(0,p.getStateLabel)(i)}),Ve.map(Y=>(0,c.jsx)("option",{value:Y.code,children:Y.name},Y.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:Ke,onChange:Y=>{Ct("state"),Pt.current.state=!0,an.current=Y.target.value,on(Y.target.value)},onPointerDown:()=>Ct("state"),onKeyDown:()=>Ct("state"),onBlur:()=>jn("state"),disabled:N,required:!0,"aria-invalid":Ot("state")||void 0,"aria-describedby":Ot("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:H()})})]}),Ot("city")&&(0,c.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Ro,children:"City is required"}),Ot("state")&&(0,c.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Ro,children:[(0,p.getStateLabel)(i)," is required"]}),((0,p.isAVSFieldVisible)(te.country,i)||(0,p.isAVSFieldVisible)(te.postal_code,i))&&(0,c.jsxs)("div",{style:{display:"flex",flexDirection:$==="column"?"column":"row",gap:$==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,p.isAVSFieldVisible)(te.country,i)&&(0,c.jsx)("div",{style:{flex:$==="row"?1:void 0,backgroundColor:Jr,borderTop:`1px solid ${Io}`,borderRight:`1px solid ${Io}`,borderBottom:`1px solid ${Io}`,borderLeft:`1px solid ${Io}`,padding:"10px",...$==="row"&&(0,p.isAVSFieldVisible)(te.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:$t,borderBottomLeftRadius:$t,borderRight:"none"}:{borderRadius:$t}},children:(0,c.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:j,onChange:Y=>{Pt.current.country=!0,jt.current=Y.target.value,yn(Y.target.value),et?.(Y.target.value),an.current="",on("")},disabled:N,autoComplete:"billing country","data-testid":"flopay-country",style:{...H(),cursor:"pointer"},children:p.COUNTRY_OPTIONS.map(Y=>(0,c.jsxs)("option",{value:Y.code,children:[Y.flag," ",Y.name]},Y.code))})}),(0,p.isAVSFieldVisible)(te.postal_code,i)&&(0,c.jsx)("div",{style:{flex:$==="row"?1:void 0,backgroundColor:Jr,border:`1px solid ${Kl}`,padding:"10px",...$==="row"&&(0,p.isAVSFieldVisible)(te.country,i)?{borderRadius:"0",borderTopRightRadius:$t,borderBottomRightRadius:$t}:{borderRadius:$t}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,p.getPostalCodeLabel)(j),autoComplete:"billing postal-code",value:wn,onChange:Y=>{Ct("zip"),Pt.current.zip=!0,ht.current=Y.target.value,cn(Y.target.value),he?.(Y.target.value)},onPointerDown:()=>Ct("zip"),onKeyDown:()=>Ct("zip"),onBlur:()=>{Pn("zip")&&er(!0)},disabled:N,required:vn.required,"aria-invalid":ta||void 0,"aria-describedby":ta?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:H()})})]}),ta&&(0,c.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Ro,children:vn.empty?`${(0,p.getPostalCodeLabel)(i)} is required`:Pd(i)})]})})()}),We&&Jl,m&&(0,c.jsx)(lo,{margin:"0.75rem 0",styleOverride:C.errorBanner,children:m})]}),na={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"},ys=i=>Mt?!k||!hr?(0,c.jsx)("pre",{"data-testid":i,style:na,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":i,style:na,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${k}`,` directPaypalConfigured=${hr}`,` inAppBrowserDetected=${String(Xo)}`,` shouldRenderDirectPayPal=${Po}`,` shouldRenderStripePayPal=${Co}`,` hasPaypalStripeInstance=${!!He}`].join(`
|
|
39
|
+
`)}):null,fs=i=>Mt?!q||!gt?(0,c.jsx)("pre",{"data-testid":i,style:na,children:"FloPay/Stripe-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":i,style:na,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${q}`,` currency=${xe}`,` amountInCents=${On}`,` enabledPaymentMethods: ${JSON.stringify(z??[])}`,` enabledPaymentMethodsProvided=${bo}`,` hasEnabledMethods=${Go}`,` expressMethods: ${JSON.stringify(Yo)}`,` walletExpressMethods: ${JSON.stringify(Gr)}`,` paymentElementMethods: ${JSON.stringify(vo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Jo)}`,` hasStripeInstance=${!!gt}`,` shouldRenderWallets=${Yr}`,` shouldRenderPaymentElement=${So}`].join(`
|
|
40
|
+
`)}):null,gs=Xe==="apm-expanding"||Xe==="apm-form"||Xe==="apm-collapsing",Zr;Xe==="apm-expanding"?Zr=al:Xe==="apm-collapsing"&&(Zr=il);let ra=pn?vl($a,pn):null;if(me==="buttons"){let i=Xe==="buttons"||Xe==="expanding"||Xe==="apm-expanding",I=Xe==="expanding"||Xe==="card"||Xe==="collapsing",H=Ue===void 0?{boxSizing:"border-box",height:_a,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ve;Xe==="expanding"||Xe==="apm-expanding"?Ve=yd:(Xe==="collapsing"||Xe==="apm-collapsing")&&(Ve=md);let Y;return Xe==="expanding"?Y=al:Xe==="collapsing"&&(Y=il),(0,c.jsxs)("form",{onSubmit:Wa,className:R,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(ki,{}),M&&(0,c.jsx)(Jn,{status:M,errorMessage:m,authorized:hn}),(0,c.jsxs)("div",{style:{display:"grid"},children:[(0,c.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Ve?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Ve?gd:{},...Ve?{animation:Ve,pointerEvents:"none"}:{}},children:[ys("flopay-direct-paypal-gate-debug"),fs("flopay-stripe-gate-debug"),Po&&Me&&(0,c.jsxs)(c.Fragment,{children:[tt&&(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)(Do,{sessionId:e,nonce:t,billingApiUrl:J,email:re.email,billingName:Et||void 0,onBuyerIdentityReady:g,clientId:Me.clientId,environment:Me.environment,currency:xe.toUpperCase(),isSubscription:be,providerObjectType:$e,approvalPresentation:Zo==="popup"?void 0:Zo,onTokenizedBody:An,onComplete:l,onErrorChange:Ie,onDecline:u,onTechnicalFailure:Hr,onButtonClick:X,runBeforeButtonClick:ar,isProcessing:N,onLoadStateChange:Va,onInitializationStateChange:ja,session:A,existingOrderId:tt?.orderId,debug:Mt},tt?.orderId??"fresh")]}),Co&&(0,c.jsx)(Vt.Elements,{stripe:He,options:qi,children:(0,c.jsx)(dl,{sessionId:e,nonce:t,email:re.email,billingName:Et||void 0,onBuyerIdentityReady:g,billingApiUrl:J,onTokenizedBody:An,onErrorChange:Ie,isProcessing:N,onButtonClick:X,onDecline:u,onTechnicalFailure:Hr,runBeforeButtonClick:ar,onLoadStateChange:Hi,placeholderBorderRadius:Dr})}),Yr?(0,c.jsx)(Vt.Elements,{stripe:gt,options:Ui,children:(0,c.jsx)(ul,{sessionId:e,nonce:t,email:re.email,billingName:Et||void 0,onBuyerIdentityReady:g,billingApiUrl:J,intentKind:ct>0?"payment":"setup",expressMethods:Gr,onTokenizedBody:An,onErrorChange:Ie,onButtonClick:X,onDecline:u,onTechnicalFailure:Hr,runBeforeButtonClick:ar,onLoadStateChange:Yi,placeholderBorderRadius:Dr})}):null,!Yr&&es?(0,c.jsx)("div",{style:{height:_a,borderRadius:Dr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,So&&(0,c.jsx)(pl,{sessionId:e,nonce:t,email:re.email,billingName:[re.firstName,re.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:g,billingApiUrl:J,paymentElementMethods:Jo,stripeInstance:gt,paymentElementBaseOptions:$a,onTokenizedBody:An,onErrorChange:Ie,onButtonClick:X,onDecline:u,runBeforeButtonClick:ar,onLoadStateChange:Xi,isProcessing:N,submitButtonColor:Lr,submitButtonBorderRadius:$t,submitButtonStyle:C.submitButton,onExpandApm:Fr,expandedApmMethod:pn,themeId:fe,buttonAppearance:{backgroundColor:C.cardButton?.backgroundColor,borderColor:C.cardInputBorder,textColor:C.cardButton?.color,borderRadius:Dr}}),We&&(0,c.jsx)("button",{type:"button",onClick:async()=>{N||!(await ar("card")).proceed||(X?.("card"),Br())},disabled:N,style:{width:"100%",...H,...C.cardButton,...Ai({themeBundle:w,resolvedPrimaryColor:Lr,resolvedBorderRadius:$t,submitButtonStyle:C.submitButton,explicitPrimaryColor:xn?.colorPrimary}),fontSize:C.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:N?"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:N?.6:1},onMouseEnter:dt=>{!N&&(w||xn?.colorPrimary)&&(dt.currentTarget.style.backgroundColor=Gl)},onMouseLeave:dt=>{(w||xn?.colorPrimary)&&(dt.currentTarget.style.backgroundColor=Lr)},onMouseDown:dt=>{dt.currentTarget.style.transform="scale(0.985)"},onMouseUp:dt=>{dt.currentTarget.style.transform="scale(1)"},children:(0,c.jsx)(eo,{content:Ue})}),m&&Xe==="buttons"&&(0,c.jsx)(lo,{margin:"0.25rem 0",styleOverride:C.errorBanner,children:m})]}),We&&I&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...Y?{animation:Y}:{},...Xe==="collapsing"?{pointerEvents:"none"}:{}},children:ms}),q&&gs&&pn&&ra&>&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...Zr?{animation:Zr}:{},...Xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Ga,borderRadius:Qa,..._o,padding:Za},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:Zt,style:{display:"inline-flex",alignItems:"center",gap:Ya?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:C.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...C.backButton},"aria-label":"Back to payment methods",children:[(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",...C.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)(to,{content:le})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:C.titleFontSize??"1.05rem",color:Ja,paddingRight:80,...C.title},children:`Pay with ${(0,p.getStripeMethodDisplayName)(pn)}`})]}),(0,c.jsx)(Vt.Elements,{stripe:gt,options:ra,children:(0,c.jsx)(_i,{method:pn,sessionId:e,nonce:t,email:re.email,billingName:[re.firstName,re.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:g,billingApiUrl:J,onTokenizedBody:An,onErrorChange:Ie,onDecline:u,onCancel:Zt,runBeforeButtonClick:ar,onButtonClick:X,isProcessing:N,submitButtonColor:Lr,submitButtonBorderRadius:$t,submitButtonStyle:C.submitButton,errorText:m})},pn)]})})]})]})}return gs&&pn&&ra&>&&q?(0,c.jsxs)("form",{onSubmit:Wa,className:R,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(ki,{}),M&&(0,c.jsx)(Jn,{status:M,errorMessage:m,authorized:hn}),(0,c.jsx)("div",{style:{...Zr?{animation:Zr}:{},...Xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Ga,borderRadius:Qa,..._o,padding:Za},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:Zt,style:{display:"inline-flex",alignItems:"center",gap:Ya?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:C.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...C.backButton},"aria-label":"Back to payment methods",children:[(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",...C.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)(to,{content:le})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:C.titleFontSize??"1.05rem",color:Ja,paddingRight:80,...C.title},children:`Pay with ${(0,p.getStripeMethodDisplayName)(pn)}`})]}),(0,c.jsx)(Vt.Elements,{stripe:gt,options:ra,children:(0,c.jsx)(_i,{method:pn,sessionId:e,nonce:t,email:re.email,billingName:[re.firstName,re.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:g,billingApiUrl:J,onTokenizedBody:An,onErrorChange:Ie,onDecline:u,onCancel:Zt,runBeforeButtonClick:ar,onButtonClick:X,isProcessing:N,submitButtonColor:Lr,submitButtonBorderRadius:$t,submitButtonStyle:C.submitButton,errorText:m})},pn)]})})]}):(0,c.jsxs)("form",{onSubmit:Wa,className:R,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(ki,{}),M&&(0,c.jsx)(Jn,{status:M,errorMessage:m,authorized:hn}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ys("flopay-direct-paypal-gate-debug-default"),fs("flopay-stripe-gate-debug-default"),Po&&Me&&(0,c.jsxs)(c.Fragment,{children:[tt&&(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)(Do,{sessionId:e,nonce:t,billingApiUrl:J,email:re.email,billingName:Et||void 0,onBuyerIdentityReady:g,clientId:Me.clientId,environment:Me.environment,currency:xe.toUpperCase(),isSubscription:be,providerObjectType:$e,approvalPresentation:Zo==="popup"?void 0:Zo,onTokenizedBody:An,onComplete:l,onErrorChange:Ie,onDecline:u,onTechnicalFailure:Hr,onButtonClick:X,runBeforeButtonClick:ar,isProcessing:N,onLoadStateChange:Va,onInitializationStateChange:ja,session:A,existingOrderId:tt?.orderId,debug:Mt},tt?.orderId??"fresh")]}),Co&&(0,c.jsx)(Vt.Elements,{stripe:He,options:qi,children:(0,c.jsx)(dl,{sessionId:e,nonce:t,email:re.email,billingName:Et||void 0,onBuyerIdentityReady:g,billingApiUrl:J,onTokenizedBody:An,onErrorChange:Ie,isProcessing:N,onButtonClick:X,onDecline:u,onTechnicalFailure:Hr,runBeforeButtonClick:ar,onLoadStateChange:Hi,placeholderBorderRadius:Dr})}),Yr&&(0,c.jsx)(Vt.Elements,{stripe:gt,options:Ui,children:(0,c.jsx)(ul,{sessionId:e,nonce:t,email:re.email,billingName:Et||void 0,onBuyerIdentityReady:g,billingApiUrl:J,intentKind:ct>0?"payment":"setup",expressMethods:Gr,onTokenizedBody:An,onErrorChange:Ie,onButtonClick:X,onDecline:u,onTechnicalFailure:Hr,runBeforeButtonClick:ar,onLoadStateChange:Yi,placeholderBorderRadius:Dr})}),So&&(0,c.jsx)(pl,{sessionId:e,nonce:t,email:re.email,billingName:[re.firstName,re.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:J,paymentElementMethods:Jo,stripeInstance:gt,paymentElementBaseOptions:$a,onTokenizedBody:An,onErrorChange:Ie,onButtonClick:X,onDecline:u,runBeforeButtonClick:ar,onLoadStateChange:Xi,isProcessing:N,submitButtonColor:Lr,submitButtonBorderRadius:$t,submitButtonStyle:C.submitButton,themeId:fe,onExpandApm:Fr,expandedApmMethod:pn,buttonAppearance:{backgroundColor:C.cardButton?.backgroundColor,borderColor:C.cardInputBorder,textColor:C.cardButton?.color,borderRadius:Dr}})]}),We&&(ql||Ul||$l)&&(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&&ms]})}var T=require("react/jsx-runtime"),ho=44,Ni="flopay_checkout_saved_payment_resume",Ba=new Map,xa=new Map;function Pl(e,t){t.settled&&t.consumers===0&&Ba.get(e)===t&&Ba.delete(e)}function Rd(e,t,n){let r=xa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};xa.set(e,a);let l=()=>{xa.get(e)===a&&xa.delete(e)};return o.then(l,l),o}function Ko(e){return new Promise(t=>setTimeout(t,e))}function Ma(e,t,n){let r=pa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:je.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Wo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function xi(e,t,n,r,o,a){let l=Ma(e,t,n);l.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),Wo(l)}function Cl(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 Sl(e,t,n,r,o){let a=(0,je.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 je.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof je.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 Li(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 Mi(e){return!e||e.data.stripe?.publishableKey?!1:!!Li(e)?.clientId}var _d={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Ed(e){return new _r.FloPay(_d,{publishableKey:"provider_unavailable",...e})}async function Bi(e,t){let{publishableKey:n,paypalPublishableKey:r}=fi(e);return{...await gi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Oi(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Td(){if(!Oi())return null;try{let e=window.sessionStorage.getItem(Ni);return e?JSON.parse(e):null}catch{return null}}function wl(e){if(Oi())try{window.sessionStorage.setItem(Ni,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Fi(){if(Oi())try{window.sessionStorage.removeItem(Ni)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Ad(){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 kl(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 Di(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function xd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Il(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Md(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 Fa({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:d,error:u,onComplete:h,onError:y,onInstrument:v,onDecline:b,onCountryChange:R,onZipChange:B,showPayPal:O=!0,showStripe:ue=!0,enabledPaymentMethods:oe,showApplePay:k=!0,showGooglePay:q=!0,debug:z=!1,layout:se,theme:Ce,buttonsTheme:ae,buttonsStyles:me,cardButtonContent:fe,cardBackButtonContent:pt,cardTitleContent:Ge,showSecurityFooter:ge,onButtonClick:Ue,onBeforeButtonClick:le,enableAVS:Se,cardFieldOrder:Ye,cardPreFormSlot:X,avsLayout:we,submitLabel:ce,className:rt,initialErrorMessage:ot=null,children:_,checkoutMode:$,confirmLabel:ye,renderConfirmButton:Z,onSessionCompleted:ke}){let F=(0,je.resolveBillingApiUrl)(r),De=(0,S.useMemo)(()=>(0,je.resolveTheme)(Ce),[Ce]),mt=a??De?.appearance,et=n?"embedded_checkout":"standard_checkout",he=Di(_,se),[U,ne]=(0,S.useState)(null),[qe,ct]=(0,S.useState)(null),xe=(0,S.useRef)(null),Je=(0,S.useRef)(null),Me=(0,S.useRef)(0),[be,_e]=(0,S.useState)(null),Ht=(0,S.useRef)(null),[Q,Mt]=(0,S.useState)(null),ft=(0,S.useMemo)(()=>n?uo(n):"",[n]),D=n?`create:${ft}`:`session:${e??""}`,de=Il(Q),f=(0,S.useRef)(new Set),A=(0,S.useRef)(D),$e=(0,S.useRef)(D);$r(()=>{$e.current=D,A.current!==D&&(A.current=D,f.current.clear())},[D]);let Re=(0,S.useCallback)(M=>{if($e.current===D){if(ii.has(M.name)){if(f.current.has(M.name))return;f.current.add(M.name)}lt(()=>v?.(M))}},[D,v]),kt=so(Re,D),st=(0,S.useRef)(!1),Bt=(0,S.useCallback)(M=>{if(st.current)return;let P=M.gateway||!de?M:{...M,gateway:de};Re(P)},[Re,de]);(0,S.useEffect)(()=>{kt({class:"lifecycle",name:"checkout.mount"})},[kt]);let[J,Gt]=(0,S.useState)(e??""),Rt=e??J,mn=n?"":Rt,[ur,j]=(0,S.useState)(!0),[yn,wn]=(0,S.useState)(null),[cn,rn]=(0,S.useState)(0),[fn,Zn]=(0,S.useState)("full"),[dn,Yt]=(0,S.useState)(!1),[Ne,Ke]=(0,S.useState)(ot),[on,yt]=(0,S.useState)(null),[$n,Ft]=(0,S.useState)(null),[Jt,ht]=(0,S.useState)(!1),[jt,un]=(0,S.useState)(void 0),[Dt,_t]=(0,S.useState)(""),[an,Bn]=(0,S.useState)(!1),[Pt,te]=(0,S.useState)(!1),[gn,hn]=(0,S.useState)(!1),Lt=(0,S.useRef)(null),Ut=(0,S.useRef)(0),Fn=(0,S.useRef)(void 0),[Vn,Qn]=(0,S.useState)("loading"),[Xt,We]=(0,S.useState)(0),qt=(0,S.useRef)(!1),Ee=(0,S.useRef)(!1),L=(0,S.useRef)(!1),Te=(0,S.useRef)(null),x=(0,S.useMemo)(()=>({checkoutMode:$??fn,layout:xd(_,se)}),[$,_,fn,se]),Nt=(0,S.useRef)(h);Nt.current=h;let bn=(0,S.useRef)(y);bn.current=y;let sn=(0,S.useRef)(b);sn.current=b;let Dn=(0,S.useCallback)((M,P)=>{xe.current=M,ct(M),Ht.current=P,_e(P)},[]),ve=(0,S.useCallback)(()=>{let M=Je.current;M&&(Je.current=null,M.destroy())},[]);(0,S.useEffect)(()=>{en(qe)?.setCheckoutContext(x),be&&be!==qe&&en(be)?.setCheckoutContext(x)},[qe,be,x]);let vn=(0,S.useRef)(ke);vn.current=ke;let xr=(0,S.useCallback)(M=>{Qn(M),!(M!=="exhausted"||L.current)&&(L.current=!0,bn.current?.(new je.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Kr=(0,S.useCallback)(()=>{Qn("retrying"),We(M=>M+1)},[]);(0,S.useEffect)(()=>{Qn("loading"),We(0),L.current=!1},[Rt]),(0,S.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:je.SDK_VERSION,checkout_type:et,checkout_layout:he,billing_api_url:F})},[he,et,F]);let kn=(0,S.useMemo)(()=>n?uo(n,!0):"",[n]),Er=(0,S.useMemo)(()=>Dt===kn?jt:void 0,[jt,Dt,kn]),pr=(0,S.useMemo)(()=>n?ni(n,Er):void 0,[n,Er]),er=$??pr?.checkoutMode??"full",Kt=(0,S.useMemo)(()=>pr?{...pr,checkoutMode:er}:void 0,[pr,er]);(0,S.useEffect)(()=>{un(void 0),_t(kn),Fn.current=void 0,Lt.current=null,hn(!1)},[kn]),(0,S.useEffect)(()=>{Ke(ot)},[ot]);let In=(0,S.useCallback)((M,P,ee)=>{lt(()=>{sn.current?.(nn(M,P,ee))})},[]),Cr=(0,S.useCallback)(async(M,P)=>{Ke(null),Ft(null),ht(!1),yt("processing");let ee=P?.sessionId??M.id,K=Il(M),Be=xe.current??Ht.current,tt=en(Be),Le=Be?null:Ma(F,o,x),G={log:Ae=>{tt?tt.log(Ae):Le?.log(Ae)},error:Ae=>{tt?tt.error(Ae):Le?.error(Ae)},terminal:Ae=>{tt?tt.terminal(Ae):Le?.terminal(Ae)},performance:Ae=>{tt?tt.performance(Ae):Le?.performance(Ae)},now:()=>tt?.now()??Le?.now()??0,elapsed:Ae=>tt?.elapsed(Ae)??Math.max(0,(Le?.now()??Ae)-Ae)},pe=G.now(),V=!!(P?.initialAutoProcessingError||P?.initialAutoProcessingPending),g=!1,m,w=()=>{g||(g=!0,V=!0,m=G.now(),G.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),G.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},C=!1,Pe=()=>{C||(C=!0,G.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),G.performance({stage:"processing",durationMs:G.elapsed(pe),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),m!==void 0&&G.performance({stage:"recovery",durationMs:G.elapsed(m),durationMode:"machine",paymentMethodCategory:"saved"}))};G.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),st.current=!0;try{G.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{st.current=!1}kt({class:"lifecycle",name:"payment.processing.started",provider:K}),V&&w();let ie;try{let Ae=qs(P?.initialAutoProcessingError),N;if(Ae)w(),Ae.type==="paypal_redirect_required"&&Te.current?.publishableKey&&wl({sessionId:ee,publishableKey:Te.current.publishableKey,paypalPublishableKey:Te.current.paypalPublishableKey}),N=await Sa(Ae,{flopay:xe.current,paypalFlopay:Ht.current,attempt3DS:P?.attempt3DS,billingApiUrl:F,sessionId:ee,session:M,telemetry:!1}),Ae.type==="paypal_redirect_required"&&Fi();else if(P?.initialAutoProcessingPending){let Et=(await new _r.PaymentAPI(F,{telemetry:!1}).waitForCheckoutSessionCompletion(P.initialAutoProcessingPending.sessionId,{initialDelayMs:P.initialAutoProcessingPending.retryAfterMs})).data.session;if(!ro(Et))throw sa(Et);N=Ur(Et,ee)}else{if(P?.initialAutoProcessingError)throw Ar(P.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:P.initialAutoProcessingError.checkoutMethod});if(P?.fromCreateSession)return P?.fallbackToFull&&(Zn("full"),kl("full")),!1;{let at=await yo({billingApiUrl:F,sessionId:ee,session:M,telemetry:!1});at.type==="success"?N=at.result:(w(),at.type==="paypal_redirect_required"&&Te.current?.publishableKey&&wl({sessionId:ee,publishableKey:Te.current.publishableKey,paypalPublishableKey:Te.current.paypalPublishableKey}),N=await Sa(at,{flopay:xe.current,paypalFlopay:Ht.current,attempt3DS:P?.attempt3DS,billingApiUrl:F,sessionId:ee,session:M,telemetry:!1}),at.type==="paypal_redirect_required"&&Fi())}}ee&&po(ee),Pe(),V&&(G.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),G.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),G.terminal({outcome:N.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),ht(N.status==="authorized"),yt("success"),await Ko(600),ie=()=>Nt.current?.(N)}catch(Ae){let N=Uo(Ae),at=N.checkoutMethod??zo;Ke(N.message),Ft(N.message),ht(!1),P?.fallbackToFull&&(G.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Zn("full"),kl("full")),Pe();let re=N.statusCode===void 0?void 0:(0,je.telemetryStatusClass)(N.statusCode,"unknown"),Et=re==="4xx"?{requestCategory:"process_payment",statusClass:re}:{},Oe=re===void 0||re==="4xx";if(Oe&&(N.telemetryOutcome==="payment_declined"||!!(N.declineCode||N.code?.toLowerCase().includes("declin"))))G.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Et});else if(Oe&&(N.telemetryOutcome==="validation_rejected"||N.type==="validation_error"))G.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Et});else{let ze=(0,je.classifyTelemetryFailure)(Ae,V?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Fe=N.telemetryRequestCategory??"process_payment";st.current=!0;try{G.error({...ze,...N.telemetryFailureCategory?{failureCategory:N.telemetryFailureCategory}:{},stage:V?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Fe})}finally{st.current=!1}kt({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Fe,provider:K})}return lt(()=>bn.current?.(N)),In(at,N,{code:N.code,declineCode:N.declineCode}),yt("error"),await Promise.allSettled([Ko(400),P?.ensureProvidersReady?P.ensureProvidersReady():Promise.resolve()]),V&&(G.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),G.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Pe(),Le&&Wo(Le),yt(null),Ft(null)}return lt(ie),!0},[In,kt,F,o,x]);(0,S.useEffect)(()=>{if(typeof window>"u"||Ee.current)return;let M=new URLSearchParams(window.location.search),P=M.get("payment_intent_client_secret");if(!P)return;let ee=Td();ee&&(Ee.current=!0,(async()=>{let K,Be=0;Ke(null),Ft(null),yt("processing"),Yt(!0);try{if(M.get("redirect_status")==="failed")throw Object.assign(new je.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:tt,paypalFlopay:Le}=await gi({publishableKey:ee.publishableKey,paypalPublishableKey:ee.paypalPublishableKey,billingApiUrl:F,locale:l,telemetry:o});K=en(Le??tt),K?.setCheckoutContext(x),Be=K?.now()??0,K?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),K?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let G=(Le??tt)?.getRawProvider();if(!G)throw Object.assign(new je.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:pe,error:V}=await G.retrievePaymentIntent(P);if(V)throw Object.assign(new je.FloPayError(V.message??"Failed to retrieve PayPal payment status.","api_error",{code:V.code}),{checkoutMethod:"paypal"});let g=Is(pe?.status);if(!pe||g==="failed")throw Object.assign(new je.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let m=typeof pe.payment_method=="string"?pe.payment_method:pe.payment_method?.id,w=g;if(ee.sessionId){let ie=(await new _r.PaymentAPI(F,{telemetry:!1}).getUnifiedCheckoutSession(ee.sessionId)).data.session;if(ie&&ie.status!=="complete"){let Ae=await yo({billingApiUrl:F,sessionId:ee.sessionId,session:ie,telemetry:!1,tokenizedData:{id:m??pe.id,type:"card",threeDSecureActionResultTokenId:pe.id,isPaypal:!0}});if(Ae.type!=="success")throw Object.assign(new je.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});w=Ae.result.status}}ee.sessionId&&po(ee.sessionId),K?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),K?.performance({stage:"redirect_resume",durationMs:K.elapsed(Be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),K?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),yt("success"),await Ko(600),lt(()=>Nt.current?.({status:w,paymentIntentId:pe.id,paymentMethodId:m,checkoutMethod:"paypal"}))}catch(tt){let Le=Uo(tt),G=Le.checkoutMethod??"paypal",pe=!!(Le.declineCode||Le.code?.toLowerCase().includes("declin"));if(K)K.performance({stage:"redirect_resume",durationMs:K.elapsed(Be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),pe?K.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):K.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(pe){let V=Ma(F,o,x);V.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Wo(V)}else xi(F,o,x,"REDIRECT_RESUME_FAILED","redirect_resume");Ke(Le.message),Ft(Le.message),lt(()=>bn.current?.(Le)),In(G,Le,{code:Le.code,declineCode:Le.declineCode}),yt("error"),await Ko(400)}finally{Fi(),Ad(),yt(null),Ft(null),Yt(!1)}})())},[In,l,F,o,x]);let Ln=(0,S.useRef)(null),Rn=(0,S.useMemo)(()=>Kt?uo(Kt):"",[Kt]),tr=(0,S.useRef)(Kt);tr.current=Kt,(0,S.useEffect)(()=>{Gt(e??"")},[e]),(0,S.useEffect)(()=>{qt.current=!1,Ke(ot),Ft(null),ht(!1),yt(null)},[Rn,ot,e]);async function nr(M,P,ee){let K=Ma(F,o,x),Be=new _r.PaymentAPI(F,{telemetry:!1}),tt=!1;try{let Le=M.idempotencyKey===void 0?void 0:(0,je.resolveIdempotencyKey)(M.idempotencyKey),G=di(P,ee),pe=ui(P,ee);G?.canonicalIdentity===ee&&pe&&pe.canonicalIdentity===void 0&&(va(P,ee,pe.idempotencyKey),pe={...pe,canonicalIdentity:ee});let V=Le??(pe?.canonicalIdentity===ee?pe.idempotencyKey:void 0),g,m=!1;K.log({name:G?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let w=G?.sid??null,C=null,Pe,ie,Ae=!1;if(w)try{C=await Be.getUnifiedCheckoutSession(w,G?.nonce),G&&G.canonicalIdentity===void 0&&(Ns(C.data.session,M)?(ba(P,ee,w,G.nonce??C.data.session?.clientSecret),pe&&pe.canonicalIdentity===void 0&&(va(P,ee,pe.idempotencyKey),V??(V=pe.idempotencyKey))):(ha(P,ee),pe=null,V=Le,w=null,C=null));let at=C?.data.session?.status,re=C?.data.session,Et=re?.clientSecret||G?.nonce;if(w&&re?.buyerIdentified===!1&&Et&&(ie=no(Be,w,Et,M.account)),w&&C&&at==="complete"){if(pi(w))return{sid:w,result:C};ha(P,ee),w=null,C=null,m=!0}}catch{K.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),G?.canonicalIdentity===void 0?(ha(P,ee),V=Le):ga(P,ee),w=null}if(!w){!Le&&(m||!V)&&(V=(0,je.resolveIdempotencyKey)(),g=V),V&&va(P,ee,V);let at=K.now(),re=0;K.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Et={...M,idempotencyKey:V,avsCheck:!!Se,avsConfig:typeof Se=="object"?Se:void 0,checkoutType:"embedded_checkout",checkoutLayout:Di(_,se)};Object.defineProperty(Et,_r.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:W=>{re=Math.max(re,W)}}});let Oe=()=>{Cl(K,"session_create",at,re)},Ze=W=>{Sl(K,W,"session_create",at,re)&&kt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,je.isDetachedSessionEligible)(Et)){let W=await Be.createDetachedSession(Et);W.claimed.catch(()=>{}),C=W.shell,w=W.sessionId,ie=W.claim;let ze=K.now();K.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Pe=W.claimed.then(Fe=>{let gt=Fe.data.session?.id??W.sessionId;return gt&&ba(P,ee,gt,Fe.data.session?.clientSecret??W.nonce),Cl(K,"session_claim",ze),Oe(),Fe},Fe=>{throw ga(P,ee),Sl(K,Fe,"session_claim",ze,0)&&kt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Fe}).finally(()=>Wo(K)),Pe.catch(()=>{}),tt=!0,K.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),K.performance({stage:"session_shell",durationMs:K.now()-at,durationMode:"machine",requestCategory:"session_create",attempt:re,statusClass:"2xx",paymentMethodCategory:"card"})}else C=await Be.createAndFetchSession(Et),Oe()}catch(W){throw Ze(W),W}w=C.data.session?.id??w??"",w&&!Pe&&ba(P,ee,w,C.data.session?.clientSecret)}let N=C?.data.session;return!ie&&w&&N?.buyerIdentified===!1&&N.clientSecret&&(ie=no(Be,w,N.clientSecret,M.account)),{sid:w??"",result:C,sdkGeneratedIdempotencyKey:g,...Pe?{claimed:Pe}:{},...ie?{claim:ie}:{},...Ae?{claimRequiresIdentity:!0}:{}}}finally{tt||Wo(K)}}let Ct=(0,S.useRef)(nr);$r(()=>{Ct.current=nr},[nr]);let Pn=(0,S.useCallback)(async(M,P)=>{let ee=tr.current;if(!ee)throw new je.FloPayError("createSession is required to bootstrap checkout.","validation_error");let K=ni(ee,M),Be=uo(K),tt=Ls(K),Le=Ba.get(Be);if(!Le){let V={canonicalIdentity:Be,promise:Ct.current(K,tt,Be),consumers:0,settled:!1};Le=V,Ba.set(Be,V);let g=()=>{V.settled=!0,Pl(Be,V)};V.promise.then(g,g)}Le.consumers+=1;let G=!1,pe=()=>{G||(G=!0,Le.consumers-=1,Pl(Be,Le))};P?.(pe);try{let V=await Le.promise;Ln.current=Be,M&&(_t(kn),un(N=>Ss(N,M)));let{sid:g,result:m,claimed:w,claim:C,claimRequiresIdentity:Pe}=V;if(Fn.current=C,hn(Pe===!0),ne(m),m.data.session&&Mt(m.data.session),g&&Gt(g),w){Ut.current+=1;let N=Ut.current;Lt.current=w,te(!0),w.then(at=>{Ut.current===N&&(Lt.current===w&&(Lt.current=null),ne(at),at.data.session&&Mt(at.data.session),te(!1),hn(!1))},at=>{Ut.current===N&&(Lt.current===w&&(Lt.current=null),te(!1),hn(!1),wn(at instanceof je.FloPayError?at:new je.FloPayError(at instanceof Error?at.message:"Failed to create session","api_error")))})}else Ut.current+=1,Lt.current=null,te(!1),hn(!1);let{flopay:ie,paypalFlopay:Ae}=await Bi(m,{billingApiUrl:F,locale:l,telemetry:o});return Dn(ie,Ae),j(!1),V}catch(V){throw Ln.current===Be&&(Ln.current=null),V}finally{P||pe()}},[kn,Dn,l,F,o]),jn=(0,S.useRef)(Cr);jn.current=Cr;let rr=(0,S.useRef)(Pn);rr.current=Pn;let _n=(0,S.useCallback)(async M=>{if(!Md(M)||an)return{sessionId:J,session:Q};Bn(!0);try{let P=await Pn(M);return{sessionId:P.sid,session:P.result.data.session??null}}finally{Bn(!1)}},[Pn,an,J,Q]),Xe=(0,S.useCallback)(async M=>{let P=Fn.current;if(!P)return;let ee=Ut.current,K=await P(M);Ut.current===ee&&(ne(K),K.data.session&&Mt(K.data.session))},[]),tn=(0,S.useCallback)(async()=>{await Lt.current},[]),pn=(0,S.useCallback)(async()=>(await tn(),{proceed:!0}),[tn]);(0,S.useEffect)(()=>{let M=!1,P,ee=++Me.current;ve(),wn(null),rn(0);let K=()=>{M=!0,Me.current===ee&&(Me.current+=1,ve())},Be=tr.current;if(Rn&&Be)return Zn(er),j(!1),Ln.current===Rn?K:(Mt(ws(Be,$)),(async()=>{let G=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),pe=er==="auto"&&!qt.current&&!G;pe&&(Ke(null),Ft(null),yt("processing"));try{let V=await rr.current(void 0,C=>{P=C}),g=V.result.data.session??null;Te.current=fi(V.result);let m=Mi(V.result),w=pi(V.sid||g?.id);if(!M&&pe&&g&&!m&&!w){qt.current=!0,await Rd(Rn,V.sdkGeneratedIdempotencyKey,()=>jn.current(g,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:V.result.autoProcessingError,initialAutoProcessingPending:V.result.autoProcessingPending,autoProcessingAttempted:V.result.autoProcessingAttempted,sessionId:V.sid||g.id}));return}!M&&pe&&((m||w)&&(qt.current=!0),yt(null),Ft(null))}catch(V){if(M)return;let g=ia(V);if(pe&&g==="session_auto_completed"){qt.current=!0,yt("success"),await Ko(600),M||(lt(()=>{Nt.current?.({status:"succeeded"})}),yt(null),Ft(null));return}pe&&(yt(null),Ft(null));let m=V instanceof je.FloPayError?V:new je.FloPayError(V instanceof Error?V.message:"Failed to create session","api_error");wn(m)}finally{P?.(),P=void 0}})(),()=>{K(),P?.()});j(!0);async function tt(){let G=!1,pe=null;try{let V=new _r.PaymentAPI(F,{telemetry:!1}),g=await V.getUnifiedCheckoutSession(Rt,t);if(pe=g,M)return;ne(g);let m=g.data.session??null;if(Mt(m),!m)throw new je.FloPayError("No session data returned","api_error");let w=m.checkoutMode;if(w==="setup")throw new je.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(m.status==="authorized"){j(!1),lt(()=>{Nt.current?.(Ur(m,Rt)),vn.current?.(m.successUrl??"")});return}if(m.status==="complete"){j(!1),lt(()=>{vn.current?.(m.successUrl??"")});return}if(m.status==="expired")throw aa(m);G=!0;let C=$??w??"full";Zn(C),Ut.current+=1;let Pe=m.clientSecret||t;Fn.current=m.buyerIdentified===!1&&Pe?no(V,Rt,Pe,{...m.customer?.id?{userId:m.customer.id}:{}}):void 0,te(!1),hn(!1);let ie=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ae=Mi(g);if(C==="auto"&&!qt.current&&!ie&&!Ae){qt.current=!0;let N=Le(g);try{if(await jn.current(m,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>N,sessionId:Rt||m.id}),M)return;await N,M||j(!1);return}catch{if(M)return;await N,M||j(!1);return}}await Le(g),M||j(!1)}catch(V){if(M)return;let g=Cs(V,G);if(G&&kt({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),g){let{errorCode:w,stage:C,...Pe}=g;xi(F,o,x,w,C,Pe)}if(g?.stage==="provider_load"&&($??pe?.data.session?.checkoutMode??"full")==="full"&&Ps(pe,O,ue)){let w=Ed({billingApiUrl:F,locale:l,telemetry:o});Je.current=w,Dn(w,null),rn(1),j(!1);return}let m=V instanceof je.FloPayError&&g?.stage!=="provider_load"?V:vs();m!==V&<(()=>bn.current?.(m)),wn(m),j(!1)}}async function Le(G){let{flopay:pe,paypalFlopay:V,...g}=await Bi(G,{billingApiUrl:F,locale:l,telemetry:o});Te.current={publishableKey:g.publishableKey,paypalPublishableKey:g.paypalPublishableKey},Dn(pe,V),rn(0)}return tt(),K},[$,Rn,er,mn,t,O,ue]);let mr=(0,S.useCallback)(async()=>{if(!U||cn!==1)return;let M=Me.current;rn(2);try{let{flopay:P,paypalFlopay:ee}=await Bi(U,{billingApiUrl:F,locale:l,telemetry:o});if(Me.current!==M)return;ve(),Dn(P,ee),rn(0)}catch(P){if(Me.current!==M)return;let{errorCode:ee,stage:K,...Be}=ei(P);xi(F,o,x,ee,K,Be)}},[ve,Dn,l,cn,F,o,x,U]),Mr=(0,S.useCallback)(async()=>{if(!(dn||!Q)){Yt(!0),Ke(null);try{await Cr(Q,{attempt3DS:!0,fallbackToFull:!0,sessionId:Rt||Q.id})}finally{Yt(!1)}}},[Rt,dn,Cr,Q]),or=Li(U),yr=Mi(U),En=(0,S.useMemo)(()=>{if(!(!U||!Q||!U.data.stripe?.publishableKey))return{billingApiUrl:F}},[U,Q,F]),Tn=!!(n&&!_&&se==="buttons"&&le&&er==="full"),Br=!!(Rt&&(Q?.vault?.html||Or(Q))),Nn=(0,S.useMemo)(()=>({session:Q,loading:ur,error:yn,checkoutMode:fn,inlineSessionDraft:Kt,applyInlineSessionPatch:Tn?_n:void 0,inlineSessionPatchProcessing:an,claimPending:Pt,claimRequiresIdentity:gn,claimBuyerIdentity:Xe,waitForDataAttachment:tn}),[Q,ur,yn,fn,Kt,Tn,_n,an,Pt,gn,Xe,tn]),Fr=!!n&&se==="buttons"&&!yr&&!Br&&(!qe||!En),Zt=on?(0,T.jsx)(Jn,{status:on,errorMessage:$n,authorized:Jt}):null;if(ur&&!Br){if(d)return(0,T.jsxs)(T.Fragment,{children:[d,Zt]});if(se==="buttons"){let M=De?.buttonsLayout?.cardButton?.borderRadius??De?.appearance.variables?.borderRadius??8,P=ee=>(0,T.jsx)("div",{style:{height:ee,borderRadius:M,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[O&&P(ho),ue&&(k||q)&&P(ho),ue&&P(ho),(0,T.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Zt]})}return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,T.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,T.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Zt]})}return yn?u?(0,T.jsx)(ir.Provider,{value:Nn,children:u(yn)}):(0,T.jsx)(ir.Provider,{value:Nn,children:(0,T.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:yn.message})}):Fr?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(ir.Provider,{value:Nn,children:(0,T.jsx)(Fd,{onButtonClick:Ue,showPayPal:O,showStripe:ue,showApplePay:k,showGooglePay:q,theme:Ce,buttonsTheme:ae,buttonsStyles:me,cardButtonContent:fe,cardBackButtonContent:pt,cardTitleContent:Ge})}),Zt]}):yr&&Q&&or?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(ir.Provider,{value:Nn,children:(0,T.jsxs)("div",{className:rt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ne&&(0,T.jsx)(lo,{icon:!1,children:Ne}),Vn==="retrying"&&(0,T.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Vn==="exhausted"&&(0,T.jsxs)("div",{role:"alert",children:[(0,T.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,T.jsx)("button",{type:"button",onClick:Kr,children:"Retry PayPal"})]}),Vn!=="exhausted"&&(0,T.jsx)("div",{"aria-hidden":Vn==="retrying"?!0:void 0,style:Vn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,T.jsx)(Ds,{sessionId:Rt,nonce:Q.clientSecret||void 0,billingApiUrl:F,email:Q.customer?.email||Kt?.account?.email,billingName:[Q.customer?.firstName,Q.customer?.lastName].filter(Boolean).join(" ")||[Kt?.account?.firstName,Kt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Xe,clientId:or.clientId,environment:or.environment,currency:(Q.currency??"usd").toUpperCase(),isSubscription:Q.mode==="subscription",providerObjectType:or.providerObjectType,approvalPresentation:or.approvalPresentation,onComplete:h,onErrorChange:Ke,onDecline:b,onButtonClick:Ue,runBeforeButtonClick:pn,onInitializationStateChange:xr,allowAutomaticRetry:Xt===0,session:Q,telemetry:o,telemetryContext:x,onInstrument:Bt,debug:z},`${D}:paypal-init-${Xt}`)})]})}),Zt]}):(!qe||!En)&&!(Br&&fn==="full")?(0,T.jsx)(T.Fragment,{children:Zt}):fn==="confirm"?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(ir.Provider,{value:Nn,children:(0,T.jsx)(No,{flopay:qe,paypalFlopay:be,options:En??{billingApiUrl:F},onInstrument:Bt,children:(0,T.jsxs)("div",{className:rt,children:[Ne&&(0,T.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ne}),Z?Z({onConfirm:Mr,isProcessing:dn}):(0,T.jsx)("button",{type:"button",onClick:Mr,disabled:dn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:dn?"not-allowed":"pointer",opacity:dn?.6:1},children:dn?"Processing...":ye??"Confirm Purchase"})]})},D)}),Zt]}):(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(ir.Provider,{value:Nn,children:(0,T.jsxs)(No,{flopay:qe,paypalFlopay:be,options:En??{billingApiUrl:F},onInstrument:Bt,children:[cn===1&&(0,T.jsx)("button",{type:"button",onClick:mr,children:"Retry payment methods"}),_?(0,T.jsxs)(T.Fragment,{children:[Ne&&(0,T.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ne}),(0,T.jsx)(Bd,{sessionId:Rt,nonce:Q?.clientSecret||void 0,billingApiUrl:F,session:Q,submitLabel:ce,children:_})]}):(0,T.jsx)(Aa,{sessionId:Rt,nonce:Q?.clientSecret||void 0,telemetry:o,email:Q?.customer?.email||Kt?.account?.email,userId:Q?.customer?.id||Kt?.account?.userId,firstName:Q?.customer?.firstName||Kt?.account?.firstName,lastName:Q?.customer?.lastName||Kt?.account?.lastName,totalAmount:Q?Math.round((0,je.buildCheckoutDisplayData)(Q).total*100):0,currency:Q?.currency?.toLowerCase()??"usd",onComplete:h,onError:y,onDecline:b,error:Ne,onErrorChange:Ke,showPayPal:O,showStripe:ue,enabledPaymentMethods:cn?[]:oe??U?.data.stripe?.enabledPaymentMethods??Q?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:U?.data.stripe?.enabledPaymentMethodCountries,showApplePay:k,showGooglePay:q,layout:se,theme:Ce,buttonsTheme:ae,buttonsStyles:me,appearance:mt,cardButtonContent:fe,cardBackButtonContent:pt,cardTitleContent:Ge,onButtonClick:Ue,onBeforeButtonClick:le,onBuyerIdentityReady:Xe,enableAVS:Se,...Ye?{cardFieldOrder:Ye}:{},...X?{cardPreFormSlot:X}:{},avsLayout:we,country:Q?.customer?.country,city:Q?.customer?.city,state:Q?.customer?.state,onCountryChange:R,onZipChange:B,avsCheck:!!Se,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Di(_,se),className:rt,submitLabel:ce,directPaypal:Li(U),isSubscription:Q?.mode==="subscription",session:Q,dataAttachmentPending:Pt,dataAttachmentRequiresIdentity:gn,debug:z})]},D)}),Zt]})}function Bd({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,children:a}){return(0,T.jsx)(T.Fragment,{children:S.default.Children.map(a,l=>{if(!S.default.isValidElement(l))return l;let d=l.props,u={};return d.sessionId||(u.sessionId=e),!d.nonce&&t&&(u.nonce=t),d.billingApiUrl||(u.billingApiUrl=n),d.submitLabel===void 0&&o!==void 0&&(u.submitLabel=o),r?.customer&&(d.email||(u.email=r.customer.email),d.userId||(u.userId=r.customer.id),d.firstName||(u.firstName=r.customer.firstName),d.lastName||(u.lastName=r.customer.lastName)),Object.keys(u).length===0?l:S.default.cloneElement(l,u)})})}function Fd({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:d,cardButtonContent:u,cardBackButtonContent:h,cardTitleContent:y}){let[v,b]=(0,S.useState)(!1),R=(0,S.useMemo)(()=>(0,je.resolveTheme)(a),[a]),B=(0,S.useMemo)(()=>{let k=R?.buttonsLayout??(0,je.resolveButtonsLayoutTheme)(l);return d?{...k,...d,cardButton:{...k.cardButton,...d.cardButton},cardFormContainer:{...k.cardFormContainer,...d.cardFormContainer},backButton:{...k.backButton,...d.backButton},backButtonIcon:{...k.backButtonIcon,...d.backButtonIcon},submitButton:{...k.submitButton,...d.submitButton},title:{...k.title,...d.title}}:k},[R,l,d]),O=R?.buttonsLayout?.cardButton?.borderRadius??R?.appearance.variables?.borderRadius??8,ue=k=>(0,T.jsx)("div",{style:{height:k,borderRadius:O,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),oe=u===void 0?{boxSizing:"border-box",height:ho,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(v){let k=B.cardInputBorder??"#e5e7eb",q=B.cardInputBackground??"white",z=Qr(h),se=Qr(y);return(0,T.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,T.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,T.jsxs)("button",{type:"button",onClick:()=>b(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:z?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,T.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...B.backButtonIcon},children:(0,T.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,T.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,T.jsx)(to,{content:h})]}),se?(0,T.jsx)("div",{style:{flex:1}}):(0,T.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...B.title},children:(0,T.jsx)(To,{content:y})})]}),(0,T.jsx)("div",{style:{backgroundColor:q,border:`1px solid ${k}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,T.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,T.jsxs)("div",{style:{display:"flex"},children:[(0,T.jsx)("div",{style:{flex:1,backgroundColor:q,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${k}`,borderLeft:`1px solid ${k}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,T.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,T.jsx)("div",{style:{flex:1,backgroundColor:q,borderTop:"none",borderRight:`1px solid ${k}`,borderBottom:`1px solid ${k}`,borderLeft:`1px solid ${k}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,T.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,T.jsx)("div",{style:{backgroundColor:q,border:`1px solid ${k}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,T.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,T.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,T.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,E.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&pe(go),n&&(r||o)&&pe(go),n&&(0,E.jsx)("button",{type:"button",onClick:()=>{e?.("card"),v(!0)},style:{width:"100%",...ae,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:M.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...M.cardButton},onMouseDown:w=>{w.currentTarget.style.transform="scale(0.985)"},onMouseUp:w=>{w.currentTarget.style.transform="scale(1)"},children:(0,E.jsx)(Qr,{content:u})}),(0,E.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var ir=require("react/jsx-runtime"),Md=44;function wl(e){return new Promise(t=>setTimeout(t,e))}function Bd(e,t){return e instanceof Jn.FloPayError?e:new Jn.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 Dd(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 kl({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:d,subscriptions:u,account:b,successUrl:f,cancelUrl:P,couponCodes:v,tagsData:I,utmMetadata:M,billingApiUrl:N,locale:pe,theme:ae,appearance:w,buttonsTheme:q,buttonsStyles:O,onSuccess:le,onError:Se,onDecline:ie,children:ye,disabled:he=!1,type:dt="button",style:Je,...be}){let Ue=(0,tt.useMemo)(()=>(0,Jn.resolveBillingApiUrl)(N),[N]),ce=(0,tt.useMemo)(()=>Dd({createSession:n,clientId:a,products:l,items:d,subscriptions:u,account:b,successUrl:f,cancelUrl:P,couponCodes:v,tagsData:I,utmMetadata:M}),[b,P,a,v,n,l,d,u,f,I,M]),[we,Xe]=(0,tt.useState)(!1),[Z,ke]=(0,tt.useState)(null),[de,nt]=(0,tt.useState)(null),[rt,R]=(0,tt.useState)(!1),[$,fe]=(0,tt.useState)(null),Q=(0,tt.useRef)(!0),Ie=(0,tt.useRef)(null),F=(0,tt.useRef)($),Me=(0,tt.useRef)(le),ut=(0,tt.useRef)(Se),et=(0,tt.useRef)(ie);(0,tt.useEffect)(()=>{F.current=$},[$]),(0,tt.useEffect)(()=>{Me.current=le},[le]),(0,tt.useEffect)(()=>{ut.current=Se},[Se]),(0,tt.useEffect)(()=>{et.current=ie},[ie]),(0,tt.useEffect)(()=>(Q.current=!0,()=>{Q.current=!1,Ie.current?.abort()}),[]),(0,tt.useEffect)(()=>{if(typeof window>"u")return;let g=T=>{T.key==="Escape"&&fe(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let ve=(0,tt.useCallback)((g,T=Oo)=>{et.current?.(rn(T,g,{code:g.code,declineCode:g.declineCode}))},[]),z=(0,tt.useCallback)(async g=>{Q.current&&(nt(null),R(g.result.status==="authorized"),ke("success"),await wl(600),Q.current&&st(()=>Me.current?.(g)))},[]),oe=(0,tt.useCallback)(async(g,T)=>{Q.current&&(ut.current?.(g),T?.emitDecline&&ve(g,T.method),nt(g.message),R(!1),ke("error"),await wl(400))},[ve]),qe=(0,tt.useCallback)(async(g,T,$e)=>{let _e=g.data.session??null;if(!_e)throw new Jn.FloPayError("No session data returned","api_error");let St=_e.clientSecret||t;if(no(_e)){await z({result:zr(_e,T),session:_e,sessionId:_e.id||T,autoCompleted:!1});return}if(_e.status==="expired")throw oa(_e);try{if(g.autoProcessingPending){let Xt=(await new Fa.PaymentAPI(Ue).waitForCheckoutSessionCompletion(g.autoProcessingPending.sessionId,{initialDelayMs:g.autoProcessingPending.retryAfterMs})).data.session;if(!no(Xt))throw ia(Xt);await z({result:zr(Xt,T),session:Xt,sessionId:Xt.id||T,autoCompleted:!1});return}if(g.autoProcessingError){if(g.autoProcessingError.type==="3ds_required"&&g.autoProcessingError.nextActionRedirectUrl&&T&&St){let xt=new AbortController;Ie.current=xt;let J;try{J=await zs({billingApiUrl:Ue,sessionId:T,nonce:St,nextActionRedirectUrl:g.autoProcessingError.nextActionRedirectUrl,signal:xt.signal})}finally{Ie.current===xt&&(Ie.current=null)}if(J.status==="declined")throw Ar({type:J.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:J.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let fn=(await new Fa.PaymentAPI(Ue).waitForCheckoutSessionCompletion(T,{initialDelayMs:0,nonce:St})).data.session;if(!no(fn))throw Ar({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await z({result:zr(fn,T),session:fn,sessionId:fn.id||T,autoCompleted:!1});return}throw Ar(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if($e?.fromCreateSession&&g.autoProcessingAttempted===!0)throw Ar({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let at=await mo({billingApiUrl:Ue,sessionId:T??_e.id,session:_e,nonce:St});if(at.type!=="success")throw Ar({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await z({result:at.result,session:_e,sessionId:_e.id||T,autoCompleted:!1})}catch(at){let xt=zo(at),J=_e.id||T;await oe(xt,{emitDecline:!0,method:xt.checkoutMethod??Oo}),Fd(xt,J)&&J&&Q.current&&fe({sessionId:J,errorMessage:xt.message,nonce:St||void 0})}},[t,Ue,oe,z]),lt=(0,tt.useCallback)(async g=>{if(be.onClick?.(g),!(g.defaultPrevented||he||we)){if(fe(null),e&&ce){let T=new Jn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await oe(T),Q.current&&(ke(null),nt(null));return}if(!e&&!ce){let T=new Jn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await oe(T),Q.current&&(ke(null),nt(null));return}Xe(!0),nt(null),R(!1),ke("processing");try{let T=new Fa.PaymentAPI(Ue);if(e){let $e=await T.getUnifiedCheckoutSession(e,t);await qe($e,e);return}try{let $e=await T.createAndFetchSession({...ce});await qe($e,$e.data.session?.id??null,{fromCreateSession:!0})}catch($e){if(aa($e)==="session_auto_completed"){await z({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw $e}}catch(T){await oe(Bd(T,"Automatic payment failed. Please try again."))}finally{Q.current&&(ke(null),nt(null),Xe(!1))}}},[be.onClick,ce,he,we,t,qe,Ue,e,oe,z]),Te=(0,tt.useCallback)(g=>{let T=F.current;fe(null),Me.current?.({result:g,session:null,sessionId:T?.sessionId??null,autoCompleted:!1})},[]),Ze=(0,tt.useCallback)(g=>{ut.current?.(g)},[]),Ae=(0,tt.useCallback)(g=>{et.current?.(g)},[]),Pe=(0,tt.useMemo)(()=>(0,Jn.resolveTheme)(ae),[ae]),Be=(0,tt.useMemo)(()=>{let g=Pe?.buttonsLayout??(0,Jn.resolveButtonsLayoutTheme)(q);return O?{...g,...O,cardButton:{...g.cardButton,...O.cardButton}}:g},[Pe,q,O]),Jt=(0,tt.useMemo)(()=>{let g=Pe?.appearance;return w?g?{...g,...w,variables:{...g.variables,...w.variables}}:w:g},[w,Pe]),te=Jt?.variables,At=te?.colorPrimary??"#4A49FF",mt=te?.colorPrimaryHover??fo(At,.12),D=te?.borderRadius??"8px";return(0,ir.jsxs)(ir.Fragment,{children:[(0,ir.jsx)("button",{...be,type:dt,onClick:lt,disabled:he||we,"aria-busy":we,style:{width:"100%",...ye===void 0?{boxSizing:"border-box",height:Md,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Be.cardButton,..._i({themeBundle:Pe,resolvedPrimaryColor:At,resolvedBorderRadius:D,submitButtonStyle:Be.submitButton,explicitPrimaryColor:te?.colorPrimary}),fontSize:Be.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:he||we?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:he||we?.6:1,...Je},onMouseEnter:g=>{be.onMouseEnter?.(g),!g.defaultPrevented&&!he&&!we&&(Pe||te?.colorPrimary)&&(g.currentTarget.style.backgroundColor=mt)},onMouseLeave:g=>{be.onMouseLeave?.(g),!g.defaultPrevented&&(Pe||te?.colorPrimary)&&(g.currentTarget.style.backgroundColor=At)},onMouseDown:g=>{be.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{be.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:(0,ir.jsx)(Qr,{content:ye})}),Z&&(0,ir.jsx)(Yn,{status:Z,errorMessage:de,authorized:rt}),$&&(0,ir.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.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,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)(Ba,{sessionId:$.sessionId,nonce:$.nonce,checkoutMode:"full",billingApiUrl:Ue,locale:pe,theme:ae,...Jt?{appearance:Jt}:{},buttonsTheme:q,buttonsStyles:O,initialErrorMessage:$.errorMessage,cardTitleContent:null,onComplete:Te,onError:Ze,onDecline:Ae})})})]})}var Da=require("@flopay/js/card-setup"),On=require("@flopay/shared"),bt=require("react");var Il={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function Rl(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?Il.dark:Il.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 hr=require("react/jsx-runtime"),Wo=class extends On.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function _l(e,t={}){let n=e instanceof On.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 Wo(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 El({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:l=null,onReady:d,onComplete:u,onDecline:b,onCancel:f,onValidation:P,onError:v}){let[I,M]=(0,bt.useState)(null),[N,pe]=(0,bt.useState)(null),[ae,w]=(0,bt.useState)(null),[q,O]=(0,bt.useState)(null),[le,Se]=(0,bt.useState)(null),ie=(0,bt.useRef)(!1),ye=(0,bt.useRef)(!1),he=(0,bt.useMemo)(()=>typeof o=="object"?void 0:(0,On.resolveTheme)(o),[o]),dt=(0,bt.useMemo)(()=>typeof o=="object"?o:he?wa({appearance:he.appearance,buttonsStyles:he.buttonsLayout,layout:"default"}):null,[he,o]),Je=(0,bt.useMemo)(()=>$s(he?.buttonsLayout.cardFormContainer,a),[he,a]),be=(0,bt.useMemo)(()=>he?Rl(he):void 0,[he]),Ue=(0,bt.useRef)(d),ce=(0,bt.useRef)(v),we=(0,bt.useRef)(u),Xe=(0,bt.useRef)(b),Z=(0,bt.useRef)(f),ke=(0,bt.useRef)(P),de=(0,bt.useRef)(!1),nt=(0,bt.useRef)(!1),rt=(0,bt.useRef)(0);return Ue.current=d,ce.current=v,we.current=u,Xe.current=b,Z.current=f,ke.current=P,(0,bt.useEffect)(()=>{let R=rt.current+1;return rt.current=R,()=>{queueMicrotask(()=>{rt.current===R&&(de.current||nt.current||(nt.current=!0,st(()=>{Z.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,bt.useEffect)(()=>{let R=!0,$=new Da.PaymentAPI((0,On.resolveBillingApiUrl)(n),{telemetry:r});return M(null),pe(null),w(null),de.current=!1,nt.current=!1,(async()=>{try{if(!e.trim())throw new On.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new On.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let fe=await $.getUnifiedCheckoutSession(e,t);if(!R)return;let Q=fe.data.session;if(!Q||!(0,On.isCardSetupCheckoutSession)(Q))throw new On.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Ie=Q.vault;if(Ie?.html?.trim()||(Ie=await $.getVaultCapture(e,t)),!Ie.html?.trim())throw new On.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!R)return;pe(Ie),M(new Da.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(fe){if(!R)return;let Q=_l(fe);de.current=!0,w(Q),st(()=>ce.current?.(Q))}})(),()=>{R=!1,$.destroy()}},[n,t,e,r]),(0,bt.useEffect)(()=>{if(!I)return;let R=!1;ye.current=!1,ie.current=!1;let $=I.on("submitting",()=>{ie.current=!0,Se(null),O("processing")}),fe=I.on("complete",Ie=>{de.current=!0,ie.current=!1,O("success"),(async()=>(await new Promise(F=>setTimeout(F,600)),!ye.current&&(ye.current=!0,st(()=>{we.current?.({status:"succeeded",sessionId:e,...Ie.paymentMethod?{paymentMethod:Ie.paymentMethod}:{}})}),R||O(null))))()}),Q=I.on("decline",Ie=>{de.current=!0,ie.current=!1,Se(Ie.message??null),O("error"),st(()=>{Xe.current?.({status:"declined",sessionId:e,...Ie.declineReason?{reason:Ie.declineReason}:{},...Ie.message?{message:Ie.message}:{}})}),(async()=>(await new Promise(F=>setTimeout(F,400)),R||O(null)))()});return()=>{R=!0,$(),fe(),Q()}},[I,e]),ae?(0,hr.jsx)("div",{role:"alert",children:ae.message}):!I||!N?.html?(0,hr.jsx)(hr.Fragment,{children:l}):(0,hr.jsxs)(hr.Fragment,{children:[q&&(0,hr.jsx)(Yn,{status:q,errorMessage:le,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...be?{theme:be}:{}}),(0,hr.jsx)(yo,{capture:I,html:N.html,messageToken:N.messageToken,expectedOrigin:N.expectedOrigin,theme:dt,containerStyle:Je,onReady:()=>{st(()=>Ue.current?.())},onValidation:R=>{st(()=>ke.current?.(R))},onError:R=>{if(!R)return;ie.current&&(ie.current=!1,Se(R),O("error"),setTimeout(()=>O(null),400));let $=_l(new Error(R),{code:"card_setup_widget_failed",retryable:!0});st(()=>ce.current?.($))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}return(0,T.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&ue(ho),n&&(r||o)&&ue(ho),n&&(0,T.jsx)("button",{type:"button",onClick:()=>{e?.("card"),b(!0)},style:{width:"100%",...oe,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:k=>{k.currentTarget.style.transform="scale(0.985)"},onMouseUp:k=>{k.currentTarget.style.transform="scale(1)"},children:(0,T.jsx)(eo,{content:u})}),(0,T.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var dr=require("react/jsx-runtime"),Dd=44;function Rl(e){return new Promise(t=>setTimeout(t,e))}function Ld(e,t){return e instanceof Xn.FloPayError?e:new Xn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Nd(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Od(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 _l({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:d,subscriptions:u,account:h,successUrl:y,cancelUrl:v,couponCodes:b,tagsData:R,utmMetadata:B,billingApiUrl:O,locale:ue,theme:oe,appearance:k,buttonsTheme:q,buttonsStyles:z,onSuccess:se,onError:Ce,onDecline:ae,children:me,disabled:fe=!1,type:pt="button",style:Ge,...ge}){let Ue=(0,nt.useMemo)(()=>(0,Xn.resolveBillingApiUrl)(O),[O]),le=(0,nt.useMemo)(()=>Od({createSession:n,clientId:a,products:l,items:d,subscriptions:u,account:h,successUrl:y,cancelUrl:v,couponCodes:b,tagsData:R,utmMetadata:B}),[h,v,a,b,n,l,d,u,y,R,B]),[Se,Ye]=(0,nt.useState)(!1),[X,we]=(0,nt.useState)(null),[ce,rt]=(0,nt.useState)(null),[ot,_]=(0,nt.useState)(!1),[$,ye]=(0,nt.useState)(null),Z=(0,nt.useRef)(!0),ke=(0,nt.useRef)(null),F=(0,nt.useRef)($),De=(0,nt.useRef)(se),mt=(0,nt.useRef)(Ce),et=(0,nt.useRef)(ae);(0,nt.useEffect)(()=>{F.current=$},[$]),(0,nt.useEffect)(()=>{De.current=se},[se]),(0,nt.useEffect)(()=>{mt.current=Ce},[Ce]),(0,nt.useEffect)(()=>{et.current=ae},[ae]),(0,nt.useEffect)(()=>(Z.current=!0,()=>{Z.current=!1,ke.current?.abort()}),[]),(0,nt.useEffect)(()=>{if(typeof window>"u")return;let f=A=>{A.key==="Escape"&&ye(null)};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f)}},[]);let he=(0,nt.useCallback)((f,A=zo)=>{et.current?.(nn(A,f,{code:f.code,declineCode:f.declineCode}))},[]),U=(0,nt.useCallback)(async f=>{Z.current&&(rt(null),_(f.result.status==="authorized"),we("success"),await Rl(600),Z.current&<(()=>De.current?.(f)))},[]),ne=(0,nt.useCallback)(async(f,A)=>{Z.current&&(mt.current?.(f),A?.emitDecline&&he(f,A.method),rt(f.message),_(!1),we("error"),await Rl(400))},[he]),qe=(0,nt.useCallback)(async(f,A,$e)=>{let Re=f.data.session??null;if(!Re)throw new Xn.FloPayError("No session data returned","api_error");let kt=Re.clientSecret||t;if(ro(Re)){await U({result:Ur(Re,A),session:Re,sessionId:Re.id||A,autoCompleted:!1});return}if(Re.status==="expired")throw aa(Re);try{if(f.autoProcessingPending){let Gt=(await new Da.PaymentAPI(Ue).waitForCheckoutSessionCompletion(f.autoProcessingPending.sessionId,{initialDelayMs:f.autoProcessingPending.retryAfterMs})).data.session;if(!ro(Gt))throw sa(Gt);await U({result:Ur(Gt,A),session:Gt,sessionId:Gt.id||A,autoCompleted:!1});return}if(f.autoProcessingError){if(f.autoProcessingError.type==="3ds_required"&&f.autoProcessingError.nextActionRedirectUrl&&A&&kt){let Bt=new AbortController;ke.current=Bt;let J;try{J=await $s({billingApiUrl:Ue,sessionId:A,nonce:kt,nextActionRedirectUrl:f.autoProcessingError.nextActionRedirectUrl,signal:Bt.signal})}finally{ke.current===Bt&&(ke.current=null)}if(J.status==="declined")throw Ar({type:J.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:J.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:f.autoProcessingError.checkoutMethod});let mn=(await new Da.PaymentAPI(Ue).waitForCheckoutSessionCompletion(A,{initialDelayMs:0,nonce:kt})).data.session;if(!ro(mn))throw Ar({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:f.autoProcessingError.checkoutMethod});await U({result:Ur(mn,A),session:mn,sessionId:mn.id||A,autoCompleted:!1});return}throw Ar(f.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:f.autoProcessingError.checkoutMethod})}if($e?.fromCreateSession&&f.autoProcessingAttempted===!0)throw Ar({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let st=await yo({billingApiUrl:Ue,sessionId:A??Re.id,session:Re,nonce:kt});if(st.type!=="success")throw Ar({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await U({result:st.result,session:Re,sessionId:Re.id||A,autoCompleted:!1})}catch(st){let Bt=Uo(st),J=Re.id||A;await ne(Bt,{emitDecline:!0,method:Bt.checkoutMethod??zo}),Nd(Bt,J)&&J&&Z.current&&ye({sessionId:J,errorMessage:Bt.message,nonce:kt||void 0})}},[t,Ue,ne,U]),ct=(0,nt.useCallback)(async f=>{if(ge.onClick?.(f),!(f.defaultPrevented||fe||Se)){if(ye(null),e&&le){let A=new Xn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await ne(A),Z.current&&(we(null),rt(null));return}if(!e&&!le){let A=new Xn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await ne(A),Z.current&&(we(null),rt(null));return}Ye(!0),rt(null),_(!1),we("processing");try{let A=new Da.PaymentAPI(Ue);if(e){let $e=await A.getUnifiedCheckoutSession(e,t);await qe($e,e);return}try{let $e=await A.createAndFetchSession({...le});await qe($e,$e.data.session?.id??null,{fromCreateSession:!0})}catch($e){if(ia($e)==="session_auto_completed"){await U({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw $e}}catch(A){await ne(Ld(A,"Automatic payment failed. Please try again."))}finally{Z.current&&(we(null),rt(null),Ye(!1))}}},[ge.onClick,le,fe,Se,t,qe,Ue,e,ne,U]),xe=(0,nt.useCallback)(f=>{let A=F.current;ye(null),De.current?.({result:f,session:null,sessionId:A?.sessionId??null,autoCompleted:!1})},[]),Je=(0,nt.useCallback)(f=>{mt.current?.(f)},[]),Me=(0,nt.useCallback)(f=>{et.current?.(f)},[]),be=(0,nt.useMemo)(()=>(0,Xn.resolveTheme)(oe),[oe]),_e=(0,nt.useMemo)(()=>{let f=be?.buttonsLayout??(0,Xn.resolveButtonsLayoutTheme)(q);return z?{...f,...z,cardButton:{...f.cardButton,...z.cardButton}}:f},[be,q,z]),Ht=(0,nt.useMemo)(()=>{let f=be?.appearance;return k?f?{...f,...k,variables:{...f.variables,...k.variables}}:k:f},[k,be]),Q=Ht?.variables,Mt=Q?.colorPrimary??"#4A49FF",ft=Q?.colorPrimaryHover??go(Mt,.12),D=Q?.borderRadius??"8px";return(0,dr.jsxs)(dr.Fragment,{children:[(0,dr.jsx)("button",{...ge,type:pt,onClick:ct,disabled:fe||Se,"aria-busy":Se,style:{width:"100%",...me===void 0?{boxSizing:"border-box",height:Dd,padding:"0 1rem"}:{padding:"0.9rem 1rem"},..._e.cardButton,...Ai({themeBundle:be,resolvedPrimaryColor:Mt,resolvedBorderRadius:D,submitButtonStyle:_e.submitButton,explicitPrimaryColor:Q?.colorPrimary}),fontSize:_e.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:fe||Se?"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:fe||Se?.6:1,...Ge},onMouseEnter:f=>{ge.onMouseEnter?.(f),!f.defaultPrevented&&!fe&&!Se&&(be||Q?.colorPrimary)&&(f.currentTarget.style.backgroundColor=ft)},onMouseLeave:f=>{ge.onMouseLeave?.(f),!f.defaultPrevented&&(be||Q?.colorPrimary)&&(f.currentTarget.style.backgroundColor=Mt)},onMouseDown:f=>{ge.onMouseDown?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(0.985)")},onMouseUp:f=>{ge.onMouseUp?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(1)")},children:(0,dr.jsx)(eo,{content:me})}),X&&(0,dr.jsx)(Jn,{status:X,errorMessage:ce,authorized:ot}),$&&(0,dr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:f=>{f.target===f.currentTarget&&ye(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,dr.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,dr.jsx)(Fa,{sessionId:$.sessionId,nonce:$.nonce,checkoutMode:"full",billingApiUrl:Ue,locale:ue,theme:oe,...Ht?{appearance:Ht}:{},buttonsTheme:q,buttonsStyles:z,initialErrorMessage:$.errorMessage,cardTitleContent:null,onComplete:xe,onError:Je,onDecline:Me})})})]})}var La=require("@flopay/js/card-setup"),qn=require("@flopay/shared"),vt=require("react");var El={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function Tl(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?El.dark:El.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 Pr=require("react/jsx-runtime"),Ho=class extends qn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Al(e,t={}){let n=e instanceof qn.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 Ho(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 xl({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:l=null,onReady:d,onComplete:u,onDecline:h,onCancel:y,onValidation:v,onError:b}){let[R,B]=(0,vt.useState)(null),[O,ue]=(0,vt.useState)(null),[oe,k]=(0,vt.useState)(null),[q,z]=(0,vt.useState)(null),[se,Ce]=(0,vt.useState)(null),ae=(0,vt.useRef)(!1),me=(0,vt.useRef)(!1),fe=(0,vt.useMemo)(()=>typeof o=="object"?void 0:(0,qn.resolveTheme)(o),[o]),pt=(0,vt.useMemo)(()=>typeof o=="object"?o:fe?ka({appearance:fe.appearance,buttonsStyles:fe.buttonsLayout,layout:"default"}):null,[fe,o]),Ge=(0,vt.useMemo)(()=>Ks(fe?.buttonsLayout.cardFormContainer,a),[fe,a]),ge=(0,vt.useMemo)(()=>fe?Tl(fe):void 0,[fe]),Ue=(0,vt.useRef)(d),le=(0,vt.useRef)(b),Se=(0,vt.useRef)(u),Ye=(0,vt.useRef)(h),X=(0,vt.useRef)(y),we=(0,vt.useRef)(v),ce=(0,vt.useRef)(!1),rt=(0,vt.useRef)(!1),ot=(0,vt.useRef)(0);return Ue.current=d,le.current=b,Se.current=u,Ye.current=h,X.current=y,we.current=v,(0,vt.useEffect)(()=>{let _=ot.current+1;return ot.current=_,()=>{queueMicrotask(()=>{ot.current===_&&(ce.current||rt.current||(rt.current=!0,lt(()=>{X.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,vt.useEffect)(()=>{let _=!0,$=new La.PaymentAPI((0,qn.resolveBillingApiUrl)(n),{telemetry:r});return B(null),ue(null),k(null),ce.current=!1,rt.current=!1,(async()=>{try{if(!e.trim())throw new qn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new qn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ye=await $.getUnifiedCheckoutSession(e,t);if(!_)return;let Z=ye.data.session;if(!Z||!(0,qn.isCardSetupCheckoutSession)(Z))throw new qn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let ke=Z.vault;if(ke?.html?.trim()||(ke=await $.getVaultCapture(e,t)),!ke.html?.trim())throw new qn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!_)return;ue(ke),B(new La.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(ye){if(!_)return;let Z=Al(ye);ce.current=!0,k(Z),lt(()=>le.current?.(Z))}})(),()=>{_=!1,$.destroy()}},[n,t,e,r]),(0,vt.useEffect)(()=>{if(!R)return;let _=!1;me.current=!1,ae.current=!1;let $=R.on("submitting",()=>{ae.current=!0,Ce(null),z("processing")}),ye=R.on("complete",ke=>{ce.current=!0,ae.current=!1,z("success"),(async()=>(await new Promise(F=>setTimeout(F,600)),!me.current&&(me.current=!0,lt(()=>{Se.current?.({status:"succeeded",sessionId:e,...ke.paymentMethod?{paymentMethod:ke.paymentMethod}:{}})}),_||z(null))))()}),Z=R.on("decline",ke=>{ce.current=!0,ae.current=!1,Ce(ke.message??null),z("error"),lt(()=>{Ye.current?.({status:"declined",sessionId:e,...ke.declineReason?{reason:ke.declineReason}:{},...ke.message?{message:ke.message}:{}})}),(async()=>(await new Promise(F=>setTimeout(F,400)),_||z(null)))()});return()=>{_=!0,$(),ye(),Z()}},[R,e]),oe?(0,Pr.jsx)("div",{role:"alert",children:oe.message}):!R||!O?.html?(0,Pr.jsx)(Pr.Fragment,{children:l}):(0,Pr.jsxs)(Pr.Fragment,{children:[q&&(0,Pr.jsx)(Jn,{status:q,errorMessage:se,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...ge?{theme:ge}:{}}),(0,Pr.jsx)(fo,{capture:R,html:O.html,messageToken:O.messageToken,expectedOrigin:O.expectedOrigin,theme:pt,containerStyle:Ge,onReady:()=>{lt(()=>Ue.current?.())},onValidation:_=>{lt(()=>we.current?.(_))},onError:_=>{if(!_)return;ae.current&&(ae.current=!1,Ce(_),z("error"),setTimeout(()=>z(null),400));let $=Al(new Error(_),{code:"card_setup_widget_failed",retryable:!0});lt(()=>le.current?.($))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|