@flopay/react 1.10.0 → 1.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +7 -7
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var pd=Object.create;var Va=Object.defineProperty;var md=Object.getOwnPropertyDescriptor;var yd=Object.getOwnPropertyNames;var fd=Object.getPrototypeOf,gd=Object.prototype.hasOwnProperty;var hd=(e,t)=>{for(var n in t)Va(e,n,{get:t[n],enumerable:!0})},fl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of yd(t))!gd.call(e,o)&&o!==n&&Va(e,o,{get:()=>t[o],enumerable:!(r=md(t,o))||r.enumerable});return e};var ji=(e,t,n)=>(n=e!=null?pd(fd(e)):{},fl(t||!e||!e.__esModule?Va(n,"default",{value:e,enumerable:!0}):n,e)),Pd=e=>fl(Va({},"__esModule",{value:!0}),e);var fp={};hd(fp,{DirectPayPalButton:()=>fa,FloPayAutomaticPaymentButton:()=>Ec,FloPayCardSetup:()=>Ac,FloPayCardSetupError:()=>Ta,FloPayCheckout:()=>vi,FloPayPaymentMethodSetup:()=>Hc,FloPayProvider:()=>ha,SplitCardForm:()=>gi,VaultCardFields:()=>so,dropThirdPartyOnlyError:()=>Gc.dropThirdPartyOnlyError,useCheckout:()=>El,useFloPay:()=>Hr,usePayPalFloPay:()=>Wa});module.exports=Pd(fp);var Gc=require("@flopay/shared");var Ci=require("@flopay/js"),sr=require("@flopay/shared"),ot=require("react");var Ut=require("react/jsx-runtime");function bd(){return(0,Ut.jsxs)(Ut.Fragment,{children:[(0,Ut.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,Ut.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Ut.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Ut.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,Ut.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function vd(){return(0,Ut.jsx)(Ut.Fragment,{children:"Go back"})}function Cd(){return(0,Ut.jsx)(Ut.Fragment,{children:"Secure card checkout"})}function xo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Mo({content:e}){return(0,Ut.jsx)(Ut.Fragment,{children:e===void 0?(0,Ut.jsx)(bd,{}):e})}function Fo({content:e}){return(0,Ut.jsx)(Ut.Fragment,{children:e===void 0?(0,Ut.jsx)(vd,{}):e})}function ca({content:e}){return(0,Ut.jsx)(Ut.Fragment,{children:e===void 0?(0,Ut.jsx)(Cd,{}):e})}var wt=require("@flopay/shared"),Sd="Checkout is temporarily unavailable. Please try again later.";function $i(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof wt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function wd(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 gl(){return new wt.FloPayError(Sd,"api_error",{code:"CheckoutInitializationFailed"})}function Wi(e){return!!e?.gateways?.worldpayCorporateGateway}function Zr(e){return e?.status==="open"&&Wi(e)}function hl(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")||Zr(r))||t&&e?.data.paypal?.publishableKey)}function Pl(e,t){if(t&&(!(e instanceof wt.FloPayError)||e.type==="authentication_error"))return $i(e);if(!(e instanceof wt.FloPayError&&wd(e))){if(!t&&!(e instanceof wt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,wt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof wt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof wt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Bo(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let s={...r,...a,email:a.email?.trim()||r.email?.trim()},c=(0,wt.isCardHolderNamePlaceholder)(s.firstName,s.lastName);if(!(0,wt.isValidEmail)(s.email))return Promise.reject(new wt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let u={};for(let[p,h]of Object.entries(s)){if(c&&p.endsWith("Name")||typeof h!="string")continue;let b=h.trim();b&&(u[p]=b)}return o=e.claimCheckoutSession(t,n,{accountData:u}),o.catch(()=>{}),o}}function bl(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 Hi(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 vl(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,s)=>a+(s.overrideAmount??s.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,s)=>({uuid:`synthetic-${a.type??"item"}-${s}`,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 mo(e){if((0,wt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Ki(e,t){return t?{...e,...t}:e}function un(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,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{},...s?{sessionId:s}:{}}}function Qr(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var kd=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function eo(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of kd)if(n.test(t))return r;return e}function jr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function $r(e){return e?.status==="authorized"||e?.status==="complete"}function to(e,t){if(e.data.session)return e.data.session;let n=e.raw,r=n?.latestTransactionAttempt?.result,o=n?.status==="authorized"||r==="AUTHORIZED";return o||n?.status==="completed"||r==="SUCCESS"?{...t,status:o?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function Cl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ja(e){let t=Cl(e);return new wt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function $a(e){return e instanceof wt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Do(e){return Cl(e)?new wt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new wt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new wt.FloPayError(wt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function da(e,t){return e==="processing"||(0,wt.isMoneySettledOutcome)(e,t)}function Sl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function wl(e,t){let n=e;if((0,wt.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:s}=await n.retrieveSetupIntent(t);if(s)throw new wt.FloPayError(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new wt.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function kl(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 Gi(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 ua(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Yr=require("@flopay/js"),tt=require("@flopay/shared"),w=ji(require("react"),1);var Yi=require("react"),rr=(0,Yi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Pr=(0,Yi.createContext)({session:null,loading:!1,error:null});var Ja=require("@flopay/js"),$t=require("@flopay/shared"),Fl=require("@paypal/paypal-js"),A=require("react");var Il=require("@flopay/shared"),br=require("react"),Wr=require("react/jsx-runtime");function On(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),s=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...s||t?{lastName:s??""}:{}}}function Oo(){let[e,t]=(0,br.useState)(null),n=(0,br.useRef)(null),r=(0,br.useRef)(0),o=(0,br.useCallback)((s,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:c}),new Promise(u=>{n.current=u})),[]),a=(0,br.useCallback)(s=>{let c=n.current;n.current=null,t(null),c?.(s)},[]);return(0,br.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Lo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[s,c]=(0,br.useState)(e.email?.trim()??""),u=(0,Il.isValidEmail)(s.trim());return(0,Wr.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,Wr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Wr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Wr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:p=>c(p.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Wr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Wr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Wr.jsxs)("button",{type:"button",disabled:!u||o,onClick:()=>{n(On({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Id=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),Rd=["https://www.paypal.com","https://www.sandbox.paypal.com"];function no(e,t,n){let r=`We couldn't open ${e}. Try again or choose another payment method.`;return t?n?`${r} Open this page in your system browser, then try again.`:`${r} Allow pop-ups for this site, then try again.`:r}function Rl(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 yo(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Mr(e){if(typeof e!="object"||e===null)return;let t=e;return yo(t.code)??yo(t.type)??yo(t.name)}function No(e){if(!(typeof e!="object"||e===null))return yo(e.decline_code)}function fo(e){return typeof e!="object"||e===null?!1:yo(e.type)?.toLowerCase()==="card_error"||No(e)!==void 0}function _d(e){let t=Rl(e)?.toLowerCase()??"",n=Mr(e)?.toLowerCase()??"";return Id.has(n)?!0:/(?:popup|pop-up).{0,40}(?:block|denied|prevent)/i.test(t)||/(?:block|denied|prevent).{0,40}(?:popup|pop-up)/i.test(t)}function Xi(e){if(Mr(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=Rl(e)??"";return n.includes("No ack for postMessage init()")&&Rd.some(r=>n.includes(r))&&n.includes("10000ms")}function ro(e,t){if(fo(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=_d(e)||t.inAppBrowser&&!t.handoffObserved&&Xi(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function oo(e){return ro(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}var _l=require("@flopay/shared"),pa=require("react");function Hr(){return(0,pa.useContext)(rr).flopay}function Wa(){return(0,pa.useContext)(rr).paypalFlopay??null}function El(){return(0,pa.useContext)(Pr)}function Tl(){return(0,pa.useContext)(rr).billingApiUrl||(0,_l.resolveBillingApiUrl)()}function Kr(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 Ha(e,t,n=e.popupCapability){return e.inAppBrowser||n==="blocked"||t==="prefer_redirect"?"redirect":"popup"}function Ka(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var Al=require("@flopay/shared"),ho=require("react");function We(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 Ga=require("react"),go=typeof window>"u"?Ga.useEffect:Ga.useLayoutEffect;var Ed={"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 Td(e){return e==="stripe"||e==="paypal"?e:void 0}function Ad(e){let t=Td(e.provider),n={schemaVersion:Al.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Ed[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 Ji=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function zo(e,t){let n=(0,ho.useRef)(e);n.current=e;let r=(0,ho.useRef)(new Set),o=(0,ho.useRef)(t),a=(0,ho.useRef)(t);return go(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,ho.useCallback)(s=>{if(a.current!==t)return;let c=Ad(s);if(c){if(Ji.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}We(()=>n.current?.(c))}},[t])}var xl=require("react"),ma=(0,xl.createContext)(null);function Ya(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var xd=Symbol.for("@flopay/js.telemetry.bridge.v1"),Md=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Fd(){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 Bd(e){let t=Fd(),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 Xa(e){let t=globalThis[Md];return Bd(t?.(e)??{})}function pn(e){if(e)return e[xd]}var mn=require("react");function ya(e,t){let n=(0,mn.useRef)(0),r=(0,mn.useRef)(null),o=(0,mn.useRef)(null),a=(0,mn.useRef)(e),s=(0,mn.useRef)(t?.onHandoffObserved);(0,mn.useEffect)(()=>{a.current=e,s.current=t?.onHandoffObserved},[e,t?.onHandoffObserved]);let c=(0,mn.useCallback)((f=o.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),u=(0,mn.useCallback)(f=>{c();let S=n.current+1;return n.current=S,r.current=null,o.current={generation:S,method:f,timer:null,yieldedControl:!1},S},[c]),p=(0,mn.useCallback)(f=>{let S=o.current;return f!==void 0&&S?.generation!==f?!1:(c(S),o.current=null,(f===void 0||r.current===f)&&(r.current=null),!0)},[c]),h=(0,mn.useCallback)(f=>{let S=o.current,G=f??S?.generation??n.current;(f===void 0||S?.generation===f)&&(c(S),o.current=null),r.current=G},[c]),b=(0,mn.useCallback)(f=>r.current===(f??n.current),[]),I=(0,mn.useCallback)(f=>o.current?.generation===f&&r.current!==f,[]),k=(0,mn.useCallback)(()=>{let f=o.current;f&&(c(f),!f.yieldedControl&&(f.yieldedControl=!0,s.current?.(f.method)))},[c]),C=(0,mn.useCallback)(()=>{let f=o.current;!f?.yieldedControl||document.visibilityState!=="visible"||(c(f),f.timer=setTimeout(()=>{f.timer=null,o.current?.generation===f.generation&&(o.current=null,r.current=f.generation,a.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[c]);return(0,mn.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?C():k()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",k),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",k),window.removeEventListener("focus",C),c()}},[c,k,C]),{startAttempt:u,finishAttempt:p,invalidateAttempt:h,isAttemptInvalidated:b,isAttemptCurrent:I,generationRef:n}}var or=require("react/jsx-runtime"),Za=45,Dd=1e3,Od=11e3,Ld={width:"100%",minHeight:Za,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"},Nd={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 zd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Nd[e.kind]??null}}function Ml(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Xi(t)?"paypal_init_timeout":"paypal_init_failure"}function Ud(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 qd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Bl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:s,environment:c,currency:u,isSubscription:p,providerObjectType:h,approvalPresentation:b,onTokenizedBody:I,onComplete:k,onErrorChange:C,onDecline:f,onTechnicalFailure:S,isProcessing:G=!1,onLoadStateChange:_,onInitializationStateChange:q,allowAutomaticRetry:E=!0,onButtonClick:ne,runBeforeButtonClick:$,session:W,existingOrderId:ie,telemetry:V,telemetryContext:Be,onInstrument:Ue,debug:X=!1}){let Ae=Hr(),it=zo(Ue,e),Re=(0,A.useMemo)(()=>{if(Ae)return null;let L=Xa({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:$t.SDK_VERSION,enabled:V!==!1});return L.setCheckoutContext(Be??{}),L.beginCheckout(Be??{}),L},[n,Ae,V,Be?.checkoutMode,Be?.layout]),xe=(0,A.useMemo)(()=>pn(Ae),[Ae]);(0,A.useEffect)(()=>()=>{Re&&Re.flush().catch(()=>{}).finally(()=>Re.destroy())},[Re]);let ve=(0,A.useMemo)(()=>({error:L=>{xe?xe.error(L):Re?.error(L),it({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):Re?.log(L),it({class:"lifecycle",name:L.name,provider:L.provider})},performance:L=>{xe?xe.performance(L):Re?.performance(L)},terminal:L=>{xe?xe.terminal(L):Re?.terminal(L)},startTiming:()=>xe?.now()??Re?.now()??0,elapsed:L=>xe?.elapsed(L)??Math.max(0,(Re?.now()??L)-L)}),[it,xe,Re]),se=(0,A.useRef)(null),me=(0,A.useRef)(0),He=(0,A.useRef)(null),st=(0,A.useRef)(null),T=(0,A.useRef)(null),ye=(0,A.useContext)(ma),le=(0,A.useRef)(null);le.current||(le.current=Ya());let F=ye??le.current,Se=(0,A.useRef)(null),ce=(0,A.useRef)(!1),[De,re]=(0,A.useState)(!1),[$e,dt]=(0,A.useState)(!1),[Me,Oe]=(0,A.useState)(0),ut=(0,A.useRef)(0),[Y,J]=(0,A.useState)(!1),mt=(0,A.useRef)(!1),gt=(0,A.useRef)(!1),[Ie,ft]=(0,A.useState)(!1),[U,we]=(0,A.useState)(!1),{request:lt,collect:Z,finish:qe}=Oo(),St=(0,A.useRef)({sessionId:e,required:!(0,$t.isValidEmail)(r?.trim()||W?.customer?.email?.trim())});St.current.sessionId!==e&&(St.current={sessionId:e,required:!(0,$t.isValidEmail)(r?.trim()||W?.customer?.email?.trim())});let Ze=St.current.required,H=(0,A.useMemo)(()=>n.replace(/\/+$/,""),[n]),g=W?.gateways?.paypal?.providerObjectType??h,v=g??(p?"subscription":"order"),[ee]=(0,A.useState)(Kr),de=W?.gateways?.paypal?.approvalPresentation??b,Xe=Ka(ee,de==="app_switch"?"app_switch":void 0,v),kt=g==="order"||g==="setup_token",Qe=(0,A.useMemo)(()=>JSON.stringify([H,s,u,c??"",v,kt,Xe,e,ie??""]),[H,s,u,c,ie,v,kt,Xe,e]),ae=(0,A.useRef)(Qe),yt=ae.current!==Qe,It=(0,A.useRef)(X),qt=(0,A.useRef)(null),[Ke,Lt]=(0,A.useState)([]),Ge=(0,A.useCallback)(L=>{It.current&&Lt(rt=>[...rt,`${new Date().toISOString().slice(11,23)} ${L}`])},[]);(0,A.useEffect)(()=>{It.current=X,X&&Ge("debug:enabled"),qt.current?.setEnabled(X)},[Ge,X]);let zn=(0,A.useRef)(I),Tn=(0,A.useRef)(k),Dt=(0,A.useRef)(C),Rn=(0,A.useRef)(f),Un=(0,A.useRef)(S),qn=(0,A.useRef)(ne),on=(0,A.useRef)(_),Ee=(0,A.useRef)(q),Rt=(0,A.useRef)(a),Mt=(0,A.useRef)($),wn=(0,A.useRef)(W),Ot=(0,A.useRef)(r),Yn=(0,A.useRef)(o),yn=(0,A.useRef)(t),Ht=(0,A.useRef)(null),ln=(0,A.useRef)(new Map),Xn=(0,A.useRef)(new Map),fn=(0,A.useRef)(!1);(0,A.useEffect)(()=>(fn.current=!0,()=>{fn.current=!1}),[]),(0,A.useEffect)(()=>{zn.current=I},[I]),(0,A.useEffect)(()=>{Rt.current=a},[a]),(0,A.useEffect)(()=>{Tn.current=k},[k]),(0,A.useEffect)(()=>{Dt.current=C},[C]),(0,A.useEffect)(()=>{Rn.current=f},[f]),(0,A.useEffect)(()=>{Un.current=S},[S]),(0,A.useEffect)(()=>{qn.current=ne},[ne]),(0,A.useEffect)(()=>{on.current=_},[_]),(0,A.useEffect)(()=>{Ee.current=q},[q]),(0,A.useEffect)(()=>{Mt.current=$},[$]),(0,A.useEffect)(()=>{wn.current=W},[W]),(0,A.useEffect)(()=>{Ot.current=r},[r]),(0,A.useEffect)(()=>{Yn.current=o},[o]),(0,A.useEffect)(()=>{yn.current=t},[t]),(0,A.useEffect)(()=>{ut.current=Me},[Me]),(0,A.useEffect)(()=>{Y&&Se.current?.focus()},[Y,Me]);let _t=(0,A.useCallback)(()=>{window.setTimeout(()=>{Se.current?.focus()},0)},[]),Qt=(0,A.useCallback)(()=>{re(!1),Oe(L=>L+1)},[]),gn=(0,A.useCallback)(()=>{J(!1),(se.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??se.current)?.focus?.()},[]);(0,A.useEffect)(()=>{!De||!ce.current||(ce.current=!1,gn())},[gn,De,Me]);let Nt=(0,A.useCallback)((L,rt)=>{let he=rt?.popupBlocked??oo(L);he&&F.markBlocked();let Jn=no("PayPal",he,ee.inAppBrowser),Pn=Un.current;if(Pn){let Gt=he&&ee.inAppBrowser?new $t.FloPayError(Jn,"api_error",{code:rt?.code??"paypal_popup_blocked"}):L;Pn("paypal",Gt,rt);return}Dt.current?.(Jn)},[F,ee.inAppBrowser]),en=(0,A.useCallback)(L=>{let rt=He.current,he=st.current;rt===null||!he||(ve.log({...he,popupCapability:F.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),ve.performance({...he,popupCapability:F.current(),stage:"overlay_return",durationMs:ve.elapsed(rt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),He.current=null)},[F,ve]),Kt=(0,A.useCallback)((L,rt,he)=>{let Jn=st.current;en("overlay_timeout"),Jn&&ve.error({...Jn,popupCapability:F.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Nt(rt,{...he,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Xe,terminalReason:"overlay_timeout"}),J(!0),Qt(),_t()},[en,_t,Nt,F,Xe,Qt,ve]),hn=(0,A.useCallback)(()=>{F.markAvailable();let L=st.current;L&&(T.current=L.attempt,ve.log({...L,popupCapability:F.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[F,ve]),{finishAttempt:vt,generationRef:ue,invalidateAttempt:Vn,isAttemptCurrent:jn,isAttemptInvalidated:Sr,startAttempt:kn}=ya(Kt,{onHandoffObserved:hn}),cn=(0,A.useCallback)(()=>(J(!1),kn("paypal")),[kn]),An=(0,A.useCallback)(L=>{Vn(L?.generation),L?.showRetry&&J(!0),L?.remount&&Qt(),L?.focus!==!1&&_t()},[_t,Vn,Qt]),Le=L=>{let rt=Ht.current;return rt&&Xn.current.set(L,rt),L};(0,A.useEffect)(()=>{ae.current!==Qe&&(ae.current=Qe,mt.current=!1,gt.current=!1,re(!1),dt(!1),ft(!1),Ee.current?.("loading"))},[Qe]),(0,A.useEffect)(()=>{We(()=>on.current?.(De&&!Ie))},[De,Ie]);let Ct=(0,$t.normalizeGatewayEnvironment)(c);(0,A.useEffect)(()=>{let L={attempt:ue.current+1,inAppBrowser:ee.inAppBrowser,appFamily:ee.appFamily,popupCapability:F.current(),presentationMode:Xe},rt=()=>({...st.current??L,popupCapability:F.current()}),he={error:m=>ve.error({...m,...rt()}),log:m=>ve.log({...m,...rt()}),performance:m=>ve.performance({...m,...rt()}),terminal:m=>ve.terminal({...m,...rt()}),startTiming:ve.startTiming,elapsed:ve.elapsed},Jn=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",Pn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Ge(`mount clientId=${Jn} env=${c??"(unset)"}\u2192${Ct??"live"} ccy=${u} sub=${p}`),Ge(`ua=${Pn.slice(0,80)}${Pn.length>80?"\u2026":""}`),!s){Ge("FAIL: clientId empty \u2014 gateway misconfigured"),ft(!0),he.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(!se.current){Ge("FAIL: containerRef not attached");return}me.current=he.startTiming(),he.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Gt=!1,Zn=!1,pt=()=>Gt||Zn,Xr,Yt=!1,bn=()=>{Xr=(0,$t.generateIdempotencyKey)(),Xr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Yt=!0},Nr=null,zr=!1,xn=null,tn=!1,wr=()=>{!xn||tn||(tn=!0,xn.close().catch(()=>{}))},Mn=!1,Ur=!1,Fn=se.current,kr=null,Ir=null,cr=[],Qn=null,er=!1,Bt=!1,dr=null,_n=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let P=m.getBoundingClientRect();return`${Math.round(P.width)}\xD7${Math.round(P.height)}`},tr=m=>{if(!m)return"(empty)";try{let P=new URL(m,typeof window>"u"?"https://localhost":window.location.href),N=P.pathname.toLowerCase();return N.includes("checkcaptcha")||N.includes("captcha")?`CAPTCHA(${P.host}${N})`:N.includes("risk")||N.includes("challenge")?`RISK(${P.host}${N})`:N.includes("smart/buttons")?`smart-buttons(${P.host})`:`${P.host}${N}`.slice(0,100)}catch{return m.slice(0,80)}},Rr=m=>{let P=m.getAttribute("src"),N=m.getAttribute("srcdoc"),j=m.getAttribute("name"),be=m.getAttribute("sandbox"),oe=[];return P&&oe.push(`src=${tr(P)}`),N&&oe.push(`srcdoc[${N.length}ch]`),!P&&!N&&oe.push("src=(empty) srcdoc=(empty)"),j&&oe.push(`name=${j.slice(0,40)}`),be!==null&&oe.push(`sandbox="${be.slice(0,40)}"`),oe.join(" ")},ht=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let P=m.contentDocument;if(!P)return"cd=null";let N=P.body?.children.length??0,j=P.body?.innerHTML.length??0,be=P.head?.innerHTML.length??0;return`cd=same-origin readyState=${P.readyState} body[${N}children,${j}ch] head[${be}ch]`}catch(P){return`cd=cross-origin(${P.message.slice(0,30)})`}},an=[],nn=m=>{if(pt())return;let P=m.message??String(m.error??"(no message)");P&&(P.toLowerCase().includes("paypal")||P.toLowerCase().includes("zoid")||P.toLowerCase().includes("postrobot")||P.toLowerCase().includes("storage"))&&(Ge(`window:error ${P.slice(0,140)}`),an.push(P))},qr=m=>{if(pt())return;let P=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");P&&(P.toLowerCase().includes("paypal")||P.toLowerCase().includes("zoid")||P.toLowerCase().includes("postrobot")||P.toLowerCase().includes("storage"))&&(Ge(`window:rejection ${P.slice(0,140)}`),an.push(P))},$n={value:0},Jr=()=>{kr?.disconnect(),kr=null,Ir?.disconnect(),Ir=null;for(let m of cr.splice(0))clearTimeout(m);Bt=!1,er&&typeof window<"u"&&(window.removeEventListener("error",nn),window.removeEventListener("unhandledrejection",qr)),er=!1},ur=()=>{if(!(er||pt()||Mn)){if(er=!0,an.length=0,$n.value=0,typeof window<"u"&&(window.addEventListener("error",nn),window.addEventListener("unhandledrejection",qr)),typeof PerformanceObserver<"u")try{Ir=new PerformanceObserver(m=>{if(!pt())for(let P of m.getEntries()){if(!P.name.toLowerCase().includes("paypal"))continue;$n.value+=1;let N=Math.round(P.duration);Ge(`net ${N}ms ${P.name.slice(0,90)}`)}}),Ir.observe({type:"resource",buffered:!0})}catch{}dr?.()}},pr=()=>{Qn&&(clearTimeout(Qn),Qn=null)},vn=()=>{Jr(),pr()},mr={setEnabled:m=>{m?ur():Jr()}};qt.current=mr,It.current&&ur();let Vr=m=>{if(!m)return!1;let P=m.toLowerCase();return P.includes("zoid destroyed")||P.includes("destroyed all components")||P.includes("window closed")||P.includes("detected container element removed")},En=m=>{if(pt()||Vr(m))return;let P=eo(m)??m;We(()=>Dt.current?.(P))},D=(m,P)=>{if(Gt||zr)return;zr=!0,Zn=!0,vn(),wr();let N=zd({kind:m,generationActive:!0,automaticRetryAllowed:E,automaticRetryUsed:mt.current});if(N.action==="retry"){mt.current=!0,re(!1),we(!1),dt(!0),Ee.current?.("retrying"),Nr=setTimeout(()=>{Gt||Oe(j=>j+1)},Dd);return}if(re(!1),we(!1),dt(!1),ft(!0),N.action!=="ignore"){if(Ee.current?.("exhausted"),N.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",P);return}if(N.report){let j=ro({code:Ml(m,P),message:P},{inAppBrowser:ee.inAppBrowser,handoffObserved:!1});j.popupBlocked&&F.markBlocked(),he.error({errorCode:j.popupBlocked?j.errorCode:N.report.errorCode,stage:N.report.stage,operationOutcome:N.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:j.terminalReason})}gt.current||(gt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Ml(m,P)))}};ft(!1);let z=async(m,P=Ht.current)=>{if(pt())return;let N=P?.sessionId??e;if(zn.current){await zn.current(m,{sessionId:N,accountPatch:P?.accountPatch,nonce:P?.nonce});return}let j=he.startTiming();he.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let be=()=>{he.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),he.performance({stage:"processing",durationMs:he.elapsed(j),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let oe=wn.current,et=P?.accountPatch?.email??Ot.current,Tt=P?.accountPatch?.userId??oe?.customer?.id??oe?.accountData?.userId??"",M=P?.accountPatch?.firstName??oe?.customer?.firstName??oe?.accountData?.firstName,_e=P?.accountPatch?.lastName??oe?.customer?.lastName??oe?.accountData?.lastName,ke=await new Ja.PaymentAPI(H,{telemetry:!1}).processPayment(Tt,{sessionId:N,nonce:P?.nonce??yn.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:Tt,email:et??oe?.customer?.email??"",...M?{firstName:M}:{},..._e?{lastName:_e}:{},country:P?.accountPatch?.country??oe?.customer?.country??oe?.accountData?.country??void 0,zip:P?.accountPatch?.zip??oe?.customer?.zip??oe?.accountData?.zip??void 0}});if(ke.ok){if(Zn||Gt&&fn.current)return;be(),he.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),We(()=>Tn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(pt())return;let K=await ke.json().catch(()=>null),fe=K?.message??"PayPal payment failed.",x=eo(fe)??fe;be(),ke.status===400&&(typeof K?.declineCode=="string"||!Array.isArray(K?.fields))?he.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ke.status===400||ke.status===422?he.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):he.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:qd(ke.status),failureCategory:ke.status>=500?"server_error":void 0}),En(x),We(()=>Rn.current?.(un("paypal",x,{code:K?.code,declineCode:K?.declineCode})));return}catch(oe){if(pt())return;be(),he.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let et=oe instanceof Error?oe.message:"PayPal payment failed.",Tt=eo(et)??et;En(Tt),We(()=>Rn.current?.(un("paypal",Tt)));return}},B=()=>new $t.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Pe=m=>pt()?Promise.reject(B()):Promise.resolve(m),Ve=async m=>{if(pt())throw B();Yt||bn();let P=Ht.current,N=P?.sessionId??e,j=P?.nonce??yn.current;he.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let be;try{be=await new Ja.PaymentAPI(H,{telemetry:!1}).createSessionIntent(N,j??"",kt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:$t.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:v==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Xr})}catch(oe){throw he.error({...(0,$t.classifyTelemetryFailure)(oe,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),oe}if(pt())throw B();if(be.provider!=="paypal"||be.providerObjectType!==v)throw new Error(m);return he.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),be.providerObjectId},Pt=(m,P)=>{let N=P?.nonce??yn.current;if(!N)return;let j=P?.sessionId??e,be=No(m)??Mr(m)??"provider_declined";new Ja.PaymentAPI(H,{telemetry:!1}).reportSessionIntentDecline(j,N,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:be}).catch(()=>{})},Ce=Me;Ge("loadScript:scheduled (deferred 1 tick)");let je=null,Q=setTimeout(()=>{if(Gt){Ge("loadScript:skipped (cancelled before defer ran)");return}Ge("loadScript:start");let m=Ct==="live"?"production":Ct,P={};v==="subscription"?P={intent:"subscription",vault:!0}:v==="order"&&(P={intent:"capture"}),je=(0,Fl.loadScript)({clientId:s,currency:u,...P,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let N=!1;je.then(j=>{if(N=!0,Ge(`loadScript:resolved inactive=${pt()} ns=${!!j} buttons=${!!j?.Buttons}`),pt())return;if(!j?.Buttons){Ge("FAIL: namespace missing Buttons factory"),D("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}he.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),he.performance({stage:"provider_ready",durationMs:he.elapsed(me.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),he.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let be=async(ke,K)=>{if(pt()||ut.current!==Ce)return;let fe=ke.vaultSetupToken??ke.subscriptionID??ke.orderID??"",x=fe?Xn.current.get(fe):ln.current.get(Ce);if(!(!x||!jn(x.generation))&&vt(x.generation)){Xn.current.delete(fe),ln.current.delete(x.surfaceKey),en("approved");try{if(we(!0),We(()=>Dt.current?.(null)),!fe)throw new $t.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ye=wn.current,At=mo(Yn.current??[Ye?.customer?.firstName,Ye?.customer?.lastName].filter(Boolean).join(" ")),Ne=On({email:x.accountPatch?.email?.trim()||Ot.current?.trim()||Ye?.customer?.email?.trim(),firstName:x.accountPatch?.firstName?.trim()||At.firstName,lastName:x.accountPatch?.lastName?.trim()||At.lastName});if(!(0,$t.isValidEmail)(Ne.email)||!(Ne.firstName||Ne.lastName))try{let _r=Ud(await K?.order?.get?.());Ne=On({email:_r.email||Ne.email,firstName:_r.firstName||Ne.firstName,lastName:_r.lastName||Ne.lastName})}catch{}if((Rt.current||Ze)&&!(0,$t.isValidEmail)(Ne.email)){let _r=await Z("PayPal",Ne);if(!_r)return;Ne=_r}(0,$t.isValidEmail)(Ne.email)&&(x.accountPatch=On({...x.accountPatch,...Ne}),await Rt.current?.(Ne));let In;v==="setup_token"?In={id:fe,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:$t.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:kt?In={id:fe,isPaypal:!0,gateway:"paypal",paymentMethodType:$t.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:In={id:fe,isPaypal:!0},await z(In,x)}catch(Ye){En(Ye instanceof Error?Ye.message:"PayPal capture failed.")}finally{pt()||we(!1)}}},oe=ke=>{let K=ie?()=>Pe(ie):()=>Ve(ke);return async()=>Le(await K())},et=j.Buttons({style:{layout:"horizontal",height:Za,tagline:!1},...Xe==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ke,K)=>{if(pt()){await K.reject();return}bn();let fe=Mt.current,x={};if(fe)try{let Ne=await fe("paypal");if(pt()){await K.reject();return}if(!Ne.proceed){Ht.current=null,ln.current.delete(Ce),await K.reject();return}x={sessionId:Ne.sessionId,accountPatch:Ne.accountPatch,nonce:Ne.nonce}}catch(Ne){Ge(`onClick:runBeforeButtonClick rejected msg=${(Ne instanceof Error?Ne.message:String(Ne)).slice(0,120)}`),Ht.current=null,ln.current.delete(Ce),await K.reject();return}We(()=>qn.current?.("paypal"));let Ye=cn(),At={generation:Ye,surfaceKey:Ce,...x};Ht.current=At,ln.current.set(Ce,At),st.current={...L,attempt:Ye},await K.resolve(),he.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),he.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),He.current=he.startTiming()},createOrder:v==="order"?oe("Failed to create PayPal order."):void 0,createSubscription:v==="subscription"?oe("Failed to create PayPal subscription."):void 0,createVaultSetupToken:v==="setup_token"?async()=>Le(await Ve("Failed to create PayPal setup token.")):void 0,onApprove:be,onCancel:()=>{if(pt())return;let ke=ln.current.get(Ce)??Ht.current;ke&&ln.current.delete(ke.surfaceKey),Ht.current=null,en("cancelled"),he.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ce.current=!0,An({generation:ke?.generation,remount:!0,focus:!1})},onError:ke=>{if(pt()||ut.current!==Ce)return;let K=ke instanceof Error?ke.message:"PayPal failed to render.";if(Ge(`onError rendered=${Mn} msg=${K.slice(0,120)}`),Mn){let fe=ln.current.get(Ce)??Ht.current;if(fe&&!jn(fe.generation)||!fe&&Sr())return;if(Vr(K)){vt(fe?.generation);return}let{errorCode:x,popupBlocked:Ye,providerDeclined:At,terminalReason:Ne}=ro(ke,{inAppBrowser:ee.inAppBrowser,handoffObserved:fe!=null&&T.current===fe.generation});if(Ye&&F.markBlocked(),en(Ne),At){he.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ne}),Pt(ke,fe),We(()=>Rn.current?.(un("paypal",K))),fe&&ln.current.delete(fe.surfaceKey),Ht.current=null,vt(fe?.generation);return}he.error({errorCode:x,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ne}),fe&&ln.current.delete(fe.surfaceKey),Ht.current=null,An({generation:fe?.generation,remount:!0,showRetry:!0,focus:!0}),Nt(ke,{code:"paypal_runtime_failed",popupBlocked:Ye,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Xe,terminalReason:Ne});return}D(Vr(K)?"teardown":"pre_ready_callback",K)}}),Tt=et.isEligible();if(Ge(`isEligible=${Tt}`),he.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Tt){re(!1),D("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ur=!0,xn=et,dr=()=>{if(!er||Bt||pt()||Mn)return;Bt=!0,Ge(`container:dims ${_n(Fn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(kr=new MutationObserver(K=>{if(!pt()){for(let fe of K)if(fe.type==="childList")fe.addedNodes.forEach(x=>{if(!(x instanceof Element))return;let Ye=x.tagName.toLowerCase(),At=(x.getAttribute("title")??"").slice(0,40),Ne=Ye==="iframe"?` ${Rr(x)}`:"";Ge(`child+ ${Ye}${At?` title="${At}"`:""}${Ne} dims=${_n(x)}`)});else if(fe.type==="attributes"&&fe.target instanceof Element){let x=fe.target;if(x.tagName.toLowerCase()!=="iframe")continue;let Ye=fe.attributeName;(Ye==="src"||Ye==="srcdoc")&&Ge(`attr~ iframe ${Ye}=${Ye==="srcdoc"?`[${(x.getAttribute("srcdoc")??"").length}ch]`:tr(x.getAttribute("src"))} dims=${_n(x)}`)}}}),kr.observe(Fn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ke=K=>{if(pt()||Mn)return;let fe=Fn.querySelectorAll("iframe"),x=typeof document<"u"&&"hasStorageAccess"in document;Ge(`watchdog:${K} container=${_n(Fn)} children=${Fn.childElementCount} iframes=${fe.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${x} paypalNetRequests=${$n.value}`),fe.forEach((Ye,At)=>{let Ne=(Ye.getAttribute("title")??"").slice(0,40);Ge(` iframe[${At}] ${_n(Ye)}${Ne?` title="${Ne}"`:""} ${Rr(Ye)}`);let In=ht(Ye);In&&Ge(` ${In}`)}),an.length===0&&Ge(" (no PayPal/zoid window errors captured)")};cr.push(setTimeout(()=>ke("3s"),3e3)),cr.push(setTimeout(()=>ke("8s"),8e3)),cr.push(setTimeout(()=>ke("15s"),15e3))},dr(),Ge("render:start");let _e=he.startTiming();Qn=setTimeout(()=>{pt()||Mn||(Ge("watchdog:11s retryable render timeout"),D("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Od);let Ft=et.render(Fn);(async()=>{try{if(await Ft,Ge(`render:resolved inactive=${pt()}`),vn(),pt()){wr();return}Mn=!0,re(!0),dt(!1),Ee.current?.("ready"),he.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),he.performance({stage:"checkout_render",durationMs:he.elapsed(_e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ke){let K=ke instanceof Error?ke.message:"PayPal failed to render.";Ge(`render:rejected msg=${K.slice(0,120)}`),vn(),D(Vr(K)?"teardown":"render_rejected",K)}})()}).catch(j=>{let be=j instanceof Error?j.message:"PayPal operation failed.";Ge(`provider:failed msg=${be.slice(0,120)}`);let oe="script_rejected";N&&Vr(be)?oe="teardown":N&&Ur&&(oe="render_rejected"),D(oe,be)})},0);return()=>{Gt=!0,clearTimeout(Q),Nr&&clearTimeout(Nr),vn(),qt.current===mr&&(qt.current=null),wr(),He.current=null,st.current=null}},[E,H,s,u,c,v,Xe,kt,e,ie,Me,ve,Z,Ze,Ge,en]);let ge=X?(0,or.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ie?"#fef2f2":"#f3f4f6",border:`1px solid ${Ie?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${De} failed=${Ie})`,Ke.length===0?`
|
|
1
|
+
"use strict";var md=Object.create;var Va=Object.defineProperty;var yd=Object.getOwnPropertyDescriptor;var fd=Object.getOwnPropertyNames;var gd=Object.getPrototypeOf,hd=Object.prototype.hasOwnProperty;var Pd=(e,t)=>{for(var n in t)Va(e,n,{get:t[n],enumerable:!0})},fl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fd(t))!hd.call(e,o)&&o!==n&&Va(e,o,{get:()=>t[o],enumerable:!(r=yd(t,o))||r.enumerable});return e};var ji=(e,t,n)=>(n=e!=null?md(gd(e)):{},fl(t||!e||!e.__esModule?Va(n,"default",{value:e,enumerable:!0}):n,e)),bd=e=>fl(Va({},"__esModule",{value:!0}),e);var gp={};Pd(gp,{DirectPayPalButton:()=>fa,FloPayAutomaticPaymentButton:()=>Tc,FloPayCardSetup:()=>Mc,FloPayCardSetupError:()=>Ta,FloPayCheckout:()=>vi,FloPayPaymentMethodSetup:()=>Kc,FloPayProvider:()=>ha,SplitCardForm:()=>gi,VaultCardFields:()=>so,dropThirdPartyOnlyError:()=>Yc.dropThirdPartyOnlyError,useCheckout:()=>El,useFloPay:()=>Hr,usePayPalFloPay:()=>Wa});module.exports=bd(gp);var Yc=require("@flopay/shared");var Ci=require("@flopay/js"),ar=require("@flopay/shared"),it=require("react");var zt=require("react/jsx-runtime");function vd(){return(0,zt.jsxs)(zt.Fragment,{children:[(0,zt.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,zt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,zt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,zt.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,zt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Cd(){return(0,zt.jsx)(zt.Fragment,{children:"Go back"})}function Sd(){return(0,zt.jsx)(zt.Fragment,{children:"Secure card checkout"})}function Mo(e){return e!==void 0&&(e===""||e===null||e===!1)}function xo({content:e}){return(0,zt.jsx)(zt.Fragment,{children:e===void 0?(0,zt.jsx)(vd,{}):e})}function Fo({content:e}){return(0,zt.jsx)(zt.Fragment,{children:e===void 0?(0,zt.jsx)(Cd,{}):e})}function ca({content:e}){return(0,zt.jsx)(zt.Fragment,{children:e===void 0?(0,zt.jsx)(Sd,{}):e})}var St=require("@flopay/shared"),wd="Checkout is temporarily unavailable. Please try again later.";function $i(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof St.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function kd(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 gl(){return new St.FloPayError(wd,"api_error",{code:"CheckoutInitializationFailed"})}function Wi(e){return!!e?.gateways?.worldpayCorporateGateway}function Zr(e){return e?.status==="open"&&Wi(e)}function hl(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")||Zr(r))||t&&e?.data.paypal?.publishableKey)}function Pl(e,t){if(t&&(!(e instanceof St.FloPayError)||e.type==="authentication_error"))return $i(e);if(!(e instanceof St.FloPayError&&kd(e))){if(!t&&!(e instanceof St.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,St.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof St.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof St.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Bo(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let s={...r,...a,email:a.email?.trim()||r.email?.trim()},d=(0,St.isCardHolderNamePlaceholder)(s.firstName,s.lastName);if(!(0,St.isValidEmail)(s.email))return Promise.reject(new St.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[u,f]of Object.entries(s)){if(d&&u.endsWith("Name")||typeof f!="string")continue;let P=f.trim();P&&(p[u]=P)}return o=e.claimCheckoutSession(t,n,{accountData:p}),o.catch(()=>{}),o}}function bl(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 Hi(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 vl(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,s)=>a+(s.overrideAmount??s.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,s)=>({uuid:`synthetic-${a.type??"item"}-${s}`,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 mo(e){if((0,St.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Ki(e,t){return t?{...e,...t}:e}function un(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,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{},...s?{sessionId:s}:{}}}function Qr(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var Id=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function eo(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Id)if(n.test(t))return r;return e}function jr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function $r(e){return e?.status==="authorized"||e?.status==="complete"}function to(e,t){if(e.data.session)return e.data.session;let n=e.raw,r=n?.latestTransactionAttempt?.result,o=n?.status==="authorized"||r==="AUTHORIZED";return o||n?.status==="completed"||r==="SUCCESS"?{...t,status:o?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function Cl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ja(e){let t=Cl(e);return new St.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function $a(e){return e instanceof St.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Do(e){return Cl(e)?new St.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new St.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new St.FloPayError(St.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function da(e,t){return e==="processing"||(0,St.isMoneySettledOutcome)(e,t)}function Sl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function wl(e,t){let n=e;if((0,St.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:s}=await n.retrieveSetupIntent(t);if(s)throw new St.FloPayError(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new St.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function kl(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 Gi(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 ua(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Yr=require("@flopay/js"),ot=require("@flopay/shared"),w=ji(require("react"),1);var Yi=require("react"),tr=(0,Yi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Pr=(0,Yi.createContext)({session:null,loading:!1,error:null});var Ja=require("@flopay/js"),jt=require("@flopay/shared"),Fl=require("@paypal/paypal-js"),M=require("react");var Il=require("@flopay/shared"),br=require("react"),Wr=require("react/jsx-runtime");function On(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),s=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...s||t?{lastName:s??""}:{}}}function Oo(){let[e,t]=(0,br.useState)(null),n=(0,br.useRef)(null),r=(0,br.useRef)(0),o=(0,br.useCallback)((s,d)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:d}),new Promise(p=>{n.current=p})),[]),a=(0,br.useCallback)(s=>{let d=n.current;n.current=null,t(null),d?.(s)},[]);return(0,br.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Lo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[s,d]=(0,br.useState)(e.email?.trim()??""),p=(0,Il.isValidEmail)(s.trim());return(0,Wr.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,Wr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Wr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Wr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:u=>d(u.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Wr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Wr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Wr.jsxs)("button",{type:"button",disabled:!p||o,onClick:()=>{n(On({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Rd=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),_d=["https://www.paypal.com","https://www.sandbox.paypal.com"];function no(e,t,n){let r=`We couldn't open ${e}. Try again or choose another payment method.`;return t?n?`${r} Open this page in your system browser, then try again.`:`${r} Allow pop-ups for this site, then try again.`:r}function Rl(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 yo(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Mr(e){if(typeof e!="object"||e===null)return;let t=e;return yo(t.code)??yo(t.type)??yo(t.name)}function No(e){if(!(typeof e!="object"||e===null))return yo(e.decline_code)}function fo(e){return typeof e!="object"||e===null?!1:yo(e.type)?.toLowerCase()==="card_error"||No(e)!==void 0}function Ed(e){let t=Rl(e)?.toLowerCase()??"",n=Mr(e)?.toLowerCase()??"";return Rd.has(n)?!0:/(?:popup|pop-up).{0,40}(?:block|denied|prevent)/i.test(t)||/(?:block|denied|prevent).{0,40}(?:popup|pop-up)/i.test(t)}function Xi(e){if(Mr(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=Rl(e)??"";return n.includes("No ack for postMessage init()")&&_d.some(r=>n.includes(r))&&n.includes("10000ms")}function ro(e,t){if(fo(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=Ed(e)||t.inAppBrowser&&!t.handoffObserved&&Xi(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function oo(e){return ro(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}var _l=require("@flopay/shared"),pa=require("react");function Hr(){return(0,pa.useContext)(tr).flopay}function Wa(){return(0,pa.useContext)(tr).paypalFlopay??null}function El(){return(0,pa.useContext)(Pr)}function Tl(){return(0,pa.useContext)(tr).billingApiUrl||(0,_l.resolveBillingApiUrl)()}function Kr(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 Ha(e,t,n=e.popupCapability){return e.inAppBrowser||n==="blocked"||t==="prefer_redirect"?"redirect":"popup"}function Ka(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var Al=require("@flopay/shared"),ho=require("react");function Ke(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 Ga=require("react"),go=typeof window>"u"?Ga.useEffect:Ga.useLayoutEffect;var Td={"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 Ad(e){return e==="stripe"||e==="paypal"?e:void 0}function Md(e){let t=Ad(e.provider),n={schemaVersion:Al.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Td[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 Ji=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function zo(e,t){let n=(0,ho.useRef)(e);n.current=e;let r=(0,ho.useRef)(new Set),o=(0,ho.useRef)(t),a=(0,ho.useRef)(t);return go(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,ho.useCallback)(s=>{if(a.current!==t)return;let d=Md(s);if(d){if(Ji.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}Ke(()=>n.current?.(d))}},[t])}var Ml=require("react"),ma=(0,Ml.createContext)(null);function Ya(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var xd=Symbol.for("@flopay/js.telemetry.bridge.v1"),Fd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Bd(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function Dd(e){let t=Bd(),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 Xa(e){let t=globalThis[Fd];return Dd(t?.(e)??{})}function pn(e){if(e)return e[xd]}var tn=require("react");function ya(e,t){let n=(0,tn.useRef)(0),r=(0,tn.useRef)(null),o=(0,tn.useRef)(null),a=(0,tn.useRef)(e),s=(0,tn.useRef)(t?.onHandoffObserved),d=(0,tn.useRef)(t?.defersMissingTerminal),p=(0,tn.useRef)(t?.onMissingTerminalDeferred);(0,tn.useEffect)(()=>{a.current=e,s.current=t?.onHandoffObserved,d.current=t?.defersMissingTerminal,p.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let u=(0,tn.useCallback)((b=o.current)=>{b?.timer&&(clearTimeout(b.timer),b.timer=null)},[]),f=(0,tn.useCallback)(b=>{u();let C=n.current+1;return n.current=C,r.current=null,o.current={generation:C,method:b,timer:null,yieldedControl:!1},C},[u]),P=(0,tn.useCallback)(b=>{let C=o.current;return b!==void 0&&C?.generation!==b?!1:(u(C),o.current=null,(b===void 0||r.current===b)&&(r.current=null),!0)},[u]),k=(0,tn.useCallback)(b=>{let C=o.current,j=b??C?.generation??n.current;(b===void 0||C?.generation===b)&&(u(C),o.current=null),r.current=j},[u]),R=(0,tn.useCallback)(b=>r.current===(b??n.current),[]),S=(0,tn.useCallback)(b=>o.current?.generation===b&&r.current!==b,[]),T=(0,tn.useCallback)(()=>{let b=o.current;b&&(u(b),!b.yieldedControl&&(b.yieldedControl=!0,s.current?.(b.method)))},[u]),E=(0,tn.useCallback)(()=>{let b=o.current;!b?.yieldedControl||document.visibilityState!=="visible"||(u(b),b.timer=setTimeout(()=>{if(b.timer=null,o.current?.generation===b.generation){if(d.current?.(b.method)){p.current?.(b.method,b.generation);return}o.current=null,r.current=b.generation,a.current(b.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},600))},[u]);return(0,tn.useEffect)(()=>{let b=()=>{document.visibilityState==="visible"?E():T()};return document.addEventListener("visibilitychange",b),window.addEventListener("blur",T),window.addEventListener("focus",E),()=>{document.removeEventListener("visibilitychange",b),window.removeEventListener("blur",T),window.removeEventListener("focus",E),u()}},[u,T,E]),{startAttempt:f,finishAttempt:P,invalidateAttempt:k,isAttemptInvalidated:R,isAttemptCurrent:S,generationRef:n}}var nr=require("react/jsx-runtime"),Za=45,Od=1e3,Ld=11e3,Nd={width:"100%",minHeight:Za,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"},zd={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 Ud(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:zd[e.kind]??null}}function xl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Xi(t)?"paypal_init_timeout":"paypal_init_failure"}function qd(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function Vd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Bl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:s,environment:d,currency:p,isSubscription:u,providerObjectType:f,approvalPresentation:P,onTokenizedBody:k,onComplete:R,onErrorChange:S,onDecline:T,onTechnicalFailure:E,isProcessing:b=!1,onLoadStateChange:C,onInitializationStateChange:j,allowAutomaticRetry:_=!0,onButtonClick:re,runBeforeButtonClick:q,session:K,existingOrderId:le,telemetry:$,telemetryContext:Oe,onInstrument:Ue,debug:J=!1}){let xe=Hr(),lt=zo(Ue,e),Ee=(0,M.useMemo)(()=>{if(xe)return null;let F=Xa({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:jt.SDK_VERSION,enabled:$!==!1});return F.setCheckoutContext(Oe??{}),F.beginCheckout(Oe??{}),F},[n,xe,$,Oe?.checkoutMode,Oe?.layout]),Fe=(0,M.useMemo)(()=>pn(xe),[xe]);(0,M.useEffect)(()=>()=>{Ee&&Ee.flush().catch(()=>{}).finally(()=>Ee.destroy())},[Ee]);let be=(0,M.useMemo)(()=>({error:F=>{Fe?Fe.error(F):Ee?.error(F),lt({class:"technical_error",errorCode:F.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":F.errorCode,requestCategory:F.requestCategory,provider:F.provider})},log:F=>{Fe?Fe.log(F):Ee?.log(F),lt({class:"lifecycle",name:F.name,provider:F.provider})},performance:F=>{Fe?Fe.performance(F):Ee?.performance(F)},terminal:F=>{Fe?Fe.terminal(F):Ee?.terminal(F)},startTiming:()=>Fe?.now()??Ee?.now()??0,elapsed:F=>Fe?.elapsed(F)??Math.max(0,(Ee?.now()??F)-F)}),[lt,Fe,Ee]),ce=(0,M.useRef)(null),me=(0,M.useRef)(0),Ge=(0,M.useRef)(null),ct=(0,M.useRef)(null),A=(0,M.useRef)(null),fe=(0,M.useContext)(ma),de=(0,M.useRef)(null);de.current||(de.current=Ya());let D=fe??de.current,Se=(0,M.useRef)(null),ue=(0,M.useRef)(!1),[Le,oe]=(0,M.useState)(!1),[We,ut]=(0,M.useState)(!1),[Be,Je]=(0,M.useState)(0),Ze=(0,M.useRef)(0),[Z,Q]=(0,M.useState)(!1),pt=(0,M.useRef)(!1),ft=(0,M.useRef)(!1),[Ae,gt]=(0,M.useState)(!1),[V,ke]=(0,M.useState)(!1),{request:tt,collect:ee,finish:qe}=Oo(),vt=(0,M.useRef)({sessionId:e,required:!(0,jt.isValidEmail)(r?.trim()||K?.customer?.email?.trim())});vt.current.sessionId!==e&&(vt.current={sessionId:e,required:!(0,jt.isValidEmail)(r?.trim()||K?.customer?.email?.trim())});let nt=vt.current.required,Et=(0,M.useMemo)(()=>n.replace(/\/+$/,""),[n]),h=K?.gateways?.paypal?.providerObjectType??f,v=h??(u?"subscription":"order"),[X]=(0,M.useState)(Kr),W=K?.gateways?.paypal?.approvalPresentation??P,ve=Ka(X,W==="app_switch"?"app_switch":void 0,v),Bt=h==="order"||h==="setup_token",Ve=(0,M.useMemo)(()=>JSON.stringify([Et,s,p,d??"",v,Bt,ve,e,le??""]),[Et,s,p,d,le,v,Bt,ve,e]),Ye=(0,M.useRef)(Ve),we=Ye.current!==Ve,Ct=(0,M.useRef)(J),Wt=(0,M.useRef)(null),[He,Tn]=(0,M.useState)([]),Ie=(0,M.useCallback)(F=>{Ct.current&&Tn(at=>[...at,`${new Date().toISOString().slice(11,23)} ${F}`])},[]);(0,M.useEffect)(()=>{Ct.current=J,J&&Ie("debug:enabled"),Wt.current?.setEnabled(J)},[Ie,J]);let zn=(0,M.useRef)(k),Un=(0,M.useRef)(R),Mt=(0,M.useRef)(S),kn=(0,M.useRef)(T),An=(0,M.useRef)(E),Kn=(0,M.useRef)(re),mn=(0,M.useRef)(C),Dt=(0,M.useRef)(j),mt=(0,M.useRef)(a),Qe=(0,M.useRef)(q),In=(0,M.useRef)(K),xt=(0,M.useRef)(r),Rn=(0,M.useRef)(o),yn=(0,M.useRef)(t),Ht=(0,M.useRef)(null),sn=(0,M.useRef)(new Map),Gn=(0,M.useRef)(new Map),Yn=(0,M.useRef)(!1);(0,M.useEffect)(()=>(Yn.current=!0,()=>{Yn.current=!1}),[]),(0,M.useEffect)(()=>{zn.current=k},[k]),(0,M.useEffect)(()=>{mt.current=a},[a]),(0,M.useEffect)(()=>{Un.current=R},[R]),(0,M.useEffect)(()=>{Mt.current=S},[S]),(0,M.useEffect)(()=>{kn.current=T},[T]),(0,M.useEffect)(()=>{An.current=E},[E]),(0,M.useEffect)(()=>{Kn.current=re},[re]),(0,M.useEffect)(()=>{mn.current=C},[C]),(0,M.useEffect)(()=>{Dt.current=j},[j]),(0,M.useEffect)(()=>{Qe.current=q},[q]),(0,M.useEffect)(()=>{In.current=K},[K]),(0,M.useEffect)(()=>{xt.current=r},[r]),(0,M.useEffect)(()=>{Rn.current=o},[o]),(0,M.useEffect)(()=>{yn.current=t},[t]),(0,M.useEffect)(()=>{Ze.current=Be},[Be]),(0,M.useEffect)(()=>{Z&&Se.current?.focus()},[Z,Be]);let Tt=(0,M.useCallback)(()=>{window.setTimeout(()=>{Se.current?.focus()},0)},[]),wt=(0,M.useCallback)(()=>{oe(!1),Je(F=>F+1)},[]),vn=(0,M.useCallback)(()=>{Q(!1),(ce.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ce.current)?.focus?.()},[]);(0,M.useEffect)(()=>{!Le||!ue.current||(ue.current=!1,vn())},[vn,Le,Be]);let rn=(0,M.useCallback)((F,at)=>{let ie=at?.popupBlocked??oo(F);ie&&D.markBlocked();let Sn=no("PayPal",ie,X.inAppBrowser),fn=An.current;if(fn){let Kt=ie&&X.inAppBrowser?new jt.FloPayError(Sn,"api_error",{code:at?.code??"paypal_popup_blocked"}):F;fn("paypal",Kt,at);return}Mt.current?.(Sn)},[D,X.inAppBrowser]),Ot=(0,M.useCallback)(F=>{let at=Ge.current,ie=ct.current;at===null||!ie||(be.log({...ie,popupCapability:D.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:F}),be.performance({...ie,popupCapability:D.current(),stage:"overlay_return",durationMs:be.elapsed(at),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:F}),Ge.current=null)},[D,be]),ln=(0,M.useCallback)((F,at,ie)=>{let Sn=ct.current;Ot("overlay_timeout"),Sn&&be.error({...Sn,popupCapability:D.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),rn(at,{...ie,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ve,terminalReason:"overlay_timeout"}),Q(!0),wt(),Tt()},[Ot,Tt,rn,D,ve,wt,be]),Zt=(0,M.useCallback)(()=>{D.markAvailable();let F=ct.current;F&&(A.current=F.attempt,be.log({...F,popupCapability:D.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[D,be]),{finishAttempt:Lt,generationRef:se,invalidateAttempt:cn,isAttemptCurrent:qn,isAttemptInvalidated:Lr,startAttempt:sr}=ya(ln,{onHandoffObserved:Zt}),Ut=(0,M.useCallback)(()=>(Q(!1),sr("paypal")),[sr]),lr=(0,M.useCallback)(F=>{cn(F?.generation),F?.showRetry&&Q(!0),F?.remount&&wt(),F?.focus!==!1&&Tt()},[Tt,cn,wt]),Cn=F=>{let at=Ht.current;return at&&Gn.current.set(F,at),F};(0,M.useEffect)(()=>{Ye.current!==Ve&&(Ye.current=Ve,pt.current=!1,ft.current=!1,oe(!1),ut(!1),gt(!1),Dt.current?.("loading"))},[Ve]),(0,M.useEffect)(()=>{Ke(()=>mn.current?.(Le&&!Ae))},[Le,Ae]);let Re=(0,jt.normalizeGatewayEnvironment)(d);(0,M.useEffect)(()=>{let F={attempt:se.current+1,inAppBrowser:X.inAppBrowser,appFamily:X.appFamily,popupCapability:D.current(),presentationMode:ve},at=()=>({...ct.current??F,popupCapability:D.current()}),ie={error:m=>be.error({...m,...at()}),log:m=>be.log({...m,...at()}),performance:m=>be.performance({...m,...at()}),terminal:m=>be.terminal({...m,...at()}),startTiming:be.startTiming,elapsed:be.elapsed},Sn=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",fn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Ie(`mount clientId=${Sn} env=${d??"(unset)"}\u2192${Re??"live"} ccy=${p} sub=${u}`),Ie(`ua=${fn.slice(0,80)}${fn.length>80?"\u2026":""}`),!s){Ie("FAIL: clientId empty \u2014 gateway misconfigured"),gt(!0),ie.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!ce.current){Ie("FAIL: containerRef not attached");return}me.current=ie.startTiming(),ie.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Kt=!1,Xn=!1,yt=()=>Kt||Xn,Xr,Gt=!1,gn=()=>{Xr=(0,jt.generateIdempotencyKey)(),Xr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Gt=!0},Nr=null,zr=!1,Mn=null,Qt=!1,Sr=()=>{!Mn||Qt||(Qt=!0,Mn.close().catch(()=>{}))},xn=!1,Ur=!1,Fn=ce.current,wr=null,kr=null,cr=[],Jn=null,Zn=!1,Ft=!1,dr=null,_n=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let g=m.getBoundingClientRect();return`${Math.round(g.width)}\xD7${Math.round(g.height)}`},Qn=m=>{if(!m)return"(empty)";try{let g=new URL(m,typeof window>"u"?"https://localhost":window.location.href),z=g.pathname.toLowerCase();return z.includes("checkcaptcha")||z.includes("captcha")?`CAPTCHA(${g.host}${z})`:z.includes("risk")||z.includes("challenge")?`RISK(${g.host}${z})`:z.includes("smart/buttons")?`smart-buttons(${g.host})`:`${g.host}${z}`.slice(0,100)}catch{return m.slice(0,80)}},Ir=m=>{let g=m.getAttribute("src"),z=m.getAttribute("srcdoc"),H=m.getAttribute("name"),Pe=m.getAttribute("sandbox"),ae=[];return g&&ae.push(`src=${Qn(g)}`),z&&ae.push(`srcdoc[${z.length}ch]`),!g&&!z&&ae.push("src=(empty) srcdoc=(empty)"),H&&ae.push(`name=${H.slice(0,40)}`),Pe!==null&&ae.push(`sandbox="${Pe.slice(0,40)}"`),ae.join(" ")},ht=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let g=m.contentDocument;if(!g)return"cd=null";let z=g.body?.children.length??0,H=g.body?.innerHTML.length??0,Pe=g.head?.innerHTML.length??0;return`cd=same-origin readyState=${g.readyState} body[${z}children,${H}ch] head[${Pe}ch]`}catch(g){return`cd=cross-origin(${g.message.slice(0,30)})`}},on=[],en=m=>{if(yt())return;let g=m.message??String(m.error??"(no message)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(Ie(`window:error ${g.slice(0,140)}`),on.push(g))},qr=m=>{if(yt())return;let g=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(Ie(`window:rejection ${g.slice(0,140)}`),on.push(g))},Vn={value:0},Jr=()=>{wr?.disconnect(),wr=null,kr?.disconnect(),kr=null;for(let m of cr.splice(0))clearTimeout(m);Ft=!1,Zn&&typeof window<"u"&&(window.removeEventListener("error",en),window.removeEventListener("unhandledrejection",qr)),Zn=!1},ur=()=>{if(!(Zn||yt()||xn)){if(Zn=!0,on.length=0,Vn.value=0,typeof window<"u"&&(window.addEventListener("error",en),window.addEventListener("unhandledrejection",qr)),typeof PerformanceObserver<"u")try{kr=new PerformanceObserver(m=>{if(!yt())for(let g of m.getEntries()){if(!g.name.toLowerCase().includes("paypal"))continue;Vn.value+=1;let z=Math.round(g.duration);Ie(`net ${z}ms ${g.name.slice(0,90)}`)}}),kr.observe({type:"resource",buffered:!0})}catch{}dr?.()}},pr=()=>{Jn&&(clearTimeout(Jn),Jn=null)},hn=()=>{Jr(),pr()},mr={setEnabled:m=>{m?ur():Jr()}};Wt.current=mr,Ct.current&&ur();let Vr=m=>{if(!m)return!1;let g=m.toLowerCase();return g.includes("zoid destroyed")||g.includes("destroyed all components")||g.includes("window closed")||g.includes("detected container element removed")},En=m=>{if(yt()||Vr(m))return;let g=eo(m)??m;Ke(()=>Mt.current?.(g))},L=(m,g)=>{if(Kt||zr)return;zr=!0,Xn=!0,hn(),Sr();let z=Ud({kind:m,generationActive:!0,automaticRetryAllowed:_,automaticRetryUsed:pt.current});if(z.action==="retry"){pt.current=!0,oe(!1),ke(!1),ut(!0),Dt.current?.("retrying"),Nr=setTimeout(()=>{Kt||Je(H=>H+1)},Od);return}if(oe(!1),ke(!1),ut(!1),gt(!0),z.action!=="ignore"){if(Dt.current?.("exhausted"),z.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",g);return}if(z.report){let H=ro({code:xl(m,g),message:g},{inAppBrowser:X.inAppBrowser,handoffObserved:!1});H.popupBlocked&&D.markBlocked(),ie.error({errorCode:H.popupBlocked?H.errorCode:z.report.errorCode,stage:z.report.stage,operationOutcome:z.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:H.terminalReason})}ft.current||(ft.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",xl(m,g)))}};gt(!1);let U=async(m,g=Ht.current)=>{if(yt())return;let z=g?.sessionId??e;if(zn.current){await zn.current(m,{sessionId:z,accountPatch:g?.accountPatch,nonce:g?.nonce});return}let H=ie.startTiming();ie.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=()=>{ie.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ie.performance({stage:"processing",durationMs:ie.elapsed(H),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ae=In.current,rt=g?.accountPatch?.email??xt.current,It=g?.accountPatch?.userId??ae?.customer?.id??ae?.accountData?.userId??"",B=g?.accountPatch?.firstName??ae?.customer?.firstName??ae?.accountData?.firstName,Te=g?.accountPatch?.lastName??ae?.customer?.lastName??ae?.accountData?.lastName,_e=await new Ja.PaymentAPI(Et,{telemetry:!1}).processPayment(It,{sessionId:z,nonce:g?.nonce??yn.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:It,email:rt??ae?.customer?.email??"",...B?{firstName:B}:{},...Te?{lastName:Te}:{},country:g?.accountPatch?.country??ae?.customer?.country??ae?.accountData?.country??void 0,zip:g?.accountPatch?.zip??ae?.customer?.zip??ae?.accountData?.zip??void 0}});if(_e.ok){if(Xn||Kt&&Yn.current)return;Pe(),ie.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Ke(()=>Un.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(yt())return;let G=await _e.json().catch(()=>null),ge=G?.message??"PayPal payment failed.",x=eo(ge)??ge;Pe(),_e.status===400&&(typeof G?.declineCode=="string"||!Array.isArray(G?.fields))?ie.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):_e.status===400||_e.status===422?ie.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):ie.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Vd(_e.status),failureCategory:_e.status>=500?"server_error":void 0}),En(x),Ke(()=>kn.current?.(un("paypal",x,{code:G?.code,declineCode:G?.declineCode})));return}catch(ae){if(yt())return;Pe(),ie.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let rt=ae instanceof Error?ae.message:"PayPal payment failed.",It=eo(rt)??rt;En(It),Ke(()=>kn.current?.(un("paypal",It)));return}},O=()=>new jt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),he=m=>yt()?Promise.reject(O()):Promise.resolve(m),je=async m=>{if(yt())throw O();Gt||gn();let g=Ht.current,z=g?.sessionId??e,H=g?.nonce??yn.current;ie.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Pe;try{Pe=await new Ja.PaymentAPI(Et,{telemetry:!1}).createSessionIntent(z,H??"",Bt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:jt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:v==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Xr})}catch(ae){throw ie.error({...(0,jt.classifyTelemetryFailure)(ae,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ae}if(yt())throw O();if(Pe.provider!=="paypal"||Pe.providerObjectType!==v)throw new Error(m);return ie.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Pe.providerObjectId},Pt=(m,g)=>{let z=g?.nonce??yn.current;if(!z)return;let H=g?.sessionId??e,Pe=No(m)??Mr(m)??"provider_declined";new Ja.PaymentAPI(Et,{telemetry:!1}).reportSessionIntentDecline(H,z,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Pe}).catch(()=>{})},Ce=Be;Ie("loadScript:scheduled (deferred 1 tick)");let $e=null,te=setTimeout(()=>{if(Kt){Ie("loadScript:skipped (cancelled before defer ran)");return}Ie("loadScript:start");let m=Re==="live"?"production":Re,g={};v==="subscription"?g={intent:"subscription",vault:!0}:v==="order"&&(g={intent:"capture"}),$e=(0,Fl.loadScript)({clientId:s,currency:p,...g,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let z=!1;$e.then(H=>{if(z=!0,Ie(`loadScript:resolved inactive=${yt()} ns=${!!H} buttons=${!!H?.Buttons}`),yt())return;if(!H?.Buttons){Ie("FAIL: namespace missing Buttons factory"),L("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}ie.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),ie.performance({stage:"provider_ready",durationMs:ie.elapsed(me.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ie.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=async(_e,G)=>{if(yt()||Ze.current!==Ce)return;let ge=_e.vaultSetupToken??_e.subscriptionID??_e.orderID??"",x=ge?Gn.current.get(ge):sn.current.get(Ce);if(!(!x||!qn(x.generation))&&Lt(x.generation)){Gn.current.delete(ge),sn.current.delete(x.surfaceKey),Ot("approved");try{if(ke(!0),Ke(()=>Mt.current?.(null)),!ge)throw new jt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Xe=In.current,Rt=mo(Rn.current??[Xe?.customer?.firstName,Xe?.customer?.lastName].filter(Boolean).join(" ")),Ne=On({email:x.accountPatch?.email?.trim()||xt.current?.trim()||Xe?.customer?.email?.trim(),firstName:x.accountPatch?.firstName?.trim()||Rt.firstName,lastName:x.accountPatch?.lastName?.trim()||Rt.lastName});if(!(0,jt.isValidEmail)(Ne.email)||!(Ne.firstName||Ne.lastName))try{let Rr=qd(await G?.order?.get?.());Ne=On({email:Rr.email||Ne.email,firstName:Rr.firstName||Ne.firstName,lastName:Rr.lastName||Ne.lastName})}catch{}if((mt.current||nt)&&!(0,jt.isValidEmail)(Ne.email)){let Rr=await ee("PayPal",Ne);if(!Rr)return;Ne=Rr}(0,jt.isValidEmail)(Ne.email)&&(x.accountPatch=On({...x.accountPatch,...Ne}),await mt.current?.(Ne));let wn;v==="setup_token"?wn={id:ge,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:jt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Bt?wn={id:ge,isPaypal:!0,gateway:"paypal",paymentMethodType:jt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:wn={id:ge,isPaypal:!0},await U(wn,x)}catch(Xe){En(Xe instanceof Error?Xe.message:"PayPal capture failed.")}finally{yt()||ke(!1)}}},ae=_e=>{let G=le?()=>he(le):()=>je(_e);return async()=>Cn(await G())},rt=H.Buttons({style:{layout:"horizontal",height:Za,tagline:!1},...ve==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(_e,G)=>{if(yt()){await G.reject();return}gn();let ge=Qe.current,x={};if(ge)try{let Ne=await ge("paypal");if(yt()){await G.reject();return}if(!Ne.proceed){Ht.current=null,sn.current.delete(Ce),await G.reject();return}x={sessionId:Ne.sessionId,accountPatch:Ne.accountPatch,nonce:Ne.nonce}}catch(Ne){Ie(`onClick:runBeforeButtonClick rejected msg=${(Ne instanceof Error?Ne.message:String(Ne)).slice(0,120)}`),Ht.current=null,sn.current.delete(Ce),await G.reject();return}Ke(()=>Kn.current?.("paypal"));let Xe=Ut(),Rt={generation:Xe,surfaceKey:Ce,...x};Ht.current=Rt,sn.current.set(Ce,Rt),ct.current={...F,attempt:Xe},await G.resolve(),ie.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ie.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Ge.current=ie.startTiming()},createOrder:v==="order"?ae("Failed to create PayPal order."):void 0,createSubscription:v==="subscription"?ae("Failed to create PayPal subscription."):void 0,createVaultSetupToken:v==="setup_token"?async()=>Cn(await je("Failed to create PayPal setup token.")):void 0,onApprove:Pe,onCancel:()=>{if(yt())return;let _e=sn.current.get(Ce)??Ht.current;_e&&sn.current.delete(_e.surfaceKey),Ht.current=null,Ot("cancelled"),ie.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ue.current=!0,lr({generation:_e?.generation,remount:!0,focus:!1})},onError:_e=>{if(yt()||Ze.current!==Ce)return;let G=_e instanceof Error?_e.message:"PayPal failed to render.";if(Ie(`onError rendered=${xn} msg=${G.slice(0,120)}`),xn){let ge=sn.current.get(Ce)??Ht.current;if(ge&&!qn(ge.generation)||!ge&&Lr())return;if(Vr(G)){Lt(ge?.generation);return}let{errorCode:x,popupBlocked:Xe,providerDeclined:Rt,terminalReason:Ne}=ro(_e,{inAppBrowser:X.inAppBrowser,handoffObserved:ge!=null&&A.current===ge.generation});if(Xe&&D.markBlocked(),Ot(Ne),Rt){ie.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ne}),Pt(_e,ge),Ke(()=>kn.current?.(un("paypal",G))),ge&&sn.current.delete(ge.surfaceKey),Ht.current=null,Lt(ge?.generation);return}ie.error({errorCode:x,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ne}),ge&&sn.current.delete(ge.surfaceKey),Ht.current=null,lr({generation:ge?.generation,remount:!0,showRetry:!0,focus:!0}),rn(_e,{code:"paypal_runtime_failed",popupBlocked:Xe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ve,terminalReason:Ne});return}L(Vr(G)?"teardown":"pre_ready_callback",G)}}),It=rt.isEligible();if(Ie(`isEligible=${It}`),ie.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!It){oe(!1),L("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ur=!0,Mn=rt,dr=()=>{if(!Zn||Ft||yt()||xn)return;Ft=!0,Ie(`container:dims ${_n(Fn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(wr=new MutationObserver(G=>{if(!yt()){for(let ge of G)if(ge.type==="childList")ge.addedNodes.forEach(x=>{if(!(x instanceof Element))return;let Xe=x.tagName.toLowerCase(),Rt=(x.getAttribute("title")??"").slice(0,40),Ne=Xe==="iframe"?` ${Ir(x)}`:"";Ie(`child+ ${Xe}${Rt?` title="${Rt}"`:""}${Ne} dims=${_n(x)}`)});else if(ge.type==="attributes"&&ge.target instanceof Element){let x=ge.target;if(x.tagName.toLowerCase()!=="iframe")continue;let Xe=ge.attributeName;(Xe==="src"||Xe==="srcdoc")&&Ie(`attr~ iframe ${Xe}=${Xe==="srcdoc"?`[${(x.getAttribute("srcdoc")??"").length}ch]`:Qn(x.getAttribute("src"))} dims=${_n(x)}`)}}}),wr.observe(Fn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let _e=G=>{if(yt()||xn)return;let ge=Fn.querySelectorAll("iframe"),x=typeof document<"u"&&"hasStorageAccess"in document;Ie(`watchdog:${G} container=${_n(Fn)} children=${Fn.childElementCount} iframes=${ge.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${x} paypalNetRequests=${Vn.value}`),ge.forEach((Xe,Rt)=>{let Ne=(Xe.getAttribute("title")??"").slice(0,40);Ie(` iframe[${Rt}] ${_n(Xe)}${Ne?` title="${Ne}"`:""} ${Ir(Xe)}`);let wn=ht(Xe);wn&&Ie(` ${wn}`)}),on.length===0&&Ie(" (no PayPal/zoid window errors captured)")};cr.push(setTimeout(()=>_e("3s"),3e3)),cr.push(setTimeout(()=>_e("8s"),8e3)),cr.push(setTimeout(()=>_e("15s"),15e3))},dr(),Ie("render:start");let Te=ie.startTiming();Jn=setTimeout(()=>{yt()||xn||(Ie("watchdog:11s retryable render timeout"),L("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Ld);let At=rt.render(Fn);(async()=>{try{if(await At,Ie(`render:resolved inactive=${yt()}`),hn(),yt()){Sr();return}xn=!0,oe(!0),ut(!1),Dt.current?.("ready"),ie.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),ie.performance({stage:"checkout_render",durationMs:ie.elapsed(Te),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(_e){let G=_e instanceof Error?_e.message:"PayPal failed to render.";Ie(`render:rejected msg=${G.slice(0,120)}`),hn(),L(Vr(G)?"teardown":"render_rejected",G)}})()}).catch(H=>{let Pe=H instanceof Error?H.message:"PayPal operation failed.";Ie(`provider:failed msg=${Pe.slice(0,120)}`);let ae="script_rejected";z&&Vr(Pe)?ae="teardown":z&&Ur&&(ae="render_rejected"),L(ae,Pe)})},0);return()=>{Kt=!0,clearTimeout(te),Nr&&clearTimeout(Nr),hn(),Wt.current===mr&&(Wt.current=null),Sr(),Ge.current=null,ct.current=null}},[_,Et,s,p,d,v,ve,Bt,e,le,Be,be,ee,nt,Ie,Ot]);let ye=J?(0,nr.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ae?"#fef2f2":"#f3f4f6",border:`1px solid ${Ae?"#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=${Le} failed=${Ae})`,He.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return
|
|
3
|
+
${He.join(`
|
|
4
|
+
`)}`]}):null;return Ae&&!we?J?(0,nr.jsx)("div",{children:ye}):null:(0,nr.jsxs)("div",{children:[ye,tt&&(0,nr.jsx)(Lo,{identity:tt.identity,methodLabel:tt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:qe,onCancel:()=>qe(null)}),(0,nr.jsxs)("div",{"aria-hidden":We||tt?!0:void 0,style:We||tt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Za},children:[!Le&&!We&&(0,nr.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,nr.jsx)("div",{ref:ce,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Za,display:"flex",opacity:Le?1:0},"aria-busy":V||b},Be)]},Be),Z&&(0,nr.jsx)("button",{ref:Se,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:vn,style:Nd,children:"Try PayPal again"})]})}function fa(e){return(0,nr.jsx)(Bl,{...e})}function Dl(e){return(0,nr.jsx)(Bl,{...e})}var ga=require("react/jsx-runtime");function Uo({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,ga.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,ga.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,ga.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 Qa=require("@flopay/shared");function qo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Qi=":idempotency-key";function es(e,t){if(!qo())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 ts(e,t){if(!qo())return null;try{let n=window.sessionStorage.getItem(e+Qi);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 ei(e,t){if(qo())try{es(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ti(e,t){if(ei(e,t),!!qo())try{ts(e,t)&&window.sessionStorage.removeItem(e+Qi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function ni(e,t,n,r){if(qo())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 ri(e,t,n){if(qo())try{window.sessionStorage.setItem(e+Qi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Zi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function jd(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([s],[d])=>s<d?-1:s>d?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let s=0;s<t.length;s++){let d=t.charCodeAt(s);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(s=>(s>>>0).toString(16).padStart(8,"0")).join("")}function Vo(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=>Zi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Zi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Zi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:jd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Ol(e,t=!1){let n=Vo(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function Ll(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=(0,Qa.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,Qa.foldIntoProducts)(t.items,t.subscriptions)).map(u=>({type:u.type,code:u.code??u.providerItemId??u.providerPlanId??"",quantity:u.quantity??1,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount??null,currency:(u.currency??o).toUpperCase()})).sort((u,f)=>`${u.code}:${u.type??""}`.localeCompare(`${f.code}:${f.type??""}`)),s=e.products.map(u=>({type:u.type,code:u.code??"",quantity:u.quantity??1,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount??null,currency:(u.currency??e.currency).toUpperCase()})).sort((u,f)=>`${u.code}:${u.type??""}`.localeCompare(`${f.code}:${f.type??""}`));if(a.length!==s.length)return!1;for(let[u,f]of a.entries()){let P=s[u];if(P===void 0||f.code!==P.code||f.type!==void 0&&f.type!==P.type||f.quantity!==P.quantity||f.totalAmount!==P.totalAmount||f.overrideAmount!==P.overrideAmount||f.currency!==P.currency)return!1}let d=[...t.couponCodes??[]].sort(),p=[...e.coupons??[]].sort();return d.length===p.length&&d.every((u,f)=>u===p[f])}var nn=require("react/jsx-runtime");var $d={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function Ln({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:s="You will be automatically redirected, do not close or navigate away from this window.",theme:d=$d}){let p={fontSize:13,color:d.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,nn.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,nn.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,nn.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,nn.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,nn.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:d.spinnerTrackColor,strokeWidth:"3"}),(0,nn.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:d.spinnerAccentColor})]}),e==="success"&&(0,nn.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,nn.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,nn.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,nn.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,nn.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,nn.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,nn.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,nn.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,nn.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"&&s!==null&&(0,nn.jsx)("p",{style:p,children:s}),e==="error"&&t&&(0,nn.jsx)("p",{style:p,children:t}),(0,nn.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 Nl=require("@flopay/shared"),Cn=require("react");var zl=require("react/jsx-runtime");function ha({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,s]=(0,Cn.useState)(e instanceof Promise?null:e),[c,u]=(0,Cn.useState)(t instanceof Promise||!t?null:t),p=(0,Cn.useRef)(null),h=(0,Cn.useRef)(null),b=zo(r);(0,Cn.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,Cn.useEffect)(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),(0,Cn.useEffect)(()=>{if(a)return pn(a)?.subscribe?.(b)},[b,a]),(0,Cn.useEffect)(()=>{if(!(!c||c===a))return pn(c)?.subscribe?.(b)},[b,a,c]),(0,Cn.useEffect)(()=>{if(!a)return;let C=pn(a);return p.current=C?.beginCheckout()??C?.now()??0,C?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{C?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,Cn.useEffect)(()=>{let C=!1;return e instanceof Promise?e.then(f=>{C||s(f)},()=>{C||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{C=!0}},[b,e]),(0,Cn.useEffect)(()=>{let C=!1;if(!t){u(null);return}return t instanceof Promise?t.then(f=>{C||u(f)},()=>{C||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):u(t),()=>{C=!0}},[b,t]),(0,Cn.useEffect)(()=>{if(!a||h.current===a)return;h.current=a;let C=pn(a);C?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),C?.performance({stage:"checkout_render",durationMs:C.elapsed(p.current??0),durationMode:"machine"})},[b,a]);let I=(0,Nl.resolveBillingApiUrl)(n?.billingApiUrl),k=(0,Cn.useMemo)(()=>({flopay:a,paypalFlopay:c,billingApiUrl:I,emitInstrument:b}),[a,c,I,b]);return(0,zl.jsx)(rr.Provider,{value:k,children:o})}var oi="flopay_recent_completion_";function jo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(oi+e,JSON.stringify(t))}catch{}}function ns(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(oi+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(oi+e),!1):!0}catch{return!1}}async function ai(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}var ao=require("@flopay/js"),Je=require("@flopay/shared");var ba="card",$d=1e3;async function Wd(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:s}=await e.retrieveSetupIntent(t);return{error:s,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 Hd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:s??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 io(e){return new Je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function rs(){return new Je.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function as(e,t){return Object.assign(e,{checkoutMethod:t})}function Gr(e,t){let n=e instanceof Je.FloPayError?e:new Je.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Pa(e,t){try{return await e()}catch(n){throw Gr(n,t)}}function ql(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 Kd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function is(e){if(typeof document>"u"||typeof window>"u")throw new Je.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw io();let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let b=new AbortController,I=()=>b.abort();e.signal?.aborted?b.abort():e.signal?.addEventListener("abort",I);let k=window.setTimeout(()=>b.abort(),n);try{let C=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:b.signal});if(!C.ok)return{status:"unknown"};let f=await C.json().catch(()=>null);return Gd(f)}catch{return{status:"unknown"}}finally{window.clearTimeout(k),e.signal?.removeEventListener("abort",I)}},a,s=()=>e.pollCompletionEndpoint!==!1?o():(a??(a=o()),a),c=document.activeElement instanceof HTMLElement?document.activeElement:null,u=document.createElement("div");u.setAttribute("data-flopay-auto-3ds-overlay","1"),u.setAttribute("role","dialog"),u.setAttribute("aria-modal","true"),u.setAttribute("aria-label","Card authentication"),u.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let p=document.createElement("iframe");p.setAttribute("title","Card authentication"),p.setAttribute("allow","payment"),p.tabIndex=0,p.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}try{let b=await new Promise((I,k)=>{let C=!1,f=0,S=0,G=0,_=!1,q=()=>{window.clearTimeout(f),window.clearInterval(S),window.clearTimeout(G),window.removeEventListener("message",W),p.removeEventListener("load",ne),e.signal?.removeEventListener("abort",$)},E=async()=>{if(!(C||_)){_=!0;try{let ie=await s();if(C||!Kd(ie))return;C=!0,q(),I(ie)}finally{_=!1}}},ne=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(G),G=window.setTimeout(()=>{E()},250))},$=()=>{C||(C=!0,q(),k(io()))},W=ie=>{if(ie.source!==p.contentWindow||h&&ie.origin!==h)return;let V=ie.data;!V||typeof V!="object"||V.source!=="flopay-vault-3ds-return"||C||(C=!0,q(),I(null))};f=window.setTimeout(()=>{C||(C=!0,q(),k(rs()))},Je.THREE_DS_CHALLENGE_WINDOW_MS),e.pollCompletionEndpoint!==!1&&(S=window.setInterval(()=>{E()},t)),p.addEventListener("load",ne),window.addEventListener("message",W),e.signal?.addEventListener("abort",$),p.src=e.nextActionRedirectUrl,u.appendChild(p),document.body.appendChild(u),p.focus(),e.signal?.aborted&&$()});return b||await s()}finally{u.parentNode?.removeChild(u),c?.isConnected&&c.focus()}}async function $o(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,a=t.nonce??t.session.clientSecret,s=new ao.PaymentAPI(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,u=new AbortController,p=new AbortController,h=()=>{u.abort(o.reason),p.abort(o.reason)};o.aborted?h():o.addEventListener("abort",h,{once:!0});let b=is({billingApiUrl:n,sessionId:r,nonce:a,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:u.signal,pollCompletionEndpoint:!1}),I=s.waitForCheckoutSessionCompletion(r,{initialDelayMs:$d,nonce:a,statusUrl:c,continueAfterActionRequired:!0,timeoutMs:Je.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:p.signal}),k;try{let f=await Promise.race([b,I]);if("data"in f)k=f;else{if(f.status==="declined")throw Fr({type:f.declineReason??"authorization_declined",gatewayErrorCode:f.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(f.status==="timeout")throw rs();k=await I}}catch(f){if(o.aborted||f instanceof Error&&f.name==="AbortError")throw io(f);if(!(f instanceof Je.FloPayError)||f.code!=="three_ds_timeout"&&f.code!=="checkout_processing_timeout")throw f;try{k=await s.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:a,statusUrl:c,timeoutMs:5e3,signal:o})}catch(G){if(o.aborted)throw io(G);if(!(G instanceof Je.FloPayError)||G.code!=="checkout_processing_timeout")throw G}let S=k&&to(k,t.session);if(!$r(S)&&S?.status!=="expired"){if(t.telemetry){let G=new ao.PaymentAPI(n);try{G.reportThreeDsAbandoned(r)}finally{G.destroy()}}throw rs()}}finally{o.removeEventListener("abort",h),u.abort(),p.abort()}let C=k&&to(k,t.session);if(!$r(C))throw Do(C);return{...jr(C,r),checkoutMethod:"card"}}function Gd(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,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"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Fr(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=eo(o)??o,s=as(new Je.FloPayError(a,"api_error",{code:e?.code??(0,Je.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Je.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(s.orderId=e.orderId),s}function os(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ii(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Vl(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ii(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let c of a)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||ii(c)))return c;let s=o.gateways;if(s&&typeof s=="object"){let c=s.stripe;if(c&&typeof c=="object"){let u=c,p=[u.stripeClientSecret,u.clientSecret];for(let h of p)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||ii(h)))return h}}}}async function Yd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Vl(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let c=(await new ao.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ii(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function Wo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:s}){let c=e.replace(/\/+$/,""),u=t??n.id,p=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",I=n.customer?.firstName??n.accountData?.firstName??"",k=n.customer?.lastName??n.accountData?.lastName??"",C=n.customer?.country??n.accountData?.country??void 0,f=n.customer?.zip??n.accountData?.zip??void 0,G=await new ao.PaymentAPI(c,s===!1?{telemetry:!1}:void 0).processPayment(h,{sessionId:u,nonce:p,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:h,email:b,firstName:I,lastName:k,country:C,zip:f},returnUrl:a??os(n)});if(G.ok){let E=typeof G.json=="function"?await G.json().catch(()=>null):null;if((0,Je.isAuthorizationOnlySession)(n)||E?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof E?.paymentId=="string"?E.paymentId:n.paymentId,sessionId:typeof E?.sessionId=="string"?E.sessionId:u,authorizationExpiresAt:typeof E?.authorizationExpiresAt=="string"?E.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:ua(o),checkoutMethod:Ul(o,n)}};let ne=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ne?{paymentIntentId:ne}:{},paymentMethodId:ua(o),checkoutMethod:Ul(o,n)}}}let _;try{_=await G.json()}catch(E){throw new Je.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:G.status,cause:E})}if(_?.type==="3ds_required"&&typeof _.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:_.nextActionRedirectUrl};if(_?.type==="paypal_redirect_required"||_?.type==="3ds_required"){let E=Vl(_);if(!E)throw new Je.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:G.status});return{type:_.type,threeDSecureToken:E,paymentMethodId:_.paymentMethodId}}if(_?.gatewayErrorCode==="authentication_required"){let E=await Yd({billingApiUrl:c,sessionId:u,nonce:p,responseJson:_});if(E)return E;throw as(new Je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let q=new Je.FloPayError(_?.message??"Payment failed. Please try again.","api_error",{code:_?.code??_?.gatewayErrorCode,declineCode:_?.declineCode??_?.gatewayDeclineReason,statusCode:G.status});throw Object.assign(q,{telemetryOutcome:(0,Je.classifyPaymentRejection)(G.status,_)})}async function si(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:s,returnUrl:c,telemetry:u,signal:p}){let h=t?.getRawProvider();if(!h)throw Gr(new Je.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw as(new Je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let b=(0,Je.isSetupIntentClientSecret)(e.threeDSecureToken),I=null,k=e.paymentMethodId,C=await Pa(()=>Wd(h,e.threeDSecureToken,b),"card");if(C){if(C.error)throw Gr(new Je.FloPayError(C.error.message??`Failed to retrieve 3DS ${b?"setup":"payment"} status.`,"api_error",{code:C.error.code}),"card");let S=C.intent;!k&&S?.payment_method&&(typeof S.payment_method=="string"?k=S.payment_method:"id"in S.payment_method&&(k=S.payment_method.id??void 0))}let f=k?await Pa(()=>Hd(h,e.threeDSecureToken,{payment_method:k,return_url:c??os(s)??window.location.href},b),"card"):null;if(f){if(f.error)throw Gr(new Je.FloPayError(f.error.message??"3DS authentication failed.","api_error",{code:f.error.code}),"card");I=f.intent}else{let S=await Pa(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(S.error)throw Gr(new Je.FloPayError(S.error.message??"3DS authentication failed.","api_error",{code:S.error.code}),"card");I=(b?S.setupIntent:S.paymentIntent)??null}if(I&&(I.status==="requires_capture"||I.status==="succeeded"||I.status==="processing")){let S=await Wo({billingApiUrl:o,sessionId:a,session:s,telemetry:u,tokenizedData:{id:I.id,type:"card",threeDSecureActionResultTokenId:I.id},returnUrl:c});return S.type==="success"?{...S.result,paymentIntentId:S.result.paymentIntentId??I.id,paymentMethodId:S.result.paymentMethodId??k}:S.type==="next_action_required"?$o(S,{billingApiUrl:o,sessionId:a??s.id,session:s,signal:p}):si(S,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:s,returnUrl:c,telemetry:u,signal:p})}throw Gr(new Je.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let b=(n??t)?.getRawProvider();if(!b)throw Gr(new Je.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:k}=await Pa(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(k)throw Gr(new Je.FloPayError(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:I}=await Pa(()=>b.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??os(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(I)throw Gr(new Je.FloPayError(I.message??"PayPal authorization failed.","api_error",{code:I.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Je.FloPayError("Unsupported payment redirect state.","api_error")}function va(e){if(e instanceof Je.FloPayError){let r=eo(e.message);return r&&r!==e.message?Object.assign(new Je.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=eo(t)??t;return new Je.FloPayError(n,"api_error")}function ss(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Zr(e.data.session);if(!t&&!n&&!r)throw new Je.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function Ul(e,t){return e?e.isPaypal?"paypal":"card":t&&Zr(t)?"card":void 0}async function ls({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,[s,c]=await Promise.all([(0,ao.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,ao.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(p=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",p),null)):Promise.resolve(null)]);if(!s)throw new Je.FloPayError("The payment provider did not initialize.","authentication_error");let u=null;return a?u=c:t&&(u=s),{flopay:s,paypalFlopay:u}}var Cr=require("@flopay/js"),y=require("@flopay/shared"),Zt=require("@stripe/react-stripe-js"),i=ji(require("react"),1);function Ho(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function li(e,t){if(e)return{error:n=>e.error(Ho(t,n)),log:n=>e.log(Ho(t,n)),performance:n=>e.performance(Ho(t,n)),terminal:n=>e.terminal(Ho(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}var jl={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 Kn=require("react");function ci(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(s=>s.startsWith("background")),a={};for(let[s,c]of Object.entries(e))s in n||o&&s.startsWith("background")||(a[s]=c);for(let s of r)a[s]=n[s];return a}var Xd=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 Jd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Xd.has(t.charAt(0).toLowerCase()+t.slice(1))}function Zd(e,t){return typeof t=="number"&&t!==0&&!Jd(e)?`${t}px`:String(t).trim()}function $l(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]=Zd(n,r)}}}var Wl=require("react/jsx-runtime"),cs=new WeakSet;function so({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:s,onReady:c,onError:u,onValidation:p}){let h=(0,Kn.useRef)(null),b=(0,Kn.useRef)(c),I=(0,Kn.useRef)(u),k=(0,Kn.useRef)(p);b.current=c,I.current=u,k.current=p;let C=(0,Kn.useRef)(o);C.current=o;let f=(0,Kn.useRef)(null),S=a??void 0,G=(0,Kn.useRef)(S);G.current=S;let _=(0,Kn.useRef)(void 0);return(0,Kn.useEffect)(()=>{let q=h.current;if(!q)return;let E=!0,ne=!1,$=()=>{!E||ne||(ne=!0,b.current?.())},W=e.on("ready",()=>{$()}),ie=e.on("error",X=>{I.current?.(X.message??"There was a problem loading the secure card form.")}),V=e.on("validation",X=>{k.current?.(X.message??null)}),Be=G.current??(cs.has(e)?null:void 0),Ue={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...C.current?{theme:C.current}:{},...Be===void 0?{}:{submitLabel:Be}};return f.current=C.current??null,_.current=G.current,G.current!==void 0&&cs.add(e),e.mount(q,Ue).then(()=>{$()}).catch(X=>{E&&I.current?.(X instanceof Error?X.message:"Failed to load the secure card form.")}),()=>{E=!1,W(),ie(),V(),e.unmount()}},[e,t,n,r]),go(()=>{let q=h.current;q&&$l(q,s)},[s]),(0,Kn.useEffect)(()=>{o!==void 0&&(o===null&&f.current===null||(f.current=o,e.applyTheme?.(o)))},[e,o]),(0,Kn.useEffect)(()=>{S!==_.current&&(_.current=S,S!==void 0&&cs.add(e),e.setSubmitLabel?.(S??null))},[e,S]),(0,Wl.jsx)("div",{ref:h,"data-testid":"flopay-vault-card-fields"})}var Kl=/^#([0-9a-f]{6})$/i,Qd=/^#([0-9a-f]{3})$/i,Gl=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Yl=/^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,eu=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,tu=/^(-?\d+(?:\.\d+)?)(?:px)?$/,nu=/^(-?\d+(?:\.\d+)?)em$/,ru=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,ou=/^[a-z][a-z0-9 -]{0,31}$/i,au=new Set(["none","uppercase","lowercase","capitalize"]);function Xl(e){if(typeof e!="string")return null;let t=e.trim(),n=Kl.exec(t);if(n){let h=Number.parseInt(n[1],16);return{r:h>>16&255,g:h>>8&255,b:h&255,a:null}}let r=Qd.exec(t);if(r){let[h,b,I]=r[1].split("").map(k=>Number.parseInt(k+k,16));return{r:h,g:b,b:I,a:null}}let o=Gl.exec(t),a=o?null:Yl.exec(t),s=o??a;if(!s)return null;let c=Number(s[1]),u=Number(s[2]),p=Number(s[3]);return c>255||u>255||p>255?null:{r:c,g:u,b:p,a:a?Number(a[4]):null}}function Jl({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 Ca(e){if(typeof e!="string")return;let t=e.trim();if(Kl.test(t)||Gl.test(t))return t;let n=Yl.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=Xl(t);return r?Jl(r):void 0}function di(e,t=.12){let n=Xl(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Jl({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function Sa(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 Po(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=tu.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function iu(e,t,n){if(typeof e!="string")return;let r=nu.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function su(e){let t=Sa(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=Sa(o," "),s=Ca(a[0]);if(!s)return;let c=r/(t.length-1)*100,u=a[1]===void 0?c:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),p=n[n.length-1]?.position??-1;if(!Number.isFinite(u)||u<0||u>100||u<p)return;n.push({color:s,position:u})}return{type:"linearGradient",angle:0,stops:n}}function lu(e){if(typeof e!="string")return;let t=e.trim(),n=Ca(t);if(n)return{type:"solid",color:n};let r=eu.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=su(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function cu(e){return e.type==="solid"?{type:"solid",color:di(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:di(t.color)}))}}function du(e){let t=!1,n,r=[];for(let u of Sa(e," ")){if(u.toLowerCase()==="inset"){t=!0;continue}let p=Ca(u);if(p){n=p;continue}let h=Po(u,-128,128);if(h===void 0)return;r.push(h)}if(!n||r.length<2||r.length>4)return;let[o,a,s=0,c=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||s>128||Math.abs(c)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:s,spread:c}}function uu(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=Sa(t,",").map(du);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function Hl(e){if(typeof e!="string")return;let t=Sa(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>ou.test(n)).slice(0,4);return t.length>0?t:void 0}function pu(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=Po(t[0],0,64),r=Po(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function mu(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 Zl({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=lu(r.background??r.backgroundColor),s=Ca(o?.colorPrimaryHover),c=s?{type:"solid",color:s}:a&&cu(a),u={fontFamilies:Hl(r.fontFamily)??Hl(n),fontSize:Po(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:mu(r.fontWeight)??600,letterSpacing:iu(r.letterSpacing,-.1,.5)??.01,lineHeight:Po(r.lineHeight,.8,2)??1,textTransform:au.has(String(r.textTransform))?r.textTransform:"uppercase"},p=pu(r.padding),h=uu(r.boxShadow),b=Po(r.borderRadius,0,9999),I=typeof r.backdropFilter=="string"?Po(ru.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Ca(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...c?{hoverBackground:c}:{},typography:u,...p?{spacing:p}:{},...h?{shadow:h}:{},...b===void 0?{}:{borderRadius:b},disabledOpacity:e?.theme==="night"?.8:.6,...I===void 0?{}:{backdropBlur:I}}}function Ko(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)?di(r,t):e}function ds(e){if(typeof e=="number"||typeof e=="string")return e}function Go({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=b=>typeof b=="string"&&b?b:void 0,a=t.submitButton,s=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",c=n==="buttons",u=t.nameInput,p=o(u?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",h=Zl({appearance:e,buttonsStyles:t,fontFamily:p});return{primaryColor:s,primaryHoverColor:o(r?.colorPrimaryHover)??Ko(s,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(u?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(c?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:p,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(ds(u?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...h?{submitButton:h}:{}}}var d=require("react/jsx-runtime"),Br="flopay_stripe_resume",Ql="flopay_wallet_resume",uc="fw1",yu="fw2",pc=300*1e3,fu=900,gu=25e3,hu=25e3,Pu=1e4,mc=["payment_intent","payment_intent_client_secret","redirect_status"],vr={provider:"paypal",paymentMethodCategory:"paypal"},ui={},us={};function Wt(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function bs(e){return`${yu}:${e}`}function pi(e){return Wt(bs(e))}function mi(e,t){if(typeof window>"u")return null;let n=bs(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>pc||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(pi(e),null):o}catch{return pi(e),null}}function bu(e){return Wt(bs(e.sessionId),e)}function ec(e,t,n){let r=mi(e,t);return!r||r.clientSecret!==n?!1:pi(e)}function ps(e,t,n){if(typeof window>"u")return;mi(e,t)?.clientSecret===n&&pi(e)}function vu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ms(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":da(e.status),o=vu(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function tc(e,t,n){let r=null;try{return await Promise.race([wl(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},Pu),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Cu(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function yc(e){return e instanceof y.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function yi(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Cr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw yc(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ka="flopay_paypal_resume",wa=new Map;function fc(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(ka);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function Su(){if(typeof window>"u")return!1;let[e,t]=vs();return e?fc(t)!==null:!1}function vs(){let e=new URLSearchParams(window.location.search);return mc.map(t=>e.get(t))}function Cs(){let e=new URL(window.location.href);for(let t of mc)e.searchParams.delete(t);return e.toString()}function wu(){Wt(ka),window.history.replaceState({},"",Cs())}var ku=250,nc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Iu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Ss(e,t,n,r){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...r?{terminalReason:r}:{}})}async function fi({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Cr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Ru(e){return e instanceof y.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ys(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function gc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=mo(n),s=a.firstName?a:mo(r?.name);return On({email:(0,y.isValidEmail)(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function _u({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let s=gc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,y.isValidEmail)(s.email)?s:a(o,s)}var Eu=`
|
|
9
|
+
`})]})})}var Nl=require("@flopay/shared"),Pn=require("react");var zl=require("react/jsx-runtime");function ha({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,s]=(0,Pn.useState)(e instanceof Promise?null:e),[d,p]=(0,Pn.useState)(t instanceof Promise||!t?null:t),u=(0,Pn.useRef)(null),f=(0,Pn.useRef)(null),P=zo(r);(0,Pn.useEffect)(()=>{P({class:"lifecycle",name:"checkout.mount"})},[P]),(0,Pn.useEffect)(()=>{a&&P({class:"lifecycle",name:"sdk.initialize.ready"})},[P,a]),(0,Pn.useEffect)(()=>{if(a)return pn(a)?.subscribe?.(P)},[P,a]),(0,Pn.useEffect)(()=>{if(!(!d||d===a))return pn(d)?.subscribe?.(P)},[P,a,d]),(0,Pn.useEffect)(()=>{if(!a)return;let S=pn(a);return u.current=S?.beginCheckout()??S?.now()??0,S?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{S?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,Pn.useEffect)(()=>{let S=!1;return e instanceof Promise?e.then(T=>{S||s(T)},()=>{S||P({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{S=!0}},[P,e]),(0,Pn.useEffect)(()=>{let S=!1;if(!t){p(null);return}return t instanceof Promise?t.then(T=>{S||p(T)},()=>{S||P({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{S=!0}},[P,t]),(0,Pn.useEffect)(()=>{if(!a||f.current===a)return;f.current=a;let S=pn(a);S?.log({name:"checkout.rendered",stage:"checkout_render"}),P({class:"lifecycle",name:"checkout.rendered"}),S?.performance({stage:"checkout_render",durationMs:S.elapsed(u.current??0),durationMode:"machine"})},[P,a]);let k=(0,Nl.resolveBillingApiUrl)(n?.billingApiUrl),R=(0,Pn.useMemo)(()=>({flopay:a,paypalFlopay:d,billingApiUrl:k,emitInstrument:P}),[a,d,k,P]);return(0,zl.jsx)(tr.Provider,{value:R,children:o})}var oi="flopay_recent_completion_";function jo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(oi+e,JSON.stringify(t))}catch{}}function ns(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(oi+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(oi+e),!1):!0}catch{return!1}}async function ai(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}var ao=require("@flopay/js"),et=require("@flopay/shared");var ba="card",Wd=1e3;async function Hd(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:s}=await e.retrieveSetupIntent(t);return{error:s,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 Kd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:s??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 io(e){return new et.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function rs(){return new et.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function as(e,t){return Object.assign(e,{checkoutMethod:t})}function Gr(e,t){let n=e instanceof et.FloPayError?e:new et.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 Pa(e,t){try{return await e()}catch(n){throw Gr(n,t)}}function ql(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Gd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function is(e){if(typeof document>"u"||typeof window>"u")throw new et.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw io();let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let P=new AbortController,k=()=>P.abort();e.signal?.aborted?P.abort():e.signal?.addEventListener("abort",k);let R=window.setTimeout(()=>P.abort(),n);try{let S=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:P.signal});if(!S.ok)return{status:"unknown"};let T=await S.json().catch(()=>null);return Yd(T)}catch{return{status:"unknown"}}finally{window.clearTimeout(R),e.signal?.removeEventListener("abort",k)}},a,s=()=>e.pollCompletionEndpoint!==!1?o():(a??(a=o()),a),d=document.activeElement instanceof HTMLElement?document.activeElement:null,p=document.createElement("div");p.setAttribute("data-flopay-auto-3ds-overlay","1"),p.setAttribute("role","dialog"),p.setAttribute("aria-modal","true"),p.setAttribute("aria-label","Card authentication"),p.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let 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(";");let f=null;try{f=new URL(e.billingApiUrl,window.location.href).origin}catch{f=null}try{let P=await new Promise((k,R)=>{let S=!1,T=0,E=0,b=0,C=!1,j=()=>{window.clearTimeout(T),window.clearInterval(E),window.clearTimeout(b),window.removeEventListener("message",K),u.removeEventListener("load",re),e.signal?.removeEventListener("abort",q)},_=async()=>{if(!(S||C)){C=!0;try{let le=await s();if(S||!Gd(le))return;S=!0,j(),k(le)}finally{C=!1}}},re=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(b),b=window.setTimeout(()=>{_()},250))},q=()=>{S||(S=!0,j(),R(io()))},K=le=>{if(le.source!==u.contentWindow||f&&le.origin!==f)return;let $=le.data;!$||typeof $!="object"||$.source!=="flopay-vault-3ds-return"||S||(S=!0,j(),k(null))};T=window.setTimeout(()=>{S||(S=!0,j(),R(rs()))},et.THREE_DS_CHALLENGE_WINDOW_MS),e.pollCompletionEndpoint!==!1&&(E=window.setInterval(()=>{_()},t)),u.addEventListener("load",re),window.addEventListener("message",K),e.signal?.addEventListener("abort",q),u.src=e.nextActionRedirectUrl,p.appendChild(u),document.body.appendChild(p),u.focus(),e.signal?.aborted&&q()});return P||await s()}finally{p.parentNode?.removeChild(p),d?.isConnected&&d.focus()}}async function $o(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,a=t.nonce??t.session.clientSecret,s=new ao.PaymentAPI(n,{telemetry:!1}),d=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,p=new AbortController,u=new AbortController,f=()=>{p.abort(o.reason),u.abort(o.reason)};o.aborted?f():o.addEventListener("abort",f,{once:!0});let P=is({billingApiUrl:n,sessionId:r,nonce:a,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:p.signal,pollCompletionEndpoint:!1}),k=s.waitForCheckoutSessionCompletion(r,{initialDelayMs:Wd,nonce:a,statusUrl:d,continueAfterActionRequired:!0,timeoutMs:et.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:u.signal}),R;try{let T=await Promise.race([P,k]);if("data"in T)R=T;else{if(T.status==="declined")throw xr({type:T.declineReason??"authorization_declined",gatewayErrorCode:T.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(T.status==="timeout")throw rs();R=await k}}catch(T){if(o.aborted||T instanceof Error&&T.name==="AbortError")throw io(T);if(!(T instanceof et.FloPayError)||T.code!=="three_ds_timeout"&&T.code!=="checkout_processing_timeout")throw T;try{R=await s.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:a,statusUrl:d,timeoutMs:5e3,signal:o})}catch(b){if(o.aborted)throw io(b);if(!(b instanceof et.FloPayError)||b.code!=="checkout_processing_timeout")throw b}let E=R&&to(R,t.session);if(!$r(E)&&E?.status!=="expired"){if(t.telemetry){let b=new ao.PaymentAPI(n);try{b.reportThreeDsAbandoned(r)}finally{b.destroy()}}throw rs()}}finally{o.removeEventListener("abort",f),p.abort(),u.abort()}let S=R&&to(R,t.session);if(!$r(S))throw Do(S);return{...jr(S,r),checkoutMethod:"card"}}function Yd(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,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"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function xr(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=eo(o)??o,s=as(new et.FloPayError(a,"api_error",{code:e?.code??(0,et.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,et.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(s.orderId=e.orderId),s}function os(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ii(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Vl(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ii(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||ii(d)))return d;let s=o.gateways;if(s&&typeof s=="object"){let d=s.stripe;if(d&&typeof d=="object"){let p=d,u=[p.stripeClientSecret,p.clientSecret];for(let f of u)if(typeof f=="string"&&f.length>0&&(!t?.requirePaymentIntentClientSecret||ii(f)))return f}}}}async function Xd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Vl(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new ao.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ii(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function Wo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:s}){let d=e.replace(/\/+$/,""),p=t??n.id,u=r??n.clientSecret,f=n.customer?.id??n.accountData?.userId??"",P=n.customer?.email??n.accountData?.email??"",k=n.customer?.firstName??n.accountData?.firstName??"",R=n.customer?.lastName??n.accountData?.lastName??"",S=n.customer?.country??n.accountData?.country??void 0,T=n.customer?.zip??n.accountData?.zip??void 0,b=await new ao.PaymentAPI(d,s===!1?{telemetry:!1}:void 0).processPayment(f,{sessionId:p,nonce:u,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:f,email:P,firstName:k,lastName:R,country:S,zip:T},returnUrl:a??os(n)});if(b.ok){let _=typeof b.json=="function"?await b.json().catch(()=>null):null;if((0,et.isAuthorizationOnlySession)(n)||_?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof _?.paymentId=="string"?_.paymentId:n.paymentId,sessionId:typeof _?.sessionId=="string"?_.sessionId:p,authorizationExpiresAt:typeof _?.authorizationExpiresAt=="string"?_.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:ua(o),checkoutMethod:Ul(o,n)}};let re=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...re?{paymentIntentId:re}:{},paymentMethodId:ua(o),checkoutMethod:Ul(o,n)}}}let C;try{C=await b.json()}catch(_){throw new et.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:b.status,cause:_})}if(C?.type==="3ds_required"&&typeof C.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:C.nextActionRedirectUrl};if(C?.type==="paypal_redirect_required"||C?.type==="3ds_required"){let _=Vl(C);if(!_)throw new et.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:b.status});return{type:C.type,threeDSecureToken:_,paymentMethodId:C.paymentMethodId}}if(C?.gatewayErrorCode==="authentication_required"){let _=await Xd({billingApiUrl:d,sessionId:p,nonce:u,responseJson:C});if(_)return _;throw as(new et.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let j=new et.FloPayError(C?.message??"Payment failed. Please try again.","api_error",{code:C?.code??C?.gatewayErrorCode,declineCode:C?.declineCode??C?.gatewayDeclineReason,statusCode:b.status});throw Object.assign(j,{telemetryOutcome:(0,et.classifyPaymentRejection)(b.status,C)})}async function si(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:s,returnUrl:d,telemetry:p,signal:u}){let f=t?.getRawProvider();if(!f)throw Gr(new et.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw as(new et.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let P=(0,et.isSetupIntentClientSecret)(e.threeDSecureToken),k=null,R=e.paymentMethodId,S=await Pa(()=>Hd(f,e.threeDSecureToken,P),"card");if(S){if(S.error)throw Gr(new et.FloPayError(S.error.message??`Failed to retrieve 3DS ${P?"setup":"payment"} status.`,"api_error",{code:S.error.code}),"card");let E=S.intent;!R&&E?.payment_method&&(typeof E.payment_method=="string"?R=E.payment_method:"id"in E.payment_method&&(R=E.payment_method.id??void 0))}let T=R?await Pa(()=>Kd(f,e.threeDSecureToken,{payment_method:R,return_url:d??os(s)??window.location.href},P),"card"):null;if(T){if(T.error)throw Gr(new et.FloPayError(T.error.message??"3DS authentication failed.","api_error",{code:T.error.code}),"card");k=T.intent}else{let E=await Pa(()=>f.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(E.error)throw Gr(new et.FloPayError(E.error.message??"3DS authentication failed.","api_error",{code:E.error.code}),"card");k=(P?E.setupIntent:E.paymentIntent)??null}if(k&&(k.status==="requires_capture"||k.status==="succeeded"||k.status==="processing")){let E=await Wo({billingApiUrl:o,sessionId:a,session:s,telemetry:p,tokenizedData:{id:k.id,type:"card",threeDSecureActionResultTokenId:k.id},returnUrl:d});return E.type==="success"?{...E.result,paymentIntentId:E.result.paymentIntentId??k.id,paymentMethodId:E.result.paymentMethodId??R}:E.type==="next_action_required"?$o(E,{billingApiUrl:o,sessionId:a??s.id,session:s,signal:u}):si(E,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:s,returnUrl:d,telemetry:p,signal:u})}throw Gr(new et.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let P=(n??t)?.getRawProvider();if(!P)throw Gr(new et.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:R}=await Pa(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(R)throw Gr(new et.FloPayError(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:k}=await Pa(()=>P.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??os(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(k)throw Gr(new et.FloPayError(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new et.FloPayError("Unsupported payment redirect state.","api_error")}function va(e){if(e instanceof et.FloPayError){let r=eo(e.message);return r&&r!==e.message?Object.assign(new et.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=eo(t)??t;return new et.FloPayError(n,"api_error")}function ss(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Zr(e.data.session);if(!t&&!n&&!r)throw new et.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 Ul(e,t){return e?e.isPaypal?"paypal":"card":t&&Zr(t)?"card":void 0}async function ls({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,[s,d]=await Promise.all([(0,ao.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,ao.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(u=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",u),null)):Promise.resolve(null)]);if(!s)throw new et.FloPayError("The payment provider did not initialize.","authentication_error");let p=null;return a?p=d:t&&(p=s),{flopay:s,paypalFlopay:p}}var Cr=require("@flopay/js"),y=require("@flopay/shared"),Jt=require("@stripe/react-stripe-js"),i=ji(require("react"),1);function Ho(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function li(e,t){if(e)return{error:n=>e.error(Ho(t,n)),log:n=>e.log(Ho(t,n)),performance:n=>e.performance(Ho(t,n)),terminal:n=>e.terminal(Ho(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}var jl={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 Wn=require("react");function ci(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(s=>s.startsWith("background")),a={};for(let[s,d]of Object.entries(e))s in n||o&&s.startsWith("background")||(a[s]=d);for(let s of r)a[s]=n[s];return a}var Jd=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 Zd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Jd.has(t.charAt(0).toLowerCase()+t.slice(1))}function Qd(e,t){return typeof t=="number"&&t!==0&&!Zd(e)?`${t}px`:String(t).trim()}function $l(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]=Qd(n,r)}}}var Wl=require("react/jsx-runtime"),cs=new WeakSet;function so({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:s,onReady:d,onError:p,onValidation:u}){let f=(0,Wn.useRef)(null),P=(0,Wn.useRef)(d),k=(0,Wn.useRef)(p),R=(0,Wn.useRef)(u);P.current=d,k.current=p,R.current=u;let S=(0,Wn.useRef)(o);S.current=o;let T=(0,Wn.useRef)(null),E=a??void 0,b=(0,Wn.useRef)(E);b.current=E;let C=(0,Wn.useRef)(void 0);return(0,Wn.useEffect)(()=>{let j=f.current;if(!j)return;let _=!0,re=!1,q=()=>{!_||re||(re=!0,P.current?.())},K=e.on("ready",()=>{q()}),le=e.on("error",J=>{k.current?.(J.message??"There was a problem loading the secure card form.")}),$=e.on("validation",J=>{R.current?.(J.message??null)}),Oe=b.current??(cs.has(e)?null:void 0),Ue={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...S.current?{theme:S.current}:{},...Oe===void 0?{}:{submitLabel:Oe}};return T.current=S.current??null,C.current=b.current,b.current!==void 0&&cs.add(e),e.mount(j,Ue).then(()=>{q()}).catch(J=>{_&&k.current?.(J instanceof Error?J.message:"Failed to load the secure card form.")}),()=>{_=!1,K(),le(),$(),e.unmount()}},[e,t,n,r]),go(()=>{let j=f.current;j&&$l(j,s)},[s]),(0,Wn.useEffect)(()=>{o!==void 0&&(o===null&&T.current===null||(T.current=o,e.applyTheme?.(o)))},[e,o]),(0,Wn.useEffect)(()=>{E!==C.current&&(C.current=E,E!==void 0&&cs.add(e),e.setSubmitLabel?.(E??null))},[e,E]),(0,Wl.jsx)("div",{ref:f,"data-testid":"flopay-vault-card-fields"})}var Kl=/^#([0-9a-f]{6})$/i,eu=/^#([0-9a-f]{3})$/i,Gl=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Yl=/^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,tu=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,nu=/^(-?\d+(?:\.\d+)?)(?:px)?$/,ru=/^(-?\d+(?:\.\d+)?)em$/,ou=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,au=/^[a-z][a-z0-9 -]{0,31}$/i,iu=new Set(["none","uppercase","lowercase","capitalize"]);function Xl(e){if(typeof e!="string")return null;let t=e.trim(),n=Kl.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=eu.exec(t);if(r){let[f,P,k]=r[1].split("").map(R=>Number.parseInt(R+R,16));return{r:f,g:P,b:k,a:null}}let o=Gl.exec(t),a=o?null:Yl.exec(t),s=o??a;if(!s)return null;let d=Number(s[1]),p=Number(s[2]),u=Number(s[3]);return d>255||p>255||u>255?null:{r:d,g:p,b:u,a:a?Number(a[4]):null}}function Jl({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 Ca(e){if(typeof e!="string")return;let t=e.trim();if(Kl.test(t)||Gl.test(t))return t;let n=Yl.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=Xl(t);return r?Jl(r):void 0}function di(e,t=.12){let n=Xl(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Jl({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function Sa(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 Po(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=nu.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function su(e,t,n){if(typeof e!="string")return;let r=ru.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function lu(e){let t=Sa(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=Sa(o," "),s=Ca(a[0]);if(!s)return;let d=r/(t.length-1)*100,p=a[1]===void 0?d:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),u=n[n.length-1]?.position??-1;if(!Number.isFinite(p)||p<0||p>100||p<u)return;n.push({color:s,position:p})}return{type:"linearGradient",angle:0,stops:n}}function cu(e){if(typeof e!="string")return;let t=e.trim(),n=Ca(t);if(n)return{type:"solid",color:n};let r=tu.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=lu(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function du(e){return e.type==="solid"?{type:"solid",color:di(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:di(t.color)}))}}function uu(e){let t=!1,n,r=[];for(let p of Sa(e," ")){if(p.toLowerCase()==="inset"){t=!0;continue}let u=Ca(p);if(u){n=u;continue}let f=Po(p,-128,128);if(f===void 0)return;r.push(f)}if(!n||r.length<2||r.length>4)return;let[o,a,s=0,d=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||s>128||Math.abs(d)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:s,spread:d}}function pu(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=Sa(t,",").map(uu);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function Hl(e){if(typeof e!="string")return;let t=Sa(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>au.test(n)).slice(0,4);return t.length>0?t:void 0}function mu(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=Po(t[0],0,64),r=Po(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function yu(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 Zl({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=cu(r.background??r.backgroundColor),s=Ca(o?.colorPrimaryHover),d=s?{type:"solid",color:s}:a&&du(a),p={fontFamilies:Hl(r.fontFamily)??Hl(n),fontSize:Po(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:yu(r.fontWeight)??600,letterSpacing:su(r.letterSpacing,-.1,.5)??.01,lineHeight:Po(r.lineHeight,.8,2)??1,textTransform:iu.has(String(r.textTransform))?r.textTransform:"uppercase"},u=mu(r.padding),f=pu(r.boxShadow),P=Po(r.borderRadius,0,9999),k=typeof r.backdropFilter=="string"?Po(ou.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Ca(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...d?{hoverBackground:d}:{},typography:p,...u?{spacing:u}:{},...f?{shadow:f}:{},...P===void 0?{}:{borderRadius:P},disabledOpacity:e?.theme==="night"?.8:.6,...k===void 0?{}:{backdropBlur:k}}}function Ko(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)?di(r,t):e}function ds(e){if(typeof e=="number"||typeof e=="string")return e}function Go({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=P=>typeof P=="string"&&P?P:void 0,a=t.submitButton,s=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",d=n==="buttons",p=t.nameInput,u=o(p?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",f=Zl({appearance:e,buttonsStyles:t,fontFamily:u});return{primaryColor:s,primaryHoverColor:o(r?.colorPrimaryHover)??Ko(s,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(p?.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:u,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(ds(p?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...f?{submitButton:f}:{}}}var c=require("react/jsx-runtime"),Fr="flopay_stripe_resume",Ql="flopay_wallet_resume",pc="fw1",fu="fw2",mc=300*1e3,gu=900,hu=25e3,Pu=25e3,bu=1e4,yc=["payment_intent","payment_intent_client_secret","redirect_status"],vr={provider:"paypal",paymentMethodCategory:"paypal"},ui={},us={};function $t(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function bs(e){return`${fu}:${e}`}function pi(e){return $t(bs(e))}function mi(e,t){if(typeof window>"u")return null;let n=bs(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>mc||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(pi(e),null):o}catch{return pi(e),null}}function vu(e){return $t(bs(e.sessionId),e)}function ec(e,t,n){let r=mi(e,t);return!r||r.clientSecret!==n?!1:pi(e)}function ps(e,t,n){if(typeof window>"u")return;mi(e,t)?.clientSecret===n&&pi(e)}function Cu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ms(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":da(e.status),o=Cu(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function tc(e,t,n){let r=null;try{return await Promise.race([wl(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},bu),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Su(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function fc(e){return e instanceof y.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function yi(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Cr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw fc(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ka="flopay_paypal_resume",wa=new Map;function gc(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(ka);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function wu(){if(typeof window>"u")return!1;let[e,t]=vs();return e?gc(t)!==null:!1}function vs(){let e=new URLSearchParams(window.location.search);return yc.map(t=>e.get(t))}function Cs(){let e=new URL(window.location.href);for(let t of yc)e.searchParams.delete(t);return e.toString()}function ku(){$t(ka),window.history.replaceState({},"",Cs())}var Iu=250,nc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Ru="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Ss(e,t,n,r){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...r?{terminalReason:r}:{}})}async function fi({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Cr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function _u(e){return e instanceof y.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ys(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function hc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=mo(n),s=a.firstName?a:mo(r?.name);return On({email:(0,y.isValidEmail)(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Eu({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let s=hc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,y.isValidEmail)(s.email)?s:a(o,s)}var Tu=`
|
|
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 @@ ${Ke.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
|
-
`,Ia=44,Ra=180,rc=`flopay-card-enter ${Ra}ms cubic-bezier(0, 0, 0.2, 1) both`,oc=`flopay-card-exit ${Ra}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Tu=`flopay-buttons-enter ${Ra}ms cubic-bezier(0, 0, 0.2, 1) both`,Au=`flopay-buttons-exit ${Ra}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function xu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ws(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 Mu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Fu(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 gs={width:"100%",minHeight:Ia,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Bu(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ac(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function hs(e){return e==="paypal"?"PayPal":(0,y.getStripeMethodDisplayName)(e)}function Du(e){let t=(0,y.getPostalCodeExample)(e);return`Enter a valid ${(0,y.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Ou(e,t,n){let r=(0,y.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,s=a&&!o,c=a&&!!o&&!(0,y.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:s,malformed:c}}function Lu(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,y.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function ic(e,t){return t instanceof y.FloPayError?t:new y.FloPayError(t instanceof Error?t.message:`${Bu(e)} before-click hook failed.`,"validation_error")}function fs(){return(0,d.jsx)("style",{children:Eu})}function Nu(e){return typeof e=="number"?`${e}px`:e}function hc(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Pc({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,d.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,d.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,d.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function sc(e){return e!=="unavailable"&&e!=="load_error"}function gi(e){return(0,d.jsx)(Uu,{...e})}function lc({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:s=!1,onButtonClick:c,onDecline:u,onTechnicalFailure:p,runBeforeButtonClick:h,billingName:b,onBuyerIdentityReady:I,onLoadStateChange:k,placeholderBorderRadius:C,popupCapabilityOwner:f,externalTelemetryContext:S,presentationMode:G}){let _=Hr(),{emitInstrument:q}=(0,i.useContext)(rr),E=(0,Zt.useStripe)(),ne=(0,Zt.useElements)(),$=(0,i.useMemo)(()=>li(pn(_),S),[S,_]),[W,ie]=(0,i.useState)("loading");(0,i.useEffect)(()=>{k?.(W)},[W,k]);let[V,Be]=(0,i.useState)(!1),Ue=(0,i.useRef)(!1),X=!(0,y.isValidEmail)(n?.trim())||!b?.trim(),{request:Ae,collect:it,finish:Re}=Oo(),xe=(0,i.useRef)(!1),ve=(0,i.useRef)(null),se=(0,i.useRef)(null),[me,He]=(0,i.useState)(0),[st,T]=(0,i.useState)(!1),ye=(0,i.useRef)(!1),le=(0,i.useRef)(new Map),{startAttempt:F,finishAttempt:Se,invalidateAttempt:ce,isAttemptInvalidated:De,isAttemptCurrent:re,generationRef:$e}=ya((U,we,lt)=>{p?.(U,we,{...lt,popupBlocked:lt?.popupBlocked??oo(we),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:G,terminalReason:"overlay_timeout"}),T(!0),He(Z=>Z+1)},{onHandoffObserved:()=>{f.markAvailable(),$?.log({name:"provider.popup.opened",stage:"overlay_open",...vr,attempt:$e.current})}});(0,i.useEffect)(()=>{st&&se.current?.focus()},[st,me]);let dt=(0,i.useCallback)(()=>{He(U=>U+1)},[]),Me=(0,i.useCallback)((U,we,lt)=>{ce(lt),p?.("paypal",U,{code:we,popupBlocked:oo(U),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:G}),T(!0),dt()},[ce,p,G,dt]),Oe=(0,i.useCallback)(()=>{window.setTimeout(()=>{(ve.current?.querySelector("iframe")??ve.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{ye.current&&(ye.current=!1,Oe())},[Oe,me]);let ut=(0,i.useCallback)(()=>{T(!1),a?.(null),Oe()},[Oe,a]);(0,i.useEffect)(()=>{if(!E||xe.current)return;let[U,we,lt]=vs();if(!U||!we)return;let Z=fc(we);if(!Z)return;xe.current=!0;let qe=!0,St=wa.get(we);St||(St=lt==="failed"?Promise.resolve(null):Promise.resolve().then(()=>E.retrievePaymentIntent(we)),wa.set(we,St));let Ze={accountPatch:Z.accountPatch,sessionId:Z.sessionId,nonce:Z.nonce},H=()=>{$?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...vr,requestCategory:"provider_sdk"})};return $?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...vr}),(async()=>{try{Be(!0);let g=await St;if(!qe)return;if(g?.error){wa.delete(we),H(),a?.(g.error.message??"Failed to retrieve PayPal payment status.");return}if(wu(),wa.delete(we),lt==="failed"){let ee="PayPal payment was declined. Please try again.";$?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}),a?.(ee),u?.(un("paypal",ee));return}let v=g?.paymentIntent;if(v&&v.id!==U){H(),a?.("Failed to match the returned PayPal payment.");return}if(v&&(v.status==="requires_capture"||v.status==="succeeded")){let ee=typeof v.payment_method=="string"?v.payment_method:v.payment_method?.id;o({id:ee??v.id,type:"card",threeDSecureActionResultTokenId:v.id,isPaypal:!0},{...Ze,presentationMode:"redirect"})}else{let ee="PayPal payment was not completed. Please try again.";$?.terminal({outcome:v?.status==="canceled"?"payment_cancelled":"payment_declined",...vr,terminalReason:v?.status==="canceled"?"cancelled":"provider_declined"}),a?.(ee),u?.(un("paypal",ee))}}catch(g){if(!qe)return;wa.delete(we),H(),a?.(g instanceof Error?g.message:"Failed to complete PayPal payment.")}finally{qe&&Be(!1)}})(),()=>{qe=!1,xe.current=!1}},[E,o,a,u,$]);let Y=(0,i.useCallback)(async(U=!1)=>{let we=h?await h("paypal"):{proceed:!0};if(!we.proceed)return le.current.delete(me),!1;let lt=F("paypal");return le.current.set(me,{generation:lt,accountPatch:we.accountPatch,sessionId:we.sessionId,nonce:we.nonce}),T(!1),$?.log({name:`provider.${U?"redirect.started":"handoff.requested"}`,stage:U?"redirect":"overlay_open",...vr,attempt:lt}),c?.("paypal"),!0},[c,$,h,F,me]),J=(0,i.useCallback)(async U=>{if(s||V||!await Y()){U.reject();return}U.resolve()},[s,Y,V]),mt=(0,i.useCallback)(async U=>{if(!E||!ne)return;let we=le.current.get(me);if(we&&!re(we.generation)){le.current.delete(me);return}if(!we&&De()||we&&!Se(we.generation))return;we||Se();let lt=we??null;if(le.current.delete(me),!lt&&h){let nt=await h("paypal");if(!nt.proceed){U.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}lt={accountPatch:nt.accountPatch,sessionId:nt.sessionId,nonce:nt.nonce}}let Z=lt?.sessionId??e,qe=lt?.nonce??t,St=await _u({event:U,prepared:lt,email:n,billingName:b,methodLabel:"PayPal",collect:it});if(!St){U.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ze=St.email,H={...lt?.accountPatch,...On(St,!0)};try{if(Be(!0),a?.(null),!Z||!(0,y.isValidEmail)(Ze))throw new Error("Missing sessionId or email for PayPal payment");await I?.(St);let nt=E.createPaymentMethod,{error:g,paymentMethod:v}=await nt({type:"paypal"});if(g){Me(g,"stripe_paypal_create_payment_method_failed",we?.generation),U.paymentFailed({reason:"fail"});return}let ee=await yi(r,q,Z,qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:v?.id??null,intentKind:"payment"});if(ee.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let de=ee.clientSecret,Xe={return_url:Cs()};if(v?.id&&(Xe.payment_method=v.id),!Wt(ka,{clientSecret:de,sessionId:Z,nonce:qe,accountPatch:H})&&G==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:Qe,paymentIntent:ae}=await E.confirmPayment({clientSecret:de,confirmParams:Xe,redirect:"if_required"});if(Qe){if(Wt(ka),fo(Qe)){let It=Qe.message??"Your payment was declined.";$?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}),a?.(It),u?.(un("paypal",It,{code:Mr(Qe),declineCode:No(Qe)})),await fi({billingApiUrl:r,sessionId:Z,nonce:qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mr(Qe)??"provider_declined"}})}else Me(Qe,"stripe_paypal_confirm_failed",we?.generation);return}Wt(ka);let yt=typeof ae?.payment_method=="string"?ae.payment_method:ae?.payment_method?.id;o({id:yt??ae?.id,type:"card",threeDSecureActionResultTokenId:ae?.id,isPaypal:!0},{accountPatch:H,paymentMethodCategory:"paypal",presentationMode:G,sessionId:Z,nonce:qe});return}catch(nt){Me(nt,"stripe_paypal_failed",we?.generation)}finally{Be(!1)}},[E,ne,e,t,n,b,it,I,r,q,o,a,u,h,Me,Se,re,De,$,G,me]),gt=(0,i.useCallback)(async()=>{if(!(Ue.current||s||V||!E||!ne)){Ue.current=!0,Be(!0);try{if(!await Y(!0))return;await mt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Ue.current=!1,Be(!1)}}},[ne,mt,s,Y,E,V]),Ie=G==="redirect"?(0,d.jsx)("button",{type:"button",disabled:s||V,onClick:()=>{gt()},style:{width:"100%",minHeight:Ia,border:"1px solid #d1d5db",borderRadius:C??8,background:"#ffc439",color:"#111827",cursor:s||V?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,d.jsx)(Zt.ExpressCheckoutElement,{onReady:U=>ie(hc(U,["paypal"])),onLoadError:()=>{ie("load_error"),Ss($,"paypal","paypal","provider_error")},onClick:J,onConfirm:mt,onCancel:()=>{let U=le.current.get(me);le.current.delete(me),$?.terminal({outcome:"payment_cancelled",...vr,terminalReason:"cancelled",...U?{attempt:U.generation}:{}}),ce(U?.generation),T(!1),ye.current=!0,dt()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:X,emailRequired:X,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},me),ft=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{ref:ve,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[st&&(0,d.jsx)("button",{ref:se,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ut,style:gs,children:"Try PayPal again"}),Ae&&(0,d.jsx)(Lo,{identity:Ae.identity,methodLabel:Ae.methodLabel,onComplete:Re,onCancel:()=>Re(null)},Ae.id),(0,d.jsx)("div",{style:{display:Ae?"none":void 0},children:Ie})]}),V&&!Ae&&(0,d.jsx)(Ln,{status:"processing"})]});return G==="redirect"?ft:(0,d.jsx)(Pc,{state:W,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:ft})}function cc({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:s,onErrorChange:c,onButtonClick:u,onDecline:p,onTechnicalFailure:h,runBeforeButtonClick:b,billingName:I,onBuyerIdentityReady:k,onLoadStateChange:C,placeholderBorderRadius:f,popupCapabilityOwner:S,externalTelemetryContext:G}){let _=Hr(),{emitInstrument:q}=(0,i.useContext)(rr),E=(0,Zt.useStripe)(),ne=(0,Zt.useElements)(),$=(0,i.useMemo)(()=>li(pn(_),G),[G,_]),[W,ie]=(0,i.useState)("loading");(0,i.useEffect)(()=>{C?.(W)},[W,C]);let[V,Be]=(0,i.useState)(!1),Ue=(0,i.useRef)(!(0,y.isValidEmail)(n?.trim())||!I?.trim()).current,{request:X,collect:Ae,finish:it}=Oo(),Re=(0,i.useRef)(null),xe=(0,i.useRef)(null),[ve,se]=(0,i.useState)(0),[me,He]=(0,i.useState)(!1),[st,T]=(0,i.useState)(()=>mi(e,t)?"blocked":"idle"),[ye,le]=(0,i.useState)("google_pay"),F=(0,i.useRef)(null),Se=(0,i.useRef)(!0),ce=(0,i.useRef)(!1),De=(0,i.useRef)("google_pay"),re=(0,i.useRef)("google_pay"),$e=(0,i.useRef)(null),dt=(0,i.useRef)(null),Me=(0,i.useRef)(new Set);(0,i.useEffect)(()=>(Se.current=!0,()=>{Se.current=!1;for(let H of Me.current)window.clearTimeout(H);Me.current.clear()}),[]);let Oe=(0,i.useRef)(new Map),{startAttempt:ut,finishAttempt:Y,invalidateAttempt:J,isAttemptInvalidated:mt,isAttemptCurrent:gt,generationRef:Ie}=ya((H,nt,g)=>{h?.(H,nt,{...g,popupBlocked:g?.popupBlocked??oo(nt),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),le(H),He(!0),se(v=>v+1)},{onHandoffObserved:H=>{S.markAvailable(),$?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Ie.current,...H==="apple_pay"||H==="google_pay"?{walletType:H}:{}})}});(0,i.useEffect)(()=>{me&&xe.current?.focus()},[me,ve]);let ft=(0,i.useCallback)(()=>{se(H=>H+1)},[]),U=(0,i.useCallback)((H,nt,g,v,ee=!1)=>{J(v),h?.(H,nt,{code:g,popupBlocked:oo(nt),telemetryReported:ee,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),le(H),He(!0),ft()},[J,h,ft]),we=(0,i.useCallback)(()=>{window.setTimeout(()=>{(Re.current?.querySelector("iframe")??Re.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{ce.current&&(ce.current=!1,we())},[we,ve]);let lt=(0,i.useCallback)(()=>{He(!1),c?.(null),we()},[we,c]),Z=(0,i.useCallback)(()=>{F.current?.()},[]);(0,i.useEffect)(()=>{let H=mi(e,t);if(!H)return;let nt=!1,g=!1,v=async()=>{if(!g){g=!0,nt||T("checking");try{let ee=await tc(E,H.clientSecret,Me.current);if(nt)return;let de=ms(ee,H.providerObjectId,(0,y.isSetupIntentClientSecret)(H.clientSecret));if(de.kind==="confirmed"){if(!ec(e,t,H.clientSecret))return;F.current=null,T("idle"),s({id:de.paymentMethodId,type:"card",threeDSecureActionResultTokenId:de.intentId},{...H.accountPatch?{accountPatch:H.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(de.kind==="terminal"){ps(e,t,H.clientSecret),F.current=null,T("idle"),le(H.paymentMethodType),He(!0),ft();return}T("blocked")}catch{nt||T("blocked")}finally{g=!1}}};return F.current=v,T("blocked"),()=>{nt=!0,F.current===v&&(F.current=null)}},[t,s,ft,e,E]);let qe=(0,i.useCallback)(async H=>{let nt=!1,g=Ee=>{nt||(nt=!0,H.paymentFailed({reason:"fail",...Ee?{message:Ee}:{}}))};if(!E||!ne){g();return}let v=Oe.current.get(ve);if(v&&!gt(v.generation)){Oe.current.delete(ve),g();return}if(!v&&mt()){g();return}if(v&&!Y(v.generation)){g();return}v||Y();let ee=H.expressPaymentType??v?.method??De.current,de=v??null,Xe=ac(ee),kt;ee==="apple_pay"?kt="apple_pay":ee==="google_pay"&&(kt="google_pay");let Qe=v?.generation??Ie.current,ae=$,yt=ae?.now()??globalThis.performance?.now()??Date.now(),It=new AbortController,qt=!1,Ke=!1,Lt=null,Ge=e,zn="processing",Tn="other",Dt="provider_runtime",Rn,Un=new Promise((Ee,Rt)=>{Rn=Rt}),qn=window.setTimeout(()=>{qt=!0,It.abort(),Rn(ui)},gu),on=async(Ee,Rt,Mt)=>{zn=Ee,Tn=Rt,Dt=Rt==="intent_create"||Rt==="session_claim"?"transport_error":"provider_runtime";let wn=ae?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Mt,Un])}finally{let Ot=ae?.now()??globalThis.performance?.now()??Date.now();ae?.performance({stage:Ee,durationMs:Math.max(0,Ot-wn),durationMode:"machine",requestCategory:Rt,paymentMethodCategory:"wallet",provider:"stripe",...qt?{statusClass:"timeout"}:{}})}};try{if(Be(!0),c?.(null),!de&&b){let Le=await on("processing","other",b(Xe));if(!Le.proceed){g();return}de={accountPatch:Le.accountPatch,sessionId:Le.sessionId,nonce:Le.nonce}}let Ee=de?.sessionId??e;Ge=Ee;let Rt=de?.nonce??t,Mt=$e.current??de?.accountPatch,wn=gc({event:H,fallbackEmail:Mt?.email??n,fallbackName:[Mt?.firstName,Mt?.lastName].join(" ").trim()||I});if(!(0,y.isValidEmail)(wn.email)){g("Buyer details are required."),Ae(hs(ee),wn).then(Le=>{Le&&($e.current=Le)});return}$e.current=null;let Ot={...de?.accountPatch,...On(wn,!0)};await on("processing","session_claim",Promise.resolve(k?.(wn)));let{error:Yn}=await on("tokenization","provider_sdk",ne.submit());if(Yn){g(),U(ee,Yn,"stripe_wallet_submit_failed",v?.generation);return}if(!Ee)throw new Error("Missing sessionId or email for payment.");let yn={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ee,paymentMethodId:null,intentKind:o},Ht=JSON.stringify({sessionId:Ee,nonce:Rt??"",request:yn}),ln=dt.current,Xn=ln?.retryIdentity===Ht?ln.authorizationAttemptId:(0,y.randomUuidV4)();dt.current={authorizationAttemptId:Xn,retryIdentity:Ht};let fn=await on("processing","intent_create",yi(r,q,Ee,Rt??"",{...yn,authorizationAttemptId:Xn},{signal:It.signal}));if(fn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let _t=fn.clientSecret,Qt=bu({createdAt:Date.now(),sessionId:Ee,...Rt?{nonce:Rt}:{},clientSecret:_t,providerObjectId:fn.providerObjectId,paymentMethodType:ee,accountPatch:Ot});window.clearTimeout(qn),Ke=!0,ae?.performance({stage:"callback",durationMs:Math.max(0,(ae?.now()??globalThis.performance?.now()??Date.now())-yt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let gn=ae?.now()??globalThis.performance?.now()??Date.now(),Nt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...kt?{walletType:kt}:{},attempt:Qe},en=!1,Kt=null;ae?.log({name:"payment.provider_confirmation.started",...Nt}),Lt=window.setTimeout(()=>{Lt!==null&&Me.current.delete(Lt),en=!0;let Le=ae?.now()??globalThis.performance?.now()??Date.now();ae?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Nt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Le-gn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),ae?.flush?.().catch(()=>{}),Kt?.()},hu),Me.current.add(Lt);let hn=(Le,Ct)=>{Lt!==null&&(window.clearTimeout(Lt),Me.current.delete(Lt),Lt=null);let ge=ae?.now()??globalThis.performance?.now()??Date.now(),L=Math.max(0,ge-gn),rt=Le;en&&(Le==="resolved"?rt="resolved_late":Le==="returned_error"?rt="returned_error_late":rt="rejected_late");let he=Ct??(Le==="resolved"?"approved":"provider_error");return ae?.log({name:"payment.provider_confirmation.returned",...Nt,operationOutcome:rt,terminalReason:he}),ae?.performance({...Nt,durationMs:L,durationMode:"buyer",operationOutcome:rt,terminalReason:he}),{durationMs:L,operationOutcome:rt,terminalReason:he}},vt=!1,ue=!1,Vn=Le=>{if(!Le||typeof Le!="object")return null;let Ct=Le;if(Ct.error)return null;let ge=Ct.setupIntent??Ct.paymentIntent,L=ms(ge??null,void 0,!!Ct.setupIntent);return L.kind==="confirmed"?L:null},jn=Le=>{if(vt||v&&Ie.current!==v.generation)return;let Ct=Vn(Le);if(!Ct)return;if(Qt&&!ec(Ee,Rt,_t)){vt=!0;return}let{intentId:ge,paymentMethodId:L}=Ct;vt=!0,ue=!0,dt.current=null,F.current=null,Se.current&&(T("idle"),Be(!1));let rt=`${uc}:${Ee}`;Wt(rt,{createdAt:Date.now(),sessionId:Ee,nonce:Rt,accountPatch:Ot,paymentMethodId:L,providerIntentId:ge,paymentMethodType:ee});try{s({id:L,type:"card",threeDSecureActionResultTokenId:ge},{accountPatch:Ot,paymentMethodCategory:"wallet",sessionId:Ee,nonce:Rt})}finally{Wt(rt)}},Sr=!1;Kt=async()=>{if(!(Sr||vt||ue)){Sr=!0,Se.current&&T("checking");try{let Le=await tc(E,_t,Me.current);if(vt||ue)return;let Ct=(0,y.isSetupIntentClientSecret)(_t),ge=ms(Le,fn.providerObjectId,Ct);if(ge.kind==="confirmed"){jn(Ct?{setupIntent:Le}:{paymentIntent:Le});return}if(ge.kind==="terminal"){if(ue=!0,ps(Ee,Rt,_t),dt.current=null,F.current=null,!Se.current)return;T("idle"),g(),U(ee,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",v?.generation,!0);return}Se.current&&!ue&&(T("blocked"),Be(!1))}catch{Se.current&&!ue&&(T("blocked"),Be(!1))}finally{Sr=!1}}},F.current=Kt;let kn,cn;try{let Le=await((0,y.isSetupIntentClientSecret)(_t)?E.confirmSetup({elements:ne,clientSecret:_t,redirect:"if_required"}):E.confirmPayment({elements:ne,clientSecret:_t,redirect:"if_required"}));if(!Le||typeof Le!="object"||(kn=Le,!kn.error&&!Vn(kn)))throw us;cn=hn(kn.error?"returned_error":"resolved",kn.error&&fo(kn.error)?"provider_declined":void 0)}catch(Le){let Ct=Le===us,ge=hn(Ct?"returned_error":"rejected");if(ae?.error({...Ct?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:Gi(Le),...Nt,operationOutcome:ge.operationOutcome,durationMs:ge.durationMs,statusClass:"unknown",terminalReason:ge.terminalReason}),!Se.current||vt)return;await Kt?.();return}let An=kn.error;if(An){if(!Se.current||vt)return;if(fo(An)){ue=!0,ps(Ee,Rt,_t),dt.current=null,F.current=null,T("idle");let Le=An.message??"Your payment was declined.";g(Le),c?.(Le),p?.(un(Xe,Le,{code:Mr(An),declineCode:No(An)})),fi({billingApiUrl:r,sessionId:Ee,nonce:Rt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ee,providerDeclineReason:Mr(An)??"provider_declined",...fn.intentKind==="payment"&&fn.providerObjectId.startsWith("pi_")?{providerIntentId:fn.providerObjectId}:{}}})}else ae?.error({...Gi(An),...Nt,operationOutcome:cn.operationOutcome,durationMs:cn.durationMs,statusClass:"unknown",terminalReason:cn.terminalReason}),await Kt?.();return}if(jn(kn),!vt)throw new Error("Invalid provider returned for APM intent")}catch(Ee){if(Ee===ui){let Rt=ae?.now()??globalThis.performance?.now()??Date.now();ae?.error({errorCode:Cu(Tn),stage:zn,requestCategory:Tn,paymentMethodCategory:"wallet",provider:"stripe",...kt?{walletType:kt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ge,durationMs:Math.max(0,Rt-yt),statusClass:"timeout",failureCategory:Dt,attempt:Qe,terminalReason:"provider_error"}),ae?.flush?.().catch(()=>{})}g(),U(ee,Ee,Ee===ui?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",v?.generation,Ee===ui)}finally{if(window.clearTimeout(qn),Lt!==null&&(window.clearTimeout(Lt),Me.current.delete(Lt)),!Ke){let Ee=ae?.now()??globalThis.performance?.now()??Date.now();ae?.performance({stage:"callback",durationMs:Math.max(0,Ee-yt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...qt?{statusClass:"timeout"}:{}})}Se.current&&Be(!1)}},[E,ne,e,t,n,I,Ae,k,r,q,o,s,c,p,b,U,Y,gt,mt,Ie,$,ve]),St=(0,i.useMemo)(()=>{let H=["applePay","googlePay","paypal","link","amazonPay","klarna"],nt=new Set(["applePay","googlePay"]),g=new Set(a.map(y.stripeExpressMethodToOptionKey)),v={};for(let ee of H)g.has(ee)?v[ee]=nt.has(ee)?"always":"auto":v[ee]="never";return v},[a]),Ze=(0,i.useMemo)(()=>a.map(y.stripeExpressMethodToOptionKey),[a]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Pc,{state:W,placeholderTestId:"flopay-wallet-placeholder",borderRadius:f,children:(0,d.jsxs)("div",{ref:Re,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[me&&(0,d.jsxs)("button",{ref:xe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:lt,style:gs,children:["Try ",hs(ye)," again"]}),st!=="idle"&&(0,d.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,d.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,d.jsx)("button",{type:"button",onClick:Z,disabled:st==="checking",style:gs,children:st==="checking"?"Checking payment status\u2026":"Check payment status"})]}),X&&(0,d.jsx)(Lo,{identity:X.identity,methodLabel:X.methodLabel,onComplete:it,onCancel:()=>it(null)},X.id),st==="idle"&&(0,d.jsx)("div",{style:{display:X?"none":void 0},children:(0,d.jsx)(Zt.ExpressCheckoutElement,{onReady:H=>{ie(hc(H,Ze))},onLoadError:H=>{ie("load_error"),Ss($,"stripe","wallet","provider_error")},onClick:async H=>{De.current=H.expressPaymentType,re.current=ac(H.expressPaymentType);let nt=!0,g=window.setTimeout(()=>{nt=!1,H.reject()},fu),v=b?await b(re.current):{proceed:!0};if(window.clearTimeout(g),!nt)return;if(!v.proceed){Oe.current.delete(ve),H.reject();return}let ee=ut(H.expressPaymentType);Oe.current.set(ve,{generation:ee,method:H.expressPaymentType,accountPatch:v.accountPatch,sessionId:v.sessionId,nonce:v.nonce}),He(!1),$?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ee,...H.expressPaymentType==="apple_pay"||H.expressPaymentType==="google_pay"?{walletType:H.expressPaymentType}:{}}),u?.(re.current),H.resolve()},onConfirm:qe,onCancel:()=>{let H=Oe.current.get(ve);Oe.current.delete(ve),$?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...H?{attempt:H.generation}:{}}),J(H?.generation),dt.current=null,He(!1),ce.current=!0,ft()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:St,emailRequired:Ue,billingAddressRequired:Ue,layout:{maxColumns:1,overflow:"never"}}},ve)})]})}),V&&(0,d.jsx)(Ln,{status:"processing"})]})}function bc(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function zu({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:s,backgroundColor:c,borderColor:u,textColor:p,borderRadius:h,fontFamily:b}){let I=(0,y.resolveStripeMethodBrandVariant)(e,t),k=jl[e],[C,f]=(0,i.useState)(!1),S=!!k&&!C,G=I?.backgroundColor??c??"#ffffff",_=I?.borderColor??u??"#d1d5db",q=I?.textColor??p??"#262833";return(0,d.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&s()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Ia,padding:"0 1rem",backgroundColor:G,color:q,border:`1px solid ${_}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,d.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,y.getStripeMethodDisplayName)(e)}\u2026`}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,y.hasVendoredStripeMethodLogo)(e)?8:0},children:[S?(0,d.jsx)("img",{src:k,alt:"","aria-hidden":"true",onError:()=>f(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!S&&I?.logoSvg?(0,d.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:I.logoSvg}}):null,(0,d.jsx)("span",{children:(0,y.getStripeMethodDisplayName)(e)})]}),a&&(0,d.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,d.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Ps({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:c,onErrorChange:u,onDecline:p,onCancel:h,runBeforeButtonClick:b,onButtonClick:I,isProcessing:k,submitButtonColor:C,submitButtonBorderRadius:f,submitButtonStyle:S,errorText:G}){let _=Hr(),{emitInstrument:q}=(0,i.useContext)(rr),E=(0,Zt.useStripe)(),ne=(0,Zt.useElements)(),[$,W]=(0,i.useState)(!1),ie=(0,i.useRef)(!1),[V,Be]=(0,i.useState)(!1),[Ue,X]=(0,i.useState)("loading"),[Ae,it]=(0,i.useState)(""),Re=!(0,y.isValidEmail)(r?.trim()),xe=!Re||(0,y.isValidEmail)(Ae.trim()),ve=(0,i.useCallback)(async()=>{if(!E||!ne||k||ie.current||!V)return;ie.current=!0,W(!0);let se=b?await b("card"):{proceed:!0};if(!se.proceed){ie.current=!1,W(!1);return}I?.("card");let me=se.sessionId??t,He=se.nonce??n,st=mo(o?.trim()),T=On({email:se.accountPatch?.email?.trim()||r?.trim()||Ae.trim(),firstName:se.accountPatch?.firstName?.trim()||st.firstName,lastName:se.accountPatch?.lastName?.trim()||st.lastName}),ye=T.email,le=On({...se.accountPatch,...T});try{if(u?.(null),!(0,y.isValidEmail)(ye))throw new Error("A valid email address is required for payment.");await a?.(T);let F=await ne.submit();if(F.error){u?.(F.error.message??"Payment failed.");return}let Se=[T.firstName,T.lastName].filter(Boolean).join(" "),ce=await E.createPaymentMethod({elements:ne,params:{billing_details:{email:ye,...Se?{name:Se}:{}}}});if(ce.error||!ce.paymentMethod){u?.(ce.error?.message??"Failed to create payment method.");return}let De=ce.paymentMethod;if(!me||!ye)throw new Error("Missing sessionId or email for payment.");let re=De.type||e,$e=await yi(s,q,me,He??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,paymentMethodId:null,intentKind:"payment"});if($e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let dt=$e.clientSecret;Wt(Br,{clientSecret:dt,sessionId:me,nonce:He,accountPatch:le,paymentMethodId:De.id,paymentMethodType:De.type??e,gateway:"stripe"});let{error:Me,paymentIntent:Oe}=await E.confirmPayment({clientSecret:dt,confirmParams:{return_url:window.location.href,payment_method:De.id},redirect:"if_required"});if(Me){Wt(Br);let J=Me.message??"Payment failed.";u?.(J),p?.(un("card",J,{code:Me.code})),await fi({billingApiUrl:s,sessionId:me,nonce:He,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Me.code??"provider_declined"}});return}let ut=Oe?.status;if(!da(ut)){Wt(Br);let J=ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";u?.(J),p?.(un("card",J,{code:ut??"missing_payment_intent"}));return}Wt(Br);let Y=typeof Oe?.payment_method=="string"?Oe.payment_method:Oe?.payment_method?.id;c({id:Y??De.id,type:"card",threeDSecureActionResultTokenId:Oe?.id,gateway:"stripe",paymentMethodType:De.type??e},{accountPatch:le,paymentMethodCategory:"apm",sessionId:me,nonce:He})}catch(F){u?.(F instanceof Error?F.message:"Payment failed. Please try again.")}finally{ie.current=!1,W(!1)}},[E,ne,k,V,b,I,t,n,r,o,Ae,a,s,q,e,c,u,p]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Re&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Re&&(0,d.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,d.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Ae,onChange:se=>it(se.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(Zt.PaymentElement,{onReady:()=>X("ready"),onLoadError:()=>{X("load_error"),Ss(pn(_),"stripe","apm")},onChange:se=>{Be(!!se.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,y.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,d.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{ve()},disabled:!V||!xe||$||k||Ue!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:C,color:"white",border:"none",borderRadius:f,fontSize:"1rem",fontWeight:600,cursor:!V||!xe||$||k||Ue!=="ready"?"not-allowed":"pointer",opacity:!V||!xe||$||k||Ue!=="ready"?.5:1,transition:"opacity 120ms ease-out",...S??{}},children:$?"Processing\u2026":`Pay with ${(0,y.getStripeMethodDisplayName)(e)}`}),G&&(0,d.jsx)(Uo,{margin:"0.75rem 0 0",children:G})]})}function dc({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:s,stripeInstance:c,paymentElementBaseOptions:u,onTokenizedBody:p,onErrorChange:h,onButtonClick:b,onDecline:I,runBeforeButtonClick:k,onLoadStateChange:C,isProcessing:f=!1,submitButtonColor:S="#4A49FF",submitButtonBorderRadius:G=8,submitButtonStyle:_,buttonAppearance:q,themeId:E,onExpandApm:ne,expandedApmMethod:$}){let{emitInstrument:W}=(0,i.useContext)(rr),[ie,V]=(0,i.useState)(null),[Be,Ue]=(0,i.useState)(null),X=(0,i.useRef)(!1),{request:Ae,collect:it,finish:Re}=Oo();(0,i.useEffect)(()=>{s.length>0&&c?C?.("ready"):c||C?.("loading")},[s.length,c,C]);let xe=(0,i.useCallback)(async T=>{if(!c||X.current||f)return;X.current=!0,Ue(T);let ye=k?await k("card"):{proceed:!0};if(!ye.proceed){X.current=!1,Ue(null);return}b?.("card");let le=ye.sessionId??e,F=ye.nonce??t,Se=mo([ye.accountPatch?.firstName,ye.accountPatch?.lastName].filter(Boolean).join(" ")||r),ce=On({email:ye.accountPatch?.email?.trim()||n?.trim(),firstName:ye.accountPatch?.firstName?.trim()||Se.firstName,lastName:ye.accountPatch?.lastName?.trim()||Se.lastName});if(!(0,y.isValidEmail)(ce.email)){Ue(null);let $e=await it((0,y.getStripeMethodDisplayName)(T),ce);if(!$e){X.current=!1;return}ce=$e,Ue(T)}let De=ce.email,re=On({...ye.accountPatch,...ce});try{if(h?.(null),!le||!(0,y.isValidEmail)(De))throw new Error("Missing sessionId or email for payment.");await o?.(ce);let $e=await yi(a,W,le,F??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,paymentMethodId:null,intentKind:"payment"});if($e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let dt=$e.clientSecret;Wt(Br,{clientSecret:dt,sessionId:le,nonce:F,accountPatch:re,paymentMethodType:T,gateway:"stripe"});let{error:Me,paymentIntent:Oe}=await c.confirmPayment({clientSecret:dt,confirmParams:{return_url:window.location.href,payment_method_data:{type:T,billing_details:{name:[ce.firstName,ce.lastName].filter(Boolean).join(" "),...De?{email:De}:{}}}},redirect:"if_required"});if(Me){Wt(Br);let J=Me.message??"Payment failed.";h?.(J),I?.(un("card",J,{code:Me.code})),await fi({billingApiUrl:a,sessionId:le,nonce:F,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,providerDeclineReason:Me.code??"provider_declined"}});return}let ut=Oe?.status;if(!da(ut)){Wt(Br);let J=ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(J),I?.(un("card",J,{code:ut??"missing_payment_intent"}));return}Wt(Br);let Y=typeof Oe?.payment_method=="string"?Oe.payment_method:Oe?.payment_method?.id;p({id:Y??Oe?.id,type:"card",threeDSecureActionResultTokenId:Oe?.id,gateway:"stripe",paymentMethodType:T},{accountPatch:re,paymentMethodCategory:"apm",sessionId:le,nonce:F})}catch($e){h?.($e instanceof Error?$e.message:"Payment failed. Please try again.")}finally{X.current=!1,Ue(null)}},[c,f,k,b,e,t,n,it,a,W,r,o,p,h,I]),[ve,se]=(0,i.useState)(null),me=ne?$??null:ve,He=(0,i.useCallback)(T=>{X.current||f||me&&me!==T||((0,y.needsStripeMethodExplicitConfirm)(T)?ne?ne(T):se(T):xe(T))},[me,f,xe,ne]),st=(0,i.useMemo)(()=>ve?bc(u,ve):null,[ve,u]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ae?(0,d.jsx)(Lo,{identity:Ae.identity,methodLabel:Ae.methodLabel,onComplete:Re,onCancel:()=>Re(null)},Ae.id):s.map(T=>{let ye=$===T,le=Be===T,F=Be!==null&&Be!==T||$!=null&&$!==T;return(0,d.jsxs)(i.default.Fragment,{children:[(0,d.jsx)(zu,{method:T,themeId:E,submitting:le,disabled:F,highlighted:ye,hasNextStep:(0,y.needsStripeMethodExplicitConfirm)(T),onClick:()=>He(T),backgroundColor:q?.backgroundColor,borderColor:q?.borderColor,textColor:q?.textColor,borderRadius:q?.borderRadius,fontFamily:q?.fontFamily}),!ne&&ve===T&&st&&c&&(0,d.jsx)(Zt.Elements,{stripe:c,options:st,children:(0,d.jsx)(Ps,{method:T,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:p,onErrorChange:h,onDecline:I,onCancel:()=>se(null),runBeforeButtonClick:k,onButtonClick:b,isProcessing:f,submitButtonColor:S,submitButtonBorderRadius:G,submitButtonStyle:_})},T)]},T)})})}function Uu({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:s,onError:c,onDecline:u,onTokenizedBody:p,firstName:h,lastName:b,chv:I,className:k,submitLabel:C,isProcessing:f,error:S,onErrorChange:G,showPayPal:_=!0,showStripe:q=!0,walletPresentation:E="auto",enabledPaymentMethods:ne,enabledPaymentMethodCountries:$,showApplePay:W=!0,showGooglePay:ie=!0,layout:V="default",theme:Be,buttonsTheme:Ue,buttonsStyles:X,appearance:Ae,cardButtonContent:it,cardBackButtonContent:Re,cardTitleContent:xe,showSecurityFooter:ve,onButtonClick:se,onBeforeButtonClick:me,onBuyerIdentityReady:He,enableAVS:st,cardFieldOrder:T,cardPreFormSlot:ye,avsLayout:le="row",country:F,zip:Se,addressLine1:ce,addressLine2:De,city:re,state:$e,onCountryChange:dt,onZipChange:Me,avsCheck:Oe,checkoutType:ut,checkoutLayout:Y,totalAmount:J=0,currency:mt="usd",initialCardOpen:gt=!1,directPaypal:Ie,isSubscription:ft=!1,session:U,dataAttachmentPending:we=!1,dataAttachmentRequiresIdentity:lt=!1,debug:Z=!1}){let qe=Hr(),St=Wa(),Ze=(0,i.useContext)(Pr),{emitInstrument:H}=(0,i.useContext)(rr),nt=(0,i.useRef)(null);nt.current||(nt.current=Ya());let g=nt.current,[,v]=(0,i.useState)(0),ee=(0,i.useRef)(null);ee.current||(ee.current=Kr());let de=ee.current,Xe=(0,i.useMemo)(()=>({browser:de,capability:g,presentationMode:"popup"}),[de,g]),kt=U??Ze.session,Qe=kt?.gateways?.paypal?.providerObjectType??Ie?.providerObjectType,ae=we||Ze.claimPending===!0,yt=lt||Ze.claimRequiresIdentity===!0,It=ae&&!yt,qt=Tl(),Ke=n||qt,[Lt,Ge]=(0,i.useState)(!1),[zn,Tn]=(0,i.useState)(null),[Dt,Rn]=(0,i.useState)(F??""),[Un,qn]=(0,i.useState)(Se??""),[on,Ee]=(0,i.useState)(ce??""),[Rt,Mt]=(0,i.useState)(De??""),[wn,Ot]=(0,i.useState)(re??""),[Yn,yn]=(0,i.useState)($e??""),[Ht,ln]=(0,i.useState)(""),[Xn,fn]=(0,i.useState)({}),_t=(0,i.useRef)(Se??""),Qt=(0,i.useRef)(F??""),gn=(0,i.useRef)(ce??""),Nt=(0,i.useRef)(De??""),en=(0,i.useRef)(re??""),Kt=(0,i.useRef)($e??""),hn=(0,i.useRef)(""),vt=(0,i.useRef)({});(0,i.useEffect)(()=>{let l=(R,te,ze,pe,Te)=>{if(vt.current[R])return;let Jt=te?.trim();!Jt||Jt===ze.current||(ze.current=Jt,pe(Jt),Te?.(Jt))};l("country",F,Qt,Rn,dt),l("zip",Se,_t,qn,Me),l("addressLine1",ce,gn,Ee),l("addressLine2",De,Nt,Mt),l("city",re,en,Ot),l("state",$e,Kt,yn)},[F,Se,ce,De,re,$e,dt,Me]);let ue=(0,i.useMemo)(()=>(0,y.resolveAVSConfig)(st),[st]),Vn=ue!==null,jn=(0,i.useMemo)(()=>(0,y.isAuthorizationOnlySession)(U),[U]),Sr=!!U?.vault?.html,kn=!!U?.gateways?.pcivault,cn=Wi(U),Le=!!(U?.gateways?.stripe?.enabledPaymentMethods??ne)?.includes("card")||Zr(U),Ct=Sr||Le||kn,ge=!!(q&&Ct&&e),[L,rt]=(0,i.useState)(()=>V!=="buttons"||gt?e??null:null),[he,Jn]=(0,i.useState)(0),Pn=V!=="buttons"||gt||!!e&&L===e,Gt=U?.captureMethod,Zn=(0,i.useRef)(qe);(0,i.useEffect)(()=>{Zn.current=qe},[qe]);let[pt,Xr]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!ge||!e||!Pn){Xr(null);return}let l=Zn.current?Zn.current.cardCapture({sessionId:e,captureMethod:Gt}):new Cr.PciVaultCardCapture({sessionId:e,captureMethod:Gt,billingApiUrl:Ke,telemetry:r});return Xr({sessionId:e,captureMethod:Gt,billingApiUrl:Ke,telemetry:r,capture:l}),()=>{l.unmount()}},[ge,e,Pn,Gt,Ke,r]);let Yt=ge&&e&&Pn&&pt?.sessionId===e&&pt.captureMethod===Gt&&pt.billingApiUrl===Ke&&pt.telemetry===r?pt.capture:null,bn=(0,i.useMemo)(()=>{let l=Dt,R=ue?(0,y.isAVSFieldVisible)(ue.postal_code,l):!1;return Ou(l,Un,R)},[ue,Dt,Un]),{avsInvalid:Nr,invalidAvsFields:zr}=(0,i.useMemo)(()=>{let l={line1:!1,city:!1,state:!1,zip:!1};if(!ge||!ue)return{avsInvalid:!1,invalidAvsFields:l};let R=Dt,te=(Te,Jt)=>(0,y.isAVSFieldVisible)(Te,R)&&!Jt.trim(),ze={line1:te(ue.address_line_1,on),city:te(ue.city,wn),state:te(ue.state,Yn),zip:bn.empty||bn.malformed};return{avsInvalid:ze.line1||ze.city||ze.state||ze.zip,invalidAvsFields:ze}},[ge,ue,Dt,on,wn,Yn,bn]),[xn,tn]=(0,i.useState)(!1),[wr,Mn]=(0,i.useState)(!1),[Ur,Fn]=(0,i.useState)(!1),[kr,Ir]=(0,i.useState)({line1:!1,city:!1,state:!1}),cr=(0,i.useRef)(!1),Qn=(0,i.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),er=(0,i.useRef)(!1),Bt=(0,i.useCallback)(l=>{Qn.current[l]=!0,er.current=!0},[]),dr=(0,i.useCallback)(l=>!cr.current&&Qn.current[l],[]),_n=(0,i.useCallback)(l=>{dr(l)&&Ir(R=>R[l]?R:{...R,[l]:!0})},[dr]),[tr,Rr]=(0,i.useState)(()=>ys(U?.vault)),[ht,an]=(0,i.useState)(gt&&Ct?"card":"buttons"),[nn,qr]=(0,i.useState)(null),$n=ht==="expanding"||ht==="card",Jr=U?.gateways?.stripe&&!cn?"stripe":void 0,ur=(0,i.useCallback)(()=>{H?.({class:"card_surface",provider:Jr})},[Jr,H]),pr=(0,i.useRef)(null),vn=(0,i.useCallback)(l=>{pr.current&&clearTimeout(pr.current),pr.current=setTimeout(()=>{pr.current=null,l()},Ra)},[]);(0,i.useEffect)(()=>()=>{pr.current&&clearTimeout(pr.current)},[]);let mr=(0,i.useCallback)(()=>{ur(),rt(e??null),Jn(l=>l+1),an("expanding"),vn(()=>an("card"))},[vn,ur,e]),Vr=(0,i.useCallback)(()=>{an("collapsing"),vn(()=>an("buttons"))},[vn]),En=(0,i.useCallback)(l=>{qr(l),an("apm-expanding"),vn(()=>an("apm-form"))},[vn]),D=(0,i.useCallback)(()=>{an("apm-collapsing"),vn(()=>{an("buttons"),qr(null)})},[vn]);(0,i.useEffect)(()=>{V==="buttons"&>&&Ct&&(rt(e??null),an("card"))},[V,gt,Ct,e]);let[z,B]=(0,i.useState)(null),Pe=(0,i.useRef)(!1),Ve=(0,i.useRef)(null),Pt=(0,i.useRef)("idle"),[Ce,je]=(0,i.useState)(!1),Q=(0,i.useRef)(Ce);Q.current=Ce;let[m,P]=(0,i.useState)(()=>Ie?.existingOrderId?{orderId:Ie.existingOrderId,attempts:1}:null),N=(0,i.useRef)(m);(0,i.useEffect)(()=>{N.current=m},[m]);let j=(0,i.useRef)(null),be=(0,i.useMemo)(()=>{if(He||Ze.claimBuyerIdentity||U?.buyerIdentified!==!1||!e||!t)return;let l=`${Ke}|${e}|${t}`;j.current?.key!==l&&(j.current={key:l,claim:Bo(new Cr.PaymentAPI(Ke,{telemetry:!1}),e,t,{...a?{userId:a}:{},...h?{firstName:h}:{},...b?{lastName:b}:{}})});let R=j.current.claim;return async te=>{await R(te)}},[He,Ze.claimBuyerIdentity,U?.buyerIdentified,e,t,Ke,a,h,b]),oe=He??Ze.claimBuyerIdentity??be,et=S??zn,Tt=(0,i.useMemo)(()=>(0,y.resolveTheme)(Be),[Be]),M=(0,i.useMemo)(()=>{let l=Tt?.buttonsLayout??(0,y.resolveButtonsLayoutTheme)(Ue);return X?{...l,...X,cardButton:{...l.cardButton,...X.cardButton},cardFormContainer:{...l.cardFormContainer,...X.cardFormContainer},backButton:{...l.backButton,...X.backButton},backButtonIcon:{...l.backButtonIcon,...X.backButtonIcon},submitButton:{...l.submitButton,...X.submitButton},title:{...l.title,...X.title}}:l},[Tt,Ue,X]),_e=Ae??Tt?.appearance,Ft=(0,i.useMemo)(()=>Go({appearance:_e,buttonsStyles:M,layout:V}),[_e,M,V]),ke=Ze.inlineSessionPatchProcessing??!1,K=(f??Lt)||ke,fe=Ke.replace(/\/+$/,""),x=(0,i.useMemo)(()=>Ki({userId:a,email:o,firstName:h,lastName:b,country:F,zip:Se},Xn),[a,o,h,b,F,Se,Xn]),Ye=[x.firstName,x.lastName].filter(l=>!!l?.trim()).join(" "),At=!(0,y.isValidEmail)(x.email?.trim()),Ne=(0,i.useRef)(null);ge&&Ne.current===null&&(Ne.current=At);let In=ge&&(Ne.current??At),_r=(0,i.useMemo)(()=>Lu(Ht,In),[Ht,In]),Co=_r.empty||_r.malformed,Wn=(0,i.useMemo)(()=>qe?qe.getRawProvider():null,[qe]),Fs=(0,i.useMemo)(()=>St?St.getRawProvider():null,[St]),Xo=J||100,So=mt.toLowerCase(),Ri=(0,i.useMemo)(()=>_e?(0,Cr.toStripeAppearance)(_e):null,[_e]),wo=Ri,Bs=(0,i.useMemo)(()=>{let l=Ri??{},R=l.rules??{};return{...l,rules:{...R,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...R[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...R[".AccordionItemContents"]??{}}}}},[Ri]),Ds=(0,i.useMemo)(()=>({...kl(J,U?.captureMethod),currency:So,...wo?{appearance:wo}:null}),[J,So,U?.captureMethod,wo]),Os=(0,i.useMemo)(()=>({mode:"payment",amount:Xo,currency:So,captureMethod:"manual",setupFutureUsage:"off_session",...wo?{appearance:wo}:null}),[Xo,So,wo]),Fe=(0,i.useCallback)(l=>{Tn(l),G?.(l)},[G]),_i=(0,i.useRef)(""),[Ls,Yc]=(0,i.useState)(!1),Ei=(0,i.useCallback)(()=>{Yc(!0)},[]);(0,i.useEffect)(()=>{if(!ge||!In||!oe||!Ls||Co||_i.current)return;let l=On({email:(0,y.isValidEmail)(x.email?.trim())?x.email?.trim():hn.current.trim(),firstName:x.firstName?.trim(),lastName:x.lastName?.trim()});_i.current=JSON.stringify(l),fn(R=>({...R,...l})),Promise.resolve(oe(l)).catch(R=>{_i.current="",Fe(R instanceof Error?R.message:"Failed to attach buyer details.")})},[ge,In,oe,Ls,Co,x.email,x.firstName,x.lastName,Fe]),(0,i.useEffect)(()=>{!ge||!Yt||Yt.setCardFieldOrder?.(T??null,ue==null&&!In)},[ge,Yt,T,ue,In]),(0,i.useEffect)(()=>{(ht==="expanding"||ht==="collapsing"||ht==="apm-expanding"||ht==="apm-collapsing")&&Fe(null)},[ht,Fe]);let Er=(0,i.useCallback)((l,R,te)=>{u?.(un(l,R,te))},[u]),ko=(0,i.useCallback)((l,R,te)=>{let ze=te?.popupBlocked??oo(R);ze&&g.markBlocked()&&v(ct=>ct+1);let pe=no(hs(l),ze,de.inAppBrowser),Te=Mr(R),Jt=(Te?.toLowerCase()==="error"?void 0:Te)??yo(te?.code)??"external_payment_method_failed",gr=new y.FloPayError(pe,"api_error",{code:"external_payment_method_failed",param:l,details:{providerCode:Jt,popupBlocked:ze,inAppBrowser:de.inAppBrowser,appFamily:de.appFamily,popupCapability:g.current(),presentationMode:te?.presentationMode??"popup"}});te?.telemetryReported||pn(qe)?.error(Ho({...Xe,presentationMode:te?.presentationMode??"popup"},{errorCode:ze?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:te?.provider??(l==="paypal"?"paypal":"stripe"),paymentMethodCategory:te?.paymentMethodCategory??(l==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:te?.terminalReason??(ze?"popup_blocked":"provider_error")})),B(null),V==="buttons"&&(an("buttons"),qr(null)),Fe(pe),c?.(gr),console.error("[FloPay] External payment method failed:",{method:l,code:Jt,popupBlocked:ze})},[de,Xe,qe,V,c,g,Fe]);(0,i.useEffect)(()=>{if(!ge||!e){Rr(null);return}let l=ys(U?.vault);if(l){Rr(l);return}if(!Pn){Rr(null);return}Rr(null);let R=!0;return new Cr.PaymentAPI(fe).getVaultCapture(e,t).then(te=>{if(!R)return;let ze=ys(te);ze?Rr(ze):Fe("Failed to load the secure card form.")}).catch(te=>{R&&Fe(te instanceof Error?te.message:"Failed to load the secure card form.")}),()=>{R=!1}},[ge,Pn,he,e,U?.vault,fe,t,Fe]);let yr=(0,i.useRef)({onComplete:s,onError:c,updateError:Fe,emitDecline:Er,resolvedAccount:x,avsConfig:ue,avsCheckProp:Oe,sessionId:e,nonce:t,baseUrl:fe,captureMethod:U?.captureMethod,paymentId:U?.paymentId,authorizationExpiresAt:U?.authorizationExpiresAt,serverSideCardGateway:cn});yr.current={onComplete:s,onError:c,updateError:Fe,emitDecline:Er,resolvedAccount:x,avsConfig:ue,avsCheckProp:Oe,sessionId:e,nonce:t,baseUrl:fe,captureMethod:U?.captureMethod,paymentId:U?.paymentId,authorizationExpiresAt:U?.authorizationExpiresAt,serverSideCardGateway:cn};let Ti=(0,i.useRef)(!1),Ns=(0,i.useCallback)(()=>{let l=yr.current,R=l.resolvedAccount.email?.trim(),te=(0,y.isValidEmail)(R)?R:hn.current.trim();if(!(0,y.isValidEmail)(te))return null;let ze=l.resolvedAccount.firstName?.trim(),pe=l.resolvedAccount.lastName?.trim(),Te=Qt.current.trim()||l.resolvedAccount.country?.trim()||"",Jt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.state,Te):!1,gr=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_1,Te):!1,ct=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.postal_code,Te):!1,bt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.city,Te):!1,Et=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_2,Te):!1,jt=gr&&!Jt&&ct?(0,y.getStateFromPostalCode)(Te,(_t.current??"").trim()):null,dn=Jt?Kt.current:jt;return{accountData:{userId:l.resolvedAccount.userId??"",email:te,...ze?{firstName:ze}:{},...pe?{lastName:pe}:{},...ct&&_t.current?{zip:_t.current}:{},...bt&&en.current?{city:en.current}:{},...dn?{state:dn}:{},...gr&&gn.current?{addressLine1:gn.current}:{},...Et&&Nt.current?{addressLine2:Nt.current}:{},...Te?{country:Te}:{}},...l.avsCheckProp===void 0?{}:{avsCheck:l.avsCheckProp},...l.avsConfig?{avsConfig:{country:(0,y.isAVSFieldVisible)(l.avsConfig.country,Te),postal_code:ct,address_line_1:gr,address_line_2:Et,city:bt,state:Jt}}:{}}},[]),zs=(0,i.useRef)(ae);zs.current=ae,(0,i.useEffect)(()=>{ae||et!==nc||yr.current.updateError(null)},[ae,et]),(0,i.useEffect)(()=>{!ge||!Yt||Yt.setSubmitGate?.(Nr||ae||Co||Ce)},[ge,Yt,Nr,ae,Co,Ce]),(0,i.useEffect)(()=>{if(!ge||!Yt)return;Ti.current=!1;let l=null,R=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null,Pt.current="idle",B(null)},400)},te=Yt.on("submitting",()=>{tn(!0),Ve.current&&clearTimeout(Ve.current),Pt.current="validation-window",Ve.current=setTimeout(()=>{Ve.current=null,Pt.current==="validation-window"&&(Pt.current="processing")},ku),B("processing");let ct=yr.current;if(!ct.sessionId||!ct.nonce)return;let bt=Ns();if(!bt){ct.updateError("Enter a valid email address."),Pt.current="idle",B(null);return}new Cr.PaymentAPI(ct.baseUrl).patchAccountSnapshot(ct.sessionId,ct.nonce,bt,{telemetryMode:"best_effort"}).catch(Et=>{if(!Ru(Et))return;let jt=Et instanceof Error?Et.message:"Please check your billing address and try again.";ct.updateError(jt),Pt.current="idle",B(null),ct.onError?.(Et instanceof y.FloPayError?Et:new y.FloPayError(jt,"api_error"))})}),ze=Yt.on("complete",async ct=>{if(jo(ct.sessionId??yr.current.sessionId),Pt.current="terminal",je(!1),B("success"),await new Promise(dn=>setTimeout(dn,600)),Ti.current)return;Ti.current=!0;let bt=yr.current,Et=(0,y.isAuthorizationOnlySession)(bt)||ct.outcome==="authorized",jt=bt.serverSideCardGateway?{}:{paymentIntentId:ct.intentId};yr.current.onComplete?.(Et?{status:"authorized",...jt,paymentId:ct.paymentId??bt.paymentId,sessionId:ct.sessionId??bt.sessionId,authorizationExpiresAt:ct.authorizationExpiresAt??bt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...jt,checkoutMethod:"card"})}),pe=Yt.on("decline",ct=>{let bt=yr.current,Et=ct.message??"Your payment was declined. Please try another card or contact your bank.";Pt.current="terminal",je(!1),bt.updateError(Et),B("error");let jt=ct.failureOutcome??(0,y.normalizeCheckoutFailureOutcome)(ct.declineReason)??"authorization_declined";bt.emitDecline("card",Et,{code:jt,declineCode:jt}),R()}),Te=Yt.on("error",ct=>{let bt=yr.current,Et=ct.message??"There was a problem processing your payment. Please try again.";Pt.current="terminal",je(!1),bt.updateError(Et),B("error"),bt.onError?.(new y.FloPayError(Et,"api_error",{code:ct.failureOutcome??"capture_failed"})),R()}),Jt=Yt.on("challenge_dismissed",()=>{Ve.current&&(clearTimeout(Ve.current),Ve.current=null),Pt.current="processing",je(!0),B(null)}),gr=Yt.on("blocked",()=>{if(Q.current){yr.current.updateError(Iu);return}if(!zs.current){tn(!0);return}Ei(),yr.current.updateError(nc)});return()=>{l&&(clearTimeout(l),l=null),Ve.current&&(clearTimeout(Ve.current),Ve.current=null),Pt.current="idle",je(!1),B(null),te(),ze(),pe(),Te(),Jt(),gr()}},[ge,Yt,Ei,Ns]);let Tr=!!Ie?.clientId,Jo=Array.isArray(ne),xa=Jo&&ne.length>0,Us=Jo&&ne.includes("paypal"),Ma=(0,i.useRef)(null);Ma.current===null&&(Ma.current=Su());let Io=Ma.current?"redirect":Ha(de,E,g.current()),{expressMethods:Fa,paymentElementMethods:Zo}=(0,i.useMemo)(()=>(0,y.partitionStripeMethods)(ne,{excludePaypal:Tr}),[ne,Tr]),qs=Tr||!!St||Us&&Io==="redirect",Xc=(0,i.useMemo)(()=>qs?Fa.filter(l=>l!=="paypal"):Fa,[Fa,qs]),Jc=(0,i.useMemo)(()=>{let l=[];return W&&l.push("apple_pay"),ie&&l.push("google_pay"),l},[W,ie]),Ro=Jo?Xc:Jc,Zc=q&&Ro.length>0,Ai=Vn?Dt:F,Ba=(0,i.useMemo)(()=>{let l=Ai?.trim().toUpperCase();return l?$?Zo.filter(R=>{let te=$[R];return!te||te.length===0||te.includes(l)}):(0,y.filterStripeMethodsByCountry)(Zo,Ai):Zo},[Zo,Ai,$]),xi=(0,i.useMemo)(()=>({mode:"payment",amount:Xo,currency:So,paymentMethodCreation:"manual",appearance:Bs}),[Xo,So,Bs]),[Vs,js]=(0,i.useState)("loading"),[$s,Ws]=(0,i.useState)("loading"),[Hs,Ks]=(0,i.useState)("loading"),[Qc,Mi]=(0,i.useState)(!1),[Gs,Fi]=(0,i.useState)("loading"),[Bi,ed]=(0,i.useState)();(0,i.useEffect)(()=>{ed(Kr())},[]);let Da=Bi?.inAppBrowser,Oa=Bi?Ka(Bi,Ie?.approvalPresentation,Qe??(ft?"subscription":"order")):"popup",Ys=_&&(Tr||(Jo?Us:Da===!1)),Xs=q&&Zc,Qo=(!It||!!Ze.waitForDataAttachment)&&Ys&&Tr,Js=Gs==="retrying"||Gs==="exhausted",ea=null;q&&(St?ea=Fs:Io==="redirect"&&(ea=Wn));let Zs=(0,i.useMemo)(()=>({...Xe,presentationMode:Io}),[Xe,Io]),ta=!It&&Ys&&!!ea&&(!Tr||Js),_o=!It&&Xs&&!!Wn,na=!It&&q&&xa&&Ba.length>0&&!!Wn,td=Qo&&!Js?Qc:ta&&sc(Vs),nd=_o&&sc($s),rd=na&&Hs!=="load_error",Qs=l=>l==="loading"||l==="ready",el=Qo||ta&&Qs(Vs)||_o&&Qs($s)||na&&Hs!=="load_error",La=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(!La.current){if(!q&&!_){La.current=!0;let l=new y.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(l),Fe(l.message)}else if(!q&&_&&!Tr){La.current=!0;let l=new y.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(l),Fe(l.message)}else if(Da!==void 0&&!It&&!Ct&&!el){La.current=!0;let l=new y.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"});c?.(l),Fe(l.message)}}},[q,_,Tr,Da,It,Ct,el,c,Fe]);let tl=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(tl.current||!xa)return;let l=[];W!==!0&&l.push("showApplePay"),ie!==!0&&l.push("showGooglePay"),l.length!==0&&(tl.current=!0,console.warn(`[FloPay] ${l.join(" / ")} ${l.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.`))},[xa,W,ie]);let nl=(0,i.useCallback)((l,R)=>Ze.applyInlineSessionPatch?Ze.applyInlineSessionPatch(l).then(te=>({error:null,sessionId:te.sessionId||e,nonce:te.session?.clientSecret||t})).catch(te=>{let ze=ic(R,te);return Fe(ze.message),c?.(ze),{error:ze,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ze.applyInlineSessionPatch,t,c,e,Fe]),fr=(0,i.useCallback)(async l=>{if(l!=="card"&&It&&await Ze.waitForDataAttachment?.(),!me)return{proceed:!0};try{let R=await me({method:l,sessionId:e||void 0,createSession:Ze.inlineSessionDraft});if(R===!1)return{proceed:!1};if(R&&typeof R=="object"){R.account&&fn(ze=>({...ze??{},...R.account}));let te=await nl(R,l);return te.error?{proceed:!1,accountPatch:R.account}:{proceed:!0,accountPatch:R.account,sessionId:te.sessionId,nonce:te.nonce}}return{proceed:!0}}catch(R){let te=ic(l,R);return Fe(te.message),c?.(te),{proceed:!1}}},[nl,Ze.inlineSessionDraft,Ze.waitForDataAttachment,It,me,c,e,Fe]),rl=(0,i.useCallback)(async(l,R)=>{if(Pe.current)return;Pe.current=!0,Ge(!0),B("processing"),Fe(null);let te=R?.sessionId??e,ze=R?.nonce??t,pe=Ki(x,R?.accountPatch),Te=R?.completionPaymentMethodId??ua(l),Jt=l.originalPaymentMethodId?{...l,originalPaymentMethodId:void 0}:l,gr=xu(l),ct=R?.presentationMode?li(pn(qe),{...Xe,presentationMode:R.presentationMode}):void 0,bt=()=>{H?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:gr}),ct?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...vr,requestCategory:"process_payment"})};try{let jt=await new Cr.PaymentAPI(fe).processPayment(pe.userId??"",{sessionId:te,nonce:ze,paymentMethodCategory:R?.paymentMethodCategory??Fu(l),tokenizedData:Jt,accountData:{...R?.accountPatch,userId:pe.userId??"",email:pe.email??"",firstName:pe.firstName||void 0,lastName:pe.lastName||void 0,...ue?(()=>{let zt=Qt.current,Ar=(0,y.isAVSFieldVisible)(ue.state,zt),Hn=(0,y.isAVSFieldVisible)(ue.address_line_1,zt),xr=(0,y.isAVSFieldVisible)(ue.postal_code,zt),po=Hn&&!Ar&&xr?(0,y.getStateFromPostalCode)(zt,(_t.current??"").trim()):null,la=Ar?Kt.current:po;return{country:zt,...xr&&_t.current?{zip:_t.current}:{},...(0,y.isAVSFieldVisible)(ue.city,zt)&&en.current?{city:en.current}:{},...la?{state:la}:{},...Hn&&gn.current?{addressLine1:gn.current}:{},...(0,y.isAVSFieldVisible)(ue.address_line_2,zt)&&Nt.current?{addressLine2:Nt.current}:{}}})():{}},chv:I,avsCheck:Oe??!1,checkoutType:ut,checkoutLayout:Y,avsConfig:ue?{country:(0,y.isAVSFieldVisible)(ue.country,Qt.current),postal_code:(0,y.isAVSFieldVisible)(ue.postal_code,Qt.current),address_line_1:(0,y.isAVSFieldVisible)(ue.address_line_1,Qt.current),address_line_2:(0,y.isAVSFieldVisible)(ue.address_line_2,Qt.current),city:(0,y.isAVSFieldVisible)(ue.city,Qt.current),state:(0,y.isAVSFieldVisible)(ue.state,Qt.current)}:void 0});if(jt.ok){let zt=jt.status===204?null:await jt.json().catch(()=>null),Ar=(0,y.isAuthorizationOnlySession)(U)||zt?.status==="authorized";jo(te),ct?.terminal({outcome:"payment_succeeded",...vr}),B("success"),P(null),await new Promise(po=>setTimeout(po,600));let Hn;typeof zt?.paymentId=="string"?Hn=zt.paymentId:U?.paymentId&&(Hn=U.paymentId);let xr;typeof zt?.authorizationExpiresAt=="string"?xr=zt.authorizationExpiresAt:U?.authorizationExpiresAt&&(xr=U.authorizationExpiresAt),s?.(Ar?{status:"authorized",...Hn===void 0?{}:{paymentId:Hn},sessionId:typeof zt?.sessionId=="string"?zt.sessionId:te,...xr===void 0?{}:{authorizationExpiresAt:xr},paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Te,checkoutMethod:l.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Te,checkoutMethod:l.isPaypal?"paypal":"card"});return}let dn=await jt.json().catch(()=>null);if(dn?.type==="paypal_redirect_required"){let zt=dn.threeDSecureToken,Ar=dn.paymentMethodId||l.id||"";if(!qe||!zt){B("error"),Fe("PayPal authorization required but no token provided.");return}try{let Hn=St?.getRawProvider();if(!Hn){Fe("PayPal is not available.");return}let xr={return_url:window.location.href};Ar&&(xr.payment_method=Ar);let{error:po}=await Hn.confirmPayment({clientSecret:zt,confirmParams:xr,redirect:"if_required"});if(po){B("error");let la=po.message??"PayPal payment failed.";Fe(la),Er("paypal",la,{code:po.code})}}catch(Hn){B("error"),Fe(Hn instanceof Error?Hn.message:"PayPal authorization failed.")}return}if(dn?.type==="paypal_direct_required"){let zt=dn.orderId;if(!zt){B("error"),Fe("PayPal retry required but no order id provided.");return}let Ar=N.current?.attempts??0;if(Ar>=2){B("error"),Fe("PayPal payment could not be completed after multiple attempts."),Er("paypal","paypal_direct_required retry limit exceeded");return}Mi(!1),Fi("loading"),P({orderId:zt,attempts:Ar+1}),B(null);return}(0,y.classifyPaymentRejection)(jt.status,dn)?ct?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}):bt(),B("error");let hr=dn?.message??"Payment failed. Please try again.";Fe(hr),Er(l.isPaypal?"paypal":"card",hr,{code:dn?.code??dn?.gatewayErrorCode,declineCode:dn?.declineCode??dn?.gatewayDeclineReason}),await new Promise(zt=>setTimeout(zt,400))}catch(Et){yc(Et)||bt(),B("error"),Fe(Et instanceof Error?Et.message:"An unexpected error occurred"),await new Promise(jt=>setTimeout(jt,400))}finally{Ge(!1),B(null),Pe.current=!1}},[fe,e,t,x,ue,Oe,ut,Y,I,qe,St,U,s,Fe,Er,H,Xe]),Bn=(0,i.useCallback)((l,R)=>{p?p(l):rl(l,R)},[p,rl]),ra=`${uc}:${e}`;(0,i.useEffect)(()=>{if(typeof window>"u")return;let l=localStorage.getItem(ra);if(!l)return;let R;try{R=JSON.parse(l)}catch{Wt(ra);return}if(!R||typeof R.createdAt!="number"||Date.now()-R.createdAt<0||Date.now()-R.createdAt>pc||typeof R.paymentMethodId!="string"||typeof R.providerIntentId!="string"||typeof R.paymentMethodType!="string"||R.sessionId!==e||!t||R.nonce!==t||!Ro.includes(R.paymentMethodType)){Wt(ra);return}Wt(ra),Bn({id:R.paymentMethodId,type:"card",threeDSecureActionResultTokenId:R.providerIntentId,gateway:"stripe",paymentMethodType:R.paymentMethodType},{...R.accountPatch?{accountPatch:R.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Bn,t,e,ra,Ro]);let ol=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(typeof window>"u"||ol.current)return;let[l,R,te]=vs();if(!l||!R||Ma.current||!qe)return;let ze=qe.getRawProvider();if(!ze)return;let pe=bt=>{let Et=localStorage.getItem(bt);if(!Et)return null;try{return JSON.parse(Et)}catch{return Wt(bt),null}},Te=pe(Br)??pe(Ql),Jt;if(Te?.clientSecret){if(Te.clientSecret!==R)return;Jt={...Te.accountPatch?{accountPatch:Te.accountPatch}:{},...Te.sessionId?{sessionId:Te.sessionId}:{},...Te.nonce?{nonce:Te.nonce}:{}}}else if(Te?.sessionId&&Te.sessionId!==e)return;ol.current=!0,Wt(Br),Wt(Ql),window.history.replaceState({},"",Cs());let gr=Te?.paymentMethodType??Te?.tokenType??"card",ct="card";(async()=>{if(te==="failed"){let hr="Payment was declined. Please try again.";Fe(hr),Er(ct,hr);return}let{paymentIntent:bt,error:Et}=await ze.retrievePaymentIntent(R);if(Et){let hr=Et.message??"Failed to retrieve payment status.";Fe(hr),Er(ct,hr,{code:Et.code});return}let jt=bt?.status,dn=da(jt);if(!bt||!dn){let hr=jt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Fe(hr),Er(ct,hr,{code:jt??"missing_payment_intent"});return}let yl=typeof bt.payment_method=="string"?bt.payment_method:bt.payment_method?.id;Bn({id:yl??Te?.paymentMethodId??Te?.tokenId??bt.id,type:"card",threeDSecureActionResultTokenId:bt.id,gateway:Te?.gateway??"stripe",paymentMethodType:gr},Jt)})()},[e,Bn,qe,Fe,Er]);let Di=(0,i.useCallback)(l=>{l.preventDefault()},[]);if(!(ge||qe!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let oa=V==="buttons",Dn=_e?.variables,od=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Oi=Dn?.colorBackground,ad=Oi&&!od.has(Oi)?Oi:void 0,aa=M.cardInputBorder??(oa?"#e5e7eb":"#A4A4FF"),al=Dn?.colorDanger??"#dc2626",Vt=l=>zr[l]&&(kr[l]||xn),Na=Co&&(Ur||xn),nr=l=>l?al:aa,za=(bn.malformed||bn.empty)&&(wr||xn),id=nr(za),Li=M.cardFormContainer?.backgroundColor??ad??(oa?"white":"#EDEDFF"),Eo=M.cardInputBackground??Dn?.colorBackground??"white",Ni=xo(Re),il=xo(xe),To=M.nameInput,sl=M.cardInputFontSize??Nu(To?.fontSize)??Dn?.fontSizeBase??"16px",ll=typeof To?.fontFamily=="string"?To.fontFamily:Dn?.fontFamily??"Poppins, sans-serif",cl=ds(To?.fontWeight)??400,sd=M.cardInputColor??(typeof To?.color=="string"?To.color:void 0)??Dn?.colorText??"#262833",ld=M.cardInputPlaceholderColor??"#9ca3af",Xt=Dn?.borderRadius??"8px",co=Dn?.borderRadius??M.cardButton?.borderRadius??Xt,uo=Dn?.colorPrimary??"#4A49FF",cd=Dn?.colorPrimaryHover??Ko(uo,.12),zi=Dn?.colorText??"#262833",Ui={fontSize:sl,fontFamily:ll,fontWeight:cl,color:sd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ia={marginTop:"0.375rem",...Ui,fontSize:"0.75rem",lineHeight:1.4,color:al},dd={"--flopay-input-placeholder-color":ld,"--flopay-input-font-size":sl,"--flopay-input-font-family":ll,"--flopay-input-font-weight":String(cl)},sa=M.cardFormContainer??{},qi=sa.padding??(oa?"0":"1rem"),Vi=sa.borderRadius??Xt,ud=Yt&&tr?(0,d.jsx)(so,{capture:Yt,html:tr.html,messageToken:tr.messageToken,expectedOrigin:tr.expectedOrigin,theme:Ft,submitLabel:C,onReady:()=>{if(!In&&!ue||typeof document>"u")return;let l=()=>{let te=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(te){cr.current=!0;try{te.focus()}finally{cr.current=!1}}};er.current||l()},onError:l=>Fe(l),onValidation:l=>{let R=Pt.current;(R==="idle"||R==="validation-window")&&(Fe(l),l&&Pt.current==="validation-window"&&(Ve.current&&(clearTimeout(Ve.current),Ve.current=null),Pt.current="idle",B(null)))}}):(0,d.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),dl=(0,d.jsxs)("div",{onFocusCapture:l=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(l.target.tagName)&&ur()},style:{backgroundColor:Li,borderRadius:Vi,...sa,padding:qi,...dd,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
|
|
30
|
+
`,Ia=44,Ra=180,rc=`flopay-card-enter ${Ra}ms cubic-bezier(0, 0, 0.2, 1) both`,oc=`flopay-card-exit ${Ra}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Au=`flopay-buttons-enter ${Ra}ms cubic-bezier(0, 0, 0.2, 1) both`,Mu=`flopay-buttons-exit ${Ra}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function xu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ws(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var Fu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Bu(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 gs={width:"100%",minHeight:Ia,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Du(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ac(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function hs(e){return e==="paypal"?"PayPal":(0,y.getStripeMethodDisplayName)(e)}function Ou(e){let t=(0,y.getPostalCodeExample)(e);return`Enter a valid ${(0,y.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Lu(e,t,n){let r=(0,y.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,s=a&&!o,d=a&&!!o&&!(0,y.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:s,malformed:d}}function Nu(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,y.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function ic(e,t){return t instanceof y.FloPayError?t:new y.FloPayError(t instanceof Error?t.message:`${Du(e)} before-click hook failed.`,"validation_error")}function fs(){return(0,c.jsx)("style",{children:Tu})}function zu(e){return typeof e=="number"?`${e}px`:e}function Pc(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function bc({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 sc(e){return e!=="unavailable"&&e!=="load_error"}function gi(e){return(0,c.jsx)(qu,{...e})}function lc({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:s=!1,onButtonClick:d,onDecline:p,onTechnicalFailure:u,runBeforeButtonClick:f,billingName:P,onBuyerIdentityReady:k,onLoadStateChange:R,placeholderBorderRadius:S,popupCapabilityOwner:T,externalTelemetryContext:E,presentationMode:b}){let C=Hr(),{emitInstrument:j}=(0,i.useContext)(tr),_=(0,Jt.useStripe)(),re=(0,Jt.useElements)(),q=(0,i.useMemo)(()=>li(pn(C),E),[E,C]),[K,le]=(0,i.useState)("loading");(0,i.useEffect)(()=>{R?.(K)},[K,R]);let[$,Oe]=(0,i.useState)(!1),Ue=(0,i.useRef)(!1),J=!(0,y.isValidEmail)(n?.trim())||!P?.trim(),{request:xe,collect:lt,finish:Ee}=Oo(),Fe=(0,i.useRef)(!1),be=(0,i.useRef)(null),ce=(0,i.useRef)(null),[me,Ge]=(0,i.useState)(0),[ct,A]=(0,i.useState)(!1),fe=(0,i.useRef)(!1),de=(0,i.useRef)(new Map),{startAttempt:D,finishAttempt:Se,invalidateAttempt:ue,isAttemptInvalidated:Le,isAttemptCurrent:oe,generationRef:We}=ya((V,ke,tt)=>{u?.(V,ke,{...tt,popupBlocked:tt?.popupBlocked??oo(ke),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:b,terminalReason:"overlay_timeout"}),A(!0),Ge(ee=>ee+1)},{onHandoffObserved:()=>{T.markAvailable(),q?.log({name:"provider.popup.opened",stage:"overlay_open",...vr,attempt:We.current})}});(0,i.useEffect)(()=>{ct&&ce.current?.focus()},[ct,me]);let ut=(0,i.useCallback)(()=>{Ge(V=>V+1)},[]),Be=(0,i.useCallback)((V,ke,tt)=>{ue(tt),u?.("paypal",V,{code:ke,popupBlocked:oo(V),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:b}),A(!0),ut()},[ue,u,b,ut]),Je=(0,i.useCallback)(()=>{window.setTimeout(()=>{(be.current?.querySelector("iframe")??be.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{fe.current&&(fe.current=!1,Je())},[Je,me]);let Ze=(0,i.useCallback)(()=>{A(!1),a?.(null),Je()},[Je,a]);(0,i.useEffect)(()=>{if(!_||Fe.current)return;let[V,ke,tt]=vs();if(!V||!ke)return;let ee=gc(ke);if(!ee)return;Fe.current=!0;let qe=!0,vt=wa.get(ke);vt||(vt=tt==="failed"?Promise.resolve(null):Promise.resolve().then(()=>_.retrievePaymentIntent(ke)),wa.set(ke,vt));let nt={accountPatch:ee.accountPatch,sessionId:ee.sessionId,nonce:ee.nonce},Et=()=>{q?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...vr,requestCategory:"provider_sdk"})};return q?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...vr}),(async()=>{try{Oe(!0);let h=await vt;if(!qe)return;if(h?.error){wa.delete(ke),Et(),a?.(h.error.message??"Failed to retrieve PayPal payment status.");return}if(ku(),wa.delete(ke),tt==="failed"){let X="PayPal payment was declined. Please try again.";q?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}),a?.(X),p?.(un("paypal",X));return}let v=h?.paymentIntent;if(v&&v.id!==V){Et(),a?.("Failed to match the returned PayPal payment.");return}if(v&&(v.status==="requires_capture"||v.status==="succeeded")){let X=typeof v.payment_method=="string"?v.payment_method:v.payment_method?.id;o({id:X??v.id,type:"card",threeDSecureActionResultTokenId:v.id,isPaypal:!0},{...nt,presentationMode:"redirect"})}else{let X="PayPal payment was not completed. Please try again.";q?.terminal({outcome:v?.status==="canceled"?"payment_cancelled":"payment_declined",...vr,terminalReason:v?.status==="canceled"?"cancelled":"provider_declined"}),a?.(X),p?.(un("paypal",X))}}catch(h){if(!qe)return;wa.delete(ke),Et(),a?.(h instanceof Error?h.message:"Failed to complete PayPal payment.")}finally{qe&&Oe(!1)}})(),()=>{qe=!1,Fe.current=!1}},[_,o,a,p,q]);let Z=(0,i.useCallback)(async(V=!1)=>{let ke=f?await f("paypal"):{proceed:!0};if(!ke.proceed)return de.current.delete(me),!1;let tt=D("paypal");return de.current.set(me,{generation:tt,accountPatch:ke.accountPatch,sessionId:ke.sessionId,nonce:ke.nonce}),A(!1),q?.log({name:`provider.${V?"redirect.started":"handoff.requested"}`,stage:V?"redirect":"overlay_open",...vr,attempt:tt}),d?.("paypal"),!0},[d,q,f,D,me]),Q=(0,i.useCallback)(async V=>{if(s||$||!await Z()){V.reject();return}V.resolve()},[s,Z,$]),pt=(0,i.useCallback)(async V=>{if(!_||!re)return;let ke=de.current.get(me);if(ke&&!oe(ke.generation)){de.current.delete(me);return}if(!ke&&Le()||ke&&!Se(ke.generation))return;ke||Se();let tt=ke??null;if(de.current.delete(me),!tt&&f){let Y=await f("paypal");if(!Y.proceed){V.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}tt={accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}}let ee=tt?.sessionId??e,qe=tt?.nonce??t,vt=await Eu({event:V,prepared:tt,email:n,billingName:P,methodLabel:"PayPal",collect:lt});if(!vt){V.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let nt=vt.email,Et={...tt?.accountPatch,...On(vt,!0)};try{if(Oe(!0),a?.(null),!ee||!(0,y.isValidEmail)(nt))throw new Error("Missing sessionId or email for PayPal payment");await k?.(vt);let Y=_.createPaymentMethod,{error:h,paymentMethod:v}=await Y({type:"paypal"});if(h){Be(h,"stripe_paypal_create_payment_method_failed",ke?.generation),V.paymentFailed({reason:"fail"});return}let X=await yi(r,j,ee,qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:v?.id??null,intentKind:"payment"});if(X.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let W=X.clientSecret,ve={return_url:Cs()};if(v?.id&&(ve.payment_method=v.id),!$t(ka,{clientSecret:W,sessionId:ee,nonce:qe,accountPatch:Et})&&b==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:Ve,paymentIntent:Ye}=await _.confirmPayment({clientSecret:W,confirmParams:ve,redirect:"if_required"});if(Ve){if($t(ka),fo(Ve)){let Ct=Ve.message??"Your payment was declined.";q?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}),a?.(Ct),p?.(un("paypal",Ct,{code:Mr(Ve),declineCode:No(Ve)})),await fi({billingApiUrl:r,sessionId:ee,nonce:qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mr(Ve)??"provider_declined"}})}else Be(Ve,"stripe_paypal_confirm_failed",ke?.generation);return}$t(ka);let we=typeof Ye?.payment_method=="string"?Ye.payment_method:Ye?.payment_method?.id;o({id:we??Ye?.id,type:"card",threeDSecureActionResultTokenId:Ye?.id,isPaypal:!0},{accountPatch:Et,paymentMethodCategory:"paypal",presentationMode:b,sessionId:ee,nonce:qe});return}catch(Y){Be(Y,"stripe_paypal_failed",ke?.generation)}finally{Oe(!1)}},[_,re,e,t,n,P,lt,k,r,j,o,a,p,f,Be,Se,oe,Le,q,b,me]),ft=(0,i.useCallback)(async()=>{if(!(Ue.current||s||$||!_||!re)){Ue.current=!0,Oe(!0);try{if(!await Z(!0))return;await pt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Ue.current=!1,Oe(!1)}}},[re,pt,s,Z,_,$]),Ae=b==="redirect"?(0,c.jsx)("button",{type:"button",disabled:s||$,onClick:()=>{ft()},style:{width:"100%",minHeight:Ia,border:"1px solid #d1d5db",borderRadius:S??8,background:"#ffc439",color:"#111827",cursor:s||$?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,c.jsx)(Jt.ExpressCheckoutElement,{onReady:V=>le(Pc(V,["paypal"])),onLoadError:()=>{le("load_error"),Ss(q,"paypal","paypal","provider_error")},onClick:Q,onConfirm:pt,onCancel:()=>{let V=de.current.get(me);de.current.delete(me),q?.terminal({outcome:"payment_cancelled",...vr,terminalReason:"cancelled",...V?{attempt:V.generation}:{}}),ue(V?.generation),A(!1),fe.current=!0,ut()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:J,emailRequired:J,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},me),gt=(0,c.jsxs)(c.Fragment,{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:[ct&&(0,c.jsx)("button",{ref:ce,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ze,style:gs,children:"Try PayPal again"}),xe&&(0,c.jsx)(Lo,{identity:xe.identity,methodLabel:xe.methodLabel,onComplete:Ee,onCancel:()=>Ee(null)},xe.id),(0,c.jsx)("div",{style:{display:xe?"none":void 0},children:Ae})]}),$&&!xe&&(0,c.jsx)(Ln,{status:"processing"})]});return b==="redirect"?gt:(0,c.jsx)(bc,{state:K,placeholderTestId:"flopay-paypal-placeholder",borderRadius:S,children:gt})}function cc(e){return e==="apple_pay"||e==="google_pay"}function dc({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:s,onErrorChange:d,onButtonClick:p,onDecline:u,onTechnicalFailure:f,runBeforeButtonClick:P,billingName:k,onBuyerIdentityReady:R,onLoadStateChange:S,placeholderBorderRadius:T,popupCapabilityOwner:E,externalTelemetryContext:b}){let C=Hr(),{emitInstrument:j}=(0,i.useContext)(tr),_=(0,Jt.useStripe)(),re=(0,Jt.useElements)(),q=(0,i.useMemo)(()=>li(pn(C),b),[b,C]),[K,le]=(0,i.useState)("loading");(0,i.useEffect)(()=>{S?.(K)},[K,S]);let[$,Oe]=(0,i.useState)(!1),Ue=(0,i.useRef)(!(0,y.isValidEmail)(n?.trim())||!k?.trim()).current,{request:J,collect:xe,finish:lt}=Oo(),Ee=(0,i.useRef)(null),Fe=(0,i.useRef)(null),[be,ce]=(0,i.useState)(0),[me,Ge]=(0,i.useState)(!1),[ct,A]=(0,i.useState)(()=>mi(e,t)?"blocked":"idle"),[fe,de]=(0,i.useState)("google_pay"),D=(0,i.useRef)(null),Se=(0,i.useRef)(!0),ue=(0,i.useRef)(!1),Le=(0,i.useRef)("google_pay"),oe=(0,i.useRef)("google_pay"),We=(0,i.useRef)(null),ut=(0,i.useRef)(null),Be=(0,i.useRef)(new Set),Je=(0,i.useRef)(null);(0,i.useEffect)(()=>(Se.current=!0,()=>{Se.current=!1;for(let Y of Be.current)window.clearTimeout(Y);Be.current.clear()}),[]);let Ze=(0,i.useRef)(new Map),{startAttempt:Z,finishAttempt:Q,invalidateAttempt:pt,isAttemptInvalidated:ft,isAttemptCurrent:Ae,generationRef:gt}=ya((Y,h,v)=>{f?.(Y,h,{...v,popupBlocked:v?.popupBlocked??oo(h),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),de(Y),Ge(!0),ce(X=>X+1)},{onHandoffObserved:Y=>{E.markAvailable(),q?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:gt.current,...Y==="apple_pay"||Y==="google_pay"?{walletType:Y}:{}})},defersMissingTerminal:cc,onMissingTerminalDeferred:(Y,h)=>{let v=q?.now()??globalThis.performance?.now()??Date.now(),X=Je.current,W=X?.generation===h?X.startedAt:v;q?.performance({stage:"overlay_return",durationMs:Math.max(0,v-W),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:h,...cc(Y)?{walletType:Y}:{}}),q?.flush?.().catch(()=>{})}});(0,i.useEffect)(()=>{me&&Fe.current?.focus()},[me,be]);let V=(0,i.useCallback)(()=>{ce(Y=>Y+1)},[]),ke=(0,i.useCallback)((Y,h,v,X,W=!1)=>{pt(X),f?.(Y,h,{code:v,popupBlocked:oo(h),telemetryReported:W,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),de(Y),Ge(!0),V()},[pt,f,V]),tt=(0,i.useCallback)(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{ue.current&&(ue.current=!1,tt())},[tt,be]);let ee=(0,i.useCallback)(()=>{Ge(!1),d?.(null),tt()},[tt,d]),qe=(0,i.useCallback)(()=>{D.current?.()},[]);(0,i.useEffect)(()=>{let Y=mi(e,t);if(!Y)return;let h=!1,v=!1,X=async()=>{if(!v){v=!0,h||A("checking");try{let W=await tc(_,Y.clientSecret,Be.current);if(h)return;let ve=ms(W,Y.providerObjectId,(0,y.isSetupIntentClientSecret)(Y.clientSecret));if(ve.kind==="confirmed"){if(!ec(e,t,Y.clientSecret))return;D.current=null,A("idle"),s({id:ve.paymentMethodId,type:"card",threeDSecureActionResultTokenId:ve.intentId},{...Y.accountPatch?{accountPatch:Y.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(ve.kind==="terminal"){ps(e,t,Y.clientSecret),D.current=null,A("idle"),de(Y.paymentMethodType),Ge(!0),V();return}A("blocked")}catch{h||A("blocked")}finally{v=!1}}};return D.current=X,A("blocked"),()=>{h=!0,D.current===X&&(D.current=null)}},[t,s,V,e,_]);let vt=(0,i.useCallback)(async Y=>{let h=!1,v=mt=>{h||(h=!0,Y.paymentFailed({reason:"fail",...mt?{message:mt}:{}}))};if(!_||!re){v();return}let X=Ze.current.get(be);if(X&&!Ae(X.generation)){Ze.current.delete(be),v();return}if(!X&&ft()){v();return}if(X&&!Q(X.generation)){v();return}X||Q();let W=Y.expressPaymentType??X?.method??Le.current,ve=X??null,Bt=ac(W),Ve;W==="apple_pay"?Ve="apple_pay":W==="google_pay"&&(Ve="google_pay");let Ye=X?.generation??gt.current,we=q,Ct=we?.now()??globalThis.performance?.now()??Date.now(),Wt=new AbortController,He=!1,Tn=!1,Ie=null,zn=e,Un="processing",Mt="other",kn="provider_runtime",An,Kn=new Promise((mt,Qe)=>{An=Qe}),mn=window.setTimeout(()=>{He=!0,Wt.abort(),An(ui)},hu),Dt=async(mt,Qe,In)=>{Un=mt,Mt=Qe,kn=Qe==="intent_create"||Qe==="session_claim"?"transport_error":"provider_runtime";let xt=we?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([In,Kn])}finally{let Rn=we?.now()??globalThis.performance?.now()??Date.now();we?.performance({stage:mt,durationMs:Math.max(0,Rn-xt),durationMode:"machine",requestCategory:Qe,paymentMethodCategory:"wallet",provider:"stripe",...He?{statusClass:"timeout"}:{}})}};try{if(Oe(!0),d?.(null),!ve&&P){let Re=await Dt("processing","other",P(Bt));if(!Re.proceed){v();return}ve={accountPatch:Re.accountPatch,sessionId:Re.sessionId,nonce:Re.nonce}}let mt=ve?.sessionId??e;zn=mt;let Qe=ve?.nonce??t,In=We.current??ve?.accountPatch,xt=hc({event:Y,fallbackEmail:In?.email??n,fallbackName:[In?.firstName,In?.lastName].join(" ").trim()||k});if(!(0,y.isValidEmail)(xt.email)){v("Buyer details are required."),xe(hs(W),xt).then(Re=>{Re&&(We.current=Re)});return}We.current=null;let Rn={...ve?.accountPatch,...On(xt,!0)};await Dt("processing","session_claim",Promise.resolve(R?.(xt)));let{error:yn}=await Dt("tokenization","provider_sdk",re.submit());if(yn){v(),ke(W,yn,"stripe_wallet_submit_failed",X?.generation);return}if(!mt)throw new Error("Missing sessionId or email for payment.");let Ht={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,paymentMethodId:null,intentKind:o},sn=JSON.stringify({sessionId:mt,nonce:Qe??"",request:Ht}),Gn=ut.current,Yn=Gn?.retryIdentity===sn?Gn.authorizationAttemptId:(0,y.randomUuidV4)();ut.current={authorizationAttemptId:Yn,retryIdentity:sn};let Tt=await Dt("processing","intent_create",yi(r,j,mt,Qe??"",{...Ht,authorizationAttemptId:Yn},{signal:Wt.signal}));if(Tt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let wt=Tt.clientSecret,vn=vu({createdAt:Date.now(),sessionId:mt,...Qe?{nonce:Qe}:{},clientSecret:wt,providerObjectId:Tt.providerObjectId,paymentMethodType:W,accountPatch:Rn});window.clearTimeout(mn),Tn=!0,we?.performance({stage:"callback",durationMs:Math.max(0,(we?.now()??globalThis.performance?.now()??Date.now())-Ct),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let rn=we?.now()??globalThis.performance?.now()??Date.now(),Ot={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Ve?{walletType:Ve}:{},attempt:Ye},ln=!1,Zt=null;we?.log({name:"payment.provider_confirmation.started",...Ot}),Ie=window.setTimeout(()=>{Ie!==null&&Be.current.delete(Ie),ln=!0;let Re=we?.now()??globalThis.performance?.now()??Date.now();we?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Ot,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Re-rn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),we?.flush?.().catch(()=>{}),Zt?.()},Pu),Be.current.add(Ie);let Lt=(Re,ye)=>{Ie!==null&&(window.clearTimeout(Ie),Be.current.delete(Ie),Ie=null);let F=we?.now()??globalThis.performance?.now()??Date.now(),at=Math.max(0,F-rn),ie=Re;ln&&(Re==="resolved"?ie="resolved_late":Re==="returned_error"?ie="returned_error_late":ie="rejected_late");let Sn=ye??(Re==="resolved"?"approved":"provider_error");return we?.log({name:"payment.provider_confirmation.returned",...Ot,operationOutcome:ie,terminalReason:Sn}),we?.performance({...Ot,durationMs:at,durationMode:"buyer",operationOutcome:ie,terminalReason:Sn}),{durationMs:at,operationOutcome:ie,terminalReason:Sn}},se=!1,cn=!1,qn=Re=>{if(!Re||typeof Re!="object")return null;let ye=Re;if(ye.error)return null;let F=ye.setupIntent??ye.paymentIntent,at=ms(F??null,void 0,!!ye.setupIntent);return at.kind==="confirmed"?at:null},Lr=Re=>{if(se||X&>.current!==X.generation)return;let ye=qn(Re);if(!ye)return;if(vn&&!ec(mt,Qe,wt)){se=!0;return}let{intentId:F,paymentMethodId:at}=ye;se=!0,cn=!0,ut.current=null,D.current=null,Se.current&&(A("idle"),Oe(!1));let ie=`${pc}:${mt}`;$t(ie,{createdAt:Date.now(),sessionId:mt,nonce:Qe,accountPatch:Rn,paymentMethodId:at,providerIntentId:F,paymentMethodType:W});try{s({id:at,type:"card",threeDSecureActionResultTokenId:F},{accountPatch:Rn,paymentMethodCategory:"wallet",sessionId:mt,nonce:Qe})}finally{$t(ie)}},sr=!1;Zt=async()=>{if(!(sr||se||cn)){sr=!0,Se.current&&A("checking");try{let Re=await tc(_,wt,Be.current);if(se||cn)return;let ye=(0,y.isSetupIntentClientSecret)(wt),F=ms(Re,Tt.providerObjectId,ye);if(F.kind==="confirmed"){Lr(ye?{setupIntent:Re}:{paymentIntent:Re});return}if(F.kind==="terminal"){if(cn=!0,ps(mt,Qe,wt),ut.current=null,D.current=null,!Se.current)return;A("idle"),v(),ke(W,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",X?.generation,!0);return}Se.current&&!cn&&(A("blocked"),Oe(!1))}catch{Se.current&&!cn&&(A("blocked"),Oe(!1))}finally{sr=!1}}},D.current=Zt;let Ut,lr;try{let Re=await((0,y.isSetupIntentClientSecret)(wt)?_.confirmSetup({elements:re,clientSecret:wt,redirect:"if_required"}):_.confirmPayment({elements:re,clientSecret:wt,redirect:"if_required"}));if(!Re||typeof Re!="object"||(Ut=Re,!Ut.error&&!qn(Ut)))throw us;lr=Lt(Ut.error?"returned_error":"resolved",Ut.error&&fo(Ut.error)?"provider_declined":void 0)}catch(Re){let ye=Re===us,F=Lt(ye?"returned_error":"rejected");if(we?.error({...ye?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:Gi(Re),...Ot,operationOutcome:F.operationOutcome,durationMs:F.durationMs,statusClass:"unknown",terminalReason:F.terminalReason}),!Se.current||se)return;await Zt?.();return}let Cn=Ut.error;if(Cn){if(!Se.current||se)return;if(fo(Cn)){cn=!0,ps(mt,Qe,wt),ut.current=null,D.current=null,A("idle");let Re=Cn.message??"Your payment was declined.";v(Re),d?.(Re),u?.(un(Bt,Re,{code:Mr(Cn),declineCode:No(Cn)})),fi({billingApiUrl:r,sessionId:mt,nonce:Qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,providerDeclineReason:Mr(Cn)??"provider_declined",...Tt.intentKind==="payment"&&Tt.providerObjectId.startsWith("pi_")?{providerIntentId:Tt.providerObjectId}:{}}})}else we?.error({...Gi(Cn),...Ot,operationOutcome:lr.operationOutcome,durationMs:lr.durationMs,statusClass:"unknown",terminalReason:lr.terminalReason}),await Zt?.();return}if(Lr(Ut),!se)throw new Error("Invalid provider returned for APM intent")}catch(mt){if(mt===ui){let Qe=we?.now()??globalThis.performance?.now()??Date.now();we?.error({errorCode:Su(Mt),stage:Un,requestCategory:Mt,paymentMethodCategory:"wallet",provider:"stripe",...Ve?{walletType:Ve}:{},operationOutcome:"watchdog_expired",checkoutSessionId:zn,durationMs:Math.max(0,Qe-Ct),statusClass:"timeout",failureCategory:kn,attempt:Ye,terminalReason:"provider_error"}),we?.flush?.().catch(()=>{})}v(),ke(W,mt,mt===ui?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",X?.generation,mt===ui)}finally{if(window.clearTimeout(mn),Ie!==null&&(window.clearTimeout(Ie),Be.current.delete(Ie)),!Tn){let mt=we?.now()??globalThis.performance?.now()??Date.now();we?.performance({stage:"callback",durationMs:Math.max(0,mt-Ct),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...He?{statusClass:"timeout"}:{}})}Se.current&&Oe(!1)}},[_,re,e,t,n,k,xe,R,r,j,o,s,d,u,P,ke,Q,Ae,ft,gt,q,be]),nt=(0,i.useMemo)(()=>{let Y=["applePay","googlePay","paypal","link","amazonPay","klarna"],h=new Set(["applePay","googlePay"]),v=new Set(a.map(y.stripeExpressMethodToOptionKey)),X={};for(let W of Y)v.has(W)?X[W]=h.has(W)?"always":"auto":X[W]="never";return X},[a]),Et=(0,i.useMemo)(()=>a.map(y.stripeExpressMethodToOptionKey),[a]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(bc,{state:K,placeholderTestId:"flopay-wallet-placeholder",borderRadius:T,children:(0,c.jsxs)("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[me&&(0,c.jsxs)("button",{ref:Fe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ee,style:gs,children:["Try ",hs(fe)," again"]}),ct!=="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:qe,disabled:ct==="checking",style:gs,children:ct==="checking"?"Checking payment status\u2026":"Check payment status"})]}),J&&(0,c.jsx)(Lo,{identity:J.identity,methodLabel:J.methodLabel,onComplete:lt,onCancel:()=>lt(null)},J.id),ct==="idle"&&(0,c.jsx)("div",{style:{display:J?"none":void 0},children:(0,c.jsx)(Jt.ExpressCheckoutElement,{onReady:Y=>{le(Pc(Y,Et))},onLoadError:Y=>{le("load_error"),Ss(q,"stripe","wallet","provider_error")},onClick:async Y=>{let h=q?.now()??globalThis.performance?.now()??Date.now();Le.current=Y.expressPaymentType,oe.current=ac(Y.expressPaymentType);let v=!0,X=window.setTimeout(()=>{v=!1,Y.reject()},gu),W=P?await P(oe.current):{proceed:!0};if(window.clearTimeout(X),!v)return;if(!W.proceed){Ze.current.delete(be),Y.reject();return}let ve=Z(Y.expressPaymentType);Je.current={generation:ve,startedAt:h},Ze.current.set(be,{generation:ve,method:Y.expressPaymentType,accountPatch:W.accountPatch,sessionId:W.sessionId,nonce:W.nonce}),Ge(!1),q?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ve,...Y.expressPaymentType==="apple_pay"||Y.expressPaymentType==="google_pay"?{walletType:Y.expressPaymentType}:{}}),p?.(oe.current),Y.resolve()},onConfirm:vt,onCancel:()=>{let Y=Ze.current.get(be);Ze.current.delete(be),q?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...Y?{attempt:Y.generation}:{}}),pt(Y?.generation),ut.current=null,Ge(!1),ue.current=!0,V()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:nt,emailRequired:Ue,billingAddressRequired:Ue,layout:{maxColumns:1,overflow:"never"}}},be)})]})}),$&&(0,c.jsx)(Ln,{status:"processing"})]})}function vc(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function Uu({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:s,backgroundColor:d,borderColor:p,textColor:u,borderRadius:f,fontFamily:P}){let k=(0,y.resolveStripeMethodBrandVariant)(e,t),R=jl[e],[S,T]=(0,i.useState)(!1),E=!!R&&!S,b=k?.backgroundColor??d??"#ffffff",C=k?.borderColor??p??"#d1d5db",j=k?.textColor??u??"#262833";return(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&s()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Ia,padding:"0 1rem",backgroundColor:b,color:j,border:`1px solid ${C}`,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,y.getStripeMethodDisplayName)(e)}\u2026`}):(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,y.hasVendoredStripeMethodLogo)(e)?8:0},children:[E?(0,c.jsx)("img",{src:R,alt:"","aria-hidden":"true",onError:()=>T(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!E&&k?.logoSvg?(0,c.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:k.logoSvg}}):null,(0,c.jsx)("span",{children:(0,y.getStripeMethodDisplayName)(e)})]}),a&&(0,c.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:j,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,c.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Ps({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:d,onErrorChange:p,onDecline:u,onCancel:f,runBeforeButtonClick:P,onButtonClick:k,isProcessing:R,submitButtonColor:S,submitButtonBorderRadius:T,submitButtonStyle:E,errorText:b}){let C=Hr(),{emitInstrument:j}=(0,i.useContext)(tr),_=(0,Jt.useStripe)(),re=(0,Jt.useElements)(),[q,K]=(0,i.useState)(!1),le=(0,i.useRef)(!1),[$,Oe]=(0,i.useState)(!1),[Ue,J]=(0,i.useState)("loading"),[xe,lt]=(0,i.useState)(""),Ee=!(0,y.isValidEmail)(r?.trim()),Fe=!Ee||(0,y.isValidEmail)(xe.trim()),be=(0,i.useCallback)(async()=>{if(!_||!re||R||le.current||!$)return;le.current=!0,K(!0);let ce=P?await P("card"):{proceed:!0};if(!ce.proceed){le.current=!1,K(!1);return}k?.("card");let me=ce.sessionId??t,Ge=ce.nonce??n,ct=mo(o?.trim()),A=On({email:ce.accountPatch?.email?.trim()||r?.trim()||xe.trim(),firstName:ce.accountPatch?.firstName?.trim()||ct.firstName,lastName:ce.accountPatch?.lastName?.trim()||ct.lastName}),fe=A.email,de=On({...ce.accountPatch,...A});try{if(p?.(null),!(0,y.isValidEmail)(fe))throw new Error("A valid email address is required for payment.");await a?.(A);let D=await re.submit();if(D.error){p?.(D.error.message??"Payment failed.");return}let Se=[A.firstName,A.lastName].filter(Boolean).join(" "),ue=await _.createPaymentMethod({elements:re,params:{billing_details:{email:fe,...Se?{name:Se}:{}}}});if(ue.error||!ue.paymentMethod){p?.(ue.error?.message??"Failed to create payment method.");return}let Le=ue.paymentMethod;if(!me||!fe)throw new Error("Missing sessionId or email for payment.");let oe=Le.type||e,We=await yi(s,j,me,Ge??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:oe,paymentMethodId:null,intentKind:"payment"});if(We.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ut=We.clientSecret;$t(Fr,{clientSecret:ut,sessionId:me,nonce:Ge,accountPatch:de,paymentMethodId:Le.id,paymentMethodType:Le.type??e,gateway:"stripe"});let{error:Be,paymentIntent:Je}=await _.confirmPayment({clientSecret:ut,confirmParams:{return_url:window.location.href,payment_method:Le.id},redirect:"if_required"});if(Be){$t(Fr);let Q=Be.message??"Payment failed.";p?.(Q),u?.(un("card",Q,{code:Be.code})),await fi({billingApiUrl:s,sessionId:me,nonce:Ge,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Be.code??"provider_declined"}});return}let Ze=Je?.status;if(!da(Ze)){$t(Fr);let Q=Ze==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(Q),u?.(un("card",Q,{code:Ze??"missing_payment_intent"}));return}$t(Fr);let Z=typeof Je?.payment_method=="string"?Je.payment_method:Je?.payment_method?.id;d({id:Z??Le.id,type:"card",threeDSecureActionResultTokenId:Je?.id,gateway:"stripe",paymentMethodType:Le.type??e},{accountPatch:de,paymentMethodCategory:"apm",sessionId:me,nonce:Ge})}catch(D){p?.(D instanceof Error?D.message:"Payment failed. Please try again.")}finally{le.current=!1,K(!1)}},[_,re,R,$,P,k,t,n,r,o,xe,a,s,j,e,d,p,u]);return(0,c.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Ee&&(0,c.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Ee&&(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:xe,onChange:ce=>lt(ce.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,c.jsx)(Jt.PaymentElement,{onReady:()=>J("ready"),onLoadError:()=>{J("load_error"),Ss(pn(C),"stripe","apm")},onChange:ce=>{Oe(!!ce.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,y.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{be()},disabled:!$||!Fe||q||R||Ue!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:S,color:"white",border:"none",borderRadius:T,fontSize:"1rem",fontWeight:600,cursor:!$||!Fe||q||R||Ue!=="ready"?"not-allowed":"pointer",opacity:!$||!Fe||q||R||Ue!=="ready"?.5:1,transition:"opacity 120ms ease-out",...E??{}},children:q?"Processing\u2026":`Pay with ${(0,y.getStripeMethodDisplayName)(e)}`}),b&&(0,c.jsx)(Uo,{margin:"0.75rem 0 0",children:b})]})}function uc({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:s,stripeInstance:d,paymentElementBaseOptions:p,onTokenizedBody:u,onErrorChange:f,onButtonClick:P,onDecline:k,runBeforeButtonClick:R,onLoadStateChange:S,isProcessing:T=!1,submitButtonColor:E="#4A49FF",submitButtonBorderRadius:b=8,submitButtonStyle:C,buttonAppearance:j,themeId:_,onExpandApm:re,expandedApmMethod:q}){let{emitInstrument:K}=(0,i.useContext)(tr),[le,$]=(0,i.useState)(null),[Oe,Ue]=(0,i.useState)(null),J=(0,i.useRef)(!1),{request:xe,collect:lt,finish:Ee}=Oo();(0,i.useEffect)(()=>{s.length>0&&d?S?.("ready"):d||S?.("loading")},[s.length,d,S]);let Fe=(0,i.useCallback)(async A=>{if(!d||J.current||T)return;J.current=!0,Ue(A);let fe=R?await R("card"):{proceed:!0};if(!fe.proceed){J.current=!1,Ue(null);return}P?.("card");let de=fe.sessionId??e,D=fe.nonce??t,Se=mo([fe.accountPatch?.firstName,fe.accountPatch?.lastName].filter(Boolean).join(" ")||r),ue=On({email:fe.accountPatch?.email?.trim()||n?.trim(),firstName:fe.accountPatch?.firstName?.trim()||Se.firstName,lastName:fe.accountPatch?.lastName?.trim()||Se.lastName});if(!(0,y.isValidEmail)(ue.email)){Ue(null);let We=await lt((0,y.getStripeMethodDisplayName)(A),ue);if(!We){J.current=!1;return}ue=We,Ue(A)}let Le=ue.email,oe=On({...fe.accountPatch,...ue});try{if(f?.(null),!de||!(0,y.isValidEmail)(Le))throw new Error("Missing sessionId or email for payment.");await o?.(ue);let We=await yi(a,K,de,D??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:A,paymentMethodId:null,intentKind:"payment"});if(We.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ut=We.clientSecret;$t(Fr,{clientSecret:ut,sessionId:de,nonce:D,accountPatch:oe,paymentMethodType:A,gateway:"stripe"});let{error:Be,paymentIntent:Je}=await d.confirmPayment({clientSecret:ut,confirmParams:{return_url:window.location.href,payment_method_data:{type:A,billing_details:{name:[ue.firstName,ue.lastName].filter(Boolean).join(" "),...Le?{email:Le}:{}}}},redirect:"if_required"});if(Be){$t(Fr);let Q=Be.message??"Payment failed.";f?.(Q),k?.(un("card",Q,{code:Be.code})),await fi({billingApiUrl:a,sessionId:de,nonce:D,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:A,providerDeclineReason:Be.code??"provider_declined"}});return}let Ze=Je?.status;if(!da(Ze)){$t(Fr);let Q=Ze==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(Q),k?.(un("card",Q,{code:Ze??"missing_payment_intent"}));return}$t(Fr);let Z=typeof Je?.payment_method=="string"?Je.payment_method:Je?.payment_method?.id;u({id:Z??Je?.id,type:"card",threeDSecureActionResultTokenId:Je?.id,gateway:"stripe",paymentMethodType:A},{accountPatch:oe,paymentMethodCategory:"apm",sessionId:de,nonce:D})}catch(We){f?.(We instanceof Error?We.message:"Payment failed. Please try again.")}finally{J.current=!1,Ue(null)}},[d,T,R,P,e,t,n,lt,a,K,r,o,u,f,k]),[be,ce]=(0,i.useState)(null),me=re?q??null:be,Ge=(0,i.useCallback)(A=>{J.current||T||me&&me!==A||((0,y.needsStripeMethodExplicitConfirm)(A)?re?re(A):ce(A):Fe(A))},[me,T,Fe,re]),ct=(0,i.useMemo)(()=>be?vc(p,be):null,[be,p]);return(0,c.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:xe?(0,c.jsx)(Lo,{identity:xe.identity,methodLabel:xe.methodLabel,onComplete:Ee,onCancel:()=>Ee(null)},xe.id):s.map(A=>{let fe=q===A,de=Oe===A,D=Oe!==null&&Oe!==A||q!=null&&q!==A;return(0,c.jsxs)(i.default.Fragment,{children:[(0,c.jsx)(Uu,{method:A,themeId:_,submitting:de,disabled:D,highlighted:fe,hasNextStep:(0,y.needsStripeMethodExplicitConfirm)(A),onClick:()=>Ge(A),backgroundColor:j?.backgroundColor,borderColor:j?.borderColor,textColor:j?.textColor,borderRadius:j?.borderRadius,fontFamily:j?.fontFamily}),!re&&be===A&&ct&&d&&(0,c.jsx)(Jt.Elements,{stripe:d,options:ct,children:(0,c.jsx)(Ps,{method:A,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:u,onErrorChange:f,onDecline:k,onCancel:()=>ce(null),runBeforeButtonClick:R,onButtonClick:P,isProcessing:T,submitButtonColor:E,submitButtonBorderRadius:b,submitButtonStyle:C})},A)]},A)})})}function qu({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:s,onError:d,onDecline:p,onTokenizedBody:u,firstName:f,lastName:P,chv:k,className:R,submitLabel:S,isProcessing:T,error:E,onErrorChange:b,showPayPal:C=!0,showStripe:j=!0,walletPresentation:_="auto",enabledPaymentMethods:re,enabledPaymentMethodCountries:q,showApplePay:K=!0,showGooglePay:le=!0,layout:$="default",theme:Oe,buttonsTheme:Ue,buttonsStyles:J,appearance:xe,cardButtonContent:lt,cardBackButtonContent:Ee,cardTitleContent:Fe,showSecurityFooter:be,onButtonClick:ce,onBeforeButtonClick:me,onBuyerIdentityReady:Ge,enableAVS:ct,cardFieldOrder:A,cardPreFormSlot:fe,avsLayout:de="row",country:D,zip:Se,addressLine1:ue,addressLine2:Le,city:oe,state:We,onCountryChange:ut,onZipChange:Be,avsCheck:Je,checkoutType:Ze,checkoutLayout:Z,totalAmount:Q=0,currency:pt="usd",initialCardOpen:ft=!1,directPaypal:Ae,isSubscription:gt=!1,session:V,dataAttachmentPending:ke=!1,dataAttachmentRequiresIdentity:tt=!1,debug:ee=!1}){let qe=Hr(),vt=Wa(),nt=(0,i.useContext)(Pr),{emitInstrument:Et}=(0,i.useContext)(tr),Y=(0,i.useRef)(null);Y.current||(Y.current=Ya());let h=Y.current,[,v]=(0,i.useState)(0),X=(0,i.useRef)(null);X.current||(X.current=Kr());let W=X.current,ve=(0,i.useMemo)(()=>({browser:W,capability:h,presentationMode:"popup"}),[W,h]),Bt=V??nt.session,Ve=Bt?.gateways?.paypal?.providerObjectType??Ae?.providerObjectType,Ye=ke||nt.claimPending===!0,we=tt||nt.claimRequiresIdentity===!0,Ct=Ye&&!we,Wt=Tl(),He=n||Wt,[Tn,Ie]=(0,i.useState)(!1),[zn,Un]=(0,i.useState)(null),[Mt,kn]=(0,i.useState)(D??""),[An,Kn]=(0,i.useState)(Se??""),[mn,Dt]=(0,i.useState)(ue??""),[mt,Qe]=(0,i.useState)(Le??""),[In,xt]=(0,i.useState)(oe??""),[Rn,yn]=(0,i.useState)(We??""),[Ht,sn]=(0,i.useState)(""),[Gn,Yn]=(0,i.useState)({}),Tt=(0,i.useRef)(Se??""),wt=(0,i.useRef)(D??""),vn=(0,i.useRef)(ue??""),rn=(0,i.useRef)(Le??""),Ot=(0,i.useRef)(oe??""),ln=(0,i.useRef)(We??""),Zt=(0,i.useRef)(""),Lt=(0,i.useRef)({});(0,i.useEffect)(()=>{let l=(I,ne,ze,pe,Me)=>{if(Lt.current[I])return;let Xt=ne?.trim();!Xt||Xt===ze.current||(ze.current=Xt,pe(Xt),Me?.(Xt))};l("country",D,wt,kn,ut),l("zip",Se,Tt,Kn,Be),l("addressLine1",ue,vn,Dt),l("addressLine2",Le,rn,Qe),l("city",oe,Ot,xt),l("state",We,ln,yn)},[D,Se,ue,Le,oe,We,ut,Be]);let se=(0,i.useMemo)(()=>(0,y.resolveAVSConfig)(ct),[ct]),cn=se!==null,qn=(0,i.useMemo)(()=>(0,y.isAuthorizationOnlySession)(V),[V]),Lr=!!V?.vault?.html,sr=!!V?.gateways?.pcivault,Ut=Wi(V),Cn=!!(V?.gateways?.stripe?.enabledPaymentMethods??re)?.includes("card")||Zr(V),Re=Lr||Cn||sr,ye=!!(j&&Re&&e),[F,at]=(0,i.useState)(()=>$!=="buttons"||ft?e??null:null),[ie,Sn]=(0,i.useState)(0),fn=$!=="buttons"||ft||!!e&&F===e,Kt=V?.captureMethod,Xn=(0,i.useRef)(qe);(0,i.useEffect)(()=>{Xn.current=qe},[qe]);let[yt,Xr]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!ye||!e||!fn){Xr(null);return}let l=Xn.current?Xn.current.cardCapture({sessionId:e,captureMethod:Kt}):new Cr.PciVaultCardCapture({sessionId:e,captureMethod:Kt,billingApiUrl:He,telemetry:r});return Xr({sessionId:e,captureMethod:Kt,billingApiUrl:He,telemetry:r,capture:l}),()=>{l.unmount()}},[ye,e,fn,Kt,He,r]);let Gt=ye&&e&&fn&&yt?.sessionId===e&&yt.captureMethod===Kt&&yt.billingApiUrl===He&&yt.telemetry===r?yt.capture:null,gn=(0,i.useMemo)(()=>{let l=Mt,I=se?(0,y.isAVSFieldVisible)(se.postal_code,l):!1;return Lu(l,An,I)},[se,Mt,An]),{avsInvalid:Nr,invalidAvsFields:zr}=(0,i.useMemo)(()=>{let l={line1:!1,city:!1,state:!1,zip:!1};if(!ye||!se)return{avsInvalid:!1,invalidAvsFields:l};let I=Mt,ne=(Me,Xt)=>(0,y.isAVSFieldVisible)(Me,I)&&!Xt.trim(),ze={line1:ne(se.address_line_1,mn),city:ne(se.city,In),state:ne(se.state,Rn),zip:gn.empty||gn.malformed};return{avsInvalid:ze.line1||ze.city||ze.state||ze.zip,invalidAvsFields:ze}},[ye,se,Mt,mn,In,Rn,gn]),[Mn,Qt]=(0,i.useState)(!1),[Sr,xn]=(0,i.useState)(!1),[Ur,Fn]=(0,i.useState)(!1),[wr,kr]=(0,i.useState)({line1:!1,city:!1,state:!1}),cr=(0,i.useRef)(!1),Jn=(0,i.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Zn=(0,i.useRef)(!1),Ft=(0,i.useCallback)(l=>{Jn.current[l]=!0,Zn.current=!0},[]),dr=(0,i.useCallback)(l=>!cr.current&&Jn.current[l],[]),_n=(0,i.useCallback)(l=>{dr(l)&&kr(I=>I[l]?I:{...I,[l]:!0})},[dr]),[Qn,Ir]=(0,i.useState)(()=>ys(V?.vault)),[ht,on]=(0,i.useState)(ft&&Re?"card":"buttons"),[en,qr]=(0,i.useState)(null),Vn=ht==="expanding"||ht==="card",Jr=V?.gateways?.stripe&&!Ut?"stripe":void 0,ur=(0,i.useCallback)(()=>{Et?.({class:"card_surface",provider:Jr})},[Jr,Et]),pr=(0,i.useRef)(null),hn=(0,i.useCallback)(l=>{pr.current&&clearTimeout(pr.current),pr.current=setTimeout(()=>{pr.current=null,l()},Ra)},[]);(0,i.useEffect)(()=>()=>{pr.current&&clearTimeout(pr.current)},[]);let mr=(0,i.useCallback)(()=>{ur(),at(e??null),Sn(l=>l+1),on("expanding"),hn(()=>on("card"))},[hn,ur,e]),Vr=(0,i.useCallback)(()=>{on("collapsing"),hn(()=>on("buttons"))},[hn]),En=(0,i.useCallback)(l=>{qr(l),on("apm-expanding"),hn(()=>on("apm-form"))},[hn]),L=(0,i.useCallback)(()=>{on("apm-collapsing"),hn(()=>{on("buttons"),qr(null)})},[hn]);(0,i.useEffect)(()=>{$==="buttons"&&ft&&Re&&(at(e??null),on("card"))},[$,ft,Re,e]);let[U,O]=(0,i.useState)(null),he=(0,i.useRef)(!1),je=(0,i.useRef)(null),Pt=(0,i.useRef)("idle"),[Ce,$e]=(0,i.useState)(!1),te=(0,i.useRef)(Ce);te.current=Ce;let[m,g]=(0,i.useState)(()=>Ae?.existingOrderId?{orderId:Ae.existingOrderId,attempts:1}:null),z=(0,i.useRef)(m);(0,i.useEffect)(()=>{z.current=m},[m]);let H=(0,i.useRef)(null),Pe=(0,i.useMemo)(()=>{if(Ge||nt.claimBuyerIdentity||V?.buyerIdentified!==!1||!e||!t)return;let l=`${He}|${e}|${t}`;H.current?.key!==l&&(H.current={key:l,claim:Bo(new Cr.PaymentAPI(He,{telemetry:!1}),e,t,{...a?{userId:a}:{},...f?{firstName:f}:{},...P?{lastName:P}:{}})});let I=H.current.claim;return async ne=>{await I(ne)}},[Ge,nt.claimBuyerIdentity,V?.buyerIdentified,e,t,He,a,f,P]),ae=Ge??nt.claimBuyerIdentity??Pe,rt=E??zn,It=(0,i.useMemo)(()=>(0,y.resolveTheme)(Oe),[Oe]),B=(0,i.useMemo)(()=>{let l=It?.buttonsLayout??(0,y.resolveButtonsLayoutTheme)(Ue);return J?{...l,...J,cardButton:{...l.cardButton,...J.cardButton},cardFormContainer:{...l.cardFormContainer,...J.cardFormContainer},backButton:{...l.backButton,...J.backButton},backButtonIcon:{...l.backButtonIcon,...J.backButtonIcon},submitButton:{...l.submitButton,...J.submitButton},title:{...l.title,...J.title}}:l},[It,Ue,J]),Te=xe??It?.appearance,At=(0,i.useMemo)(()=>Go({appearance:Te,buttonsStyles:B,layout:$}),[Te,B,$]),_e=nt.inlineSessionPatchProcessing??!1,G=(T??Tn)||_e,ge=He.replace(/\/+$/,""),x=(0,i.useMemo)(()=>Ki({userId:a,email:o,firstName:f,lastName:P,country:D,zip:Se},Gn),[a,o,f,P,D,Se,Gn]),Xe=[x.firstName,x.lastName].filter(l=>!!l?.trim()).join(" "),Rt=!(0,y.isValidEmail)(x.email?.trim()),Ne=(0,i.useRef)(null);ye&&Ne.current===null&&(Ne.current=Rt);let wn=ye&&(Ne.current??Rt),Rr=(0,i.useMemo)(()=>Nu(Ht,wn),[Ht,wn]),Co=Rr.empty||Rr.malformed,jn=(0,i.useMemo)(()=>qe?qe.getRawProvider():null,[qe]),Fs=(0,i.useMemo)(()=>vt?vt.getRawProvider():null,[vt]),Xo=Q||100,So=pt.toLowerCase(),Ri=(0,i.useMemo)(()=>Te?(0,Cr.toStripeAppearance)(Te):null,[Te]),wo=Ri,Bs=(0,i.useMemo)(()=>{let l=Ri??{},I=l.rules??{};return{...l,rules:{...I,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...I[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...I[".AccordionItemContents"]??{}}}}},[Ri]),Ds=(0,i.useMemo)(()=>({...kl(Q,V?.captureMethod),currency:So,...wo?{appearance:wo}:null}),[Q,So,V?.captureMethod,wo]),Os=(0,i.useMemo)(()=>({mode:"payment",amount:Xo,currency:So,captureMethod:"manual",setupFutureUsage:"off_session",...wo?{appearance:wo}:null}),[Xo,So,wo]),De=(0,i.useCallback)(l=>{Un(l),b?.(l)},[b]),_i=(0,i.useRef)(""),[Ls,Xc]=(0,i.useState)(!1),Ei=(0,i.useCallback)(()=>{Xc(!0)},[]);(0,i.useEffect)(()=>{if(!ye||!wn||!ae||!Ls||Co||_i.current)return;let l=On({email:(0,y.isValidEmail)(x.email?.trim())?x.email?.trim():Zt.current.trim(),firstName:x.firstName?.trim(),lastName:x.lastName?.trim()});_i.current=JSON.stringify(l),Yn(I=>({...I,...l})),Promise.resolve(ae(l)).catch(I=>{_i.current="",De(I instanceof Error?I.message:"Failed to attach buyer details.")})},[ye,wn,ae,Ls,Co,x.email,x.firstName,x.lastName,De]),(0,i.useEffect)(()=>{!ye||!Gt||Gt.setCardFieldOrder?.(A??null,se==null&&!wn)},[ye,Gt,A,se,wn]),(0,i.useEffect)(()=>{(ht==="expanding"||ht==="collapsing"||ht==="apm-expanding"||ht==="apm-collapsing")&&De(null)},[ht,De]);let _r=(0,i.useCallback)((l,I,ne)=>{p?.(un(l,I,ne))},[p]),ko=(0,i.useCallback)((l,I,ne)=>{let ze=ne?.popupBlocked??oo(I);ze&&h.markBlocked()&&v(dt=>dt+1);let pe=no(hs(l),ze,W.inAppBrowser),Me=Mr(I),Xt=(Me?.toLowerCase()==="error"?void 0:Me)??yo(ne?.code)??"external_payment_method_failed",gr=new y.FloPayError(pe,"api_error",{code:"external_payment_method_failed",param:l,details:{providerCode:Xt,popupBlocked:ze,inAppBrowser:W.inAppBrowser,appFamily:W.appFamily,popupCapability:h.current(),presentationMode:ne?.presentationMode??"popup"}});ne?.telemetryReported||pn(qe)?.error(Ho({...ve,presentationMode:ne?.presentationMode??"popup"},{errorCode:ze?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:ne?.provider??(l==="paypal"?"paypal":"stripe"),paymentMethodCategory:ne?.paymentMethodCategory??(l==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:ne?.terminalReason??(ze?"popup_blocked":"provider_error")})),O(null),$==="buttons"&&(on("buttons"),qr(null)),De(pe),d?.(gr),console.error("[FloPay] External payment method failed:",{method:l,code:Xt,popupBlocked:ze})},[W,ve,qe,$,d,h,De]);(0,i.useEffect)(()=>{if(!ye||!e){Ir(null);return}let l=ys(V?.vault);if(l){Ir(l);return}if(!fn){Ir(null);return}Ir(null);let I=!0;return new Cr.PaymentAPI(ge).getVaultCapture(e,t).then(ne=>{if(!I)return;let ze=ys(ne);ze?Ir(ze):De("Failed to load the secure card form.")}).catch(ne=>{I&&De(ne instanceof Error?ne.message:"Failed to load the secure card form.")}),()=>{I=!1}},[ye,fn,ie,e,V?.vault,ge,t,De]);let yr=(0,i.useRef)({onComplete:s,onError:d,updateError:De,emitDecline:_r,resolvedAccount:x,avsConfig:se,avsCheckProp:Je,sessionId:e,nonce:t,baseUrl:ge,captureMethod:V?.captureMethod,paymentId:V?.paymentId,authorizationExpiresAt:V?.authorizationExpiresAt,serverSideCardGateway:Ut});yr.current={onComplete:s,onError:d,updateError:De,emitDecline:_r,resolvedAccount:x,avsConfig:se,avsCheckProp:Je,sessionId:e,nonce:t,baseUrl:ge,captureMethod:V?.captureMethod,paymentId:V?.paymentId,authorizationExpiresAt:V?.authorizationExpiresAt,serverSideCardGateway:Ut};let Ti=(0,i.useRef)(!1),Ns=(0,i.useCallback)(()=>{let l=yr.current,I=l.resolvedAccount.email?.trim(),ne=(0,y.isValidEmail)(I)?I:Zt.current.trim();if(!(0,y.isValidEmail)(ne))return null;let ze=l.resolvedAccount.firstName?.trim(),pe=l.resolvedAccount.lastName?.trim(),Me=wt.current.trim()||l.resolvedAccount.country?.trim()||"",Xt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.state,Me):!1,gr=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_1,Me):!1,dt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.postal_code,Me):!1,bt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.city,Me):!1,kt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_2,Me):!1,Vt=gr&&!Xt&&dt?(0,y.getStateFromPostalCode)(Me,(Tt.current??"").trim()):null,dn=Xt?ln.current:Vt;return{accountData:{userId:l.resolvedAccount.userId??"",email:ne,...ze?{firstName:ze}:{},...pe?{lastName:pe}:{},...dt&&Tt.current?{zip:Tt.current}:{},...bt&&Ot.current?{city:Ot.current}:{},...dn?{state:dn}:{},...gr&&vn.current?{addressLine1:vn.current}:{},...kt&&rn.current?{addressLine2:rn.current}:{},...Me?{country:Me}:{}},...l.avsCheckProp===void 0?{}:{avsCheck:l.avsCheckProp},...l.avsConfig?{avsConfig:{country:(0,y.isAVSFieldVisible)(l.avsConfig.country,Me),postal_code:dt,address_line_1:gr,address_line_2:kt,city:bt,state:Xt}}:{}}},[]),zs=(0,i.useRef)(Ye);zs.current=Ye,(0,i.useEffect)(()=>{Ye||rt!==nc||yr.current.updateError(null)},[Ye,rt]),(0,i.useEffect)(()=>{!ye||!Gt||Gt.setSubmitGate?.(Nr||Ye||Co||Ce)},[ye,Gt,Nr,Ye,Co,Ce]),(0,i.useEffect)(()=>{if(!ye||!Gt)return;Ti.current=!1;let l=null,I=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null,Pt.current="idle",O(null)},400)},ne=Gt.on("submitting",()=>{Qt(!0),je.current&&clearTimeout(je.current),Pt.current="validation-window",je.current=setTimeout(()=>{je.current=null,Pt.current==="validation-window"&&(Pt.current="processing")},Iu),O("processing");let dt=yr.current;if(!dt.sessionId||!dt.nonce)return;let bt=Ns();if(!bt){dt.updateError("Enter a valid email address."),Pt.current="idle",O(null);return}new Cr.PaymentAPI(dt.baseUrl).patchAccountSnapshot(dt.sessionId,dt.nonce,bt,{telemetryMode:"best_effort"}).catch(kt=>{if(!_u(kt))return;let Vt=kt instanceof Error?kt.message:"Please check your billing address and try again.";dt.updateError(Vt),Pt.current="idle",O(null),dt.onError?.(kt instanceof y.FloPayError?kt:new y.FloPayError(Vt,"api_error"))})}),ze=Gt.on("complete",async dt=>{if(jo(dt.sessionId??yr.current.sessionId),Pt.current="terminal",$e(!1),O("success"),await new Promise(dn=>setTimeout(dn,600)),Ti.current)return;Ti.current=!0;let bt=yr.current,kt=(0,y.isAuthorizationOnlySession)(bt)||dt.outcome==="authorized",Vt=bt.serverSideCardGateway?{}:{paymentIntentId:dt.intentId};yr.current.onComplete?.(kt?{status:"authorized",...Vt,paymentId:dt.paymentId??bt.paymentId,sessionId:dt.sessionId??bt.sessionId,authorizationExpiresAt:dt.authorizationExpiresAt??bt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Vt,checkoutMethod:"card"})}),pe=Gt.on("decline",dt=>{let bt=yr.current,kt=dt.message??"Your payment was declined. Please try another card or contact your bank.";Pt.current="terminal",$e(!1),bt.updateError(kt),O("error");let Vt=dt.failureOutcome??(0,y.normalizeCheckoutFailureOutcome)(dt.declineReason)??"authorization_declined";bt.emitDecline("card",kt,{code:Vt,declineCode:Vt}),I()}),Me=Gt.on("error",dt=>{let bt=yr.current,kt=dt.message??"There was a problem processing your payment. Please try again.";Pt.current="terminal",$e(!1),bt.updateError(kt),O("error"),bt.onError?.(new y.FloPayError(kt,"api_error",{code:dt.failureOutcome??"capture_failed"})),I()}),Xt=Gt.on("challenge_dismissed",()=>{je.current&&(clearTimeout(je.current),je.current=null),Pt.current="processing",$e(!0),O(null)}),gr=Gt.on("blocked",()=>{if(te.current){yr.current.updateError(Ru);return}if(!zs.current){Qt(!0);return}Ei(),yr.current.updateError(nc)});return()=>{l&&(clearTimeout(l),l=null),je.current&&(clearTimeout(je.current),je.current=null),Pt.current="idle",$e(!1),O(null),ne(),ze(),pe(),Me(),Xt(),gr()}},[ye,Gt,Ei,Ns]);let Er=!!Ae?.clientId,Jo=Array.isArray(re),Ma=Jo&&re.length>0,Us=Jo&&re.includes("paypal"),xa=(0,i.useRef)(null);xa.current===null&&(xa.current=wu());let Io=xa.current?"redirect":Ha(W,_,h.current()),{expressMethods:Fa,paymentElementMethods:Zo}=(0,i.useMemo)(()=>(0,y.partitionStripeMethods)(re,{excludePaypal:Er}),[re,Er]),qs=Er||!!vt||Us&&Io==="redirect",Jc=(0,i.useMemo)(()=>qs?Fa.filter(l=>l!=="paypal"):Fa,[Fa,qs]),Zc=(0,i.useMemo)(()=>{let l=[];return K&&l.push("apple_pay"),le&&l.push("google_pay"),l},[K,le]),Ro=Jo?Jc:Zc,Qc=j&&Ro.length>0,Ai=cn?Mt:D,Ba=(0,i.useMemo)(()=>{let l=Ai?.trim().toUpperCase();return l?q?Zo.filter(I=>{let ne=q[I];return!ne||ne.length===0||ne.includes(l)}):(0,y.filterStripeMethodsByCountry)(Zo,Ai):Zo},[Zo,Ai,q]),Mi=(0,i.useMemo)(()=>({mode:"payment",amount:Xo,currency:So,paymentMethodCreation:"manual",appearance:Bs}),[Xo,So,Bs]),[Vs,js]=(0,i.useState)("loading"),[$s,Ws]=(0,i.useState)("loading"),[Hs,Ks]=(0,i.useState)("loading"),[ed,xi]=(0,i.useState)(!1),[Gs,Fi]=(0,i.useState)("loading"),[Bi,td]=(0,i.useState)();(0,i.useEffect)(()=>{td(Kr())},[]);let Da=Bi?.inAppBrowser,Oa=Bi?Ka(Bi,Ae?.approvalPresentation,Ve??(gt?"subscription":"order")):"popup",Ys=C&&(Er||(Jo?Us:Da===!1)),Xs=j&&Qc,Qo=(!Ct||!!nt.waitForDataAttachment)&&Ys&&Er,Js=Gs==="retrying"||Gs==="exhausted",ea=null;j&&(vt?ea=Fs:Io==="redirect"&&(ea=jn));let Zs=(0,i.useMemo)(()=>({...ve,presentationMode:Io}),[ve,Io]),ta=!Ct&&Ys&&!!ea&&(!Er||Js),_o=!Ct&&Xs&&!!jn,na=!Ct&&j&&Ma&&Ba.length>0&&!!jn,nd=Qo&&!Js?ed:ta&&sc(Vs),rd=_o&&sc($s),od=na&&Hs!=="load_error",Qs=l=>l==="loading"||l==="ready",el=Qo||ta&&Qs(Vs)||_o&&Qs($s)||na&&Hs!=="load_error",La=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(!La.current){if(!j&&!C){La.current=!0;let l=new y.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(l),De(l.message)}else if(!j&&C&&!Er){La.current=!0;let l=new y.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(l),De(l.message)}else if(Da!==void 0&&!Ct&&!Re&&!el){La.current=!0;let l=new y.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?.(l),De(l.message)}}},[j,C,Er,Da,Ct,Re,el,d,De]);let tl=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(tl.current||!Ma)return;let l=[];K!==!0&&l.push("showApplePay"),le!==!0&&l.push("showGooglePay"),l.length!==0&&(tl.current=!0,console.warn(`[FloPay] ${l.join(" / ")} ${l.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.`))},[Ma,K,le]);let nl=(0,i.useCallback)((l,I)=>nt.applyInlineSessionPatch?nt.applyInlineSessionPatch(l).then(ne=>({error:null,sessionId:ne.sessionId||e,nonce:ne.session?.clientSecret||t})).catch(ne=>{let ze=ic(I,ne);return De(ze.message),d?.(ze),{error:ze,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[nt.applyInlineSessionPatch,t,d,e,De]),fr=(0,i.useCallback)(async l=>{if(l!=="card"&&Ct&&await nt.waitForDataAttachment?.(),!me)return{proceed:!0};try{let I=await me({method:l,sessionId:e||void 0,createSession:nt.inlineSessionDraft});if(I===!1)return{proceed:!1};if(I&&typeof I=="object"){I.account&&Yn(ze=>({...ze??{},...I.account}));let ne=await nl(I,l);return ne.error?{proceed:!1,accountPatch:I.account}:{proceed:!0,accountPatch:I.account,sessionId:ne.sessionId,nonce:ne.nonce}}return{proceed:!0}}catch(I){let ne=ic(l,I);return De(ne.message),d?.(ne),{proceed:!1}}},[nl,nt.inlineSessionDraft,nt.waitForDataAttachment,Ct,me,d,e,De]),rl=(0,i.useCallback)(async(l,I)=>{if(he.current)return;he.current=!0,Ie(!0),O("processing"),De(null);let ne=I?.sessionId??e,ze=I?.nonce??t,pe=Ki(x,I?.accountPatch),Me=I?.completionPaymentMethodId??ua(l),Xt=l.originalPaymentMethodId?{...l,originalPaymentMethodId:void 0}:l,gr=xu(l),dt=I?.presentationMode?li(pn(qe),{...ve,presentationMode:I.presentationMode}):void 0,bt=()=>{Et?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:gr}),dt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...vr,requestCategory:"process_payment"})};try{let Vt=await new Cr.PaymentAPI(ge).processPayment(pe.userId??"",{sessionId:ne,nonce:ze,paymentMethodCategory:I?.paymentMethodCategory??Bu(l),tokenizedData:Xt,accountData:{...I?.accountPatch,userId:pe.userId??"",email:pe.email??"",firstName:pe.firstName||void 0,lastName:pe.lastName||void 0,...se?(()=>{let Nt=wt.current,Tr=(0,y.isAVSFieldVisible)(se.state,Nt),$n=(0,y.isAVSFieldVisible)(se.address_line_1,Nt),Ar=(0,y.isAVSFieldVisible)(se.postal_code,Nt),po=$n&&!Tr&&Ar?(0,y.getStateFromPostalCode)(Nt,(Tt.current??"").trim()):null,la=Tr?ln.current:po;return{country:Nt,...Ar&&Tt.current?{zip:Tt.current}:{},...(0,y.isAVSFieldVisible)(se.city,Nt)&&Ot.current?{city:Ot.current}:{},...la?{state:la}:{},...$n&&vn.current?{addressLine1:vn.current}:{},...(0,y.isAVSFieldVisible)(se.address_line_2,Nt)&&rn.current?{addressLine2:rn.current}:{}}})():{}},chv:k,avsCheck:Je??!1,checkoutType:Ze,checkoutLayout:Z,avsConfig:se?{country:(0,y.isAVSFieldVisible)(se.country,wt.current),postal_code:(0,y.isAVSFieldVisible)(se.postal_code,wt.current),address_line_1:(0,y.isAVSFieldVisible)(se.address_line_1,wt.current),address_line_2:(0,y.isAVSFieldVisible)(se.address_line_2,wt.current),city:(0,y.isAVSFieldVisible)(se.city,wt.current),state:(0,y.isAVSFieldVisible)(se.state,wt.current)}:void 0});if(Vt.ok){let Nt=Vt.status===204?null:await Vt.json().catch(()=>null),Tr=(0,y.isAuthorizationOnlySession)(V)||Nt?.status==="authorized";jo(ne),dt?.terminal({outcome:"payment_succeeded",...vr}),O("success"),g(null),await new Promise(po=>setTimeout(po,600));let $n;typeof Nt?.paymentId=="string"?$n=Nt.paymentId:V?.paymentId&&($n=V.paymentId);let Ar;typeof Nt?.authorizationExpiresAt=="string"?Ar=Nt.authorizationExpiresAt:V?.authorizationExpiresAt&&(Ar=V.authorizationExpiresAt),s?.(Tr?{status:"authorized",...$n===void 0?{}:{paymentId:$n},sessionId:typeof Nt?.sessionId=="string"?Nt.sessionId:ne,...Ar===void 0?{}:{authorizationExpiresAt:Ar},paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Me,checkoutMethod:l.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Me,checkoutMethod:l.isPaypal?"paypal":"card"});return}let dn=await Vt.json().catch(()=>null);if(dn?.type==="paypal_redirect_required"){let Nt=dn.threeDSecureToken,Tr=dn.paymentMethodId||l.id||"";if(!qe||!Nt){O("error"),De("PayPal authorization required but no token provided.");return}try{let $n=vt?.getRawProvider();if(!$n){De("PayPal is not available.");return}let Ar={return_url:window.location.href};Tr&&(Ar.payment_method=Tr);let{error:po}=await $n.confirmPayment({clientSecret:Nt,confirmParams:Ar,redirect:"if_required"});if(po){O("error");let la=po.message??"PayPal payment failed.";De(la),_r("paypal",la,{code:po.code})}}catch($n){O("error"),De($n instanceof Error?$n.message:"PayPal authorization failed.")}return}if(dn?.type==="paypal_direct_required"){let Nt=dn.orderId;if(!Nt){O("error"),De("PayPal retry required but no order id provided.");return}let Tr=z.current?.attempts??0;if(Tr>=2){O("error"),De("PayPal payment could not be completed after multiple attempts."),_r("paypal","paypal_direct_required retry limit exceeded");return}xi(!1),Fi("loading"),g({orderId:Nt,attempts:Tr+1}),O(null);return}(0,y.classifyPaymentRejection)(Vt.status,dn)?dt?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}):bt(),O("error");let hr=dn?.message??"Payment failed. Please try again.";De(hr),_r(l.isPaypal?"paypal":"card",hr,{code:dn?.code??dn?.gatewayErrorCode,declineCode:dn?.declineCode??dn?.gatewayDeclineReason}),await new Promise(Nt=>setTimeout(Nt,400))}catch(kt){fc(kt)||bt(),O("error"),De(kt instanceof Error?kt.message:"An unexpected error occurred"),await new Promise(Vt=>setTimeout(Vt,400))}finally{Ie(!1),O(null),he.current=!1}},[ge,e,t,x,se,Je,Ze,Z,k,qe,vt,V,s,De,_r,Et,ve]),Bn=(0,i.useCallback)((l,I)=>{u?u(l):rl(l,I)},[u,rl]),ra=`${pc}:${e}`;(0,i.useEffect)(()=>{if(typeof window>"u")return;let l=localStorage.getItem(ra);if(!l)return;let I;try{I=JSON.parse(l)}catch{$t(ra);return}if(!I||typeof I.createdAt!="number"||Date.now()-I.createdAt<0||Date.now()-I.createdAt>mc||typeof I.paymentMethodId!="string"||typeof I.providerIntentId!="string"||typeof I.paymentMethodType!="string"||I.sessionId!==e||!t||I.nonce!==t||!Ro.includes(I.paymentMethodType)){$t(ra);return}$t(ra),Bn({id:I.paymentMethodId,type:"card",threeDSecureActionResultTokenId:I.providerIntentId,gateway:"stripe",paymentMethodType:I.paymentMethodType},{...I.accountPatch?{accountPatch:I.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Bn,t,e,ra,Ro]);let ol=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(typeof window>"u"||ol.current)return;let[l,I,ne]=vs();if(!l||!I||xa.current||!qe)return;let ze=qe.getRawProvider();if(!ze)return;let pe=bt=>{let kt=localStorage.getItem(bt);if(!kt)return null;try{return JSON.parse(kt)}catch{return $t(bt),null}},Me=pe(Fr)??pe(Ql),Xt;if(Me?.clientSecret){if(Me.clientSecret!==I)return;Xt={...Me.accountPatch?{accountPatch:Me.accountPatch}:{},...Me.sessionId?{sessionId:Me.sessionId}:{},...Me.nonce?{nonce:Me.nonce}:{}}}else if(Me?.sessionId&&Me.sessionId!==e)return;ol.current=!0,$t(Fr),$t(Ql),window.history.replaceState({},"",Cs());let gr=Me?.paymentMethodType??Me?.tokenType??"card",dt="card";(async()=>{if(ne==="failed"){let hr="Payment was declined. Please try again.";De(hr),_r(dt,hr);return}let{paymentIntent:bt,error:kt}=await ze.retrievePaymentIntent(I);if(kt){let hr=kt.message??"Failed to retrieve payment status.";De(hr),_r(dt,hr,{code:kt.code});return}let Vt=bt?.status,dn=da(Vt);if(!bt||!dn){let hr=Vt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";De(hr),_r(dt,hr,{code:Vt??"missing_payment_intent"});return}let yl=typeof bt.payment_method=="string"?bt.payment_method:bt.payment_method?.id;Bn({id:yl??Me?.paymentMethodId??Me?.tokenId??bt.id,type:"card",threeDSecureActionResultTokenId:bt.id,gateway:Me?.gateway??"stripe",paymentMethodType:gr},Xt)})()},[e,Bn,qe,De,_r]);let Di=(0,i.useCallback)(l=>{l.preventDefault()},[]);if(!(ye||qe!==null))return(0,c.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let oa=$==="buttons",Dn=Te?.variables,ad=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Oi=Dn?.colorBackground,id=Oi&&!ad.has(Oi)?Oi:void 0,aa=B.cardInputBorder??(oa?"#e5e7eb":"#A4A4FF"),al=Dn?.colorDanger??"#dc2626",qt=l=>zr[l]&&(wr[l]||Mn),Na=Co&&(Ur||Mn),er=l=>l?al:aa,za=(gn.malformed||gn.empty)&&(Sr||Mn),sd=er(za),Li=B.cardFormContainer?.backgroundColor??id??(oa?"white":"#EDEDFF"),Eo=B.cardInputBackground??Dn?.colorBackground??"white",Ni=Mo(Ee),il=Mo(Fe),To=B.nameInput,sl=B.cardInputFontSize??zu(To?.fontSize)??Dn?.fontSizeBase??"16px",ll=typeof To?.fontFamily=="string"?To.fontFamily:Dn?.fontFamily??"Poppins, sans-serif",cl=ds(To?.fontWeight)??400,ld=B.cardInputColor??(typeof To?.color=="string"?To.color:void 0)??Dn?.colorText??"#262833",cd=B.cardInputPlaceholderColor??"#9ca3af",Yt=Dn?.borderRadius??"8px",co=Dn?.borderRadius??B.cardButton?.borderRadius??Yt,uo=Dn?.colorPrimary??"#4A49FF",dd=Dn?.colorPrimaryHover??Ko(uo,.12),zi=Dn?.colorText??"#262833",Ui={fontSize:sl,fontFamily:ll,fontWeight:cl,color:ld,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ia={marginTop:"0.375rem",...Ui,fontSize:"0.75rem",lineHeight:1.4,color:al},ud={"--flopay-input-placeholder-color":cd,"--flopay-input-font-size":sl,"--flopay-input-font-family":ll,"--flopay-input-font-weight":String(cl)},sa=B.cardFormContainer??{},qi=sa.padding??(oa?"0":"1rem"),Vi=sa.borderRadius??Yt,pd=Gt&&Qn?(0,c.jsx)(so,{capture:Gt,html:Qn.html,messageToken:Qn.messageToken,expectedOrigin:Qn.expectedOrigin,theme:At,submitLabel:S,onReady:()=>{if(!wn&&!se||typeof document>"u")return;let l=()=>{let ne=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(ne){cr.current=!0;try{ne.focus()}finally{cr.current=!1}}};Zn.current||l()},onError:l=>De(l),onValidation:l=>{let I=Pt.current;(I==="idle"||I==="validation-window")&&(De(l),l&&Pt.current==="validation-window"&&(je.current&&(clearTimeout(je.current),je.current=null),Pt.current="idle",O(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"}),dl=(0,c.jsxs)("div",{onFocusCapture:l=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(l.target.tagName)&&ur()},style:{backgroundColor:Li,borderRadius:Vi,...sa,padding:qi,...ud,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 @@ ${Ke.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),oa&&$n&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ge?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:Vr,style:{display:"inline-flex",alignItems:"center",gap:Ni?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,d.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,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Fo,{content:Re})]}),il?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:M.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...M.title},children:(0,d.jsx)(ca,{content:xe})})]}),!oa&&!il&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:zi,order:ge?-3:0,...M.title},children:(0,d.jsx)(ca,{content:xe})}),ge&&ye&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:ye}),ge&&In&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:Eo,border:`1px solid ${nr(Na)}`,borderRadius:Xt,padding:"10px"},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Ht,onChange:l=>{Bt("email"),hn.current=l.target.value,ln(l.target.value)},onPointerDown:()=>Bt("email"),onKeyDown:()=>Bt("email"),onBlur:()=>{dr("email")&&Fn(!0),Co||Ei()},disabled:K,required:!0,"aria-invalid":Na||void 0,"aria-describedby":Na?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ui}})}),Na&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ia,children:_r.empty?"Email address is required":"Enter a valid email address"})]}),ue&&(0,d.jsx)("div",{style:{order:ge?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let l=Dt,R=(pe=!1)=>({backgroundColor:Eo,border:`1px solid ${nr(pe)}`,borderRadius:Xt,marginTop:"0.5rem",padding:"10px"}),te=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ui}),ze=(0,y.getStateOptions)(l);return(0,d.jsxs)(d.Fragment,{children:[(0,y.isAVSFieldVisible)(ue.address_line_1,l)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:R(Vt("line1")),children:(0,d.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:on,onChange:pe=>{Bt("line1"),vt.current.addressLine1=!0,gn.current=pe.target.value,Ee(pe.target.value)},onPointerDown:()=>Bt("line1"),onKeyDown:()=>Bt("line1"),onBlur:()=>_n("line1"),disabled:K,required:!0,"aria-invalid":Vt("line1")||void 0,"aria-describedby":Vt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:te()})}),Vt("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ia,children:"Street address is required"})]}),(0,y.isAVSFieldVisible)(ue.address_line_2,l)&&(0,d.jsx)("div",{style:R(),children:(0,d.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:Rt,onChange:pe=>{vt.current.addressLine2=!0,Nt.current=pe.target.value,Mt(pe.target.value)},disabled:K,"data-testid":"flopay-address-line2",style:te()})}),((0,y.isAVSFieldVisible)(ue.city,l)||(0,y.isAVSFieldVisible)(ue.state,l))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(ue.city,l)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Eo,borderTop:`1px solid ${nr(Vt("city"))}`,borderRight:`1px solid ${nr(Vt("city"))}`,borderBottom:`1px solid ${nr(Vt("city"))}`,borderLeft:`1px solid ${nr(Vt("city"))}`,padding:"10px",borderTopLeftRadius:Xt,borderBottomLeftRadius:Xt,...(0,y.isAVSFieldVisible)(ue.state,l)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Xt}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:wn,onChange:pe=>{Bt("city"),vt.current.city=!0,en.current=pe.target.value,Ot(pe.target.value)},onPointerDown:()=>Bt("city"),onKeyDown:()=>Bt("city"),onBlur:()=>_n("city"),disabled:K,required:!0,"aria-invalid":Vt("city")||void 0,"aria-describedby":Vt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:te()})}),(0,y.isAVSFieldVisible)(ue.state,l)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Eo,borderTop:`1px solid ${nr(Vt("state"))}`,borderRight:`1px solid ${nr(Vt("state"))}`,borderBottom:`1px solid ${nr(Vt("state"))}`,borderLeft:`1px solid ${nr(Vt("state"))}`,padding:"10px",borderTopRightRadius:Xt,borderBottomRightRadius:Xt,...(0,y.isAVSFieldVisible)(ue.city,l)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${nr(Vt("state")||Vt("city"))}`}:{borderRadius:Xt}},children:ze?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Yn,onChange:pe=>{Bt("state"),vt.current.state=!0,Kt.current=pe.target.value,yn(pe.target.value)},onPointerDown:()=>Bt("state"),onKeyDown:()=>Bt("state"),onBlur:()=>_n("state"),disabled:K,autoComplete:"billing address-level1",required:!0,"aria-invalid":Vt("state")||void 0,"aria-describedby":Vt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...te(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,y.getStateLabel)(l)}),ze.map(pe=>(0,d.jsx)("option",{value:pe.code,children:pe.name},pe.code))]}):(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,y.getStateLabel)(l),autoComplete:"billing address-level1",value:Yn,onChange:pe=>{Bt("state"),vt.current.state=!0,Kt.current=pe.target.value,yn(pe.target.value)},onPointerDown:()=>Bt("state"),onKeyDown:()=>Bt("state"),onBlur:()=>_n("state"),disabled:K,required:!0,"aria-invalid":Vt("state")||void 0,"aria-describedby":Vt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:te()})})]}),Vt("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ia,children:"City is required"}),Vt("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ia,children:[(0,y.getStateLabel)(l)," is required"]}),((0,y.isAVSFieldVisible)(ue.country,l)||(0,y.isAVSFieldVisible)(ue.postal_code,l))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:le==="column"?"column":"row",gap:le==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(ue.country,l)&&(0,d.jsx)("div",{style:{flex:le==="row"?1:void 0,backgroundColor:Eo,borderTop:`1px solid ${aa}`,borderRight:`1px solid ${aa}`,borderBottom:`1px solid ${aa}`,borderLeft:`1px solid ${aa}`,padding:"10px",...le==="row"&&(0,y.isAVSFieldVisible)(ue.postal_code,l)?{borderRadius:"0",borderTopLeftRadius:Xt,borderBottomLeftRadius:Xt,borderRight:"none"}:{borderRadius:Xt}},children:(0,d.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Dt,onChange:pe=>{vt.current.country=!0,Qt.current=pe.target.value,Rn(pe.target.value),dt?.(pe.target.value),Kt.current="",yn("")},disabled:K,autoComplete:"billing country","data-testid":"flopay-country",style:{...te(),cursor:"pointer"},children:[Dt===""?(0,d.jsx)("option",{value:"",children:"Select country"}):null,y.COUNTRY_OPTIONS.map(pe=>(0,d.jsxs)("option",{value:pe.code,children:[pe.flag," ",pe.name]},pe.code))]})}),(0,y.isAVSFieldVisible)(ue.postal_code,l)&&(0,d.jsx)("div",{style:{flex:le==="row"?1:void 0,backgroundColor:Eo,border:`1px solid ${id}`,padding:"10px",...le==="row"&&(0,y.isAVSFieldVisible)(ue.country,l)?{borderRadius:"0",borderTopRightRadius:Xt,borderBottomRightRadius:Xt}:{borderRadius:Xt}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,y.getPostalCodeLabel)(Dt),autoComplete:"billing postal-code",value:Un,onChange:pe=>{Bt("zip"),vt.current.zip=!0,_t.current=pe.target.value,qn(pe.target.value),Me?.(pe.target.value)},onPointerDown:()=>Bt("zip"),onKeyDown:()=>Bt("zip"),onBlur:()=>{dr("zip")&&Mn(!0)},disabled:K,required:bn.required,"aria-invalid":za||void 0,"aria-describedby":za?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:te()})})]}),za&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ia,children:bn.empty?`${(0,y.getPostalCodeLabel)(l)} is required`:Du(l)})]})})()}),ge&&ud,et&&(0,d.jsx)(Uo,{margin:"0.75rem 0",styleOverride:M.errorBanner,children:et})]}),Ua={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"},ul=l=>Z?!_||!Tr?(0,d.jsx)("pre",{"data-testid":l,style:Ua,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":l,style:Ua,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${_}`,` directPaypalConfigured=${Tr}`,` inAppBrowserDetected=${String(Da)}`,` shouldRenderDirectPayPal=${Qo}`,` shouldRenderStripePayPal=${ta}`,` hasPaypalStripeInstance=${!!Fs}`].join(`
|
|
39
|
-
`)}):null,pl=l=>
|
|
40
|
-
`)}):null,ml=ht==="apm-expanding"||ht==="apm-form"||ht==="apm-collapsing",Ao;ht==="apm-expanding"?Ao=rc:ht==="apm-collapsing"&&(Ao=oc);let qa=nn?bc(xi,nn):null;if(V==="buttons"){let l=ht==="buttons"||ht==="expanding"||ht==="apm-expanding",R=ht==="expanding"||ht==="card"||ht==="collapsing",te=it===void 0?{boxSizing:"border-box",height:Ia,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ze;ht==="expanding"||ht==="apm-expanding"?ze=Au:(ht==="collapsing"||ht==="apm-collapsing")&&(ze=Tu);let pe;return ht==="expanding"?pe=rc:ht==="collapsing"&&(pe=oc),(0,d.jsxs)("form",{onSubmit:Di,className:k,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(fs,{}),z&&(0,d.jsx)(Ln,{status:z,errorMessage:et,authorized:jn}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!l&&!ze?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!l&&!ze?Mu:{},...ze?{animation:ze,pointerEvents:"none"}:{}},children:[ul("flopay-direct-paypal-gate-debug"),pl("flopay-stripe-gate-debug"),Qo&&Ie&&(0,d.jsxs)(d.Fragment,{children:[m&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(ma.Provider,{value:g,children:(0,d.jsx)(fa,{sessionId:e,nonce:t,billingApiUrl:Ke,email:x.email,billingName:Ye||void 0,onBuyerIdentityReady:oe,clientId:Ie.clientId,environment:Ie.environment,currency:mt.toUpperCase(),isSubscription:ft,providerObjectType:Qe,approvalPresentation:Oa==="popup"?void 0:Oa,onTokenizedBody:Bn,onComplete:s,onErrorChange:Fe,onDecline:u,onTechnicalFailure:ko,onButtonClick:se,runBeforeButtonClick:fr,isProcessing:K,onLoadStateChange:Mi,onInitializationStateChange:Fi,session:kt,existingOrderId:m?.orderId,debug:Z},m?.orderId??"fresh")})]}),ta&&(0,d.jsx)(Zt.Elements,{stripe:ea,options:Os,children:(0,d.jsx)(lc,{sessionId:e,nonce:t,email:x.email,billingName:Ye||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,onTokenizedBody:Bn,onErrorChange:Fe,isProcessing:K,onButtonClick:se,onDecline:u,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:js,placeholderBorderRadius:co,popupCapabilityOwner:g,externalTelemetryContext:Zs,presentationMode:Io})}),_o?(0,d.jsx)(Zt.Elements,{stripe:Wn,options:Ds,children:(0,d.jsx)(cc,{sessionId:e,nonce:t,email:x.email,billingName:Ye||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,intentKind:J>0?"payment":"setup",expressMethods:Ro,onTokenizedBody:Bn,onErrorChange:Fe,onButtonClick:se,onDecline:u,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:Ws,placeholderBorderRadius:co,popupCapabilityOwner:g,externalTelemetryContext:Xe})}):null,!_o&&Xs?(0,d.jsx)("div",{style:{height:Ia,borderRadius:co,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,na&&(0,d.jsx)(dc,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,paymentElementMethods:Ba,stripeInstance:Wn,paymentElementBaseOptions:xi,onTokenizedBody:Bn,onErrorChange:Fe,onButtonClick:se,onDecline:u,runBeforeButtonClick:fr,onLoadStateChange:Ks,isProcessing:K,submitButtonColor:uo,submitButtonBorderRadius:Xt,submitButtonStyle:M.submitButton,onExpandApm:En,expandedApmMethod:nn,themeId:Be,buttonAppearance:{backgroundColor:M.cardButton?.backgroundColor,borderColor:M.cardInputBorder,textColor:M.cardButton?.color,borderRadius:co}}),ge&&(0,d.jsx)("button",{type:"button",onClick:async()=>{K||!(await fr("card")).proceed||(se?.("card"),mr())},disabled:K,style:{width:"100%",...te,...M.cardButton,...ws({themeBundle:Tt,resolvedPrimaryColor:uo,resolvedBorderRadius:Xt,submitButtonStyle:M.submitButton,explicitPrimaryColor:Dn?.colorPrimary}),fontSize:M.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:K?"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:K?.6:1},onMouseEnter:Te=>{!K&&(Tt||Dn?.colorPrimary)&&(Te.currentTarget.style.backgroundColor=cd)},onMouseLeave:Te=>{(Tt||Dn?.colorPrimary)&&(Te.currentTarget.style.backgroundColor=uo)},onMouseDown:Te=>{Te.currentTarget.style.transform="scale(0.985)"},onMouseUp:Te=>{Te.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(Mo,{content:it})}),et&&ht==="buttons"&&(0,d.jsx)(Uo,{margin:"0.25rem 0",styleOverride:M.errorBanner,children:et})]}),ge&&R&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...pe?{animation:pe}:{},...ht==="collapsing"?{pointerEvents:"none"}:{}},children:dl}),q&&ml&&nn&&qa&&Wn&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Ao?{animation:Ao}:{},...ht==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Li,borderRadius:Vi,...sa,padding:qi},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:D,style:{display:"inline-flex",alignItems:"center",gap:Ni?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,d.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,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Fo,{content:Re})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:M.titleFontSize??"1.05rem",color:zi,paddingRight:80,...M.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(nn)}`})]}),(0,d.jsx)(Zt.Elements,{stripe:Wn,options:qa,children:(0,d.jsx)(Ps,{method:nn,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,onTokenizedBody:Bn,onErrorChange:Fe,onDecline:u,onCancel:D,runBeforeButtonClick:fr,onButtonClick:se,isProcessing:K,submitButtonColor:uo,submitButtonBorderRadius:Xt,submitButtonStyle:M.submitButton,errorText:et})},nn)]})})]})]})}return ml&&nn&&qa&&Wn&&q?(0,d.jsxs)("form",{onSubmit:Di,className:k,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(fs,{}),z&&(0,d.jsx)(Ln,{status:z,errorMessage:et,authorized:jn}),(0,d.jsx)("div",{style:{...Ao?{animation:Ao}:{},...ht==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Li,borderRadius:Vi,...sa,padding:qi},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:D,style:{display:"inline-flex",alignItems:"center",gap:Ni?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,d.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,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Fo,{content:Re})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:M.titleFontSize??"1.05rem",color:zi,paddingRight:80,...M.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(nn)}`})]}),(0,d.jsx)(Zt.Elements,{stripe:Wn,options:qa,children:(0,d.jsx)(Ps,{method:nn,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,onTokenizedBody:Bn,onErrorChange:Fe,onDecline:u,onCancel:D,runBeforeButtonClick:fr,onButtonClick:se,isProcessing:K,submitButtonColor:uo,submitButtonBorderRadius:Xt,submitButtonStyle:M.submitButton,errorText:et})},nn)]})})]}):(0,d.jsxs)("form",{onSubmit:Di,className:k,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(fs,{}),z&&(0,d.jsx)(Ln,{status:z,errorMessage:et,authorized:jn}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ul("flopay-direct-paypal-gate-debug-default"),pl("flopay-stripe-gate-debug-default"),Qo&&Ie&&(0,d.jsxs)(d.Fragment,{children:[m&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(ma.Provider,{value:g,children:(0,d.jsx)(fa,{sessionId:e,nonce:t,billingApiUrl:Ke,email:x.email,billingName:Ye||void 0,onBuyerIdentityReady:oe,clientId:Ie.clientId,environment:Ie.environment,currency:mt.toUpperCase(),isSubscription:ft,providerObjectType:Qe,approvalPresentation:Oa==="popup"?void 0:Oa,onTokenizedBody:Bn,onComplete:s,onErrorChange:Fe,onDecline:u,onTechnicalFailure:ko,onButtonClick:se,runBeforeButtonClick:fr,isProcessing:K,onLoadStateChange:Mi,onInitializationStateChange:Fi,session:kt,existingOrderId:m?.orderId,debug:Z},m?.orderId??"fresh")})]}),ta&&(0,d.jsx)(Zt.Elements,{stripe:ea,options:Os,children:(0,d.jsx)(lc,{sessionId:e,nonce:t,email:x.email,billingName:Ye||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,onTokenizedBody:Bn,onErrorChange:Fe,isProcessing:K,onButtonClick:se,onDecline:u,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:js,placeholderBorderRadius:co,popupCapabilityOwner:g,externalTelemetryContext:Zs,presentationMode:Io})}),_o&&(0,d.jsx)(Zt.Elements,{stripe:Wn,options:Ds,children:(0,d.jsx)(cc,{sessionId:e,nonce:t,email:x.email,billingName:Ye||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,intentKind:J>0?"payment":"setup",expressMethods:Ro,onTokenizedBody:Bn,onErrorChange:Fe,onButtonClick:se,onDecline:u,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:Ws,placeholderBorderRadius:co,popupCapabilityOwner:g,externalTelemetryContext:Xe})}),na&&(0,d.jsx)(dc,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Ke,paymentElementMethods:Ba,stripeInstance:Wn,paymentElementBaseOptions:xi,onTokenizedBody:Bn,onErrorChange:Fe,onButtonClick:se,onDecline:u,runBeforeButtonClick:fr,onLoadStateChange:Ks,isProcessing:K,submitButtonColor:uo,submitButtonBorderRadius:Xt,submitButtonStyle:M.submitButton,themeId:Be,onExpandApm:En,expandedApmMethod:nn,buttonAppearance:{backgroundColor:M.cardButton?.backgroundColor,borderColor:M.cardInputBorder,textColor:M.cardButton?.color,borderRadius:co}})]}),ge&&(nd||td||rd)&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,d.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,d.jsx)("span",{children:"or pay with card"}),(0,d.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),ge&&dl]})}var O=require("react/jsx-runtime"),Yo=44,Ts="flopay_checkout_saved_payment_resume",bi=new Map,hi=new Map;function vc(e,t){t.settled&&t.consumers===0&&bi.get(e)===t&&bi.delete(e)}function qu(e,t,n){let r=hi.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};hi.set(e,a);let s=()=>{hi.get(e)===a&&hi.delete(e)};return o.then(s,s),o}function _a(e){return new Promise(t=>setTimeout(t,e))}function Pi(e,t,n){let r=Xa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:tt.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Ea(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ks(e,t,n,r,o,a){let s=Pi(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),Ea(s)}function Cc(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 Sc(e,t,n,r,o){let a=(0,tt.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 tt.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof tt.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 Rc(e,t){let n=e?.data.paypal?.publishableKey;if(n)return{clientId:n,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation,...t?{existingOrderId:t}:{}}}function Is(e){return!e||e.data.stripe?.publishableKey?!1:!!Rc(e)?.clientId}var Vu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function ju(e){return new Yr.FloPay(Vu,{publishableKey:"provider_unavailable",...e})}async function Rs(e,t){let{publishableKey:n,paypalPublishableKey:r}=ss(e);return{...await ls({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function As(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function $u(){if(!As())return null;try{let e=window.sessionStorage.getItem(Ts);return e?JSON.parse(e):null}catch{return null}}function wc(e){if(As())try{window.sessionStorage.setItem(Ts,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function _s(){if(As())try{window.sessionStorage.removeItem(Ts)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Wu(){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 kc(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 Es(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Hu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Ic(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Ku(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 vi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:s,loading:c,error:u,onComplete:p,onError:h,onInstrument:b,onDecline:I,onCountryChange:k,onZipChange:C,showPayPal:f=!0,showStripe:S=!0,walletPresentation:G="auto",enabledPaymentMethods:_,showApplePay:q=!0,showGooglePay:E=!0,debug:ne=!1,layout:$,theme:W,buttonsTheme:ie,buttonsStyles:V,cardButtonContent:Be,cardBackButtonContent:Ue,cardTitleContent:X,showSecurityFooter:Ae,onButtonClick:it,onBeforeButtonClick:Re,enableAVS:xe,cardFieldOrder:ve,cardPreFormSlot:se,avsLayout:me,submitLabel:He,className:st,initialErrorMessage:T=null,initialPayPalOrderId:ye,children:le,checkoutMode:F,confirmLabel:Se,renderConfirmButton:ce,onSessionCompleted:De}){let re=(0,tt.resolveBillingApiUrl)(r),$e=(0,w.useMemo)(()=>(0,tt.resolveTheme)(W),[W]),dt=a??$e?.appearance,Me=n?"embedded_checkout":"standard_checkout",Oe=Es(le,$),[ut,Y]=(0,w.useState)(null),[J,mt]=(0,w.useState)(null),gt=(0,w.useRef)(null),Ie=(0,w.useRef)(null),ft=(0,w.useRef)(0),[U,we]=(0,w.useState)(null),lt=(0,w.useRef)(null),[Z,qe]=(0,w.useState)(null),St=(0,w.useMemo)(()=>n?Vo(n):"",[n]),Ze=n?`create:${St}`:`session:${e??""}`,H=Ic(Z),nt=(0,w.useRef)(new Set),g=(0,w.useRef)(Ze),v=(0,w.useRef)(Ze);go(()=>{v.current=Ze,g.current!==Ze&&(g.current=Ze,nt.current.clear())},[Ze]);let ee=(0,w.useCallback)(D=>{if(v.current===Ze){if(Ji.has(D.name)){if(nt.current.has(D.name))return;nt.current.add(D.name)}We(()=>b?.(D))}},[Ze,b]),de=zo(ee,Ze),Xe=(0,w.useRef)(!1),kt=(0,w.useCallback)(D=>{if(Xe.current)return;let z=D.gateway||!H?D:{...D,gateway:H};ee(z)},[ee,H]);(0,w.useEffect)(()=>{de({class:"lifecycle",name:"checkout.mount"})},[de]);let[Qe,ae]=(0,w.useState)(e??""),yt=e??Qe,It=n?"":yt,[qt,Ke]=(0,w.useState)(!0),[Lt,Ge]=(0,w.useState)(null),[zn,Tn]=(0,w.useState)(0),[Dt,Rn]=(0,w.useState)("full"),[Un,qn]=(0,w.useState)(!1),[on,Ee]=(0,w.useState)(T),[Rt,Mt]=(0,w.useState)(null),[wn,Ot]=(0,w.useState)(null),[Yn,yn]=(0,w.useState)(!1),[Ht,ln]=(0,w.useState)(void 0),[Xn,fn]=(0,w.useState)(""),[_t,Qt]=(0,w.useState)(!1),[gn,Nt]=(0,w.useState)(!1),[en,Kt]=(0,w.useState)(!1),hn=(0,w.useRef)(null),vt=(0,w.useRef)(0),ue=(0,w.useRef)(void 0),[Vn,jn]=(0,w.useState)("loading"),[Sr,kn]=(0,w.useState)(0),cn=(0,w.useRef)(!1),An=(0,w.useRef)(!1),Le=(0,w.useRef)(!1),Ct=(0,w.useRef)(null),ge=(0,w.useRef)(null),L=(0,w.useMemo)(()=>({checkoutMode:F??Dt,layout:Hu(le,$)}),[F,le,Dt,$]),rt=(0,w.useRef)(p);rt.current=p;let he=(0,w.useRef)(h);he.current=h;let Jn=(0,w.useRef)(I);Jn.current=I;let Pn=(0,w.useCallback)(D=>ai(Ct,async z=>{try{return await D(z)}catch(B){throw z.aborted?io(B):B}}),[]);(0,w.useEffect)(()=>()=>{Ct.current?.abort(),Ct.current=null},[]);let Gt=(0,w.useCallback)((D,z)=>{gt.current=D,mt(D),lt.current=z,we(z)},[]),Zn=(0,w.useCallback)(()=>{let D=Ie.current;D&&(Ie.current=null,D.destroy())},[]);(0,w.useEffect)(()=>{pn(J)?.setCheckoutContext(L),U&&U!==J&&pn(U)?.setCheckoutContext(L)},[J,U,L]);let pt=(0,w.useRef)(De);pt.current=De;let Xr=(0,w.useCallback)(D=>{jn(D),!(D!=="exhausted"||Le.current)&&(Le.current=!0,he.current?.(new tt.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Yt=(0,w.useCallback)(()=>{jn("retrying"),kn(D=>D+1)},[]);(0,w.useEffect)(()=>{jn("loading"),kn(0),Le.current=!1},[yt]),(0,w.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:tt.SDK_VERSION,checkout_type:Me,checkout_layout:Oe,billing_api_url:re})},[Oe,Me,re]);let bn=(0,w.useMemo)(()=>n?Vo(n,!0):"",[n]),Nr=(0,w.useMemo)(()=>Xn===bn?Ht:void 0,[Ht,Xn,bn]),zr=(0,w.useMemo)(()=>n?Hi(n,Nr):void 0,[n,Nr]),xn=F??zr?.checkoutMode??"full",tn=(0,w.useMemo)(()=>zr?{...zr,checkoutMode:xn}:void 0,[zr,xn]);(0,w.useEffect)(()=>{ln(void 0),fn(bn),ue.current=void 0,hn.current=null,Kt(!1)},[bn]),(0,w.useEffect)(()=>{Ee(T)},[T]);let wr=(0,w.useCallback)((D,z,B)=>{We(()=>{Jn.current?.(un(D,z,B))})},[]),Mn=(0,w.useCallback)(async(D,z)=>{Ee(null),Ot(null),yn(!1),Mt("processing");let B=z?.sessionId??D.id,Pe=D.clientSecret||t,Ve=Ic(D),Pt=gt.current??lt.current,Ce=pn(Pt),je=Pt?null:Pi(re,o,L),Q={log:M=>{Ce?Ce.log(M):je?.log(M)},error:M=>{Ce?Ce.error(M):je?.error(M)},terminal:M=>{Ce?Ce.terminal(M):je?.terminal(M)},performance:M=>{Ce?Ce.performance(M):je?.performance(M)},now:()=>Ce?.now()??je?.now()??0,elapsed:M=>Ce?.elapsed(M)??Math.max(0,(je?.now()??M)-M)},m=Q.now(),P=!!(z?.initialAutoProcessingError||z?.initialAutoProcessingPending),N=!1,j,be=()=>{N||(N=!0,P=!0,j=Q.now(),Q.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},oe=!1,et=()=>{oe||(oe=!0,Q.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),Q.performance({stage:"processing",durationMs:Q.elapsed(m),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),j!==void 0&&Q.performance({stage:"recovery",durationMs:Q.elapsed(j),durationMode:"machine",paymentMethodCategory:"saved"}))};Q.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Xe.current=!0;try{Q.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Xe.current=!1}de({class:"lifecycle",name:"payment.processing.started",provider:Ve}),P&&be();let Tt;try{let M=ql(z?.initialAutoProcessingError),_e=z?.initialAutoProcessingError?.type==="3ds_required"&&!z.initialAutoProcessingError.threeDSecureToken&&z.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:z.initialAutoProcessingError.nextActionRedirectUrl}:null,Ft,ke=K=>(be(),Pn(fe=>$o(K,{billingApiUrl:re,sessionId:B,nonce:Pe,session:D,signal:fe})));if(_e)Ft=await ke(_e);else if(M)be(),M.type==="paypal_redirect_required"&&ge.current?.publishableKey&&wc({sessionId:B,publishableKey:ge.current.publishableKey,paypalPublishableKey:ge.current.paypalPublishableKey}),Ft=await Pn(K=>si(M,{flopay:gt.current,paypalFlopay:lt.current,attempt3DS:z?.attempt3DS,billingApiUrl:re,sessionId:B,session:D,telemetry:!1,signal:K})),M.type==="paypal_redirect_required"&&_s();else if(z?.initialAutoProcessingPending){let K=z.initialAutoProcessingPending,fe=new Yr.PaymentAPI(re,{telemetry:!1}),x=await Pn(Ne=>fe.waitForCheckoutSessionCompletion(K.sessionId,{initialDelayMs:K.retryAfterMs,nonce:Pe,statusUrl:K.statusUrl,signal:Ne})),Ye=to(x,D),At=x.autoProcessingError?.type==="3ds_required"&&x.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:x.autoProcessingError.nextActionRedirectUrl}:null;if(At)Ft=await ke(At);else{if(!$r(Ye))throw Do(Ye);Ft=jr(Ye,B)}}else{if(z?.initialAutoProcessingError)throw Fr(z.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:z.initialAutoProcessingError.checkoutMethod});if(z?.fromCreateSession)return z?.fallbackToFull&&(Rn("full"),kc("full")),!1;{let K=await Wo({billingApiUrl:re,sessionId:B,session:D,nonce:Pe,telemetry:!1});K.type==="success"?Ft=K.result:K.type==="next_action_required"?Ft=await ke(K):(be(),K.type==="paypal_redirect_required"&&ge.current?.publishableKey&&wc({sessionId:B,publishableKey:ge.current.publishableKey,paypalPublishableKey:ge.current.paypalPublishableKey}),Ft=await Pn(fe=>si(K,{flopay:gt.current,paypalFlopay:lt.current,attempt3DS:z?.attempt3DS,billingApiUrl:re,sessionId:B,session:D,telemetry:!1,signal:fe})),K.type==="paypal_redirect_required"&&_s())}}B&&jo(B),et(),P&&(Q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),Q.terminal({outcome:Ft.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),yn(Ft.status==="authorized"),Mt("success"),await _a(600),Tt=()=>rt.current?.(Ft)}catch(M){let _e=Qr(va(M),B);if(_e.code==="three_ds_aborted")return!1;let Ft=_e.checkoutMethod??ba;Ee(_e.message),Ot(_e.message),yn(!1),z?.fallbackToFull&&(Q.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Rn("full"),kc("full")),et();let ke=_e.statusCode===void 0?void 0:(0,tt.telemetryStatusClass)(_e.statusCode,"unknown"),K=ke==="4xx"?{requestCategory:"process_payment",statusClass:ke}:{},fe=ke===void 0||ke==="4xx";if(fe&&(_e.telemetryOutcome==="payment_declined"||!!(_e.declineCode||_e.code?.toLowerCase().includes("declin"))))Q.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...K});else if(fe&&(_e.telemetryOutcome==="validation_rejected"||_e.type==="validation_error"))Q.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...K});else{let At=(0,tt.classifyTelemetryFailure)(M,P?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Ne=_e.telemetryRequestCategory??"process_payment";Xe.current=!0;try{Q.error({...At,..._e.telemetryFailureCategory?{failureCategory:_e.telemetryFailureCategory}:{},stage:P?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Ne})}finally{Xe.current=!1}de({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Ne,provider:Ve})}return We(()=>he.current?.(_e)),wr(Ft,_e,{code:_e.code,declineCode:_e.declineCode}),Mt("error"),await Promise.allSettled([_a(400),z?.ensureProvidersReady?z.ensureProvidersReady():Promise.resolve()]),P&&(Q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{et(),je&&Ea(je),Mt(null),Ot(null)}return We(Tt),!0},[wr,de,t,re,Pn,o,L]);(0,w.useEffect)(()=>{if(typeof window>"u"||An.current)return;let D=new URLSearchParams(window.location.search),z=D.get("payment_intent_client_secret");if(!z)return;let B=$u();B&&(An.current=!0,(async()=>{let Pe,Ve=0;Ee(null),Ot(null),Mt("processing"),qn(!0);try{if(D.get("redirect_status")==="failed")throw Object.assign(new tt.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Pt,paypalFlopay:Ce}=await ls({publishableKey:B.publishableKey,paypalPublishableKey:B.paypalPublishableKey,billingApiUrl:re,locale:s,telemetry:o});Pe=pn(Ce??Pt),Pe?.setCheckoutContext(L),Ve=Pe?.now()??0,Pe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let je=(Ce??Pt)?.getRawProvider();if(!je)throw Object.assign(new tt.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:Q,error:m}=await je.retrievePaymentIntent(z);if(m)throw Object.assign(new tt.FloPayError(m.message??"Failed to retrieve PayPal payment status.","api_error",{code:m.code}),{checkoutMethod:"paypal"});let P=Sl(Q?.status);if(!Q||P==="failed")throw Object.assign(new tt.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let N=typeof Q.payment_method=="string"?Q.payment_method:Q.payment_method?.id,j=P;if(B.sessionId){let et=(await new Yr.PaymentAPI(re,{telemetry:!1}).getUnifiedCheckoutSession(B.sessionId)).data.session;if(et&&et.status!=="complete"){let Tt=await Wo({billingApiUrl:re,sessionId:B.sessionId,session:et,telemetry:!1,tokenizedData:{id:N??Q.id,type:"card",threeDSecureActionResultTokenId:Q.id,isPaypal:!0}});if(Tt.type!=="success")throw Object.assign(new tt.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});j=Tt.result.status}}B.sessionId&&jo(B.sessionId),Pe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.performance({stage:"redirect_resume",durationMs:Pe.elapsed(Ve),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Mt("success"),await _a(600),We(()=>rt.current?.({status:j,paymentIntentId:Q.id,paymentMethodId:N,checkoutMethod:"paypal"}))}catch(Pt){let Ce=Qr(va(Pt),B.sessionId),je=Ce.checkoutMethod??"paypal",Q=!!(Ce.declineCode||Ce.code?.toLowerCase().includes("declin"));if(Pe)Pe.performance({stage:"redirect_resume",durationMs:Pe.elapsed(Ve),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Q?Pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Pe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(Q){let m=Pi(re,o,L);m.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ea(m)}else ks(re,o,L,"REDIRECT_RESUME_FAILED","redirect_resume");Ee(Ce.message),Ot(Ce.message),We(()=>he.current?.(Ce)),wr(je,Ce,{code:Ce.code,declineCode:Ce.declineCode}),Mt("error"),await _a(400)}finally{_s(),Wu(),Mt(null),Ot(null),qn(!1)}})())},[wr,s,re,o,L]);let Ur=(0,w.useRef)(null),Fn=(0,w.useMemo)(()=>tn?Vo(tn):"",[tn]),kr=(0,w.useRef)(tn);kr.current=tn,(0,w.useEffect)(()=>{ae(e??"")},[e]),(0,w.useEffect)(()=>{cn.current=!1,Ee(T),Ot(null),yn(!1),Mt(null)},[Fn,T,e]);async function Ir(D,z,B){let Pe=Pi(re,o,L),Ve=new Yr.PaymentAPI(re,{telemetry:!1}),Pt=!1;try{let Ce=D.idempotencyKey===void 0?void 0:(0,tt.resolveIdempotencyKey)(D.idempotencyKey),je=es(z,B),Q=ts(z,B);je?.canonicalIdentity===B&&Q&&Q.canonicalIdentity===void 0&&(ri(z,B,Q.idempotencyKey),Q={...Q,canonicalIdentity:B});let m=Ce??(Q?.canonicalIdentity===B?Q.idempotencyKey:void 0),P,N=!1;Pe.log({name:je?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let j=je?.sid??null,be=null,oe,et,Tt=!1;if(j)try{be=await Ve.getUnifiedCheckoutSession(j,je?.nonce),je&&je.canonicalIdentity===void 0&&(Ll(be.data.session,D)?(ni(z,B,j,je.nonce??be.data.session?.clientSecret),Q&&Q.canonicalIdentity===void 0&&(ri(z,B,Q.idempotencyKey),m??(m=Q.idempotencyKey))):(ti(z,B),Q=null,m=Ce,j=null,be=null));let _e=be?.data.session?.status,Ft=be?.data.session,ke=Ft?.clientSecret||je?.nonce;if(j&&Ft?.buyerIdentified===!1&&ke&&(et=Bo(Ve,j,ke,D.account)),j&&be&&_e==="complete"){if(ns(j))return{sid:j,result:be};ti(z,B),j=null,be=null,N=!0}}catch{Pe.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),je?.canonicalIdentity===void 0?(ti(z,B),m=Ce):ei(z,B),j=null}if(!j){!Ce&&(N||!m)&&(m=(0,tt.resolveIdempotencyKey)(),P=m),m&&ri(z,B,m);let _e=Pe.now(),Ft=0;Pe.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ke={...D,idempotencyKey:m,avsCheck:!!xe,avsConfig:typeof xe=="object"?xe:void 0,checkoutType:"embedded_checkout",checkoutLayout:Es(le,$)};Object.defineProperty(ke,Yr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:x=>{Ft=Math.max(Ft,x)}}});let K=()=>{Cc(Pe,"session_create",_e,Ft)},fe=x=>{Sc(Pe,x,"session_create",_e,Ft)&&de({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,tt.isDetachedSessionEligible)(ke)){let x=await Ve.createDetachedSession(ke);x.claimed.catch(()=>{}),be=x.shell,j=x.sessionId,et=x.claim;let Ye=Pe.now();Pe.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),oe=x.claimed.then(At=>{let Ne=At.data.session?.id??x.sessionId;return Ne&&ni(z,B,Ne,At.data.session?.clientSecret??x.nonce),Cc(Pe,"session_claim",Ye),K(),At},At=>{throw ei(z,B),Sc(Pe,At,"session_claim",Ye,0)&&de({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),At}).finally(()=>Ea(Pe)),oe.catch(()=>{}),Pt=!0,Pe.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Pe.performance({stage:"session_shell",durationMs:Pe.now()-_e,durationMode:"machine",requestCategory:"session_create",attempt:Ft,statusClass:"2xx",paymentMethodCategory:"card"})}else be=await Ve.createAndFetchSession(ke),K()}catch(x){throw fe(x),x}j=be.data.session?.id??j??"",j&&!oe&&ni(z,B,j,be.data.session?.clientSecret)}let M=be?.data.session;return!et&&j&&M?.buyerIdentified===!1&&M.clientSecret&&(et=Bo(Ve,j,M.clientSecret,D.account)),{sid:j??"",result:be,sdkGeneratedIdempotencyKey:P,...oe?{claimed:oe}:{},...et?{claim:et}:{},...Tt?{claimRequiresIdentity:!0}:{}}}finally{Pt||Ea(Pe)}}let cr=(0,w.useRef)(Ir);go(()=>{cr.current=Ir},[Ir]);let Qn=(0,w.useCallback)(async(D,z)=>{let B=kr.current;if(!B)throw new tt.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Pe=Hi(B,D),Ve=Vo(Pe),Pt=Ol(Pe),Ce=bi.get(Ve);if(!Ce){let m={canonicalIdentity:Ve,promise:cr.current(Pe,Pt,Ve),consumers:0,settled:!1};Ce=m,bi.set(Ve,m);let P=()=>{m.settled=!0,vc(Ve,m)};m.promise.then(P,P)}Ce.consumers+=1;let je=!1,Q=()=>{je||(je=!0,Ce.consumers-=1,vc(Ve,Ce))};z?.(Q);try{let m=await Ce.promise;Ur.current=Ve,D&&(fn(bn),ln(M=>bl(M,D)));let{sid:P,result:N,claimed:j,claim:be,claimRequiresIdentity:oe}=m;if(ue.current=be,Kt(oe===!0),Y(N),N.data.session&&qe(N.data.session),P&&ae(P),j){vt.current+=1;let M=vt.current;hn.current=j,Nt(!0),j.then(_e=>{vt.current===M&&(hn.current===j&&(hn.current=null),Y(_e),_e.data.session&&qe(_e.data.session),Nt(!1),Kt(!1))},_e=>{vt.current===M&&(hn.current===j&&(hn.current=null),Nt(!1),Kt(!1),Ge(_e instanceof tt.FloPayError?_e:new tt.FloPayError(_e instanceof Error?_e.message:"Failed to create session","api_error")))})}else vt.current+=1,hn.current=null,Nt(!1),Kt(!1);let{flopay:et,paypalFlopay:Tt}=await Rs(N,{billingApiUrl:re,locale:s,telemetry:o});return Gt(et,Tt),Ke(!1),m}catch(m){throw Ur.current===Ve&&(Ur.current=null),m}finally{z||Q()}},[bn,Gt,s,re,o]),er=(0,w.useRef)(Mn);er.current=Mn;let Bt=(0,w.useRef)(Qn);Bt.current=Qn;let dr=(0,w.useCallback)(async D=>{if(!Ku(D)||_t)return{sessionId:Qe,session:Z};Qt(!0);try{let z=await Qn(D);return{sessionId:z.sid,session:z.result.data.session??null}}finally{Qt(!1)}},[Qn,_t,Qe,Z]),_n=(0,w.useCallback)(async D=>{let z=ue.current;if(!z)return;let B=vt.current,Pe=await z(D);vt.current===B&&(Y(Pe),Pe.data.session&&qe(Pe.data.session))},[]),tr=(0,w.useCallback)(async()=>{await hn.current},[]),Rr=(0,w.useCallback)(async()=>(await tr(),{proceed:!0}),[tr]);(0,w.useEffect)(()=>{let D=!1,z,B=++ft.current;Zn(),Ge(null),Tn(0);let Pe=()=>{D=!0,ft.current===B&&(ft.current+=1,Zn())},Ve=kr.current;if(Fn&&Ve)return Rn(xn),Ke(!1),Ur.current===Fn?Pe:(qe(vl(Ve,F)),(async()=>{let je=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Q=xn==="auto"&&!cn.current&&!je;Q&&(Ee(null),Ot(null),Mt("processing"));try{let m=await Bt.current(void 0,be=>{z=be}),P=m.result.data.session??null;ge.current=ss(m.result);let N=Is(m.result),j=ns(m.sid||P?.id);if(!D&&Q&&P&&!N&&!j){cn.current=!0,await qu(Fn,m.sdkGeneratedIdempotencyKey,()=>er.current(P,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:m.result.autoProcessingError,initialAutoProcessingPending:m.result.autoProcessingPending,autoProcessingAttempted:m.result.autoProcessingAttempted,sessionId:m.sid||P.id}));return}!D&&Q&&((N||j)&&(cn.current=!0),Mt(null),Ot(null))}catch(m){if(D)return;let P=$a(m);if(Q&&P==="session_auto_completed"){cn.current=!0,Mt("success"),await _a(600),D||(We(()=>{rt.current?.({status:"succeeded"})}),Mt(null),Ot(null));return}Q&&(Mt(null),Ot(null));let N=m instanceof tt.FloPayError?m:new tt.FloPayError(m instanceof Error?m.message:"Failed to create session","api_error");Ge(N)}finally{z?.(),z=void 0}})(),()=>{Pe(),z?.()});Ke(!0);async function Pt(){let je=!1,Q=null;try{let m=new Yr.PaymentAPI(re,{telemetry:!1}),P=await m.getUnifiedCheckoutSession(yt,t);if(Q=P,D)return;Y(P);let N=P.data.session??null;if(qe(N),!N)throw new tt.FloPayError("No session data returned","api_error");let j=N.checkoutMode;if(j==="setup")throw new tt.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(N.status==="authorized"){Ke(!1),We(()=>{rt.current?.(jr(N,yt)),pt.current?.(N.successUrl??"")});return}if(N.status==="complete"){Ke(!1),We(()=>{pt.current?.(N.successUrl??"")});return}if(N.status==="expired")throw ja(N);je=!0;let be=F??j??"full";Rn(be),vt.current+=1;let oe=N.clientSecret||t;ue.current=N.buyerIdentified===!1&&oe?Bo(m,yt,oe,{...N.customer?.id?{userId:N.customer.id}:{}}):void 0,Nt(!1),Kt(!1);let et=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Tt=Is(P);if(be==="auto"&&!cn.current&&!et&&!Tt){cn.current=!0;let M=Ce(P);try{if(await er.current(N,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>M,sessionId:yt||N.id}),D)return;await M,D||Ke(!1);return}catch{if(D)return;await M,D||Ke(!1);return}}await Ce(P),D||Ke(!1)}catch(m){if(D)return;let P=Pl(m,je);if(je&&de({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),P){let{errorCode:j,stage:be,...oe}=P;ks(re,o,L,j,be,oe)}if(P?.stage==="provider_load"&&(F??Q?.data.session?.checkoutMode??"full")==="full"&&hl(Q,f,S)){let j=ju({billingApiUrl:re,locale:s,telemetry:o});Ie.current=j,Gt(j,null),Tn(1),Ke(!1);return}let N=m instanceof tt.FloPayError&&P?.stage!=="provider_load"?m:gl();N!==m&&We(()=>he.current?.(N)),Ge(N),Ke(!1)}}async function Ce(je){let{flopay:Q,paypalFlopay:m,...P}=await Rs(je,{billingApiUrl:re,locale:s,telemetry:o});ge.current={publishableKey:P.publishableKey,paypalPublishableKey:P.paypalPublishableKey},Gt(Q,m),Tn(0)}return Pt(),Pe},[F,Fn,xn,It,t,f,S]);let ht=(0,w.useCallback)(async()=>{if(!ut||zn!==1)return;let D=ft.current;Tn(2);try{let{flopay:z,paypalFlopay:B}=await Rs(ut,{billingApiUrl:re,locale:s,telemetry:o});if(ft.current!==D)return;Zn(),Gt(z,B),Tn(0)}catch(z){if(ft.current!==D)return;let{errorCode:B,stage:Pe,...Ve}=$i(z);ks(re,o,L,B,Pe,Ve)}},[Zn,Gt,s,zn,re,o,L,ut]),an=!!(yt&&(Z?.clientSecret||t)),nn=Un||!an,qr=(0,w.useCallback)(async()=>{if(!(Un||!an||!Z)){qn(!0),Ee(null);try{await Mn(Z,{attempt3DS:!0,fallbackToFull:!0,sessionId:yt||Z.id})}finally{qn(!1)}}},[yt,Un,an,Mn,Z]),$n=Rc(ut,ye),Jr=Is(ut),ur=(0,w.useMemo)(()=>{if(!(!ut||!Z||!ut.data.stripe?.publishableKey))return{billingApiUrl:re}},[ut,Z,re]),pr=!!(n&&!le&&$==="buttons"&&Re&&xn==="full"),vn=!!(yt&&(Z?.vault?.html||Zr(Z))),mr=(0,w.useMemo)(()=>({session:Z,loading:qt,error:Lt,checkoutMode:Dt,inlineSessionDraft:tn,applyInlineSessionPatch:pr?dr:void 0,inlineSessionPatchProcessing:_t,claimPending:gn,claimRequiresIdentity:en,claimBuyerIdentity:_n,waitForDataAttachment:tr}),[Z,qt,Lt,Dt,tn,pr,dr,_t,gn,en,_n,tr]),Vr=!!n&&$==="buttons"&&!Jr&&!vn&&(!J||!ur),En=Rt?(0,O.jsx)(Ln,{status:Rt,errorMessage:wn,authorized:Yn}):null;if(qt&&!vn){if(c)return(0,O.jsxs)(O.Fragment,{children:[c,En]});if($==="buttons"){let D=$e?.buttonsLayout?.cardButton?.borderRadius??$e?.appearance.variables?.borderRadius??8,z=B=>(0,O.jsx)("div",{style:{height:B,borderRadius:D,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[f&&z(Yo),S&&(q||E)&&z(Yo),S&&z(Yo),(0,O.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),En]})}return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,O.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,O.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),En]})}return Lt?u?(0,O.jsx)(Pr.Provider,{value:mr,children:u(Lt)}):(0,O.jsx)(Pr.Provider,{value:mr,children:(0,O.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Lt.message})}):Vr?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:mr,children:(0,O.jsx)(Yu,{onButtonClick:it,showPayPal:f,showStripe:S,showApplePay:q,showGooglePay:E,theme:W,buttonsTheme:ie,buttonsStyles:V,cardButtonContent:Be,cardBackButtonContent:Ue,cardTitleContent:X})}),En]}):Jr&&Z&&$n?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:mr,children:(0,O.jsxs)("div",{className:st,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[on&&(0,O.jsx)(Uo,{icon:!1,children:on}),Vn==="retrying"&&(0,O.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Vn==="exhausted"&&(0,O.jsxs)("div",{role:"alert",children:[(0,O.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,O.jsx)("button",{type:"button",onClick:Yt,children:"Retry PayPal"})]}),Vn!=="exhausted"&&(0,O.jsx)("div",{"aria-hidden":Vn==="retrying"?!0:void 0,style:Vn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,O.jsx)(Dl,{sessionId:yt,nonce:Z.clientSecret||void 0,billingApiUrl:re,email:Z.customer?.email||tn?.account?.email,billingName:[Z.customer?.firstName,Z.customer?.lastName].filter(Boolean).join(" ")||[tn?.account?.firstName,tn?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:_n,clientId:$n.clientId,environment:$n.environment,currency:(Z.currency??"usd").toUpperCase(),isSubscription:Z.mode==="subscription",providerObjectType:$n.providerObjectType,approvalPresentation:$n.approvalPresentation,existingOrderId:$n.existingOrderId,onComplete:p,onErrorChange:Ee,onDecline:I,onButtonClick:it,runBeforeButtonClick:Rr,onInitializationStateChange:Xr,allowAutomaticRetry:Sr===0,session:Z,telemetry:o,telemetryContext:L,onInstrument:kt,debug:ne},`${Ze}:paypal-init-${Sr}`)})]})}),En]}):Dt==="confirm"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:mr,children:(0,O.jsx)(ha,{flopay:J,paypalFlopay:U,options:ur??{billingApiUrl:re},onInstrument:kt,children:(0,O.jsxs)("div",{className:st,children:[on&&(0,O.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:on}),ce?ce({onConfirm:qr,isProcessing:nn}):(0,O.jsx)("button",{type:"button",onClick:qr,disabled:nn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:nn?"not-allowed":"pointer",opacity:nn?.6:1},children:Un?"Processing...":Se??"Confirm Purchase"})]})},Ze)}),En]}):(!J||!ur)&&!(vn&&Dt==="full")?(0,O.jsx)(O.Fragment,{children:En}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:mr,children:(0,O.jsxs)(ha,{flopay:J,paypalFlopay:U,options:ur??{billingApiUrl:re},onInstrument:kt,children:[zn===1&&(0,O.jsx)("button",{type:"button",onClick:ht,children:"Retry payment methods"}),le?(0,O.jsxs)(O.Fragment,{children:[on&&(0,O.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:on}),(0,O.jsx)(Gu,{sessionId:yt,nonce:Z?.clientSecret||void 0,billingApiUrl:re,session:Z,submitLabel:He,walletPresentation:G,children:le})]}):(0,O.jsx)(gi,{sessionId:yt,nonce:Z?.clientSecret||void 0,telemetry:o,email:Z?.customer?.email||tn?.account?.email,userId:Z?.customer?.id||tn?.account?.userId,firstName:Z?.customer?.firstName||tn?.account?.firstName,lastName:Z?.customer?.lastName||tn?.account?.lastName,totalAmount:Z?Math.round((0,tt.buildCheckoutDisplayData)(Z).total*100):0,currency:Z?.currency?.toLowerCase()??"usd",onComplete:p,onError:h,onDecline:I,error:on,onErrorChange:Ee,showPayPal:f,showStripe:S,walletPresentation:G,enabledPaymentMethods:zn?[]:_??ut?.data.stripe?.enabledPaymentMethods??Z?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ut?.data.stripe?.enabledPaymentMethodCountries,showApplePay:q,showGooglePay:E,layout:$,theme:W,buttonsTheme:ie,buttonsStyles:V,appearance:dt,cardButtonContent:Be,cardBackButtonContent:Ue,cardTitleContent:X,onButtonClick:it,onBeforeButtonClick:Re,onBuyerIdentityReady:_n,enableAVS:xe,...ve?{cardFieldOrder:ve}:{},...se?{cardPreFormSlot:se}:{},avsLayout:me,country:Z?.customer?.country,city:Z?.customer?.city,state:Z?.customer?.state,onCountryChange:k,onZipChange:C,avsCheck:!!xe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Es(le,$),className:st,submitLabel:He,directPaypal:$n,isSubscription:Z?.mode==="subscription",session:Z,dataAttachmentPending:gn,dataAttachmentRequiresIdentity:en,debug:ne})]},Ze)}),En]})}function Gu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:a,children:s}){return(0,O.jsx)(O.Fragment,{children:w.default.Children.map(s,c=>{if(!w.default.isValidElement(c))return c;let u=c.props,p={};return u.sessionId||(p.sessionId=e),!u.nonce&&t&&(p.nonce=t),u.billingApiUrl||(p.billingApiUrl=n),u.submitLabel===void 0&&o!==void 0&&(p.submitLabel=o),u.walletPresentation===void 0&&(p.walletPresentation=a),r?.customer&&(u.email||(p.email=r.customer.email),u.userId||(p.userId=r.customer.id),u.firstName||(p.firstName=r.customer.firstName),u.lastName||(p.lastName=r.customer.lastName)),Object.keys(p).length===0?c:w.default.cloneElement(c,p)})})}function Yu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:s,buttonsStyles:c,cardButtonContent:u,cardBackButtonContent:p,cardTitleContent:h}){let[b,I]=(0,w.useState)(!1),k=(0,w.useMemo)(()=>(0,tt.resolveTheme)(a),[a]),C=(0,w.useMemo)(()=>{let _=k?.buttonsLayout??(0,tt.resolveButtonsLayoutTheme)(s);return c?{..._,...c,cardButton:{..._.cardButton,...c.cardButton},cardFormContainer:{..._.cardFormContainer,...c.cardFormContainer},backButton:{..._.backButton,...c.backButton},backButtonIcon:{..._.backButtonIcon,...c.backButtonIcon},submitButton:{..._.submitButton,...c.submitButton},title:{..._.title,...c.title}}:_},[k,s,c]),f=k?.buttonsLayout?.cardButton?.borderRadius??k?.appearance.variables?.borderRadius??8,S=_=>(0,O.jsx)("div",{style:{height:_,borderRadius:f,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),G=u===void 0?{boxSizing:"border-box",height:Yo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let _=C.cardInputBorder??"#e5e7eb",q=C.cardInputBackground??"white",E=xo(p),ne=xo(h);return(0,O.jsxs)("div",{style:{backgroundColor:C.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...C.cardFormContainer},children:[(0,O.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,O.jsxs)("button",{type:"button",onClick:()=>I(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:E?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...C.backButton},children:[(0,O.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...C.backButtonIcon},children:(0,O.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,O.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,O.jsx)(Fo,{content:p})]}),ne?(0,O.jsx)("div",{style:{flex:1}}):(0,O.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...C.title},children:(0,O.jsx)(ca,{content:h})})]}),(0,O.jsx)("div",{style:{backgroundColor:q,border:`1px solid ${_}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsxs)("div",{style:{display:"flex"},children:[(0,O.jsx)("div",{style:{flex:1,backgroundColor:q,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${_}`,borderLeft:`1px solid ${_}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsx)("div",{style:{flex:1,backgroundColor:q,borderTop:"none",borderRight:`1px solid ${_}`,borderBottom:`1px solid ${_}`,borderLeft:`1px solid ${_}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,O.jsx)("div",{style:{backgroundColor:q,border:`1px solid ${_}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...C.submitButton,opacity:.5}}),(0,O.jsx)("style",{children:`
|
|
38
|
+
`}),oa&&Vn&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ye?-2:0},children:[(0,c.jsxs)("button",{type:"button",onClick:Vr,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:B.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...B.backButton},"aria-label":"Back to payment methods",children:[(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",...B.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)(Fo,{content:Ee})]}),il?(0,c.jsx)("div",{style:{flex:1}}):(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:B.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...B.title},children:(0,c.jsx)(ca,{content:Fe})})]}),!oa&&!il&&(0,c.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:zi,order:ye?-3:0,...B.title},children:(0,c.jsx)(ca,{content:Fe})}),ye&&fe&&(0,c.jsx)("div",{style:{order:-2,width:"100%"},children:fe}),ye&&wn&&(0,c.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,c.jsx)("div",{style:{backgroundColor:Eo,border:`1px solid ${er(Na)}`,borderRadius:Yt,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:Ht,onChange:l=>{Ft("email"),Zt.current=l.target.value,sn(l.target.value)},onPointerDown:()=>Ft("email"),onKeyDown:()=>Ft("email"),onBlur:()=>{dr("email")&&Fn(!0),Co||Ei()},disabled:G,required:!0,"aria-invalid":Na||void 0,"aria-describedby":Na?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ui}})}),Na&&(0,c.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ia,children:Rr.empty?"Email address is required":"Enter a valid email address"})]}),se&&(0,c.jsx)("div",{style:{order:ye?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let l=Mt,I=(pe=!1)=>({backgroundColor:Eo,border:`1px solid ${er(pe)}`,borderRadius:Yt,marginTop:"0.5rem",padding:"10px"}),ne=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ui}),ze=(0,y.getStateOptions)(l);return(0,c.jsxs)(c.Fragment,{children:[(0,y.isAVSFieldVisible)(se.address_line_1,l)&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("div",{style:I(qt("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:mn,onChange:pe=>{Ft("line1"),Lt.current.addressLine1=!0,vn.current=pe.target.value,Dt(pe.target.value)},onPointerDown:()=>Ft("line1"),onKeyDown:()=>Ft("line1"),onBlur:()=>_n("line1"),disabled:G,required:!0,"aria-invalid":qt("line1")||void 0,"aria-describedby":qt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:ne()})}),qt("line1")&&(0,c.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ia,children:"Street address is required"})]}),(0,y.isAVSFieldVisible)(se.address_line_2,l)&&(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:mt,onChange:pe=>{Lt.current.addressLine2=!0,rn.current=pe.target.value,Qe(pe.target.value)},disabled:G,"data-testid":"flopay-address-line2",style:ne()})}),((0,y.isAVSFieldVisible)(se.city,l)||(0,y.isAVSFieldVisible)(se.state,l))&&(0,c.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(se.city,l)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Eo,borderTop:`1px solid ${er(qt("city"))}`,borderRight:`1px solid ${er(qt("city"))}`,borderBottom:`1px solid ${er(qt("city"))}`,borderLeft:`1px solid ${er(qt("city"))}`,padding:"10px",borderTopLeftRadius:Yt,borderBottomLeftRadius:Yt,...(0,y.isAVSFieldVisible)(se.state,l)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Yt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:In,onChange:pe=>{Ft("city"),Lt.current.city=!0,Ot.current=pe.target.value,xt(pe.target.value)},onPointerDown:()=>Ft("city"),onKeyDown:()=>Ft("city"),onBlur:()=>_n("city"),disabled:G,required:!0,"aria-invalid":qt("city")||void 0,"aria-describedby":qt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:ne()})}),(0,y.isAVSFieldVisible)(se.state,l)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Eo,borderTop:`1px solid ${er(qt("state"))}`,borderRight:`1px solid ${er(qt("state"))}`,borderBottom:`1px solid ${er(qt("state"))}`,borderLeft:`1px solid ${er(qt("state"))}`,padding:"10px",borderTopRightRadius:Yt,borderBottomRightRadius:Yt,...(0,y.isAVSFieldVisible)(se.city,l)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${er(qt("state")||qt("city"))}`}:{borderRadius:Yt}},children:ze?(0,c.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Rn,onChange:pe=>{Ft("state"),Lt.current.state=!0,ln.current=pe.target.value,yn(pe.target.value)},onPointerDown:()=>Ft("state"),onKeyDown:()=>Ft("state"),onBlur:()=>_n("state"),disabled:G,autoComplete:"billing address-level1",required:!0,"aria-invalid":qt("state")||void 0,"aria-describedby":qt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...ne(),cursor:"pointer"},children:[(0,c.jsx)("option",{value:"",children:(0,y.getStateLabel)(l)}),ze.map(pe=>(0,c.jsx)("option",{value:pe.code,children:pe.name},pe.code))]}):(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,y.getStateLabel)(l),autoComplete:"billing address-level1",value:Rn,onChange:pe=>{Ft("state"),Lt.current.state=!0,ln.current=pe.target.value,yn(pe.target.value)},onPointerDown:()=>Ft("state"),onKeyDown:()=>Ft("state"),onBlur:()=>_n("state"),disabled:G,required:!0,"aria-invalid":qt("state")||void 0,"aria-describedby":qt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:ne()})})]}),qt("city")&&(0,c.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ia,children:"City is required"}),qt("state")&&(0,c.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ia,children:[(0,y.getStateLabel)(l)," is required"]}),((0,y.isAVSFieldVisible)(se.country,l)||(0,y.isAVSFieldVisible)(se.postal_code,l))&&(0,c.jsxs)("div",{style:{display:"flex",flexDirection:de==="column"?"column":"row",gap:de==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(se.country,l)&&(0,c.jsx)("div",{style:{flex:de==="row"?1:void 0,backgroundColor:Eo,borderTop:`1px solid ${aa}`,borderRight:`1px solid ${aa}`,borderBottom:`1px solid ${aa}`,borderLeft:`1px solid ${aa}`,padding:"10px",...de==="row"&&(0,y.isAVSFieldVisible)(se.postal_code,l)?{borderRadius:"0",borderTopLeftRadius:Yt,borderBottomLeftRadius:Yt,borderRight:"none"}:{borderRadius:Yt}},children:(0,c.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Mt,onChange:pe=>{Lt.current.country=!0,wt.current=pe.target.value,kn(pe.target.value),ut?.(pe.target.value),ln.current="",yn("")},disabled:G,autoComplete:"billing country","data-testid":"flopay-country",style:{...ne(),cursor:"pointer"},children:[Mt===""?(0,c.jsx)("option",{value:"",children:"Select country"}):null,y.COUNTRY_OPTIONS.map(pe=>(0,c.jsxs)("option",{value:pe.code,children:[pe.flag," ",pe.name]},pe.code))]})}),(0,y.isAVSFieldVisible)(se.postal_code,l)&&(0,c.jsx)("div",{style:{flex:de==="row"?1:void 0,backgroundColor:Eo,border:`1px solid ${sd}`,padding:"10px",...de==="row"&&(0,y.isAVSFieldVisible)(se.country,l)?{borderRadius:"0",borderTopRightRadius:Yt,borderBottomRightRadius:Yt}:{borderRadius:Yt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,y.getPostalCodeLabel)(Mt),autoComplete:"billing postal-code",value:An,onChange:pe=>{Ft("zip"),Lt.current.zip=!0,Tt.current=pe.target.value,Kn(pe.target.value),Be?.(pe.target.value)},onPointerDown:()=>Ft("zip"),onKeyDown:()=>Ft("zip"),onBlur:()=>{dr("zip")&&xn(!0)},disabled:G,required:gn.required,"aria-invalid":za||void 0,"aria-describedby":za?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:ne()})})]}),za&&(0,c.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ia,children:gn.empty?`${(0,y.getPostalCodeLabel)(l)} is required`:Ou(l)})]})})()}),ye&&pd,rt&&(0,c.jsx)(Uo,{margin:"0.75rem 0",styleOverride:B.errorBanner,children:rt})]}),Ua={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"},ul=l=>ee?!C||!Er?(0,c.jsx)("pre",{"data-testid":l,style:Ua,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":l,style:Ua,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${C}`,` directPaypalConfigured=${Er}`,` inAppBrowserDetected=${String(Da)}`,` shouldRenderDirectPayPal=${Qo}`,` shouldRenderStripePayPal=${ta}`,` hasPaypalStripeInstance=${!!Fs}`].join(`
|
|
39
|
+
`)}):null,pl=l=>ee?!j||!jn?(0,c.jsx)("pre",{"data-testid":l,style:Ua,children:"FloPay/Stripe-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":l,style:Ua,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${j}`,` currency=${pt}`,` amountInCents=${Xo}`,` enabledPaymentMethods: ${JSON.stringify(re??[])}`,` enabledPaymentMethodsProvided=${Jo}`,` hasEnabledMethods=${Ma}`,` expressMethods: ${JSON.stringify(Fa)}`,` walletExpressMethods: ${JSON.stringify(Ro)}`,` paymentElementMethods: ${JSON.stringify(Zo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ba)}`,` hasStripeInstance=${!!jn}`,` shouldRenderWallets=${_o}`,` shouldRenderPaymentElement=${na}`].join(`
|
|
40
|
+
`)}):null,ml=ht==="apm-expanding"||ht==="apm-form"||ht==="apm-collapsing",Ao;ht==="apm-expanding"?Ao=rc:ht==="apm-collapsing"&&(Ao=oc);let qa=en?vc(Mi,en):null;if($==="buttons"){let l=ht==="buttons"||ht==="expanding"||ht==="apm-expanding",I=ht==="expanding"||ht==="card"||ht==="collapsing",ne=lt===void 0?{boxSizing:"border-box",height:Ia,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ze;ht==="expanding"||ht==="apm-expanding"?ze=Mu:(ht==="collapsing"||ht==="apm-collapsing")&&(ze=Au);let pe;return ht==="expanding"?pe=rc:ht==="collapsing"&&(pe=oc),(0,c.jsxs)("form",{onSubmit:Di,className:R,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(fs,{}),U&&(0,c.jsx)(Ln,{status:U,errorMessage:rt,authorized:qn}),(0,c.jsxs)("div",{style:{display:"grid"},children:[(0,c.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!l&&!ze?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!l&&!ze?Fu:{},...ze?{animation:ze,pointerEvents:"none"}:{}},children:[ul("flopay-direct-paypal-gate-debug"),pl("flopay-stripe-gate-debug"),Qo&&Ae&&(0,c.jsxs)(c.Fragment,{children:[m&&(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)(ma.Provider,{value:h,children:(0,c.jsx)(fa,{sessionId:e,nonce:t,billingApiUrl:He,email:x.email,billingName:Xe||void 0,onBuyerIdentityReady:ae,clientId:Ae.clientId,environment:Ae.environment,currency:pt.toUpperCase(),isSubscription:gt,providerObjectType:Ve,approvalPresentation:Oa==="popup"?void 0:Oa,onTokenizedBody:Bn,onComplete:s,onErrorChange:De,onDecline:p,onTechnicalFailure:ko,onButtonClick:ce,runBeforeButtonClick:fr,isProcessing:G,onLoadStateChange:xi,onInitializationStateChange:Fi,session:Bt,existingOrderId:m?.orderId,debug:ee},m?.orderId??"fresh")})]}),ta&&(0,c.jsx)(Jt.Elements,{stripe:ea,options:Os,children:(0,c.jsx)(lc,{sessionId:e,nonce:t,email:x.email,billingName:Xe||void 0,onBuyerIdentityReady:ae,billingApiUrl:He,onTokenizedBody:Bn,onErrorChange:De,isProcessing:G,onButtonClick:ce,onDecline:p,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:js,placeholderBorderRadius:co,popupCapabilityOwner:h,externalTelemetryContext:Zs,presentationMode:Io})}),_o?(0,c.jsx)(Jt.Elements,{stripe:jn,options:Ds,children:(0,c.jsx)(dc,{sessionId:e,nonce:t,email:x.email,billingName:Xe||void 0,onBuyerIdentityReady:ae,billingApiUrl:He,intentKind:Q>0?"payment":"setup",expressMethods:Ro,onTokenizedBody:Bn,onErrorChange:De,onButtonClick:ce,onDecline:p,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:Ws,placeholderBorderRadius:co,popupCapabilityOwner:h,externalTelemetryContext:ve})}):null,!_o&&Xs?(0,c.jsx)("div",{style:{height:Ia,borderRadius:co,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,na&&(0,c.jsx)(uc,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ae,billingApiUrl:He,paymentElementMethods:Ba,stripeInstance:jn,paymentElementBaseOptions:Mi,onTokenizedBody:Bn,onErrorChange:De,onButtonClick:ce,onDecline:p,runBeforeButtonClick:fr,onLoadStateChange:Ks,isProcessing:G,submitButtonColor:uo,submitButtonBorderRadius:Yt,submitButtonStyle:B.submitButton,onExpandApm:En,expandedApmMethod:en,themeId:Oe,buttonAppearance:{backgroundColor:B.cardButton?.backgroundColor,borderColor:B.cardInputBorder,textColor:B.cardButton?.color,borderRadius:co}}),ye&&(0,c.jsx)("button",{type:"button",onClick:async()=>{G||!(await fr("card")).proceed||(ce?.("card"),mr())},disabled:G,style:{width:"100%",...ne,...B.cardButton,...ws({themeBundle:It,resolvedPrimaryColor:uo,resolvedBorderRadius:Yt,submitButtonStyle:B.submitButton,explicitPrimaryColor:Dn?.colorPrimary}),fontSize:B.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:G?"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:G?.6:1},onMouseEnter:Me=>{!G&&(It||Dn?.colorPrimary)&&(Me.currentTarget.style.backgroundColor=dd)},onMouseLeave:Me=>{(It||Dn?.colorPrimary)&&(Me.currentTarget.style.backgroundColor=uo)},onMouseDown:Me=>{Me.currentTarget.style.transform="scale(0.985)"},onMouseUp:Me=>{Me.currentTarget.style.transform="scale(1)"},children:(0,c.jsx)(xo,{content:lt})}),rt&&ht==="buttons"&&(0,c.jsx)(Uo,{margin:"0.25rem 0",styleOverride:B.errorBanner,children:rt})]}),ye&&I&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...pe?{animation:pe}:{},...ht==="collapsing"?{pointerEvents:"none"}:{}},children:dl}),j&&ml&&en&&qa&&jn&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...Ao?{animation:Ao}:{},...ht==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Li,borderRadius:Vi,...sa,padding:qi},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:L,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:B.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...B.backButton},"aria-label":"Back to payment methods",children:[(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",...B.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)(Fo,{content:Ee})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:B.titleFontSize??"1.05rem",color:zi,paddingRight:80,...B.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(en)}`})]}),(0,c.jsx)(Jt.Elements,{stripe:jn,options:qa,children:(0,c.jsx)(Ps,{method:en,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ae,billingApiUrl:He,onTokenizedBody:Bn,onErrorChange:De,onDecline:p,onCancel:L,runBeforeButtonClick:fr,onButtonClick:ce,isProcessing:G,submitButtonColor:uo,submitButtonBorderRadius:Yt,submitButtonStyle:B.submitButton,errorText:rt})},en)]})})]})]})}return ml&&en&&qa&&jn&&j?(0,c.jsxs)("form",{onSubmit:Di,className:R,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(fs,{}),U&&(0,c.jsx)(Ln,{status:U,errorMessage:rt,authorized:qn}),(0,c.jsx)("div",{style:{...Ao?{animation:Ao}:{},...ht==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Li,borderRadius:Vi,...sa,padding:qi},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:L,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:B.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...B.backButton},"aria-label":"Back to payment methods",children:[(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",...B.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)(Fo,{content:Ee})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:B.titleFontSize??"1.05rem",color:zi,paddingRight:80,...B.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(en)}`})]}),(0,c.jsx)(Jt.Elements,{stripe:jn,options:qa,children:(0,c.jsx)(Ps,{method:en,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ae,billingApiUrl:He,onTokenizedBody:Bn,onErrorChange:De,onDecline:p,onCancel:L,runBeforeButtonClick:fr,onButtonClick:ce,isProcessing:G,submitButtonColor:uo,submitButtonBorderRadius:Yt,submitButtonStyle:B.submitButton,errorText:rt})},en)]})})]}):(0,c.jsxs)("form",{onSubmit:Di,className:R,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(fs,{}),U&&(0,c.jsx)(Ln,{status:U,errorMessage:rt,authorized:qn}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ul("flopay-direct-paypal-gate-debug-default"),pl("flopay-stripe-gate-debug-default"),Qo&&Ae&&(0,c.jsxs)(c.Fragment,{children:[m&&(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)(ma.Provider,{value:h,children:(0,c.jsx)(fa,{sessionId:e,nonce:t,billingApiUrl:He,email:x.email,billingName:Xe||void 0,onBuyerIdentityReady:ae,clientId:Ae.clientId,environment:Ae.environment,currency:pt.toUpperCase(),isSubscription:gt,providerObjectType:Ve,approvalPresentation:Oa==="popup"?void 0:Oa,onTokenizedBody:Bn,onComplete:s,onErrorChange:De,onDecline:p,onTechnicalFailure:ko,onButtonClick:ce,runBeforeButtonClick:fr,isProcessing:G,onLoadStateChange:xi,onInitializationStateChange:Fi,session:Bt,existingOrderId:m?.orderId,debug:ee},m?.orderId??"fresh")})]}),ta&&(0,c.jsx)(Jt.Elements,{stripe:ea,options:Os,children:(0,c.jsx)(lc,{sessionId:e,nonce:t,email:x.email,billingName:Xe||void 0,onBuyerIdentityReady:ae,billingApiUrl:He,onTokenizedBody:Bn,onErrorChange:De,isProcessing:G,onButtonClick:ce,onDecline:p,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:js,placeholderBorderRadius:co,popupCapabilityOwner:h,externalTelemetryContext:Zs,presentationMode:Io})}),_o&&(0,c.jsx)(Jt.Elements,{stripe:jn,options:Ds,children:(0,c.jsx)(dc,{sessionId:e,nonce:t,email:x.email,billingName:Xe||void 0,onBuyerIdentityReady:ae,billingApiUrl:He,intentKind:Q>0?"payment":"setup",expressMethods:Ro,onTokenizedBody:Bn,onErrorChange:De,onButtonClick:ce,onDecline:p,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:Ws,placeholderBorderRadius:co,popupCapabilityOwner:h,externalTelemetryContext:ve})}),na&&(0,c.jsx)(uc,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:He,paymentElementMethods:Ba,stripeInstance:jn,paymentElementBaseOptions:Mi,onTokenizedBody:Bn,onErrorChange:De,onButtonClick:ce,onDecline:p,runBeforeButtonClick:fr,onLoadStateChange:Ks,isProcessing:G,submitButtonColor:uo,submitButtonBorderRadius:Yt,submitButtonStyle:B.submitButton,themeId:Oe,onExpandApm:En,expandedApmMethod:en,buttonAppearance:{backgroundColor:B.cardButton?.backgroundColor,borderColor:B.cardInputBorder,textColor:B.cardButton?.color,borderRadius:co}})]}),ye&&(rd||nd||od)&&(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"}})]}),ye&&dl]})}var N=require("react/jsx-runtime"),Yo=44,Ts="flopay_checkout_saved_payment_resume",bi=new Map,hi=new Map;function Cc(e,t){t.settled&&t.consumers===0&&bi.get(e)===t&&bi.delete(e)}function Vu(e,t,n){let r=hi.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};hi.set(e,a);let s=()=>{hi.get(e)===a&&hi.delete(e)};return o.then(s,s),o}function _a(e){return new Promise(t=>setTimeout(t,e))}function Pi(e,t,n){let r=Xa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:ot.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Ea(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ks(e,t,n,r,o,a){let s=Pi(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),Ea(s)}function Sc(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 wc(e,t,n,r,o){let a=(0,ot.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 ot.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof ot.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 _c(e,t){let n=e?.data.paypal?.publishableKey;if(n)return{clientId:n,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation,...t?{existingOrderId:t}:{}}}function Is(e){return!e||e.data.stripe?.publishableKey?!1:!!_c(e)?.clientId}var ju={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function $u(e){return new Yr.FloPay(ju,{publishableKey:"provider_unavailable",...e})}async function Rs(e,t){let{publishableKey:n,paypalPublishableKey:r}=ss(e);return{...await ls({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function As(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Wu(){if(!As())return null;try{let e=window.sessionStorage.getItem(Ts);return e?JSON.parse(e):null}catch{return null}}function kc(e){if(As())try{window.sessionStorage.setItem(Ts,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function _s(){if(As())try{window.sessionStorage.removeItem(Ts)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Hu(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Ic(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function Es(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Ku(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Rc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Gu(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 vi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:s,loading:d,error:p,onComplete:u,onError:f,onInstrument:P,onDecline:k,onCountryChange:R,onZipChange:S,showPayPal:T=!0,showStripe:E=!0,walletPresentation:b="auto",enabledPaymentMethods:C,showApplePay:j=!0,showGooglePay:_=!0,debug:re=!1,layout:q,theme:K,buttonsTheme:le,buttonsStyles:$,cardButtonContent:Oe,cardBackButtonContent:Ue,cardTitleContent:J,showSecurityFooter:xe,onButtonClick:lt,onBeforeButtonClick:Ee,enableAVS:Fe,cardFieldOrder:be,cardPreFormSlot:ce,avsLayout:me,submitLabel:Ge,className:ct,initialErrorMessage:A=null,initialPayPalOrderId:fe,children:de,checkoutMode:D,confirmLabel:Se,renderConfirmButton:ue,onSessionCompleted:Le}){let oe=(0,ot.resolveBillingApiUrl)(r),We=(0,w.useMemo)(()=>(0,ot.resolveTheme)(K),[K]),ut=a??We?.appearance,Be=n?"embedded_checkout":"standard_checkout",Je=Es(de,q),[Ze,Z]=(0,w.useState)(null),[Q,pt]=(0,w.useState)(null),ft=(0,w.useRef)(null),Ae=(0,w.useRef)(null),gt=(0,w.useRef)(0),[V,ke]=(0,w.useState)(null),tt=(0,w.useRef)(null),[ee,qe]=(0,w.useState)(null),vt=(0,w.useMemo)(()=>n?Vo(n):"",[n]),nt=n?`create:${vt}`:`session:${e??""}`,Et=Rc(ee),Y=(0,w.useRef)(new Set),h=(0,w.useRef)(nt),v=(0,w.useRef)(nt);go(()=>{v.current=nt,h.current!==nt&&(h.current=nt,Y.current.clear())},[nt]);let X=(0,w.useCallback)(L=>{if(v.current===nt){if(Ji.has(L.name)){if(Y.current.has(L.name))return;Y.current.add(L.name)}Ke(()=>P?.(L))}},[nt,P]),W=zo(X,nt),ve=(0,w.useRef)(!1),Bt=(0,w.useCallback)(L=>{if(ve.current)return;let U=L.gateway||!Et?L:{...L,gateway:Et};X(U)},[X,Et]);(0,w.useEffect)(()=>{W({class:"lifecycle",name:"checkout.mount"})},[W]);let[Ve,Ye]=(0,w.useState)(e??""),we=e??Ve,Ct=n?"":we,[Wt,He]=(0,w.useState)(!0),[Tn,Ie]=(0,w.useState)(null),[zn,Un]=(0,w.useState)(0),[Mt,kn]=(0,w.useState)("full"),[An,Kn]=(0,w.useState)(!1),[mn,Dt]=(0,w.useState)(A),[mt,Qe]=(0,w.useState)(null),[In,xt]=(0,w.useState)(null),[Rn,yn]=(0,w.useState)(!1),[Ht,sn]=(0,w.useState)(void 0),[Gn,Yn]=(0,w.useState)(""),[Tt,wt]=(0,w.useState)(!1),[vn,rn]=(0,w.useState)(!1),[Ot,ln]=(0,w.useState)(!1),Zt=(0,w.useRef)(null),Lt=(0,w.useRef)(0),se=(0,w.useRef)(void 0),[cn,qn]=(0,w.useState)("loading"),[Lr,sr]=(0,w.useState)(0),Ut=(0,w.useRef)(!1),lr=(0,w.useRef)(!1),Cn=(0,w.useRef)(!1),Re=(0,w.useRef)(null),ye=(0,w.useRef)(null),F=(0,w.useMemo)(()=>({checkoutMode:D??Mt,layout:Ku(de,q)}),[D,de,Mt,q]),at=(0,w.useRef)(u);at.current=u;let ie=(0,w.useRef)(f);ie.current=f;let Sn=(0,w.useRef)(k);Sn.current=k;let fn=(0,w.useCallback)(L=>ai(Re,async U=>{try{return await L(U)}catch(O){throw U.aborted?io(O):O}}),[]);(0,w.useEffect)(()=>()=>{Re.current?.abort(),Re.current=null},[]);let Kt=(0,w.useCallback)((L,U)=>{ft.current=L,pt(L),tt.current=U,ke(U)},[]),Xn=(0,w.useCallback)(()=>{let L=Ae.current;L&&(Ae.current=null,L.destroy())},[]);(0,w.useEffect)(()=>{pn(Q)?.setCheckoutContext(F),V&&V!==Q&&pn(V)?.setCheckoutContext(F)},[Q,V,F]);let yt=(0,w.useRef)(Le);yt.current=Le;let Xr=(0,w.useCallback)(L=>{qn(L),!(L!=="exhausted"||Cn.current)&&(Cn.current=!0,ie.current?.(new ot.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Gt=(0,w.useCallback)(()=>{qn("retrying"),sr(L=>L+1)},[]);(0,w.useEffect)(()=>{qn("loading"),sr(0),Cn.current=!1},[we]),(0,w.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:ot.SDK_VERSION,checkout_type:Be,checkout_layout:Je,billing_api_url:oe})},[Je,Be,oe]);let gn=(0,w.useMemo)(()=>n?Vo(n,!0):"",[n]),Nr=(0,w.useMemo)(()=>Gn===gn?Ht:void 0,[Ht,Gn,gn]),zr=(0,w.useMemo)(()=>n?Hi(n,Nr):void 0,[n,Nr]),Mn=D??zr?.checkoutMode??"full",Qt=(0,w.useMemo)(()=>zr?{...zr,checkoutMode:Mn}:void 0,[zr,Mn]);(0,w.useEffect)(()=>{sn(void 0),Yn(gn),se.current=void 0,Zt.current=null,ln(!1)},[gn]),(0,w.useEffect)(()=>{Dt(A)},[A]);let Sr=(0,w.useCallback)((L,U,O)=>{Ke(()=>{Sn.current?.(un(L,U,O))})},[]),xn=(0,w.useCallback)(async(L,U)=>{Dt(null),xt(null),yn(!1),Qe("processing");let O=U?.sessionId??L.id,he=L.clientSecret||t,je=Rc(L),Pt=ft.current??tt.current,Ce=pn(Pt),$e=Pt?null:Pi(oe,o,F),te={log:B=>{Ce?Ce.log(B):$e?.log(B)},error:B=>{Ce?Ce.error(B):$e?.error(B)},terminal:B=>{Ce?Ce.terminal(B):$e?.terminal(B)},performance:B=>{Ce?Ce.performance(B):$e?.performance(B)},now:()=>Ce?.now()??$e?.now()??0,elapsed:B=>Ce?.elapsed(B)??Math.max(0,($e?.now()??B)-B)},m=te.now(),g=!!(U?.initialAutoProcessingError||U?.initialAutoProcessingPending),z=!1,H,Pe=()=>{z||(z=!0,g=!0,H=te.now(),te.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ae=!1,rt=()=>{ae||(ae=!0,te.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),te.performance({stage:"processing",durationMs:te.elapsed(m),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),H!==void 0&&te.performance({stage:"recovery",durationMs:te.elapsed(H),durationMode:"machine",paymentMethodCategory:"saved"}))};te.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ve.current=!0;try{te.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ve.current=!1}W({class:"lifecycle",name:"payment.processing.started",provider:je}),g&&Pe();let It;try{let B=ql(U?.initialAutoProcessingError),Te=U?.initialAutoProcessingError?.type==="3ds_required"&&!U.initialAutoProcessingError.threeDSecureToken&&U.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:U.initialAutoProcessingError.nextActionRedirectUrl}:null,At,_e=G=>(Pe(),fn(ge=>$o(G,{billingApiUrl:oe,sessionId:O,nonce:he,session:L,signal:ge})));if(Te)At=await _e(Te);else if(B)Pe(),B.type==="paypal_redirect_required"&&ye.current?.publishableKey&&kc({sessionId:O,publishableKey:ye.current.publishableKey,paypalPublishableKey:ye.current.paypalPublishableKey}),At=await fn(G=>si(B,{flopay:ft.current,paypalFlopay:tt.current,attempt3DS:U?.attempt3DS,billingApiUrl:oe,sessionId:O,session:L,telemetry:!1,signal:G})),B.type==="paypal_redirect_required"&&_s();else if(U?.initialAutoProcessingPending){let G=U.initialAutoProcessingPending,ge=new Yr.PaymentAPI(oe,{telemetry:!1}),x=await fn(Ne=>ge.waitForCheckoutSessionCompletion(G.sessionId,{initialDelayMs:G.retryAfterMs,nonce:he,statusUrl:G.statusUrl,signal:Ne})),Xe=to(x,L),Rt=x.autoProcessingError?.type==="3ds_required"&&x.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:x.autoProcessingError.nextActionRedirectUrl}:null;if(Rt)At=await _e(Rt);else{if(!$r(Xe))throw Do(Xe);At=jr(Xe,O)}}else{if(U?.initialAutoProcessingError)throw xr(U.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:U.initialAutoProcessingError.checkoutMethod});if(U?.fromCreateSession)return U?.fallbackToFull&&(kn("full"),Ic("full")),!1;{let G=await Wo({billingApiUrl:oe,sessionId:O,session:L,nonce:he,telemetry:!1});G.type==="success"?At=G.result:G.type==="next_action_required"?At=await _e(G):(Pe(),G.type==="paypal_redirect_required"&&ye.current?.publishableKey&&kc({sessionId:O,publishableKey:ye.current.publishableKey,paypalPublishableKey:ye.current.paypalPublishableKey}),At=await fn(ge=>si(G,{flopay:ft.current,paypalFlopay:tt.current,attempt3DS:U?.attempt3DS,billingApiUrl:oe,sessionId:O,session:L,telemetry:!1,signal:ge})),G.type==="paypal_redirect_required"&&_s())}}O&&jo(O),rt(),g&&(te.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),te.terminal({outcome:At.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),yn(At.status==="authorized"),Qe("success"),await _a(600),It=()=>at.current?.(At)}catch(B){let Te=Qr(va(B),O);if(Te.code==="three_ds_aborted")return!1;let At=Te.checkoutMethod??ba;Dt(Te.message),xt(Te.message),yn(!1),U?.fallbackToFull&&(te.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),kn("full"),Ic("full")),rt();let _e=Te.statusCode===void 0?void 0:(0,ot.telemetryStatusClass)(Te.statusCode,"unknown"),G=_e==="4xx"?{requestCategory:"process_payment",statusClass:_e}:{},ge=_e===void 0||_e==="4xx";if(ge&&(Te.telemetryOutcome==="payment_declined"||!!(Te.declineCode||Te.code?.toLowerCase().includes("declin"))))te.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...G});else if(ge&&(Te.telemetryOutcome==="validation_rejected"||Te.type==="validation_error"))te.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...G});else{let Rt=(0,ot.classifyTelemetryFailure)(B,g?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Ne=Te.telemetryRequestCategory??"process_payment";ve.current=!0;try{te.error({...Rt,...Te.telemetryFailureCategory?{failureCategory:Te.telemetryFailureCategory}:{},stage:g?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Ne})}finally{ve.current=!1}W({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Ne,provider:je})}return Ke(()=>ie.current?.(Te)),Sr(At,Te,{code:Te.code,declineCode:Te.declineCode}),Qe("error"),await Promise.allSettled([_a(400),U?.ensureProvidersReady?U.ensureProvidersReady():Promise.resolve()]),g&&(te.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{rt(),$e&&Ea($e),Qe(null),xt(null)}return Ke(It),!0},[Sr,W,t,oe,fn,o,F]);(0,w.useEffect)(()=>{if(typeof window>"u"||lr.current)return;let L=new URLSearchParams(window.location.search),U=L.get("payment_intent_client_secret");if(!U)return;let O=Wu();O&&(lr.current=!0,(async()=>{let he,je=0;Dt(null),xt(null),Qe("processing"),Kn(!0);try{if(L.get("redirect_status")==="failed")throw Object.assign(new ot.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Pt,paypalFlopay:Ce}=await ls({publishableKey:O.publishableKey,paypalPublishableKey:O.paypalPublishableKey,billingApiUrl:oe,locale:s,telemetry:o});he=pn(Ce??Pt),he?.setCheckoutContext(F),je=he?.now()??0,he?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),he?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let $e=(Ce??Pt)?.getRawProvider();if(!$e)throw Object.assign(new ot.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:te,error:m}=await $e.retrievePaymentIntent(U);if(m)throw Object.assign(new ot.FloPayError(m.message??"Failed to retrieve PayPal payment status.","api_error",{code:m.code}),{checkoutMethod:"paypal"});let g=Sl(te?.status);if(!te||g==="failed")throw Object.assign(new ot.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let z=typeof te.payment_method=="string"?te.payment_method:te.payment_method?.id,H=g;if(O.sessionId){let rt=(await new Yr.PaymentAPI(oe,{telemetry:!1}).getUnifiedCheckoutSession(O.sessionId)).data.session;if(rt&&rt.status!=="complete"){let It=await Wo({billingApiUrl:oe,sessionId:O.sessionId,session:rt,telemetry:!1,tokenizedData:{id:z??te.id,type:"card",threeDSecureActionResultTokenId:te.id,isPaypal:!0}});if(It.type!=="success")throw Object.assign(new ot.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});H=It.result.status}}O.sessionId&&jo(O.sessionId),he?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),he?.performance({stage:"redirect_resume",durationMs:he.elapsed(je),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),he?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Qe("success"),await _a(600),Ke(()=>at.current?.({status:H,paymentIntentId:te.id,paymentMethodId:z,checkoutMethod:"paypal"}))}catch(Pt){let Ce=Qr(va(Pt),O.sessionId),$e=Ce.checkoutMethod??"paypal",te=!!(Ce.declineCode||Ce.code?.toLowerCase().includes("declin"));if(he)he.performance({stage:"redirect_resume",durationMs:he.elapsed(je),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),te?he.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):he.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(te){let m=Pi(oe,o,F);m.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ea(m)}else ks(oe,o,F,"REDIRECT_RESUME_FAILED","redirect_resume");Dt(Ce.message),xt(Ce.message),Ke(()=>ie.current?.(Ce)),Sr($e,Ce,{code:Ce.code,declineCode:Ce.declineCode}),Qe("error"),await _a(400)}finally{_s(),Hu(),Qe(null),xt(null),Kn(!1)}})())},[Sr,s,oe,o,F]);let Ur=(0,w.useRef)(null),Fn=(0,w.useMemo)(()=>Qt?Vo(Qt):"",[Qt]),wr=(0,w.useRef)(Qt);wr.current=Qt,(0,w.useEffect)(()=>{Ye(e??"")},[e]),(0,w.useEffect)(()=>{Ut.current=!1,Dt(A),xt(null),yn(!1),Qe(null)},[Fn,A,e]);async function kr(L,U,O){let he=Pi(oe,o,F),je=new Yr.PaymentAPI(oe,{telemetry:!1}),Pt=!1;try{let Ce=L.idempotencyKey===void 0?void 0:(0,ot.resolveIdempotencyKey)(L.idempotencyKey),$e=es(U,O),te=ts(U,O);$e?.canonicalIdentity===O&&te&&te.canonicalIdentity===void 0&&(ri(U,O,te.idempotencyKey),te={...te,canonicalIdentity:O});let m=Ce??(te?.canonicalIdentity===O?te.idempotencyKey:void 0),g,z=!1;he.log({name:$e?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let H=$e?.sid??null,Pe=null,ae,rt,It=!1;if(H)try{Pe=await je.getUnifiedCheckoutSession(H,$e?.nonce),$e&&$e.canonicalIdentity===void 0&&(Ll(Pe.data.session,L)?(ni(U,O,H,$e.nonce??Pe.data.session?.clientSecret),te&&te.canonicalIdentity===void 0&&(ri(U,O,te.idempotencyKey),m??(m=te.idempotencyKey))):(ti(U,O),te=null,m=Ce,H=null,Pe=null));let Te=Pe?.data.session?.status,At=Pe?.data.session,_e=At?.clientSecret||$e?.nonce;if(H&&At?.buyerIdentified===!1&&_e&&(rt=Bo(je,H,_e,L.account)),H&&Pe&&Te==="complete"){if(ns(H))return{sid:H,result:Pe};ti(U,O),H=null,Pe=null,z=!0}}catch{he.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),$e?.canonicalIdentity===void 0?(ti(U,O),m=Ce):ei(U,O),H=null}if(!H){!Ce&&(z||!m)&&(m=(0,ot.resolveIdempotencyKey)(),g=m),m&&ri(U,O,m);let Te=he.now(),At=0;he.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let _e={...L,idempotencyKey:m,avsCheck:!!Fe,avsConfig:typeof Fe=="object"?Fe:void 0,checkoutType:"embedded_checkout",checkoutLayout:Es(de,q)};Object.defineProperty(_e,Yr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:x=>{At=Math.max(At,x)}}});let G=()=>{Sc(he,"session_create",Te,At)},ge=x=>{wc(he,x,"session_create",Te,At)&&W({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,ot.isDetachedSessionEligible)(_e)){let x=await je.createDetachedSession(_e);x.claimed.catch(()=>{}),Pe=x.shell,H=x.sessionId,rt=x.claim;let Xe=he.now();he.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ae=x.claimed.then(Rt=>{let Ne=Rt.data.session?.id??x.sessionId;return Ne&&ni(U,O,Ne,Rt.data.session?.clientSecret??x.nonce),Sc(he,"session_claim",Xe),G(),Rt},Rt=>{throw ei(U,O),wc(he,Rt,"session_claim",Xe,0)&&W({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Rt}).finally(()=>Ea(he)),ae.catch(()=>{}),Pt=!0,he.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),he.performance({stage:"session_shell",durationMs:he.now()-Te,durationMode:"machine",requestCategory:"session_create",attempt:At,statusClass:"2xx",paymentMethodCategory:"card"})}else Pe=await je.createAndFetchSession(_e),G()}catch(x){throw ge(x),x}H=Pe.data.session?.id??H??"",H&&!ae&&ni(U,O,H,Pe.data.session?.clientSecret)}let B=Pe?.data.session;return!rt&&H&&B?.buyerIdentified===!1&&B.clientSecret&&(rt=Bo(je,H,B.clientSecret,L.account)),{sid:H??"",result:Pe,sdkGeneratedIdempotencyKey:g,...ae?{claimed:ae}:{},...rt?{claim:rt}:{},...It?{claimRequiresIdentity:!0}:{}}}finally{Pt||Ea(he)}}let cr=(0,w.useRef)(kr);go(()=>{cr.current=kr},[kr]);let Jn=(0,w.useCallback)(async(L,U)=>{let O=wr.current;if(!O)throw new ot.FloPayError("createSession is required to bootstrap checkout.","validation_error");let he=Hi(O,L),je=Vo(he),Pt=Ol(he),Ce=bi.get(je);if(!Ce){let m={canonicalIdentity:je,promise:cr.current(he,Pt,je),consumers:0,settled:!1};Ce=m,bi.set(je,m);let g=()=>{m.settled=!0,Cc(je,m)};m.promise.then(g,g)}Ce.consumers+=1;let $e=!1,te=()=>{$e||($e=!0,Ce.consumers-=1,Cc(je,Ce))};U?.(te);try{let m=await Ce.promise;Ur.current=je,L&&(Yn(gn),sn(B=>bl(B,L)));let{sid:g,result:z,claimed:H,claim:Pe,claimRequiresIdentity:ae}=m;if(se.current=Pe,ln(ae===!0),Z(z),z.data.session&&qe(z.data.session),g&&Ye(g),H){Lt.current+=1;let B=Lt.current;Zt.current=H,rn(!0),H.then(Te=>{Lt.current===B&&(Zt.current===H&&(Zt.current=null),Z(Te),Te.data.session&&qe(Te.data.session),rn(!1),ln(!1))},Te=>{Lt.current===B&&(Zt.current===H&&(Zt.current=null),rn(!1),ln(!1),Ie(Te instanceof ot.FloPayError?Te:new ot.FloPayError(Te instanceof Error?Te.message:"Failed to create session","api_error")))})}else Lt.current+=1,Zt.current=null,rn(!1),ln(!1);let{flopay:rt,paypalFlopay:It}=await Rs(z,{billingApiUrl:oe,locale:s,telemetry:o});return Kt(rt,It),He(!1),m}catch(m){throw Ur.current===je&&(Ur.current=null),m}finally{U||te()}},[gn,Kt,s,oe,o]),Zn=(0,w.useRef)(xn);Zn.current=xn;let Ft=(0,w.useRef)(Jn);Ft.current=Jn;let dr=(0,w.useCallback)(async L=>{if(!Gu(L)||Tt)return{sessionId:Ve,session:ee};wt(!0);try{let U=await Jn(L);return{sessionId:U.sid,session:U.result.data.session??null}}finally{wt(!1)}},[Jn,Tt,Ve,ee]),_n=(0,w.useCallback)(async L=>{let U=se.current;if(!U)return;let O=Lt.current,he=await U(L);Lt.current===O&&(Z(he),he.data.session&&qe(he.data.session))},[]),Qn=(0,w.useCallback)(async()=>{await Zt.current},[]),Ir=(0,w.useCallback)(async()=>(await Qn(),{proceed:!0}),[Qn]);(0,w.useEffect)(()=>{let L=!1,U,O=++gt.current;Xn(),Ie(null),Un(0);let he=()=>{L=!0,gt.current===O&&(gt.current+=1,Xn())},je=wr.current;if(Fn&&je)return kn(Mn),He(!1),Ur.current===Fn?he:(qe(vl(je,D)),(async()=>{let $e=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),te=Mn==="auto"&&!Ut.current&&!$e;te&&(Dt(null),xt(null),Qe("processing"));try{let m=await Ft.current(void 0,Pe=>{U=Pe}),g=m.result.data.session??null;ye.current=ss(m.result);let z=Is(m.result),H=ns(m.sid||g?.id);if(!L&&te&&g&&!z&&!H){Ut.current=!0,await Vu(Fn,m.sdkGeneratedIdempotencyKey,()=>Zn.current(g,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:m.result.autoProcessingError,initialAutoProcessingPending:m.result.autoProcessingPending,autoProcessingAttempted:m.result.autoProcessingAttempted,sessionId:m.sid||g.id}));return}!L&&te&&((z||H)&&(Ut.current=!0),Qe(null),xt(null))}catch(m){if(L)return;let g=$a(m);if(te&&g==="session_auto_completed"){Ut.current=!0,Qe("success"),await _a(600),L||(Ke(()=>{at.current?.({status:"succeeded"})}),Qe(null),xt(null));return}te&&(Qe(null),xt(null));let z=m instanceof ot.FloPayError?m:new ot.FloPayError(m instanceof Error?m.message:"Failed to create session","api_error");Ie(z)}finally{U?.(),U=void 0}})(),()=>{he(),U?.()});He(!0);async function Pt(){let $e=!1,te=null;try{let m=new Yr.PaymentAPI(oe,{telemetry:!1}),g=await m.getUnifiedCheckoutSession(we,t);if(te=g,L)return;Z(g);let z=g.data.session??null;if(qe(z),!z)throw new ot.FloPayError("No session data returned","api_error");let H=z.checkoutMode;if(H==="setup")throw new ot.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(z.status==="authorized"){He(!1),Ke(()=>{at.current?.(jr(z,we)),yt.current?.(z.successUrl??"")});return}if(z.status==="complete"){He(!1),Ke(()=>{yt.current?.(z.successUrl??"")});return}if(z.status==="expired")throw ja(z);$e=!0;let Pe=D??H??"full";kn(Pe),Lt.current+=1;let ae=z.clientSecret||t;se.current=z.buyerIdentified===!1&&ae?Bo(m,we,ae,{...z.customer?.id?{userId:z.customer.id}:{}}):void 0,rn(!1),ln(!1);let rt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),It=Is(g);if(Pe==="auto"&&!Ut.current&&!rt&&!It){Ut.current=!0;let B=Ce(g);try{if(await Zn.current(z,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>B,sessionId:we||z.id}),L)return;await B,L||He(!1);return}catch{if(L)return;await B,L||He(!1);return}}await Ce(g),L||He(!1)}catch(m){if(L)return;let g=Pl(m,$e);if($e&&W({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),g){let{errorCode:H,stage:Pe,...ae}=g;ks(oe,o,F,H,Pe,ae)}if(g?.stage==="provider_load"&&(D??te?.data.session?.checkoutMode??"full")==="full"&&hl(te,T,E)){let H=$u({billingApiUrl:oe,locale:s,telemetry:o});Ae.current=H,Kt(H,null),Un(1),He(!1);return}let z=m instanceof ot.FloPayError&&g?.stage!=="provider_load"?m:gl();z!==m&&Ke(()=>ie.current?.(z)),Ie(z),He(!1)}}async function Ce($e){let{flopay:te,paypalFlopay:m,...g}=await Rs($e,{billingApiUrl:oe,locale:s,telemetry:o});ye.current={publishableKey:g.publishableKey,paypalPublishableKey:g.paypalPublishableKey},Kt(te,m),Un(0)}return Pt(),he},[D,Fn,Mn,Ct,t,T,E]);let ht=(0,w.useCallback)(async()=>{if(!Ze||zn!==1)return;let L=gt.current;Un(2);try{let{flopay:U,paypalFlopay:O}=await Rs(Ze,{billingApiUrl:oe,locale:s,telemetry:o});if(gt.current!==L)return;Xn(),Kt(U,O),Un(0)}catch(U){if(gt.current!==L)return;let{errorCode:O,stage:he,...je}=$i(U);ks(oe,o,F,O,he,je)}},[Xn,Kt,s,zn,oe,o,F,Ze]),on=!!(we&&(ee?.clientSecret||t)),en=An||!on,qr=(0,w.useCallback)(async()=>{if(!(An||!on||!ee)){Kn(!0),Dt(null);try{await xn(ee,{attempt3DS:!0,fallbackToFull:!0,sessionId:we||ee.id})}finally{Kn(!1)}}},[we,An,on,xn,ee]),Vn=_c(Ze,fe),Jr=Is(Ze),ur=(0,w.useMemo)(()=>{if(!(!Ze||!ee||!Ze.data.stripe?.publishableKey))return{billingApiUrl:oe}},[Ze,ee,oe]),pr=!!(n&&!de&&q==="buttons"&&Ee&&Mn==="full"),hn=!!(we&&(ee?.vault?.html||Zr(ee))),mr=(0,w.useMemo)(()=>({session:ee,loading:Wt,error:Tn,checkoutMode:Mt,inlineSessionDraft:Qt,applyInlineSessionPatch:pr?dr:void 0,inlineSessionPatchProcessing:Tt,claimPending:vn,claimRequiresIdentity:Ot,claimBuyerIdentity:_n,waitForDataAttachment:Qn}),[ee,Wt,Tn,Mt,Qt,pr,dr,Tt,vn,Ot,_n,Qn]),Vr=!!n&&q==="buttons"&&!Jr&&!hn&&(!Q||!ur),En=mt?(0,N.jsx)(Ln,{status:mt,errorMessage:In,authorized:Rn}):null;if(Wt&&!hn){if(d)return(0,N.jsxs)(N.Fragment,{children:[d,En]});if(q==="buttons"){let L=We?.buttonsLayout?.cardButton?.borderRadius??We?.appearance.variables?.borderRadius??8,U=O=>(0,N.jsx)("div",{style:{height:O,borderRadius:L,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[T&&U(Yo),E&&(j||_)&&U(Yo),E&&U(Yo),(0,N.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),En]})}return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,N.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,N.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),En]})}return Tn?p?(0,N.jsx)(Pr.Provider,{value:mr,children:p(Tn)}):(0,N.jsx)(Pr.Provider,{value:mr,children:(0,N.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Tn.message})}):Vr?(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(Pr.Provider,{value:mr,children:(0,N.jsx)(Xu,{onButtonClick:lt,showPayPal:T,showStripe:E,showApplePay:j,showGooglePay:_,theme:K,buttonsTheme:le,buttonsStyles:$,cardButtonContent:Oe,cardBackButtonContent:Ue,cardTitleContent:J})}),En]}):Jr&&ee&&Vn?(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(Pr.Provider,{value:mr,children:(0,N.jsxs)("div",{className:ct,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[mn&&(0,N.jsx)(Uo,{icon:!1,children:mn}),cn==="retrying"&&(0,N.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),cn==="exhausted"&&(0,N.jsxs)("div",{role:"alert",children:[(0,N.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,N.jsx)("button",{type:"button",onClick:Gt,children:"Retry PayPal"})]}),cn!=="exhausted"&&(0,N.jsx)("div",{"aria-hidden":cn==="retrying"?!0:void 0,style:cn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,N.jsx)(Dl,{sessionId:we,nonce:ee.clientSecret||void 0,billingApiUrl:oe,email:ee.customer?.email||Qt?.account?.email,billingName:[ee.customer?.firstName,ee.customer?.lastName].filter(Boolean).join(" ")||[Qt?.account?.firstName,Qt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:_n,clientId:Vn.clientId,environment:Vn.environment,currency:(ee.currency??"usd").toUpperCase(),isSubscription:ee.mode==="subscription",providerObjectType:Vn.providerObjectType,approvalPresentation:Vn.approvalPresentation,existingOrderId:Vn.existingOrderId,onComplete:u,onErrorChange:Dt,onDecline:k,onButtonClick:lt,runBeforeButtonClick:Ir,onInitializationStateChange:Xr,allowAutomaticRetry:Lr===0,session:ee,telemetry:o,telemetryContext:F,onInstrument:Bt,debug:re},`${nt}:paypal-init-${Lr}`)})]})}),En]}):Mt==="confirm"?(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(Pr.Provider,{value:mr,children:(0,N.jsx)(ha,{flopay:Q,paypalFlopay:V,options:ur??{billingApiUrl:oe},onInstrument:Bt,children:(0,N.jsxs)("div",{className:ct,children:[mn&&(0,N.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:mn}),ue?ue({onConfirm:qr,isProcessing:en}):(0,N.jsx)("button",{type:"button",onClick:qr,disabled:en,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:en?"not-allowed":"pointer",opacity:en?.6:1},children:An?"Processing...":Se??"Confirm Purchase"})]})},nt)}),En]}):(!Q||!ur)&&!(hn&&Mt==="full")?(0,N.jsx)(N.Fragment,{children:En}):(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(Pr.Provider,{value:mr,children:(0,N.jsxs)(ha,{flopay:Q,paypalFlopay:V,options:ur??{billingApiUrl:oe},onInstrument:Bt,children:[zn===1&&(0,N.jsx)("button",{type:"button",onClick:ht,children:"Retry payment methods"}),de?(0,N.jsxs)(N.Fragment,{children:[mn&&(0,N.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:mn}),(0,N.jsx)(Yu,{sessionId:we,nonce:ee?.clientSecret||void 0,billingApiUrl:oe,session:ee,submitLabel:Ge,walletPresentation:b,children:de})]}):(0,N.jsx)(gi,{sessionId:we,nonce:ee?.clientSecret||void 0,telemetry:o,email:ee?.customer?.email||Qt?.account?.email,userId:ee?.customer?.id||Qt?.account?.userId,firstName:ee?.customer?.firstName||Qt?.account?.firstName,lastName:ee?.customer?.lastName||Qt?.account?.lastName,totalAmount:ee?Math.round((0,ot.buildCheckoutDisplayData)(ee).total*100):0,currency:ee?.currency?.toLowerCase()??"usd",onComplete:u,onError:f,onDecline:k,error:mn,onErrorChange:Dt,showPayPal:T,showStripe:E,walletPresentation:b,enabledPaymentMethods:zn?[]:C??Ze?.data.stripe?.enabledPaymentMethods??ee?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ze?.data.stripe?.enabledPaymentMethodCountries,showApplePay:j,showGooglePay:_,layout:q,theme:K,buttonsTheme:le,buttonsStyles:$,appearance:ut,cardButtonContent:Oe,cardBackButtonContent:Ue,cardTitleContent:J,onButtonClick:lt,onBeforeButtonClick:Ee,onBuyerIdentityReady:_n,enableAVS:Fe,...be?{cardFieldOrder:be}:{},...ce?{cardPreFormSlot:ce}:{},avsLayout:me,country:ee?.customer?.country,city:ee?.customer?.city,state:ee?.customer?.state,onCountryChange:R,onZipChange:S,avsCheck:!!Fe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Es(de,q),className:ct,submitLabel:Ge,directPaypal:Vn,isSubscription:ee?.mode==="subscription",session:ee,dataAttachmentPending:vn,dataAttachmentRequiresIdentity:Ot,debug:re})]},nt)}),En]})}function Yu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:a,children:s}){return(0,N.jsx)(N.Fragment,{children:w.default.Children.map(s,d=>{if(!w.default.isValidElement(d))return d;let p=d.props,u={};return p.sessionId||(u.sessionId=e),!p.nonce&&t&&(u.nonce=t),p.billingApiUrl||(u.billingApiUrl=n),p.submitLabel===void 0&&o!==void 0&&(u.submitLabel=o),p.walletPresentation===void 0&&(u.walletPresentation=a),r?.customer&&(p.email||(u.email=r.customer.email),p.userId||(u.userId=r.customer.id),p.firstName||(u.firstName=r.customer.firstName),p.lastName||(u.lastName=r.customer.lastName)),Object.keys(u).length===0?d:w.default.cloneElement(d,u)})})}function Xu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:s,buttonsStyles:d,cardButtonContent:p,cardBackButtonContent:u,cardTitleContent:f}){let[P,k]=(0,w.useState)(!1),R=(0,w.useMemo)(()=>(0,ot.resolveTheme)(a),[a]),S=(0,w.useMemo)(()=>{let C=R?.buttonsLayout??(0,ot.resolveButtonsLayoutTheme)(s);return d?{...C,...d,cardButton:{...C.cardButton,...d.cardButton},cardFormContainer:{...C.cardFormContainer,...d.cardFormContainer},backButton:{...C.backButton,...d.backButton},backButtonIcon:{...C.backButtonIcon,...d.backButtonIcon},submitButton:{...C.submitButton,...d.submitButton},title:{...C.title,...d.title}}:C},[R,s,d]),T=R?.buttonsLayout?.cardButton?.borderRadius??R?.appearance.variables?.borderRadius??8,E=C=>(0,N.jsx)("div",{style:{height:C,borderRadius:T,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),b=p===void 0?{boxSizing:"border-box",height:Yo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(P){let C=S.cardInputBorder??"#e5e7eb",j=S.cardInputBackground??"white",_=Mo(u),re=Mo(f);return(0,N.jsxs)("div",{style:{backgroundColor:S.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...S.cardFormContainer},children:[(0,N.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,N.jsxs)("button",{type:"button",onClick:()=>k(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:_?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...S.backButton},children:[(0,N.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...S.backButtonIcon},children:(0,N.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,N.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,N.jsx)(Fo,{content:u})]}),re?(0,N.jsx)("div",{style:{flex:1}}):(0,N.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...S.title},children:(0,N.jsx)(ca,{content:f})})]}),(0,N.jsx)("div",{style:{backgroundColor:j,border:`1px solid ${C}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,N.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,N.jsxs)("div",{style:{display:"flex"},children:[(0,N.jsx)("div",{style:{flex:1,backgroundColor:j,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,N.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,N.jsx)("div",{style:{flex:1,backgroundColor:j,borderTop:"none",borderRight:`1px solid ${C}`,borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,N.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,N.jsx)("div",{style:{backgroundColor:j,border:`1px solid ${C}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,N.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,N.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...S.submitButton,opacity:.5}}),(0,N.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,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&S(Yo),n&&(r||o)&&S(Yo),n&&(0,O.jsx)("button",{type:"button",onClick:()=>{e?.("card"),I(!0)},style:{width:"100%",...G,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:C.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...C.cardButton},onMouseDown:_=>{_.currentTarget.style.transform="scale(0.985)"},onMouseUp:_=>{_.currentTarget.style.transform="scale(1)"},children:(0,O.jsx)(Mo,{content:u})}),(0,O.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var ir=require("react/jsx-runtime"),Xu=44;function _c(e){return new Promise(t=>setTimeout(t,e))}function Ju(e,t){return e instanceof sr.FloPayError?e:new sr.FloPayError(e instanceof Error?e.message:t,"api_error")}function Zu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Qu(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 Ec({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:s,items:c,subscriptions:u,account:p,successUrl:h,cancelUrl:b,couponCodes:I,tagsData:k,utmMetadata:C,billingApiUrl:f,locale:S,theme:G,appearance:_,buttonsTheme:q,buttonsStyles:E,onSuccess:ne,onError:$,onDecline:W,children:ie,disabled:V=!1,type:Be="button",style:Ue,...X}){let Ae=(0,ot.useMemo)(()=>(0,sr.resolveBillingApiUrl)(f),[f]),it=(0,ot.useMemo)(()=>Qu({createSession:n,clientId:a,products:s,items:c,subscriptions:u,account:p,successUrl:h,cancelUrl:b,couponCodes:I,tagsData:k,utmMetadata:C}),[p,b,a,I,n,s,c,u,h,k,C]),[Re,xe]=(0,ot.useState)(!1),[ve,se]=(0,ot.useState)(null),[me,He]=(0,ot.useState)(null),[st,T]=(0,ot.useState)(!1),[ye,le]=(0,ot.useState)(null),[F,Se]=(0,ot.useState)(null),ce=(0,ot.useRef)(!0),De=(0,ot.useRef)(null),re=(0,ot.useRef)(F),$e=(0,ot.useRef)(ne),dt=(0,ot.useRef)($),Me=(0,ot.useRef)(W),Oe=(0,ot.useCallback)(g=>ai(De,async v=>{try{return await g(v)}catch(ee){throw v.aborted?io(ee):ee}}),[]);(0,ot.useEffect)(()=>{re.current=F},[F]),(0,ot.useEffect)(()=>{$e.current=ne},[ne]),(0,ot.useEffect)(()=>{dt.current=$},[$]),(0,ot.useEffect)(()=>{Me.current=W},[W]),(0,ot.useEffect)(()=>(ce.current=!0,()=>{ce.current=!1,De.current?.abort()}),[]),(0,ot.useEffect)(()=>{if(typeof window>"u")return;let g=v=>{v.key==="Escape"&&Se(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let ut=(0,ot.useCallback)((g,v=ba)=>{Me.current?.(un(v,g,{code:g.code,declineCode:g.declineCode}))},[]),Y=(0,ot.useCallback)(async g=>{ce.current&&(He(null),T(g.result.status==="authorized"),se("success"),await _c(600),ce.current&&We(()=>$e.current?.(g)))},[]),J=(0,ot.useCallback)(async(g,v)=>{ce.current&&(dt.current?.(g),v?.emitDecline&&ut(g,v.method),He(g.message),T(!1),se("error"),await _c(400))},[ut]),mt=(0,ot.useCallback)(async(g,v,ee)=>{let de=g.data.session??null;if(!de)throw Qr(new sr.FloPayError("No session data returned","api_error"),v);let Xe=de.clientSecret||t;if($r(de)){await Y({result:jr(de,v),session:de,sessionId:de.id||v,autoCompleted:!1});return}if(de.status==="expired")throw Qr(ja(de),de.id||v);try{if(g.autoProcessingPending){let Qe=g.autoProcessingPending,ae=new Ci.PaymentAPI(Ae),yt=await Oe(Ke=>ae.waitForCheckoutSessionCompletion(Qe.sessionId,{initialDelayMs:Qe.retryAfterMs,nonce:Xe,statusUrl:Qe.statusUrl,signal:Ke})),It=to(yt,de),qt=yt.autoProcessingError?.type==="3ds_required"&&yt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:yt.autoProcessingError.nextActionRedirectUrl}:null;if(qt&&v&&Xe){let Ke=await Oe(Lt=>$o(qt,{billingApiUrl:Ae,sessionId:v,nonce:Xe,session:de,signal:Lt,telemetry:!0}));await Y({result:Ke,session:de,sessionId:de.id||v,autoCompleted:!1});return}if(yt.autoProcessingError)throw Fr(yt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:yt.autoProcessingError.checkoutMethod});if(!$r(It))throw Do(It);await Y({result:jr(It,v),session:It,sessionId:It.id||v,autoCompleted:!1});return}if(g.autoProcessingError){let Qe=g.autoProcessingError.nextActionRedirectUrl;if(g.autoProcessingError.type==="3ds_required"&&Qe&&v&&Xe){let ae=await Oe(Ke=>is({billingApiUrl:Ae,sessionId:v,nonce:Xe,nextActionRedirectUrl:Qe,signal:Ke}));if(ae.status==="declined")throw Fr({type:ae.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:ae.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let It=await new Ci.PaymentAPI(Ae).waitForCheckoutSessionCompletion(v,{initialDelayMs:0,nonce:Xe}),qt=to(It,de);if(!$r(qt))throw Fr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await Y({result:jr(qt,v),session:qt,sessionId:qt.id||v,autoCompleted:!1});return}throw Fr(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(ee?.fromCreateSession&&g.autoProcessingAttempted===!0)throw Fr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let kt=await Wo({billingApiUrl:Ae,sessionId:v??de.id,session:de,nonce:Xe});if(kt.type==="next_action_required"&&Xe){let Qe=v??de.id,ae=await Oe(yt=>$o(kt,{billingApiUrl:Ae,sessionId:Qe,nonce:Xe,session:de,signal:yt,telemetry:!0}));await Y({result:ae,session:de,sessionId:de.id||Qe,autoCompleted:!1});return}if(kt.type!=="success")throw Fr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Y({result:kt.result,session:de,sessionId:de.id||v,autoCompleted:!1})}catch(kt){let Qe=de.id||v,ae=Qr(va(kt),Qe);if(ae.code==="three_ds_aborted")return;if(ae.code==="checkout_processing_timeout"){if(!ce.current)return;le(ae.message),We(()=>dt.current?.(ae));return}await J(ae,{emitDecline:!0,method:ae.checkoutMethod??ba}),Zu(ae,Qe)&&Qe&&ce.current&&Se({sessionId:Qe,errorMessage:ae.message,nonce:Xe||void 0,payPalOrderId:ae.orderId})}},[t,Ae,Oe,J,Y]),gt=(0,ot.useCallback)(async g=>{if(X.onClick?.(g),!(g.defaultPrevented||V||Re)){if(Se(null),le(null),e&&it){let v=new sr.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await J(v),ce.current&&(se(null),He(null));return}if(!e&&!it){let v=new sr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await J(v),ce.current&&(se(null),He(null));return}xe(!0),He(null),T(!1),se("processing");try{let v=new Ci.PaymentAPI(Ae);if(e){let ee=await v.getUnifiedCheckoutSession(e,t);await mt(ee,e);return}try{let ee=await v.createAndFetchSession({...it});await mt(ee,ee.data.session?.id??null,{fromCreateSession:!0})}catch(ee){if($a(ee)==="session_auto_completed"){await Y({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw ee}}catch(v){await J(Qr(Ju(v,"Automatic payment failed. Please try again."),e))}finally{ce.current&&(se(null),He(null),xe(!1))}}},[X.onClick,it,V,Re,t,mt,Ae,e,J,Y]),Ie=(0,ot.useCallback)(g=>{let v=re.current;Se(null),$e.current?.({result:g,session:null,sessionId:v?.sessionId??null,autoCompleted:!1})},[]),ft=(0,ot.useCallback)(g=>{dt.current?.(g)},[]),U=(0,ot.useCallback)(g=>{Me.current?.(g)},[]),we=(0,ot.useMemo)(()=>(0,sr.resolveTheme)(G),[G]),lt=(0,ot.useMemo)(()=>{let g=we?.buttonsLayout??(0,sr.resolveButtonsLayoutTheme)(q);return E?{...g,...E,cardButton:{...g.cardButton,...E.cardButton}}:g},[we,q,E]),Z=(0,ot.useMemo)(()=>{let g=we?.appearance;return _?g?{...g,..._,variables:{...g.variables,..._.variables}}:_:g},[_,we]),qe=Z?.variables,St=qe?.colorPrimary??"#4A49FF",Ze=qe?.colorPrimaryHover??Ko(St,.12),H=qe?.borderRadius??"8px";return(0,ir.jsxs)(ir.Fragment,{children:[(0,ir.jsx)("button",{...X,type:Be,onClick:gt,disabled:V||Re,"aria-busy":Re,style:{width:"100%",...ie===void 0?{boxSizing:"border-box",height:Xu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...lt.cardButton,...ws({themeBundle:we,resolvedPrimaryColor:St,resolvedBorderRadius:H,submitButtonStyle:lt.submitButton,explicitPrimaryColor:qe?.colorPrimary}),fontSize:lt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:V||Re?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:V||Re?.6:1,...Ue},onMouseEnter:g=>{X.onMouseEnter?.(g),!g.defaultPrevented&&!V&&!Re&&(we||qe?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Ze)},onMouseLeave:g=>{X.onMouseLeave?.(g),!g.defaultPrevented&&(we||qe?.colorPrimary)&&(g.currentTarget.style.backgroundColor=St)},onMouseDown:g=>{X.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{X.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:(0,ir.jsx)(Mo,{content:ie})}),ye&&(0,ir.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ye}),ve&&(0,ir.jsx)(Ln,{status:ve,errorMessage:me,authorized:st}),F&&(0,ir.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&Se(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)(vi,{sessionId:F.sessionId,nonce:F.nonce,checkoutMode:"full",billingApiUrl:Ae,locale:S,theme:G,...Z?{appearance:Z}:{},buttonsTheme:q,buttonsStyles:E,initialErrorMessage:F.errorMessage,initialPayPalOrderId:F.payPalOrderId,cardTitleContent:null,onComplete:Ie,onError:ft,onDecline:U})})})]})}var wi=require("@flopay/js/card-setup"),Gn=require("@flopay/shared"),xt=require("react");var Tc={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function Si(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?Tc.dark:Tc.light,a=t.colorText??(r?"#F1F5F9":"#262833"),s=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:s?.color??a}}var Dr=require("react/jsx-runtime"),Ta=class extends Gn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function bo(e,t={}){let n=e instanceof Gn.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 Ta(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 Ac({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:s=null,onReady:c,onComplete:u,onDecline:p,onCancel:h,onValidation:b,onError:I}){let[k,C]=(0,xt.useState)(null),[f,S]=(0,xt.useState)(null),[G,_]=(0,xt.useState)(null),[q,E]=(0,xt.useState)(null),[ne,$]=(0,xt.useState)(null),W=(0,xt.useRef)(!1),ie=(0,xt.useRef)(!1),V=(0,xt.useMemo)(()=>typeof o=="object"?void 0:(0,Gn.resolveTheme)(o),[o]),Be=(0,xt.useMemo)(()=>typeof o=="object"?o:V?Go({appearance:V.appearance,buttonsStyles:V.buttonsLayout,layout:"default"}):null,[V,o]),Ue=(0,xt.useMemo)(()=>ci(V?.buttonsLayout.cardFormContainer,a),[V,a]),X=(0,xt.useMemo)(()=>V?Si(V):void 0,[V]),Ae=(0,xt.useRef)(c),it=(0,xt.useRef)(I),Re=(0,xt.useRef)(u),xe=(0,xt.useRef)(p),ve=(0,xt.useRef)(h),se=(0,xt.useRef)(b),me=(0,xt.useRef)(!1),He=(0,xt.useRef)(!1),st=(0,xt.useRef)(0);return Ae.current=c,it.current=I,Re.current=u,xe.current=p,ve.current=h,se.current=b,(0,xt.useEffect)(()=>{let T=st.current+1;return st.current=T,()=>{queueMicrotask(()=>{st.current===T&&(me.current||He.current||(He.current=!0,We(()=>{ve.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,xt.useEffect)(()=>{let T=!0,ye=new wi.PaymentAPI((0,Gn.resolveBillingApiUrl)(n),{telemetry:r});return C(null),S(null),_(null),me.current=!1,He.current=!1,(async()=>{try{if(!e.trim())throw new Gn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Gn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let le=await ye.getUnifiedCheckoutSession(e,t);if(!T)return;let F=le.data.session;if(!F||!(0,Gn.isCardSetupCheckoutSession)(F))throw new Gn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Se=F.vault;if(Se?.html?.trim()||(Se=await ye.getVaultCapture(e,t)),!Se.html?.trim())throw new Gn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!T)return;S(Se),C(new wi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(le){if(!T)return;let F=bo(le);me.current=!0,_(F),We(()=>it.current?.(F))}})(),()=>{T=!1,ye.destroy()}},[n,t,e,r]),(0,xt.useEffect)(()=>{if(!k)return;let T=!1;ie.current=!1,W.current=!1;let ye=k.on("submitting",()=>{W.current=!0,$(null),E("processing")}),le=k.on("complete",ce=>{me.current=!0,W.current=!1,E("success"),(async()=>(await new Promise(De=>setTimeout(De,600)),!ie.current&&(ie.current=!0,We(()=>{Re.current?.({status:"succeeded",sessionId:e,...ce.paymentMethod?{paymentMethod:ce.paymentMethod}:{}})}),T||E(null))))()}),F=k.on("decline",ce=>{me.current=!0,W.current=!1,$(ce.message??null),E("error"),We(()=>{xe.current?.({status:"declined",sessionId:e,...ce.declineReason?{reason:ce.declineReason}:{},...ce.message?{message:ce.message}:{}})}),(async()=>(await new Promise(De=>setTimeout(De,400)),T||E(null)))()}),Se=k.on("challenge_dismissed",()=>{E(null)});return()=>{T=!0,ye(),le(),F(),Se()}},[k,e]),G?(0,Dr.jsx)("div",{role:"alert",children:G.message}):!k||!f?.html?(0,Dr.jsx)(Dr.Fragment,{children:s}):(0,Dr.jsxs)(Dr.Fragment,{children:[q&&(0,Dr.jsx)(Ln,{status:q,errorMessage:ne,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...X?{theme:X}:{}}),(0,Dr.jsx)(so,{capture:k,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,theme:Be,containerStyle:Ue,onReady:()=>{We(()=>Ae.current?.())},onValidation:T=>{We(()=>se.current?.(T))},onError:T=>{if(!T)return;W.current&&(W.current=!1,$(T),E("error"),setTimeout(()=>E(null),400));let ye=bo(new Error(T),{code:"card_setup_widget_failed",retryable:!0});We(()=>it.current?.(ye))}})]})}var xc=require("@flopay/js/card-setup"),lo=require("@flopay/shared"),Mc=require("@paypal/paypal-js"),vo=require("react");var Bc=require("react/jsx-runtime");function Fc({clientId:e,environment:t,currency:n,sessionId:r,nonce:o,billingApiUrl:a,telemetry:s,customer:{userId:c,email:u},onSubmitting:p,onConfirmed:h,onFailed:b,onAbandoned:I}){let k=(0,vo.useRef)(null),C=(0,vo.useRef)({onSubmitting:p,onConfirmed:h,onFailed:b,onAbandoned:I});C.current={onSubmitting:p,onConfirmed:h,onFailed:b,onAbandoned:I};let[f]=(0,vo.useState)(()=>Kr().inAppBrowser);return(0,vo.useEffect)(()=>{let S=!0,G,_=new xc.PaymentAPI(a,{telemetry:s}),q={userId:c,email:u};return(async()=>{try{let E=await(0,Mc.loadScript)({clientId:e,currency:n.toUpperCase(),components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),ne=k.current;if(!S||!ne)return;if(!E?.Buttons)throw new lo.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let $=E.Buttons({createVaultSetupToken:async()=>{C.current.onSubmitting();let W=await _.createSessionIntent(r,o,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:lo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(W.provider!=="paypal"||W.providerObjectType!=="setup_token")throw new lo.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return W.providerObjectId},onApprove:async W=>{let ie=W.vaultSetupToken;if(!ie)throw new lo.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let V=await _.processPayment(q.userId,{sessionId:r,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:ie,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:lo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:q});if(!V.ok)throw new lo.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:V.status});S&&C.current.onConfirmed()},onCancel:()=>{S&&C.current.onAbandoned()},onError:W=>{if(!S)return;let{popupBlocked:ie}=ro(W,{inAppBrowser:f,handoffObserved:!1});C.current.onFailed(ie?new Error(no("PayPal",!0,f)):W,{code:ie?"popup_blocked":"paypal_setup_failed",retryable:!0})}});G=()=>$.close(),await $.render(ne)}catch(E){if(!S)return;C.current.onFailed(E,{code:"paypal_unavailable",retryable:!0})}})(),()=>{S=!1,G?.().catch(()=>{}),_.destroy()}},[a,e,n,u,t,f,o,r,s,c]),(0,Bc.jsx)("div",{ref:k,"data-flopay-paypal-setup":""})}var Dc=require("@flopay/js/card-setup"),ki=require("@flopay/shared"),Lr=require("@stripe/react-stripe-js"),Oc=require("@stripe/stripe-js"),lr=require("react");var Or=require("react/jsx-runtime"),Lc={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},xs=new Map;function ep(e){let t=xs.get(e);if(t)return t;let n=(0,Oc.loadStripe)(e).catch(r=>{throw xs.delete(e),r});return xs.set(e,n),n}var tp={night:"night",flat:"flat"};function np(e){return e?{theme:tp[e.theme??"default"]??"stripe",...e.variables?{variables:e.variables}:{},...e.rules?{rules:e.rules}:{}}:void 0}function rp(e){return fo(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function op(e){return e==="paypal"?"PayPal":(0,ki.getStripeMethodDisplayName)(e)}function ap(){return typeof window>"u"?"":window.location.href}function Nc(e){let{publishableKey:t,method:n,currency:r,appearance:o}=e,[a]=(0,lr.useState)(()=>ep(t)),s=(0,lr.useMemo)(()=>{let c=np(o);return{mode:"setup",currency:r.toLowerCase(),paymentMethodTypes:Lc[n]?.types??[n],...c?{appearance:c}:{}}},[o,r,n]);return(0,Or.jsx)(Lr.Elements,{stripe:a,options:s,children:(0,Or.jsx)(ip,{...e})})}function ip({method:e,category:t,sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onSubmitting:s,onConfirmed:c,onDeclined:u,onFailed:p,onValidation:h}){let b=(0,Lr.useStripe)(),I=(0,Lr.useElements)(),[k,C]=(0,lr.useState)(!1),f=(0,lr.useRef)(!1),[S]=(0,lr.useState)(()=>Kr()),[G,_]=(0,lr.useState)(!1),q=(0,lr.useCallback)((W,ie)=>{if(ro(W,{inAppBrowser:S.inAppBrowser,handoffObserved:!1}).popupBlocked){_(!0),p(new Error(no(op(e),!0,S.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}p(ie.message===void 0?W:new Error(ie.message),{code:ie.code,retryable:!0})},[S.inAppBrowser,e,p]),E=(0,lr.useCallback)(async()=>{if(!(!b||!I||f.current)){f.current=!0,C(!0);try{let W=await I.submit();if(W.error){h(W.error.message??null);return}s();let ie=await new Dc.PaymentAPI(o,{telemetry:a}).createSessionIntent(n,r,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(ie.provider!=="stripe"||ie.intentKind!=="setup")throw new ki.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let V=await b.confirmSetup({elements:I,clientSecret:ie.clientSecret,confirmParams:{return_url:ap()},redirect:"if_required"});if(V.error){rp(V.error)?u({...V.error.decline_code||V.error.code?{reason:V.error.decline_code??V.error.code}:{},...V.error.message?{message:V.error.message}:{}}):q(V.error,{code:"payment_method_setup_provider_failed",message:V.error.message??"The payment method could not be saved."});return}c()}catch(W){q(W,{code:"payment_method_setup_failed"})}finally{f.current=!1,C(!1)}}},[o,t,I,e,r,c,u,s,h,q,n,b,a]),ne=Lc[e]?.wallet,$=ne==="paypal"&&Ha(S,"auto",G?"blocked":S.popupCapability)==="redirect";if(t==="wallet"&&ne&&!$){let W={applePay:"never",googlePay:"never",link:"never",paypal:"never",amazonPay:"never"};return W[ne]="auto",(0,Or.jsx)(Lr.ExpressCheckoutElement,{options:{paymentMethods:W},onConfirm:()=>{E()}})}return(0,Or.jsxs)(Or.Fragment,{children:[(0,Or.jsx)(Lr.PaymentElement,{onChange:W=>{W.complete&&h(null)}}),(0,Or.jsx)("button",{type:"button","data-flopay-payment-method-save":e,disabled:!b||!I||k,onClick:()=>{E()},children:"Save payment method"})]})}var Aa=require("@flopay/js/card-setup"),Sn=require("@flopay/shared"),at=ji(require("react"),1);var sp=new Set(["apple_pay","google_pay","link","paypal","amazon_pay"]);function zc(e){let t=e.data.stripe,n=Array.from(new Set(t?.enabledPaymentMethods??[])),r=e.data.paypal,o=r?.publishableKey?{clientId:r.publishableKey,...r.environment?{environment:String(r.environment)}:{}}:null,a=n.filter(s=>s!=="card"&&!(o&&s==="paypal"));return{card:n.includes("card"),stripe:t?.publishableKey&&a.length>0?{publishableKey:t.publishableKey,methods:a}:null,paypal:o}}function Uc(e){return e.card||e.stripe!==null||e.paypal!==null}function qc(e){return sp.has(e)?"wallet":"apm"}var lp=["setup_intent","setup_intent_client_secret","redirect_status"];function Vc(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function jc(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let n of lp)e.searchParams.has(n)&&(e.searchParams.delete(n),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}function $c(e){return e==="card"?{processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED"}:{processingLabel:"SAVING PAYMENT METHOD...",successLabel:"PAYMENT METHOD SAVED",errorLabel:"PAYMENT METHOD NOT SAVED"}}var sn=require("react/jsx-runtime"),cp=15,dp=2e3;function up(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Ms(e){return new Promise(t=>setTimeout(t,e))}async function pp(e,t,n){if(!t.trim())throw new Sn.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!n.trim())throw new Sn.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let r=await e.getUnifiedCheckoutSession(t,n),o=r.data.session;if(!o||!(0,Sn.isCardSetupCheckoutSession)(o))throw new Sn.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let a=zc(r);if(!Uc(a))throw new Sn.FloPayError("FloPay: this setup session advertises no payment method.","validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"});return{session:o,advertisement:a}}async function mp(e,t,n,r){let o=t.vault??null;if(o?.html?.trim()||(o=await e.getVaultCapture(n,r)),!o.html?.trim())throw new Sn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return o}var Ii=class extends at.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(n){this.props.onFailed(n,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function Wc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,theme:s="modern-light",containerStyle:c,loading:u=null,onReady:p,onComplete:h,onDecline:b,onCancel:I,onValidation:k,onError:C}){let[f]=(0,at.useState)(Vc),[S,G]=(0,at.useState)(null),[_,q]=(0,at.useState)(!1),[E,ne]=(0,at.useState)(null),[$,W]=(0,at.useState)(null),[ie,V]=(0,at.useState)(null),[Be,Ue]=(0,at.useState)(null),X=(0,at.useRef)(!1),Ae=(0,at.useRef)(!1),it=(0,at.useRef)(!1),Re=(0,at.useRef)(!1),xe=(0,at.useRef)(0),ve=(0,at.useRef)(0),se=(0,at.useRef)(!1),me=(0,at.useMemo)(()=>typeof s=="object"?void 0:(0,Sn.resolveTheme)(s),[s]),He=(0,at.useMemo)(()=>typeof s=="object"?s:me?Go({appearance:me.appearance,buttonsStyles:me.buttonsLayout,layout:"default"}):null,[me,s]),st=(0,at.useMemo)(()=>ci(me?.buttonsLayout.cardFormContainer,c),[me,c]),T=(0,at.useMemo)(()=>me?Si(me):void 0,[me]),ye=(0,at.useRef)({sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:p,onComplete:h,onDecline:b,onCancel:I,onValidation:k,onError:C});ye.current={sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:p,onComplete:h,onDecline:b,onCancel:I,onValidation:k,onError:C},(0,at.useEffect)(()=>{se.current=!0;let Y=xe.current+1;return xe.current=Y,()=>{se.current=!1,ve.current+=1,queueMicrotask(()=>{xe.current===Y&&(it.current||Re.current||(Re.current=!0,We(()=>{ye.current.onCancel?.({status:"cancelled",sessionId:n})})))})}},[n]);let le=(0,at.useCallback)((Y,J)=>{it.current=!0,X.current=!1,Ue({status:"success",wording:Y,message:null}),(async()=>(await Ms(600),!Ae.current&&(Ae.current=!0,We(()=>{ye.current.onComplete?.({status:"succeeded",sessionId:ye.current.sessionId,...J?{paymentMethod:J}:{}})}),se.current&&Ue(null))))()},[]),F=(0,at.useCallback)((Y,J)=>{it.current=!0,X.current=!1,Ue({status:"error",wording:Y,message:J.message??null}),We(()=>{ye.current.onDecline?.({status:"declined",sessionId:ye.current.sessionId,...J.reason?{reason:J.reason}:{},...J.message?{message:J.message}:{}})}),(async()=>(await Ms(400),se.current&&Ue(null)))()},[]),Se=(0,at.useCallback)((Y,J)=>{X.current?(X.current=!1,Ue({status:"error",wording:Y,message:J.message}),setTimeout(()=>{se.current&&Ue(null)},400)):Ue(null),We(()=>ye.current.onError?.(J))},[]),ce=(0,at.useCallback)(async Y=>{let J=ve.current+1;ve.current=J;let mt=()=>!se.current||J!==ve.current;X.current=!0,Ue({status:"processing",wording:"payment_method",message:null});let gt=new Aa.PaymentAPI((0,Sn.resolveBillingApiUrl)(ye.current.billingApiUrl),{telemetry:ye.current.telemetry});try{for(let Ie=0;Ie<cp;Ie+=1){if((Ie>0||Y.waitFirst)&&await Ms(dp),mt())return;let ft=await gt.getUnifiedCheckoutSession(ye.current.sessionId,ye.current.nonce);if(mt())return;let U=ft.data.session?.status;if(U==="complete"){q(!0),le("payment_method");return}if(U==="expired")throw new Sn.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Sn.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(Ie){if(mt())return;let ft=Ie instanceof Sn.FloPayError&&Ie.code==="payment_method_setup_unverified";Se("payment_method",bo(Ie,ft?{retryable:!0}:{}))}finally{gt.destroy()}},[Se,le]);(0,at.useEffect)(()=>{let Y=!0,J=new Aa.PaymentAPI((0,Sn.resolveBillingApiUrl)(o),{telemetry:a});return G(null),q(!1),ne(null),W(null),V(null),it.current=!1,Re.current=!1,Ae.current=!1,(async()=>{try{let{session:mt,advertisement:gt}=await pp(J,n,r);if(!Y)return;let Ie={advertisement:gt,currency:mt.currency,customer:up(mt)};if(f){if(jc(),mt.status==="complete"){q(!0),G(Ie),le("payment_method");return}f.failed?F("payment_method",{reason:"redirect_failed"}):ce({waitFirst:!0})}let ft=gt.card?await mp(J,mt,n,r):null;if(!Y)return;G(Ie),ft&&(W(ft),ne(new Aa.PciVaultCardCapture({sessionId:n,operation:"card_setup",telemetry:a})))}catch(mt){if(!Y)return;let gt=bo(mt);it.current=!0,V(gt),We(()=>ye.current.onError?.(gt))}})(),()=>{Y=!1,J.destroy()}},[o,r,f,F,le,n,a,ce]),(0,at.useEffect)(()=>{if(!E)return;X.current=!1;let Y=E.on("submitting",()=>{X.current=!0,Ue({status:"processing",wording:"card",message:null})}),J=E.on("complete",Ie=>{le("card",Ie.paymentMethod)}),mt=E.on("decline",Ie=>{F("card",{...Ie.declineReason?{reason:Ie.declineReason}:{},...Ie.message?{message:Ie.message}:{}})}),gt=E.on("challenge_dismissed",()=>{Ue(null)});return()=>{Y(),J(),mt(),gt()}},[E,F,le]);let De=(0,at.useMemo)(()=>({onSubmitting:()=>{X.current=!0,Ue({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{ce({waitFirst:!1})},onDeclined:Y=>F("payment_method",Y),onFailed:(Y,J)=>{Se("payment_method",bo(Y,J))},onValidation:Y=>{We(()=>ye.current.onValidation?.(Y))},onAbandoned:()=>{X.current=!1,Ue(null)}}),[F,Se,ce]),re=Be?(0,sn.jsx)(Ln,{status:Be.status,errorMessage:Be.message,...$c(Be.wording),successNote:null,...T?{theme:T}:{}}):null;if(ie)return(0,sn.jsx)("div",{role:"alert",children:ie.message});if(!S||_)return(0,sn.jsxs)(sn.Fragment,{children:[re,S?null:u]});let{advertisement:$e,currency:dt,customer:Me}=S,Oe=(0,Sn.resolveBillingApiUrl)(o),ut=a===void 0?{}:{telemetry:a};return(0,sn.jsxs)(sn.Fragment,{children:[re,$e.card&&E&&$?.html?(0,sn.jsx)("div",{"data-flopay-payment-method":"card",children:(0,sn.jsx)(so,{capture:E,html:$.html,messageToken:$.messageToken,expectedOrigin:$.expectedOrigin,theme:He,containerStyle:st,onReady:()=>{We(()=>ye.current.onReady?.())},onValidation:Y=>{We(()=>ye.current.onValidation?.(Y))},onError:Y=>{Y&&Se("card",bo(new Error(Y),{code:"card_setup_widget_failed",retryable:!0}))}})}):null,$e.stripe?.methods.map(Y=>(0,sn.jsx)("div",{"data-flopay-payment-method":Y,children:(0,sn.jsx)(Ii,{onFailed:De.onFailed,children:(0,sn.jsx)(at.Suspense,{fallback:null,children:(0,sn.jsx)(e,{method:Y,category:qc(Y),publishableKey:$e.stripe?.publishableKey??"",currency:dt,sessionId:n,nonce:r,billingApiUrl:Oe,...ut,...me?{appearance:me.appearance}:{},...De})})})},Y)),$e.paypal?(0,sn.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,sn.jsx)(Ii,{onFailed:De.onFailed,children:(0,sn.jsx)(at.Suspense,{fallback:null,children:(0,sn.jsx)(t,{clientId:$e.paypal.clientId,...$e.paypal.environment?{environment:$e.paypal.environment}:{},currency:dt,sessionId:n,nonce:r,billingApiUrl:Oe,customer:Me,...ut,...De})})})}):null]})}var Kc=require("react/jsx-runtime"),yp={StripeSetupMethod:Nc,PayPalSetupMethod:Fc};function Hc(e){return(0,Kc.jsx)(Wc,{...e,branches:yp})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}return(0,N.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&E(Yo),n&&(r||o)&&E(Yo),n&&(0,N.jsx)("button",{type:"button",onClick:()=>{e?.("card"),k(!0)},style:{width:"100%",...b,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:S.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,...S.cardButton},onMouseDown:C=>{C.currentTarget.style.transform="scale(0.985)"},onMouseUp:C=>{C.currentTarget.style.transform="scale(1)"},children:(0,N.jsx)(xo,{content:p})}),(0,N.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var or=require("react/jsx-runtime"),Ju=44;function Ec(e){return new Promise(t=>setTimeout(t,e))}function Zu(e,t){return e instanceof ar.FloPayError?e:new ar.FloPayError(e instanceof Error?e.message:t,"api_error")}function Qu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function ep(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 Tc({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:s,items:d,subscriptions:p,account:u,successUrl:f,cancelUrl:P,couponCodes:k,tagsData:R,utmMetadata:S,billingApiUrl:T,locale:E,theme:b,appearance:C,buttonsTheme:j,buttonsStyles:_,onSuccess:re,onError:q,onDecline:K,children:le,disabled:$=!1,type:Oe="button",style:Ue,...J}){let xe=(0,it.useMemo)(()=>(0,ar.resolveBillingApiUrl)(T),[T]),lt=(0,it.useMemo)(()=>ep({createSession:n,clientId:a,products:s,items:d,subscriptions:p,account:u,successUrl:f,cancelUrl:P,couponCodes:k,tagsData:R,utmMetadata:S}),[u,P,a,k,n,s,d,p,f,R,S]),[Ee,Fe]=(0,it.useState)(!1),[be,ce]=(0,it.useState)(null),[me,Ge]=(0,it.useState)(null),[ct,A]=(0,it.useState)(!1),[fe,de]=(0,it.useState)(null),[D,Se]=(0,it.useState)(null),ue=(0,it.useRef)(!0),Le=(0,it.useRef)(null),oe=(0,it.useRef)(D),We=(0,it.useRef)(re),ut=(0,it.useRef)(q),Be=(0,it.useRef)(K),Je=(0,it.useCallback)(h=>ai(Le,async v=>{try{return await h(v)}catch(X){throw v.aborted?io(X):X}}),[]);(0,it.useEffect)(()=>{oe.current=D},[D]),(0,it.useEffect)(()=>{We.current=re},[re]),(0,it.useEffect)(()=>{ut.current=q},[q]),(0,it.useEffect)(()=>{Be.current=K},[K]),(0,it.useEffect)(()=>(ue.current=!0,()=>{ue.current=!1,Le.current?.abort()}),[]),(0,it.useEffect)(()=>{if(typeof window>"u")return;let h=v=>{v.key==="Escape"&&Se(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let Ze=(0,it.useCallback)((h,v=ba)=>{Be.current?.(un(v,h,{code:h.code,declineCode:h.declineCode}))},[]),Z=(0,it.useCallback)(async h=>{ue.current&&(Ge(null),A(h.result.status==="authorized"),ce("success"),await Ec(600),ue.current&&Ke(()=>We.current?.(h)))},[]),Q=(0,it.useCallback)(async(h,v)=>{ue.current&&(ut.current?.(h),v?.emitDecline&&Ze(h,v.method),Ge(h.message),A(!1),ce("error"),await Ec(400))},[Ze]),pt=(0,it.useCallback)(async(h,v,X)=>{let W=h.data.session??null;if(!W)throw Qr(new ar.FloPayError("No session data returned","api_error"),v);let ve=W.clientSecret||t;if($r(W)){await Z({result:jr(W,v),session:W,sessionId:W.id||v,autoCompleted:!1});return}if(W.status==="expired")throw Qr(ja(W),W.id||v);try{if(h.autoProcessingPending){let Ve=h.autoProcessingPending,Ye=new Ci.PaymentAPI(xe),we=await Je(He=>Ye.waitForCheckoutSessionCompletion(Ve.sessionId,{initialDelayMs:Ve.retryAfterMs,nonce:ve,statusUrl:Ve.statusUrl,signal:He})),Ct=to(we,W),Wt=we.autoProcessingError?.type==="3ds_required"&&we.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:we.autoProcessingError.nextActionRedirectUrl}:null;if(Wt&&v&&ve){let He=await Je(Tn=>$o(Wt,{billingApiUrl:xe,sessionId:v,nonce:ve,session:W,signal:Tn,telemetry:!0}));await Z({result:He,session:W,sessionId:W.id||v,autoCompleted:!1});return}if(we.autoProcessingError)throw xr(we.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:we.autoProcessingError.checkoutMethod});if(!$r(Ct))throw Do(Ct);await Z({result:jr(Ct,v),session:Ct,sessionId:Ct.id||v,autoCompleted:!1});return}if(h.autoProcessingError){let Ve=h.autoProcessingError.nextActionRedirectUrl;if(h.autoProcessingError.type==="3ds_required"&&Ve&&v&&ve){let Ye=await Je(He=>is({billingApiUrl:xe,sessionId:v,nonce:ve,nextActionRedirectUrl:Ve,signal:He}));if(Ye.status==="declined")throw xr({type:Ye.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ye.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let Ct=await new Ci.PaymentAPI(xe).waitForCheckoutSessionCompletion(v,{initialDelayMs:0,nonce:ve}),Wt=to(Ct,W);if(!$r(Wt))throw xr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await Z({result:jr(Wt,v),session:Wt,sessionId:Wt.id||v,autoCompleted:!1});return}throw xr(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(X?.fromCreateSession&&h.autoProcessingAttempted===!0)throw xr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Bt=await Wo({billingApiUrl:xe,sessionId:v??W.id,session:W,nonce:ve});if(Bt.type==="next_action_required"&&ve){let Ve=v??W.id,Ye=await Je(we=>$o(Bt,{billingApiUrl:xe,sessionId:Ve,nonce:ve,session:W,signal:we,telemetry:!0}));await Z({result:Ye,session:W,sessionId:W.id||Ve,autoCompleted:!1});return}if(Bt.type!=="success")throw xr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Z({result:Bt.result,session:W,sessionId:W.id||v,autoCompleted:!1})}catch(Bt){let Ve=W.id||v,Ye=Qr(va(Bt),Ve);if(Ye.code==="three_ds_aborted")return;if(Ye.code==="checkout_processing_timeout"){if(!ue.current)return;de(Ye.message),Ke(()=>ut.current?.(Ye));return}await Q(Ye,{emitDecline:!0,method:Ye.checkoutMethod??ba}),Qu(Ye,Ve)&&Ve&&ue.current&&Se({sessionId:Ve,errorMessage:Ye.message,nonce:ve||void 0,payPalOrderId:Ye.orderId})}},[t,xe,Je,Q,Z]),ft=(0,it.useCallback)(async h=>{if(J.onClick?.(h),!(h.defaultPrevented||$||Ee)){if(Se(null),de(null),e&<){let v=new ar.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Q(v),ue.current&&(ce(null),Ge(null));return}if(!e&&!lt){let v=new ar.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Q(v),ue.current&&(ce(null),Ge(null));return}Fe(!0),Ge(null),A(!1),ce("processing");try{let v=new Ci.PaymentAPI(xe);if(e){let X=await v.getUnifiedCheckoutSession(e,t);await pt(X,e);return}try{let X=await v.createAndFetchSession({...lt});await pt(X,X.data.session?.id??null,{fromCreateSession:!0})}catch(X){if($a(X)==="session_auto_completed"){await Z({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw X}}catch(v){await Q(Qr(Zu(v,"Automatic payment failed. Please try again."),e))}finally{ue.current&&(ce(null),Ge(null),Fe(!1))}}},[J.onClick,lt,$,Ee,t,pt,xe,e,Q,Z]),Ae=(0,it.useCallback)(h=>{let v=oe.current;Se(null),We.current?.({result:h,session:null,sessionId:v?.sessionId??null,autoCompleted:!1})},[]),gt=(0,it.useCallback)(h=>{ut.current?.(h)},[]),V=(0,it.useCallback)(h=>{Be.current?.(h)},[]),ke=(0,it.useMemo)(()=>(0,ar.resolveTheme)(b),[b]),tt=(0,it.useMemo)(()=>{let h=ke?.buttonsLayout??(0,ar.resolveButtonsLayoutTheme)(j);return _?{...h,..._,cardButton:{...h.cardButton,..._.cardButton}}:h},[ke,j,_]),ee=(0,it.useMemo)(()=>{let h=ke?.appearance;return C?h?{...h,...C,variables:{...h.variables,...C.variables}}:C:h},[C,ke]),qe=ee?.variables,vt=qe?.colorPrimary??"#4A49FF",nt=qe?.colorPrimaryHover??Ko(vt,.12),Et=qe?.borderRadius??"8px";return(0,or.jsxs)(or.Fragment,{children:[(0,or.jsx)("button",{...J,type:Oe,onClick:ft,disabled:$||Ee,"aria-busy":Ee,style:{width:"100%",...le===void 0?{boxSizing:"border-box",height:Ju,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...tt.cardButton,...ws({themeBundle:ke,resolvedPrimaryColor:vt,resolvedBorderRadius:Et,submitButtonStyle:tt.submitButton,explicitPrimaryColor:qe?.colorPrimary}),fontSize:tt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:$||Ee?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:$||Ee?.6:1,...Ue},onMouseEnter:h=>{J.onMouseEnter?.(h),!h.defaultPrevented&&!$&&!Ee&&(ke||qe?.colorPrimary)&&(h.currentTarget.style.backgroundColor=nt)},onMouseLeave:h=>{J.onMouseLeave?.(h),!h.defaultPrevented&&(ke||qe?.colorPrimary)&&(h.currentTarget.style.backgroundColor=vt)},onMouseDown:h=>{J.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{J.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,or.jsx)(xo,{content:le})}),fe&&(0,or.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:fe}),be&&(0,or.jsx)(Ln,{status:be,errorMessage:me,authorized:ct}),D&&(0,or.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&Se(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,or.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,or.jsx)(vi,{sessionId:D.sessionId,nonce:D.nonce,checkoutMode:"full",billingApiUrl:xe,locale:E,theme:b,...ee?{appearance:ee}:{},buttonsTheme:j,buttonsStyles:_,initialErrorMessage:D.errorMessage,initialPayPalOrderId:D.payPalOrderId,cardTitleContent:null,onComplete:Ae,onError:gt,onDecline:V})})})]})}var wi=require("@flopay/js/card-setup"),Hn=require("@flopay/shared"),_t=require("react");var Ac={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function Si(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?Ac.dark:Ac.light,a=t.colorText??(r?"#F1F5F9":"#262833"),s=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:s?.color??a}}var Br=require("react/jsx-runtime"),Ta=class extends Hn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function bo(e,t={}){let n=e instanceof Hn.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 Ta(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 Mc({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:s=null,onReady:d,onComplete:p,onDecline:u,onCancel:f,onValidation:P,onError:k}){let[R,S]=(0,_t.useState)(null),[T,E]=(0,_t.useState)(null),[b,C]=(0,_t.useState)(null),[j,_]=(0,_t.useState)(null),[re,q]=(0,_t.useState)(null),K=(0,_t.useRef)(!1),le=(0,_t.useRef)(!1),$=(0,_t.useMemo)(()=>typeof o=="object"?void 0:(0,Hn.resolveTheme)(o),[o]),Oe=(0,_t.useMemo)(()=>typeof o=="object"?o:$?Go({appearance:$.appearance,buttonsStyles:$.buttonsLayout,layout:"default"}):null,[$,o]),Ue=(0,_t.useMemo)(()=>ci($?.buttonsLayout.cardFormContainer,a),[$,a]),J=(0,_t.useMemo)(()=>$?Si($):void 0,[$]),xe=(0,_t.useRef)(d),lt=(0,_t.useRef)(k),Ee=(0,_t.useRef)(p),Fe=(0,_t.useRef)(u),be=(0,_t.useRef)(f),ce=(0,_t.useRef)(P),me=(0,_t.useRef)(!1),Ge=(0,_t.useRef)(!1),ct=(0,_t.useRef)(0);return xe.current=d,lt.current=k,Ee.current=p,Fe.current=u,be.current=f,ce.current=P,(0,_t.useEffect)(()=>{let A=ct.current+1;return ct.current=A,()=>{queueMicrotask(()=>{ct.current===A&&(me.current||Ge.current||(Ge.current=!0,Ke(()=>{be.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,_t.useEffect)(()=>{let A=!0,fe=new wi.PaymentAPI((0,Hn.resolveBillingApiUrl)(n),{telemetry:r});return S(null),E(null),C(null),me.current=!1,Ge.current=!1,(async()=>{try{if(!e.trim())throw new Hn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Hn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let de=await fe.getUnifiedCheckoutSession(e,t);if(!A)return;let D=de.data.session;if(!D||!(0,Hn.isCardSetupCheckoutSession)(D))throw new Hn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Se=D.vault;if(Se?.html?.trim()||(Se=await fe.getVaultCapture(e,t)),!Se.html?.trim())throw new Hn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!A)return;E(Se),S(new wi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(de){if(!A)return;let D=bo(de);me.current=!0,C(D),Ke(()=>lt.current?.(D))}})(),()=>{A=!1,fe.destroy()}},[n,t,e,r]),(0,_t.useEffect)(()=>{if(!R)return;let A=!1;le.current=!1,K.current=!1;let fe=R.on("submitting",()=>{K.current=!0,q(null),_("processing")}),de=R.on("complete",ue=>{me.current=!0,K.current=!1,_("success"),(async()=>(await new Promise(Le=>setTimeout(Le,600)),!le.current&&(le.current=!0,Ke(()=>{Ee.current?.({status:"succeeded",sessionId:e,...ue.paymentMethod?{paymentMethod:ue.paymentMethod}:{}})}),A||_(null))))()}),D=R.on("decline",ue=>{me.current=!0,K.current=!1,q(ue.message??null),_("error"),Ke(()=>{Fe.current?.({status:"declined",sessionId:e,...ue.declineReason?{reason:ue.declineReason}:{},...ue.message?{message:ue.message}:{}})}),(async()=>(await new Promise(Le=>setTimeout(Le,400)),A||_(null)))()}),Se=R.on("challenge_dismissed",()=>{_(null)});return()=>{A=!0,fe(),de(),D(),Se()}},[R,e]),b?(0,Br.jsx)("div",{role:"alert",children:b.message}):!R||!T?.html?(0,Br.jsx)(Br.Fragment,{children:s}):(0,Br.jsxs)(Br.Fragment,{children:[j&&(0,Br.jsx)(Ln,{status:j,errorMessage:re,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...J?{theme:J}:{}}),(0,Br.jsx)(so,{capture:R,html:T.html,messageToken:T.messageToken,expectedOrigin:T.expectedOrigin,theme:Oe,containerStyle:Ue,onReady:()=>{Ke(()=>xe.current?.())},onValidation:A=>{Ke(()=>ce.current?.(A))},onError:A=>{if(!A)return;K.current&&(K.current=!1,q(A),_("error"),setTimeout(()=>_(null),400));let fe=bo(new Error(A),{code:"card_setup_widget_failed",retryable:!0});Ke(()=>lt.current?.(fe))}})]})}var xc=require("@flopay/js/card-setup"),lo=require("@flopay/shared"),Fc=require("@paypal/paypal-js"),vo=require("react");var Dc=require("react/jsx-runtime");function Bc({clientId:e,environment:t,currency:n,sessionId:r,nonce:o,billingApiUrl:a,telemetry:s,customer:{userId:d,email:p},onSubmitting:u,onConfirmed:f,onFailed:P,onAbandoned:k}){let R=(0,vo.useRef)(null),S=(0,vo.useRef)({onSubmitting:u,onConfirmed:f,onFailed:P,onAbandoned:k});S.current={onSubmitting:u,onConfirmed:f,onFailed:P,onAbandoned:k};let[T]=(0,vo.useState)(()=>Kr().inAppBrowser);return(0,vo.useEffect)(()=>{let E=!0,b,C=new xc.PaymentAPI(a,{telemetry:s}),j={userId:d,email:p};return(async()=>{try{let _=await(0,Fc.loadScript)({clientId:e,currency:n.toUpperCase(),components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),re=R.current;if(!E||!re)return;if(!_?.Buttons)throw new lo.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let q=_.Buttons({createVaultSetupToken:async()=>{S.current.onSubmitting();let K=await C.createSessionIntent(r,o,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:lo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(K.provider!=="paypal"||K.providerObjectType!=="setup_token")throw new lo.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return K.providerObjectId},onApprove:async K=>{let le=K.vaultSetupToken;if(!le)throw new lo.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let $=await C.processPayment(j.userId,{sessionId:r,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:le,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:lo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:j});if(!$.ok)throw new lo.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:$.status});E&&S.current.onConfirmed()},onCancel:()=>{E&&S.current.onAbandoned()},onError:K=>{if(!E)return;let{popupBlocked:le}=ro(K,{inAppBrowser:T,handoffObserved:!1});S.current.onFailed(le?new Error(no("PayPal",!0,T)):K,{code:le?"popup_blocked":"paypal_setup_failed",retryable:!0})}});b=()=>q.close(),await q.render(re)}catch(_){if(!E)return;S.current.onFailed(_,{code:"paypal_unavailable",retryable:!0})}})(),()=>{E=!1,b?.().catch(()=>{}),C.destroy()}},[a,e,n,p,t,T,o,r,s,d]),(0,Dc.jsx)("div",{ref:R,"data-flopay-paypal-setup":""})}var Oc=require("@flopay/js/card-setup"),ki=require("@flopay/shared"),Or=require("@stripe/react-stripe-js"),Lc=require("@stripe/stripe-js"),ir=require("react");var Dr=require("react/jsx-runtime"),Nc={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},Ms=new Map;function tp(e){let t=Ms.get(e);if(t)return t;let n=(0,Lc.loadStripe)(e).catch(r=>{throw Ms.delete(e),r});return Ms.set(e,n),n}var np={night:"night",flat:"flat"};function rp(e){return e?{theme:np[e.theme??"default"]??"stripe",...e.variables?{variables:e.variables}:{},...e.rules?{rules:e.rules}:{}}:void 0}function op(e){return fo(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function ap(e){return e==="paypal"?"PayPal":(0,ki.getStripeMethodDisplayName)(e)}function ip(){return typeof window>"u"?"":window.location.href}function zc(e){let{publishableKey:t,method:n,currency:r,appearance:o}=e,[a]=(0,ir.useState)(()=>tp(t)),s=(0,ir.useMemo)(()=>{let d=rp(o);return{mode:"setup",currency:r.toLowerCase(),paymentMethodTypes:Nc[n]?.types??[n],...d?{appearance:d}:{}}},[o,r,n]);return(0,Dr.jsx)(Or.Elements,{stripe:a,options:s,children:(0,Dr.jsx)(sp,{...e})})}function sp({method:e,category:t,sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onSubmitting:s,onConfirmed:d,onDeclined:p,onFailed:u,onValidation:f}){let P=(0,Or.useStripe)(),k=(0,Or.useElements)(),[R,S]=(0,ir.useState)(!1),T=(0,ir.useRef)(!1),[E]=(0,ir.useState)(()=>Kr()),[b,C]=(0,ir.useState)(!1),j=(0,ir.useCallback)((K,le)=>{if(ro(K,{inAppBrowser:E.inAppBrowser,handoffObserved:!1}).popupBlocked){C(!0),u(new Error(no(ap(e),!0,E.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}u(le.message===void 0?K:new Error(le.message),{code:le.code,retryable:!0})},[E.inAppBrowser,e,u]),_=(0,ir.useCallback)(async()=>{if(!(!P||!k||T.current)){T.current=!0,S(!0);try{let K=await k.submit();if(K.error){f(K.error.message??null);return}s();let le=await new Oc.PaymentAPI(o,{telemetry:a}).createSessionIntent(n,r,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(le.provider!=="stripe"||le.intentKind!=="setup")throw new ki.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let $=await P.confirmSetup({elements:k,clientSecret:le.clientSecret,confirmParams:{return_url:ip()},redirect:"if_required"});if($.error){op($.error)?p({...$.error.decline_code||$.error.code?{reason:$.error.decline_code??$.error.code}:{},...$.error.message?{message:$.error.message}:{}}):j($.error,{code:"payment_method_setup_provider_failed",message:$.error.message??"The payment method could not be saved."});return}d()}catch(K){j(K,{code:"payment_method_setup_failed"})}finally{T.current=!1,S(!1)}}},[o,t,k,e,r,d,p,s,f,j,n,P,a]),re=Nc[e]?.wallet,q=re==="paypal"&&Ha(E,"auto",b?"blocked":E.popupCapability)==="redirect";if(t==="wallet"&&re&&!q){let K={applePay:"never",googlePay:"never",link:"never",paypal:"never",amazonPay:"never"};return K[re]="auto",(0,Dr.jsx)(Or.ExpressCheckoutElement,{options:{paymentMethods:K},onConfirm:()=>{_()}})}return(0,Dr.jsxs)(Dr.Fragment,{children:[(0,Dr.jsx)(Or.PaymentElement,{onChange:K=>{K.complete&&f(null)}}),(0,Dr.jsx)("button",{type:"button","data-flopay-payment-method-save":e,disabled:!P||!k||R,onClick:()=>{_()},children:"Save payment method"})]})}var Aa=require("@flopay/js/card-setup"),bn=require("@flopay/shared"),st=ji(require("react"),1);var lp=new Set(["apple_pay","google_pay","link","paypal","amazon_pay"]);function Uc(e){let t=e.data.stripe,n=Array.from(new Set(t?.enabledPaymentMethods??[])),r=e.data.paypal,o=r?.publishableKey?{clientId:r.publishableKey,...r.environment?{environment:String(r.environment)}:{}}:null,a=n.filter(s=>s!=="card"&&!(o&&s==="paypal"));return{card:n.includes("card"),stripe:t?.publishableKey&&a.length>0?{publishableKey:t.publishableKey,methods:a}:null,paypal:o}}function qc(e){return e.card||e.stripe!==null||e.paypal!==null}function Vc(e){return lp.has(e)?"wallet":"apm"}var cp=["setup_intent","setup_intent_client_secret","redirect_status"];function jc(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function $c(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let n of cp)e.searchParams.has(n)&&(e.searchParams.delete(n),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}function Wc(e){return e==="card"?{processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED"}:{processingLabel:"SAVING PAYMENT METHOD...",successLabel:"PAYMENT METHOD SAVED",errorLabel:"PAYMENT METHOD NOT SAVED"}}var an=require("react/jsx-runtime"),dp=15,up=2e3;function pp(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function xs(e){return new Promise(t=>setTimeout(t,e))}async function mp(e,t,n){if(!t.trim())throw new bn.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!n.trim())throw new bn.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let r=await e.getUnifiedCheckoutSession(t,n),o=r.data.session;if(!o||!(0,bn.isCardSetupCheckoutSession)(o))throw new bn.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let a=Uc(r);if(!qc(a))throw new bn.FloPayError("FloPay: this setup session advertises no payment method.","validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"});return{session:o,advertisement:a}}async function yp(e,t,n,r){let o=t.vault??null;if(o?.html?.trim()||(o=await e.getVaultCapture(n,r)),!o.html?.trim())throw new bn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return o}var Ii=class extends st.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(n){this.props.onFailed(n,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function Hc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,theme:s="modern-light",containerStyle:d,loading:p=null,onReady:u,onComplete:f,onDecline:P,onCancel:k,onValidation:R,onError:S}){let[T]=(0,st.useState)(jc),[E,b]=(0,st.useState)(null),[C,j]=(0,st.useState)(!1),[_,re]=(0,st.useState)(null),[q,K]=(0,st.useState)(null),[le,$]=(0,st.useState)(null),[Oe,Ue]=(0,st.useState)(null),J=(0,st.useRef)(!1),xe=(0,st.useRef)(!1),lt=(0,st.useRef)(!1),Ee=(0,st.useRef)(!1),Fe=(0,st.useRef)(0),be=(0,st.useRef)(0),ce=(0,st.useRef)(!1),me=(0,st.useMemo)(()=>typeof s=="object"?void 0:(0,bn.resolveTheme)(s),[s]),Ge=(0,st.useMemo)(()=>typeof s=="object"?s:me?Go({appearance:me.appearance,buttonsStyles:me.buttonsLayout,layout:"default"}):null,[me,s]),ct=(0,st.useMemo)(()=>ci(me?.buttonsLayout.cardFormContainer,d),[me,d]),A=(0,st.useMemo)(()=>me?Si(me):void 0,[me]),fe=(0,st.useRef)({sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:u,onComplete:f,onDecline:P,onCancel:k,onValidation:R,onError:S});fe.current={sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:u,onComplete:f,onDecline:P,onCancel:k,onValidation:R,onError:S},(0,st.useEffect)(()=>{ce.current=!0;let Z=Fe.current+1;return Fe.current=Z,()=>{ce.current=!1,be.current+=1,queueMicrotask(()=>{Fe.current===Z&&(lt.current||Ee.current||(Ee.current=!0,Ke(()=>{fe.current.onCancel?.({status:"cancelled",sessionId:n})})))})}},[n]);let de=(0,st.useCallback)((Z,Q)=>{lt.current=!0,J.current=!1,Ue({status:"success",wording:Z,message:null}),(async()=>(await xs(600),!xe.current&&(xe.current=!0,Ke(()=>{fe.current.onComplete?.({status:"succeeded",sessionId:fe.current.sessionId,...Q?{paymentMethod:Q}:{}})}),ce.current&&Ue(null))))()},[]),D=(0,st.useCallback)((Z,Q)=>{lt.current=!0,J.current=!1,Ue({status:"error",wording:Z,message:Q.message??null}),Ke(()=>{fe.current.onDecline?.({status:"declined",sessionId:fe.current.sessionId,...Q.reason?{reason:Q.reason}:{},...Q.message?{message:Q.message}:{}})}),(async()=>(await xs(400),ce.current&&Ue(null)))()},[]),Se=(0,st.useCallback)((Z,Q)=>{J.current?(J.current=!1,Ue({status:"error",wording:Z,message:Q.message}),setTimeout(()=>{ce.current&&Ue(null)},400)):Ue(null),Ke(()=>fe.current.onError?.(Q))},[]),ue=(0,st.useCallback)(async Z=>{let Q=be.current+1;be.current=Q;let pt=()=>!ce.current||Q!==be.current;J.current=!0,Ue({status:"processing",wording:"payment_method",message:null});let ft=new Aa.PaymentAPI((0,bn.resolveBillingApiUrl)(fe.current.billingApiUrl),{telemetry:fe.current.telemetry});try{for(let Ae=0;Ae<dp;Ae+=1){if((Ae>0||Z.waitFirst)&&await xs(up),pt())return;let gt=await ft.getUnifiedCheckoutSession(fe.current.sessionId,fe.current.nonce);if(pt())return;let V=gt.data.session?.status;if(V==="complete"){j(!0),de("payment_method");return}if(V==="expired")throw new bn.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new bn.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(Ae){if(pt())return;let gt=Ae instanceof bn.FloPayError&&Ae.code==="payment_method_setup_unverified";Se("payment_method",bo(Ae,gt?{retryable:!0}:{}))}finally{ft.destroy()}},[Se,de]);(0,st.useEffect)(()=>{let Z=!0,Q=new Aa.PaymentAPI((0,bn.resolveBillingApiUrl)(o),{telemetry:a});return b(null),j(!1),re(null),K(null),$(null),lt.current=!1,Ee.current=!1,xe.current=!1,(async()=>{try{let{session:pt,advertisement:ft}=await mp(Q,n,r);if(!Z)return;let Ae={advertisement:ft,currency:pt.currency,customer:pp(pt)};if(T){if($c(),pt.status==="complete"){j(!0),b(Ae),de("payment_method");return}T.failed?D("payment_method",{reason:"redirect_failed"}):ue({waitFirst:!0})}let gt=ft.card?await yp(Q,pt,n,r):null;if(!Z)return;b(Ae),gt&&(K(gt),re(new Aa.PciVaultCardCapture({sessionId:n,operation:"card_setup",telemetry:a})))}catch(pt){if(!Z)return;let ft=bo(pt);lt.current=!0,$(ft),Ke(()=>fe.current.onError?.(ft))}})(),()=>{Z=!1,Q.destroy()}},[o,r,T,D,de,n,a,ue]),(0,st.useEffect)(()=>{if(!_)return;J.current=!1;let Z=_.on("submitting",()=>{J.current=!0,Ue({status:"processing",wording:"card",message:null})}),Q=_.on("complete",Ae=>{de("card",Ae.paymentMethod)}),pt=_.on("decline",Ae=>{D("card",{...Ae.declineReason?{reason:Ae.declineReason}:{},...Ae.message?{message:Ae.message}:{}})}),ft=_.on("challenge_dismissed",()=>{Ue(null)});return()=>{Z(),Q(),pt(),ft()}},[_,D,de]);let Le=(0,st.useMemo)(()=>({onSubmitting:()=>{J.current=!0,Ue({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{ue({waitFirst:!1})},onDeclined:Z=>D("payment_method",Z),onFailed:(Z,Q)=>{Se("payment_method",bo(Z,Q))},onValidation:Z=>{Ke(()=>fe.current.onValidation?.(Z))},onAbandoned:()=>{J.current=!1,Ue(null)}}),[D,Se,ue]),oe=Oe?(0,an.jsx)(Ln,{status:Oe.status,errorMessage:Oe.message,...Wc(Oe.wording),successNote:null,...A?{theme:A}:{}}):null;if(le)return(0,an.jsx)("div",{role:"alert",children:le.message});if(!E||C)return(0,an.jsxs)(an.Fragment,{children:[oe,E?null:p]});let{advertisement:We,currency:ut,customer:Be}=E,Je=(0,bn.resolveBillingApiUrl)(o),Ze=a===void 0?{}:{telemetry:a};return(0,an.jsxs)(an.Fragment,{children:[oe,We.card&&_&&q?.html?(0,an.jsx)("div",{"data-flopay-payment-method":"card",children:(0,an.jsx)(so,{capture:_,html:q.html,messageToken:q.messageToken,expectedOrigin:q.expectedOrigin,theme:Ge,containerStyle:ct,onReady:()=>{Ke(()=>fe.current.onReady?.())},onValidation:Z=>{Ke(()=>fe.current.onValidation?.(Z))},onError:Z=>{Z&&Se("card",bo(new Error(Z),{code:"card_setup_widget_failed",retryable:!0}))}})}):null,We.stripe?.methods.map(Z=>(0,an.jsx)("div",{"data-flopay-payment-method":Z,children:(0,an.jsx)(Ii,{onFailed:Le.onFailed,children:(0,an.jsx)(st.Suspense,{fallback:null,children:(0,an.jsx)(e,{method:Z,category:Vc(Z),publishableKey:We.stripe?.publishableKey??"",currency:ut,sessionId:n,nonce:r,billingApiUrl:Je,...Ze,...me?{appearance:me.appearance}:{},...Le})})})},Z)),We.paypal?(0,an.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,an.jsx)(Ii,{onFailed:Le.onFailed,children:(0,an.jsx)(st.Suspense,{fallback:null,children:(0,an.jsx)(t,{clientId:We.paypal.clientId,...We.paypal.environment?{environment:We.paypal.environment}:{},currency:ut,sessionId:n,nonce:r,billingApiUrl:Je,customer:Be,...Ze,...Le})})})}):null]})}var Gc=require("react/jsx-runtime"),fp={StripeSetupMethod:zc,PayPalSetupMethod:Bc};function Kc(e){return(0,Gc.jsx)(Hc,{...e,branches:fp})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|