@flopay/react 1.10.3 → 1.10.4

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 CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var gd=Object.create;var ja=Object.defineProperty;var hd=Object.getOwnPropertyDescriptor;var Pd=Object.getOwnPropertyNames;var bd=Object.getPrototypeOf,vd=Object.prototype.hasOwnProperty;var Cd=(e,t)=>{for(var n in t)ja(e,n,{get:t[n],enumerable:!0})},hl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Pd(t))!vd.call(e,o)&&o!==n&&ja(e,o,{get:()=>t[o],enumerable:!(r=hd(t,o))||r.enumerable});return e};var $i=(e,t,n)=>(n=e!=null?gd(bd(e)):{},hl(t||!e||!e.__esModule?ja(n,"default",{value:e,enumerable:!0}):n,e)),Sd=e=>hl(ja({},"__esModule",{value:!0}),e);var Sp={};Cd(Sp,{DirectPayPalButton:()=>ga,FloPayAutomaticPaymentButton:()=>Mc,FloPayCardSetup:()=>Fc,FloPayCardSetupError:()=>Aa,FloPayCheckout:()=>Ci,FloPayPaymentMethodSetup:()=>Xc,FloPayProvider:()=>Pa,SplitCardForm:()=>hi,VaultCardFields:()=>so,dropThirdPartyOnlyError:()=>Zc.dropThirdPartyOnlyError,useCheckout:()=>Al,useFloPay:()=>Hr,usePayPalFloPay:()=>Ha});module.exports=Sd(Sp);var Zc=require("@flopay/shared");var Si=require("@flopay/js"),ar=require("@flopay/shared"),ct=require("react");var zt=require("react/jsx-runtime");function wd(){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 kd(){return(0,zt.jsx)(zt.Fragment,{children:"Go back"})}function Rd(){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)(wd,{}):e})}function Fo({content:e}){return(0,zt.jsx)(zt.Fragment,{children:e===void 0?(0,zt.jsx)(kd,{}):e})}function da({content:e}){return(0,zt.jsx)(zt.Fragment,{children:e===void 0?(0,zt.jsx)(Rd,{}):e})}var vt=require("@flopay/shared"),Id="Checkout is temporarily unavailable. Please try again later.";function Wi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof vt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function _d(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 Pl(){return new vt.FloPayError(Id,"api_error",{code:"CheckoutInitializationFailed"})}function Hi(e){return!!e?.gateways?.worldpayCorporateGateway}function Zr(e){return e?.status==="open"&&Hi(e)}function bl(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 vl(e,t){if(t&&(!(e instanceof vt.FloPayError)||e.type==="authentication_error"))return Wi(e);if(!(e instanceof vt.FloPayError&&_d(e))){if(!t&&!(e instanceof vt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,vt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof vt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof vt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Bo(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let i={...r,...a,email:a.email?.trim()||r.email?.trim()},c=(0,vt.isCardHolderNamePlaceholder)(i.firstName,i.lastName);if(!(0,vt.isValidEmail)(i.email))return Promise.reject(new vt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[u,g]of Object.entries(i)){if(c&&u.endsWith("Name")||typeof g!="string")continue;let P=g.trim();P&&(p[u]=P)}return o=e.claimCheckoutSession(t,n,{accountData:p}),o.catch(()=>{}),o}}function Cl(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 Ki(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 Sl(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,i)=>a+(i.overrideAmount??i.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,i)=>({uuid:`synthetic-${a.type??"item"}-${i}`,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 yo(e){if((0,vt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Gi(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,i=typeof t=="string"?void 0:t.sessionId;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{},...i?{sessionId:i}:{}}}function Qr(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var Ed=[{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 Ed)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 wl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function $a(e){let t=wl(e);return new vt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Wa(e){return e instanceof vt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Do(e){return wl(e)?new vt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new vt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new vt.FloPayError(vt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function ua(e,t){return e==="processing"||(0,vt.isMoneySettledOutcome)(e,t)}function kl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Rl(e,t){let n=e;if((0,vt.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:i}=await n.retrieveSetupIntent(t);if(i)throw new vt.FloPayError(i.message??"Failed to retrieve setup intent.","api_error",{...i.code?{code:i.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new vt.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function Il(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 Yi(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 pa(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"),it=require("@flopay/shared"),k=$i(require("react"),1);var Xi=require("react"),tr=(0,Xi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Pr=(0,Xi.createContext)({session:null,loading:!1,error:null});var Za=require("@flopay/js"),jt=require("@flopay/shared"),Dl=require("@paypal/paypal-js"),x=require("react");var _l=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(),i=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...i||t?{lastName:i??""}:{}}}function Oo(){let[e,t]=(0,br.useState)(null),n=(0,br.useRef)(null),r=(0,br.useRef)(0),o=(0,br.useCallback)((i,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:i,identity:c}),new Promise(p=>{n.current=p})),[]),a=(0,br.useCallback)(i=>{let c=n.current;n.current=null,t(null),c?.(i)},[]);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[i,c]=(0,br.useState)(e.email?.trim()??""),p=(0,_l.isValidEmail)(i.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:i,onChange:u=>c(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:i.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Td=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),Ad=["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 El(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function fo(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 fo(t.code)??fo(t.type)??fo(t.name)}function No(e){if(!(typeof e!="object"||e===null))return fo(e.decline_code)}function go(e){return typeof e!="object"||e===null?!1:fo(e.type)?.toLowerCase()==="card_error"||No(e)!==void 0}function Md(e){let t=El(e)?.toLowerCase()??"",n=Mr(e)?.toLowerCase()??"";return Td.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 Ji(e){if(Mr(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=El(e)??"";return n.includes("No ack for postMessage init()")&&Ad.some(r=>n.includes(r))&&n.includes("10000ms")}function ro(e,t){if(go(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=Md(e)||t.inAppBrowser&&!t.handoffObserved&&Ji(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 Tl=require("@flopay/shared"),ma=require("react");function Hr(){return(0,ma.useContext)(tr).flopay}function Ha(){return(0,ma.useContext)(tr).paypalFlopay??null}function Al(){return(0,ma.useContext)(Pr)}function Ml(){return(0,ma.useContext)(tr).billingApiUrl||(0,Tl.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 Ka(e,t,n=e.popupCapability){return e.inAppBrowser||n==="blocked"||t==="prefer_redirect"?"redirect":"popup"}function Ga(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var xl=require("@flopay/shared"),Po=require("react");function Xe(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 Ya=require("react"),ho=typeof window>"u"?Ya.useEffect:Ya.useLayoutEffect;var xd={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function Fd(e){return e==="stripe"||e==="paypal"?e:void 0}function Bd(e){let t=Fd(e.provider),n={schemaVersion:xl.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=xd[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 Zi=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function zo(e,t){let n=(0,Po.useRef)(e);n.current=e;let r=(0,Po.useRef)(new Set),o=(0,Po.useRef)(t),a=(0,Po.useRef)(t);return ho(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,Po.useCallback)(i=>{if(a.current!==t)return;let c=Bd(i);if(c){if(Zi.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}Xe(()=>n.current?.(c))}},[t])}var Fl=require("react"),ya=(0,Fl.createContext)(null);function Xa(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Dd=Symbol.for("@flopay/js.telemetry.bridge.v1"),Od=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ld(){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 Nd(e){let t=Ld(),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 Ja(e){let t=globalThis[Od];return Nd(t?.(e)??{})}function pn(e){if(e)return e[Dd]}var tn=require("react");function fa(e,t){let n=(0,tn.useRef)(0),r=(0,tn.useRef)(null),o=(0,tn.useRef)(null),a=(0,tn.useRef)(e),i=(0,tn.useRef)(t?.onHandoffObserved),c=(0,tn.useRef)(t?.defersMissingTerminal),p=(0,tn.useRef)(t?.onMissingTerminalDeferred);(0,tn.useEffect)(()=>{a.current=e,i.current=t?.onHandoffObserved,c.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)},[]),g=(0,tn.useCallback)(b=>{u();let S=n.current+1;return n.current=S,r.current=null,o.current={generation:S,method:b,timer:null,yieldedControl:!1},S},[u]),P=(0,tn.useCallback)(b=>{let S=o.current;return b!==void 0&&S?.generation!==b?!1:(u(S),o.current=null,(b===void 0||r.current===b)&&(r.current=null),!0)},[u]),R=(0,tn.useCallback)(b=>{let S=o.current,W=b??S?.generation??n.current;(b===void 0||S?.generation===b)&&(u(S),o.current=null),r.current=W},[u]),E=(0,tn.useCallback)(b=>r.current===(b??n.current),[]),w=(0,tn.useCallback)(b=>o.current?.generation===b&&r.current!==b,[]),M=(0,tn.useCallback)(()=>{let b=o.current;b&&(u(b),!b.yieldedControl&&(b.yieldedControl=!0,i.current?.(b.method)))},[u]),T=(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(c.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"?T():M()};return document.addEventListener("visibilitychange",b),window.addEventListener("blur",M),window.addEventListener("focus",T),()=>{document.removeEventListener("visibilitychange",b),window.removeEventListener("blur",M),window.removeEventListener("focus",T),u()}},[u,M,T]),{startAttempt:g,finishAttempt:P,invalidateAttempt:R,isAttemptInvalidated:E,isAttemptCurrent:w,generationRef:n}}var nr=require("react/jsx-runtime"),Qa=45,zd=1e3,Ud=11e3,qd={width:"100%",minHeight:Qa,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"},Vd={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 jd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Vd[e.kind]??null}}function Bl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Ji(t)?"paypal_init_timeout":"paypal_init_failure"}function $d(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 Wd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Ol({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:i,environment:c,currency:p,isSubscription:u,providerObjectType:g,approvalPresentation:P,onTokenizedBody:R,onComplete:E,onErrorChange:w,onDecline:M,onTechnicalFailure:T,isProcessing:b=!1,onLoadStateChange:S,onInitializationStateChange:W,allowAutomaticRetry:A=!0,onButtonClick:re,runBeforeButtonClick:V,session:Y,existingOrderId:le,telemetry:H,telemetryContext:Ne,onInstrument:je,debug:oe=!1}){let ze=Hr(),ut=zo(je,e),xe=(0,x.useMemo)(()=>{if(ze)return null;let B=Ja({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:jt.SDK_VERSION,enabled:H!==!1});return B.setCheckoutContext(Ne??{}),B.beginCheckout(Ne??{}),B},[n,ze,H,Ne?.checkoutMode,Ne?.layout]),we=(0,x.useMemo)(()=>pn(ze),[ze]);(0,x.useEffect)(()=>()=>{xe&&xe.flush().catch(()=>{}).finally(()=>xe.destroy())},[xe]);let ve=(0,x.useMemo)(()=>({error:B=>{we?we.error(B):xe?.error(B),ut({class:"technical_error",errorCode:B.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":B.errorCode,requestCategory:B.requestCategory,provider:B.provider})},log:B=>{we?we.log(B):xe?.log(B),ut({class:"lifecycle",name:B.name,provider:B.provider})},performance:B=>{we?we.performance(B):xe?.performance(B)},terminal:B=>{we?we.terminal(B):xe?.terminal(B)},startTiming:()=>we?.now()??xe?.now()??0,elapsed:B=>we?.elapsed(B)??Math.max(0,(xe?.now()??B)-B)}),[ut,we,xe]),de=(0,x.useRef)(null),Te=(0,x.useRef)(0),$e=(0,x.useRef)(null),ot=(0,x.useRef)(null),I=(0,x.useRef)(null),ke=(0,x.useContext)(ya),ge=(0,x.useRef)(null);ge.current||(ge.current=Xa());let j=ke??ge.current,Ee=(0,x.useRef)(null),Q=(0,x.useRef)(!1),[Be,ee]=(0,x.useState)(!1),[Je,st]=(0,x.useState)(!1),[De,et]=(0,x.useState)(0),tt=(0,x.useRef)(0),[pt,Ae]=(0,x.useState)(!1),At=(0,x.useRef)(!1),kt=(0,x.useRef)(!1),[gt,Ct]=(0,x.useState)(!1),[$,he]=(0,x.useState)(!1),{request:Ue,collect:v,finish:J}=Oo(),Fe=(0,x.useRef)({sessionId:e,required:!(0,jt.isValidEmail)(r?.trim()||Y?.customer?.email?.trim())});Fe.current.sessionId!==e&&(Fe.current={sessionId:e,required:!(0,jt.isValidEmail)(r?.trim()||Y?.customer?.email?.trim())});let ue=Fe.current.required,Ce=(0,x.useMemo)(()=>n.replace(/\/+$/,""),[n]),f=Y?.gateways?.paypal?.providerObjectType??g,C=f??(u?"subscription":"order"),[Z]=(0,x.useState)(Kr),K=Y?.gateways?.paypal?.approvalPresentation??P,Pe=Ga(Z,K==="app_switch"?"app_switch":void 0,C),Bt=f==="order"||f==="setup_token",We=(0,x.useMemo)(()=>JSON.stringify([Ce,i,p,c??"",C,Bt,Pe,e,le??""]),[Ce,i,p,c,le,C,Bt,Pe,e]),Ze=(0,x.useRef)(We),Se=Ze.current!==We,bt=(0,x.useRef)(oe),Wt=(0,x.useRef)(null),[Ye,Tn]=(0,x.useState)([]),Re=(0,x.useCallback)(B=>{bt.current&&Tn(lt=>[...lt,`${new Date().toISOString().slice(11,23)} ${B}`])},[]);(0,x.useEffect)(()=>{bt.current=oe,oe&&Re("debug:enabled"),Wt.current?.setEnabled(oe)},[Re,oe]);let zn=(0,x.useRef)(R),Un=(0,x.useRef)(E),Mt=(0,x.useRef)(w),kn=(0,x.useRef)(M),An=(0,x.useRef)(T),Kn=(0,x.useRef)(re),mn=(0,x.useRef)(S),Dt=(0,x.useRef)(W),mt=(0,x.useRef)(a),nt=(0,x.useRef)(V),Rn=(0,x.useRef)(Y),xt=(0,x.useRef)(r),In=(0,x.useRef)(o),yn=(0,x.useRef)(t),Ht=(0,x.useRef)(null),sn=(0,x.useRef)(new Map),Gn=(0,x.useRef)(new Map),Yn=(0,x.useRef)(!1);(0,x.useEffect)(()=>(Yn.current=!0,()=>{Yn.current=!1}),[]),(0,x.useEffect)(()=>{zn.current=R},[R]),(0,x.useEffect)(()=>{mt.current=a},[a]),(0,x.useEffect)(()=>{Un.current=E},[E]),(0,x.useEffect)(()=>{Mt.current=w},[w]),(0,x.useEffect)(()=>{kn.current=M},[M]),(0,x.useEffect)(()=>{An.current=T},[T]),(0,x.useEffect)(()=>{Kn.current=re},[re]),(0,x.useEffect)(()=>{mn.current=S},[S]),(0,x.useEffect)(()=>{Dt.current=W},[W]),(0,x.useEffect)(()=>{nt.current=V},[V]),(0,x.useEffect)(()=>{Rn.current=Y},[Y]),(0,x.useEffect)(()=>{xt.current=r},[r]),(0,x.useEffect)(()=>{In.current=o},[o]),(0,x.useEffect)(()=>{yn.current=t},[t]),(0,x.useEffect)(()=>{tt.current=De},[De]),(0,x.useEffect)(()=>{pt&&Ee.current?.focus()},[pt,De]);let Et=(0,x.useCallback)(()=>{window.setTimeout(()=>{Ee.current?.focus()},0)},[]),St=(0,x.useCallback)(()=>{ee(!1),et(B=>B+1)},[]),vn=(0,x.useCallback)(()=>{Ae(!1),(de.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??de.current)?.focus?.()},[]);(0,x.useEffect)(()=>{!Be||!Q.current||(Q.current=!1,vn())},[vn,Be,De]);let rn=(0,x.useCallback)((B,lt)=>{let ie=lt?.popupBlocked??oo(B);ie&&j.markBlocked();let Sn=no("PayPal",ie,Z.inAppBrowser),fn=An.current;if(fn){let Kt=ie&&Z.inAppBrowser?new jt.FloPayError(Sn,"api_error",{code:lt?.code??"paypal_popup_blocked"}):B;fn("paypal",Kt,lt);return}Mt.current?.(Sn)},[j,Z.inAppBrowser]),Ot=(0,x.useCallback)(B=>{let lt=$e.current,ie=ot.current;lt===null||!ie||(ve.log({...ie,popupCapability:j.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:B}),ve.performance({...ie,popupCapability:j.current(),stage:"overlay_return",durationMs:ve.elapsed(lt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:B}),$e.current=null)},[j,ve]),ln=(0,x.useCallback)((B,lt,ie)=>{let Sn=ot.current;Ot("overlay_timeout"),Sn&&ve.error({...Sn,popupCapability:j.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),rn(lt,{...ie,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Pe,terminalReason:"overlay_timeout"}),Ae(!0),St(),Et()},[Ot,Et,rn,j,Pe,St,ve]),Zt=(0,x.useCallback)(()=>{j.markAvailable();let B=ot.current;B&&(I.current=B.attempt,ve.log({...B,popupCapability:j.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[j,ve]),{finishAttempt:Lt,generationRef:se,invalidateAttempt:cn,isAttemptCurrent:qn,isAttemptInvalidated:Lr,startAttempt:sr}=fa(ln,{onHandoffObserved:Zt}),Ut=(0,x.useCallback)(()=>(Ae(!1),sr("paypal")),[sr]),lr=(0,x.useCallback)(B=>{cn(B?.generation),B?.showRetry&&Ae(!0),B?.remount&&St(),B?.focus!==!1&&Et()},[Et,cn,St]),Cn=B=>{let lt=Ht.current;return lt&&Gn.current.set(B,lt),B};(0,x.useEffect)(()=>{Ze.current!==We&&(Ze.current=We,At.current=!1,kt.current=!1,ee(!1),st(!1),Ct(!1),Dt.current?.("loading"))},[We]),(0,x.useEffect)(()=>{Xe(()=>mn.current?.(Be&&!gt))},[Be,gt]);let Ie=(0,jt.normalizeGatewayEnvironment)(c);(0,x.useEffect)(()=>{let B={attempt:se.current+1,inAppBrowser:Z.inAppBrowser,appFamily:Z.appFamily,popupCapability:j.current(),presentationMode:Pe},lt=()=>({...ot.current??B,popupCapability:j.current()}),ie={error:m=>ve.error({...m,...lt()}),log:m=>ve.log({...m,...lt()}),performance:m=>ve.performance({...m,...lt()}),terminal:m=>ve.terminal({...m,...lt()}),startTiming:ve.startTiming,elapsed:ve.elapsed},Sn=i?`${i.slice(0,6)}\u2026(len ${i.length})`:"(empty)",fn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Re(`mount clientId=${Sn} env=${c??"(unset)"}\u2192${Ie??"live"} ccy=${p} sub=${u}`),Re(`ua=${fn.slice(0,80)}${fn.length>80?"\u2026":""}`),!i){Re("FAIL: clientId empty \u2014 gateway misconfigured"),Ct(!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(!de.current){Re("FAIL: containerRef not attached");return}Te.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=de.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 h=m.getBoundingClientRect();return`${Math.round(h.width)}\xD7${Math.round(h.height)}`},Qn=m=>{if(!m)return"(empty)";try{let h=new URL(m,typeof window>"u"?"https://localhost":window.location.href),U=h.pathname.toLowerCase();return U.includes("checkcaptcha")||U.includes("captcha")?`CAPTCHA(${h.host}${U})`:U.includes("risk")||U.includes("challenge")?`RISK(${h.host}${U})`:U.includes("smart/buttons")?`smart-buttons(${h.host})`:`${h.host}${U}`.slice(0,100)}catch{return m.slice(0,80)}},Rr=m=>{let h=m.getAttribute("src"),U=m.getAttribute("srcdoc"),G=m.getAttribute("name"),fe=m.getAttribute("sandbox"),ae=[];return h&&ae.push(`src=${Qn(h)}`),U&&ae.push(`srcdoc[${U.length}ch]`),!h&&!U&&ae.push("src=(empty) srcdoc=(empty)"),G&&ae.push(`name=${G.slice(0,40)}`),fe!==null&&ae.push(`sandbox="${fe.slice(0,40)}"`),ae.join(" ")},ft=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let h=m.contentDocument;if(!h)return"cd=null";let U=h.body?.children.length??0,G=h.body?.innerHTML.length??0,fe=h.head?.innerHTML.length??0;return`cd=same-origin readyState=${h.readyState} body[${U}children,${G}ch] head[${fe}ch]`}catch(h){return`cd=cross-origin(${h.message.slice(0,30)})`}},on=[],en=m=>{if(yt())return;let h=m.message??String(m.error??"(no message)");h&&(h.toLowerCase().includes("paypal")||h.toLowerCase().includes("zoid")||h.toLowerCase().includes("postrobot")||h.toLowerCase().includes("storage"))&&(Re(`window:error ${h.slice(0,140)}`),on.push(h))},qr=m=>{if(yt())return;let h=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");h&&(h.toLowerCase().includes("paypal")||h.toLowerCase().includes("zoid")||h.toLowerCase().includes("postrobot")||h.toLowerCase().includes("storage"))&&(Re(`window:rejection ${h.slice(0,140)}`),on.push(h))},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 h of m.getEntries()){if(!h.name.toLowerCase().includes("paypal"))continue;Vn.value+=1;let U=Math.round(h.duration);Re(`net ${U}ms ${h.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,bt.current&&ur();let Vr=m=>{if(!m)return!1;let h=m.toLowerCase();return h.includes("zoid destroyed")||h.includes("destroyed all components")||h.includes("window closed")||h.includes("detected container element removed")},En=m=>{if(yt()||Vr(m))return;let h=eo(m)??m;Xe(()=>Mt.current?.(h))},L=(m,h)=>{if(Kt||zr)return;zr=!0,Xn=!0,hn(),Sr();let U=jd({kind:m,generationActive:!0,automaticRetryAllowed:A,automaticRetryUsed:At.current});if(U.action==="retry"){At.current=!0,ee(!1),he(!1),st(!0),Dt.current?.("retrying"),Nr=setTimeout(()=>{Kt||et(G=>G+1)},zd);return}if(ee(!1),he(!1),st(!1),Ct(!0),U.action!=="ignore"){if(Dt.current?.("exhausted"),U.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",h);return}if(U.report){let G=ro({code:Bl(m,h),message:h},{inAppBrowser:Z.inAppBrowser,handoffObserved:!1});G.popupBlocked&&j.markBlocked(),ie.error({errorCode:G.popupBlocked?G.errorCode:U.report.errorCode,stage:U.report.stage,operationOutcome:U.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:G.terminalReason})}kt.current||(kt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Bl(m,h)))}};Ct(!1);let q=async(m,h=Ht.current)=>{if(yt())return;let U=h?.sessionId??e;if(zn.current){await zn.current(m,{sessionId:U,accountPatch:h?.accountPatch,nonce:h?.nonce});return}let G=ie.startTiming();ie.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let fe=()=>{ie.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ie.performance({stage:"processing",durationMs:ie.elapsed(G),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ae=Rn.current,at=h?.accountPatch?.email??xt.current,Rt=h?.accountPatch?.userId??ae?.customer?.id??ae?.accountData?.userId??"",D=h?.accountPatch?.firstName??ae?.customer?.firstName??ae?.accountData?.firstName,Me=h?.accountPatch?.lastName??ae?.customer?.lastName??ae?.accountData?.lastName,_e=await new Za.PaymentAPI(Ce,{telemetry:!1}).processPayment(Rt,{sessionId:U,nonce:h?.nonce??yn.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:Rt,email:at??ae?.customer?.email??"",...D?{firstName:D}:{},...Me?{lastName:Me}:{},country:h?.accountPatch?.country??ae?.customer?.country??ae?.accountData?.country??void 0,zip:h?.accountPatch?.zip??ae?.customer?.zip??ae?.accountData?.zip??void 0}});if(_e.ok){if(Xn||Kt&&Yn.current)return;fe(),ie.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Xe(()=>Un.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(yt())return;let X=await _e.json().catch(()=>null),me=X?.message??"PayPal payment failed.",F=eo(me)??me;fe(),_e.status===400&&(typeof X?.declineCode=="string"||!Array.isArray(X?.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:Wd(_e.status),failureCategory:_e.status>=500?"server_error":void 0}),En(F),Xe(()=>kn.current?.(un("paypal",F,{code:X?.code,declineCode:X?.declineCode})));return}catch(ae){if(yt())return;fe(),ie.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let at=ae instanceof Error?ae.message:"PayPal payment failed.",Rt=eo(at)??at;En(Rt),Xe(()=>kn.current?.(un("paypal",Rt)));return}},O=()=>new jt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ye=m=>yt()?Promise.reject(O()):Promise.resolve(m),He=async m=>{if(yt())throw O();Gt||gn();let h=Ht.current,U=h?.sessionId??e,G=h?.nonce??yn.current;ie.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let fe;try{fe=await new Za.PaymentAPI(Ce,{telemetry:!1}).createSessionIntent(U,G??"",Bt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:jt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:C==="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(fe.provider!=="paypal"||fe.providerObjectType!==C)throw new Error(m);return ie.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),fe.providerObjectId},ht=(m,h)=>{let U=h?.nonce??yn.current;if(!U)return;let G=h?.sessionId??e,fe=No(m)??Mr(m)??"provider_declined";new Za.PaymentAPI(Ce,{telemetry:!1}).reportSessionIntentDecline(G,U,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:fe}).catch(()=>{})},be=De;Re("loadScript:scheduled (deferred 1 tick)");let Ke=null,te=setTimeout(()=>{if(Kt){Re("loadScript:skipped (cancelled before defer ran)");return}Re("loadScript:start");let m=Ie==="live"?"production":Ie,h={};C==="subscription"?h={intent:"subscription",vault:!0}:C==="order"&&(h={intent:"capture"}),Ke=(0,Dl.loadScript)({clientId:i,currency:p,...h,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let U=!1;Ke.then(G=>{if(U=!0,Re(`loadScript:resolved inactive=${yt()} ns=${!!G} buttons=${!!G?.Buttons}`),yt())return;if(!G?.Buttons){Re("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(Te.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ie.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let fe=async(_e,X)=>{if(yt()||tt.current!==be)return;let me=_e.vaultSetupToken??_e.subscriptionID??_e.orderID??"",F=me?Gn.current.get(me):sn.current.get(be);if(!(!F||!qn(F.generation))&&Lt(F.generation)){Gn.current.delete(me),sn.current.delete(F.surfaceKey),Ot("approved");try{if(he(!0),Xe(()=>Mt.current?.(null)),!me)throw new jt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Qe=Rn.current,It=yo(In.current??[Qe?.customer?.firstName,Qe?.customer?.lastName].filter(Boolean).join(" ")),qe=On({email:F.accountPatch?.email?.trim()||xt.current?.trim()||Qe?.customer?.email?.trim(),firstName:F.accountPatch?.firstName?.trim()||It.firstName,lastName:F.accountPatch?.lastName?.trim()||It.lastName});if(!(0,jt.isValidEmail)(qe.email)||!(qe.firstName||qe.lastName))try{let Ir=$d(await X?.order?.get?.());qe=On({email:Ir.email||qe.email,firstName:Ir.firstName||qe.firstName,lastName:Ir.lastName||qe.lastName})}catch{}if((mt.current||ue)&&!(0,jt.isValidEmail)(qe.email)){let Ir=await v("PayPal",qe);if(!Ir)return;qe=Ir}(0,jt.isValidEmail)(qe.email)&&(F.accountPatch=On({...F.accountPatch,...qe}),await mt.current?.(qe));let wn;C==="setup_token"?wn={id:me,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:jt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Bt?wn={id:me,isPaypal:!0,gateway:"paypal",paymentMethodType:jt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:wn={id:me,isPaypal:!0},await q(wn,F)}catch(Qe){En(Qe instanceof Error?Qe.message:"PayPal capture failed.")}finally{yt()||he(!1)}}},ae=_e=>{let X=le?()=>ye(le):()=>He(_e);return async()=>Cn(await X())},at=G.Buttons({style:{layout:"horizontal",height:Qa,tagline:!1},...Pe==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(_e,X)=>{if(yt()){await X.reject();return}gn();let me=nt.current,F={};if(me)try{let qe=await me("paypal");if(yt()){await X.reject();return}if(!qe.proceed){Ht.current=null,sn.current.delete(be),await X.reject();return}F={sessionId:qe.sessionId,accountPatch:qe.accountPatch,nonce:qe.nonce}}catch(qe){Re(`onClick:runBeforeButtonClick rejected msg=${(qe instanceof Error?qe.message:String(qe)).slice(0,120)}`),Ht.current=null,sn.current.delete(be),await X.reject();return}Xe(()=>Kn.current?.("paypal"));let Qe=Ut(),It={generation:Qe,surfaceKey:be,...F};Ht.current=It,sn.current.set(be,It),ot.current={...B,attempt:Qe},await X.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"}),$e.current=ie.startTiming()},createOrder:C==="order"?ae("Failed to create PayPal order."):void 0,createSubscription:C==="subscription"?ae("Failed to create PayPal subscription."):void 0,createVaultSetupToken:C==="setup_token"?async()=>Cn(await He("Failed to create PayPal setup token.")):void 0,onApprove:fe,onCancel:()=>{if(yt())return;let _e=sn.current.get(be)??Ht.current;_e&&sn.current.delete(_e.surfaceKey),Ht.current=null,Ot("cancelled"),ie.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Q.current=!0,lr({generation:_e?.generation,remount:!0,focus:!1})},onError:_e=>{if(yt()||tt.current!==be)return;let X=_e instanceof Error?_e.message:"PayPal failed to render.";if(Re(`onError rendered=${xn} msg=${X.slice(0,120)}`),xn){let me=sn.current.get(be)??Ht.current;if(me&&!qn(me.generation)||!me&&Lr())return;if(Vr(X)){Lt(me?.generation);return}let{errorCode:F,popupBlocked:Qe,providerDeclined:It,terminalReason:qe}=ro(_e,{inAppBrowser:Z.inAppBrowser,handoffObserved:me!=null&&I.current===me.generation});if(Qe&&j.markBlocked(),Ot(qe),It){ie.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:qe}),ht(_e,me),Xe(()=>kn.current?.(un("paypal",X))),me&&sn.current.delete(me.surfaceKey),Ht.current=null,Lt(me?.generation);return}ie.error({errorCode:F,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:qe}),me&&sn.current.delete(me.surfaceKey),Ht.current=null,lr({generation:me?.generation,remount:!0,showRetry:!0,focus:!0}),rn(_e,{code:"paypal_runtime_failed",popupBlocked:Qe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Pe,terminalReason:qe});return}L(Vr(X)?"teardown":"pre_ready_callback",X)}}),Rt=at.isEligible();if(Re(`isEligible=${Rt}`),ie.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Rt){ee(!1),L("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ur=!0,Mn=at,dr=()=>{if(!Zn||Ft||yt()||xn)return;Ft=!0,Re(`container:dims ${_n(Fn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(wr=new MutationObserver(X=>{if(!yt()){for(let me of X)if(me.type==="childList")me.addedNodes.forEach(F=>{if(!(F instanceof Element))return;let Qe=F.tagName.toLowerCase(),It=(F.getAttribute("title")??"").slice(0,40),qe=Qe==="iframe"?` ${Rr(F)}`:"";Re(`child+ ${Qe}${It?` title="${It}"`:""}${qe} dims=${_n(F)}`)});else if(me.type==="attributes"&&me.target instanceof Element){let F=me.target;if(F.tagName.toLowerCase()!=="iframe")continue;let Qe=me.attributeName;(Qe==="src"||Qe==="srcdoc")&&Re(`attr~ iframe ${Qe}=${Qe==="srcdoc"?`[${(F.getAttribute("srcdoc")??"").length}ch]`:Qn(F.getAttribute("src"))} dims=${_n(F)}`)}}}),wr.observe(Fn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let _e=X=>{if(yt()||xn)return;let me=Fn.querySelectorAll("iframe"),F=typeof document<"u"&&"hasStorageAccess"in document;Re(`watchdog:${X} container=${_n(Fn)} children=${Fn.childElementCount} iframes=${me.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${F} paypalNetRequests=${Vn.value}`),me.forEach((Qe,It)=>{let qe=(Qe.getAttribute("title")??"").slice(0,40);Re(` iframe[${It}] ${_n(Qe)}${qe?` title="${qe}"`:""} ${Rr(Qe)}`);let wn=ft(Qe);wn&&Re(` ${wn}`)}),on.length===0&&Re(" (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(),Re("render:start");let Me=ie.startTiming();Jn=setTimeout(()=>{yt()||xn||(Re("watchdog:11s retryable render timeout"),L("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Ud);let Tt=at.render(Fn);(async()=>{try{if(await Tt,Re(`render:resolved inactive=${yt()}`),hn(),yt()){Sr();return}xn=!0,ee(!0),st(!1),Dt.current?.("ready"),ie.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),ie.performance({stage:"checkout_render",durationMs:ie.elapsed(Me),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(_e){let X=_e instanceof Error?_e.message:"PayPal failed to render.";Re(`render:rejected msg=${X.slice(0,120)}`),hn(),L(Vr(X)?"teardown":"render_rejected",X)}})()}).catch(G=>{let fe=G instanceof Error?G.message:"PayPal operation failed.";Re(`provider:failed msg=${fe.slice(0,120)}`);let ae="script_rejected";U&&Vr(fe)?ae="teardown":U&&Ur&&(ae="render_rejected"),L(ae,fe)})},0);return()=>{Kt=!0,clearTimeout(te),Nr&&clearTimeout(Nr),hn(),Wt.current===mr&&(Wt.current=null),Sr(),$e.current=null,ot.current=null}},[A,Ce,i,p,c,C,Pe,Bt,e,le,De,ve,v,ue,Re,Ot]);let pe=oe?(0,nr.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:gt?"#fef2f2":"#f3f4f6",border:`1px solid ${gt?"#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=${Be} failed=${gt})`,Ye.length===0?`
1
+ "use strict";var Id=Object.create;var Ya=Object.defineProperty;var _d=Object.getOwnPropertyDescriptor;var Ed=Object.getOwnPropertyNames;var Td=Object.getPrototypeOf,Ad=Object.prototype.hasOwnProperty;var Md=(e,t)=>{for(var n in t)Ya(e,n,{get:t[n],enumerable:!0})},Al=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ed(t))!Ad.call(e,o)&&o!==n&&Ya(e,o,{get:()=>t[o],enumerable:!(r=_d(t,o))||r.enumerable});return e};var os=(e,t,n)=>(n=e!=null?Id(Td(e)):{},Al(t||!e||!e.__esModule?Ya(n,"default",{value:e,enumerable:!0}):n,e)),xd=e=>Al(Ya({},"__esModule",{value:!0}),e);var Mp={};Md(Mp,{DirectPayPalButton:()=>Ca,FloPayAutomaticPaymentButton:()=>qc,FloPayCardSetup:()=>$c,FloPayCardSetupError:()=>Oa,FloPayCheckout:()=>Fi,FloPayPaymentMethodSetup:()=>id,FloPayProvider:()=>wa,SplitCardForm:()=>Ti,VaultCardFields:()=>uo,dropThirdPartyOnlyError:()=>ld.dropThirdPartyOnlyError,useCheckout:()=>$l,useFloPay:()=>Kr,usePayPalFloPay:()=>Za});module.exports=xd(Mp);var ld=require("@flopay/shared");var Bi=require("@flopay/js"),lr=require("@flopay/shared"),dt=require("react");var zt=require("react/jsx-runtime");function Fd(){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 Bd(){return(0,zt.jsx)(zt.Fragment,{children:"Go back"})}function Dd(){return(0,zt.jsx)(zt.Fragment,{children:"Secure card checkout"})}function Bo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Do({content:e}){return(0,zt.jsx)(zt.Fragment,{children:e===void 0?(0,zt.jsx)(Fd,{}):e})}function Oo({content:e}){return(0,zt.jsx)(zt.Fragment,{children:e===void 0?(0,zt.jsx)(Bd,{}):e})}function fa({content:e}){return(0,zt.jsx)(zt.Fragment,{children:e===void 0?(0,zt.jsx)(Dd,{}):e})}var Ct=require("@flopay/shared"),Od="Checkout is temporarily unavailable. Please try again later.";function as(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Ct.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Ld(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function Ml(){return new Ct.FloPayError(Od,"api_error",{code:"CheckoutInitializationFailed"})}function is(e){return!!e?.gateways?.worldpayCorporateGateway}function to(e){return e?.status==="open"&&is(e)}function xl(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")||to(r))||t&&e?.data.paypal?.publishableKey)}function Fl(e,t){if(t&&(!(e instanceof Ct.FloPayError)||e.type==="authentication_error"))return as(e);if(!(e instanceof Ct.FloPayError&&Ld(e))){if(!t&&!(e instanceof Ct.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,Ct.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Ct.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Ct.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Lo(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let i={...r,...a,email:a.email?.trim()||r.email?.trim()},c=(0,Ct.isCardHolderNamePlaceholder)(i.firstName,i.lastName);if(!(0,Ct.isValidEmail)(i.email))return Promise.reject(new Ct.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[u,h]of Object.entries(i)){if(c&&u.endsWith("Name")||typeof h!="string")continue;let v=h.trim();v&&(p[u]=v)}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 ss(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 Dl(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,i)=>a+(i.overrideAmount??i.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,i)=>({uuid:`synthetic-${a.type??"item"}-${i}`,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 go(e){if((0,Ct.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function ls(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,i=typeof t=="string"?void 0:t.sessionId;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{},...i?{sessionId:i}:{}}}function no(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var Nd=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function ro(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Nd)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 Hr(e){return e?.status==="authorized"||e?.status==="complete"}function oo(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 Ol(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Xa(e){let t=Ol(e);return new Ct.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Ja(e){return e instanceof Ct.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function No(e){return Ol(e)?new Ct.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Ct.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Ct.FloPayError(Ct.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function ga(e,t){return e==="processing"||(0,Ct.isMoneySettledOutcome)(e,t)}function Ll(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Nl(e,t){let n=e;if((0,Ct.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:i}=await n.retrieveSetupIntent(t);if(i)throw new Ct.FloPayError(i.message??"Failed to retrieve setup intent.","api_error",{...i.code?{code:i.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new Ct.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function zl(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 cs(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 ha(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Jr=require("@flopay/js"),it=require("@flopay/shared"),k=os(require("react"),1);var ds=require("react"),or=(0,ds.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),vr=(0,ds.createContext)({session:null,loading:!1,error:null});var oi=require("@flopay/js"),$t=require("@flopay/shared"),Gl=require("@paypal/paypal-js"),F=require("react");var Ul=require("@flopay/shared"),Cr=require("react"),Wr=require("react/jsx-runtime");function zn(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),i=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...i||t?{lastName:i??""}:{}}}function zo(){let[e,t]=(0,Cr.useState)(null),n=(0,Cr.useRef)(null),r=(0,Cr.useRef)(0),o=(0,Cr.useCallback)((i,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:i,identity:c}),new Promise(p=>{n.current=p})),[]),a=(0,Cr.useCallback)(i=>{let c=n.current;n.current=null,t(null),c?.(i)},[]);return(0,Cr.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Uo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[i,c]=(0,Cr.useState)(e.email?.trim()??""),p=(0,Ul.isValidEmail)(i.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:i,onChange:u=>c(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(zn({...e,email:i.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var zd=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),Ud=["https://www.paypal.com","https://www.sandbox.paypal.com"];function ao(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 ql(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 ho(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Fr(e){if(typeof e!="object"||e===null)return;let t=e;return ho(t.code)??ho(t.type)??ho(t.name)}function qo(e){if(!(typeof e!="object"||e===null))return ho(e.decline_code)}function bo(e){return typeof e!="object"||e===null?!1:ho(e.type)?.toLowerCase()==="card_error"||qo(e)!==void 0}function qd(e){let t=ql(e)?.toLowerCase()??"",n=Fr(e)?.toLowerCase()??"";return zd.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 us(e){if(Fr(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=ql(e)??"";return n.includes("No ack for postMessage init()")&&Ud.some(r=>n.includes(r))&&n.includes("10000ms")}function io(e,t){if(bo(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=qd(e)||t.inAppBrowser&&!t.handoffObserved&&us(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function so(e){return io(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}var Vl=require("@flopay/shared"),ba=require("react");function Kr(){return(0,ba.useContext)(or).flopay}function Za(){return(0,ba.useContext)(or).paypalFlopay??null}function $l(){return(0,ba.useContext)(vr)}function jl(){return(0,ba.useContext)(or).billingApiUrl||(0,Vl.resolveBillingApiUrl)()}function Gr(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 Qa(e,t,n=e.popupCapability){return e.inAppBrowser||n==="blocked"||t==="prefer_redirect"?"redirect":"popup"}function ei(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var Hl=require("@flopay/shared"),vo=require("react");function Je(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 ti=require("react"),Po=typeof window>"u"?ti.useEffect:ti.useLayoutEffect;var Vd={"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 $d(e){return e==="stripe"||e==="paypal"?e:void 0}function jd(e){let t=$d(e.provider),n={schemaVersion:Hl.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Vd[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 ps=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Vo(e,t){let n=(0,vo.useRef)(e);n.current=e;let r=(0,vo.useRef)(new Set),o=(0,vo.useRef)(t),a=(0,vo.useRef)(t);return Po(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,vo.useCallback)(i=>{if(a.current!==t)return;let c=jd(i);if(c){if(ps.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}Je(()=>n.current?.(c))}},[t])}var Wl=require("react"),Pa=(0,Wl.createContext)(null);function ni(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Hd=Symbol.for("@flopay/js.telemetry.bridge.v1"),Wd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Kd(){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 Gd(e){let t=Kd(),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 ri(e){let t=globalThis[Wd];return Gd(t?.(e)??{})}function pn(e){if(e)return e[Hd]}var nn=require("react");function va(e,t){let n=(0,nn.useRef)(0),r=(0,nn.useRef)(null),o=(0,nn.useRef)(null),a=(0,nn.useRef)(e),i=(0,nn.useRef)(t?.onHandoffObserved),c=(0,nn.useRef)(t?.defersMissingTerminal),p=(0,nn.useRef)(t?.onMissingTerminalDeferred);(0,nn.useEffect)(()=>{a.current=e,i.current=t?.onHandoffObserved,c.current=t?.defersMissingTerminal,p.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let u=(0,nn.useCallback)((P=o.current)=>{P?.timer&&(clearTimeout(P.timer),P.timer=null)},[]),h=(0,nn.useCallback)(P=>{u();let C=n.current+1;return n.current=C,r.current=null,o.current={generation:C,method:P,timer:null,yieldedControl:!1},C},[u]),v=(0,nn.useCallback)(P=>{let C=o.current;return P!==void 0&&C?.generation!==P?!1:(u(C),o.current=null,(P===void 0||r.current===P)&&(r.current=null),!0)},[u]),E=(0,nn.useCallback)(P=>{let C=o.current,H=P??C?.generation??n.current;(P===void 0||C?.generation===P)&&(u(C),o.current=null),r.current=H},[u]),T=(0,nn.useCallback)(P=>r.current===(P??n.current),[]),w=(0,nn.useCallback)(P=>o.current?.generation===P&&r.current!==P,[]),x=(0,nn.useCallback)(()=>{let P=o.current;P&&(u(P),!P.yieldedControl&&(P.yieldedControl=!0,i.current?.(P.method)))},[u]),A=(0,nn.useCallback)(()=>{let P=o.current;!P?.yieldedControl||document.visibilityState!=="visible"||(u(P),P.timer=setTimeout(()=>{if(P.timer=null,o.current?.generation===P.generation){if(c.current?.(P.method)){p.current?.(P.method,P.generation);return}o.current=null,r.current=P.generation,a.current(P.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},600))},[u]);return(0,nn.useEffect)(()=>{let P=()=>{document.visibilityState==="visible"?A():x()};return document.addEventListener("visibilitychange",P),window.addEventListener("blur",x),window.addEventListener("focus",A),()=>{document.removeEventListener("visibilitychange",P),window.removeEventListener("blur",x),window.removeEventListener("focus",A),u()}},[u,x,A]),{startAttempt:h,finishAttempt:v,invalidateAttempt:E,isAttemptInvalidated:T,isAttemptCurrent:w,generationRef:n}}var ar=require("react/jsx-runtime"),ai=45,Yd=1e3,Xd=11e3,Jd={width:"100%",minHeight:ai,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 Qd(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 Kl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":us(t)?"paypal_init_timeout":"paypal_init_failure"}function eu(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 tu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Yl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:i,environment:c,currency:p,isSubscription:u,providerObjectType:h,approvalPresentation:v,onTokenizedBody:E,onComplete:T,onErrorChange:w,onDecline:x,onTechnicalFailure:A,isProcessing:P=!1,onLoadStateChange:C,onInitializationStateChange:H,allowAutomaticRetry:I=!0,onButtonClick:se,runBeforeButtonClick:j,session:ee,existingOrderId:we,telemetry:ne,telemetryContext:Ee,onInstrument:We,debug:oe=!1}){let xe=Kr(),Ze=Vo(We,e),ke=(0,F.useMemo)(()=>{if(xe)return null;let D=ri({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:$t.SDK_VERSION,enabled:ne!==!1});return D.setCheckoutContext(Ee??{}),D.beginCheckout(Ee??{}),D},[n,xe,ne,Ee?.checkoutMode,Ee?.layout]),Ie=(0,F.useMemo)(()=>pn(xe),[xe]);(0,F.useEffect)(()=>()=>{ke&&ke.flush().catch(()=>{}).finally(()=>ke.destroy())},[ke]);let ge=(0,F.useMemo)(()=>({error:D=>{Ie?Ie.error(D):ke?.error(D),Ze({class:"technical_error",errorCode:D.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":D.errorCode,requestCategory:D.requestCategory,provider:D.provider})},log:D=>{Ie?Ie.log(D):ke?.log(D),Ze({class:"lifecycle",name:D.name,provider:D.provider})},performance:D=>{Ie?Ie.performance(D):ke?.performance(D)},terminal:D=>{Ie?Ie.terminal(D):ke?.terminal(D)},startTiming:()=>Ie?.now()??ke?.now()??0,elapsed:D=>Ie?.elapsed(D)??Math.max(0,(ke?.now()??D)-D)}),[Ze,Ie,ke]),ue=(0,F.useRef)(null),ae=(0,F.useRef)(0),be=(0,F.useRef)(null),_e=(0,F.useRef)(null),R=(0,F.useRef)(null),Re=(0,F.useContext)(Pa),Ce=(0,F.useRef)(null);Ce.current||(Ce.current=ni());let V=Re??Ce.current,Fe=(0,F.useRef)(null),X=(0,F.useRef)(!1),[Le,Q]=(0,F.useState)(!1),[Ke,st]=(0,F.useState)(!1),[Ne,tt]=(0,F.useState)(0),nt=(0,F.useRef)(0),[pt,Be]=(0,F.useState)(!1),At=(0,F.useRef)(!1),Bt=(0,F.useRef)(!1),[gt,St]=(0,F.useState)(!1),[$,ye]=(0,F.useState)(!1),{request:Qe,collect:Z,finish:ze}=zo(),ft=(0,F.useRef)({sessionId:e,required:!(0,$t.isValidEmail)(r?.trim()||ee?.customer?.email?.trim())});ft.current.sessionId!==e&&(ft.current={sessionId:e,required:!(0,$t.isValidEmail)(r?.trim()||ee?.customer?.email?.trim())});let Ve=ft.current.required,vt=(0,F.useMemo)(()=>n.replace(/\/+$/,""),[n]),b=ee?.gateways?.paypal?.providerObjectType??h,S=b??(u?"subscription":"order"),[Y]=(0,F.useState)(Gr),y=ee?.gateways?.paypal?.approvalPresentation??v,M=ei(Y,y==="app_switch"?"app_switch":void 0,S),De=b==="order"||b==="setup_token",ie=(0,F.useMemo)(()=>JSON.stringify([vt,i,p,c??"",S,De,M,e,we??""]),[vt,i,p,c,we,S,De,M,e]),J=(0,F.useRef)(ie),le=J.current!==ie,lt=(0,F.useRef)(oe),Ht=(0,F.useRef)(null),[Xe,xn]=(0,F.useState)([]),Te=(0,F.useCallback)(D=>{lt.current&&xn(ct=>[...ct,`${new Date().toISOString().slice(11,23)} ${D}`])},[]);(0,F.useEffect)(()=>{lt.current=oe,oe&&Te("debug:enabled"),Ht.current?.setEnabled(oe)},[Te,oe]);let Vn=(0,F.useRef)(E),$n=(0,F.useRef)(T),Mt=(0,F.useRef)(w),In=(0,F.useRef)(x),Fn=(0,F.useRef)(A),Xn=(0,F.useRef)(se),yn=(0,F.useRef)(C),Dt=(0,F.useRef)(H),mt=(0,F.useRef)(a),rt=(0,F.useRef)(j),_n=(0,F.useRef)(ee),xt=(0,F.useRef)(r),En=(0,F.useRef)(o),fn=(0,F.useRef)(t),Wt=(0,F.useRef)(null),sn=(0,F.useRef)(new Map),Jn=(0,F.useRef)(new Map),Zn=(0,F.useRef)(!1);(0,F.useEffect)(()=>(Zn.current=!0,()=>{Zn.current=!1}),[]),(0,F.useEffect)(()=>{Vn.current=E},[E]),(0,F.useEffect)(()=>{mt.current=a},[a]),(0,F.useEffect)(()=>{$n.current=T},[T]),(0,F.useEffect)(()=>{Mt.current=w},[w]),(0,F.useEffect)(()=>{In.current=x},[x]),(0,F.useEffect)(()=>{Fn.current=A},[A]),(0,F.useEffect)(()=>{Xn.current=se},[se]),(0,F.useEffect)(()=>{yn.current=C},[C]),(0,F.useEffect)(()=>{Dt.current=H},[H]),(0,F.useEffect)(()=>{rt.current=j},[j]),(0,F.useEffect)(()=>{_n.current=ee},[ee]),(0,F.useEffect)(()=>{xt.current=r},[r]),(0,F.useEffect)(()=>{En.current=o},[o]),(0,F.useEffect)(()=>{fn.current=t},[t]),(0,F.useEffect)(()=>{nt.current=Ne},[Ne]),(0,F.useEffect)(()=>{pt&&Fe.current?.focus()},[pt,Ne]);let Et=(0,F.useCallback)(()=>{window.setTimeout(()=>{Fe.current?.focus()},0)},[]),wt=(0,F.useCallback)(()=>{Q(!1),tt(D=>D+1)},[]),Cn=(0,F.useCallback)(()=>{Be(!1),(ue.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ue.current)?.focus?.()},[]);(0,F.useEffect)(()=>{!Le||!X.current||(X.current=!1,Cn())},[Cn,Le,Ne]);let on=(0,F.useCallback)((D,ct)=>{let de=ct?.popupBlocked??so(D);de&&V.markBlocked();let wn=ao("PayPal",de,Y.inAppBrowser),gn=Fn.current;if(gn){let Kt=de&&Y.inAppBrowser?new $t.FloPayError(wn,"api_error",{code:ct?.code??"paypal_popup_blocked"}):D;gn("paypal",Kt,ct);return}Mt.current?.(wn)},[V,Y.inAppBrowser]),Ot=(0,F.useCallback)(D=>{let ct=be.current,de=_e.current;ct===null||!de||(ge.log({...de,popupCapability:V.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:D}),ge.performance({...de,popupCapability:V.current(),stage:"overlay_return",durationMs:ge.elapsed(ct),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:D}),be.current=null)},[V,ge]),ln=(0,F.useCallback)((D,ct,de)=>{let wn=_e.current;Ot("overlay_timeout"),wn&&ge.error({...wn,popupCapability:V.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),on(ct,{...de,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:M,terminalReason:"overlay_timeout"}),Be(!0),wt(),Et()},[Ot,Et,on,V,M,wt,ge]),Qt=(0,F.useCallback)(()=>{V.markAvailable();let D=_e.current;D&&(R.current=D.attempt,ge.log({...D,popupCapability:V.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[V,ge]),{finishAttempt:Lt,generationRef:pe,invalidateAttempt:cn,isAttemptCurrent:jn,isAttemptInvalidated:Nr,startAttempt:cr}=va(ln,{onHandoffObserved:Qt}),Ut=(0,F.useCallback)(()=>(Be(!1),cr("paypal")),[cr]),dr=(0,F.useCallback)(D=>{cn(D?.generation),D?.showRetry&&Be(!0),D?.remount&&wt(),D?.focus!==!1&&Et()},[Et,cn,wt]),Sn=D=>{let ct=Wt.current;return ct&&Jn.current.set(D,ct),D};(0,F.useEffect)(()=>{J.current!==ie&&(J.current=ie,At.current=!1,Bt.current=!1,Q(!1),st(!1),St(!1),Dt.current?.("loading"))},[ie]),(0,F.useEffect)(()=>{Je(()=>yn.current?.(Le&&!gt))},[Le,gt]);let Ae=(0,$t.normalizeGatewayEnvironment)(c);(0,F.useEffect)(()=>{let D={attempt:pe.current+1,inAppBrowser:Y.inAppBrowser,appFamily:Y.appFamily,popupCapability:V.current(),presentationMode:M},ct=()=>({..._e.current??D,popupCapability:V.current()}),de={error:m=>ge.error({...m,...ct()}),log:m=>ge.log({...m,...ct()}),performance:m=>ge.performance({...m,...ct()}),terminal:m=>ge.terminal({...m,...ct()}),startTiming:ge.startTiming,elapsed:ge.elapsed},wn=i?`${i.slice(0,6)}\u2026(len ${i.length})`:"(empty)",gn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Te(`mount clientId=${wn} env=${c??"(unset)"}\u2192${Ae??"live"} ccy=${p} sub=${u}`),Te(`ua=${gn.slice(0,80)}${gn.length>80?"\u2026":""}`),!i){Te("FAIL: clientId empty \u2014 gateway misconfigured"),St(!0),de.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(!ue.current){Te("FAIL: containerRef not attached");return}ae.current=de.startTiming(),de.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Kt=!1,Qn=!1,yt=()=>Kt||Qn,Qr,Gt=!1,hn=()=>{Qr=(0,$t.generateIdempotencyKey)(),Qr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Gt=!0},zr=null,Ur=!1,Bn=null,en=!1,kr=()=>{!Bn||en||(en=!0,Bn.close().catch(()=>{}))},Dn=!1,qr=!1,On=ue.current,Rr=null,Ir=null,ur=[],er=null,tr=!1,Ft=!1,pr=null,Tn=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let g=m.getBoundingClientRect();return`${Math.round(g.width)}\xD7${Math.round(g.height)}`},nr=m=>{if(!m)return"(empty)";try{let g=new URL(m,typeof window>"u"?"https://localhost":window.location.href),U=g.pathname.toLowerCase();return U.includes("checkcaptcha")||U.includes("captcha")?`CAPTCHA(${g.host}${U})`:U.includes("risk")||U.includes("challenge")?`RISK(${g.host}${U})`:U.includes("smart/buttons")?`smart-buttons(${g.host})`:`${g.host}${U}`.slice(0,100)}catch{return m.slice(0,80)}},_r=m=>{let g=m.getAttribute("src"),U=m.getAttribute("srcdoc"),W=m.getAttribute("name"),ve=m.getAttribute("sandbox"),ce=[];return g&&ce.push(`src=${nr(g)}`),U&&ce.push(`srcdoc[${U.length}ch]`),!g&&!U&&ce.push("src=(empty) srcdoc=(empty)"),W&&ce.push(`name=${W.slice(0,40)}`),ve!==null&&ce.push(`sandbox="${ve.slice(0,40)}"`),ce.join(" ")},ht=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let g=m.contentDocument;if(!g)return"cd=null";let U=g.body?.children.length??0,W=g.body?.innerHTML.length??0,ve=g.head?.innerHTML.length??0;return`cd=same-origin readyState=${g.readyState} body[${U}children,${W}ch] head[${ve}ch]`}catch(g){return`cd=cross-origin(${g.message.slice(0,30)})`}},an=[],tn=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"))&&(Te(`window:error ${g.slice(0,140)}`),an.push(g))},Vr=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"))&&(Te(`window:rejection ${g.slice(0,140)}`),an.push(g))},Hn={value:0},eo=()=>{Rr?.disconnect(),Rr=null,Ir?.disconnect(),Ir=null;for(let m of ur.splice(0))clearTimeout(m);Ft=!1,tr&&typeof window<"u"&&(window.removeEventListener("error",tn),window.removeEventListener("unhandledrejection",Vr)),tr=!1},mr=()=>{if(!(tr||yt()||Dn)){if(tr=!0,an.length=0,Hn.value=0,typeof window<"u"&&(window.addEventListener("error",tn),window.addEventListener("unhandledrejection",Vr)),typeof PerformanceObserver<"u")try{Ir=new PerformanceObserver(m=>{if(!yt())for(let g of m.getEntries()){if(!g.name.toLowerCase().includes("paypal"))continue;Hn.value+=1;let U=Math.round(g.duration);Te(`net ${U}ms ${g.name.slice(0,90)}`)}}),Ir.observe({type:"resource",buffered:!0})}catch{}pr?.()}},yr=()=>{er&&(clearTimeout(er),er=null)},bn=()=>{eo(),yr()},fr={setEnabled:m=>{m?mr():eo()}};Ht.current=fr,lt.current&&mr();let $r=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")},An=m=>{if(yt()||$r(m))return;let g=ro(m)??m;Je(()=>Mt.current?.(g))},N=(m,g)=>{if(Kt||Ur)return;Ur=!0,Qn=!0,bn(),kr();let U=Qd({kind:m,generationActive:!0,automaticRetryAllowed:I,automaticRetryUsed:At.current});if(U.action==="retry"){At.current=!0,Q(!1),ye(!1),st(!0),Dt.current?.("retrying"),zr=setTimeout(()=>{Kt||tt(W=>W+1)},Yd);return}if(Q(!1),ye(!1),st(!1),St(!0),U.action!=="ignore"){if(Dt.current?.("exhausted"),U.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",g);return}if(U.report){let W=io({code:Kl(m,g),message:g},{inAppBrowser:Y.inAppBrowser,handoffObserved:!1});W.popupBlocked&&V.markBlocked(),de.error({errorCode:W.popupBlocked?W.errorCode:U.report.errorCode,stage:U.report.stage,operationOutcome:U.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:W.terminalReason})}Bt.current||(Bt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Kl(m,g)))}};St(!1);let q=async(m,g=Wt.current)=>{if(yt())return;let U=g?.sessionId??e;if(Vn.current){await Vn.current(m,{sessionId:U,accountPatch:g?.accountPatch,nonce:g?.nonce});return}let W=de.startTiming();de.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ve=()=>{de.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),de.performance({stage:"processing",durationMs:de.elapsed(W),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ce=_n.current,at=g?.accountPatch?.email??xt.current,Rt=g?.accountPatch?.userId??ce?.customer?.id??ce?.accountData?.userId??"",O=g?.accountPatch?.firstName??ce?.customer?.firstName??ce?.accountData?.firstName,Oe=g?.accountPatch?.lastName??ce?.customer?.lastName??ce?.accountData?.lastName,Me=await new oi.PaymentAPI(vt,{telemetry:!1}).processPayment(Rt,{sessionId:U,nonce:g?.nonce??fn.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:Rt,email:at??ce?.customer?.email??"",...O?{firstName:O}:{},...Oe?{lastName:Oe}:{},country:g?.accountPatch?.country??ce?.customer?.country??ce?.accountData?.country??void 0,zip:g?.accountPatch?.zip??ce?.customer?.zip??ce?.accountData?.zip??void 0}});if(Me.ok){if(Qn||Kt&&Zn.current)return;ve(),de.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Je(()=>$n.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(yt())return;let K=await Me.json().catch(()=>null),he=K?.message??"PayPal payment failed.",B=ro(he)??he;ve(),Me.status===400&&(typeof K?.declineCode=="string"||!Array.isArray(K?.fields))?de.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Me.status===400||Me.status===422?de.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):de.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:tu(Me.status),failureCategory:Me.status>=500?"server_error":void 0}),An(B),Je(()=>In.current?.(un("paypal",B,{code:K?.code,declineCode:K?.declineCode})));return}catch(ce){if(yt())return;ve(),de.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let at=ce instanceof Error?ce.message:"PayPal payment failed.",Rt=ro(at)??at;An(Rt),Je(()=>In.current?.(un("paypal",Rt)));return}},L=()=>new $t.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Pe=m=>yt()?Promise.reject(L()):Promise.resolve(m),Ge=async m=>{if(yt())throw L();Gt||hn();let g=Wt.current,U=g?.sessionId??e,W=g?.nonce??fn.current;de.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ve;try{ve=await new oi.PaymentAPI(vt,{telemetry:!1}).createSessionIntent(U,W??"",De?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:$t.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:S==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Qr})}catch(ce){throw de.error({...(0,$t.classifyTelemetryFailure)(ce,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ce}if(yt())throw L();if(ve.provider!=="paypal"||ve.providerObjectType!==S)throw new Error(m);return de.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ve.providerObjectId},bt=(m,g)=>{let U=g?.nonce??fn.current;if(!U)return;let W=g?.sessionId??e,ve=qo(m)??Fr(m)??"provider_declined";new oi.PaymentAPI(vt,{telemetry:!1}).reportSessionIntentDecline(W,U,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ve}).catch(()=>{})},Se=Ne;Te("loadScript:scheduled (deferred 1 tick)");let Ye=null,te=setTimeout(()=>{if(Kt){Te("loadScript:skipped (cancelled before defer ran)");return}Te("loadScript:start");let m=Ae==="live"?"production":Ae,g={};S==="subscription"?g={intent:"subscription",vault:!0}:S==="order"&&(g={intent:"capture"}),Ye=(0,Gl.loadScript)({clientId:i,currency:p,...g,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let U=!1;Ye.then(W=>{if(U=!0,Te(`loadScript:resolved inactive=${yt()} ns=${!!W} buttons=${!!W?.Buttons}`),yt())return;if(!W?.Buttons){Te("FAIL: namespace missing Buttons factory"),N("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}de.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),de.performance({stage:"provider_ready",durationMs:de.elapsed(ae.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),de.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let ve=async(Me,K)=>{if(yt()||nt.current!==Se)return;let he=Me.vaultSetupToken??Me.subscriptionID??Me.orderID??"",B=he?Jn.current.get(he):sn.current.get(Se);if(!(!B||!jn(B.generation))&&Lt(B.generation)){Jn.current.delete(he),sn.current.delete(B.surfaceKey),Ot("approved");try{if(ye(!0),Je(()=>Mt.current?.(null)),!he)throw new $t.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let et=_n.current,It=go(En.current??[et?.customer?.firstName,et?.customer?.lastName].filter(Boolean).join(" ")),je=zn({email:B.accountPatch?.email?.trim()||xt.current?.trim()||et?.customer?.email?.trim(),firstName:B.accountPatch?.firstName?.trim()||It.firstName,lastName:B.accountPatch?.lastName?.trim()||It.lastName});if(!(0,$t.isValidEmail)(je.email)||!(je.firstName||je.lastName))try{let Er=eu(await K?.order?.get?.());je=zn({email:Er.email||je.email,firstName:Er.firstName||je.firstName,lastName:Er.lastName||je.lastName})}catch{}if((mt.current||Ve)&&!(0,$t.isValidEmail)(je.email)){let Er=await Z("PayPal",je);if(!Er)return;je=Er}(0,$t.isValidEmail)(je.email)&&(B.accountPatch=zn({...B.accountPatch,...je}),await mt.current?.(je));let kn;S==="setup_token"?kn={id:he,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:$t.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:De?kn={id:he,isPaypal:!0,gateway:"paypal",paymentMethodType:$t.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:kn={id:he,isPaypal:!0},await q(kn,B)}catch(et){An(et instanceof Error?et.message:"PayPal capture failed.")}finally{yt()||ye(!1)}}},ce=Me=>{let K=we?()=>Pe(we):()=>Ge(Me);return async()=>Sn(await K())},at=W.Buttons({style:{layout:"horizontal",height:ai,tagline:!1},...M==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Me,K)=>{if(yt()){await K.reject();return}hn();let he=rt.current,B={};if(he)try{let je=await he("paypal");if(yt()){await K.reject();return}if(!je.proceed){Wt.current=null,sn.current.delete(Se),await K.reject();return}B={sessionId:je.sessionId,accountPatch:je.accountPatch,nonce:je.nonce}}catch(je){Te(`onClick:runBeforeButtonClick rejected msg=${(je instanceof Error?je.message:String(je)).slice(0,120)}`),Wt.current=null,sn.current.delete(Se),await K.reject();return}Je(()=>Xn.current?.("paypal"));let et=Ut(),It={generation:et,surfaceKey:Se,...B};Wt.current=It,sn.current.set(Se,It),_e.current={...D,attempt:et},await K.resolve(),de.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),de.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),be.current=de.startTiming()},createOrder:S==="order"?ce("Failed to create PayPal order."):void 0,createSubscription:S==="subscription"?ce("Failed to create PayPal subscription."):void 0,createVaultSetupToken:S==="setup_token"?async()=>Sn(await Ge("Failed to create PayPal setup token.")):void 0,onApprove:ve,onCancel:()=>{if(yt())return;let Me=sn.current.get(Se)??Wt.current;Me&&sn.current.delete(Me.surfaceKey),Wt.current=null,Ot("cancelled"),de.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),X.current=!0,dr({generation:Me?.generation,remount:!0,focus:!1})},onError:Me=>{if(yt()||nt.current!==Se)return;let K=Me instanceof Error?Me.message:"PayPal failed to render.";if(Te(`onError rendered=${Dn} msg=${K.slice(0,120)}`),Dn){let he=sn.current.get(Se)??Wt.current;if(he&&!jn(he.generation)||!he&&Nr())return;if($r(K)){Lt(he?.generation);return}let{errorCode:B,popupBlocked:et,providerDeclined:It,terminalReason:je}=io(Me,{inAppBrowser:Y.inAppBrowser,handoffObserved:he!=null&&R.current===he.generation});if(et&&V.markBlocked(),Ot(je),It){de.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:je}),bt(Me,he),Je(()=>In.current?.(un("paypal",K))),he&&sn.current.delete(he.surfaceKey),Wt.current=null,Lt(he?.generation);return}de.error({errorCode:B,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:je}),he&&sn.current.delete(he.surfaceKey),Wt.current=null,dr({generation:he?.generation,remount:!0,showRetry:!0,focus:!0}),on(Me,{code:"paypal_runtime_failed",popupBlocked:et,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:M,terminalReason:je});return}N($r(K)?"teardown":"pre_ready_callback",K)}}),Rt=at.isEligible();if(Te(`isEligible=${Rt}`),de.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Rt){Q(!1),N("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}qr=!0,Bn=at,pr=()=>{if(!tr||Ft||yt()||Dn)return;Ft=!0,Te(`container:dims ${Tn(On)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Rr=new MutationObserver(K=>{if(!yt()){for(let he of K)if(he.type==="childList")he.addedNodes.forEach(B=>{if(!(B instanceof Element))return;let et=B.tagName.toLowerCase(),It=(B.getAttribute("title")??"").slice(0,40),je=et==="iframe"?` ${_r(B)}`:"";Te(`child+ ${et}${It?` title="${It}"`:""}${je} dims=${Tn(B)}`)});else if(he.type==="attributes"&&he.target instanceof Element){let B=he.target;if(B.tagName.toLowerCase()!=="iframe")continue;let et=he.attributeName;(et==="src"||et==="srcdoc")&&Te(`attr~ iframe ${et}=${et==="srcdoc"?`[${(B.getAttribute("srcdoc")??"").length}ch]`:nr(B.getAttribute("src"))} dims=${Tn(B)}`)}}}),Rr.observe(On,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Me=K=>{if(yt()||Dn)return;let he=On.querySelectorAll("iframe"),B=typeof document<"u"&&"hasStorageAccess"in document;Te(`watchdog:${K} container=${Tn(On)} children=${On.childElementCount} iframes=${he.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${B} paypalNetRequests=${Hn.value}`),he.forEach((et,It)=>{let je=(et.getAttribute("title")??"").slice(0,40);Te(` iframe[${It}] ${Tn(et)}${je?` title="${je}"`:""} ${_r(et)}`);let kn=ht(et);kn&&Te(` ${kn}`)}),an.length===0&&Te(" (no PayPal/zoid window errors captured)")};ur.push(setTimeout(()=>Me("3s"),3e3)),ur.push(setTimeout(()=>Me("8s"),8e3)),ur.push(setTimeout(()=>Me("15s"),15e3))},pr(),Te("render:start");let Oe=de.startTiming();er=setTimeout(()=>{yt()||Dn||(Te("watchdog:11s retryable render timeout"),N("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Xd);let Tt=at.render(On);(async()=>{try{if(await Tt,Te(`render:resolved inactive=${yt()}`),bn(),yt()){kr();return}Dn=!0,Q(!0),st(!1),Dt.current?.("ready"),de.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),de.performance({stage:"checkout_render",durationMs:de.elapsed(Oe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Me){let K=Me instanceof Error?Me.message:"PayPal failed to render.";Te(`render:rejected msg=${K.slice(0,120)}`),bn(),N($r(K)?"teardown":"render_rejected",K)}})()}).catch(W=>{let ve=W instanceof Error?W.message:"PayPal operation failed.";Te(`provider:failed msg=${ve.slice(0,120)}`);let ce="script_rejected";U&&$r(ve)?ce="teardown":U&&qr&&(ce="render_rejected"),N(ce,ve)})},0);return()=>{Kt=!0,clearTimeout(te),zr&&clearTimeout(zr),bn(),Ht.current===fr&&(Ht.current=null),kr(),be.current=null,_e.current=null}},[I,vt,i,p,c,S,M,De,e,we,Ne,ge,Z,Ve,Te,Ot]);let fe=oe?(0,ar.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:gt?"#fef2f2":"#f3f4f6",border:`1px solid ${gt?"#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=${gt})`,Xe.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${Ye.join(`
4
- `)}`]}):null;return gt&&!Se?oe?(0,nr.jsx)("div",{children:pe}):null:(0,nr.jsxs)("div",{children:[pe,Ue&&(0,nr.jsx)(Lo,{identity:Ue.identity,methodLabel:Ue.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:J,onCancel:()=>J(null)}),(0,nr.jsxs)("div",{"aria-hidden":Je||Ue?!0:void 0,style:Je||Ue?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Qa},children:[!Be&&!Je&&(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:de,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Qa,display:"flex",opacity:Be?1:0},"aria-busy":$||b},De)]},De),pt&&(0,nr.jsx)("button",{ref:Ee,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:vn,style:qd,children:"Try PayPal again"})]})}function ga(e){return(0,nr.jsx)(Ol,{...e})}function Ll(e){return(0,nr.jsx)(Ol,{...e})}var ha=require("react/jsx-runtime");function Uo({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,ha.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,ha.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,ha.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 ei=require("@flopay/shared");function qo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var es=":idempotency-key";function ts(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 ns(e,t){if(!qo())return null;try{let n=window.sessionStorage.getItem(e+es);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 ti(e,t){if(qo())try{ts(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ni(e,t){if(ti(e,t),!!qo())try{ns(e,t)&&window.sessionStorage.removeItem(e+es)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function ri(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 oi(e,t,n){if(qo())try{window.sessionStorage.setItem(e+es,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Qi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Hd(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([i],[c])=>i<c?-1:i>c?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let i=0;i<t.length;i++){let c=t.charCodeAt(i);n=r^Math.imul(n^c,597399067),r=o^Math.imul(r^c,2869860233),o=a^Math.imul(o^c,951274213),a=n^Math.imul(a^c,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(i=>(i>>>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=>Qi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Qi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Qi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Hd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Nl(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 zl(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,ei.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,ei.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,g)=>`${u.code}:${u.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),i=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,g)=>`${u.code}:${u.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(a.length!==i.length)return!1;for(let[u,g]of a.entries()){let P=i[u];if(P===void 0||g.code!==P.code||g.type!==void 0&&g.type!==P.type||g.quantity!==P.quantity||g.totalAmount!==P.totalAmount||g.overrideAmount!==P.overrideAmount||g.currency!==P.currency)return!1}let c=[...t.couponCodes??[]].sort(),p=[...e.coupons??[]].sort();return c.length===p.length&&c.every((u,g)=>u===p[g])}var nn=require("react/jsx-runtime");var Kd={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:i="You will be automatically redirected, do not close or navigate away from this window.",theme:c=Kd}){let p={fontSize:13,color:c.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)",...c.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:c.spinnerTrackColor,strokeWidth:"3"}),(0,nn.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:c.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:c.labelColors[e]},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&a]}),e==="success"&&i!==null&&(0,nn.jsx)("p",{style:p,children:i}),e==="error"&&t&&(0,nn.jsx)("p",{style:p,children:t}),(0,nn.jsx)("style",{children:`
3
+ ${Xe.join(`
4
+ `)}`]}):null;return gt&&!le?oe?(0,ar.jsx)("div",{children:fe}):null:(0,ar.jsxs)("div",{children:[fe,Qe&&(0,ar.jsx)(Uo,{identity:Qe.identity,methodLabel:Qe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:ze,onCancel:()=>ze(null)}),(0,ar.jsxs)("div",{"aria-hidden":Ke||Qe?!0:void 0,style:Ke||Qe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ai},children:[!Le&&!Ke&&(0,ar.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,ar.jsx)("div",{ref:ue,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ai,display:"flex",opacity:Le?1:0},"aria-busy":$||P},Ne)]},Ne),pt&&(0,ar.jsx)("button",{ref:Fe,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Cn,style:Jd,children:"Try PayPal again"})]})}function Ca(e){return(0,ar.jsx)(Yl,{...e})}function Xl(e){return(0,ar.jsx)(Yl,{...e})}var Sa=require("react/jsx-runtime");function $o({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,Sa.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,Sa.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Sa.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 ii=require("@flopay/shared");function jo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var ys=":idempotency-key";function fs(e,t){if(!jo())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 gs(e,t){if(!jo())return null;try{let n=window.sessionStorage.getItem(e+ys);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 si(e,t){if(jo())try{fs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function li(e,t){if(si(e,t),!!jo())try{gs(e,t)&&window.sessionStorage.removeItem(e+ys)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function ci(e,t,n,r){if(jo())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 di(e,t,n){if(jo())try{window.sessionStorage.setItem(e+ys,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function ms(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function nu(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([i],[c])=>i<c?-1:i>c?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let i=0;i<t.length;i++){let c=t.charCodeAt(i);n=r^Math.imul(n^c,597399067),r=o^Math.imul(r^c,2869860233),o=a^Math.imul(o^c,951274213),a=n^Math.imul(a^c,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(i=>(i>>>0).toString(16).padStart(8,"0")).join("")}function Ho(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>ms(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ms(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ms(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:nu(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Jl(e,t=!1){let n=Ho(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function Zl(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,ii.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,ii.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,h)=>`${u.code}:${u.type??""}`.localeCompare(`${h.code}:${h.type??""}`)),i=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,h)=>`${u.code}:${u.type??""}`.localeCompare(`${h.code}:${h.type??""}`));if(a.length!==i.length)return!1;for(let[u,h]of a.entries()){let v=i[u];if(v===void 0||h.code!==v.code||h.type!==void 0&&h.type!==v.type||h.quantity!==v.quantity||h.totalAmount!==v.totalAmount||h.overrideAmount!==v.overrideAmount||h.currency!==v.currency)return!1}let c=[...t.couponCodes??[]].sort(),p=[...e.coupons??[]].sort();return c.length===p.length&&c.every((u,h)=>u===p[h])}var rn=require("react/jsx-runtime");var ru={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function Un({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:i="You will be automatically redirected, do not close or navigate away from this window.",theme:c=ru}){let p={fontSize:13,color:c.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,rn.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,rn.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...c.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,rn.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,rn.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,rn.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:c.spinnerTrackColor,strokeWidth:"3"}),(0,rn.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:c.spinnerAccentColor})]}),e==="success"&&(0,rn.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,rn.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,rn.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,rn.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,rn.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,rn.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,rn.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,rn.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,rn.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:c.labelColors[e]},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&a]}),e==="success"&&i!==null&&(0,rn.jsx)("p",{style:p,children:i}),e==="error"&&t&&(0,rn.jsx)("p",{style:p,children:t}),(0,rn.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 Ul=require("@flopay/shared"),Pn=require("react");var ql=require("react/jsx-runtime");function Pa({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,i]=(0,Pn.useState)(e instanceof Promise?null:e),[c,p]=(0,Pn.useState)(t instanceof Promise||!t?null:t),u=(0,Pn.useRef)(null),g=(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(!(!c||c===a))return pn(c)?.subscribe?.(P)},[P,a,c]),(0,Pn.useEffect)(()=>{if(!a)return;let w=pn(a);return u.current=w?.beginCheckout()??w?.now()??0,w?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{w?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,Pn.useEffect)(()=>{let w=!1;return e instanceof Promise?e.then(M=>{w||i(M)},()=>{w||P({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):i(e),()=>{w=!0}},[P,e]),(0,Pn.useEffect)(()=>{let w=!1;if(!t){p(null);return}return t instanceof Promise?t.then(M=>{w||p(M)},()=>{w||P({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{w=!0}},[P,t]),(0,Pn.useEffect)(()=>{if(!a||g.current===a)return;g.current=a;let w=pn(a);w?.log({name:"checkout.rendered",stage:"checkout_render"}),P({class:"lifecycle",name:"checkout.rendered"}),w?.performance({stage:"checkout_render",durationMs:w.elapsed(u.current??0),durationMode:"machine"})},[P,a]);let R=(0,Ul.resolveBillingApiUrl)(n?.billingApiUrl),E=(0,Pn.useMemo)(()=>({flopay:a,paypalFlopay:c,billingApiUrl:R,emitInstrument:P}),[a,c,R,P]);return(0,ql.jsx)(tr.Provider,{value:E,children:o})}var ai="flopay_recent_completion_";function jo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ai+e,JSON.stringify(t))}catch{}}function rs(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ai+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ai+e),!1):!0}catch{return!1}}async function ii(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"),rt=require("@flopay/shared");var va="card",Gd=1e3;async function Yd(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:i}=await e.retrieveSetupIntent(t);return{error:i,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 Xd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:i,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:i??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 rt.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function os(){return new rt.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function is(e,t){return Object.assign(e,{checkoutMethod:t})}function Gr(e,t){let n=e instanceof rt.FloPayError?e:new rt.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 ba(e,t){try{return await e()}catch(n){throw Gr(n,t)}}function jl(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 Jd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function ss(e){if(typeof document>"u"||typeof window>"u")throw new rt.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,R=()=>P.abort();e.signal?.aborted?P.abort():e.signal?.addEventListener("abort",R);let E=window.setTimeout(()=>P.abort(),n);try{let w=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:P.signal});if(!w.ok)return{status:"unknown"};let M=await w.json().catch(()=>null);return Zd(M)}catch{return{status:"unknown"}}finally{window.clearTimeout(E),e.signal?.removeEventListener("abort",R)}},a,i=()=>e.pollCompletionEndpoint!==!1?o():(a??(a=o()),a),c=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 g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let P=await new Promise((R,E)=>{let w=!1,M=0,T=0,b=0,S=!1,W=()=>{window.clearTimeout(M),window.clearInterval(T),window.clearTimeout(b),window.removeEventListener("message",Y),u.removeEventListener("load",re),e.signal?.removeEventListener("abort",V)},A=async()=>{if(!(w||S)){S=!0;try{let le=await i();if(w||!Jd(le))return;w=!0,W(),R(le)}finally{S=!1}}},re=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(b),b=window.setTimeout(()=>{A()},250))},V=()=>{w||(w=!0,W(),E(io()))},Y=le=>{if(le.source!==u.contentWindow||g&&le.origin!==g)return;let H=le.data;!H||typeof H!="object"||H.source!=="flopay-vault-3ds-return"||w||(w=!0,W(),R(null))};M=window.setTimeout(()=>{w||(w=!0,W(),E(os()))},rt.THREE_DS_CHALLENGE_WINDOW_MS),e.pollCompletionEndpoint!==!1&&(T=window.setInterval(()=>{A()},t)),u.addEventListener("load",re),window.addEventListener("message",Y),e.signal?.addEventListener("abort",V),u.src=e.nextActionRedirectUrl,p.appendChild(u),document.body.appendChild(p),u.focus(),e.signal?.aborted&&V()});return P||await i()}finally{p.parentNode?.removeChild(p),c?.isConnected&&c.focus()}}async function $o(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,a=t.nonce??t.session.clientSecret,i=new ao.PaymentAPI(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,p=new AbortController,u=new AbortController,g=()=>{p.abort(o.reason),u.abort(o.reason)};o.aborted?g():o.addEventListener("abort",g,{once:!0});let P=ss({billingApiUrl:n,sessionId:r,nonce:a,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:p.signal,pollCompletionEndpoint:!1}),R=i.waitForCheckoutSessionCompletion(r,{initialDelayMs:Gd,nonce:a,statusUrl:c,continueAfterActionRequired:!0,timeoutMs:rt.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:u.signal}),E;try{let M=await Promise.race([P,R]);if("data"in M)E=M;else{if(M.status==="declined")throw xr({type:M.declineReason??"authorization_declined",gatewayErrorCode:M.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(M.status==="timeout")throw os();E=await R}}catch(M){if(o.aborted||M instanceof Error&&M.name==="AbortError")throw io(M);if(!(M instanceof rt.FloPayError)||M.code!=="three_ds_timeout"&&M.code!=="checkout_processing_timeout")throw M;try{E=await i.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:a,statusUrl:c,timeoutMs:5e3,signal:o})}catch(b){if(o.aborted)throw io(b);if(!(b instanceof rt.FloPayError)||b.code!=="checkout_processing_timeout")throw b}let T=E&&to(E,t.session);if(!$r(T)&&T?.status!=="expired"){if(t.telemetry){let b=new ao.PaymentAPI(n);try{b.reportThreeDsAbandoned(r)}finally{b.destroy()}}throw os()}}finally{o.removeEventListener("abort",g),p.abort(),u.abort()}let w=E&&to(E,t.session);if(!$r(w))throw Do(w);return{...jr(w,r),checkoutMethod:"card"}}function Zd(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,i=is(new rt.FloPayError(a,"api_error",{code:e?.code??(0,rt.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,rt.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(i.orderId=e.orderId),i}function as(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function si(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function $l(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||si(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||si(c)))return c;let i=o.gateways;if(i&&typeof i=="object"){let c=i.stripe;if(c&&typeof c=="object"){let p=c,u=[p.stripeClientSecret,p.clientSecret];for(let g of u)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||si(g)))return g}}}}async function Qd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=$l(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(si(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:i}){let c=e.replace(/\/+$/,""),p=t??n.id,u=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",P=n.customer?.email??n.accountData?.email??"",R=n.customer?.firstName??n.accountData?.firstName??"",E=n.customer?.lastName??n.accountData?.lastName??"",w=n.customer?.country??n.accountData?.country??void 0,M=n.customer?.zip??n.accountData?.zip??void 0,b=await new ao.PaymentAPI(c,i===!1?{telemetry:!1}:void 0).processPayment(g,{sessionId:p,nonce:u,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:g,email:P,firstName:R,lastName:E,country:w,zip:M},returnUrl:a??as(n)});if(b.ok){let A=typeof b.json=="function"?await b.json().catch(()=>null):null;if((0,rt.isAuthorizationOnlySession)(n)||A?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof A?.paymentId=="string"?A.paymentId:n.paymentId,sessionId:typeof A?.sessionId=="string"?A.sessionId:p,authorizationExpiresAt:typeof A?.authorizationExpiresAt=="string"?A.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:pa(o),checkoutMethod:Vl(o,n)}};let re=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...re?{paymentIntentId:re}:{},paymentMethodId:pa(o),checkoutMethod:Vl(o,n)}}}let S;try{S=await b.json()}catch(A){throw new rt.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:b.status,cause:A})}if(S?.type==="3ds_required"&&typeof S.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:S.nextActionRedirectUrl};if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let A=$l(S);if(!A)throw new rt.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:b.status});return{type:S.type,threeDSecureToken:A,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let A=await Qd({billingApiUrl:c,sessionId:p,nonce:u,responseJson:S});if(A)return A;throw is(new rt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let W=new rt.FloPayError(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:b.status});throw Object.assign(W,{telemetryOutcome:(0,rt.classifyPaymentRejection)(b.status,S)})}async function li(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:i,returnUrl:c,telemetry:p,signal:u}){let g=t?.getRawProvider();if(!g)throw Gr(new rt.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw is(new rt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let P=(0,rt.isSetupIntentClientSecret)(e.threeDSecureToken),R=null,E=e.paymentMethodId,w=await ba(()=>Yd(g,e.threeDSecureToken,P),"card");if(w){if(w.error)throw Gr(new rt.FloPayError(w.error.message??`Failed to retrieve 3DS ${P?"setup":"payment"} status.`,"api_error",{code:w.error.code}),"card");let T=w.intent;!E&&T?.payment_method&&(typeof T.payment_method=="string"?E=T.payment_method:"id"in T.payment_method&&(E=T.payment_method.id??void 0))}let M=E?await ba(()=>Xd(g,e.threeDSecureToken,{payment_method:E,return_url:c??as(i)??window.location.href},P),"card"):null;if(M){if(M.error)throw Gr(new rt.FloPayError(M.error.message??"3DS authentication failed.","api_error",{code:M.error.code}),"card");R=M.intent}else{let T=await ba(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(T.error)throw Gr(new rt.FloPayError(T.error.message??"3DS authentication failed.","api_error",{code:T.error.code}),"card");R=(P?T.setupIntent:T.paymentIntent)??null}if(R&&(R.status==="requires_capture"||R.status==="succeeded"||R.status==="processing")){let T=await Wo({billingApiUrl:o,sessionId:a,session:i,telemetry:p,tokenizedData:{id:R.id,type:"card",threeDSecureActionResultTokenId:R.id},returnUrl:c});return T.type==="success"?{...T.result,paymentIntentId:T.result.paymentIntentId??R.id,paymentMethodId:T.result.paymentMethodId??E}:T.type==="next_action_required"?$o(T,{billingApiUrl:o,sessionId:a??i.id,session:i,signal:u}):li(T,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:i,returnUrl:c,telemetry:p,signal:u})}throw Gr(new rt.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 rt.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:E}=await ba(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(E)throw Gr(new rt.FloPayError(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:R}=await ba(()=>P.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??as(i)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(R)throw Gr(new rt.FloPayError(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new rt.FloPayError("Unsupported payment redirect state.","api_error")}function Ca(e){if(e instanceof rt.FloPayError){let r=eo(e.message);return r&&r!==e.message?Object.assign(new rt.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 rt.FloPayError(n,"api_error")}function ls(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 rt.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 Vl(e,t){return e?e.isPaypal?"paypal":"card":t&&Zr(t)?"card":void 0}async function cs({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,[i,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(u=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",u),null)):Promise.resolve(null)]);if(!i)throw new rt.FloPayError("The payment provider did not initialize.","authentication_error");let p=null;return a?p=c:t&&(p=i),{flopay:i,paypalFlopay:p}}var Cr=require("@flopay/js"),y=require("@flopay/shared"),Jt=require("@stripe/react-stripe-js"),s=$i(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 ci(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 Wl={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 di(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(i=>i.startsWith("background")),a={};for(let[i,c]of Object.entries(e))i in n||o&&i.startsWith("background")||(a[i]=c);for(let i of r)a[i]=n[i];return a}var eu=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 tu(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return eu.has(t.charAt(0).toLowerCase()+t.slice(1))}function nu(e,t){return typeof t=="number"&&t!==0&&!tu(e)?`${t}px`:String(t).trim()}function Hl(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]=nu(n,r)}}}var Kl=require("react/jsx-runtime"),ds=new WeakSet;function so({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:i,onReady:c,onError:p,onValidation:u}){let g=(0,Wn.useRef)(null),P=(0,Wn.useRef)(c),R=(0,Wn.useRef)(p),E=(0,Wn.useRef)(u);P.current=c,R.current=p,E.current=u;let w=(0,Wn.useRef)(o);w.current=o;let M=(0,Wn.useRef)(null),T=a??void 0,b=(0,Wn.useRef)(T);b.current=T;let S=(0,Wn.useRef)(void 0);return(0,Wn.useEffect)(()=>{let W=g.current;if(!W)return;let A=!0,re=!1,V=()=>{!A||re||(re=!0,P.current?.())},Y=e.on("ready",()=>{V()}),le=e.on("error",oe=>{R.current?.(oe.message??"There was a problem loading the secure card form.")}),H=e.on("validation",oe=>{E.current?.(oe.message??null)}),Ne=b.current??(ds.has(e)?null:void 0),je={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...w.current?{theme:w.current}:{},...Ne===void 0?{}:{submitLabel:Ne}};return M.current=w.current??null,S.current=b.current,b.current!==void 0&&ds.add(e),e.mount(W,je).then(()=>{V()}).catch(oe=>{A&&R.current?.(oe instanceof Error?oe.message:"Failed to load the secure card form.")}),()=>{A=!1,Y(),le(),H(),e.unmount()}},[e,t,n,r]),ho(()=>{let W=g.current;W&&Hl(W,i)},[i]),(0,Wn.useEffect)(()=>{o!==void 0&&(o===null&&M.current===null||(M.current=o,e.applyTheme?.(o)))},[e,o]),(0,Wn.useEffect)(()=>{T!==S.current&&(S.current=T,T!==void 0&&ds.add(e),e.setSubmitLabel?.(T??null))},[e,T]),(0,Kl.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields"})}var Yl=/^#([0-9a-f]{6})$/i,ru=/^#([0-9a-f]{3})$/i,Xl=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Jl=/^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,ou=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,au=/^(-?\d+(?:\.\d+)?)(?:px)?$/,iu=/^(-?\d+(?:\.\d+)?)em$/,su=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,lu=/^[a-z][a-z0-9 -]{0,31}$/i,cu=new Set(["none","uppercase","lowercase","capitalize"]);function Zl(e){if(typeof e!="string")return null;let t=e.trim(),n=Yl.exec(t);if(n){let g=Number.parseInt(n[1],16);return{r:g>>16&255,g:g>>8&255,b:g&255,a:null}}let r=ru.exec(t);if(r){let[g,P,R]=r[1].split("").map(E=>Number.parseInt(E+E,16));return{r:g,g:P,b:R,a:null}}let o=Xl.exec(t),a=o?null:Jl.exec(t),i=o??a;if(!i)return null;let c=Number(i[1]),p=Number(i[2]),u=Number(i[3]);return c>255||p>255||u>255?null:{r:c,g:p,b:u,a:a?Number(a[4]):null}}function Ql({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 Sa(e){if(typeof e!="string")return;let t=e.trim();if(Yl.test(t)||Xl.test(t))return t;let n=Jl.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=Zl(t);return r?Ql(r):void 0}function ui(e,t=.12){let n=Zl(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Ql({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function wa(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 bo(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=au.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function du(e,t,n){if(typeof e!="string")return;let r=iu.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function uu(e){let t=wa(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=wa(o," "),i=Sa(a[0]);if(!i)return;let c=r/(t.length-1)*100,p=a[1]===void 0?c: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:i,position:p})}return{type:"linearGradient",angle:0,stops:n}}function pu(e){if(typeof e!="string")return;let t=e.trim(),n=Sa(t);if(n)return{type:"solid",color:n};let r=ou.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=uu(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function mu(e){return e.type==="solid"?{type:"solid",color:ui(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:ui(t.color)}))}}function yu(e){let t=!1,n,r=[];for(let p of wa(e," ")){if(p.toLowerCase()==="inset"){t=!0;continue}let u=Sa(p);if(u){n=u;continue}let g=bo(p,-128,128);if(g===void 0)return;r.push(g)}if(!n||r.length<2||r.length>4)return;let[o,a,i=0,c=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||i>128||Math.abs(c)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:i,spread:c}}function fu(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=wa(t,",").map(yu);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function Gl(e){if(typeof e!="string")return;let t=wa(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>lu.test(n)).slice(0,4);return t.length>0?t:void 0}function gu(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=bo(t[0],0,64),r=bo(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function hu(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 ec({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=pu(r.background??r.backgroundColor),i=Sa(o?.colorPrimaryHover),c=i?{type:"solid",color:i}:a&&mu(a),p={fontFamilies:Gl(r.fontFamily)??Gl(n),fontSize:bo(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:hu(r.fontWeight)??600,letterSpacing:du(r.letterSpacing,-.1,.5)??.01,lineHeight:bo(r.lineHeight,.8,2)??1,textTransform:cu.has(String(r.textTransform))?r.textTransform:"uppercase"},u=gu(r.padding),g=fu(r.boxShadow),P=bo(r.borderRadius,0,9999),R=typeof r.backdropFilter=="string"?bo(su.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Sa(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...c?{hoverBackground:c}:{},typography:p,...u?{spacing:u}:{},...g?{shadow:g}:{},...P===void 0?{}:{borderRadius:P},disabledOpacity:e?.theme==="night"?.8:.6,...R===void 0?{}:{backdropBlur:R}}}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)?ui(r,t):e}function us(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,i=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",c=n==="buttons",p=t.nameInput,u=o(p?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",g=ec({appearance:e,buttonsStyles:t,fontFamily:u});return{primaryColor:i,primaryHoverColor:o(r?.colorPrimaryHover)??Ko(i,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(p?.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:u,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(us(p?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...g?{submitButton:g}:{}}}var d=require("react/jsx-runtime"),Fr="flopay_stripe_resume",tc="flopay_wallet_resume",yc="fw1",Pu="fw2",fc=300*1e3,bu=900,vu=25e3,Cu=25e3,Su=1e4,gc=["payment_intent","payment_intent_client_secret","redirect_status"],vr={provider:"paypal",paymentMethodCategory:"paypal"},pi={},ps={};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 vs(e){return`${Pu}:${e}`}function mi(e){return $t(vs(e))}function yi(e,t){if(typeof window>"u")return null;let n=vs(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>fc||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(mi(e),null):o}catch{return mi(e),null}}function wu(e){return $t(vs(e.sessionId),e)}function nc(e,t,n){let r=yi(e,t);return!r||r.clientSecret!==n?!1:mi(e)}function ms(e,t,n){if(typeof window>"u")return;yi(e,t)?.clientSecret===n&&mi(e)}function ku(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ys(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":ua(e.status),o=ku(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function rc(e,t,n){let r=null;try{return await Promise.race([Rl(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},Su),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Ru(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function hc(e){return e instanceof y.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function fi(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 hc(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Ra="flopay_paypal_resume",ka=new Map;function Pc(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(Ra);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function Iu(){if(typeof window>"u")return!1;let[e,t]=Cs();return e?Pc(t)!==null:!1}function Cs(){let e=new URLSearchParams(window.location.search);return gc.map(t=>e.get(t))}function Ss(){let e=new URL(window.location.href);for(let t of gc)e.searchParams.delete(t);return e.toString()}function _u(){$t(Ra),window.history.replaceState({},"",Ss())}var Eu=250,oc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Tu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function ws(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 gi({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 Au(e){return e instanceof y.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function fs(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function bc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=yo(n),i=a.firstName?a:yo(r?.name);return On({email:(0,y.isValidEmail)(o)?o:r?.email?.trim(),firstName:i.firstName,lastName:i.lastName})}async function Mu({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let i=bc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,y.isValidEmail)(i.email)?i:a(o,i)}var xu=`
9
+ `})]})})}var Ql=require("@flopay/shared"),Pn=require("react");var ec=require("react/jsx-runtime");function wa({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,i]=(0,Pn.useState)(e instanceof Promise?null:e),[c,p]=(0,Pn.useState)(t instanceof Promise||!t?null:t),u=(0,Pn.useRef)(null),h=(0,Pn.useRef)(null),v=Vo(r);(0,Pn.useEffect)(()=>{v({class:"lifecycle",name:"checkout.mount"})},[v]),(0,Pn.useEffect)(()=>{a&&v({class:"lifecycle",name:"sdk.initialize.ready"})},[v,a]),(0,Pn.useEffect)(()=>{if(a)return pn(a)?.subscribe?.(v)},[v,a]),(0,Pn.useEffect)(()=>{if(!(!c||c===a))return pn(c)?.subscribe?.(v)},[v,a,c]),(0,Pn.useEffect)(()=>{if(!a)return;let w=pn(a);return u.current=w?.beginCheckout()??w?.now()??0,w?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{w?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,Pn.useEffect)(()=>{let w=!1;return e instanceof Promise?e.then(x=>{w||i(x)},()=>{w||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):i(e),()=>{w=!0}},[v,e]),(0,Pn.useEffect)(()=>{let w=!1;if(!t){p(null);return}return t instanceof Promise?t.then(x=>{w||p(x)},()=>{w||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{w=!0}},[v,t]),(0,Pn.useEffect)(()=>{if(!a||h.current===a)return;h.current=a;let w=pn(a);w?.log({name:"checkout.rendered",stage:"checkout_render"}),v({class:"lifecycle",name:"checkout.rendered"}),w?.performance({stage:"checkout_render",durationMs:w.elapsed(u.current??0),durationMode:"machine"})},[v,a]);let E=(0,Ql.resolveBillingApiUrl)(n?.billingApiUrl),T=(0,Pn.useMemo)(()=>({flopay:a,paypalFlopay:c,billingApiUrl:E,emitInstrument:v}),[a,c,E,v]);return(0,ec.jsx)(or.Provider,{value:T,children:o})}var ui="flopay_recent_completion_";function Wo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ui+e,JSON.stringify(t))}catch{}}function hs(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ui+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ui+e),!1):!0}catch{return!1}}async function pi(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 lo=require("@flopay/js"),ot=require("@flopay/shared");var Ra="card",ou=1e3;async function au(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:i}=await e.retrieveSetupIntent(t);return{error:i,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 iu(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:i,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:i??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 co(e){return new ot.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function bs(){return new ot.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function vs(e,t){return Object.assign(e,{checkoutMethod:t})}function Yr(e,t){let n=e instanceof ot.FloPayError?e:new ot.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 ka(e,t){try{return await e()}catch(n){throw Yr(n,t)}}function nc(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 su(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function Cs(e){if(typeof document>"u"||typeof window>"u")throw new ot.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw co();let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let v=new AbortController,E=()=>v.abort();e.signal?.aborted?v.abort():e.signal?.addEventListener("abort",E);let T=window.setTimeout(()=>v.abort(),n);try{let w=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:v.signal});if(!w.ok)return{status:"unknown"};let x=await w.json().catch(()=>null);return lu(x)}catch{return{status:"unknown"}}finally{window.clearTimeout(T),e.signal?.removeEventListener("abort",E)}},a,i=()=>e.pollCompletionEndpoint!==!1?o():(a??(a=o()),a),c=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 h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}try{let v=await new Promise((E,T)=>{let w=!1,x=0,A=0,P=0,C=!1,H=()=>{window.clearTimeout(x),window.clearInterval(A),window.clearTimeout(P),window.removeEventListener("message",ee),u.removeEventListener("load",se),e.signal?.removeEventListener("abort",j)},I=async()=>{if(!(w||C)){C=!0;try{let we=await i();if(w||!su(we))return;w=!0,H(),E(we)}finally{C=!1}}},se=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(P),P=window.setTimeout(()=>{I()},250))},j=()=>{w||(w=!0,H(),T(co()))},ee=we=>{if(we.source!==u.contentWindow||h&&we.origin!==h)return;let ne=we.data;!ne||typeof ne!="object"||ne.source!=="flopay-vault-3ds-return"||w||(w=!0,H(),E(null))};x=window.setTimeout(()=>{w||(w=!0,H(),T(bs()))},ot.THREE_DS_CHALLENGE_WINDOW_MS),e.pollCompletionEndpoint!==!1&&(A=window.setInterval(()=>{I()},t)),u.addEventListener("load",se),window.addEventListener("message",ee),e.signal?.addEventListener("abort",j),u.src=e.nextActionRedirectUrl,p.appendChild(u),document.body.appendChild(p),u.focus(),e.signal?.aborted&&j()});return v||await i()}finally{p.parentNode?.removeChild(p),c?.isConnected&&c.focus()}}async function Ko(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,a=t.nonce??t.session.clientSecret,i=new lo.PaymentAPI(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,p=new AbortController,u=new AbortController,h=()=>{p.abort(o.reason),u.abort(o.reason)};o.aborted?h():o.addEventListener("abort",h,{once:!0});let v=Cs({billingApiUrl:n,sessionId:r,nonce:a,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:p.signal,pollCompletionEndpoint:!1}),E=i.waitForCheckoutSessionCompletion(r,{initialDelayMs:ou,nonce:a,statusUrl:c,continueAfterActionRequired:!0,timeoutMs:ot.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:u.signal}),T;try{let x=await Promise.race([v,E]);if("data"in x)T=x;else{if(x.status==="declined")throw Br({type:x.declineReason??"authorization_declined",gatewayErrorCode:x.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(x.status==="timeout")throw bs();T=await E}}catch(x){if(o.aborted||x instanceof Error&&x.name==="AbortError")throw co(x);if(!(x instanceof ot.FloPayError)||x.code!=="three_ds_timeout"&&x.code!=="checkout_processing_timeout")throw x;try{T=await i.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:a,statusUrl:c,timeoutMs:5e3,signal:o})}catch(P){if(o.aborted)throw co(P);if(!(P instanceof ot.FloPayError)||P.code!=="checkout_processing_timeout")throw P}let A=T&&oo(T,t.session);if(!Hr(A)&&A?.status!=="expired"){if(t.telemetry){let P=new lo.PaymentAPI(n);try{P.reportThreeDsAbandoned(r)}finally{P.destroy()}}throw bs()}}finally{o.removeEventListener("abort",h),p.abort(),u.abort()}let w=T&&oo(T,t.session);if(!Hr(w))throw No(w);return{...jr(w,r),checkoutMethod:"card"}}function lu(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 Br(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=ro(o)??o,i=vs(new ot.FloPayError(a,"api_error",{code:e?.code??(0,ot.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,ot.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(i.orderId=e.orderId),i}function Ps(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function mi(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function rc(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||mi(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||mi(c)))return c;let i=o.gateways;if(i&&typeof i=="object"){let c=i.stripe;if(c&&typeof c=="object"){let p=c,u=[p.stripeClientSecret,p.clientSecret];for(let h of u)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||mi(h)))return h}}}}async function cu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=rc(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 lo.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(mi(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function Go({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:i}){let c=e.replace(/\/+$/,""),p=t??n.id,u=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",v=n.customer?.email??n.accountData?.email??"",E=n.customer?.firstName??n.accountData?.firstName??"",T=n.customer?.lastName??n.accountData?.lastName??"",w=n.customer?.country??n.accountData?.country??void 0,x=n.customer?.zip??n.accountData?.zip??void 0,P=await new lo.PaymentAPI(c,i===!1?{telemetry:!1}:void 0).processPayment(h,{sessionId:p,nonce:u,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:h,email:v,firstName:E,lastName:T,country:w,zip:x},returnUrl:a??Ps(n)});if(P.ok){let I=typeof P.json=="function"?await P.json().catch(()=>null):null;if((0,ot.isAuthorizationOnlySession)(n)||I?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof I?.paymentId=="string"?I.paymentId:n.paymentId,sessionId:typeof I?.sessionId=="string"?I.sessionId:p,authorizationExpiresAt:typeof I?.authorizationExpiresAt=="string"?I.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:ha(o),checkoutMethod:tc(o,n)}};let se=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...se?{paymentIntentId:se}:{},paymentMethodId:ha(o),checkoutMethod:tc(o,n)}}}let C;try{C=await P.json()}catch(I){throw new ot.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:P.status,cause:I})}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 I=rc(C);if(!I)throw new ot.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:P.status});return{type:C.type,threeDSecureToken:I,paymentMethodId:C.paymentMethodId}}if(C?.gatewayErrorCode==="authentication_required"){let I=await cu({billingApiUrl:c,sessionId:p,nonce:u,responseJson:C});if(I)return I;throw vs(new ot.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let H=new ot.FloPayError(C?.message??"Payment failed. Please try again.","api_error",{code:C?.code??C?.gatewayErrorCode,declineCode:C?.declineCode??C?.gatewayDeclineReason,statusCode:P.status});throw Object.assign(H,{telemetryOutcome:(0,ot.classifyPaymentRejection)(P.status,C)})}async function yi(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:i,returnUrl:c,telemetry:p,signal:u}){let h=t?.getRawProvider();if(!h)throw Yr(new ot.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw vs(new ot.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let v=(0,ot.isSetupIntentClientSecret)(e.threeDSecureToken),E=null,T=e.paymentMethodId,w=await ka(()=>au(h,e.threeDSecureToken,v),"card");if(w){if(w.error)throw Yr(new ot.FloPayError(w.error.message??`Failed to retrieve 3DS ${v?"setup":"payment"} status.`,"api_error",{code:w.error.code}),"card");let A=w.intent;!T&&A?.payment_method&&(typeof A.payment_method=="string"?T=A.payment_method:"id"in A.payment_method&&(T=A.payment_method.id??void 0))}let x=T?await ka(()=>iu(h,e.threeDSecureToken,{payment_method:T,return_url:c??Ps(i)??window.location.href},v),"card"):null;if(x){if(x.error)throw Yr(new ot.FloPayError(x.error.message??"3DS authentication failed.","api_error",{code:x.error.code}),"card");E=x.intent}else{let A=await ka(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(A.error)throw Yr(new ot.FloPayError(A.error.message??"3DS authentication failed.","api_error",{code:A.error.code}),"card");E=(v?A.setupIntent:A.paymentIntent)??null}if(E&&(E.status==="requires_capture"||E.status==="succeeded"||E.status==="processing")){let A=await Go({billingApiUrl:o,sessionId:a,session:i,telemetry:p,tokenizedData:{id:E.id,type:"card",threeDSecureActionResultTokenId:E.id},returnUrl:c});return A.type==="success"?{...A.result,paymentIntentId:A.result.paymentIntentId??E.id,paymentMethodId:A.result.paymentMethodId??T}:A.type==="next_action_required"?Ko(A,{billingApiUrl:o,sessionId:a??i.id,session:i,signal:u}):yi(A,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:i,returnUrl:c,telemetry:p,signal:u})}throw Yr(new ot.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let v=(n??t)?.getRawProvider();if(!v)throw Yr(new ot.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:T}=await ka(()=>v.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(T)throw Yr(new ot.FloPayError(T.message??"PayPal authorization failed.","api_error",{code:T.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:E}=await ka(()=>v.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Ps(i)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(E)throw Yr(new ot.FloPayError(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new ot.FloPayError("Unsupported payment redirect state.","api_error")}function Ia(e){if(e instanceof ot.FloPayError){let r=ro(e.message);return r&&r!==e.message?Object.assign(new ot.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=ro(t)??t;return new ot.FloPayError(n,"api_error")}function Ss(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||to(e.data.session);if(!t&&!n&&!r)throw new ot.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 tc(e,t){return e?e.isPaypal?"paypal":"card":t&&to(t)?"card":void 0}async function ws({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,[i,c]=await Promise.all([(0,lo.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,lo.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(!i)throw new ot.FloPayError("The payment provider did not initialize.","authentication_error");let p=null;return a?p=c:t&&(p=i),{flopay:i,paypalFlopay:p}}var wr=require("@flopay/js"),f=require("@flopay/shared"),Jt=require("@stripe/react-stripe-js"),s=os(require("react"),1);function Yo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function fi(e,t){if(e)return{error:n=>e.error(Yo(t,n)),log:n=>e.log(Yo(t,n)),performance:n=>e.performance(Yo(t,n)),terminal:n=>e.terminal(Yo(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 Xr=require("@flopay/shared"),ac=require("react");var oc={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 mn=require("react/jsx-runtime"),du=`
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 @@ ${Ye.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,_a=180,ac=`flopay-card-enter ${_a}ms cubic-bezier(0, 0, 0.2, 1) both`,ic=`flopay-card-exit ${_a}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Fu=`flopay-buttons-enter ${_a}ms cubic-bezier(0, 0, 0.2, 1) both`,Bu=`flopay-buttons-exit ${_a}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Du(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ks(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var Ou={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Lu(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 hs={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 Nu(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function sc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ps(e){return e==="paypal"?"PayPal":(0,y.getStripeMethodDisplayName)(e)}function zu(e){let t=(0,y.getPostalCodeExample)(e);return`Enter a valid ${(0,y.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Uu(e,t,n){let r=(0,y.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,i=a&&!o,c=a&&!!o&&!(0,y.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:i,malformed:c}}function qu(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 lc(e,t){return t instanceof y.FloPayError?t:new y.FloPayError(t instanceof Error?t.message:`${Nu(e)} before-click hook failed.`,"validation_error")}function gs(){return(0,d.jsx)("style",{children:xu})}function Vu(e){return typeof e=="number"?`${e}px`:e}function vc(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Cc({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 cc(e){return e!=="unavailable"&&e!=="load_error"}function hi(e){return(0,d.jsx)($u,{...e})}function dc({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:i=!1,onButtonClick:c,onDecline:p,onTechnicalFailure:u,runBeforeButtonClick:g,billingName:P,onBuyerIdentityReady:R,onLoadStateChange:E,placeholderBorderRadius:w,popupCapabilityOwner:M,externalTelemetryContext:T,presentationMode:b}){let S=Hr(),{emitInstrument:W}=(0,s.useContext)(tr),A=(0,Jt.useStripe)(),re=(0,Jt.useElements)(),V=(0,s.useMemo)(()=>ci(pn(S),T),[T,S]),[Y,le]=(0,s.useState)("loading");(0,s.useEffect)(()=>{E?.(Y)},[Y,E]);let[H,Ne]=(0,s.useState)(!1),je=(0,s.useRef)(!1),oe=!(0,y.isValidEmail)(n?.trim())||!P?.trim(),{request:ze,collect:ut,finish:xe}=Oo(),we=(0,s.useRef)(!1),ve=(0,s.useRef)(null),de=(0,s.useRef)(null),[Te,$e]=(0,s.useState)(0),[ot,I]=(0,s.useState)(!1),ke=(0,s.useRef)(!1),ge=(0,s.useRef)(new Map),{startAttempt:j,finishAttempt:Ee,invalidateAttempt:Q,isAttemptInvalidated:Be,isAttemptCurrent:ee,generationRef:Je}=fa(($,he,Ue)=>{u?.($,he,{...Ue,popupBlocked:Ue?.popupBlocked??oo(he),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:b,terminalReason:"overlay_timeout"}),I(!0),$e(v=>v+1)},{onHandoffObserved:()=>{M.markAvailable(),V?.log({name:"provider.popup.opened",stage:"overlay_open",...vr,attempt:Je.current})}});(0,s.useEffect)(()=>{ot&&de.current?.focus()},[ot,Te]);let st=(0,s.useCallback)(()=>{$e($=>$+1)},[]),De=(0,s.useCallback)(($,he,Ue)=>{Q(Ue),u?.("paypal",$,{code:he,popupBlocked:oo($),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:b}),I(!0),st()},[Q,u,b,st]),et=(0,s.useCallback)(()=>{window.setTimeout(()=>{(ve.current?.querySelector("iframe")??ve.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{ke.current&&(ke.current=!1,et())},[et,Te]);let tt=(0,s.useCallback)(()=>{I(!1),a?.(null),et()},[et,a]);(0,s.useEffect)(()=>{if(!A||we.current)return;let[$,he,Ue]=Cs();if(!$||!he)return;let v=Pc(he);if(!v)return;we.current=!0;let J=!0,Fe=ka.get(he);Fe||(Fe=Ue==="failed"?Promise.resolve(null):Promise.resolve().then(()=>A.retrievePaymentIntent(he)),ka.set(he,Fe));let ue={accountPatch:v.accountPatch,sessionId:v.sessionId,nonce:v.nonce},Ce=()=>{V?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...vr,requestCategory:"provider_sdk"})};return V?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...vr}),(async()=>{try{Ne(!0);let f=await Fe;if(!J)return;if(f?.error){ka.delete(he),Ce(),a?.(f.error.message??"Failed to retrieve PayPal payment status.");return}if(_u(),ka.delete(he),Ue==="failed"){let Z="PayPal payment was declined. Please try again.";V?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}),a?.(Z),p?.(un("paypal",Z));return}let C=f?.paymentIntent;if(C&&C.id!==$){Ce(),a?.("Failed to match the returned PayPal payment.");return}if(C&&(C.status==="requires_capture"||C.status==="succeeded")){let Z=typeof C.payment_method=="string"?C.payment_method:C.payment_method?.id;o({id:Z??C.id,type:"card",threeDSecureActionResultTokenId:C.id,isPaypal:!0},{...ue,presentationMode:"redirect"})}else{let Z="PayPal payment was not completed. Please try again.";V?.terminal({outcome:C?.status==="canceled"?"payment_cancelled":"payment_declined",...vr,terminalReason:C?.status==="canceled"?"cancelled":"provider_declined"}),a?.(Z),p?.(un("paypal",Z))}}catch(f){if(!J)return;ka.delete(he),Ce(),a?.(f instanceof Error?f.message:"Failed to complete PayPal payment.")}finally{J&&Ne(!1)}})(),()=>{J=!1,we.current=!1}},[A,o,a,p,V]);let pt=(0,s.useCallback)(async($=!1)=>{let he=g?await g("paypal"):{proceed:!0};if(!he.proceed)return ge.current.delete(Te),!1;let Ue=j("paypal");return ge.current.set(Te,{generation:Ue,accountPatch:he.accountPatch,sessionId:he.sessionId,nonce:he.nonce}),I(!1),V?.log({name:`provider.${$?"redirect.started":"handoff.requested"}`,stage:$?"redirect":"overlay_open",...vr,attempt:Ue}),c?.("paypal"),!0},[c,V,g,j,Te]),Ae=(0,s.useCallback)(async $=>{if(i||H||!await pt()){$.reject();return}$.resolve()},[i,pt,H]),At=(0,s.useCallback)(async $=>{if(!A||!re)return;let he=ge.current.get(Te);if(he&&!ee(he.generation)){ge.current.delete(Te);return}if(!he&&Be()||he&&!Ee(he.generation))return;he||Ee();let Ue=he??null;if(ge.current.delete(Te),!Ue&&g){let z=await g("paypal");if(!z.proceed){$.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Ue={accountPatch:z.accountPatch,sessionId:z.sessionId,nonce:z.nonce}}let v=Ue?.sessionId??e,J=Ue?.nonce??t,Fe=await Mu({event:$,prepared:Ue,email:n,billingName:P,methodLabel:"PayPal",collect:ut});if(!Fe){$.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let ue=Fe.email,Ce={...Ue?.accountPatch,...On(Fe,!0)};try{if(Ne(!0),a?.(null),!v||!(0,y.isValidEmail)(ue))throw new Error("Missing sessionId or email for PayPal payment");await R?.(Fe);let z=A.createPaymentMethod,{error:f,paymentMethod:C}=await z({type:"paypal"});if(f){De(f,"stripe_paypal_create_payment_method_failed",he?.generation),$.paymentFailed({reason:"fail"});return}let Z=await fi(r,W,v,J??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:C?.id??null,intentKind:"payment"});if(Z.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let K=Z.clientSecret,Pe={return_url:Ss()};if(C?.id&&(Pe.payment_method=C.id),!$t(Ra,{clientSecret:K,sessionId:v,nonce:J,accountPatch:Ce})&&b==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:We,paymentIntent:Ze}=await A.confirmPayment({clientSecret:K,confirmParams:Pe,redirect:"if_required"});if(We){if($t(Ra),go(We)){let bt=We.message??"Your payment was declined.";V?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}),a?.(bt),p?.(un("paypal",bt,{code:Mr(We),declineCode:No(We)})),await gi({billingApiUrl:r,sessionId:v,nonce:J,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mr(We)??"provider_declined"}})}else De(We,"stripe_paypal_confirm_failed",he?.generation);return}$t(Ra);let Se=typeof Ze?.payment_method=="string"?Ze.payment_method:Ze?.payment_method?.id;o({id:Se??Ze?.id,type:"card",threeDSecureActionResultTokenId:Ze?.id,isPaypal:!0},{accountPatch:Ce,paymentMethodCategory:"paypal",presentationMode:b,sessionId:v,nonce:J});return}catch(z){De(z,"stripe_paypal_failed",he?.generation)}finally{Ne(!1)}},[A,re,e,t,n,P,ut,R,r,W,o,a,p,g,De,Ee,ee,Be,V,b,Te]),kt=(0,s.useCallback)(async()=>{if(!(je.current||i||H||!A||!re)){je.current=!0,Ne(!0);try{if(!await pt(!0))return;await At({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{je.current=!1,Ne(!1)}}},[re,At,i,pt,A,H]),gt=b==="redirect"?(0,d.jsx)("button",{type:"button",disabled:i||H,onClick:()=>{kt()},style:{width:"100%",minHeight:Ia,border:"1px solid #d1d5db",borderRadius:w??8,background:"#ffc439",color:"#111827",cursor:i||H?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,d.jsx)(Jt.ExpressCheckoutElement,{onReady:$=>le(vc($,["paypal"])),onLoadError:()=>{le("load_error"),ws(V,"paypal","paypal","provider_error")},onClick:Ae,onConfirm:At,onCancel:()=>{let $=ge.current.get(Te);ge.current.delete(Te),V?.terminal({outcome:"payment_cancelled",...vr,terminalReason:"cancelled",...$?{attempt:$.generation}:{}}),Q($?.generation),I(!1),ke.current=!0,st()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:oe,emailRequired:oe,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},Te),Ct=(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:[ot&&(0,d.jsx)("button",{ref:de,type:"button","data-testid":"flopay-paypal-retry-button",onClick:tt,style:hs,children:"Try PayPal again"}),ze&&(0,d.jsx)(Lo,{identity:ze.identity,methodLabel:ze.methodLabel,onComplete:xe,onCancel:()=>xe(null)},ze.id),(0,d.jsx)("div",{style:{display:ze?"none":void 0},children:gt})]}),H&&!ze&&(0,d.jsx)(Ln,{status:"processing"})]});return b==="redirect"?Ct:(0,d.jsx)(Cc,{state:Y,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:Ct})}function uc(e){return e==="apple_pay"||e==="google_pay"}function pc({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:i,onErrorChange:c,onButtonClick:p,onDecline:u,onTechnicalFailure:g,runBeforeButtonClick:P,billingName:R,onBuyerIdentityReady:E,onLoadStateChange:w,placeholderBorderRadius:M,popupCapabilityOwner:T,externalTelemetryContext:b}){let S=Hr(),{emitInstrument:W}=(0,s.useContext)(tr),A=(0,Jt.useStripe)(),re=(0,Jt.useElements)(),V=(0,s.useMemo)(()=>ci(pn(S),b),[b,S]),[Y,le]=(0,s.useState)("loading");(0,s.useEffect)(()=>{w?.(Y)},[Y,w]);let[H,Ne]=(0,s.useState)(!1),je=(0,s.useRef)(!(0,y.isValidEmail)(n?.trim())||!R?.trim()).current,{request:oe,collect:ze,finish:ut}=Oo(),xe=(0,s.useRef)(null),we=(0,s.useRef)(null),[ve,de]=(0,s.useState)(0),[Te,$e]=(0,s.useState)(!1),[ot,I]=(0,s.useState)(()=>yi(e,t)?"blocked":"idle"),[ke,ge]=(0,s.useState)("google_pay"),j=(0,s.useRef)(null),Ee=(0,s.useRef)(!0),Q=(0,s.useRef)(!1),Be=(0,s.useRef)("google_pay"),ee=(0,s.useRef)("google_pay"),Je=(0,s.useRef)(null),st=(0,s.useRef)(null),De=(0,s.useRef)(new Set),et=(0,s.useRef)(null);(0,s.useEffect)(()=>(Ee.current=!0,()=>{Ee.current=!1;for(let z of De.current)window.clearTimeout(z);De.current.clear()}),[]);let tt=(0,s.useRef)(new Map),{startAttempt:pt,finishAttempt:Ae,invalidateAttempt:At,isAttemptInvalidated:kt,isAttemptCurrent:gt,generationRef:Ct}=fa((z,f,C)=>{g?.(z,f,{...C,popupBlocked:C?.popupBlocked??oo(f),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ge(z),$e(!0),de(Z=>Z+1)},{onHandoffObserved:z=>{T.markAvailable(),V?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Ct.current,...z==="apple_pay"||z==="google_pay"?{walletType:z}:{}})},defersMissingTerminal:uc,onMissingTerminalDeferred:(z,f)=>{let C=V?.now()??globalThis.performance?.now()??Date.now(),Z=et.current,K=Z?.generation===f?Z.startedAt:C;V?.performance({stage:"overlay_return",durationMs:Math.max(0,C-K),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:f,...uc(z)?{walletType:z}:{}}),V?.flush?.().catch(()=>{})}});(0,s.useEffect)(()=>{Te&&we.current?.focus()},[Te,ve]);let $=(0,s.useCallback)(()=>{de(z=>z+1)},[]),he=(0,s.useCallback)((z,f,C,Z,K=!1)=>{At(Z),g?.(z,f,{code:C,popupBlocked:oo(f),telemetryReported:K,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ge(z),$e(!0),$()},[At,g,$]),Ue=(0,s.useCallback)(()=>{window.setTimeout(()=>{(xe.current?.querySelector("iframe")??xe.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{Q.current&&(Q.current=!1,Ue())},[Ue,ve]);let v=(0,s.useCallback)(()=>{$e(!1),c?.(null),Ue()},[Ue,c]),J=(0,s.useCallback)(()=>{j.current?.()},[]);(0,s.useEffect)(()=>{let z=yi(e,t);if(!z)return;let f=!1,C=!1,Z=async()=>{if(!C){C=!0,f||I("checking");try{let K=await rc(A,z.clientSecret,De.current);if(f)return;let Pe=ys(K,z.providerObjectId,(0,y.isSetupIntentClientSecret)(z.clientSecret));if(Pe.kind==="confirmed"){if(!nc(e,t,z.clientSecret))return;j.current=null,I("idle"),i({id:Pe.paymentMethodId,type:"card",threeDSecureActionResultTokenId:Pe.intentId},{...z.accountPatch?{accountPatch:z.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(Pe.kind==="terminal"){ms(e,t,z.clientSecret),j.current=null,I("idle"),ge(z.paymentMethodType),$e(!0),$();return}I("blocked")}catch{f||I("blocked")}finally{C=!1}}};return j.current=Z,I("blocked"),()=>{f=!0,j.current===Z&&(j.current=null)}},[t,i,$,e,A]);let Fe=(0,s.useCallback)(async z=>{let f=!1,C=mt=>{f||(f=!0,z.paymentFailed({reason:"fail",...mt?{message:mt}:{}}))};if(!A||!re){C();return}let Z=tt.current.get(ve);if(Z&&!gt(Z.generation)){tt.current.delete(ve),C();return}if(!Z&&kt()){C();return}if(Z&&!Ae(Z.generation)){C();return}Z||Ae();let K=z.expressPaymentType??Z?.method??Be.current,Pe=Z??null,Bt=sc(K),We;K==="apple_pay"?We="apple_pay":K==="google_pay"&&(We="google_pay");let Ze=Z?.generation??Ct.current,Se=V,bt=Se?.now()??globalThis.performance?.now()??Date.now(),Wt=new AbortController,Ye=!1,Tn=!1,Re=null,zn=e,Un="processing",Mt="other",kn="provider_runtime",An,Kn=new Promise((mt,nt)=>{An=nt}),mn=window.setTimeout(()=>{Ye=!0,Wt.abort(),An(pi)},vu),Dt=async(mt,nt,Rn)=>{Un=mt,Mt=nt,kn=nt==="intent_create"||nt==="session_claim"?"transport_error":"provider_runtime";let xt=Se?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Rn,Kn])}finally{let In=Se?.now()??globalThis.performance?.now()??Date.now();Se?.performance({stage:mt,durationMs:Math.max(0,In-xt),durationMode:"machine",requestCategory:nt,paymentMethodCategory:"wallet",provider:"stripe",...Ye?{statusClass:"timeout"}:{}})}};try{if(Ne(!0),c?.(null),!Pe&&P){let Ie=await Dt("processing","other",P(Bt));if(!Ie.proceed){C();return}Pe={accountPatch:Ie.accountPatch,sessionId:Ie.sessionId,nonce:Ie.nonce}}let mt=Pe?.sessionId??e;zn=mt;let nt=Pe?.nonce??t,Rn=Je.current??Pe?.accountPatch,xt=bc({event:z,fallbackEmail:Rn?.email??n,fallbackName:[Rn?.firstName,Rn?.lastName].join(" ").trim()||R});if(!(0,y.isValidEmail)(xt.email)){C("Buyer details are required."),ze(Ps(K),xt).then(Ie=>{Ie&&(Je.current=Ie)});return}Je.current=null;let In={...Pe?.accountPatch,...On(xt,!0)};await Dt("processing","session_claim",Promise.resolve(E?.(xt)));let{error:yn}=await Dt("tokenization","provider_sdk",re.submit());if(yn){C(),he(K,yn,"stripe_wallet_submit_failed",Z?.generation);return}if(!mt)throw new Error("Missing sessionId or email for payment.");let Ht={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:K,paymentMethodId:null,intentKind:o},sn=JSON.stringify({sessionId:mt,nonce:nt??"",request:Ht}),Gn=st.current,Yn=Gn?.retryIdentity===sn?Gn.authorizationAttemptId:(0,y.randomUuidV4)();st.current={authorizationAttemptId:Yn,retryIdentity:sn};let Et=await Dt("processing","intent_create",fi(r,W,mt,nt??"",{...Ht,authorizationAttemptId:Yn},{signal:Wt.signal}));if(Et.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let St=Et.clientSecret,vn=wu({createdAt:Date.now(),sessionId:mt,...nt?{nonce:nt}:{},clientSecret:St,providerObjectId:Et.providerObjectId,paymentMethodType:K,accountPatch:In});window.clearTimeout(mn),Tn=!0,Se?.performance({stage:"callback",durationMs:Math.max(0,(Se?.now()??globalThis.performance?.now()??Date.now())-bt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let rn=Se?.now()??globalThis.performance?.now()??Date.now(),Ot={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...We?{walletType:We}:{},attempt:Ze},ln=!1,Zt=null;Se?.log({name:"payment.provider_confirmation.started",...Ot}),Re=window.setTimeout(()=>{Re!==null&&De.current.delete(Re),ln=!0;let Ie=Se?.now()??globalThis.performance?.now()??Date.now();Se?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Ot,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Ie-rn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Se?.flush?.().catch(()=>{}),Zt?.()},Cu),De.current.add(Re);let Lt=(Ie,pe)=>{Re!==null&&(window.clearTimeout(Re),De.current.delete(Re),Re=null);let B=Se?.now()??globalThis.performance?.now()??Date.now(),lt=Math.max(0,B-rn),ie=Ie;ln&&(Ie==="resolved"?ie="resolved_late":Ie==="returned_error"?ie="returned_error_late":ie="rejected_late");let Sn=pe??(Ie==="resolved"?"approved":"provider_error");return Se?.log({name:"payment.provider_confirmation.returned",...Ot,operationOutcome:ie,terminalReason:Sn}),Se?.performance({...Ot,durationMs:lt,durationMode:"buyer",operationOutcome:ie,terminalReason:Sn}),{durationMs:lt,operationOutcome:ie,terminalReason:Sn}},se=!1,cn=!1,qn=Ie=>{if(!Ie||typeof Ie!="object")return null;let pe=Ie;if(pe.error)return null;let B=pe.setupIntent??pe.paymentIntent,lt=ys(B??null,void 0,!!pe.setupIntent);return lt.kind==="confirmed"?lt:null},Lr=Ie=>{if(se||Z&&Ct.current!==Z.generation)return;let pe=qn(Ie);if(!pe)return;if(vn&&!nc(mt,nt,St)){se=!0;return}let{intentId:B,paymentMethodId:lt}=pe;se=!0,cn=!0,st.current=null,j.current=null,Ee.current&&(I("idle"),Ne(!1));let ie=`${yc}:${mt}`;$t(ie,{createdAt:Date.now(),sessionId:mt,nonce:nt,accountPatch:In,paymentMethodId:lt,providerIntentId:B,paymentMethodType:K});try{i({id:lt,type:"card",threeDSecureActionResultTokenId:B},{accountPatch:In,paymentMethodCategory:"wallet",sessionId:mt,nonce:nt})}finally{$t(ie)}},sr=!1;Zt=async()=>{if(!(sr||se||cn)){sr=!0,Ee.current&&I("checking");try{let Ie=await rc(A,St,De.current);if(se||cn)return;let pe=(0,y.isSetupIntentClientSecret)(St),B=ys(Ie,Et.providerObjectId,pe);if(B.kind==="confirmed"){Lr(pe?{setupIntent:Ie}:{paymentIntent:Ie});return}if(B.kind==="terminal"){if(cn=!0,ms(mt,nt,St),st.current=null,j.current=null,!Ee.current)return;I("idle"),C(),he(K,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",Z?.generation,!0);return}Ee.current&&!cn&&(I("blocked"),Ne(!1))}catch{Ee.current&&!cn&&(I("blocked"),Ne(!1))}finally{sr=!1}}},j.current=Zt;let Ut,lr;try{let Ie=await((0,y.isSetupIntentClientSecret)(St)?A.confirmSetup({elements:re,clientSecret:St,redirect:"if_required"}):A.confirmPayment({elements:re,clientSecret:St,redirect:"if_required"}));if(!Ie||typeof Ie!="object"||(Ut=Ie,!Ut.error&&!qn(Ut)))throw ps;lr=Lt(Ut.error?"returned_error":"resolved",Ut.error&&go(Ut.error)?"provider_declined":void 0)}catch(Ie){let pe=Ie===ps,B=Lt(pe?"returned_error":"rejected");if(Se?.error({...pe?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:Yi(Ie),...Ot,operationOutcome:B.operationOutcome,durationMs:B.durationMs,statusClass:"unknown",terminalReason:B.terminalReason}),!Ee.current||se)return;await Zt?.();return}let Cn=Ut.error;if(Cn){if(!Ee.current||se)return;if(go(Cn)){cn=!0,ms(mt,nt,St),st.current=null,j.current=null,I("idle");let Ie=Cn.message??"Your payment was declined.";C(Ie),c?.(Ie),u?.(un(Bt,Ie,{code:Mr(Cn),declineCode:No(Cn)})),gi({billingApiUrl:r,sessionId:mt,nonce:nt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:K,providerDeclineReason:Mr(Cn)??"provider_declined",...Et.intentKind==="payment"&&Et.providerObjectId.startsWith("pi_")?{providerIntentId:Et.providerObjectId}:{}}})}else Se?.error({...Yi(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===pi){let nt=Se?.now()??globalThis.performance?.now()??Date.now();Se?.error({errorCode:Ru(Mt),stage:Un,requestCategory:Mt,paymentMethodCategory:"wallet",provider:"stripe",...We?{walletType:We}:{},operationOutcome:"watchdog_expired",checkoutSessionId:zn,durationMs:Math.max(0,nt-bt),statusClass:"timeout",failureCategory:kn,attempt:Ze,terminalReason:"provider_error"}),Se?.flush?.().catch(()=>{})}C(),he(K,mt,mt===pi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",Z?.generation,mt===pi)}finally{if(window.clearTimeout(mn),Re!==null&&(window.clearTimeout(Re),De.current.delete(Re)),!Tn){let mt=Se?.now()??globalThis.performance?.now()??Date.now();Se?.performance({stage:"callback",durationMs:Math.max(0,mt-bt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Ye?{statusClass:"timeout"}:{}})}Ee.current&&Ne(!1)}},[A,re,e,t,n,R,ze,E,r,W,o,i,c,u,P,he,Ae,gt,kt,Ct,V,ve]),ue=(0,s.useMemo)(()=>{let z=["applePay","googlePay","paypal","link","amazonPay","klarna"],f=new Set(["applePay","googlePay"]),C=new Set(a.map(y.stripeExpressMethodToOptionKey)),Z={};for(let K of z)C.has(K)?Z[K]=f.has(K)?"always":"auto":Z[K]="never";return Z},[a]),Ce=(0,s.useMemo)(()=>a.map(y.stripeExpressMethodToOptionKey),[a]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Cc,{state:Y,placeholderTestId:"flopay-wallet-placeholder",borderRadius:M,children:(0,d.jsxs)("div",{ref:xe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Te&&(0,d.jsxs)("button",{ref:we,type:"button","data-testid":"flopay-wallet-retry-button",onClick:v,style:hs,children:["Try ",Ps(ke)," again"]}),ot!=="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:J,disabled:ot==="checking",style:hs,children:ot==="checking"?"Checking payment status\u2026":"Check payment status"})]}),oe&&(0,d.jsx)(Lo,{identity:oe.identity,methodLabel:oe.methodLabel,onComplete:ut,onCancel:()=>ut(null)},oe.id),ot==="idle"&&(0,d.jsx)("div",{style:{display:oe?"none":void 0},children:(0,d.jsx)(Jt.ExpressCheckoutElement,{onReady:z=>{le(vc(z,Ce))},onLoadError:z=>{le("load_error"),ws(V,"stripe","wallet","provider_error")},onClick:async z=>{let f=V?.now()??globalThis.performance?.now()??Date.now();Be.current=z.expressPaymentType,ee.current=sc(z.expressPaymentType);let C=!0,Z=window.setTimeout(()=>{C=!1,z.reject()},bu),K=P?await P(ee.current):{proceed:!0};if(window.clearTimeout(Z),!C)return;if(!K.proceed){tt.current.delete(ve),z.reject();return}let Pe=pt(z.expressPaymentType);et.current={generation:Pe,startedAt:f},tt.current.set(ve,{generation:Pe,method:z.expressPaymentType,accountPatch:K.accountPatch,sessionId:K.sessionId,nonce:K.nonce}),$e(!1),V?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Pe,...z.expressPaymentType==="apple_pay"||z.expressPaymentType==="google_pay"?{walletType:z.expressPaymentType}:{}}),p?.(ee.current),z.resolve()},onConfirm:Fe,onCancel:()=>{let z=tt.current.get(ve);tt.current.delete(ve),V?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...z?{attempt:z.generation}:{}}),At(z?.generation),st.current=null,$e(!1),Q.current=!0,$()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ue,emailRequired:je,billingAddressRequired:je,layout:{maxColumns:1,overflow:"never"}}},ve)})]})}),H&&(0,d.jsx)(Ln,{status:"processing"})]})}function Sc(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function ju({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:i,backgroundColor:c,borderColor:p,textColor:u,borderRadius:g,fontFamily:P}){let R=(0,y.resolveStripeMethodBrandVariant)(e,t),E=Wl[e],[w,M]=(0,s.useState)(!1),T=!!E&&!w,b=R?.backgroundColor??c??"#ffffff",S=R?.borderColor??p??"#d1d5db",W=R?.textColor??u??"#262833";return(0,d.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&i()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Ia,padding:"0 1rem",backgroundColor:b,color:W,border:`1px solid ${S}`,borderRadius:g??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,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:[T?(0,d.jsx)("img",{src:E,alt:"","aria-hidden":"true",onError:()=>M(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!T&&R?.logoSvg?(0,d.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:R.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:W,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,d.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function bs({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:c,onErrorChange:p,onDecline:u,onCancel:g,runBeforeButtonClick:P,onButtonClick:R,isProcessing:E,submitButtonColor:w,submitButtonBorderRadius:M,submitButtonStyle:T,errorText:b}){let S=Hr(),{emitInstrument:W}=(0,s.useContext)(tr),A=(0,Jt.useStripe)(),re=(0,Jt.useElements)(),[V,Y]=(0,s.useState)(!1),le=(0,s.useRef)(!1),[H,Ne]=(0,s.useState)(!1),[je,oe]=(0,s.useState)("loading"),[ze,ut]=(0,s.useState)(""),xe=!(0,y.isValidEmail)(r?.trim()),we=!xe||(0,y.isValidEmail)(ze.trim()),ve=(0,s.useCallback)(async()=>{if(!A||!re||E||le.current||!H)return;le.current=!0,Y(!0);let de=P?await P("card"):{proceed:!0};if(!de.proceed){le.current=!1,Y(!1);return}R?.("card");let Te=de.sessionId??t,$e=de.nonce??n,ot=yo(o?.trim()),I=On({email:de.accountPatch?.email?.trim()||r?.trim()||ze.trim(),firstName:de.accountPatch?.firstName?.trim()||ot.firstName,lastName:de.accountPatch?.lastName?.trim()||ot.lastName}),ke=I.email,ge=On({...de.accountPatch,...I});try{if(p?.(null),!(0,y.isValidEmail)(ke))throw new Error("A valid email address is required for payment.");await a?.(I);let j=await re.submit();if(j.error){p?.(j.error.message??"Payment failed.");return}let Ee=[I.firstName,I.lastName].filter(Boolean).join(" "),Q=await A.createPaymentMethod({elements:re,params:{billing_details:{email:ke,...Ee?{name:Ee}:{}}}});if(Q.error||!Q.paymentMethod){p?.(Q.error?.message??"Failed to create payment method.");return}let Be=Q.paymentMethod;if(!Te||!ke)throw new Error("Missing sessionId or email for payment.");let ee=Be.type||e,Je=await fi(i,W,Te,$e??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,paymentMethodId:null,intentKind:"payment"});if(Je.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let st=Je.clientSecret;$t(Fr,{clientSecret:st,sessionId:Te,nonce:$e,accountPatch:ge,paymentMethodId:Be.id,paymentMethodType:Be.type??e,gateway:"stripe"});let{error:De,paymentIntent:et}=await A.confirmPayment({clientSecret:st,confirmParams:{return_url:window.location.href,payment_method:Be.id},redirect:"if_required"});if(De){$t(Fr);let Ae=De.message??"Payment failed.";p?.(Ae),u?.(un("card",Ae,{code:De.code})),await gi({billingApiUrl:i,sessionId:Te,nonce:$e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:De.code??"provider_declined"}});return}let tt=et?.status;if(!ua(tt)){$t(Fr);let Ae=tt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(Ae),u?.(un("card",Ae,{code:tt??"missing_payment_intent"}));return}$t(Fr);let pt=typeof et?.payment_method=="string"?et.payment_method:et?.payment_method?.id;c({id:pt??Be.id,type:"card",threeDSecureActionResultTokenId:et?.id,gateway:"stripe",paymentMethodType:Be.type??e},{accountPatch:ge,paymentMethodCategory:"apm",sessionId:Te,nonce:$e})}catch(j){p?.(j instanceof Error?j.message:"Payment failed. Please try again.")}finally{le.current=!1,Y(!1)}},[A,re,E,H,P,R,t,n,r,o,ze,a,i,W,e,c,p,u]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[xe&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:xe&&(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:ze,onChange:de=>ut(de.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(Jt.PaymentElement,{onReady:()=>oe("ready"),onLoadError:()=>{oe("load_error"),ws(pn(S),"stripe","apm")},onChange:de=>{Ne(!!de.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:!H||!we||V||E||je!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:w,color:"white",border:"none",borderRadius:M,fontSize:"1rem",fontWeight:600,cursor:!H||!we||V||E||je!=="ready"?"not-allowed":"pointer",opacity:!H||!we||V||E||je!=="ready"?.5:1,transition:"opacity 120ms ease-out",...T??{}},children:V?"Processing\u2026":`Pay with ${(0,y.getStripeMethodDisplayName)(e)}`}),b&&(0,d.jsx)(Uo,{margin:"0.75rem 0 0",children:b})]})}function mc({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:i,stripeInstance:c,paymentElementBaseOptions:p,onTokenizedBody:u,onErrorChange:g,onButtonClick:P,onDecline:R,runBeforeButtonClick:E,onLoadStateChange:w,isProcessing:M=!1,submitButtonColor:T="#4A49FF",submitButtonBorderRadius:b=8,submitButtonStyle:S,buttonAppearance:W,themeId:A,onExpandApm:re,expandedApmMethod:V}){let{emitInstrument:Y}=(0,s.useContext)(tr),[le,H]=(0,s.useState)(null),[Ne,je]=(0,s.useState)(null),oe=(0,s.useRef)(!1),{request:ze,collect:ut,finish:xe}=Oo();(0,s.useEffect)(()=>{i.length>0&&c?w?.("ready"):c||w?.("loading")},[i.length,c,w]);let we=(0,s.useCallback)(async I=>{if(!c||oe.current||M)return;oe.current=!0,je(I);let ke=E?await E("card"):{proceed:!0};if(!ke.proceed){oe.current=!1,je(null);return}P?.("card");let ge=ke.sessionId??e,j=ke.nonce??t,Ee=yo([ke.accountPatch?.firstName,ke.accountPatch?.lastName].filter(Boolean).join(" ")||r),Q=On({email:ke.accountPatch?.email?.trim()||n?.trim(),firstName:ke.accountPatch?.firstName?.trim()||Ee.firstName,lastName:ke.accountPatch?.lastName?.trim()||Ee.lastName});if(!(0,y.isValidEmail)(Q.email)){je(null);let Je=await ut((0,y.getStripeMethodDisplayName)(I),Q);if(!Je){oe.current=!1;return}Q=Je,je(I)}let Be=Q.email,ee=On({...ke.accountPatch,...Q});try{if(g?.(null),!ge||!(0,y.isValidEmail)(Be))throw new Error("Missing sessionId or email for payment.");await o?.(Q);let Je=await fi(a,Y,ge,j??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:I,paymentMethodId:null,intentKind:"payment"});if(Je.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let st=Je.clientSecret;$t(Fr,{clientSecret:st,sessionId:ge,nonce:j,accountPatch:ee,paymentMethodType:I,gateway:"stripe"});let{error:De,paymentIntent:et}=await c.confirmPayment({clientSecret:st,confirmParams:{return_url:window.location.href,payment_method_data:{type:I,billing_details:{name:[Q.firstName,Q.lastName].filter(Boolean).join(" "),...Be?{email:Be}:{}}}},redirect:"if_required"});if(De){$t(Fr);let Ae=De.message??"Payment failed.";g?.(Ae),R?.(un("card",Ae,{code:De.code})),await gi({billingApiUrl:a,sessionId:ge,nonce:j,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:I,providerDeclineReason:De.code??"provider_declined"}});return}let tt=et?.status;if(!ua(tt)){$t(Fr);let Ae=tt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(Ae),R?.(un("card",Ae,{code:tt??"missing_payment_intent"}));return}$t(Fr);let pt=typeof et?.payment_method=="string"?et.payment_method:et?.payment_method?.id;u({id:pt??et?.id,type:"card",threeDSecureActionResultTokenId:et?.id,gateway:"stripe",paymentMethodType:I},{accountPatch:ee,paymentMethodCategory:"apm",sessionId:ge,nonce:j})}catch(Je){g?.(Je instanceof Error?Je.message:"Payment failed. Please try again.")}finally{oe.current=!1,je(null)}},[c,M,E,P,e,t,n,ut,a,Y,r,o,u,g,R]),[ve,de]=(0,s.useState)(null),Te=re?V??null:ve,$e=(0,s.useCallback)(I=>{oe.current||M||Te&&Te!==I||((0,y.needsStripeMethodExplicitConfirm)(I)?re?re(I):de(I):we(I))},[Te,M,we,re]),ot=(0,s.useMemo)(()=>ve?Sc(p,ve):null,[ve,p]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:ze?(0,d.jsx)(Lo,{identity:ze.identity,methodLabel:ze.methodLabel,onComplete:xe,onCancel:()=>xe(null)},ze.id):i.map(I=>{let ke=V===I,ge=Ne===I,j=Ne!==null&&Ne!==I||V!=null&&V!==I;return(0,d.jsxs)(s.default.Fragment,{children:[(0,d.jsx)(ju,{method:I,themeId:A,submitting:ge,disabled:j,highlighted:ke,hasNextStep:(0,y.needsStripeMethodExplicitConfirm)(I),onClick:()=>$e(I),backgroundColor:W?.backgroundColor,borderColor:W?.borderColor,textColor:W?.textColor,borderRadius:W?.borderRadius,fontFamily:W?.fontFamily}),!re&&ve===I&&ot&&c&&(0,d.jsx)(Jt.Elements,{stripe:c,options:ot,children:(0,d.jsx)(bs,{method:I,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:u,onErrorChange:g,onDecline:R,onCancel:()=>de(null),runBeforeButtonClick:E,onButtonClick:P,isProcessing:M,submitButtonColor:T,submitButtonBorderRadius:b,submitButtonStyle:S})},I)]},I)})})}function $u({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:i,onError:c,onDecline:p,onTokenizedBody:u,firstName:g,lastName:P,chv:R,className:E,submitLabel:w,isProcessing:M,error:T,onErrorChange:b,showPayPal:S=!0,showStripe:W=!0,walletPresentation:A="auto",enabledPaymentMethods:re,enabledPaymentMethodCountries:V,showApplePay:Y=!0,showGooglePay:le=!0,layout:H="default",theme:Ne,buttonsTheme:je,buttonsStyles:oe,appearance:ze,cardButtonContent:ut,cardBackButtonContent:xe,cardTitleContent:we,showSecurityFooter:ve,onButtonClick:de,onBeforeButtonClick:Te,onBuyerIdentityReady:$e,enableAVS:ot,cardFieldOrder:I,cardPreFormSlot:ke,avsLayout:ge="row",country:j,zip:Ee,addressLine1:Q,addressLine2:Be,city:ee,state:Je,onCountryChange:st,onZipChange:De,avsCheck:et,checkoutType:tt,checkoutLayout:pt,totalAmount:Ae=0,currency:At="usd",initialCardOpen:kt=!1,directPaypal:gt,isSubscription:Ct=!1,session:$,dataAttachmentPending:he=!1,dataAttachmentRequiresIdentity:Ue=!1,debug:v=!1}){let J=Hr(),Fe=Ha(),ue=(0,s.useContext)(Pr),{emitInstrument:Ce}=(0,s.useContext)(tr),z=(0,s.useRef)(null);z.current||(z.current=Xa());let f=z.current,[,C]=(0,s.useState)(0),Z=(0,s.useRef)(null);Z.current||(Z.current=Kr());let K=Z.current,Pe=(0,s.useMemo)(()=>({browser:K,capability:f,presentationMode:"popup"}),[K,f]),Bt=$??ue.session,We=Bt?.gateways?.paypal?.providerObjectType??gt?.providerObjectType,Ze=he||ue.claimPending===!0,Se=Ue||ue.claimRequiresIdentity===!0,bt=Ze&&!Se,Wt=Ml(),Ye=n||Wt,[Tn,Re]=(0,s.useState)(!1),[zn,Un]=(0,s.useState)(null),[Mt,kn]=(0,s.useState)(j??""),[An,Kn]=(0,s.useState)(Ee??""),[mn,Dt]=(0,s.useState)(Q??""),[mt,nt]=(0,s.useState)(Be??""),[Rn,xt]=(0,s.useState)(ee??""),[In,yn]=(0,s.useState)(Je??""),[Ht,sn]=(0,s.useState)(""),[Gn,Yn]=(0,s.useState)({}),Et=(0,s.useRef)(Ee??""),St=(0,s.useRef)(j??""),vn=(0,s.useRef)(Q??""),rn=(0,s.useRef)(Be??""),Ot=(0,s.useRef)(ee??""),ln=(0,s.useRef)(Je??""),Zt=(0,s.useRef)(""),Lt=(0,s.useRef)({});(0,s.useEffect)(()=>{let l=(_,ne,Ve,ce,Oe)=>{if(Lt.current[_])return;let Xt=ne?.trim();!Xt||Xt===Ve.current||(Ve.current=Xt,ce(Xt),Oe?.(Xt))};l("country",j,St,kn,st),l("zip",Ee,Et,Kn,De),l("addressLine1",Q,vn,Dt),l("addressLine2",Be,rn,nt),l("city",ee,Ot,xt),l("state",Je,ln,yn)},[j,Ee,Q,Be,ee,Je,st,De]);let se=(0,s.useMemo)(()=>(0,y.resolveAVSConfig)(ot),[ot]),cn=se!==null,qn=(0,s.useMemo)(()=>(0,y.isAuthorizationOnlySession)($),[$]),Lr=!!$?.vault?.html,sr=!!$?.gateways?.pcivault,Ut=Hi($),Cn=!!($?.gateways?.stripe?.enabledPaymentMethods??re)?.includes("card")||Zr($),Ie=Lr||Cn||sr,pe=!!(W&&Ie&&e),[B,lt]=(0,s.useState)(()=>H!=="buttons"||kt?e??null:null),[ie,Sn]=(0,s.useState)(0),fn=H!=="buttons"||kt||!!e&&B===e,Kt=$?.captureMethod,Xn=(0,s.useRef)(J);(0,s.useEffect)(()=>{Xn.current=J},[J]);let[yt,Xr]=(0,s.useState)(null);(0,s.useEffect)(()=>{if(!pe||!e||!fn){Xr(null);return}let l=Xn.current?Xn.current.cardCapture({sessionId:e,captureMethod:Kt}):new Cr.PciVaultCardCapture({sessionId:e,captureMethod:Kt,billingApiUrl:Ye,telemetry:r});return Xr({sessionId:e,captureMethod:Kt,billingApiUrl:Ye,telemetry:r,capture:l}),()=>{l.unmount()}},[pe,e,fn,Kt,Ye,r]);let Gt=pe&&e&&fn&&yt?.sessionId===e&&yt.captureMethod===Kt&&yt.billingApiUrl===Ye&&yt.telemetry===r?yt.capture:null,gn=(0,s.useMemo)(()=>{let l=Mt,_=se?(0,y.isAVSFieldVisible)(se.postal_code,l):!1;return Uu(l,An,_)},[se,Mt,An]),{avsInvalid:Nr,invalidAvsFields:zr}=(0,s.useMemo)(()=>{let l={line1:!1,city:!1,state:!1,zip:!1};if(!pe||!se)return{avsInvalid:!1,invalidAvsFields:l};let _=Mt,ne=(Oe,Xt)=>(0,y.isAVSFieldVisible)(Oe,_)&&!Xt.trim(),Ve={line1:ne(se.address_line_1,mn),city:ne(se.city,Rn),state:ne(se.state,In),zip:gn.empty||gn.malformed};return{avsInvalid:Ve.line1||Ve.city||Ve.state||Ve.zip,invalidAvsFields:Ve}},[pe,se,Mt,mn,Rn,In,gn]),[Mn,Qt]=(0,s.useState)(!1),[Sr,xn]=(0,s.useState)(!1),[Ur,Fn]=(0,s.useState)(!1),[wr,kr]=(0,s.useState)({line1:!1,city:!1,state:!1}),cr=(0,s.useRef)(!1),Jn=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Zn=(0,s.useRef)(!1),Ft=(0,s.useCallback)(l=>{Jn.current[l]=!0,Zn.current=!0},[]),dr=(0,s.useCallback)(l=>!cr.current&&Jn.current[l],[]),_n=(0,s.useCallback)(l=>{dr(l)&&kr(_=>_[l]?_:{..._,[l]:!0})},[dr]),[Qn,Rr]=(0,s.useState)(()=>fs($?.vault)),[ft,on]=(0,s.useState)(kt&&Ie?"card":"buttons"),[en,qr]=(0,s.useState)(null),Vn=ft==="expanding"||ft==="card",Jr=$?.gateways?.stripe&&!Ut?"stripe":void 0,ur=(0,s.useCallback)(()=>{Ce?.({class:"card_surface",provider:Jr})},[Jr,Ce]),pr=(0,s.useRef)(null),hn=(0,s.useCallback)(l=>{pr.current&&clearTimeout(pr.current),pr.current=setTimeout(()=>{pr.current=null,l()},_a)},[]);(0,s.useEffect)(()=>()=>{pr.current&&clearTimeout(pr.current)},[]);let mr=(0,s.useCallback)(()=>{ur(),lt(e??null),Sn(l=>l+1),on("expanding"),hn(()=>on("card"))},[hn,ur,e]),Vr=(0,s.useCallback)(()=>{on("collapsing"),hn(()=>on("buttons"))},[hn]),En=(0,s.useCallback)(l=>{qr(l),on("apm-expanding"),hn(()=>on("apm-form"))},[hn]),L=(0,s.useCallback)(()=>{on("apm-collapsing"),hn(()=>{on("buttons"),qr(null)})},[hn]);(0,s.useEffect)(()=>{H==="buttons"&&kt&&Ie&&(lt(e??null),on("card"))},[H,kt,Ie,e]);let[q,O]=(0,s.useState)(null),ye=(0,s.useRef)(!1),He=(0,s.useRef)(null),ht=(0,s.useRef)("idle"),[be,Ke]=(0,s.useState)(!1),te=(0,s.useRef)(be);te.current=be;let[m,h]=(0,s.useState)(()=>gt?.existingOrderId?{orderId:gt.existingOrderId,attempts:1}:null),U=(0,s.useRef)(m);(0,s.useEffect)(()=>{U.current=m},[m]);let G=(0,s.useRef)(null),fe=(0,s.useMemo)(()=>{if($e||ue.claimBuyerIdentity||$?.buyerIdentified!==!1||!e||!t)return;let l=`${Ye}|${e}|${t}`;G.current?.key!==l&&(G.current={key:l,claim:Bo(new Cr.PaymentAPI(Ye,{telemetry:!1}),e,t,{...a?{userId:a}:{},...g?{firstName:g}:{},...P?{lastName:P}:{}})});let _=G.current.claim;return async ne=>{await _(ne)}},[$e,ue.claimBuyerIdentity,$?.buyerIdentified,e,t,Ye,a,g,P]),ae=$e??ue.claimBuyerIdentity??fe,at=T??zn,Rt=(0,s.useMemo)(()=>(0,y.resolveTheme)(Ne),[Ne]),D=(0,s.useMemo)(()=>{let l=Rt?.buttonsLayout??(0,y.resolveButtonsLayoutTheme)(je);return oe?{...l,...oe,cardButton:{...l.cardButton,...oe.cardButton},cardFormContainer:{...l.cardFormContainer,...oe.cardFormContainer},backButton:{...l.backButton,...oe.backButton},backButtonIcon:{...l.backButtonIcon,...oe.backButtonIcon},submitButton:{...l.submitButton,...oe.submitButton},title:{...l.title,...oe.title}}:l},[Rt,je,oe]),Me=ze??Rt?.appearance,Tt=(0,s.useMemo)(()=>Go({appearance:Me,buttonsStyles:D,layout:H}),[Me,D,H]),_e=ue.inlineSessionPatchProcessing??!1,X=(M??Tn)||_e,me=Ye.replace(/\/+$/,""),F=(0,s.useMemo)(()=>Gi({userId:a,email:o,firstName:g,lastName:P,country:j,zip:Ee},Gn),[a,o,g,P,j,Ee,Gn]),Qe=[F.firstName,F.lastName].filter(l=>!!l?.trim()).join(" "),It=!(0,y.isValidEmail)(F.email?.trim()),qe=(0,s.useRef)(null);pe&&qe.current===null&&(qe.current=It);let wn=pe&&(qe.current??It),Ir=(0,s.useMemo)(()=>qu(Ht,wn),[Ht,wn]),Co=Ir.empty||Ir.malformed,jn=(0,s.useMemo)(()=>J?J.getRawProvider():null,[J]),Ds=(0,s.useMemo)(()=>Fe?Fe.getRawProvider():null,[Fe]),Jo=Ae||100,So=At.toLowerCase(),_i=(0,s.useMemo)(()=>Me?(0,Cr.toStripeAppearance)(Me):null,[Me]),wo=_i,Os=(0,s.useMemo)(()=>{let l=_i??{},_=l.rules??{};return{...l,rules:{..._,".AccordionItem":{padding:"10px 14px",boxShadow:"none",..._[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",..._[".AccordionItemContents"]??{}}}}},[_i]),Ls=(0,s.useMemo)(()=>({...Il(Ae,$?.captureMethod),currency:So,...wo?{appearance:wo}:null}),[Ae,So,$?.captureMethod,wo]),Ns=(0,s.useMemo)(()=>({mode:"payment",amount:Jo,currency:So,captureMethod:"manual",setupFutureUsage:"off_session",...wo?{appearance:wo}:null}),[Jo,So,wo]),Le=(0,s.useCallback)(l=>{Un(l),b?.(l)},[b]),Ei=(0,s.useRef)(""),[zs,Qc]=(0,s.useState)(!1),Ti=(0,s.useCallback)(()=>{Qc(!0)},[]);(0,s.useEffect)(()=>{if(!pe||!wn||!ae||!zs||Co||Ei.current)return;let l=On({email:(0,y.isValidEmail)(F.email?.trim())?F.email?.trim():Zt.current.trim(),firstName:F.firstName?.trim(),lastName:F.lastName?.trim()});Ei.current=JSON.stringify(l),Yn(_=>({..._,...l})),Promise.resolve(ae(l)).catch(_=>{Ei.current="",Le(_ instanceof Error?_.message:"Failed to attach buyer details.")})},[pe,wn,ae,zs,Co,F.email,F.firstName,F.lastName,Le]),(0,s.useEffect)(()=>{!pe||!Gt||Gt.setCardFieldOrder?.(I??null,se==null&&!wn)},[pe,Gt,I,se,wn]),(0,s.useEffect)(()=>{(ft==="expanding"||ft==="collapsing"||ft==="apm-expanding"||ft==="apm-collapsing")&&Le(null)},[ft,Le]);let _r=(0,s.useCallback)((l,_,ne)=>{p?.(un(l,_,ne))},[p]),ko=(0,s.useCallback)((l,_,ne)=>{let Ve=ne?.popupBlocked??oo(_);Ve&&f.markBlocked()&&C(dt=>dt+1);let ce=no(Ps(l),Ve,K.inAppBrowser),Oe=Mr(_),Xt=(Oe?.toLowerCase()==="error"?void 0:Oe)??fo(ne?.code)??"external_payment_method_failed",gr=new y.FloPayError(ce,"api_error",{code:"external_payment_method_failed",param:l,details:{providerCode:Xt,popupBlocked:Ve,inAppBrowser:K.inAppBrowser,appFamily:K.appFamily,popupCapability:f.current(),presentationMode:ne?.presentationMode??"popup"}});ne?.telemetryReported||pn(J)?.error(Ho({...Pe,presentationMode:ne?.presentationMode??"popup"},{errorCode:Ve?"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??(Ve?"popup_blocked":"provider_error")})),O(null),H==="buttons"&&(on("buttons"),qr(null)),Le(ce),c?.(gr),console.error("[FloPay] External payment method failed:",{method:l,code:Xt,popupBlocked:Ve})},[K,Pe,J,H,c,f,Le]);(0,s.useEffect)(()=>{if(!pe||!e){Rr(null);return}let l=fs($?.vault);if(l){Rr(l);return}if(!fn){Rr(null);return}Rr(null);let _=!0;return new Cr.PaymentAPI(me).getVaultCapture(e,t).then(ne=>{if(!_)return;let Ve=fs(ne);Ve?Rr(Ve):Le("Failed to load the secure card form.")}).catch(ne=>{_&&Le(ne instanceof Error?ne.message:"Failed to load the secure card form.")}),()=>{_=!1}},[pe,fn,ie,e,$?.vault,me,t,Le]);let yr=(0,s.useRef)({onComplete:i,onError:c,updateError:Le,emitDecline:_r,resolvedAccount:F,avsConfig:se,avsCheckProp:et,sessionId:e,nonce:t,baseUrl:me,captureMethod:$?.captureMethod,paymentId:$?.paymentId,authorizationExpiresAt:$?.authorizationExpiresAt,serverSideCardGateway:Ut});yr.current={onComplete:i,onError:c,updateError:Le,emitDecline:_r,resolvedAccount:F,avsConfig:se,avsCheckProp:et,sessionId:e,nonce:t,baseUrl:me,captureMethod:$?.captureMethod,paymentId:$?.paymentId,authorizationExpiresAt:$?.authorizationExpiresAt,serverSideCardGateway:Ut};let Ai=(0,s.useRef)(!1),Us=(0,s.useCallback)(()=>{let l=yr.current,_=l.resolvedAccount.email?.trim(),ne=(0,y.isValidEmail)(_)?_:Zt.current.trim();if(!(0,y.isValidEmail)(ne))return null;let Ve=l.resolvedAccount.firstName?.trim(),ce=l.resolvedAccount.lastName?.trim(),Oe=St.current.trim()||l.resolvedAccount.country?.trim()||"",Xt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.state,Oe):!1,gr=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_1,Oe):!1,dt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.postal_code,Oe):!1,Pt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.city,Oe):!1,wt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_2,Oe):!1,Vt=gr&&!Xt&&dt?(0,y.getStateFromPostalCode)(Oe,(Et.current??"").trim()):null,dn=Xt?ln.current:Vt;return{accountData:{userId:l.resolvedAccount.userId??"",email:ne,...Ve?{firstName:Ve}:{},...ce?{lastName:ce}:{},...dt&&Et.current?{zip:Et.current}:{},...Pt&&Ot.current?{city:Ot.current}:{},...dn?{state:dn}:{},...gr&&vn.current?{addressLine1:vn.current}:{},...wt&&rn.current?{addressLine2:rn.current}:{},...Oe?{country:Oe}:{}},...l.avsCheckProp===void 0?{}:{avsCheck:l.avsCheckProp},...l.avsConfig?{avsConfig:{country:(0,y.isAVSFieldVisible)(l.avsConfig.country,Oe),postal_code:dt,address_line_1:gr,address_line_2:wt,city:Pt,state:Xt}}:{}}},[]),qs=(0,s.useRef)(Ze);qs.current=Ze,(0,s.useEffect)(()=>{Ze||at!==oc||yr.current.updateError(null)},[Ze,at]),(0,s.useEffect)(()=>{!pe||!Gt||Gt.setSubmitGate?.(Nr||Ze||Co||be)},[pe,Gt,Nr,Ze,Co,be]),(0,s.useEffect)(()=>{if(!pe||!Gt)return;Ai.current=!1;let l=null,_=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null,ht.current="idle",O(null)},400)},ne=Gt.on("submitting",()=>{Qt(!0),He.current&&clearTimeout(He.current),ht.current="validation-window",He.current=setTimeout(()=>{He.current=null,ht.current==="validation-window"&&(ht.current="processing")},Eu),O("processing");let dt=yr.current;if(!dt.sessionId||!dt.nonce)return;let Pt=Us();if(!Pt){dt.updateError("Enter a valid email address."),ht.current="idle",O(null);return}new Cr.PaymentAPI(dt.baseUrl).patchAccountSnapshot(dt.sessionId,dt.nonce,Pt,{telemetryMode:"best_effort"}).catch(wt=>{if(!Au(wt))return;let Vt=wt instanceof Error?wt.message:"Please check your billing address and try again.";dt.updateError(Vt),ht.current="idle",O(null),dt.onError?.(wt instanceof y.FloPayError?wt:new y.FloPayError(Vt,"api_error"))})}),Ve=Gt.on("complete",async dt=>{if(jo(dt.sessionId??yr.current.sessionId),ht.current="terminal",Ke(!1),O("success"),await new Promise(dn=>setTimeout(dn,600)),Ai.current)return;Ai.current=!0;let Pt=yr.current,wt=(0,y.isAuthorizationOnlySession)(Pt)||dt.outcome==="authorized",Vt=Pt.serverSideCardGateway?{}:{paymentIntentId:dt.intentId};yr.current.onComplete?.(wt?{status:"authorized",...Vt,paymentId:dt.paymentId??Pt.paymentId,sessionId:dt.sessionId??Pt.sessionId,authorizationExpiresAt:dt.authorizationExpiresAt??Pt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Vt,checkoutMethod:"card"})}),ce=Gt.on("decline",dt=>{let Pt=yr.current,wt=dt.message??"Your payment was declined. Please try another card or contact your bank.";ht.current="terminal",Ke(!1),Pt.updateError(wt),O("error");let Vt=dt.failureOutcome??(0,y.normalizeCheckoutFailureOutcome)(dt.declineReason)??"authorization_declined";Pt.emitDecline("card",wt,{code:Vt,declineCode:Vt}),_()}),Oe=Gt.on("error",dt=>{let Pt=yr.current,wt=dt.message??"There was a problem processing your payment. Please try again.";ht.current="terminal",Ke(!1),Pt.updateError(wt),O("error"),Pt.onError?.(new y.FloPayError(wt,"api_error",{code:dt.failureOutcome??"capture_failed"})),_()}),Xt=Gt.on("challenge_dismissed",()=>{He.current&&(clearTimeout(He.current),He.current=null),ht.current="processing",Ke(!0),O(null)}),gr=Gt.on("blocked",()=>{if(te.current){yr.current.updateError(Tu);return}if(!qs.current){Qt(!0);return}Ti(),yr.current.updateError(oc)});return()=>{l&&(clearTimeout(l),l=null),He.current&&(clearTimeout(He.current),He.current=null),ht.current="idle",Ke(!1),O(null),ne(),Ve(),ce(),Oe(),Xt(),gr()}},[pe,Gt,Ti,Us]);let Er=!!gt?.clientId,Zo=Array.isArray(re),xa=Zo&&re.length>0,Vs=Zo&&re.includes("paypal"),Fa=(0,s.useRef)(null);Fa.current===null&&(Fa.current=Iu());let Ro=Fa.current?"redirect":Ka(K,A,f.current()),{expressMethods:Ba,paymentElementMethods:Qo}=(0,s.useMemo)(()=>(0,y.partitionStripeMethods)(re,{excludePaypal:Er}),[re,Er]),js=Er||!!Fe||Vs&&Ro==="redirect",ed=(0,s.useMemo)(()=>js?Ba.filter(l=>l!=="paypal"):Ba,[Ba,js]),td=(0,s.useMemo)(()=>{let l=[];return Y&&l.push("apple_pay"),le&&l.push("google_pay"),l},[Y,le]),Io=Zo?ed:td,nd=W&&Io.length>0,Mi=cn?Mt:j,Da=(0,s.useMemo)(()=>{let l=Mi?.trim().toUpperCase();return l?V?Qo.filter(_=>{let ne=V[_];return!ne||ne.length===0||ne.includes(l)}):(0,y.filterStripeMethodsByCountry)(Qo,Mi):Qo},[Qo,Mi,V]),xi=(0,s.useMemo)(()=>({mode:"payment",amount:Jo,currency:So,paymentMethodCreation:"manual",appearance:Os}),[Jo,So,Os]),[$s,Ws]=(0,s.useState)("loading"),[Hs,Ks]=(0,s.useState)("loading"),[Gs,Ys]=(0,s.useState)("loading"),[rd,Fi]=(0,s.useState)(!1),[Xs,Bi]=(0,s.useState)("loading"),[Di,od]=(0,s.useState)();(0,s.useEffect)(()=>{od(Kr())},[]);let Oa=Di?.inAppBrowser,La=Di?Ga(Di,gt?.approvalPresentation,We??(Ct?"subscription":"order")):"popup",Js=S&&(Er||(Zo?Vs:Oa===!1)),Zs=W&&nd,ea=(!bt||!!ue.waitForDataAttachment)&&Js&&Er,Qs=Xs==="retrying"||Xs==="exhausted",ta=null;W&&(Fe?ta=Ds:Ro==="redirect"&&(ta=jn));let el=(0,s.useMemo)(()=>({...Pe,presentationMode:Ro}),[Pe,Ro]),na=!bt&&Js&&!!ta&&(!Er||Qs),_o=!bt&&Zs&&!!jn,ra=!bt&&W&&xa&&Da.length>0&&!!jn,ad=ea&&!Qs?rd:na&&cc($s),id=_o&&cc(Hs),sd=ra&&Gs!=="load_error",tl=l=>l==="loading"||l==="ready",nl=ea||na&&tl($s)||_o&&tl(Hs)||ra&&Gs!=="load_error",Na=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!Na.current){if(!W&&!S){Na.current=!0;let l=new y.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(l),Le(l.message)}else if(!W&&S&&!Er){Na.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),Le(l.message)}else if(Oa!==void 0&&!bt&&!Ie&&!nl){Na.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),Le(l.message)}}},[W,S,Er,Oa,bt,Ie,nl,c,Le]);let rl=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(rl.current||!xa)return;let l=[];Y!==!0&&l.push("showApplePay"),le!==!0&&l.push("showGooglePay"),l.length!==0&&(rl.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,Y,le]);let ol=(0,s.useCallback)((l,_)=>ue.applyInlineSessionPatch?ue.applyInlineSessionPatch(l).then(ne=>({error:null,sessionId:ne.sessionId||e,nonce:ne.session?.clientSecret||t})).catch(ne=>{let Ve=lc(_,ne);return Le(Ve.message),c?.(Ve),{error:Ve,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ue.applyInlineSessionPatch,t,c,e,Le]),fr=(0,s.useCallback)(async l=>{if(l!=="card"&&bt&&await ue.waitForDataAttachment?.(),!Te)return{proceed:!0};try{let _=await Te({method:l,sessionId:e||void 0,createSession:ue.inlineSessionDraft});if(_===!1)return{proceed:!1};if(_&&typeof _=="object"){_.account&&Yn(Ve=>({...Ve??{},..._.account}));let ne=await ol(_,l);return ne.error?{proceed:!1,accountPatch:_.account}:{proceed:!0,accountPatch:_.account,sessionId:ne.sessionId,nonce:ne.nonce}}return{proceed:!0}}catch(_){let ne=lc(l,_);return Le(ne.message),c?.(ne),{proceed:!1}}},[ol,ue.inlineSessionDraft,ue.waitForDataAttachment,bt,Te,c,e,Le]),al=(0,s.useCallback)(async(l,_)=>{if(ye.current)return;ye.current=!0,Re(!0),O("processing"),Le(null);let ne=_?.sessionId??e,Ve=_?.nonce??t,ce=Gi(F,_?.accountPatch),Oe=_?.completionPaymentMethodId??pa(l),Xt=l.originalPaymentMethodId?{...l,originalPaymentMethodId:void 0}:l,gr=Du(l),dt=_?.presentationMode?ci(pn(J),{...Pe,presentationMode:_.presentationMode}):void 0,Pt=()=>{Ce?.({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(me).processPayment(ce.userId??"",{sessionId:ne,nonce:Ve,paymentMethodCategory:_?.paymentMethodCategory??Lu(l),tokenizedData:Xt,accountData:{..._?.accountPatch,userId:ce.userId??"",email:ce.email??"",firstName:ce.firstName||void 0,lastName:ce.lastName||void 0,...se?(()=>{let Nt=St.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),mo=$n&&!Tr&&Ar?(0,y.getStateFromPostalCode)(Nt,(Et.current??"").trim()):null,ca=Tr?ln.current:mo;return{country:Nt,...Ar&&Et.current?{zip:Et.current}:{},...(0,y.isAVSFieldVisible)(se.city,Nt)&&Ot.current?{city:Ot.current}:{},...ca?{state:ca}:{},...$n&&vn.current?{addressLine1:vn.current}:{},...(0,y.isAVSFieldVisible)(se.address_line_2,Nt)&&rn.current?{addressLine2:rn.current}:{}}})():{}},chv:R,avsCheck:et??!1,checkoutType:tt,checkoutLayout:pt,avsConfig:se?{country:(0,y.isAVSFieldVisible)(se.country,St.current),postal_code:(0,y.isAVSFieldVisible)(se.postal_code,St.current),address_line_1:(0,y.isAVSFieldVisible)(se.address_line_1,St.current),address_line_2:(0,y.isAVSFieldVisible)(se.address_line_2,St.current),city:(0,y.isAVSFieldVisible)(se.city,St.current),state:(0,y.isAVSFieldVisible)(se.state,St.current)}:void 0});if(Vt.ok){let Nt=Vt.status===204?null:await Vt.json().catch(()=>null),Tr=(0,y.isAuthorizationOnlySession)($)||Nt?.status==="authorized";jo(ne),dt?.terminal({outcome:"payment_succeeded",...vr}),O("success"),h(null),await new Promise(mo=>setTimeout(mo,600));let $n;typeof Nt?.paymentId=="string"?$n=Nt.paymentId:$?.paymentId&&($n=$.paymentId);let Ar;typeof Nt?.authorizationExpiresAt=="string"?Ar=Nt.authorizationExpiresAt:$?.authorizationExpiresAt&&(Ar=$.authorizationExpiresAt),i?.(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:Oe,checkoutMethod:l.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Oe,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(!J||!Nt){O("error"),Le("PayPal authorization required but no token provided.");return}try{let $n=Fe?.getRawProvider();if(!$n){Le("PayPal is not available.");return}let Ar={return_url:window.location.href};Tr&&(Ar.payment_method=Tr);let{error:mo}=await $n.confirmPayment({clientSecret:Nt,confirmParams:Ar,redirect:"if_required"});if(mo){O("error");let ca=mo.message??"PayPal payment failed.";Le(ca),_r("paypal",ca,{code:mo.code})}}catch($n){O("error"),Le($n instanceof Error?$n.message:"PayPal authorization failed.")}return}if(dn?.type==="paypal_direct_required"){let Nt=dn.orderId;if(!Nt){O("error"),Le("PayPal retry required but no order id provided.");return}let Tr=U.current?.attempts??0;if(Tr>=2){O("error"),Le("PayPal payment could not be completed after multiple attempts."),_r("paypal","paypal_direct_required retry limit exceeded");return}Fi(!1),Bi("loading"),h({orderId:Nt,attempts:Tr+1}),O(null);return}(0,y.classifyPaymentRejection)(Vt.status,dn)?dt?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}):Pt(),O("error");let hr=dn?.message??"Payment failed. Please try again.";Le(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(wt){hc(wt)||Pt(),O("error"),Le(wt instanceof Error?wt.message:"An unexpected error occurred"),await new Promise(Vt=>setTimeout(Vt,400))}finally{Re(!1),O(null),ye.current=!1}},[me,e,t,F,se,et,tt,pt,R,J,Fe,$,i,Le,_r,Ce,Pe]),Bn=(0,s.useCallback)((l,_)=>{u?u(l):al(l,_)},[u,al]),oa=`${yc}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let l=localStorage.getItem(oa);if(!l)return;let _;try{_=JSON.parse(l)}catch{$t(oa);return}if(!_||typeof _.createdAt!="number"||Date.now()-_.createdAt<0||Date.now()-_.createdAt>fc||typeof _.paymentMethodId!="string"||typeof _.providerIntentId!="string"||typeof _.paymentMethodType!="string"||_.sessionId!==e||!t||_.nonce!==t||!Io.includes(_.paymentMethodType)){$t(oa);return}$t(oa),Bn({id:_.paymentMethodId,type:"card",threeDSecureActionResultTokenId:_.providerIntentId,gateway:"stripe",paymentMethodType:_.paymentMethodType},{..._.accountPatch?{accountPatch:_.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Bn,t,e,oa,Io]);let il=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||il.current)return;let[l,_,ne]=Cs();if(!l||!_||Fa.current||!J)return;let Ve=J.getRawProvider();if(!Ve)return;let ce=Pt=>{let wt=localStorage.getItem(Pt);if(!wt)return null;try{return JSON.parse(wt)}catch{return $t(Pt),null}},Oe=ce(Fr)??ce(tc),Xt;if(Oe?.clientSecret){if(Oe.clientSecret!==_)return;Xt={...Oe.accountPatch?{accountPatch:Oe.accountPatch}:{},...Oe.sessionId?{sessionId:Oe.sessionId}:{},...Oe.nonce?{nonce:Oe.nonce}:{}}}else if(Oe?.sessionId&&Oe.sessionId!==e)return;il.current=!0,$t(Fr),$t(tc),window.history.replaceState({},"",Ss());let gr=Oe?.paymentMethodType??Oe?.tokenType??"card",dt="card";(async()=>{if(ne==="failed"){let hr="Payment was declined. Please try again.";Le(hr),_r(dt,hr);return}let{paymentIntent:Pt,error:wt}=await Ve.retrievePaymentIntent(_);if(wt){let hr=wt.message??"Failed to retrieve payment status.";Le(hr),_r(dt,hr,{code:wt.code});return}let Vt=Pt?.status,dn=ua(Vt);if(!Pt||!dn){let hr=Vt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Le(hr),_r(dt,hr,{code:Vt??"missing_payment_intent"});return}let gl=typeof Pt.payment_method=="string"?Pt.payment_method:Pt.payment_method?.id;Bn({id:gl??Oe?.paymentMethodId??Oe?.tokenId??Pt.id,type:"card",threeDSecureActionResultTokenId:Pt.id,gateway:Oe?.gateway??"stripe",paymentMethodType:gr},Xt)})()},[e,Bn,J,Le,_r]);let Oi=(0,s.useCallback)(l=>{l.preventDefault()},[]);if(!(pe||J!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let aa=H==="buttons",Dn=Me?.variables,ld=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Li=Dn?.colorBackground,cd=Li&&!ld.has(Li)?Li:void 0,ia=D.cardInputBorder??(aa?"#e5e7eb":"#A4A4FF"),sl=Dn?.colorDanger??"#dc2626",qt=l=>zr[l]&&(wr[l]||Mn),za=Co&&(Ur||Mn),er=l=>l?sl:ia,Ua=(gn.malformed||gn.empty)&&(Sr||Mn),dd=er(Ua),Ni=D.cardFormContainer?.backgroundColor??cd??(aa?"white":"#EDEDFF"),Eo=D.cardInputBackground??Dn?.colorBackground??"white",zi=Mo(xe),ll=Mo(we),To=D.nameInput,cl=D.cardInputFontSize??Vu(To?.fontSize)??Dn?.fontSizeBase??"16px",dl=typeof To?.fontFamily=="string"?To.fontFamily:Dn?.fontFamily??"Poppins, sans-serif",ul=us(To?.fontWeight)??400,ud=D.cardInputColor??(typeof To?.color=="string"?To.color:void 0)??Dn?.colorText??"#262833",pd=D.cardInputPlaceholderColor??"#9ca3af",Yt=Dn?.borderRadius??"8px",uo=Dn?.borderRadius??D.cardButton?.borderRadius??Yt,po=Dn?.colorPrimary??"#4A49FF",md=Dn?.colorPrimaryHover??Ko(po,.12),Ui=Dn?.colorText??"#262833",qi={fontSize:cl,fontFamily:dl,fontWeight:ul,color:ud,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},sa={marginTop:"0.375rem",...qi,fontSize:"0.75rem",lineHeight:1.4,color:sl},yd={"--flopay-input-placeholder-color":pd,"--flopay-input-font-size":cl,"--flopay-input-font-family":dl,"--flopay-input-font-weight":String(ul)},la=D.cardFormContainer??{},Vi=la.padding??(aa?"0":"1rem"),ji=la.borderRadius??Yt,fd=Gt&&Qn?(0,d.jsx)(so,{capture:Gt,html:Qn.html,messageToken:Qn.messageToken,expectedOrigin:Qn.expectedOrigin,theme:Tt,submitLabel:w,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=>Le(l),onValidation:l=>{let _=ht.current;(_==="idle"||_==="validation-window")&&(Le(l),l&&ht.current==="validation-window"&&(He.current&&(clearTimeout(He.current),He.current=null),ht.current="idle",O(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"}),pl=(0,d.jsxs)("div",{onFocusCapture:l=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(l.target.tagName)&&ur()},style:{backgroundColor:Ni,borderRadius:ji,...la,padding:Vi,...yd,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
30
+ `,Xo=44;function Jo(){return(0,mn.jsx)("style",{children:du})}function _a(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Ea({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,mn.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,mn.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,mn.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 ks(e){return e!=="unavailable"&&e!=="load_error"}function gi({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:i,backgroundColor:c,borderColor:p,textColor:u,borderRadius:h,fontFamily:v}){let E=(0,Xr.resolveStripeMethodBrandVariant)(e,t),T=oc[e],[w,x]=(0,ac.useState)(!1),A=!!T&&!w,P=E?.backgroundColor??c??"#ffffff",C=E?.borderColor??p??"#d1d5db",H=E?.textColor??u??"#262833";return(0,mn.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&i()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Xo,padding:"0 1rem",backgroundColor:P,color:H,border:`1px solid ${C}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:v,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,mn.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,Xr.getStripeMethodDisplayName)(e)}\u2026`}):(0,mn.jsxs)(mn.Fragment,{children:[(0,mn.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,Xr.hasVendoredStripeMethodLogo)(e)?8:0},children:[A?(0,mn.jsx)("img",{src:T,alt:"","aria-hidden":"true",onError:()=>x(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!A&&E?.logoSvg?(0,mn.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:E.logoSvg}}):null,(0,mn.jsx)("span",{children:(0,Xr.getStripeMethodDisplayName)(e)})]}),a&&(0,mn.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:H,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,mn.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function hi(e){let t=new Set(e.map(Xr.stripeExpressMethodToOptionKey)),n=r=>r==="applePay"||r==="googlePay"?"always":"auto";return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?n(r):"never"]))}var bi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},Pi={type:"accordion",defaultCollapsed:!1,radios:"never"};function vi({testId:e,attributes:t,disabled:n,onClick:r,color:o,borderRadius:a,style:i,children:c}){return(0,mn.jsx)("button",{type:"button","data-testid":e,...t,onClick:r,disabled:n,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:o,color:"white",border:"none",borderRadius:a,fontSize:"1rem",fontWeight:600,cursor:n?"not-allowed":"pointer",opacity:n?.5:1,transition:"opacity 120ms ease-out",...i??{}},children:c})}var Gn=require("react");function Ci(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(i=>i.startsWith("background")),a={};for(let[i,c]of Object.entries(e))i in n||o&&i.startsWith("background")||(a[i]=c);for(let i of r)a[i]=n[i];return a}var uu=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 pu(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return uu.has(t.charAt(0).toLowerCase()+t.slice(1))}function mu(e,t){return typeof t=="number"&&t!==0&&!pu(e)?`${t}px`:String(t).trim()}function ic(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]=mu(n,r)}}}var Co=require("react/jsx-runtime"),Rs=new WeakSet;function uo({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:i,onReady:c,onError:p,onValidation:u}){let h=(0,Gn.useRef)(null),v=(0,Gn.useRef)(c),E=(0,Gn.useRef)(p),T=(0,Gn.useRef)(u);v.current=c,E.current=p,T.current=u;let w=(0,Gn.useRef)(o);w.current=o;let x=(0,Gn.useRef)(null),A=a??void 0,P=(0,Gn.useRef)(A);P.current=A;let C=(0,Gn.useRef)(void 0);return(0,Gn.useEffect)(()=>{let H=h.current;if(!H)return;let I=!0,se=!1,j=()=>{!I||se||(se=!0,v.current?.())},ee=e.on("ready",()=>{j()}),we=e.on("error",oe=>{E.current?.(oe.message??"There was a problem loading the secure card form.")}),ne=e.on("validation",oe=>{T.current?.(oe.message??null)}),Ee=P.current??(Rs.has(e)?null:void 0),We={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...w.current?{theme:w.current}:{},...Ee===void 0?{}:{submitLabel:Ee}};return x.current=w.current??null,C.current=P.current,P.current!==void 0&&Rs.add(e),e.mount(H,We).then(()=>{j()}).catch(oe=>{I&&E.current?.(oe instanceof Error?oe.message:"Failed to load the secure card form.")}),()=>{I=!1,ee(),we(),ne(),e.unmount()}},[e,t,n,r]),Po(()=>{let H=h.current;H&&ic(H,i)},[i]),(0,Gn.useEffect)(()=>{o!==void 0&&(o===null&&x.current===null||(x.current=o,e.applyTheme?.(o)))},[e,o]),(0,Gn.useEffect)(()=>{A!==C.current&&(C.current=A,A!==void 0&&Rs.add(e),e.setSubmitLabel?.(A??null))},[e,A]),(0,Co.jsx)("div",{ref:h,"data-testid":"flopay-vault-card-fields"})}function Si({label:e}){return(0,Co.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,Co.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,Co.jsx)("span",{children:e}),(0,Co.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var lc=/^#([0-9a-f]{6})$/i,yu=/^#([0-9a-f]{3})$/i,cc=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,dc=/^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,fu=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,gu=/^(-?\d+(?:\.\d+)?)(?:px)?$/,hu=/^(-?\d+(?:\.\d+)?)em$/,bu=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,Pu=/^[a-z][a-z0-9 -]{0,31}$/i,vu=new Set(["none","uppercase","lowercase","capitalize"]);function uc(e){if(typeof e!="string")return null;let t=e.trim(),n=lc.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=yu.exec(t);if(r){let[h,v,E]=r[1].split("").map(T=>Number.parseInt(T+T,16));return{r:h,g:v,b:E,a:null}}let o=cc.exec(t),a=o?null:dc.exec(t),i=o??a;if(!i)return null;let c=Number(i[1]),p=Number(i[2]),u=Number(i[3]);return c>255||p>255||u>255?null:{r:c,g:p,b:u,a:a?Number(a[4]):null}}function pc({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 Ta(e){if(typeof e!="string")return;let t=e.trim();if(lc.test(t)||cc.test(t))return t;let n=dc.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=uc(t);return r?pc(r):void 0}function wi(e,t=.12){let n=uc(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return pc({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function Aa(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 So(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=gu.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Cu(e,t,n){if(typeof e!="string")return;let r=hu.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=Aa(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=Aa(o," "),i=Ta(a[0]);if(!i)return;let c=r/(t.length-1)*100,p=a[1]===void 0?c: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:i,position:p})}return{type:"linearGradient",angle:0,stops:n}}function wu(e){if(typeof e!="string")return;let t=e.trim(),n=Ta(t);if(n)return{type:"solid",color:n};let r=fu.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 ku(e){return e.type==="solid"?{type:"solid",color:wi(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:wi(t.color)}))}}function Ru(e){let t=!1,n,r=[];for(let p of Aa(e," ")){if(p.toLowerCase()==="inset"){t=!0;continue}let u=Ta(p);if(u){n=u;continue}let h=So(p,-128,128);if(h===void 0)return;r.push(h)}if(!n||r.length<2||r.length>4)return;let[o,a,i=0,c=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||i>128||Math.abs(c)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:i,spread:c}}function Iu(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=Aa(t,",").map(Ru);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function sc(e){if(typeof e!="string")return;let t=Aa(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>Pu.test(n)).slice(0,4);return t.length>0?t:void 0}function _u(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=So(t[0],0,64),r=So(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function Eu(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 mc({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=wu(r.background??r.backgroundColor),i=Ta(o?.colorPrimaryHover),c=i?{type:"solid",color:i}:a&&ku(a),p={fontFamilies:sc(r.fontFamily)??sc(n),fontSize:So(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:Eu(r.fontWeight)??600,letterSpacing:Cu(r.letterSpacing,-.1,.5)??.01,lineHeight:So(r.lineHeight,.8,2)??1,textTransform:vu.has(String(r.textTransform))?r.textTransform:"uppercase"},u=_u(r.padding),h=Iu(r.boxShadow),v=So(r.borderRadius,0,9999),E=typeof r.backdropFilter=="string"?So(bu.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Ta(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...c?{hoverBackground:c}:{},typography:p,...u?{spacing:u}:{},...h?{shadow:h}:{},...v===void 0?{}:{borderRadius:v},disabledOpacity:e?.theme==="night"?.8:.6,...E===void 0?{}:{backdropBlur:E}}}function Zo(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)?wi(r,t):e}function Is(e){if(typeof e=="number"||typeof e=="string")return e}function Qo({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=v=>typeof v=="string"&&v?v:void 0,a=t.submitButton,i=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",c=n==="buttons",p=t.nameInput,u=o(p?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",h=mc({appearance:e,buttonsStyles:t,fontFamily:u});return{primaryColor:i,primaryHoverColor:o(r?.colorPrimaryHover)??Zo(i,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(p?.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:u,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(Is(p?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...h?{submitButton:h}:{}}}var d=require("react/jsx-runtime"),Dr="flopay_stripe_resume",yc="flopay_wallet_resume",Ic="fw1",Tu="fw2",_c=300*1e3,Au=900,Mu=25e3,xu=25e3,Fu=1e4,Ec=["payment_intent","payment_intent_client_secret","redirect_status"],Sr={provider:"paypal",paymentMethodCategory:"paypal"},ki={},_s={};function jt(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`${Tu}:${e}`}function Ri(e){return jt(Bs(e))}function Ii(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>_c||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Ri(e),null):o}catch{return Ri(e),null}}function Bu(e){return jt(Bs(e.sessionId),e)}function fc(e,t,n){let r=Ii(e,t);return!r||r.clientSecret!==n?!1:Ri(e)}function Es(e,t,n){if(typeof window>"u")return;Ii(e,t)?.clientSecret===n&&Ri(e)}function Du(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Ts(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":ga(e.status),o=Du(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function gc(e,t,n){let r=null;try{return await Promise.race([Nl(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},Fu),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Ou(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Tc(e){return e instanceof f.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function _i(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new wr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Tc(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var xa="flopay_paypal_resume",Ma=new Map;function Ac(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(xa);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function Lu(){if(typeof window>"u")return!1;let[e,t]=Ds();return e?Ac(t)!==null:!1}function Ds(){let e=new URLSearchParams(window.location.search);return Ec.map(t=>e.get(t))}function Os(){let e=new URL(window.location.href);for(let t of Ec)e.searchParams.delete(t);return e.toString()}function Nu(){jt(xa),window.history.replaceState({},"",Os())}var zu=250,hc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Uu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Ls(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 Ei({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new wr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function qu(e){return e instanceof f.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function As(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Mc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=go(n),i=a.firstName?a:go(r?.name);return zn({email:(0,f.isValidEmail)(o)?o:r?.email?.trim(),firstName:i.firstName,lastName:i.lastName})}async function Vu({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let i=Mc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,f.isValidEmail)(i.email)?i:a(o,i)}var Fa=180,bc=`flopay-card-enter ${Fa}ms cubic-bezier(0, 0, 0.2, 1) both`,Pc=`flopay-card-exit ${Fa}ms cubic-bezier(0.4, 0, 0.2, 1) both`,$u=`flopay-buttons-enter ${Fa}ms cubic-bezier(0, 0, 0.2, 1) both`,ju=`flopay-buttons-exit ${Fa}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Hu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Ns(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 Wu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Ku(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 Ms={width:"100%",minHeight:Xo,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 Gu(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function vc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function xs(e){return e==="paypal"?"PayPal":(0,f.getStripeMethodDisplayName)(e)}function Yu(e){let t=(0,f.getPostalCodeExample)(e);return`Enter a valid ${(0,f.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Xu(e,t,n){let r=(0,f.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,i=a&&!o,c=a&&!!o&&!(0,f.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:i,malformed:c}}function Ju(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,f.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function Cc(e,t){return t instanceof f.FloPayError?t:new f.FloPayError(t instanceof Error?t.message:`${Gu(e)} before-click hook failed.`,"validation_error")}function Zu(e){return typeof e=="number"?`${e}px`:e}function Ti(e){return(0,d.jsx)(Qu,{...e})}function Sc({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:i=!1,onButtonClick:c,onDecline:p,onTechnicalFailure:u,runBeforeButtonClick:h,billingName:v,onBuyerIdentityReady:E,onLoadStateChange:T,placeholderBorderRadius:w,popupCapabilityOwner:x,externalTelemetryContext:A,presentationMode:P}){let C=Kr(),{emitInstrument:H}=(0,s.useContext)(or),I=(0,Jt.useStripe)(),se=(0,Jt.useElements)(),j=(0,s.useMemo)(()=>fi(pn(C),A),[A,C]),[ee,we]=(0,s.useState)("loading");(0,s.useEffect)(()=>{T?.(ee)},[ee,T]);let[ne,Ee]=(0,s.useState)(!1),We=(0,s.useRef)(!1),oe=!(0,f.isValidEmail)(n?.trim())||!v?.trim(),{request:xe,collect:Ze,finish:ke}=zo(),Ie=(0,s.useRef)(!1),ge=(0,s.useRef)(null),ue=(0,s.useRef)(null),[ae,be]=(0,s.useState)(0),[_e,R]=(0,s.useState)(!1),Re=(0,s.useRef)(!1),Ce=(0,s.useRef)(new Map),{startAttempt:V,finishAttempt:Fe,invalidateAttempt:X,isAttemptInvalidated:Le,isAttemptCurrent:Q,generationRef:Ke}=va(($,ye,Qe)=>{u?.($,ye,{...Qe,popupBlocked:Qe?.popupBlocked??so(ye),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:P,terminalReason:"overlay_timeout"}),R(!0),be(Z=>Z+1)},{onHandoffObserved:()=>{x.markAvailable(),j?.log({name:"provider.popup.opened",stage:"overlay_open",...Sr,attempt:Ke.current})}});(0,s.useEffect)(()=>{_e&&ue.current?.focus()},[_e,ae]);let st=(0,s.useCallback)(()=>{be($=>$+1)},[]),Ne=(0,s.useCallback)(($,ye,Qe)=>{X(Qe),u?.("paypal",$,{code:ye,popupBlocked:so($),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:P}),R(!0),st()},[X,u,P,st]),tt=(0,s.useCallback)(()=>{window.setTimeout(()=>{(ge.current?.querySelector("iframe")??ge.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{Re.current&&(Re.current=!1,tt())},[tt,ae]);let nt=(0,s.useCallback)(()=>{R(!1),a?.(null),tt()},[tt,a]);(0,s.useEffect)(()=>{if(!I||Ie.current)return;let[$,ye,Qe]=Ds();if(!$||!ye)return;let Z=Ac(ye);if(!Z)return;Ie.current=!0;let ze=!0,ft=Ma.get(ye);ft||(ft=Qe==="failed"?Promise.resolve(null):Promise.resolve().then(()=>I.retrievePaymentIntent(ye)),Ma.set(ye,ft));let Ve={accountPatch:Z.accountPatch,sessionId:Z.sessionId,nonce:Z.nonce},vt=()=>{j?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Sr,requestCategory:"provider_sdk"})};return j?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Sr}),(async()=>{try{Ee(!0);let b=await ft;if(!ze)return;if(b?.error){Ma.delete(ye),vt(),a?.(b.error.message??"Failed to retrieve PayPal payment status.");return}if(Nu(),Ma.delete(ye),Qe==="failed"){let Y="PayPal payment was declined. Please try again.";j?.terminal({outcome:"payment_declined",...Sr,terminalReason:"provider_declined"}),a?.(Y),p?.(un("paypal",Y));return}let S=b?.paymentIntent;if(S&&S.id!==$){vt(),a?.("Failed to match the returned PayPal payment.");return}if(S&&(S.status==="requires_capture"||S.status==="succeeded")){let Y=typeof S.payment_method=="string"?S.payment_method:S.payment_method?.id;o({id:Y??S.id,type:"card",threeDSecureActionResultTokenId:S.id,isPaypal:!0},{...Ve,presentationMode:"redirect"})}else{let Y="PayPal payment was not completed. Please try again.";j?.terminal({outcome:S?.status==="canceled"?"payment_cancelled":"payment_declined",...Sr,terminalReason:S?.status==="canceled"?"cancelled":"provider_declined"}),a?.(Y),p?.(un("paypal",Y))}}catch(b){if(!ze)return;Ma.delete(ye),vt(),a?.(b instanceof Error?b.message:"Failed to complete PayPal payment.")}finally{ze&&Ee(!1)}})(),()=>{ze=!1,Ie.current=!1}},[I,o,a,p,j]);let pt=(0,s.useCallback)(async($=!1)=>{let ye=h?await h("paypal"):{proceed:!0};if(!ye.proceed)return Ce.current.delete(ae),!1;let Qe=V("paypal");return Ce.current.set(ae,{generation:Qe,accountPatch:ye.accountPatch,sessionId:ye.sessionId,nonce:ye.nonce}),R(!1),j?.log({name:`provider.${$?"redirect.started":"handoff.requested"}`,stage:$?"redirect":"overlay_open",...Sr,attempt:Qe}),c?.("paypal"),!0},[c,j,h,V,ae]),Be=(0,s.useCallback)(async $=>{if(i||ne||!await pt()){$.reject();return}$.resolve()},[i,pt,ne]),At=(0,s.useCallback)(async $=>{if(!I||!se)return;let ye=Ce.current.get(ae);if(ye&&!Q(ye.generation)){Ce.current.delete(ae);return}if(!ye&&Le()||ye&&!Fe(ye.generation))return;ye||Fe();let Qe=ye??null;if(Ce.current.delete(ae),!Qe&&h){let G=await h("paypal");if(!G.proceed){$.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Qe={accountPatch:G.accountPatch,sessionId:G.sessionId,nonce:G.nonce}}let Z=Qe?.sessionId??e,ze=Qe?.nonce??t,ft=await Vu({event:$,prepared:Qe,email:n,billingName:v,methodLabel:"PayPal",collect:Ze});if(!ft){$.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ve=ft.email,vt={...Qe?.accountPatch,...zn(ft,!0)};try{if(Ee(!0),a?.(null),!Z||!(0,f.isValidEmail)(Ve))throw new Error("Missing sessionId or email for PayPal payment");await E?.(ft);let G=I.createPaymentMethod,{error:b,paymentMethod:S}=await G({type:"paypal"});if(b){Ne(b,"stripe_paypal_create_payment_method_failed",ye?.generation),$.paymentFailed({reason:"fail"});return}let Y=await _i(r,H,Z,ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:S?.id??null,intentKind:"payment"});if(Y.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let y=Y.clientSecret,M={return_url:Os()};if(S?.id&&(M.payment_method=S.id),!jt(xa,{clientSecret:y,sessionId:Z,nonce:ze,accountPatch:vt})&&P==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:ie,paymentIntent:J}=await I.confirmPayment({clientSecret:y,confirmParams:M,redirect:"if_required"});if(ie){if(jt(xa),bo(ie)){let lt=ie.message??"Your payment was declined.";j?.terminal({outcome:"payment_declined",...Sr,terminalReason:"provider_declined"}),a?.(lt),p?.(un("paypal",lt,{code:Fr(ie),declineCode:qo(ie)})),await Ei({billingApiUrl:r,sessionId:Z,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Fr(ie)??"provider_declined"}})}else Ne(ie,"stripe_paypal_confirm_failed",ye?.generation);return}jt(xa);let le=typeof J?.payment_method=="string"?J.payment_method:J?.payment_method?.id;o({id:le??J?.id,type:"card",threeDSecureActionResultTokenId:J?.id,isPaypal:!0},{accountPatch:vt,paymentMethodCategory:"paypal",presentationMode:P,sessionId:Z,nonce:ze});return}catch(G){Ne(G,"stripe_paypal_failed",ye?.generation)}finally{Ee(!1)}},[I,se,e,t,n,v,Ze,E,r,H,o,a,p,h,Ne,Fe,Q,Le,j,P,ae]),Bt=(0,s.useCallback)(async()=>{if(!(We.current||i||ne||!I||!se)){We.current=!0,Ee(!0);try{if(!await pt(!0))return;await At({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{We.current=!1,Ee(!1)}}},[se,At,i,pt,I,ne]),gt=P==="redirect"?(0,d.jsx)("button",{type:"button",disabled:i||ne,onClick:()=>{Bt()},style:{width:"100%",minHeight:Xo,border:"1px solid #d1d5db",borderRadius:w??8,background:"#ffc439",color:"#111827",cursor:i||ne?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,d.jsx)(Jt.ExpressCheckoutElement,{onReady:$=>we(_a($,["paypal"])),onLoadError:()=>{we("load_error"),Ls(j,"paypal","paypal","provider_error")},onClick:Be,onConfirm:At,onCancel:()=>{let $=Ce.current.get(ae);Ce.current.delete(ae),j?.terminal({outcome:"payment_cancelled",...Sr,terminalReason:"cancelled",...$?{attempt:$.generation}:{}}),X($?.generation),R(!1),Re.current=!0,st()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:oe,emailRequired:oe,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ae),St=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{ref:ge,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[_e&&(0,d.jsx)("button",{ref:ue,type:"button","data-testid":"flopay-paypal-retry-button",onClick:nt,style:Ms,children:"Try PayPal again"}),xe&&(0,d.jsx)(Uo,{identity:xe.identity,methodLabel:xe.methodLabel,onComplete:ke,onCancel:()=>ke(null)},xe.id),(0,d.jsx)("div",{style:{display:xe?"none":void 0},children:gt})]}),ne&&!xe&&(0,d.jsx)(Un,{status:"processing"})]});return P==="redirect"?St:(0,d.jsx)(Ea,{state:ee,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:St})}function wc(e){return e==="apple_pay"||e==="google_pay"}function kc({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:i,onErrorChange:c,onButtonClick:p,onDecline:u,onTechnicalFailure:h,runBeforeButtonClick:v,billingName:E,onBuyerIdentityReady:T,onLoadStateChange:w,placeholderBorderRadius:x,popupCapabilityOwner:A,externalTelemetryContext:P}){let C=Kr(),{emitInstrument:H}=(0,s.useContext)(or),I=(0,Jt.useStripe)(),se=(0,Jt.useElements)(),j=(0,s.useMemo)(()=>fi(pn(C),P),[P,C]),[ee,we]=(0,s.useState)("loading");(0,s.useEffect)(()=>{w?.(ee)},[ee,w]);let[ne,Ee]=(0,s.useState)(!1),We=(0,s.useRef)(!(0,f.isValidEmail)(n?.trim())||!E?.trim()).current,{request:oe,collect:xe,finish:Ze}=zo(),ke=(0,s.useRef)(null),Ie=(0,s.useRef)(null),[ge,ue]=(0,s.useState)(0),[ae,be]=(0,s.useState)(!1),[_e,R]=(0,s.useState)(()=>Ii(e,t)?"blocked":"idle"),[Re,Ce]=(0,s.useState)("google_pay"),V=(0,s.useRef)(null),Fe=(0,s.useRef)(!0),X=(0,s.useRef)(!1),Le=(0,s.useRef)("google_pay"),Q=(0,s.useRef)("google_pay"),Ke=(0,s.useRef)(null),st=(0,s.useRef)(null),Ne=(0,s.useRef)(new Set),tt=(0,s.useRef)(null);(0,s.useEffect)(()=>(Fe.current=!0,()=>{Fe.current=!1;for(let G of Ne.current)window.clearTimeout(G);Ne.current.clear()}),[]);let nt=(0,s.useRef)(new Map),{startAttempt:pt,finishAttempt:Be,invalidateAttempt:At,isAttemptInvalidated:Bt,isAttemptCurrent:gt,generationRef:St}=va((G,b,S)=>{h?.(G,b,{...S,popupBlocked:S?.popupBlocked??so(b),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Ce(G),be(!0),ue(Y=>Y+1)},{onHandoffObserved:G=>{A.markAvailable(),j?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:St.current,...G==="apple_pay"||G==="google_pay"?{walletType:G}:{}})},defersMissingTerminal:wc,onMissingTerminalDeferred:(G,b)=>{let S=j?.now()??globalThis.performance?.now()??Date.now(),Y=tt.current,y=Y?.generation===b?Y.startedAt:S;j?.performance({stage:"overlay_return",durationMs:Math.max(0,S-y),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:b,...wc(G)?{walletType:G}:{}}),j?.flush?.().catch(()=>{})}});(0,s.useEffect)(()=>{ae&&Ie.current?.focus()},[ae,ge]);let $=(0,s.useCallback)(()=>{ue(G=>G+1)},[]),ye=(0,s.useCallback)((G,b,S,Y,y=!1)=>{At(Y),h?.(G,b,{code:S,popupBlocked:so(b),telemetryReported:y,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Ce(G),be(!0),$()},[At,h,$]),Qe=(0,s.useCallback)(()=>{window.setTimeout(()=>{(ke.current?.querySelector("iframe")??ke.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{X.current&&(X.current=!1,Qe())},[Qe,ge]);let Z=(0,s.useCallback)(()=>{be(!1),c?.(null),Qe()},[Qe,c]),ze=(0,s.useCallback)(()=>{V.current?.()},[]);(0,s.useEffect)(()=>{let G=Ii(e,t);if(!G)return;let b=!1,S=!1,Y=async()=>{if(!S){S=!0,b||R("checking");try{let y=await gc(I,G.clientSecret,Ne.current);if(b)return;let M=Ts(y,G.providerObjectId,(0,f.isSetupIntentClientSecret)(G.clientSecret));if(M.kind==="confirmed"){if(!fc(e,t,G.clientSecret))return;V.current=null,R("idle"),i({id:M.paymentMethodId,type:"card",threeDSecureActionResultTokenId:M.intentId},{...G.accountPatch?{accountPatch:G.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(M.kind==="terminal"){Es(e,t,G.clientSecret),V.current=null,R("idle"),Ce(G.paymentMethodType),be(!0),$();return}R("blocked")}catch{b||R("blocked")}finally{S=!1}}};return V.current=Y,R("blocked"),()=>{b=!0,V.current===Y&&(V.current=null)}},[t,i,$,e,I]);let ft=(0,s.useCallback)(async G=>{let b=!1,S=mt=>{b||(b=!0,G.paymentFailed({reason:"fail",...mt?{message:mt}:{}}))};if(!I||!se){S();return}let Y=nt.current.get(ge);if(Y&&!gt(Y.generation)){nt.current.delete(ge),S();return}if(!Y&&Bt()){S();return}if(Y&&!Be(Y.generation)){S();return}Y||Be();let y=G.expressPaymentType??Y?.method??Le.current,M=Y??null,De=vc(y),ie;y==="apple_pay"?ie="apple_pay":y==="google_pay"&&(ie="google_pay");let J=Y?.generation??St.current,le=j,lt=le?.now()??globalThis.performance?.now()??Date.now(),Ht=new AbortController,Xe=!1,xn=!1,Te=null,Vn=e,$n="processing",Mt="other",In="provider_runtime",Fn,Xn=new Promise((mt,rt)=>{Fn=rt}),yn=window.setTimeout(()=>{Xe=!0,Ht.abort(),Fn(ki)},Mu),Dt=async(mt,rt,_n)=>{$n=mt,Mt=rt,In=rt==="intent_create"||rt==="session_claim"?"transport_error":"provider_runtime";let xt=le?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([_n,Xn])}finally{let En=le?.now()??globalThis.performance?.now()??Date.now();le?.performance({stage:mt,durationMs:Math.max(0,En-xt),durationMode:"machine",requestCategory:rt,paymentMethodCategory:"wallet",provider:"stripe",...Xe?{statusClass:"timeout"}:{}})}};try{if(Ee(!0),c?.(null),!M&&v){let Ae=await Dt("processing","other",v(De));if(!Ae.proceed){S();return}M={accountPatch:Ae.accountPatch,sessionId:Ae.sessionId,nonce:Ae.nonce}}let mt=M?.sessionId??e;Vn=mt;let rt=M?.nonce??t,_n=Ke.current??M?.accountPatch,xt=Mc({event:G,fallbackEmail:_n?.email??n,fallbackName:[_n?.firstName,_n?.lastName].join(" ").trim()||E});if(!(0,f.isValidEmail)(xt.email)){S("Buyer details are required."),xe(xs(y),xt).then(Ae=>{Ae&&(Ke.current=Ae)});return}Ke.current=null;let En={...M?.accountPatch,...zn(xt,!0)};await Dt("processing","session_claim",Promise.resolve(T?.(xt)));let{error:fn}=await Dt("tokenization","provider_sdk",se.submit());if(fn){S(),ye(y,fn,"stripe_wallet_submit_failed",Y?.generation);return}if(!mt)throw new Error("Missing sessionId or email for payment.");let Wt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:y,paymentMethodId:null,intentKind:o},sn=JSON.stringify({sessionId:mt,nonce:rt??"",request:Wt}),Jn=st.current,Zn=Jn?.retryIdentity===sn?Jn.authorizationAttemptId:(0,f.randomUuidV4)();st.current={authorizationAttemptId:Zn,retryIdentity:sn};let Et=await Dt("processing","intent_create",_i(r,H,mt,rt??"",{...Wt,authorizationAttemptId:Zn},{signal:Ht.signal}));if(Et.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let wt=Et.clientSecret,Cn=Bu({createdAt:Date.now(),sessionId:mt,...rt?{nonce:rt}:{},clientSecret:wt,providerObjectId:Et.providerObjectId,paymentMethodType:y,accountPatch:En});window.clearTimeout(yn),xn=!0,le?.performance({stage:"callback",durationMs:Math.max(0,(le?.now()??globalThis.performance?.now()??Date.now())-lt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let on=le?.now()??globalThis.performance?.now()??Date.now(),Ot={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...ie?{walletType:ie}:{},attempt:J},ln=!1,Qt=null;le?.log({name:"payment.provider_confirmation.started",...Ot}),Te=window.setTimeout(()=>{Te!==null&&Ne.current.delete(Te),ln=!0;let Ae=le?.now()??globalThis.performance?.now()??Date.now();le?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Ot,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Ae-on),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),le?.flush?.().catch(()=>{}),Qt?.()},xu),Ne.current.add(Te);let Lt=(Ae,fe)=>{Te!==null&&(window.clearTimeout(Te),Ne.current.delete(Te),Te=null);let D=le?.now()??globalThis.performance?.now()??Date.now(),ct=Math.max(0,D-on),de=Ae;ln&&(Ae==="resolved"?de="resolved_late":Ae==="returned_error"?de="returned_error_late":de="rejected_late");let wn=fe??(Ae==="resolved"?"approved":"provider_error");return le?.log({name:"payment.provider_confirmation.returned",...Ot,operationOutcome:de,terminalReason:wn}),le?.performance({...Ot,durationMs:ct,durationMode:"buyer",operationOutcome:de,terminalReason:wn}),{durationMs:ct,operationOutcome:de,terminalReason:wn}},pe=!1,cn=!1,jn=Ae=>{if(!Ae||typeof Ae!="object")return null;let fe=Ae;if(fe.error)return null;let D=fe.setupIntent??fe.paymentIntent,ct=Ts(D??null,void 0,!!fe.setupIntent);return ct.kind==="confirmed"?ct:null},Nr=Ae=>{if(pe||Y&&St.current!==Y.generation)return;let fe=jn(Ae);if(!fe)return;if(Cn&&!fc(mt,rt,wt)){pe=!0;return}let{intentId:D,paymentMethodId:ct}=fe;pe=!0,cn=!0,st.current=null,V.current=null,Fe.current&&(R("idle"),Ee(!1));let de=`${Ic}:${mt}`;jt(de,{createdAt:Date.now(),sessionId:mt,nonce:rt,accountPatch:En,paymentMethodId:ct,providerIntentId:D,paymentMethodType:y});try{i({id:ct,type:"card",threeDSecureActionResultTokenId:D},{accountPatch:En,paymentMethodCategory:"wallet",sessionId:mt,nonce:rt})}finally{jt(de)}},cr=!1;Qt=async()=>{if(!(cr||pe||cn)){cr=!0,Fe.current&&R("checking");try{let Ae=await gc(I,wt,Ne.current);if(pe||cn)return;let fe=(0,f.isSetupIntentClientSecret)(wt),D=Ts(Ae,Et.providerObjectId,fe);if(D.kind==="confirmed"){Nr(fe?{setupIntent:Ae}:{paymentIntent:Ae});return}if(D.kind==="terminal"){if(cn=!0,Es(mt,rt,wt),st.current=null,V.current=null,!Fe.current)return;R("idle"),S(),ye(y,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",Y?.generation,!0);return}Fe.current&&!cn&&(R("blocked"),Ee(!1))}catch{Fe.current&&!cn&&(R("blocked"),Ee(!1))}finally{cr=!1}}},V.current=Qt;let Ut,dr;try{let Ae=await((0,f.isSetupIntentClientSecret)(wt)?I.confirmSetup({elements:se,clientSecret:wt,redirect:"if_required"}):I.confirmPayment({elements:se,clientSecret:wt,redirect:"if_required"}));if(!Ae||typeof Ae!="object"||(Ut=Ae,!Ut.error&&!jn(Ut)))throw _s;dr=Lt(Ut.error?"returned_error":"resolved",Ut.error&&bo(Ut.error)?"provider_declined":void 0)}catch(Ae){let fe=Ae===_s,D=Lt(fe?"returned_error":"rejected");if(le?.error({...fe?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:cs(Ae),...Ot,operationOutcome:D.operationOutcome,durationMs:D.durationMs,statusClass:"unknown",terminalReason:D.terminalReason}),!Fe.current||pe)return;await Qt?.();return}let Sn=Ut.error;if(Sn){if(!Fe.current||pe)return;if(bo(Sn)){cn=!0,Es(mt,rt,wt),st.current=null,V.current=null,R("idle");let Ae=Sn.message??"Your payment was declined.";S(Ae),c?.(Ae),u?.(un(De,Ae,{code:Fr(Sn),declineCode:qo(Sn)})),Ei({billingApiUrl:r,sessionId:mt,nonce:rt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:y,providerDeclineReason:Fr(Sn)??"provider_declined",...Et.intentKind==="payment"&&Et.providerObjectId.startsWith("pi_")?{providerIntentId:Et.providerObjectId}:{}}})}else le?.error({...cs(Sn),...Ot,operationOutcome:dr.operationOutcome,durationMs:dr.durationMs,statusClass:"unknown",terminalReason:dr.terminalReason}),await Qt?.();return}if(Nr(Ut),!pe)throw new Error("Invalid provider returned for APM intent")}catch(mt){if(mt===ki){let rt=le?.now()??globalThis.performance?.now()??Date.now();le?.error({errorCode:Ou(Mt),stage:$n,requestCategory:Mt,paymentMethodCategory:"wallet",provider:"stripe",...ie?{walletType:ie}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Vn,durationMs:Math.max(0,rt-lt),statusClass:"timeout",failureCategory:In,attempt:J,terminalReason:"provider_error"}),le?.flush?.().catch(()=>{})}S(),ye(y,mt,mt===ki?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",Y?.generation,mt===ki)}finally{if(window.clearTimeout(yn),Te!==null&&(window.clearTimeout(Te),Ne.current.delete(Te)),!xn){let mt=le?.now()??globalThis.performance?.now()??Date.now();le?.performance({stage:"callback",durationMs:Math.max(0,mt-lt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Xe?{statusClass:"timeout"}:{}})}Fe.current&&Ee(!1)}},[I,se,e,t,n,E,xe,T,r,H,o,i,c,u,v,ye,Be,gt,Bt,St,j,ge]),Ve=(0,s.useMemo)(()=>hi(a),[a]),vt=(0,s.useMemo)(()=>a.map(f.stripeExpressMethodToOptionKey),[a]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Ea,{state:ee,placeholderTestId:"flopay-wallet-placeholder",borderRadius:x,children:(0,d.jsxs)("div",{ref:ke,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[ae&&(0,d.jsxs)("button",{ref:Ie,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Z,style:Ms,children:["Try ",xs(Re)," again"]}),_e!=="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:ze,disabled:_e==="checking",style:Ms,children:_e==="checking"?"Checking payment status\u2026":"Check payment status"})]}),oe&&(0,d.jsx)(Uo,{identity:oe.identity,methodLabel:oe.methodLabel,onComplete:Ze,onCancel:()=>Ze(null)},oe.id),_e==="idle"&&(0,d.jsx)("div",{style:{display:oe?"none":void 0},children:(0,d.jsx)(Jt.ExpressCheckoutElement,{onReady:G=>{we(_a(G,vt))},onLoadError:G=>{we("load_error"),Ls(j,"stripe","wallet","provider_error")},onClick:async G=>{let b=j?.now()??globalThis.performance?.now()??Date.now();Le.current=G.expressPaymentType,Q.current=vc(G.expressPaymentType);let S=!0,Y=window.setTimeout(()=>{S=!1,G.reject()},Au),y=v?await v(Q.current):{proceed:!0};if(window.clearTimeout(Y),!S)return;if(!y.proceed){nt.current.delete(ge),G.reject();return}let M=pt(G.expressPaymentType);tt.current={generation:M,startedAt:b},nt.current.set(ge,{generation:M,method:G.expressPaymentType,accountPatch:y.accountPatch,sessionId:y.sessionId,nonce:y.nonce}),be(!1),j?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:M,...G.expressPaymentType==="apple_pay"||G.expressPaymentType==="google_pay"?{walletType:G.expressPaymentType}:{}}),p?.(Q.current),G.resolve()},onConfirm:ft,onCancel:()=>{let G=nt.current.get(ge);nt.current.delete(ge),j?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...G?{attempt:G.generation}:{}}),At(G?.generation),st.current=null,be(!1),X.current=!0,$()},options:{...bi,paymentMethods:Ve,emailRequired:We,billingAddressRequired:We}},ge)})]})}),ne&&(0,d.jsx)(Un,{status:"processing"})]})}function xc(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function Fs({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:c,onErrorChange:p,onDecline:u,onCancel:h,runBeforeButtonClick:v,onButtonClick:E,isProcessing:T,submitButtonColor:w,submitButtonBorderRadius:x,submitButtonStyle:A,errorText:P}){let C=Kr(),{emitInstrument:H}=(0,s.useContext)(or),I=(0,Jt.useStripe)(),se=(0,Jt.useElements)(),[j,ee]=(0,s.useState)(!1),we=(0,s.useRef)(!1),[ne,Ee]=(0,s.useState)(!1),[We,oe]=(0,s.useState)("loading"),[xe,Ze]=(0,s.useState)(""),ke=!(0,f.isValidEmail)(r?.trim()),Ie=!ke||(0,f.isValidEmail)(xe.trim()),ge=(0,s.useCallback)(async()=>{if(!I||!se||T||we.current||!ne)return;we.current=!0,ee(!0);let ue=v?await v("card"):{proceed:!0};if(!ue.proceed){we.current=!1,ee(!1);return}E?.("card");let ae=ue.sessionId??t,be=ue.nonce??n,_e=go(o?.trim()),R=zn({email:ue.accountPatch?.email?.trim()||r?.trim()||xe.trim(),firstName:ue.accountPatch?.firstName?.trim()||_e.firstName,lastName:ue.accountPatch?.lastName?.trim()||_e.lastName}),Re=R.email,Ce=zn({...ue.accountPatch,...R});try{if(p?.(null),!(0,f.isValidEmail)(Re))throw new Error("A valid email address is required for payment.");await a?.(R);let V=await se.submit();if(V.error){p?.(V.error.message??"Payment failed.");return}let Fe=[R.firstName,R.lastName].filter(Boolean).join(" "),X=await I.createPaymentMethod({elements:se,params:{billing_details:{email:Re,...Fe?{name:Fe}:{}}}});if(X.error||!X.paymentMethod){p?.(X.error?.message??"Failed to create payment method.");return}let Le=X.paymentMethod;if(!ae||!Re)throw new Error("Missing sessionId or email for payment.");let Q=Le.type||e,Ke=await _i(i,H,ae,be??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,paymentMethodId:null,intentKind:"payment"});if(Ke.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let st=Ke.clientSecret;jt(Dr,{clientSecret:st,sessionId:ae,nonce:be,accountPatch:Ce,paymentMethodId:Le.id,paymentMethodType:Le.type??e,gateway:"stripe"});let{error:Ne,paymentIntent:tt}=await I.confirmPayment({clientSecret:st,confirmParams:{return_url:window.location.href,payment_method:Le.id},redirect:"if_required"});if(Ne){jt(Dr);let Be=Ne.message??"Payment failed.";p?.(Be),u?.(un("card",Be,{code:Ne.code})),await Ei({billingApiUrl:i,sessionId:ae,nonce:be,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ne.code??"provider_declined"}});return}let nt=tt?.status;if(!ga(nt)){jt(Dr);let Be=nt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(Be),u?.(un("card",Be,{code:nt??"missing_payment_intent"}));return}jt(Dr);let pt=typeof tt?.payment_method=="string"?tt.payment_method:tt?.payment_method?.id;c({id:pt??Le.id,type:"card",threeDSecureActionResultTokenId:tt?.id,gateway:"stripe",paymentMethodType:Le.type??e},{accountPatch:Ce,paymentMethodCategory:"apm",sessionId:ae,nonce:be})}catch(V){p?.(V instanceof Error?V.message:"Payment failed. Please try again.")}finally{we.current=!1,ee(!1)}},[I,se,T,ne,v,E,t,n,r,o,xe,a,i,H,e,c,p,u]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ke&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ke&&(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:xe,onChange:ue=>Ze(ue.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(Jt.PaymentElement,{onReady:()=>oe("ready"),onLoadError:()=>{oe("load_error"),Ls(pn(C),"stripe","apm")},onChange:ue=>{Ee(!!ue.complete)},options:{layout:Pi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,f.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,d.jsx)(vi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ge()},disabled:!ne||!Ie||j||T||We!=="ready",color:w,borderRadius:x,style:A,children:j?"Processing\u2026":`Pay with ${(0,f.getStripeMethodDisplayName)(e)}`}),P&&(0,d.jsx)($o,{margin:"0.75rem 0 0",children:P})]})}function Rc({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:i,stripeInstance:c,paymentElementBaseOptions:p,onTokenizedBody:u,onErrorChange:h,onButtonClick:v,onDecline:E,runBeforeButtonClick:T,onLoadStateChange:w,isProcessing:x=!1,submitButtonColor:A="#4A49FF",submitButtonBorderRadius:P=8,submitButtonStyle:C,buttonAppearance:H,themeId:I,onExpandApm:se,expandedApmMethod:j}){let{emitInstrument:ee}=(0,s.useContext)(or),[we,ne]=(0,s.useState)(null),[Ee,We]=(0,s.useState)(null),oe=(0,s.useRef)(!1),{request:xe,collect:Ze,finish:ke}=zo();(0,s.useEffect)(()=>{i.length>0&&c?w?.("ready"):c||w?.("loading")},[i.length,c,w]);let Ie=(0,s.useCallback)(async R=>{if(!c||oe.current||x)return;oe.current=!0,We(R);let Re=T?await T("card"):{proceed:!0};if(!Re.proceed){oe.current=!1,We(null);return}v?.("card");let Ce=Re.sessionId??e,V=Re.nonce??t,Fe=go([Re.accountPatch?.firstName,Re.accountPatch?.lastName].filter(Boolean).join(" ")||r),X=zn({email:Re.accountPatch?.email?.trim()||n?.trim(),firstName:Re.accountPatch?.firstName?.trim()||Fe.firstName,lastName:Re.accountPatch?.lastName?.trim()||Fe.lastName});if(!(0,f.isValidEmail)(X.email)){We(null);let Ke=await Ze((0,f.getStripeMethodDisplayName)(R),X);if(!Ke){oe.current=!1;return}X=Ke,We(R)}let Le=X.email,Q=zn({...Re.accountPatch,...X});try{if(h?.(null),!Ce||!(0,f.isValidEmail)(Le))throw new Error("Missing sessionId or email for payment.");await o?.(X);let Ke=await _i(a,ee,Ce,V??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:R,paymentMethodId:null,intentKind:"payment"});if(Ke.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let st=Ke.clientSecret;jt(Dr,{clientSecret:st,sessionId:Ce,nonce:V,accountPatch:Q,paymentMethodType:R,gateway:"stripe"});let{error:Ne,paymentIntent:tt}=await c.confirmPayment({clientSecret:st,confirmParams:{return_url:window.location.href,payment_method_data:{type:R,billing_details:{name:[X.firstName,X.lastName].filter(Boolean).join(" "),...Le?{email:Le}:{}}}},redirect:"if_required"});if(Ne){jt(Dr);let Be=Ne.message??"Payment failed.";h?.(Be),E?.(un("card",Be,{code:Ne.code})),await Ei({billingApiUrl:a,sessionId:Ce,nonce:V,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:R,providerDeclineReason:Ne.code??"provider_declined"}});return}let nt=tt?.status;if(!ga(nt)){jt(Dr);let Be=nt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(Be),E?.(un("card",Be,{code:nt??"missing_payment_intent"}));return}jt(Dr);let pt=typeof tt?.payment_method=="string"?tt.payment_method:tt?.payment_method?.id;u({id:pt??tt?.id,type:"card",threeDSecureActionResultTokenId:tt?.id,gateway:"stripe",paymentMethodType:R},{accountPatch:Q,paymentMethodCategory:"apm",sessionId:Ce,nonce:V})}catch(Ke){h?.(Ke instanceof Error?Ke.message:"Payment failed. Please try again.")}finally{oe.current=!1,We(null)}},[c,x,T,v,e,t,n,Ze,a,ee,r,o,u,h,E]),[ge,ue]=(0,s.useState)(null),ae=se?j??null:ge,be=(0,s.useCallback)(R=>{oe.current||x||ae&&ae!==R||((0,f.needsStripeMethodExplicitConfirm)(R)?se?se(R):ue(R):Ie(R))},[ae,x,Ie,se]),_e=(0,s.useMemo)(()=>ge?xc(p,ge):null,[ge,p]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:xe?(0,d.jsx)(Uo,{identity:xe.identity,methodLabel:xe.methodLabel,onComplete:ke,onCancel:()=>ke(null)},xe.id):i.map(R=>{let Re=j===R,Ce=Ee===R,V=Ee!==null&&Ee!==R||j!=null&&j!==R;return(0,d.jsxs)(s.default.Fragment,{children:[(0,d.jsx)(gi,{method:R,themeId:I,submitting:Ce,disabled:V,highlighted:Re,hasNextStep:(0,f.needsStripeMethodExplicitConfirm)(R),onClick:()=>be(R),backgroundColor:H?.backgroundColor,borderColor:H?.borderColor,textColor:H?.textColor,borderRadius:H?.borderRadius,fontFamily:H?.fontFamily}),!se&&ge===R&&_e&&c&&(0,d.jsx)(Jt.Elements,{stripe:c,options:_e,children:(0,d.jsx)(Fs,{method:R,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:u,onErrorChange:h,onDecline:E,onCancel:()=>ue(null),runBeforeButtonClick:T,onButtonClick:v,isProcessing:x,submitButtonColor:A,submitButtonBorderRadius:P,submitButtonStyle:C})},R)]},R)})})}function Qu({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:i,onError:c,onDecline:p,onTokenizedBody:u,firstName:h,lastName:v,chv:E,className:T,submitLabel:w,isProcessing:x,error:A,onErrorChange:P,showPayPal:C=!0,showStripe:H=!0,walletPresentation:I="auto",enabledPaymentMethods:se,enabledPaymentMethodCountries:j,showApplePay:ee=!0,showGooglePay:we=!0,layout:ne="default",theme:Ee,buttonsTheme:We,buttonsStyles:oe,appearance:xe,cardButtonContent:Ze,cardBackButtonContent:ke,cardTitleContent:Ie,showSecurityFooter:ge,onButtonClick:ue,onBeforeButtonClick:ae,onBuyerIdentityReady:be,enableAVS:_e,cardFieldOrder:R,cardPreFormSlot:Re,avsLayout:Ce="row",country:V,zip:Fe,addressLine1:X,addressLine2:Le,city:Q,state:Ke,onCountryChange:st,onZipChange:Ne,avsCheck:tt,checkoutType:nt,checkoutLayout:pt,totalAmount:Be=0,currency:At="usd",initialCardOpen:Bt=!1,directPaypal:gt,isSubscription:St=!1,session:$,dataAttachmentPending:ye=!1,dataAttachmentRequiresIdentity:Qe=!1,debug:Z=!1}){let ze=Kr(),ft=Za(),Ve=(0,s.useContext)(vr),{emitInstrument:vt}=(0,s.useContext)(or),G=(0,s.useRef)(null);G.current||(G.current=ni());let b=G.current,[,S]=(0,s.useState)(0),Y=(0,s.useRef)(null);Y.current||(Y.current=Gr());let y=Y.current,M=(0,s.useMemo)(()=>({browser:y,capability:b,presentationMode:"popup"}),[y,b]),De=$??Ve.session,ie=De?.gateways?.paypal?.providerObjectType??gt?.providerObjectType,J=ye||Ve.claimPending===!0,le=Qe||Ve.claimRequiresIdentity===!0,lt=J&&!le,Ht=jl(),Xe=n||Ht,[xn,Te]=(0,s.useState)(!1),[Vn,$n]=(0,s.useState)(null),[Mt,In]=(0,s.useState)(V??""),[Fn,Xn]=(0,s.useState)(Fe??""),[yn,Dt]=(0,s.useState)(X??""),[mt,rt]=(0,s.useState)(Le??""),[_n,xt]=(0,s.useState)(Q??""),[En,fn]=(0,s.useState)(Ke??""),[Wt,sn]=(0,s.useState)(""),[Jn,Zn]=(0,s.useState)({}),Et=(0,s.useRef)(Fe??""),wt=(0,s.useRef)(V??""),Cn=(0,s.useRef)(X??""),on=(0,s.useRef)(Le??""),Ot=(0,s.useRef)(Q??""),ln=(0,s.useRef)(Ke??""),Qt=(0,s.useRef)(""),Lt=(0,s.useRef)({});(0,s.useEffect)(()=>{let l=(_,re,He,me,Ue)=>{if(Lt.current[_])return;let Xt=re?.trim();!Xt||Xt===He.current||(He.current=Xt,me(Xt),Ue?.(Xt))};l("country",V,wt,In,st),l("zip",Fe,Et,Xn,Ne),l("addressLine1",X,Cn,Dt),l("addressLine2",Le,on,rt),l("city",Q,Ot,xt),l("state",Ke,ln,fn)},[V,Fe,X,Le,Q,Ke,st,Ne]);let pe=(0,s.useMemo)(()=>(0,f.resolveAVSConfig)(_e),[_e]),cn=pe!==null,jn=(0,s.useMemo)(()=>(0,f.isAuthorizationOnlySession)($),[$]),Nr=!!$?.vault?.html,cr=!!$?.gateways?.pcivault,Ut=is($),Sn=!!($?.gateways?.stripe?.enabledPaymentMethods??se)?.includes("card")||to($),Ae=Nr||Sn||cr,fe=!!(H&&Ae&&e),[D,ct]=(0,s.useState)(()=>ne!=="buttons"||Bt?e??null:null),[de,wn]=(0,s.useState)(0),gn=ne!=="buttons"||Bt||!!e&&D===e,Kt=$?.captureMethod,Qn=(0,s.useRef)(ze);(0,s.useEffect)(()=>{Qn.current=ze},[ze]);let[yt,Qr]=(0,s.useState)(null);(0,s.useEffect)(()=>{if(!fe||!e||!gn){Qr(null);return}let l=Qn.current?Qn.current.cardCapture({sessionId:e,captureMethod:Kt}):new wr.PciVaultCardCapture({sessionId:e,captureMethod:Kt,billingApiUrl:Xe,telemetry:r});return Qr({sessionId:e,captureMethod:Kt,billingApiUrl:Xe,telemetry:r,capture:l}),()=>{l.unmount()}},[fe,e,gn,Kt,Xe,r]);let Gt=fe&&e&&gn&&yt?.sessionId===e&&yt.captureMethod===Kt&&yt.billingApiUrl===Xe&&yt.telemetry===r?yt.capture:null,hn=(0,s.useMemo)(()=>{let l=Mt,_=pe?(0,f.isAVSFieldVisible)(pe.postal_code,l):!1;return Xu(l,Fn,_)},[pe,Mt,Fn]),{avsInvalid:zr,invalidAvsFields:Ur}=(0,s.useMemo)(()=>{let l={line1:!1,city:!1,state:!1,zip:!1};if(!fe||!pe)return{avsInvalid:!1,invalidAvsFields:l};let _=Mt,re=(Ue,Xt)=>(0,f.isAVSFieldVisible)(Ue,_)&&!Xt.trim(),He={line1:re(pe.address_line_1,yn),city:re(pe.city,_n),state:re(pe.state,En),zip:hn.empty||hn.malformed};return{avsInvalid:He.line1||He.city||He.state||He.zip,invalidAvsFields:He}},[fe,pe,Mt,yn,_n,En,hn]),[Bn,en]=(0,s.useState)(!1),[kr,Dn]=(0,s.useState)(!1),[qr,On]=(0,s.useState)(!1),[Rr,Ir]=(0,s.useState)({line1:!1,city:!1,state:!1}),ur=(0,s.useRef)(!1),er=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),tr=(0,s.useRef)(!1),Ft=(0,s.useCallback)(l=>{er.current[l]=!0,tr.current=!0},[]),pr=(0,s.useCallback)(l=>!ur.current&&er.current[l],[]),Tn=(0,s.useCallback)(l=>{pr(l)&&Ir(_=>_[l]?_:{..._,[l]:!0})},[pr]),[nr,_r]=(0,s.useState)(()=>As($?.vault)),[ht,an]=(0,s.useState)(Bt&&Ae?"card":"buttons"),[tn,Vr]=(0,s.useState)(null),Hn=ht==="expanding"||ht==="card",eo=$?.gateways?.stripe&&!Ut?"stripe":void 0,mr=(0,s.useCallback)(()=>{vt?.({class:"card_surface",provider:eo})},[eo,vt]),yr=(0,s.useRef)(null),bn=(0,s.useCallback)(l=>{yr.current&&clearTimeout(yr.current),yr.current=setTimeout(()=>{yr.current=null,l()},Fa)},[]);(0,s.useEffect)(()=>()=>{yr.current&&clearTimeout(yr.current)},[]);let fr=(0,s.useCallback)(()=>{mr(),ct(e??null),wn(l=>l+1),an("expanding"),bn(()=>an("card"))},[bn,mr,e]),$r=(0,s.useCallback)(()=>{an("collapsing"),bn(()=>an("buttons"))},[bn]),An=(0,s.useCallback)(l=>{Vr(l),an("apm-expanding"),bn(()=>an("apm-form"))},[bn]),N=(0,s.useCallback)(()=>{an("apm-collapsing"),bn(()=>{an("buttons"),Vr(null)})},[bn]);(0,s.useEffect)(()=>{ne==="buttons"&&Bt&&Ae&&(ct(e??null),an("card"))},[ne,Bt,Ae,e]);let[q,L]=(0,s.useState)(null),Pe=(0,s.useRef)(!1),Ge=(0,s.useRef)(null),bt=(0,s.useRef)("idle"),[Se,Ye]=(0,s.useState)(!1),te=(0,s.useRef)(Se);te.current=Se;let[m,g]=(0,s.useState)(()=>gt?.existingOrderId?{orderId:gt.existingOrderId,attempts:1}:null),U=(0,s.useRef)(m);(0,s.useEffect)(()=>{U.current=m},[m]);let W=(0,s.useRef)(null),ve=(0,s.useMemo)(()=>{if(be||Ve.claimBuyerIdentity||$?.buyerIdentified!==!1||!e||!t)return;let l=`${Xe}|${e}|${t}`;W.current?.key!==l&&(W.current={key:l,claim:Lo(new wr.PaymentAPI(Xe,{telemetry:!1}),e,t,{...a?{userId:a}:{},...h?{firstName:h}:{},...v?{lastName:v}:{}})});let _=W.current.claim;return async re=>{await _(re)}},[be,Ve.claimBuyerIdentity,$?.buyerIdentified,e,t,Xe,a,h,v]),ce=be??Ve.claimBuyerIdentity??ve,at=A??Vn,Rt=(0,s.useMemo)(()=>(0,f.resolveTheme)(Ee),[Ee]),O=(0,s.useMemo)(()=>{let l=Rt?.buttonsLayout??(0,f.resolveButtonsLayoutTheme)(We);return oe?{...l,...oe,cardButton:{...l.cardButton,...oe.cardButton},cardFormContainer:{...l.cardFormContainer,...oe.cardFormContainer},backButton:{...l.backButton,...oe.backButton},backButtonIcon:{...l.backButtonIcon,...oe.backButtonIcon},submitButton:{...l.submitButton,...oe.submitButton},title:{...l.title,...oe.title}}:l},[Rt,We,oe]),Oe=xe??Rt?.appearance,Tt=(0,s.useMemo)(()=>Qo({appearance:Oe,buttonsStyles:O,layout:ne}),[Oe,O,ne]),Me=Ve.inlineSessionPatchProcessing??!1,K=(x??xn)||Me,he=Xe.replace(/\/+$/,""),B=(0,s.useMemo)(()=>ls({userId:a,email:o,firstName:h,lastName:v,country:V,zip:Fe},Jn),[a,o,h,v,V,Fe,Jn]),et=[B.firstName,B.lastName].filter(l=>!!l?.trim()).join(" "),It=!(0,f.isValidEmail)(B.email?.trim()),je=(0,s.useRef)(null);fe&&je.current===null&&(je.current=It);let kn=fe&&(je.current??It),Er=(0,s.useMemo)(()=>Ju(Wt,kn),[Wt,kn]),ko=Er.empty||Er.malformed,Wn=(0,s.useMemo)(()=>ze?ze.getRawProvider():null,[ze]),Gs=(0,s.useMemo)(()=>ft?ft.getRawProvider():null,[ft]),na=Be||100,Ro=At.toLowerCase(),qi=(0,s.useMemo)(()=>Oe?(0,wr.toStripeAppearance)(Oe):null,[Oe]),Io=qi,Ys=(0,s.useMemo)(()=>{let l=qi??{},_=l.rules??{};return{...l,rules:{..._,".AccordionItem":{padding:"10px 14px",boxShadow:"none",..._[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",..._[".AccordionItemContents"]??{}}}}},[qi]),Xs=(0,s.useMemo)(()=>({...zl(Be,$?.captureMethod),currency:Ro,...Io?{appearance:Io}:null}),[Be,Ro,$?.captureMethod,Io]),Js=(0,s.useMemo)(()=>({mode:"payment",amount:na,currency:Ro,captureMethod:"manual",setupFutureUsage:"off_session",...Io?{appearance:Io}:null}),[na,Ro,Io]),$e=(0,s.useCallback)(l=>{$n(l),P?.(l)},[P]),Vi=(0,s.useRef)(""),[Zs,cd]=(0,s.useState)(!1),$i=(0,s.useCallback)(()=>{cd(!0)},[]);(0,s.useEffect)(()=>{if(!fe||!kn||!ce||!Zs||ko||Vi.current)return;let l=zn({email:(0,f.isValidEmail)(B.email?.trim())?B.email?.trim():Qt.current.trim(),firstName:B.firstName?.trim(),lastName:B.lastName?.trim()});Vi.current=JSON.stringify(l),Zn(_=>({..._,...l})),Promise.resolve(ce(l)).catch(_=>{Vi.current="",$e(_ instanceof Error?_.message:"Failed to attach buyer details.")})},[fe,kn,ce,Zs,ko,B.email,B.firstName,B.lastName,$e]),(0,s.useEffect)(()=>{!fe||!Gt||Gt.setCardFieldOrder?.(R??null,pe==null&&!kn)},[fe,Gt,R,pe,kn]),(0,s.useEffect)(()=>{(ht==="expanding"||ht==="collapsing"||ht==="apm-expanding"||ht==="apm-collapsing")&&$e(null)},[ht,$e]);let Tr=(0,s.useCallback)((l,_,re)=>{p?.(un(l,_,re))},[p]),_o=(0,s.useCallback)((l,_,re)=>{let He=re?.popupBlocked??so(_);He&&b.markBlocked()&&S(ut=>ut+1);let me=ao(xs(l),He,y.inAppBrowser),Ue=Fr(_),Xt=(Ue?.toLowerCase()==="error"?void 0:Ue)??ho(re?.code)??"external_payment_method_failed",br=new f.FloPayError(me,"api_error",{code:"external_payment_method_failed",param:l,details:{providerCode:Xt,popupBlocked:He,inAppBrowser:y.inAppBrowser,appFamily:y.appFamily,popupCapability:b.current(),presentationMode:re?.presentationMode??"popup"}});re?.telemetryReported||pn(ze)?.error(Yo({...M,presentationMode:re?.presentationMode??"popup"},{errorCode:He?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:re?.provider??(l==="paypal"?"paypal":"stripe"),paymentMethodCategory:re?.paymentMethodCategory??(l==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:re?.terminalReason??(He?"popup_blocked":"provider_error")})),L(null),ne==="buttons"&&(an("buttons"),Vr(null)),$e(me),c?.(br),console.error("[FloPay] External payment method failed:",{method:l,code:Xt,popupBlocked:He})},[y,M,ze,ne,c,b,$e]);(0,s.useEffect)(()=>{if(!fe||!e){_r(null);return}let l=As($?.vault);if(l){_r(l);return}if(!gn){_r(null);return}_r(null);let _=!0;return new wr.PaymentAPI(he).getVaultCapture(e,t).then(re=>{if(!_)return;let He=As(re);He?_r(He):$e("Failed to load the secure card form.")}).catch(re=>{_&&$e(re instanceof Error?re.message:"Failed to load the secure card form.")}),()=>{_=!1}},[fe,gn,de,e,$?.vault,he,t,$e]);let gr=(0,s.useRef)({onComplete:i,onError:c,updateError:$e,emitDecline:Tr,resolvedAccount:B,avsConfig:pe,avsCheckProp:tt,sessionId:e,nonce:t,baseUrl:he,captureMethod:$?.captureMethod,paymentId:$?.paymentId,authorizationExpiresAt:$?.authorizationExpiresAt,serverSideCardGateway:Ut});gr.current={onComplete:i,onError:c,updateError:$e,emitDecline:Tr,resolvedAccount:B,avsConfig:pe,avsCheckProp:tt,sessionId:e,nonce:t,baseUrl:he,captureMethod:$?.captureMethod,paymentId:$?.paymentId,authorizationExpiresAt:$?.authorizationExpiresAt,serverSideCardGateway:Ut};let ji=(0,s.useRef)(!1),Qs=(0,s.useCallback)(()=>{let l=gr.current,_=l.resolvedAccount.email?.trim(),re=(0,f.isValidEmail)(_)?_:Qt.current.trim();if(!(0,f.isValidEmail)(re))return null;let He=l.resolvedAccount.firstName?.trim(),me=l.resolvedAccount.lastName?.trim(),Ue=wt.current.trim()||l.resolvedAccount.country?.trim()||"",Xt=l.avsConfig?(0,f.isAVSFieldVisible)(l.avsConfig.state,Ue):!1,br=l.avsConfig?(0,f.isAVSFieldVisible)(l.avsConfig.address_line_1,Ue):!1,ut=l.avsConfig?(0,f.isAVSFieldVisible)(l.avsConfig.postal_code,Ue):!1,Pt=l.avsConfig?(0,f.isAVSFieldVisible)(l.avsConfig.city,Ue):!1,kt=l.avsConfig?(0,f.isAVSFieldVisible)(l.avsConfig.address_line_2,Ue):!1,Vt=br&&!Xt&&ut?(0,f.getStateFromPostalCode)(Ue,(Et.current??"").trim()):null,dn=Xt?ln.current:Vt;return{accountData:{userId:l.resolvedAccount.userId??"",email:re,...He?{firstName:He}:{},...me?{lastName:me}:{},...ut&&Et.current?{zip:Et.current}:{},...Pt&&Ot.current?{city:Ot.current}:{},...dn?{state:dn}:{},...br&&Cn.current?{addressLine1:Cn.current}:{},...kt&&on.current?{addressLine2:on.current}:{},...Ue?{country:Ue}:{}},...l.avsCheckProp===void 0?{}:{avsCheck:l.avsCheckProp},...l.avsConfig?{avsConfig:{country:(0,f.isAVSFieldVisible)(l.avsConfig.country,Ue),postal_code:ut,address_line_1:br,address_line_2:kt,city:Pt,state:Xt}}:{}}},[]),el=(0,s.useRef)(J);el.current=J,(0,s.useEffect)(()=>{J||at!==hc||gr.current.updateError(null)},[J,at]),(0,s.useEffect)(()=>{!fe||!Gt||Gt.setSubmitGate?.(zr||J||ko||Se)},[fe,Gt,zr,J,ko,Se]),(0,s.useEffect)(()=>{if(!fe||!Gt)return;ji.current=!1;let l=null,_=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null,bt.current="idle",L(null)},400)},re=Gt.on("submitting",()=>{en(!0),Ge.current&&clearTimeout(Ge.current),bt.current="validation-window",Ge.current=setTimeout(()=>{Ge.current=null,bt.current==="validation-window"&&(bt.current="processing")},zu),L("processing");let ut=gr.current;if(!ut.sessionId||!ut.nonce)return;let Pt=Qs();if(!Pt){ut.updateError("Enter a valid email address."),bt.current="idle",L(null);return}new wr.PaymentAPI(ut.baseUrl).patchAccountSnapshot(ut.sessionId,ut.nonce,Pt,{telemetryMode:"best_effort"}).catch(kt=>{if(!qu(kt))return;let Vt=kt instanceof Error?kt.message:"Please check your billing address and try again.";ut.updateError(Vt),bt.current="idle",L(null),ut.onError?.(kt instanceof f.FloPayError?kt:new f.FloPayError(Vt,"api_error"))})}),He=Gt.on("complete",async ut=>{if(Wo(ut.sessionId??gr.current.sessionId),bt.current="terminal",Ye(!1),L("success"),await new Promise(dn=>setTimeout(dn,600)),ji.current)return;ji.current=!0;let Pt=gr.current,kt=(0,f.isAuthorizationOnlySession)(Pt)||ut.outcome==="authorized",Vt=Pt.serverSideCardGateway?{}:{paymentIntentId:ut.intentId};gr.current.onComplete?.(kt?{status:"authorized",...Vt,paymentId:ut.paymentId??Pt.paymentId,sessionId:ut.sessionId??Pt.sessionId,authorizationExpiresAt:ut.authorizationExpiresAt??Pt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Vt,checkoutMethod:"card"})}),me=Gt.on("decline",ut=>{let Pt=gr.current,kt=ut.message??"Your payment was declined. Please try another card or contact your bank.";bt.current="terminal",Ye(!1),Pt.updateError(kt),L("error");let Vt=ut.failureOutcome??(0,f.normalizeCheckoutFailureOutcome)(ut.declineReason)??"authorization_declined";Pt.emitDecline("card",kt,{code:Vt,declineCode:Vt}),_()}),Ue=Gt.on("error",ut=>{let Pt=gr.current,kt=ut.message??"There was a problem processing your payment. Please try again.";bt.current="terminal",Ye(!1),Pt.updateError(kt),L("error"),Pt.onError?.(new f.FloPayError(kt,"api_error",{code:ut.failureOutcome??"capture_failed"})),_()}),Xt=Gt.on("challenge_dismissed",()=>{Ge.current&&(clearTimeout(Ge.current),Ge.current=null),bt.current="processing",Ye(!0),L(null)}),br=Gt.on("blocked",()=>{if(te.current){gr.current.updateError(Uu);return}if(!el.current){en(!0);return}$i(),gr.current.updateError(hc)});return()=>{l&&(clearTimeout(l),l=null),Ge.current&&(clearTimeout(Ge.current),Ge.current=null),bt.current="idle",Ye(!1),L(null),re(),He(),me(),Ue(),Xt(),br()}},[fe,Gt,$i,Qs]);let Ar=!!gt?.clientId,ra=Array.isArray(se),Na=ra&&se.length>0,tl=ra&&se.includes("paypal"),za=(0,s.useRef)(null);za.current===null&&(za.current=Lu());let Eo=za.current?"redirect":Qa(y,I,b.current()),{expressMethods:Ua,paymentElementMethods:oa}=(0,s.useMemo)(()=>(0,f.partitionStripeMethods)(se,{excludePaypal:Ar}),[se,Ar]),nl=Ar||!!ft||tl&&Eo==="redirect",dd=(0,s.useMemo)(()=>nl?Ua.filter(l=>l!=="paypal"):Ua,[Ua,nl]),ud=(0,s.useMemo)(()=>{let l=[];return ee&&l.push("apple_pay"),we&&l.push("google_pay"),l},[ee,we]),To=ra?dd:ud,pd=H&&To.length>0,Hi=cn?Mt:V,qa=(0,s.useMemo)(()=>{let l=Hi?.trim().toUpperCase();return l?j?oa.filter(_=>{let re=j[_];return!re||re.length===0||re.includes(l)}):(0,f.filterStripeMethodsByCountry)(oa,Hi):oa},[oa,Hi,j]),Wi=(0,s.useMemo)(()=>({mode:"payment",amount:na,currency:Ro,paymentMethodCreation:"manual",appearance:Ys}),[na,Ro,Ys]),[rl,ol]=(0,s.useState)("loading"),[al,il]=(0,s.useState)("loading"),[sl,ll]=(0,s.useState)("loading"),[md,Ki]=(0,s.useState)(!1),[cl,Gi]=(0,s.useState)("loading"),[Yi,yd]=(0,s.useState)();(0,s.useEffect)(()=>{yd(Gr())},[]);let Va=Yi?.inAppBrowser,$a=Yi?ei(Yi,gt?.approvalPresentation,ie??(St?"subscription":"order")):"popup",dl=C&&(Ar||(ra?tl:Va===!1)),ul=H&&pd,aa=(!lt||!!Ve.waitForDataAttachment)&&dl&&Ar,pl=cl==="retrying"||cl==="exhausted",ia=null;H&&(ft?ia=Gs:Eo==="redirect"&&(ia=Wn));let ml=(0,s.useMemo)(()=>({...M,presentationMode:Eo}),[M,Eo]),sa=!lt&&dl&&!!ia&&(!Ar||pl),Ao=!lt&&ul&&!!Wn,la=!lt&&H&&Na&&qa.length>0&&!!Wn,fd=aa&&!pl?md:sa&&ks(rl),gd=Ao&&ks(al),hd=la&&sl!=="load_error",yl=l=>l==="loading"||l==="ready",fl=aa||sa&&yl(rl)||Ao&&yl(al)||la&&sl!=="load_error",ja=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!ja.current){if(!H&&!C){ja.current=!0;let l=new f.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(l),$e(l.message)}else if(!H&&C&&!Ar){ja.current=!0;let l=new f.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(l),$e(l.message)}else if(Va!==void 0&&!lt&&!Ae&&!fl){ja.current=!0;let l=new f.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),$e(l.message)}}},[H,C,Ar,Va,lt,Ae,fl,c,$e]);let gl=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(gl.current||!Na)return;let l=[];ee!==!0&&l.push("showApplePay"),we!==!0&&l.push("showGooglePay"),l.length!==0&&(gl.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.`))},[Na,ee,we]);let hl=(0,s.useCallback)((l,_)=>Ve.applyInlineSessionPatch?Ve.applyInlineSessionPatch(l).then(re=>({error:null,sessionId:re.sessionId||e,nonce:re.session?.clientSecret||t})).catch(re=>{let He=Cc(_,re);return $e(He.message),c?.(He),{error:He,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ve.applyInlineSessionPatch,t,c,e,$e]),hr=(0,s.useCallback)(async l=>{if(l!=="card"&&lt&&await Ve.waitForDataAttachment?.(),!ae)return{proceed:!0};try{let _=await ae({method:l,sessionId:e||void 0,createSession:Ve.inlineSessionDraft});if(_===!1)return{proceed:!1};if(_&&typeof _=="object"){_.account&&Zn(He=>({...He??{},..._.account}));let re=await hl(_,l);return re.error?{proceed:!1,accountPatch:_.account}:{proceed:!0,accountPatch:_.account,sessionId:re.sessionId,nonce:re.nonce}}return{proceed:!0}}catch(_){let re=Cc(l,_);return $e(re.message),c?.(re),{proceed:!1}}},[hl,Ve.inlineSessionDraft,Ve.waitForDataAttachment,lt,ae,c,e,$e]),bl=(0,s.useCallback)(async(l,_)=>{if(Pe.current)return;Pe.current=!0,Te(!0),L("processing"),$e(null);let re=_?.sessionId??e,He=_?.nonce??t,me=ls(B,_?.accountPatch),Ue=_?.completionPaymentMethodId??ha(l),Xt=l.originalPaymentMethodId?{...l,originalPaymentMethodId:void 0}:l,br=Hu(l),ut=_?.presentationMode?fi(pn(ze),{...M,presentationMode:_.presentationMode}):void 0,Pt=()=>{vt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:br}),ut?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Sr,requestCategory:"process_payment"})};try{let Vt=await new wr.PaymentAPI(he).processPayment(me.userId??"",{sessionId:re,nonce:He,paymentMethodCategory:_?.paymentMethodCategory??Ku(l),tokenizedData:Xt,accountData:{..._?.accountPatch,userId:me.userId??"",email:me.email??"",firstName:me.firstName||void 0,lastName:me.lastName||void 0,...pe?(()=>{let Nt=wt.current,Mr=(0,f.isAVSFieldVisible)(pe.state,Nt),Kn=(0,f.isAVSFieldVisible)(pe.address_line_1,Nt),xr=(0,f.isAVSFieldVisible)(pe.postal_code,Nt),fo=Kn&&!Mr&&xr?(0,f.getStateFromPostalCode)(Nt,(Et.current??"").trim()):null,ya=Mr?ln.current:fo;return{country:Nt,...xr&&Et.current?{zip:Et.current}:{},...(0,f.isAVSFieldVisible)(pe.city,Nt)&&Ot.current?{city:Ot.current}:{},...ya?{state:ya}:{},...Kn&&Cn.current?{addressLine1:Cn.current}:{},...(0,f.isAVSFieldVisible)(pe.address_line_2,Nt)&&on.current?{addressLine2:on.current}:{}}})():{}},chv:E,avsCheck:tt??!1,checkoutType:nt,checkoutLayout:pt,avsConfig:pe?{country:(0,f.isAVSFieldVisible)(pe.country,wt.current),postal_code:(0,f.isAVSFieldVisible)(pe.postal_code,wt.current),address_line_1:(0,f.isAVSFieldVisible)(pe.address_line_1,wt.current),address_line_2:(0,f.isAVSFieldVisible)(pe.address_line_2,wt.current),city:(0,f.isAVSFieldVisible)(pe.city,wt.current),state:(0,f.isAVSFieldVisible)(pe.state,wt.current)}:void 0});if(Vt.ok){let Nt=Vt.status===204?null:await Vt.json().catch(()=>null),Mr=(0,f.isAuthorizationOnlySession)($)||Nt?.status==="authorized";Wo(re),ut?.terminal({outcome:"payment_succeeded",...Sr}),L("success"),g(null),await new Promise(fo=>setTimeout(fo,600));let Kn;typeof Nt?.paymentId=="string"?Kn=Nt.paymentId:$?.paymentId&&(Kn=$.paymentId);let xr;typeof Nt?.authorizationExpiresAt=="string"?xr=Nt.authorizationExpiresAt:$?.authorizationExpiresAt&&(xr=$.authorizationExpiresAt),i?.(Mr?{status:"authorized",...Kn===void 0?{}:{paymentId:Kn},sessionId:typeof Nt?.sessionId=="string"?Nt.sessionId:re,...xr===void 0?{}:{authorizationExpiresAt:xr},paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Ue,checkoutMethod:l.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Ue,checkoutMethod:l.isPaypal?"paypal":"card"});return}let dn=await Vt.json().catch(()=>null);if(dn?.type==="paypal_redirect_required"){let Nt=dn.threeDSecureToken,Mr=dn.paymentMethodId||l.id||"";if(!ze||!Nt){L("error"),$e("PayPal authorization required but no token provided.");return}try{let Kn=ft?.getRawProvider();if(!Kn){$e("PayPal is not available.");return}let xr={return_url:window.location.href};Mr&&(xr.payment_method=Mr);let{error:fo}=await Kn.confirmPayment({clientSecret:Nt,confirmParams:xr,redirect:"if_required"});if(fo){L("error");let ya=fo.message??"PayPal payment failed.";$e(ya),Tr("paypal",ya,{code:fo.code})}}catch(Kn){L("error"),$e(Kn instanceof Error?Kn.message:"PayPal authorization failed.")}return}if(dn?.type==="paypal_direct_required"){let Nt=dn.orderId;if(!Nt){L("error"),$e("PayPal retry required but no order id provided.");return}let Mr=U.current?.attempts??0;if(Mr>=2){L("error"),$e("PayPal payment could not be completed after multiple attempts."),Tr("paypal","paypal_direct_required retry limit exceeded");return}Ki(!1),Gi("loading"),g({orderId:Nt,attempts:Mr+1}),L(null);return}(0,f.classifyPaymentRejection)(Vt.status,dn)?ut?.terminal({outcome:"payment_declined",...Sr,terminalReason:"provider_declined"}):Pt(),L("error");let Pr=dn?.message??"Payment failed. Please try again.";$e(Pr),Tr(l.isPaypal?"paypal":"card",Pr,{code:dn?.code??dn?.gatewayErrorCode,declineCode:dn?.declineCode??dn?.gatewayDeclineReason}),await new Promise(Nt=>setTimeout(Nt,400))}catch(kt){Tc(kt)||Pt(),L("error"),$e(kt instanceof Error?kt.message:"An unexpected error occurred"),await new Promise(Vt=>setTimeout(Vt,400))}finally{Te(!1),L(null),Pe.current=!1}},[he,e,t,B,pe,tt,nt,pt,E,ze,ft,$,i,$e,Tr,vt,M]),Ln=(0,s.useCallback)((l,_)=>{u?u(l):bl(l,_)},[u,bl]),ca=`${Ic}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let l=localStorage.getItem(ca);if(!l)return;let _;try{_=JSON.parse(l)}catch{jt(ca);return}if(!_||typeof _.createdAt!="number"||Date.now()-_.createdAt<0||Date.now()-_.createdAt>_c||typeof _.paymentMethodId!="string"||typeof _.providerIntentId!="string"||typeof _.paymentMethodType!="string"||_.sessionId!==e||!t||_.nonce!==t||!To.includes(_.paymentMethodType)){jt(ca);return}jt(ca),Ln({id:_.paymentMethodId,type:"card",threeDSecureActionResultTokenId:_.providerIntentId,gateway:"stripe",paymentMethodType:_.paymentMethodType},{..._.accountPatch?{accountPatch:_.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Ln,t,e,ca,To]);let Pl=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||Pl.current)return;let[l,_,re]=Ds();if(!l||!_||za.current||!ze)return;let He=ze.getRawProvider();if(!He)return;let me=Pt=>{let kt=localStorage.getItem(Pt);if(!kt)return null;try{return JSON.parse(kt)}catch{return jt(Pt),null}},Ue=me(Dr)??me(yc),Xt;if(Ue?.clientSecret){if(Ue.clientSecret!==_)return;Xt={...Ue.accountPatch?{accountPatch:Ue.accountPatch}:{},...Ue.sessionId?{sessionId:Ue.sessionId}:{},...Ue.nonce?{nonce:Ue.nonce}:{}}}else if(Ue?.sessionId&&Ue.sessionId!==e)return;Pl.current=!0,jt(Dr),jt(yc),window.history.replaceState({},"",Os());let br=Ue?.paymentMethodType??Ue?.tokenType??"card",ut="card";(async()=>{if(re==="failed"){let Pr="Payment was declined. Please try again.";$e(Pr),Tr(ut,Pr);return}let{paymentIntent:Pt,error:kt}=await He.retrievePaymentIntent(_);if(kt){let Pr=kt.message??"Failed to retrieve payment status.";$e(Pr),Tr(ut,Pr,{code:kt.code});return}let Vt=Pt?.status,dn=ga(Vt);if(!Pt||!dn){let Pr=Vt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";$e(Pr),Tr(ut,Pr,{code:Vt??"missing_payment_intent"});return}let Tl=typeof Pt.payment_method=="string"?Pt.payment_method:Pt.payment_method?.id;Ln({id:Tl??Ue?.paymentMethodId??Ue?.tokenId??Pt.id,type:"card",threeDSecureActionResultTokenId:Pt.id,gateway:Ue?.gateway??"stripe",paymentMethodType:br},Xt)})()},[e,Ln,ze,$e,Tr]);let Xi=(0,s.useCallback)(l=>{l.preventDefault()},[]);if(!(fe||ze!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let da=ne==="buttons",Nn=Oe?.variables,bd=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ji=Nn?.colorBackground,Pd=Ji&&!bd.has(Ji)?Ji:void 0,ua=O.cardInputBorder??(da?"#e5e7eb":"#A4A4FF"),vl=Nn?.colorDanger??"#dc2626",qt=l=>Ur[l]&&(Rr[l]||Bn),Ha=ko&&(qr||Bn),rr=l=>l?vl:ua,Wa=(hn.malformed||hn.empty)&&(kr||Bn),vd=rr(Wa),Zi=O.cardFormContainer?.backgroundColor??Pd??(da?"white":"#EDEDFF"),Mo=O.cardInputBackground??Nn?.colorBackground??"white",Qi=Bo(ke),Cl=Bo(Ie),xo=O.nameInput,Sl=O.cardInputFontSize??Zu(xo?.fontSize)??Nn?.fontSizeBase??"16px",wl=typeof xo?.fontFamily=="string"?xo.fontFamily:Nn?.fontFamily??"Poppins, sans-serif",kl=Is(xo?.fontWeight)??400,Cd=O.cardInputColor??(typeof xo?.color=="string"?xo.color:void 0)??Nn?.colorText??"#262833",Sd=O.cardInputPlaceholderColor??"#9ca3af",Yt=Nn?.borderRadius??"8px",mo=Nn?.borderRadius??O.cardButton?.borderRadius??Yt,yo=Nn?.colorPrimary??"#4A49FF",wd=Nn?.colorPrimaryHover??Zo(yo,.12),es=Nn?.colorText??"#262833",ts={fontSize:Sl,fontFamily:wl,fontWeight:kl,color:Cd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},pa={marginTop:"0.375rem",...ts,fontSize:"0.75rem",lineHeight:1.4,color:vl},kd={"--flopay-input-placeholder-color":Sd,"--flopay-input-font-size":Sl,"--flopay-input-font-family":wl,"--flopay-input-font-weight":String(kl)},ma=O.cardFormContainer??{},ns=ma.padding??(da?"0":"1rem"),rs=ma.borderRadius??Yt,Rd=Gt&&nr?(0,d.jsx)(uo,{capture:Gt,html:nr.html,messageToken:nr.messageToken,expectedOrigin:nr.expectedOrigin,theme:Tt,submitLabel:w,onReady:()=>{if(!kn&&!pe||typeof document>"u")return;let l=()=>{let re=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(re){ur.current=!0;try{re.focus()}finally{ur.current=!1}}};tr.current||l()},onError:l=>$e(l),onValidation:l=>{let _=bt.current;(_==="idle"||_==="validation-window")&&($e(l),l&&bt.current==="validation-window"&&(Ge.current&&(clearTimeout(Ge.current),Ge.current=null),bt.current="idle",L(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"}),Rl=(0,d.jsxs)("div",{onFocusCapture:l=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(l.target.tagName)&&mr()},style:{backgroundColor:Zi,borderRadius:rs,...ma,padding:ns,...kd,display:"flex",flexDirection:"column"},children:[(0,d.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 @@ ${Ye.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),aa&&Vn&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:pe?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:Vr,style:{display:"inline-flex",alignItems:"center",gap:zi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:D.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...D.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",...D.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:xe})]}),ll?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:D.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...D.title},children:(0,d.jsx)(da,{content:we})})]}),!aa&&!ll&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ui,order:pe?-3:0,...D.title},children:(0,d.jsx)(da,{content:we})}),pe&&ke&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:ke}),pe&&wn&&(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 ${er(za)}`,borderRadius:Yt,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=>{Ft("email"),Zt.current=l.target.value,sn(l.target.value)},onPointerDown:()=>Ft("email"),onKeyDown:()=>Ft("email"),onBlur:()=>{dr("email")&&Fn(!0),Co||Ti()},disabled:X,required:!0,"aria-invalid":za||void 0,"aria-describedby":za?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...qi}})}),za&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:sa,children:Ir.empty?"Email address is required":"Enter a valid email address"})]}),se&&(0,d.jsx)("div",{style:{order:pe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let l=Mt,_=(ce=!1)=>({backgroundColor:Eo,border:`1px solid ${er(ce)}`,borderRadius:Yt,marginTop:"0.5rem",padding:"10px"}),ne=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...qi}),Ve=(0,y.getStateOptions)(l);return(0,d.jsxs)(d.Fragment,{children:[(0,y.isAVSFieldVisible)(se.address_line_1,l)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:_(qt("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:mn,onChange:ce=>{Ft("line1"),Lt.current.addressLine1=!0,vn.current=ce.target.value,Dt(ce.target.value)},onPointerDown:()=>Ft("line1"),onKeyDown:()=>Ft("line1"),onBlur:()=>_n("line1"),disabled:X,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,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:sa,children:"Street address is required"})]}),(0,y.isAVSFieldVisible)(se.address_line_2,l)&&(0,d.jsx)("div",{style:_(),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:mt,onChange:ce=>{Lt.current.addressLine2=!0,rn.current=ce.target.value,nt(ce.target.value)},disabled:X,"data-testid":"flopay-address-line2",style:ne()})}),((0,y.isAVSFieldVisible)(se.city,l)||(0,y.isAVSFieldVisible)(se.state,l))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(se.city,l)&&(0,d.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,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Rn,onChange:ce=>{Ft("city"),Lt.current.city=!0,Ot.current=ce.target.value,xt(ce.target.value)},onPointerDown:()=>Ft("city"),onKeyDown:()=>Ft("city"),onBlur:()=>_n("city"),disabled:X,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,d.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:Ve?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:In,onChange:ce=>{Ft("state"),Lt.current.state=!0,ln.current=ce.target.value,yn(ce.target.value)},onPointerDown:()=>Ft("state"),onKeyDown:()=>Ft("state"),onBlur:()=>_n("state"),disabled:X,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,d.jsx)("option",{value:"",children:(0,y.getStateLabel)(l)}),Ve.map(ce=>(0,d.jsx)("option",{value:ce.code,children:ce.name},ce.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:In,onChange:ce=>{Ft("state"),Lt.current.state=!0,ln.current=ce.target.value,yn(ce.target.value)},onPointerDown:()=>Ft("state"),onKeyDown:()=>Ft("state"),onBlur:()=>_n("state"),disabled:X,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,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:sa,children:"City is required"}),qt("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:sa,children:[(0,y.getStateLabel)(l)," is required"]}),((0,y.isAVSFieldVisible)(se.country,l)||(0,y.isAVSFieldVisible)(se.postal_code,l))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:ge==="column"?"column":"row",gap:ge==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(se.country,l)&&(0,d.jsx)("div",{style:{flex:ge==="row"?1:void 0,backgroundColor:Eo,borderTop:`1px solid ${ia}`,borderRight:`1px solid ${ia}`,borderBottom:`1px solid ${ia}`,borderLeft:`1px solid ${ia}`,padding:"10px",...ge==="row"&&(0,y.isAVSFieldVisible)(se.postal_code,l)?{borderRadius:"0",borderTopLeftRadius:Yt,borderBottomLeftRadius:Yt,borderRight:"none"}:{borderRadius:Yt}},children:(0,d.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Mt,onChange:ce=>{Lt.current.country=!0,St.current=ce.target.value,kn(ce.target.value),st?.(ce.target.value),ln.current="",yn("")},disabled:X,autoComplete:"billing country","data-testid":"flopay-country",style:{...ne(),cursor:"pointer"},children:[Mt===""?(0,d.jsx)("option",{value:"",children:"Select country"}):null,y.COUNTRY_OPTIONS.map(ce=>(0,d.jsxs)("option",{value:ce.code,children:[ce.flag," ",ce.name]},ce.code))]})}),(0,y.isAVSFieldVisible)(se.postal_code,l)&&(0,d.jsx)("div",{style:{flex:ge==="row"?1:void 0,backgroundColor:Eo,border:`1px solid ${dd}`,padding:"10px",...ge==="row"&&(0,y.isAVSFieldVisible)(se.country,l)?{borderRadius:"0",borderTopRightRadius:Yt,borderBottomRightRadius:Yt}:{borderRadius:Yt}},children:(0,d.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:ce=>{Ft("zip"),Lt.current.zip=!0,Et.current=ce.target.value,Kn(ce.target.value),De?.(ce.target.value)},onPointerDown:()=>Ft("zip"),onKeyDown:()=>Ft("zip"),onBlur:()=>{dr("zip")&&xn(!0)},disabled:X,required:gn.required,"aria-invalid":Ua||void 0,"aria-describedby":Ua?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:ne()})})]}),Ua&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:sa,children:gn.empty?`${(0,y.getPostalCodeLabel)(l)} is required`:zu(l)})]})})()}),pe&&fd,at&&(0,d.jsx)(Uo,{margin:"0.75rem 0",styleOverride:D.errorBanner,children:at})]}),qa={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"},ml=l=>v?!S||!Er?(0,d.jsx)("pre",{"data-testid":l,style:qa,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":l,style:qa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${S}`,` directPaypalConfigured=${Er}`,` inAppBrowserDetected=${String(Oa)}`,` shouldRenderDirectPayPal=${ea}`,` shouldRenderStripePayPal=${na}`,` hasPaypalStripeInstance=${!!Ds}`].join(`
39
- `)}):null,yl=l=>v?!W||!jn?(0,d.jsx)("pre",{"data-testid":l,style:qa,children:"FloPay/Stripe-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":l,style:qa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${W}`,` currency=${At}`,` amountInCents=${Jo}`,` enabledPaymentMethods: ${JSON.stringify(re??[])}`,` enabledPaymentMethodsProvided=${Zo}`,` hasEnabledMethods=${xa}`,` expressMethods: ${JSON.stringify(Ba)}`,` walletExpressMethods: ${JSON.stringify(Io)}`,` paymentElementMethods: ${JSON.stringify(Qo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Da)}`,` hasStripeInstance=${!!jn}`,` shouldRenderWallets=${_o}`,` shouldRenderPaymentElement=${ra}`].join(`
40
- `)}):null,fl=ft==="apm-expanding"||ft==="apm-form"||ft==="apm-collapsing",Ao;ft==="apm-expanding"?Ao=ac:ft==="apm-collapsing"&&(Ao=ic);let Va=en?Sc(xi,en):null;if(H==="buttons"){let l=ft==="buttons"||ft==="expanding"||ft==="apm-expanding",_=ft==="expanding"||ft==="card"||ft==="collapsing",ne=ut===void 0?{boxSizing:"border-box",height:Ia,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ve;ft==="expanding"||ft==="apm-expanding"?Ve=Bu:(ft==="collapsing"||ft==="apm-collapsing")&&(Ve=Fu);let ce;return ft==="expanding"?ce=ac:ft==="collapsing"&&(ce=ic),(0,d.jsxs)("form",{onSubmit:Oi,className:E,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(gs,{}),q&&(0,d.jsx)(Ln,{status:q,errorMessage:at,authorized:qn}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!l&&!Ve?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!l&&!Ve?Ou:{},...Ve?{animation:Ve,pointerEvents:"none"}:{}},children:[ml("flopay-direct-paypal-gate-debug"),yl("flopay-stripe-gate-debug"),ea&&gt&&(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)(ya.Provider,{value:f,children:(0,d.jsx)(ga,{sessionId:e,nonce:t,billingApiUrl:Ye,email:F.email,billingName:Qe||void 0,onBuyerIdentityReady:ae,clientId:gt.clientId,environment:gt.environment,currency:At.toUpperCase(),isSubscription:Ct,providerObjectType:We,approvalPresentation:La==="popup"?void 0:La,onTokenizedBody:Bn,onComplete:i,onErrorChange:Le,onDecline:p,onTechnicalFailure:ko,onButtonClick:de,runBeforeButtonClick:fr,isProcessing:X,onLoadStateChange:Fi,onInitializationStateChange:Bi,session:Bt,existingOrderId:m?.orderId,debug:v},m?.orderId??"fresh")})]}),na&&(0,d.jsx)(Jt.Elements,{stripe:ta,options:Ns,children:(0,d.jsx)(dc,{sessionId:e,nonce:t,email:F.email,billingName:Qe||void 0,onBuyerIdentityReady:ae,billingApiUrl:Ye,onTokenizedBody:Bn,onErrorChange:Le,isProcessing:X,onButtonClick:de,onDecline:p,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:Ws,placeholderBorderRadius:uo,popupCapabilityOwner:f,externalTelemetryContext:el,presentationMode:Ro})}),_o?(0,d.jsx)(Jt.Elements,{stripe:jn,options:Ls,children:(0,d.jsx)(pc,{sessionId:e,nonce:t,email:F.email,billingName:Qe||void 0,onBuyerIdentityReady:ae,billingApiUrl:Ye,intentKind:Ae>0?"payment":"setup",expressMethods:Io,onTokenizedBody:Bn,onErrorChange:Le,onButtonClick:de,onDecline:p,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:Ks,placeholderBorderRadius:uo,popupCapabilityOwner:f,externalTelemetryContext:Pe})}):null,!_o&&Zs?(0,d.jsx)("div",{style:{height:Ia,borderRadius:uo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ra&&(0,d.jsx)(mc,{sessionId:e,nonce:t,email:F.email,billingName:[F.firstName,F.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ae,billingApiUrl:Ye,paymentElementMethods:Da,stripeInstance:jn,paymentElementBaseOptions:xi,onTokenizedBody:Bn,onErrorChange:Le,onButtonClick:de,onDecline:p,runBeforeButtonClick:fr,onLoadStateChange:Ys,isProcessing:X,submitButtonColor:po,submitButtonBorderRadius:Yt,submitButtonStyle:D.submitButton,onExpandApm:En,expandedApmMethod:en,themeId:Ne,buttonAppearance:{backgroundColor:D.cardButton?.backgroundColor,borderColor:D.cardInputBorder,textColor:D.cardButton?.color,borderRadius:uo}}),pe&&(0,d.jsx)("button",{type:"button",onClick:async()=>{X||!(await fr("card")).proceed||(de?.("card"),mr())},disabled:X,style:{width:"100%",...ne,...D.cardButton,...ks({themeBundle:Rt,resolvedPrimaryColor:po,resolvedBorderRadius:Yt,submitButtonStyle:D.submitButton,explicitPrimaryColor:Dn?.colorPrimary}),fontSize:D.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:X?"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:X?.6:1},onMouseEnter:Oe=>{!X&&(Rt||Dn?.colorPrimary)&&(Oe.currentTarget.style.backgroundColor=md)},onMouseLeave:Oe=>{(Rt||Dn?.colorPrimary)&&(Oe.currentTarget.style.backgroundColor=po)},onMouseDown:Oe=>{Oe.currentTarget.style.transform="scale(0.985)"},onMouseUp:Oe=>{Oe.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(xo,{content:ut})}),at&&ft==="buttons"&&(0,d.jsx)(Uo,{margin:"0.25rem 0",styleOverride:D.errorBanner,children:at})]}),pe&&_&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...ce?{animation:ce}:{},...ft==="collapsing"?{pointerEvents:"none"}:{}},children:pl}),W&&fl&&en&&Va&&jn&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Ao?{animation:Ao}:{},...ft==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Ni,borderRadius:ji,...la,padding:Vi},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:L,style:{display:"inline-flex",alignItems:"center",gap:zi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:D.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...D.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",...D.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:xe})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:D.titleFontSize??"1.05rem",color:Ui,paddingRight:80,...D.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(en)}`})]}),(0,d.jsx)(Jt.Elements,{stripe:jn,options:Va,children:(0,d.jsx)(bs,{method:en,sessionId:e,nonce:t,email:F.email,billingName:[F.firstName,F.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ae,billingApiUrl:Ye,onTokenizedBody:Bn,onErrorChange:Le,onDecline:p,onCancel:L,runBeforeButtonClick:fr,onButtonClick:de,isProcessing:X,submitButtonColor:po,submitButtonBorderRadius:Yt,submitButtonStyle:D.submitButton,errorText:at})},en)]})})]})]})}return fl&&en&&Va&&jn&&W?(0,d.jsxs)("form",{onSubmit:Oi,className:E,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(gs,{}),q&&(0,d.jsx)(Ln,{status:q,errorMessage:at,authorized:qn}),(0,d.jsx)("div",{style:{...Ao?{animation:Ao}:{},...ft==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Ni,borderRadius:ji,...la,padding:Vi},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:L,style:{display:"inline-flex",alignItems:"center",gap:zi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:D.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...D.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",...D.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:xe})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:D.titleFontSize??"1.05rem",color:Ui,paddingRight:80,...D.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(en)}`})]}),(0,d.jsx)(Jt.Elements,{stripe:jn,options:Va,children:(0,d.jsx)(bs,{method:en,sessionId:e,nonce:t,email:F.email,billingName:[F.firstName,F.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ae,billingApiUrl:Ye,onTokenizedBody:Bn,onErrorChange:Le,onDecline:p,onCancel:L,runBeforeButtonClick:fr,onButtonClick:de,isProcessing:X,submitButtonColor:po,submitButtonBorderRadius:Yt,submitButtonStyle:D.submitButton,errorText:at})},en)]})})]}):(0,d.jsxs)("form",{onSubmit:Oi,className:E,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(gs,{}),q&&(0,d.jsx)(Ln,{status:q,errorMessage:at,authorized:qn}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ml("flopay-direct-paypal-gate-debug-default"),yl("flopay-stripe-gate-debug-default"),ea&&gt&&(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)(ya.Provider,{value:f,children:(0,d.jsx)(ga,{sessionId:e,nonce:t,billingApiUrl:Ye,email:F.email,billingName:Qe||void 0,onBuyerIdentityReady:ae,clientId:gt.clientId,environment:gt.environment,currency:At.toUpperCase(),isSubscription:Ct,providerObjectType:We,approvalPresentation:La==="popup"?void 0:La,onTokenizedBody:Bn,onComplete:i,onErrorChange:Le,onDecline:p,onTechnicalFailure:ko,onButtonClick:de,runBeforeButtonClick:fr,isProcessing:X,onLoadStateChange:Fi,onInitializationStateChange:Bi,session:Bt,existingOrderId:m?.orderId,debug:v},m?.orderId??"fresh")})]}),na&&(0,d.jsx)(Jt.Elements,{stripe:ta,options:Ns,children:(0,d.jsx)(dc,{sessionId:e,nonce:t,email:F.email,billingName:Qe||void 0,onBuyerIdentityReady:ae,billingApiUrl:Ye,onTokenizedBody:Bn,onErrorChange:Le,isProcessing:X,onButtonClick:de,onDecline:p,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:Ws,placeholderBorderRadius:uo,popupCapabilityOwner:f,externalTelemetryContext:el,presentationMode:Ro})}),_o&&(0,d.jsx)(Jt.Elements,{stripe:jn,options:Ls,children:(0,d.jsx)(pc,{sessionId:e,nonce:t,email:F.email,billingName:Qe||void 0,onBuyerIdentityReady:ae,billingApiUrl:Ye,intentKind:Ae>0?"payment":"setup",expressMethods:Io,onTokenizedBody:Bn,onErrorChange:Le,onButtonClick:de,onDecline:p,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:Ks,placeholderBorderRadius:uo,popupCapabilityOwner:f,externalTelemetryContext:Pe})}),ra&&(0,d.jsx)(mc,{sessionId:e,nonce:t,email:F.email,billingName:[F.firstName,F.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Ye,paymentElementMethods:Da,stripeInstance:jn,paymentElementBaseOptions:xi,onTokenizedBody:Bn,onErrorChange:Le,onButtonClick:de,onDecline:p,runBeforeButtonClick:fr,onLoadStateChange:Ys,isProcessing:X,submitButtonColor:po,submitButtonBorderRadius:Yt,submitButtonStyle:D.submitButton,themeId:Ne,onExpandApm:En,expandedApmMethod:en,buttonAppearance:{backgroundColor:D.cardButton?.backgroundColor,borderColor:D.cardInputBorder,textColor:D.cardButton?.color,borderRadius:uo}})]}),pe&&(id||ad||sd)&&(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"}})]}),pe&&pl]})}var N=require("react/jsx-runtime"),Yo=44,As="flopay_checkout_saved_payment_resume",vi=new Map,Pi=new Map;function wc(e,t){t.settled&&t.consumers===0&&vi.get(e)===t&&vi.delete(e)}function Wu(e,t,n){let r=Pi.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Pi.set(e,a);let i=()=>{Pi.get(e)===a&&Pi.delete(e)};return o.then(i,i),o}function Ea(e){return new Promise(t=>setTimeout(t,e))}function bi(e,t,n){let r=Ja({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:it.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Ta(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Rs(e,t,n,r,o,a){let i=bi(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),Ta(i)}function kc(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 Rc(e,t,n,r,o){let a=(0,it.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 it.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof it.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 Tc(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:!!Tc(e)?.clientId}var Hu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Ku(e){return new Yr.FloPay(Hu,{publishableKey:"provider_unavailable",...e})}async function _s(e,t){let{publishableKey:n,paypalPublishableKey:r}=ls(e);return{...await cs({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Ms(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Gu(){if(!Ms())return null;try{let e=window.sessionStorage.getItem(As);return e?JSON.parse(e):null}catch{return null}}function Ic(e){if(Ms())try{window.sessionStorage.setItem(As,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Es(){if(Ms())try{window.sessionStorage.removeItem(As)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Yu(){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 _c(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 Ts(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Xu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Ec(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Ju(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 Ci({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:i,loading:c,error:p,onComplete:u,onError:g,onInstrument:P,onDecline:R,onCountryChange:E,onZipChange:w,showPayPal:M=!0,showStripe:T=!0,walletPresentation:b="auto",enabledPaymentMethods:S,showApplePay:W=!0,showGooglePay:A=!0,debug:re=!1,layout:V,theme:Y,buttonsTheme:le,buttonsStyles:H,cardButtonContent:Ne,cardBackButtonContent:je,cardTitleContent:oe,showSecurityFooter:ze,onButtonClick:ut,onBeforeButtonClick:xe,enableAVS:we,cardFieldOrder:ve,cardPreFormSlot:de,avsLayout:Te,submitLabel:$e,className:ot,initialErrorMessage:I=null,initialPayPalOrderId:ke,children:ge,checkoutMode:j,confirmLabel:Ee,renderConfirmButton:Q,onSessionCompleted:Be}){let ee=(0,it.resolveBillingApiUrl)(r),Je=(0,k.useMemo)(()=>(0,it.resolveTheme)(Y),[Y]),st=a??Je?.appearance,De=n?"embedded_checkout":"standard_checkout",et=Ts(ge,V),[tt,pt]=(0,k.useState)(null),[Ae,At]=(0,k.useState)(null),kt=(0,k.useRef)(null),gt=(0,k.useRef)(null),Ct=(0,k.useRef)(0),[$,he]=(0,k.useState)(null),Ue=(0,k.useRef)(null),[v,J]=(0,k.useState)(null),Fe=(0,k.useMemo)(()=>n?Vo(n):"",[n]),ue=n?`create:${Fe}`:`session:${e??""}`,Ce=Ec(v),z=(0,k.useRef)(new Set),f=(0,k.useRef)(ue),C=(0,k.useRef)(ue);ho(()=>{C.current=ue,f.current!==ue&&(f.current=ue,z.current.clear())},[ue]);let Z=(0,k.useCallback)(L=>{if(C.current===ue){if(Zi.has(L.name)){if(z.current.has(L.name))return;z.current.add(L.name)}Xe(()=>P?.(L))}},[ue,P]),K=zo(Z,ue),Pe=(0,k.useRef)(!1),Bt=(0,k.useCallback)(L=>{if(Pe.current)return;let q=L.gateway||!Ce?L:{...L,gateway:Ce};Z(q)},[Z,Ce]);(0,k.useEffect)(()=>{K({class:"lifecycle",name:"checkout.mount"})},[K]);let[We,Ze]=(0,k.useState)(e??""),Se=e??We,bt=n?"":Se,[Wt,Ye]=(0,k.useState)(!0),[Tn,Re]=(0,k.useState)(null),[zn,Un]=(0,k.useState)(0),[Mt,kn]=(0,k.useState)("full"),[An,Kn]=(0,k.useState)(!1),[mn,Dt]=(0,k.useState)(I),[mt,nt]=(0,k.useState)(null),[Rn,xt]=(0,k.useState)(null),[In,yn]=(0,k.useState)(!1),[Ht,sn]=(0,k.useState)(void 0),[Gn,Yn]=(0,k.useState)(""),[Et,St]=(0,k.useState)(!1),[vn,rn]=(0,k.useState)(!1),[Ot,ln]=(0,k.useState)(!1),Zt=(0,k.useRef)(null),Lt=(0,k.useRef)(0),se=(0,k.useRef)(void 0),[cn,qn]=(0,k.useState)("loading"),[Lr,sr]=(0,k.useState)(0),Ut=(0,k.useRef)(!1),lr=(0,k.useRef)(!1),Cn=(0,k.useRef)(!1),Ie=(0,k.useRef)(null),pe=(0,k.useRef)(null),B=(0,k.useMemo)(()=>({checkoutMode:j??Mt,layout:Xu(ge,V)}),[j,ge,Mt,V]),lt=(0,k.useRef)(u);lt.current=u;let ie=(0,k.useRef)(g);ie.current=g;let Sn=(0,k.useRef)(R);Sn.current=R;let fn=(0,k.useCallback)(L=>ii(Ie,async q=>{try{return await L(q)}catch(O){throw q.aborted?io(O):O}}),[]);(0,k.useEffect)(()=>()=>{Ie.current?.abort(),Ie.current=null},[]);let Kt=(0,k.useCallback)((L,q)=>{kt.current=L,At(L),Ue.current=q,he(q)},[]),Xn=(0,k.useCallback)(()=>{let L=gt.current;L&&(gt.current=null,L.destroy())},[]);(0,k.useEffect)(()=>{pn(Ae)?.setCheckoutContext(B),$&&$!==Ae&&pn($)?.setCheckoutContext(B)},[Ae,$,B]);let yt=(0,k.useRef)(Be);yt.current=Be;let Xr=(0,k.useCallback)(L=>{qn(L),!(L!=="exhausted"||Cn.current)&&(Cn.current=!0,ie.current?.(new it.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Gt=(0,k.useCallback)(()=>{qn("retrying"),sr(L=>L+1)},[]);(0,k.useEffect)(()=>{qn("loading"),sr(0),Cn.current=!1},[Se]),(0,k.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:it.SDK_VERSION,checkout_type:De,checkout_layout:et,billing_api_url:ee})},[et,De,ee]);let gn=(0,k.useMemo)(()=>n?Vo(n,!0):"",[n]),Nr=(0,k.useMemo)(()=>Gn===gn?Ht:void 0,[Ht,Gn,gn]),zr=(0,k.useMemo)(()=>n?Ki(n,Nr):void 0,[n,Nr]),Mn=j??zr?.checkoutMode??"full",Qt=(0,k.useMemo)(()=>zr?{...zr,checkoutMode:Mn}:void 0,[zr,Mn]);(0,k.useEffect)(()=>{sn(void 0),Yn(gn),se.current=void 0,Zt.current=null,ln(!1)},[gn]),(0,k.useEffect)(()=>{Dt(I)},[I]);let Sr=(0,k.useCallback)((L,q,O)=>{Xe(()=>{Sn.current?.(un(L,q,O))})},[]),xn=(0,k.useCallback)(async(L,q)=>{Dt(null),xt(null),yn(!1),nt("processing");let O=q?.sessionId??L.id,ye=L.clientSecret||t,He=Ec(L),ht=kt.current??Ue.current,be=pn(ht),Ke=ht?null:bi(ee,o,B),te={log:D=>{be?be.log(D):Ke?.log(D)},error:D=>{be?be.error(D):Ke?.error(D)},terminal:D=>{be?be.terminal(D):Ke?.terminal(D)},performance:D=>{be?be.performance(D):Ke?.performance(D)},now:()=>be?.now()??Ke?.now()??0,elapsed:D=>be?.elapsed(D)??Math.max(0,(Ke?.now()??D)-D)},m=te.now(),h=!!(q?.initialAutoProcessingError||q?.initialAutoProcessingPending),U=!1,G,fe=()=>{U||(U=!0,h=!0,G=te.now(),te.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ae=!1,at=()=>{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"}),G!==void 0&&te.performance({stage:"recovery",durationMs:te.elapsed(G),durationMode:"machine",paymentMethodCategory:"saved"}))};te.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Pe.current=!0;try{te.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Pe.current=!1}K({class:"lifecycle",name:"payment.processing.started",provider:He}),h&&fe();let Rt;try{let D=jl(q?.initialAutoProcessingError),Me=q?.initialAutoProcessingError?.type==="3ds_required"&&!q.initialAutoProcessingError.threeDSecureToken&&q.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:q.initialAutoProcessingError.nextActionRedirectUrl}:null,Tt,_e=X=>(fe(),fn(me=>$o(X,{billingApiUrl:ee,sessionId:O,nonce:ye,session:L,signal:me})));if(Me)Tt=await _e(Me);else if(D)fe(),D.type==="paypal_redirect_required"&&pe.current?.publishableKey&&Ic({sessionId:O,publishableKey:pe.current.publishableKey,paypalPublishableKey:pe.current.paypalPublishableKey}),Tt=await fn(X=>li(D,{flopay:kt.current,paypalFlopay:Ue.current,attempt3DS:q?.attempt3DS,billingApiUrl:ee,sessionId:O,session:L,telemetry:!1,signal:X})),D.type==="paypal_redirect_required"&&Es();else if(q?.initialAutoProcessingPending){let X=q.initialAutoProcessingPending,me=new Yr.PaymentAPI(ee,{telemetry:!1}),F=await fn(qe=>me.waitForCheckoutSessionCompletion(X.sessionId,{initialDelayMs:X.retryAfterMs,nonce:ye,statusUrl:X.statusUrl,signal:qe})),Qe=to(F,L),It=F.autoProcessingError?.type==="3ds_required"&&F.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:F.autoProcessingError.nextActionRedirectUrl}:null;if(It)Tt=await _e(It);else{if(!$r(Qe))throw Do(Qe);Tt=jr(Qe,O)}}else{if(q?.initialAutoProcessingError)throw xr(q.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:q.initialAutoProcessingError.checkoutMethod});if(q?.fromCreateSession)return q?.fallbackToFull&&(kn("full"),_c("full")),!1;{let X=await Wo({billingApiUrl:ee,sessionId:O,session:L,nonce:ye,telemetry:!1});X.type==="success"?Tt=X.result:X.type==="next_action_required"?Tt=await _e(X):(fe(),X.type==="paypal_redirect_required"&&pe.current?.publishableKey&&Ic({sessionId:O,publishableKey:pe.current.publishableKey,paypalPublishableKey:pe.current.paypalPublishableKey}),Tt=await fn(me=>li(X,{flopay:kt.current,paypalFlopay:Ue.current,attempt3DS:q?.attempt3DS,billingApiUrl:ee,sessionId:O,session:L,telemetry:!1,signal:me})),X.type==="paypal_redirect_required"&&Es())}}O&&jo(O),at(),h&&(te.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),te.terminal({outcome:Tt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),yn(Tt.status==="authorized"),nt("success"),await Ea(600),Rt=()=>lt.current?.(Tt)}catch(D){let Me=Qr(Ca(D),O);if(Me.code==="three_ds_aborted")return!1;let Tt=Me.checkoutMethod??va;Dt(Me.message),xt(Me.message),yn(!1),q?.fallbackToFull&&(te.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),kn("full"),_c("full")),at();let _e=Me.statusCode===void 0?void 0:(0,it.telemetryStatusClass)(Me.statusCode,"unknown"),X=_e==="4xx"?{requestCategory:"process_payment",statusClass:_e}:{},me=_e===void 0||_e==="4xx";if(me&&(Me.telemetryOutcome==="payment_declined"||!!(Me.declineCode||Me.code?.toLowerCase().includes("declin"))))te.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...X});else if(me&&(Me.telemetryOutcome==="validation_rejected"||Me.type==="validation_error"))te.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...X});else{let It=(0,it.classifyTelemetryFailure)(D,h?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),qe=Me.telemetryRequestCategory??"process_payment";Pe.current=!0;try{te.error({...It,...Me.telemetryFailureCategory?{failureCategory:Me.telemetryFailureCategory}:{},stage:h?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:qe})}finally{Pe.current=!1}K({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:qe,provider:He})}return Xe(()=>ie.current?.(Me)),Sr(Tt,Me,{code:Me.code,declineCode:Me.declineCode}),nt("error"),await Promise.allSettled([Ea(400),q?.ensureProvidersReady?q.ensureProvidersReady():Promise.resolve()]),h&&(te.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{at(),Ke&&Ta(Ke),nt(null),xt(null)}return Xe(Rt),!0},[Sr,K,t,ee,fn,o,B]);(0,k.useEffect)(()=>{if(typeof window>"u"||lr.current)return;let L=new URLSearchParams(window.location.search),q=L.get("payment_intent_client_secret");if(!q)return;let O=Gu();O&&(lr.current=!0,(async()=>{let ye,He=0;Dt(null),xt(null),nt("processing"),Kn(!0);try{if(L.get("redirect_status")==="failed")throw Object.assign(new it.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ht,paypalFlopay:be}=await cs({publishableKey:O.publishableKey,paypalPublishableKey:O.paypalPublishableKey,billingApiUrl:ee,locale:i,telemetry:o});ye=pn(be??ht),ye?.setCheckoutContext(B),He=ye?.now()??0,ye?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ye?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Ke=(be??ht)?.getRawProvider();if(!Ke)throw Object.assign(new it.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:te,error:m}=await Ke.retrievePaymentIntent(q);if(m)throw Object.assign(new it.FloPayError(m.message??"Failed to retrieve PayPal payment status.","api_error",{code:m.code}),{checkoutMethod:"paypal"});let h=kl(te?.status);if(!te||h==="failed")throw Object.assign(new it.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let U=typeof te.payment_method=="string"?te.payment_method:te.payment_method?.id,G=h;if(O.sessionId){let at=(await new Yr.PaymentAPI(ee,{telemetry:!1}).getUnifiedCheckoutSession(O.sessionId)).data.session;if(at&&at.status!=="complete"){let Rt=await Wo({billingApiUrl:ee,sessionId:O.sessionId,session:at,telemetry:!1,tokenizedData:{id:U??te.id,type:"card",threeDSecureActionResultTokenId:te.id,isPaypal:!0}});if(Rt.type!=="success")throw Object.assign(new it.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});G=Rt.result.status}}O.sessionId&&jo(O.sessionId),ye?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ye?.performance({stage:"redirect_resume",durationMs:ye.elapsed(He),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ye?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),nt("success"),await Ea(600),Xe(()=>lt.current?.({status:G,paymentIntentId:te.id,paymentMethodId:U,checkoutMethod:"paypal"}))}catch(ht){let be=Qr(Ca(ht),O.sessionId),Ke=be.checkoutMethod??"paypal",te=!!(be.declineCode||be.code?.toLowerCase().includes("declin"));if(ye)ye.performance({stage:"redirect_resume",durationMs:ye.elapsed(He),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),te?ye.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ye.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(te){let m=bi(ee,o,B);m.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ta(m)}else Rs(ee,o,B,"REDIRECT_RESUME_FAILED","redirect_resume");Dt(be.message),xt(be.message),Xe(()=>ie.current?.(be)),Sr(Ke,be,{code:be.code,declineCode:be.declineCode}),nt("error"),await Ea(400)}finally{Es(),Yu(),nt(null),xt(null),Kn(!1)}})())},[Sr,i,ee,o,B]);let Ur=(0,k.useRef)(null),Fn=(0,k.useMemo)(()=>Qt?Vo(Qt):"",[Qt]),wr=(0,k.useRef)(Qt);wr.current=Qt,(0,k.useEffect)(()=>{Ze(e??"")},[e]),(0,k.useEffect)(()=>{Ut.current=!1,Dt(I),xt(null),yn(!1),nt(null)},[Fn,I,e]);async function kr(L,q,O){let ye=bi(ee,o,B),He=new Yr.PaymentAPI(ee,{telemetry:!1}),ht=!1;try{let be=L.idempotencyKey===void 0?void 0:(0,it.resolveIdempotencyKey)(L.idempotencyKey),Ke=ts(q,O),te=ns(q,O);Ke?.canonicalIdentity===O&&te&&te.canonicalIdentity===void 0&&(oi(q,O,te.idempotencyKey),te={...te,canonicalIdentity:O});let m=be??(te?.canonicalIdentity===O?te.idempotencyKey:void 0),h,U=!1;ye.log({name:Ke?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let G=Ke?.sid??null,fe=null,ae,at,Rt=!1;if(G)try{fe=await He.getUnifiedCheckoutSession(G,Ke?.nonce),Ke&&Ke.canonicalIdentity===void 0&&(zl(fe.data.session,L)?(ri(q,O,G,Ke.nonce??fe.data.session?.clientSecret),te&&te.canonicalIdentity===void 0&&(oi(q,O,te.idempotencyKey),m??(m=te.idempotencyKey))):(ni(q,O),te=null,m=be,G=null,fe=null));let Me=fe?.data.session?.status,Tt=fe?.data.session,_e=Tt?.clientSecret||Ke?.nonce;if(G&&Tt?.buyerIdentified===!1&&_e&&(at=Bo(He,G,_e,L.account)),G&&fe&&Me==="complete"){if(rs(G))return{sid:G,result:fe};ni(q,O),G=null,fe=null,U=!0}}catch{ye.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ke?.canonicalIdentity===void 0?(ni(q,O),m=be):ti(q,O),G=null}if(!G){!be&&(U||!m)&&(m=(0,it.resolveIdempotencyKey)(),h=m),m&&oi(q,O,m);let Me=ye.now(),Tt=0;ye.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let _e={...L,idempotencyKey:m,avsCheck:!!we,avsConfig:typeof we=="object"?we:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ts(ge,V)};Object.defineProperty(_e,Yr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:F=>{Tt=Math.max(Tt,F)}}});let X=()=>{kc(ye,"session_create",Me,Tt)},me=F=>{Rc(ye,F,"session_create",Me,Tt)&&K({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,it.isDetachedSessionEligible)(_e)){let F=await He.createDetachedSession(_e);F.claimed.catch(()=>{}),fe=F.shell,G=F.sessionId,at=F.claim;let Qe=ye.now();ye.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ae=F.claimed.then(It=>{let qe=It.data.session?.id??F.sessionId;return qe&&ri(q,O,qe,It.data.session?.clientSecret??F.nonce),kc(ye,"session_claim",Qe),X(),It},It=>{throw ti(q,O),Rc(ye,It,"session_claim",Qe,0)&&K({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),It}).finally(()=>Ta(ye)),ae.catch(()=>{}),ht=!0,ye.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),ye.performance({stage:"session_shell",durationMs:ye.now()-Me,durationMode:"machine",requestCategory:"session_create",attempt:Tt,statusClass:"2xx",paymentMethodCategory:"card"})}else fe=await He.createAndFetchSession(_e),X()}catch(F){throw me(F),F}G=fe.data.session?.id??G??"",G&&!ae&&ri(q,O,G,fe.data.session?.clientSecret)}let D=fe?.data.session;return!at&&G&&D?.buyerIdentified===!1&&D.clientSecret&&(at=Bo(He,G,D.clientSecret,L.account)),{sid:G??"",result:fe,sdkGeneratedIdempotencyKey:h,...ae?{claimed:ae}:{},...at?{claim:at}:{},...Rt?{claimRequiresIdentity:!0}:{}}}finally{ht||Ta(ye)}}let cr=(0,k.useRef)(kr);ho(()=>{cr.current=kr},[kr]);let Jn=(0,k.useCallback)(async(L,q)=>{let O=wr.current;if(!O)throw new it.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ye=Ki(O,L),He=Vo(ye),ht=Nl(ye),be=vi.get(He);if(!be){let m={canonicalIdentity:He,promise:cr.current(ye,ht,He),consumers:0,settled:!1};be=m,vi.set(He,m);let h=()=>{m.settled=!0,wc(He,m)};m.promise.then(h,h)}be.consumers+=1;let Ke=!1,te=()=>{Ke||(Ke=!0,be.consumers-=1,wc(He,be))};q?.(te);try{let m=await be.promise;Ur.current=He,L&&(Yn(gn),sn(D=>Cl(D,L)));let{sid:h,result:U,claimed:G,claim:fe,claimRequiresIdentity:ae}=m;if(se.current=fe,ln(ae===!0),pt(U),U.data.session&&J(U.data.session),h&&Ze(h),G){Lt.current+=1;let D=Lt.current;Zt.current=G,rn(!0),G.then(Me=>{Lt.current===D&&(Zt.current===G&&(Zt.current=null),pt(Me),Me.data.session&&J(Me.data.session),rn(!1),ln(!1))},Me=>{Lt.current===D&&(Zt.current===G&&(Zt.current=null),rn(!1),ln(!1),Re(Me instanceof it.FloPayError?Me:new it.FloPayError(Me instanceof Error?Me.message:"Failed to create session","api_error")))})}else Lt.current+=1,Zt.current=null,rn(!1),ln(!1);let{flopay:at,paypalFlopay:Rt}=await _s(U,{billingApiUrl:ee,locale:i,telemetry:o});return Kt(at,Rt),Ye(!1),m}catch(m){throw Ur.current===He&&(Ur.current=null),m}finally{q||te()}},[gn,Kt,i,ee,o]),Zn=(0,k.useRef)(xn);Zn.current=xn;let Ft=(0,k.useRef)(Jn);Ft.current=Jn;let dr=(0,k.useCallback)(async L=>{if(!Ju(L)||Et)return{sessionId:We,session:v};St(!0);try{let q=await Jn(L);return{sessionId:q.sid,session:q.result.data.session??null}}finally{St(!1)}},[Jn,Et,We,v]),_n=(0,k.useCallback)(async L=>{let q=se.current;if(!q)return;let O=Lt.current,ye=await q(L);Lt.current===O&&(pt(ye),ye.data.session&&J(ye.data.session))},[]),Qn=(0,k.useCallback)(async()=>{await Zt.current},[]),Rr=(0,k.useCallback)(async()=>(await Qn(),{proceed:!0}),[Qn]);(0,k.useEffect)(()=>{let L=!1,q,O=++Ct.current;Xn(),Re(null),Un(0);let ye=()=>{L=!0,Ct.current===O&&(Ct.current+=1,Xn())},He=wr.current;if(Fn&&He)return kn(Mn),Ye(!1),Ur.current===Fn?ye:(J(Sl(He,j)),(async()=>{let Ke=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),te=Mn==="auto"&&!Ut.current&&!Ke;te&&(Dt(null),xt(null),nt("processing"));try{let m=await Ft.current(void 0,fe=>{q=fe}),h=m.result.data.session??null;pe.current=ls(m.result);let U=Is(m.result),G=rs(m.sid||h?.id);if(!L&&te&&h&&!U&&!G){Ut.current=!0,await Wu(Fn,m.sdkGeneratedIdempotencyKey,()=>Zn.current(h,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:m.result.autoProcessingError,initialAutoProcessingPending:m.result.autoProcessingPending,autoProcessingAttempted:m.result.autoProcessingAttempted,sessionId:m.sid||h.id}));return}!L&&te&&((U||G)&&(Ut.current=!0),nt(null),xt(null))}catch(m){if(L)return;let h=Wa(m);if(te&&h==="session_auto_completed"){Ut.current=!0,nt("success"),await Ea(600),L||(Xe(()=>{lt.current?.({status:"succeeded"})}),nt(null),xt(null));return}te&&(nt(null),xt(null));let U=m instanceof it.FloPayError?m:new it.FloPayError(m instanceof Error?m.message:"Failed to create session","api_error");Re(U)}finally{q?.(),q=void 0}})(),()=>{ye(),q?.()});Ye(!0);async function ht(){let Ke=!1,te=null;try{let m=new Yr.PaymentAPI(ee,{telemetry:!1}),h=await m.getUnifiedCheckoutSession(Se,t);if(te=h,L)return;pt(h);let U=h.data.session??null;if(J(U),!U)throw new it.FloPayError("No session data returned","api_error");let G=U.checkoutMode;if(G==="setup")throw new it.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(U.status==="authorized"){Ye(!1),Xe(()=>{lt.current?.(jr(U,Se)),yt.current?.(U.successUrl??"")});return}if(U.status==="complete"){Ye(!1),Xe(()=>{yt.current?.(U.successUrl??"")});return}if(U.status==="expired")throw $a(U);Ke=!0;let fe=j??G??"full";kn(fe),Lt.current+=1;let ae=U.clientSecret||t;se.current=U.buyerIdentified===!1&&ae?Bo(m,Se,ae,{...U.customer?.id?{userId:U.customer.id}:{}}):void 0,rn(!1),ln(!1);let at=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Rt=Is(h);if(fe==="auto"&&!Ut.current&&!at&&!Rt){Ut.current=!0;let D=be(h);try{if(await Zn.current(U,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>D,sessionId:Se||U.id}),L)return;await D,L||Ye(!1);return}catch{if(L)return;await D,L||Ye(!1);return}}await be(h),L||Ye(!1)}catch(m){if(L)return;let h=vl(m,Ke);if(Ke&&K({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),h){let{errorCode:G,stage:fe,...ae}=h;Rs(ee,o,B,G,fe,ae)}if(h?.stage==="provider_load"&&(j??te?.data.session?.checkoutMode??"full")==="full"&&bl(te,M,T)){let G=Ku({billingApiUrl:ee,locale:i,telemetry:o});gt.current=G,Kt(G,null),Un(1),Ye(!1);return}let U=m instanceof it.FloPayError&&h?.stage!=="provider_load"?m:Pl();U!==m&&Xe(()=>ie.current?.(U)),Re(U),Ye(!1)}}async function be(Ke){let{flopay:te,paypalFlopay:m,...h}=await _s(Ke,{billingApiUrl:ee,locale:i,telemetry:o});pe.current={publishableKey:h.publishableKey,paypalPublishableKey:h.paypalPublishableKey},Kt(te,m),Un(0)}return ht(),ye},[j,Fn,Mn,bt,t,M,T]);let ft=(0,k.useCallback)(async()=>{if(!tt||zn!==1)return;let L=Ct.current;Un(2);try{let{flopay:q,paypalFlopay:O}=await _s(tt,{billingApiUrl:ee,locale:i,telemetry:o});if(Ct.current!==L)return;Xn(),Kt(q,O),Un(0)}catch(q){if(Ct.current!==L)return;let{errorCode:O,stage:ye,...He}=Wi(q);Rs(ee,o,B,O,ye,He)}},[Xn,Kt,i,zn,ee,o,B,tt]),on=!!(Se&&(v?.clientSecret||t)),en=An||!on,qr=(0,k.useCallback)(async()=>{if(!(An||!on||!v)){Kn(!0),Dt(null);try{await xn(v,{attempt3DS:!0,fallbackToFull:!0,sessionId:Se||v.id})}finally{Kn(!1)}}},[Se,An,on,xn,v]),Vn=Tc(tt,ke),Jr=Is(tt),ur=(0,k.useMemo)(()=>{if(!(!tt||!v||!tt.data.stripe?.publishableKey))return{billingApiUrl:ee}},[tt,v,ee]),pr=!!(n&&!ge&&V==="buttons"&&xe&&Mn==="full"),hn=!!(Se&&(v?.vault?.html||Zr(v))),mr=(0,k.useMemo)(()=>({session:v,loading:Wt,error:Tn,checkoutMode:Mt,inlineSessionDraft:Qt,applyInlineSessionPatch:pr?dr:void 0,inlineSessionPatchProcessing:Et,claimPending:vn,claimRequiresIdentity:Ot,claimBuyerIdentity:_n,waitForDataAttachment:Qn}),[v,Wt,Tn,Mt,Qt,pr,dr,Et,vn,Ot,_n,Qn]),Vr=!!n&&V==="buttons"&&!Jr&&!hn&&(!Ae||!ur),En=mt?(0,N.jsx)(Ln,{status:mt,errorMessage:Rn,authorized:In}):null;if(Wt&&!hn){if(c)return(0,N.jsxs)(N.Fragment,{children:[c,En]});if(V==="buttons"){let L=Je?.buttonsLayout?.cardButton?.borderRadius??Je?.appearance.variables?.borderRadius??8,q=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:[M&&q(Yo),T&&(W||A)&&q(Yo),T&&q(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)(Qu,{onButtonClick:ut,showPayPal:M,showStripe:T,showApplePay:W,showGooglePay:A,theme:Y,buttonsTheme:le,buttonsStyles:H,cardButtonContent:Ne,cardBackButtonContent:je,cardTitleContent:oe})}),En]}):Jr&&v&&Vn?(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(Pr.Provider,{value:mr,children:(0,N.jsxs)("div",{className:ot,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)(Ll,{sessionId:Se,nonce:v.clientSecret||void 0,billingApiUrl:ee,email:v.customer?.email||Qt?.account?.email,billingName:[v.customer?.firstName,v.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:(v.currency??"usd").toUpperCase(),isSubscription:v.mode==="subscription",providerObjectType:Vn.providerObjectType,approvalPresentation:Vn.approvalPresentation,existingOrderId:Vn.existingOrderId,onComplete:u,onErrorChange:Dt,onDecline:R,onButtonClick:ut,runBeforeButtonClick:Rr,onInitializationStateChange:Xr,allowAutomaticRetry:Lr===0,session:v,telemetry:o,telemetryContext:B,onInstrument:Bt,debug:re},`${ue}:paypal-init-${Lr}`)})]})}),En]}):Mt==="confirm"?(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(Pr.Provider,{value:mr,children:(0,N.jsx)(Pa,{flopay:Ae,paypalFlopay:$,options:ur??{billingApiUrl:ee},onInstrument:Bt,children:(0,N.jsxs)("div",{className:ot,children:[mn&&(0,N.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:mn}),Q?Q({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...":Ee??"Confirm Purchase"})]})},ue)}),En]}):(!Ae||!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)(Pa,{flopay:Ae,paypalFlopay:$,options:ur??{billingApiUrl:ee},onInstrument:Bt,children:[zn===1&&(0,N.jsx)("button",{type:"button",onClick:ft,children:"Retry payment methods"}),ge?(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)(Zu,{sessionId:Se,nonce:v?.clientSecret||void 0,billingApiUrl:ee,session:v,submitLabel:$e,walletPresentation:b,children:ge})]}):(0,N.jsx)(hi,{sessionId:Se,nonce:v?.clientSecret||void 0,telemetry:o,email:v?.customer?.email||Qt?.account?.email,userId:v?.customer?.id||Qt?.account?.userId,firstName:v?.customer?.firstName||Qt?.account?.firstName,lastName:v?.customer?.lastName||Qt?.account?.lastName,totalAmount:v?Math.round((0,it.buildCheckoutDisplayData)(v).total*100):0,currency:v?.currency?.toLowerCase()??"usd",onComplete:u,onError:g,onDecline:R,error:mn,onErrorChange:Dt,showPayPal:M,showStripe:T,walletPresentation:b,enabledPaymentMethods:zn?[]:S??tt?.data.stripe?.enabledPaymentMethods??v?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:tt?.data.stripe?.enabledPaymentMethodCountries,showApplePay:W,showGooglePay:A,layout:V,theme:Y,buttonsTheme:le,buttonsStyles:H,appearance:st,cardButtonContent:Ne,cardBackButtonContent:je,cardTitleContent:oe,onButtonClick:ut,onBeforeButtonClick:xe,onBuyerIdentityReady:_n,enableAVS:we,...ve?{cardFieldOrder:ve}:{},...de?{cardPreFormSlot:de}:{},avsLayout:Te,country:v?.customer?.country,city:v?.customer?.city,state:v?.customer?.state,onCountryChange:E,onZipChange:w,avsCheck:!!we,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Ts(ge,V),className:ot,submitLabel:$e,directPaypal:Vn,isSubscription:v?.mode==="subscription",session:v,dataAttachmentPending:vn,dataAttachmentRequiresIdentity:Ot,debug:re})]},ue)}),En]})}function Zu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:a,children:i}){return(0,N.jsx)(N.Fragment,{children:k.default.Children.map(i,c=>{if(!k.default.isValidElement(c))return c;let p=c.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?c:k.default.cloneElement(c,u)})})}function Qu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:i,buttonsStyles:c,cardButtonContent:p,cardBackButtonContent:u,cardTitleContent:g}){let[P,R]=(0,k.useState)(!1),E=(0,k.useMemo)(()=>(0,it.resolveTheme)(a),[a]),w=(0,k.useMemo)(()=>{let S=E?.buttonsLayout??(0,it.resolveButtonsLayoutTheme)(i);return c?{...S,...c,cardButton:{...S.cardButton,...c.cardButton},cardFormContainer:{...S.cardFormContainer,...c.cardFormContainer},backButton:{...S.backButton,...c.backButton},backButtonIcon:{...S.backButtonIcon,...c.backButtonIcon},submitButton:{...S.submitButton,...c.submitButton},title:{...S.title,...c.title}}:S},[E,i,c]),M=E?.buttonsLayout?.cardButton?.borderRadius??E?.appearance.variables?.borderRadius??8,T=S=>(0,N.jsx)("div",{style:{height:S,borderRadius:M,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 S=w.cardInputBorder??"#e5e7eb",W=w.cardInputBackground??"white",A=Mo(u),re=Mo(g);return(0,N.jsxs)("div",{style:{backgroundColor:w.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...w.cardFormContainer},children:[(0,N.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,N.jsxs)("button",{type:"button",onClick:()=>R(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:A?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...w.backButton},children:[(0,N.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...w.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,...w.title},children:(0,N.jsx)(da,{content:g})})]}),(0,N.jsx)("div",{style:{backgroundColor:W,border:`1px solid ${S}`,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:W,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,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:W,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,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:W,border:`1px solid ${S}`,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",...w.submitButton,opacity:.5}}),(0,N.jsx)("style",{children:`
38
+ `}),da&&Hn&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:fe?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:$r,style:{display:"inline-flex",alignItems:"center",gap:Qi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:O.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...O.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",...O.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)(Oo,{content:ke})]}),Cl?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:O.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...O.title},children:(0,d.jsx)(fa,{content:Ie})})]}),!da&&!Cl&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:es,order:fe?-3:0,...O.title},children:(0,d.jsx)(fa,{content:Ie})}),fe&&Re&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:Re}),fe&&kn&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:Mo,border:`1px solid ${rr(Ha)}`,borderRadius:Yt,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:Wt,onChange:l=>{Ft("email"),Qt.current=l.target.value,sn(l.target.value)},onPointerDown:()=>Ft("email"),onKeyDown:()=>Ft("email"),onBlur:()=>{pr("email")&&On(!0),ko||$i()},disabled:K,required:!0,"aria-invalid":Ha||void 0,"aria-describedby":Ha?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...ts}})}),Ha&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:pa,children:Er.empty?"Email address is required":"Enter a valid email address"})]}),pe&&(0,d.jsx)("div",{style:{order:fe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let l=Mt,_=(me=!1)=>({backgroundColor:Mo,border:`1px solid ${rr(me)}`,borderRadius:Yt,marginTop:"0.5rem",padding:"10px"}),re=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ts}),He=(0,f.getStateOptions)(l);return(0,d.jsxs)(d.Fragment,{children:[(0,f.isAVSFieldVisible)(pe.address_line_1,l)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:_(qt("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:yn,onChange:me=>{Ft("line1"),Lt.current.addressLine1=!0,Cn.current=me.target.value,Dt(me.target.value)},onPointerDown:()=>Ft("line1"),onKeyDown:()=>Ft("line1"),onBlur:()=>Tn("line1"),disabled:K,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:re()})}),qt("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:pa,children:"Street address is required"})]}),(0,f.isAVSFieldVisible)(pe.address_line_2,l)&&(0,d.jsx)("div",{style:_(),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:mt,onChange:me=>{Lt.current.addressLine2=!0,on.current=me.target.value,rt(me.target.value)},disabled:K,"data-testid":"flopay-address-line2",style:re()})}),((0,f.isAVSFieldVisible)(pe.city,l)||(0,f.isAVSFieldVisible)(pe.state,l))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,f.isAVSFieldVisible)(pe.city,l)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Mo,borderTop:`1px solid ${rr(qt("city"))}`,borderRight:`1px solid ${rr(qt("city"))}`,borderBottom:`1px solid ${rr(qt("city"))}`,borderLeft:`1px solid ${rr(qt("city"))}`,padding:"10px",borderTopLeftRadius:Yt,borderBottomLeftRadius:Yt,...(0,f.isAVSFieldVisible)(pe.state,l)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Yt}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:_n,onChange:me=>{Ft("city"),Lt.current.city=!0,Ot.current=me.target.value,xt(me.target.value)},onPointerDown:()=>Ft("city"),onKeyDown:()=>Ft("city"),onBlur:()=>Tn("city"),disabled:K,required:!0,"aria-invalid":qt("city")||void 0,"aria-describedby":qt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:re()})}),(0,f.isAVSFieldVisible)(pe.state,l)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Mo,borderTop:`1px solid ${rr(qt("state"))}`,borderRight:`1px solid ${rr(qt("state"))}`,borderBottom:`1px solid ${rr(qt("state"))}`,borderLeft:`1px solid ${rr(qt("state"))}`,padding:"10px",borderTopRightRadius:Yt,borderBottomRightRadius:Yt,...(0,f.isAVSFieldVisible)(pe.city,l)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${rr(qt("state")||qt("city"))}`}:{borderRadius:Yt}},children:He?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:En,onChange:me=>{Ft("state"),Lt.current.state=!0,ln.current=me.target.value,fn(me.target.value)},onPointerDown:()=>Ft("state"),onKeyDown:()=>Ft("state"),onBlur:()=>Tn("state"),disabled:K,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:{...re(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,f.getStateLabel)(l)}),He.map(me=>(0,d.jsx)("option",{value:me.code,children:me.name},me.code))]}):(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,f.getStateLabel)(l),autoComplete:"billing address-level1",value:En,onChange:me=>{Ft("state"),Lt.current.state=!0,ln.current=me.target.value,fn(me.target.value)},onPointerDown:()=>Ft("state"),onKeyDown:()=>Ft("state"),onBlur:()=>Tn("state"),disabled:K,required:!0,"aria-invalid":qt("state")||void 0,"aria-describedby":qt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:re()})})]}),qt("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:pa,children:"City is required"}),qt("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:pa,children:[(0,f.getStateLabel)(l)," is required"]}),((0,f.isAVSFieldVisible)(pe.country,l)||(0,f.isAVSFieldVisible)(pe.postal_code,l))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:Ce==="column"?"column":"row",gap:Ce==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,f.isAVSFieldVisible)(pe.country,l)&&(0,d.jsx)("div",{style:{flex:Ce==="row"?1:void 0,backgroundColor:Mo,borderTop:`1px solid ${ua}`,borderRight:`1px solid ${ua}`,borderBottom:`1px solid ${ua}`,borderLeft:`1px solid ${ua}`,padding:"10px",...Ce==="row"&&(0,f.isAVSFieldVisible)(pe.postal_code,l)?{borderRadius:"0",borderTopLeftRadius:Yt,borderBottomLeftRadius:Yt,borderRight:"none"}:{borderRadius:Yt}},children:(0,d.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Mt,onChange:me=>{Lt.current.country=!0,wt.current=me.target.value,In(me.target.value),st?.(me.target.value),ln.current="",fn("")},disabled:K,autoComplete:"billing country","data-testid":"flopay-country",style:{...re(),cursor:"pointer"},children:[Mt===""?(0,d.jsx)("option",{value:"",children:"Select country"}):null,f.COUNTRY_OPTIONS.map(me=>(0,d.jsxs)("option",{value:me.code,children:[me.flag," ",me.name]},me.code))]})}),(0,f.isAVSFieldVisible)(pe.postal_code,l)&&(0,d.jsx)("div",{style:{flex:Ce==="row"?1:void 0,backgroundColor:Mo,border:`1px solid ${vd}`,padding:"10px",...Ce==="row"&&(0,f.isAVSFieldVisible)(pe.country,l)?{borderRadius:"0",borderTopRightRadius:Yt,borderBottomRightRadius:Yt}:{borderRadius:Yt}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,f.getPostalCodeLabel)(Mt),autoComplete:"billing postal-code",value:Fn,onChange:me=>{Ft("zip"),Lt.current.zip=!0,Et.current=me.target.value,Xn(me.target.value),Ne?.(me.target.value)},onPointerDown:()=>Ft("zip"),onKeyDown:()=>Ft("zip"),onBlur:()=>{pr("zip")&&Dn(!0)},disabled:K,required:hn.required,"aria-invalid":Wa||void 0,"aria-describedby":Wa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:re()})})]}),Wa&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:pa,children:hn.empty?`${(0,f.getPostalCodeLabel)(l)} is required`:Yu(l)})]})})()}),fe&&Rd,at&&(0,d.jsx)($o,{margin:"0.75rem 0",styleOverride:O.errorBanner,children:at})]}),Ka={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},Il=l=>Z?!C||!Ar?(0,d.jsx)("pre",{"data-testid":l,style:Ka,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":l,style:Ka,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${C}`,` directPaypalConfigured=${Ar}`,` inAppBrowserDetected=${String(Va)}`,` shouldRenderDirectPayPal=${aa}`,` shouldRenderStripePayPal=${sa}`,` hasPaypalStripeInstance=${!!Gs}`].join(`
39
+ `)}):null,_l=l=>Z?!H||!Wn?(0,d.jsx)("pre",{"data-testid":l,style:Ka,children:"FloPay/Stripe-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":l,style:Ka,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${H}`,` currency=${At}`,` amountInCents=${na}`,` enabledPaymentMethods: ${JSON.stringify(se??[])}`,` enabledPaymentMethodsProvided=${ra}`,` hasEnabledMethods=${Na}`,` expressMethods: ${JSON.stringify(Ua)}`,` walletExpressMethods: ${JSON.stringify(To)}`,` paymentElementMethods: ${JSON.stringify(oa)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(qa)}`,` hasStripeInstance=${!!Wn}`,` shouldRenderWallets=${Ao}`,` shouldRenderPaymentElement=${la}`].join(`
40
+ `)}):null,El=ht==="apm-expanding"||ht==="apm-form"||ht==="apm-collapsing",Fo;ht==="apm-expanding"?Fo=bc:ht==="apm-collapsing"&&(Fo=Pc);let Ga=tn?xc(Wi,tn):null;if(ne==="buttons"){let l=ht==="buttons"||ht==="expanding"||ht==="apm-expanding",_=ht==="expanding"||ht==="card"||ht==="collapsing",re=Ze===void 0?{boxSizing:"border-box",height:Xo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},He;ht==="expanding"||ht==="apm-expanding"?He=ju:(ht==="collapsing"||ht==="apm-collapsing")&&(He=$u);let me;return ht==="expanding"?me=bc:ht==="collapsing"&&(me=Pc),(0,d.jsxs)("form",{onSubmit:Xi,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Jo,{}),q&&(0,d.jsx)(Un,{status:q,errorMessage:at,authorized:jn}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!l&&!He?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!l&&!He?Wu:{},...He?{animation:He,pointerEvents:"none"}:{}},children:[Il("flopay-direct-paypal-gate-debug"),_l("flopay-stripe-gate-debug"),aa&&gt&&(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)(Pa.Provider,{value:b,children:(0,d.jsx)(Ca,{sessionId:e,nonce:t,billingApiUrl:Xe,email:B.email,billingName:et||void 0,onBuyerIdentityReady:ce,clientId:gt.clientId,environment:gt.environment,currency:At.toUpperCase(),isSubscription:St,providerObjectType:ie,approvalPresentation:$a==="popup"?void 0:$a,onTokenizedBody:Ln,onComplete:i,onErrorChange:$e,onDecline:p,onTechnicalFailure:_o,onButtonClick:ue,runBeforeButtonClick:hr,isProcessing:K,onLoadStateChange:Ki,onInitializationStateChange:Gi,session:De,existingOrderId:m?.orderId,debug:Z},m?.orderId??"fresh")})]}),sa&&(0,d.jsx)(Jt.Elements,{stripe:ia,options:Js,children:(0,d.jsx)(Sc,{sessionId:e,nonce:t,email:B.email,billingName:et||void 0,onBuyerIdentityReady:ce,billingApiUrl:Xe,onTokenizedBody:Ln,onErrorChange:$e,isProcessing:K,onButtonClick:ue,onDecline:p,onTechnicalFailure:_o,runBeforeButtonClick:hr,onLoadStateChange:ol,placeholderBorderRadius:mo,popupCapabilityOwner:b,externalTelemetryContext:ml,presentationMode:Eo})}),Ao?(0,d.jsx)(Jt.Elements,{stripe:Wn,options:Xs,children:(0,d.jsx)(kc,{sessionId:e,nonce:t,email:B.email,billingName:et||void 0,onBuyerIdentityReady:ce,billingApiUrl:Xe,intentKind:Be>0?"payment":"setup",expressMethods:To,onTokenizedBody:Ln,onErrorChange:$e,onButtonClick:ue,onDecline:p,onTechnicalFailure:_o,runBeforeButtonClick:hr,onLoadStateChange:il,placeholderBorderRadius:mo,popupCapabilityOwner:b,externalTelemetryContext:M})}):null,!Ao&&ul?(0,d.jsx)("div",{style:{height:Xo,borderRadius:mo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,la&&(0,d.jsx)(Rc,{sessionId:e,nonce:t,email:B.email,billingName:[B.firstName,B.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ce,billingApiUrl:Xe,paymentElementMethods:qa,stripeInstance:Wn,paymentElementBaseOptions:Wi,onTokenizedBody:Ln,onErrorChange:$e,onButtonClick:ue,onDecline:p,runBeforeButtonClick:hr,onLoadStateChange:ll,isProcessing:K,submitButtonColor:yo,submitButtonBorderRadius:Yt,submitButtonStyle:O.submitButton,onExpandApm:An,expandedApmMethod:tn,themeId:Ee,buttonAppearance:{backgroundColor:O.cardButton?.backgroundColor,borderColor:O.cardInputBorder,textColor:O.cardButton?.color,borderRadius:mo}}),fe&&(0,d.jsx)("button",{type:"button",onClick:async()=>{K||!(await hr("card")).proceed||(ue?.("card"),fr())},disabled:K,style:{width:"100%",...re,...O.cardButton,...Ns({themeBundle:Rt,resolvedPrimaryColor:yo,resolvedBorderRadius:Yt,submitButtonStyle:O.submitButton,explicitPrimaryColor:Nn?.colorPrimary}),fontSize:O.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:Ue=>{!K&&(Rt||Nn?.colorPrimary)&&(Ue.currentTarget.style.backgroundColor=wd)},onMouseLeave:Ue=>{(Rt||Nn?.colorPrimary)&&(Ue.currentTarget.style.backgroundColor=yo)},onMouseDown:Ue=>{Ue.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ue=>{Ue.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(Do,{content:Ze})}),at&&ht==="buttons"&&(0,d.jsx)($o,{margin:"0.25rem 0",styleOverride:O.errorBanner,children:at})]}),fe&&_&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...me?{animation:me}:{},...ht==="collapsing"?{pointerEvents:"none"}:{}},children:Rl}),H&&El&&tn&&Ga&&Wn&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Fo?{animation:Fo}:{},...ht==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Zi,borderRadius:rs,...ma,padding:ns},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:N,style:{display:"inline-flex",alignItems:"center",gap:Qi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:O.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...O.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",...O.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)(Oo,{content:ke})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:O.titleFontSize??"1.05rem",color:es,paddingRight:80,...O.title},children:`Pay with ${(0,f.getStripeMethodDisplayName)(tn)}`})]}),(0,d.jsx)(Jt.Elements,{stripe:Wn,options:Ga,children:(0,d.jsx)(Fs,{method:tn,sessionId:e,nonce:t,email:B.email,billingName:[B.firstName,B.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ce,billingApiUrl:Xe,onTokenizedBody:Ln,onErrorChange:$e,onDecline:p,onCancel:N,runBeforeButtonClick:hr,onButtonClick:ue,isProcessing:K,submitButtonColor:yo,submitButtonBorderRadius:Yt,submitButtonStyle:O.submitButton,errorText:at})},tn)]})})]})]})}return El&&tn&&Ga&&Wn&&H?(0,d.jsxs)("form",{onSubmit:Xi,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Jo,{}),q&&(0,d.jsx)(Un,{status:q,errorMessage:at,authorized:jn}),(0,d.jsx)("div",{style:{...Fo?{animation:Fo}:{},...ht==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Zi,borderRadius:rs,...ma,padding:ns},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:N,style:{display:"inline-flex",alignItems:"center",gap:Qi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:O.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...O.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",...O.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)(Oo,{content:ke})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:O.titleFontSize??"1.05rem",color:es,paddingRight:80,...O.title},children:`Pay with ${(0,f.getStripeMethodDisplayName)(tn)}`})]}),(0,d.jsx)(Jt.Elements,{stripe:Wn,options:Ga,children:(0,d.jsx)(Fs,{method:tn,sessionId:e,nonce:t,email:B.email,billingName:[B.firstName,B.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ce,billingApiUrl:Xe,onTokenizedBody:Ln,onErrorChange:$e,onDecline:p,onCancel:N,runBeforeButtonClick:hr,onButtonClick:ue,isProcessing:K,submitButtonColor:yo,submitButtonBorderRadius:Yt,submitButtonStyle:O.submitButton,errorText:at})},tn)]})})]}):(0,d.jsxs)("form",{onSubmit:Xi,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Jo,{}),q&&(0,d.jsx)(Un,{status:q,errorMessage:at,authorized:jn}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Il("flopay-direct-paypal-gate-debug-default"),_l("flopay-stripe-gate-debug-default"),aa&&gt&&(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)(Pa.Provider,{value:b,children:(0,d.jsx)(Ca,{sessionId:e,nonce:t,billingApiUrl:Xe,email:B.email,billingName:et||void 0,onBuyerIdentityReady:ce,clientId:gt.clientId,environment:gt.environment,currency:At.toUpperCase(),isSubscription:St,providerObjectType:ie,approvalPresentation:$a==="popup"?void 0:$a,onTokenizedBody:Ln,onComplete:i,onErrorChange:$e,onDecline:p,onTechnicalFailure:_o,onButtonClick:ue,runBeforeButtonClick:hr,isProcessing:K,onLoadStateChange:Ki,onInitializationStateChange:Gi,session:De,existingOrderId:m?.orderId,debug:Z},m?.orderId??"fresh")})]}),sa&&(0,d.jsx)(Jt.Elements,{stripe:ia,options:Js,children:(0,d.jsx)(Sc,{sessionId:e,nonce:t,email:B.email,billingName:et||void 0,onBuyerIdentityReady:ce,billingApiUrl:Xe,onTokenizedBody:Ln,onErrorChange:$e,isProcessing:K,onButtonClick:ue,onDecline:p,onTechnicalFailure:_o,runBeforeButtonClick:hr,onLoadStateChange:ol,placeholderBorderRadius:mo,popupCapabilityOwner:b,externalTelemetryContext:ml,presentationMode:Eo})}),Ao&&(0,d.jsx)(Jt.Elements,{stripe:Wn,options:Xs,children:(0,d.jsx)(kc,{sessionId:e,nonce:t,email:B.email,billingName:et||void 0,onBuyerIdentityReady:ce,billingApiUrl:Xe,intentKind:Be>0?"payment":"setup",expressMethods:To,onTokenizedBody:Ln,onErrorChange:$e,onButtonClick:ue,onDecline:p,onTechnicalFailure:_o,runBeforeButtonClick:hr,onLoadStateChange:il,placeholderBorderRadius:mo,popupCapabilityOwner:b,externalTelemetryContext:M})}),la&&(0,d.jsx)(Rc,{sessionId:e,nonce:t,email:B.email,billingName:[B.firstName,B.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Xe,paymentElementMethods:qa,stripeInstance:Wn,paymentElementBaseOptions:Wi,onTokenizedBody:Ln,onErrorChange:$e,onButtonClick:ue,onDecline:p,runBeforeButtonClick:hr,onLoadStateChange:ll,isProcessing:K,submitButtonColor:yo,submitButtonBorderRadius:Yt,submitButtonStyle:O.submitButton,themeId:Ee,onExpandApm:An,expandedApmMethod:tn,buttonAppearance:{backgroundColor:O.cardButton?.backgroundColor,borderColor:O.cardInputBorder,textColor:O.cardButton?.color,borderRadius:mo}})]}),fe&&(gd||fd||hd)&&(0,d.jsx)(Si,{label:"or pay with card"}),fe&&Rl]})}var z=require("react/jsx-runtime"),ea=44,js="flopay_checkout_saved_payment_resume",xi=new Map,Ai=new Map;function Fc(e,t){t.settled&&t.consumers===0&&xi.get(e)===t&&xi.delete(e)}function ep(e,t,n){let r=Ai.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Ai.set(e,a);let i=()=>{Ai.get(e)===a&&Ai.delete(e)};return o.then(i,i),o}function Ba(e){return new Promise(t=>setTimeout(t,e))}function Mi(e,t,n){let r=ri({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:it.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Da(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function zs(e,t,n,r,o,a){let i=Mi(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),Da(i)}function Bc(e,t,n,r){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function Dc(e,t,n,r,o){let a=(0,it.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 it.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof it.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 zc(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 Us(e){return!e||e.data.stripe?.publishableKey?!1:!!zc(e)?.clientId}var tp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function np(e){return new Jr.FloPay(tp,{publishableKey:"provider_unavailable",...e})}async function qs(e,t){let{publishableKey:n,paypalPublishableKey:r}=Ss(e);return{...await ws({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Hs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function rp(){if(!Hs())return null;try{let e=window.sessionStorage.getItem(js);return e?JSON.parse(e):null}catch{return null}}function Oc(e){if(Hs())try{window.sessionStorage.setItem(js,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Vs(){if(Hs())try{window.sessionStorage.removeItem(js)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function op(){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 Lc(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 $s(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function ap(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Nc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function ip(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 Fi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:i,loading:c,error:p,onComplete:u,onError:h,onInstrument:v,onDecline:E,onCountryChange:T,onZipChange:w,showPayPal:x=!0,showStripe:A=!0,walletPresentation:P="auto",enabledPaymentMethods:C,showApplePay:H=!0,showGooglePay:I=!0,debug:se=!1,layout:j,theme:ee,buttonsTheme:we,buttonsStyles:ne,cardButtonContent:Ee,cardBackButtonContent:We,cardTitleContent:oe,showSecurityFooter:xe,onButtonClick:Ze,onBeforeButtonClick:ke,enableAVS:Ie,cardFieldOrder:ge,cardPreFormSlot:ue,avsLayout:ae,submitLabel:be,className:_e,initialErrorMessage:R=null,initialPayPalOrderId:Re,children:Ce,checkoutMode:V,confirmLabel:Fe,renderConfirmButton:X,onSessionCompleted:Le}){let Q=(0,it.resolveBillingApiUrl)(r),Ke=(0,k.useMemo)(()=>(0,it.resolveTheme)(ee),[ee]),st=a??Ke?.appearance,Ne=n?"embedded_checkout":"standard_checkout",tt=$s(Ce,j),[nt,pt]=(0,k.useState)(null),[Be,At]=(0,k.useState)(null),Bt=(0,k.useRef)(null),gt=(0,k.useRef)(null),St=(0,k.useRef)(0),[$,ye]=(0,k.useState)(null),Qe=(0,k.useRef)(null),[Z,ze]=(0,k.useState)(null),ft=(0,k.useMemo)(()=>n?Ho(n):"",[n]),Ve=n?`create:${ft}`:`session:${e??""}`,vt=Nc(Z),G=(0,k.useRef)(new Set),b=(0,k.useRef)(Ve),S=(0,k.useRef)(Ve);Po(()=>{S.current=Ve,b.current!==Ve&&(b.current=Ve,G.current.clear())},[Ve]);let Y=(0,k.useCallback)(N=>{if(S.current===Ve){if(ps.has(N.name)){if(G.current.has(N.name))return;G.current.add(N.name)}Je(()=>v?.(N))}},[Ve,v]),y=Vo(Y,Ve),M=(0,k.useRef)(!1),De=(0,k.useCallback)(N=>{if(M.current)return;let q=N.gateway||!vt?N:{...N,gateway:vt};Y(q)},[Y,vt]);(0,k.useEffect)(()=>{y({class:"lifecycle",name:"checkout.mount"})},[y]);let[ie,J]=(0,k.useState)(e??""),le=e??ie,lt=n?"":le,[Ht,Xe]=(0,k.useState)(!0),[xn,Te]=(0,k.useState)(null),[Vn,$n]=(0,k.useState)(0),[Mt,In]=(0,k.useState)("full"),[Fn,Xn]=(0,k.useState)(!1),[yn,Dt]=(0,k.useState)(R),[mt,rt]=(0,k.useState)(null),[_n,xt]=(0,k.useState)(null),[En,fn]=(0,k.useState)(!1),[Wt,sn]=(0,k.useState)(void 0),[Jn,Zn]=(0,k.useState)(""),[Et,wt]=(0,k.useState)(!1),[Cn,on]=(0,k.useState)(!1),[Ot,ln]=(0,k.useState)(!1),Qt=(0,k.useRef)(null),Lt=(0,k.useRef)(0),pe=(0,k.useRef)(void 0),[cn,jn]=(0,k.useState)("loading"),[Nr,cr]=(0,k.useState)(0),Ut=(0,k.useRef)(!1),dr=(0,k.useRef)(!1),Sn=(0,k.useRef)(!1),Ae=(0,k.useRef)(null),fe=(0,k.useRef)(null),D=(0,k.useMemo)(()=>({checkoutMode:V??Mt,layout:ap(Ce,j)}),[V,Ce,Mt,j]),ct=(0,k.useRef)(u);ct.current=u;let de=(0,k.useRef)(h);de.current=h;let wn=(0,k.useRef)(E);wn.current=E;let gn=(0,k.useCallback)(N=>pi(Ae,async q=>{try{return await N(q)}catch(L){throw q.aborted?co(L):L}}),[]);(0,k.useEffect)(()=>()=>{Ae.current?.abort(),Ae.current=null},[]);let Kt=(0,k.useCallback)((N,q)=>{Bt.current=N,At(N),Qe.current=q,ye(q)},[]),Qn=(0,k.useCallback)(()=>{let N=gt.current;N&&(gt.current=null,N.destroy())},[]);(0,k.useEffect)(()=>{pn(Be)?.setCheckoutContext(D),$&&$!==Be&&pn($)?.setCheckoutContext(D)},[Be,$,D]);let yt=(0,k.useRef)(Le);yt.current=Le;let Qr=(0,k.useCallback)(N=>{jn(N),!(N!=="exhausted"||Sn.current)&&(Sn.current=!0,de.current?.(new it.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Gt=(0,k.useCallback)(()=>{jn("retrying"),cr(N=>N+1)},[]);(0,k.useEffect)(()=>{jn("loading"),cr(0),Sn.current=!1},[le]),(0,k.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:it.SDK_VERSION,checkout_type:Ne,checkout_layout:tt,billing_api_url:Q})},[tt,Ne,Q]);let hn=(0,k.useMemo)(()=>n?Ho(n,!0):"",[n]),zr=(0,k.useMemo)(()=>Jn===hn?Wt:void 0,[Wt,Jn,hn]),Ur=(0,k.useMemo)(()=>n?ss(n,zr):void 0,[n,zr]),Bn=V??Ur?.checkoutMode??"full",en=(0,k.useMemo)(()=>Ur?{...Ur,checkoutMode:Bn}:void 0,[Ur,Bn]);(0,k.useEffect)(()=>{sn(void 0),Zn(hn),pe.current=void 0,Qt.current=null,ln(!1)},[hn]),(0,k.useEffect)(()=>{Dt(R)},[R]);let kr=(0,k.useCallback)((N,q,L)=>{Je(()=>{wn.current?.(un(N,q,L))})},[]),Dn=(0,k.useCallback)(async(N,q)=>{Dt(null),xt(null),fn(!1),rt("processing");let L=q?.sessionId??N.id,Pe=N.clientSecret||t,Ge=Nc(N),bt=Bt.current??Qe.current,Se=pn(bt),Ye=bt?null:Mi(Q,o,D),te={log:O=>{Se?Se.log(O):Ye?.log(O)},error:O=>{Se?Se.error(O):Ye?.error(O)},terminal:O=>{Se?Se.terminal(O):Ye?.terminal(O)},performance:O=>{Se?Se.performance(O):Ye?.performance(O)},now:()=>Se?.now()??Ye?.now()??0,elapsed:O=>Se?.elapsed(O)??Math.max(0,(Ye?.now()??O)-O)},m=te.now(),g=!!(q?.initialAutoProcessingError||q?.initialAutoProcessingPending),U=!1,W,ve=()=>{U||(U=!0,g=!0,W=te.now(),te.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ce=!1,at=()=>{ce||(ce=!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"}),W!==void 0&&te.performance({stage:"recovery",durationMs:te.elapsed(W),durationMode:"machine",paymentMethodCategory:"saved"}))};te.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),M.current=!0;try{te.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{M.current=!1}y({class:"lifecycle",name:"payment.processing.started",provider:Ge}),g&&ve();let Rt;try{let O=nc(q?.initialAutoProcessingError),Oe=q?.initialAutoProcessingError?.type==="3ds_required"&&!q.initialAutoProcessingError.threeDSecureToken&&q.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:q.initialAutoProcessingError.nextActionRedirectUrl}:null,Tt,Me=K=>(ve(),gn(he=>Ko(K,{billingApiUrl:Q,sessionId:L,nonce:Pe,session:N,signal:he})));if(Oe)Tt=await Me(Oe);else if(O)ve(),O.type==="paypal_redirect_required"&&fe.current?.publishableKey&&Oc({sessionId:L,publishableKey:fe.current.publishableKey,paypalPublishableKey:fe.current.paypalPublishableKey}),Tt=await gn(K=>yi(O,{flopay:Bt.current,paypalFlopay:Qe.current,attempt3DS:q?.attempt3DS,billingApiUrl:Q,sessionId:L,session:N,telemetry:!1,signal:K})),O.type==="paypal_redirect_required"&&Vs();else if(q?.initialAutoProcessingPending){let K=q.initialAutoProcessingPending,he=new Jr.PaymentAPI(Q,{telemetry:!1}),B=await gn(je=>he.waitForCheckoutSessionCompletion(K.sessionId,{initialDelayMs:K.retryAfterMs,nonce:Pe,statusUrl:K.statusUrl,signal:je})),et=oo(B,N),It=B.autoProcessingError?.type==="3ds_required"&&B.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:B.autoProcessingError.nextActionRedirectUrl}:null;if(It)Tt=await Me(It);else{if(!Hr(et))throw No(et);Tt=jr(et,L)}}else{if(q?.initialAutoProcessingError)throw Br(q.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:q.initialAutoProcessingError.checkoutMethod});if(q?.fromCreateSession)return q?.fallbackToFull&&(In("full"),Lc("full")),!1;{let K=await Go({billingApiUrl:Q,sessionId:L,session:N,nonce:Pe,telemetry:!1});K.type==="success"?Tt=K.result:K.type==="next_action_required"?Tt=await Me(K):(ve(),K.type==="paypal_redirect_required"&&fe.current?.publishableKey&&Oc({sessionId:L,publishableKey:fe.current.publishableKey,paypalPublishableKey:fe.current.paypalPublishableKey}),Tt=await gn(he=>yi(K,{flopay:Bt.current,paypalFlopay:Qe.current,attempt3DS:q?.attempt3DS,billingApiUrl:Q,sessionId:L,session:N,telemetry:!1,signal:he})),K.type==="paypal_redirect_required"&&Vs())}}L&&Wo(L),at(),g&&(te.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),te.terminal({outcome:Tt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),fn(Tt.status==="authorized"),rt("success"),await Ba(600),Rt=()=>ct.current?.(Tt)}catch(O){let Oe=no(Ia(O),L);if(Oe.code==="three_ds_aborted")return!1;let Tt=Oe.checkoutMethod??Ra;Dt(Oe.message),xt(Oe.message),fn(!1),q?.fallbackToFull&&(te.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),In("full"),Lc("full")),at();let Me=Oe.statusCode===void 0?void 0:(0,it.telemetryStatusClass)(Oe.statusCode,"unknown"),K=Me==="4xx"?{requestCategory:"process_payment",statusClass:Me}:{},he=Me===void 0||Me==="4xx";if(he&&(Oe.telemetryOutcome==="payment_declined"||!!(Oe.declineCode||Oe.code?.toLowerCase().includes("declin"))))te.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...K});else if(he&&(Oe.telemetryOutcome==="validation_rejected"||Oe.type==="validation_error"))te.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...K});else{let It=(0,it.classifyTelemetryFailure)(O,g?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),je=Oe.telemetryRequestCategory??"process_payment";M.current=!0;try{te.error({...It,...Oe.telemetryFailureCategory?{failureCategory:Oe.telemetryFailureCategory}:{},stage:g?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:je})}finally{M.current=!1}y({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:je,provider:Ge})}return Je(()=>de.current?.(Oe)),kr(Tt,Oe,{code:Oe.code,declineCode:Oe.declineCode}),rt("error"),await Promise.allSettled([Ba(400),q?.ensureProvidersReady?q.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{at(),Ye&&Da(Ye),rt(null),xt(null)}return Je(Rt),!0},[kr,y,t,Q,gn,o,D]);(0,k.useEffect)(()=>{if(typeof window>"u"||dr.current)return;let N=new URLSearchParams(window.location.search),q=N.get("payment_intent_client_secret");if(!q)return;let L=rp();L&&(dr.current=!0,(async()=>{let Pe,Ge=0;Dt(null),xt(null),rt("processing"),Xn(!0);try{if(N.get("redirect_status")==="failed")throw Object.assign(new it.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:bt,paypalFlopay:Se}=await ws({publishableKey:L.publishableKey,paypalPublishableKey:L.paypalPublishableKey,billingApiUrl:Q,locale:i,telemetry:o});Pe=pn(Se??bt),Pe?.setCheckoutContext(D),Ge=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 Ye=(Se??bt)?.getRawProvider();if(!Ye)throw Object.assign(new it.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:te,error:m}=await Ye.retrievePaymentIntent(q);if(m)throw Object.assign(new it.FloPayError(m.message??"Failed to retrieve PayPal payment status.","api_error",{code:m.code}),{checkoutMethod:"paypal"});let g=Ll(te?.status);if(!te||g==="failed")throw Object.assign(new it.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let U=typeof te.payment_method=="string"?te.payment_method:te.payment_method?.id,W=g;if(L.sessionId){let at=(await new Jr.PaymentAPI(Q,{telemetry:!1}).getUnifiedCheckoutSession(L.sessionId)).data.session;if(at&&at.status!=="complete"){let Rt=await Go({billingApiUrl:Q,sessionId:L.sessionId,session:at,telemetry:!1,tokenizedData:{id:U??te.id,type:"card",threeDSecureActionResultTokenId:te.id,isPaypal:!0}});if(Rt.type!=="success")throw Object.assign(new it.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});W=Rt.result.status}}L.sessionId&&Wo(L.sessionId),Pe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.performance({stage:"redirect_resume",durationMs:Pe.elapsed(Ge),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),rt("success"),await Ba(600),Je(()=>ct.current?.({status:W,paymentIntentId:te.id,paymentMethodId:U,checkoutMethod:"paypal"}))}catch(bt){let Se=no(Ia(bt),L.sessionId),Ye=Se.checkoutMethod??"paypal",te=!!(Se.declineCode||Se.code?.toLowerCase().includes("declin"));if(Pe)Pe.performance({stage:"redirect_resume",durationMs:Pe.elapsed(Ge),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),te?Pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Pe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(te){let m=Mi(Q,o,D);m.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Da(m)}else zs(Q,o,D,"REDIRECT_RESUME_FAILED","redirect_resume");Dt(Se.message),xt(Se.message),Je(()=>de.current?.(Se)),kr(Ye,Se,{code:Se.code,declineCode:Se.declineCode}),rt("error"),await Ba(400)}finally{Vs(),op(),rt(null),xt(null),Xn(!1)}})())},[kr,i,Q,o,D]);let qr=(0,k.useRef)(null),On=(0,k.useMemo)(()=>en?Ho(en):"",[en]),Rr=(0,k.useRef)(en);Rr.current=en,(0,k.useEffect)(()=>{J(e??"")},[e]),(0,k.useEffect)(()=>{Ut.current=!1,Dt(R),xt(null),fn(!1),rt(null)},[On,R,e]);async function Ir(N,q,L){let Pe=Mi(Q,o,D),Ge=new Jr.PaymentAPI(Q,{telemetry:!1}),bt=!1;try{let Se=N.idempotencyKey===void 0?void 0:(0,it.resolveIdempotencyKey)(N.idempotencyKey),Ye=fs(q,L),te=gs(q,L);Ye?.canonicalIdentity===L&&te&&te.canonicalIdentity===void 0&&(di(q,L,te.idempotencyKey),te={...te,canonicalIdentity:L});let m=Se??(te?.canonicalIdentity===L?te.idempotencyKey:void 0),g,U=!1;Pe.log({name:Ye?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let W=Ye?.sid??null,ve=null,ce,at,Rt=!1;if(W)try{ve=await Ge.getUnifiedCheckoutSession(W,Ye?.nonce),Ye&&Ye.canonicalIdentity===void 0&&(Zl(ve.data.session,N)?(ci(q,L,W,Ye.nonce??ve.data.session?.clientSecret),te&&te.canonicalIdentity===void 0&&(di(q,L,te.idempotencyKey),m??(m=te.idempotencyKey))):(li(q,L),te=null,m=Se,W=null,ve=null));let Oe=ve?.data.session?.status,Tt=ve?.data.session,Me=Tt?.clientSecret||Ye?.nonce;if(W&&Tt?.buyerIdentified===!1&&Me&&(at=Lo(Ge,W,Me,N.account)),W&&ve&&Oe==="complete"){if(hs(W))return{sid:W,result:ve};li(q,L),W=null,ve=null,U=!0}}catch{Pe.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ye?.canonicalIdentity===void 0?(li(q,L),m=Se):si(q,L),W=null}if(!W){!Se&&(U||!m)&&(m=(0,it.resolveIdempotencyKey)(),g=m),m&&di(q,L,m);let Oe=Pe.now(),Tt=0;Pe.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Me={...N,idempotencyKey:m,avsCheck:!!Ie,avsConfig:typeof Ie=="object"?Ie:void 0,checkoutType:"embedded_checkout",checkoutLayout:$s(Ce,j)};Object.defineProperty(Me,Jr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:B=>{Tt=Math.max(Tt,B)}}});let K=()=>{Bc(Pe,"session_create",Oe,Tt)},he=B=>{Dc(Pe,B,"session_create",Oe,Tt)&&y({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,it.isDetachedSessionEligible)(Me)){let B=await Ge.createDetachedSession(Me);B.claimed.catch(()=>{}),ve=B.shell,W=B.sessionId,at=B.claim;let et=Pe.now();Pe.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ce=B.claimed.then(It=>{let je=It.data.session?.id??B.sessionId;return je&&ci(q,L,je,It.data.session?.clientSecret??B.nonce),Bc(Pe,"session_claim",et),K(),It},It=>{throw si(q,L),Dc(Pe,It,"session_claim",et,0)&&y({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),It}).finally(()=>Da(Pe)),ce.catch(()=>{}),bt=!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()-Oe,durationMode:"machine",requestCategory:"session_create",attempt:Tt,statusClass:"2xx",paymentMethodCategory:"card"})}else ve=await Ge.createAndFetchSession(Me),K()}catch(B){throw he(B),B}W=ve.data.session?.id??W??"",W&&!ce&&ci(q,L,W,ve.data.session?.clientSecret)}let O=ve?.data.session;return!at&&W&&O?.buyerIdentified===!1&&O.clientSecret&&(at=Lo(Ge,W,O.clientSecret,N.account)),{sid:W??"",result:ve,sdkGeneratedIdempotencyKey:g,...ce?{claimed:ce}:{},...at?{claim:at}:{},...Rt?{claimRequiresIdentity:!0}:{}}}finally{bt||Da(Pe)}}let ur=(0,k.useRef)(Ir);Po(()=>{ur.current=Ir},[Ir]);let er=(0,k.useCallback)(async(N,q)=>{let L=Rr.current;if(!L)throw new it.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Pe=ss(L,N),Ge=Ho(Pe),bt=Jl(Pe),Se=xi.get(Ge);if(!Se){let m={canonicalIdentity:Ge,promise:ur.current(Pe,bt,Ge),consumers:0,settled:!1};Se=m,xi.set(Ge,m);let g=()=>{m.settled=!0,Fc(Ge,m)};m.promise.then(g,g)}Se.consumers+=1;let Ye=!1,te=()=>{Ye||(Ye=!0,Se.consumers-=1,Fc(Ge,Se))};q?.(te);try{let m=await Se.promise;qr.current=Ge,N&&(Zn(hn),sn(O=>Bl(O,N)));let{sid:g,result:U,claimed:W,claim:ve,claimRequiresIdentity:ce}=m;if(pe.current=ve,ln(ce===!0),pt(U),U.data.session&&ze(U.data.session),g&&J(g),W){Lt.current+=1;let O=Lt.current;Qt.current=W,on(!0),W.then(Oe=>{Lt.current===O&&(Qt.current===W&&(Qt.current=null),pt(Oe),Oe.data.session&&ze(Oe.data.session),on(!1),ln(!1))},Oe=>{Lt.current===O&&(Qt.current===W&&(Qt.current=null),on(!1),ln(!1),Te(Oe instanceof it.FloPayError?Oe:new it.FloPayError(Oe instanceof Error?Oe.message:"Failed to create session","api_error")))})}else Lt.current+=1,Qt.current=null,on(!1),ln(!1);let{flopay:at,paypalFlopay:Rt}=await qs(U,{billingApiUrl:Q,locale:i,telemetry:o});return Kt(at,Rt),Xe(!1),m}catch(m){throw qr.current===Ge&&(qr.current=null),m}finally{q||te()}},[hn,Kt,i,Q,o]),tr=(0,k.useRef)(Dn);tr.current=Dn;let Ft=(0,k.useRef)(er);Ft.current=er;let pr=(0,k.useCallback)(async N=>{if(!ip(N)||Et)return{sessionId:ie,session:Z};wt(!0);try{let q=await er(N);return{sessionId:q.sid,session:q.result.data.session??null}}finally{wt(!1)}},[er,Et,ie,Z]),Tn=(0,k.useCallback)(async N=>{let q=pe.current;if(!q)return;let L=Lt.current,Pe=await q(N);Lt.current===L&&(pt(Pe),Pe.data.session&&ze(Pe.data.session))},[]),nr=(0,k.useCallback)(async()=>{await Qt.current},[]),_r=(0,k.useCallback)(async()=>(await nr(),{proceed:!0}),[nr]);(0,k.useEffect)(()=>{let N=!1,q,L=++St.current;Qn(),Te(null),$n(0);let Pe=()=>{N=!0,St.current===L&&(St.current+=1,Qn())},Ge=Rr.current;if(On&&Ge)return In(Bn),Xe(!1),qr.current===On?Pe:(ze(Dl(Ge,V)),(async()=>{let Ye=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),te=Bn==="auto"&&!Ut.current&&!Ye;te&&(Dt(null),xt(null),rt("processing"));try{let m=await Ft.current(void 0,ve=>{q=ve}),g=m.result.data.session??null;fe.current=Ss(m.result);let U=Us(m.result),W=hs(m.sid||g?.id);if(!N&&te&&g&&!U&&!W){Ut.current=!0,await ep(On,m.sdkGeneratedIdempotencyKey,()=>tr.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}!N&&te&&((U||W)&&(Ut.current=!0),rt(null),xt(null))}catch(m){if(N)return;let g=Ja(m);if(te&&g==="session_auto_completed"){Ut.current=!0,rt("success"),await Ba(600),N||(Je(()=>{ct.current?.({status:"succeeded"})}),rt(null),xt(null));return}te&&(rt(null),xt(null));let U=m instanceof it.FloPayError?m:new it.FloPayError(m instanceof Error?m.message:"Failed to create session","api_error");Te(U)}finally{q?.(),q=void 0}})(),()=>{Pe(),q?.()});Xe(!0);async function bt(){let Ye=!1,te=null;try{let m=new Jr.PaymentAPI(Q,{telemetry:!1}),g=await m.getUnifiedCheckoutSession(le,t);if(te=g,N)return;pt(g);let U=g.data.session??null;if(ze(U),!U)throw new it.FloPayError("No session data returned","api_error");let W=U.checkoutMode;if(W==="setup")throw new it.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(U.status==="authorized"){Xe(!1),Je(()=>{ct.current?.(jr(U,le)),yt.current?.(U.successUrl??"")});return}if(U.status==="complete"){Xe(!1),Je(()=>{yt.current?.(U.successUrl??"")});return}if(U.status==="expired")throw Xa(U);Ye=!0;let ve=V??W??"full";In(ve),Lt.current+=1;let ce=U.clientSecret||t;pe.current=U.buyerIdentified===!1&&ce?Lo(m,le,ce,{...U.customer?.id?{userId:U.customer.id}:{}}):void 0,on(!1),ln(!1);let at=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Rt=Us(g);if(ve==="auto"&&!Ut.current&&!at&&!Rt){Ut.current=!0;let O=Se(g);try{if(await tr.current(U,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>O,sessionId:le||U.id}),N)return;await O,N||Xe(!1);return}catch{if(N)return;await O,N||Xe(!1);return}}await Se(g),N||Xe(!1)}catch(m){if(N)return;let g=Fl(m,Ye);if(Ye&&y({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),g){let{errorCode:W,stage:ve,...ce}=g;zs(Q,o,D,W,ve,ce)}if(g?.stage==="provider_load"&&(V??te?.data.session?.checkoutMode??"full")==="full"&&xl(te,x,A)){let W=np({billingApiUrl:Q,locale:i,telemetry:o});gt.current=W,Kt(W,null),$n(1),Xe(!1);return}let U=m instanceof it.FloPayError&&g?.stage!=="provider_load"?m:Ml();U!==m&&Je(()=>de.current?.(U)),Te(U),Xe(!1)}}async function Se(Ye){let{flopay:te,paypalFlopay:m,...g}=await qs(Ye,{billingApiUrl:Q,locale:i,telemetry:o});fe.current={publishableKey:g.publishableKey,paypalPublishableKey:g.paypalPublishableKey},Kt(te,m),$n(0)}return bt(),Pe},[V,On,Bn,lt,t,x,A]);let ht=(0,k.useCallback)(async()=>{if(!nt||Vn!==1)return;let N=St.current;$n(2);try{let{flopay:q,paypalFlopay:L}=await qs(nt,{billingApiUrl:Q,locale:i,telemetry:o});if(St.current!==N)return;Qn(),Kt(q,L),$n(0)}catch(q){if(St.current!==N)return;let{errorCode:L,stage:Pe,...Ge}=as(q);zs(Q,o,D,L,Pe,Ge)}},[Qn,Kt,i,Vn,Q,o,D,nt]),an=!!(le&&(Z?.clientSecret||t)),tn=Fn||!an,Vr=(0,k.useCallback)(async()=>{if(!(Fn||!an||!Z)){Xn(!0),Dt(null);try{await Dn(Z,{attempt3DS:!0,fallbackToFull:!0,sessionId:le||Z.id})}finally{Xn(!1)}}},[le,Fn,an,Dn,Z]),Hn=zc(nt,Re),eo=Us(nt),mr=(0,k.useMemo)(()=>{if(!(!nt||!Z||!nt.data.stripe?.publishableKey))return{billingApiUrl:Q}},[nt,Z,Q]),yr=!!(n&&!Ce&&j==="buttons"&&ke&&Bn==="full"),bn=!!(le&&(Z?.vault?.html||to(Z))),fr=(0,k.useMemo)(()=>({session:Z,loading:Ht,error:xn,checkoutMode:Mt,inlineSessionDraft:en,applyInlineSessionPatch:yr?pr:void 0,inlineSessionPatchProcessing:Et,claimPending:Cn,claimRequiresIdentity:Ot,claimBuyerIdentity:Tn,waitForDataAttachment:nr}),[Z,Ht,xn,Mt,en,yr,pr,Et,Cn,Ot,Tn,nr]),$r=!!n&&j==="buttons"&&!eo&&!bn&&(!Be||!mr),An=mt?(0,z.jsx)(Un,{status:mt,errorMessage:_n,authorized:En}):null;if(Ht&&!bn){if(c)return(0,z.jsxs)(z.Fragment,{children:[c,An]});if(j==="buttons"){let N=Ke?.buttonsLayout?.cardButton?.borderRadius??Ke?.appearance.variables?.borderRadius??8,q=L=>(0,z.jsx)("div",{style:{height:L,borderRadius:N,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[x&&q(ea),A&&(H||I)&&q(ea),A&&q(ea),(0,z.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),An]})}return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,z.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,z.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),An]})}return xn?p?(0,z.jsx)(vr.Provider,{value:fr,children:p(xn)}):(0,z.jsx)(vr.Provider,{value:fr,children:(0,z.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:xn.message})}):$r?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(vr.Provider,{value:fr,children:(0,z.jsx)(lp,{onButtonClick:Ze,showPayPal:x,showStripe:A,showApplePay:H,showGooglePay:I,theme:ee,buttonsTheme:we,buttonsStyles:ne,cardButtonContent:Ee,cardBackButtonContent:We,cardTitleContent:oe})}),An]}):eo&&Z&&Hn?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(vr.Provider,{value:fr,children:(0,z.jsxs)("div",{className:_e,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[yn&&(0,z.jsx)($o,{icon:!1,children:yn}),cn==="retrying"&&(0,z.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),cn==="exhausted"&&(0,z.jsxs)("div",{role:"alert",children:[(0,z.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,z.jsx)("button",{type:"button",onClick:Gt,children:"Retry PayPal"})]}),cn!=="exhausted"&&(0,z.jsx)("div",{"aria-hidden":cn==="retrying"?!0:void 0,style:cn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,z.jsx)(Xl,{sessionId:le,nonce:Z.clientSecret||void 0,billingApiUrl:Q,email:Z.customer?.email||en?.account?.email,billingName:[Z.customer?.firstName,Z.customer?.lastName].filter(Boolean).join(" ")||[en?.account?.firstName,en?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Tn,clientId:Hn.clientId,environment:Hn.environment,currency:(Z.currency??"usd").toUpperCase(),isSubscription:Z.mode==="subscription",providerObjectType:Hn.providerObjectType,approvalPresentation:Hn.approvalPresentation,existingOrderId:Hn.existingOrderId,onComplete:u,onErrorChange:Dt,onDecline:E,onButtonClick:Ze,runBeforeButtonClick:_r,onInitializationStateChange:Qr,allowAutomaticRetry:Nr===0,session:Z,telemetry:o,telemetryContext:D,onInstrument:De,debug:se},`${Ve}:paypal-init-${Nr}`)})]})}),An]}):Mt==="confirm"?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(vr.Provider,{value:fr,children:(0,z.jsx)(wa,{flopay:Be,paypalFlopay:$,options:mr??{billingApiUrl:Q},onInstrument:De,children:(0,z.jsxs)("div",{className:_e,children:[yn&&(0,z.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:yn}),X?X({onConfirm:Vr,isProcessing:tn}):(0,z.jsx)("button",{type:"button",onClick:Vr,disabled:tn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:tn?"not-allowed":"pointer",opacity:tn?.6:1},children:Fn?"Processing...":Fe??"Confirm Purchase"})]})},Ve)}),An]}):(!Be||!mr)&&!(bn&&Mt==="full")?(0,z.jsx)(z.Fragment,{children:An}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(vr.Provider,{value:fr,children:(0,z.jsxs)(wa,{flopay:Be,paypalFlopay:$,options:mr??{billingApiUrl:Q},onInstrument:De,children:[Vn===1&&(0,z.jsx)("button",{type:"button",onClick:ht,children:"Retry payment methods"}),Ce?(0,z.jsxs)(z.Fragment,{children:[yn&&(0,z.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:yn}),(0,z.jsx)(sp,{sessionId:le,nonce:Z?.clientSecret||void 0,billingApiUrl:Q,session:Z,submitLabel:be,walletPresentation:P,children:Ce})]}):(0,z.jsx)(Ti,{sessionId:le,nonce:Z?.clientSecret||void 0,telemetry:o,email:Z?.customer?.email||en?.account?.email,userId:Z?.customer?.id||en?.account?.userId,firstName:Z?.customer?.firstName||en?.account?.firstName,lastName:Z?.customer?.lastName||en?.account?.lastName,totalAmount:Z?Math.round((0,it.buildCheckoutDisplayData)(Z).total*100):0,currency:Z?.currency?.toLowerCase()??"usd",onComplete:u,onError:h,onDecline:E,error:yn,onErrorChange:Dt,showPayPal:x,showStripe:A,walletPresentation:P,enabledPaymentMethods:Vn?[]:C??nt?.data.stripe?.enabledPaymentMethods??Z?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:nt?.data.stripe?.enabledPaymentMethodCountries,showApplePay:H,showGooglePay:I,layout:j,theme:ee,buttonsTheme:we,buttonsStyles:ne,appearance:st,cardButtonContent:Ee,cardBackButtonContent:We,cardTitleContent:oe,onButtonClick:Ze,onBeforeButtonClick:ke,onBuyerIdentityReady:Tn,enableAVS:Ie,...ge?{cardFieldOrder:ge}:{},...ue?{cardPreFormSlot:ue}:{},avsLayout:ae,country:Z?.customer?.country,city:Z?.customer?.city,state:Z?.customer?.state,onCountryChange:T,onZipChange:w,avsCheck:!!Ie,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:$s(Ce,j),className:_e,submitLabel:be,directPaypal:Hn,isSubscription:Z?.mode==="subscription",session:Z,dataAttachmentPending:Cn,dataAttachmentRequiresIdentity:Ot,debug:se})]},Ve)}),An]})}function sp({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:a,children:i}){return(0,z.jsx)(z.Fragment,{children:k.default.Children.map(i,c=>{if(!k.default.isValidElement(c))return c;let p=c.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?c:k.default.cloneElement(c,u)})})}function lp({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:i,buttonsStyles:c,cardButtonContent:p,cardBackButtonContent:u,cardTitleContent:h}){let[v,E]=(0,k.useState)(!1),T=(0,k.useMemo)(()=>(0,it.resolveTheme)(a),[a]),w=(0,k.useMemo)(()=>{let C=T?.buttonsLayout??(0,it.resolveButtonsLayoutTheme)(i);return c?{...C,...c,cardButton:{...C.cardButton,...c.cardButton},cardFormContainer:{...C.cardFormContainer,...c.cardFormContainer},backButton:{...C.backButton,...c.backButton},backButtonIcon:{...C.backButtonIcon,...c.backButtonIcon},submitButton:{...C.submitButton,...c.submitButton},title:{...C.title,...c.title}}:C},[T,i,c]),x=T?.buttonsLayout?.cardButton?.borderRadius??T?.appearance.variables?.borderRadius??8,A=C=>(0,z.jsx)("div",{style:{height:C,borderRadius:x,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),P=p===void 0?{boxSizing:"border-box",height:ea,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(v){let C=w.cardInputBorder??"#e5e7eb",H=w.cardInputBackground??"white",I=Bo(u),se=Bo(h);return(0,z.jsxs)("div",{style:{backgroundColor:w.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...w.cardFormContainer},children:[(0,z.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,z.jsxs)("button",{type:"button",onClick:()=>E(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:I?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...w.backButton},children:[(0,z.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...w.backButtonIcon},children:(0,z.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,z.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,z.jsx)(Oo,{content:u})]}),se?(0,z.jsx)("div",{style:{flex:1}}):(0,z.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...w.title},children:(0,z.jsx)(fa,{content:h})})]}),(0,z.jsx)("div",{style:{backgroundColor:H,border:`1px solid ${C}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,z.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,z.jsxs)("div",{style:{display:"flex"},children:[(0,z.jsx)("div",{style:{flex:1,backgroundColor:H,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,z.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,z.jsx)("div",{style:{flex:1,backgroundColor:H,borderTop:"none",borderRight:`1px solid ${C}`,borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,z.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,z.jsx)("div",{style:{backgroundColor:H,border:`1px solid ${C}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,z.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,z.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...w.submitButton,opacity:.5}}),(0,z.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,N.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&T(Yo),n&&(r||o)&&T(Yo),n&&(0,N.jsx)("button",{type:"button",onClick:()=>{e?.("card"),R(!0)},style:{width:"100%",...b,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:w.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...w.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.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"),ep=44;function Ac(e){return new Promise(t=>setTimeout(t,e))}function tp(e,t){return e instanceof ar.FloPayError?e:new ar.FloPayError(e instanceof Error?e.message:t,"api_error")}function np(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function rp(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 Mc({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:i,items:c,subscriptions:p,account:u,successUrl:g,cancelUrl:P,couponCodes:R,tagsData:E,utmMetadata:w,billingApiUrl:M,locale:T,theme:b,appearance:S,buttonsTheme:W,buttonsStyles:A,onSuccess:re,onError:V,onDecline:Y,children:le,disabled:H=!1,type:Ne="button",style:je,...oe}){let ze=(0,ct.useMemo)(()=>(0,ar.resolveBillingApiUrl)(M),[M]),ut=(0,ct.useMemo)(()=>rp({createSession:n,clientId:a,products:i,items:c,subscriptions:p,account:u,successUrl:g,cancelUrl:P,couponCodes:R,tagsData:E,utmMetadata:w}),[u,P,a,R,n,i,c,p,g,E,w]),[xe,we]=(0,ct.useState)(!1),[ve,de]=(0,ct.useState)(null),[Te,$e]=(0,ct.useState)(null),[ot,I]=(0,ct.useState)(!1),[ke,ge]=(0,ct.useState)(null),[j,Ee]=(0,ct.useState)(null),Q=(0,ct.useRef)(!0),Be=(0,ct.useRef)(null),ee=(0,ct.useRef)(j),Je=(0,ct.useRef)(re),st=(0,ct.useRef)(V),De=(0,ct.useRef)(Y),et=(0,ct.useCallback)(f=>ii(Be,async C=>{try{return await f(C)}catch(Z){throw C.aborted?io(Z):Z}}),[]);(0,ct.useEffect)(()=>{ee.current=j},[j]),(0,ct.useEffect)(()=>{Je.current=re},[re]),(0,ct.useEffect)(()=>{st.current=V},[V]),(0,ct.useEffect)(()=>{De.current=Y},[Y]),(0,ct.useEffect)(()=>(Q.current=!0,()=>{Q.current=!1,Be.current?.abort()}),[]),(0,ct.useEffect)(()=>{if(typeof window>"u")return;let f=C=>{C.key==="Escape"&&Ee(null)};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f)}},[]);let tt=(0,ct.useCallback)((f,C=va)=>{De.current?.(un(C,f,{code:f.code,declineCode:f.declineCode}))},[]),pt=(0,ct.useCallback)(async f=>{Q.current&&($e(null),I(f.result.status==="authorized"),de("success"),await Ac(600),Q.current&&Xe(()=>Je.current?.(f)))},[]),Ae=(0,ct.useCallback)(async(f,C)=>{Q.current&&(st.current?.(f),C?.emitDecline&&tt(f,C.method),$e(f.message),I(!1),de("error"),await Ac(400))},[tt]),At=(0,ct.useCallback)(async(f,C,Z)=>{let K=f.data.session??null;if(!K)throw Qr(new ar.FloPayError("No session data returned","api_error"),C);let Pe=K.clientSecret||t;if($r(K)){await pt({result:jr(K,C),session:K,sessionId:K.id||C,autoCompleted:!1});return}if(K.status==="expired")throw Qr($a(K),K.id||C);try{if(f.autoProcessingPending){let We=f.autoProcessingPending,Ze=new Si.PaymentAPI(ze),Se=await et(Ye=>Ze.waitForCheckoutSessionCompletion(We.sessionId,{initialDelayMs:We.retryAfterMs,nonce:Pe,statusUrl:We.statusUrl,signal:Ye})),bt=to(Se,K),Wt=Se.autoProcessingError?.type==="3ds_required"&&Se.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Se.autoProcessingError.nextActionRedirectUrl}:null;if(Wt&&C&&Pe){let Ye=await et(Tn=>$o(Wt,{billingApiUrl:ze,sessionId:C,nonce:Pe,session:K,signal:Tn,telemetry:!0}));await pt({result:Ye,session:K,sessionId:K.id||C,autoCompleted:!1});return}if(Se.autoProcessingError)throw xr(Se.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Se.autoProcessingError.checkoutMethod});if(!$r(bt))throw Do(bt);await pt({result:jr(bt,C),session:bt,sessionId:bt.id||C,autoCompleted:!1});return}if(f.autoProcessingError){let We=f.autoProcessingError.nextActionRedirectUrl;if(f.autoProcessingError.type==="3ds_required"&&We&&C&&Pe){let Ze=await et(Ye=>ss({billingApiUrl:ze,sessionId:C,nonce:Pe,nextActionRedirectUrl:We,signal:Ye}));if(Ze.status==="declined")throw xr({type:Ze.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ze.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:f.autoProcessingError.checkoutMethod});let bt=await new Si.PaymentAPI(ze).waitForCheckoutSessionCompletion(C,{initialDelayMs:0,nonce:Pe}),Wt=to(bt,K);if(!$r(Wt))throw xr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:f.autoProcessingError.checkoutMethod});await pt({result:jr(Wt,C),session:Wt,sessionId:Wt.id||C,autoCompleted:!1});return}throw xr(f.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:f.autoProcessingError.checkoutMethod})}if(Z?.fromCreateSession&&f.autoProcessingAttempted===!0)throw xr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Bt=await Wo({billingApiUrl:ze,sessionId:C??K.id,session:K,nonce:Pe});if(Bt.type==="next_action_required"&&Pe){let We=C??K.id,Ze=await et(Se=>$o(Bt,{billingApiUrl:ze,sessionId:We,nonce:Pe,session:K,signal:Se,telemetry:!0}));await pt({result:Ze,session:K,sessionId:K.id||We,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 pt({result:Bt.result,session:K,sessionId:K.id||C,autoCompleted:!1})}catch(Bt){let We=K.id||C,Ze=Qr(Ca(Bt),We);if(Ze.code==="three_ds_aborted")return;if(Ze.code==="checkout_processing_timeout"){if(!Q.current)return;ge(Ze.message),Xe(()=>st.current?.(Ze));return}await Ae(Ze,{emitDecline:!0,method:Ze.checkoutMethod??va}),np(Ze,We)&&We&&Q.current&&Ee({sessionId:We,errorMessage:Ze.message,nonce:Pe||void 0,payPalOrderId:Ze.orderId})}},[t,ze,et,Ae,pt]),kt=(0,ct.useCallback)(async f=>{if(oe.onClick?.(f),!(f.defaultPrevented||H||xe)){if(Ee(null),ge(null),e&&ut){let C=new ar.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Ae(C),Q.current&&(de(null),$e(null));return}if(!e&&!ut){let C=new ar.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Ae(C),Q.current&&(de(null),$e(null));return}we(!0),$e(null),I(!1),de("processing");try{let C=new Si.PaymentAPI(ze);if(e){let Z=await C.getUnifiedCheckoutSession(e,t);await At(Z,e);return}try{let Z=await C.createAndFetchSession({...ut});await At(Z,Z.data.session?.id??null,{fromCreateSession:!0})}catch(Z){if(Wa(Z)==="session_auto_completed"){await pt({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Z}}catch(C){await Ae(Qr(tp(C,"Automatic payment failed. Please try again."),e))}finally{Q.current&&(de(null),$e(null),we(!1))}}},[oe.onClick,ut,H,xe,t,At,ze,e,Ae,pt]),gt=(0,ct.useCallback)(f=>{let C=ee.current;Ee(null),Je.current?.({result:f,session:null,sessionId:C?.sessionId??null,autoCompleted:!1})},[]),Ct=(0,ct.useCallback)(f=>{st.current?.(f)},[]),$=(0,ct.useCallback)(f=>{De.current?.(f)},[]),he=(0,ct.useMemo)(()=>(0,ar.resolveTheme)(b),[b]),Ue=(0,ct.useMemo)(()=>{let f=he?.buttonsLayout??(0,ar.resolveButtonsLayoutTheme)(W);return A?{...f,...A,cardButton:{...f.cardButton,...A.cardButton}}:f},[he,W,A]),v=(0,ct.useMemo)(()=>{let f=he?.appearance;return S?f?{...f,...S,variables:{...f.variables,...S.variables}}:S:f},[S,he]),J=v?.variables,Fe=J?.colorPrimary??"#4A49FF",ue=J?.colorPrimaryHover??Ko(Fe,.12),Ce=J?.borderRadius??"8px";return(0,or.jsxs)(or.Fragment,{children:[(0,or.jsx)("button",{...oe,type:Ne,onClick:kt,disabled:H||xe,"aria-busy":xe,style:{width:"100%",...le===void 0?{boxSizing:"border-box",height:ep,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Ue.cardButton,...ks({themeBundle:he,resolvedPrimaryColor:Fe,resolvedBorderRadius:Ce,submitButtonStyle:Ue.submitButton,explicitPrimaryColor:J?.colorPrimary}),fontSize:Ue.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:H||xe?"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:H||xe?.6:1,...je},onMouseEnter:f=>{oe.onMouseEnter?.(f),!f.defaultPrevented&&!H&&!xe&&(he||J?.colorPrimary)&&(f.currentTarget.style.backgroundColor=ue)},onMouseLeave:f=>{oe.onMouseLeave?.(f),!f.defaultPrevented&&(he||J?.colorPrimary)&&(f.currentTarget.style.backgroundColor=Fe)},onMouseDown:f=>{oe.onMouseDown?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(0.985)")},onMouseUp:f=>{oe.onMouseUp?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(1)")},children:(0,or.jsx)(xo,{content:le})}),ke&&(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:ke}),ve&&(0,or.jsx)(Ln,{status:ve,errorMessage:Te,authorized:ot}),j&&(0,or.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:f=>{f.target===f.currentTarget&&Ee(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(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)(Ci,{sessionId:j.sessionId,nonce:j.nonce,checkoutMode:"full",billingApiUrl:ze,locale:T,theme:b,...v?{appearance:v}:{},buttonsTheme:W,buttonsStyles:A,initialErrorMessage:j.errorMessage,initialPayPalOrderId:j.payPalOrderId,cardTitleContent:null,onComplete:gt,onError:Ct,onDecline:$})})})]})}var ki=require("@flopay/js/card-setup"),Hn=require("@flopay/shared"),_t=require("react");var xc={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function wi(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?xc.dark:xc.light,a=t.colorText??(r?"#F1F5F9":"#262833"),i=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:i?.color??a}}var Br=require("react/jsx-runtime"),Aa=class extends Hn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function lo(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 Aa(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 Fc({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:i=null,onReady:c,onComplete:p,onDecline:u,onCancel:g,onValidation:P,onError:R}){let[E,w]=(0,_t.useState)(null),[M,T]=(0,_t.useState)(null),[b,S]=(0,_t.useState)(null),[W,A]=(0,_t.useState)(null),[re,V]=(0,_t.useState)(null),Y=(0,_t.useRef)(!1),le=(0,_t.useRef)(!1),H=(0,_t.useMemo)(()=>typeof o=="object"?void 0:(0,Hn.resolveTheme)(o),[o]),Ne=(0,_t.useMemo)(()=>typeof o=="object"?o:H?Go({appearance:H.appearance,buttonsStyles:H.buttonsLayout,layout:"default"}):null,[H,o]),je=(0,_t.useMemo)(()=>di(H?.buttonsLayout.cardFormContainer,a),[H,a]),oe=(0,_t.useMemo)(()=>H?wi(H):void 0,[H]),ze=(0,_t.useRef)(c),ut=(0,_t.useRef)(R),xe=(0,_t.useRef)(p),we=(0,_t.useRef)(u),ve=(0,_t.useRef)(g),de=(0,_t.useRef)(P),Te=(0,_t.useRef)(!1),$e=(0,_t.useRef)(!1),ot=(0,_t.useRef)(0);return ze.current=c,ut.current=R,xe.current=p,we.current=u,ve.current=g,de.current=P,(0,_t.useEffect)(()=>{let I=ot.current+1;return ot.current=I,()=>{queueMicrotask(()=>{ot.current===I&&(Te.current||$e.current||($e.current=!0,Xe(()=>{ve.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,_t.useEffect)(()=>{let I=!0,ke=new ki.PaymentAPI((0,Hn.resolveBillingApiUrl)(n),{telemetry:r});return w(null),T(null),S(null),Te.current=!1,$e.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 ge=await ke.getUnifiedCheckoutSession(e,t);if(!I)return;let j=ge.data.session;if(!j||!(0,Hn.isCardSetupCheckoutSession)(j))throw new Hn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Ee=j.vault;if(Ee?.html?.trim()||(Ee=await ke.getVaultCapture(e,t)),!Ee.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(!I)return;T(Ee),w(new ki.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(ge){if(!I)return;let j=lo(ge);Te.current=!0,S(j),Xe(()=>ut.current?.(j))}})(),()=>{I=!1,ke.destroy()}},[n,t,e,r]),(0,_t.useEffect)(()=>{if(!E)return;let I=!1;le.current=!1,Y.current=!1;let ke=E.on("submitting",()=>{Y.current=!0,V(null),A("processing")}),ge=E.on("complete",Q=>{Te.current=!0,Y.current=!1,A("success"),(async()=>(await new Promise(Be=>setTimeout(Be,600)),!le.current&&(le.current=!0,Xe(()=>{xe.current?.({status:"succeeded",sessionId:e,...Q.paymentMethod?{paymentMethod:Q.paymentMethod}:{}})}),I||A(null))))()}),j=E.on("decline",Q=>{Te.current=!0,Y.current=!1,V(Q.message??null),A("error"),Xe(()=>{we.current?.({status:"declined",sessionId:e,...Q.declineReason?{reason:Q.declineReason}:{},...Q.message?{message:Q.message}:{}})}),(async()=>(await new Promise(Be=>setTimeout(Be,400)),I||A(null)))()}),Ee=E.on("challenge_dismissed",()=>{A(null)});return()=>{I=!0,ke(),ge(),j(),Ee()}},[E,e]),b?(0,Br.jsx)("div",{role:"alert",children:b.message}):!E||!M?.html?(0,Br.jsx)(Br.Fragment,{children:i}):(0,Br.jsxs)(Br.Fragment,{children:[W&&(0,Br.jsx)(Ln,{status:W,errorMessage:re,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...oe?{theme:oe}:{}}),(0,Br.jsx)(so,{capture:E,html:M.html,messageToken:M.messageToken,expectedOrigin:M.expectedOrigin,theme:Ne,containerStyle:je,onReady:()=>{Xe(()=>ze.current?.())},onValidation:I=>{Xe(()=>de.current?.(I))},onError:I=>{if(!I)return;Y.current&&(Y.current=!1,V(I),A("error"),setTimeout(()=>A(null),400));let ke=lo(new Error(I),{code:"card_setup_widget_failed",retryable:!0});Xe(()=>ut.current?.(ke))}})]})}var Bc=require("@flopay/js/card-setup"),co=require("@flopay/shared"),Dc=require("@paypal/paypal-js"),vo=require("react");var Lc=require("react/jsx-runtime");function Oc({clientId:e,environment:t,currency:n,sessionId:r,nonce:o,billingApiUrl:a,telemetry:i,customer:{userId:c,email:p},onSubmitting:u,onConfirmed:g,onFailed:P,onAbandoned:R}){let E=(0,vo.useRef)(null),w=(0,vo.useRef)({onSubmitting:u,onConfirmed:g,onFailed:P,onAbandoned:R});w.current={onSubmitting:u,onConfirmed:g,onFailed:P,onAbandoned:R};let[M]=(0,vo.useState)(()=>Kr().inAppBrowser);return(0,vo.useEffect)(()=>{let T=!0,b,S=new Bc.PaymentAPI(a,{telemetry:i}),W={userId:c,email:p};return(async()=>{try{let A=await(0,Dc.loadScript)({clientId:e,...n?{currency:n.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),re=E.current;if(!T||!re)return;if(!A?.Buttons)throw new co.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let V=A.Buttons({createVaultSetupToken:async()=>{w.current.onSubmitting();let Y=await S.createSessionIntent(r,o,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:co.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(Y.provider!=="paypal"||Y.providerObjectType!=="setup_token")throw new co.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return Y.providerObjectId},onApprove:async Y=>{let le=Y.vaultSetupToken;if(!le)throw new co.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let H=await S.processPayment(W.userId,{sessionId:r,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:le,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:co.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:W});if(!H.ok)throw new co.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:H.status});T&&w.current.onConfirmed()},onCancel:()=>{T&&w.current.onAbandoned()},onError:Y=>{if(!T)return;let{popupBlocked:le}=ro(Y,{inAppBrowser:M,handoffObserved:!1});w.current.onFailed(le?new Error(no("PayPal",!0,M)):Y,{code:le?"popup_blocked":"paypal_setup_failed",retryable:!0})}});b=()=>V.close(),await V.render(re)}catch(A){if(!T)return;w.current.onFailed(A,{code:"paypal_unavailable",retryable:!0})}})(),()=>{T=!1,b?.().catch(()=>{}),S.destroy()}},[a,e,n,p,t,M,o,r,i,c]),(0,Lc.jsx)("div",{ref:E,"data-flopay-paypal-setup":""})}var Nc=require("@flopay/js/card-setup"),Ri=require("@flopay/shared"),Or=require("@stripe/react-stripe-js"),zc=require("@stripe/stripe-js"),ir=require("react");var Dr=require("react/jsx-runtime"),Uc={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 op(e){let t=xs.get(e);if(t)return t;let n=(0,zc.loadStripe)(e).catch(r=>{throw xs.delete(e),r});return xs.set(e,n),n}var ap={night:"night",flat:"flat"};function ip(e){return e?{theme:ap[e.theme??"default"]??"stripe",...e.variables?{variables:e.variables}:{},...e.rules?{rules:e.rules}:{}}:void 0}function sp(e){return go(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function lp(e){return e==="paypal"?"PayPal":(0,Ri.getStripeMethodDisplayName)(e)}function cp(){return typeof window>"u"?"":window.location.href}function qc(e){let{publishableKey:t,method:n,currency:r,appearance:o}=e,[a]=(0,ir.useState)(()=>op(t)),i=(0,ir.useMemo)(()=>{let c=ip(o);return{mode:"setup",currency:r.toLowerCase(),paymentMethodTypes:Uc[n]?.types??[n],...c?{appearance:c}:{}}},[o,r,n]);return(0,Dr.jsx)(Or.Elements,{stripe:a,options:i,children:(0,Dr.jsx)(dp,{...e})})}function dp({method:e,category:t,sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onSubmitting:i,onConfirmed:c,onDeclined:p,onFailed:u,onValidation:g}){let P=(0,Or.useStripe)(),R=(0,Or.useElements)(),[E,w]=(0,ir.useState)(!1),M=(0,ir.useRef)(!1),[T]=(0,ir.useState)(()=>Kr()),[b,S]=(0,ir.useState)(!1),W=(0,ir.useCallback)((Y,le)=>{if(ro(Y,{inAppBrowser:T.inAppBrowser,handoffObserved:!1}).popupBlocked){S(!0),u(new Error(no(lp(e),!0,T.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}u(le.message===void 0?Y:new Error(le.message),{code:le.code,retryable:!0})},[T.inAppBrowser,e,u]),A=(0,ir.useCallback)(async()=>{if(!(!P||!R||M.current)){M.current=!0,w(!0);try{let Y=await R.submit();if(Y.error){g(Y.error.message??null);return}i();let le=await new Nc.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 Ri.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let H=await P.confirmSetup({elements:R,clientSecret:le.clientSecret,confirmParams:{return_url:cp()},redirect:"if_required"});if(H.error){sp(H.error)?p({...H.error.decline_code||H.error.code?{reason:H.error.decline_code??H.error.code}:{},...H.error.message?{message:H.error.message}:{}}):W(H.error,{code:"payment_method_setup_provider_failed",message:H.error.message??"The payment method could not be saved."});return}c()}catch(Y){W(Y,{code:"payment_method_setup_failed"})}finally{M.current=!1,w(!1)}}},[o,t,R,e,r,c,p,i,g,W,n,P,a]),re=Uc[e]?.wallet,V=re==="paypal"&&Ka(T,"auto",b?"blocked":T.popupCapability)==="redirect";if(t==="wallet"&&re&&!V){let Y={applePay:"never",googlePay:"never",link:"never",paypal:"never",amazonPay:"never"};return Y[re]="auto",(0,Dr.jsx)(Or.ExpressCheckoutElement,{options:{paymentMethods:Y},onConfirm:()=>{A()}})}return(0,Dr.jsxs)(Dr.Fragment,{children:[(0,Dr.jsx)(Or.PaymentElement,{onChange:Y=>{Y.complete&&g(null)}}),(0,Dr.jsx)("button",{type:"button","data-flopay-payment-method-save":e,disabled:!P||!R||E,onClick:()=>{A()},children:"Save payment method"})]})}var Ma=require("@flopay/js/card-setup"),bn=require("@flopay/shared"),Ge=$i(require("react"),1);var Vc=require("@flopay/shared"),up=new Set(["apple_pay","google_pay","link","paypal","amazon_pay"]),pp=new Set(["wallet","apm"]);function Xo(e){return typeof e=="string"&&e.trim().length>0}function mp(e){if(typeof e!="object"||e===null)return!1;let t=e;return Xo(t.family)&&Xo(t.paymentMethodType)}function yp(e){let n=e.raw?.data?.currency;return Xo(n)?n.trim().toUpperCase():null}function jc(e){let t=yp(e),n=e.data.session?.advertisedPaymentMethods;if(!Array.isArray(n))return{card:!0,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]};let r={card:!1,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]},o=new Set;for(let a of n){if(!mp(a)||o.has(a.paymentMethodType))continue;let{family:i,paymentMethodType:c,providerType:p,publishableKey:u}=a;if(i==="card"){if(c!=="card")continue;r.card=!0}else if(pp.has(i)){if(p!=="stripe"||c==="card"||!Xo(u))continue;if(t===null){r.skippedForMissingCurrency.includes(c)||r.skippedForMissingCurrency.push(c);continue}r.stripe.push({method:c,publishableKey:u,currency:t})}else if(i==="paypal"){if(c!==Vc.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE||p!=="paypal"||!Xo(u))continue;r.paypal={clientId:u,...Xo(a.environment)?{environment:a.environment}:{}}}else continue;o.add(c)}return r.paypal&&(r.stripe=r.stripe.filter(a=>a.method!=="paypal")),r}function Fs(e){return[...e.card?["card"]:[],...e.stripe.map(t=>t.method),...e.paypal?["paypal"]:[]]}function $c(e){return Fs(e).length>0}function Wc(e){return up.has(e)?"wallet":"apm"}var fp=["setup_intent","setup_intent_client_secret","redirect_status"];function Hc(){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 Kc(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let n of fp)e.searchParams.has(n)&&(e.searchParams.delete(n),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}function Gc(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"),gp=15,hp=2e3;function Pp(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Bs(e){return new Promise(t=>setTimeout(t,e))}async function bp(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=jc(r);if(!$c(a)){let{skippedForMissingCurrency:i}=a,c=i.length>0?`FloPay: this setup session advertises only Stripe methods (${i.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new bn.FloPayError(c,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:o,advertisement:a}}async function vp(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 Ge.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 Yc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,theme:i="modern-light",containerStyle:c,loading:p=null,onReady:u,onComplete:g,onDecline:P,onCancel:R,onValidation:E,onError:w}){let[M]=(0,Ge.useState)(Hc),[T,b]=(0,Ge.useState)(null),[S,W]=(0,Ge.useState)(!1),[A,re]=(0,Ge.useState)(null),[V,Y]=(0,Ge.useState)(null),[le,H]=(0,Ge.useState)(null),[Ne,je]=(0,Ge.useState)(null),[oe,ze]=(0,Ge.useState)(()=>new Set),ut=(0,Ge.useRef)(oe),xe=(0,Ge.useRef)(null);xe.current=T;let we=(0,Ge.useRef)(!1),ve=(0,Ge.useRef)(!1),de=(0,Ge.useRef)(!1),Te=(0,Ge.useRef)(!1),$e=(0,Ge.useRef)(0),ot=(0,Ge.useRef)(0),I=(0,Ge.useRef)(!1),ke=(0,Ge.useMemo)(()=>typeof i=="object"?void 0:(0,bn.resolveTheme)(i),[i]),ge=(0,Ge.useMemo)(()=>typeof i=="object"?i:ke?Go({appearance:ke.appearance,buttonsStyles:ke.buttonsLayout,layout:"default"}):null,[ke,i]),j=(0,Ge.useMemo)(()=>di(ke?.buttonsLayout.cardFormContainer,c),[ke,c]),Ee=(0,Ge.useMemo)(()=>ke?wi(ke):void 0,[ke]),Q=(0,Ge.useRef)({sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:u,onComplete:g,onDecline:P,onCancel:R,onValidation:E,onError:w});Q.current={sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:u,onComplete:g,onDecline:P,onCancel:R,onValidation:E,onError:w},(0,Ge.useEffect)(()=>{I.current=!0;let v=$e.current+1;return $e.current=v,()=>{I.current=!1,ot.current+=1,queueMicrotask(()=>{$e.current===v&&(de.current||Te.current||(Te.current=!0,Xe(()=>{Q.current.onCancel?.({status:"cancelled",sessionId:n})})))})}},[n]);let Be=(0,Ge.useCallback)((v,J)=>{de.current=!0,we.current=!1,je({status:"success",wording:v,message:null}),(async()=>(await Bs(600),!ve.current&&(ve.current=!0,Xe(()=>{Q.current.onComplete?.({status:"succeeded",sessionId:Q.current.sessionId,...J?{paymentMethod:J}:{}})}),I.current&&je(null))))()},[]),ee=(0,Ge.useCallback)((v,J)=>{de.current=!0,we.current=!1,je({status:"error",wording:v,message:J.message??null}),Xe(()=>{Q.current.onDecline?.({status:"declined",sessionId:Q.current.sessionId,...J.reason?{reason:J.reason}:{},...J.message?{message:J.message}:{}})}),(async()=>(await Bs(400),I.current&&je(null)))()},[]),Je=(0,Ge.useCallback)((v,J)=>{we.current?(we.current=!1,je({status:"error",wording:v,message:J.message}),setTimeout(()=>{I.current&&je(null)},400)):je(null),Xe(()=>Q.current.onError?.(J))},[]),st=(0,Ge.useCallback)(async v=>{let J=ot.current+1;ot.current=J;let Fe=()=>!I.current||J!==ot.current;we.current=!0,je({status:"processing",wording:"payment_method",message:null});let ue=new Ma.PaymentAPI((0,bn.resolveBillingApiUrl)(Q.current.billingApiUrl),{telemetry:Q.current.telemetry});try{for(let Ce=0;Ce<gp;Ce+=1){if((Ce>0||v.waitFirst)&&await Bs(hp),Fe())return;let z=await ue.getUnifiedCheckoutSession(Q.current.sessionId,Q.current.nonce);if(Fe())return;let f=z.data.session?.status;if(f==="complete"){W(!0),Be("payment_method");return}if(f==="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(Ce){if(Fe())return;let z=Ce instanceof bn.FloPayError&&Ce.code==="payment_method_setup_unverified";Je("payment_method",lo(Ce,z?{retryable:!0}:{}))}finally{ue.destroy()}},[Je,Be]);(0,Ge.useEffect)(()=>{let v=!0,J=new Ma.PaymentAPI((0,bn.resolveBillingApiUrl)(o),{telemetry:a});b(null),W(!1),re(null),Y(null),H(null);let Fe=new Set;return ut.current=Fe,ze(Fe),de.current=!1,Te.current=!1,ve.current=!1,(async()=>{try{let{session:ue,advertisement:Ce}=await bp(J,n,r);if(!v)return;let z={advertisement:Ce,customer:Pp(ue)};if(M){if(Kc(),ue.status==="complete"){W(!0),b(z),Be("payment_method");return}M.failed?ee("payment_method",{reason:"redirect_failed"}):st({waitFirst:!0})}let f=Ce.card?await vp(J,ue,n,r):null;if(!v)return;b(z),f&&(Y(f),re(new Ma.PciVaultCardCapture({sessionId:n,operation:"card_setup",telemetry:a})))}catch(ue){if(!v)return;let Ce=lo(ue);de.current=!0,H(Ce),Xe(()=>Q.current.onError?.(Ce))}})(),()=>{v=!1,J.destroy()}},[o,r,M,ee,Be,n,a,st]),(0,Ge.useEffect)(()=>{if(!A)return;we.current=!1;let v=A.on("submitting",()=>{we.current=!0,je({status:"processing",wording:"card",message:null})}),J=A.on("complete",Ce=>{Be("card",Ce.paymentMethod)}),Fe=A.on("decline",Ce=>{ee("card",{...Ce.declineReason?{reason:Ce.declineReason}:{},...Ce.message?{message:Ce.message}:{}})}),ue=A.on("challenge_dismissed",()=>{je(null)});return()=>{v(),J(),Fe(),ue()}},[A,ee,Be]);let De=(0,Ge.useCallback)((v,J,Fe)=>{if(Fe.retryable){Je("payment_method",lo(J,Fe));return}if(ut.current.has(v))return;let ue=new Set(ut.current);ue.add(v),ut.current=ue,ze(ue);let Ce=xe.current?.advertisement,z=Ce?Fs(Ce).some(f=>!ue.has(f)):!1;Je("payment_method",lo(J,{code:Fe.code,retryable:z}))},[Je]),et=(0,Ge.useMemo)(()=>({onSubmitting:()=>{we.current=!0,je({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{st({waitFirst:!1})},onDeclined:v=>ee("payment_method",v),onValidation:v=>{Xe(()=>Q.current.onValidation?.(v))},onAbandoned:()=>{we.current=!1,je(null)}}),[ee,st]),tt=(0,Ge.useRef)(De);tt.current=De;let pt=(0,Ge.useRef)(new Map),Ae=v=>{let J=pt.current.get(v);if(J)return J;let Fe=(ue,Ce)=>tt.current(v,ue,Ce);return pt.current.set(v,Fe),Fe},At=Ne?(0,an.jsx)(Ln,{status:Ne.status,errorMessage:Ne.message,...Gc(Ne.wording),successNote:null,...Ee?{theme:Ee}:{}}):null;if(le)return(0,an.jsx)("div",{role:"alert",children:le.message});if(!T||S)return(0,an.jsxs)(an.Fragment,{children:[At,T?null:p]});let{advertisement:kt,customer:gt}=T,Ct=(0,bn.resolveBillingApiUrl)(o),$=a===void 0?{}:{telemetry:a},he=kt.stripe.filter(({method:v})=>!oe.has(v)),Ue=oe.has("paypal")?null:kt.paypal;return(0,an.jsxs)(an.Fragment,{children:[At,kt.card&&A&&V?.html?(0,an.jsx)("div",{"data-flopay-payment-method":"card",children:(0,an.jsx)(so,{capture:A,html:V.html,messageToken:V.messageToken,expectedOrigin:V.expectedOrigin,theme:ge,containerStyle:j,onReady:()=>{Xe(()=>Q.current.onReady?.())},onValidation:v=>{Xe(()=>Q.current.onValidation?.(v))},onError:v=>{v&&Je("card",lo(new Error(v),{code:"card_setup_widget_failed",retryable:!0}))}})}):null,he.map(({method:v,publishableKey:J,currency:Fe})=>(0,an.jsx)("div",{"data-flopay-payment-method":v,children:(0,an.jsx)(Ii,{onFailed:Ae(v),children:(0,an.jsx)(Ge.Suspense,{fallback:null,children:(0,an.jsx)(e,{method:v,category:Wc(v),publishableKey:J,currency:Fe,sessionId:n,nonce:r,billingApiUrl:Ct,...$,...ke?{appearance:ke.appearance}:{},...et,onFailed:Ae(v)})})})},v)),Ue?(0,an.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,an.jsx)(Ii,{onFailed:Ae("paypal"),children:(0,an.jsx)(Ge.Suspense,{fallback:null,children:(0,an.jsx)(t,{clientId:Ue.clientId,...Ue.environment?{environment:Ue.environment}:{},...kt.currency?{currency:kt.currency}:{},sessionId:n,nonce:r,billingApiUrl:Ct,customer:gt,...$,...et,onFailed:Ae("paypal")})})})}):null]})}var Jc=require("react/jsx-runtime"),Cp={StripeSetupMethod:qc,PayPalSetupMethod:Oc};function Xc(e){return(0,Jc.jsx)(Yc,{...e,branches:Cp})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,z.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&A(ea),n&&(r||o)&&A(ea),n&&(0,z.jsx)("button",{type:"button",onClick:()=>{e?.("card"),E(!0)},style:{width:"100%",...P,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:w.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...w.cardButton},onMouseDown:C=>{C.currentTarget.style.transform="scale(0.985)"},onMouseUp:C=>{C.currentTarget.style.transform="scale(1)"},children:(0,z.jsx)(Do,{content:p})}),(0,z.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var sr=require("react/jsx-runtime"),cp=44;function Uc(e){return new Promise(t=>setTimeout(t,e))}function dp(e,t){return e instanceof lr.FloPayError?e:new lr.FloPayError(e instanceof Error?e.message:t,"api_error")}function up(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function pp(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 qc({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:i,items:c,subscriptions:p,account:u,successUrl:h,cancelUrl:v,couponCodes:E,tagsData:T,utmMetadata:w,billingApiUrl:x,locale:A,theme:P,appearance:C,buttonsTheme:H,buttonsStyles:I,onSuccess:se,onError:j,onDecline:ee,children:we,disabled:ne=!1,type:Ee="button",style:We,...oe}){let xe=(0,dt.useMemo)(()=>(0,lr.resolveBillingApiUrl)(x),[x]),Ze=(0,dt.useMemo)(()=>pp({createSession:n,clientId:a,products:i,items:c,subscriptions:p,account:u,successUrl:h,cancelUrl:v,couponCodes:E,tagsData:T,utmMetadata:w}),[u,v,a,E,n,i,c,p,h,T,w]),[ke,Ie]=(0,dt.useState)(!1),[ge,ue]=(0,dt.useState)(null),[ae,be]=(0,dt.useState)(null),[_e,R]=(0,dt.useState)(!1),[Re,Ce]=(0,dt.useState)(null),[V,Fe]=(0,dt.useState)(null),X=(0,dt.useRef)(!0),Le=(0,dt.useRef)(null),Q=(0,dt.useRef)(V),Ke=(0,dt.useRef)(se),st=(0,dt.useRef)(j),Ne=(0,dt.useRef)(ee),tt=(0,dt.useCallback)(b=>pi(Le,async S=>{try{return await b(S)}catch(Y){throw S.aborted?co(Y):Y}}),[]);(0,dt.useEffect)(()=>{Q.current=V},[V]),(0,dt.useEffect)(()=>{Ke.current=se},[se]),(0,dt.useEffect)(()=>{st.current=j},[j]),(0,dt.useEffect)(()=>{Ne.current=ee},[ee]),(0,dt.useEffect)(()=>(X.current=!0,()=>{X.current=!1,Le.current?.abort()}),[]),(0,dt.useEffect)(()=>{if(typeof window>"u")return;let b=S=>{S.key==="Escape"&&Fe(null)};return window.addEventListener("keydown",b),()=>{window.removeEventListener("keydown",b)}},[]);let nt=(0,dt.useCallback)((b,S=Ra)=>{Ne.current?.(un(S,b,{code:b.code,declineCode:b.declineCode}))},[]),pt=(0,dt.useCallback)(async b=>{X.current&&(be(null),R(b.result.status==="authorized"),ue("success"),await Uc(600),X.current&&Je(()=>Ke.current?.(b)))},[]),Be=(0,dt.useCallback)(async(b,S)=>{X.current&&(st.current?.(b),S?.emitDecline&&nt(b,S.method),be(b.message),R(!1),ue("error"),await Uc(400))},[nt]),At=(0,dt.useCallback)(async(b,S,Y)=>{let y=b.data.session??null;if(!y)throw no(new lr.FloPayError("No session data returned","api_error"),S);let M=y.clientSecret||t;if(Hr(y)){await pt({result:jr(y,S),session:y,sessionId:y.id||S,autoCompleted:!1});return}if(y.status==="expired")throw no(Xa(y),y.id||S);try{if(b.autoProcessingPending){let ie=b.autoProcessingPending,J=new Bi.PaymentAPI(xe),le=await tt(Xe=>J.waitForCheckoutSessionCompletion(ie.sessionId,{initialDelayMs:ie.retryAfterMs,nonce:M,statusUrl:ie.statusUrl,signal:Xe})),lt=oo(le,y),Ht=le.autoProcessingError?.type==="3ds_required"&&le.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:le.autoProcessingError.nextActionRedirectUrl}:null;if(Ht&&S&&M){let Xe=await tt(xn=>Ko(Ht,{billingApiUrl:xe,sessionId:S,nonce:M,session:y,signal:xn,telemetry:!0}));await pt({result:Xe,session:y,sessionId:y.id||S,autoCompleted:!1});return}if(le.autoProcessingError)throw Br(le.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:le.autoProcessingError.checkoutMethod});if(!Hr(lt))throw No(lt);await pt({result:jr(lt,S),session:lt,sessionId:lt.id||S,autoCompleted:!1});return}if(b.autoProcessingError){let ie=b.autoProcessingError.nextActionRedirectUrl;if(b.autoProcessingError.type==="3ds_required"&&ie&&S&&M){let J=await tt(Xe=>Cs({billingApiUrl:xe,sessionId:S,nonce:M,nextActionRedirectUrl:ie,signal:Xe}));if(J.status==="declined")throw Br({type:J.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:J.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:b.autoProcessingError.checkoutMethod});let lt=await new Bi.PaymentAPI(xe).waitForCheckoutSessionCompletion(S,{initialDelayMs:0,nonce:M}),Ht=oo(lt,y);if(!Hr(Ht))throw Br({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:b.autoProcessingError.checkoutMethod});await pt({result:jr(Ht,S),session:Ht,sessionId:Ht.id||S,autoCompleted:!1});return}throw Br(b.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.autoProcessingError.checkoutMethod})}if(Y?.fromCreateSession&&b.autoProcessingAttempted===!0)throw Br({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let De=await Go({billingApiUrl:xe,sessionId:S??y.id,session:y,nonce:M});if(De.type==="next_action_required"&&M){let ie=S??y.id,J=await tt(le=>Ko(De,{billingApiUrl:xe,sessionId:ie,nonce:M,session:y,signal:le,telemetry:!0}));await pt({result:J,session:y,sessionId:y.id||ie,autoCompleted:!1});return}if(De.type!=="success")throw Br({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await pt({result:De.result,session:y,sessionId:y.id||S,autoCompleted:!1})}catch(De){let ie=y.id||S,J=no(Ia(De),ie);if(J.code==="three_ds_aborted")return;if(J.code==="checkout_processing_timeout"){if(!X.current)return;Ce(J.message),Je(()=>st.current?.(J));return}await Be(J,{emitDecline:!0,method:J.checkoutMethod??Ra}),up(J,ie)&&ie&&X.current&&Fe({sessionId:ie,errorMessage:J.message,nonce:M||void 0,payPalOrderId:J.orderId})}},[t,xe,tt,Be,pt]),Bt=(0,dt.useCallback)(async b=>{if(oe.onClick?.(b),!(b.defaultPrevented||ne||ke)){if(Fe(null),Ce(null),e&&Ze){let S=new lr.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Be(S),X.current&&(ue(null),be(null));return}if(!e&&!Ze){let S=new lr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Be(S),X.current&&(ue(null),be(null));return}Ie(!0),be(null),R(!1),ue("processing");try{let S=new Bi.PaymentAPI(xe);if(e){let Y=await S.getUnifiedCheckoutSession(e,t);await At(Y,e);return}try{let Y=await S.createAndFetchSession({...Ze});await At(Y,Y.data.session?.id??null,{fromCreateSession:!0})}catch(Y){if(Ja(Y)==="session_auto_completed"){await pt({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Y}}catch(S){await Be(no(dp(S,"Automatic payment failed. Please try again."),e))}finally{X.current&&(ue(null),be(null),Ie(!1))}}},[oe.onClick,Ze,ne,ke,t,At,xe,e,Be,pt]),gt=(0,dt.useCallback)(b=>{let S=Q.current;Fe(null),Ke.current?.({result:b,session:null,sessionId:S?.sessionId??null,autoCompleted:!1})},[]),St=(0,dt.useCallback)(b=>{st.current?.(b)},[]),$=(0,dt.useCallback)(b=>{Ne.current?.(b)},[]),ye=(0,dt.useMemo)(()=>(0,lr.resolveTheme)(P),[P]),Qe=(0,dt.useMemo)(()=>{let b=ye?.buttonsLayout??(0,lr.resolveButtonsLayoutTheme)(H);return I?{...b,...I,cardButton:{...b.cardButton,...I.cardButton}}:b},[ye,H,I]),Z=(0,dt.useMemo)(()=>{let b=ye?.appearance;return C?b?{...b,...C,variables:{...b.variables,...C.variables}}:C:b},[C,ye]),ze=Z?.variables,ft=ze?.colorPrimary??"#4A49FF",Ve=ze?.colorPrimaryHover??Zo(ft,.12),vt=ze?.borderRadius??"8px";return(0,sr.jsxs)(sr.Fragment,{children:[(0,sr.jsx)("button",{...oe,type:Ee,onClick:Bt,disabled:ne||ke,"aria-busy":ke,style:{width:"100%",...we===void 0?{boxSizing:"border-box",height:cp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Qe.cardButton,...Ns({themeBundle:ye,resolvedPrimaryColor:ft,resolvedBorderRadius:vt,submitButtonStyle:Qe.submitButton,explicitPrimaryColor:ze?.colorPrimary}),fontSize:Qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ne||ke?"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:ne||ke?.6:1,...We},onMouseEnter:b=>{oe.onMouseEnter?.(b),!b.defaultPrevented&&!ne&&!ke&&(ye||ze?.colorPrimary)&&(b.currentTarget.style.backgroundColor=Ve)},onMouseLeave:b=>{oe.onMouseLeave?.(b),!b.defaultPrevented&&(ye||ze?.colorPrimary)&&(b.currentTarget.style.backgroundColor=ft)},onMouseDown:b=>{oe.onMouseDown?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(0.985)")},onMouseUp:b=>{oe.onMouseUp?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(1)")},children:(0,sr.jsx)(Do,{content:we})}),Re&&(0,sr.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Re}),ge&&(0,sr.jsx)(Un,{status:ge,errorMessage:ae,authorized:_e}),V&&(0,sr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:b=>{b.target===b.currentTarget&&Fe(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,sr.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,sr.jsx)(Fi,{sessionId:V.sessionId,nonce:V.nonce,checkoutMode:"full",billingApiUrl:xe,locale:A,theme:P,...Z?{appearance:Z}:{},buttonsTheme:H,buttonsStyles:I,initialErrorMessage:V.errorMessage,initialPayPalOrderId:V.payPalOrderId,cardTitleContent:null,onComplete:gt,onError:St,onDecline:$})})})]})}var Oi=require("@flopay/js/card-setup"),Yn=require("@flopay/shared"),_t=require("react");var Vc={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function Di(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?Vc.dark:Vc.light,a=t.colorText??(r?"#F1F5F9":"#262833"),i=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:i?.color??a}}var Or=require("react/jsx-runtime"),Oa=class extends Yn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Zr(e,t={}){let n=e instanceof Yn.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 Oa(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 $c({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:i=null,onReady:c,onComplete:p,onDecline:u,onCancel:h,onValidation:v,onError:E}){let[T,w]=(0,_t.useState)(null),[x,A]=(0,_t.useState)(null),[P,C]=(0,_t.useState)(null),[H,I]=(0,_t.useState)(null),[se,j]=(0,_t.useState)(null),ee=(0,_t.useRef)(!1),we=(0,_t.useRef)(!1),ne=(0,_t.useMemo)(()=>typeof o=="object"?void 0:(0,Yn.resolveTheme)(o),[o]),Ee=(0,_t.useMemo)(()=>typeof o=="object"?o:ne?Qo({appearance:ne.appearance,buttonsStyles:ne.buttonsLayout,layout:"default"}):null,[ne,o]),We=(0,_t.useMemo)(()=>Ci(ne?.buttonsLayout.cardFormContainer,a),[ne,a]),oe=(0,_t.useMemo)(()=>ne?Di(ne):void 0,[ne]),xe=(0,_t.useRef)(c),Ze=(0,_t.useRef)(E),ke=(0,_t.useRef)(p),Ie=(0,_t.useRef)(u),ge=(0,_t.useRef)(h),ue=(0,_t.useRef)(v),ae=(0,_t.useRef)(!1),be=(0,_t.useRef)(!1),_e=(0,_t.useRef)(0);return xe.current=c,Ze.current=E,ke.current=p,Ie.current=u,ge.current=h,ue.current=v,(0,_t.useEffect)(()=>{let R=_e.current+1;return _e.current=R,()=>{queueMicrotask(()=>{_e.current===R&&(ae.current||be.current||(be.current=!0,Je(()=>{ge.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,_t.useEffect)(()=>{let R=!0,Re=new Oi.PaymentAPI((0,Yn.resolveBillingApiUrl)(n),{telemetry:r});return w(null),A(null),C(null),ae.current=!1,be.current=!1,(async()=>{try{if(!e.trim())throw new Yn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Yn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Ce=await Re.getUnifiedCheckoutSession(e,t);if(!R)return;let V=Ce.data.session;if(!V||!(0,Yn.isCardSetupCheckoutSession)(V))throw new Yn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Fe=V.vault;if(Fe?.html?.trim()||(Fe=await Re.getVaultCapture(e,t)),!Fe.html?.trim())throw new Yn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!R)return;A(Fe),w(new Oi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(Ce){if(!R)return;let V=Zr(Ce);ae.current=!0,C(V),Je(()=>Ze.current?.(V))}})(),()=>{R=!1,Re.destroy()}},[n,t,e,r]),(0,_t.useEffect)(()=>{if(!T)return;let R=!1;we.current=!1,ee.current=!1;let Re=T.on("submitting",()=>{ee.current=!0,j(null),I("processing")}),Ce=T.on("complete",X=>{ae.current=!0,ee.current=!1,I("success"),(async()=>(await new Promise(Le=>setTimeout(Le,600)),!we.current&&(we.current=!0,Je(()=>{ke.current?.({status:"succeeded",sessionId:e,...X.paymentMethod?{paymentMethod:X.paymentMethod}:{}})}),R||I(null))))()}),V=T.on("decline",X=>{ae.current=!0,ee.current=!1,j(X.message??null),I("error"),Je(()=>{Ie.current?.({status:"declined",sessionId:e,...X.declineReason?{reason:X.declineReason}:{},...X.message?{message:X.message}:{}})}),(async()=>(await new Promise(Le=>setTimeout(Le,400)),R||I(null)))()}),Fe=T.on("challenge_dismissed",()=>{I(null)});return()=>{R=!0,Re(),Ce(),V(),Fe()}},[T,e]),P?(0,Or.jsx)("div",{role:"alert",children:P.message}):!T||!x?.html?(0,Or.jsx)(Or.Fragment,{children:i}):(0,Or.jsxs)(Or.Fragment,{children:[H&&(0,Or.jsx)(Un,{status:H,errorMessage:se,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...oe?{theme:oe}:{}}),(0,Or.jsx)(uo,{capture:T,html:x.html,messageToken:x.messageToken,expectedOrigin:x.expectedOrigin,theme:Ee,containerStyle:We,onReady:()=>{Je(()=>xe.current?.())},onValidation:R=>{Je(()=>ue.current?.(R))},onError:R=>{if(!R)return;ee.current&&(ee.current=!1,j(R),I("error"),setTimeout(()=>I(null),400));let Re=Zr(new Error(R),{code:"card_setup_widget_failed",retryable:!0});Je(()=>Ze.current?.(Re))}})]})}var jc=require("@flopay/js/card-setup"),po=require("@flopay/shared"),Hc=require("@paypal/paypal-js"),wo=require("react");var Kc=require("react/jsx-runtime");function Wc({clientId:e,environment:t,currency:n,sessionId:r,nonce:o,billingApiUrl:a,telemetry:i,customer:{userId:c,email:p},onSubmitting:u,onConfirmed:h,onFailed:v,onAbandoned:E}){let T=(0,wo.useRef)(null),w=(0,wo.useRef)({onSubmitting:u,onConfirmed:h,onFailed:v,onAbandoned:E});w.current={onSubmitting:u,onConfirmed:h,onFailed:v,onAbandoned:E};let[x]=(0,wo.useState)(()=>Gr().inAppBrowser);return(0,wo.useEffect)(()=>{let A=!0,P,C=new jc.PaymentAPI(a,{telemetry:i}),H={userId:c,email:p};return(async()=>{try{let I=await(0,Hc.loadScript)({clientId:e,...n?{currency:n.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),se=T.current;if(!A||!se)return;if(!I?.Buttons)throw new po.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let j=I.Buttons({createVaultSetupToken:async()=>{w.current.onSubmitting();let ee=await C.createSessionIntent(r,o,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:po.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(ee.provider!=="paypal"||ee.providerObjectType!=="setup_token")throw new po.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return ee.providerObjectId},onApprove:async ee=>{let we=ee.vaultSetupToken;if(!we)throw new po.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let ne=await C.processPayment(H.userId,{sessionId:r,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:we,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:po.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:H});if(!ne.ok)throw new po.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:ne.status});A&&w.current.onConfirmed()},onCancel:()=>{A&&w.current.onAbandoned()},onError:ee=>{if(!A)return;let{popupBlocked:we}=io(ee,{inAppBrowser:x,handoffObserved:!1});w.current.onFailed(we?new Error(ao("PayPal",!0,x)):ee,{code:we?"popup_blocked":"paypal_setup_failed",retryable:!0})}});P=()=>j.close(),await j.render(se)}catch(I){if(!A)return;w.current.onFailed(I,{code:"paypal_unavailable",retryable:!0})}})(),()=>{A=!1,P?.().catch(()=>{}),C.destroy()}},[a,e,n,p,t,x,o,r,i,c]),(0,Kc.jsx)("div",{ref:T,"data-flopay-paypal-setup":""})}var Yc=require("@flopay/js/card-setup"),Li=require("@flopay/shared"),Lr=require("@stripe/react-stripe-js"),Xc=require("@stripe/stripe-js"),Mn=require("react");var Rn=require("react/jsx-runtime"),Jc={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"}},Ws=new Map;function mp(e){let t=Ws.get(e);if(t)return t;let n=(0,Xc.loadStripe)(e).catch(r=>{throw Ws.delete(e),r});return Ws.set(e,n),n}var yp={night:"night",flat:"flat"};function fp(e){return e?{theme:yp[e.theme??"default"]??"stripe",...e.variables?{variables:e.variables}:{},...e.rules?{rules:e.rules}:{}}:void 0}function gp(e){return bo(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function Gc(e){return e==="paypal"?"PayPal":(0,Li.getStripeMethodDisplayName)(e)}function hp(){return typeof window>"u"?"":window.location.href}var bp={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function Zc(e){let{publishableKey:t,method:n,currency:r,appearance:o}=e,[a]=(0,Mn.useState)(()=>mp(t)),i=(0,Mn.useMemo)(()=>{let c=fp(o);return{mode:"setup",currency:r.toLowerCase(),paymentMethodTypes:Jc[n]?.types??[n],...c?{appearance:c}:{}}},[o,r,n]);return(0,Rn.jsx)(Lr.Elements,{stripe:a,options:i,children:(0,Rn.jsx)(Pp,{...e})})}function Pp({method:e,category:t,sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,appearance:i,themeId:c,buttonsLayout:p,onSubmitting:u,onConfirmed:h,onDeclined:v,onFailed:E,onValidation:T,onUnavailable:w}){let x=(0,Lr.useStripe)(),A=(0,Lr.useElements)(),[P,C]=(0,Mn.useState)(!1),[H,I]=(0,Mn.useState)("loading"),[se,j]=(0,Mn.useState)(!1),[ee,we]=(0,Mn.useState)(!1),ne=(0,Mn.useRef)(!1),[Ee]=(0,Mn.useState)(()=>Gr()),[We,oe]=(0,Mn.useState)(!1),xe=(0,Mn.useCallback)((ae,be)=>{if(io(ae,{inAppBrowser:Ee.inAppBrowser,handoffObserved:!1}).popupBlocked){oe(!0),E(new Error(ao(Gc(e),!0,Ee.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}E(be.message===void 0?ae:new Error(be.message),{code:be.code,retryable:!0})},[Ee.inAppBrowser,e,E]),Ze=(0,Mn.useCallback)(async()=>{if(!(!x||!A||ne.current)){ne.current=!0,C(!0);try{let ae=await A.submit();if(ae.error){T(ae.error.message??null);return}u();let be=await new Yc.PaymentAPI(o,{telemetry:a}).createSessionIntent(n,r,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(be.provider!=="stripe"||be.intentKind!=="setup")throw new Li.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let _e=await x.confirmSetup({elements:A,clientSecret:be.clientSecret,confirmParams:{return_url:hp()},redirect:"if_required"});if(_e.error){gp(_e.error)?v({..._e.error.decline_code||_e.error.code?{reason:_e.error.decline_code??_e.error.code}:{},..._e.error.message?{message:_e.error.message}:{}}):xe(_e.error,{code:"payment_method_setup_provider_failed",message:_e.error.message??"The payment method could not be saved."});return}h()}catch(ae){xe(ae,{code:"payment_method_setup_failed"})}finally{ne.current=!1,C(!1)}}},[o,t,A,e,r,h,v,u,T,xe,n,x,a]),ke=Jc[e]?.wallet,Ie=ke==="paypal"&&Qa(Ee,"auto",We?"blocked":Ee.popupCapability)==="redirect",ge=i?.variables?.borderRadius??p?.cardButton?.borderRadius??8;if(t==="wallet"&&ke&&!Ie)return(0,Rn.jsxs)(Rn.Fragment,{children:[(0,Rn.jsx)(Jo,{}),(0,Rn.jsx)(Ea,{state:H,borderRadius:ge,children:(0,Rn.jsx)(Lr.ExpressCheckoutElement,{options:{...bi,paymentMethods:hi([e])},onReady:ae=>{let be=_a(ae,[ke]);I(be),be==="unavailable"&&w()},onLoadError:()=>{I("load_error"),w()},onConfirm:()=>{Ze()}})})]});let ue=Gc(e);return(0,Rn.jsxs)(Rn.Fragment,{children:[se?(0,Rn.jsx)(gi,{method:e,themeId:c,hasNextStep:!0,highlighted:ee,disabled:P,onClick:()=>we(ae=>!ae),backgroundColor:p?.cardButton?.backgroundColor,borderColor:p?.cardInputBorder,textColor:p?.cardButton?.color,borderRadius:ge}):null,(0,Rn.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!ee,style:ee?{display:"flex",flexDirection:"column"}:bp,children:[(0,Rn.jsx)(Lr.PaymentElement,{options:{layout:Pi},onReady:()=>j(!0),onLoadError:()=>w(),onChange:ae=>{ae.complete&&T(null)}}),(0,Rn.jsx)(vi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!x||!A||P||!ee,onClick:()=>{Ze()},color:i?.variables?.colorPrimary??"#4A49FF",borderRadius:i?.variables?.borderRadius??"8px",style:p?.submitButton,children:P?"Saving\u2026":`Save ${ue}`})]})]})}var La=require("@flopay/js/card-setup"),vn=require("@flopay/shared"),qe=os(require("react"),1);var Qc=require("@flopay/shared"),vp=new Set(["apple_pay","google_pay","link","paypal","amazon_pay"]),Cp=new Set(["wallet","apm"]);function ta(e){return typeof e=="string"&&e.trim().length>0}function Sp(e){if(typeof e!="object"||e===null)return!1;let t=e;return ta(t.family)&&ta(t.paymentMethodType)}function wp(e){let n=e.raw?.data?.currency;return ta(n)?n.trim().toUpperCase():null}function ed(e){let t=wp(e),n=e.data.session?.advertisedPaymentMethods;if(!Array.isArray(n))return{card:!0,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]};let r={card:!1,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]},o=new Set;for(let a of n){if(!Sp(a)||o.has(a.paymentMethodType))continue;let{family:i,paymentMethodType:c,providerType:p,publishableKey:u}=a;if(i==="card"){if(c!=="card")continue;r.card=!0}else if(Cp.has(i)){if(p!=="stripe"||c==="card"||!ta(u))continue;if(t===null){r.skippedForMissingCurrency.includes(c)||r.skippedForMissingCurrency.push(c);continue}r.stripe.push({method:c,publishableKey:u,currency:t})}else if(i==="paypal"){if(c!==Qc.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE||p!=="paypal"||!ta(u))continue;r.paypal={clientId:u,...ta(a.environment)?{environment:a.environment}:{}}}else continue;o.add(c)}return r.paypal&&(r.stripe=r.stripe.filter(a=>a.method!=="paypal")),r}function Ni(e){return[...e.card?["card"]:[],...e.stripe.map(t=>t.method),...e.paypal?["paypal"]:[]]}function td(e){return Ni(e).length>0}function zi(e){return vp.has(e)?"wallet":"apm"}var kp=["setup_intent","setup_intent_client_secret","redirect_status"];function nd(){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 rd(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let n of kp)e.searchParams.has(n)&&(e.searchParams.delete(n),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}function od(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 Zt=require("react/jsx-runtime"),Rp=15,Ip=2e3;function _p(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Ks(e){return new Promise(t=>setTimeout(t,e))}async function Ep(e,t,n){if(!t.trim())throw new vn.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!n.trim())throw new vn.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,vn.isCardSetupCheckoutSession)(o))throw new vn.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let a=ed(r);if(!td(a)){let{skippedForMissingCurrency:i}=a,c=i.length>0?`FloPay: this setup session advertises only Stripe methods (${i.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new vn.FloPayError(c,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:o,advertisement:a}}async function Tp(e,t,n,r){let o=t.vault??null;if(o?.html?.trim()||(o=await e.getVaultCapture(n,r)),!o.html?.trim())throw new vn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return o}var Ui=class extends qe.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 ad({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,theme:i="modern-light",containerStyle:c,loading:p=null,onReady:u,onComplete:h,onDecline:v,onCancel:E,onValidation:T,onError:w}){let[x]=(0,qe.useState)(nd),[A,P]=(0,qe.useState)(null),[C,H]=(0,qe.useState)(!1),[I,se]=(0,qe.useState)(null),[j,ee]=(0,qe.useState)(null),[we,ne]=(0,qe.useState)(null),[Ee,We]=(0,qe.useState)(null),[oe,xe]=(0,qe.useState)(()=>new Set),Ze=(0,qe.useRef)(oe),ke=(0,qe.useRef)(null);ke.current=A;let Ie=(0,qe.useRef)(!1),ge=(0,qe.useRef)(!1),ue=(0,qe.useRef)(!1),ae=(0,qe.useRef)(!1),be=(0,qe.useRef)(0),_e=(0,qe.useRef)(0),R=(0,qe.useRef)(!1),Re=(0,qe.useMemo)(()=>typeof i=="object"?void 0:(0,vn.resolveTheme)(i),[i]),Ce=(0,qe.useMemo)(()=>typeof i=="object"?i:Re?Qo({appearance:Re.appearance,buttonsStyles:Re.buttonsLayout,layout:"default"}):null,[Re,i]),V=(0,qe.useMemo)(()=>Ci(Re?.buttonsLayout.cardFormContainer,c),[Re,c]),Fe=(0,qe.useMemo)(()=>Re?Di(Re):void 0,[Re]),X=(0,qe.useRef)({sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:u,onComplete:h,onDecline:v,onCancel:E,onValidation:T,onError:w});X.current={sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:u,onComplete:h,onDecline:v,onCancel:E,onValidation:T,onError:w},(0,qe.useEffect)(()=>{R.current=!0;let y=be.current+1;return be.current=y,()=>{R.current=!1,_e.current+=1,queueMicrotask(()=>{be.current===y&&(ue.current||ae.current||(ae.current=!0,Je(()=>{X.current.onCancel?.({status:"cancelled",sessionId:n})})))})}},[n]);let Le=(0,qe.useCallback)((y,M)=>{ue.current=!0,Ie.current=!1,We({status:"success",wording:y,message:null}),(async()=>(await Ks(600),!ge.current&&(ge.current=!0,Je(()=>{X.current.onComplete?.({status:"succeeded",sessionId:X.current.sessionId,...M?{paymentMethod:M}:{}})}),R.current&&We(null))))()},[]),Q=(0,qe.useCallback)((y,M)=>{ue.current=!0,Ie.current=!1,We({status:"error",wording:y,message:M.message??null}),Je(()=>{X.current.onDecline?.({status:"declined",sessionId:X.current.sessionId,...M.reason?{reason:M.reason}:{},...M.message?{message:M.message}:{}})}),(async()=>(await Ks(400),R.current&&We(null)))()},[]),Ke=(0,qe.useCallback)((y,M)=>{Ie.current?(Ie.current=!1,We({status:"error",wording:y,message:M.message}),setTimeout(()=>{R.current&&We(null)},400)):We(null),Je(()=>X.current.onError?.(M))},[]),st=(0,qe.useCallback)(async y=>{let M=_e.current+1;_e.current=M;let De=()=>!R.current||M!==_e.current;Ie.current=!0,We({status:"processing",wording:"payment_method",message:null});let ie=new La.PaymentAPI((0,vn.resolveBillingApiUrl)(X.current.billingApiUrl),{telemetry:X.current.telemetry});try{for(let J=0;J<Rp;J+=1){if((J>0||y.waitFirst)&&await Ks(Ip),De())return;let le=await ie.getUnifiedCheckoutSession(X.current.sessionId,X.current.nonce);if(De())return;let lt=le.data.session?.status;if(lt==="complete"){H(!0),Le("payment_method");return}if(lt==="expired")throw new vn.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new vn.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(J){if(De())return;let le=J instanceof vn.FloPayError&&J.code==="payment_method_setup_unverified";Ke("payment_method",Zr(J,le?{retryable:!0}:{}))}finally{ie.destroy()}},[Ke,Le]);(0,qe.useEffect)(()=>{let y=!0,M=new La.PaymentAPI((0,vn.resolveBillingApiUrl)(o),{telemetry:a});P(null),H(!1),se(null),ee(null),ne(null);let De=new Set;return Ze.current=De,xe(De),ue.current=!1,ae.current=!1,ge.current=!1,(async()=>{try{let{session:ie,advertisement:J}=await Ep(M,n,r);if(!y)return;let le={advertisement:J,customer:_p(ie)};if(x){if(rd(),ie.status==="complete"){H(!0),P(le),Le("payment_method");return}x.failed?Q("payment_method",{reason:"redirect_failed"}):st({waitFirst:!0})}let lt=J.card?await Tp(M,ie,n,r):null;if(!y)return;P(le),lt&&(ee(lt),se(new La.PciVaultCardCapture({sessionId:n,operation:"card_setup",telemetry:a})))}catch(ie){if(!y)return;let J=Zr(ie);ue.current=!0,ne(J),Je(()=>X.current.onError?.(J))}})(),()=>{y=!1,M.destroy()}},[o,r,x,Q,Le,n,a,st]),(0,qe.useEffect)(()=>{if(!I)return;Ie.current=!1;let y=I.on("submitting",()=>{Ie.current=!0,We({status:"processing",wording:"card",message:null})}),M=I.on("complete",J=>{Le("card",J.paymentMethod)}),De=I.on("decline",J=>{Q("card",{...J.declineReason?{reason:J.declineReason}:{},...J.message?{message:J.message}:{}})}),ie=I.on("challenge_dismissed",()=>{We(null)});return()=>{y(),M(),De(),ie()}},[I,Q,Le]);let Ne=(0,qe.useCallback)((y,M,De)=>{if(De.retryable){Ke("payment_method",Zr(M,De));return}if(Ze.current.has(y))return;let ie=new Set(Ze.current);ie.add(y),Ze.current=ie,xe(ie);let J=ke.current?.advertisement,le=J?Ni(J).some(lt=>!ie.has(lt)):!1;Ke("payment_method",Zr(M,{code:De.code,retryable:le}))},[Ke]),tt=(0,qe.useMemo)(()=>({onSubmitting:()=>{Ie.current=!0,We({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{st({waitFirst:!1})},onDeclined:y=>Q("payment_method",y),onValidation:y=>{Je(()=>X.current.onValidation?.(y))},onAbandoned:()=>{Ie.current=!1,We(null)}}),[Q,st]),nt=(0,qe.useRef)(Ne);nt.current=Ne;let pt=(0,qe.useRef)(new Map),Be=y=>{let M=pt.current.get(y);if(M)return M;let De=(ie,J)=>nt.current(y,ie,J);return pt.current.set(y,De),De},At=(0,qe.useCallback)(y=>{if(Ze.current.has(y))return;let M=new Set(Ze.current);M.add(y),Ze.current=M,xe(M);let De=ke.current?.advertisement;De&&Ni(De).some(J=>!M.has(J))||Ke("payment_method",Zr(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[Ke]),Bt=(0,qe.useRef)(At);Bt.current=At;let gt=(0,qe.useRef)(new Map),St=y=>{let M=gt.current.get(y);if(M)return M;let De=()=>Bt.current(y);return gt.current.set(y,De),De},$=Ee?(0,Zt.jsx)(Un,{status:Ee.status,errorMessage:Ee.message,...od(Ee.wording),successNote:null,...Fe?{theme:Fe}:{}}):null;if(we)return(0,Zt.jsx)("div",{role:"alert",children:we.message});if(!A||C)return(0,Zt.jsxs)(Zt.Fragment,{children:[$,A?null:p]});let{advertisement:ye,customer:Qe}=A,Z=(0,vn.resolveBillingApiUrl)(o),ze=a===void 0?{}:{telemetry:a},ft=ye.stripe.filter(({method:y})=>!oe.has(y)),Ve=oe.has("paypal")?null:ye.paypal,vt=!!(ye.card&&I&&j?.html),G=({method:y,publishableKey:M,currency:De})=>(0,Zt.jsx)("div",{"data-flopay-payment-method":y,style:{display:"contents"},children:(0,Zt.jsx)(Ui,{onFailed:Be(y),children:(0,Zt.jsx)(qe.Suspense,{fallback:null,children:(0,Zt.jsx)(e,{method:y,category:zi(y),publishableKey:M,currency:De,sessionId:n,nonce:r,billingApiUrl:Z,...ze,...Re?{appearance:Re.appearance,buttonsLayout:Re.buttonsLayout}:{},...typeof i=="string"?{themeId:i}:{},...tt,onFailed:Be(y),onUnavailable:St(y)})})})},y),b=ft.filter(({method:y})=>zi(y)==="wallet"),S=ft.filter(({method:y})=>zi(y)!=="wallet"),Y=ft.length>0||Ve!==null;return(0,Zt.jsxs)(Zt.Fragment,{children:[$,Y?(0,Zt.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[b.map(G),Ve?(0,Zt.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,Zt.jsx)(Ui,{onFailed:Be("paypal"),children:(0,Zt.jsx)(qe.Suspense,{fallback:null,children:(0,Zt.jsx)(t,{clientId:Ve.clientId,...Ve.environment?{environment:Ve.environment}:{},...ye.currency?{currency:ye.currency}:{},sessionId:n,nonce:r,billingApiUrl:Z,customer:Qe,...ze,...tt,onFailed:Be("paypal"),onUnavailable:St("paypal")})})})}):null,S.map(G)]}):null,vt&&Y?(0,Zt.jsx)(Si,{label:"or add a card"}):null,vt&&I&&j?.html?(0,Zt.jsx)("div",{"data-flopay-payment-method":"card",children:(0,Zt.jsx)(uo,{capture:I,html:j.html,messageToken:j.messageToken,expectedOrigin:j.expectedOrigin,theme:Ce,containerStyle:V,onReady:()=>{Je(()=>X.current.onReady?.())},onValidation:y=>{Je(()=>X.current.onValidation?.(y))},onError:y=>{y&&Ke("card",Zr(new Error(y),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var sd=require("react/jsx-runtime"),Ap={StripeSetupMethod:Zc,PayPalSetupMethod:Wc};function id(e){return(0,sd.jsx)(ad,{...e,branches:Ap})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});