@flopay/react 1.9.27 → 1.9.29

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 Dc=Object.create;var Ea=Object.defineProperty;var Lc=Object.getOwnPropertyDescriptor;var Oc=Object.getOwnPropertyNames;var Nc=Object.getPrototypeOf,zc=Object.prototype.hasOwnProperty;var Uc=(e,t)=>{for(var n in t)Ea(e,n,{get:t[n],enumerable:!0})},Ys=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Oc(t))!zc.call(e,o)&&o!==n&&Ea(e,o,{get:()=>t[o],enumerable:!(r=Lc(t,o))||r.enumerable});return e};var Xs=(e,t,n)=>(n=e!=null?Dc(Nc(e)):{},Ys(t||!e||!e.__esModule?Ea(n,"default",{value:e,enumerable:!0}):n,e)),qc=e=>Ys(Ea({},"__esModule",{value:!0}),e);var wu={};Uc(wu,{DirectPayPalButton:()=>ta,FloPayAutomaticPaymentButton:()=>pc,FloPayCardSetup:()=>gc,FloPayCardSetupError:()=>ga,FloPayCheckout:()=>si,FloPayProvider:()=>ra,SplitCardForm:()=>ri,VaultCardFields:()=>xo,dropThirdPartyOnlyError:()=>hc.dropThirdPartyOnlyError,useCheckout:()=>cl,useFloPay:()=>zr,usePayPalFloPay:()=>Ba});module.exports=qc(wu);var hc=require("@flopay/shared");var li=require("@flopay/js"),tr=require("@flopay/shared"),et=require("react");var Lt=require("react/jsx-runtime");function $c(){return(0,Lt.jsxs)(Lt.Fragment,{children:[(0,Lt.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,Lt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Lt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Lt.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,Lt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function jc(){return(0,Lt.jsx)(Lt.Fragment,{children:"Go back"})}function Vc(){return(0,Lt.jsx)(Lt.Fragment,{children:"Secure card checkout"})}function fo(e){return e!==void 0&&(e===""||e===null||e===!1)}function go({content:e}){return(0,Lt.jsx)(Lt.Fragment,{children:e===void 0?(0,Lt.jsx)($c,{}):e})}function ho({content:e}){return(0,Lt.jsx)(Lt.Fragment,{children:e===void 0?(0,Lt.jsx)(jc,{}):e})}function Ko({content:e}){return(0,Lt.jsx)(Lt.Fragment,{children:e===void 0?(0,Lt.jsx)(Vc,{}):e})}var xt=require("@flopay/shared"),Wc="Checkout is temporarily unavailable. Please try again later.";function _i(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof xt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Hc(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 Js(){return new xt.FloPayError(Wc,"api_error",{code:"CheckoutInitializationFailed"})}function Ei(e){return!!e?.gateways?.worldpayCorporateGateway}function Vr(e){return e?.status==="open"&&Ei(e)}function Zs(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")||Vr(r))||t&&e?.data.paypal?.publishableKey)}function Qs(e,t){if(t&&(!(e instanceof xt.FloPayError)||e.type==="authentication_error"))return _i(e);if(!(e instanceof xt.FloPayError&&Hc(e))){if(!t&&!(e instanceof xt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,xt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof xt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof xt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function bo(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let l={...r,...a,email:a.email?.trim()||r.email?.trim()},d=(0,xt.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,xt.isValidEmail)(l.email))return Promise.reject(new xt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[f,h]of Object.entries(l)){if(d&&f.endsWith("Name")||typeof h!="string")continue;let b=h.trim();b&&(p[f]=b)}return o=e.claimCheckoutSession(t,n,{accountData:p}),o.catch(()=>{}),o}}function el(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 Ti(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 tl(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,l)=>a+(l.overrideAmount??l.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,l)=>({uuid:`synthetic-${a.type??"item"}-${l}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function Jr(e){if((0,xt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Ai(e,t){return t?{...e,...t}:e}function ln(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var Kc=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Wr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Kc)if(n.test(t))return r;return e}function Or(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Hr(e){return e?.status==="authorized"||e?.status==="complete"}function Zr(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 nl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Ta(e){let t=nl(e);return new xt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Aa(e){return e instanceof xt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Po(e){let t=nl(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new xt.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function Go(e,t){return e==="processing"||(0,xt.isMoneySettledOutcome)(e,t)}function rl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function ol(e,t){let n=e;if((0,xt.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:l}=await n.retrieveSetupIntent(t);if(l)throw new xt.FloPayError(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new xt.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function al(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 xi(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 Yo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var qr=require("@flopay/js"),He=require("@flopay/shared"),P=Xs(require("react"),1);var Mi=require("react"),Zn=(0,Mi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),ur=(0,Mi.createContext)({session:null,loading:!1,error:null});var Na=require("@flopay/js"),zt=require("@flopay/shared"),fl=require("@paypal/paypal-js"),I=require("react");var il=require("@flopay/shared"),pr=require("react"),Nr=require("react/jsx-runtime");function Bn(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),l=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...l||t?{lastName:l??""}:{}}}function vo(){let[e,t]=(0,pr.useState)(null),n=(0,pr.useRef)(null),r=(0,pr.useRef)(0),o=(0,pr.useCallback)((l,d)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:d}),new Promise(p=>{n.current=p})),[]),a=(0,pr.useCallback)(l=>{let d=n.current;n.current=null,t(null),d?.(l)},[]);return(0,pr.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Co({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,d]=(0,pr.useState)(e.email?.trim()??""),p=(0,il.isValidEmail)(l.trim());return(0,Nr.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,Nr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Nr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Nr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:f=>d(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Nr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Nr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Nr.jsxs)("button",{type:"button",disabled:!p||o,onClick:()=>{n(Bn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Gc=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),Yc=["https://www.paypal.com","https://www.sandbox.paypal.com"];function xa(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 sl(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Qr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function _r(e){if(typeof e!="object"||e===null)return;let t=e;return Qr(t.code)??Qr(t.type)??Qr(t.name)}function So(e){if(!(typeof e!="object"||e===null))return Qr(e.decline_code)}function Xo(e){return typeof e!="object"||e===null?!1:Qr(e.type)?.toLowerCase()==="card_error"||So(e)!==void 0}function Xc(e){let t=sl(e)?.toLowerCase()??"",n=_r(e)?.toLowerCase()??"";return Gc.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 Bi(e){if(_r(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=sl(e)??"";return n.includes("No ack for postMessage init()")&&Yc.some(r=>n.includes(r))&&n.includes("10000ms")}function Ma(e,t){if(Xo(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=Xc(e)||t.inAppBrowser&&!t.handoffObserved&&Bi(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function Kr(e){return Ma(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}var ll=require("@flopay/shared"),Jo=require("react");function zr(){return(0,Jo.useContext)(Zn).flopay}function Ba(){return(0,Jo.useContext)(Zn).paypalFlopay??null}function cl(){return(0,Jo.useContext)(ur)}function dl(){return(0,Jo.useContext)(Zn).billingApiUrl||(0,ll.resolveBillingApiUrl)()}function Zo(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 ul(e,t,n=e.popupCapability){return e.inAppBrowser||n==="blocked"||t==="prefer_redirect"?"redirect":"popup"}function Fa(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var pl=require("@flopay/shared"),to=require("react");function dt(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}var Da=require("react"),eo=typeof window>"u"?Da.useEffect:Da.useLayoutEffect;var Jc={"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 Zc(e){return e==="stripe"||e==="paypal"?e:void 0}function Qc(e){let t=Zc(e.provider),n={schemaVersion:pl.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Jc[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 Fi=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function wo(e,t){let n=(0,to.useRef)(e);n.current=e;let r=(0,to.useRef)(new Set),o=(0,to.useRef)(t),a=(0,to.useRef)(t);return eo(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,to.useCallback)(l=>{if(a.current!==t)return;let d=Qc(l);if(d){if(Fi.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}dt(()=>n.current?.(d))}},[t])}var ml=require("react"),Qo=(0,ml.createContext)(null);function La(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var ed=Symbol.for("@flopay/js.telemetry.bridge.v1"),td=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function nd(){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 rd(e){let t=nd(),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 Oa(e){let t=globalThis[td];return rd(t?.(e)??{})}function cn(e){if(e)return e[ed]}var dn=require("react");function ea(e,t){let n=(0,dn.useRef)(0),r=(0,dn.useRef)(null),o=(0,dn.useRef)(null),a=(0,dn.useRef)(e),l=(0,dn.useRef)(t?.onHandoffObserved);(0,dn.useEffect)(()=>{a.current=e,l.current=t?.onHandoffObserved},[e,t?.onHandoffObserved]);let d=(0,dn.useCallback)((v=o.current)=>{v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),p=(0,dn.useCallback)(v=>{d();let N=n.current+1;return n.current=N,r.current=null,o.current={generation:N,method:v,timer:null,yieldedControl:!1},N},[d]),f=(0,dn.useCallback)(v=>{let N=o.current;return v!==void 0&&N?.generation!==v?!1:(d(N),o.current=null,(v===void 0||r.current===v)&&(r.current=null),!0)},[d]),h=(0,dn.useCallback)(v=>{let N=o.current,re=v??N?.generation??n.current;(v===void 0||N?.generation===v)&&(d(N),o.current=null),r.current=re},[d]),b=(0,dn.useCallback)(v=>r.current===(v??n.current),[]),A=(0,dn.useCallback)(v=>o.current?.generation===v&&r.current!==v,[]),k=(0,dn.useCallback)(()=>{let v=o.current;v&&(d(v),!v.yieldedControl&&(v.yieldedControl=!0,l.current?.(v.method)))},[d]),S=(0,dn.useCallback)(()=>{let v=o.current;!v?.yieldedControl||document.visibilityState!=="visible"||(d(v),v.timer=setTimeout(()=>{v.timer=null,o.current?.generation===v.generation&&(o.current=null,r.current=v.generation,a.current(v.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[d]);return(0,dn.useEffect)(()=>{let v=()=>{document.visibilityState==="visible"?S():k()};return document.addEventListener("visibilitychange",v),window.addEventListener("blur",k),window.addEventListener("focus",S),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("blur",k),window.removeEventListener("focus",S),d()}},[d,k,S]),{startAttempt:p,finishAttempt:f,invalidateAttempt:h,isAttemptInvalidated:b,isAttemptCurrent:A,generationRef:n}}var Qn=require("react/jsx-runtime"),za=45,od=1e3,ad=11e3,id={width:"100%",minHeight:za,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},sd={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 ld(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:sd[e.kind]??null}}function yl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Bi(t)?"paypal_init_timeout":"paypal_init_failure"}function cd(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 dd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function gl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:d,currency:p,isSubscription:f,providerObjectType:h,approvalPresentation:b,onTokenizedBody:A,onComplete:k,onErrorChange:S,onDecline:v,onTechnicalFailure:N,isProcessing:re=!1,onLoadStateChange:T,onInitializationStateChange:G,allowAutomaticRetry:$=!0,onButtonClick:de,runBeforeButtonClick:Y,session:fe,existingOrderId:De,telemetry:ne,telemetryContext:$e,onInstrument:ft,debug:te=!1}){let Le=zr(),gt=wo(ft,e),Re=(0,I.useMemo)(()=>{if(Le)return null;let F=Oa({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:zt.SDK_VERSION,enabled:ne!==!1});return F.setCheckoutContext($e??{}),F.beginCheckout($e??{}),F},[n,Le,ne,$e?.checkoutMode,$e?.layout]),Oe=(0,I.useMemo)(()=>cn(Le),[Le]);(0,I.useEffect)(()=>()=>{Re&&Re.flush().catch(()=>{}).finally(()=>Re.destroy())},[Re]);let ge=(0,I.useMemo)(()=>({error:F=>{Oe?Oe.error(F):Re?.error(F),gt({class:"technical_error",errorCode:F.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":F.errorCode,requestCategory:F.requestCategory,provider:F.provider})},log:F=>{Oe?Oe.log(F):Re?.log(F),gt({class:"lifecycle",name:F.name,provider:F.provider})},performance:F=>{Oe?Oe.performance(F):Re?.performance(F)},terminal:F=>{Oe?Oe.terminal(F):Re?.terminal(F)},startTiming:()=>Oe?.now()??Re?.now()??0,elapsed:F=>Oe?.elapsed(F)??Math.max(0,(Re?.now()??F)-F)}),[gt,Oe,Re]),pe=(0,I.useRef)(null),_e=(0,I.useRef)(0),je=(0,I.useRef)(null),ot=(0,I.useRef)(null),R=(0,I.useRef)(null),Se=(0,I.useContext)(Qo),ae=(0,I.useRef)(null);ae.current||(ae.current=La());let O=Se??ae.current,xe=(0,I.useRef)(null),we=(0,I.useRef)(!1),[Ue,Z]=(0,I.useState)(!1),[at,it]=(0,I.useState)(!1),[Fe,ke]=(0,I.useState)(0),Ze=(0,I.useRef)(0),[Pt,Ke]=(0,I.useState)(!1),tn=(0,I.useRef)(!1),qt=(0,I.useRef)(!1),[ut,lt]=(0,I.useState)(!1),[z,be]=(0,I.useState)(!1),{request:Ve,collect:W,finish:Ge}=vo(),wt=(0,I.useRef)({sessionId:e,required:!(0,zt.isValidEmail)(r?.trim()||fe?.customer?.email?.trim())});wt.current.sessionId!==e&&(wt.current={sessionId:e,required:!(0,zt.isValidEmail)(r?.trim()||fe?.customer?.email?.trim())});let Ye=wt.current.required,u=(0,I.useMemo)(()=>n.replace(/\/+$/,""),[n]),V=fe?.gateways?.paypal?.providerObjectType??h,w=V??(f?"subscription":"order"),[X]=(0,I.useState)(Zo),qe=fe?.gateways?.paypal?.approvalPresentation??b,Pe=Fa(X,qe==="app_switch"?"app_switch":void 0,w),st=V==="order"||V==="setup_token",tt=(0,I.useMemo)(()=>JSON.stringify([u,l,p,d??"",w,st,Pe,e,De??""]),[u,l,p,d,De,w,st,Pe,e]),me=(0,I.useRef)(tt),pt=me.current!==tt,_t=(0,I.useRef)(te),Pn=(0,I.useRef)(null),[nt,$t]=(0,I.useState)([]),Ne=(0,I.useCallback)(F=>{_t.current&&$t(Xe=>[...Xe,`${new Date().toISOString().slice(11,23)} ${F}`])},[]);(0,I.useEffect)(()=>{_t.current=te,te&&Ne("debug:enabled"),Pn.current?.setEnabled(te)},[Ne,te]);let Fn=(0,I.useRef)(A),Rn=(0,I.useRef)(k),Mt=(0,I.useRef)(S),wn=(0,I.useRef)(v),Dn=(0,I.useRef)(N),Ln=(0,I.useRef)(de),nn=(0,I.useRef)(T),ve=(0,I.useRef)(G),vt=(0,I.useRef)(a),Et=(0,I.useRef)(Y),vn=(0,I.useRef)(fe),Bt=(0,I.useRef)(r),Vn=(0,I.useRef)(o),un=(0,I.useRef)(t),jt=(0,I.useRef)(null),on=(0,I.useRef)(new Map),Wn=(0,I.useRef)(new Map),pn=(0,I.useRef)(!1);(0,I.useEffect)(()=>(pn.current=!0,()=>{pn.current=!1}),[]),(0,I.useEffect)(()=>{Fn.current=A},[A]),(0,I.useEffect)(()=>{vt.current=a},[a]),(0,I.useEffect)(()=>{Rn.current=k},[k]),(0,I.useEffect)(()=>{Mt.current=S},[S]),(0,I.useEffect)(()=>{wn.current=v},[v]),(0,I.useEffect)(()=>{Dn.current=N},[N]),(0,I.useEffect)(()=>{Ln.current=de},[de]),(0,I.useEffect)(()=>{nn.current=T},[T]),(0,I.useEffect)(()=>{ve.current=G},[G]),(0,I.useEffect)(()=>{Et.current=Y},[Y]),(0,I.useEffect)(()=>{vn.current=fe},[fe]),(0,I.useEffect)(()=>{Bt.current=r},[r]),(0,I.useEffect)(()=>{Vn.current=o},[o]),(0,I.useEffect)(()=>{un.current=t},[t]),(0,I.useEffect)(()=>{Ze.current=Fe},[Fe]),(0,I.useEffect)(()=>{Pt&&xe.current?.focus()},[Pt,Fe]);let Ct=(0,I.useCallback)(()=>{window.setTimeout(()=>{xe.current?.focus()},0)},[]),Xt=(0,I.useCallback)(()=>{Z(!1),ke(F=>F+1)},[]),mn=(0,I.useCallback)(()=>{Ke(!1),(pe.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??pe.current)?.focus?.()},[]);(0,I.useEffect)(()=>{!Ue||!we.current||(we.current=!1,mn())},[mn,Ue,Fe]);let Ft=(0,I.useCallback)((F,Xe)=>{let se=Xe?.popupBlocked??Kr(F);se&&O.markBlocked();let Hn=xa("PayPal",se,X.inAppBrowser),fn=Dn.current;if(fn){let Wt=se&&X.inAppBrowser?new zt.FloPayError(Hn,"api_error",{code:Xe?.code??"paypal_popup_blocked"}):F;fn("paypal",Wt,Xe);return}Mt.current?.(Hn)},[O,X.inAppBrowser]),Jt=(0,I.useCallback)(F=>{let Xe=je.current,se=ot.current;Xe===null||!se||(ge.log({...se,popupCapability:O.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:F}),ge.performance({...se,popupCapability:O.current(),stage:"overlay_return",durationMs:ge.elapsed(Xe),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:F}),je.current=null)},[O,ge]),Vt=(0,I.useCallback)((F,Xe,se)=>{let Hn=ot.current;Jt("overlay_timeout"),Hn&&ge.error({...Hn,popupCapability:O.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Ft(Xe,{...se,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Pe,terminalReason:"overlay_timeout"}),Ke(!0),Xt(),Ct()},[Jt,Ct,Ft,O,Pe,Xt,ge]),yn=(0,I.useCallback)(()=>{O.markAvailable();let F=ot.current;F&&(R.current=F.attempt,ge.log({...F,popupCapability:O.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[O,ge]),{finishAttempt:ht,generationRef:Q,invalidateAttempt:On,isAttemptCurrent:Nn,isAttemptInvalidated:hr,startAttempt:Cn}=ea(Vt,{onHandoffObserved:yn}),an=(0,I.useCallback)(()=>(Ke(!1),Cn("paypal")),[Cn]),_n=(0,I.useCallback)(F=>{On(F?.generation),F?.showRetry&&Ke(!0),F?.remount&&Xt(),F?.focus!==!1&&Ct()},[Ct,On,Xt]),Ee=F=>{let Xe=jt.current;return Xe&&Wn.current.set(F,Xe),F};(0,I.useEffect)(()=>{me.current!==tt&&(me.current=tt,tn.current=!1,qt.current=!1,Z(!1),it(!1),lt(!1),ve.current?.("loading"))},[tt]),(0,I.useEffect)(()=>{dt(()=>nn.current?.(Ue&&!ut))},[Ue,ut]);let bt=(0,zt.normalizeGatewayEnvironment)(d);(0,I.useEffect)(()=>{let F={attempt:Q.current+1,inAppBrowser:X.inAppBrowser,appFamily:X.appFamily,popupCapability:O.current(),presentationMode:Pe},Xe=()=>({...ot.current??F,popupCapability:O.current()}),se={error:m=>ge.error({...m,...Xe()}),log:m=>ge.log({...m,...Xe()}),performance:m=>ge.performance({...m,...Xe()}),terminal:m=>ge.terminal({...m,...Xe()}),startTiming:ge.startTiming,elapsed:ge.elapsed},Hn=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",fn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Ne(`mount clientId=${Hn} env=${d??"(unset)"}\u2192${bt??"live"} ccy=${p} sub=${f}`),Ne(`ua=${fn.slice(0,80)}${fn.length>80?"\u2026":""}`),!l){Ne("FAIL: clientId empty \u2014 gateway misconfigured"),lt(!0),se.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(!pe.current){Ne("FAIL: containerRef not attached");return}_e.current=se.startTiming(),se.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Wt=!1,Kn=!1,rt=()=>Wt||Kn,$r,Ht=!1,gn=()=>{$r=(0,zt.generateIdempotencyKey)(),$r||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Ht=!0},Mr=null,Br=!1,En=null,Zt=!1,br=()=>{!En||Zt||(Zt=!0,En.close().catch(()=>{}))},Tn=!1,Fr=!1,An=pe.current,Pr=null,vr=null,nr=[],Gn=null,Yn=!1,At=!1,rr=null,kn=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let g=m.getBoundingClientRect();return`${Math.round(g.width)}\xD7${Math.round(g.height)}`},Xn=m=>{if(!m)return"(empty)";try{let g=new URL(m,typeof window>"u"?"https://localhost":window.location.href),D=g.pathname.toLowerCase();return D.includes("checkcaptcha")||D.includes("captcha")?`CAPTCHA(${g.host}${D})`:D.includes("risk")||D.includes("challenge")?`RISK(${g.host}${D})`:D.includes("smart/buttons")?`smart-buttons(${g.host})`:`${g.host}${D}`.slice(0,100)}catch{return m.slice(0,80)}},Cr=m=>{let g=m.getAttribute("src"),D=m.getAttribute("srcdoc"),q=m.getAttribute("name"),ce=m.getAttribute("sandbox"),J=[];return g&&J.push(`src=${Xn(g)}`),D&&J.push(`srcdoc[${D.length}ch]`),!g&&!D&&J.push("src=(empty) srcdoc=(empty)"),q&&J.push(`name=${q.slice(0,40)}`),ce!==null&&J.push(`sandbox="${ce.slice(0,40)}"`),J.join(" ")},ct=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let g=m.contentDocument;if(!g)return"cd=null";let D=g.body?.children.length??0,q=g.body?.innerHTML.length??0,ce=g.head?.innerHTML.length??0;return`cd=same-origin readyState=${g.readyState} body[${D}children,${q}ch] head[${ce}ch]`}catch(g){return`cd=cross-origin(${g.message.slice(0,30)})`}},rn=[],Qt=m=>{if(rt())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"))&&(Ne(`window:error ${g.slice(0,140)}`),rn.push(g))},Dr=m=>{if(rt())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"))&&(Ne(`window:rejection ${g.slice(0,140)}`),rn.push(g))},zn={value:0},jr=()=>{Pr?.disconnect(),Pr=null,vr?.disconnect(),vr=null;for(let m of nr.splice(0))clearTimeout(m);At=!1,Yn&&typeof window<"u"&&(window.removeEventListener("error",Qt),window.removeEventListener("unhandledrejection",Dr)),Yn=!1},or=()=>{if(!(Yn||rt()||Tn)){if(Yn=!0,rn.length=0,zn.value=0,typeof window<"u"&&(window.addEventListener("error",Qt),window.addEventListener("unhandledrejection",Dr)),typeof PerformanceObserver<"u")try{vr=new PerformanceObserver(m=>{if(!rt())for(let g of m.getEntries()){if(!g.name.toLowerCase().includes("paypal"))continue;zn.value+=1;let D=Math.round(g.duration);Ne(`net ${D}ms ${g.name.slice(0,90)}`)}}),vr.observe({type:"resource",buffered:!0})}catch{}rr?.()}},ar=()=>{Gn&&(clearTimeout(Gn),Gn=null)},hn=()=>{jr(),ar()},ir={setEnabled:m=>{m?or():jr()}};Pn.current=ir,_t.current&&or();let Lr=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")},In=m=>{if(rt()||Lr(m))return;let g=Wr(m)??m;dt(()=>Mt.current?.(g))},x=(m,g)=>{if(Wt||Br)return;Br=!0,Kn=!0,hn(),br();let D=ld({kind:m,generationActive:!0,automaticRetryAllowed:$,automaticRetryUsed:tn.current});if(D.action==="retry"){tn.current=!0,Z(!1),be(!1),it(!0),ve.current?.("retrying"),Mr=setTimeout(()=>{Wt||ke(q=>q+1)},od);return}if(Z(!1),be(!1),it(!1),lt(!0),D.action!=="ignore"){if(ve.current?.("exhausted"),D.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",g);return}if(D.report){let q=Ma({code:yl(m,g),message:g},{inAppBrowser:X.inAppBrowser,handoffObserved:!1});q.popupBlocked&&O.markBlocked(),se.error({errorCode:q.popupBlocked?q.errorCode:D.report.errorCode,stage:D.report.stage,operationOutcome:D.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:q.terminalReason})}qt.current||(qt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",yl(m,g)))}};lt(!1);let L=async(m,g=jt.current)=>{if(rt())return;let D=g?.sessionId??e;if(Fn.current){await Fn.current(m,{sessionId:D,accountPatch:g?.accountPatch,nonce:g?.nonce});return}let q=se.startTiming();se.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ce=()=>{se.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),se.performance({stage:"processing",durationMs:se.elapsed(q),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let J=vn.current,We=g?.accountPatch?.email??Bt.current,kt=g?.accountPatch?.userId??J?.customer?.id??J?.accountData?.userId??"",E=g?.accountPatch?.firstName??J?.customer?.firstName??J?.accountData?.firstName,he=g?.accountPatch?.lastName??J?.customer?.lastName??J?.accountData?.lastName,ye=await new Na.PaymentAPI(u,{telemetry:!1}).processPayment(kt,{sessionId:D,nonce:g?.nonce??un.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:kt,email:We??J?.customer?.email??"",...E?{firstName:E}:{},...he?{lastName:he}:{},country:g?.accountPatch?.country??J?.customer?.country??J?.accountData?.country??void 0,zip:g?.accountPatch?.zip??J?.customer?.zip??J?.accountData?.zip??void 0}});if(ye.ok){if(Kn||Wt&&pn.current)return;ce(),se.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),dt(()=>Rn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(rt())return;let j=await ye.json().catch(()=>null),oe=j?.message??"PayPal payment failed.",_=Wr(oe)??oe;ce(),ye.status===400&&(typeof j?.declineCode=="string"||!Array.isArray(j?.fields))?se.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ye.status===400||ye.status===422?se.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):se.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:dd(ye.status),failureCategory:ye.status>=500?"server_error":void 0}),In(_),dt(()=>wn.current?.(ln("paypal",_,{code:j?.code,declineCode:j?.declineCode})));return}catch(J){if(rt())return;ce(),se.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let We=J instanceof Error?J.message:"PayPal payment failed.",kt=Wr(We)??We;In(kt),dt(()=>wn.current?.(ln("paypal",kt)));return}},B=()=>new zt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),le=m=>rt()?Promise.reject(B()):Promise.resolve(m),Me=async m=>{if(rt())throw B();Ht||gn();let g=jt.current,D=g?.sessionId??e,q=g?.nonce??un.current;se.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ce;try{ce=await new Na.PaymentAPI(u,{telemetry:!1}).createSessionIntent(D,q??"",st?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:zt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:w==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:$r})}catch(J){throw se.error({...(0,zt.classifyTelemetryFailure)(J,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),J}if(rt())throw B();if(ce.provider!=="paypal"||ce.providerObjectType!==w)throw new Error(m);return se.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ce.providerObjectId},mt=(m,g)=>{let D=g?.nonce??un.current;if(!D)return;let q=g?.sessionId??e,ce=So(m)??_r(m)??"provider_declined";new Na.PaymentAPI(u,{telemetry:!1}).reportSessionIntentDecline(q,D,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ce}).catch(()=>{})},ue=Fe;Ne("loadScript:scheduled (deferred 1 tick)");let Be=null,H=setTimeout(()=>{if(Wt){Ne("loadScript:skipped (cancelled before defer ran)");return}Ne("loadScript:start");let m=bt==="live"?"production":bt,g={};w==="subscription"?g={intent:"subscription",vault:!0}:w==="order"&&(g={intent:"capture"}),Be=(0,fl.loadScript)({clientId:l,currency:p,...g,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let D=!1;Be.then(q=>{if(D=!0,Ne(`loadScript:resolved inactive=${rt()} ns=${!!q} buttons=${!!q?.Buttons}`),rt())return;if(!q?.Buttons){Ne("FAIL: namespace missing Buttons factory"),x("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}se.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),se.performance({stage:"provider_ready",durationMs:se.elapsed(_e.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),se.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let ce=async(ye,j)=>{if(rt()||Ze.current!==ue)return;let oe=ye.vaultSetupToken??ye.subscriptionID??ye.orderID??"",_=oe?Wn.current.get(oe):on.current.get(ue);if(!(!_||!Nn(_.generation))&&ht(_.generation)){Wn.current.delete(oe),on.current.delete(_.surfaceKey),Jt("approved");try{if(be(!0),dt(()=>Mt.current?.(null)),!oe)throw new zt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ze=vn.current,It=Jr(Vn.current??[ze?.customer?.firstName,ze?.customer?.lastName].filter(Boolean).join(" ")),Te=Bn({email:_.accountPatch?.email?.trim()||Bt.current?.trim()||ze?.customer?.email?.trim(),firstName:_.accountPatch?.firstName?.trim()||It.firstName,lastName:_.accountPatch?.lastName?.trim()||It.lastName});if(!(0,zt.isValidEmail)(Te.email)||!(Te.firstName||Te.lastName))try{let Sr=cd(await j?.order?.get?.());Te=Bn({email:Sr.email||Te.email,firstName:Sr.firstName||Te.firstName,lastName:Sr.lastName||Te.lastName})}catch{}if((vt.current||Ye)&&!(0,zt.isValidEmail)(Te.email)){let Sr=await W("PayPal",Te);if(!Sr)return;Te=Sr}(0,zt.isValidEmail)(Te.email)&&(_.accountPatch=Bn({..._.accountPatch,...Te}),await vt.current?.(Te));let Sn;w==="setup_token"?Sn={id:oe,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:zt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:st?Sn={id:oe,isPaypal:!0,gateway:"paypal",paymentMethodType:zt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Sn={id:oe,isPaypal:!0},await L(Sn,_)}catch(ze){In(ze instanceof Error?ze.message:"PayPal capture failed.")}finally{rt()||be(!1)}}},J=ye=>{let j=De?()=>le(De):()=>Me(ye);return async()=>Ee(await j())},We=q.Buttons({style:{layout:"horizontal",height:za,tagline:!1},...Pe==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ye,j)=>{if(rt()){await j.reject();return}gn();let oe=Et.current,_={};if(oe)try{let Te=await oe("paypal");if(rt()){await j.reject();return}if(!Te.proceed){jt.current=null,on.current.delete(ue),await j.reject();return}_={sessionId:Te.sessionId,accountPatch:Te.accountPatch,nonce:Te.nonce}}catch(Te){Ne(`onClick:runBeforeButtonClick rejected msg=${(Te instanceof Error?Te.message:String(Te)).slice(0,120)}`),jt.current=null,on.current.delete(ue),await j.reject();return}dt(()=>Ln.current?.("paypal"));let ze=an(),It={generation:ze,surfaceKey:ue,..._};jt.current=It,on.current.set(ue,It),ot.current={...F,attempt:ze},await j.resolve(),se.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),se.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),je.current=se.startTiming()},createOrder:w==="order"?J("Failed to create PayPal order."):void 0,createSubscription:w==="subscription"?J("Failed to create PayPal subscription."):void 0,createVaultSetupToken:w==="setup_token"?async()=>Ee(await Me("Failed to create PayPal setup token.")):void 0,onApprove:ce,onCancel:()=>{if(rt())return;let ye=on.current.get(ue)??jt.current;ye&&on.current.delete(ye.surfaceKey),jt.current=null,Jt("cancelled"),se.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we.current=!0,_n({generation:ye?.generation,remount:!0,focus:!1})},onError:ye=>{if(rt()||Ze.current!==ue)return;let j=ye instanceof Error?ye.message:"PayPal failed to render.";if(Ne(`onError rendered=${Tn} msg=${j.slice(0,120)}`),Tn){let oe=on.current.get(ue)??jt.current;if(oe&&!Nn(oe.generation)||!oe&&hr())return;if(Lr(j)){ht(oe?.generation);return}let{errorCode:_,popupBlocked:ze,providerDeclined:It,terminalReason:Te}=Ma(ye,{inAppBrowser:X.inAppBrowser,handoffObserved:oe!=null&&R.current===oe.generation});if(ze&&O.markBlocked(),Jt(Te),It){se.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Te}),mt(ye,oe),dt(()=>wn.current?.(ln("paypal",j))),oe&&on.current.delete(oe.surfaceKey),jt.current=null,ht(oe?.generation);return}se.error({errorCode:_,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Te}),oe&&on.current.delete(oe.surfaceKey),jt.current=null,_n({generation:oe?.generation,remount:!0,showRetry:!0,focus:!0}),Ft(ye,{code:"paypal_runtime_failed",popupBlocked:ze,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Pe,terminalReason:Te});return}x(Lr(j)?"teardown":"pre_ready_callback",j)}}),kt=We.isEligible();if(Ne(`isEligible=${kt}`),se.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!kt){Z(!1),x("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Fr=!0,En=We,rr=()=>{if(!Yn||At||rt()||Tn)return;At=!0,Ne(`container:dims ${kn(An)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Pr=new MutationObserver(j=>{if(!rt()){for(let oe of j)if(oe.type==="childList")oe.addedNodes.forEach(_=>{if(!(_ instanceof Element))return;let ze=_.tagName.toLowerCase(),It=(_.getAttribute("title")??"").slice(0,40),Te=ze==="iframe"?` ${Cr(_)}`:"";Ne(`child+ ${ze}${It?` title="${It}"`:""}${Te} dims=${kn(_)}`)});else if(oe.type==="attributes"&&oe.target instanceof Element){let _=oe.target;if(_.tagName.toLowerCase()!=="iframe")continue;let ze=oe.attributeName;(ze==="src"||ze==="srcdoc")&&Ne(`attr~ iframe ${ze}=${ze==="srcdoc"?`[${(_.getAttribute("srcdoc")??"").length}ch]`:Xn(_.getAttribute("src"))} dims=${kn(_)}`)}}}),Pr.observe(An,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ye=j=>{if(rt()||Tn)return;let oe=An.querySelectorAll("iframe"),_=typeof document<"u"&&"hasStorageAccess"in document;Ne(`watchdog:${j} container=${kn(An)} children=${An.childElementCount} iframes=${oe.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${_} paypalNetRequests=${zn.value}`),oe.forEach((ze,It)=>{let Te=(ze.getAttribute("title")??"").slice(0,40);Ne(` iframe[${It}] ${kn(ze)}${Te?` title="${Te}"`:""} ${Cr(ze)}`);let Sn=ct(ze);Sn&&Ne(` ${Sn}`)}),rn.length===0&&Ne(" (no PayPal/zoid window errors captured)")};nr.push(setTimeout(()=>ye("3s"),3e3)),nr.push(setTimeout(()=>ye("8s"),8e3)),nr.push(setTimeout(()=>ye("15s"),15e3))},rr(),Ne("render:start");let he=se.startTiming();Gn=setTimeout(()=>{rt()||Tn||(Ne("watchdog:11s retryable render timeout"),x("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},ad);let Tt=We.render(An);(async()=>{try{if(await Tt,Ne(`render:resolved inactive=${rt()}`),hn(),rt()){br();return}Tn=!0,Z(!0),it(!1),ve.current?.("ready"),se.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),se.performance({stage:"checkout_render",durationMs:se.elapsed(he),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ye){let j=ye instanceof Error?ye.message:"PayPal failed to render.";Ne(`render:rejected msg=${j.slice(0,120)}`),hn(),x(Lr(j)?"teardown":"render_rejected",j)}})()}).catch(q=>{let ce=q instanceof Error?q.message:"PayPal operation failed.";Ne(`provider:failed msg=${ce.slice(0,120)}`);let J="script_rejected";D&&Lr(ce)?J="teardown":D&&Fr&&(J="render_rejected"),x(J,ce)})},0);return()=>{Wt=!0,clearTimeout(H),Mr&&clearTimeout(Mr),hn(),Pn.current===ir&&(Pn.current=null),br(),je.current=null,ot.current=null}},[$,u,l,p,d,w,Pe,st,e,De,Fe,ge,W,Ye,Ne,Jt]);let ie=te?(0,Qn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ut?"#fef2f2":"#f3f4f6",border:`1px solid ${ut?"#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=${Ue} failed=${ut})`,nt.length===0?`
1
+ "use strict";var Dc=Object.create;var Ea=Object.defineProperty;var Oc=Object.getOwnPropertyDescriptor;var Lc=Object.getOwnPropertyNames;var Nc=Object.getPrototypeOf,zc=Object.prototype.hasOwnProperty;var Uc=(e,t)=>{for(var n in t)Ea(e,n,{get:t[n],enumerable:!0})},Xs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Lc(t))!zc.call(e,o)&&o!==n&&Ea(e,o,{get:()=>t[o],enumerable:!(r=Oc(t,o))||r.enumerable});return e};var Js=(e,t,n)=>(n=e!=null?Dc(Nc(e)):{},Xs(t||!e||!e.__esModule?Ea(n,"default",{value:e,enumerable:!0}):n,e)),qc=e=>Xs(Ea({},"__esModule",{value:!0}),e);var wu={};Uc(wu,{DirectPayPalButton:()=>na,FloPayAutomaticPaymentButton:()=>pc,FloPayCardSetup:()=>gc,FloPayCardSetupError:()=>ga,FloPayCheckout:()=>si,FloPayProvider:()=>oa,SplitCardForm:()=>ri,VaultCardFields:()=>Mo,dropThirdPartyOnlyError:()=>hc.dropThirdPartyOnlyError,useCheckout:()=>dl,useFloPay:()=>Ur,usePayPalFloPay:()=>Ba});module.exports=qc(wu);var hc=require("@flopay/shared");var li=require("@flopay/js"),nr=require("@flopay/shared"),Qe=require("react");var Lt=require("react/jsx-runtime");function $c(){return(0,Lt.jsxs)(Lt.Fragment,{children:[(0,Lt.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,Lt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Lt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Lt.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,Lt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function jc(){return(0,Lt.jsx)(Lt.Fragment,{children:"Go back"})}function Vc(){return(0,Lt.jsx)(Lt.Fragment,{children:"Secure card checkout"})}function go(e){return e!==void 0&&(e===""||e===null||e===!1)}function ho({content:e}){return(0,Lt.jsx)(Lt.Fragment,{children:e===void 0?(0,Lt.jsx)($c,{}):e})}function bo({content:e}){return(0,Lt.jsx)(Lt.Fragment,{children:e===void 0?(0,Lt.jsx)(jc,{}):e})}function Go({content:e}){return(0,Lt.jsx)(Lt.Fragment,{children:e===void 0?(0,Lt.jsx)(Vc,{}):e})}var Pt=require("@flopay/shared"),Wc="Checkout is temporarily unavailable. Please try again later.";function _i(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Pt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Hc(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function Zs(){return new Pt.FloPayError(Wc,"api_error",{code:"CheckoutInitializationFailed"})}function Ei(e){return!!e?.gateways?.worldpayCorporateGateway}function Wr(e){return e?.status==="open"&&Ei(e)}function Qs(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")||Wr(r))||t&&e?.data.paypal?.publishableKey)}function el(e,t){if(t&&(!(e instanceof Pt.FloPayError)||e.type==="authentication_error"))return _i(e);if(!(e instanceof Pt.FloPayError&&Hc(e))){if(!t&&!(e instanceof Pt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,Pt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Pt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Pt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Po(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let l={...r,...a,email:a.email?.trim()||r.email?.trim()},d=(0,Pt.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,Pt.isValidEmail)(l.email))return Promise.reject(new Pt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let u={};for(let[p,b]of Object.entries(l)){if(d&&p.endsWith("Name")||typeof b!="string")continue;let v=b.trim();v&&(u[p]=v)}return o=e.claimCheckoutSession(t,n,{accountData:u}),o.catch(()=>{}),o}}function tl(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 Ti(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 nl(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,l)=>a+(l.overrideAmount??l.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,l)=>({uuid:`synthetic-${a.type??"item"}-${l}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function eo(e){if((0,Pt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Ai(e,t){return t?{...e,...t}:e}function cn(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var Kc=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Hr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Kc)if(n.test(t))return r;return e}function Lr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Nr(e){return e?.status==="authorized"||e?.status==="complete"}function Kr(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 rl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Ta(e){let t=rl(e);return new Pt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Aa(e){return e instanceof Pt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function vo(e){return rl(e)?new Pt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Pt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Pt.FloPayError(Pt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function Yo(e,t){return e==="processing"||(0,Pt.isMoneySettledOutcome)(e,t)}function ol(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function al(e,t){let n=e;if((0,Pt.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:l}=await n.retrieveSetupIntent(t);if(l)throw new Pt.FloPayError(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new Pt.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 xi(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Xo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var $r=require("@flopay/js"),Xe=require("@flopay/shared"),C=Js(require("react"),1);var Mi=require("react"),Zn=(0,Mi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),pr=(0,Mi.createContext)({session:null,loading:!1,error:null});var Na=require("@flopay/js"),qt=require("@flopay/shared"),gl=require("@paypal/paypal-js"),k=require("react");var sl=require("@flopay/shared"),mr=require("react"),zr=require("react/jsx-runtime");function Bn(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),l=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...l||t?{lastName:l??""}:{}}}function Co(){let[e,t]=(0,mr.useState)(null),n=(0,mr.useRef)(null),r=(0,mr.useRef)(0),o=(0,mr.useCallback)((l,d)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:d}),new Promise(u=>{n.current=u})),[]),a=(0,mr.useCallback)(l=>{let d=n.current;n.current=null,t(null),d?.(l)},[]);return(0,mr.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function So({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,d]=(0,mr.useState)(e.email?.trim()??""),u=(0,sl.isValidEmail)(l.trim());return(0,zr.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,zr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,zr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,zr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:p=>d(p.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,zr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,zr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,zr.jsxs)("button",{type:"button",disabled:!u||o,onClick:()=>{n(Bn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Gc=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),Yc=["https://www.paypal.com","https://www.sandbox.paypal.com"];function xa(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 ll(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 to(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function _r(e){if(typeof e!="object"||e===null)return;let t=e;return to(t.code)??to(t.type)??to(t.name)}function wo(e){if(!(typeof e!="object"||e===null))return to(e.decline_code)}function Jo(e){return typeof e!="object"||e===null?!1:to(e.type)?.toLowerCase()==="card_error"||wo(e)!==void 0}function Xc(e){let t=ll(e)?.toLowerCase()??"",n=_r(e)?.toLowerCase()??"";return Gc.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 Bi(e){if(_r(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=ll(e)??"";return n.includes("No ack for postMessage init()")&&Yc.some(r=>n.includes(r))&&n.includes("10000ms")}function Ma(e,t){if(Jo(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=Xc(e)||t.inAppBrowser&&!t.handoffObserved&&Bi(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function Gr(e){return Ma(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}var cl=require("@flopay/shared"),Zo=require("react");function Ur(){return(0,Zo.useContext)(Zn).flopay}function Ba(){return(0,Zo.useContext)(Zn).paypalFlopay??null}function dl(){return(0,Zo.useContext)(pr)}function ul(){return(0,Zo.useContext)(Zn).billingApiUrl||(0,cl.resolveBillingApiUrl)()}function Qo(e){let t=e??(typeof navigator>"u"?"":navigator.userAgent),n=r=>({inAppBrowser:r!=="none",appFamily:r,popupCapability:"unknown"});return t?/FBAN|FBAV|FB_IAB|FBIOS/i.test(t)?n("facebook"):/Instagram/i.test(t)?n("instagram"):/musical_ly|BytedanceWebview|TikTok/i.test(t)?n("tiktok"):/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)?n("other_in_app"):/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)?n("generic_webview"):n("none"):n("none")}function pl(e,t,n=e.popupCapability){return e.inAppBrowser||n==="blocked"||t==="prefer_redirect"?"redirect":"popup"}function Fa(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var ml=require("@flopay/shared"),ro=require("react");function st(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}var Da=require("react"),no=typeof window>"u"?Da.useEffect:Da.useLayoutEffect;var Jc={"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 Zc(e){return e==="stripe"||e==="paypal"?e:void 0}function Qc(e){let t=Zc(e.provider),n={schemaVersion:ml.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Jc[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 Fi=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function ko(e,t){let n=(0,ro.useRef)(e);n.current=e;let r=(0,ro.useRef)(new Set),o=(0,ro.useRef)(t),a=(0,ro.useRef)(t);return no(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,ro.useCallback)(l=>{if(a.current!==t)return;let d=Qc(l);if(d){if(Fi.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}st(()=>n.current?.(d))}},[t])}var yl=require("react"),ea=(0,yl.createContext)(null);function Oa(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var ed=Symbol.for("@flopay/js.telemetry.bridge.v1"),td=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function nd(){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 rd(e){let t=nd(),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 La(e){let t=globalThis[td];return rd(t?.(e)??{})}function dn(e){if(e)return e[ed]}var un=require("react");function ta(e,t){let n=(0,un.useRef)(0),r=(0,un.useRef)(null),o=(0,un.useRef)(null),a=(0,un.useRef)(e),l=(0,un.useRef)(t?.onHandoffObserved);(0,un.useEffect)(()=>{a.current=e,l.current=t?.onHandoffObserved},[e,t?.onHandoffObserved]);let d=(0,un.useCallback)((h=o.current)=>{h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),u=(0,un.useCallback)(h=>{d();let O=n.current+1;return n.current=O,r.current=null,o.current={generation:O,method:h,timer:null,yieldedControl:!1},O},[d]),p=(0,un.useCallback)(h=>{let O=o.current;return h!==void 0&&O?.generation!==h?!1:(d(O),o.current=null,(h===void 0||r.current===h)&&(r.current=null),!0)},[d]),b=(0,un.useCallback)(h=>{let O=o.current,G=h??O?.generation??n.current;(h===void 0||O?.generation===h)&&(d(O),o.current=null),r.current=G},[d]),v=(0,un.useCallback)(h=>r.current===(h??n.current),[]),M=(0,un.useCallback)(h=>o.current?.generation===h&&r.current!==h,[]),I=(0,un.useCallback)(()=>{let h=o.current;h&&(d(h),!h.yieldedControl&&(h.yieldedControl=!0,l.current?.(h.method)))},[d]),w=(0,un.useCallback)(()=>{let h=o.current;!h?.yieldedControl||document.visibilityState!=="visible"||(d(h),h.timer=setTimeout(()=>{h.timer=null,o.current?.generation===h.generation&&(o.current=null,r.current=h.generation,a.current(h.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[d]);return(0,un.useEffect)(()=>{let h=()=>{document.visibilityState==="visible"?w():I()};return document.addEventListener("visibilitychange",h),window.addEventListener("blur",I),window.addEventListener("focus",w),()=>{document.removeEventListener("visibilitychange",h),window.removeEventListener("blur",I),window.removeEventListener("focus",w),d()}},[d,I,w]),{startAttempt:u,finishAttempt:p,invalidateAttempt:b,isAttemptInvalidated:v,isAttemptCurrent:M,generationRef:n}}var Qn=require("react/jsx-runtime"),za=45,od=1e3,ad=11e3,id={width:"100%",minHeight:za,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},sd={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 ld(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:sd[e.kind]??null}}function fl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Bi(t)?"paypal_init_timeout":"paypal_init_failure"}function cd(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 dd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function hl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:d,currency:u,isSubscription:p,providerObjectType:b,approvalPresentation:v,onTokenizedBody:M,onComplete:I,onErrorChange:w,onDecline:h,onTechnicalFailure:O,isProcessing:G=!1,onLoadStateChange:T,onInitializationStateChange:Y,allowAutomaticRetry:U=!0,onButtonClick:de,runBeforeButtonClick:X,session:he,existingOrderId:De,telemetry:re,telemetryContext:Ve,onInstrument:yt,debug:te=!1}){let Oe=Ur(),ft=ko(yt,e),ke=(0,k.useMemo)(()=>{if(Oe)return null;let F=La({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:qt.SDK_VERSION,enabled:re!==!1});return F.setCheckoutContext(Ve??{}),F.beginCheckout(Ve??{}),F},[n,Oe,re,Ve?.checkoutMode,Ve?.layout]),Le=(0,k.useMemo)(()=>dn(Oe),[Oe]);(0,k.useEffect)(()=>()=>{ke&&ke.flush().catch(()=>{}).finally(()=>ke.destroy())},[ke]);let be=(0,k.useMemo)(()=>({error:F=>{Le?Le.error(F):ke?.error(F),ft({class:"technical_error",errorCode:F.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":F.errorCode,requestCategory:F.requestCategory,provider:F.provider})},log:F=>{Le?Le.log(F):ke?.log(F),ft({class:"lifecycle",name:F.name,provider:F.provider})},performance:F=>{Le?Le.performance(F):ke?.performance(F)},terminal:F=>{Le?Le.terminal(F):ke?.terminal(F)},startTiming:()=>Le?.now()??ke?.now()??0,elapsed:F=>Le?.elapsed(F)??Math.max(0,(ke?.now()??F)-F)}),[ft,Le,ke]),me=(0,k.useRef)(null),Ie=(0,k.useRef)(0),We=(0,k.useRef)(null),rt=(0,k.useRef)(null),R=(0,k.useRef)(null),He=(0,k.useContext)(ea),ye=(0,k.useRef)(null);ye.current||(ye.current=Oa());let N=He??ye.current,ve=(0,k.useRef)(null),ue=(0,k.useRef)(!1),[Ke,Z]=(0,k.useState)(!1),[ot,lt]=(0,k.useState)(!1),[Ae,Ne]=(0,k.useState)(0),ct=(0,k.useRef)(0),[at,xe]=(0,k.useState)(!1),jt=(0,k.useRef)(!1),Vt=(0,k.useRef)(!1),[ut,Et]=(0,k.useState)(!1),[q,fe]=(0,k.useState)(!1),{request:et,collect:V,finish:Me}=Co(),bt=(0,k.useRef)({sessionId:e,required:!(0,qt.isValidEmail)(r?.trim()||he?.customer?.email?.trim())});bt.current.sessionId!==e&&(bt.current={sessionId:e,required:!(0,qt.isValidEmail)(r?.trim()||he?.customer?.email?.trim())});let Ge=bt.current.required,$=(0,k.useMemo)(()=>n.replace(/\/+$/,""),[n]),f=he?.gateways?.paypal?.providerObjectType??b,P=f??(p?"subscription":"order"),[H]=(0,k.useState)(Qo),ne=he?.gateways?.paypal?.approvalPresentation??v,$e=Fa(H,ne==="app_switch"?"app_switch":void 0,P),vt=f==="order"||f==="setup_token",Re=(0,k.useMemo)(()=>JSON.stringify([$,l,u,d??"",P,vt,$e,e,De??""]),[$,l,u,d,De,P,vt,$e,e]),ae=(0,k.useRef)(Re),it=ae.current!==Re,Ct=(0,k.useRef)(te),Nt=(0,k.useRef)(null),[ze,Ft]=(0,k.useState)([]),Ue=(0,k.useCallback)(F=>{Ct.current&&Ft(Ze=>[...Ze,`${new Date().toISOString().slice(11,23)} ${F}`])},[]);(0,k.useEffect)(()=>{Ct.current=te,te&&Ue("debug:enabled"),Nt.current?.setEnabled(te)},[Ue,te]);let Fn=(0,k.useRef)(M),Rn=(0,k.useRef)(I),Mt=(0,k.useRef)(w),wn=(0,k.useRef)(h),Dn=(0,k.useRef)(O),On=(0,k.useRef)(de),rn=(0,k.useRef)(T),Ce=(0,k.useRef)(Y),St=(0,k.useRef)(a),Tt=(0,k.useRef)(X),vn=(0,k.useRef)(he),Bt=(0,k.useRef)(r),Vn=(0,k.useRef)(o),pn=(0,k.useRef)(t),Wt=(0,k.useRef)(null),an=(0,k.useRef)(new Map),Wn=(0,k.useRef)(new Map),mn=(0,k.useRef)(!1);(0,k.useEffect)(()=>(mn.current=!0,()=>{mn.current=!1}),[]),(0,k.useEffect)(()=>{Fn.current=M},[M]),(0,k.useEffect)(()=>{St.current=a},[a]),(0,k.useEffect)(()=>{Rn.current=I},[I]),(0,k.useEffect)(()=>{Mt.current=w},[w]),(0,k.useEffect)(()=>{wn.current=h},[h]),(0,k.useEffect)(()=>{Dn.current=O},[O]),(0,k.useEffect)(()=>{On.current=de},[de]),(0,k.useEffect)(()=>{rn.current=T},[T]),(0,k.useEffect)(()=>{Ce.current=Y},[Y]),(0,k.useEffect)(()=>{Tt.current=X},[X]),(0,k.useEffect)(()=>{vn.current=he},[he]),(0,k.useEffect)(()=>{Bt.current=r},[r]),(0,k.useEffect)(()=>{Vn.current=o},[o]),(0,k.useEffect)(()=>{pn.current=t},[t]),(0,k.useEffect)(()=>{ct.current=Ae},[Ae]),(0,k.useEffect)(()=>{at&&ve.current?.focus()},[at,Ae]);let wt=(0,k.useCallback)(()=>{window.setTimeout(()=>{ve.current?.focus()},0)},[]),Zt=(0,k.useCallback)(()=>{Z(!1),Ne(F=>F+1)},[]),yn=(0,k.useCallback)(()=>{xe(!1),(me.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??me.current)?.focus?.()},[]);(0,k.useEffect)(()=>{!Ke||!ue.current||(ue.current=!1,yn())},[yn,Ke,Ae]);let Dt=(0,k.useCallback)((F,Ze)=>{let se=Ze?.popupBlocked??Gr(F);se&&N.markBlocked();let Hn=xa("PayPal",se,H.inAppBrowser),gn=Dn.current;if(gn){let Kt=se&&H.inAppBrowser?new qt.FloPayError(Hn,"api_error",{code:Ze?.code??"paypal_popup_blocked"}):F;gn("paypal",Kt,Ze);return}Mt.current?.(Hn)},[N,H.inAppBrowser]),Qt=(0,k.useCallback)(F=>{let Ze=We.current,se=rt.current;Ze===null||!se||(be.log({...se,popupCapability:N.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:F}),be.performance({...se,popupCapability:N.current(),stage:"overlay_return",durationMs:be.elapsed(Ze),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:F}),We.current=null)},[N,be]),Ht=(0,k.useCallback)((F,Ze,se)=>{let Hn=rt.current;Qt("overlay_timeout"),Hn&&be.error({...Hn,popupCapability:N.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Dt(Ze,{...se,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:$e,terminalReason:"overlay_timeout"}),xe(!0),Zt(),wt()},[Qt,wt,Dt,N,$e,Zt,be]),fn=(0,k.useCallback)(()=>{N.markAvailable();let F=rt.current;F&&(R.current=F.attempt,be.log({...F,popupCapability:N.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[N,be]),{finishAttempt:gt,generationRef:Q,invalidateAttempt:Ln,isAttemptCurrent:Nn,isAttemptInvalidated:hr,startAttempt:Cn}=ta(Ht,{onHandoffObserved:fn}),sn=(0,k.useCallback)(()=>(xe(!1),Cn("paypal")),[Cn]),_n=(0,k.useCallback)(F=>{Ln(F?.generation),F?.showRetry&&xe(!0),F?.remount&&Zt(),F?.focus!==!1&&wt()},[wt,Ln,Zt]),_e=F=>{let Ze=Wt.current;return Ze&&Wn.current.set(F,Ze),F};(0,k.useEffect)(()=>{ae.current!==Re&&(ae.current=Re,jt.current=!1,Vt.current=!1,Z(!1),lt(!1),Et(!1),Ce.current?.("loading"))},[Re]),(0,k.useEffect)(()=>{st(()=>rn.current?.(Ke&&!ut))},[Ke,ut]);let ht=(0,qt.normalizeGatewayEnvironment)(d);(0,k.useEffect)(()=>{let F={attempt:Q.current+1,inAppBrowser:H.inAppBrowser,appFamily:H.appFamily,popupCapability:N.current(),presentationMode:$e},Ze=()=>({...rt.current??F,popupCapability:N.current()}),se={error:m=>be.error({...m,...Ze()}),log:m=>be.log({...m,...Ze()}),performance:m=>be.performance({...m,...Ze()}),terminal:m=>be.terminal({...m,...Ze()}),startTiming:be.startTiming,elapsed:be.elapsed},Hn=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",gn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Ue(`mount clientId=${Hn} env=${d??"(unset)"}\u2192${ht??"live"} ccy=${u} sub=${p}`),Ue(`ua=${gn.slice(0,80)}${gn.length>80?"\u2026":""}`),!l){Ue("FAIL: clientId empty \u2014 gateway misconfigured"),Et(!0),se.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(!me.current){Ue("FAIL: containerRef not attached");return}Ie.current=se.startTiming(),se.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Kt=!1,Kn=!1,nt=()=>Kt||Kn,jr,Gt=!1,hn=()=>{jr=(0,qt.generateIdempotencyKey)(),jr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Gt=!0},Mr=null,Br=!1,En=null,en=!1,br=()=>{!En||en||(en=!0,En.close().catch(()=>{}))},Tn=!1,Fr=!1,An=me.current,Pr=null,vr=null,rr=[],Gn=null,Yn=!1,xt=!1,or=null,kn=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let g=m.getBoundingClientRect();return`${Math.round(g.width)}\xD7${Math.round(g.height)}`},Xn=m=>{if(!m)return"(empty)";try{let g=new URL(m,typeof window>"u"?"https://localhost":window.location.href),D=g.pathname.toLowerCase();return D.includes("checkcaptcha")||D.includes("captcha")?`CAPTCHA(${g.host}${D})`:D.includes("risk")||D.includes("challenge")?`RISK(${g.host}${D})`:D.includes("smart/buttons")?`smart-buttons(${g.host})`:`${g.host}${D}`.slice(0,100)}catch{return m.slice(0,80)}},Cr=m=>{let g=m.getAttribute("src"),D=m.getAttribute("srcdoc"),z=m.getAttribute("name"),ce=m.getAttribute("sandbox"),J=[];return g&&J.push(`src=${Xn(g)}`),D&&J.push(`srcdoc[${D.length}ch]`),!g&&!D&&J.push("src=(empty) srcdoc=(empty)"),z&&J.push(`name=${z.slice(0,40)}`),ce!==null&&J.push(`sandbox="${ce.slice(0,40)}"`),J.join(" ")},dt=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let g=m.contentDocument;if(!g)return"cd=null";let D=g.body?.children.length??0,z=g.body?.innerHTML.length??0,ce=g.head?.innerHTML.length??0;return`cd=same-origin readyState=${g.readyState} body[${D}children,${z}ch] head[${ce}ch]`}catch(g){return`cd=cross-origin(${g.message.slice(0,30)})`}},on=[],tn=m=>{if(nt())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"))&&(Ue(`window:error ${g.slice(0,140)}`),on.push(g))},Dr=m=>{if(nt())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"))&&(Ue(`window:rejection ${g.slice(0,140)}`),on.push(g))},zn={value:0},Vr=()=>{Pr?.disconnect(),Pr=null,vr?.disconnect(),vr=null;for(let m of rr.splice(0))clearTimeout(m);xt=!1,Yn&&typeof window<"u"&&(window.removeEventListener("error",tn),window.removeEventListener("unhandledrejection",Dr)),Yn=!1},ar=()=>{if(!(Yn||nt()||Tn)){if(Yn=!0,on.length=0,zn.value=0,typeof window<"u"&&(window.addEventListener("error",tn),window.addEventListener("unhandledrejection",Dr)),typeof PerformanceObserver<"u")try{vr=new PerformanceObserver(m=>{if(!nt())for(let g of m.getEntries()){if(!g.name.toLowerCase().includes("paypal"))continue;zn.value+=1;let D=Math.round(g.duration);Ue(`net ${D}ms ${g.name.slice(0,90)}`)}}),vr.observe({type:"resource",buffered:!0})}catch{}or?.()}},ir=()=>{Gn&&(clearTimeout(Gn),Gn=null)},bn=()=>{Vr(),ir()},sr={setEnabled:m=>{m?ar():Vr()}};Nt.current=sr,Ct.current&&ar();let Or=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")},In=m=>{if(nt()||Or(m))return;let g=Hr(m)??m;st(()=>Mt.current?.(g))},A=(m,g)=>{if(Kt||Br)return;Br=!0,Kn=!0,bn(),br();let D=ld({kind:m,generationActive:!0,automaticRetryAllowed:U,automaticRetryUsed:jt.current});if(D.action==="retry"){jt.current=!0,Z(!1),fe(!1),lt(!0),Ce.current?.("retrying"),Mr=setTimeout(()=>{Kt||Ne(z=>z+1)},od);return}if(Z(!1),fe(!1),lt(!1),Et(!0),D.action!=="ignore"){if(Ce.current?.("exhausted"),D.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",g);return}if(D.report){let z=Ma({code:fl(m,g),message:g},{inAppBrowser:H.inAppBrowser,handoffObserved:!1});z.popupBlocked&&N.markBlocked(),se.error({errorCode:z.popupBlocked?z.errorCode:D.report.errorCode,stage:D.report.stage,operationOutcome:D.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:z.terminalReason})}Vt.current||(Vt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",fl(m,g)))}};Et(!1);let L=async(m,g=Wt.current)=>{if(nt())return;let D=g?.sessionId??e;if(Fn.current){await Fn.current(m,{sessionId:D,accountPatch:g?.accountPatch,nonce:g?.nonce});return}let z=se.startTiming();se.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ce=()=>{se.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),se.performance({stage:"processing",durationMs:se.elapsed(z),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let J=vn.current,Ye=g?.accountPatch?.email??Bt.current,It=g?.accountPatch?.userId??J?.customer?.id??J?.accountData?.userId??"",E=g?.accountPatch?.firstName??J?.customer?.firstName??J?.accountData?.firstName,Pe=g?.accountPatch?.lastName??J?.customer?.lastName??J?.accountData?.lastName,ge=await new Na.PaymentAPI($,{telemetry:!1}).processPayment(It,{sessionId:D,nonce:g?.nonce??pn.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:It,email:Ye??J?.customer?.email??"",...E?{firstName:E}:{},...Pe?{lastName:Pe}:{},country:g?.accountPatch?.country??J?.customer?.country??J?.accountData?.country??void 0,zip:g?.accountPatch?.zip??J?.customer?.zip??J?.accountData?.zip??void 0}});if(ge.ok){if(Kn||Kt&&mn.current)return;ce(),se.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),st(()=>Rn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(nt())return;let j=await ge.json().catch(()=>null),oe=j?.message??"PayPal payment failed.",_=Hr(oe)??oe;ce(),ge.status===400&&(typeof j?.declineCode=="string"||!Array.isArray(j?.fields))?se.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ge.status===400||ge.status===422?se.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):se.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:dd(ge.status),failureCategory:ge.status>=500?"server_error":void 0}),In(_),st(()=>wn.current?.(cn("paypal",_,{code:j?.code,declineCode:j?.declineCode})));return}catch(J){if(nt())return;ce(),se.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ye=J instanceof Error?J.message:"PayPal payment failed.",It=Hr(Ye)??Ye;In(It),st(()=>wn.current?.(cn("paypal",It)));return}},B=()=>new qt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),le=m=>nt()?Promise.reject(B()):Promise.resolve(m),Be=async m=>{if(nt())throw B();Gt||hn();let g=Wt.current,D=g?.sessionId??e,z=g?.nonce??pn.current;se.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ce;try{ce=await new Na.PaymentAPI($,{telemetry:!1}).createSessionIntent(D,z??"",vt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:qt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:P==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:jr})}catch(J){throw se.error({...(0,qt.classifyTelemetryFailure)(J,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),J}if(nt())throw B();if(ce.provider!=="paypal"||ce.providerObjectType!==P)throw new Error(m);return se.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ce.providerObjectId},pt=(m,g)=>{let D=g?.nonce??pn.current;if(!D)return;let z=g?.sessionId??e,ce=wo(m)??_r(m)??"provider_declined";new Na.PaymentAPI($,{telemetry:!1}).reportSessionIntentDecline(z,D,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ce}).catch(()=>{})},pe=Ae;Ue("loadScript:scheduled (deferred 1 tick)");let Fe=null,W=setTimeout(()=>{if(Kt){Ue("loadScript:skipped (cancelled before defer ran)");return}Ue("loadScript:start");let m=ht==="live"?"production":ht,g={};P==="subscription"?g={intent:"subscription",vault:!0}:P==="order"&&(g={intent:"capture"}),Fe=(0,gl.loadScript)({clientId:l,currency:u,...g,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let D=!1;Fe.then(z=>{if(D=!0,Ue(`loadScript:resolved inactive=${nt()} ns=${!!z} buttons=${!!z?.Buttons}`),nt())return;if(!z?.Buttons){Ue("FAIL: namespace missing Buttons factory"),A("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}se.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),se.performance({stage:"provider_ready",durationMs:se.elapsed(Ie.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),se.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let ce=async(ge,j)=>{if(nt()||ct.current!==pe)return;let oe=ge.vaultSetupToken??ge.subscriptionID??ge.orderID??"",_=oe?Wn.current.get(oe):an.current.get(pe);if(!(!_||!Nn(_.generation))&&gt(_.generation)){Wn.current.delete(oe),an.current.delete(_.surfaceKey),Qt("approved");try{if(fe(!0),st(()=>Mt.current?.(null)),!oe)throw new qt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let qe=vn.current,Rt=eo(Vn.current??[qe?.customer?.firstName,qe?.customer?.lastName].filter(Boolean).join(" ")),Ee=Bn({email:_.accountPatch?.email?.trim()||Bt.current?.trim()||qe?.customer?.email?.trim(),firstName:_.accountPatch?.firstName?.trim()||Rt.firstName,lastName:_.accountPatch?.lastName?.trim()||Rt.lastName});if(!(0,qt.isValidEmail)(Ee.email)||!(Ee.firstName||Ee.lastName))try{let Sr=cd(await j?.order?.get?.());Ee=Bn({email:Sr.email||Ee.email,firstName:Sr.firstName||Ee.firstName,lastName:Sr.lastName||Ee.lastName})}catch{}if((St.current||Ge)&&!(0,qt.isValidEmail)(Ee.email)){let Sr=await V("PayPal",Ee);if(!Sr)return;Ee=Sr}(0,qt.isValidEmail)(Ee.email)&&(_.accountPatch=Bn({..._.accountPatch,...Ee}),await St.current?.(Ee));let Sn;P==="setup_token"?Sn={id:oe,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:qt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:vt?Sn={id:oe,isPaypal:!0,gateway:"paypal",paymentMethodType:qt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Sn={id:oe,isPaypal:!0},await L(Sn,_)}catch(qe){In(qe instanceof Error?qe.message:"PayPal capture failed.")}finally{nt()||fe(!1)}}},J=ge=>{let j=De?()=>le(De):()=>Be(ge);return async()=>_e(await j())},Ye=z.Buttons({style:{layout:"horizontal",height:za,tagline:!1},...$e==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ge,j)=>{if(nt()){await j.reject();return}hn();let oe=Tt.current,_={};if(oe)try{let Ee=await oe("paypal");if(nt()){await j.reject();return}if(!Ee.proceed){Wt.current=null,an.current.delete(pe),await j.reject();return}_={sessionId:Ee.sessionId,accountPatch:Ee.accountPatch,nonce:Ee.nonce}}catch(Ee){Ue(`onClick:runBeforeButtonClick rejected msg=${(Ee instanceof Error?Ee.message:String(Ee)).slice(0,120)}`),Wt.current=null,an.current.delete(pe),await j.reject();return}st(()=>On.current?.("paypal"));let qe=sn(),Rt={generation:qe,surfaceKey:pe,..._};Wt.current=Rt,an.current.set(pe,Rt),rt.current={...F,attempt:qe},await j.resolve(),se.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),se.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),We.current=se.startTiming()},createOrder:P==="order"?J("Failed to create PayPal order."):void 0,createSubscription:P==="subscription"?J("Failed to create PayPal subscription."):void 0,createVaultSetupToken:P==="setup_token"?async()=>_e(await Be("Failed to create PayPal setup token.")):void 0,onApprove:ce,onCancel:()=>{if(nt())return;let ge=an.current.get(pe)??Wt.current;ge&&an.current.delete(ge.surfaceKey),Wt.current=null,Qt("cancelled"),se.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ue.current=!0,_n({generation:ge?.generation,remount:!0,focus:!1})},onError:ge=>{if(nt()||ct.current!==pe)return;let j=ge instanceof Error?ge.message:"PayPal failed to render.";if(Ue(`onError rendered=${Tn} msg=${j.slice(0,120)}`),Tn){let oe=an.current.get(pe)??Wt.current;if(oe&&!Nn(oe.generation)||!oe&&hr())return;if(Or(j)){gt(oe?.generation);return}let{errorCode:_,popupBlocked:qe,providerDeclined:Rt,terminalReason:Ee}=Ma(ge,{inAppBrowser:H.inAppBrowser,handoffObserved:oe!=null&&R.current===oe.generation});if(qe&&N.markBlocked(),Qt(Ee),Rt){se.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ee}),pt(ge,oe),st(()=>wn.current?.(cn("paypal",j))),oe&&an.current.delete(oe.surfaceKey),Wt.current=null,gt(oe?.generation);return}se.error({errorCode:_,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ee}),oe&&an.current.delete(oe.surfaceKey),Wt.current=null,_n({generation:oe?.generation,remount:!0,showRetry:!0,focus:!0}),Dt(ge,{code:"paypal_runtime_failed",popupBlocked:qe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:$e,terminalReason:Ee});return}A(Or(j)?"teardown":"pre_ready_callback",j)}}),It=Ye.isEligible();if(Ue(`isEligible=${It}`),se.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!It){Z(!1),A("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Fr=!0,En=Ye,or=()=>{if(!Yn||xt||nt()||Tn)return;xt=!0,Ue(`container:dims ${kn(An)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Pr=new MutationObserver(j=>{if(!nt()){for(let oe of j)if(oe.type==="childList")oe.addedNodes.forEach(_=>{if(!(_ instanceof Element))return;let qe=_.tagName.toLowerCase(),Rt=(_.getAttribute("title")??"").slice(0,40),Ee=qe==="iframe"?` ${Cr(_)}`:"";Ue(`child+ ${qe}${Rt?` title="${Rt}"`:""}${Ee} dims=${kn(_)}`)});else if(oe.type==="attributes"&&oe.target instanceof Element){let _=oe.target;if(_.tagName.toLowerCase()!=="iframe")continue;let qe=oe.attributeName;(qe==="src"||qe==="srcdoc")&&Ue(`attr~ iframe ${qe}=${qe==="srcdoc"?`[${(_.getAttribute("srcdoc")??"").length}ch]`:Xn(_.getAttribute("src"))} dims=${kn(_)}`)}}}),Pr.observe(An,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ge=j=>{if(nt()||Tn)return;let oe=An.querySelectorAll("iframe"),_=typeof document<"u"&&"hasStorageAccess"in document;Ue(`watchdog:${j} container=${kn(An)} children=${An.childElementCount} iframes=${oe.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${_} paypalNetRequests=${zn.value}`),oe.forEach((qe,Rt)=>{let Ee=(qe.getAttribute("title")??"").slice(0,40);Ue(` iframe[${Rt}] ${kn(qe)}${Ee?` title="${Ee}"`:""} ${Cr(qe)}`);let Sn=dt(qe);Sn&&Ue(` ${Sn}`)}),on.length===0&&Ue(" (no PayPal/zoid window errors captured)")};rr.push(setTimeout(()=>ge("3s"),3e3)),rr.push(setTimeout(()=>ge("8s"),8e3)),rr.push(setTimeout(()=>ge("15s"),15e3))},or(),Ue("render:start");let Pe=se.startTiming();Gn=setTimeout(()=>{nt()||Tn||(Ue("watchdog:11s retryable render timeout"),A("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},ad);let At=Ye.render(An);(async()=>{try{if(await At,Ue(`render:resolved inactive=${nt()}`),bn(),nt()){br();return}Tn=!0,Z(!0),lt(!1),Ce.current?.("ready"),se.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),se.performance({stage:"checkout_render",durationMs:se.elapsed(Pe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ge){let j=ge instanceof Error?ge.message:"PayPal failed to render.";Ue(`render:rejected msg=${j.slice(0,120)}`),bn(),A(Or(j)?"teardown":"render_rejected",j)}})()}).catch(z=>{let ce=z instanceof Error?z.message:"PayPal operation failed.";Ue(`provider:failed msg=${ce.slice(0,120)}`);let J="script_rejected";D&&Or(ce)?J="teardown":D&&Fr&&(J="render_rejected"),A(J,ce)})},0);return()=>{Kt=!0,clearTimeout(W),Mr&&clearTimeout(Mr),bn(),Nt.current===sr&&(Nt.current=null),br(),We.current=null,rt.current=null}},[U,$,l,u,d,P,$e,vt,e,De,Ae,be,V,Ge,Ue,Qt]);let ie=te?(0,Qn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ut?"#fef2f2":"#f3f4f6",border:`1px solid ${ut?"#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=${Ke} failed=${ut})`,ze.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${nt.join(`
4
- `)}`]}):null;return ut&&!pt?te?(0,Qn.jsx)("div",{children:ie}):null:(0,Qn.jsxs)("div",{children:[ie,Ve&&(0,Qn.jsx)(Co,{identity:Ve.identity,methodLabel:Ve.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Ge,onCancel:()=>Ge(null)}),(0,Qn.jsxs)("div",{"aria-hidden":at||Ve?!0:void 0,style:at||Ve?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:za},children:[!Ue&&!at&&(0,Qn.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,Qn.jsx)("div",{ref:pe,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:za,display:"flex",opacity:Ue?1:0},"aria-busy":z||re},Fe)]},Fe),Pt&&(0,Qn.jsx)("button",{ref:xe,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:mn,style:id,children:"Try PayPal again"})]})}function ta(e){return(0,Qn.jsx)(gl,{...e})}function hl(e){return(0,Qn.jsx)(gl,{...e})}var na=require("react/jsx-runtime");function ko({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,na.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,na.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,na.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 Ua=require("@flopay/shared");function Io(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Li=":idempotency-key";function Oi(e,t){if(!Io())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function Ni(e,t){if(!Io())return null;try{let n=window.sessionStorage.getItem(e+Li);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 qa(e,t){if(Io())try{Oi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function $a(e,t){if(qa(e,t),!!Io())try{Ni(e,t)&&window.sessionStorage.removeItem(e+Li)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function ja(e,t,n,r){if(Io())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function Va(e,t,n){if(Io())try{window.sessionStorage.setItem(e+Li,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Di(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function ud(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([l],[d])=>l<d?-1:l>d?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let l=0;l<t.length;l++){let d=t.charCodeAt(l);n=r^Math.imul(n^d,597399067),r=o^Math.imul(r^d,2869860233),o=a^Math.imul(o^d,951274213),a=n^Math.imul(a^d,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(a^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),a=Math.imul(r^a>>>19,2716044179),n^=r^o^a,r^=n,o^=n,a^=n,[n,r,o,a].map(l=>(l>>>0).toString(16).padStart(8,"0")).join("")}function Ro(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=>Di(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Di(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Di(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:ud(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function bl(e,t=!1){let n=Ro(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 Pl(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,Ua.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,Ua.foldIntoProducts)(t.items,t.subscriptions)).map(f=>({type:f.type,code:f.code??f.providerItemId??f.providerPlanId??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??o).toUpperCase()})).sort((f,h)=>`${f.code}:${f.type??""}`.localeCompare(`${h.code}:${h.type??""}`)),l=e.products.map(f=>({type:f.type,code:f.code??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??e.currency).toUpperCase()})).sort((f,h)=>`${f.code}:${f.type??""}`.localeCompare(`${h.code}:${h.type??""}`));if(a.length!==l.length)return!1;for(let[f,h]of a.entries()){let b=l[f];if(b===void 0||h.code!==b.code||h.type!==void 0&&h.type!==b.type||h.quantity!==b.quantity||h.totalAmount!==b.totalAmount||h.overrideAmount!==b.overrideAmount||h.currency!==b.currency)return!1}let d=[...t.couponCodes??[]].sort(),p=[...e.coupons??[]].sort();return d.length===p.length&&d.every((f,h)=>f===p[h])}var en=require("react/jsx-runtime");var pd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function er({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:l="You will be automatically redirected, do not close or navigate away from this window.",theme:d=pd}){let p={fontSize:13,color:d.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,en.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,en.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...d.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,en.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,en.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,en.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:d.spinnerTrackColor,strokeWidth:"3"}),(0,en.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:d.spinnerAccentColor})]}),e==="success"&&(0,en.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,en.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,en.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,en.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,en.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,en.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,en.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,en.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,en.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:d.labelColors[e]},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&a]}),e==="success"&&l!==null&&(0,en.jsx)("p",{style:p,children:l}),e==="error"&&t&&(0,en.jsx)("p",{style:p,children:t}),(0,en.jsx)("style",{children:`
3
+ ${ze.join(`
4
+ `)}`]}):null;return ut&&!it?te?(0,Qn.jsx)("div",{children:ie}):null:(0,Qn.jsxs)("div",{children:[ie,et&&(0,Qn.jsx)(So,{identity:et.identity,methodLabel:et.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Me,onCancel:()=>Me(null)}),(0,Qn.jsxs)("div",{"aria-hidden":ot||et?!0:void 0,style:ot||et?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:za},children:[!Ke&&!ot&&(0,Qn.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,Qn.jsx)("div",{ref:me,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:za,display:"flex",opacity:Ke?1:0},"aria-busy":q||G},Ae)]},Ae),at&&(0,Qn.jsx)("button",{ref:ve,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:yn,style:id,children:"Try PayPal again"})]})}function na(e){return(0,Qn.jsx)(hl,{...e})}function bl(e){return(0,Qn.jsx)(hl,{...e})}var ra=require("react/jsx-runtime");function Io({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,ra.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,ra.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,ra.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 Ua=require("@flopay/shared");function Ro(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Oi=":idempotency-key";function Li(e,t){if(!Ro())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 Ni(e,t){if(!Ro())return null;try{let n=window.sessionStorage.getItem(e+Oi);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 qa(e,t){if(Ro())try{Li(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function $a(e,t){if(qa(e,t),!!Ro())try{Ni(e,t)&&window.sessionStorage.removeItem(e+Oi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function ja(e,t,n,r){if(Ro())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function Va(e,t,n){if(Ro())try{window.sessionStorage.setItem(e+Oi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Di(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function ud(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([l],[d])=>l<d?-1:l>d?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let l=0;l<t.length;l++){let d=t.charCodeAt(l);n=r^Math.imul(n^d,597399067),r=o^Math.imul(r^d,2869860233),o=a^Math.imul(o^d,951274213),a=n^Math.imul(a^d,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(a^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),a=Math.imul(r^a>>>19,2716044179),n^=r^o^a,r^=n,o^=n,a^=n,[n,r,o,a].map(l=>(l>>>0).toString(16).padStart(8,"0")).join("")}function _o(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=>Di(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Di(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Di(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:ud(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Pl(e,t=!1){let n=_o(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 vl(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,Ua.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,Ua.foldIntoProducts)(t.items,t.subscriptions)).map(p=>({type:p.type,code:p.code??p.providerItemId??p.providerPlanId??"",quantity:p.quantity??1,totalAmount:p.totalAmount,overrideAmount:p.overrideAmount??null,currency:(p.currency??o).toUpperCase()})).sort((p,b)=>`${p.code}:${p.type??""}`.localeCompare(`${b.code}:${b.type??""}`)),l=e.products.map(p=>({type:p.type,code:p.code??"",quantity:p.quantity??1,totalAmount:p.totalAmount,overrideAmount:p.overrideAmount??null,currency:(p.currency??e.currency).toUpperCase()})).sort((p,b)=>`${p.code}:${p.type??""}`.localeCompare(`${b.code}:${b.type??""}`));if(a.length!==l.length)return!1;for(let[p,b]of a.entries()){let v=l[p];if(v===void 0||b.code!==v.code||b.type!==void 0&&b.type!==v.type||b.quantity!==v.quantity||b.totalAmount!==v.totalAmount||b.overrideAmount!==v.overrideAmount||b.currency!==v.currency)return!1}let d=[...t.couponCodes??[]].sort(),u=[...e.coupons??[]].sort();return d.length===u.length&&d.every((p,b)=>p===u[b])}var nn=require("react/jsx-runtime");var pd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function er({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:l="You will be automatically redirected, do not close or navigate away from this window.",theme:d=pd}){let u={fontSize:13,color:d.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,nn.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,nn.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...d.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,nn.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,nn.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,nn.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:d.spinnerTrackColor,strokeWidth:"3"}),(0,nn.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:d.spinnerAccentColor})]}),e==="success"&&(0,nn.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,nn.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,nn.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,nn.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,nn.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,nn.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,nn.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,nn.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,nn.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:d.labelColors[e]},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&a]}),e==="success"&&l!==null&&(0,nn.jsx)("p",{style:u,children:l}),e==="error"&&t&&(0,nn.jsx)("p",{style:u,children:t}),(0,nn.jsx)("style",{children:`
5
5
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
6
6
  @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
7
7
  @keyframes flopay-draw { to { stroke-dashoffset: 0; } }
8
8
  @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
9
- `})]})})}var vl=require("@flopay/shared"),bn=require("react");var Cl=require("react/jsx-runtime");function ra({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=(0,bn.useState)(e instanceof Promise?null:e),[d,p]=(0,bn.useState)(t instanceof Promise||!t?null:t),f=(0,bn.useRef)(null),h=(0,bn.useRef)(null),b=wo(r);(0,bn.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,bn.useEffect)(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),(0,bn.useEffect)(()=>{if(a)return cn(a)?.subscribe?.(b)},[b,a]),(0,bn.useEffect)(()=>{if(!(!d||d===a))return cn(d)?.subscribe?.(b)},[b,a,d]),(0,bn.useEffect)(()=>{if(!a)return;let S=cn(a);return f.current=S?.beginCheckout()??S?.now()??0,S?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{S?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,bn.useEffect)(()=>{let S=!1;return e instanceof Promise?e.then(v=>{S||l(v)},()=>{S||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{S=!0}},[b,e]),(0,bn.useEffect)(()=>{let S=!1;if(!t){p(null);return}return t instanceof Promise?t.then(v=>{S||p(v)},()=>{S||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{S=!0}},[b,t]),(0,bn.useEffect)(()=>{if(!a||h.current===a)return;h.current=a;let S=cn(a);S?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),S?.performance({stage:"checkout_render",durationMs:S.elapsed(f.current??0),durationMode:"machine"})},[b,a]);let A=(0,vl.resolveBillingApiUrl)(n?.billingApiUrl),k=(0,bn.useMemo)(()=>({flopay:a,paypalFlopay:d,billingApiUrl:A,emitInstrument:b}),[a,d,A,b]);return(0,Cl.jsx)(Zn.Provider,{value:k,children:o})}var Wa="flopay_recent_completion_";function _o(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Wa+e,JSON.stringify(t))}catch{}}function zi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Wa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Wa+e),!1):!0}catch{return!1}}async function Ha(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 no=require("@flopay/js"),Je=require("@flopay/shared");var aa="card",md=1e3,wl=3e5;async function yd(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function fd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function ia(e){return new Je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function qi(e,t){return Object.assign(e,{checkoutMethod:t})}function Ur(e,t){let n=e instanceof Je.FloPayError?e:new Je.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function oa(e,t){try{return await e()}catch(n){throw Ur(n,t)}}function kl(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function gd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function $i(e){if(typeof document>"u"||typeof window>"u")throw new Je.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let b=new AbortController,A=()=>b.abort();e.signal?.aborted?b.abort():e.signal?.addEventListener("abort",A);let k=window.setTimeout(()=>b.abort(),n);try{let S=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:b.signal});if(!S.ok)return{status:"unknown"};let v=await S.json().catch(()=>null);return hd(v)}catch{return{status:"unknown"}}finally{window.clearTimeout(k),e.signal?.removeEventListener("abort",A)}},a,l=()=>e.pollCompletionEndpoint!==!1?o():(a??(a=o()),a),d=document.activeElement instanceof HTMLElement?document.activeElement:null,p=document.createElement("div");p.setAttribute("data-flopay-auto-3ds-overlay","1"),p.setAttribute("role","dialog"),p.setAttribute("aria-modal","true"),p.setAttribute("aria-label","Card authentication"),p.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let f=document.createElement("iframe");f.setAttribute("title","Card authentication"),f.setAttribute("allow","payment"),f.tabIndex=0,f.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}try{let b=await new Promise((A,k)=>{let S=!1,v=0,N=0,re=0,T=!1,G=()=>{window.clearTimeout(v),window.clearInterval(N),window.clearTimeout(re),window.removeEventListener("message",fe),f.removeEventListener("load",de),e.signal?.removeEventListener("abort",Y)},$=async()=>{if(!(S||T)){T=!0;try{let De=await l();if(S||!gd(De))return;S=!0,G(),A(De)}finally{T=!1}}},de=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(re),re=window.setTimeout(()=>{$()},250))},Y=()=>{S||(S=!0,G(),k(new Je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},fe=De=>{if(De.source!==f.contentWindow||h&&De.origin!==h)return;let ne=De.data;!ne||typeof ne!="object"||ne.source!=="flopay-vault-3ds-return"||S||(S=!0,G(),A(null))};v=window.setTimeout(()=>{S||(S=!0,G(),k(new Je.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},wl),e.pollCompletionEndpoint!==!1&&(N=window.setInterval(()=>{$()},t)),f.addEventListener("load",de),window.addEventListener("message",fe),e.signal?.addEventListener("abort",Y),f.src=e.nextActionRedirectUrl,p.appendChild(f),document.body.appendChild(p),f.focus(),e.signal?.aborted&&Y()});return b||await l()}finally{p.parentNode?.removeChild(p),d?.isConnected&&d.focus()}}async function Eo(e,t){let n=t.nonce??t.session.clientSecret,r=new no.PaymentAPI(t.billingApiUrl,{telemetry:!1}),o=new AbortController,a=new AbortController,l=()=>{o.abort(t.signal.reason),a.abort(t.signal.reason)};t.signal.aborted?l():t.signal.addEventListener("abort",l,{once:!0});let d=$i({billingApiUrl:t.billingApiUrl,sessionId:t.sessionId,nonce:n,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1}),p=null,f=()=>(p??(p=r.waitForCheckoutSessionCompletion(t.sessionId,{initialDelayMs:md,nonce:n,statusUrl:`${t.billingApiUrl.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/status`,continueAfterActionRequired:!0,timeoutMs:wl,signal:a.signal})),p),h=f(),b;try{let k=await Promise.race([d.then(S=>({kind:"challenge",outcome:S})),h.then(S=>({kind:"status",session:S}))]);if(k.kind==="status")o.abort(),b=k.session;else{if(k.outcome.status==="declined")throw Er({type:k.outcome.declineReason??"authorization_declined",message:"Card was declined.",gatewayErrorCode:k.outcome.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});b=await f()}}catch(k){throw t.signal.aborted||k instanceof Error&&k.name==="AbortError"?ia(k):k}finally{t.signal.removeEventListener("abort",l),o.abort(),a.abort()}let A=Zr(b,t.session);if(!Hr(A))throw Po(A);return{...Or(A,t.sessionId),checkoutMethod:"card"}}function hd(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"authorized":return{status:"authorized",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Er(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=Wr(o)??o,l=qi(new Je.FloPayError(a,"api_error",{code:e?.code??(0,Je.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Je.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(l.orderId=e.orderId),l}function Ui(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ka(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Il(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Ka(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let d of a)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||Ka(d)))return d;let l=o.gateways;if(l&&typeof l=="object"){let d=l.stripe;if(d&&typeof d=="object"){let p=d,f=[p.stripeClientSecret,p.clientSecret];for(let h of f)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||Ka(h)))return h}}}}async function bd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Il(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new no.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ka(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function To({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let d=e.replace(/\/+$/,""),p=t??n.id,f=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",A=n.customer?.firstName??n.accountData?.firstName??"",k=n.customer?.lastName??n.accountData?.lastName??"",S=n.customer?.country??n.accountData?.country??void 0,v=n.customer?.zip??n.accountData?.zip??void 0,re=await new no.PaymentAPI(d,l===!1?{telemetry:!1}:void 0).processPayment(h,{sessionId:p,nonce:f,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:h,email:b,firstName:A,lastName:k,country:S,zip:v},returnUrl:a??Ui(n)});if(re.ok){let $=typeof re.json=="function"?await re.json().catch(()=>null):null;if((0,Je.isAuthorizationOnlySession)(n)||$?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof $?.paymentId=="string"?$.paymentId:n.paymentId,sessionId:typeof $?.sessionId=="string"?$.sessionId:p,authorizationExpiresAt:typeof $?.authorizationExpiresAt=="string"?$.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Yo(o),checkoutMethod:Sl(o,n)}};let de=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...de?{paymentIntentId:de}:{},paymentMethodId:Yo(o),checkoutMethod:Sl(o,n)}}}let T;try{T=await re.json()}catch($){throw new Je.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:re.status,cause:$})}if(T?.type==="3ds_required"&&typeof T.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:T.nextActionRedirectUrl};if(T?.type==="paypal_redirect_required"||T?.type==="3ds_required"){let $=Il(T);if(!$)throw new Je.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:re.status});return{type:T.type,threeDSecureToken:$,paymentMethodId:T.paymentMethodId}}if(T?.gatewayErrorCode==="authentication_required"){let $=await bd({billingApiUrl:d,sessionId:p,nonce:f,responseJson:T});if($)return $;throw qi(new Je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let G=new Je.FloPayError(T?.message??"Payment failed. Please try again.","api_error",{code:T?.code??T?.gatewayErrorCode,declineCode:T?.declineCode??T?.gatewayDeclineReason,statusCode:re.status});throw Object.assign(G,{telemetryOutcome:(0,Je.classifyPaymentRejection)(re.status,T)})}async function Ga(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:d,telemetry:p,signal:f}){let h=t?.getRawProvider();if(!h)throw Ur(new Je.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw qi(new Je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let b=(0,Je.isSetupIntentClientSecret)(e.threeDSecureToken),A=null,k=e.paymentMethodId,S=await oa(()=>yd(h,e.threeDSecureToken,b),"card");if(S){if(S.error)throw Ur(new Je.FloPayError(S.error.message??`Failed to retrieve 3DS ${b?"setup":"payment"} status.`,"api_error",{code:S.error.code}),"card");let N=S.intent;!k&&N?.payment_method&&(typeof N.payment_method=="string"?k=N.payment_method:"id"in N.payment_method&&(k=N.payment_method.id??void 0))}let v=k?await oa(()=>fd(h,e.threeDSecureToken,{payment_method:k,return_url:d??Ui(l)??window.location.href},b),"card"):null;if(v){if(v.error)throw Ur(new Je.FloPayError(v.error.message??"3DS authentication failed.","api_error",{code:v.error.code}),"card");A=v.intent}else{let N=await oa(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(N.error)throw Ur(new Je.FloPayError(N.error.message??"3DS authentication failed.","api_error",{code:N.error.code}),"card");A=(b?N.setupIntent:N.paymentIntent)??null}if(A&&(A.status==="requires_capture"||A.status==="succeeded"||A.status==="processing")){let N=await To({billingApiUrl:o,sessionId:a,session:l,telemetry:p,tokenizedData:{id:A.id,type:"card",threeDSecureActionResultTokenId:A.id},returnUrl:d});return N.type==="success"?{...N.result,paymentIntentId:N.result.paymentIntentId??A.id,paymentMethodId:N.result.paymentMethodId??k}:N.type==="next_action_required"?Eo(N,{billingApiUrl:o,sessionId:a??l.id,session:l,signal:f}):Ga(N,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:d,telemetry:p,signal:f})}throw Ur(new Je.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let b=(n??t)?.getRawProvider();if(!b)throw Ur(new Je.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:k}=await oa(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(k)throw Ur(new Je.FloPayError(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:A}=await oa(()=>b.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Ui(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(A)throw Ur(new Je.FloPayError(A.message??"PayPal authorization failed.","api_error",{code:A.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Je.FloPayError("Unsupported payment redirect state.","api_error")}function sa(e){if(e instanceof Je.FloPayError){let r=Wr(e.message);return r&&r!==e.message?Object.assign(new Je.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,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=Wr(t)??t;return new Je.FloPayError(n,"api_error")}function ji(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Vr(e.data.session);if(!t&&!n&&!r)throw new Je.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function Sl(e,t){return e?e.isPaypal?"paypal":"card":t&&Vr(t)?"card":void 0}async function Vi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=t&&t!==e?t:void 0,[l,d]=await Promise.all([(0,no.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,no.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(f=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",f),null)):Promise.resolve(null)]);if(!l)throw new Je.FloPayError("The payment provider did not initialize.","authentication_error");let p=null;return a?p=d:t&&(p=l),{flopay:l,paypalFlopay:p}}var yr=require("@flopay/js"),y=require("@flopay/shared"),Yt=require("@stripe/react-stripe-js"),i=Xs(require("react"),1);function Ao(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Ya(e,t){if(e)return{error:n=>e.error(Ao(t,n)),log:n=>e.log(Ao(t,n)),performance:n=>e.performance(Ao(t,n)),terminal:n=>e.terminal(Ao(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 Rl={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 $n=require("react");function _l(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(l=>l.startsWith("background")),a={};for(let[l,d]of Object.entries(e))l in n||o&&l.startsWith("background")||(a[l]=d);for(let l of r)a[l]=n[l];return a}var Pd=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 vd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Pd.has(t.charAt(0).toLowerCase()+t.slice(1))}function Cd(e,t){return typeof t=="number"&&t!==0&&!vd(e)?`${t}px`:String(t).trim()}function El(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]=Cd(n,r)}}}var Tl=require("react/jsx-runtime"),Wi=new WeakSet;function xo({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:l,onReady:d,onError:p,onValidation:f}){let h=(0,$n.useRef)(null),b=(0,$n.useRef)(d),A=(0,$n.useRef)(p),k=(0,$n.useRef)(f);b.current=d,A.current=p,k.current=f;let S=(0,$n.useRef)(o);S.current=o;let v=(0,$n.useRef)(null),N=a??void 0,re=(0,$n.useRef)(N);re.current=N;let T=(0,$n.useRef)(void 0);return(0,$n.useEffect)(()=>{let G=h.current;if(!G)return;let $=!0,de=!1,Y=()=>{!$||de||(de=!0,b.current?.())},fe=e.on("ready",()=>{Y()}),De=e.on("error",te=>{A.current?.(te.message??"There was a problem loading the secure card form.")}),ne=e.on("validation",te=>{k.current?.(te.message??null)}),$e=re.current??(Wi.has(e)?null:void 0),ft={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...S.current?{theme:S.current}:{},...$e===void 0?{}:{submitLabel:$e}};return v.current=S.current??null,T.current=re.current,re.current!==void 0&&Wi.add(e),e.mount(G,ft).then(()=>{Y()}).catch(te=>{$&&A.current?.(te instanceof Error?te.message:"Failed to load the secure card form.")}),()=>{$=!1,fe(),De(),ne(),e.unmount()}},[e,t,n,r]),eo(()=>{let G=h.current;G&&El(G,l)},[l]),(0,$n.useEffect)(()=>{o!==void 0&&(o===null&&v.current===null||(v.current=o,e.applyTheme?.(o)))},[e,o]),(0,$n.useEffect)(()=>{N!==T.current&&(T.current=N,N!==void 0&&Wi.add(e),e.setSubmitLabel?.(N??null))},[e,N]),(0,Tl.jsx)("div",{ref:h,"data-testid":"flopay-vault-card-fields"})}var xl=/^#([0-9a-f]{6})$/i,Sd=/^#([0-9a-f]{3})$/i,Ml=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Bl=/^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,wd=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,kd=/^(-?\d+(?:\.\d+)?)(?:px)?$/,Id=/^(-?\d+(?:\.\d+)?)em$/,Rd=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,_d=/^[a-z][a-z0-9 -]{0,31}$/i,Ed=new Set(["none","uppercase","lowercase","capitalize"]);function Fl(e){if(typeof e!="string")return null;let t=e.trim(),n=xl.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=Sd.exec(t);if(r){let[h,b,A]=r[1].split("").map(k=>Number.parseInt(k+k,16));return{r:h,g:b,b:A,a:null}}let o=Ml.exec(t),a=o?null:Bl.exec(t),l=o??a;if(!l)return null;let d=Number(l[1]),p=Number(l[2]),f=Number(l[3]);return d>255||p>255||f>255?null:{r:d,g:p,b:f,a:a?Number(a[4]):null}}function Dl({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 la(e){if(typeof e!="string")return;let t=e.trim();if(xl.test(t)||Ml.test(t))return t;let n=Bl.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=Fl(t);return r?Dl(r):void 0}function Xa(e,t=.12){let n=Fl(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Dl({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function ca(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 ro(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=kd.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Td(e,t,n){if(typeof e!="string")return;let r=Id.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Ad(e){let t=ca(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=ca(o," "),l=la(a[0]);if(!l)return;let d=r/(t.length-1)*100,p=a[1]===void 0?d:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),f=n[n.length-1]?.position??-1;if(!Number.isFinite(p)||p<0||p>100||p<f)return;n.push({color:l,position:p})}return{type:"linearGradient",angle:0,stops:n}}function xd(e){if(typeof e!="string")return;let t=e.trim(),n=la(t);if(n)return{type:"solid",color:n};let r=wd.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=Ad(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function Md(e){return e.type==="solid"?{type:"solid",color:Xa(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:Xa(t.color)}))}}function Bd(e){let t=!1,n,r=[];for(let p of ca(e," ")){if(p.toLowerCase()==="inset"){t=!0;continue}let f=la(p);if(f){n=f;continue}let h=ro(p,-128,128);if(h===void 0)return;r.push(h)}if(!n||r.length<2||r.length>4)return;let[o,a,l=0,d=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||l>128||Math.abs(d)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:l,spread:d}}function Fd(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=ca(t,",").map(Bd);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function Al(e){if(typeof e!="string")return;let t=ca(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>_d.test(n)).slice(0,4);return t.length>0?t:void 0}function Dd(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=ro(t[0],0,64),r=ro(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function Ld(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 Ll({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=xd(r.background??r.backgroundColor),l=la(o?.colorPrimaryHover),d=l?{type:"solid",color:l}:a&&Md(a),p={fontFamilies:Al(r.fontFamily)??Al(n),fontSize:ro(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:Ld(r.fontWeight)??600,letterSpacing:Td(r.letterSpacing,-.1,.5)??.01,lineHeight:ro(r.lineHeight,.8,2)??1,textTransform:Ed.has(String(r.textTransform))?r.textTransform:"uppercase"},f=Dd(r.padding),h=Fd(r.boxShadow),b=ro(r.borderRadius,0,9999),A=typeof r.backdropFilter=="string"?ro(Rd.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:la(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...d?{hoverBackground:d}:{},typography:p,...f?{spacing:f}:{},...h?{shadow:h}:{},...b===void 0?{}:{borderRadius:b},disabledOpacity:e?.theme==="night"?.8:.6,...A===void 0?{}:{backdropBlur:A}}}function Mo(e,t=.12){let n=e.trim(),r=/^[0-9a-fA-F]{6}$/.test(n)?`#${n}`:n;return/^#[0-9a-fA-F]{6}$/.test(r)?Xa(r,t):e}function Hi(e){if(typeof e=="number"||typeof e=="string")return e}function Ja({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=b=>typeof b=="string"&&b?b:void 0,a=t.submitButton,l=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",d=n==="buttons",p=t.nameInput,f=o(p?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",h=Ll({appearance:e,buttonsStyles:t,fontFamily:f});return{primaryColor:l,primaryHoverColor:o(r?.colorPrimaryHover)??Mo(l,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(p?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(d?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:f,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(Hi(p?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...h?{submitButton:h}:{}}}var c=require("react/jsx-runtime"),Tr="flopay_stripe_resume",Ol="flopay_wallet_resume",Yl="fw1",Od="fw2",Xl=300*1e3,Nd=900,zd=25e3,Ud=25e3,qd=1e4,Jl=["payment_intent","payment_intent_client_secret","redirect_status"],mr={provider:"paypal",paymentMethodCategory:"paypal"},Za={},Ki={};function Ut(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 ts(e){return`${Od}:${e}`}function Qa(e){return Ut(ts(e))}function ei(e,t){if(typeof window>"u")return null;let n=ts(e);try{let r=localStorage.getItem(n);if(!r)return null;let o=JSON.parse(r);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>Xl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Qa(e),null):o}catch{return Qa(e),null}}function $d(e){return Ut(ts(e.sessionId),e)}function Nl(e,t,n){let r=ei(e,t);return!r||r.clientSecret!==n?!1:Qa(e)}function Gi(e,t,n){if(typeof window>"u")return;ei(e,t)?.clientSecret===n&&Qa(e)}function jd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Yi(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let r=n?e.status==="succeeded":Go(e.status),o=jd(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function zl(e,t,n){let r=null;try{return await Promise.race([ol(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},qd),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Vd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Zl(e){return e instanceof y.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ti(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new yr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Zl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ua="flopay_paypal_resume",da=new Map;function Ql(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(ua);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function Wd(){if(typeof window>"u")return!1;let[e,t]=ns();return e?Ql(t)!==null:!1}function ns(){let e=new URLSearchParams(window.location.search);return Jl.map(t=>e.get(t))}function rs(){let e=new URL(window.location.href);for(let t of Jl)e.searchParams.delete(t);return e.toString()}function Hd(){Ut(ua),window.history.replaceState({},"",rs())}var Kd=250,Ul="Just a moment \u2014 we are finalizing your order. Please press pay again.",Gd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function os(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 ni({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new yr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Yd(e){return e instanceof y.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Xi(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function ec({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=Jr(n),l=a.firstName?a:Jr(r?.name);return Bn({email:(0,y.isValidEmail)(o)?o:r?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Xd({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=ec({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,y.isValidEmail)(l.email)?l:a(o,l)}var Jd=`
9
+ `})]})})}var Cl=require("@flopay/shared"),Pn=require("react");var Sl=require("react/jsx-runtime");function oa({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=(0,Pn.useState)(e instanceof Promise?null:e),[d,u]=(0,Pn.useState)(t instanceof Promise||!t?null:t),p=(0,Pn.useRef)(null),b=(0,Pn.useRef)(null),v=ko(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 dn(a)?.subscribe?.(v)},[v,a]),(0,Pn.useEffect)(()=>{if(!(!d||d===a))return dn(d)?.subscribe?.(v)},[v,a,d]),(0,Pn.useEffect)(()=>{if(!a)return;let w=dn(a);return p.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(h=>{w||l(h)},()=>{w||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{w=!0}},[v,e]),(0,Pn.useEffect)(()=>{let w=!1;if(!t){u(null);return}return t instanceof Promise?t.then(h=>{w||u(h)},()=>{w||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):u(t),()=>{w=!0}},[v,t]),(0,Pn.useEffect)(()=>{if(!a||b.current===a)return;b.current=a;let w=dn(a);w?.log({name:"checkout.rendered",stage:"checkout_render"}),v({class:"lifecycle",name:"checkout.rendered"}),w?.performance({stage:"checkout_render",durationMs:w.elapsed(p.current??0),durationMode:"machine"})},[v,a]);let M=(0,Cl.resolveBillingApiUrl)(n?.billingApiUrl),I=(0,Pn.useMemo)(()=>({flopay:a,paypalFlopay:d,billingApiUrl:M,emitInstrument:v}),[a,d,M,v]);return(0,Sl.jsx)(Zn.Provider,{value:I,children:o})}var Wa="flopay_recent_completion_";function Eo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Wa+e,JSON.stringify(t))}catch{}}function zi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Wa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Wa+e),!1):!0}catch{return!1}}async function Ha(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 Yr=require("@flopay/js"),je=require("@flopay/shared");var ia="card",md=1e3;async function yd(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function fd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Xr(e){return new je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Ui(){return new je.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function $i(e,t){return Object.assign(e,{checkoutMethod:t})}function qr(e,t){let n=e instanceof je.FloPayError?e:new je.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function aa(e,t){try{return await e()}catch(n){throw qr(n,t)}}function kl(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function gd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function ji(e){if(typeof document>"u"||typeof window>"u")throw new je.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw Xr();let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let v=new AbortController,M=()=>v.abort();e.signal?.aborted?v.abort():e.signal?.addEventListener("abort",M);let I=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 h=await w.json().catch(()=>null);return hd(h)}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",M)}},a,l=()=>e.pollCompletionEndpoint!==!1?o():(a??(a=o()),a),d=document.activeElement instanceof HTMLElement?document.activeElement:null,u=document.createElement("div");u.setAttribute("data-flopay-auto-3ds-overlay","1"),u.setAttribute("role","dialog"),u.setAttribute("aria-modal","true"),u.setAttribute("aria-label","Card authentication"),u.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let p=document.createElement("iframe");p.setAttribute("title","Card authentication"),p.setAttribute("allow","payment"),p.tabIndex=0,p.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let b=null;try{b=new URL(e.billingApiUrl,window.location.href).origin}catch{b=null}try{let v=await new Promise((M,I)=>{let w=!1,h=0,O=0,G=0,T=!1,Y=()=>{window.clearTimeout(h),window.clearInterval(O),window.clearTimeout(G),window.removeEventListener("message",he),p.removeEventListener("load",de),e.signal?.removeEventListener("abort",X)},U=async()=>{if(!(w||T)){T=!0;try{let De=await l();if(w||!gd(De))return;w=!0,Y(),M(De)}finally{T=!1}}},de=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(G),G=window.setTimeout(()=>{U()},250))},X=()=>{w||(w=!0,Y(),I(Xr()))},he=De=>{if(De.source!==p.contentWindow||b&&De.origin!==b)return;let re=De.data;!re||typeof re!="object"||re.source!=="flopay-vault-3ds-return"||w||(w=!0,Y(),M(null))};h=window.setTimeout(()=>{w||(w=!0,Y(),I(Ui()))},je.THREE_DS_CHALLENGE_WINDOW_MS),e.pollCompletionEndpoint!==!1&&(O=window.setInterval(()=>{U()},t)),p.addEventListener("load",de),window.addEventListener("message",he),e.signal?.addEventListener("abort",X),p.src=e.nextActionRedirectUrl,u.appendChild(p),document.body.appendChild(u),p.focus(),e.signal?.aborted&&X()});return v||await l()}finally{u.parentNode?.removeChild(u),d?.isConnected&&d.focus()}}async function To(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,a=t.nonce??t.session.clientSecret,l=new Yr.PaymentAPI(n,{telemetry:!1}),d=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,u=new AbortController,p=new AbortController,b=()=>{u.abort(o.reason),p.abort(o.reason)};o.aborted?b():o.addEventListener("abort",b,{once:!0});let v=ji({billingApiUrl:n,sessionId:r,nonce:a,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:u.signal,pollCompletionEndpoint:!1}),M=l.waitForCheckoutSessionCompletion(r,{initialDelayMs:md,nonce:a,statusUrl:d,continueAfterActionRequired:!0,timeoutMs:je.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:p.signal}),I;try{let h=await Promise.race([v,M]);if("data"in h)I=h;else{if(h.status==="declined")throw Er({type:h.declineReason??"authorization_declined",gatewayErrorCode:h.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(h.status==="timeout")throw Ui();I=await M}}catch(h){if(o.aborted||h instanceof Error&&h.name==="AbortError")throw Xr(h);if(!(h instanceof je.FloPayError)||h.code!=="three_ds_timeout"&&h.code!=="checkout_processing_timeout")throw h;try{I=await l.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:a,statusUrl:d,timeoutMs:5e3,signal:o})}catch(G){if(o.aborted)throw Xr(G);if(!(G instanceof je.FloPayError)||G.code!=="checkout_processing_timeout")throw G}let O=I&&Kr(I,t.session);if(!Nr(O)&&O?.status!=="expired"){if(t.telemetry){let G=new Yr.PaymentAPI(n);try{G.reportThreeDsAbandoned(r)}finally{G.destroy()}}throw Ui()}}finally{o.removeEventListener("abort",b),u.abort(),p.abort()}let w=I&&Kr(I,t.session);if(!Nr(w))throw vo(w);return{...Lr(w,r),checkoutMethod:"card"}}function hd(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 Er(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=Hr(o)??o,l=$i(new je.FloPayError(a,"api_error",{code:e?.code??(0,je.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,je.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(l.orderId=e.orderId),l}function qi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ka(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Il(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Ka(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let d of a)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||Ka(d)))return d;let l=o.gateways;if(l&&typeof l=="object"){let d=l.stripe;if(d&&typeof d=="object"){let u=d,p=[u.stripeClientSecret,u.clientSecret];for(let b of p)if(typeof b=="string"&&b.length>0&&(!t?.requirePaymentIntentClientSecret||Ka(b)))return b}}}}async function bd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Il(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new Yr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ka(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function Ao({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let d=e.replace(/\/+$/,""),u=t??n.id,p=r??n.clientSecret,b=n.customer?.id??n.accountData?.userId??"",v=n.customer?.email??n.accountData?.email??"",M=n.customer?.firstName??n.accountData?.firstName??"",I=n.customer?.lastName??n.accountData?.lastName??"",w=n.customer?.country??n.accountData?.country??void 0,h=n.customer?.zip??n.accountData?.zip??void 0,G=await new Yr.PaymentAPI(d,l===!1?{telemetry:!1}:void 0).processPayment(b,{sessionId:u,nonce:p,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:b,email:v,firstName:M,lastName:I,country:w,zip:h},returnUrl:a??qi(n)});if(G.ok){let U=typeof G.json=="function"?await G.json().catch(()=>null):null;if((0,je.isAuthorizationOnlySession)(n)||U?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof U?.paymentId=="string"?U.paymentId:n.paymentId,sessionId:typeof U?.sessionId=="string"?U.sessionId:u,authorizationExpiresAt:typeof U?.authorizationExpiresAt=="string"?U.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Xo(o),checkoutMethod:wl(o,n)}};let de=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...de?{paymentIntentId:de}:{},paymentMethodId:Xo(o),checkoutMethod:wl(o,n)}}}let T;try{T=await G.json()}catch(U){throw new je.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:G.status,cause:U})}if(T?.type==="3ds_required"&&typeof T.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:T.nextActionRedirectUrl};if(T?.type==="paypal_redirect_required"||T?.type==="3ds_required"){let U=Il(T);if(!U)throw new je.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:G.status});return{type:T.type,threeDSecureToken:U,paymentMethodId:T.paymentMethodId}}if(T?.gatewayErrorCode==="authentication_required"){let U=await bd({billingApiUrl:d,sessionId:u,nonce:p,responseJson:T});if(U)return U;throw $i(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let Y=new je.FloPayError(T?.message??"Payment failed. Please try again.","api_error",{code:T?.code??T?.gatewayErrorCode,declineCode:T?.declineCode??T?.gatewayDeclineReason,statusCode:G.status});throw Object.assign(Y,{telemetryOutcome:(0,je.classifyPaymentRejection)(G.status,T)})}async function Ga(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:d,telemetry:u,signal:p}){let b=t?.getRawProvider();if(!b)throw qr(new je.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw $i(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let v=(0,je.isSetupIntentClientSecret)(e.threeDSecureToken),M=null,I=e.paymentMethodId,w=await aa(()=>yd(b,e.threeDSecureToken,v),"card");if(w){if(w.error)throw qr(new je.FloPayError(w.error.message??`Failed to retrieve 3DS ${v?"setup":"payment"} status.`,"api_error",{code:w.error.code}),"card");let O=w.intent;!I&&O?.payment_method&&(typeof O.payment_method=="string"?I=O.payment_method:"id"in O.payment_method&&(I=O.payment_method.id??void 0))}let h=I?await aa(()=>fd(b,e.threeDSecureToken,{payment_method:I,return_url:d??qi(l)??window.location.href},v),"card"):null;if(h){if(h.error)throw qr(new je.FloPayError(h.error.message??"3DS authentication failed.","api_error",{code:h.error.code}),"card");M=h.intent}else{let O=await aa(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(O.error)throw qr(new je.FloPayError(O.error.message??"3DS authentication failed.","api_error",{code:O.error.code}),"card");M=(v?O.setupIntent:O.paymentIntent)??null}if(M&&(M.status==="requires_capture"||M.status==="succeeded"||M.status==="processing")){let O=await Ao({billingApiUrl:o,sessionId:a,session:l,telemetry:u,tokenizedData:{id:M.id,type:"card",threeDSecureActionResultTokenId:M.id},returnUrl:d});return O.type==="success"?{...O.result,paymentIntentId:O.result.paymentIntentId??M.id,paymentMethodId:O.result.paymentMethodId??I}:O.type==="next_action_required"?To(O,{billingApiUrl:o,sessionId:a??l.id,session:l,signal:p}):Ga(O,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:d,telemetry:u,signal:p})}throw qr(new je.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let v=(n??t)?.getRawProvider();if(!v)throw qr(new je.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:I}=await aa(()=>v.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(I)throw qr(new je.FloPayError(I.message??"PayPal authorization failed.","api_error",{code:I.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:M}=await aa(()=>v.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??qi(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(M)throw qr(new je.FloPayError(M.message??"PayPal authorization failed.","api_error",{code:M.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new je.FloPayError("Unsupported payment redirect state.","api_error")}function sa(e){if(e instanceof je.FloPayError){let r=Hr(e.message);return r&&r!==e.message?Object.assign(new je.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,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=Hr(t)??t;return new je.FloPayError(n,"api_error")}function Vi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Wr(e.data.session);if(!t&&!n&&!r)throw new je.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function wl(e,t){return e?e.isPaypal?"paypal":"card":t&&Wr(t)?"card":void 0}async function Wi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=t&&t!==e?t:void 0,[l,d]=await Promise.all([(0,Yr.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,Yr.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(p=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",p),null)):Promise.resolve(null)]);if(!l)throw new je.FloPayError("The payment provider did not initialize.","authentication_error");let u=null;return a?u=d:t&&(u=l),{flopay:l,paypalFlopay:u}}var fr=require("@flopay/js"),y=require("@flopay/shared"),Jt=require("@stripe/react-stripe-js"),i=Js(require("react"),1);function xo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Ya(e,t){if(e)return{error:n=>e.error(xo(t,n)),log:n=>e.log(xo(t,n)),performance:n=>e.performance(xo(t,n)),terminal:n=>e.terminal(xo(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 Rl={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 $n=require("react");function _l(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(l=>l.startsWith("background")),a={};for(let[l,d]of Object.entries(e))l in n||o&&l.startsWith("background")||(a[l]=d);for(let l of r)a[l]=n[l];return a}var Pd=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 vd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Pd.has(t.charAt(0).toLowerCase()+t.slice(1))}function Cd(e,t){return typeof t=="number"&&t!==0&&!vd(e)?`${t}px`:String(t).trim()}function El(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]=Cd(n,r)}}}var Tl=require("react/jsx-runtime"),Hi=new WeakSet;function Mo({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:l,onReady:d,onError:u,onValidation:p}){let b=(0,$n.useRef)(null),v=(0,$n.useRef)(d),M=(0,$n.useRef)(u),I=(0,$n.useRef)(p);v.current=d,M.current=u,I.current=p;let w=(0,$n.useRef)(o);w.current=o;let h=(0,$n.useRef)(null),O=a??void 0,G=(0,$n.useRef)(O);G.current=O;let T=(0,$n.useRef)(void 0);return(0,$n.useEffect)(()=>{let Y=b.current;if(!Y)return;let U=!0,de=!1,X=()=>{!U||de||(de=!0,v.current?.())},he=e.on("ready",()=>{X()}),De=e.on("error",te=>{M.current?.(te.message??"There was a problem loading the secure card form.")}),re=e.on("validation",te=>{I.current?.(te.message??null)}),Ve=G.current??(Hi.has(e)?null:void 0),yt={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...w.current?{theme:w.current}:{},...Ve===void 0?{}:{submitLabel:Ve}};return h.current=w.current??null,T.current=G.current,G.current!==void 0&&Hi.add(e),e.mount(Y,yt).then(()=>{X()}).catch(te=>{U&&M.current?.(te instanceof Error?te.message:"Failed to load the secure card form.")}),()=>{U=!1,he(),De(),re(),e.unmount()}},[e,t,n,r]),no(()=>{let Y=b.current;Y&&El(Y,l)},[l]),(0,$n.useEffect)(()=>{o!==void 0&&(o===null&&h.current===null||(h.current=o,e.applyTheme?.(o)))},[e,o]),(0,$n.useEffect)(()=>{O!==T.current&&(T.current=O,O!==void 0&&Hi.add(e),e.setSubmitLabel?.(O??null))},[e,O]),(0,Tl.jsx)("div",{ref:b,"data-testid":"flopay-vault-card-fields"})}var xl=/^#([0-9a-f]{6})$/i,Sd=/^#([0-9a-f]{3})$/i,Ml=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Bl=/^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,wd=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,kd=/^(-?\d+(?:\.\d+)?)(?:px)?$/,Id=/^(-?\d+(?:\.\d+)?)em$/,Rd=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,_d=/^[a-z][a-z0-9 -]{0,31}$/i,Ed=new Set(["none","uppercase","lowercase","capitalize"]);function Fl(e){if(typeof e!="string")return null;let t=e.trim(),n=xl.exec(t);if(n){let b=Number.parseInt(n[1],16);return{r:b>>16&255,g:b>>8&255,b:b&255,a:null}}let r=Sd.exec(t);if(r){let[b,v,M]=r[1].split("").map(I=>Number.parseInt(I+I,16));return{r:b,g:v,b:M,a:null}}let o=Ml.exec(t),a=o?null:Bl.exec(t),l=o??a;if(!l)return null;let d=Number(l[1]),u=Number(l[2]),p=Number(l[3]);return d>255||u>255||p>255?null:{r:d,g:u,b:p,a:a?Number(a[4]):null}}function Dl({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 la(e){if(typeof e!="string")return;let t=e.trim();if(xl.test(t)||Ml.test(t))return t;let n=Bl.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=Fl(t);return r?Dl(r):void 0}function Xa(e,t=.12){let n=Fl(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Dl({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function ca(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 oo(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=kd.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Td(e,t,n){if(typeof e!="string")return;let r=Id.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Ad(e){let t=ca(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=ca(o," "),l=la(a[0]);if(!l)return;let d=r/(t.length-1)*100,u=a[1]===void 0?d:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),p=n[n.length-1]?.position??-1;if(!Number.isFinite(u)||u<0||u>100||u<p)return;n.push({color:l,position:u})}return{type:"linearGradient",angle:0,stops:n}}function xd(e){if(typeof e!="string")return;let t=e.trim(),n=la(t);if(n)return{type:"solid",color:n};let r=wd.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=Ad(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function Md(e){return e.type==="solid"?{type:"solid",color:Xa(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:Xa(t.color)}))}}function Bd(e){let t=!1,n,r=[];for(let u of ca(e," ")){if(u.toLowerCase()==="inset"){t=!0;continue}let p=la(u);if(p){n=p;continue}let b=oo(u,-128,128);if(b===void 0)return;r.push(b)}if(!n||r.length<2||r.length>4)return;let[o,a,l=0,d=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||l>128||Math.abs(d)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:l,spread:d}}function Fd(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=ca(t,",").map(Bd);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function Al(e){if(typeof e!="string")return;let t=ca(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>_d.test(n)).slice(0,4);return t.length>0?t:void 0}function Dd(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=oo(t[0],0,64),r=oo(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function Od(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 Ol({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=xd(r.background??r.backgroundColor),l=la(o?.colorPrimaryHover),d=l?{type:"solid",color:l}:a&&Md(a),u={fontFamilies:Al(r.fontFamily)??Al(n),fontSize:oo(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:Od(r.fontWeight)??600,letterSpacing:Td(r.letterSpacing,-.1,.5)??.01,lineHeight:oo(r.lineHeight,.8,2)??1,textTransform:Ed.has(String(r.textTransform))?r.textTransform:"uppercase"},p=Dd(r.padding),b=Fd(r.boxShadow),v=oo(r.borderRadius,0,9999),M=typeof r.backdropFilter=="string"?oo(Rd.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:la(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...d?{hoverBackground:d}:{},typography:u,...p?{spacing:p}:{},...b?{shadow:b}:{},...v===void 0?{}:{borderRadius:v},disabledOpacity:e?.theme==="night"?.8:.6,...M===void 0?{}:{backdropBlur:M}}}function Bo(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)?Xa(r,t):e}function Ki(e){if(typeof e=="number"||typeof e=="string")return e}function Ja({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=v=>typeof v=="string"&&v?v:void 0,a=t.submitButton,l=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",d=n==="buttons",u=t.nameInput,p=o(u?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",b=Ol({appearance:e,buttonsStyles:t,fontFamily:p});return{primaryColor:l,primaryHoverColor:o(r?.colorPrimaryHover)??Bo(l,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(u?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(d?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:p,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(Ki(u?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...b?{submitButton:b}:{}}}var c=require("react/jsx-runtime"),Tr="flopay_stripe_resume",Ll="flopay_wallet_resume",Yl="fw1",Ld="fw2",Xl=300*1e3,Nd=900,zd=25e3,Ud=25e3,qd=1e4,Jl=["payment_intent","payment_intent_client_secret","redirect_status"],yr={provider:"paypal",paymentMethodCategory:"paypal"},Za={},Gi={};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 ns(e){return`${Ld}:${e}`}function Qa(e){return $t(ns(e))}function ei(e,t){if(typeof window>"u")return null;let n=ns(e);try{let r=localStorage.getItem(n);if(!r)return null;let o=JSON.parse(r);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>Xl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Qa(e),null):o}catch{return Qa(e),null}}function $d(e){return $t(ns(e.sessionId),e)}function Nl(e,t,n){let r=ei(e,t);return!r||r.clientSecret!==n?!1:Qa(e)}function Yi(e,t,n){if(typeof window>"u")return;ei(e,t)?.clientSecret===n&&Qa(e)}function jd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Xi(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let r=n?e.status==="succeeded":Yo(e.status),o=jd(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function zl(e,t,n){let r=null;try{return await Promise.race([al(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},qd),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Vd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Zl(e){return e instanceof y.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ti(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new fr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Zl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ua="flopay_paypal_resume",da=new Map;function Ql(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(ua);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function Wd(){if(typeof window>"u")return!1;let[e,t]=rs();return e?Ql(t)!==null:!1}function rs(){let e=new URLSearchParams(window.location.search);return Jl.map(t=>e.get(t))}function os(){let e=new URL(window.location.href);for(let t of Jl)e.searchParams.delete(t);return e.toString()}function Hd(){$t(ua),window.history.replaceState({},"",os())}var Kd=250,Ul="Just a moment \u2014 we are finalizing your order. Please press pay again.",Gd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function as(e,t,n,r){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...r?{terminalReason:r}:{}})}async function ni({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new fr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Yd(e){return e instanceof y.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ji(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function ec({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=eo(n),l=a.firstName?a:eo(r?.name);return Bn({email:(0,y.isValidEmail)(o)?o:r?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Xd({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=ec({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,y.isValidEmail)(l.email)?l:a(o,l)}var Jd=`
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 @@ ${nt.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
- `,pa=44,ma=180,ql=`flopay-card-enter ${ma}ms cubic-bezier(0, 0, 0.2, 1) both`,$l=`flopay-card-exit ${ma}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Zd=`flopay-buttons-enter ${ma}ms cubic-bezier(0, 0, 0.2, 1) both`,Qd=`flopay-buttons-exit ${ma}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function eu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function as(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 tu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function nu(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 Zi={width:"100%",minHeight:pa,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function ru(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function jl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Qi(e){return e==="paypal"?"PayPal":(0,y.getStripeMethodDisplayName)(e)}function ou(e){let t=(0,y.getPostalCodeExample)(e);return`Enter a valid ${(0,y.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function au(e,t,n){let r=(0,y.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,l=a&&!o,d=a&&!!o&&!(0,y.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:d}}function iu(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 Vl(e,t){return t instanceof y.FloPayError?t:new y.FloPayError(t instanceof Error?t.message:`${ru(e)} before-click hook failed.`,"validation_error")}function Ji(){return(0,c.jsx)("style",{children:Jd})}function su(e){return typeof e=="number"?`${e}px`:e}function tc(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function nc({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,c.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,c.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,c.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function Wl(e){return e!=="unavailable"&&e!=="load_error"}function ri(e){return(0,c.jsx)(cu,{...e})}function Hl({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:d,onDecline:p,onTechnicalFailure:f,runBeforeButtonClick:h,billingName:b,onBuyerIdentityReady:A,onLoadStateChange:k,placeholderBorderRadius:S,popupCapabilityOwner:v,externalTelemetryContext:N,presentationMode:re}){let T=zr(),{emitInstrument:G}=(0,i.useContext)(Zn),$=(0,Yt.useStripe)(),de=(0,Yt.useElements)(),Y=(0,i.useMemo)(()=>Ya(cn(T),N),[N,T]),[fe,De]=(0,i.useState)("loading");(0,i.useEffect)(()=>{k?.(fe)},[fe,k]);let[ne,$e]=(0,i.useState)(!1),ft=(0,i.useRef)(!1),te=!(0,y.isValidEmail)(n?.trim())||!b?.trim(),{request:Le,collect:gt,finish:Re}=vo(),Oe=(0,i.useRef)(!1),ge=(0,i.useRef)(null),pe=(0,i.useRef)(null),[_e,je]=(0,i.useState)(0),[ot,R]=(0,i.useState)(!1),Se=(0,i.useRef)(!1),ae=(0,i.useRef)(new Map),{startAttempt:O,finishAttempt:xe,invalidateAttempt:we,isAttemptInvalidated:Ue,isAttemptCurrent:Z,generationRef:at}=ea((z,be,Ve)=>{f?.(z,be,{...Ve,popupBlocked:Ve?.popupBlocked??Kr(be),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:re,terminalReason:"overlay_timeout"}),R(!0),je(W=>W+1)},{onHandoffObserved:()=>{v.markAvailable(),Y?.log({name:"provider.popup.opened",stage:"overlay_open",...mr,attempt:at.current})}});(0,i.useEffect)(()=>{ot&&pe.current?.focus()},[ot,_e]);let it=(0,i.useCallback)(()=>{je(z=>z+1)},[]),Fe=(0,i.useCallback)((z,be,Ve)=>{we(Ve),f?.("paypal",z,{code:be,popupBlocked:Kr(z),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:re}),R(!0),it()},[we,f,re,it]),ke=(0,i.useCallback)(()=>{window.setTimeout(()=>{(ge.current?.querySelector("iframe")??ge.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{Se.current&&(Se.current=!1,ke())},[ke,_e]);let Ze=(0,i.useCallback)(()=>{R(!1),a?.(null),ke()},[ke,a]);(0,i.useEffect)(()=>{if(!$||Oe.current)return;let[z,be,Ve]=ns();if(!z||!be)return;let W=Ql(be);if(!W)return;Oe.current=!0;let Ge=!0,wt=da.get(be);wt||(wt=Ve==="failed"?Promise.resolve(null):Promise.resolve().then(()=>$.retrievePaymentIntent(be)),da.set(be,wt));let Ye={accountPatch:W.accountPatch,sessionId:W.sessionId,nonce:W.nonce},u=()=>{Y?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...mr,requestCategory:"provider_sdk"})};return Y?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...mr}),(async()=>{try{$e(!0);let V=await wt;if(!Ge)return;if(V?.error){da.delete(be),u(),a?.(V.error.message??"Failed to retrieve PayPal payment status.");return}if(Hd(),da.delete(be),Ve==="failed"){let X="PayPal payment was declined. Please try again.";Y?.terminal({outcome:"payment_declined",...mr,terminalReason:"provider_declined"}),a?.(X),p?.(ln("paypal",X));return}let w=V?.paymentIntent;if(w&&w.id!==z){u(),a?.("Failed to match the returned PayPal payment.");return}if(w&&(w.status==="requires_capture"||w.status==="succeeded")){let X=typeof w.payment_method=="string"?w.payment_method:w.payment_method?.id;o({id:X??w.id,type:"card",threeDSecureActionResultTokenId:w.id,isPaypal:!0},{...Ye,presentationMode:"redirect"})}else{let X="PayPal payment was not completed. Please try again.";Y?.terminal({outcome:w?.status==="canceled"?"payment_cancelled":"payment_declined",...mr,terminalReason:w?.status==="canceled"?"cancelled":"provider_declined"}),a?.(X),p?.(ln("paypal",X))}}catch(V){if(!Ge)return;da.delete(be),u(),a?.(V instanceof Error?V.message:"Failed to complete PayPal payment.")}finally{Ge&&$e(!1)}})(),()=>{Ge=!1,Oe.current=!1}},[$,o,a,p,Y]);let Pt=(0,i.useCallback)(async(z=!1)=>{let be=h?await h("paypal"):{proceed:!0};if(!be.proceed)return ae.current.delete(_e),!1;let Ve=O("paypal");return ae.current.set(_e,{generation:Ve,accountPatch:be.accountPatch,sessionId:be.sessionId,nonce:be.nonce}),R(!1),Y?.log({name:`provider.${z?"redirect.started":"handoff.requested"}`,stage:z?"redirect":"overlay_open",...mr,attempt:Ve}),d?.("paypal"),!0},[d,Y,h,O,_e]),Ke=(0,i.useCallback)(async z=>{if(l||ne||!await Pt()){z.reject();return}z.resolve()},[l,Pt,ne]),tn=(0,i.useCallback)(async z=>{if(!$||!de)return;let be=ae.current.get(_e);if(be&&!Z(be.generation)){ae.current.delete(_e);return}if(!be&&Ue()||be&&!xe(be.generation))return;be||xe();let Ve=be??null;if(ae.current.delete(_e),!Ve&&h){let U=await h("paypal");if(!U.proceed){z.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Ve={accountPatch:U.accountPatch,sessionId:U.sessionId,nonce:U.nonce}}let W=Ve?.sessionId??e,Ge=Ve?.nonce??t,wt=await Xd({event:z,prepared:Ve,email:n,billingName:b,methodLabel:"PayPal",collect:gt});if(!wt){z.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ye=wt.email,u={...Ve?.accountPatch,...Bn(wt,!0)};try{if($e(!0),a?.(null),!W||!(0,y.isValidEmail)(Ye))throw new Error("Missing sessionId or email for PayPal payment");await A?.(wt);let U=$.createPaymentMethod,{error:V,paymentMethod:w}=await U({type:"paypal"});if(V){Fe(V,"stripe_paypal_create_payment_method_failed",be?.generation),z.paymentFailed({reason:"fail"});return}let X=await ti(r,G,W,Ge??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:w?.id??null,intentKind:"payment"});if(X.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let qe=X.clientSecret,Pe={return_url:rs()};if(w?.id&&(Pe.payment_method=w.id),!Ut(ua,{clientSecret:qe,sessionId:W,nonce:Ge,accountPatch:u})&&re==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:tt,paymentIntent:me}=await $.confirmPayment({clientSecret:qe,confirmParams:Pe,redirect:"if_required"});if(tt){if(Ut(ua),Xo(tt)){let _t=tt.message??"Your payment was declined.";Y?.terminal({outcome:"payment_declined",...mr,terminalReason:"provider_declined"}),a?.(_t),p?.(ln("paypal",_t,{code:_r(tt),declineCode:So(tt)})),await ni({billingApiUrl:r,sessionId:W,nonce:Ge,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:_r(tt)??"provider_declined"}})}else Fe(tt,"stripe_paypal_confirm_failed",be?.generation);return}Ut(ua);let pt=typeof me?.payment_method=="string"?me.payment_method:me?.payment_method?.id;o({id:pt??me?.id,type:"card",threeDSecureActionResultTokenId:me?.id,isPaypal:!0},{accountPatch:u,paymentMethodCategory:"paypal",presentationMode:re,sessionId:W,nonce:Ge});return}catch(U){Fe(U,"stripe_paypal_failed",be?.generation)}finally{$e(!1)}},[$,de,e,t,n,b,gt,A,r,G,o,a,p,h,Fe,xe,Z,Ue,Y,re,_e]),qt=(0,i.useCallback)(async()=>{if(!(ft.current||l||ne||!$||!de)){ft.current=!0,$e(!0);try{if(!await Pt(!0))return;await tn({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{ft.current=!1,$e(!1)}}},[de,tn,l,Pt,$,ne]),ut=re==="redirect"?(0,c.jsx)("button",{type:"button",disabled:l||ne,onClick:()=>{qt()},style:{width:"100%",minHeight:pa,border:"1px solid #d1d5db",borderRadius:S??8,background:"#ffc439",color:"#111827",cursor:l||ne?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,c.jsx)(Yt.ExpressCheckoutElement,{onReady:z=>De(tc(z,["paypal"])),onLoadError:()=>{De("load_error"),os(Y,"paypal","paypal","provider_error")},onClick:Ke,onConfirm:tn,onCancel:()=>{let z=ae.current.get(_e);ae.current.delete(_e),Y?.terminal({outcome:"payment_cancelled",...mr,terminalReason:"cancelled",...z?{attempt:z.generation}:{}}),we(z?.generation),R(!1),Se.current=!0,it()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:te,emailRequired:te,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},_e),lt=(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)("div",{ref:ge,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[ot&&(0,c.jsx)("button",{ref:pe,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ze,style:Zi,children:"Try PayPal again"}),Le&&(0,c.jsx)(Co,{identity:Le.identity,methodLabel:Le.methodLabel,onComplete:Re,onCancel:()=>Re(null)},Le.id),(0,c.jsx)("div",{style:{display:Le?"none":void 0},children:ut})]}),ne&&!Le&&(0,c.jsx)(er,{status:"processing"})]});return re==="redirect"?lt:(0,c.jsx)(nc,{state:fe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:S,children:lt})}function Kl({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:d,onButtonClick:p,onDecline:f,onTechnicalFailure:h,runBeforeButtonClick:b,billingName:A,onBuyerIdentityReady:k,onLoadStateChange:S,placeholderBorderRadius:v,popupCapabilityOwner:N,externalTelemetryContext:re}){let T=zr(),{emitInstrument:G}=(0,i.useContext)(Zn),$=(0,Yt.useStripe)(),de=(0,Yt.useElements)(),Y=(0,i.useMemo)(()=>Ya(cn(T),re),[re,T]),[fe,De]=(0,i.useState)("loading");(0,i.useEffect)(()=>{S?.(fe)},[fe,S]);let[ne,$e]=(0,i.useState)(!1),ft=(0,i.useRef)(!(0,y.isValidEmail)(n?.trim())||!A?.trim()).current,{request:te,collect:Le,finish:gt}=vo(),Re=(0,i.useRef)(null),Oe=(0,i.useRef)(null),[ge,pe]=(0,i.useState)(0),[_e,je]=(0,i.useState)(!1),[ot,R]=(0,i.useState)(()=>ei(e,t)?"blocked":"idle"),[Se,ae]=(0,i.useState)("google_pay"),O=(0,i.useRef)(null),xe=(0,i.useRef)(!0),we=(0,i.useRef)(!1),Ue=(0,i.useRef)("google_pay"),Z=(0,i.useRef)("google_pay"),at=(0,i.useRef)(null),it=(0,i.useRef)(null),Fe=(0,i.useRef)(new Set);(0,i.useEffect)(()=>(xe.current=!0,()=>{xe.current=!1;for(let u of Fe.current)window.clearTimeout(u);Fe.current.clear()}),[]);let ke=(0,i.useRef)(new Map),{startAttempt:Ze,finishAttempt:Pt,invalidateAttempt:Ke,isAttemptInvalidated:tn,isAttemptCurrent:qt,generationRef:ut}=ea((u,U,V)=>{h?.(u,U,{...V,popupBlocked:V?.popupBlocked??Kr(U),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ae(u),je(!0),pe(w=>w+1)},{onHandoffObserved:u=>{N.markAvailable(),Y?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ut.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})}});(0,i.useEffect)(()=>{_e&&Oe.current?.focus()},[_e,ge]);let lt=(0,i.useCallback)(()=>{pe(u=>u+1)},[]),z=(0,i.useCallback)((u,U,V,w,X=!1)=>{Ke(w),h?.(u,U,{code:V,popupBlocked:Kr(U),telemetryReported:X,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ae(u),je(!0),lt()},[Ke,h,lt]),be=(0,i.useCallback)(()=>{window.setTimeout(()=>{(Re.current?.querySelector("iframe")??Re.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{we.current&&(we.current=!1,be())},[be,ge]);let Ve=(0,i.useCallback)(()=>{je(!1),d?.(null),be()},[be,d]),W=(0,i.useCallback)(()=>{O.current?.()},[]);(0,i.useEffect)(()=>{let u=ei(e,t);if(!u)return;let U=!1,V=!1,w=async()=>{if(!V){V=!0,U||R("checking");try{let X=await zl($,u.clientSecret,Fe.current);if(U)return;let qe=Yi(X,u.providerObjectId,(0,y.isSetupIntentClientSecret)(u.clientSecret));if(qe.kind==="confirmed"){if(!Nl(e,t,u.clientSecret))return;O.current=null,R("idle"),l({id:qe.paymentMethodId,type:"card",threeDSecureActionResultTokenId:qe.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(qe.kind==="terminal"){Gi(e,t,u.clientSecret),O.current=null,R("idle"),ae(u.paymentMethodType),je(!0),lt();return}R("blocked")}catch{U||R("blocked")}finally{V=!1}}};return O.current=w,R("blocked"),()=>{U=!0,O.current===w&&(O.current=null)}},[t,l,lt,e,$]);let Ge=(0,i.useCallback)(async u=>{let U=!1,V=ve=>{U||(U=!0,u.paymentFailed({reason:"fail",...ve?{message:ve}:{}}))};if(!$||!de){V();return}let w=ke.current.get(ge);if(w&&!qt(w.generation)){ke.current.delete(ge),V();return}if(!w&&tn()){V();return}if(w&&!Pt(w.generation)){V();return}w||Pt();let X=u.expressPaymentType??w?.method??Ue.current,qe=w??null,Pe=jl(X),st;X==="apple_pay"?st="apple_pay":X==="google_pay"&&(st="google_pay");let tt=w?.generation??ut.current,me=Y,pt=me?.now()??globalThis.performance?.now()??Date.now(),_t=new AbortController,Pn=!1,nt=!1,$t=null,Ne=e,Fn="processing",Rn="other",Mt="provider_runtime",wn,Dn=new Promise((ve,vt)=>{wn=vt}),Ln=window.setTimeout(()=>{Pn=!0,_t.abort(),wn(Za)},zd),nn=async(ve,vt,Et)=>{Fn=ve,Rn=vt,Mt=vt==="intent_create"||vt==="session_claim"?"transport_error":"provider_runtime";let vn=me?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Et,Dn])}finally{let Bt=me?.now()??globalThis.performance?.now()??Date.now();me?.performance({stage:ve,durationMs:Math.max(0,Bt-vn),durationMode:"machine",requestCategory:vt,paymentMethodCategory:"wallet",provider:"stripe",...Pn?{statusClass:"timeout"}:{}})}};try{if($e(!0),d?.(null),!qe&&b){let Ee=await nn("processing","other",b(Pe));if(!Ee.proceed){V();return}qe={accountPatch:Ee.accountPatch,sessionId:Ee.sessionId,nonce:Ee.nonce}}let ve=qe?.sessionId??e;Ne=ve;let vt=qe?.nonce??t,Et=at.current??qe?.accountPatch,vn=ec({event:u,fallbackEmail:Et?.email??n,fallbackName:[Et?.firstName,Et?.lastName].join(" ").trim()||A});if(!(0,y.isValidEmail)(vn.email)){V("Buyer details are required."),Le(Qi(X),vn).then(Ee=>{Ee&&(at.current=Ee)});return}at.current=null;let Bt={...qe?.accountPatch,...Bn(vn,!0)};await nn("processing","session_claim",Promise.resolve(k?.(vn)));let{error:Vn}=await nn("tokenization","provider_sdk",de.submit());if(Vn){V(),z(X,Vn,"stripe_wallet_submit_failed",w?.generation);return}if(!ve)throw new Error("Missing sessionId or email for payment.");let un={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:X,paymentMethodId:null,intentKind:o},jt=JSON.stringify({sessionId:ve,nonce:vt??"",request:un}),on=it.current,Wn=on?.retryIdentity===jt?on.authorizationAttemptId:(0,y.randomUuidV4)();it.current={authorizationAttemptId:Wn,retryIdentity:jt};let pn=await nn("processing","intent_create",ti(r,G,ve,vt??"",{...un,authorizationAttemptId:Wn},{signal:_t.signal}));if(pn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ct=pn.clientSecret,Xt=$d({createdAt:Date.now(),sessionId:ve,...vt?{nonce:vt}:{},clientSecret:Ct,providerObjectId:pn.providerObjectId,paymentMethodType:X,accountPatch:Bt});window.clearTimeout(Ln),nt=!0,me?.performance({stage:"callback",durationMs:Math.max(0,(me?.now()??globalThis.performance?.now()??Date.now())-pt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let mn=me?.now()??globalThis.performance?.now()??Date.now(),Ft={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...st?{walletType:st}:{},attempt:tt},Jt=!1,Vt=null;me?.log({name:"payment.provider_confirmation.started",...Ft}),$t=window.setTimeout(()=>{$t!==null&&Fe.current.delete($t),Jt=!0;let Ee=me?.now()??globalThis.performance?.now()??Date.now();me?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Ft,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Ee-mn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),me?.flush?.().catch(()=>{}),Vt?.()},Ud),Fe.current.add($t);let yn=(Ee,bt)=>{$t!==null&&(window.clearTimeout($t),Fe.current.delete($t),$t=null);let ie=me?.now()??globalThis.performance?.now()??Date.now(),F=Math.max(0,ie-mn),Xe=Ee;Jt&&(Ee==="resolved"?Xe="resolved_late":Ee==="returned_error"?Xe="returned_error_late":Xe="rejected_late");let se=bt??(Ee==="resolved"?"approved":"provider_error");return me?.log({name:"payment.provider_confirmation.returned",...Ft,operationOutcome:Xe,terminalReason:se}),me?.performance({...Ft,durationMs:F,durationMode:"buyer",operationOutcome:Xe,terminalReason:se}),{durationMs:F,operationOutcome:Xe,terminalReason:se}},ht=!1,Q=!1,On=Ee=>{if(!Ee||typeof Ee!="object")return null;let bt=Ee;if(bt.error)return null;let ie=bt.setupIntent??bt.paymentIntent,F=Yi(ie??null,void 0,!!bt.setupIntent);return F.kind==="confirmed"?F:null},Nn=Ee=>{if(ht||w&&ut.current!==w.generation)return;let bt=On(Ee);if(!bt)return;if(Xt&&!Nl(ve,vt,Ct)){ht=!0;return}let{intentId:ie,paymentMethodId:F}=bt;ht=!0,Q=!0,it.current=null,O.current=null,xe.current&&(R("idle"),$e(!1));let Xe=`${Yl}:${ve}`;Ut(Xe,{createdAt:Date.now(),sessionId:ve,nonce:vt,accountPatch:Bt,paymentMethodId:F,providerIntentId:ie,paymentMethodType:X});try{l({id:F,type:"card",threeDSecureActionResultTokenId:ie},{accountPatch:Bt,paymentMethodCategory:"wallet",sessionId:ve,nonce:vt})}finally{Ut(Xe)}},hr=!1;Vt=async()=>{if(!(hr||ht||Q)){hr=!0,xe.current&&R("checking");try{let Ee=await zl($,Ct,Fe.current);if(ht||Q)return;let bt=(0,y.isSetupIntentClientSecret)(Ct),ie=Yi(Ee,pn.providerObjectId,bt);if(ie.kind==="confirmed"){Nn(bt?{setupIntent:Ee}:{paymentIntent:Ee});return}if(ie.kind==="terminal"){if(Q=!0,Gi(ve,vt,Ct),it.current=null,O.current=null,!xe.current)return;R("idle"),V(),z(X,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",w?.generation,!0);return}xe.current&&!Q&&(R("blocked"),$e(!1))}catch{xe.current&&!Q&&(R("blocked"),$e(!1))}finally{hr=!1}}},O.current=Vt;let Cn,an;try{let Ee=await((0,y.isSetupIntentClientSecret)(Ct)?$.confirmSetup({elements:de,clientSecret:Ct,redirect:"if_required"}):$.confirmPayment({elements:de,clientSecret:Ct,redirect:"if_required"}));if(!Ee||typeof Ee!="object"||(Cn=Ee,!Cn.error&&!On(Cn)))throw Ki;an=yn(Cn.error?"returned_error":"resolved",Cn.error&&Xo(Cn.error)?"provider_declined":void 0)}catch(Ee){let bt=Ee===Ki,ie=yn(bt?"returned_error":"rejected");if(me?.error({...bt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:xi(Ee),...Ft,operationOutcome:ie.operationOutcome,durationMs:ie.durationMs,statusClass:"unknown",terminalReason:ie.terminalReason}),!xe.current||ht)return;await Vt?.();return}let _n=Cn.error;if(_n){if(!xe.current||ht)return;if(Xo(_n)){Q=!0,Gi(ve,vt,Ct),it.current=null,O.current=null,R("idle");let Ee=_n.message??"Your payment was declined.";V(Ee),d?.(Ee),f?.(ln(Pe,Ee,{code:_r(_n),declineCode:So(_n)})),ni({billingApiUrl:r,sessionId:ve,nonce:vt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:X,providerDeclineReason:_r(_n)??"provider_declined",...pn.intentKind==="payment"&&pn.providerObjectId.startsWith("pi_")?{providerIntentId:pn.providerObjectId}:{}}})}else me?.error({...xi(_n),...Ft,operationOutcome:an.operationOutcome,durationMs:an.durationMs,statusClass:"unknown",terminalReason:an.terminalReason}),await Vt?.();return}if(Nn(Cn),!ht)throw new Error("Invalid provider returned for APM intent")}catch(ve){if(ve===Za){let vt=me?.now()??globalThis.performance?.now()??Date.now();me?.error({errorCode:Vd(Rn),stage:Fn,requestCategory:Rn,paymentMethodCategory:"wallet",provider:"stripe",...st?{walletType:st}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ne,durationMs:Math.max(0,vt-pt),statusClass:"timeout",failureCategory:Mt,attempt:tt,terminalReason:"provider_error"}),me?.flush?.().catch(()=>{})}V(),z(X,ve,ve===Za?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",w?.generation,ve===Za)}finally{if(window.clearTimeout(Ln),$t!==null&&(window.clearTimeout($t),Fe.current.delete($t)),!nt){let ve=me?.now()??globalThis.performance?.now()??Date.now();me?.performance({stage:"callback",durationMs:Math.max(0,ve-pt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Pn?{statusClass:"timeout"}:{}})}xe.current&&$e(!1)}},[$,de,e,t,n,A,Le,k,r,G,o,l,d,f,b,z,Pt,qt,tn,ut,Y,ge]),wt=(0,i.useMemo)(()=>{let u=["applePay","googlePay","paypal","link","amazonPay","klarna"],U=new Set(["applePay","googlePay"]),V=new Set(a.map(y.stripeExpressMethodToOptionKey)),w={};for(let X of u)V.has(X)?w[X]=U.has(X)?"always":"auto":w[X]="never";return w},[a]),Ye=(0,i.useMemo)(()=>a.map(y.stripeExpressMethodToOptionKey),[a]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(nc,{state:fe,placeholderTestId:"flopay-wallet-placeholder",borderRadius:v,children:(0,c.jsxs)("div",{ref:Re,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[_e&&(0,c.jsxs)("button",{ref:Oe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ve,style:Zi,children:["Try ",Qi(Se)," again"]}),ot!=="idle"&&(0,c.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,c.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,c.jsx)("button",{type:"button",onClick:W,disabled:ot==="checking",style:Zi,children:ot==="checking"?"Checking payment status\u2026":"Check payment status"})]}),te&&(0,c.jsx)(Co,{identity:te.identity,methodLabel:te.methodLabel,onComplete:gt,onCancel:()=>gt(null)},te.id),ot==="idle"&&(0,c.jsx)("div",{style:{display:te?"none":void 0},children:(0,c.jsx)(Yt.ExpressCheckoutElement,{onReady:u=>{De(tc(u,Ye))},onLoadError:u=>{De("load_error"),os(Y,"stripe","wallet","provider_error")},onClick:async u=>{Ue.current=u.expressPaymentType,Z.current=jl(u.expressPaymentType);let U=!0,V=window.setTimeout(()=>{U=!1,u.reject()},Nd),w=b?await b(Z.current):{proceed:!0};if(window.clearTimeout(V),!U)return;if(!w.proceed){ke.current.delete(ge),u.reject();return}let X=Ze(u.expressPaymentType);ke.current.set(ge,{generation:X,method:u.expressPaymentType,accountPatch:w.accountPatch,sessionId:w.sessionId,nonce:w.nonce}),je(!1),Y?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:X,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),p?.(Z.current),u.resolve()},onConfirm:Ge,onCancel:()=>{let u=ke.current.get(ge);ke.current.delete(ge),Y?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),Ke(u?.generation),it.current=null,je(!1),we.current=!0,lt()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:wt,emailRequired:ft,billingAddressRequired:ft,layout:{maxColumns:1,overflow:"never"}}},ge)})]})}),ne&&(0,c.jsx)(er,{status:"processing"})]})}function rc(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function lu({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:d,borderColor:p,textColor:f,borderRadius:h,fontFamily:b}){let A=(0,y.resolveStripeMethodBrandVariant)(e,t),k=Rl[e],[S,v]=(0,i.useState)(!1),N=!!k&&!S,re=A?.backgroundColor??d??"#ffffff",T=A?.borderColor??p??"#d1d5db",G=A?.textColor??f??"#262833";return(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&l()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:pa,padding:"0 1rem",backgroundColor:re,color:G,border:`1px solid ${T}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,c.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,y.getStripeMethodDisplayName)(e)}\u2026`}):(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,y.hasVendoredStripeMethodLogo)(e)?8:0},children:[N?(0,c.jsx)("img",{src:k,alt:"","aria-hidden":"true",onError:()=>v(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!N&&A?.logoSvg?(0,c.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:A.logoSvg}}):null,(0,c.jsx)("span",{children:(0,y.getStripeMethodDisplayName)(e)})]}),a&&(0,c.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:G,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,c.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function es({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:d,onErrorChange:p,onDecline:f,onCancel:h,runBeforeButtonClick:b,onButtonClick:A,isProcessing:k,submitButtonColor:S,submitButtonBorderRadius:v,submitButtonStyle:N,errorText:re}){let T=zr(),{emitInstrument:G}=(0,i.useContext)(Zn),$=(0,Yt.useStripe)(),de=(0,Yt.useElements)(),[Y,fe]=(0,i.useState)(!1),De=(0,i.useRef)(!1),[ne,$e]=(0,i.useState)(!1),[ft,te]=(0,i.useState)("loading"),[Le,gt]=(0,i.useState)(""),Re=!(0,y.isValidEmail)(r?.trim()),Oe=!Re||(0,y.isValidEmail)(Le.trim()),ge=(0,i.useCallback)(async()=>{if(!$||!de||k||De.current||!ne)return;De.current=!0,fe(!0);let pe=b?await b("card"):{proceed:!0};if(!pe.proceed){De.current=!1,fe(!1);return}A?.("card");let _e=pe.sessionId??t,je=pe.nonce??n,ot=Jr(o?.trim()),R=Bn({email:pe.accountPatch?.email?.trim()||r?.trim()||Le.trim(),firstName:pe.accountPatch?.firstName?.trim()||ot.firstName,lastName:pe.accountPatch?.lastName?.trim()||ot.lastName}),Se=R.email,ae=Bn({...pe.accountPatch,...R});try{if(p?.(null),!(0,y.isValidEmail)(Se))throw new Error("A valid email address is required for payment.");await a?.(R);let O=await de.submit();if(O.error){p?.(O.error.message??"Payment failed.");return}let xe=[R.firstName,R.lastName].filter(Boolean).join(" "),we=await $.createPaymentMethod({elements:de,params:{billing_details:{email:Se,...xe?{name:xe}:{}}}});if(we.error||!we.paymentMethod){p?.(we.error?.message??"Failed to create payment method.");return}let Ue=we.paymentMethod;if(!_e||!Se)throw new Error("Missing sessionId or email for payment.");let Z=Ue.type||e,at=await ti(l,G,_e,je??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,paymentMethodId:null,intentKind:"payment"});if(at.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let it=at.clientSecret;Ut(Tr,{clientSecret:it,sessionId:_e,nonce:je,accountPatch:ae,paymentMethodId:Ue.id,paymentMethodType:Ue.type??e,gateway:"stripe"});let{error:Fe,paymentIntent:ke}=await $.confirmPayment({clientSecret:it,confirmParams:{return_url:window.location.href,payment_method:Ue.id},redirect:"if_required"});if(Fe){Ut(Tr);let Ke=Fe.message??"Payment failed.";p?.(Ke),f?.(ln("card",Ke,{code:Fe.code})),await ni({billingApiUrl:l,sessionId:_e,nonce:je,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Fe.code??"provider_declined"}});return}let Ze=ke?.status;if(!Go(Ze)){Ut(Tr);let Ke=Ze==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(Ke),f?.(ln("card",Ke,{code:Ze??"missing_payment_intent"}));return}Ut(Tr);let Pt=typeof ke?.payment_method=="string"?ke.payment_method:ke?.payment_method?.id;d({id:Pt??Ue.id,type:"card",threeDSecureActionResultTokenId:ke?.id,gateway:"stripe",paymentMethodType:Ue.type??e},{accountPatch:ae,paymentMethodCategory:"apm",sessionId:_e,nonce:je})}catch(O){p?.(O instanceof Error?O.message:"Payment failed. Please try again.")}finally{De.current=!1,fe(!1)}},[$,de,k,ne,b,A,t,n,r,o,Le,a,l,G,e,d,p,f]);return(0,c.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Re&&(0,c.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Re&&(0,c.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,c.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Le,onChange:pe=>gt(pe.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,c.jsx)(Yt.PaymentElement,{onReady:()=>te("ready"),onLoadError:()=>{te("load_error"),os(cn(T),"stripe","apm")},onChange:pe=>{$e(!!pe.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,y.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{ge()},disabled:!ne||!Oe||Y||k||ft!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:S,color:"white",border:"none",borderRadius:v,fontSize:"1rem",fontWeight:600,cursor:!ne||!Oe||Y||k||ft!=="ready"?"not-allowed":"pointer",opacity:!ne||!Oe||Y||k||ft!=="ready"?.5:1,transition:"opacity 120ms ease-out",...N??{}},children:Y?"Processing\u2026":`Pay with ${(0,y.getStripeMethodDisplayName)(e)}`}),re&&(0,c.jsx)(ko,{margin:"0.75rem 0 0",children:re})]})}function Gl({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:d,paymentElementBaseOptions:p,onTokenizedBody:f,onErrorChange:h,onButtonClick:b,onDecline:A,runBeforeButtonClick:k,onLoadStateChange:S,isProcessing:v=!1,submitButtonColor:N="#4A49FF",submitButtonBorderRadius:re=8,submitButtonStyle:T,buttonAppearance:G,themeId:$,onExpandApm:de,expandedApmMethod:Y}){let{emitInstrument:fe}=(0,i.useContext)(Zn),[De,ne]=(0,i.useState)(null),[$e,ft]=(0,i.useState)(null),te=(0,i.useRef)(!1),{request:Le,collect:gt,finish:Re}=vo();(0,i.useEffect)(()=>{l.length>0&&d?S?.("ready"):d||S?.("loading")},[l.length,d,S]);let Oe=(0,i.useCallback)(async R=>{if(!d||te.current||v)return;te.current=!0,ft(R);let Se=k?await k("card"):{proceed:!0};if(!Se.proceed){te.current=!1,ft(null);return}b?.("card");let ae=Se.sessionId??e,O=Se.nonce??t,xe=Jr([Se.accountPatch?.firstName,Se.accountPatch?.lastName].filter(Boolean).join(" ")||r),we=Bn({email:Se.accountPatch?.email?.trim()||n?.trim(),firstName:Se.accountPatch?.firstName?.trim()||xe.firstName,lastName:Se.accountPatch?.lastName?.trim()||xe.lastName});if(!(0,y.isValidEmail)(we.email)){ft(null);let at=await gt((0,y.getStripeMethodDisplayName)(R),we);if(!at){te.current=!1;return}we=at,ft(R)}let Ue=we.email,Z=Bn({...Se.accountPatch,...we});try{if(h?.(null),!ae||!(0,y.isValidEmail)(Ue))throw new Error("Missing sessionId or email for payment.");await o?.(we);let at=await ti(a,fe,ae,O??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:R,paymentMethodId:null,intentKind:"payment"});if(at.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let it=at.clientSecret;Ut(Tr,{clientSecret:it,sessionId:ae,nonce:O,accountPatch:Z,paymentMethodType:R,gateway:"stripe"});let{error:Fe,paymentIntent:ke}=await d.confirmPayment({clientSecret:it,confirmParams:{return_url:window.location.href,payment_method_data:{type:R,billing_details:{name:[we.firstName,we.lastName].filter(Boolean).join(" "),...Ue?{email:Ue}:{}}}},redirect:"if_required"});if(Fe){Ut(Tr);let Ke=Fe.message??"Payment failed.";h?.(Ke),A?.(ln("card",Ke,{code:Fe.code})),await ni({billingApiUrl:a,sessionId:ae,nonce:O,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:R,providerDeclineReason:Fe.code??"provider_declined"}});return}let Ze=ke?.status;if(!Go(Ze)){Ut(Tr);let Ke=Ze==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(Ke),A?.(ln("card",Ke,{code:Ze??"missing_payment_intent"}));return}Ut(Tr);let Pt=typeof ke?.payment_method=="string"?ke.payment_method:ke?.payment_method?.id;f({id:Pt??ke?.id,type:"card",threeDSecureActionResultTokenId:ke?.id,gateway:"stripe",paymentMethodType:R},{accountPatch:Z,paymentMethodCategory:"apm",sessionId:ae,nonce:O})}catch(at){h?.(at instanceof Error?at.message:"Payment failed. Please try again.")}finally{te.current=!1,ft(null)}},[d,v,k,b,e,t,n,gt,a,fe,r,o,f,h,A]),[ge,pe]=(0,i.useState)(null),_e=de?Y??null:ge,je=(0,i.useCallback)(R=>{te.current||v||_e&&_e!==R||((0,y.needsStripeMethodExplicitConfirm)(R)?de?de(R):pe(R):Oe(R))},[_e,v,Oe,de]),ot=(0,i.useMemo)(()=>ge?rc(p,ge):null,[ge,p]);return(0,c.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Le?(0,c.jsx)(Co,{identity:Le.identity,methodLabel:Le.methodLabel,onComplete:Re,onCancel:()=>Re(null)},Le.id):l.map(R=>{let Se=Y===R,ae=$e===R,O=$e!==null&&$e!==R||Y!=null&&Y!==R;return(0,c.jsxs)(i.default.Fragment,{children:[(0,c.jsx)(lu,{method:R,themeId:$,submitting:ae,disabled:O,highlighted:Se,hasNextStep:(0,y.needsStripeMethodExplicitConfirm)(R),onClick:()=>je(R),backgroundColor:G?.backgroundColor,borderColor:G?.borderColor,textColor:G?.textColor,borderRadius:G?.borderRadius,fontFamily:G?.fontFamily}),!de&&ge===R&&ot&&d&&(0,c.jsx)(Yt.Elements,{stripe:d,options:ot,children:(0,c.jsx)(es,{method:R,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:f,onErrorChange:h,onDecline:A,onCancel:()=>pe(null),runBeforeButtonClick:k,onButtonClick:b,isProcessing:v,submitButtonColor:N,submitButtonBorderRadius:re,submitButtonStyle:T})},R)]},R)})})}function cu({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:l,onError:d,onDecline:p,onTokenizedBody:f,firstName:h,lastName:b,chv:A,className:k,submitLabel:S,isProcessing:v,error:N,onErrorChange:re,showPayPal:T=!0,showStripe:G=!0,walletPresentation:$="auto",enabledPaymentMethods:de,enabledPaymentMethodCountries:Y,showApplePay:fe=!0,showGooglePay:De=!0,layout:ne="default",theme:$e,buttonsTheme:ft,buttonsStyles:te,appearance:Le,cardButtonContent:gt,cardBackButtonContent:Re,cardTitleContent:Oe,showSecurityFooter:ge,onButtonClick:pe,onBeforeButtonClick:_e,onBuyerIdentityReady:je,enableAVS:ot,cardFieldOrder:R,cardPreFormSlot:Se,avsLayout:ae="row",country:O,zip:xe,addressLine1:we,addressLine2:Ue,city:Z,state:at,onCountryChange:it,onZipChange:Fe,avsCheck:ke,checkoutType:Ze,checkoutLayout:Pt,totalAmount:Ke=0,currency:tn="usd",initialCardOpen:qt=!1,directPaypal:ut,isSubscription:lt=!1,session:z,dataAttachmentPending:be=!1,dataAttachmentRequiresIdentity:Ve=!1,debug:W=!1}){let Ge=zr(),wt=Ba(),Ye=(0,i.useContext)(ur),{emitInstrument:u}=(0,i.useContext)(Zn),U=(0,i.useRef)(null);U.current||(U.current=La());let V=U.current,[,w]=(0,i.useState)(0),X=(0,i.useRef)(null);X.current||(X.current=Zo());let qe=X.current,Pe=(0,i.useMemo)(()=>({browser:qe,capability:V,presentationMode:"popup"}),[qe,V]),st=z??Ye.session,tt=st?.gateways?.paypal?.providerObjectType??ut?.providerObjectType,me=be||Ye.claimPending===!0,pt=Ve||Ye.claimRequiresIdentity===!0,_t=me&&!pt,Pn=dl(),nt=n||Pn,[$t,Ne]=(0,i.useState)(!1),[Fn,Rn]=(0,i.useState)(null),[Mt,wn]=(0,i.useState)(O??""),[Dn,Ln]=(0,i.useState)(xe??""),[nn,ve]=(0,i.useState)(we??""),[vt,Et]=(0,i.useState)(Ue??""),[vn,Bt]=(0,i.useState)(Z??""),[Vn,un]=(0,i.useState)(at??""),[jt,on]=(0,i.useState)(""),[Wn,pn]=(0,i.useState)({}),Ct=(0,i.useRef)(xe??""),Xt=(0,i.useRef)(O??""),mn=(0,i.useRef)(we??""),Ft=(0,i.useRef)(Ue??""),Jt=(0,i.useRef)(Z??""),Vt=(0,i.useRef)(at??""),yn=(0,i.useRef)(""),ht=(0,i.useRef)({});(0,i.useEffect)(()=>{let s=(C,K,Ae,ee,Ce)=>{if(ht.current[C])return;let Gt=K?.trim();!Gt||Gt===Ae.current||(Ae.current=Gt,ee(Gt),Ce?.(Gt))};s("country",O,Xt,wn,it),s("zip",xe,Ct,Ln,Fe),s("addressLine1",we,mn,ve),s("addressLine2",Ue,Ft,Et),s("city",Z,Jt,Bt),s("state",at,Vt,un)},[O,xe,we,Ue,Z,at,it,Fe]);let Q=(0,i.useMemo)(()=>(0,y.resolveAVSConfig)(ot),[ot]),On=Q!==null,Nn=(0,i.useMemo)(()=>(0,y.isAuthorizationOnlySession)(z),[z]),hr=!!z?.vault?.html,Cn=!!z?.gateways?.pcivault,an=Ei(z),Ee=!!(z?.gateways?.stripe?.enabledPaymentMethods??de)?.includes("card")||Vr(z),bt=hr||Ee||Cn,ie=!!(G&&bt&&e),[F,Xe]=(0,i.useState)(()=>ne!=="buttons"||qt?e??null:null),[se,Hn]=(0,i.useState)(0),fn=ne!=="buttons"||qt||!!e&&F===e,Wt=z?.captureMethod,Kn=(0,i.useRef)(Ge);(0,i.useEffect)(()=>{Kn.current=Ge},[Ge]);let[rt,$r]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!ie||!e||!fn){$r(null);return}let s=Kn.current?Kn.current.cardCapture({sessionId:e,captureMethod:Wt}):new yr.PciVaultCardCapture({sessionId:e,captureMethod:Wt,billingApiUrl:nt,telemetry:r});return $r({sessionId:e,captureMethod:Wt,billingApiUrl:nt,telemetry:r,capture:s}),()=>{s.unmount()}},[ie,e,fn,Wt,nt,r]);let Ht=ie&&e&&fn&&rt?.sessionId===e&&rt.captureMethod===Wt&&rt.billingApiUrl===nt&&rt.telemetry===r?rt.capture:null,gn=(0,i.useMemo)(()=>{let s=Mt,C=Q?(0,y.isAVSFieldVisible)(Q.postal_code,s):!1;return au(s,Dn,C)},[Q,Mt,Dn]),{avsInvalid:Mr,invalidAvsFields:Br}=(0,i.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!ie||!Q)return{avsInvalid:!1,invalidAvsFields:s};let C=Mt,K=(Ce,Gt)=>(0,y.isAVSFieldVisible)(Ce,C)&&!Gt.trim(),Ae={line1:K(Q.address_line_1,nn),city:K(Q.city,vn),state:K(Q.state,Vn),zip:gn.empty||gn.malformed};return{avsInvalid:Ae.line1||Ae.city||Ae.state||Ae.zip,invalidAvsFields:Ae}},[ie,Q,Mt,nn,vn,Vn,gn]),[En,Zt]=(0,i.useState)(!1),[br,Tn]=(0,i.useState)(!1),[Fr,An]=(0,i.useState)(!1),[Pr,vr]=(0,i.useState)({line1:!1,city:!1,state:!1}),nr=(0,i.useRef)(!1),Gn=(0,i.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Yn=(0,i.useRef)(!1),At=(0,i.useCallback)(s=>{Gn.current[s]=!0,Yn.current=!0},[]),rr=(0,i.useCallback)(s=>!nr.current&&Gn.current[s],[]),kn=(0,i.useCallback)(s=>{rr(s)&&vr(C=>C[s]?C:{...C,[s]:!0})},[rr]),[Xn,Cr]=(0,i.useState)(()=>Xi(z?.vault)),[ct,rn]=(0,i.useState)(qt&&bt?"card":"buttons"),[Qt,Dr]=(0,i.useState)(null),zn=ct==="expanding"||ct==="card",jr=z?.gateways?.stripe&&!an?"stripe":void 0,or=(0,i.useCallback)(()=>{u?.({class:"card_surface",provider:jr})},[jr,u]),ar=(0,i.useRef)(null),hn=(0,i.useCallback)(s=>{ar.current&&clearTimeout(ar.current),ar.current=setTimeout(()=>{ar.current=null,s()},ma)},[]);(0,i.useEffect)(()=>()=>{ar.current&&clearTimeout(ar.current)},[]);let ir=(0,i.useCallback)(()=>{or(),Xe(e??null),Hn(s=>s+1),rn("expanding"),hn(()=>rn("card"))},[hn,or,e]),Lr=(0,i.useCallback)(()=>{rn("collapsing"),hn(()=>rn("buttons"))},[hn]),In=(0,i.useCallback)(s=>{Dr(s),rn("apm-expanding"),hn(()=>rn("apm-form"))},[hn]),x=(0,i.useCallback)(()=>{rn("apm-collapsing"),hn(()=>{rn("buttons"),Dr(null)})},[hn]);(0,i.useEffect)(()=>{ne==="buttons"&&qt&&bt&&(Xe(e??null),rn("card"))},[ne,qt,bt,e]);let[L,B]=(0,i.useState)(null),le=(0,i.useRef)(!1),Me=(0,i.useRef)(null),mt=(0,i.useRef)("idle"),[ue,Be]=(0,i.useState)(!1),H=(0,i.useRef)(ue);H.current=ue;let[m,g]=(0,i.useState)(()=>ut?.existingOrderId?{orderId:ut.existingOrderId,attempts:1}:null),D=(0,i.useRef)(m);(0,i.useEffect)(()=>{D.current=m},[m]);let q=(0,i.useRef)(null),ce=(0,i.useMemo)(()=>{if(je||Ye.claimBuyerIdentity||z?.buyerIdentified!==!1||!e||!t)return;let s=`${nt}|${e}|${t}`;q.current?.key!==s&&(q.current={key:s,claim:bo(new yr.PaymentAPI(nt,{telemetry:!1}),e,t,{...a?{userId:a}:{},...h?{firstName:h}:{},...b?{lastName:b}:{}})});let C=q.current.claim;return async K=>{await C(K)}},[je,Ye.claimBuyerIdentity,z?.buyerIdentified,e,t,nt,a,h,b]),J=je??Ye.claimBuyerIdentity??ce,We=N??Fn,kt=(0,i.useMemo)(()=>(0,y.resolveTheme)($e),[$e]),E=(0,i.useMemo)(()=>{let s=kt?.buttonsLayout??(0,y.resolveButtonsLayoutTheme)(ft);return te?{...s,...te,cardButton:{...s.cardButton,...te.cardButton},cardFormContainer:{...s.cardFormContainer,...te.cardFormContainer},backButton:{...s.backButton,...te.backButton},backButtonIcon:{...s.backButtonIcon,...te.backButtonIcon},submitButton:{...s.submitButton,...te.submitButton},title:{...s.title,...te.title}}:s},[kt,ft,te]),he=Le??kt?.appearance,Tt=(0,i.useMemo)(()=>Ja({appearance:he,buttonsStyles:E,layout:ne}),[he,E,ne]),ye=Ye.inlineSessionPatchProcessing??!1,j=(v??$t)||ye,oe=nt.replace(/\/+$/,""),_=(0,i.useMemo)(()=>Ai({userId:a,email:o,firstName:h,lastName:b,country:O,zip:xe},Wn),[a,o,h,b,O,xe,Wn]),ze=[_.firstName,_.lastName].filter(s=>!!s?.trim()).join(" "),It=!(0,y.isValidEmail)(_.email?.trim()),Te=(0,i.useRef)(null);ie&&Te.current===null&&(Te.current=It);let Sn=ie&&(Te.current??It),Sr=(0,i.useMemo)(()=>iu(jt,Sn),[jt,Sn]),oo=Sr.empty||Sr.malformed,Un=(0,i.useMemo)(()=>Ge?Ge.getRawProvider():null,[Ge]),ms=(0,i.useMemo)(()=>wt?wt.getRawProvider():null,[wt]),Fo=Ke||100,ao=tn.toLowerCase(),di=(0,i.useMemo)(()=>he?(0,yr.toStripeAppearance)(he):null,[he]),io=di,ys=(0,i.useMemo)(()=>{let s=di??{},C=s.rules??{};return{...s,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[di]),fs=(0,i.useMemo)(()=>({...al(Ke,z?.captureMethod),currency:ao,...io?{appearance:io}:null}),[Ke,ao,z?.captureMethod,io]),gs=(0,i.useMemo)(()=>({mode:"payment",amount:Fo,currency:ao,captureMethod:"manual",setupFutureUsage:"off_session",...io?{appearance:io}:null}),[Fo,ao,io]),Ie=(0,i.useCallback)(s=>{Rn(s),re?.(s)},[re]),ui=(0,i.useRef)(""),[hs,bc]=(0,i.useState)(!1),pi=(0,i.useCallback)(()=>{bc(!0)},[]);(0,i.useEffect)(()=>{if(!ie||!Sn||!J||!hs||oo||ui.current)return;let s=Bn({email:(0,y.isValidEmail)(_.email?.trim())?_.email?.trim():yn.current.trim(),firstName:_.firstName?.trim(),lastName:_.lastName?.trim()});ui.current=JSON.stringify(s),pn(C=>({...C,...s})),Promise.resolve(J(s)).catch(C=>{ui.current="",Ie(C instanceof Error?C.message:"Failed to attach buyer details.")})},[ie,Sn,J,hs,oo,_.email,_.firstName,_.lastName,Ie]),(0,i.useEffect)(()=>{!ie||!Ht||Ht.setCardFieldOrder?.(R??null,Q==null&&!Sn)},[ie,Ht,R,Q,Sn]),(0,i.useEffect)(()=>{(ct==="expanding"||ct==="collapsing"||ct==="apm-expanding"||ct==="apm-collapsing")&&Ie(null)},[ct,Ie]);let wr=(0,i.useCallback)((s,C,K)=>{p?.(ln(s,C,K))},[p]),so=(0,i.useCallback)((s,C,K)=>{let Ae=K?.popupBlocked??Kr(C);Ae&&V.markBlocked()&&w(Qe=>Qe+1);let ee=xa(Qi(s),Ae,qe.inAppBrowser),Ce=_r(C),Gt=(Ce?.toLowerCase()==="error"?void 0:Ce)??Qr(K?.code)??"external_payment_method_failed",cr=new y.FloPayError(ee,"api_error",{code:"external_payment_method_failed",param:s,details:{providerCode:Gt,popupBlocked:Ae,inAppBrowser:qe.inAppBrowser,appFamily:qe.appFamily,popupCapability:V.current(),presentationMode:K?.presentationMode??"popup"}});K?.telemetryReported||cn(Ge)?.error(Ao({...Pe,presentationMode:K?.presentationMode??"popup"},{errorCode:Ae?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:K?.provider??(s==="paypal"?"paypal":"stripe"),paymentMethodCategory:K?.paymentMethodCategory??(s==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:K?.terminalReason??(Ae?"popup_blocked":"provider_error")})),B(null),ne==="buttons"&&(rn("buttons"),Dr(null)),Ie(ee),d?.(cr),console.error("[FloPay] External payment method failed:",{method:s,code:Gt,popupBlocked:Ae})},[qe,Pe,Ge,ne,d,V,Ie]);(0,i.useEffect)(()=>{if(!ie||!e){Cr(null);return}let s=Xi(z?.vault);if(s){Cr(s);return}if(!fn){Cr(null);return}Cr(null);let C=!0;return new yr.PaymentAPI(oe).getVaultCapture(e,t).then(K=>{if(!C)return;let Ae=Xi(K);Ae?Cr(Ae):Ie("Failed to load the secure card form.")}).catch(K=>{C&&Ie(K instanceof Error?K.message:"Failed to load the secure card form.")}),()=>{C=!1}},[ie,fn,se,e,z?.vault,oe,t,Ie]);let sr=(0,i.useRef)({onComplete:l,onError:d,updateError:Ie,emitDecline:wr,resolvedAccount:_,avsConfig:Q,avsCheckProp:ke,sessionId:e,nonce:t,baseUrl:oe,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt,serverSideCardGateway:an});sr.current={onComplete:l,onError:d,updateError:Ie,emitDecline:wr,resolvedAccount:_,avsConfig:Q,avsCheckProp:ke,sessionId:e,nonce:t,baseUrl:oe,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt,serverSideCardGateway:an};let mi=(0,i.useRef)(!1),bs=(0,i.useCallback)(()=>{let s=sr.current,C=s.resolvedAccount.email?.trim(),K=(0,y.isValidEmail)(C)?C:yn.current.trim();if(!(0,y.isValidEmail)(K))return null;let Ae=s.resolvedAccount.firstName?.trim(),ee=s.resolvedAccount.lastName?.trim(),Ce=Xt.current.trim()||s.resolvedAccount.country?.trim()||"",Gt=s.avsConfig?(0,y.isAVSFieldVisible)(s.avsConfig.state,Ce):!1,cr=s.avsConfig?(0,y.isAVSFieldVisible)(s.avsConfig.address_line_1,Ce):!1,Qe=s.avsConfig?(0,y.isAVSFieldVisible)(s.avsConfig.postal_code,Ce):!1,yt=s.avsConfig?(0,y.isAVSFieldVisible)(s.avsConfig.city,Ce):!1,St=s.avsConfig?(0,y.isAVSFieldVisible)(s.avsConfig.address_line_2,Ce):!1,Nt=cr&&!Gt&&Qe?(0,y.getStateFromPostalCode)(Ce,(Ct.current??"").trim()):null,sn=Gt?Vt.current:Nt;return{accountData:{userId:s.resolvedAccount.userId??"",email:K,...Ae?{firstName:Ae}:{},...ee?{lastName:ee}:{},...Qe&&Ct.current?{zip:Ct.current}:{},...yt&&Jt.current?{city:Jt.current}:{},...sn?{state:sn}:{},...cr&&mn.current?{addressLine1:mn.current}:{},...St&&Ft.current?{addressLine2:Ft.current}:{},...Ce?{country:Ce}:{}},...s.avsCheckProp===void 0?{}:{avsCheck:s.avsCheckProp},...s.avsConfig?{avsConfig:{country:(0,y.isAVSFieldVisible)(s.avsConfig.country,Ce),postal_code:Qe,address_line_1:cr,address_line_2:St,city:yt,state:Gt}}:{}}},[]),Ps=(0,i.useRef)(me);Ps.current=me,(0,i.useEffect)(()=>{me||We!==Ul||sr.current.updateError(null)},[me,We]),(0,i.useEffect)(()=>{!ie||!Ht||Ht.setSubmitGate?.(Mr||me||oo||ue)},[ie,Ht,Mr,me,oo,ue]),(0,i.useEffect)(()=>{if(!ie||!Ht)return;mi.current=!1;let s=null,C=()=>{s&&clearTimeout(s),s=setTimeout(()=>{s=null,mt.current="idle",B(null)},400)},K=Ht.on("submitting",()=>{Zt(!0),Me.current&&clearTimeout(Me.current),mt.current="validation-window",Me.current=setTimeout(()=>{Me.current=null,mt.current==="validation-window"&&(mt.current="processing")},Kd),B("processing");let Qe=sr.current;if(!Qe.sessionId||!Qe.nonce)return;let yt=bs();if(!yt){Qe.updateError("Enter a valid email address."),mt.current="idle",B(null);return}new yr.PaymentAPI(Qe.baseUrl).patchAccountSnapshot(Qe.sessionId,Qe.nonce,yt,{telemetryMode:"best_effort"}).catch(St=>{if(!Yd(St))return;let Nt=St instanceof Error?St.message:"Please check your billing address and try again.";Qe.updateError(Nt),mt.current="idle",B(null),Qe.onError?.(St instanceof y.FloPayError?St:new y.FloPayError(Nt,"api_error"))})}),Ae=Ht.on("complete",async Qe=>{if(_o(Qe.sessionId??sr.current.sessionId),mt.current="terminal",Be(!1),B("success"),await new Promise(sn=>setTimeout(sn,600)),mi.current)return;mi.current=!0;let yt=sr.current,St=(0,y.isAuthorizationOnlySession)(yt)||Qe.outcome==="authorized",Nt=yt.serverSideCardGateway?{}:{paymentIntentId:Qe.intentId};sr.current.onComplete?.(St?{status:"authorized",...Nt,paymentId:Qe.paymentId??yt.paymentId,sessionId:Qe.sessionId??yt.sessionId,authorizationExpiresAt:Qe.authorizationExpiresAt??yt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Nt,checkoutMethod:"card"})}),ee=Ht.on("decline",Qe=>{let yt=sr.current,St=Qe.message??"Your payment was declined. Please try another card or contact your bank.";mt.current="terminal",Be(!1),yt.updateError(St),B("error");let Nt=Qe.failureOutcome??(0,y.normalizeCheckoutFailureOutcome)(Qe.declineReason)??"authorization_declined";yt.emitDecline("card",St,{code:Nt,declineCode:Nt}),C()}),Ce=Ht.on("error",Qe=>{let yt=sr.current,St=Qe.message??"There was a problem processing your payment. Please try again.";mt.current="terminal",Be(!1),yt.updateError(St),B("error"),yt.onError?.(new y.FloPayError(St,"api_error",{code:Qe.failureOutcome??"capture_failed"})),C()}),Gt=Ht.on("challenge_dismissed",()=>{Me.current&&(clearTimeout(Me.current),Me.current=null),mt.current="processing",Be(!0),B(null)}),cr=Ht.on("blocked",()=>{if(H.current){sr.current.updateError(Gd);return}if(!Ps.current){Zt(!0);return}pi(),sr.current.updateError(Ul)});return()=>{s&&(clearTimeout(s),s=null),Me.current&&(clearTimeout(Me.current),Me.current=null),mt.current="idle",Be(!1),B(null),K(),Ae(),ee(),Ce(),Gt(),cr()}},[ie,Ht,pi,bs]);let kr=!!ut?.clientId,Do=Array.isArray(de),ha=Do&&de.length>0,vs=Do&&de.includes("paypal"),ba=(0,i.useRef)(null);ba.current===null&&(ba.current=Wd());let lo=ba.current?"redirect":ul(qe,$,V.current()),{expressMethods:Pa,paymentElementMethods:Lo}=(0,i.useMemo)(()=>(0,y.partitionStripeMethods)(de,{excludePaypal:kr}),[de,kr]),Cs=kr||!!wt||vs&&lo==="redirect",Pc=(0,i.useMemo)(()=>Cs?Pa.filter(s=>s!=="paypal"):Pa,[Pa,Cs]),vc=(0,i.useMemo)(()=>{let s=[];return fe&&s.push("apple_pay"),De&&s.push("google_pay"),s},[fe,De]),co=Do?Pc:vc,Cc=G&&co.length>0,yi=On?Mt:O,va=(0,i.useMemo)(()=>{let s=yi?.trim().toUpperCase();return s?Y?Lo.filter(C=>{let K=Y[C];return!K||K.length===0||K.includes(s)}):(0,y.filterStripeMethodsByCountry)(Lo,yi):Lo},[Lo,yi,Y]),fi=(0,i.useMemo)(()=>({mode:"payment",amount:Fo,currency:ao,paymentMethodCreation:"manual",appearance:ys}),[Fo,ao,ys]),[Ss,ws]=(0,i.useState)("loading"),[ks,Is]=(0,i.useState)("loading"),[Rs,_s]=(0,i.useState)("loading"),[Sc,gi]=(0,i.useState)(!1),[Es,hi]=(0,i.useState)("loading"),[bi,wc]=(0,i.useState)();(0,i.useEffect)(()=>{wc(Zo())},[]);let Ca=bi?.inAppBrowser,Sa=bi?Fa(bi,ut?.approvalPresentation,tt??(lt?"subscription":"order")):"popup",Ts=T&&(kr||(Do?vs:Ca===!1)),As=G&&Cc,Oo=(!_t||!!Ye.waitForDataAttachment)&&Ts&&kr,xs=Es==="retrying"||Es==="exhausted",No=null;G&&(wt?No=ms:lo==="redirect"&&(No=Un));let Ms=(0,i.useMemo)(()=>({...Pe,presentationMode:lo}),[Pe,lo]),zo=!_t&&Ts&&!!No&&(!kr||xs),uo=!_t&&As&&!!Un,Uo=!_t&&G&&ha&&va.length>0&&!!Un,kc=Oo&&!xs?Sc:zo&&Wl(Ss),Ic=uo&&Wl(ks),Rc=Uo&&Rs!=="load_error",Bs=s=>s==="loading"||s==="ready",Fs=Oo||zo&&Bs(Ss)||uo&&Bs(ks)||Uo&&Rs!=="load_error",wa=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(!wa.current){if(!G&&!T){wa.current=!0;let s=new y.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(s),Ie(s.message)}else if(!G&&T&&!kr){wa.current=!0;let s=new y.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(s),Ie(s.message)}else if(Ca!==void 0&&!_t&&!bt&&!Fs){wa.current=!0;let s=new y.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});d?.(s),Ie(s.message)}}},[G,T,kr,Ca,_t,bt,Fs,d,Ie]);let Ds=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(Ds.current||!ha)return;let s=[];fe!==!0&&s.push("showApplePay"),De!==!0&&s.push("showGooglePay"),s.length!==0&&(Ds.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.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.`))},[ha,fe,De]);let Ls=(0,i.useCallback)((s,C)=>Ye.applyInlineSessionPatch?Ye.applyInlineSessionPatch(s).then(K=>({error:null,sessionId:K.sessionId||e,nonce:K.session?.clientSecret||t})).catch(K=>{let Ae=Vl(C,K);return Ie(Ae.message),d?.(Ae),{error:Ae,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ye.applyInlineSessionPatch,t,d,e,Ie]),lr=(0,i.useCallback)(async s=>{if(s!=="card"&&_t&&await Ye.waitForDataAttachment?.(),!_e)return{proceed:!0};try{let C=await _e({method:s,sessionId:e||void 0,createSession:Ye.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&pn(Ae=>({...Ae??{},...C.account}));let K=await Ls(C,s);return K.error?{proceed:!1,accountPatch:C.account}:{proceed:!0,accountPatch:C.account,sessionId:K.sessionId,nonce:K.nonce}}return{proceed:!0}}catch(C){let K=Vl(s,C);return Ie(K.message),d?.(K),{proceed:!1}}},[Ls,Ye.inlineSessionDraft,Ye.waitForDataAttachment,_t,_e,d,e,Ie]),Os=(0,i.useCallback)(async(s,C)=>{if(le.current)return;le.current=!0,Ne(!0),B("processing"),Ie(null);let K=C?.sessionId??e,Ae=C?.nonce??t,ee=Ai(_,C?.accountPatch),Ce=C?.completionPaymentMethodId??Yo(s),Gt=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,cr=eu(s),Qe=C?.presentationMode?Ya(cn(Ge),{...Pe,presentationMode:C.presentationMode}):void 0,yt=()=>{u?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:cr}),Qe?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...mr,requestCategory:"process_payment"})};try{let Nt=await new yr.PaymentAPI(oe).processPayment(ee.userId??"",{sessionId:K,nonce:Ae,paymentMethodCategory:C?.paymentMethodCategory??nu(s),tokenizedData:Gt,accountData:{...C?.accountPatch,userId:ee.userId??"",email:ee.email??"",firstName:ee.firstName||void 0,lastName:ee.lastName||void 0,...Q?(()=>{let Dt=Xt.current,Ir=(0,y.isAVSFieldVisible)(Q.state,Dt),qn=(0,y.isAVSFieldVisible)(Q.address_line_1,Dt),Rr=(0,y.isAVSFieldVisible)(Q.postal_code,Dt),Xr=qn&&!Ir&&Rr?(0,y.getStateFromPostalCode)(Dt,(Ct.current??"").trim()):null,Ho=Ir?Vt.current:Xr;return{country:Dt,...Rr&&Ct.current?{zip:Ct.current}:{},...(0,y.isAVSFieldVisible)(Q.city,Dt)&&Jt.current?{city:Jt.current}:{},...Ho?{state:Ho}:{},...qn&&mn.current?{addressLine1:mn.current}:{},...(0,y.isAVSFieldVisible)(Q.address_line_2,Dt)&&Ft.current?{addressLine2:Ft.current}:{}}})():{}},chv:A,avsCheck:ke??!1,checkoutType:Ze,checkoutLayout:Pt,avsConfig:Q?{country:(0,y.isAVSFieldVisible)(Q.country,Xt.current),postal_code:(0,y.isAVSFieldVisible)(Q.postal_code,Xt.current),address_line_1:(0,y.isAVSFieldVisible)(Q.address_line_1,Xt.current),address_line_2:(0,y.isAVSFieldVisible)(Q.address_line_2,Xt.current),city:(0,y.isAVSFieldVisible)(Q.city,Xt.current),state:(0,y.isAVSFieldVisible)(Q.state,Xt.current)}:void 0});if(Nt.ok){let Dt=Nt.status===204?null:await Nt.json().catch(()=>null),Ir=(0,y.isAuthorizationOnlySession)(z)||Dt?.status==="authorized";_o(K),Qe?.terminal({outcome:"payment_succeeded",...mr}),B("success"),g(null),await new Promise(Xr=>setTimeout(Xr,600));let qn;typeof Dt?.paymentId=="string"?qn=Dt.paymentId:z?.paymentId&&(qn=z.paymentId);let Rr;typeof Dt?.authorizationExpiresAt=="string"?Rr=Dt.authorizationExpiresAt:z?.authorizationExpiresAt&&(Rr=z.authorizationExpiresAt),l?.(Ir?{status:"authorized",...qn===void 0?{}:{paymentId:qn},sessionId:typeof Dt?.sessionId=="string"?Dt.sessionId:K,...Rr===void 0?{}:{authorizationExpiresAt:Rr},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Ce,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Ce,checkoutMethod:s.isPaypal?"paypal":"card"});return}let sn=await Nt.json().catch(()=>null);if(sn?.type==="paypal_redirect_required"){let Dt=sn.threeDSecureToken,Ir=sn.paymentMethodId||s.id||"";if(!Ge||!Dt){B("error"),Ie("PayPal authorization required but no token provided.");return}try{let qn=wt?.getRawProvider();if(!qn){Ie("PayPal is not available.");return}let Rr={return_url:window.location.href};Ir&&(Rr.payment_method=Ir);let{error:Xr}=await qn.confirmPayment({clientSecret:Dt,confirmParams:Rr,redirect:"if_required"});if(Xr){B("error");let Ho=Xr.message??"PayPal payment failed.";Ie(Ho),wr("paypal",Ho,{code:Xr.code})}}catch(qn){B("error"),Ie(qn instanceof Error?qn.message:"PayPal authorization failed.")}return}if(sn?.type==="paypal_direct_required"){let Dt=sn.orderId;if(!Dt){B("error"),Ie("PayPal retry required but no order id provided.");return}let Ir=D.current?.attempts??0;if(Ir>=2){B("error"),Ie("PayPal payment could not be completed after multiple attempts."),wr("paypal","paypal_direct_required retry limit exceeded");return}gi(!1),hi("loading"),g({orderId:Dt,attempts:Ir+1}),B(null);return}(0,y.classifyPaymentRejection)(Nt.status,sn)?Qe?.terminal({outcome:"payment_declined",...mr,terminalReason:"provider_declined"}):yt(),B("error");let dr=sn?.message??"Payment failed. Please try again.";Ie(dr),wr(s.isPaypal?"paypal":"card",dr,{code:sn?.code??sn?.gatewayErrorCode,declineCode:sn?.declineCode??sn?.gatewayDeclineReason}),await new Promise(Dt=>setTimeout(Dt,400))}catch(St){Zl(St)||yt(),B("error"),Ie(St instanceof Error?St.message:"An unexpected error occurred"),await new Promise(Nt=>setTimeout(Nt,400))}finally{Ne(!1),B(null),le.current=!1}},[oe,e,t,_,Q,ke,Ze,Pt,A,Ge,wt,z,l,Ie,wr,u,Pe]),xn=(0,i.useCallback)((s,C)=>{f?f(s):Os(s,C)},[f,Os]),qo=`${Yl}:${e}`;(0,i.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem(qo);if(!s)return;let C;try{C=JSON.parse(s)}catch{Ut(qo);return}if(!C||typeof C.createdAt!="number"||Date.now()-C.createdAt<0||Date.now()-C.createdAt>Xl||typeof C.paymentMethodId!="string"||typeof C.providerIntentId!="string"||typeof C.paymentMethodType!="string"||C.sessionId!==e||!t||C.nonce!==t||!co.includes(C.paymentMethodType)){Ut(qo);return}Ut(qo),xn({id:C.paymentMethodId,type:"card",threeDSecureActionResultTokenId:C.providerIntentId,gateway:"stripe",paymentMethodType:C.paymentMethodType},{...C.accountPatch?{accountPatch:C.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[xn,t,e,qo,co]);let Ns=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(typeof window>"u"||Ns.current)return;let[s,C,K]=ns();if(!s||!C||ba.current||!Ge)return;let Ae=Ge.getRawProvider();if(!Ae)return;let ee=yt=>{let St=localStorage.getItem(yt);if(!St)return null;try{return JSON.parse(St)}catch{return Ut(yt),null}},Ce=ee(Tr)??ee(Ol),Gt;if(Ce?.clientSecret){if(Ce.clientSecret!==C)return;Gt={...Ce.accountPatch?{accountPatch:Ce.accountPatch}:{},...Ce.sessionId?{sessionId:Ce.sessionId}:{},...Ce.nonce?{nonce:Ce.nonce}:{}}}else if(Ce?.sessionId&&Ce.sessionId!==e)return;Ns.current=!0,Ut(Tr),Ut(Ol),window.history.replaceState({},"",rs());let cr=Ce?.paymentMethodType??Ce?.tokenType??"card",Qe="card";(async()=>{if(K==="failed"){let dr="Payment was declined. Please try again.";Ie(dr),wr(Qe,dr);return}let{paymentIntent:yt,error:St}=await Ae.retrievePaymentIntent(C);if(St){let dr=St.message??"Failed to retrieve payment status.";Ie(dr),wr(Qe,dr,{code:St.code});return}let Nt=yt?.status,sn=Go(Nt);if(!yt||!sn){let dr=Nt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ie(dr),wr(Qe,dr,{code:Nt??"missing_payment_intent"});return}let Gs=typeof yt.payment_method=="string"?yt.payment_method:yt.payment_method?.id;xn({id:Gs??Ce?.paymentMethodId??Ce?.tokenId??yt.id,type:"card",threeDSecureActionResultTokenId:yt.id,gateway:Ce?.gateway??"stripe",paymentMethodType:cr},Gt)})()},[e,xn,Ge,Ie,wr]);let Pi=(0,i.useCallback)(s=>{s.preventDefault()},[]);if(!(ie||Ge!==null))return(0,c.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let $o=ne==="buttons",Mn=he?.variables,_c=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),vi=Mn?.colorBackground,Ec=vi&&!_c.has(vi)?vi:void 0,jo=E.cardInputBorder??($o?"#e5e7eb":"#A4A4FF"),zs=Mn?.colorDanger??"#dc2626",Ot=s=>Br[s]&&(Pr[s]||En),ka=oo&&(Fr||En),Jn=s=>s?zs:jo,Ia=(gn.malformed||gn.empty)&&(br||En),Tc=Jn(Ia),Ci=E.cardFormContainer?.backgroundColor??Ec??($o?"white":"#EDEDFF"),po=E.cardInputBackground??Mn?.colorBackground??"white",Si=fo(Re),Us=fo(Oe),mo=E.nameInput,qs=E.cardInputFontSize??su(mo?.fontSize)??Mn?.fontSizeBase??"16px",$s=typeof mo?.fontFamily=="string"?mo.fontFamily:Mn?.fontFamily??"Poppins, sans-serif",js=Hi(mo?.fontWeight)??400,Ac=E.cardInputColor??(typeof mo?.color=="string"?mo.color:void 0)??Mn?.colorText??"#262833",xc=E.cardInputPlaceholderColor??"#9ca3af",Kt=Mn?.borderRadius??"8px",Gr=Mn?.borderRadius??E.cardButton?.borderRadius??Kt,Yr=Mn?.colorPrimary??"#4A49FF",Mc=Mn?.colorPrimaryHover??Mo(Yr,.12),wi=Mn?.colorText??"#262833",ki={fontSize:qs,fontFamily:$s,fontWeight:js,color:Ac,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Vo={marginTop:"0.375rem",...ki,fontSize:"0.75rem",lineHeight:1.4,color:zs},Bc={"--flopay-input-placeholder-color":xc,"--flopay-input-font-size":qs,"--flopay-input-font-family":$s,"--flopay-input-font-weight":String(js)},Wo=E.cardFormContainer??{},Ii=Wo.padding??($o?"0":"1rem"),Ri=Wo.borderRadius??Kt,Fc=Ht&&Xn?(0,c.jsx)(xo,{capture:Ht,html:Xn.html,messageToken:Xn.messageToken,expectedOrigin:Xn.expectedOrigin,theme:Tt,submitLabel:S,onReady:()=>{if(!Sn&&!Q||typeof document>"u")return;let s=()=>{let K=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(K){nr.current=!0;try{K.focus()}finally{nr.current=!1}}};Yn.current||s()},onError:s=>Ie(s),onValidation:s=>{let C=mt.current;(C==="idle"||C==="validation-window")&&(Ie(s),s&&mt.current==="validation-window"&&(Me.current&&(clearTimeout(Me.current),Me.current=null),mt.current="idle",B(null)))}}):(0,c.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Vs=(0,c.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&or()},style:{backgroundColor:Ci,borderRadius:Ri,...Wo,padding:Ii,...Bc,display:"flex",flexDirection:"column"},children:[(0,c.jsx)("style",{children:`
30
+ `,pa=44,ma=180,ql=`flopay-card-enter ${ma}ms cubic-bezier(0, 0, 0.2, 1) both`,$l=`flopay-card-exit ${ma}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Zd=`flopay-buttons-enter ${ma}ms cubic-bezier(0, 0, 0.2, 1) both`,Qd=`flopay-buttons-exit ${ma}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function eu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function is(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var tu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function nu(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var Qi={width:"100%",minHeight:pa,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function ru(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function jl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function es(e){return e==="paypal"?"PayPal":(0,y.getStripeMethodDisplayName)(e)}function ou(e){let t=(0,y.getPostalCodeExample)(e);return`Enter a valid ${(0,y.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function au(e,t,n){let r=(0,y.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,l=a&&!o,d=a&&!!o&&!(0,y.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:d}}function iu(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 Vl(e,t){return t instanceof y.FloPayError?t:new y.FloPayError(t instanceof Error?t.message:`${ru(e)} before-click hook failed.`,"validation_error")}function Zi(){return(0,c.jsx)("style",{children:Jd})}function su(e){return typeof e=="number"?`${e}px`:e}function tc(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function nc({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,c.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,c.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,c.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function Wl(e){return e!=="unavailable"&&e!=="load_error"}function ri(e){return(0,c.jsx)(cu,{...e})}function Hl({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:d,onDecline:u,onTechnicalFailure:p,runBeforeButtonClick:b,billingName:v,onBuyerIdentityReady:M,onLoadStateChange:I,placeholderBorderRadius:w,popupCapabilityOwner:h,externalTelemetryContext:O,presentationMode:G}){let T=Ur(),{emitInstrument:Y}=(0,i.useContext)(Zn),U=(0,Jt.useStripe)(),de=(0,Jt.useElements)(),X=(0,i.useMemo)(()=>Ya(dn(T),O),[O,T]),[he,De]=(0,i.useState)("loading");(0,i.useEffect)(()=>{I?.(he)},[he,I]);let[re,Ve]=(0,i.useState)(!1),yt=(0,i.useRef)(!1),te=!(0,y.isValidEmail)(n?.trim())||!v?.trim(),{request:Oe,collect:ft,finish:ke}=Co(),Le=(0,i.useRef)(!1),be=(0,i.useRef)(null),me=(0,i.useRef)(null),[Ie,We]=(0,i.useState)(0),[rt,R]=(0,i.useState)(!1),He=(0,i.useRef)(!1),ye=(0,i.useRef)(new Map),{startAttempt:N,finishAttempt:ve,invalidateAttempt:ue,isAttemptInvalidated:Ke,isAttemptCurrent:Z,generationRef:ot}=ta((q,fe,et)=>{p?.(q,fe,{...et,popupBlocked:et?.popupBlocked??Gr(fe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:G,terminalReason:"overlay_timeout"}),R(!0),We(V=>V+1)},{onHandoffObserved:()=>{h.markAvailable(),X?.log({name:"provider.popup.opened",stage:"overlay_open",...yr,attempt:ot.current})}});(0,i.useEffect)(()=>{rt&&me.current?.focus()},[rt,Ie]);let lt=(0,i.useCallback)(()=>{We(q=>q+1)},[]),Ae=(0,i.useCallback)((q,fe,et)=>{ue(et),p?.("paypal",q,{code:fe,popupBlocked:Gr(q),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:G}),R(!0),lt()},[ue,p,G,lt]),Ne=(0,i.useCallback)(()=>{window.setTimeout(()=>{(be.current?.querySelector("iframe")??be.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{He.current&&(He.current=!1,Ne())},[Ne,Ie]);let ct=(0,i.useCallback)(()=>{R(!1),a?.(null),Ne()},[Ne,a]);(0,i.useEffect)(()=>{if(!U||Le.current)return;let[q,fe,et]=rs();if(!q||!fe)return;let V=Ql(fe);if(!V)return;Le.current=!0;let Me=!0,bt=da.get(fe);bt||(bt=et==="failed"?Promise.resolve(null):Promise.resolve().then(()=>U.retrievePaymentIntent(fe)),da.set(fe,bt));let Ge={accountPatch:V.accountPatch,sessionId:V.sessionId,nonce:V.nonce},$=()=>{X?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...yr,requestCategory:"provider_sdk"})};return X?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...yr}),(async()=>{try{Ve(!0);let f=await bt;if(!Me)return;if(f?.error){da.delete(fe),$(),a?.(f.error.message??"Failed to retrieve PayPal payment status.");return}if(Hd(),da.delete(fe),et==="failed"){let H="PayPal payment was declined. Please try again.";X?.terminal({outcome:"payment_declined",...yr,terminalReason:"provider_declined"}),a?.(H),u?.(cn("paypal",H));return}let P=f?.paymentIntent;if(P&&P.id!==q){$(),a?.("Failed to match the returned PayPal payment.");return}if(P&&(P.status==="requires_capture"||P.status==="succeeded")){let H=typeof P.payment_method=="string"?P.payment_method:P.payment_method?.id;o({id:H??P.id,type:"card",threeDSecureActionResultTokenId:P.id,isPaypal:!0},{...Ge,presentationMode:"redirect"})}else{let H="PayPal payment was not completed. Please try again.";X?.terminal({outcome:P?.status==="canceled"?"payment_cancelled":"payment_declined",...yr,terminalReason:P?.status==="canceled"?"cancelled":"provider_declined"}),a?.(H),u?.(cn("paypal",H))}}catch(f){if(!Me)return;da.delete(fe),$(),a?.(f instanceof Error?f.message:"Failed to complete PayPal payment.")}finally{Me&&Ve(!1)}})(),()=>{Me=!1,Le.current=!1}},[U,o,a,u,X]);let at=(0,i.useCallback)(async(q=!1)=>{let fe=b?await b("paypal"):{proceed:!0};if(!fe.proceed)return ye.current.delete(Ie),!1;let et=N("paypal");return ye.current.set(Ie,{generation:et,accountPatch:fe.accountPatch,sessionId:fe.sessionId,nonce:fe.nonce}),R(!1),X?.log({name:`provider.${q?"redirect.started":"handoff.requested"}`,stage:q?"redirect":"overlay_open",...yr,attempt:et}),d?.("paypal"),!0},[d,X,b,N,Ie]),xe=(0,i.useCallback)(async q=>{if(l||re||!await at()){q.reject();return}q.resolve()},[l,at,re]),jt=(0,i.useCallback)(async q=>{if(!U||!de)return;let fe=ye.current.get(Ie);if(fe&&!Z(fe.generation)){ye.current.delete(Ie);return}if(!fe&&Ke()||fe&&!ve(fe.generation))return;fe||ve();let et=fe??null;if(ye.current.delete(Ie),!et&&b){let Je=await b("paypal");if(!Je.proceed){q.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}et={accountPatch:Je.accountPatch,sessionId:Je.sessionId,nonce:Je.nonce}}let V=et?.sessionId??e,Me=et?.nonce??t,bt=await Xd({event:q,prepared:et,email:n,billingName:v,methodLabel:"PayPal",collect:ft});if(!bt){q.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ge=bt.email,$={...et?.accountPatch,...Bn(bt,!0)};try{if(Ve(!0),a?.(null),!V||!(0,y.isValidEmail)(Ge))throw new Error("Missing sessionId or email for PayPal payment");await M?.(bt);let Je=U.createPaymentMethod,{error:f,paymentMethod:P}=await Je({type:"paypal"});if(f){Ae(f,"stripe_paypal_create_payment_method_failed",fe?.generation),q.paymentFailed({reason:"fail"});return}let H=await ti(r,Y,V,Me??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:P?.id??null,intentKind:"payment"});if(H.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ne=H.clientSecret,$e={return_url:os()};if(P?.id&&($e.payment_method=P.id),!$t(ua,{clientSecret:ne,sessionId:V,nonce:Me,accountPatch:$})&&G==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:Re,paymentIntent:ae}=await U.confirmPayment({clientSecret:ne,confirmParams:$e,redirect:"if_required"});if(Re){if($t(ua),Jo(Re)){let Ct=Re.message??"Your payment was declined.";X?.terminal({outcome:"payment_declined",...yr,terminalReason:"provider_declined"}),a?.(Ct),u?.(cn("paypal",Ct,{code:_r(Re),declineCode:wo(Re)})),await ni({billingApiUrl:r,sessionId:V,nonce:Me,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:_r(Re)??"provider_declined"}})}else Ae(Re,"stripe_paypal_confirm_failed",fe?.generation);return}$t(ua);let it=typeof ae?.payment_method=="string"?ae.payment_method:ae?.payment_method?.id;o({id:it??ae?.id,type:"card",threeDSecureActionResultTokenId:ae?.id,isPaypal:!0},{accountPatch:$,paymentMethodCategory:"paypal",presentationMode:G,sessionId:V,nonce:Me});return}catch(Je){Ae(Je,"stripe_paypal_failed",fe?.generation)}finally{Ve(!1)}},[U,de,e,t,n,v,ft,M,r,Y,o,a,u,b,Ae,ve,Z,Ke,X,G,Ie]),Vt=(0,i.useCallback)(async()=>{if(!(yt.current||l||re||!U||!de)){yt.current=!0,Ve(!0);try{if(!await at(!0))return;await jt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{yt.current=!1,Ve(!1)}}},[de,jt,l,at,U,re]),ut=G==="redirect"?(0,c.jsx)("button",{type:"button",disabled:l||re,onClick:()=>{Vt()},style:{width:"100%",minHeight:pa,border:"1px solid #d1d5db",borderRadius:w??8,background:"#ffc439",color:"#111827",cursor:l||re?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,c.jsx)(Jt.ExpressCheckoutElement,{onReady:q=>De(tc(q,["paypal"])),onLoadError:()=>{De("load_error"),as(X,"paypal","paypal","provider_error")},onClick:xe,onConfirm:jt,onCancel:()=>{let q=ye.current.get(Ie);ye.current.delete(Ie),X?.terminal({outcome:"payment_cancelled",...yr,terminalReason:"cancelled",...q?{attempt:q.generation}:{}}),ue(q?.generation),R(!1),He.current=!0,lt()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:te,emailRequired:te,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},Ie),Et=(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)("div",{ref:be,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[rt&&(0,c.jsx)("button",{ref:me,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ct,style:Qi,children:"Try PayPal again"}),Oe&&(0,c.jsx)(So,{identity:Oe.identity,methodLabel:Oe.methodLabel,onComplete:ke,onCancel:()=>ke(null)},Oe.id),(0,c.jsx)("div",{style:{display:Oe?"none":void 0},children:ut})]}),re&&!Oe&&(0,c.jsx)(er,{status:"processing"})]});return G==="redirect"?Et:(0,c.jsx)(nc,{state:he,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:Et})}function Kl({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:d,onButtonClick:u,onDecline:p,onTechnicalFailure:b,runBeforeButtonClick:v,billingName:M,onBuyerIdentityReady:I,onLoadStateChange:w,placeholderBorderRadius:h,popupCapabilityOwner:O,externalTelemetryContext:G}){let T=Ur(),{emitInstrument:Y}=(0,i.useContext)(Zn),U=(0,Jt.useStripe)(),de=(0,Jt.useElements)(),X=(0,i.useMemo)(()=>Ya(dn(T),G),[G,T]),[he,De]=(0,i.useState)("loading");(0,i.useEffect)(()=>{w?.(he)},[he,w]);let[re,Ve]=(0,i.useState)(!1),yt=(0,i.useRef)(!(0,y.isValidEmail)(n?.trim())||!M?.trim()).current,{request:te,collect:Oe,finish:ft}=Co(),ke=(0,i.useRef)(null),Le=(0,i.useRef)(null),[be,me]=(0,i.useState)(0),[Ie,We]=(0,i.useState)(!1),[rt,R]=(0,i.useState)(()=>ei(e,t)?"blocked":"idle"),[He,ye]=(0,i.useState)("google_pay"),N=(0,i.useRef)(null),ve=(0,i.useRef)(!0),ue=(0,i.useRef)(!1),Ke=(0,i.useRef)("google_pay"),Z=(0,i.useRef)("google_pay"),ot=(0,i.useRef)(null),lt=(0,i.useRef)(null),Ae=(0,i.useRef)(new Set);(0,i.useEffect)(()=>(ve.current=!0,()=>{ve.current=!1;for(let $ of Ae.current)window.clearTimeout($);Ae.current.clear()}),[]);let Ne=(0,i.useRef)(new Map),{startAttempt:ct,finishAttempt:at,invalidateAttempt:xe,isAttemptInvalidated:jt,isAttemptCurrent:Vt,generationRef:ut}=ta(($,Je,f)=>{b?.($,Je,{...f,popupBlocked:f?.popupBlocked??Gr(Je),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ye($),We(!0),me(P=>P+1)},{onHandoffObserved:$=>{O.markAvailable(),X?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ut.current,...$==="apple_pay"||$==="google_pay"?{walletType:$}:{}})}});(0,i.useEffect)(()=>{Ie&&Le.current?.focus()},[Ie,be]);let Et=(0,i.useCallback)(()=>{me($=>$+1)},[]),q=(0,i.useCallback)(($,Je,f,P,H=!1)=>{xe(P),b?.($,Je,{code:f,popupBlocked:Gr(Je),telemetryReported:H,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ye($),We(!0),Et()},[xe,b,Et]),fe=(0,i.useCallback)(()=>{window.setTimeout(()=>{(ke.current?.querySelector("iframe")??ke.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{ue.current&&(ue.current=!1,fe())},[fe,be]);let et=(0,i.useCallback)(()=>{We(!1),d?.(null),fe()},[fe,d]),V=(0,i.useCallback)(()=>{N.current?.()},[]);(0,i.useEffect)(()=>{let $=ei(e,t);if(!$)return;let Je=!1,f=!1,P=async()=>{if(!f){f=!0,Je||R("checking");try{let H=await zl(U,$.clientSecret,Ae.current);if(Je)return;let ne=Xi(H,$.providerObjectId,(0,y.isSetupIntentClientSecret)($.clientSecret));if(ne.kind==="confirmed"){if(!Nl(e,t,$.clientSecret))return;N.current=null,R("idle"),l({id:ne.paymentMethodId,type:"card",threeDSecureActionResultTokenId:ne.intentId},{...$.accountPatch?{accountPatch:$.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(ne.kind==="terminal"){Yi(e,t,$.clientSecret),N.current=null,R("idle"),ye($.paymentMethodType),We(!0),Et();return}R("blocked")}catch{Je||R("blocked")}finally{f=!1}}};return N.current=P,R("blocked"),()=>{Je=!0,N.current===P&&(N.current=null)}},[t,l,Et,e,U]);let Me=(0,i.useCallback)(async $=>{let Je=!1,f=Ce=>{Je||(Je=!0,$.paymentFailed({reason:"fail",...Ce?{message:Ce}:{}}))};if(!U||!de){f();return}let P=Ne.current.get(be);if(P&&!Vt(P.generation)){Ne.current.delete(be),f();return}if(!P&&jt()){f();return}if(P&&!at(P.generation)){f();return}P||at();let H=$.expressPaymentType??P?.method??Ke.current,ne=P??null,$e=jl(H),vt;H==="apple_pay"?vt="apple_pay":H==="google_pay"&&(vt="google_pay");let Re=P?.generation??ut.current,ae=X,it=ae?.now()??globalThis.performance?.now()??Date.now(),Ct=new AbortController,Nt=!1,ze=!1,Ft=null,Ue=e,Fn="processing",Rn="other",Mt="provider_runtime",wn,Dn=new Promise((Ce,St)=>{wn=St}),On=window.setTimeout(()=>{Nt=!0,Ct.abort(),wn(Za)},zd),rn=async(Ce,St,Tt)=>{Fn=Ce,Rn=St,Mt=St==="intent_create"||St==="session_claim"?"transport_error":"provider_runtime";let vn=ae?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Tt,Dn])}finally{let Bt=ae?.now()??globalThis.performance?.now()??Date.now();ae?.performance({stage:Ce,durationMs:Math.max(0,Bt-vn),durationMode:"machine",requestCategory:St,paymentMethodCategory:"wallet",provider:"stripe",...Nt?{statusClass:"timeout"}:{}})}};try{if(Ve(!0),d?.(null),!ne&&v){let _e=await rn("processing","other",v($e));if(!_e.proceed){f();return}ne={accountPatch:_e.accountPatch,sessionId:_e.sessionId,nonce:_e.nonce}}let Ce=ne?.sessionId??e;Ue=Ce;let St=ne?.nonce??t,Tt=ot.current??ne?.accountPatch,vn=ec({event:$,fallbackEmail:Tt?.email??n,fallbackName:[Tt?.firstName,Tt?.lastName].join(" ").trim()||M});if(!(0,y.isValidEmail)(vn.email)){f("Buyer details are required."),Oe(es(H),vn).then(_e=>{_e&&(ot.current=_e)});return}ot.current=null;let Bt={...ne?.accountPatch,...Bn(vn,!0)};await rn("processing","session_claim",Promise.resolve(I?.(vn)));let{error:Vn}=await rn("tokenization","provider_sdk",de.submit());if(Vn){f(),q(H,Vn,"stripe_wallet_submit_failed",P?.generation);return}if(!Ce)throw new Error("Missing sessionId or email for payment.");let pn={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H,paymentMethodId:null,intentKind:o},Wt=JSON.stringify({sessionId:Ce,nonce:St??"",request:pn}),an=lt.current,Wn=an?.retryIdentity===Wt?an.authorizationAttemptId:(0,y.randomUuidV4)();lt.current={authorizationAttemptId:Wn,retryIdentity:Wt};let mn=await rn("processing","intent_create",ti(r,Y,Ce,St??"",{...pn,authorizationAttemptId:Wn},{signal:Ct.signal}));if(mn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let wt=mn.clientSecret,Zt=$d({createdAt:Date.now(),sessionId:Ce,...St?{nonce:St}:{},clientSecret:wt,providerObjectId:mn.providerObjectId,paymentMethodType:H,accountPatch:Bt});window.clearTimeout(On),ze=!0,ae?.performance({stage:"callback",durationMs:Math.max(0,(ae?.now()??globalThis.performance?.now()??Date.now())-it),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let yn=ae?.now()??globalThis.performance?.now()??Date.now(),Dt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...vt?{walletType:vt}:{},attempt:Re},Qt=!1,Ht=null;ae?.log({name:"payment.provider_confirmation.started",...Dt}),Ft=window.setTimeout(()=>{Ft!==null&&Ae.current.delete(Ft),Qt=!0;let _e=ae?.now()??globalThis.performance?.now()??Date.now();ae?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Dt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,_e-yn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),ae?.flush?.().catch(()=>{}),Ht?.()},Ud),Ae.current.add(Ft);let fn=(_e,ht)=>{Ft!==null&&(window.clearTimeout(Ft),Ae.current.delete(Ft),Ft=null);let ie=ae?.now()??globalThis.performance?.now()??Date.now(),F=Math.max(0,ie-yn),Ze=_e;Qt&&(_e==="resolved"?Ze="resolved_late":_e==="returned_error"?Ze="returned_error_late":Ze="rejected_late");let se=ht??(_e==="resolved"?"approved":"provider_error");return ae?.log({name:"payment.provider_confirmation.returned",...Dt,operationOutcome:Ze,terminalReason:se}),ae?.performance({...Dt,durationMs:F,durationMode:"buyer",operationOutcome:Ze,terminalReason:se}),{durationMs:F,operationOutcome:Ze,terminalReason:se}},gt=!1,Q=!1,Ln=_e=>{if(!_e||typeof _e!="object")return null;let ht=_e;if(ht.error)return null;let ie=ht.setupIntent??ht.paymentIntent,F=Xi(ie??null,void 0,!!ht.setupIntent);return F.kind==="confirmed"?F:null},Nn=_e=>{if(gt||P&&ut.current!==P.generation)return;let ht=Ln(_e);if(!ht)return;if(Zt&&!Nl(Ce,St,wt)){gt=!0;return}let{intentId:ie,paymentMethodId:F}=ht;gt=!0,Q=!0,lt.current=null,N.current=null,ve.current&&(R("idle"),Ve(!1));let Ze=`${Yl}:${Ce}`;$t(Ze,{createdAt:Date.now(),sessionId:Ce,nonce:St,accountPatch:Bt,paymentMethodId:F,providerIntentId:ie,paymentMethodType:H});try{l({id:F,type:"card",threeDSecureActionResultTokenId:ie},{accountPatch:Bt,paymentMethodCategory:"wallet",sessionId:Ce,nonce:St})}finally{$t(Ze)}},hr=!1;Ht=async()=>{if(!(hr||gt||Q)){hr=!0,ve.current&&R("checking");try{let _e=await zl(U,wt,Ae.current);if(gt||Q)return;let ht=(0,y.isSetupIntentClientSecret)(wt),ie=Xi(_e,mn.providerObjectId,ht);if(ie.kind==="confirmed"){Nn(ht?{setupIntent:_e}:{paymentIntent:_e});return}if(ie.kind==="terminal"){if(Q=!0,Yi(Ce,St,wt),lt.current=null,N.current=null,!ve.current)return;R("idle"),f(),q(H,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",P?.generation,!0);return}ve.current&&!Q&&(R("blocked"),Ve(!1))}catch{ve.current&&!Q&&(R("blocked"),Ve(!1))}finally{hr=!1}}},N.current=Ht;let Cn,sn;try{let _e=await((0,y.isSetupIntentClientSecret)(wt)?U.confirmSetup({elements:de,clientSecret:wt,redirect:"if_required"}):U.confirmPayment({elements:de,clientSecret:wt,redirect:"if_required"}));if(!_e||typeof _e!="object"||(Cn=_e,!Cn.error&&!Ln(Cn)))throw Gi;sn=fn(Cn.error?"returned_error":"resolved",Cn.error&&Jo(Cn.error)?"provider_declined":void 0)}catch(_e){let ht=_e===Gi,ie=fn(ht?"returned_error":"rejected");if(ae?.error({...ht?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:xi(_e),...Dt,operationOutcome:ie.operationOutcome,durationMs:ie.durationMs,statusClass:"unknown",terminalReason:ie.terminalReason}),!ve.current||gt)return;await Ht?.();return}let _n=Cn.error;if(_n){if(!ve.current||gt)return;if(Jo(_n)){Q=!0,Yi(Ce,St,wt),lt.current=null,N.current=null,R("idle");let _e=_n.message??"Your payment was declined.";f(_e),d?.(_e),p?.(cn($e,_e,{code:_r(_n),declineCode:wo(_n)})),ni({billingApiUrl:r,sessionId:Ce,nonce:St,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H,providerDeclineReason:_r(_n)??"provider_declined",...mn.intentKind==="payment"&&mn.providerObjectId.startsWith("pi_")?{providerIntentId:mn.providerObjectId}:{}}})}else ae?.error({...xi(_n),...Dt,operationOutcome:sn.operationOutcome,durationMs:sn.durationMs,statusClass:"unknown",terminalReason:sn.terminalReason}),await Ht?.();return}if(Nn(Cn),!gt)throw new Error("Invalid provider returned for APM intent")}catch(Ce){if(Ce===Za){let St=ae?.now()??globalThis.performance?.now()??Date.now();ae?.error({errorCode:Vd(Rn),stage:Fn,requestCategory:Rn,paymentMethodCategory:"wallet",provider:"stripe",...vt?{walletType:vt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ue,durationMs:Math.max(0,St-it),statusClass:"timeout",failureCategory:Mt,attempt:Re,terminalReason:"provider_error"}),ae?.flush?.().catch(()=>{})}f(),q(H,Ce,Ce===Za?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",P?.generation,Ce===Za)}finally{if(window.clearTimeout(On),Ft!==null&&(window.clearTimeout(Ft),Ae.current.delete(Ft)),!ze){let Ce=ae?.now()??globalThis.performance?.now()??Date.now();ae?.performance({stage:"callback",durationMs:Math.max(0,Ce-it),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Nt?{statusClass:"timeout"}:{}})}ve.current&&Ve(!1)}},[U,de,e,t,n,M,Oe,I,r,Y,o,l,d,p,v,q,at,Vt,jt,ut,X,be]),bt=(0,i.useMemo)(()=>{let $=["applePay","googlePay","paypal","link","amazonPay","klarna"],Je=new Set(["applePay","googlePay"]),f=new Set(a.map(y.stripeExpressMethodToOptionKey)),P={};for(let H of $)f.has(H)?P[H]=Je.has(H)?"always":"auto":P[H]="never";return P},[a]),Ge=(0,i.useMemo)(()=>a.map(y.stripeExpressMethodToOptionKey),[a]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(nc,{state:he,placeholderTestId:"flopay-wallet-placeholder",borderRadius:h,children:(0,c.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:[Ie&&(0,c.jsxs)("button",{ref:Le,type:"button","data-testid":"flopay-wallet-retry-button",onClick:et,style:Qi,children:["Try ",es(He)," again"]}),rt!=="idle"&&(0,c.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,c.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,c.jsx)("button",{type:"button",onClick:V,disabled:rt==="checking",style:Qi,children:rt==="checking"?"Checking payment status\u2026":"Check payment status"})]}),te&&(0,c.jsx)(So,{identity:te.identity,methodLabel:te.methodLabel,onComplete:ft,onCancel:()=>ft(null)},te.id),rt==="idle"&&(0,c.jsx)("div",{style:{display:te?"none":void 0},children:(0,c.jsx)(Jt.ExpressCheckoutElement,{onReady:$=>{De(tc($,Ge))},onLoadError:$=>{De("load_error"),as(X,"stripe","wallet","provider_error")},onClick:async $=>{Ke.current=$.expressPaymentType,Z.current=jl($.expressPaymentType);let Je=!0,f=window.setTimeout(()=>{Je=!1,$.reject()},Nd),P=v?await v(Z.current):{proceed:!0};if(window.clearTimeout(f),!Je)return;if(!P.proceed){Ne.current.delete(be),$.reject();return}let H=ct($.expressPaymentType);Ne.current.set(be,{generation:H,method:$.expressPaymentType,accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}),We(!1),X?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:H,...$.expressPaymentType==="apple_pay"||$.expressPaymentType==="google_pay"?{walletType:$.expressPaymentType}:{}}),u?.(Z.current),$.resolve()},onConfirm:Me,onCancel:()=>{let $=Ne.current.get(be);Ne.current.delete(be),X?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...$?{attempt:$.generation}:{}}),xe($?.generation),lt.current=null,We(!1),ue.current=!0,Et()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:bt,emailRequired:yt,billingAddressRequired:yt,layout:{maxColumns:1,overflow:"never"}}},be)})]})}),re&&(0,c.jsx)(er,{status:"processing"})]})}function rc(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function lu({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:d,borderColor:u,textColor:p,borderRadius:b,fontFamily:v}){let M=(0,y.resolveStripeMethodBrandVariant)(e,t),I=Rl[e],[w,h]=(0,i.useState)(!1),O=!!I&&!w,G=M?.backgroundColor??d??"#ffffff",T=M?.borderColor??u??"#d1d5db",Y=M?.textColor??p??"#262833";return(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&l()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:pa,padding:"0 1rem",backgroundColor:G,color:Y,border:`1px solid ${T}`,borderRadius:b??8,fontSize:"0.95rem",fontWeight:600,fontFamily:v,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,c.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,y.getStripeMethodDisplayName)(e)}\u2026`}):(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,y.hasVendoredStripeMethodLogo)(e)?8:0},children:[O?(0,c.jsx)("img",{src:I,alt:"","aria-hidden":"true",onError:()=>h(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!O&&M?.logoSvg?(0,c.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:M.logoSvg}}):null,(0,c.jsx)("span",{children:(0,y.getStripeMethodDisplayName)(e)})]}),a&&(0,c.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:Y,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,c.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function ts({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:d,onErrorChange:u,onDecline:p,onCancel:b,runBeforeButtonClick:v,onButtonClick:M,isProcessing:I,submitButtonColor:w,submitButtonBorderRadius:h,submitButtonStyle:O,errorText:G}){let T=Ur(),{emitInstrument:Y}=(0,i.useContext)(Zn),U=(0,Jt.useStripe)(),de=(0,Jt.useElements)(),[X,he]=(0,i.useState)(!1),De=(0,i.useRef)(!1),[re,Ve]=(0,i.useState)(!1),[yt,te]=(0,i.useState)("loading"),[Oe,ft]=(0,i.useState)(""),ke=!(0,y.isValidEmail)(r?.trim()),Le=!ke||(0,y.isValidEmail)(Oe.trim()),be=(0,i.useCallback)(async()=>{if(!U||!de||I||De.current||!re)return;De.current=!0,he(!0);let me=v?await v("card"):{proceed:!0};if(!me.proceed){De.current=!1,he(!1);return}M?.("card");let Ie=me.sessionId??t,We=me.nonce??n,rt=eo(o?.trim()),R=Bn({email:me.accountPatch?.email?.trim()||r?.trim()||Oe.trim(),firstName:me.accountPatch?.firstName?.trim()||rt.firstName,lastName:me.accountPatch?.lastName?.trim()||rt.lastName}),He=R.email,ye=Bn({...me.accountPatch,...R});try{if(u?.(null),!(0,y.isValidEmail)(He))throw new Error("A valid email address is required for payment.");await a?.(R);let N=await de.submit();if(N.error){u?.(N.error.message??"Payment failed.");return}let ve=[R.firstName,R.lastName].filter(Boolean).join(" "),ue=await U.createPaymentMethod({elements:de,params:{billing_details:{email:He,...ve?{name:ve}:{}}}});if(ue.error||!ue.paymentMethod){u?.(ue.error?.message??"Failed to create payment method.");return}let Ke=ue.paymentMethod;if(!Ie||!He)throw new Error("Missing sessionId or email for payment.");let Z=Ke.type||e,ot=await ti(l,Y,Ie,We??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,paymentMethodId:null,intentKind:"payment"});if(ot.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let lt=ot.clientSecret;$t(Tr,{clientSecret:lt,sessionId:Ie,nonce:We,accountPatch:ye,paymentMethodId:Ke.id,paymentMethodType:Ke.type??e,gateway:"stripe"});let{error:Ae,paymentIntent:Ne}=await U.confirmPayment({clientSecret:lt,confirmParams:{return_url:window.location.href,payment_method:Ke.id},redirect:"if_required"});if(Ae){$t(Tr);let xe=Ae.message??"Payment failed.";u?.(xe),p?.(cn("card",xe,{code:Ae.code})),await ni({billingApiUrl:l,sessionId:Ie,nonce:We,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ae.code??"provider_declined"}});return}let ct=Ne?.status;if(!Yo(ct)){$t(Tr);let xe=ct==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";u?.(xe),p?.(cn("card",xe,{code:ct??"missing_payment_intent"}));return}$t(Tr);let at=typeof Ne?.payment_method=="string"?Ne.payment_method:Ne?.payment_method?.id;d({id:at??Ke.id,type:"card",threeDSecureActionResultTokenId:Ne?.id,gateway:"stripe",paymentMethodType:Ke.type??e},{accountPatch:ye,paymentMethodCategory:"apm",sessionId:Ie,nonce:We})}catch(N){u?.(N instanceof Error?N.message:"Payment failed. Please try again.")}finally{De.current=!1,he(!1)}},[U,de,I,re,v,M,t,n,r,o,Oe,a,l,Y,e,d,u,p]);return(0,c.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ke&&(0,c.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ke&&(0,c.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,c.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Oe,onChange:me=>ft(me.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,c.jsx)(Jt.PaymentElement,{onReady:()=>te("ready"),onLoadError:()=>{te("load_error"),as(dn(T),"stripe","apm")},onChange:me=>{Ve(!!me.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,y.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{be()},disabled:!re||!Le||X||I||yt!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:w,color:"white",border:"none",borderRadius:h,fontSize:"1rem",fontWeight:600,cursor:!re||!Le||X||I||yt!=="ready"?"not-allowed":"pointer",opacity:!re||!Le||X||I||yt!=="ready"?.5:1,transition:"opacity 120ms ease-out",...O??{}},children:X?"Processing\u2026":`Pay with ${(0,y.getStripeMethodDisplayName)(e)}`}),G&&(0,c.jsx)(Io,{margin:"0.75rem 0 0",children:G})]})}function Gl({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:d,paymentElementBaseOptions:u,onTokenizedBody:p,onErrorChange:b,onButtonClick:v,onDecline:M,runBeforeButtonClick:I,onLoadStateChange:w,isProcessing:h=!1,submitButtonColor:O="#4A49FF",submitButtonBorderRadius:G=8,submitButtonStyle:T,buttonAppearance:Y,themeId:U,onExpandApm:de,expandedApmMethod:X}){let{emitInstrument:he}=(0,i.useContext)(Zn),[De,re]=(0,i.useState)(null),[Ve,yt]=(0,i.useState)(null),te=(0,i.useRef)(!1),{request:Oe,collect:ft,finish:ke}=Co();(0,i.useEffect)(()=>{l.length>0&&d?w?.("ready"):d||w?.("loading")},[l.length,d,w]);let Le=(0,i.useCallback)(async R=>{if(!d||te.current||h)return;te.current=!0,yt(R);let He=I?await I("card"):{proceed:!0};if(!He.proceed){te.current=!1,yt(null);return}v?.("card");let ye=He.sessionId??e,N=He.nonce??t,ve=eo([He.accountPatch?.firstName,He.accountPatch?.lastName].filter(Boolean).join(" ")||r),ue=Bn({email:He.accountPatch?.email?.trim()||n?.trim(),firstName:He.accountPatch?.firstName?.trim()||ve.firstName,lastName:He.accountPatch?.lastName?.trim()||ve.lastName});if(!(0,y.isValidEmail)(ue.email)){yt(null);let ot=await ft((0,y.getStripeMethodDisplayName)(R),ue);if(!ot){te.current=!1;return}ue=ot,yt(R)}let Ke=ue.email,Z=Bn({...He.accountPatch,...ue});try{if(b?.(null),!ye||!(0,y.isValidEmail)(Ke))throw new Error("Missing sessionId or email for payment.");await o?.(ue);let ot=await ti(a,he,ye,N??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:R,paymentMethodId:null,intentKind:"payment"});if(ot.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let lt=ot.clientSecret;$t(Tr,{clientSecret:lt,sessionId:ye,nonce:N,accountPatch:Z,paymentMethodType:R,gateway:"stripe"});let{error:Ae,paymentIntent:Ne}=await d.confirmPayment({clientSecret:lt,confirmParams:{return_url:window.location.href,payment_method_data:{type:R,billing_details:{name:[ue.firstName,ue.lastName].filter(Boolean).join(" "),...Ke?{email:Ke}:{}}}},redirect:"if_required"});if(Ae){$t(Tr);let xe=Ae.message??"Payment failed.";b?.(xe),M?.(cn("card",xe,{code:Ae.code})),await ni({billingApiUrl:a,sessionId:ye,nonce:N,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:R,providerDeclineReason:Ae.code??"provider_declined"}});return}let ct=Ne?.status;if(!Yo(ct)){$t(Tr);let xe=ct==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";b?.(xe),M?.(cn("card",xe,{code:ct??"missing_payment_intent"}));return}$t(Tr);let at=typeof Ne?.payment_method=="string"?Ne.payment_method:Ne?.payment_method?.id;p({id:at??Ne?.id,type:"card",threeDSecureActionResultTokenId:Ne?.id,gateway:"stripe",paymentMethodType:R},{accountPatch:Z,paymentMethodCategory:"apm",sessionId:ye,nonce:N})}catch(ot){b?.(ot instanceof Error?ot.message:"Payment failed. Please try again.")}finally{te.current=!1,yt(null)}},[d,h,I,v,e,t,n,ft,a,he,r,o,p,b,M]),[be,me]=(0,i.useState)(null),Ie=de?X??null:be,We=(0,i.useCallback)(R=>{te.current||h||Ie&&Ie!==R||((0,y.needsStripeMethodExplicitConfirm)(R)?de?de(R):me(R):Le(R))},[Ie,h,Le,de]),rt=(0,i.useMemo)(()=>be?rc(u,be):null,[be,u]);return(0,c.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Oe?(0,c.jsx)(So,{identity:Oe.identity,methodLabel:Oe.methodLabel,onComplete:ke,onCancel:()=>ke(null)},Oe.id):l.map(R=>{let He=X===R,ye=Ve===R,N=Ve!==null&&Ve!==R||X!=null&&X!==R;return(0,c.jsxs)(i.default.Fragment,{children:[(0,c.jsx)(lu,{method:R,themeId:U,submitting:ye,disabled:N,highlighted:He,hasNextStep:(0,y.needsStripeMethodExplicitConfirm)(R),onClick:()=>We(R),backgroundColor:Y?.backgroundColor,borderColor:Y?.borderColor,textColor:Y?.textColor,borderRadius:Y?.borderRadius,fontFamily:Y?.fontFamily}),!de&&be===R&&rt&&d&&(0,c.jsx)(Jt.Elements,{stripe:d,options:rt,children:(0,c.jsx)(ts,{method:R,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:p,onErrorChange:b,onDecline:M,onCancel:()=>me(null),runBeforeButtonClick:I,onButtonClick:v,isProcessing:h,submitButtonColor:O,submitButtonBorderRadius:G,submitButtonStyle:T})},R)]},R)})})}function cu({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:l,onError:d,onDecline:u,onTokenizedBody:p,firstName:b,lastName:v,chv:M,className:I,submitLabel:w,isProcessing:h,error:O,onErrorChange:G,showPayPal:T=!0,showStripe:Y=!0,walletPresentation:U="auto",enabledPaymentMethods:de,enabledPaymentMethodCountries:X,showApplePay:he=!0,showGooglePay:De=!0,layout:re="default",theme:Ve,buttonsTheme:yt,buttonsStyles:te,appearance:Oe,cardButtonContent:ft,cardBackButtonContent:ke,cardTitleContent:Le,showSecurityFooter:be,onButtonClick:me,onBeforeButtonClick:Ie,onBuyerIdentityReady:We,enableAVS:rt,cardFieldOrder:R,cardPreFormSlot:He,avsLayout:ye="row",country:N,zip:ve,addressLine1:ue,addressLine2:Ke,city:Z,state:ot,onCountryChange:lt,onZipChange:Ae,avsCheck:Ne,checkoutType:ct,checkoutLayout:at,totalAmount:xe=0,currency:jt="usd",initialCardOpen:Vt=!1,directPaypal:ut,isSubscription:Et=!1,session:q,dataAttachmentPending:fe=!1,dataAttachmentRequiresIdentity:et=!1,debug:V=!1}){let Me=Ur(),bt=Ba(),Ge=(0,i.useContext)(pr),{emitInstrument:$}=(0,i.useContext)(Zn),Je=(0,i.useRef)(null);Je.current||(Je.current=Oa());let f=Je.current,[,P]=(0,i.useState)(0),H=(0,i.useRef)(null);H.current||(H.current=Qo());let ne=H.current,$e=(0,i.useMemo)(()=>({browser:ne,capability:f,presentationMode:"popup"}),[ne,f]),vt=q??Ge.session,Re=vt?.gateways?.paypal?.providerObjectType??ut?.providerObjectType,ae=fe||Ge.claimPending===!0,it=et||Ge.claimRequiresIdentity===!0,Ct=ae&&!it,Nt=ul(),ze=n||Nt,[Ft,Ue]=(0,i.useState)(!1),[Fn,Rn]=(0,i.useState)(null),[Mt,wn]=(0,i.useState)(N??""),[Dn,On]=(0,i.useState)(ve??""),[rn,Ce]=(0,i.useState)(ue??""),[St,Tt]=(0,i.useState)(Ke??""),[vn,Bt]=(0,i.useState)(Z??""),[Vn,pn]=(0,i.useState)(ot??""),[Wt,an]=(0,i.useState)(""),[Wn,mn]=(0,i.useState)({}),wt=(0,i.useRef)(ve??""),Zt=(0,i.useRef)(N??""),yn=(0,i.useRef)(ue??""),Dt=(0,i.useRef)(Ke??""),Qt=(0,i.useRef)(Z??""),Ht=(0,i.useRef)(ot??""),fn=(0,i.useRef)(""),gt=(0,i.useRef)({});(0,i.useEffect)(()=>{let s=(S,K,Te,ee,Se)=>{if(gt.current[S])return;let Xt=K?.trim();!Xt||Xt===Te.current||(Te.current=Xt,ee(Xt),Se?.(Xt))};s("country",N,Zt,wn,lt),s("zip",ve,wt,On,Ae),s("addressLine1",ue,yn,Ce),s("addressLine2",Ke,Dt,Tt),s("city",Z,Qt,Bt),s("state",ot,Ht,pn)},[N,ve,ue,Ke,Z,ot,lt,Ae]);let Q=(0,i.useMemo)(()=>(0,y.resolveAVSConfig)(rt),[rt]),Ln=Q!==null,Nn=(0,i.useMemo)(()=>(0,y.isAuthorizationOnlySession)(q),[q]),hr=!!q?.vault?.html,Cn=!!q?.gateways?.pcivault,sn=Ei(q),_e=!!(q?.gateways?.stripe?.enabledPaymentMethods??de)?.includes("card")||Wr(q),ht=hr||_e||Cn,ie=!!(Y&&ht&&e),[F,Ze]=(0,i.useState)(()=>re!=="buttons"||Vt?e??null:null),[se,Hn]=(0,i.useState)(0),gn=re!=="buttons"||Vt||!!e&&F===e,Kt=q?.captureMethod,Kn=(0,i.useRef)(Me);(0,i.useEffect)(()=>{Kn.current=Me},[Me]);let[nt,jr]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!ie||!e||!gn){jr(null);return}let s=Kn.current?Kn.current.cardCapture({sessionId:e,captureMethod:Kt}):new fr.PciVaultCardCapture({sessionId:e,captureMethod:Kt,billingApiUrl:ze,telemetry:r});return jr({sessionId:e,captureMethod:Kt,billingApiUrl:ze,telemetry:r,capture:s}),()=>{s.unmount()}},[ie,e,gn,Kt,ze,r]);let Gt=ie&&e&&gn&&nt?.sessionId===e&&nt.captureMethod===Kt&&nt.billingApiUrl===ze&&nt.telemetry===r?nt.capture:null,hn=(0,i.useMemo)(()=>{let s=Mt,S=Q?(0,y.isAVSFieldVisible)(Q.postal_code,s):!1;return au(s,Dn,S)},[Q,Mt,Dn]),{avsInvalid:Mr,invalidAvsFields:Br}=(0,i.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!ie||!Q)return{avsInvalid:!1,invalidAvsFields:s};let S=Mt,K=(Se,Xt)=>(0,y.isAVSFieldVisible)(Se,S)&&!Xt.trim(),Te={line1:K(Q.address_line_1,rn),city:K(Q.city,vn),state:K(Q.state,Vn),zip:hn.empty||hn.malformed};return{avsInvalid:Te.line1||Te.city||Te.state||Te.zip,invalidAvsFields:Te}},[ie,Q,Mt,rn,vn,Vn,hn]),[En,en]=(0,i.useState)(!1),[br,Tn]=(0,i.useState)(!1),[Fr,An]=(0,i.useState)(!1),[Pr,vr]=(0,i.useState)({line1:!1,city:!1,state:!1}),rr=(0,i.useRef)(!1),Gn=(0,i.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Yn=(0,i.useRef)(!1),xt=(0,i.useCallback)(s=>{Gn.current[s]=!0,Yn.current=!0},[]),or=(0,i.useCallback)(s=>!rr.current&&Gn.current[s],[]),kn=(0,i.useCallback)(s=>{or(s)&&vr(S=>S[s]?S:{...S,[s]:!0})},[or]),[Xn,Cr]=(0,i.useState)(()=>Ji(q?.vault)),[dt,on]=(0,i.useState)(Vt&&ht?"card":"buttons"),[tn,Dr]=(0,i.useState)(null),zn=dt==="expanding"||dt==="card",Vr=q?.gateways?.stripe&&!sn?"stripe":void 0,ar=(0,i.useCallback)(()=>{$?.({class:"card_surface",provider:Vr})},[Vr,$]),ir=(0,i.useRef)(null),bn=(0,i.useCallback)(s=>{ir.current&&clearTimeout(ir.current),ir.current=setTimeout(()=>{ir.current=null,s()},ma)},[]);(0,i.useEffect)(()=>()=>{ir.current&&clearTimeout(ir.current)},[]);let sr=(0,i.useCallback)(()=>{ar(),Ze(e??null),Hn(s=>s+1),on("expanding"),bn(()=>on("card"))},[bn,ar,e]),Or=(0,i.useCallback)(()=>{on("collapsing"),bn(()=>on("buttons"))},[bn]),In=(0,i.useCallback)(s=>{Dr(s),on("apm-expanding"),bn(()=>on("apm-form"))},[bn]),A=(0,i.useCallback)(()=>{on("apm-collapsing"),bn(()=>{on("buttons"),Dr(null)})},[bn]);(0,i.useEffect)(()=>{re==="buttons"&&Vt&&ht&&(Ze(e??null),on("card"))},[re,Vt,ht,e]);let[L,B]=(0,i.useState)(null),le=(0,i.useRef)(!1),Be=(0,i.useRef)(null),pt=(0,i.useRef)("idle"),[pe,Fe]=(0,i.useState)(!1),W=(0,i.useRef)(pe);W.current=pe;let[m,g]=(0,i.useState)(()=>ut?.existingOrderId?{orderId:ut.existingOrderId,attempts:1}:null),D=(0,i.useRef)(m);(0,i.useEffect)(()=>{D.current=m},[m]);let z=(0,i.useRef)(null),ce=(0,i.useMemo)(()=>{if(We||Ge.claimBuyerIdentity||q?.buyerIdentified!==!1||!e||!t)return;let s=`${ze}|${e}|${t}`;z.current?.key!==s&&(z.current={key:s,claim:Po(new fr.PaymentAPI(ze,{telemetry:!1}),e,t,{...a?{userId:a}:{},...b?{firstName:b}:{},...v?{lastName:v}:{}})});let S=z.current.claim;return async K=>{await S(K)}},[We,Ge.claimBuyerIdentity,q?.buyerIdentified,e,t,ze,a,b,v]),J=We??Ge.claimBuyerIdentity??ce,Ye=O??Fn,It=(0,i.useMemo)(()=>(0,y.resolveTheme)(Ve),[Ve]),E=(0,i.useMemo)(()=>{let s=It?.buttonsLayout??(0,y.resolveButtonsLayoutTheme)(yt);return te?{...s,...te,cardButton:{...s.cardButton,...te.cardButton},cardFormContainer:{...s.cardFormContainer,...te.cardFormContainer},backButton:{...s.backButton,...te.backButton},backButtonIcon:{...s.backButtonIcon,...te.backButtonIcon},submitButton:{...s.submitButton,...te.submitButton},title:{...s.title,...te.title}}:s},[It,yt,te]),Pe=Oe??It?.appearance,At=(0,i.useMemo)(()=>Ja({appearance:Pe,buttonsStyles:E,layout:re}),[Pe,E,re]),ge=Ge.inlineSessionPatchProcessing??!1,j=(h??Ft)||ge,oe=ze.replace(/\/+$/,""),_=(0,i.useMemo)(()=>Ai({userId:a,email:o,firstName:b,lastName:v,country:N,zip:ve},Wn),[a,o,b,v,N,ve,Wn]),qe=[_.firstName,_.lastName].filter(s=>!!s?.trim()).join(" "),Rt=!(0,y.isValidEmail)(_.email?.trim()),Ee=(0,i.useRef)(null);ie&&Ee.current===null&&(Ee.current=Rt);let Sn=ie&&(Ee.current??Rt),Sr=(0,i.useMemo)(()=>iu(Wt,Sn),[Wt,Sn]),ao=Sr.empty||Sr.malformed,Un=(0,i.useMemo)(()=>Me?Me.getRawProvider():null,[Me]),ys=(0,i.useMemo)(()=>bt?bt.getRawProvider():null,[bt]),Do=xe||100,io=jt.toLowerCase(),di=(0,i.useMemo)(()=>Pe?(0,fr.toStripeAppearance)(Pe):null,[Pe]),so=di,fs=(0,i.useMemo)(()=>{let s=di??{},S=s.rules??{};return{...s,rules:{...S,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...S[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...S[".AccordionItemContents"]??{}}}}},[di]),gs=(0,i.useMemo)(()=>({...il(xe,q?.captureMethod),currency:io,...so?{appearance:so}:null}),[xe,io,q?.captureMethod,so]),hs=(0,i.useMemo)(()=>({mode:"payment",amount:Do,currency:io,captureMethod:"manual",setupFutureUsage:"off_session",...so?{appearance:so}:null}),[Do,io,so]),we=(0,i.useCallback)(s=>{Rn(s),G?.(s)},[G]),ui=(0,i.useRef)(""),[bs,bc]=(0,i.useState)(!1),pi=(0,i.useCallback)(()=>{bc(!0)},[]);(0,i.useEffect)(()=>{if(!ie||!Sn||!J||!bs||ao||ui.current)return;let s=Bn({email:(0,y.isValidEmail)(_.email?.trim())?_.email?.trim():fn.current.trim(),firstName:_.firstName?.trim(),lastName:_.lastName?.trim()});ui.current=JSON.stringify(s),mn(S=>({...S,...s})),Promise.resolve(J(s)).catch(S=>{ui.current="",we(S instanceof Error?S.message:"Failed to attach buyer details.")})},[ie,Sn,J,bs,ao,_.email,_.firstName,_.lastName,we]),(0,i.useEffect)(()=>{!ie||!Gt||Gt.setCardFieldOrder?.(R??null,Q==null&&!Sn)},[ie,Gt,R,Q,Sn]),(0,i.useEffect)(()=>{(dt==="expanding"||dt==="collapsing"||dt==="apm-expanding"||dt==="apm-collapsing")&&we(null)},[dt,we]);let wr=(0,i.useCallback)((s,S,K)=>{u?.(cn(s,S,K))},[u]),lo=(0,i.useCallback)((s,S,K)=>{let Te=K?.popupBlocked??Gr(S);Te&&f.markBlocked()&&P(tt=>tt+1);let ee=xa(es(s),Te,ne.inAppBrowser),Se=_r(S),Xt=(Se?.toLowerCase()==="error"?void 0:Se)??to(K?.code)??"external_payment_method_failed",dr=new y.FloPayError(ee,"api_error",{code:"external_payment_method_failed",param:s,details:{providerCode:Xt,popupBlocked:Te,inAppBrowser:ne.inAppBrowser,appFamily:ne.appFamily,popupCapability:f.current(),presentationMode:K?.presentationMode??"popup"}});K?.telemetryReported||dn(Me)?.error(xo({...$e,presentationMode:K?.presentationMode??"popup"},{errorCode:Te?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:K?.provider??(s==="paypal"?"paypal":"stripe"),paymentMethodCategory:K?.paymentMethodCategory??(s==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:K?.terminalReason??(Te?"popup_blocked":"provider_error")})),B(null),re==="buttons"&&(on("buttons"),Dr(null)),we(ee),d?.(dr),console.error("[FloPay] External payment method failed:",{method:s,code:Xt,popupBlocked:Te})},[ne,$e,Me,re,d,f,we]);(0,i.useEffect)(()=>{if(!ie||!e){Cr(null);return}let s=Ji(q?.vault);if(s){Cr(s);return}if(!gn){Cr(null);return}Cr(null);let S=!0;return new fr.PaymentAPI(oe).getVaultCapture(e,t).then(K=>{if(!S)return;let Te=Ji(K);Te?Cr(Te):we("Failed to load the secure card form.")}).catch(K=>{S&&we(K instanceof Error?K.message:"Failed to load the secure card form.")}),()=>{S=!1}},[ie,gn,se,e,q?.vault,oe,t,we]);let lr=(0,i.useRef)({onComplete:l,onError:d,updateError:we,emitDecline:wr,resolvedAccount:_,avsConfig:Q,avsCheckProp:Ne,sessionId:e,nonce:t,baseUrl:oe,captureMethod:q?.captureMethod,paymentId:q?.paymentId,authorizationExpiresAt:q?.authorizationExpiresAt,serverSideCardGateway:sn});lr.current={onComplete:l,onError:d,updateError:we,emitDecline:wr,resolvedAccount:_,avsConfig:Q,avsCheckProp:Ne,sessionId:e,nonce:t,baseUrl:oe,captureMethod:q?.captureMethod,paymentId:q?.paymentId,authorizationExpiresAt:q?.authorizationExpiresAt,serverSideCardGateway:sn};let mi=(0,i.useRef)(!1),Ps=(0,i.useCallback)(()=>{let s=lr.current,S=s.resolvedAccount.email?.trim(),K=(0,y.isValidEmail)(S)?S:fn.current.trim();if(!(0,y.isValidEmail)(K))return null;let Te=s.resolvedAccount.firstName?.trim(),ee=s.resolvedAccount.lastName?.trim(),Se=Zt.current.trim()||s.resolvedAccount.country?.trim()||"",Xt=s.avsConfig?(0,y.isAVSFieldVisible)(s.avsConfig.state,Se):!1,dr=s.avsConfig?(0,y.isAVSFieldVisible)(s.avsConfig.address_line_1,Se):!1,tt=s.avsConfig?(0,y.isAVSFieldVisible)(s.avsConfig.postal_code,Se):!1,mt=s.avsConfig?(0,y.isAVSFieldVisible)(s.avsConfig.city,Se):!1,kt=s.avsConfig?(0,y.isAVSFieldVisible)(s.avsConfig.address_line_2,Se):!1,Ut=dr&&!Xt&&tt?(0,y.getStateFromPostalCode)(Se,(wt.current??"").trim()):null,ln=Xt?Ht.current:Ut;return{accountData:{userId:s.resolvedAccount.userId??"",email:K,...Te?{firstName:Te}:{},...ee?{lastName:ee}:{},...tt&&wt.current?{zip:wt.current}:{},...mt&&Qt.current?{city:Qt.current}:{},...ln?{state:ln}:{},...dr&&yn.current?{addressLine1:yn.current}:{},...kt&&Dt.current?{addressLine2:Dt.current}:{},...Se?{country:Se}:{}},...s.avsCheckProp===void 0?{}:{avsCheck:s.avsCheckProp},...s.avsConfig?{avsConfig:{country:(0,y.isAVSFieldVisible)(s.avsConfig.country,Se),postal_code:tt,address_line_1:dr,address_line_2:kt,city:mt,state:Xt}}:{}}},[]),vs=(0,i.useRef)(ae);vs.current=ae,(0,i.useEffect)(()=>{ae||Ye!==Ul||lr.current.updateError(null)},[ae,Ye]),(0,i.useEffect)(()=>{!ie||!Gt||Gt.setSubmitGate?.(Mr||ae||ao||pe)},[ie,Gt,Mr,ae,ao,pe]),(0,i.useEffect)(()=>{if(!ie||!Gt)return;mi.current=!1;let s=null,S=()=>{s&&clearTimeout(s),s=setTimeout(()=>{s=null,pt.current="idle",B(null)},400)},K=Gt.on("submitting",()=>{en(!0),Be.current&&clearTimeout(Be.current),pt.current="validation-window",Be.current=setTimeout(()=>{Be.current=null,pt.current==="validation-window"&&(pt.current="processing")},Kd),B("processing");let tt=lr.current;if(!tt.sessionId||!tt.nonce)return;let mt=Ps();if(!mt){tt.updateError("Enter a valid email address."),pt.current="idle",B(null);return}new fr.PaymentAPI(tt.baseUrl).patchAccountSnapshot(tt.sessionId,tt.nonce,mt,{telemetryMode:"best_effort"}).catch(kt=>{if(!Yd(kt))return;let Ut=kt instanceof Error?kt.message:"Please check your billing address and try again.";tt.updateError(Ut),pt.current="idle",B(null),tt.onError?.(kt instanceof y.FloPayError?kt:new y.FloPayError(Ut,"api_error"))})}),Te=Gt.on("complete",async tt=>{if(Eo(tt.sessionId??lr.current.sessionId),pt.current="terminal",Fe(!1),B("success"),await new Promise(ln=>setTimeout(ln,600)),mi.current)return;mi.current=!0;let mt=lr.current,kt=(0,y.isAuthorizationOnlySession)(mt)||tt.outcome==="authorized",Ut=mt.serverSideCardGateway?{}:{paymentIntentId:tt.intentId};lr.current.onComplete?.(kt?{status:"authorized",...Ut,paymentId:tt.paymentId??mt.paymentId,sessionId:tt.sessionId??mt.sessionId,authorizationExpiresAt:tt.authorizationExpiresAt??mt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Ut,checkoutMethod:"card"})}),ee=Gt.on("decline",tt=>{let mt=lr.current,kt=tt.message??"Your payment was declined. Please try another card or contact your bank.";pt.current="terminal",Fe(!1),mt.updateError(kt),B("error");let Ut=tt.failureOutcome??(0,y.normalizeCheckoutFailureOutcome)(tt.declineReason)??"authorization_declined";mt.emitDecline("card",kt,{code:Ut,declineCode:Ut}),S()}),Se=Gt.on("error",tt=>{let mt=lr.current,kt=tt.message??"There was a problem processing your payment. Please try again.";pt.current="terminal",Fe(!1),mt.updateError(kt),B("error"),mt.onError?.(new y.FloPayError(kt,"api_error",{code:tt.failureOutcome??"capture_failed"})),S()}),Xt=Gt.on("challenge_dismissed",()=>{Be.current&&(clearTimeout(Be.current),Be.current=null),pt.current="processing",Fe(!0),B(null)}),dr=Gt.on("blocked",()=>{if(W.current){lr.current.updateError(Gd);return}if(!vs.current){en(!0);return}pi(),lr.current.updateError(Ul)});return()=>{s&&(clearTimeout(s),s=null),Be.current&&(clearTimeout(Be.current),Be.current=null),pt.current="idle",Fe(!1),B(null),K(),Te(),ee(),Se(),Xt(),dr()}},[ie,Gt,pi,Ps]);let kr=!!ut?.clientId,Oo=Array.isArray(de),ha=Oo&&de.length>0,Cs=Oo&&de.includes("paypal"),ba=(0,i.useRef)(null);ba.current===null&&(ba.current=Wd());let co=ba.current?"redirect":pl(ne,U,f.current()),{expressMethods:Pa,paymentElementMethods:Lo}=(0,i.useMemo)(()=>(0,y.partitionStripeMethods)(de,{excludePaypal:kr}),[de,kr]),Ss=kr||!!bt||Cs&&co==="redirect",Pc=(0,i.useMemo)(()=>Ss?Pa.filter(s=>s!=="paypal"):Pa,[Pa,Ss]),vc=(0,i.useMemo)(()=>{let s=[];return he&&s.push("apple_pay"),De&&s.push("google_pay"),s},[he,De]),uo=Oo?Pc:vc,Cc=Y&&uo.length>0,yi=Ln?Mt:N,va=(0,i.useMemo)(()=>{let s=yi?.trim().toUpperCase();return s?X?Lo.filter(S=>{let K=X[S];return!K||K.length===0||K.includes(s)}):(0,y.filterStripeMethodsByCountry)(Lo,yi):Lo},[Lo,yi,X]),fi=(0,i.useMemo)(()=>({mode:"payment",amount:Do,currency:io,paymentMethodCreation:"manual",appearance:fs}),[Do,io,fs]),[ws,ks]=(0,i.useState)("loading"),[Is,Rs]=(0,i.useState)("loading"),[_s,Es]=(0,i.useState)("loading"),[Sc,gi]=(0,i.useState)(!1),[Ts,hi]=(0,i.useState)("loading"),[bi,wc]=(0,i.useState)();(0,i.useEffect)(()=>{wc(Qo())},[]);let Ca=bi?.inAppBrowser,Sa=bi?Fa(bi,ut?.approvalPresentation,Re??(Et?"subscription":"order")):"popup",As=T&&(kr||(Oo?Cs:Ca===!1)),xs=Y&&Cc,No=(!Ct||!!Ge.waitForDataAttachment)&&As&&kr,Ms=Ts==="retrying"||Ts==="exhausted",zo=null;Y&&(bt?zo=ys:co==="redirect"&&(zo=Un));let Bs=(0,i.useMemo)(()=>({...$e,presentationMode:co}),[$e,co]),Uo=!Ct&&As&&!!zo&&(!kr||Ms),po=!Ct&&xs&&!!Un,qo=!Ct&&Y&&ha&&va.length>0&&!!Un,kc=No&&!Ms?Sc:Uo&&Wl(ws),Ic=po&&Wl(Is),Rc=qo&&_s!=="load_error",Fs=s=>s==="loading"||s==="ready",Ds=No||Uo&&Fs(ws)||po&&Fs(Is)||qo&&_s!=="load_error",wa=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(!wa.current){if(!Y&&!T){wa.current=!0;let s=new y.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(s),we(s.message)}else if(!Y&&T&&!kr){wa.current=!0;let s=new y.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(s),we(s.message)}else if(Ca!==void 0&&!Ct&&!ht&&!Ds){wa.current=!0;let s=new y.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});d?.(s),we(s.message)}}},[Y,T,kr,Ca,Ct,ht,Ds,d,we]);let Os=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(Os.current||!ha)return;let s=[];he!==!0&&s.push("showApplePay"),De!==!0&&s.push("showGooglePay"),s.length!==0&&(Os.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.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.`))},[ha,he,De]);let Ls=(0,i.useCallback)((s,S)=>Ge.applyInlineSessionPatch?Ge.applyInlineSessionPatch(s).then(K=>({error:null,sessionId:K.sessionId||e,nonce:K.session?.clientSecret||t})).catch(K=>{let Te=Vl(S,K);return we(Te.message),d?.(Te),{error:Te,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ge.applyInlineSessionPatch,t,d,e,we]),cr=(0,i.useCallback)(async s=>{if(s!=="card"&&Ct&&await Ge.waitForDataAttachment?.(),!Ie)return{proceed:!0};try{let S=await Ie({method:s,sessionId:e||void 0,createSession:Ge.inlineSessionDraft});if(S===!1)return{proceed:!1};if(S&&typeof S=="object"){S.account&&mn(Te=>({...Te??{},...S.account}));let K=await Ls(S,s);return K.error?{proceed:!1,accountPatch:S.account}:{proceed:!0,accountPatch:S.account,sessionId:K.sessionId,nonce:K.nonce}}return{proceed:!0}}catch(S){let K=Vl(s,S);return we(K.message),d?.(K),{proceed:!1}}},[Ls,Ge.inlineSessionDraft,Ge.waitForDataAttachment,Ct,Ie,d,e,we]),Ns=(0,i.useCallback)(async(s,S)=>{if(le.current)return;le.current=!0,Ue(!0),B("processing"),we(null);let K=S?.sessionId??e,Te=S?.nonce??t,ee=Ai(_,S?.accountPatch),Se=S?.completionPaymentMethodId??Xo(s),Xt=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,dr=eu(s),tt=S?.presentationMode?Ya(dn(Me),{...$e,presentationMode:S.presentationMode}):void 0,mt=()=>{$?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:dr}),tt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...yr,requestCategory:"process_payment"})};try{let Ut=await new fr.PaymentAPI(oe).processPayment(ee.userId??"",{sessionId:K,nonce:Te,paymentMethodCategory:S?.paymentMethodCategory??nu(s),tokenizedData:Xt,accountData:{...S?.accountPatch,userId:ee.userId??"",email:ee.email??"",firstName:ee.firstName||void 0,lastName:ee.lastName||void 0,...Q?(()=>{let Ot=Zt.current,Ir=(0,y.isAVSFieldVisible)(Q.state,Ot),qn=(0,y.isAVSFieldVisible)(Q.address_line_1,Ot),Rr=(0,y.isAVSFieldVisible)(Q.postal_code,Ot),Qr=qn&&!Ir&&Rr?(0,y.getStateFromPostalCode)(Ot,(wt.current??"").trim()):null,Ko=Ir?Ht.current:Qr;return{country:Ot,...Rr&&wt.current?{zip:wt.current}:{},...(0,y.isAVSFieldVisible)(Q.city,Ot)&&Qt.current?{city:Qt.current}:{},...Ko?{state:Ko}:{},...qn&&yn.current?{addressLine1:yn.current}:{},...(0,y.isAVSFieldVisible)(Q.address_line_2,Ot)&&Dt.current?{addressLine2:Dt.current}:{}}})():{}},chv:M,avsCheck:Ne??!1,checkoutType:ct,checkoutLayout:at,avsConfig:Q?{country:(0,y.isAVSFieldVisible)(Q.country,Zt.current),postal_code:(0,y.isAVSFieldVisible)(Q.postal_code,Zt.current),address_line_1:(0,y.isAVSFieldVisible)(Q.address_line_1,Zt.current),address_line_2:(0,y.isAVSFieldVisible)(Q.address_line_2,Zt.current),city:(0,y.isAVSFieldVisible)(Q.city,Zt.current),state:(0,y.isAVSFieldVisible)(Q.state,Zt.current)}:void 0});if(Ut.ok){let Ot=Ut.status===204?null:await Ut.json().catch(()=>null),Ir=(0,y.isAuthorizationOnlySession)(q)||Ot?.status==="authorized";Eo(K),tt?.terminal({outcome:"payment_succeeded",...yr}),B("success"),g(null),await new Promise(Qr=>setTimeout(Qr,600));let qn;typeof Ot?.paymentId=="string"?qn=Ot.paymentId:q?.paymentId&&(qn=q.paymentId);let Rr;typeof Ot?.authorizationExpiresAt=="string"?Rr=Ot.authorizationExpiresAt:q?.authorizationExpiresAt&&(Rr=q.authorizationExpiresAt),l?.(Ir?{status:"authorized",...qn===void 0?{}:{paymentId:qn},sessionId:typeof Ot?.sessionId=="string"?Ot.sessionId:K,...Rr===void 0?{}:{authorizationExpiresAt:Rr},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Se,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Se,checkoutMethod:s.isPaypal?"paypal":"card"});return}let ln=await Ut.json().catch(()=>null);if(ln?.type==="paypal_redirect_required"){let Ot=ln.threeDSecureToken,Ir=ln.paymentMethodId||s.id||"";if(!Me||!Ot){B("error"),we("PayPal authorization required but no token provided.");return}try{let qn=bt?.getRawProvider();if(!qn){we("PayPal is not available.");return}let Rr={return_url:window.location.href};Ir&&(Rr.payment_method=Ir);let{error:Qr}=await qn.confirmPayment({clientSecret:Ot,confirmParams:Rr,redirect:"if_required"});if(Qr){B("error");let Ko=Qr.message??"PayPal payment failed.";we(Ko),wr("paypal",Ko,{code:Qr.code})}}catch(qn){B("error"),we(qn instanceof Error?qn.message:"PayPal authorization failed.")}return}if(ln?.type==="paypal_direct_required"){let Ot=ln.orderId;if(!Ot){B("error"),we("PayPal retry required but no order id provided.");return}let Ir=D.current?.attempts??0;if(Ir>=2){B("error"),we("PayPal payment could not be completed after multiple attempts."),wr("paypal","paypal_direct_required retry limit exceeded");return}gi(!1),hi("loading"),g({orderId:Ot,attempts:Ir+1}),B(null);return}(0,y.classifyPaymentRejection)(Ut.status,ln)?tt?.terminal({outcome:"payment_declined",...yr,terminalReason:"provider_declined"}):mt(),B("error");let ur=ln?.message??"Payment failed. Please try again.";we(ur),wr(s.isPaypal?"paypal":"card",ur,{code:ln?.code??ln?.gatewayErrorCode,declineCode:ln?.declineCode??ln?.gatewayDeclineReason}),await new Promise(Ot=>setTimeout(Ot,400))}catch(kt){Zl(kt)||mt(),B("error"),we(kt instanceof Error?kt.message:"An unexpected error occurred"),await new Promise(Ut=>setTimeout(Ut,400))}finally{Ue(!1),B(null),le.current=!1}},[oe,e,t,_,Q,Ne,ct,at,M,Me,bt,q,l,we,wr,$,$e]),xn=(0,i.useCallback)((s,S)=>{p?p(s):Ns(s,S)},[p,Ns]),$o=`${Yl}:${e}`;(0,i.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem($o);if(!s)return;let S;try{S=JSON.parse(s)}catch{$t($o);return}if(!S||typeof S.createdAt!="number"||Date.now()-S.createdAt<0||Date.now()-S.createdAt>Xl||typeof S.paymentMethodId!="string"||typeof S.providerIntentId!="string"||typeof S.paymentMethodType!="string"||S.sessionId!==e||!t||S.nonce!==t||!uo.includes(S.paymentMethodType)){$t($o);return}$t($o),xn({id:S.paymentMethodId,type:"card",threeDSecureActionResultTokenId:S.providerIntentId,gateway:"stripe",paymentMethodType:S.paymentMethodType},{...S.accountPatch?{accountPatch:S.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[xn,t,e,$o,uo]);let zs=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(typeof window>"u"||zs.current)return;let[s,S,K]=rs();if(!s||!S||ba.current||!Me)return;let Te=Me.getRawProvider();if(!Te)return;let ee=mt=>{let kt=localStorage.getItem(mt);if(!kt)return null;try{return JSON.parse(kt)}catch{return $t(mt),null}},Se=ee(Tr)??ee(Ll),Xt;if(Se?.clientSecret){if(Se.clientSecret!==S)return;Xt={...Se.accountPatch?{accountPatch:Se.accountPatch}:{},...Se.sessionId?{sessionId:Se.sessionId}:{},...Se.nonce?{nonce:Se.nonce}:{}}}else if(Se?.sessionId&&Se.sessionId!==e)return;zs.current=!0,$t(Tr),$t(Ll),window.history.replaceState({},"",os());let dr=Se?.paymentMethodType??Se?.tokenType??"card",tt="card";(async()=>{if(K==="failed"){let ur="Payment was declined. Please try again.";we(ur),wr(tt,ur);return}let{paymentIntent:mt,error:kt}=await Te.retrievePaymentIntent(S);if(kt){let ur=kt.message??"Failed to retrieve payment status.";we(ur),wr(tt,ur,{code:kt.code});return}let Ut=mt?.status,ln=Yo(Ut);if(!mt||!ln){let ur=Ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";we(ur),wr(tt,ur,{code:Ut??"missing_payment_intent"});return}let Ys=typeof mt.payment_method=="string"?mt.payment_method:mt.payment_method?.id;xn({id:Ys??Se?.paymentMethodId??Se?.tokenId??mt.id,type:"card",threeDSecureActionResultTokenId:mt.id,gateway:Se?.gateway??"stripe",paymentMethodType:dr},Xt)})()},[e,xn,Me,we,wr]);let Pi=(0,i.useCallback)(s=>{s.preventDefault()},[]);if(!(ie||Me!==null))return(0,c.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let jo=re==="buttons",Mn=Pe?.variables,_c=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),vi=Mn?.colorBackground,Ec=vi&&!_c.has(vi)?vi:void 0,Vo=E.cardInputBorder??(jo?"#e5e7eb":"#A4A4FF"),Us=Mn?.colorDanger??"#dc2626",zt=s=>Br[s]&&(Pr[s]||En),ka=ao&&(Fr||En),Jn=s=>s?Us:Vo,Ia=(hn.malformed||hn.empty)&&(br||En),Tc=Jn(Ia),Ci=E.cardFormContainer?.backgroundColor??Ec??(jo?"white":"#EDEDFF"),mo=E.cardInputBackground??Mn?.colorBackground??"white",Si=go(ke),qs=go(Le),yo=E.nameInput,$s=E.cardInputFontSize??su(yo?.fontSize)??Mn?.fontSizeBase??"16px",js=typeof yo?.fontFamily=="string"?yo.fontFamily:Mn?.fontFamily??"Poppins, sans-serif",Vs=Ki(yo?.fontWeight)??400,Ac=E.cardInputColor??(typeof yo?.color=="string"?yo.color:void 0)??Mn?.colorText??"#262833",xc=E.cardInputPlaceholderColor??"#9ca3af",Yt=Mn?.borderRadius??"8px",Jr=Mn?.borderRadius??E.cardButton?.borderRadius??Yt,Zr=Mn?.colorPrimary??"#4A49FF",Mc=Mn?.colorPrimaryHover??Bo(Zr,.12),wi=Mn?.colorText??"#262833",ki={fontSize:$s,fontFamily:js,fontWeight:Vs,color:Ac,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Wo={marginTop:"0.375rem",...ki,fontSize:"0.75rem",lineHeight:1.4,color:Us},Bc={"--flopay-input-placeholder-color":xc,"--flopay-input-font-size":$s,"--flopay-input-font-family":js,"--flopay-input-font-weight":String(Vs)},Ho=E.cardFormContainer??{},Ii=Ho.padding??(jo?"0":"1rem"),Ri=Ho.borderRadius??Yt,Fc=Gt&&Xn?(0,c.jsx)(Mo,{capture:Gt,html:Xn.html,messageToken:Xn.messageToken,expectedOrigin:Xn.expectedOrigin,theme:At,submitLabel:w,onReady:()=>{if(!Sn&&!Q||typeof document>"u")return;let s=()=>{let K=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(K){rr.current=!0;try{K.focus()}finally{rr.current=!1}}};Yn.current||s()},onError:s=>we(s),onValidation:s=>{let S=pt.current;(S==="idle"||S==="validation-window")&&(we(s),s&&pt.current==="validation-window"&&(Be.current&&(clearTimeout(Be.current),Be.current=null),pt.current="idle",B(null)))}}):(0,c.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Ws=(0,c.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&ar()},style:{backgroundColor:Ci,borderRadius:Ri,...Ho,padding:Ii,...Bc,display:"flex",flexDirection:"column"},children:[(0,c.jsx)("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${nt.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),$o&&zn&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ie?-2:0},children:[(0,c.jsxs)("button",{type:"button",onClick:Lr,style:{display:"inline-flex",alignItems:"center",gap:Si?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:E.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...E.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...E.backButtonIcon},children:(0,c.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(ho,{content:Re})]}),Us?(0,c.jsx)("div",{style:{flex:1}}):(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:E.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...E.title},children:(0,c.jsx)(Ko,{content:Oe})})]}),!$o&&!Us&&(0,c.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:wi,order:ie?-3:0,...E.title},children:(0,c.jsx)(Ko,{content:Oe})}),ie&&Se&&(0,c.jsx)("div",{style:{order:-2,width:"100%"},children:Se}),ie&&Sn&&(0,c.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,c.jsx)("div",{style:{backgroundColor:po,border:`1px solid ${Jn(ka)}`,borderRadius:Kt,padding:"10px"},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:jt,onChange:s=>{At("email"),yn.current=s.target.value,on(s.target.value)},onPointerDown:()=>At("email"),onKeyDown:()=>At("email"),onBlur:()=>{rr("email")&&An(!0),oo||pi()},disabled:j,required:!0,"aria-invalid":ka||void 0,"aria-describedby":ka?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...ki}})}),ka&&(0,c.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Vo,children:Sr.empty?"Email address is required":"Enter a valid email address"})]}),Q&&(0,c.jsx)("div",{style:{order:ie?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Mt,C=(ee=!1)=>({backgroundColor:po,border:`1px solid ${Jn(ee)}`,borderRadius:Kt,marginTop:"0.5rem",padding:"10px"}),K=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ki}),Ae=(0,y.getStateOptions)(s);return(0,c.jsxs)(c.Fragment,{children:[(0,y.isAVSFieldVisible)(Q.address_line_1,s)&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("div",{style:C(Ot("line1")),children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:nn,onChange:ee=>{At("line1"),ht.current.addressLine1=!0,mn.current=ee.target.value,ve(ee.target.value)},onPointerDown:()=>At("line1"),onKeyDown:()=>At("line1"),onBlur:()=>kn("line1"),disabled:j,required:!0,"aria-invalid":Ot("line1")||void 0,"aria-describedby":Ot("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:K()})}),Ot("line1")&&(0,c.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Vo,children:"Street address is required"})]}),(0,y.isAVSFieldVisible)(Q.address_line_2,s)&&(0,c.jsx)("div",{style:C(),children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:vt,onChange:ee=>{ht.current.addressLine2=!0,Ft.current=ee.target.value,Et(ee.target.value)},disabled:j,"data-testid":"flopay-address-line2",style:K()})}),((0,y.isAVSFieldVisible)(Q.city,s)||(0,y.isAVSFieldVisible)(Q.state,s))&&(0,c.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(Q.city,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:po,borderTop:`1px solid ${Jn(Ot("city"))}`,borderRight:`1px solid ${Jn(Ot("city"))}`,borderBottom:`1px solid ${Jn(Ot("city"))}`,borderLeft:`1px solid ${Jn(Ot("city"))}`,padding:"10px",borderTopLeftRadius:Kt,borderBottomLeftRadius:Kt,...(0,y.isAVSFieldVisible)(Q.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Kt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:vn,onChange:ee=>{At("city"),ht.current.city=!0,Jt.current=ee.target.value,Bt(ee.target.value)},onPointerDown:()=>At("city"),onKeyDown:()=>At("city"),onBlur:()=>kn("city"),disabled:j,required:!0,"aria-invalid":Ot("city")||void 0,"aria-describedby":Ot("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:K()})}),(0,y.isAVSFieldVisible)(Q.state,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:po,borderTop:`1px solid ${Jn(Ot("state"))}`,borderRight:`1px solid ${Jn(Ot("state"))}`,borderBottom:`1px solid ${Jn(Ot("state"))}`,borderLeft:`1px solid ${Jn(Ot("state"))}`,padding:"10px",borderTopRightRadius:Kt,borderBottomRightRadius:Kt,...(0,y.isAVSFieldVisible)(Q.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Jn(Ot("state")||Ot("city"))}`}:{borderRadius:Kt}},children:Ae?(0,c.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Vn,onChange:ee=>{At("state"),ht.current.state=!0,Vt.current=ee.target.value,un(ee.target.value)},onPointerDown:()=>At("state"),onKeyDown:()=>At("state"),onBlur:()=>kn("state"),disabled:j,autoComplete:"billing address-level1",required:!0,"aria-invalid":Ot("state")||void 0,"aria-describedby":Ot("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...K(),cursor:"pointer"},children:[(0,c.jsx)("option",{value:"",children:(0,y.getStateLabel)(s)}),Ae.map(ee=>(0,c.jsx)("option",{value:ee.code,children:ee.name},ee.code))]}):(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,y.getStateLabel)(s),autoComplete:"billing address-level1",value:Vn,onChange:ee=>{At("state"),ht.current.state=!0,Vt.current=ee.target.value,un(ee.target.value)},onPointerDown:()=>At("state"),onKeyDown:()=>At("state"),onBlur:()=>kn("state"),disabled:j,required:!0,"aria-invalid":Ot("state")||void 0,"aria-describedby":Ot("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:K()})})]}),Ot("city")&&(0,c.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Vo,children:"City is required"}),Ot("state")&&(0,c.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Vo,children:[(0,y.getStateLabel)(s)," is required"]}),((0,y.isAVSFieldVisible)(Q.country,s)||(0,y.isAVSFieldVisible)(Q.postal_code,s))&&(0,c.jsxs)("div",{style:{display:"flex",flexDirection:ae==="column"?"column":"row",gap:ae==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(Q.country,s)&&(0,c.jsx)("div",{style:{flex:ae==="row"?1:void 0,backgroundColor:po,borderTop:`1px solid ${jo}`,borderRight:`1px solid ${jo}`,borderBottom:`1px solid ${jo}`,borderLeft:`1px solid ${jo}`,padding:"10px",...ae==="row"&&(0,y.isAVSFieldVisible)(Q.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:Kt,borderBottomLeftRadius:Kt,borderRight:"none"}:{borderRadius:Kt}},children:(0,c.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Mt,onChange:ee=>{ht.current.country=!0,Xt.current=ee.target.value,wn(ee.target.value),it?.(ee.target.value),Vt.current="",un("")},disabled:j,autoComplete:"billing country","data-testid":"flopay-country",style:{...K(),cursor:"pointer"},children:[Mt===""?(0,c.jsx)("option",{value:"",children:"Select country"}):null,y.COUNTRY_OPTIONS.map(ee=>(0,c.jsxs)("option",{value:ee.code,children:[ee.flag," ",ee.name]},ee.code))]})}),(0,y.isAVSFieldVisible)(Q.postal_code,s)&&(0,c.jsx)("div",{style:{flex:ae==="row"?1:void 0,backgroundColor:po,border:`1px solid ${Tc}`,padding:"10px",...ae==="row"&&(0,y.isAVSFieldVisible)(Q.country,s)?{borderRadius:"0",borderTopRightRadius:Kt,borderBottomRightRadius:Kt}:{borderRadius:Kt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,y.getPostalCodeLabel)(Mt),autoComplete:"billing postal-code",value:Dn,onChange:ee=>{At("zip"),ht.current.zip=!0,Ct.current=ee.target.value,Ln(ee.target.value),Fe?.(ee.target.value)},onPointerDown:()=>At("zip"),onKeyDown:()=>At("zip"),onBlur:()=>{rr("zip")&&Tn(!0)},disabled:j,required:gn.required,"aria-invalid":Ia||void 0,"aria-describedby":Ia?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:K()})})]}),Ia&&(0,c.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Vo,children:gn.empty?`${(0,y.getPostalCodeLabel)(s)} is required`:ou(s)})]})})()}),ie&&Fc,We&&(0,c.jsx)(ko,{margin:"0.75rem 0",styleOverride:E.errorBanner,children:We})]}),Ra={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},Ws=s=>W?!T||!kr?(0,c.jsx)("pre",{"data-testid":s,style:Ra,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":s,style:Ra,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${T}`,` directPaypalConfigured=${kr}`,` inAppBrowserDetected=${String(Ca)}`,` shouldRenderDirectPayPal=${Oo}`,` shouldRenderStripePayPal=${zo}`,` hasPaypalStripeInstance=${!!ms}`].join(`
39
- `)}):null,Hs=s=>W?!G||!Un?(0,c.jsx)("pre",{"data-testid":s,style:Ra,children:"FloPay/Stripe-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":s,style:Ra,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${G}`,` currency=${tn}`,` amountInCents=${Fo}`,` enabledPaymentMethods: ${JSON.stringify(de??[])}`,` enabledPaymentMethodsProvided=${Do}`,` hasEnabledMethods=${ha}`,` expressMethods: ${JSON.stringify(Pa)}`,` walletExpressMethods: ${JSON.stringify(co)}`,` paymentElementMethods: ${JSON.stringify(Lo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(va)}`,` hasStripeInstance=${!!Un}`,` shouldRenderWallets=${uo}`,` shouldRenderPaymentElement=${Uo}`].join(`
40
- `)}):null,Ks=ct==="apm-expanding"||ct==="apm-form"||ct==="apm-collapsing",yo;ct==="apm-expanding"?yo=ql:ct==="apm-collapsing"&&(yo=$l);let _a=Qt?rc(fi,Qt):null;if(ne==="buttons"){let s=ct==="buttons"||ct==="expanding"||ct==="apm-expanding",C=ct==="expanding"||ct==="card"||ct==="collapsing",K=gt===void 0?{boxSizing:"border-box",height:pa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ae;ct==="expanding"||ct==="apm-expanding"?Ae=Qd:(ct==="collapsing"||ct==="apm-collapsing")&&(Ae=Zd);let ee;return ct==="expanding"?ee=ql:ct==="collapsing"&&(ee=$l),(0,c.jsxs)("form",{onSubmit:Pi,className:k,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Ji,{}),L&&(0,c.jsx)(er,{status:L,errorMessage:We,authorized:Nn}),(0,c.jsxs)("div",{style:{display:"grid"},children:[(0,c.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!Ae?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!Ae?tu:{},...Ae?{animation:Ae,pointerEvents:"none"}:{}},children:[Ws("flopay-direct-paypal-gate-debug"),Hs("flopay-stripe-gate-debug"),Oo&&ut&&(0,c.jsxs)(c.Fragment,{children:[m&&(0,c.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,c.jsx)(Qo.Provider,{value:V,children:(0,c.jsx)(ta,{sessionId:e,nonce:t,billingApiUrl:nt,email:_.email,billingName:ze||void 0,onBuyerIdentityReady:J,clientId:ut.clientId,environment:ut.environment,currency:tn.toUpperCase(),isSubscription:lt,providerObjectType:tt,approvalPresentation:Sa==="popup"?void 0:Sa,onTokenizedBody:xn,onComplete:l,onErrorChange:Ie,onDecline:p,onTechnicalFailure:so,onButtonClick:pe,runBeforeButtonClick:lr,isProcessing:j,onLoadStateChange:gi,onInitializationStateChange:hi,session:st,existingOrderId:m?.orderId,debug:W},m?.orderId??"fresh")})]}),zo&&(0,c.jsx)(Yt.Elements,{stripe:No,options:gs,children:(0,c.jsx)(Hl,{sessionId:e,nonce:t,email:_.email,billingName:ze||void 0,onBuyerIdentityReady:J,billingApiUrl:nt,onTokenizedBody:xn,onErrorChange:Ie,isProcessing:j,onButtonClick:pe,onDecline:p,onTechnicalFailure:so,runBeforeButtonClick:lr,onLoadStateChange:ws,placeholderBorderRadius:Gr,popupCapabilityOwner:V,externalTelemetryContext:Ms,presentationMode:lo})}),uo?(0,c.jsx)(Yt.Elements,{stripe:Un,options:fs,children:(0,c.jsx)(Kl,{sessionId:e,nonce:t,email:_.email,billingName:ze||void 0,onBuyerIdentityReady:J,billingApiUrl:nt,intentKind:Ke>0?"payment":"setup",expressMethods:co,onTokenizedBody:xn,onErrorChange:Ie,onButtonClick:pe,onDecline:p,onTechnicalFailure:so,runBeforeButtonClick:lr,onLoadStateChange:Is,placeholderBorderRadius:Gr,popupCapabilityOwner:V,externalTelemetryContext:Pe})}):null,!uo&&As?(0,c.jsx)("div",{style:{height:pa,borderRadius:Gr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Uo&&(0,c.jsx)(Gl,{sessionId:e,nonce:t,email:_.email,billingName:[_.firstName,_.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:nt,paymentElementMethods:va,stripeInstance:Un,paymentElementBaseOptions:fi,onTokenizedBody:xn,onErrorChange:Ie,onButtonClick:pe,onDecline:p,runBeforeButtonClick:lr,onLoadStateChange:_s,isProcessing:j,submitButtonColor:Yr,submitButtonBorderRadius:Kt,submitButtonStyle:E.submitButton,onExpandApm:In,expandedApmMethod:Qt,themeId:$e,buttonAppearance:{backgroundColor:E.cardButton?.backgroundColor,borderColor:E.cardInputBorder,textColor:E.cardButton?.color,borderRadius:Gr}}),ie&&(0,c.jsx)("button",{type:"button",onClick:async()=>{j||!(await lr("card")).proceed||(pe?.("card"),ir())},disabled:j,style:{width:"100%",...K,...E.cardButton,...as({themeBundle:kt,resolvedPrimaryColor:Yr,resolvedBorderRadius:Kt,submitButtonStyle:E.submitButton,explicitPrimaryColor:Mn?.colorPrimary}),fontSize:E.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:j?"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:j?.6:1},onMouseEnter:Ce=>{!j&&(kt||Mn?.colorPrimary)&&(Ce.currentTarget.style.backgroundColor=Mc)},onMouseLeave:Ce=>{(kt||Mn?.colorPrimary)&&(Ce.currentTarget.style.backgroundColor=Yr)},onMouseDown:Ce=>{Ce.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ce=>{Ce.currentTarget.style.transform="scale(1)"},children:(0,c.jsx)(go,{content:gt})}),We&&ct==="buttons"&&(0,c.jsx)(ko,{margin:"0.25rem 0",styleOverride:E.errorBanner,children:We})]}),ie&&C&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...ee?{animation:ee}:{},...ct==="collapsing"?{pointerEvents:"none"}:{}},children:Vs}),G&&Ks&&Qt&&_a&&Un&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...yo?{animation:yo}:{},...ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Ci,borderRadius:Ri,...Wo,padding:Ii},children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,c.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:x,style:{display:"inline-flex",alignItems:"center",gap:Si?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:E.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...E.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...E.backButtonIcon},children:(0,c.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(ho,{content:Re})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:E.titleFontSize??"1.05rem",color:wi,paddingRight:80,...E.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(Qt)}`})]}),(0,c.jsx)(Yt.Elements,{stripe:Un,options:_a,children:(0,c.jsx)(es,{method:Qt,sessionId:e,nonce:t,email:_.email,billingName:[_.firstName,_.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:nt,onTokenizedBody:xn,onErrorChange:Ie,onDecline:p,onCancel:x,runBeforeButtonClick:lr,onButtonClick:pe,isProcessing:j,submitButtonColor:Yr,submitButtonBorderRadius:Kt,submitButtonStyle:E.submitButton,errorText:We})},Qt)]})})]})]})}return Ks&&Qt&&_a&&Un&&G?(0,c.jsxs)("form",{onSubmit:Pi,className:k,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Ji,{}),L&&(0,c.jsx)(er,{status:L,errorMessage:We,authorized:Nn}),(0,c.jsx)("div",{style:{...yo?{animation:yo}:{},...ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Ci,borderRadius:Ri,...Wo,padding:Ii},children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,c.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:x,style:{display:"inline-flex",alignItems:"center",gap:Si?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:E.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...E.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...E.backButtonIcon},children:(0,c.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(ho,{content:Re})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:E.titleFontSize??"1.05rem",color:wi,paddingRight:80,...E.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(Qt)}`})]}),(0,c.jsx)(Yt.Elements,{stripe:Un,options:_a,children:(0,c.jsx)(es,{method:Qt,sessionId:e,nonce:t,email:_.email,billingName:[_.firstName,_.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:nt,onTokenizedBody:xn,onErrorChange:Ie,onDecline:p,onCancel:x,runBeforeButtonClick:lr,onButtonClick:pe,isProcessing:j,submitButtonColor:Yr,submitButtonBorderRadius:Kt,submitButtonStyle:E.submitButton,errorText:We})},Qt)]})})]}):(0,c.jsxs)("form",{onSubmit:Pi,className:k,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Ji,{}),L&&(0,c.jsx)(er,{status:L,errorMessage:We,authorized:Nn}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ws("flopay-direct-paypal-gate-debug-default"),Hs("flopay-stripe-gate-debug-default"),Oo&&ut&&(0,c.jsxs)(c.Fragment,{children:[m&&(0,c.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,c.jsx)(Qo.Provider,{value:V,children:(0,c.jsx)(ta,{sessionId:e,nonce:t,billingApiUrl:nt,email:_.email,billingName:ze||void 0,onBuyerIdentityReady:J,clientId:ut.clientId,environment:ut.environment,currency:tn.toUpperCase(),isSubscription:lt,providerObjectType:tt,approvalPresentation:Sa==="popup"?void 0:Sa,onTokenizedBody:xn,onComplete:l,onErrorChange:Ie,onDecline:p,onTechnicalFailure:so,onButtonClick:pe,runBeforeButtonClick:lr,isProcessing:j,onLoadStateChange:gi,onInitializationStateChange:hi,session:st,existingOrderId:m?.orderId,debug:W},m?.orderId??"fresh")})]}),zo&&(0,c.jsx)(Yt.Elements,{stripe:No,options:gs,children:(0,c.jsx)(Hl,{sessionId:e,nonce:t,email:_.email,billingName:ze||void 0,onBuyerIdentityReady:J,billingApiUrl:nt,onTokenizedBody:xn,onErrorChange:Ie,isProcessing:j,onButtonClick:pe,onDecline:p,onTechnicalFailure:so,runBeforeButtonClick:lr,onLoadStateChange:ws,placeholderBorderRadius:Gr,popupCapabilityOwner:V,externalTelemetryContext:Ms,presentationMode:lo})}),uo&&(0,c.jsx)(Yt.Elements,{stripe:Un,options:fs,children:(0,c.jsx)(Kl,{sessionId:e,nonce:t,email:_.email,billingName:ze||void 0,onBuyerIdentityReady:J,billingApiUrl:nt,intentKind:Ke>0?"payment":"setup",expressMethods:co,onTokenizedBody:xn,onErrorChange:Ie,onButtonClick:pe,onDecline:p,onTechnicalFailure:so,runBeforeButtonClick:lr,onLoadStateChange:Is,placeholderBorderRadius:Gr,popupCapabilityOwner:V,externalTelemetryContext:Pe})}),Uo&&(0,c.jsx)(Gl,{sessionId:e,nonce:t,email:_.email,billingName:[_.firstName,_.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:nt,paymentElementMethods:va,stripeInstance:Un,paymentElementBaseOptions:fi,onTokenizedBody:xn,onErrorChange:Ie,onButtonClick:pe,onDecline:p,runBeforeButtonClick:lr,onLoadStateChange:_s,isProcessing:j,submitButtonColor:Yr,submitButtonBorderRadius:Kt,submitButtonStyle:E.submitButton,themeId:$e,onExpandApm:In,expandedApmMethod:Qt,buttonAppearance:{backgroundColor:E.cardButton?.backgroundColor,borderColor:E.cardInputBorder,textColor:E.cardButton?.color,borderRadius:Gr}})]}),ie&&(Ic||kc||Rc)&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,c.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,c.jsx)("span",{children:"or pay with card"}),(0,c.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),ie&&Vs]})}var M=require("react/jsx-runtime"),Bo=44,us="flopay_checkout_saved_payment_resume",ii=new Map,oi=new Map;function oc(e,t){t.settled&&t.consumers===0&&ii.get(e)===t&&ii.delete(e)}function du(e,t,n){let r=oi.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};oi.set(e,a);let l=()=>{oi.get(e)===a&&oi.delete(e)};return o.then(l,l),o}function ya(e){return new Promise(t=>setTimeout(t,e))}function ai(e,t,n){let r=Oa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:He.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function fa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function is(e,t,n,r,o,a){let l=ai(e,t,n);l.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),fa(l)}function ac(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 ic(e,t,n,r,o){let a=(0,He.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 He.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof He.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 dc(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 ss(e){return!e||e.data.stripe?.publishableKey?!1:!!dc(e)?.clientId}var uu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function pu(e){return new qr.FloPay(uu,{publishableKey:"provider_unavailable",...e})}async function ls(e,t){let{publishableKey:n,paypalPublishableKey:r}=ji(e);return{...await Vi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function ps(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function mu(){if(!ps())return null;try{let e=window.sessionStorage.getItem(us);return e?JSON.parse(e):null}catch{return null}}function sc(e){if(ps())try{window.sessionStorage.setItem(us,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function cs(){if(ps())try{window.sessionStorage.removeItem(us)}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 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 ds(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function fu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function cc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function gu(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function si({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:d,error:p,onComplete:f,onError:h,onInstrument:b,onDecline:A,onCountryChange:k,onZipChange:S,showPayPal:v=!0,showStripe:N=!0,walletPresentation:re="auto",enabledPaymentMethods:T,showApplePay:G=!0,showGooglePay:$=!0,debug:de=!1,layout:Y,theme:fe,buttonsTheme:De,buttonsStyles:ne,cardButtonContent:$e,cardBackButtonContent:ft,cardTitleContent:te,showSecurityFooter:Le,onButtonClick:gt,onBeforeButtonClick:Re,enableAVS:Oe,cardFieldOrder:ge,cardPreFormSlot:pe,avsLayout:_e,submitLabel:je,className:ot,initialErrorMessage:R=null,initialPayPalOrderId:Se,children:ae,checkoutMode:O,confirmLabel:xe,renderConfirmButton:we,onSessionCompleted:Ue}){let Z=(0,He.resolveBillingApiUrl)(r),at=(0,P.useMemo)(()=>(0,He.resolveTheme)(fe),[fe]),it=a??at?.appearance,Fe=n?"embedded_checkout":"standard_checkout",ke=ds(ae,Y),[Ze,Pt]=(0,P.useState)(null),[Ke,tn]=(0,P.useState)(null),qt=(0,P.useRef)(null),ut=(0,P.useRef)(null),lt=(0,P.useRef)(0),[z,be]=(0,P.useState)(null),Ve=(0,P.useRef)(null),[W,Ge]=(0,P.useState)(null),wt=(0,P.useMemo)(()=>n?Ro(n):"",[n]),Ye=n?`create:${wt}`:`session:${e??""}`,u=cc(W),U=(0,P.useRef)(new Set),V=(0,P.useRef)(Ye),w=(0,P.useRef)(Ye);eo(()=>{w.current=Ye,V.current!==Ye&&(V.current=Ye,U.current.clear())},[Ye]);let X=(0,P.useCallback)(x=>{if(w.current===Ye){if(Fi.has(x.name)){if(U.current.has(x.name))return;U.current.add(x.name)}dt(()=>b?.(x))}},[Ye,b]),qe=wo(X,Ye),Pe=(0,P.useRef)(!1),st=(0,P.useCallback)(x=>{if(Pe.current)return;let L=x.gateway||!u?x:{...x,gateway:u};X(L)},[X,u]);(0,P.useEffect)(()=>{qe({class:"lifecycle",name:"checkout.mount"})},[qe]);let[tt,me]=(0,P.useState)(e??""),pt=e??tt,_t=n?"":pt,[Pn,nt]=(0,P.useState)(!0),[$t,Ne]=(0,P.useState)(null),[Fn,Rn]=(0,P.useState)(0),[Mt,wn]=(0,P.useState)("full"),[Dn,Ln]=(0,P.useState)(!1),[nn,ve]=(0,P.useState)(R),[vt,Et]=(0,P.useState)(null),[vn,Bt]=(0,P.useState)(null),[Vn,un]=(0,P.useState)(!1),[jt,on]=(0,P.useState)(void 0),[Wn,pn]=(0,P.useState)(""),[Ct,Xt]=(0,P.useState)(!1),[mn,Ft]=(0,P.useState)(!1),[Jt,Vt]=(0,P.useState)(!1),yn=(0,P.useRef)(null),ht=(0,P.useRef)(0),Q=(0,P.useRef)(void 0),[On,Nn]=(0,P.useState)("loading"),[hr,Cn]=(0,P.useState)(0),an=(0,P.useRef)(!1),_n=(0,P.useRef)(!1),Ee=(0,P.useRef)(!1),bt=(0,P.useRef)(null),ie=(0,P.useRef)(null),F=(0,P.useMemo)(()=>({checkoutMode:O??Mt,layout:fu(ae,Y)}),[O,ae,Mt,Y]),Xe=(0,P.useRef)(f);Xe.current=f;let se=(0,P.useRef)(h);se.current=h;let Hn=(0,P.useRef)(A);Hn.current=A;let fn=(0,P.useCallback)(x=>Ha(bt,async L=>{try{return await x(L)}catch(B){throw L.aborted?ia(B):B}}),[]);(0,P.useEffect)(()=>()=>{bt.current?.abort(),bt.current=null},[]);let Wt=(0,P.useCallback)((x,L)=>{qt.current=x,tn(x),Ve.current=L,be(L)},[]),Kn=(0,P.useCallback)(()=>{let x=ut.current;x&&(ut.current=null,x.destroy())},[]);(0,P.useEffect)(()=>{cn(Ke)?.setCheckoutContext(F),z&&z!==Ke&&cn(z)?.setCheckoutContext(F)},[Ke,z,F]);let rt=(0,P.useRef)(Ue);rt.current=Ue;let $r=(0,P.useCallback)(x=>{Nn(x),!(x!=="exhausted"||Ee.current)&&(Ee.current=!0,se.current?.(new He.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Ht=(0,P.useCallback)(()=>{Nn("retrying"),Cn(x=>x+1)},[]);(0,P.useEffect)(()=>{Nn("loading"),Cn(0),Ee.current=!1},[pt]),(0,P.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:He.SDK_VERSION,checkout_type:Fe,checkout_layout:ke,billing_api_url:Z})},[ke,Fe,Z]);let gn=(0,P.useMemo)(()=>n?Ro(n,!0):"",[n]),Mr=(0,P.useMemo)(()=>Wn===gn?jt:void 0,[jt,Wn,gn]),Br=(0,P.useMemo)(()=>n?Ti(n,Mr):void 0,[n,Mr]),En=O??Br?.checkoutMode??"full",Zt=(0,P.useMemo)(()=>Br?{...Br,checkoutMode:En}:void 0,[Br,En]);(0,P.useEffect)(()=>{on(void 0),pn(gn),Q.current=void 0,yn.current=null,Vt(!1)},[gn]),(0,P.useEffect)(()=>{ve(R)},[R]);let br=(0,P.useCallback)((x,L,B)=>{dt(()=>{Hn.current?.(ln(x,L,B))})},[]),Tn=(0,P.useCallback)(async(x,L)=>{ve(null),Bt(null),un(!1),Et("processing");let B=L?.sessionId??x.id,le=x.clientSecret||t,Me=cc(x),mt=qt.current??Ve.current,ue=cn(mt),Be=mt?null:ai(Z,o,F),H={log:E=>{ue?ue.log(E):Be?.log(E)},error:E=>{ue?ue.error(E):Be?.error(E)},terminal:E=>{ue?ue.terminal(E):Be?.terminal(E)},performance:E=>{ue?ue.performance(E):Be?.performance(E)},now:()=>ue?.now()??Be?.now()??0,elapsed:E=>ue?.elapsed(E)??Math.max(0,(Be?.now()??E)-E)},m=H.now(),g=!!(L?.initialAutoProcessingError||L?.initialAutoProcessingPending),D=!1,q,ce=()=>{D||(D=!0,g=!0,q=H.now(),H.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),H.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},J=!1,We=()=>{J||(J=!0,H.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),H.performance({stage:"processing",durationMs:H.elapsed(m),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),q!==void 0&&H.performance({stage:"recovery",durationMs:H.elapsed(q),durationMode:"machine",paymentMethodCategory:"saved"}))};H.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Pe.current=!0;try{H.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Pe.current=!1}qe({class:"lifecycle",name:"payment.processing.started",provider:Me}),g&&ce();let kt;try{let E=kl(L?.initialAutoProcessingError),he=L?.initialAutoProcessingError?.type==="3ds_required"&&!L.initialAutoProcessingError.threeDSecureToken&&L.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:L.initialAutoProcessingError.nextActionRedirectUrl}:null,Tt,ye=j=>(ce(),fn(oe=>Eo(j,{billingApiUrl:Z,sessionId:B,nonce:le,session:x,signal:oe})));if(he)Tt=await ye(he);else if(E)ce(),E.type==="paypal_redirect_required"&&ie.current?.publishableKey&&sc({sessionId:B,publishableKey:ie.current.publishableKey,paypalPublishableKey:ie.current.paypalPublishableKey}),Tt=await fn(j=>Ga(E,{flopay:qt.current,paypalFlopay:Ve.current,attempt3DS:L?.attempt3DS,billingApiUrl:Z,sessionId:B,session:x,telemetry:!1,signal:j})),E.type==="paypal_redirect_required"&&cs();else if(L?.initialAutoProcessingPending){let j=L.initialAutoProcessingPending,oe=new qr.PaymentAPI(Z,{telemetry:!1}),_=await fn(Te=>oe.waitForCheckoutSessionCompletion(j.sessionId,{initialDelayMs:j.retryAfterMs,nonce:le,statusUrl:j.statusUrl,signal:Te})),ze=Zr(_,x),It=_.autoProcessingError?.type==="3ds_required"&&_.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:_.autoProcessingError.nextActionRedirectUrl}:null;if(It)Tt=await ye(It);else{if(!Hr(ze))throw Po(ze);Tt=Or(ze,B)}}else{if(L?.initialAutoProcessingError)throw Er(L.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:L.initialAutoProcessingError.checkoutMethod});if(L?.fromCreateSession)return L?.fallbackToFull&&(wn("full"),lc("full")),!1;{let j=await To({billingApiUrl:Z,sessionId:B,session:x,nonce:le,telemetry:!1});j.type==="success"?Tt=j.result:j.type==="next_action_required"?Tt=await ye(j):(ce(),j.type==="paypal_redirect_required"&&ie.current?.publishableKey&&sc({sessionId:B,publishableKey:ie.current.publishableKey,paypalPublishableKey:ie.current.paypalPublishableKey}),Tt=await fn(oe=>Ga(j,{flopay:qt.current,paypalFlopay:Ve.current,attempt3DS:L?.attempt3DS,billingApiUrl:Z,sessionId:B,session:x,telemetry:!1,signal:oe})),j.type==="paypal_redirect_required"&&cs())}}B&&_o(B),We(),g&&(H.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),H.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),H.terminal({outcome:Tt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),un(Tt.status==="authorized"),Et("success"),await ya(600),kt=()=>Xe.current?.(Tt)}catch(E){let he=sa(E);if(he.code==="three_ds_aborted")return!1;let Tt=he.checkoutMethod??aa;ve(he.message),Bt(he.message),un(!1),L?.fallbackToFull&&(H.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),wn("full"),lc("full")),We();let ye=he.statusCode===void 0?void 0:(0,He.telemetryStatusClass)(he.statusCode,"unknown"),j=ye==="4xx"?{requestCategory:"process_payment",statusClass:ye}:{},oe=ye===void 0||ye==="4xx";if(oe&&(he.telemetryOutcome==="payment_declined"||!!(he.declineCode||he.code?.toLowerCase().includes("declin"))))H.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...j});else if(oe&&(he.telemetryOutcome==="validation_rejected"||he.type==="validation_error"))H.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...j});else{let It=(0,He.classifyTelemetryFailure)(E,g?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Te=he.telemetryRequestCategory??"process_payment";Pe.current=!0;try{H.error({...It,...he.telemetryFailureCategory?{failureCategory:he.telemetryFailureCategory}:{},stage:g?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Te})}finally{Pe.current=!1}qe({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Te,provider:Me})}return dt(()=>se.current?.(he)),br(Tt,he,{code:he.code,declineCode:he.declineCode}),Et("error"),await Promise.allSettled([ya(400),L?.ensureProvidersReady?L.ensureProvidersReady():Promise.resolve()]),g&&(H.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),H.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{We(),Be&&fa(Be),Et(null),Bt(null)}return dt(kt),!0},[br,qe,t,Z,fn,o,F]);(0,P.useEffect)(()=>{if(typeof window>"u"||_n.current)return;let x=new URLSearchParams(window.location.search),L=x.get("payment_intent_client_secret");if(!L)return;let B=mu();B&&(_n.current=!0,(async()=>{let le,Me=0;ve(null),Bt(null),Et("processing"),Ln(!0);try{if(x.get("redirect_status")==="failed")throw Object.assign(new He.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:mt,paypalFlopay:ue}=await Vi({publishableKey:B.publishableKey,paypalPublishableKey:B.paypalPublishableKey,billingApiUrl:Z,locale:l,telemetry:o});le=cn(ue??mt),le?.setCheckoutContext(F),Me=le?.now()??0,le?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),le?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Be=(ue??mt)?.getRawProvider();if(!Be)throw Object.assign(new He.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:H,error:m}=await Be.retrievePaymentIntent(L);if(m)throw Object.assign(new He.FloPayError(m.message??"Failed to retrieve PayPal payment status.","api_error",{code:m.code}),{checkoutMethod:"paypal"});let g=rl(H?.status);if(!H||g==="failed")throw Object.assign(new He.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let D=typeof H.payment_method=="string"?H.payment_method:H.payment_method?.id,q=g;if(B.sessionId){let We=(await new qr.PaymentAPI(Z,{telemetry:!1}).getUnifiedCheckoutSession(B.sessionId)).data.session;if(We&&We.status!=="complete"){let kt=await To({billingApiUrl:Z,sessionId:B.sessionId,session:We,telemetry:!1,tokenizedData:{id:D??H.id,type:"card",threeDSecureActionResultTokenId:H.id,isPaypal:!0}});if(kt.type!=="success")throw Object.assign(new He.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});q=kt.result.status}}B.sessionId&&_o(B.sessionId),le?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),le?.performance({stage:"redirect_resume",durationMs:le.elapsed(Me),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),le?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Et("success"),await ya(600),dt(()=>Xe.current?.({status:q,paymentIntentId:H.id,paymentMethodId:D,checkoutMethod:"paypal"}))}catch(mt){let ue=sa(mt),Be=ue.checkoutMethod??"paypal",H=!!(ue.declineCode||ue.code?.toLowerCase().includes("declin"));if(le)le.performance({stage:"redirect_resume",durationMs:le.elapsed(Me),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),H?le.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):le.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(H){let m=ai(Z,o,F);m.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),fa(m)}else is(Z,o,F,"REDIRECT_RESUME_FAILED","redirect_resume");ve(ue.message),Bt(ue.message),dt(()=>se.current?.(ue)),br(Be,ue,{code:ue.code,declineCode:ue.declineCode}),Et("error"),await ya(400)}finally{cs(),yu(),Et(null),Bt(null),Ln(!1)}})())},[br,l,Z,o,F]);let Fr=(0,P.useRef)(null),An=(0,P.useMemo)(()=>Zt?Ro(Zt):"",[Zt]),Pr=(0,P.useRef)(Zt);Pr.current=Zt,(0,P.useEffect)(()=>{me(e??"")},[e]),(0,P.useEffect)(()=>{an.current=!1,ve(R),Bt(null),un(!1),Et(null)},[An,R,e]);async function vr(x,L,B){let le=ai(Z,o,F),Me=new qr.PaymentAPI(Z,{telemetry:!1}),mt=!1;try{let ue=x.idempotencyKey===void 0?void 0:(0,He.resolveIdempotencyKey)(x.idempotencyKey),Be=Oi(L,B),H=Ni(L,B);Be?.canonicalIdentity===B&&H&&H.canonicalIdentity===void 0&&(Va(L,B,H.idempotencyKey),H={...H,canonicalIdentity:B});let m=ue??(H?.canonicalIdentity===B?H.idempotencyKey:void 0),g,D=!1;le.log({name:Be?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let q=Be?.sid??null,ce=null,J,We,kt=!1;if(q)try{ce=await Me.getUnifiedCheckoutSession(q,Be?.nonce),Be&&Be.canonicalIdentity===void 0&&(Pl(ce.data.session,x)?(ja(L,B,q,Be.nonce??ce.data.session?.clientSecret),H&&H.canonicalIdentity===void 0&&(Va(L,B,H.idempotencyKey),m??(m=H.idempotencyKey))):($a(L,B),H=null,m=ue,q=null,ce=null));let he=ce?.data.session?.status,Tt=ce?.data.session,ye=Tt?.clientSecret||Be?.nonce;if(q&&Tt?.buyerIdentified===!1&&ye&&(We=bo(Me,q,ye,x.account)),q&&ce&&he==="complete"){if(zi(q))return{sid:q,result:ce};$a(L,B),q=null,ce=null,D=!0}}catch{le.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Be?.canonicalIdentity===void 0?($a(L,B),m=ue):qa(L,B),q=null}if(!q){!ue&&(D||!m)&&(m=(0,He.resolveIdempotencyKey)(),g=m),m&&Va(L,B,m);let he=le.now(),Tt=0;le.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ye={...x,idempotencyKey:m,avsCheck:!!Oe,avsConfig:typeof Oe=="object"?Oe:void 0,checkoutType:"embedded_checkout",checkoutLayout:ds(ae,Y)};Object.defineProperty(ye,qr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:_=>{Tt=Math.max(Tt,_)}}});let j=()=>{ac(le,"session_create",he,Tt)},oe=_=>{ic(le,_,"session_create",he,Tt)&&qe({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,He.isDetachedSessionEligible)(ye)){let _=await Me.createDetachedSession(ye);_.claimed.catch(()=>{}),ce=_.shell,q=_.sessionId,We=_.claim;let ze=le.now();le.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),J=_.claimed.then(It=>{let Te=It.data.session?.id??_.sessionId;return Te&&ja(L,B,Te,It.data.session?.clientSecret??_.nonce),ac(le,"session_claim",ze),j(),It},It=>{throw qa(L,B),ic(le,It,"session_claim",ze,0)&&qe({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),It}).finally(()=>fa(le)),J.catch(()=>{}),mt=!0,le.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),le.performance({stage:"session_shell",durationMs:le.now()-he,durationMode:"machine",requestCategory:"session_create",attempt:Tt,statusClass:"2xx",paymentMethodCategory:"card"})}else ce=await Me.createAndFetchSession(ye),j()}catch(_){throw oe(_),_}q=ce.data.session?.id??q??"",q&&!J&&ja(L,B,q,ce.data.session?.clientSecret)}let E=ce?.data.session;return!We&&q&&E?.buyerIdentified===!1&&E.clientSecret&&(We=bo(Me,q,E.clientSecret,x.account)),{sid:q??"",result:ce,sdkGeneratedIdempotencyKey:g,...J?{claimed:J}:{},...We?{claim:We}:{},...kt?{claimRequiresIdentity:!0}:{}}}finally{mt||fa(le)}}let nr=(0,P.useRef)(vr);eo(()=>{nr.current=vr},[vr]);let Gn=(0,P.useCallback)(async(x,L)=>{let B=Pr.current;if(!B)throw new He.FloPayError("createSession is required to bootstrap checkout.","validation_error");let le=Ti(B,x),Me=Ro(le),mt=bl(le),ue=ii.get(Me);if(!ue){let m={canonicalIdentity:Me,promise:nr.current(le,mt,Me),consumers:0,settled:!1};ue=m,ii.set(Me,m);let g=()=>{m.settled=!0,oc(Me,m)};m.promise.then(g,g)}ue.consumers+=1;let Be=!1,H=()=>{Be||(Be=!0,ue.consumers-=1,oc(Me,ue))};L?.(H);try{let m=await ue.promise;Fr.current=Me,x&&(pn(gn),on(E=>el(E,x)));let{sid:g,result:D,claimed:q,claim:ce,claimRequiresIdentity:J}=m;if(Q.current=ce,Vt(J===!0),Pt(D),D.data.session&&Ge(D.data.session),g&&me(g),q){ht.current+=1;let E=ht.current;yn.current=q,Ft(!0),q.then(he=>{ht.current===E&&(yn.current===q&&(yn.current=null),Pt(he),he.data.session&&Ge(he.data.session),Ft(!1),Vt(!1))},he=>{ht.current===E&&(yn.current===q&&(yn.current=null),Ft(!1),Vt(!1),Ne(he instanceof He.FloPayError?he:new He.FloPayError(he instanceof Error?he.message:"Failed to create session","api_error")))})}else ht.current+=1,yn.current=null,Ft(!1),Vt(!1);let{flopay:We,paypalFlopay:kt}=await ls(D,{billingApiUrl:Z,locale:l,telemetry:o});return Wt(We,kt),nt(!1),m}catch(m){throw Fr.current===Me&&(Fr.current=null),m}finally{L||H()}},[gn,Wt,l,Z,o]),Yn=(0,P.useRef)(Tn);Yn.current=Tn;let At=(0,P.useRef)(Gn);At.current=Gn;let rr=(0,P.useCallback)(async x=>{if(!gu(x)||Ct)return{sessionId:tt,session:W};Xt(!0);try{let L=await Gn(x);return{sessionId:L.sid,session:L.result.data.session??null}}finally{Xt(!1)}},[Gn,Ct,tt,W]),kn=(0,P.useCallback)(async x=>{let L=Q.current;if(!L)return;let B=ht.current,le=await L(x);ht.current===B&&(Pt(le),le.data.session&&Ge(le.data.session))},[]),Xn=(0,P.useCallback)(async()=>{await yn.current},[]),Cr=(0,P.useCallback)(async()=>(await Xn(),{proceed:!0}),[Xn]);(0,P.useEffect)(()=>{let x=!1,L,B=++lt.current;Kn(),Ne(null),Rn(0);let le=()=>{x=!0,lt.current===B&&(lt.current+=1,Kn())},Me=Pr.current;if(An&&Me)return wn(En),nt(!1),Fr.current===An?le:(Ge(tl(Me,O)),(async()=>{let Be=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),H=En==="auto"&&!an.current&&!Be;H&&(ve(null),Bt(null),Et("processing"));try{let m=await At.current(void 0,ce=>{L=ce}),g=m.result.data.session??null;ie.current=ji(m.result);let D=ss(m.result),q=zi(m.sid||g?.id);if(!x&&H&&g&&!D&&!q){an.current=!0,await du(An,m.sdkGeneratedIdempotencyKey,()=>Yn.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}!x&&H&&((D||q)&&(an.current=!0),Et(null),Bt(null))}catch(m){if(x)return;let g=Aa(m);if(H&&g==="session_auto_completed"){an.current=!0,Et("success"),await ya(600),x||(dt(()=>{Xe.current?.({status:"succeeded"})}),Et(null),Bt(null));return}H&&(Et(null),Bt(null));let D=m instanceof He.FloPayError?m:new He.FloPayError(m instanceof Error?m.message:"Failed to create session","api_error");Ne(D)}finally{L?.(),L=void 0}})(),()=>{le(),L?.()});nt(!0);async function mt(){let Be=!1,H=null;try{let m=new qr.PaymentAPI(Z,{telemetry:!1}),g=await m.getUnifiedCheckoutSession(pt,t);if(H=g,x)return;Pt(g);let D=g.data.session??null;if(Ge(D),!D)throw new He.FloPayError("No session data returned","api_error");let q=D.checkoutMode;if(q==="setup")throw new He.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(D.status==="authorized"){nt(!1),dt(()=>{Xe.current?.(Or(D,pt)),rt.current?.(D.successUrl??"")});return}if(D.status==="complete"){nt(!1),dt(()=>{rt.current?.(D.successUrl??"")});return}if(D.status==="expired")throw Ta(D);Be=!0;let ce=O??q??"full";wn(ce),ht.current+=1;let J=D.clientSecret||t;Q.current=D.buyerIdentified===!1&&J?bo(m,pt,J,{...D.customer?.id?{userId:D.customer.id}:{}}):void 0,Ft(!1),Vt(!1);let We=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),kt=ss(g);if(ce==="auto"&&!an.current&&!We&&!kt){an.current=!0;let E=ue(g);try{if(await Yn.current(D,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>E,sessionId:pt||D.id}),x)return;await E,x||nt(!1);return}catch{if(x)return;await E,x||nt(!1);return}}await ue(g),x||nt(!1)}catch(m){if(x)return;let g=Qs(m,Be);if(Be&&qe({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),g){let{errorCode:q,stage:ce,...J}=g;is(Z,o,F,q,ce,J)}if(g?.stage==="provider_load"&&(O??H?.data.session?.checkoutMode??"full")==="full"&&Zs(H,v,N)){let q=pu({billingApiUrl:Z,locale:l,telemetry:o});ut.current=q,Wt(q,null),Rn(1),nt(!1);return}let D=m instanceof He.FloPayError&&g?.stage!=="provider_load"?m:Js();D!==m&&dt(()=>se.current?.(D)),Ne(D),nt(!1)}}async function ue(Be){let{flopay:H,paypalFlopay:m,...g}=await ls(Be,{billingApiUrl:Z,locale:l,telemetry:o});ie.current={publishableKey:g.publishableKey,paypalPublishableKey:g.paypalPublishableKey},Wt(H,m),Rn(0)}return mt(),le},[O,An,En,_t,t,v,N]);let ct=(0,P.useCallback)(async()=>{if(!Ze||Fn!==1)return;let x=lt.current;Rn(2);try{let{flopay:L,paypalFlopay:B}=await ls(Ze,{billingApiUrl:Z,locale:l,telemetry:o});if(lt.current!==x)return;Kn(),Wt(L,B),Rn(0)}catch(L){if(lt.current!==x)return;let{errorCode:B,stage:le,...Me}=_i(L);is(Z,o,F,B,le,Me)}},[Kn,Wt,l,Fn,Z,o,F,Ze]),rn=!!(pt&&(W?.clientSecret||t)),Qt=Dn||!rn,Dr=(0,P.useCallback)(async()=>{if(!(Dn||!rn||!W)){Ln(!0),ve(null);try{await Tn(W,{attempt3DS:!0,fallbackToFull:!0,sessionId:pt||W.id})}finally{Ln(!1)}}},[pt,Dn,rn,Tn,W]),zn=dc(Ze,Se),jr=ss(Ze),or=(0,P.useMemo)(()=>{if(!(!Ze||!W||!Ze.data.stripe?.publishableKey))return{billingApiUrl:Z}},[Ze,W,Z]),ar=!!(n&&!ae&&Y==="buttons"&&Re&&En==="full"),hn=!!(pt&&(W?.vault?.html||Vr(W))),ir=(0,P.useMemo)(()=>({session:W,loading:Pn,error:$t,checkoutMode:Mt,inlineSessionDraft:Zt,applyInlineSessionPatch:ar?rr:void 0,inlineSessionPatchProcessing:Ct,claimPending:mn,claimRequiresIdentity:Jt,claimBuyerIdentity:kn,waitForDataAttachment:Xn}),[W,Pn,$t,Mt,Zt,ar,rr,Ct,mn,Jt,kn,Xn]),Lr=!!n&&Y==="buttons"&&!jr&&!hn&&(!Ke||!or),In=vt?(0,M.jsx)(er,{status:vt,errorMessage:vn,authorized:Vn}):null;if(Pn&&!hn){if(d)return(0,M.jsxs)(M.Fragment,{children:[d,In]});if(Y==="buttons"){let x=at?.buttonsLayout?.cardButton?.borderRadius??at?.appearance.variables?.borderRadius??8,L=B=>(0,M.jsx)("div",{style:{height:B,borderRadius:x,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[v&&L(Bo),N&&(G||$)&&L(Bo),N&&L(Bo),(0,M.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),In]})}return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,M.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,M.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),In]})}return $t?p?(0,M.jsx)(ur.Provider,{value:ir,children:p($t)}):(0,M.jsx)(ur.Provider,{value:ir,children:(0,M.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:$t.message})}):Lr?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(ur.Provider,{value:ir,children:(0,M.jsx)(bu,{onButtonClick:gt,showPayPal:v,showStripe:N,showApplePay:G,showGooglePay:$,theme:fe,buttonsTheme:De,buttonsStyles:ne,cardButtonContent:$e,cardBackButtonContent:ft,cardTitleContent:te})}),In]}):jr&&W&&zn?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(ur.Provider,{value:ir,children:(0,M.jsxs)("div",{className:ot,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[nn&&(0,M.jsx)(ko,{icon:!1,children:nn}),On==="retrying"&&(0,M.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),On==="exhausted"&&(0,M.jsxs)("div",{role:"alert",children:[(0,M.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,M.jsx)("button",{type:"button",onClick:Ht,children:"Retry PayPal"})]}),On!=="exhausted"&&(0,M.jsx)("div",{"aria-hidden":On==="retrying"?!0:void 0,style:On==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,M.jsx)(hl,{sessionId:pt,nonce:W.clientSecret||void 0,billingApiUrl:Z,email:W.customer?.email||Zt?.account?.email,billingName:[W.customer?.firstName,W.customer?.lastName].filter(Boolean).join(" ")||[Zt?.account?.firstName,Zt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:kn,clientId:zn.clientId,environment:zn.environment,currency:(W.currency??"usd").toUpperCase(),isSubscription:W.mode==="subscription",providerObjectType:zn.providerObjectType,approvalPresentation:zn.approvalPresentation,existingOrderId:zn.existingOrderId,onComplete:f,onErrorChange:ve,onDecline:A,onButtonClick:gt,runBeforeButtonClick:Cr,onInitializationStateChange:$r,allowAutomaticRetry:hr===0,session:W,telemetry:o,telemetryContext:F,onInstrument:st,debug:de},`${Ye}:paypal-init-${hr}`)})]})}),In]}):Mt==="confirm"?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(ur.Provider,{value:ir,children:(0,M.jsx)(ra,{flopay:Ke,paypalFlopay:z,options:or??{billingApiUrl:Z},onInstrument:st,children:(0,M.jsxs)("div",{className:ot,children:[nn&&(0,M.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:nn}),we?we({onConfirm:Dr,isProcessing:Qt}):(0,M.jsx)("button",{type:"button",onClick:Dr,disabled:Qt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Qt?"not-allowed":"pointer",opacity:Qt?.6:1},children:Dn?"Processing...":xe??"Confirm Purchase"})]})},Ye)}),In]}):(!Ke||!or)&&!(hn&&Mt==="full")?(0,M.jsx)(M.Fragment,{children:In}):(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(ur.Provider,{value:ir,children:(0,M.jsxs)(ra,{flopay:Ke,paypalFlopay:z,options:or??{billingApiUrl:Z},onInstrument:st,children:[Fn===1&&(0,M.jsx)("button",{type:"button",onClick:ct,children:"Retry payment methods"}),ae?(0,M.jsxs)(M.Fragment,{children:[nn&&(0,M.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:nn}),(0,M.jsx)(hu,{sessionId:pt,nonce:W?.clientSecret||void 0,billingApiUrl:Z,session:W,submitLabel:je,walletPresentation:re,children:ae})]}):(0,M.jsx)(ri,{sessionId:pt,nonce:W?.clientSecret||void 0,telemetry:o,email:W?.customer?.email||Zt?.account?.email,userId:W?.customer?.id||Zt?.account?.userId,firstName:W?.customer?.firstName||Zt?.account?.firstName,lastName:W?.customer?.lastName||Zt?.account?.lastName,totalAmount:W?Math.round((0,He.buildCheckoutDisplayData)(W).total*100):0,currency:W?.currency?.toLowerCase()??"usd",onComplete:f,onError:h,onDecline:A,error:nn,onErrorChange:ve,showPayPal:v,showStripe:N,walletPresentation:re,enabledPaymentMethods:Fn?[]:T??Ze?.data.stripe?.enabledPaymentMethods??W?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ze?.data.stripe?.enabledPaymentMethodCountries,showApplePay:G,showGooglePay:$,layout:Y,theme:fe,buttonsTheme:De,buttonsStyles:ne,appearance:it,cardButtonContent:$e,cardBackButtonContent:ft,cardTitleContent:te,onButtonClick:gt,onBeforeButtonClick:Re,onBuyerIdentityReady:kn,enableAVS:Oe,...ge?{cardFieldOrder:ge}:{},...pe?{cardPreFormSlot:pe}:{},avsLayout:_e,country:W?.customer?.country,city:W?.customer?.city,state:W?.customer?.state,onCountryChange:k,onZipChange:S,avsCheck:!!Oe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ds(ae,Y),className:ot,submitLabel:je,directPaypal:zn,isSubscription:W?.mode==="subscription",session:W,dataAttachmentPending:mn,dataAttachmentRequiresIdentity:Jt,debug:de})]},Ye)}),In]})}function hu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:a,children:l}){return(0,M.jsx)(M.Fragment,{children:P.default.Children.map(l,d=>{if(!P.default.isValidElement(d))return d;let p=d.props,f={};return p.sessionId||(f.sessionId=e),!p.nonce&&t&&(f.nonce=t),p.billingApiUrl||(f.billingApiUrl=n),p.submitLabel===void 0&&o!==void 0&&(f.submitLabel=o),p.walletPresentation===void 0&&(f.walletPresentation=a),r?.customer&&(p.email||(f.email=r.customer.email),p.userId||(f.userId=r.customer.id),p.firstName||(f.firstName=r.customer.firstName),p.lastName||(f.lastName=r.customer.lastName)),Object.keys(f).length===0?d:P.default.cloneElement(d,f)})})}function bu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:d,cardButtonContent:p,cardBackButtonContent:f,cardTitleContent:h}){let[b,A]=(0,P.useState)(!1),k=(0,P.useMemo)(()=>(0,He.resolveTheme)(a),[a]),S=(0,P.useMemo)(()=>{let T=k?.buttonsLayout??(0,He.resolveButtonsLayoutTheme)(l);return d?{...T,...d,cardButton:{...T.cardButton,...d.cardButton},cardFormContainer:{...T.cardFormContainer,...d.cardFormContainer},backButton:{...T.backButton,...d.backButton},backButtonIcon:{...T.backButtonIcon,...d.backButtonIcon},submitButton:{...T.submitButton,...d.submitButton},title:{...T.title,...d.title}}:T},[k,l,d]),v=k?.buttonsLayout?.cardButton?.borderRadius??k?.appearance.variables?.borderRadius??8,N=T=>(0,M.jsx)("div",{style:{height:T,borderRadius:v,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),re=p===void 0?{boxSizing:"border-box",height:Bo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let T=S.cardInputBorder??"#e5e7eb",G=S.cardInputBackground??"white",$=fo(f),de=fo(h);return(0,M.jsxs)("div",{style:{backgroundColor:S.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...S.cardFormContainer},children:[(0,M.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,M.jsxs)("button",{type:"button",onClick:()=>A(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:$?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...S.backButton},children:[(0,M.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...S.backButtonIcon},children:(0,M.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,M.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,M.jsx)(ho,{content:f})]}),de?(0,M.jsx)("div",{style:{flex:1}}):(0,M.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...S.title},children:(0,M.jsx)(Ko,{content:h})})]}),(0,M.jsx)("div",{style:{backgroundColor:G,border:`1px solid ${T}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,M.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,M.jsxs)("div",{style:{display:"flex"},children:[(0,M.jsx)("div",{style:{flex:1,backgroundColor:G,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${T}`,borderLeft:`1px solid ${T}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,M.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,M.jsx)("div",{style:{flex:1,backgroundColor:G,borderTop:"none",borderRight:`1px solid ${T}`,borderBottom:`1px solid ${T}`,borderLeft:`1px solid ${T}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,M.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,M.jsx)("div",{style:{backgroundColor:G,border:`1px solid ${T}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,M.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,M.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...S.submitButton,opacity:.5}}),(0,M.jsx)("style",{children:`
38
+ `}),jo&&zn&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ie?-2:0},children:[(0,c.jsxs)("button",{type:"button",onClick:Or,style:{display:"inline-flex",alignItems:"center",gap:Si?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:E.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...E.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...E.backButtonIcon},children:(0,c.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(bo,{content:ke})]}),qs?(0,c.jsx)("div",{style:{flex:1}}):(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:E.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...E.title},children:(0,c.jsx)(Go,{content:Le})})]}),!jo&&!qs&&(0,c.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:wi,order:ie?-3:0,...E.title},children:(0,c.jsx)(Go,{content:Le})}),ie&&He&&(0,c.jsx)("div",{style:{order:-2,width:"100%"},children:He}),ie&&Sn&&(0,c.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,c.jsx)("div",{style:{backgroundColor:mo,border:`1px solid ${Jn(ka)}`,borderRadius:Yt,padding:"10px"},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Wt,onChange:s=>{xt("email"),fn.current=s.target.value,an(s.target.value)},onPointerDown:()=>xt("email"),onKeyDown:()=>xt("email"),onBlur:()=>{or("email")&&An(!0),ao||pi()},disabled:j,required:!0,"aria-invalid":ka||void 0,"aria-describedby":ka?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...ki}})}),ka&&(0,c.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Wo,children:Sr.empty?"Email address is required":"Enter a valid email address"})]}),Q&&(0,c.jsx)("div",{style:{order:ie?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Mt,S=(ee=!1)=>({backgroundColor:mo,border:`1px solid ${Jn(ee)}`,borderRadius:Yt,marginTop:"0.5rem",padding:"10px"}),K=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ki}),Te=(0,y.getStateOptions)(s);return(0,c.jsxs)(c.Fragment,{children:[(0,y.isAVSFieldVisible)(Q.address_line_1,s)&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("div",{style:S(zt("line1")),children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:rn,onChange:ee=>{xt("line1"),gt.current.addressLine1=!0,yn.current=ee.target.value,Ce(ee.target.value)},onPointerDown:()=>xt("line1"),onKeyDown:()=>xt("line1"),onBlur:()=>kn("line1"),disabled:j,required:!0,"aria-invalid":zt("line1")||void 0,"aria-describedby":zt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:K()})}),zt("line1")&&(0,c.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Wo,children:"Street address is required"})]}),(0,y.isAVSFieldVisible)(Q.address_line_2,s)&&(0,c.jsx)("div",{style:S(),children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:St,onChange:ee=>{gt.current.addressLine2=!0,Dt.current=ee.target.value,Tt(ee.target.value)},disabled:j,"data-testid":"flopay-address-line2",style:K()})}),((0,y.isAVSFieldVisible)(Q.city,s)||(0,y.isAVSFieldVisible)(Q.state,s))&&(0,c.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(Q.city,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:mo,borderTop:`1px solid ${Jn(zt("city"))}`,borderRight:`1px solid ${Jn(zt("city"))}`,borderBottom:`1px solid ${Jn(zt("city"))}`,borderLeft:`1px solid ${Jn(zt("city"))}`,padding:"10px",borderTopLeftRadius:Yt,borderBottomLeftRadius:Yt,...(0,y.isAVSFieldVisible)(Q.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Yt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:vn,onChange:ee=>{xt("city"),gt.current.city=!0,Qt.current=ee.target.value,Bt(ee.target.value)},onPointerDown:()=>xt("city"),onKeyDown:()=>xt("city"),onBlur:()=>kn("city"),disabled:j,required:!0,"aria-invalid":zt("city")||void 0,"aria-describedby":zt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:K()})}),(0,y.isAVSFieldVisible)(Q.state,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:mo,borderTop:`1px solid ${Jn(zt("state"))}`,borderRight:`1px solid ${Jn(zt("state"))}`,borderBottom:`1px solid ${Jn(zt("state"))}`,borderLeft:`1px solid ${Jn(zt("state"))}`,padding:"10px",borderTopRightRadius:Yt,borderBottomRightRadius:Yt,...(0,y.isAVSFieldVisible)(Q.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Jn(zt("state")||zt("city"))}`}:{borderRadius:Yt}},children:Te?(0,c.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Vn,onChange:ee=>{xt("state"),gt.current.state=!0,Ht.current=ee.target.value,pn(ee.target.value)},onPointerDown:()=>xt("state"),onKeyDown:()=>xt("state"),onBlur:()=>kn("state"),disabled:j,autoComplete:"billing address-level1",required:!0,"aria-invalid":zt("state")||void 0,"aria-describedby":zt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...K(),cursor:"pointer"},children:[(0,c.jsx)("option",{value:"",children:(0,y.getStateLabel)(s)}),Te.map(ee=>(0,c.jsx)("option",{value:ee.code,children:ee.name},ee.code))]}):(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,y.getStateLabel)(s),autoComplete:"billing address-level1",value:Vn,onChange:ee=>{xt("state"),gt.current.state=!0,Ht.current=ee.target.value,pn(ee.target.value)},onPointerDown:()=>xt("state"),onKeyDown:()=>xt("state"),onBlur:()=>kn("state"),disabled:j,required:!0,"aria-invalid":zt("state")||void 0,"aria-describedby":zt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:K()})})]}),zt("city")&&(0,c.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Wo,children:"City is required"}),zt("state")&&(0,c.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Wo,children:[(0,y.getStateLabel)(s)," is required"]}),((0,y.isAVSFieldVisible)(Q.country,s)||(0,y.isAVSFieldVisible)(Q.postal_code,s))&&(0,c.jsxs)("div",{style:{display:"flex",flexDirection:ye==="column"?"column":"row",gap:ye==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(Q.country,s)&&(0,c.jsx)("div",{style:{flex:ye==="row"?1:void 0,backgroundColor:mo,borderTop:`1px solid ${Vo}`,borderRight:`1px solid ${Vo}`,borderBottom:`1px solid ${Vo}`,borderLeft:`1px solid ${Vo}`,padding:"10px",...ye==="row"&&(0,y.isAVSFieldVisible)(Q.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:Yt,borderBottomLeftRadius:Yt,borderRight:"none"}:{borderRadius:Yt}},children:(0,c.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Mt,onChange:ee=>{gt.current.country=!0,Zt.current=ee.target.value,wn(ee.target.value),lt?.(ee.target.value),Ht.current="",pn("")},disabled:j,autoComplete:"billing country","data-testid":"flopay-country",style:{...K(),cursor:"pointer"},children:[Mt===""?(0,c.jsx)("option",{value:"",children:"Select country"}):null,y.COUNTRY_OPTIONS.map(ee=>(0,c.jsxs)("option",{value:ee.code,children:[ee.flag," ",ee.name]},ee.code))]})}),(0,y.isAVSFieldVisible)(Q.postal_code,s)&&(0,c.jsx)("div",{style:{flex:ye==="row"?1:void 0,backgroundColor:mo,border:`1px solid ${Tc}`,padding:"10px",...ye==="row"&&(0,y.isAVSFieldVisible)(Q.country,s)?{borderRadius:"0",borderTopRightRadius:Yt,borderBottomRightRadius:Yt}:{borderRadius:Yt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,y.getPostalCodeLabel)(Mt),autoComplete:"billing postal-code",value:Dn,onChange:ee=>{xt("zip"),gt.current.zip=!0,wt.current=ee.target.value,On(ee.target.value),Ae?.(ee.target.value)},onPointerDown:()=>xt("zip"),onKeyDown:()=>xt("zip"),onBlur:()=>{or("zip")&&Tn(!0)},disabled:j,required:hn.required,"aria-invalid":Ia||void 0,"aria-describedby":Ia?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:K()})})]}),Ia&&(0,c.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Wo,children:hn.empty?`${(0,y.getPostalCodeLabel)(s)} is required`:ou(s)})]})})()}),ie&&Fc,Ye&&(0,c.jsx)(Io,{margin:"0.75rem 0",styleOverride:E.errorBanner,children:Ye})]}),Ra={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"},Hs=s=>V?!T||!kr?(0,c.jsx)("pre",{"data-testid":s,style:Ra,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":s,style:Ra,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${T}`,` directPaypalConfigured=${kr}`,` inAppBrowserDetected=${String(Ca)}`,` shouldRenderDirectPayPal=${No}`,` shouldRenderStripePayPal=${Uo}`,` hasPaypalStripeInstance=${!!ys}`].join(`
39
+ `)}):null,Ks=s=>V?!Y||!Un?(0,c.jsx)("pre",{"data-testid":s,style:Ra,children:"FloPay/Stripe-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":s,style:Ra,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${Y}`,` currency=${jt}`,` amountInCents=${Do}`,` enabledPaymentMethods: ${JSON.stringify(de??[])}`,` enabledPaymentMethodsProvided=${Oo}`,` hasEnabledMethods=${ha}`,` expressMethods: ${JSON.stringify(Pa)}`,` walletExpressMethods: ${JSON.stringify(uo)}`,` paymentElementMethods: ${JSON.stringify(Lo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(va)}`,` hasStripeInstance=${!!Un}`,` shouldRenderWallets=${po}`,` shouldRenderPaymentElement=${qo}`].join(`
40
+ `)}):null,Gs=dt==="apm-expanding"||dt==="apm-form"||dt==="apm-collapsing",fo;dt==="apm-expanding"?fo=ql:dt==="apm-collapsing"&&(fo=$l);let _a=tn?rc(fi,tn):null;if(re==="buttons"){let s=dt==="buttons"||dt==="expanding"||dt==="apm-expanding",S=dt==="expanding"||dt==="card"||dt==="collapsing",K=ft===void 0?{boxSizing:"border-box",height:pa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Te;dt==="expanding"||dt==="apm-expanding"?Te=Qd:(dt==="collapsing"||dt==="apm-collapsing")&&(Te=Zd);let ee;return dt==="expanding"?ee=ql:dt==="collapsing"&&(ee=$l),(0,c.jsxs)("form",{onSubmit:Pi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Zi,{}),L&&(0,c.jsx)(er,{status:L,errorMessage:Ye,authorized:Nn}),(0,c.jsxs)("div",{style:{display:"grid"},children:[(0,c.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!Te?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!Te?tu:{},...Te?{animation:Te,pointerEvents:"none"}:{}},children:[Hs("flopay-direct-paypal-gate-debug"),Ks("flopay-stripe-gate-debug"),No&&ut&&(0,c.jsxs)(c.Fragment,{children:[m&&(0,c.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,c.jsx)(ea.Provider,{value:f,children:(0,c.jsx)(na,{sessionId:e,nonce:t,billingApiUrl:ze,email:_.email,billingName:qe||void 0,onBuyerIdentityReady:J,clientId:ut.clientId,environment:ut.environment,currency:jt.toUpperCase(),isSubscription:Et,providerObjectType:Re,approvalPresentation:Sa==="popup"?void 0:Sa,onTokenizedBody:xn,onComplete:l,onErrorChange:we,onDecline:u,onTechnicalFailure:lo,onButtonClick:me,runBeforeButtonClick:cr,isProcessing:j,onLoadStateChange:gi,onInitializationStateChange:hi,session:vt,existingOrderId:m?.orderId,debug:V},m?.orderId??"fresh")})]}),Uo&&(0,c.jsx)(Jt.Elements,{stripe:zo,options:hs,children:(0,c.jsx)(Hl,{sessionId:e,nonce:t,email:_.email,billingName:qe||void 0,onBuyerIdentityReady:J,billingApiUrl:ze,onTokenizedBody:xn,onErrorChange:we,isProcessing:j,onButtonClick:me,onDecline:u,onTechnicalFailure:lo,runBeforeButtonClick:cr,onLoadStateChange:ks,placeholderBorderRadius:Jr,popupCapabilityOwner:f,externalTelemetryContext:Bs,presentationMode:co})}),po?(0,c.jsx)(Jt.Elements,{stripe:Un,options:gs,children:(0,c.jsx)(Kl,{sessionId:e,nonce:t,email:_.email,billingName:qe||void 0,onBuyerIdentityReady:J,billingApiUrl:ze,intentKind:xe>0?"payment":"setup",expressMethods:uo,onTokenizedBody:xn,onErrorChange:we,onButtonClick:me,onDecline:u,onTechnicalFailure:lo,runBeforeButtonClick:cr,onLoadStateChange:Rs,placeholderBorderRadius:Jr,popupCapabilityOwner:f,externalTelemetryContext:$e})}):null,!po&&xs?(0,c.jsx)("div",{style:{height:pa,borderRadius:Jr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,qo&&(0,c.jsx)(Gl,{sessionId:e,nonce:t,email:_.email,billingName:[_.firstName,_.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:ze,paymentElementMethods:va,stripeInstance:Un,paymentElementBaseOptions:fi,onTokenizedBody:xn,onErrorChange:we,onButtonClick:me,onDecline:u,runBeforeButtonClick:cr,onLoadStateChange:Es,isProcessing:j,submitButtonColor:Zr,submitButtonBorderRadius:Yt,submitButtonStyle:E.submitButton,onExpandApm:In,expandedApmMethod:tn,themeId:Ve,buttonAppearance:{backgroundColor:E.cardButton?.backgroundColor,borderColor:E.cardInputBorder,textColor:E.cardButton?.color,borderRadius:Jr}}),ie&&(0,c.jsx)("button",{type:"button",onClick:async()=>{j||!(await cr("card")).proceed||(me?.("card"),sr())},disabled:j,style:{width:"100%",...K,...E.cardButton,...is({themeBundle:It,resolvedPrimaryColor:Zr,resolvedBorderRadius:Yt,submitButtonStyle:E.submitButton,explicitPrimaryColor:Mn?.colorPrimary}),fontSize:E.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:j?"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:j?.6:1},onMouseEnter:Se=>{!j&&(It||Mn?.colorPrimary)&&(Se.currentTarget.style.backgroundColor=Mc)},onMouseLeave:Se=>{(It||Mn?.colorPrimary)&&(Se.currentTarget.style.backgroundColor=Zr)},onMouseDown:Se=>{Se.currentTarget.style.transform="scale(0.985)"},onMouseUp:Se=>{Se.currentTarget.style.transform="scale(1)"},children:(0,c.jsx)(ho,{content:ft})}),Ye&&dt==="buttons"&&(0,c.jsx)(Io,{margin:"0.25rem 0",styleOverride:E.errorBanner,children:Ye})]}),ie&&S&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...ee?{animation:ee}:{},...dt==="collapsing"?{pointerEvents:"none"}:{}},children:Ws}),Y&&Gs&&tn&&_a&&Un&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...fo?{animation:fo}:{},...dt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Ci,borderRadius:Ri,...Ho,padding:Ii},children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,c.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:A,style:{display:"inline-flex",alignItems:"center",gap:Si?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:E.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...E.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...E.backButtonIcon},children:(0,c.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(bo,{content:ke})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:E.titleFontSize??"1.05rem",color:wi,paddingRight:80,...E.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(tn)}`})]}),(0,c.jsx)(Jt.Elements,{stripe:Un,options:_a,children:(0,c.jsx)(ts,{method:tn,sessionId:e,nonce:t,email:_.email,billingName:[_.firstName,_.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:ze,onTokenizedBody:xn,onErrorChange:we,onDecline:u,onCancel:A,runBeforeButtonClick:cr,onButtonClick:me,isProcessing:j,submitButtonColor:Zr,submitButtonBorderRadius:Yt,submitButtonStyle:E.submitButton,errorText:Ye})},tn)]})})]})]})}return Gs&&tn&&_a&&Un&&Y?(0,c.jsxs)("form",{onSubmit:Pi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Zi,{}),L&&(0,c.jsx)(er,{status:L,errorMessage:Ye,authorized:Nn}),(0,c.jsx)("div",{style:{...fo?{animation:fo}:{},...dt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Ci,borderRadius:Ri,...Ho,padding:Ii},children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,c.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:A,style:{display:"inline-flex",alignItems:"center",gap:Si?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:E.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...E.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...E.backButtonIcon},children:(0,c.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(bo,{content:ke})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:E.titleFontSize??"1.05rem",color:wi,paddingRight:80,...E.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(tn)}`})]}),(0,c.jsx)(Jt.Elements,{stripe:Un,options:_a,children:(0,c.jsx)(ts,{method:tn,sessionId:e,nonce:t,email:_.email,billingName:[_.firstName,_.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:ze,onTokenizedBody:xn,onErrorChange:we,onDecline:u,onCancel:A,runBeforeButtonClick:cr,onButtonClick:me,isProcessing:j,submitButtonColor:Zr,submitButtonBorderRadius:Yt,submitButtonStyle:E.submitButton,errorText:Ye})},tn)]})})]}):(0,c.jsxs)("form",{onSubmit:Pi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Zi,{}),L&&(0,c.jsx)(er,{status:L,errorMessage:Ye,authorized:Nn}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Hs("flopay-direct-paypal-gate-debug-default"),Ks("flopay-stripe-gate-debug-default"),No&&ut&&(0,c.jsxs)(c.Fragment,{children:[m&&(0,c.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,c.jsx)(ea.Provider,{value:f,children:(0,c.jsx)(na,{sessionId:e,nonce:t,billingApiUrl:ze,email:_.email,billingName:qe||void 0,onBuyerIdentityReady:J,clientId:ut.clientId,environment:ut.environment,currency:jt.toUpperCase(),isSubscription:Et,providerObjectType:Re,approvalPresentation:Sa==="popup"?void 0:Sa,onTokenizedBody:xn,onComplete:l,onErrorChange:we,onDecline:u,onTechnicalFailure:lo,onButtonClick:me,runBeforeButtonClick:cr,isProcessing:j,onLoadStateChange:gi,onInitializationStateChange:hi,session:vt,existingOrderId:m?.orderId,debug:V},m?.orderId??"fresh")})]}),Uo&&(0,c.jsx)(Jt.Elements,{stripe:zo,options:hs,children:(0,c.jsx)(Hl,{sessionId:e,nonce:t,email:_.email,billingName:qe||void 0,onBuyerIdentityReady:J,billingApiUrl:ze,onTokenizedBody:xn,onErrorChange:we,isProcessing:j,onButtonClick:me,onDecline:u,onTechnicalFailure:lo,runBeforeButtonClick:cr,onLoadStateChange:ks,placeholderBorderRadius:Jr,popupCapabilityOwner:f,externalTelemetryContext:Bs,presentationMode:co})}),po&&(0,c.jsx)(Jt.Elements,{stripe:Un,options:gs,children:(0,c.jsx)(Kl,{sessionId:e,nonce:t,email:_.email,billingName:qe||void 0,onBuyerIdentityReady:J,billingApiUrl:ze,intentKind:xe>0?"payment":"setup",expressMethods:uo,onTokenizedBody:xn,onErrorChange:we,onButtonClick:me,onDecline:u,onTechnicalFailure:lo,runBeforeButtonClick:cr,onLoadStateChange:Rs,placeholderBorderRadius:Jr,popupCapabilityOwner:f,externalTelemetryContext:$e})}),qo&&(0,c.jsx)(Gl,{sessionId:e,nonce:t,email:_.email,billingName:[_.firstName,_.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:ze,paymentElementMethods:va,stripeInstance:Un,paymentElementBaseOptions:fi,onTokenizedBody:xn,onErrorChange:we,onButtonClick:me,onDecline:u,runBeforeButtonClick:cr,onLoadStateChange:Es,isProcessing:j,submitButtonColor:Zr,submitButtonBorderRadius:Yt,submitButtonStyle:E.submitButton,themeId:Ve,onExpandApm:In,expandedApmMethod:tn,buttonAppearance:{backgroundColor:E.cardButton?.backgroundColor,borderColor:E.cardInputBorder,textColor:E.cardButton?.color,borderRadius:Jr}})]}),ie&&(Ic||kc||Rc)&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,c.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,c.jsx)("span",{children:"or pay with card"}),(0,c.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),ie&&Ws]})}var x=require("react/jsx-runtime"),Fo=44,ps="flopay_checkout_saved_payment_resume",ii=new Map,oi=new Map;function oc(e,t){t.settled&&t.consumers===0&&ii.get(e)===t&&ii.delete(e)}function du(e,t,n){let r=oi.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};oi.set(e,a);let l=()=>{oi.get(e)===a&&oi.delete(e)};return o.then(l,l),o}function ya(e){return new Promise(t=>setTimeout(t,e))}function ai(e,t,n){let r=La({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Xe.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function fa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ss(e,t,n,r,o,a){let l=ai(e,t,n);l.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),fa(l)}function ac(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 ic(e,t,n,r,o){let a=(0,Xe.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 Xe.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof Xe.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 dc(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 ls(e){return!e||e.data.stripe?.publishableKey?!1:!!dc(e)?.clientId}var uu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function pu(e){return new $r.FloPay(uu,{publishableKey:"provider_unavailable",...e})}async function cs(e,t){let{publishableKey:n,paypalPublishableKey:r}=Vi(e);return{...await Wi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function ms(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function mu(){if(!ms())return null;try{let e=window.sessionStorage.getItem(ps);return e?JSON.parse(e):null}catch{return null}}function sc(e){if(ms())try{window.sessionStorage.setItem(ps,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ds(){if(ms())try{window.sessionStorage.removeItem(ps)}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 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 us(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function fu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function cc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function gu(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function si({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:d,error:u,onComplete:p,onError:b,onInstrument:v,onDecline:M,onCountryChange:I,onZipChange:w,showPayPal:h=!0,showStripe:O=!0,walletPresentation:G="auto",enabledPaymentMethods:T,showApplePay:Y=!0,showGooglePay:U=!0,debug:de=!1,layout:X,theme:he,buttonsTheme:De,buttonsStyles:re,cardButtonContent:Ve,cardBackButtonContent:yt,cardTitleContent:te,showSecurityFooter:Oe,onButtonClick:ft,onBeforeButtonClick:ke,enableAVS:Le,cardFieldOrder:be,cardPreFormSlot:me,avsLayout:Ie,submitLabel:We,className:rt,initialErrorMessage:R=null,initialPayPalOrderId:He,children:ye,checkoutMode:N,confirmLabel:ve,renderConfirmButton:ue,onSessionCompleted:Ke}){let Z=(0,Xe.resolveBillingApiUrl)(r),ot=(0,C.useMemo)(()=>(0,Xe.resolveTheme)(he),[he]),lt=a??ot?.appearance,Ae=n?"embedded_checkout":"standard_checkout",Ne=us(ye,X),[ct,at]=(0,C.useState)(null),[xe,jt]=(0,C.useState)(null),Vt=(0,C.useRef)(null),ut=(0,C.useRef)(null),Et=(0,C.useRef)(0),[q,fe]=(0,C.useState)(null),et=(0,C.useRef)(null),[V,Me]=(0,C.useState)(null),bt=(0,C.useMemo)(()=>n?_o(n):"",[n]),Ge=n?`create:${bt}`:`session:${e??""}`,$=cc(V),Je=(0,C.useRef)(new Set),f=(0,C.useRef)(Ge),P=(0,C.useRef)(Ge);no(()=>{P.current=Ge,f.current!==Ge&&(f.current=Ge,Je.current.clear())},[Ge]);let H=(0,C.useCallback)(A=>{if(P.current===Ge){if(Fi.has(A.name)){if(Je.current.has(A.name))return;Je.current.add(A.name)}st(()=>v?.(A))}},[Ge,v]),ne=ko(H,Ge),$e=(0,C.useRef)(!1),vt=(0,C.useCallback)(A=>{if($e.current)return;let L=A.gateway||!$?A:{...A,gateway:$};H(L)},[H,$]);(0,C.useEffect)(()=>{ne({class:"lifecycle",name:"checkout.mount"})},[ne]);let[Re,ae]=(0,C.useState)(e??""),it=e??Re,Ct=n?"":it,[Nt,ze]=(0,C.useState)(!0),[Ft,Ue]=(0,C.useState)(null),[Fn,Rn]=(0,C.useState)(0),[Mt,wn]=(0,C.useState)("full"),[Dn,On]=(0,C.useState)(!1),[rn,Ce]=(0,C.useState)(R),[St,Tt]=(0,C.useState)(null),[vn,Bt]=(0,C.useState)(null),[Vn,pn]=(0,C.useState)(!1),[Wt,an]=(0,C.useState)(void 0),[Wn,mn]=(0,C.useState)(""),[wt,Zt]=(0,C.useState)(!1),[yn,Dt]=(0,C.useState)(!1),[Qt,Ht]=(0,C.useState)(!1),fn=(0,C.useRef)(null),gt=(0,C.useRef)(0),Q=(0,C.useRef)(void 0),[Ln,Nn]=(0,C.useState)("loading"),[hr,Cn]=(0,C.useState)(0),sn=(0,C.useRef)(!1),_n=(0,C.useRef)(!1),_e=(0,C.useRef)(!1),ht=(0,C.useRef)(null),ie=(0,C.useRef)(null),F=(0,C.useMemo)(()=>({checkoutMode:N??Mt,layout:fu(ye,X)}),[N,ye,Mt,X]),Ze=(0,C.useRef)(p);Ze.current=p;let se=(0,C.useRef)(b);se.current=b;let Hn=(0,C.useRef)(M);Hn.current=M;let gn=(0,C.useCallback)(A=>Ha(ht,async L=>{try{return await A(L)}catch(B){throw L.aborted?Xr(B):B}}),[]);(0,C.useEffect)(()=>()=>{ht.current?.abort(),ht.current=null},[]);let Kt=(0,C.useCallback)((A,L)=>{Vt.current=A,jt(A),et.current=L,fe(L)},[]),Kn=(0,C.useCallback)(()=>{let A=ut.current;A&&(ut.current=null,A.destroy())},[]);(0,C.useEffect)(()=>{dn(xe)?.setCheckoutContext(F),q&&q!==xe&&dn(q)?.setCheckoutContext(F)},[xe,q,F]);let nt=(0,C.useRef)(Ke);nt.current=Ke;let jr=(0,C.useCallback)(A=>{Nn(A),!(A!=="exhausted"||_e.current)&&(_e.current=!0,se.current?.(new Xe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Gt=(0,C.useCallback)(()=>{Nn("retrying"),Cn(A=>A+1)},[]);(0,C.useEffect)(()=>{Nn("loading"),Cn(0),_e.current=!1},[it]),(0,C.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Xe.SDK_VERSION,checkout_type:Ae,checkout_layout:Ne,billing_api_url:Z})},[Ne,Ae,Z]);let hn=(0,C.useMemo)(()=>n?_o(n,!0):"",[n]),Mr=(0,C.useMemo)(()=>Wn===hn?Wt:void 0,[Wt,Wn,hn]),Br=(0,C.useMemo)(()=>n?Ti(n,Mr):void 0,[n,Mr]),En=N??Br?.checkoutMode??"full",en=(0,C.useMemo)(()=>Br?{...Br,checkoutMode:En}:void 0,[Br,En]);(0,C.useEffect)(()=>{an(void 0),mn(hn),Q.current=void 0,fn.current=null,Ht(!1)},[hn]),(0,C.useEffect)(()=>{Ce(R)},[R]);let br=(0,C.useCallback)((A,L,B)=>{st(()=>{Hn.current?.(cn(A,L,B))})},[]),Tn=(0,C.useCallback)(async(A,L)=>{Ce(null),Bt(null),pn(!1),Tt("processing");let B=L?.sessionId??A.id,le=A.clientSecret||t,Be=cc(A),pt=Vt.current??et.current,pe=dn(pt),Fe=pt?null:ai(Z,o,F),W={log:E=>{pe?pe.log(E):Fe?.log(E)},error:E=>{pe?pe.error(E):Fe?.error(E)},terminal:E=>{pe?pe.terminal(E):Fe?.terminal(E)},performance:E=>{pe?pe.performance(E):Fe?.performance(E)},now:()=>pe?.now()??Fe?.now()??0,elapsed:E=>pe?.elapsed(E)??Math.max(0,(Fe?.now()??E)-E)},m=W.now(),g=!!(L?.initialAutoProcessingError||L?.initialAutoProcessingPending),D=!1,z,ce=()=>{D||(D=!0,g=!0,z=W.now(),W.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),W.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},J=!1,Ye=()=>{J||(J=!0,W.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),W.performance({stage:"processing",durationMs:W.elapsed(m),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),z!==void 0&&W.performance({stage:"recovery",durationMs:W.elapsed(z),durationMode:"machine",paymentMethodCategory:"saved"}))};W.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),$e.current=!0;try{W.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{$e.current=!1}ne({class:"lifecycle",name:"payment.processing.started",provider:Be}),g&&ce();let It;try{let E=kl(L?.initialAutoProcessingError),Pe=L?.initialAutoProcessingError?.type==="3ds_required"&&!L.initialAutoProcessingError.threeDSecureToken&&L.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:L.initialAutoProcessingError.nextActionRedirectUrl}:null,At,ge=j=>(ce(),gn(oe=>To(j,{billingApiUrl:Z,sessionId:B,nonce:le,session:A,signal:oe})));if(Pe)At=await ge(Pe);else if(E)ce(),E.type==="paypal_redirect_required"&&ie.current?.publishableKey&&sc({sessionId:B,publishableKey:ie.current.publishableKey,paypalPublishableKey:ie.current.paypalPublishableKey}),At=await gn(j=>Ga(E,{flopay:Vt.current,paypalFlopay:et.current,attempt3DS:L?.attempt3DS,billingApiUrl:Z,sessionId:B,session:A,telemetry:!1,signal:j})),E.type==="paypal_redirect_required"&&ds();else if(L?.initialAutoProcessingPending){let j=L.initialAutoProcessingPending,oe=new $r.PaymentAPI(Z,{telemetry:!1}),_=await gn(Ee=>oe.waitForCheckoutSessionCompletion(j.sessionId,{initialDelayMs:j.retryAfterMs,nonce:le,statusUrl:j.statusUrl,signal:Ee})),qe=Kr(_,A),Rt=_.autoProcessingError?.type==="3ds_required"&&_.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:_.autoProcessingError.nextActionRedirectUrl}:null;if(Rt)At=await ge(Rt);else{if(!Nr(qe))throw vo(qe);At=Lr(qe,B)}}else{if(L?.initialAutoProcessingError)throw Er(L.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:L.initialAutoProcessingError.checkoutMethod});if(L?.fromCreateSession)return L?.fallbackToFull&&(wn("full"),lc("full")),!1;{let j=await Ao({billingApiUrl:Z,sessionId:B,session:A,nonce:le,telemetry:!1});j.type==="success"?At=j.result:j.type==="next_action_required"?At=await ge(j):(ce(),j.type==="paypal_redirect_required"&&ie.current?.publishableKey&&sc({sessionId:B,publishableKey:ie.current.publishableKey,paypalPublishableKey:ie.current.paypalPublishableKey}),At=await gn(oe=>Ga(j,{flopay:Vt.current,paypalFlopay:et.current,attempt3DS:L?.attempt3DS,billingApiUrl:Z,sessionId:B,session:A,telemetry:!1,signal:oe})),j.type==="paypal_redirect_required"&&ds())}}B&&Eo(B),Ye(),g&&(W.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),W.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),W.terminal({outcome:At.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),pn(At.status==="authorized"),Tt("success"),await ya(600),It=()=>Ze.current?.(At)}catch(E){let Pe=sa(E);if(Pe.code==="three_ds_aborted")return!1;let At=Pe.checkoutMethod??ia;Ce(Pe.message),Bt(Pe.message),pn(!1),L?.fallbackToFull&&(W.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),wn("full"),lc("full")),Ye();let ge=Pe.statusCode===void 0?void 0:(0,Xe.telemetryStatusClass)(Pe.statusCode,"unknown"),j=ge==="4xx"?{requestCategory:"process_payment",statusClass:ge}:{},oe=ge===void 0||ge==="4xx";if(oe&&(Pe.telemetryOutcome==="payment_declined"||!!(Pe.declineCode||Pe.code?.toLowerCase().includes("declin"))))W.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...j});else if(oe&&(Pe.telemetryOutcome==="validation_rejected"||Pe.type==="validation_error"))W.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...j});else{let Rt=(0,Xe.classifyTelemetryFailure)(E,g?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Ee=Pe.telemetryRequestCategory??"process_payment";$e.current=!0;try{W.error({...Rt,...Pe.telemetryFailureCategory?{failureCategory:Pe.telemetryFailureCategory}:{},stage:g?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Ee})}finally{$e.current=!1}ne({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Ee,provider:Be})}return st(()=>se.current?.(Pe)),br(At,Pe,{code:Pe.code,declineCode:Pe.declineCode}),Tt("error"),await Promise.allSettled([ya(400),L?.ensureProvidersReady?L.ensureProvidersReady():Promise.resolve()]),g&&(W.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),W.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ye(),Fe&&fa(Fe),Tt(null),Bt(null)}return st(It),!0},[br,ne,t,Z,gn,o,F]);(0,C.useEffect)(()=>{if(typeof window>"u"||_n.current)return;let A=new URLSearchParams(window.location.search),L=A.get("payment_intent_client_secret");if(!L)return;let B=mu();B&&(_n.current=!0,(async()=>{let le,Be=0;Ce(null),Bt(null),Tt("processing"),On(!0);try{if(A.get("redirect_status")==="failed")throw Object.assign(new Xe.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:pt,paypalFlopay:pe}=await Wi({publishableKey:B.publishableKey,paypalPublishableKey:B.paypalPublishableKey,billingApiUrl:Z,locale:l,telemetry:o});le=dn(pe??pt),le?.setCheckoutContext(F),Be=le?.now()??0,le?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),le?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Fe=(pe??pt)?.getRawProvider();if(!Fe)throw Object.assign(new Xe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:W,error:m}=await Fe.retrievePaymentIntent(L);if(m)throw Object.assign(new Xe.FloPayError(m.message??"Failed to retrieve PayPal payment status.","api_error",{code:m.code}),{checkoutMethod:"paypal"});let g=ol(W?.status);if(!W||g==="failed")throw Object.assign(new Xe.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let D=typeof W.payment_method=="string"?W.payment_method:W.payment_method?.id,z=g;if(B.sessionId){let Ye=(await new $r.PaymentAPI(Z,{telemetry:!1}).getUnifiedCheckoutSession(B.sessionId)).data.session;if(Ye&&Ye.status!=="complete"){let It=await Ao({billingApiUrl:Z,sessionId:B.sessionId,session:Ye,telemetry:!1,tokenizedData:{id:D??W.id,type:"card",threeDSecureActionResultTokenId:W.id,isPaypal:!0}});if(It.type!=="success")throw Object.assign(new Xe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});z=It.result.status}}B.sessionId&&Eo(B.sessionId),le?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),le?.performance({stage:"redirect_resume",durationMs:le.elapsed(Be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),le?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Tt("success"),await ya(600),st(()=>Ze.current?.({status:z,paymentIntentId:W.id,paymentMethodId:D,checkoutMethod:"paypal"}))}catch(pt){let pe=sa(pt),Fe=pe.checkoutMethod??"paypal",W=!!(pe.declineCode||pe.code?.toLowerCase().includes("declin"));if(le)le.performance({stage:"redirect_resume",durationMs:le.elapsed(Be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),W?le.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):le.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(W){let m=ai(Z,o,F);m.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),fa(m)}else ss(Z,o,F,"REDIRECT_RESUME_FAILED","redirect_resume");Ce(pe.message),Bt(pe.message),st(()=>se.current?.(pe)),br(Fe,pe,{code:pe.code,declineCode:pe.declineCode}),Tt("error"),await ya(400)}finally{ds(),yu(),Tt(null),Bt(null),On(!1)}})())},[br,l,Z,o,F]);let Fr=(0,C.useRef)(null),An=(0,C.useMemo)(()=>en?_o(en):"",[en]),Pr=(0,C.useRef)(en);Pr.current=en,(0,C.useEffect)(()=>{ae(e??"")},[e]),(0,C.useEffect)(()=>{sn.current=!1,Ce(R),Bt(null),pn(!1),Tt(null)},[An,R,e]);async function vr(A,L,B){let le=ai(Z,o,F),Be=new $r.PaymentAPI(Z,{telemetry:!1}),pt=!1;try{let pe=A.idempotencyKey===void 0?void 0:(0,Xe.resolveIdempotencyKey)(A.idempotencyKey),Fe=Li(L,B),W=Ni(L,B);Fe?.canonicalIdentity===B&&W&&W.canonicalIdentity===void 0&&(Va(L,B,W.idempotencyKey),W={...W,canonicalIdentity:B});let m=pe??(W?.canonicalIdentity===B?W.idempotencyKey:void 0),g,D=!1;le.log({name:Fe?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let z=Fe?.sid??null,ce=null,J,Ye,It=!1;if(z)try{ce=await Be.getUnifiedCheckoutSession(z,Fe?.nonce),Fe&&Fe.canonicalIdentity===void 0&&(vl(ce.data.session,A)?(ja(L,B,z,Fe.nonce??ce.data.session?.clientSecret),W&&W.canonicalIdentity===void 0&&(Va(L,B,W.idempotencyKey),m??(m=W.idempotencyKey))):($a(L,B),W=null,m=pe,z=null,ce=null));let Pe=ce?.data.session?.status,At=ce?.data.session,ge=At?.clientSecret||Fe?.nonce;if(z&&At?.buyerIdentified===!1&&ge&&(Ye=Po(Be,z,ge,A.account)),z&&ce&&Pe==="complete"){if(zi(z))return{sid:z,result:ce};$a(L,B),z=null,ce=null,D=!0}}catch{le.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Fe?.canonicalIdentity===void 0?($a(L,B),m=pe):qa(L,B),z=null}if(!z){!pe&&(D||!m)&&(m=(0,Xe.resolveIdempotencyKey)(),g=m),m&&Va(L,B,m);let Pe=le.now(),At=0;le.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ge={...A,idempotencyKey:m,avsCheck:!!Le,avsConfig:typeof Le=="object"?Le:void 0,checkoutType:"embedded_checkout",checkoutLayout:us(ye,X)};Object.defineProperty(ge,$r.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:_=>{At=Math.max(At,_)}}});let j=()=>{ac(le,"session_create",Pe,At)},oe=_=>{ic(le,_,"session_create",Pe,At)&&ne({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,Xe.isDetachedSessionEligible)(ge)){let _=await Be.createDetachedSession(ge);_.claimed.catch(()=>{}),ce=_.shell,z=_.sessionId,Ye=_.claim;let qe=le.now();le.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),J=_.claimed.then(Rt=>{let Ee=Rt.data.session?.id??_.sessionId;return Ee&&ja(L,B,Ee,Rt.data.session?.clientSecret??_.nonce),ac(le,"session_claim",qe),j(),Rt},Rt=>{throw qa(L,B),ic(le,Rt,"session_claim",qe,0)&&ne({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Rt}).finally(()=>fa(le)),J.catch(()=>{}),pt=!0,le.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),le.performance({stage:"session_shell",durationMs:le.now()-Pe,durationMode:"machine",requestCategory:"session_create",attempt:At,statusClass:"2xx",paymentMethodCategory:"card"})}else ce=await Be.createAndFetchSession(ge),j()}catch(_){throw oe(_),_}z=ce.data.session?.id??z??"",z&&!J&&ja(L,B,z,ce.data.session?.clientSecret)}let E=ce?.data.session;return!Ye&&z&&E?.buyerIdentified===!1&&E.clientSecret&&(Ye=Po(Be,z,E.clientSecret,A.account)),{sid:z??"",result:ce,sdkGeneratedIdempotencyKey:g,...J?{claimed:J}:{},...Ye?{claim:Ye}:{},...It?{claimRequiresIdentity:!0}:{}}}finally{pt||fa(le)}}let rr=(0,C.useRef)(vr);no(()=>{rr.current=vr},[vr]);let Gn=(0,C.useCallback)(async(A,L)=>{let B=Pr.current;if(!B)throw new Xe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let le=Ti(B,A),Be=_o(le),pt=Pl(le),pe=ii.get(Be);if(!pe){let m={canonicalIdentity:Be,promise:rr.current(le,pt,Be),consumers:0,settled:!1};pe=m,ii.set(Be,m);let g=()=>{m.settled=!0,oc(Be,m)};m.promise.then(g,g)}pe.consumers+=1;let Fe=!1,W=()=>{Fe||(Fe=!0,pe.consumers-=1,oc(Be,pe))};L?.(W);try{let m=await pe.promise;Fr.current=Be,A&&(mn(hn),an(E=>tl(E,A)));let{sid:g,result:D,claimed:z,claim:ce,claimRequiresIdentity:J}=m;if(Q.current=ce,Ht(J===!0),at(D),D.data.session&&Me(D.data.session),g&&ae(g),z){gt.current+=1;let E=gt.current;fn.current=z,Dt(!0),z.then(Pe=>{gt.current===E&&(fn.current===z&&(fn.current=null),at(Pe),Pe.data.session&&Me(Pe.data.session),Dt(!1),Ht(!1))},Pe=>{gt.current===E&&(fn.current===z&&(fn.current=null),Dt(!1),Ht(!1),Ue(Pe instanceof Xe.FloPayError?Pe:new Xe.FloPayError(Pe instanceof Error?Pe.message:"Failed to create session","api_error")))})}else gt.current+=1,fn.current=null,Dt(!1),Ht(!1);let{flopay:Ye,paypalFlopay:It}=await cs(D,{billingApiUrl:Z,locale:l,telemetry:o});return Kt(Ye,It),ze(!1),m}catch(m){throw Fr.current===Be&&(Fr.current=null),m}finally{L||W()}},[hn,Kt,l,Z,o]),Yn=(0,C.useRef)(Tn);Yn.current=Tn;let xt=(0,C.useRef)(Gn);xt.current=Gn;let or=(0,C.useCallback)(async A=>{if(!gu(A)||wt)return{sessionId:Re,session:V};Zt(!0);try{let L=await Gn(A);return{sessionId:L.sid,session:L.result.data.session??null}}finally{Zt(!1)}},[Gn,wt,Re,V]),kn=(0,C.useCallback)(async A=>{let L=Q.current;if(!L)return;let B=gt.current,le=await L(A);gt.current===B&&(at(le),le.data.session&&Me(le.data.session))},[]),Xn=(0,C.useCallback)(async()=>{await fn.current},[]),Cr=(0,C.useCallback)(async()=>(await Xn(),{proceed:!0}),[Xn]);(0,C.useEffect)(()=>{let A=!1,L,B=++Et.current;Kn(),Ue(null),Rn(0);let le=()=>{A=!0,Et.current===B&&(Et.current+=1,Kn())},Be=Pr.current;if(An&&Be)return wn(En),ze(!1),Fr.current===An?le:(Me(nl(Be,N)),(async()=>{let Fe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),W=En==="auto"&&!sn.current&&!Fe;W&&(Ce(null),Bt(null),Tt("processing"));try{let m=await xt.current(void 0,ce=>{L=ce}),g=m.result.data.session??null;ie.current=Vi(m.result);let D=ls(m.result),z=zi(m.sid||g?.id);if(!A&&W&&g&&!D&&!z){sn.current=!0,await du(An,m.sdkGeneratedIdempotencyKey,()=>Yn.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}!A&&W&&((D||z)&&(sn.current=!0),Tt(null),Bt(null))}catch(m){if(A)return;let g=Aa(m);if(W&&g==="session_auto_completed"){sn.current=!0,Tt("success"),await ya(600),A||(st(()=>{Ze.current?.({status:"succeeded"})}),Tt(null),Bt(null));return}W&&(Tt(null),Bt(null));let D=m instanceof Xe.FloPayError?m:new Xe.FloPayError(m instanceof Error?m.message:"Failed to create session","api_error");Ue(D)}finally{L?.(),L=void 0}})(),()=>{le(),L?.()});ze(!0);async function pt(){let Fe=!1,W=null;try{let m=new $r.PaymentAPI(Z,{telemetry:!1}),g=await m.getUnifiedCheckoutSession(it,t);if(W=g,A)return;at(g);let D=g.data.session??null;if(Me(D),!D)throw new Xe.FloPayError("No session data returned","api_error");let z=D.checkoutMode;if(z==="setup")throw new Xe.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(D.status==="authorized"){ze(!1),st(()=>{Ze.current?.(Lr(D,it)),nt.current?.(D.successUrl??"")});return}if(D.status==="complete"){ze(!1),st(()=>{nt.current?.(D.successUrl??"")});return}if(D.status==="expired")throw Ta(D);Fe=!0;let ce=N??z??"full";wn(ce),gt.current+=1;let J=D.clientSecret||t;Q.current=D.buyerIdentified===!1&&J?Po(m,it,J,{...D.customer?.id?{userId:D.customer.id}:{}}):void 0,Dt(!1),Ht(!1);let Ye=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),It=ls(g);if(ce==="auto"&&!sn.current&&!Ye&&!It){sn.current=!0;let E=pe(g);try{if(await Yn.current(D,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>E,sessionId:it||D.id}),A)return;await E,A||ze(!1);return}catch{if(A)return;await E,A||ze(!1);return}}await pe(g),A||ze(!1)}catch(m){if(A)return;let g=el(m,Fe);if(Fe&&ne({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),g){let{errorCode:z,stage:ce,...J}=g;ss(Z,o,F,z,ce,J)}if(g?.stage==="provider_load"&&(N??W?.data.session?.checkoutMode??"full")==="full"&&Qs(W,h,O)){let z=pu({billingApiUrl:Z,locale:l,telemetry:o});ut.current=z,Kt(z,null),Rn(1),ze(!1);return}let D=m instanceof Xe.FloPayError&&g?.stage!=="provider_load"?m:Zs();D!==m&&st(()=>se.current?.(D)),Ue(D),ze(!1)}}async function pe(Fe){let{flopay:W,paypalFlopay:m,...g}=await cs(Fe,{billingApiUrl:Z,locale:l,telemetry:o});ie.current={publishableKey:g.publishableKey,paypalPublishableKey:g.paypalPublishableKey},Kt(W,m),Rn(0)}return pt(),le},[N,An,En,Ct,t,h,O]);let dt=(0,C.useCallback)(async()=>{if(!ct||Fn!==1)return;let A=Et.current;Rn(2);try{let{flopay:L,paypalFlopay:B}=await cs(ct,{billingApiUrl:Z,locale:l,telemetry:o});if(Et.current!==A)return;Kn(),Kt(L,B),Rn(0)}catch(L){if(Et.current!==A)return;let{errorCode:B,stage:le,...Be}=_i(L);ss(Z,o,F,B,le,Be)}},[Kn,Kt,l,Fn,Z,o,F,ct]),on=!!(it&&(V?.clientSecret||t)),tn=Dn||!on,Dr=(0,C.useCallback)(async()=>{if(!(Dn||!on||!V)){On(!0),Ce(null);try{await Tn(V,{attempt3DS:!0,fallbackToFull:!0,sessionId:it||V.id})}finally{On(!1)}}},[it,Dn,on,Tn,V]),zn=dc(ct,He),Vr=ls(ct),ar=(0,C.useMemo)(()=>{if(!(!ct||!V||!ct.data.stripe?.publishableKey))return{billingApiUrl:Z}},[ct,V,Z]),ir=!!(n&&!ye&&X==="buttons"&&ke&&En==="full"),bn=!!(it&&(V?.vault?.html||Wr(V))),sr=(0,C.useMemo)(()=>({session:V,loading:Nt,error:Ft,checkoutMode:Mt,inlineSessionDraft:en,applyInlineSessionPatch:ir?or:void 0,inlineSessionPatchProcessing:wt,claimPending:yn,claimRequiresIdentity:Qt,claimBuyerIdentity:kn,waitForDataAttachment:Xn}),[V,Nt,Ft,Mt,en,ir,or,wt,yn,Qt,kn,Xn]),Or=!!n&&X==="buttons"&&!Vr&&!bn&&(!xe||!ar),In=St?(0,x.jsx)(er,{status:St,errorMessage:vn,authorized:Vn}):null;if(Nt&&!bn){if(d)return(0,x.jsxs)(x.Fragment,{children:[d,In]});if(X==="buttons"){let A=ot?.buttonsLayout?.cardButton?.borderRadius??ot?.appearance.variables?.borderRadius??8,L=B=>(0,x.jsx)("div",{style:{height:B,borderRadius:A,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[h&&L(Fo),O&&(Y||U)&&L(Fo),O&&L(Fo),(0,x.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),In]})}return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,x.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,x.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),In]})}return Ft?u?(0,x.jsx)(pr.Provider,{value:sr,children:u(Ft)}):(0,x.jsx)(pr.Provider,{value:sr,children:(0,x.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ft.message})}):Or?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(pr.Provider,{value:sr,children:(0,x.jsx)(bu,{onButtonClick:ft,showPayPal:h,showStripe:O,showApplePay:Y,showGooglePay:U,theme:he,buttonsTheme:De,buttonsStyles:re,cardButtonContent:Ve,cardBackButtonContent:yt,cardTitleContent:te})}),In]}):Vr&&V&&zn?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(pr.Provider,{value:sr,children:(0,x.jsxs)("div",{className:rt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[rn&&(0,x.jsx)(Io,{icon:!1,children:rn}),Ln==="retrying"&&(0,x.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ln==="exhausted"&&(0,x.jsxs)("div",{role:"alert",children:[(0,x.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,x.jsx)("button",{type:"button",onClick:Gt,children:"Retry PayPal"})]}),Ln!=="exhausted"&&(0,x.jsx)("div",{"aria-hidden":Ln==="retrying"?!0:void 0,style:Ln==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,x.jsx)(bl,{sessionId:it,nonce:V.clientSecret||void 0,billingApiUrl:Z,email:V.customer?.email||en?.account?.email,billingName:[V.customer?.firstName,V.customer?.lastName].filter(Boolean).join(" ")||[en?.account?.firstName,en?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:kn,clientId:zn.clientId,environment:zn.environment,currency:(V.currency??"usd").toUpperCase(),isSubscription:V.mode==="subscription",providerObjectType:zn.providerObjectType,approvalPresentation:zn.approvalPresentation,existingOrderId:zn.existingOrderId,onComplete:p,onErrorChange:Ce,onDecline:M,onButtonClick:ft,runBeforeButtonClick:Cr,onInitializationStateChange:jr,allowAutomaticRetry:hr===0,session:V,telemetry:o,telemetryContext:F,onInstrument:vt,debug:de},`${Ge}:paypal-init-${hr}`)})]})}),In]}):Mt==="confirm"?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(pr.Provider,{value:sr,children:(0,x.jsx)(oa,{flopay:xe,paypalFlopay:q,options:ar??{billingApiUrl:Z},onInstrument:vt,children:(0,x.jsxs)("div",{className:rt,children:[rn&&(0,x.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:rn}),ue?ue({onConfirm:Dr,isProcessing:tn}):(0,x.jsx)("button",{type:"button",onClick:Dr,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:Dn?"Processing...":ve??"Confirm Purchase"})]})},Ge)}),In]}):(!xe||!ar)&&!(bn&&Mt==="full")?(0,x.jsx)(x.Fragment,{children:In}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(pr.Provider,{value:sr,children:(0,x.jsxs)(oa,{flopay:xe,paypalFlopay:q,options:ar??{billingApiUrl:Z},onInstrument:vt,children:[Fn===1&&(0,x.jsx)("button",{type:"button",onClick:dt,children:"Retry payment methods"}),ye?(0,x.jsxs)(x.Fragment,{children:[rn&&(0,x.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:rn}),(0,x.jsx)(hu,{sessionId:it,nonce:V?.clientSecret||void 0,billingApiUrl:Z,session:V,submitLabel:We,walletPresentation:G,children:ye})]}):(0,x.jsx)(ri,{sessionId:it,nonce:V?.clientSecret||void 0,telemetry:o,email:V?.customer?.email||en?.account?.email,userId:V?.customer?.id||en?.account?.userId,firstName:V?.customer?.firstName||en?.account?.firstName,lastName:V?.customer?.lastName||en?.account?.lastName,totalAmount:V?Math.round((0,Xe.buildCheckoutDisplayData)(V).total*100):0,currency:V?.currency?.toLowerCase()??"usd",onComplete:p,onError:b,onDecline:M,error:rn,onErrorChange:Ce,showPayPal:h,showStripe:O,walletPresentation:G,enabledPaymentMethods:Fn?[]:T??ct?.data.stripe?.enabledPaymentMethods??V?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ct?.data.stripe?.enabledPaymentMethodCountries,showApplePay:Y,showGooglePay:U,layout:X,theme:he,buttonsTheme:De,buttonsStyles:re,appearance:lt,cardButtonContent:Ve,cardBackButtonContent:yt,cardTitleContent:te,onButtonClick:ft,onBeforeButtonClick:ke,onBuyerIdentityReady:kn,enableAVS:Le,...be?{cardFieldOrder:be}:{},...me?{cardPreFormSlot:me}:{},avsLayout:Ie,country:V?.customer?.country,city:V?.customer?.city,state:V?.customer?.state,onCountryChange:I,onZipChange:w,avsCheck:!!Le,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:us(ye,X),className:rt,submitLabel:We,directPaypal:zn,isSubscription:V?.mode==="subscription",session:V,dataAttachmentPending:yn,dataAttachmentRequiresIdentity:Qt,debug:de})]},Ge)}),In]})}function hu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:a,children:l}){return(0,x.jsx)(x.Fragment,{children:C.default.Children.map(l,d=>{if(!C.default.isValidElement(d))return d;let u=d.props,p={};return u.sessionId||(p.sessionId=e),!u.nonce&&t&&(p.nonce=t),u.billingApiUrl||(p.billingApiUrl=n),u.submitLabel===void 0&&o!==void 0&&(p.submitLabel=o),u.walletPresentation===void 0&&(p.walletPresentation=a),r?.customer&&(u.email||(p.email=r.customer.email),u.userId||(p.userId=r.customer.id),u.firstName||(p.firstName=r.customer.firstName),u.lastName||(p.lastName=r.customer.lastName)),Object.keys(p).length===0?d:C.default.cloneElement(d,p)})})}function bu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:d,cardButtonContent:u,cardBackButtonContent:p,cardTitleContent:b}){let[v,M]=(0,C.useState)(!1),I=(0,C.useMemo)(()=>(0,Xe.resolveTheme)(a),[a]),w=(0,C.useMemo)(()=>{let T=I?.buttonsLayout??(0,Xe.resolveButtonsLayoutTheme)(l);return d?{...T,...d,cardButton:{...T.cardButton,...d.cardButton},cardFormContainer:{...T.cardFormContainer,...d.cardFormContainer},backButton:{...T.backButton,...d.backButton},backButtonIcon:{...T.backButtonIcon,...d.backButtonIcon},submitButton:{...T.submitButton,...d.submitButton},title:{...T.title,...d.title}}:T},[I,l,d]),h=I?.buttonsLayout?.cardButton?.borderRadius??I?.appearance.variables?.borderRadius??8,O=T=>(0,x.jsx)("div",{style:{height:T,borderRadius:h,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),G=u===void 0?{boxSizing:"border-box",height:Fo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(v){let T=w.cardInputBorder??"#e5e7eb",Y=w.cardInputBackground??"white",U=go(p),de=go(b);return(0,x.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,x.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,x.jsxs)("button",{type:"button",onClick:()=>M(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:U?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,x.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...w.backButtonIcon},children:(0,x.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,x.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,x.jsx)(bo,{content:p})]}),de?(0,x.jsx)("div",{style:{flex:1}}):(0,x.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...w.title},children:(0,x.jsx)(Go,{content:b})})]}),(0,x.jsx)("div",{style:{backgroundColor:Y,border:`1px solid ${T}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,x.jsxs)("div",{style:{display:"flex"},children:[(0,x.jsx)("div",{style:{flex:1,backgroundColor:Y,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${T}`,borderLeft:`1px solid ${T}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,x.jsx)("div",{style:{flex:1,backgroundColor:Y,borderTop:"none",borderRight:`1px solid ${T}`,borderBottom:`1px solid ${T}`,borderLeft:`1px solid ${T}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,x.jsx)("div",{style:{backgroundColor:Y,border:`1px solid ${T}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,x.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,x.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,M.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&N(Bo),n&&(r||o)&&N(Bo),n&&(0,M.jsx)("button",{type:"button",onClick:()=>{e?.("card"),A(!0)},style:{width:"100%",...re,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:S.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...S.cardButton},onMouseDown:T=>{T.currentTarget.style.transform="scale(0.985)"},onMouseUp:T=>{T.currentTarget.style.transform="scale(1)"},children:(0,M.jsx)(go,{content:p})}),(0,M.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var gr=require("react/jsx-runtime"),Pu=44;function uc(e){return new Promise(t=>setTimeout(t,e))}function vu(e,t){return e instanceof tr.FloPayError?e:new tr.FloPayError(e instanceof Error?e.message:t,"api_error")}function Cu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Su(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 pc({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:d,subscriptions:p,account:f,successUrl:h,cancelUrl:b,couponCodes:A,tagsData:k,utmMetadata:S,billingApiUrl:v,locale:N,theme:re,appearance:T,buttonsTheme:G,buttonsStyles:$,onSuccess:de,onError:Y,onDecline:fe,children:De,disabled:ne=!1,type:$e="button",style:ft,...te}){let Le=(0,et.useMemo)(()=>(0,tr.resolveBillingApiUrl)(v),[v]),gt=(0,et.useMemo)(()=>Su({createSession:n,clientId:a,products:l,items:d,subscriptions:p,account:f,successUrl:h,cancelUrl:b,couponCodes:A,tagsData:k,utmMetadata:S}),[f,b,a,A,n,l,d,p,h,k,S]),[Re,Oe]=(0,et.useState)(!1),[ge,pe]=(0,et.useState)(null),[_e,je]=(0,et.useState)(null),[ot,R]=(0,et.useState)(!1),[Se,ae]=(0,et.useState)(null),O=(0,et.useRef)(!0),xe=(0,et.useRef)(null),we=(0,et.useRef)(Se),Ue=(0,et.useRef)(de),Z=(0,et.useRef)(Y),at=(0,et.useRef)(fe),it=(0,et.useCallback)(u=>Ha(xe,async U=>{try{return await u(U)}catch(V){throw U.aborted?ia(V):V}}),[]);(0,et.useEffect)(()=>{we.current=Se},[Se]),(0,et.useEffect)(()=>{Ue.current=de},[de]),(0,et.useEffect)(()=>{Z.current=Y},[Y]),(0,et.useEffect)(()=>{at.current=fe},[fe]),(0,et.useEffect)(()=>(O.current=!0,()=>{O.current=!1,xe.current?.abort()}),[]),(0,et.useEffect)(()=>{if(typeof window>"u")return;let u=U=>{U.key==="Escape"&&ae(null)};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u)}},[]);let Fe=(0,et.useCallback)((u,U=aa)=>{at.current?.(ln(U,u,{code:u.code,declineCode:u.declineCode}))},[]),ke=(0,et.useCallback)(async u=>{O.current&&(je(null),R(u.result.status==="authorized"),pe("success"),await uc(600),O.current&&dt(()=>Ue.current?.(u)))},[]),Ze=(0,et.useCallback)(async(u,U)=>{O.current&&(Z.current?.(u),U?.emitDecline&&Fe(u,U.method),je(u.message),R(!1),pe("error"),await uc(400))},[Fe]),Pt=(0,et.useCallback)(async(u,U,V)=>{let w=u.data.session??null;if(!w)throw new tr.FloPayError("No session data returned","api_error");let X=w.clientSecret||t;if(Hr(w)){await ke({result:Or(w,U),session:w,sessionId:w.id||U,autoCompleted:!1});return}if(w.status==="expired")throw Ta(w);try{if(u.autoProcessingPending){let Pe=u.autoProcessingPending,st=new li.PaymentAPI(Le),tt=await it(_t=>st.waitForCheckoutSessionCompletion(Pe.sessionId,{initialDelayMs:Pe.retryAfterMs,nonce:X,statusUrl:Pe.statusUrl,signal:_t})),me=Zr(tt,w),pt=tt.autoProcessingError?.type==="3ds_required"&&tt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:tt.autoProcessingError.nextActionRedirectUrl}:null;if(pt&&U&&X){let _t=await it(Pn=>Eo(pt,{billingApiUrl:Le,sessionId:U,nonce:X,session:w,signal:Pn}));await ke({result:_t,session:w,sessionId:w.id||U,autoCompleted:!1});return}if(tt.autoProcessingError)throw Er(tt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:tt.autoProcessingError.checkoutMethod});if(!Hr(me))throw Po(me);await ke({result:Or(me,U),session:me,sessionId:me.id||U,autoCompleted:!1});return}if(u.autoProcessingError){let Pe=u.autoProcessingError.nextActionRedirectUrl;if(u.autoProcessingError.type==="3ds_required"&&Pe&&U&&X){let st=await it(_t=>$i({billingApiUrl:Le,sessionId:U,nonce:X,nextActionRedirectUrl:Pe,signal:_t}));if(st.status==="declined")throw Er({type:st.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:st.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:u.autoProcessingError.checkoutMethod});let me=await new li.PaymentAPI(Le).waitForCheckoutSessionCompletion(U,{initialDelayMs:0,nonce:X}),pt=Zr(me,w);if(!Hr(pt))throw Er({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:u.autoProcessingError.checkoutMethod});await ke({result:Or(pt,U),session:pt,sessionId:pt.id||U,autoCompleted:!1});return}throw Er(u.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:u.autoProcessingError.checkoutMethod})}if(V?.fromCreateSession&&u.autoProcessingAttempted===!0)throw Er({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let qe=await To({billingApiUrl:Le,sessionId:U??w.id,session:w,nonce:X});if(qe.type==="next_action_required"&&X){let Pe=U??w.id,st=await it(tt=>Eo(qe,{billingApiUrl:Le,sessionId:Pe,nonce:X,session:w,signal:tt}));await ke({result:st,session:w,sessionId:w.id||Pe,autoCompleted:!1});return}if(qe.type!=="success")throw Er({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await ke({result:qe.result,session:w,sessionId:w.id||U,autoCompleted:!1})}catch(qe){let Pe=sa(qe);if(Pe.code==="three_ds_aborted")return;let st=w.id||U;await Ze(Pe,{emitDecline:!0,method:Pe.checkoutMethod??aa}),Cu(Pe,st)&&st&&O.current&&ae({sessionId:st,errorMessage:Pe.message,nonce:X||void 0,payPalOrderId:Pe.orderId})}},[t,Le,it,Ze,ke]),Ke=(0,et.useCallback)(async u=>{if(te.onClick?.(u),!(u.defaultPrevented||ne||Re)){if(ae(null),e&&gt){let U=new tr.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Ze(U),O.current&&(pe(null),je(null));return}if(!e&&!gt){let U=new tr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Ze(U),O.current&&(pe(null),je(null));return}Oe(!0),je(null),R(!1),pe("processing");try{let U=new li.PaymentAPI(Le);if(e){let V=await U.getUnifiedCheckoutSession(e,t);await Pt(V,e);return}try{let V=await U.createAndFetchSession({...gt});await Pt(V,V.data.session?.id??null,{fromCreateSession:!0})}catch(V){if(Aa(V)==="session_auto_completed"){await ke({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw V}}catch(U){await Ze(vu(U,"Automatic payment failed. Please try again."))}finally{O.current&&(pe(null),je(null),Oe(!1))}}},[te.onClick,gt,ne,Re,t,Pt,Le,e,Ze,ke]),tn=(0,et.useCallback)(u=>{let U=we.current;ae(null),Ue.current?.({result:u,session:null,sessionId:U?.sessionId??null,autoCompleted:!1})},[]),qt=(0,et.useCallback)(u=>{Z.current?.(u)},[]),ut=(0,et.useCallback)(u=>{at.current?.(u)},[]),lt=(0,et.useMemo)(()=>(0,tr.resolveTheme)(re),[re]),z=(0,et.useMemo)(()=>{let u=lt?.buttonsLayout??(0,tr.resolveButtonsLayoutTheme)(G);return $?{...u,...$,cardButton:{...u.cardButton,...$.cardButton}}:u},[lt,G,$]),be=(0,et.useMemo)(()=>{let u=lt?.appearance;return T?u?{...u,...T,variables:{...u.variables,...T.variables}}:T:u},[T,lt]),Ve=be?.variables,W=Ve?.colorPrimary??"#4A49FF",Ge=Ve?.colorPrimaryHover??Mo(W,.12),wt=Ve?.borderRadius??"8px";return(0,gr.jsxs)(gr.Fragment,{children:[(0,gr.jsx)("button",{...te,type:$e,onClick:Ke,disabled:ne||Re,"aria-busy":Re,style:{width:"100%",...De===void 0?{boxSizing:"border-box",height:Pu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...z.cardButton,...as({themeBundle:lt,resolvedPrimaryColor:W,resolvedBorderRadius:wt,submitButtonStyle:z.submitButton,explicitPrimaryColor:Ve?.colorPrimary}),fontSize:z.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ne||Re?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ne||Re?.6:1,...ft},onMouseEnter:u=>{te.onMouseEnter?.(u),!u.defaultPrevented&&!ne&&!Re&&(lt||Ve?.colorPrimary)&&(u.currentTarget.style.backgroundColor=Ge)},onMouseLeave:u=>{te.onMouseLeave?.(u),!u.defaultPrevented&&(lt||Ve?.colorPrimary)&&(u.currentTarget.style.backgroundColor=W)},onMouseDown:u=>{te.onMouseDown?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(0.985)")},onMouseUp:u=>{te.onMouseUp?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(1)")},children:(0,gr.jsx)(go,{content:De})}),ge&&(0,gr.jsx)(er,{status:ge,errorMessage:_e,authorized:ot}),Se&&(0,gr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:u=>{u.target===u.currentTarget&&ae(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,gr.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,gr.jsx)(si,{sessionId:Se.sessionId,nonce:Se.nonce,checkoutMode:"full",billingApiUrl:Le,locale:N,theme:re,...be?{appearance:be}:{},buttonsTheme:G,buttonsStyles:$,initialErrorMessage:Se.errorMessage,initialPayPalOrderId:Se.payPalOrderId,cardTitleContent:null,onComplete:tn,onError:qt,onDecline:ut})})})]})}var ci=require("@flopay/js/card-setup"),jn=require("@flopay/shared"),Rt=require("react");var mc={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function yc(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?mc.dark:mc.light,a=t.colorText??(r?"#F1F5F9":"#262833"),l=e.appearance.rules?.[".Label"];return{panel:{...n.background===void 0?{}:{background:n.background},...n.backgroundColor===void 0?{}:{backgroundColor:n.backgroundColor},...n.border===void 0?{}:{border:n.border},...n.borderRadius===void 0?{}:{borderRadius:n.borderRadius},...n.boxShadow===void 0?{}:{boxShadow:n.boxShadow},color:a,...t.fontFamily?{fontFamily:t.fontFamily}:{}},spinnerTrackColor:e.buttonsLayout.cardInputBorder??(r?"#374151":"#e5e7eb"),spinnerAccentColor:t.colorPrimary??"#4A49FF",labelColors:{processing:a,success:o.success,error:o.error},noteColor:l?.color??a}}var xr=require("react/jsx-runtime"),ga=class extends jn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function fc(e,t={}){let n=e instanceof jn.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 ga(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 gc({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:l=null,onReady:d,onComplete:p,onDecline:f,onCancel:h,onValidation:b,onError:A}){let[k,S]=(0,Rt.useState)(null),[v,N]=(0,Rt.useState)(null),[re,T]=(0,Rt.useState)(null),[G,$]=(0,Rt.useState)(null),[de,Y]=(0,Rt.useState)(null),fe=(0,Rt.useRef)(!1),De=(0,Rt.useRef)(!1),ne=(0,Rt.useMemo)(()=>typeof o=="object"?void 0:(0,jn.resolveTheme)(o),[o]),$e=(0,Rt.useMemo)(()=>typeof o=="object"?o:ne?Ja({appearance:ne.appearance,buttonsStyles:ne.buttonsLayout,layout:"default"}):null,[ne,o]),ft=(0,Rt.useMemo)(()=>_l(ne?.buttonsLayout.cardFormContainer,a),[ne,a]),te=(0,Rt.useMemo)(()=>ne?yc(ne):void 0,[ne]),Le=(0,Rt.useRef)(d),gt=(0,Rt.useRef)(A),Re=(0,Rt.useRef)(p),Oe=(0,Rt.useRef)(f),ge=(0,Rt.useRef)(h),pe=(0,Rt.useRef)(b),_e=(0,Rt.useRef)(!1),je=(0,Rt.useRef)(!1),ot=(0,Rt.useRef)(0);return Le.current=d,gt.current=A,Re.current=p,Oe.current=f,ge.current=h,pe.current=b,(0,Rt.useEffect)(()=>{let R=ot.current+1;return ot.current=R,()=>{queueMicrotask(()=>{ot.current===R&&(_e.current||je.current||(je.current=!0,dt(()=>{ge.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Rt.useEffect)(()=>{let R=!0,Se=new ci.PaymentAPI((0,jn.resolveBillingApiUrl)(n),{telemetry:r});return S(null),N(null),T(null),_e.current=!1,je.current=!1,(async()=>{try{if(!e.trim())throw new jn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new jn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ae=await Se.getUnifiedCheckoutSession(e,t);if(!R)return;let O=ae.data.session;if(!O||!(0,jn.isCardSetupCheckoutSession)(O))throw new jn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let xe=O.vault;if(xe?.html?.trim()||(xe=await Se.getVaultCapture(e,t)),!xe.html?.trim())throw new jn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!R)return;N(xe),S(new ci.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(ae){if(!R)return;let O=fc(ae);_e.current=!0,T(O),dt(()=>gt.current?.(O))}})(),()=>{R=!1,Se.destroy()}},[n,t,e,r]),(0,Rt.useEffect)(()=>{if(!k)return;let R=!1;De.current=!1,fe.current=!1;let Se=k.on("submitting",()=>{fe.current=!0,Y(null),$("processing")}),ae=k.on("complete",we=>{_e.current=!0,fe.current=!1,$("success"),(async()=>(await new Promise(Ue=>setTimeout(Ue,600)),!De.current&&(De.current=!0,dt(()=>{Re.current?.({status:"succeeded",sessionId:e,...we.paymentMethod?{paymentMethod:we.paymentMethod}:{}})}),R||$(null))))()}),O=k.on("decline",we=>{_e.current=!0,fe.current=!1,Y(we.message??null),$("error"),dt(()=>{Oe.current?.({status:"declined",sessionId:e,...we.declineReason?{reason:we.declineReason}:{},...we.message?{message:we.message}:{}})}),(async()=>(await new Promise(Ue=>setTimeout(Ue,400)),R||$(null)))()}),xe=k.on("challenge_dismissed",()=>{$(null)});return()=>{R=!0,Se(),ae(),O(),xe()}},[k,e]),re?(0,xr.jsx)("div",{role:"alert",children:re.message}):!k||!v?.html?(0,xr.jsx)(xr.Fragment,{children:l}):(0,xr.jsxs)(xr.Fragment,{children:[G&&(0,xr.jsx)(er,{status:G,errorMessage:de,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...te?{theme:te}:{}}),(0,xr.jsx)(xo,{capture:k,html:v.html,messageToken:v.messageToken,expectedOrigin:v.expectedOrigin,theme:$e,containerStyle:ft,onReady:()=>{dt(()=>Le.current?.())},onValidation:R=>{dt(()=>pe.current?.(R))},onError:R=>{if(!R)return;fe.current&&(fe.current=!1,Y(R),$("error"),setTimeout(()=>$(null),400));let Se=fc(new Error(R),{code:"card_setup_widget_failed",retryable:!0});dt(()=>gt.current?.(Se))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,x.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&O(Fo),n&&(r||o)&&O(Fo),n&&(0,x.jsx)("button",{type:"button",onClick:()=>{e?.("card"),M(!0)},style:{width:"100%",...G,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:T=>{T.currentTarget.style.transform="scale(0.985)"},onMouseUp:T=>{T.currentTarget.style.transform="scale(1)"},children:(0,x.jsx)(ho,{content:u})}),(0,x.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var tr=require("react/jsx-runtime"),Pu=44;function uc(e){return new Promise(t=>setTimeout(t,e))}function vu(e,t){return e instanceof nr.FloPayError?e:new nr.FloPayError(e instanceof Error?e.message:t,"api_error")}function Cu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Su(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 pc({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:d,subscriptions:u,account:p,successUrl:b,cancelUrl:v,couponCodes:M,tagsData:I,utmMetadata:w,billingApiUrl:h,locale:O,theme:G,appearance:T,buttonsTheme:Y,buttonsStyles:U,onSuccess:de,onError:X,onDecline:he,children:De,disabled:re=!1,type:Ve="button",style:yt,...te}){let Oe=(0,Qe.useMemo)(()=>(0,nr.resolveBillingApiUrl)(h),[h]),ft=(0,Qe.useMemo)(()=>Su({createSession:n,clientId:a,products:l,items:d,subscriptions:u,account:p,successUrl:b,cancelUrl:v,couponCodes:M,tagsData:I,utmMetadata:w}),[p,v,a,M,n,l,d,u,b,I,w]),[ke,Le]=(0,Qe.useState)(!1),[be,me]=(0,Qe.useState)(null),[Ie,We]=(0,Qe.useState)(null),[rt,R]=(0,Qe.useState)(!1),[He,ye]=(0,Qe.useState)(null),[N,ve]=(0,Qe.useState)(null),ue=(0,Qe.useRef)(!0),Ke=(0,Qe.useRef)(null),Z=(0,Qe.useRef)(N),ot=(0,Qe.useRef)(de),lt=(0,Qe.useRef)(X),Ae=(0,Qe.useRef)(he),Ne=(0,Qe.useCallback)(f=>Ha(Ke,async P=>{try{return await f(P)}catch(H){throw P.aborted?Xr(H):H}}),[]);(0,Qe.useEffect)(()=>{Z.current=N},[N]),(0,Qe.useEffect)(()=>{ot.current=de},[de]),(0,Qe.useEffect)(()=>{lt.current=X},[X]),(0,Qe.useEffect)(()=>{Ae.current=he},[he]),(0,Qe.useEffect)(()=>(ue.current=!0,()=>{ue.current=!1,Ke.current?.abort()}),[]),(0,Qe.useEffect)(()=>{if(typeof window>"u")return;let f=P=>{P.key==="Escape"&&ve(null)};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f)}},[]);let ct=(0,Qe.useCallback)((f,P=ia)=>{Ae.current?.(cn(P,f,{code:f.code,declineCode:f.declineCode}))},[]),at=(0,Qe.useCallback)(async f=>{ue.current&&(We(null),R(f.result.status==="authorized"),me("success"),await uc(600),ue.current&&st(()=>ot.current?.(f)))},[]),xe=(0,Qe.useCallback)(async(f,P)=>{ue.current&&(lt.current?.(f),P?.emitDecline&&ct(f,P.method),We(f.message),R(!1),me("error"),await uc(400))},[ct]),jt=(0,Qe.useCallback)(async(f,P,H)=>{let ne=f.data.session??null;if(!ne)throw new nr.FloPayError("No session data returned","api_error");let $e=ne.clientSecret||t;if(Nr(ne)){await at({result:Lr(ne,P),session:ne,sessionId:ne.id||P,autoCompleted:!1});return}if(ne.status==="expired")throw Ta(ne);try{if(f.autoProcessingPending){let Re=f.autoProcessingPending,ae=new li.PaymentAPI(Oe),it=await Ne(ze=>ae.waitForCheckoutSessionCompletion(Re.sessionId,{initialDelayMs:Re.retryAfterMs,nonce:$e,statusUrl:Re.statusUrl,signal:ze})),Ct=Kr(it,ne),Nt=it.autoProcessingError?.type==="3ds_required"&&it.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:it.autoProcessingError.nextActionRedirectUrl}:null;if(Nt&&P&&$e){let ze=await Ne(Ft=>To(Nt,{billingApiUrl:Oe,sessionId:P,nonce:$e,session:ne,signal:Ft,telemetry:!0}));await at({result:ze,session:ne,sessionId:ne.id||P,autoCompleted:!1});return}if(it.autoProcessingError)throw Er(it.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:it.autoProcessingError.checkoutMethod});if(!Nr(Ct))throw vo(Ct);await at({result:Lr(Ct,P),session:Ct,sessionId:Ct.id||P,autoCompleted:!1});return}if(f.autoProcessingError){let Re=f.autoProcessingError.nextActionRedirectUrl;if(f.autoProcessingError.type==="3ds_required"&&Re&&P&&$e){let ae=await Ne(ze=>ji({billingApiUrl:Oe,sessionId:P,nonce:$e,nextActionRedirectUrl:Re,signal:ze}));if(ae.status==="declined")throw Er({type:ae.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:ae.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:f.autoProcessingError.checkoutMethod});let Ct=await new li.PaymentAPI(Oe).waitForCheckoutSessionCompletion(P,{initialDelayMs:0,nonce:$e}),Nt=Kr(Ct,ne);if(!Nr(Nt))throw Er({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:f.autoProcessingError.checkoutMethod});await at({result:Lr(Nt,P),session:Nt,sessionId:Nt.id||P,autoCompleted:!1});return}throw Er(f.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:f.autoProcessingError.checkoutMethod})}if(H?.fromCreateSession&&f.autoProcessingAttempted===!0)throw Er({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let vt=await Ao({billingApiUrl:Oe,sessionId:P??ne.id,session:ne,nonce:$e});if(vt.type==="next_action_required"&&$e){let Re=P??ne.id,ae=await Ne(it=>To(vt,{billingApiUrl:Oe,sessionId:Re,nonce:$e,session:ne,signal:it,telemetry:!0}));await at({result:ae,session:ne,sessionId:ne.id||Re,autoCompleted:!1});return}if(vt.type!=="success")throw Er({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await at({result:vt.result,session:ne,sessionId:ne.id||P,autoCompleted:!1})}catch(vt){let Re=sa(vt);if(Re.code==="three_ds_aborted")return;if(Re.code==="checkout_processing_timeout"){if(!ue.current)return;ye(Re.message),st(()=>lt.current?.(Re));return}let ae=ne.id||P;await xe(Re,{emitDecline:!0,method:Re.checkoutMethod??ia}),Cu(Re,ae)&&ae&&ue.current&&ve({sessionId:ae,errorMessage:Re.message,nonce:$e||void 0,payPalOrderId:Re.orderId})}},[t,Oe,Ne,xe,at]),Vt=(0,Qe.useCallback)(async f=>{if(te.onClick?.(f),!(f.defaultPrevented||re||ke)){if(ve(null),ye(null),e&&ft){let P=new nr.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await xe(P),ue.current&&(me(null),We(null));return}if(!e&&!ft){let P=new nr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await xe(P),ue.current&&(me(null),We(null));return}Le(!0),We(null),R(!1),me("processing");try{let P=new li.PaymentAPI(Oe);if(e){let H=await P.getUnifiedCheckoutSession(e,t);await jt(H,e);return}try{let H=await P.createAndFetchSession({...ft});await jt(H,H.data.session?.id??null,{fromCreateSession:!0})}catch(H){if(Aa(H)==="session_auto_completed"){await at({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw H}}catch(P){await xe(vu(P,"Automatic payment failed. Please try again."))}finally{ue.current&&(me(null),We(null),Le(!1))}}},[te.onClick,ft,re,ke,t,jt,Oe,e,xe,at]),ut=(0,Qe.useCallback)(f=>{let P=Z.current;ve(null),ot.current?.({result:f,session:null,sessionId:P?.sessionId??null,autoCompleted:!1})},[]),Et=(0,Qe.useCallback)(f=>{lt.current?.(f)},[]),q=(0,Qe.useCallback)(f=>{Ae.current?.(f)},[]),fe=(0,Qe.useMemo)(()=>(0,nr.resolveTheme)(G),[G]),et=(0,Qe.useMemo)(()=>{let f=fe?.buttonsLayout??(0,nr.resolveButtonsLayoutTheme)(Y);return U?{...f,...U,cardButton:{...f.cardButton,...U.cardButton}}:f},[fe,Y,U]),V=(0,Qe.useMemo)(()=>{let f=fe?.appearance;return T?f?{...f,...T,variables:{...f.variables,...T.variables}}:T:f},[T,fe]),Me=V?.variables,bt=Me?.colorPrimary??"#4A49FF",Ge=Me?.colorPrimaryHover??Bo(bt,.12),$=Me?.borderRadius??"8px";return(0,tr.jsxs)(tr.Fragment,{children:[(0,tr.jsx)("button",{...te,type:Ve,onClick:Vt,disabled:re||ke,"aria-busy":ke,style:{width:"100%",...De===void 0?{boxSizing:"border-box",height:Pu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...et.cardButton,...is({themeBundle:fe,resolvedPrimaryColor:bt,resolvedBorderRadius:$,submitButtonStyle:et.submitButton,explicitPrimaryColor:Me?.colorPrimary}),fontSize:et.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:re||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:re||ke?.6:1,...yt},onMouseEnter:f=>{te.onMouseEnter?.(f),!f.defaultPrevented&&!re&&!ke&&(fe||Me?.colorPrimary)&&(f.currentTarget.style.backgroundColor=Ge)},onMouseLeave:f=>{te.onMouseLeave?.(f),!f.defaultPrevented&&(fe||Me?.colorPrimary)&&(f.currentTarget.style.backgroundColor=bt)},onMouseDown:f=>{te.onMouseDown?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(0.985)")},onMouseUp:f=>{te.onMouseUp?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(1)")},children:(0,tr.jsx)(ho,{content:De})}),He&&(0,tr.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:He}),be&&(0,tr.jsx)(er,{status:be,errorMessage:Ie,authorized:rt}),N&&(0,tr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:f=>{f.target===f.currentTarget&&ve(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,tr.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,tr.jsx)(si,{sessionId:N.sessionId,nonce:N.nonce,checkoutMode:"full",billingApiUrl:Oe,locale:O,theme:G,...V?{appearance:V}:{},buttonsTheme:Y,buttonsStyles:U,initialErrorMessage:N.errorMessage,initialPayPalOrderId:N.payPalOrderId,cardTitleContent:null,onComplete:ut,onError:Et,onDecline:q})})})]})}var ci=require("@flopay/js/card-setup"),jn=require("@flopay/shared"),_t=require("react");var mc={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function yc(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?mc.dark:mc.light,a=t.colorText??(r?"#F1F5F9":"#262833"),l=e.appearance.rules?.[".Label"];return{panel:{...n.background===void 0?{}:{background:n.background},...n.backgroundColor===void 0?{}:{backgroundColor:n.backgroundColor},...n.border===void 0?{}:{border:n.border},...n.borderRadius===void 0?{}:{borderRadius:n.borderRadius},...n.boxShadow===void 0?{}:{boxShadow:n.boxShadow},color:a,...t.fontFamily?{fontFamily:t.fontFamily}:{}},spinnerTrackColor:e.buttonsLayout.cardInputBorder??(r?"#374151":"#e5e7eb"),spinnerAccentColor:t.colorPrimary??"#4A49FF",labelColors:{processing:a,success:o.success,error:o.error},noteColor:l?.color??a}}var xr=require("react/jsx-runtime"),ga=class extends jn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function fc(e,t={}){let n=e instanceof jn.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 ga(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 gc({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:l=null,onReady:d,onComplete:u,onDecline:p,onCancel:b,onValidation:v,onError:M}){let[I,w]=(0,_t.useState)(null),[h,O]=(0,_t.useState)(null),[G,T]=(0,_t.useState)(null),[Y,U]=(0,_t.useState)(null),[de,X]=(0,_t.useState)(null),he=(0,_t.useRef)(!1),De=(0,_t.useRef)(!1),re=(0,_t.useMemo)(()=>typeof o=="object"?void 0:(0,jn.resolveTheme)(o),[o]),Ve=(0,_t.useMemo)(()=>typeof o=="object"?o:re?Ja({appearance:re.appearance,buttonsStyles:re.buttonsLayout,layout:"default"}):null,[re,o]),yt=(0,_t.useMemo)(()=>_l(re?.buttonsLayout.cardFormContainer,a),[re,a]),te=(0,_t.useMemo)(()=>re?yc(re):void 0,[re]),Oe=(0,_t.useRef)(d),ft=(0,_t.useRef)(M),ke=(0,_t.useRef)(u),Le=(0,_t.useRef)(p),be=(0,_t.useRef)(b),me=(0,_t.useRef)(v),Ie=(0,_t.useRef)(!1),We=(0,_t.useRef)(!1),rt=(0,_t.useRef)(0);return Oe.current=d,ft.current=M,ke.current=u,Le.current=p,be.current=b,me.current=v,(0,_t.useEffect)(()=>{let R=rt.current+1;return rt.current=R,()=>{queueMicrotask(()=>{rt.current===R&&(Ie.current||We.current||(We.current=!0,st(()=>{be.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,_t.useEffect)(()=>{let R=!0,He=new ci.PaymentAPI((0,jn.resolveBillingApiUrl)(n),{telemetry:r});return w(null),O(null),T(null),Ie.current=!1,We.current=!1,(async()=>{try{if(!e.trim())throw new jn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new jn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ye=await He.getUnifiedCheckoutSession(e,t);if(!R)return;let N=ye.data.session;if(!N||!(0,jn.isCardSetupCheckoutSession)(N))throw new jn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let ve=N.vault;if(ve?.html?.trim()||(ve=await He.getVaultCapture(e,t)),!ve.html?.trim())throw new jn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!R)return;O(ve),w(new ci.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(ye){if(!R)return;let N=fc(ye);Ie.current=!0,T(N),st(()=>ft.current?.(N))}})(),()=>{R=!1,He.destroy()}},[n,t,e,r]),(0,_t.useEffect)(()=>{if(!I)return;let R=!1;De.current=!1,he.current=!1;let He=I.on("submitting",()=>{he.current=!0,X(null),U("processing")}),ye=I.on("complete",ue=>{Ie.current=!0,he.current=!1,U("success"),(async()=>(await new Promise(Ke=>setTimeout(Ke,600)),!De.current&&(De.current=!0,st(()=>{ke.current?.({status:"succeeded",sessionId:e,...ue.paymentMethod?{paymentMethod:ue.paymentMethod}:{}})}),R||U(null))))()}),N=I.on("decline",ue=>{Ie.current=!0,he.current=!1,X(ue.message??null),U("error"),st(()=>{Le.current?.({status:"declined",sessionId:e,...ue.declineReason?{reason:ue.declineReason}:{},...ue.message?{message:ue.message}:{}})}),(async()=>(await new Promise(Ke=>setTimeout(Ke,400)),R||U(null)))()}),ve=I.on("challenge_dismissed",()=>{U(null)});return()=>{R=!0,He(),ye(),N(),ve()}},[I,e]),G?(0,xr.jsx)("div",{role:"alert",children:G.message}):!I||!h?.html?(0,xr.jsx)(xr.Fragment,{children:l}):(0,xr.jsxs)(xr.Fragment,{children:[Y&&(0,xr.jsx)(er,{status:Y,errorMessage:de,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...te?{theme:te}:{}}),(0,xr.jsx)(Mo,{capture:I,html:h.html,messageToken:h.messageToken,expectedOrigin:h.expectedOrigin,theme:Ve,containerStyle:yt,onReady:()=>{st(()=>Oe.current?.())},onValidation:R=>{st(()=>me.current?.(R))},onError:R=>{if(!R)return;he.current&&(he.current=!1,X(R),U("error"),setTimeout(()=>U(null),400));let He=fc(new Error(R),{code:"card_setup_widget_failed",retryable:!0});st(()=>ft.current?.(He))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});