@flopay/react 1.9.30 → 1.10.0

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 Oc=Object.create;var Ta=Object.defineProperty;var Lc=Object.getOwnPropertyDescriptor;var Nc=Object.getOwnPropertyNames;var zc=Object.getPrototypeOf,Uc=Object.prototype.hasOwnProperty;var qc=(e,t)=>{for(var n in t)Ta(e,n,{get:t[n],enumerable:!0})},Js=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Nc(t))!Uc.call(e,o)&&o!==n&&Ta(e,o,{get:()=>t[o],enumerable:!(r=Lc(t,o))||r.enumerable});return e};var Zs=(e,t,n)=>(n=e!=null?Oc(zc(e)):{},Js(t||!e||!e.__esModule?Ta(n,"default",{value:e,enumerable:!0}):n,e)),$c=e=>Js(Ta({},"__esModule",{value:!0}),e);var ku={};qc(ku,{DirectPayPalButton:()=>ra,FloPayAutomaticPaymentButton:()=>mc,FloPayCardSetup:()=>hc,FloPayCardSetupError:()=>ha,FloPayCheckout:()=>li,FloPayProvider:()=>aa,SplitCardForm:()=>oi,VaultCardFields:()=>Bo,dropThirdPartyOnlyError:()=>bc.dropThirdPartyOnlyError,useCheckout:()=>ul,useFloPay:()=>Ur,usePayPalFloPay:()=>Fa});module.exports=$c(ku);var bc=require("@flopay/shared");var ci=require("@flopay/js"),nr=require("@flopay/shared"),Qe=require("react");var Lt=require("react/jsx-runtime");function jc(){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 Vc(){return(0,Lt.jsx)(Lt.Fragment,{children:"Go back"})}function Wc(){return(0,Lt.jsx)(Lt.Fragment,{children:"Secure card checkout"})}function ho(e){return e!==void 0&&(e===""||e===null||e===!1)}function bo({content:e}){return(0,Lt.jsx)(Lt.Fragment,{children:e===void 0?(0,Lt.jsx)(jc,{}):e})}function Po({content:e}){return(0,Lt.jsx)(Lt.Fragment,{children:e===void 0?(0,Lt.jsx)(Vc,{}):e})}function Yo({content:e}){return(0,Lt.jsx)(Lt.Fragment,{children:e===void 0?(0,Lt.jsx)(Wc,{}):e})}var Pt=require("@flopay/shared"),Hc="Checkout is temporarily unavailable. Please try again later.";function Ei(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 Kc(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 Qs(){return new Pt.FloPayError(Hc,"api_error",{code:"CheckoutInitializationFailed"})}function Ti(e){return!!e?.gateways?.worldpayCorporateGateway}function Wr(e){return e?.status==="open"&&Ti(e)}function el(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 tl(e,t){if(t&&(!(e instanceof Pt.FloPayError)||e.type==="authentication_error"))return Ei(e);if(!(e instanceof Pt.FloPayError&&Kc(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 vo(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 nl(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 Ai(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 rl(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 to(e){if((0,Pt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function xi(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,l=typeof t=="string"?void 0:t.sessionId;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{},...l?{sessionId:l}:{}}}function Hr(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var Gc=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Kr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Gc)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 Gr(e,t){if(e.data.session)return e.data.session;let n=e.raw,r=n?.latestTransactionAttempt?.result,o=n?.status==="authorized"||r==="AUTHORIZED";return o||n?.status==="completed"||r==="SUCCESS"?{...t,status:o?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function ol(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Aa(e){let t=ol(e);return new Pt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function xa(e){return e instanceof Pt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Co(e){return ol(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 Xo(e,t){return e==="processing"||(0,Pt.isMoneySettledOutcome)(e,t)}function al(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function il(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 sl(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 Mi(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 Jo(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=Zs(require("react"),1);var Bi=require("react"),Zn=(0,Bi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),pr=(0,Bi.createContext)({session:null,loading:!1,error:null});var za=require("@flopay/js"),qt=require("@flopay/shared"),hl=require("@paypal/paypal-js"),k=require("react");var ll=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 So(){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 wo({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,ll.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 Yc=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),Xc=["https://www.paypal.com","https://www.sandbox.paypal.com"];function Ma(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 cl(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 no(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 no(t.code)??no(t.type)??no(t.name)}function ko(e){if(!(typeof e!="object"||e===null))return no(e.decline_code)}function Zo(e){return typeof e!="object"||e===null?!1:no(e.type)?.toLowerCase()==="card_error"||ko(e)!==void 0}function Jc(e){let t=cl(e)?.toLowerCase()??"",n=_r(e)?.toLowerCase()??"";return Yc.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 Fi(e){if(_r(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=cl(e)??"";return n.includes("No ack for postMessage init()")&&Xc.some(r=>n.includes(r))&&n.includes("10000ms")}function Ba(e,t){if(Zo(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=Jc(e)||t.inAppBrowser&&!t.handoffObserved&&Fi(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function Yr(e){return Ba(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}var dl=require("@flopay/shared"),Qo=require("react");function Ur(){return(0,Qo.useContext)(Zn).flopay}function Fa(){return(0,Qo.useContext)(Zn).paypalFlopay??null}function ul(){return(0,Qo.useContext)(pr)}function pl(){return(0,Qo.useContext)(Zn).billingApiUrl||(0,dl.resolveBillingApiUrl)()}function ea(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 ml(e,t,n=e.popupCapability){return e.inAppBrowser||n==="blocked"||t==="prefer_redirect"?"redirect":"popup"}function Da(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var yl=require("@flopay/shared"),oo=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 Oa=require("react"),ro=typeof window>"u"?Oa.useEffect:Oa.useLayoutEffect;var Zc={"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 Qc(e){return e==="stripe"||e==="paypal"?e:void 0}function ed(e){let t=Qc(e.provider),n={schemaVersion:yl.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Zc[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 Di=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Io(e,t){let n=(0,oo.useRef)(e);n.current=e;let r=(0,oo.useRef)(new Set),o=(0,oo.useRef)(t),a=(0,oo.useRef)(t);return ro(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,oo.useCallback)(l=>{if(a.current!==t)return;let d=ed(l);if(d){if(Di.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}st(()=>n.current?.(d))}},[t])}var fl=require("react"),ta=(0,fl.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 td=Symbol.for("@flopay/js.telemetry.bridge.v1"),nd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function rd(){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 od(e){let t=rd(),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 Na(e){let t=globalThis[nd];return od(t?.(e)??{})}function dn(e){if(e)return e[td]}var un=require("react");function na(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),[]),B=(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:B,generationRef:n}}var Qn=require("react/jsx-runtime"),Ua=45,ad=1e3,id=11e3,sd={width:"100%",minHeight:Ua,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},ld={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 cd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:ld[e.kind]??null}}function gl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Fi(t)?"paypal_init_timeout":"paypal_init_failure"}function dd(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 ud(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function bl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:d,currency:u,isSubscription:p,providerObjectType:b,approvalPresentation:v,onTokenizedBody:B,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:Fe,telemetry:oe,telemetryContext:je,onInstrument:yt,debug:re=!1}){let De=Ur(),ft=Io(yt,e),ke=(0,k.useMemo)(()=>{if(De)return null;let F=Na({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:qt.SDK_VERSION,enabled:oe!==!1});return F.setCheckoutContext(je??{}),F.beginCheckout(je??{}),F},[n,De,oe,je?.checkoutMode,je?.layout]),Oe=(0,k.useMemo)(()=>dn(De),[De]);(0,k.useEffect)(()=>()=>{ke&&ke.flush().catch(()=>{}).finally(()=>ke.destroy())},[ke]);let be=(0,k.useMemo)(()=>({error:F=>{Oe?Oe.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=>{Oe?Oe.log(F):ke?.log(F),ft({class:"lifecycle",name:F.name,provider:F.provider})},performance:F=>{Oe?Oe.performance(F):ke?.performance(F)},terminal:F=>{Oe?Oe.terminal(F):ke?.terminal(F)},startTiming:()=>Oe?.now()??ke?.now()??0,elapsed:F=>Oe?.elapsed(F)??Math.max(0,(ke?.now()??F)-F)}),[ft,Oe,ke]),me=(0,k.useRef)(null),Ie=(0,k.useRef)(0),Ve=(0,k.useRef)(null),rt=(0,k.useRef)(null),R=(0,k.useRef)(null),We=(0,k.useContext)(ta),ye=(0,k.useRef)(null);ye.current||(ye.current=La());let N=We??ye.current,ve=(0,k.useRef)(null),ue=(0,k.useRef)(!1),[He,Q]=(0,k.useState)(!1),[ot,lt]=(0,k.useState)(!1),[Te,Le]=(0,k.useState)(0),ct=(0,k.useRef)(0),[at,Ae]=(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:xe}=So(),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 Ke=bt.current.required,$=(0,k.useMemo)(()=>n.replace(/\/+$/,""),[n]),f=he?.gateways?.paypal?.providerObjectType??b,P=f??(p?"subscription":"order"),[H]=(0,k.useState)(ea),ee=he?.gateways?.paypal?.approvalPresentation??v,qe=Da(H,ee==="app_switch"?"app_switch":void 0,P),vt=f==="order"||f==="setup_token",Ge=(0,k.useMemo)(()=>JSON.stringify([$,l,u,d??"",P,vt,qe,e,Fe??""]),[$,l,u,d,Fe,P,vt,qe,e]),Z=(0,k.useRef)(Ge),it=Z.current!==Ge,Ct=(0,k.useRef)(re),Nt=(0,k.useRef)(null),[Ne,Ft]=(0,k.useState)([]),ze=(0,k.useCallback)(F=>{Ct.current&&Ft(Ze=>[...Ze,`${new Date().toISOString().slice(11,23)} ${F}`])},[]);(0,k.useEffect)(()=>{Ct.current=re,re&&ze("debug:enabled"),Nt.current?.setEnabled(re)},[ze,re]);let Fn=(0,k.useRef)(B),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=B},[B]),(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=Te},[Te]),(0,k.useEffect)(()=>{at&&ve.current?.focus()},[at,Te]);let wt=(0,k.useCallback)(()=>{window.setTimeout(()=>{ve.current?.focus()},0)},[]),Zt=(0,k.useCallback)(()=>{Q(!1),Le(F=>F+1)},[]),yn=(0,k.useCallback)(()=>{Ae(!1),(me.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??me.current)?.focus?.()},[]);(0,k.useEffect)(()=>{!He||!ue.current||(ue.current=!1,yn())},[yn,He,Te]);let Dt=(0,k.useCallback)((F,Ze)=>{let se=Ze?.popupBlocked??Yr(F);se&&N.markBlocked();let Hn=Ma("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=Ve.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}),Ve.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:qe,terminalReason:"overlay_timeout"}),Ae(!0),Zt(),wt()},[Qt,wt,Dt,N,qe,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:te,invalidateAttempt:Ln,isAttemptCurrent:Nn,isAttemptInvalidated:hr,startAttempt:Cn}=na(Ht,{onHandoffObserved:fn}),sn=(0,k.useCallback)(()=>(Ae(!1),Cn("paypal")),[Cn]),_n=(0,k.useCallback)(F=>{Ln(F?.generation),F?.showRetry&&Ae(!0),F?.remount&&Zt(),F?.focus!==!1&&wt()},[wt,Ln,Zt]),Re=F=>{let Ze=Wt.current;return Ze&&Wn.current.set(F,Ze),F};(0,k.useEffect)(()=>{Z.current!==Ge&&(Z.current=Ge,jt.current=!1,Vt.current=!1,Q(!1),lt(!1),Et(!1),Ce.current?.("loading"))},[Ge]),(0,k.useEffect)(()=>{st(()=>rn.current?.(He&&!ut))},[He,ut]);let ht=(0,qt.normalizeGatewayEnvironment)(d);(0,k.useEffect)(()=>{let F={attempt:te.current+1,inAppBrowser:H.inAppBrowser,appFamily:H.appFamily,popupCapability:N.current(),presentationMode:qe},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(ze(`mount clientId=${Hn} env=${d??"(unset)"}\u2192${ht??"live"} ccy=${u} sub=${p}`),ze(`ua=${gn.slice(0,80)}${gn.length>80?"\u2026":""}`),!l){ze("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){ze("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"))&&(ze(`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"))&&(ze(`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);ze(`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=Kr(m)??m;st(()=>Mt.current?.(g))},x=(m,g)=>{if(Kt||Br)return;Br=!0,Kn=!0,bn(),br();let D=cd({kind:m,generationActive:!0,automaticRetryAllowed:U,automaticRetryUsed:jt.current});if(D.action==="retry"){jt.current=!0,Q(!1),fe(!1),lt(!0),Ce.current?.("retrying"),Mr=setTimeout(()=>{Kt||Le(z=>z+1)},ad);return}if(Q(!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=Ba({code:gl(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:",gl(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 za.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),ae=j?.message??"PayPal payment failed.",_=Kr(ae)??ae;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:ud(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=Kr(Ye)??Ye;In(It),st(()=>wn.current?.(cn("paypal",It)));return}},A=()=>new qt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),le=m=>nt()?Promise.reject(A()):Promise.resolve(m),Me=async m=>{if(nt())throw A();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 za.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 A();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=ko(m)??_r(m)??"provider_declined";new za.PaymentAPI($,{telemetry:!1}).reportSessionIntentDecline(z,D,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ce}).catch(()=>{})},pe=Te;ze("loadScript:scheduled (deferred 1 tick)");let Be=null,W=setTimeout(()=>{if(Kt){ze("loadScript:skipped (cancelled before defer ran)");return}ze("loadScript:start");let m=ht==="live"?"production":ht,g={};P==="subscription"?g={intent:"subscription",vault:!0}:P==="order"&&(g={intent:"capture"}),Be=(0,hl.loadScript)({clientId:l,currency:u,...g,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let D=!1;Be.then(z=>{if(D=!0,ze(`loadScript:resolved inactive=${nt()} ns=${!!z} buttons=${!!z?.Buttons}`),nt())return;if(!z?.Buttons){ze("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(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 ae=ge.vaultSetupToken??ge.subscriptionID??ge.orderID??"",_=ae?Wn.current.get(ae):an.current.get(pe);if(!(!_||!Nn(_.generation))&&gt(_.generation)){Wn.current.delete(ae),an.current.delete(_.surfaceKey),Qt("approved");try{if(fe(!0),st(()=>Mt.current?.(null)),!ae)throw new qt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ue=vn.current,Rt=to(Vn.current??[Ue?.customer?.firstName,Ue?.customer?.lastName].filter(Boolean).join(" ")),_e=Bn({email:_.accountPatch?.email?.trim()||Bt.current?.trim()||Ue?.customer?.email?.trim(),firstName:_.accountPatch?.firstName?.trim()||Rt.firstName,lastName:_.accountPatch?.lastName?.trim()||Rt.lastName});if(!(0,qt.isValidEmail)(_e.email)||!(_e.firstName||_e.lastName))try{let Sr=dd(await j?.order?.get?.());_e=Bn({email:Sr.email||_e.email,firstName:Sr.firstName||_e.firstName,lastName:Sr.lastName||_e.lastName})}catch{}if((St.current||Ke)&&!(0,qt.isValidEmail)(_e.email)){let Sr=await V("PayPal",_e);if(!Sr)return;_e=Sr}(0,qt.isValidEmail)(_e.email)&&(_.accountPatch=Bn({..._.accountPatch,..._e}),await St.current?.(_e));let Sn;P==="setup_token"?Sn={id:ae,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:qt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:vt?Sn={id:ae,isPaypal:!0,gateway:"paypal",paymentMethodType:qt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Sn={id:ae,isPaypal:!0},await L(Sn,_)}catch(Ue){In(Ue instanceof Error?Ue.message:"PayPal capture failed.")}finally{nt()||fe(!1)}}},J=ge=>{let j=Fe?()=>le(Fe):()=>Me(ge);return async()=>Re(await j())},Ye=z.Buttons({style:{layout:"horizontal",height:Ua,tagline:!1},...qe==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ge,j)=>{if(nt()){await j.reject();return}hn();let ae=Tt.current,_={};if(ae)try{let _e=await ae("paypal");if(nt()){await j.reject();return}if(!_e.proceed){Wt.current=null,an.current.delete(pe),await j.reject();return}_={sessionId:_e.sessionId,accountPatch:_e.accountPatch,nonce:_e.nonce}}catch(_e){ze(`onClick:runBeforeButtonClick rejected msg=${(_e instanceof Error?_e.message:String(_e)).slice(0,120)}`),Wt.current=null,an.current.delete(pe),await j.reject();return}st(()=>On.current?.("paypal"));let Ue=sn(),Rt={generation:Ue,surfaceKey:pe,..._};Wt.current=Rt,an.current.set(pe,Rt),rt.current={...F,attempt:Ue},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"}),Ve.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()=>Re(await Me("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(ze(`onError rendered=${Tn} msg=${j.slice(0,120)}`),Tn){let ae=an.current.get(pe)??Wt.current;if(ae&&!Nn(ae.generation)||!ae&&hr())return;if(Or(j)){gt(ae?.generation);return}let{errorCode:_,popupBlocked:Ue,providerDeclined:Rt,terminalReason:_e}=Ba(ge,{inAppBrowser:H.inAppBrowser,handoffObserved:ae!=null&&R.current===ae.generation});if(Ue&&N.markBlocked(),Qt(_e),Rt){se.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:_e}),pt(ge,ae),st(()=>wn.current?.(cn("paypal",j))),ae&&an.current.delete(ae.surfaceKey),Wt.current=null,gt(ae?.generation);return}se.error({errorCode:_,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:_e}),ae&&an.current.delete(ae.surfaceKey),Wt.current=null,_n({generation:ae?.generation,remount:!0,showRetry:!0,focus:!0}),Dt(ge,{code:"paypal_runtime_failed",popupBlocked:Ue,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:qe,terminalReason:_e});return}x(Or(j)?"teardown":"pre_ready_callback",j)}}),It=Ye.isEligible();if(ze(`isEligible=${It}`),se.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!It){Q(!1),x("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,ze(`container:dims ${kn(An)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Pr=new MutationObserver(j=>{if(!nt()){for(let ae of j)if(ae.type==="childList")ae.addedNodes.forEach(_=>{if(!(_ instanceof Element))return;let Ue=_.tagName.toLowerCase(),Rt=(_.getAttribute("title")??"").slice(0,40),_e=Ue==="iframe"?` ${Cr(_)}`:"";ze(`child+ ${Ue}${Rt?` title="${Rt}"`:""}${_e} dims=${kn(_)}`)});else if(ae.type==="attributes"&&ae.target instanceof Element){let _=ae.target;if(_.tagName.toLowerCase()!=="iframe")continue;let Ue=ae.attributeName;(Ue==="src"||Ue==="srcdoc")&&ze(`attr~ iframe ${Ue}=${Ue==="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 ae=An.querySelectorAll("iframe"),_=typeof document<"u"&&"hasStorageAccess"in document;ze(`watchdog:${j} container=${kn(An)} children=${An.childElementCount} iframes=${ae.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${_} paypalNetRequests=${zn.value}`),ae.forEach((Ue,Rt)=>{let _e=(Ue.getAttribute("title")??"").slice(0,40);ze(` iframe[${Rt}] ${kn(Ue)}${_e?` title="${_e}"`:""} ${Cr(Ue)}`);let Sn=dt(Ue);Sn&&ze(` ${Sn}`)}),on.length===0&&ze(" (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(),ze("render:start");let Pe=se.startTiming();Gn=setTimeout(()=>{nt()||Tn||(ze("watchdog:11s retryable render timeout"),x("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},id);let At=Ye.render(An);(async()=>{try{if(await At,ze(`render:resolved inactive=${nt()}`),bn(),nt()){br();return}Tn=!0,Q(!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.";ze(`render:rejected msg=${j.slice(0,120)}`),bn(),x(Or(j)?"teardown":"render_rejected",j)}})()}).catch(z=>{let ce=z instanceof Error?z.message:"PayPal operation failed.";ze(`provider:failed msg=${ce.slice(0,120)}`);let J="script_rejected";D&&Or(ce)?J="teardown":D&&Fr&&(J="render_rejected"),x(J,ce)})},0);return()=>{Kt=!0,clearTimeout(W),Mr&&clearTimeout(Mr),bn(),Nt.current===sr&&(Nt.current=null),br(),Ve.current=null,rt.current=null}},[U,$,l,u,d,P,qe,vt,e,Fe,Te,be,V,Ke,ze,Qt]);let ie=re?(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=${He} failed=${ut})`,Ne.length===0?`
1
+ "use strict";var pd=Object.create;var Va=Object.defineProperty;var md=Object.getOwnPropertyDescriptor;var yd=Object.getOwnPropertyNames;var fd=Object.getPrototypeOf,gd=Object.prototype.hasOwnProperty;var hd=(e,t)=>{for(var n in t)Va(e,n,{get:t[n],enumerable:!0})},fl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of yd(t))!gd.call(e,o)&&o!==n&&Va(e,o,{get:()=>t[o],enumerable:!(r=md(t,o))||r.enumerable});return e};var ji=(e,t,n)=>(n=e!=null?pd(fd(e)):{},fl(t||!e||!e.__esModule?Va(n,"default",{value:e,enumerable:!0}):n,e)),Pd=e=>fl(Va({},"__esModule",{value:!0}),e);var fp={};hd(fp,{DirectPayPalButton:()=>fa,FloPayAutomaticPaymentButton:()=>Ec,FloPayCardSetup:()=>Ac,FloPayCardSetupError:()=>Ta,FloPayCheckout:()=>vi,FloPayPaymentMethodSetup:()=>Hc,FloPayProvider:()=>ha,SplitCardForm:()=>gi,VaultCardFields:()=>so,dropThirdPartyOnlyError:()=>Gc.dropThirdPartyOnlyError,useCheckout:()=>El,useFloPay:()=>Hr,usePayPalFloPay:()=>Wa});module.exports=Pd(fp);var Gc=require("@flopay/shared");var Ci=require("@flopay/js"),sr=require("@flopay/shared"),ot=require("react");var Ut=require("react/jsx-runtime");function bd(){return(0,Ut.jsxs)(Ut.Fragment,{children:[(0,Ut.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,Ut.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Ut.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Ut.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,Ut.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function vd(){return(0,Ut.jsx)(Ut.Fragment,{children:"Go back"})}function Cd(){return(0,Ut.jsx)(Ut.Fragment,{children:"Secure card checkout"})}function xo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Mo({content:e}){return(0,Ut.jsx)(Ut.Fragment,{children:e===void 0?(0,Ut.jsx)(bd,{}):e})}function Fo({content:e}){return(0,Ut.jsx)(Ut.Fragment,{children:e===void 0?(0,Ut.jsx)(vd,{}):e})}function ca({content:e}){return(0,Ut.jsx)(Ut.Fragment,{children:e===void 0?(0,Ut.jsx)(Cd,{}):e})}var wt=require("@flopay/shared"),Sd="Checkout is temporarily unavailable. Please try again later.";function $i(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof wt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function wd(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function gl(){return new wt.FloPayError(Sd,"api_error",{code:"CheckoutInitializationFailed"})}function Wi(e){return!!e?.gateways?.worldpayCorporateGateway}function Zr(e){return e?.status==="open"&&Wi(e)}function hl(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card")||Zr(r))||t&&e?.data.paypal?.publishableKey)}function Pl(e,t){if(t&&(!(e instanceof wt.FloPayError)||e.type==="authentication_error"))return $i(e);if(!(e instanceof wt.FloPayError&&wd(e))){if(!t&&!(e instanceof wt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,wt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof wt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof wt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Bo(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let s={...r,...a,email:a.email?.trim()||r.email?.trim()},c=(0,wt.isCardHolderNamePlaceholder)(s.firstName,s.lastName);if(!(0,wt.isValidEmail)(s.email))return Promise.reject(new wt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let u={};for(let[p,h]of Object.entries(s)){if(c&&p.endsWith("Name")||typeof h!="string")continue;let b=h.trim();b&&(u[p]=b)}return o=e.claimCheckoutSession(t,n,{accountData:u}),o.catch(()=>{}),o}}function bl(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Hi(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function vl(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,s)=>a+(s.overrideAmount??s.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,s)=>({uuid:`synthetic-${a.type??"item"}-${s}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function mo(e){if((0,wt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Ki(e,t){return t?{...e,...t}:e}function un(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{},...s?{sessionId:s}:{}}}function Qr(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var kd=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function eo(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of kd)if(n.test(t))return r;return e}function jr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function $r(e){return e?.status==="authorized"||e?.status==="complete"}function to(e,t){if(e.data.session)return e.data.session;let n=e.raw,r=n?.latestTransactionAttempt?.result,o=n?.status==="authorized"||r==="AUTHORIZED";return o||n?.status==="completed"||r==="SUCCESS"?{...t,status:o?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function Cl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ja(e){let t=Cl(e);return new wt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function $a(e){return e instanceof wt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Do(e){return Cl(e)?new wt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new wt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new wt.FloPayError(wt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function da(e,t){return e==="processing"||(0,wt.isMoneySettledOutcome)(e,t)}function Sl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function wl(e,t){let n=e;if((0,wt.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:s}=await n.retrieveSetupIntent(t);if(s)throw new wt.FloPayError(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new wt.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function kl(e,t="automatic"){return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}function Gi(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function ua(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Yr=require("@flopay/js"),tt=require("@flopay/shared"),w=ji(require("react"),1);var Yi=require("react"),rr=(0,Yi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Pr=(0,Yi.createContext)({session:null,loading:!1,error:null});var Ja=require("@flopay/js"),$t=require("@flopay/shared"),Fl=require("@paypal/paypal-js"),A=require("react");var Il=require("@flopay/shared"),br=require("react"),Wr=require("react/jsx-runtime");function On(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),s=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...s||t?{lastName:s??""}:{}}}function Oo(){let[e,t]=(0,br.useState)(null),n=(0,br.useRef)(null),r=(0,br.useRef)(0),o=(0,br.useCallback)((s,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:c}),new Promise(u=>{n.current=u})),[]),a=(0,br.useCallback)(s=>{let c=n.current;n.current=null,t(null),c?.(s)},[]);return(0,br.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Lo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[s,c]=(0,br.useState)(e.email?.trim()??""),u=(0,Il.isValidEmail)(s.trim());return(0,Wr.jsxs)("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,Wr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Wr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Wr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:p=>c(p.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Wr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Wr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Wr.jsxs)("button",{type:"button",disabled:!u||o,onClick:()=>{n(On({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Id=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),Rd=["https://www.paypal.com","https://www.sandbox.paypal.com"];function no(e,t,n){let r=`We couldn't open ${e}. Try again or choose another payment method.`;return t?n?`${r} Open this page in your system browser, then try again.`:`${r} Allow pop-ups for this site, then try again.`:r}function Rl(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function yo(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Mr(e){if(typeof e!="object"||e===null)return;let t=e;return yo(t.code)??yo(t.type)??yo(t.name)}function No(e){if(!(typeof e!="object"||e===null))return yo(e.decline_code)}function fo(e){return typeof e!="object"||e===null?!1:yo(e.type)?.toLowerCase()==="card_error"||No(e)!==void 0}function _d(e){let t=Rl(e)?.toLowerCase()??"",n=Mr(e)?.toLowerCase()??"";return Id.has(n)?!0:/(?:popup|pop-up).{0,40}(?:block|denied|prevent)/i.test(t)||/(?:block|denied|prevent).{0,40}(?:popup|pop-up)/i.test(t)}function Xi(e){if(Mr(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=Rl(e)??"";return n.includes("No ack for postMessage init()")&&Rd.some(r=>n.includes(r))&&n.includes("10000ms")}function ro(e,t){if(fo(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=_d(e)||t.inAppBrowser&&!t.handoffObserved&&Xi(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function oo(e){return ro(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}var _l=require("@flopay/shared"),pa=require("react");function Hr(){return(0,pa.useContext)(rr).flopay}function Wa(){return(0,pa.useContext)(rr).paypalFlopay??null}function El(){return(0,pa.useContext)(Pr)}function Tl(){return(0,pa.useContext)(rr).billingApiUrl||(0,_l.resolveBillingApiUrl)()}function Kr(e){let t=e??(typeof navigator>"u"?"":navigator.userAgent),n=r=>({inAppBrowser:r!=="none",appFamily:r,popupCapability:"unknown"});return t?/FBAN|FBAV|FB_IAB|FBIOS/i.test(t)?n("facebook"):/Instagram/i.test(t)?n("instagram"):/musical_ly|BytedanceWebview|TikTok/i.test(t)?n("tiktok"):/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)?n("other_in_app"):/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)?n("generic_webview"):n("none"):n("none")}function Ha(e,t,n=e.popupCapability){return e.inAppBrowser||n==="blocked"||t==="prefer_redirect"?"redirect":"popup"}function Ka(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var Al=require("@flopay/shared"),ho=require("react");function We(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}var Ga=require("react"),go=typeof window>"u"?Ga.useEffect:Ga.useLayoutEffect;var Ed={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function Td(e){return e==="stripe"||e==="paypal"?e:void 0}function Ad(e){let t=Td(e.provider),n={schemaVersion:Al.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Ed[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var Ji=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function zo(e,t){let n=(0,ho.useRef)(e);n.current=e;let r=(0,ho.useRef)(new Set),o=(0,ho.useRef)(t),a=(0,ho.useRef)(t);return go(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,ho.useCallback)(s=>{if(a.current!==t)return;let c=Ad(s);if(c){if(Ji.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}We(()=>n.current?.(c))}},[t])}var xl=require("react"),ma=(0,xl.createContext)(null);function Ya(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var xd=Symbol.for("@flopay/js.telemetry.bridge.v1"),Md=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Fd(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function Bd(e){let t=Fd(),n=(o,a)=>o?o.bind(e):a,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Xa(e){let t=globalThis[Md];return Bd(t?.(e)??{})}function pn(e){if(e)return e[xd]}var mn=require("react");function ya(e,t){let n=(0,mn.useRef)(0),r=(0,mn.useRef)(null),o=(0,mn.useRef)(null),a=(0,mn.useRef)(e),s=(0,mn.useRef)(t?.onHandoffObserved);(0,mn.useEffect)(()=>{a.current=e,s.current=t?.onHandoffObserved},[e,t?.onHandoffObserved]);let c=(0,mn.useCallback)((f=o.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),u=(0,mn.useCallback)(f=>{c();let S=n.current+1;return n.current=S,r.current=null,o.current={generation:S,method:f,timer:null,yieldedControl:!1},S},[c]),p=(0,mn.useCallback)(f=>{let S=o.current;return f!==void 0&&S?.generation!==f?!1:(c(S),o.current=null,(f===void 0||r.current===f)&&(r.current=null),!0)},[c]),h=(0,mn.useCallback)(f=>{let S=o.current,G=f??S?.generation??n.current;(f===void 0||S?.generation===f)&&(c(S),o.current=null),r.current=G},[c]),b=(0,mn.useCallback)(f=>r.current===(f??n.current),[]),I=(0,mn.useCallback)(f=>o.current?.generation===f&&r.current!==f,[]),k=(0,mn.useCallback)(()=>{let f=o.current;f&&(c(f),!f.yieldedControl&&(f.yieldedControl=!0,s.current?.(f.method)))},[c]),C=(0,mn.useCallback)(()=>{let f=o.current;!f?.yieldedControl||document.visibilityState!=="visible"||(c(f),f.timer=setTimeout(()=>{f.timer=null,o.current?.generation===f.generation&&(o.current=null,r.current=f.generation,a.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[c]);return(0,mn.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?C():k()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",k),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",k),window.removeEventListener("focus",C),c()}},[c,k,C]),{startAttempt:u,finishAttempt:p,invalidateAttempt:h,isAttemptInvalidated:b,isAttemptCurrent:I,generationRef:n}}var or=require("react/jsx-runtime"),Za=45,Dd=1e3,Od=11e3,Ld={width:"100%",minHeight:Za,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},Nd={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function zd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Nd[e.kind]??null}}function Ml(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Xi(t)?"paypal_init_timeout":"paypal_init_failure"}function Ud(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function qd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Bl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:s,environment:c,currency:u,isSubscription:p,providerObjectType:h,approvalPresentation:b,onTokenizedBody:I,onComplete:k,onErrorChange:C,onDecline:f,onTechnicalFailure:S,isProcessing:G=!1,onLoadStateChange:_,onInitializationStateChange:q,allowAutomaticRetry:E=!0,onButtonClick:ne,runBeforeButtonClick:$,session:W,existingOrderId:ie,telemetry:V,telemetryContext:Be,onInstrument:Ue,debug:X=!1}){let Ae=Hr(),it=zo(Ue,e),Re=(0,A.useMemo)(()=>{if(Ae)return null;let L=Xa({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:$t.SDK_VERSION,enabled:V!==!1});return L.setCheckoutContext(Be??{}),L.beginCheckout(Be??{}),L},[n,Ae,V,Be?.checkoutMode,Be?.layout]),xe=(0,A.useMemo)(()=>pn(Ae),[Ae]);(0,A.useEffect)(()=>()=>{Re&&Re.flush().catch(()=>{}).finally(()=>Re.destroy())},[Re]);let ve=(0,A.useMemo)(()=>({error:L=>{xe?xe.error(L):Re?.error(L),it({class:"technical_error",errorCode:L.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":L.errorCode,requestCategory:L.requestCategory,provider:L.provider})},log:L=>{xe?xe.log(L):Re?.log(L),it({class:"lifecycle",name:L.name,provider:L.provider})},performance:L=>{xe?xe.performance(L):Re?.performance(L)},terminal:L=>{xe?xe.terminal(L):Re?.terminal(L)},startTiming:()=>xe?.now()??Re?.now()??0,elapsed:L=>xe?.elapsed(L)??Math.max(0,(Re?.now()??L)-L)}),[it,xe,Re]),se=(0,A.useRef)(null),me=(0,A.useRef)(0),He=(0,A.useRef)(null),st=(0,A.useRef)(null),T=(0,A.useRef)(null),ye=(0,A.useContext)(ma),le=(0,A.useRef)(null);le.current||(le.current=Ya());let F=ye??le.current,Se=(0,A.useRef)(null),ce=(0,A.useRef)(!1),[De,re]=(0,A.useState)(!1),[$e,dt]=(0,A.useState)(!1),[Me,Oe]=(0,A.useState)(0),ut=(0,A.useRef)(0),[Y,J]=(0,A.useState)(!1),mt=(0,A.useRef)(!1),gt=(0,A.useRef)(!1),[Ie,ft]=(0,A.useState)(!1),[U,we]=(0,A.useState)(!1),{request:lt,collect:Z,finish:qe}=Oo(),St=(0,A.useRef)({sessionId:e,required:!(0,$t.isValidEmail)(r?.trim()||W?.customer?.email?.trim())});St.current.sessionId!==e&&(St.current={sessionId:e,required:!(0,$t.isValidEmail)(r?.trim()||W?.customer?.email?.trim())});let Ze=St.current.required,H=(0,A.useMemo)(()=>n.replace(/\/+$/,""),[n]),g=W?.gateways?.paypal?.providerObjectType??h,v=g??(p?"subscription":"order"),[ee]=(0,A.useState)(Kr),de=W?.gateways?.paypal?.approvalPresentation??b,Xe=Ka(ee,de==="app_switch"?"app_switch":void 0,v),kt=g==="order"||g==="setup_token",Qe=(0,A.useMemo)(()=>JSON.stringify([H,s,u,c??"",v,kt,Xe,e,ie??""]),[H,s,u,c,ie,v,kt,Xe,e]),ae=(0,A.useRef)(Qe),yt=ae.current!==Qe,It=(0,A.useRef)(X),qt=(0,A.useRef)(null),[Ke,Lt]=(0,A.useState)([]),Ge=(0,A.useCallback)(L=>{It.current&&Lt(rt=>[...rt,`${new Date().toISOString().slice(11,23)} ${L}`])},[]);(0,A.useEffect)(()=>{It.current=X,X&&Ge("debug:enabled"),qt.current?.setEnabled(X)},[Ge,X]);let zn=(0,A.useRef)(I),Tn=(0,A.useRef)(k),Dt=(0,A.useRef)(C),Rn=(0,A.useRef)(f),Un=(0,A.useRef)(S),qn=(0,A.useRef)(ne),on=(0,A.useRef)(_),Ee=(0,A.useRef)(q),Rt=(0,A.useRef)(a),Mt=(0,A.useRef)($),wn=(0,A.useRef)(W),Ot=(0,A.useRef)(r),Yn=(0,A.useRef)(o),yn=(0,A.useRef)(t),Ht=(0,A.useRef)(null),ln=(0,A.useRef)(new Map),Xn=(0,A.useRef)(new Map),fn=(0,A.useRef)(!1);(0,A.useEffect)(()=>(fn.current=!0,()=>{fn.current=!1}),[]),(0,A.useEffect)(()=>{zn.current=I},[I]),(0,A.useEffect)(()=>{Rt.current=a},[a]),(0,A.useEffect)(()=>{Tn.current=k},[k]),(0,A.useEffect)(()=>{Dt.current=C},[C]),(0,A.useEffect)(()=>{Rn.current=f},[f]),(0,A.useEffect)(()=>{Un.current=S},[S]),(0,A.useEffect)(()=>{qn.current=ne},[ne]),(0,A.useEffect)(()=>{on.current=_},[_]),(0,A.useEffect)(()=>{Ee.current=q},[q]),(0,A.useEffect)(()=>{Mt.current=$},[$]),(0,A.useEffect)(()=>{wn.current=W},[W]),(0,A.useEffect)(()=>{Ot.current=r},[r]),(0,A.useEffect)(()=>{Yn.current=o},[o]),(0,A.useEffect)(()=>{yn.current=t},[t]),(0,A.useEffect)(()=>{ut.current=Me},[Me]),(0,A.useEffect)(()=>{Y&&Se.current?.focus()},[Y,Me]);let _t=(0,A.useCallback)(()=>{window.setTimeout(()=>{Se.current?.focus()},0)},[]),Qt=(0,A.useCallback)(()=>{re(!1),Oe(L=>L+1)},[]),gn=(0,A.useCallback)(()=>{J(!1),(se.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??se.current)?.focus?.()},[]);(0,A.useEffect)(()=>{!De||!ce.current||(ce.current=!1,gn())},[gn,De,Me]);let Nt=(0,A.useCallback)((L,rt)=>{let he=rt?.popupBlocked??oo(L);he&&F.markBlocked();let Jn=no("PayPal",he,ee.inAppBrowser),Pn=Un.current;if(Pn){let Gt=he&&ee.inAppBrowser?new $t.FloPayError(Jn,"api_error",{code:rt?.code??"paypal_popup_blocked"}):L;Pn("paypal",Gt,rt);return}Dt.current?.(Jn)},[F,ee.inAppBrowser]),en=(0,A.useCallback)(L=>{let rt=He.current,he=st.current;rt===null||!he||(ve.log({...he,popupCapability:F.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),ve.performance({...he,popupCapability:F.current(),stage:"overlay_return",durationMs:ve.elapsed(rt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),He.current=null)},[F,ve]),Kt=(0,A.useCallback)((L,rt,he)=>{let Jn=st.current;en("overlay_timeout"),Jn&&ve.error({...Jn,popupCapability:F.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Nt(rt,{...he,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Xe,terminalReason:"overlay_timeout"}),J(!0),Qt(),_t()},[en,_t,Nt,F,Xe,Qt,ve]),hn=(0,A.useCallback)(()=>{F.markAvailable();let L=st.current;L&&(T.current=L.attempt,ve.log({...L,popupCapability:F.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[F,ve]),{finishAttempt:vt,generationRef:ue,invalidateAttempt:Vn,isAttemptCurrent:jn,isAttemptInvalidated:Sr,startAttempt:kn}=ya(Kt,{onHandoffObserved:hn}),cn=(0,A.useCallback)(()=>(J(!1),kn("paypal")),[kn]),An=(0,A.useCallback)(L=>{Vn(L?.generation),L?.showRetry&&J(!0),L?.remount&&Qt(),L?.focus!==!1&&_t()},[_t,Vn,Qt]),Le=L=>{let rt=Ht.current;return rt&&Xn.current.set(L,rt),L};(0,A.useEffect)(()=>{ae.current!==Qe&&(ae.current=Qe,mt.current=!1,gt.current=!1,re(!1),dt(!1),ft(!1),Ee.current?.("loading"))},[Qe]),(0,A.useEffect)(()=>{We(()=>on.current?.(De&&!Ie))},[De,Ie]);let Ct=(0,$t.normalizeGatewayEnvironment)(c);(0,A.useEffect)(()=>{let L={attempt:ue.current+1,inAppBrowser:ee.inAppBrowser,appFamily:ee.appFamily,popupCapability:F.current(),presentationMode:Xe},rt=()=>({...st.current??L,popupCapability:F.current()}),he={error:m=>ve.error({...m,...rt()}),log:m=>ve.log({...m,...rt()}),performance:m=>ve.performance({...m,...rt()}),terminal:m=>ve.terminal({...m,...rt()}),startTiming:ve.startTiming,elapsed:ve.elapsed},Jn=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",Pn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Ge(`mount clientId=${Jn} env=${c??"(unset)"}\u2192${Ct??"live"} ccy=${u} sub=${p}`),Ge(`ua=${Pn.slice(0,80)}${Pn.length>80?"\u2026":""}`),!s){Ge("FAIL: clientId empty \u2014 gateway misconfigured"),ft(!0),he.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!se.current){Ge("FAIL: containerRef not attached");return}me.current=he.startTiming(),he.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Gt=!1,Zn=!1,pt=()=>Gt||Zn,Xr,Yt=!1,bn=()=>{Xr=(0,$t.generateIdempotencyKey)(),Xr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Yt=!0},Nr=null,zr=!1,xn=null,tn=!1,wr=()=>{!xn||tn||(tn=!0,xn.close().catch(()=>{}))},Mn=!1,Ur=!1,Fn=se.current,kr=null,Ir=null,cr=[],Qn=null,er=!1,Bt=!1,dr=null,_n=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let P=m.getBoundingClientRect();return`${Math.round(P.width)}\xD7${Math.round(P.height)}`},tr=m=>{if(!m)return"(empty)";try{let P=new URL(m,typeof window>"u"?"https://localhost":window.location.href),N=P.pathname.toLowerCase();return N.includes("checkcaptcha")||N.includes("captcha")?`CAPTCHA(${P.host}${N})`:N.includes("risk")||N.includes("challenge")?`RISK(${P.host}${N})`:N.includes("smart/buttons")?`smart-buttons(${P.host})`:`${P.host}${N}`.slice(0,100)}catch{return m.slice(0,80)}},Rr=m=>{let P=m.getAttribute("src"),N=m.getAttribute("srcdoc"),j=m.getAttribute("name"),be=m.getAttribute("sandbox"),oe=[];return P&&oe.push(`src=${tr(P)}`),N&&oe.push(`srcdoc[${N.length}ch]`),!P&&!N&&oe.push("src=(empty) srcdoc=(empty)"),j&&oe.push(`name=${j.slice(0,40)}`),be!==null&&oe.push(`sandbox="${be.slice(0,40)}"`),oe.join(" ")},ht=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let P=m.contentDocument;if(!P)return"cd=null";let N=P.body?.children.length??0,j=P.body?.innerHTML.length??0,be=P.head?.innerHTML.length??0;return`cd=same-origin readyState=${P.readyState} body[${N}children,${j}ch] head[${be}ch]`}catch(P){return`cd=cross-origin(${P.message.slice(0,30)})`}},an=[],nn=m=>{if(pt())return;let P=m.message??String(m.error??"(no message)");P&&(P.toLowerCase().includes("paypal")||P.toLowerCase().includes("zoid")||P.toLowerCase().includes("postrobot")||P.toLowerCase().includes("storage"))&&(Ge(`window:error ${P.slice(0,140)}`),an.push(P))},qr=m=>{if(pt())return;let P=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");P&&(P.toLowerCase().includes("paypal")||P.toLowerCase().includes("zoid")||P.toLowerCase().includes("postrobot")||P.toLowerCase().includes("storage"))&&(Ge(`window:rejection ${P.slice(0,140)}`),an.push(P))},$n={value:0},Jr=()=>{kr?.disconnect(),kr=null,Ir?.disconnect(),Ir=null;for(let m of cr.splice(0))clearTimeout(m);Bt=!1,er&&typeof window<"u"&&(window.removeEventListener("error",nn),window.removeEventListener("unhandledrejection",qr)),er=!1},ur=()=>{if(!(er||pt()||Mn)){if(er=!0,an.length=0,$n.value=0,typeof window<"u"&&(window.addEventListener("error",nn),window.addEventListener("unhandledrejection",qr)),typeof PerformanceObserver<"u")try{Ir=new PerformanceObserver(m=>{if(!pt())for(let P of m.getEntries()){if(!P.name.toLowerCase().includes("paypal"))continue;$n.value+=1;let N=Math.round(P.duration);Ge(`net ${N}ms ${P.name.slice(0,90)}`)}}),Ir.observe({type:"resource",buffered:!0})}catch{}dr?.()}},pr=()=>{Qn&&(clearTimeout(Qn),Qn=null)},vn=()=>{Jr(),pr()},mr={setEnabled:m=>{m?ur():Jr()}};qt.current=mr,It.current&&ur();let Vr=m=>{if(!m)return!1;let P=m.toLowerCase();return P.includes("zoid destroyed")||P.includes("destroyed all components")||P.includes("window closed")||P.includes("detected container element removed")},En=m=>{if(pt()||Vr(m))return;let P=eo(m)??m;We(()=>Dt.current?.(P))},D=(m,P)=>{if(Gt||zr)return;zr=!0,Zn=!0,vn(),wr();let N=zd({kind:m,generationActive:!0,automaticRetryAllowed:E,automaticRetryUsed:mt.current});if(N.action==="retry"){mt.current=!0,re(!1),we(!1),dt(!0),Ee.current?.("retrying"),Nr=setTimeout(()=>{Gt||Oe(j=>j+1)},Dd);return}if(re(!1),we(!1),dt(!1),ft(!0),N.action!=="ignore"){if(Ee.current?.("exhausted"),N.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",P);return}if(N.report){let j=ro({code:Ml(m,P),message:P},{inAppBrowser:ee.inAppBrowser,handoffObserved:!1});j.popupBlocked&&F.markBlocked(),he.error({errorCode:j.popupBlocked?j.errorCode:N.report.errorCode,stage:N.report.stage,operationOutcome:N.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:j.terminalReason})}gt.current||(gt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Ml(m,P)))}};ft(!1);let z=async(m,P=Ht.current)=>{if(pt())return;let N=P?.sessionId??e;if(zn.current){await zn.current(m,{sessionId:N,accountPatch:P?.accountPatch,nonce:P?.nonce});return}let j=he.startTiming();he.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let be=()=>{he.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),he.performance({stage:"processing",durationMs:he.elapsed(j),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let oe=wn.current,et=P?.accountPatch?.email??Ot.current,Tt=P?.accountPatch?.userId??oe?.customer?.id??oe?.accountData?.userId??"",M=P?.accountPatch?.firstName??oe?.customer?.firstName??oe?.accountData?.firstName,_e=P?.accountPatch?.lastName??oe?.customer?.lastName??oe?.accountData?.lastName,ke=await new Ja.PaymentAPI(H,{telemetry:!1}).processPayment(Tt,{sessionId:N,nonce:P?.nonce??yn.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:Tt,email:et??oe?.customer?.email??"",...M?{firstName:M}:{},..._e?{lastName:_e}:{},country:P?.accountPatch?.country??oe?.customer?.country??oe?.accountData?.country??void 0,zip:P?.accountPatch?.zip??oe?.customer?.zip??oe?.accountData?.zip??void 0}});if(ke.ok){if(Zn||Gt&&fn.current)return;be(),he.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),We(()=>Tn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(pt())return;let K=await ke.json().catch(()=>null),fe=K?.message??"PayPal payment failed.",x=eo(fe)??fe;be(),ke.status===400&&(typeof K?.declineCode=="string"||!Array.isArray(K?.fields))?he.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ke.status===400||ke.status===422?he.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):he.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:qd(ke.status),failureCategory:ke.status>=500?"server_error":void 0}),En(x),We(()=>Rn.current?.(un("paypal",x,{code:K?.code,declineCode:K?.declineCode})));return}catch(oe){if(pt())return;be(),he.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let et=oe instanceof Error?oe.message:"PayPal payment failed.",Tt=eo(et)??et;En(Tt),We(()=>Rn.current?.(un("paypal",Tt)));return}},B=()=>new $t.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Pe=m=>pt()?Promise.reject(B()):Promise.resolve(m),Ve=async m=>{if(pt())throw B();Yt||bn();let P=Ht.current,N=P?.sessionId??e,j=P?.nonce??yn.current;he.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let be;try{be=await new Ja.PaymentAPI(H,{telemetry:!1}).createSessionIntent(N,j??"",kt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:$t.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:v==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Xr})}catch(oe){throw he.error({...(0,$t.classifyTelemetryFailure)(oe,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),oe}if(pt())throw B();if(be.provider!=="paypal"||be.providerObjectType!==v)throw new Error(m);return he.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),be.providerObjectId},Pt=(m,P)=>{let N=P?.nonce??yn.current;if(!N)return;let j=P?.sessionId??e,be=No(m)??Mr(m)??"provider_declined";new Ja.PaymentAPI(H,{telemetry:!1}).reportSessionIntentDecline(j,N,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:be}).catch(()=>{})},Ce=Me;Ge("loadScript:scheduled (deferred 1 tick)");let je=null,Q=setTimeout(()=>{if(Gt){Ge("loadScript:skipped (cancelled before defer ran)");return}Ge("loadScript:start");let m=Ct==="live"?"production":Ct,P={};v==="subscription"?P={intent:"subscription",vault:!0}:v==="order"&&(P={intent:"capture"}),je=(0,Fl.loadScript)({clientId:s,currency:u,...P,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let N=!1;je.then(j=>{if(N=!0,Ge(`loadScript:resolved inactive=${pt()} ns=${!!j} buttons=${!!j?.Buttons}`),pt())return;if(!j?.Buttons){Ge("FAIL: namespace missing Buttons factory"),D("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}he.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),he.performance({stage:"provider_ready",durationMs:he.elapsed(me.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),he.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let be=async(ke,K)=>{if(pt()||ut.current!==Ce)return;let fe=ke.vaultSetupToken??ke.subscriptionID??ke.orderID??"",x=fe?Xn.current.get(fe):ln.current.get(Ce);if(!(!x||!jn(x.generation))&&vt(x.generation)){Xn.current.delete(fe),ln.current.delete(x.surfaceKey),en("approved");try{if(we(!0),We(()=>Dt.current?.(null)),!fe)throw new $t.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ye=wn.current,At=mo(Yn.current??[Ye?.customer?.firstName,Ye?.customer?.lastName].filter(Boolean).join(" ")),Ne=On({email:x.accountPatch?.email?.trim()||Ot.current?.trim()||Ye?.customer?.email?.trim(),firstName:x.accountPatch?.firstName?.trim()||At.firstName,lastName:x.accountPatch?.lastName?.trim()||At.lastName});if(!(0,$t.isValidEmail)(Ne.email)||!(Ne.firstName||Ne.lastName))try{let _r=Ud(await K?.order?.get?.());Ne=On({email:_r.email||Ne.email,firstName:_r.firstName||Ne.firstName,lastName:_r.lastName||Ne.lastName})}catch{}if((Rt.current||Ze)&&!(0,$t.isValidEmail)(Ne.email)){let _r=await Z("PayPal",Ne);if(!_r)return;Ne=_r}(0,$t.isValidEmail)(Ne.email)&&(x.accountPatch=On({...x.accountPatch,...Ne}),await Rt.current?.(Ne));let In;v==="setup_token"?In={id:fe,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:$t.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:kt?In={id:fe,isPaypal:!0,gateway:"paypal",paymentMethodType:$t.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:In={id:fe,isPaypal:!0},await z(In,x)}catch(Ye){En(Ye instanceof Error?Ye.message:"PayPal capture failed.")}finally{pt()||we(!1)}}},oe=ke=>{let K=ie?()=>Pe(ie):()=>Ve(ke);return async()=>Le(await K())},et=j.Buttons({style:{layout:"horizontal",height:Za,tagline:!1},...Xe==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ke,K)=>{if(pt()){await K.reject();return}bn();let fe=Mt.current,x={};if(fe)try{let Ne=await fe("paypal");if(pt()){await K.reject();return}if(!Ne.proceed){Ht.current=null,ln.current.delete(Ce),await K.reject();return}x={sessionId:Ne.sessionId,accountPatch:Ne.accountPatch,nonce:Ne.nonce}}catch(Ne){Ge(`onClick:runBeforeButtonClick rejected msg=${(Ne instanceof Error?Ne.message:String(Ne)).slice(0,120)}`),Ht.current=null,ln.current.delete(Ce),await K.reject();return}We(()=>qn.current?.("paypal"));let Ye=cn(),At={generation:Ye,surfaceKey:Ce,...x};Ht.current=At,ln.current.set(Ce,At),st.current={...L,attempt:Ye},await K.resolve(),he.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),he.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),He.current=he.startTiming()},createOrder:v==="order"?oe("Failed to create PayPal order."):void 0,createSubscription:v==="subscription"?oe("Failed to create PayPal subscription."):void 0,createVaultSetupToken:v==="setup_token"?async()=>Le(await Ve("Failed to create PayPal setup token.")):void 0,onApprove:be,onCancel:()=>{if(pt())return;let ke=ln.current.get(Ce)??Ht.current;ke&&ln.current.delete(ke.surfaceKey),Ht.current=null,en("cancelled"),he.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ce.current=!0,An({generation:ke?.generation,remount:!0,focus:!1})},onError:ke=>{if(pt()||ut.current!==Ce)return;let K=ke instanceof Error?ke.message:"PayPal failed to render.";if(Ge(`onError rendered=${Mn} msg=${K.slice(0,120)}`),Mn){let fe=ln.current.get(Ce)??Ht.current;if(fe&&!jn(fe.generation)||!fe&&Sr())return;if(Vr(K)){vt(fe?.generation);return}let{errorCode:x,popupBlocked:Ye,providerDeclined:At,terminalReason:Ne}=ro(ke,{inAppBrowser:ee.inAppBrowser,handoffObserved:fe!=null&&T.current===fe.generation});if(Ye&&F.markBlocked(),en(Ne),At){he.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ne}),Pt(ke,fe),We(()=>Rn.current?.(un("paypal",K))),fe&&ln.current.delete(fe.surfaceKey),Ht.current=null,vt(fe?.generation);return}he.error({errorCode:x,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ne}),fe&&ln.current.delete(fe.surfaceKey),Ht.current=null,An({generation:fe?.generation,remount:!0,showRetry:!0,focus:!0}),Nt(ke,{code:"paypal_runtime_failed",popupBlocked:Ye,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Xe,terminalReason:Ne});return}D(Vr(K)?"teardown":"pre_ready_callback",K)}}),Tt=et.isEligible();if(Ge(`isEligible=${Tt}`),he.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Tt){re(!1),D("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ur=!0,xn=et,dr=()=>{if(!er||Bt||pt()||Mn)return;Bt=!0,Ge(`container:dims ${_n(Fn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(kr=new MutationObserver(K=>{if(!pt()){for(let fe of K)if(fe.type==="childList")fe.addedNodes.forEach(x=>{if(!(x instanceof Element))return;let Ye=x.tagName.toLowerCase(),At=(x.getAttribute("title")??"").slice(0,40),Ne=Ye==="iframe"?` ${Rr(x)}`:"";Ge(`child+ ${Ye}${At?` title="${At}"`:""}${Ne} dims=${_n(x)}`)});else if(fe.type==="attributes"&&fe.target instanceof Element){let x=fe.target;if(x.tagName.toLowerCase()!=="iframe")continue;let Ye=fe.attributeName;(Ye==="src"||Ye==="srcdoc")&&Ge(`attr~ iframe ${Ye}=${Ye==="srcdoc"?`[${(x.getAttribute("srcdoc")??"").length}ch]`:tr(x.getAttribute("src"))} dims=${_n(x)}`)}}}),kr.observe(Fn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ke=K=>{if(pt()||Mn)return;let fe=Fn.querySelectorAll("iframe"),x=typeof document<"u"&&"hasStorageAccess"in document;Ge(`watchdog:${K} container=${_n(Fn)} children=${Fn.childElementCount} iframes=${fe.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${x} paypalNetRequests=${$n.value}`),fe.forEach((Ye,At)=>{let Ne=(Ye.getAttribute("title")??"").slice(0,40);Ge(` iframe[${At}] ${_n(Ye)}${Ne?` title="${Ne}"`:""} ${Rr(Ye)}`);let In=ht(Ye);In&&Ge(` ${In}`)}),an.length===0&&Ge(" (no PayPal/zoid window errors captured)")};cr.push(setTimeout(()=>ke("3s"),3e3)),cr.push(setTimeout(()=>ke("8s"),8e3)),cr.push(setTimeout(()=>ke("15s"),15e3))},dr(),Ge("render:start");let _e=he.startTiming();Qn=setTimeout(()=>{pt()||Mn||(Ge("watchdog:11s retryable render timeout"),D("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Od);let Ft=et.render(Fn);(async()=>{try{if(await Ft,Ge(`render:resolved inactive=${pt()}`),vn(),pt()){wr();return}Mn=!0,re(!0),dt(!1),Ee.current?.("ready"),he.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),he.performance({stage:"checkout_render",durationMs:he.elapsed(_e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ke){let K=ke instanceof Error?ke.message:"PayPal failed to render.";Ge(`render:rejected msg=${K.slice(0,120)}`),vn(),D(Vr(K)?"teardown":"render_rejected",K)}})()}).catch(j=>{let be=j instanceof Error?j.message:"PayPal operation failed.";Ge(`provider:failed msg=${be.slice(0,120)}`);let oe="script_rejected";N&&Vr(be)?oe="teardown":N&&Ur&&(oe="render_rejected"),D(oe,be)})},0);return()=>{Gt=!0,clearTimeout(Q),Nr&&clearTimeout(Nr),vn(),qt.current===mr&&(qt.current=null),wr(),He.current=null,st.current=null}},[E,H,s,u,c,v,Xe,kt,e,ie,Me,ve,Z,Ze,Ge,en]);let ge=X?(0,or.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ie?"#fef2f2":"#f3f4f6",border:`1px solid ${Ie?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${De} failed=${Ie})`,Ke.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${Ne.join(`
4
- `)}`]}):null;return ut&&!it?re?(0,Qn.jsx)("div",{children:ie}):null:(0,Qn.jsxs)("div",{children:[ie,et&&(0,Qn.jsx)(wo,{identity:et.identity,methodLabel:et.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:xe,onCancel:()=>xe(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:Ua},children:[!He&&!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:Ua,display:"flex",opacity:He?1:0},"aria-busy":q||G},Te)]},Te),at&&(0,Qn.jsx)("button",{ref:ve,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:yn,style:sd,children:"Try PayPal again"})]})}function ra(e){return(0,Qn.jsx)(bl,{...e})}function Pl(e){return(0,Qn.jsx)(bl,{...e})}var oa=require("react/jsx-runtime");function Ro({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,oa.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,oa.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,oa.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var qa=require("@flopay/shared");function _o(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Li=":idempotency-key";function Ni(e,t){if(!_o())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 zi(e,t){if(!_o())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 $a(e,t){if(_o())try{Ni(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ja(e,t){if($a(e,t),!!_o())try{zi(e,t)&&window.sessionStorage.removeItem(e+Li)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Va(e,t,n,r){if(_o())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 Wa(e,t,n){if(_o())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 Oi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function pd(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 Eo(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>Oi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Oi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Oi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:pd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function vl(e,t=!1){let n=Eo(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 Cl(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=(0,qa.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,qa.foldIntoProducts)(t.items,t.subscriptions)).map(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 md={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=md}){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:`
3
+ ${Ke.join(`
4
+ `)}`]}):null;return Ie&&!yt?X?(0,or.jsx)("div",{children:ge}):null:(0,or.jsxs)("div",{children:[ge,lt&&(0,or.jsx)(Lo,{identity:lt.identity,methodLabel:lt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:qe,onCancel:()=>qe(null)}),(0,or.jsxs)("div",{"aria-hidden":$e||lt?!0:void 0,style:$e||lt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Za},children:[!De&&!$e&&(0,or.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,or.jsx)("div",{ref:se,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Za,display:"flex",opacity:De?1:0},"aria-busy":U||G},Me)]},Me),Y&&(0,or.jsx)("button",{ref:Se,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:gn,style:Ld,children:"Try PayPal again"})]})}function fa(e){return(0,or.jsx)(Bl,{...e})}function Dl(e){return(0,or.jsx)(Bl,{...e})}var ga=require("react/jsx-runtime");function Uo({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,ga.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&(0,ga.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,ga.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var Qa=require("@flopay/shared");function qo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Qi=":idempotency-key";function es(e,t){if(!qo())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function ts(e,t){if(!qo())return null;try{let n=window.sessionStorage.getItem(e+Qi);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function ei(e,t){if(qo())try{es(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ti(e,t){if(ei(e,t),!!qo())try{ts(e,t)&&window.sessionStorage.removeItem(e+Qi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function ni(e,t,n,r){if(qo())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function ri(e,t,n){if(qo())try{window.sessionStorage.setItem(e+Qi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Zi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Vd(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([s],[c])=>s<c?-1:s>c?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let s=0;s<t.length;s++){let c=t.charCodeAt(s);n=r^Math.imul(n^c,597399067),r=o^Math.imul(r^c,2869860233),o=a^Math.imul(o^c,951274213),a=n^Math.imul(a^c,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(a^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),a=Math.imul(r^a>>>19,2716044179),n^=r^o^a,r^=n,o^=n,a^=n,[n,r,o,a].map(s=>(s>>>0).toString(16).padStart(8,"0")).join("")}function Vo(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>Zi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Zi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Zi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Vd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Ol(e,t=!1){let n=Vo(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function Ll(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=(0,Qa.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,Qa.foldIntoProducts)(t.items,t.subscriptions)).map(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,h)=>`${p.code}:${p.type??""}`.localeCompare(`${h.code}:${h.type??""}`)),s=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,h)=>`${p.code}:${p.type??""}`.localeCompare(`${h.code}:${h.type??""}`));if(a.length!==s.length)return!1;for(let[p,h]of a.entries()){let b=s[p];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 c=[...t.couponCodes??[]].sort(),u=[...e.coupons??[]].sort();return c.length===u.length&&c.every((p,h)=>p===u[h])}var rn=require("react/jsx-runtime");var jd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function Ln({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:s="You will be automatically redirected, do not close or navigate away from this window.",theme:c=jd}){let u={fontSize:13,color:c.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,rn.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,rn.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...c.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,rn.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,rn.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,rn.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:c.spinnerTrackColor,strokeWidth:"3"}),(0,rn.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:c.spinnerAccentColor})]}),e==="success"&&(0,rn.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,rn.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,rn.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,rn.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,rn.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,rn.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,rn.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,rn.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,rn.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:c.labelColors[e]},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&a]}),e==="success"&&s!==null&&(0,rn.jsx)("p",{style:u,children:s}),e==="error"&&t&&(0,rn.jsx)("p",{style:u,children:t}),(0,rn.jsx)("style",{children:`
5
5
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
6
6
  @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
7
7
  @keyframes flopay-draw { to { stroke-dashoffset: 0; } }
8
8
  @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
9
- `})]})})}var Sl=require("@flopay/shared"),Pn=require("react");var wl=require("react/jsx-runtime");function aa({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=Io(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 B=(0,Sl.resolveBillingApiUrl)(n?.billingApiUrl),I=(0,Pn.useMemo)(()=>({flopay:a,paypalFlopay:d,billingApiUrl:B,emitInstrument:v}),[a,d,B,v]);return(0,wl.jsx)(Zn.Provider,{value:I,children:o})}var Ha="flopay_recent_completion_";function To(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Ha+e,JSON.stringify(t))}catch{}}function Ui(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Ha+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Ha+e),!1):!0}catch{return!1}}async function Ka(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 Xr=require("@flopay/js"),$e=require("@flopay/shared");var sa="card",yd=1e3;async function fd(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 gd(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 Jr(e){return new $e.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function qi(){return new $e.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function ji(e,t){return Object.assign(e,{checkoutMethod:t})}function qr(e,t){let n=e instanceof $e.FloPayError?e:new $e.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 ia(e,t){try{return await e()}catch(n){throw qr(n,t)}}function Il(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 hd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function Vi(e){if(typeof document>"u"||typeof window>"u")throw new $e.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw Jr();let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let v=new AbortController,B=()=>v.abort();e.signal?.aborted?v.abort():e.signal?.addEventListener("abort",B);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 bd(h)}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",B)}},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((B,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 Fe=await l();if(w||!hd(Fe))return;w=!0,Y(),B(Fe)}finally{T=!1}}},de=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(G),G=window.setTimeout(()=>{U()},250))},X=()=>{w||(w=!0,Y(),I(Jr()))},he=Fe=>{if(Fe.source!==p.contentWindow||b&&Fe.origin!==b)return;let oe=Fe.data;!oe||typeof oe!="object"||oe.source!=="flopay-vault-3ds-return"||w||(w=!0,Y(),B(null))};h=window.setTimeout(()=>{w||(w=!0,Y(),I(qi()))},$e.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 Ao(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,a=t.nonce??t.session.clientSecret,l=new Xr.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=Vi({billingApiUrl:n,sessionId:r,nonce:a,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:u.signal,pollCompletionEndpoint:!1}),B=l.waitForCheckoutSessionCompletion(r,{initialDelayMs:yd,nonce:a,statusUrl:d,continueAfterActionRequired:!0,timeoutMs:$e.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:p.signal}),I;try{let h=await Promise.race([v,B]);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 qi();I=await B}}catch(h){if(o.aborted||h instanceof Error&&h.name==="AbortError")throw Jr(h);if(!(h instanceof $e.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 Jr(G);if(!(G instanceof $e.FloPayError)||G.code!=="checkout_processing_timeout")throw G}let O=I&&Gr(I,t.session);if(!Nr(O)&&O?.status!=="expired"){if(t.telemetry){let G=new Xr.PaymentAPI(n);try{G.reportThreeDsAbandoned(r)}finally{G.destroy()}}throw qi()}}finally{o.removeEventListener("abort",b),u.abort(),p.abort()}let w=I&&Gr(I,t.session);if(!Nr(w))throw Co(w);return{...Lr(w,r),checkoutMethod:"card"}}function bd(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=Kr(o)??o,l=ji(new $e.FloPayError(a,"api_error",{code:e?.code??(0,$e.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,$e.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(l.orderId=e.orderId),l}function $i(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ga(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Rl(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Ga(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||Ga(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||Ga(b)))return b}}}}async function Pd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Rl(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 Xr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ga(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function xo({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??"",B=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 Xr.PaymentAPI(d,l===!1?{telemetry:!1}:void 0).processPayment(b,{sessionId:u,nonce:p,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:b,email:v,firstName:B,lastName:I,country:w,zip:h},returnUrl:a??$i(n)});if(G.ok){let U=typeof G.json=="function"?await G.json().catch(()=>null):null;if((0,$e.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:Jo(o),checkoutMethod:kl(o,n)}};let de=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...de?{paymentIntentId:de}:{},paymentMethodId:Jo(o),checkoutMethod:kl(o,n)}}}let T;try{T=await G.json()}catch(U){throw new $e.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=Rl(T);if(!U)throw new $e.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 Pd({billingApiUrl:d,sessionId:u,nonce:p,responseJson:T});if(U)return U;throw ji(new $e.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let Y=new $e.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,$e.classifyPaymentRejection)(G.status,T)})}async function Ya(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 $e.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw ji(new $e.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let v=(0,$e.isSetupIntentClientSecret)(e.threeDSecureToken),B=null,I=e.paymentMethodId,w=await ia(()=>fd(b,e.threeDSecureToken,v),"card");if(w){if(w.error)throw qr(new $e.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 ia(()=>gd(b,e.threeDSecureToken,{payment_method:I,return_url:d??$i(l)??window.location.href},v),"card"):null;if(h){if(h.error)throw qr(new $e.FloPayError(h.error.message??"3DS authentication failed.","api_error",{code:h.error.code}),"card");B=h.intent}else{let O=await ia(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(O.error)throw qr(new $e.FloPayError(O.error.message??"3DS authentication failed.","api_error",{code:O.error.code}),"card");B=(v?O.setupIntent:O.paymentIntent)??null}if(B&&(B.status==="requires_capture"||B.status==="succeeded"||B.status==="processing")){let O=await xo({billingApiUrl:o,sessionId:a,session:l,telemetry:u,tokenizedData:{id:B.id,type:"card",threeDSecureActionResultTokenId:B.id},returnUrl:d});return O.type==="success"?{...O.result,paymentIntentId:O.result.paymentIntentId??B.id,paymentMethodId:O.result.paymentMethodId??I}:O.type==="next_action_required"?Ao(O,{billingApiUrl:o,sessionId:a??l.id,session:l,signal:p}):Ya(O,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:d,telemetry:u,signal:p})}throw qr(new $e.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 $e.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:I}=await ia(()=>v.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(I)throw qr(new $e.FloPayError(I.message??"PayPal authorization failed.","api_error",{code:I.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:B}=await ia(()=>v.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??$i(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(B)throw qr(new $e.FloPayError(B.message??"PayPal authorization failed.","api_error",{code:B.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new $e.FloPayError("Unsupported payment redirect state.","api_error")}function la(e){if(e instanceof $e.FloPayError){let r=Kr(e.message);return r&&r!==e.message?Object.assign(new $e.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Kr(t)??t;return new $e.FloPayError(n,"api_error")}function Wi(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 $e.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 kl(e,t){return e?e.isPaypal?"paypal":"card":t&&Wr(t)?"card":void 0}async function Hi({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,Xr.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,Xr.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 $e.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=Zs(require("react"),1);function Mo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Xa(e,t){if(e)return{error:n=>e.error(Mo(t,n)),log:n=>e.log(Mo(t,n)),performance:n=>e.performance(Mo(t,n)),terminal:n=>e.terminal(Mo(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 _l={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 El(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 vd=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 Cd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return vd.has(t.charAt(0).toLowerCase()+t.slice(1))}function Sd(e,t){return typeof t=="number"&&t!==0&&!Cd(e)?`${t}px`:String(t).trim()}function Tl(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]=Sd(n,r)}}}var Al=require("react/jsx-runtime"),Ki=new WeakSet;function Bo({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),B=(0,$n.useRef)(u),I=(0,$n.useRef)(p);v.current=d,B.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()}),Fe=e.on("error",re=>{B.current?.(re.message??"There was a problem loading the secure card form.")}),oe=e.on("validation",re=>{I.current?.(re.message??null)}),je=G.current??(Ki.has(e)?null:void 0),yt={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...w.current?{theme:w.current}:{},...je===void 0?{}:{submitLabel:je}};return h.current=w.current??null,T.current=G.current,G.current!==void 0&&Ki.add(e),e.mount(Y,yt).then(()=>{X()}).catch(re=>{U&&B.current?.(re instanceof Error?re.message:"Failed to load the secure card form.")}),()=>{U=!1,he(),Fe(),oe(),e.unmount()}},[e,t,n,r]),ro(()=>{let Y=b.current;Y&&Tl(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&&Ki.add(e),e.setSubmitLabel?.(O??null))},[e,O]),(0,Al.jsx)("div",{ref:b,"data-testid":"flopay-vault-card-fields"})}var Ml=/^#([0-9a-f]{6})$/i,wd=/^#([0-9a-f]{3})$/i,Bl=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Fl=/^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,kd=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,Id=/^(-?\d+(?:\.\d+)?)(?:px)?$/,Rd=/^(-?\d+(?:\.\d+)?)em$/,_d=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,Ed=/^[a-z][a-z0-9 -]{0,31}$/i,Td=new Set(["none","uppercase","lowercase","capitalize"]);function Dl(e){if(typeof e!="string")return null;let t=e.trim(),n=Ml.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=wd.exec(t);if(r){let[b,v,B]=r[1].split("").map(I=>Number.parseInt(I+I,16));return{r:b,g:v,b:B,a:null}}let o=Bl.exec(t),a=o?null:Fl.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 Ol({r:e,g:t,b:n,a:r}){return r===null?`#${(1<<24|e<<16|t<<8|n).toString(16).slice(1)}`:`rgba(${e},${t},${n},${r})`}function ca(e){if(typeof e!="string")return;let t=e.trim();if(Ml.test(t)||Bl.test(t))return t;let n=Fl.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=Dl(t);return r?Ol(r):void 0}function Ja(e,t=.12){let n=Dl(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Ol({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function da(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 ao(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=Id.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Ad(e,t,n){if(typeof e!="string")return;let r=Rd.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function xd(e){let t=da(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=da(o," "),l=ca(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 Md(e){if(typeof e!="string")return;let t=e.trim(),n=ca(t);if(n)return{type:"solid",color:n};let r=kd.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=xd(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function Bd(e){return e.type==="solid"?{type:"solid",color:Ja(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:Ja(t.color)}))}}function Fd(e){let t=!1,n,r=[];for(let u of da(e," ")){if(u.toLowerCase()==="inset"){t=!0;continue}let p=ca(u);if(p){n=p;continue}let b=ao(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 Dd(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=da(t,",").map(Fd);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function xl(e){if(typeof e!="string")return;let t=da(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>Ed.test(n)).slice(0,4);return t.length>0?t:void 0}function Od(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=ao(t[0],0,64),r=ao(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=Md(r.background??r.backgroundColor),l=ca(o?.colorPrimaryHover),d=l?{type:"solid",color:l}:a&&Bd(a),u={fontFamilies:xl(r.fontFamily)??xl(n),fontSize:ao(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:Ld(r.fontWeight)??600,letterSpacing:Ad(r.letterSpacing,-.1,.5)??.01,lineHeight:ao(r.lineHeight,.8,2)??1,textTransform:Td.has(String(r.textTransform))?r.textTransform:"uppercase"},p=Od(r.padding),b=Dd(r.boxShadow),v=ao(r.borderRadius,0,9999),B=typeof r.backdropFilter=="string"?ao(_d.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:ca(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,...B===void 0?{}:{backdropBlur:B}}}function Fo(e,t=.12){let n=e.trim(),r=/^[0-9a-fA-F]{6}$/.test(n)?`#${n}`:n;return/^#[0-9a-fA-F]{6}$/.test(r)?Ja(r,t):e}function Gi(e){if(typeof e=="number"||typeof e=="string")return e}function Za({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=Ll({appearance:e,buttonsStyles:t,fontFamily:p});return{primaryColor:l,primaryHoverColor:o(r?.colorPrimaryHover)??Fo(l,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(u?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(d?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:p,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(Gi(u?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...b?{submitButton:b}:{}}}var c=require("react/jsx-runtime"),Tr="flopay_stripe_resume",Nl="flopay_wallet_resume",Xl="fw1",Nd="fw2",Jl=300*1e3,zd=900,Ud=25e3,qd=25e3,$d=1e4,Zl=["payment_intent","payment_intent_client_secret","redirect_status"],yr={provider:"paypal",paymentMethodCategory:"paypal"},Qa={},Yi={};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 rs(e){return`${Nd}:${e}`}function ei(e){return $t(rs(e))}function ti(e,t){if(typeof window>"u")return null;let n=rs(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>Jl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(ei(e),null):o}catch{return ei(e),null}}function jd(e){return $t(rs(e.sessionId),e)}function zl(e,t,n){let r=ti(e,t);return!r||r.clientSecret!==n?!1:ei(e)}function Xi(e,t,n){if(typeof window>"u")return;ti(e,t)?.clientSecret===n&&ei(e)}function Vd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Ji(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":Xo(e.status),o=Vd(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function Ul(e,t,n){let r=null;try{return await Promise.race([il(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},$d),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Wd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Ql(e){return e instanceof y.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ni(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 Ql(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var pa="flopay_paypal_resume",ua=new Map;function ec(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(pa);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function Hd(){if(typeof window>"u")return!1;let[e,t]=os();return e?ec(t)!==null:!1}function os(){let e=new URLSearchParams(window.location.search);return Zl.map(t=>e.get(t))}function as(){let e=new URL(window.location.href);for(let t of Zl)e.searchParams.delete(t);return e.toString()}function Kd(){$t(pa),window.history.replaceState({},"",as())}var Gd=250,ql="Just a moment \u2014 we are finalizing your order. Please press pay again.",Yd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function is(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 ri({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 Xd(e){return e instanceof y.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Zi(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function tc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=to(n),l=a.firstName?a:to(r?.name);return Bn({email:(0,y.isValidEmail)(o)?o:r?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Jd({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=tc({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 Zd=`
9
+ `})]})})}var Nl=require("@flopay/shared"),Cn=require("react");var zl=require("react/jsx-runtime");function ha({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,s]=(0,Cn.useState)(e instanceof Promise?null:e),[c,u]=(0,Cn.useState)(t instanceof Promise||!t?null:t),p=(0,Cn.useRef)(null),h=(0,Cn.useRef)(null),b=zo(r);(0,Cn.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,Cn.useEffect)(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),(0,Cn.useEffect)(()=>{if(a)return pn(a)?.subscribe?.(b)},[b,a]),(0,Cn.useEffect)(()=>{if(!(!c||c===a))return pn(c)?.subscribe?.(b)},[b,a,c]),(0,Cn.useEffect)(()=>{if(!a)return;let C=pn(a);return p.current=C?.beginCheckout()??C?.now()??0,C?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{C?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,Cn.useEffect)(()=>{let C=!1;return e instanceof Promise?e.then(f=>{C||s(f)},()=>{C||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{C=!0}},[b,e]),(0,Cn.useEffect)(()=>{let C=!1;if(!t){u(null);return}return t instanceof Promise?t.then(f=>{C||u(f)},()=>{C||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):u(t),()=>{C=!0}},[b,t]),(0,Cn.useEffect)(()=>{if(!a||h.current===a)return;h.current=a;let C=pn(a);C?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),C?.performance({stage:"checkout_render",durationMs:C.elapsed(p.current??0),durationMode:"machine"})},[b,a]);let I=(0,Nl.resolveBillingApiUrl)(n?.billingApiUrl),k=(0,Cn.useMemo)(()=>({flopay:a,paypalFlopay:c,billingApiUrl:I,emitInstrument:b}),[a,c,I,b]);return(0,zl.jsx)(rr.Provider,{value:k,children:o})}var oi="flopay_recent_completion_";function jo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(oi+e,JSON.stringify(t))}catch{}}function ns(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(oi+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(oi+e),!1):!0}catch{return!1}}async function ai(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}var ao=require("@flopay/js"),Je=require("@flopay/shared");var ba="card",$d=1e3;async function Wd(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function Hd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:s??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function io(e){return new Je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function rs(){return new Je.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function as(e,t){return Object.assign(e,{checkoutMethod:t})}function Gr(e,t){let n=e instanceof Je.FloPayError?e:new Je.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Pa(e,t){try{return await e()}catch(n){throw Gr(n,t)}}function ql(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Kd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function is(e){if(typeof document>"u"||typeof window>"u")throw new Je.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw io();let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let b=new AbortController,I=()=>b.abort();e.signal?.aborted?b.abort():e.signal?.addEventListener("abort",I);let k=window.setTimeout(()=>b.abort(),n);try{let C=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:b.signal});if(!C.ok)return{status:"unknown"};let f=await C.json().catch(()=>null);return Gd(f)}catch{return{status:"unknown"}}finally{window.clearTimeout(k),e.signal?.removeEventListener("abort",I)}},a,s=()=>e.pollCompletionEndpoint!==!1?o():(a??(a=o()),a),c=document.activeElement instanceof HTMLElement?document.activeElement:null,u=document.createElement("div");u.setAttribute("data-flopay-auto-3ds-overlay","1"),u.setAttribute("role","dialog"),u.setAttribute("aria-modal","true"),u.setAttribute("aria-label","Card authentication"),u.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let p=document.createElement("iframe");p.setAttribute("title","Card authentication"),p.setAttribute("allow","payment"),p.tabIndex=0,p.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}try{let b=await new Promise((I,k)=>{let C=!1,f=0,S=0,G=0,_=!1,q=()=>{window.clearTimeout(f),window.clearInterval(S),window.clearTimeout(G),window.removeEventListener("message",W),p.removeEventListener("load",ne),e.signal?.removeEventListener("abort",$)},E=async()=>{if(!(C||_)){_=!0;try{let ie=await s();if(C||!Kd(ie))return;C=!0,q(),I(ie)}finally{_=!1}}},ne=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(G),G=window.setTimeout(()=>{E()},250))},$=()=>{C||(C=!0,q(),k(io()))},W=ie=>{if(ie.source!==p.contentWindow||h&&ie.origin!==h)return;let V=ie.data;!V||typeof V!="object"||V.source!=="flopay-vault-3ds-return"||C||(C=!0,q(),I(null))};f=window.setTimeout(()=>{C||(C=!0,q(),k(rs()))},Je.THREE_DS_CHALLENGE_WINDOW_MS),e.pollCompletionEndpoint!==!1&&(S=window.setInterval(()=>{E()},t)),p.addEventListener("load",ne),window.addEventListener("message",W),e.signal?.addEventListener("abort",$),p.src=e.nextActionRedirectUrl,u.appendChild(p),document.body.appendChild(u),p.focus(),e.signal?.aborted&&$()});return b||await s()}finally{u.parentNode?.removeChild(u),c?.isConnected&&c.focus()}}async function $o(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,a=t.nonce??t.session.clientSecret,s=new ao.PaymentAPI(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,u=new AbortController,p=new AbortController,h=()=>{u.abort(o.reason),p.abort(o.reason)};o.aborted?h():o.addEventListener("abort",h,{once:!0});let b=is({billingApiUrl:n,sessionId:r,nonce:a,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:u.signal,pollCompletionEndpoint:!1}),I=s.waitForCheckoutSessionCompletion(r,{initialDelayMs:$d,nonce:a,statusUrl:c,continueAfterActionRequired:!0,timeoutMs:Je.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:p.signal}),k;try{let f=await Promise.race([b,I]);if("data"in f)k=f;else{if(f.status==="declined")throw Fr({type:f.declineReason??"authorization_declined",gatewayErrorCode:f.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(f.status==="timeout")throw rs();k=await I}}catch(f){if(o.aborted||f instanceof Error&&f.name==="AbortError")throw io(f);if(!(f instanceof Je.FloPayError)||f.code!=="three_ds_timeout"&&f.code!=="checkout_processing_timeout")throw f;try{k=await s.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:a,statusUrl:c,timeoutMs:5e3,signal:o})}catch(G){if(o.aborted)throw io(G);if(!(G instanceof Je.FloPayError)||G.code!=="checkout_processing_timeout")throw G}let S=k&&to(k,t.session);if(!$r(S)&&S?.status!=="expired"){if(t.telemetry){let G=new ao.PaymentAPI(n);try{G.reportThreeDsAbandoned(r)}finally{G.destroy()}}throw rs()}}finally{o.removeEventListener("abort",h),u.abort(),p.abort()}let C=k&&to(k,t.session);if(!$r(C))throw Do(C);return{...jr(C,r),checkoutMethod:"card"}}function Gd(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Fr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=eo(o)??o,s=as(new Je.FloPayError(a,"api_error",{code:e?.code??(0,Je.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Je.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(s.orderId=e.orderId),s}function os(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ii(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Vl(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ii(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let c of a)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||ii(c)))return c;let s=o.gateways;if(s&&typeof s=="object"){let c=s.stripe;if(c&&typeof c=="object"){let u=c,p=[u.stripeClientSecret,u.clientSecret];for(let h of p)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||ii(h)))return h}}}}async function Yd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Vl(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let c=(await new ao.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ii(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function Wo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:s}){let c=e.replace(/\/+$/,""),u=t??n.id,p=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",I=n.customer?.firstName??n.accountData?.firstName??"",k=n.customer?.lastName??n.accountData?.lastName??"",C=n.customer?.country??n.accountData?.country??void 0,f=n.customer?.zip??n.accountData?.zip??void 0,G=await new ao.PaymentAPI(c,s===!1?{telemetry:!1}:void 0).processPayment(h,{sessionId:u,nonce:p,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:h,email:b,firstName:I,lastName:k,country:C,zip:f},returnUrl:a??os(n)});if(G.ok){let E=typeof G.json=="function"?await G.json().catch(()=>null):null;if((0,Je.isAuthorizationOnlySession)(n)||E?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof E?.paymentId=="string"?E.paymentId:n.paymentId,sessionId:typeof E?.sessionId=="string"?E.sessionId:u,authorizationExpiresAt:typeof E?.authorizationExpiresAt=="string"?E.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:ua(o),checkoutMethod:Ul(o,n)}};let ne=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ne?{paymentIntentId:ne}:{},paymentMethodId:ua(o),checkoutMethod:Ul(o,n)}}}let _;try{_=await G.json()}catch(E){throw new Je.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:G.status,cause:E})}if(_?.type==="3ds_required"&&typeof _.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:_.nextActionRedirectUrl};if(_?.type==="paypal_redirect_required"||_?.type==="3ds_required"){let E=Vl(_);if(!E)throw new Je.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:G.status});return{type:_.type,threeDSecureToken:E,paymentMethodId:_.paymentMethodId}}if(_?.gatewayErrorCode==="authentication_required"){let E=await Yd({billingApiUrl:c,sessionId:u,nonce:p,responseJson:_});if(E)return E;throw as(new Je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let q=new Je.FloPayError(_?.message??"Payment failed. Please try again.","api_error",{code:_?.code??_?.gatewayErrorCode,declineCode:_?.declineCode??_?.gatewayDeclineReason,statusCode:G.status});throw Object.assign(q,{telemetryOutcome:(0,Je.classifyPaymentRejection)(G.status,_)})}async function si(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:s,returnUrl:c,telemetry:u,signal:p}){let h=t?.getRawProvider();if(!h)throw Gr(new Je.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw as(new Je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let b=(0,Je.isSetupIntentClientSecret)(e.threeDSecureToken),I=null,k=e.paymentMethodId,C=await Pa(()=>Wd(h,e.threeDSecureToken,b),"card");if(C){if(C.error)throw Gr(new Je.FloPayError(C.error.message??`Failed to retrieve 3DS ${b?"setup":"payment"} status.`,"api_error",{code:C.error.code}),"card");let S=C.intent;!k&&S?.payment_method&&(typeof S.payment_method=="string"?k=S.payment_method:"id"in S.payment_method&&(k=S.payment_method.id??void 0))}let f=k?await Pa(()=>Hd(h,e.threeDSecureToken,{payment_method:k,return_url:c??os(s)??window.location.href},b),"card"):null;if(f){if(f.error)throw Gr(new Je.FloPayError(f.error.message??"3DS authentication failed.","api_error",{code:f.error.code}),"card");I=f.intent}else{let S=await Pa(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(S.error)throw Gr(new Je.FloPayError(S.error.message??"3DS authentication failed.","api_error",{code:S.error.code}),"card");I=(b?S.setupIntent:S.paymentIntent)??null}if(I&&(I.status==="requires_capture"||I.status==="succeeded"||I.status==="processing")){let S=await Wo({billingApiUrl:o,sessionId:a,session:s,telemetry:u,tokenizedData:{id:I.id,type:"card",threeDSecureActionResultTokenId:I.id},returnUrl:c});return S.type==="success"?{...S.result,paymentIntentId:S.result.paymentIntentId??I.id,paymentMethodId:S.result.paymentMethodId??k}:S.type==="next_action_required"?$o(S,{billingApiUrl:o,sessionId:a??s.id,session:s,signal:p}):si(S,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:s,returnUrl:c,telemetry:u,signal:p})}throw Gr(new Je.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let b=(n??t)?.getRawProvider();if(!b)throw Gr(new Je.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:k}=await Pa(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(k)throw Gr(new Je.FloPayError(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:I}=await Pa(()=>b.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??os(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(I)throw Gr(new Je.FloPayError(I.message??"PayPal authorization failed.","api_error",{code:I.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Je.FloPayError("Unsupported payment redirect state.","api_error")}function va(e){if(e instanceof Je.FloPayError){let r=eo(e.message);return r&&r!==e.message?Object.assign(new Je.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=eo(t)??t;return new Je.FloPayError(n,"api_error")}function ss(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Zr(e.data.session);if(!t&&!n&&!r)throw new Je.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function Ul(e,t){return e?e.isPaypal?"paypal":"card":t&&Zr(t)?"card":void 0}async function ls({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=t&&t!==e?t:void 0,[s,c]=await Promise.all([(0,ao.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,ao.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(p=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",p),null)):Promise.resolve(null)]);if(!s)throw new Je.FloPayError("The payment provider did not initialize.","authentication_error");let u=null;return a?u=c:t&&(u=s),{flopay:s,paypalFlopay:u}}var Cr=require("@flopay/js"),y=require("@flopay/shared"),Zt=require("@stripe/react-stripe-js"),i=ji(require("react"),1);function Ho(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function li(e,t){if(e)return{error:n=>e.error(Ho(t,n)),log:n=>e.log(Ho(t,n)),performance:n=>e.performance(Ho(t,n)),terminal:n=>e.terminal(Ho(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}var jl={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var Kn=require("react");function ci(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(s=>s.startsWith("background")),a={};for(let[s,c]of Object.entries(e))s in n||o&&s.startsWith("background")||(a[s]=c);for(let s of r)a[s]=n[s];return a}var Xd=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function Jd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Xd.has(t.charAt(0).toLowerCase()+t.slice(1))}function Zd(e,t){return typeof t=="number"&&t!==0&&!Jd(e)?`${t}px`:String(t).trim()}function $l(e,t){if(e.style.cssText="",!!t){for(let[n,r]of Object.entries(t))if(!(r==null||r==="")){if(n.startsWith("--")){e.style.setProperty(n,String(r));continue}e.style[n]=Zd(n,r)}}}var Wl=require("react/jsx-runtime"),cs=new WeakSet;function so({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:s,onReady:c,onError:u,onValidation:p}){let h=(0,Kn.useRef)(null),b=(0,Kn.useRef)(c),I=(0,Kn.useRef)(u),k=(0,Kn.useRef)(p);b.current=c,I.current=u,k.current=p;let C=(0,Kn.useRef)(o);C.current=o;let f=(0,Kn.useRef)(null),S=a??void 0,G=(0,Kn.useRef)(S);G.current=S;let _=(0,Kn.useRef)(void 0);return(0,Kn.useEffect)(()=>{let q=h.current;if(!q)return;let E=!0,ne=!1,$=()=>{!E||ne||(ne=!0,b.current?.())},W=e.on("ready",()=>{$()}),ie=e.on("error",X=>{I.current?.(X.message??"There was a problem loading the secure card form.")}),V=e.on("validation",X=>{k.current?.(X.message??null)}),Be=G.current??(cs.has(e)?null:void 0),Ue={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...C.current?{theme:C.current}:{},...Be===void 0?{}:{submitLabel:Be}};return f.current=C.current??null,_.current=G.current,G.current!==void 0&&cs.add(e),e.mount(q,Ue).then(()=>{$()}).catch(X=>{E&&I.current?.(X instanceof Error?X.message:"Failed to load the secure card form.")}),()=>{E=!1,W(),ie(),V(),e.unmount()}},[e,t,n,r]),go(()=>{let q=h.current;q&&$l(q,s)},[s]),(0,Kn.useEffect)(()=>{o!==void 0&&(o===null&&f.current===null||(f.current=o,e.applyTheme?.(o)))},[e,o]),(0,Kn.useEffect)(()=>{S!==_.current&&(_.current=S,S!==void 0&&cs.add(e),e.setSubmitLabel?.(S??null))},[e,S]),(0,Wl.jsx)("div",{ref:h,"data-testid":"flopay-vault-card-fields"})}var Kl=/^#([0-9a-f]{6})$/i,Qd=/^#([0-9a-f]{3})$/i,Gl=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Yl=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+|1\.0+)\s*\)$/i,eu=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,tu=/^(-?\d+(?:\.\d+)?)(?:px)?$/,nu=/^(-?\d+(?:\.\d+)?)em$/,ru=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,ou=/^[a-z][a-z0-9 -]{0,31}$/i,au=new Set(["none","uppercase","lowercase","capitalize"]);function Xl(e){if(typeof e!="string")return null;let t=e.trim(),n=Kl.exec(t);if(n){let h=Number.parseInt(n[1],16);return{r:h>>16&255,g:h>>8&255,b:h&255,a:null}}let r=Qd.exec(t);if(r){let[h,b,I]=r[1].split("").map(k=>Number.parseInt(k+k,16));return{r:h,g:b,b:I,a:null}}let o=Gl.exec(t),a=o?null:Yl.exec(t),s=o??a;if(!s)return null;let c=Number(s[1]),u=Number(s[2]),p=Number(s[3]);return c>255||u>255||p>255?null:{r:c,g:u,b:p,a:a?Number(a[4]):null}}function Jl({r:e,g:t,b:n,a:r}){return r===null?`#${(1<<24|e<<16|t<<8|n).toString(16).slice(1)}`:`rgba(${e},${t},${n},${r})`}function Ca(e){if(typeof e!="string")return;let t=e.trim();if(Kl.test(t)||Gl.test(t))return t;let n=Yl.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=Xl(t);return r?Jl(r):void 0}function di(e,t=.12){let n=Xl(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Jl({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function Sa(e,t){let n=[],r=0,o="";for(let a of e){if(a==="("&&(r+=1),a===")"&&(r-=1),a===t&&r===0){o.trim()&&n.push(o.trim()),o="";continue}o+=a}return o.trim()&&n.push(o.trim()),n}function Po(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=tu.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function iu(e,t,n){if(typeof e!="string")return;let r=nu.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function su(e){let t=Sa(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=Sa(o," "),s=Ca(a[0]);if(!s)return;let c=r/(t.length-1)*100,u=a[1]===void 0?c:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),p=n[n.length-1]?.position??-1;if(!Number.isFinite(u)||u<0||u>100||u<p)return;n.push({color:s,position:u})}return{type:"linearGradient",angle:0,stops:n}}function lu(e){if(typeof e!="string")return;let t=e.trim(),n=Ca(t);if(n)return{type:"solid",color:n};let r=eu.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=su(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function cu(e){return e.type==="solid"?{type:"solid",color:di(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:di(t.color)}))}}function du(e){let t=!1,n,r=[];for(let u of Sa(e," ")){if(u.toLowerCase()==="inset"){t=!0;continue}let p=Ca(u);if(p){n=p;continue}let h=Po(u,-128,128);if(h===void 0)return;r.push(h)}if(!n||r.length<2||r.length>4)return;let[o,a,s=0,c=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||s>128||Math.abs(c)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:s,spread:c}}function uu(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=Sa(t,",").map(du);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function Hl(e){if(typeof e!="string")return;let t=Sa(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>ou.test(n)).slice(0,4);return t.length>0?t:void 0}function pu(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=Po(t[0],0,64),r=Po(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function mu(e){if(e==="bold")return 700;if(e==="normal")return 400;let t=Number(e);return Number.isInteger(t)&&t>=100&&t<=900?t:void 0}function Zl({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=lu(r.background??r.backgroundColor),s=Ca(o?.colorPrimaryHover),c=s?{type:"solid",color:s}:a&&cu(a),u={fontFamilies:Hl(r.fontFamily)??Hl(n),fontSize:Po(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:mu(r.fontWeight)??600,letterSpacing:iu(r.letterSpacing,-.1,.5)??.01,lineHeight:Po(r.lineHeight,.8,2)??1,textTransform:au.has(String(r.textTransform))?r.textTransform:"uppercase"},p=pu(r.padding),h=uu(r.boxShadow),b=Po(r.borderRadius,0,9999),I=typeof r.backdropFilter=="string"?Po(ru.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Ca(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...c?{hoverBackground:c}:{},typography:u,...p?{spacing:p}:{},...h?{shadow:h}:{},...b===void 0?{}:{borderRadius:b},disabledOpacity:e?.theme==="night"?.8:.6,...I===void 0?{}:{backdropBlur:I}}}function Ko(e,t=.12){let n=e.trim(),r=/^[0-9a-fA-F]{6}$/.test(n)?`#${n}`:n;return/^#[0-9a-fA-F]{6}$/.test(r)?di(r,t):e}function ds(e){if(typeof e=="number"||typeof e=="string")return e}function Go({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=b=>typeof b=="string"&&b?b:void 0,a=t.submitButton,s=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",c=n==="buttons",u=t.nameInput,p=o(u?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",h=Zl({appearance:e,buttonsStyles:t,fontFamily:p});return{primaryColor:s,primaryHoverColor:o(r?.colorPrimaryHover)??Ko(s,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(u?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(c?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:p,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(ds(u?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...h?{submitButton:h}:{}}}var d=require("react/jsx-runtime"),Br="flopay_stripe_resume",Ql="flopay_wallet_resume",uc="fw1",yu="fw2",pc=300*1e3,fu=900,gu=25e3,hu=25e3,Pu=1e4,mc=["payment_intent","payment_intent_client_secret","redirect_status"],vr={provider:"paypal",paymentMethodCategory:"paypal"},ui={},us={};function Wt(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function bs(e){return`${yu}:${e}`}function pi(e){return Wt(bs(e))}function mi(e,t){if(typeof window>"u")return null;let n=bs(e);try{let r=localStorage.getItem(n);if(!r)return null;let o=JSON.parse(r);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>pc||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(pi(e),null):o}catch{return pi(e),null}}function bu(e){return Wt(bs(e.sessionId),e)}function ec(e,t,n){let r=mi(e,t);return!r||r.clientSecret!==n?!1:pi(e)}function ps(e,t,n){if(typeof window>"u")return;mi(e,t)?.clientSecret===n&&pi(e)}function vu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ms(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let r=n?e.status==="succeeded":da(e.status),o=vu(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function tc(e,t,n){let r=null;try{return await Promise.race([wl(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},Pu),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Cu(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function yc(e){return e instanceof y.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function yi(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Cr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw yc(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ka="flopay_paypal_resume",wa=new Map;function fc(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(ka);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function Su(){if(typeof window>"u")return!1;let[e,t]=vs();return e?fc(t)!==null:!1}function vs(){let e=new URLSearchParams(window.location.search);return mc.map(t=>e.get(t))}function Cs(){let e=new URL(window.location.href);for(let t of mc)e.searchParams.delete(t);return e.toString()}function wu(){Wt(ka),window.history.replaceState({},"",Cs())}var ku=250,nc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Iu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Ss(e,t,n,r){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...r?{terminalReason:r}:{}})}async function fi({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Cr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Ru(e){return e instanceof y.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ys(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function gc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=mo(n),s=a.firstName?a:mo(r?.name);return On({email:(0,y.isValidEmail)(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function _u({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let s=gc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,y.isValidEmail)(s.email)?s:a(o,s)}var Eu=`
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 @@ ${Ne.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
- `,ma=44,ya=180,$l=`flopay-card-enter ${ya}ms cubic-bezier(0, 0, 0.2, 1) both`,jl=`flopay-card-exit ${ya}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Qd=`flopay-buttons-enter ${ya}ms cubic-bezier(0, 0, 0.2, 1) both`,eu=`flopay-buttons-exit ${ya}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function tu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ss(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 nu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function ru(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 es={width:"100%",minHeight:ma,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function ou(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Vl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ts(e){return e==="paypal"?"PayPal":(0,y.getStripeMethodDisplayName)(e)}function au(e){let t=(0,y.getPostalCodeExample)(e);return`Enter a valid ${(0,y.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function iu(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 su(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 Wl(e,t){return t instanceof y.FloPayError?t:new y.FloPayError(t instanceof Error?t.message:`${ou(e)} before-click hook failed.`,"validation_error")}function Qi(){return(0,c.jsx)("style",{children:Zd})}function lu(e){return typeof e=="number"?`${e}px`:e}function nc(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function rc({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 Hl(e){return e!=="unavailable"&&e!=="load_error"}function oi(e){return(0,c.jsx)(du,{...e})}function Kl({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:B,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)(()=>Xa(dn(T),O),[O,T]),[he,Fe]=(0,i.useState)("loading");(0,i.useEffect)(()=>{I?.(he)},[he,I]);let[oe,je]=(0,i.useState)(!1),yt=(0,i.useRef)(!1),re=!(0,y.isValidEmail)(n?.trim())||!v?.trim(),{request:De,collect:ft,finish:ke}=So(),Oe=(0,i.useRef)(!1),be=(0,i.useRef)(null),me=(0,i.useRef)(null),[Ie,Ve]=(0,i.useState)(0),[rt,R]=(0,i.useState)(!1),We=(0,i.useRef)(!1),ye=(0,i.useRef)(new Map),{startAttempt:N,finishAttempt:ve,invalidateAttempt:ue,isAttemptInvalidated:He,isAttemptCurrent:Q,generationRef:ot}=na((q,fe,et)=>{p?.(q,fe,{...et,popupBlocked:et?.popupBlocked??Yr(fe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:G,terminalReason:"overlay_timeout"}),R(!0),Ve(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)(()=>{Ve(q=>q+1)},[]),Te=(0,i.useCallback)((q,fe,et)=>{ue(et),p?.("paypal",q,{code:fe,popupBlocked:Yr(q),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:G}),R(!0),lt()},[ue,p,G,lt]),Le=(0,i.useCallback)(()=>{window.setTimeout(()=>{(be.current?.querySelector("iframe")??be.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{We.current&&(We.current=!1,Le())},[Le,Ie]);let ct=(0,i.useCallback)(()=>{R(!1),a?.(null),Le()},[Le,a]);(0,i.useEffect)(()=>{if(!U||Oe.current)return;let[q,fe,et]=os();if(!q||!fe)return;let V=ec(fe);if(!V)return;Oe.current=!0;let xe=!0,bt=ua.get(fe);bt||(bt=et==="failed"?Promise.resolve(null):Promise.resolve().then(()=>U.retrievePaymentIntent(fe)),ua.set(fe,bt));let Ke={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{je(!0);let f=await bt;if(!xe)return;if(f?.error){ua.delete(fe),$(),a?.(f.error.message??"Failed to retrieve PayPal payment status.");return}if(Kd(),ua.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},{...Ke,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(!xe)return;ua.delete(fe),$(),a?.(f instanceof Error?f.message:"Failed to complete PayPal payment.")}finally{xe&&je(!1)}})(),()=>{xe=!1,Oe.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]),Ae=(0,i.useCallback)(async q=>{if(l||oe||!await at()){q.reject();return}q.resolve()},[l,at,oe]),jt=(0,i.useCallback)(async q=>{if(!U||!de)return;let fe=ye.current.get(Ie);if(fe&&!Q(fe.generation)){ye.current.delete(Ie);return}if(!fe&&He()||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,xe=et?.nonce??t,bt=await Jd({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 Ke=bt.email,$={...et?.accountPatch,...Bn(bt,!0)};try{if(je(!0),a?.(null),!V||!(0,y.isValidEmail)(Ke))throw new Error("Missing sessionId or email for PayPal payment");await B?.(bt);let Je=U.createPaymentMethod,{error:f,paymentMethod:P}=await Je({type:"paypal"});if(f){Te(f,"stripe_paypal_create_payment_method_failed",fe?.generation),q.paymentFailed({reason:"fail"});return}let H=await ni(r,Y,V,xe??"",{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 ee=H.clientSecret,qe={return_url:as()};if(P?.id&&(qe.payment_method=P.id),!$t(pa,{clientSecret:ee,sessionId:V,nonce:xe,accountPatch:$})&&G==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:Ge,paymentIntent:Z}=await U.confirmPayment({clientSecret:ee,confirmParams:qe,redirect:"if_required"});if(Ge){if($t(pa),Zo(Ge)){let Ct=Ge.message??"Your payment was declined.";X?.terminal({outcome:"payment_declined",...yr,terminalReason:"provider_declined"}),a?.(Ct),u?.(cn("paypal",Ct,{code:_r(Ge),declineCode:ko(Ge)})),await ri({billingApiUrl:r,sessionId:V,nonce:xe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:_r(Ge)??"provider_declined"}})}else Te(Ge,"stripe_paypal_confirm_failed",fe?.generation);return}$t(pa);let it=typeof Z?.payment_method=="string"?Z.payment_method:Z?.payment_method?.id;o({id:it??Z?.id,type:"card",threeDSecureActionResultTokenId:Z?.id,isPaypal:!0},{accountPatch:$,paymentMethodCategory:"paypal",presentationMode:G,sessionId:V,nonce:xe});return}catch(Je){Te(Je,"stripe_paypal_failed",fe?.generation)}finally{je(!1)}},[U,de,e,t,n,v,ft,B,r,Y,o,a,u,b,Te,ve,Q,He,X,G,Ie]),Vt=(0,i.useCallback)(async()=>{if(!(yt.current||l||oe||!U||!de)){yt.current=!0,je(!0);try{if(!await at(!0))return;await jt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{yt.current=!1,je(!1)}}},[de,jt,l,at,U,oe]),ut=G==="redirect"?(0,c.jsx)("button",{type:"button",disabled:l||oe,onClick:()=>{Vt()},style:{width:"100%",minHeight:ma,border:"1px solid #d1d5db",borderRadius:w??8,background:"#ffc439",color:"#111827",cursor:l||oe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,c.jsx)(Jt.ExpressCheckoutElement,{onReady:q=>Fe(nc(q,["paypal"])),onLoadError:()=>{Fe("load_error"),is(X,"paypal","paypal","provider_error")},onClick:Ae,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),We.current=!0,lt()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:re,emailRequired:re,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:es,children:"Try PayPal again"}),De&&(0,c.jsx)(wo,{identity:De.identity,methodLabel:De.methodLabel,onComplete:ke,onCancel:()=>ke(null)},De.id),(0,c.jsx)("div",{style:{display:De?"none":void 0},children:ut})]}),oe&&!De&&(0,c.jsx)(er,{status:"processing"})]});return G==="redirect"?Et:(0,c.jsx)(rc,{state:he,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:Et})}function Gl({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:B,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)(()=>Xa(dn(T),G),[G,T]),[he,Fe]=(0,i.useState)("loading");(0,i.useEffect)(()=>{w?.(he)},[he,w]);let[oe,je]=(0,i.useState)(!1),yt=(0,i.useRef)(!(0,y.isValidEmail)(n?.trim())||!B?.trim()).current,{request:re,collect:De,finish:ft}=So(),ke=(0,i.useRef)(null),Oe=(0,i.useRef)(null),[be,me]=(0,i.useState)(0),[Ie,Ve]=(0,i.useState)(!1),[rt,R]=(0,i.useState)(()=>ti(e,t)?"blocked":"idle"),[We,ye]=(0,i.useState)("google_pay"),N=(0,i.useRef)(null),ve=(0,i.useRef)(!0),ue=(0,i.useRef)(!1),He=(0,i.useRef)("google_pay"),Q=(0,i.useRef)("google_pay"),ot=(0,i.useRef)(null),lt=(0,i.useRef)(null),Te=(0,i.useRef)(new Set);(0,i.useEffect)(()=>(ve.current=!0,()=>{ve.current=!1;for(let $ of Te.current)window.clearTimeout($);Te.current.clear()}),[]);let Le=(0,i.useRef)(new Map),{startAttempt:ct,finishAttempt:at,invalidateAttempt:Ae,isAttemptInvalidated:jt,isAttemptCurrent:Vt,generationRef:ut}=na(($,Je,f)=>{b?.($,Je,{...f,popupBlocked:f?.popupBlocked??Yr(Je),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ye($),Ve(!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&&Oe.current?.focus()},[Ie,be]);let Et=(0,i.useCallback)(()=>{me($=>$+1)},[]),q=(0,i.useCallback)(($,Je,f,P,H=!1)=>{Ae(P),b?.($,Je,{code:f,popupBlocked:Yr(Je),telemetryReported:H,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ye($),Ve(!0),Et()},[Ae,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)(()=>{Ve(!1),d?.(null),fe()},[fe,d]),V=(0,i.useCallback)(()=>{N.current?.()},[]);(0,i.useEffect)(()=>{let $=ti(e,t);if(!$)return;let Je=!1,f=!1,P=async()=>{if(!f){f=!0,Je||R("checking");try{let H=await Ul(U,$.clientSecret,Te.current);if(Je)return;let ee=Ji(H,$.providerObjectId,(0,y.isSetupIntentClientSecret)($.clientSecret));if(ee.kind==="confirmed"){if(!zl(e,t,$.clientSecret))return;N.current=null,R("idle"),l({id:ee.paymentMethodId,type:"card",threeDSecureActionResultTokenId:ee.intentId},{...$.accountPatch?{accountPatch:$.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(ee.kind==="terminal"){Xi(e,t,$.clientSecret),N.current=null,R("idle"),ye($.paymentMethodType),Ve(!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 xe=(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=Le.current.get(be);if(P&&!Vt(P.generation)){Le.current.delete(be),f();return}if(!P&&jt()){f();return}if(P&&!at(P.generation)){f();return}P||at();let H=$.expressPaymentType??P?.method??He.current,ee=P??null,qe=Vl(H),vt;H==="apple_pay"?vt="apple_pay":H==="google_pay"&&(vt="google_pay");let Ge=P?.generation??ut.current,Z=X,it=Z?.now()??globalThis.performance?.now()??Date.now(),Ct=new AbortController,Nt=!1,Ne=!1,Ft=null,ze=e,Fn="processing",Rn="other",Mt="provider_runtime",wn,Dn=new Promise((Ce,St)=>{wn=St}),On=window.setTimeout(()=>{Nt=!0,Ct.abort(),wn(Qa)},Ud),rn=async(Ce,St,Tt)=>{Fn=Ce,Rn=St,Mt=St==="intent_create"||St==="session_claim"?"transport_error":"provider_runtime";let vn=Z?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Tt,Dn])}finally{let Bt=Z?.now()??globalThis.performance?.now()??Date.now();Z?.performance({stage:Ce,durationMs:Math.max(0,Bt-vn),durationMode:"machine",requestCategory:St,paymentMethodCategory:"wallet",provider:"stripe",...Nt?{statusClass:"timeout"}:{}})}};try{if(je(!0),d?.(null),!ee&&v){let Re=await rn("processing","other",v(qe));if(!Re.proceed){f();return}ee={accountPatch:Re.accountPatch,sessionId:Re.sessionId,nonce:Re.nonce}}let Ce=ee?.sessionId??e;ze=Ce;let St=ee?.nonce??t,Tt=ot.current??ee?.accountPatch,vn=tc({event:$,fallbackEmail:Tt?.email??n,fallbackName:[Tt?.firstName,Tt?.lastName].join(" ").trim()||B});if(!(0,y.isValidEmail)(vn.email)){f("Buyer details are required."),De(ts(H),vn).then(Re=>{Re&&(ot.current=Re)});return}ot.current=null;let Bt={...ee?.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",ni(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=jd({createdAt:Date.now(),sessionId:Ce,...St?{nonce:St}:{},clientSecret:wt,providerObjectId:mn.providerObjectId,paymentMethodType:H,accountPatch:Bt});window.clearTimeout(On),Ne=!0,Z?.performance({stage:"callback",durationMs:Math.max(0,(Z?.now()??globalThis.performance?.now()??Date.now())-it),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let yn=Z?.now()??globalThis.performance?.now()??Date.now(),Dt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...vt?{walletType:vt}:{},attempt:Ge},Qt=!1,Ht=null;Z?.log({name:"payment.provider_confirmation.started",...Dt}),Ft=window.setTimeout(()=>{Ft!==null&&Te.current.delete(Ft),Qt=!0;let Re=Z?.now()??globalThis.performance?.now()??Date.now();Z?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Dt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Re-yn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Z?.flush?.().catch(()=>{}),Ht?.()},qd),Te.current.add(Ft);let fn=(Re,ht)=>{Ft!==null&&(window.clearTimeout(Ft),Te.current.delete(Ft),Ft=null);let ie=Z?.now()??globalThis.performance?.now()??Date.now(),F=Math.max(0,ie-yn),Ze=Re;Qt&&(Re==="resolved"?Ze="resolved_late":Re==="returned_error"?Ze="returned_error_late":Ze="rejected_late");let se=ht??(Re==="resolved"?"approved":"provider_error");return Z?.log({name:"payment.provider_confirmation.returned",...Dt,operationOutcome:Ze,terminalReason:se}),Z?.performance({...Dt,durationMs:F,durationMode:"buyer",operationOutcome:Ze,terminalReason:se}),{durationMs:F,operationOutcome:Ze,terminalReason:se}},gt=!1,te=!1,Ln=Re=>{if(!Re||typeof Re!="object")return null;let ht=Re;if(ht.error)return null;let ie=ht.setupIntent??ht.paymentIntent,F=Ji(ie??null,void 0,!!ht.setupIntent);return F.kind==="confirmed"?F:null},Nn=Re=>{if(gt||P&&ut.current!==P.generation)return;let ht=Ln(Re);if(!ht)return;if(Zt&&!zl(Ce,St,wt)){gt=!0;return}let{intentId:ie,paymentMethodId:F}=ht;gt=!0,te=!0,lt.current=null,N.current=null,ve.current&&(R("idle"),je(!1));let Ze=`${Xl}:${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||te)){hr=!0,ve.current&&R("checking");try{let Re=await Ul(U,wt,Te.current);if(gt||te)return;let ht=(0,y.isSetupIntentClientSecret)(wt),ie=Ji(Re,mn.providerObjectId,ht);if(ie.kind==="confirmed"){Nn(ht?{setupIntent:Re}:{paymentIntent:Re});return}if(ie.kind==="terminal"){if(te=!0,Xi(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&&!te&&(R("blocked"),je(!1))}catch{ve.current&&!te&&(R("blocked"),je(!1))}finally{hr=!1}}},N.current=Ht;let Cn,sn;try{let Re=await((0,y.isSetupIntentClientSecret)(wt)?U.confirmSetup({elements:de,clientSecret:wt,redirect:"if_required"}):U.confirmPayment({elements:de,clientSecret:wt,redirect:"if_required"}));if(!Re||typeof Re!="object"||(Cn=Re,!Cn.error&&!Ln(Cn)))throw Yi;sn=fn(Cn.error?"returned_error":"resolved",Cn.error&&Zo(Cn.error)?"provider_declined":void 0)}catch(Re){let ht=Re===Yi,ie=fn(ht?"returned_error":"rejected");if(Z?.error({...ht?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:Mi(Re),...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(Zo(_n)){te=!0,Xi(Ce,St,wt),lt.current=null,N.current=null,R("idle");let Re=_n.message??"Your payment was declined.";f(Re),d?.(Re),p?.(cn(qe,Re,{code:_r(_n),declineCode:ko(_n)})),ri({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 Z?.error({...Mi(_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===Qa){let St=Z?.now()??globalThis.performance?.now()??Date.now();Z?.error({errorCode:Wd(Rn),stage:Fn,requestCategory:Rn,paymentMethodCategory:"wallet",provider:"stripe",...vt?{walletType:vt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:ze,durationMs:Math.max(0,St-it),statusClass:"timeout",failureCategory:Mt,attempt:Ge,terminalReason:"provider_error"}),Z?.flush?.().catch(()=>{})}f(),q(H,Ce,Ce===Qa?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",P?.generation,Ce===Qa)}finally{if(window.clearTimeout(On),Ft!==null&&(window.clearTimeout(Ft),Te.current.delete(Ft)),!Ne){let Ce=Z?.now()??globalThis.performance?.now()??Date.now();Z?.performance({stage:"callback",durationMs:Math.max(0,Ce-it),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Nt?{statusClass:"timeout"}:{}})}ve.current&&je(!1)}},[U,de,e,t,n,B,De,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]),Ke=(0,i.useMemo)(()=>a.map(y.stripeExpressMethodToOptionKey),[a]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(rc,{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:Oe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:et,style:es,children:["Try ",ts(We)," 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:es,children:rt==="checking"?"Checking payment status\u2026":"Check payment status"})]}),re&&(0,c.jsx)(wo,{identity:re.identity,methodLabel:re.methodLabel,onComplete:ft,onCancel:()=>ft(null)},re.id),rt==="idle"&&(0,c.jsx)("div",{style:{display:re?"none":void 0},children:(0,c.jsx)(Jt.ExpressCheckoutElement,{onReady:$=>{Fe(nc($,Ke))},onLoadError:$=>{Fe("load_error"),is(X,"stripe","wallet","provider_error")},onClick:async $=>{He.current=$.expressPaymentType,Q.current=Vl($.expressPaymentType);let Je=!0,f=window.setTimeout(()=>{Je=!1,$.reject()},zd),P=v?await v(Q.current):{proceed:!0};if(window.clearTimeout(f),!Je)return;if(!P.proceed){Le.current.delete(be),$.reject();return}let H=ct($.expressPaymentType);Le.current.set(be,{generation:H,method:$.expressPaymentType,accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}),Ve(!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?.(Q.current),$.resolve()},onConfirm:xe,onCancel:()=>{let $=Le.current.get(be);Le.current.delete(be),X?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...$?{attempt:$.generation}:{}}),Ae($?.generation),lt.current=null,Ve(!1),ue.current=!0,Et()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:bt,emailRequired:yt,billingAddressRequired:yt,layout:{maxColumns:1,overflow:"never"}}},be)})]})}),oe&&(0,c.jsx)(er,{status:"processing"})]})}function oc(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function cu({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 B=(0,y.resolveStripeMethodBrandVariant)(e,t),I=_l[e],[w,h]=(0,i.useState)(!1),O=!!I&&!w,G=B?.backgroundColor??d??"#ffffff",T=B?.borderColor??u??"#d1d5db",Y=B?.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:ma,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&&B?.logoSvg?(0,c.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:B.logoSvg}}):null,(0,c.jsx)("span",{children:(0,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 ns({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:B,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),Fe=(0,i.useRef)(!1),[oe,je]=(0,i.useState)(!1),[yt,re]=(0,i.useState)("loading"),[De,ft]=(0,i.useState)(""),ke=!(0,y.isValidEmail)(r?.trim()),Oe=!ke||(0,y.isValidEmail)(De.trim()),be=(0,i.useCallback)(async()=>{if(!U||!de||I||Fe.current||!oe)return;Fe.current=!0,he(!0);let me=v?await v("card"):{proceed:!0};if(!me.proceed){Fe.current=!1,he(!1);return}B?.("card");let Ie=me.sessionId??t,Ve=me.nonce??n,rt=to(o?.trim()),R=Bn({email:me.accountPatch?.email?.trim()||r?.trim()||De.trim(),firstName:me.accountPatch?.firstName?.trim()||rt.firstName,lastName:me.accountPatch?.lastName?.trim()||rt.lastName}),We=R.email,ye=Bn({...me.accountPatch,...R});try{if(u?.(null),!(0,y.isValidEmail)(We))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:We,...ve?{name:ve}:{}}}});if(ue.error||!ue.paymentMethod){u?.(ue.error?.message??"Failed to create payment method.");return}let He=ue.paymentMethod;if(!Ie||!We)throw new Error("Missing sessionId or email for payment.");let Q=He.type||e,ot=await ni(l,Y,Ie,Ve??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,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:Ve,accountPatch:ye,paymentMethodId:He.id,paymentMethodType:He.type??e,gateway:"stripe"});let{error:Te,paymentIntent:Le}=await U.confirmPayment({clientSecret:lt,confirmParams:{return_url:window.location.href,payment_method:He.id},redirect:"if_required"});if(Te){$t(Tr);let Ae=Te.message??"Payment failed.";u?.(Ae),p?.(cn("card",Ae,{code:Te.code})),await ri({billingApiUrl:l,sessionId:Ie,nonce:Ve,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Te.code??"provider_declined"}});return}let ct=Le?.status;if(!Xo(ct)){$t(Tr);let Ae=ct==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";u?.(Ae),p?.(cn("card",Ae,{code:ct??"missing_payment_intent"}));return}$t(Tr);let at=typeof Le?.payment_method=="string"?Le.payment_method:Le?.payment_method?.id;d({id:at??He.id,type:"card",threeDSecureActionResultTokenId:Le?.id,gateway:"stripe",paymentMethodType:He.type??e},{accountPatch:ye,paymentMethodCategory:"apm",sessionId:Ie,nonce:Ve})}catch(N){u?.(N instanceof Error?N.message:"Payment failed. Please try again.")}finally{Fe.current=!1,he(!1)}},[U,de,I,oe,v,B,t,n,r,o,De,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:De,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:()=>re("ready"),onLoadError:()=>{re("load_error"),is(dn(T),"stripe","apm")},onChange:me=>{je(!!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:!oe||!Oe||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:!oe||!Oe||X||I||yt!=="ready"?"not-allowed":"pointer",opacity:!oe||!Oe||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)(Ro,{margin:"0.75rem 0 0",children:G})]})}function Yl({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:B,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),[Fe,oe]=(0,i.useState)(null),[je,yt]=(0,i.useState)(null),re=(0,i.useRef)(!1),{request:De,collect:ft,finish:ke}=So();(0,i.useEffect)(()=>{l.length>0&&d?w?.("ready"):d||w?.("loading")},[l.length,d,w]);let Oe=(0,i.useCallback)(async R=>{if(!d||re.current||h)return;re.current=!0,yt(R);let We=I?await I("card"):{proceed:!0};if(!We.proceed){re.current=!1,yt(null);return}v?.("card");let ye=We.sessionId??e,N=We.nonce??t,ve=to([We.accountPatch?.firstName,We.accountPatch?.lastName].filter(Boolean).join(" ")||r),ue=Bn({email:We.accountPatch?.email?.trim()||n?.trim(),firstName:We.accountPatch?.firstName?.trim()||ve.firstName,lastName:We.accountPatch?.lastName?.trim()||ve.lastName});if(!(0,y.isValidEmail)(ue.email)){yt(null);let ot=await ft((0,y.getStripeMethodDisplayName)(R),ue);if(!ot){re.current=!1;return}ue=ot,yt(R)}let He=ue.email,Q=Bn({...We.accountPatch,...ue});try{if(b?.(null),!ye||!(0,y.isValidEmail)(He))throw new Error("Missing sessionId or email for payment.");await o?.(ue);let ot=await ni(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:Q,paymentMethodType:R,gateway:"stripe"});let{error:Te,paymentIntent:Le}=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(" "),...He?{email:He}:{}}}},redirect:"if_required"});if(Te){$t(Tr);let Ae=Te.message??"Payment failed.";b?.(Ae),B?.(cn("card",Ae,{code:Te.code})),await ri({billingApiUrl:a,sessionId:ye,nonce:N,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:R,providerDeclineReason:Te.code??"provider_declined"}});return}let ct=Le?.status;if(!Xo(ct)){$t(Tr);let Ae=ct==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";b?.(Ae),B?.(cn("card",Ae,{code:ct??"missing_payment_intent"}));return}$t(Tr);let at=typeof Le?.payment_method=="string"?Le.payment_method:Le?.payment_method?.id;p({id:at??Le?.id,type:"card",threeDSecureActionResultTokenId:Le?.id,gateway:"stripe",paymentMethodType:R},{accountPatch:Q,paymentMethodCategory:"apm",sessionId:ye,nonce:N})}catch(ot){b?.(ot instanceof Error?ot.message:"Payment failed. Please try again.")}finally{re.current=!1,yt(null)}},[d,h,I,v,e,t,n,ft,a,he,r,o,p,b,B]),[be,me]=(0,i.useState)(null),Ie=de?X??null:be,Ve=(0,i.useCallback)(R=>{re.current||h||Ie&&Ie!==R||((0,y.needsStripeMethodExplicitConfirm)(R)?de?de(R):me(R):Oe(R))},[Ie,h,Oe,de]),rt=(0,i.useMemo)(()=>be?oc(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:De?(0,c.jsx)(wo,{identity:De.identity,methodLabel:De.methodLabel,onComplete:ke,onCancel:()=>ke(null)},De.id):l.map(R=>{let We=X===R,ye=je===R,N=je!==null&&je!==R||X!=null&&X!==R;return(0,c.jsxs)(i.default.Fragment,{children:[(0,c.jsx)(cu,{method:R,themeId:U,submitting:ye,disabled:N,highlighted:We,hasNextStep:(0,y.needsStripeMethodExplicitConfirm)(R),onClick:()=>Ve(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)(ns,{method:R,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:p,onErrorChange:b,onDecline:B,onCancel:()=>me(null),runBeforeButtonClick:I,onButtonClick:v,isProcessing:h,submitButtonColor:O,submitButtonBorderRadius:G,submitButtonStyle:T})},R)]},R)})})}function du({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:B,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:Fe=!0,layout:oe="default",theme:je,buttonsTheme:yt,buttonsStyles:re,appearance:De,cardButtonContent:ft,cardBackButtonContent:ke,cardTitleContent:Oe,showSecurityFooter:be,onButtonClick:me,onBeforeButtonClick:Ie,onBuyerIdentityReady:Ve,enableAVS:rt,cardFieldOrder:R,cardPreFormSlot:We,avsLayout:ye="row",country:N,zip:ve,addressLine1:ue,addressLine2:He,city:Q,state:ot,onCountryChange:lt,onZipChange:Te,avsCheck:Le,checkoutType:ct,checkoutLayout:at,totalAmount:Ae=0,currency:jt="usd",initialCardOpen:Vt=!1,directPaypal:ut,isSubscription:Et=!1,session:q,dataAttachmentPending:fe=!1,dataAttachmentRequiresIdentity:et=!1,debug:V=!1}){let xe=Ur(),bt=Fa(),Ke=(0,i.useContext)(pr),{emitInstrument:$}=(0,i.useContext)(Zn),Je=(0,i.useRef)(null);Je.current||(Je.current=La());let f=Je.current,[,P]=(0,i.useState)(0),H=(0,i.useRef)(null);H.current||(H.current=ea());let ee=H.current,qe=(0,i.useMemo)(()=>({browser:ee,capability:f,presentationMode:"popup"}),[ee,f]),vt=q??Ke.session,Ge=vt?.gateways?.paypal?.providerObjectType??ut?.providerObjectType,Z=fe||Ke.claimPending===!0,it=et||Ke.claimRequiresIdentity===!0,Ct=Z&&!it,Nt=pl(),Ne=n||Nt,[Ft,ze]=(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)(He??""),[vn,Bt]=(0,i.useState)(Q??""),[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)(He??""),Qt=(0,i.useRef)(Q??""),Ht=(0,i.useRef)(ot??""),fn=(0,i.useRef)(""),gt=(0,i.useRef)({});(0,i.useEffect)(()=>{let s=(S,K,Ee,ne,Se)=>{if(gt.current[S])return;let Xt=K?.trim();!Xt||Xt===Ee.current||(Ee.current=Xt,ne(Xt),Se?.(Xt))};s("country",N,Zt,wn,lt),s("zip",ve,wt,On,Te),s("addressLine1",ue,yn,Ce),s("addressLine2",He,Dt,Tt),s("city",Q,Qt,Bt),s("state",ot,Ht,pn)},[N,ve,ue,He,Q,ot,lt,Te]);let te=(0,i.useMemo)(()=>(0,y.resolveAVSConfig)(rt),[rt]),Ln=te!==null,Nn=(0,i.useMemo)(()=>(0,y.isAuthorizationOnlySession)(q),[q]),hr=!!q?.vault?.html,Cn=!!q?.gateways?.pcivault,sn=Ti(q),Re=!!(q?.gateways?.stripe?.enabledPaymentMethods??de)?.includes("card")||Wr(q),ht=hr||Re||Cn,ie=!!(Y&&ht&&e),[F,Ze]=(0,i.useState)(()=>oe!=="buttons"||Vt?e??null:null),[se,Hn]=(0,i.useState)(0),gn=oe!=="buttons"||Vt||!!e&&F===e,Kt=q?.captureMethod,Kn=(0,i.useRef)(xe);(0,i.useEffect)(()=>{Kn.current=xe},[xe]);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:Ne,telemetry:r});return jr({sessionId:e,captureMethod:Kt,billingApiUrl:Ne,telemetry:r,capture:s}),()=>{s.unmount()}},[ie,e,gn,Kt,Ne,r]);let Gt=ie&&e&&gn&&nt?.sessionId===e&&nt.captureMethod===Kt&&nt.billingApiUrl===Ne&&nt.telemetry===r?nt.capture:null,hn=(0,i.useMemo)(()=>{let s=Mt,S=te?(0,y.isAVSFieldVisible)(te.postal_code,s):!1;return iu(s,Dn,S)},[te,Mt,Dn]),{avsInvalid:Mr,invalidAvsFields:Br}=(0,i.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!ie||!te)return{avsInvalid:!1,invalidAvsFields:s};let S=Mt,K=(Se,Xt)=>(0,y.isAVSFieldVisible)(Se,S)&&!Xt.trim(),Ee={line1:K(te.address_line_1,rn),city:K(te.city,vn),state:K(te.state,Vn),zip:hn.empty||hn.malformed};return{avsInvalid:Ee.line1||Ee.city||Ee.state||Ee.zip,invalidAvsFields:Ee}},[ie,te,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)(()=>Zi(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()},ya)},[]);(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]),x=(0,i.useCallback)(()=>{on("apm-collapsing"),bn(()=>{on("buttons"),Dr(null)})},[bn]);(0,i.useEffect)(()=>{oe==="buttons"&&Vt&&ht&&(Ze(e??null),on("card"))},[oe,Vt,ht,e]);let[L,A]=(0,i.useState)(null),le=(0,i.useRef)(!1),Me=(0,i.useRef)(null),pt=(0,i.useRef)("idle"),[pe,Be]=(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(Ve||Ke.claimBuyerIdentity||q?.buyerIdentified!==!1||!e||!t)return;let s=`${Ne}|${e}|${t}`;z.current?.key!==s&&(z.current={key:s,claim:vo(new fr.PaymentAPI(Ne,{telemetry:!1}),e,t,{...a?{userId:a}:{},...b?{firstName:b}:{},...v?{lastName:v}:{}})});let S=z.current.claim;return async K=>{await S(K)}},[Ve,Ke.claimBuyerIdentity,q?.buyerIdentified,e,t,Ne,a,b,v]),J=Ve??Ke.claimBuyerIdentity??ce,Ye=O??Fn,It=(0,i.useMemo)(()=>(0,y.resolveTheme)(je),[je]),E=(0,i.useMemo)(()=>{let s=It?.buttonsLayout??(0,y.resolveButtonsLayoutTheme)(yt);return re?{...s,...re,cardButton:{...s.cardButton,...re.cardButton},cardFormContainer:{...s.cardFormContainer,...re.cardFormContainer},backButton:{...s.backButton,...re.backButton},backButtonIcon:{...s.backButtonIcon,...re.backButtonIcon},submitButton:{...s.submitButton,...re.submitButton},title:{...s.title,...re.title}}:s},[It,yt,re]),Pe=De??It?.appearance,At=(0,i.useMemo)(()=>Za({appearance:Pe,buttonsStyles:E,layout:oe}),[Pe,E,oe]),ge=Ke.inlineSessionPatchProcessing??!1,j=(h??Ft)||ge,ae=Ne.replace(/\/+$/,""),_=(0,i.useMemo)(()=>xi({userId:a,email:o,firstName:b,lastName:v,country:N,zip:ve},Wn),[a,o,b,v,N,ve,Wn]),Ue=[_.firstName,_.lastName].filter(s=>!!s?.trim()).join(" "),Rt=!(0,y.isValidEmail)(_.email?.trim()),_e=(0,i.useRef)(null);ie&&_e.current===null&&(_e.current=Rt);let Sn=ie&&(_e.current??Rt),Sr=(0,i.useMemo)(()=>su(Wt,Sn),[Wt,Sn]),io=Sr.empty||Sr.malformed,Un=(0,i.useMemo)(()=>xe?xe.getRawProvider():null,[xe]),fs=(0,i.useMemo)(()=>bt?bt.getRawProvider():null,[bt]),Oo=Ae||100,so=jt.toLowerCase(),ui=(0,i.useMemo)(()=>Pe?(0,fr.toStripeAppearance)(Pe):null,[Pe]),lo=ui,gs=(0,i.useMemo)(()=>{let s=ui??{},S=s.rules??{};return{...s,rules:{...S,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...S[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...S[".AccordionItemContents"]??{}}}}},[ui]),hs=(0,i.useMemo)(()=>({...sl(Ae,q?.captureMethod),currency:so,...lo?{appearance:lo}:null}),[Ae,so,q?.captureMethod,lo]),bs=(0,i.useMemo)(()=>({mode:"payment",amount:Oo,currency:so,captureMethod:"manual",setupFutureUsage:"off_session",...lo?{appearance:lo}:null}),[Oo,so,lo]),we=(0,i.useCallback)(s=>{Rn(s),G?.(s)},[G]),pi=(0,i.useRef)(""),[Ps,Pc]=(0,i.useState)(!1),mi=(0,i.useCallback)(()=>{Pc(!0)},[]);(0,i.useEffect)(()=>{if(!ie||!Sn||!J||!Ps||io||pi.current)return;let s=Bn({email:(0,y.isValidEmail)(_.email?.trim())?_.email?.trim():fn.current.trim(),firstName:_.firstName?.trim(),lastName:_.lastName?.trim()});pi.current=JSON.stringify(s),mn(S=>({...S,...s})),Promise.resolve(J(s)).catch(S=>{pi.current="",we(S instanceof Error?S.message:"Failed to attach buyer details.")})},[ie,Sn,J,Ps,io,_.email,_.firstName,_.lastName,we]),(0,i.useEffect)(()=>{!ie||!Gt||Gt.setCardFieldOrder?.(R??null,te==null&&!Sn)},[ie,Gt,R,te,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]),co=(0,i.useCallback)((s,S,K)=>{let Ee=K?.popupBlocked??Yr(S);Ee&&f.markBlocked()&&P(tt=>tt+1);let ne=Ma(ts(s),Ee,ee.inAppBrowser),Se=_r(S),Xt=(Se?.toLowerCase()==="error"?void 0:Se)??no(K?.code)??"external_payment_method_failed",dr=new y.FloPayError(ne,"api_error",{code:"external_payment_method_failed",param:s,details:{providerCode:Xt,popupBlocked:Ee,inAppBrowser:ee.inAppBrowser,appFamily:ee.appFamily,popupCapability:f.current(),presentationMode:K?.presentationMode??"popup"}});K?.telemetryReported||dn(xe)?.error(Mo({...qe,presentationMode:K?.presentationMode??"popup"},{errorCode:Ee?"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??(Ee?"popup_blocked":"provider_error")})),A(null),oe==="buttons"&&(on("buttons"),Dr(null)),we(ne),d?.(dr),console.error("[FloPay] External payment method failed:",{method:s,code:Xt,popupBlocked:Ee})},[ee,qe,xe,oe,d,f,we]);(0,i.useEffect)(()=>{if(!ie||!e){Cr(null);return}let s=Zi(q?.vault);if(s){Cr(s);return}if(!gn){Cr(null);return}Cr(null);let S=!0;return new fr.PaymentAPI(ae).getVaultCapture(e,t).then(K=>{if(!S)return;let Ee=Zi(K);Ee?Cr(Ee):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,ae,t,we]);let lr=(0,i.useRef)({onComplete:l,onError:d,updateError:we,emitDecline:wr,resolvedAccount:_,avsConfig:te,avsCheckProp:Le,sessionId:e,nonce:t,baseUrl:ae,captureMethod:q?.captureMethod,paymentId:q?.paymentId,authorizationExpiresAt:q?.authorizationExpiresAt,serverSideCardGateway:sn});lr.current={onComplete:l,onError:d,updateError:we,emitDecline:wr,resolvedAccount:_,avsConfig:te,avsCheckProp:Le,sessionId:e,nonce:t,baseUrl:ae,captureMethod:q?.captureMethod,paymentId:q?.paymentId,authorizationExpiresAt:q?.authorizationExpiresAt,serverSideCardGateway:sn};let yi=(0,i.useRef)(!1),vs=(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 Ee=s.resolvedAccount.firstName?.trim(),ne=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,...Ee?{firstName:Ee}:{},...ne?{lastName:ne}:{},...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}}:{}}},[]),Cs=(0,i.useRef)(Z);Cs.current=Z,(0,i.useEffect)(()=>{Z||Ye!==ql||lr.current.updateError(null)},[Z,Ye]),(0,i.useEffect)(()=>{!ie||!Gt||Gt.setSubmitGate?.(Mr||Z||io||pe)},[ie,Gt,Mr,Z,io,pe]),(0,i.useEffect)(()=>{if(!ie||!Gt)return;yi.current=!1;let s=null,S=()=>{s&&clearTimeout(s),s=setTimeout(()=>{s=null,pt.current="idle",A(null)},400)},K=Gt.on("submitting",()=>{en(!0),Me.current&&clearTimeout(Me.current),pt.current="validation-window",Me.current=setTimeout(()=>{Me.current=null,pt.current==="validation-window"&&(pt.current="processing")},Gd),A("processing");let tt=lr.current;if(!tt.sessionId||!tt.nonce)return;let mt=vs();if(!mt){tt.updateError("Enter a valid email address."),pt.current="idle",A(null);return}new fr.PaymentAPI(tt.baseUrl).patchAccountSnapshot(tt.sessionId,tt.nonce,mt,{telemetryMode:"best_effort"}).catch(kt=>{if(!Xd(kt))return;let Ut=kt instanceof Error?kt.message:"Please check your billing address and try again.";tt.updateError(Ut),pt.current="idle",A(null),tt.onError?.(kt instanceof y.FloPayError?kt:new y.FloPayError(Ut,"api_error"))})}),Ee=Gt.on("complete",async tt=>{if(To(tt.sessionId??lr.current.sessionId),pt.current="terminal",Be(!1),A("success"),await new Promise(ln=>setTimeout(ln,600)),yi.current)return;yi.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"})}),ne=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",Be(!1),mt.updateError(kt),A("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",Be(!1),mt.updateError(kt),A("error"),mt.onError?.(new y.FloPayError(kt,"api_error",{code:tt.failureOutcome??"capture_failed"})),S()}),Xt=Gt.on("challenge_dismissed",()=>{Me.current&&(clearTimeout(Me.current),Me.current=null),pt.current="processing",Be(!0),A(null)}),dr=Gt.on("blocked",()=>{if(W.current){lr.current.updateError(Yd);return}if(!Cs.current){en(!0);return}mi(),lr.current.updateError(ql)});return()=>{s&&(clearTimeout(s),s=null),Me.current&&(clearTimeout(Me.current),Me.current=null),pt.current="idle",Be(!1),A(null),K(),Ee(),ne(),Se(),Xt(),dr()}},[ie,Gt,mi,vs]);let kr=!!ut?.clientId,Lo=Array.isArray(de),ba=Lo&&de.length>0,Ss=Lo&&de.includes("paypal"),Pa=(0,i.useRef)(null);Pa.current===null&&(Pa.current=Hd());let uo=Pa.current?"redirect":ml(ee,U,f.current()),{expressMethods:va,paymentElementMethods:No}=(0,i.useMemo)(()=>(0,y.partitionStripeMethods)(de,{excludePaypal:kr}),[de,kr]),ws=kr||!!bt||Ss&&uo==="redirect",vc=(0,i.useMemo)(()=>ws?va.filter(s=>s!=="paypal"):va,[va,ws]),Cc=(0,i.useMemo)(()=>{let s=[];return he&&s.push("apple_pay"),Fe&&s.push("google_pay"),s},[he,Fe]),po=Lo?vc:Cc,Sc=Y&&po.length>0,fi=Ln?Mt:N,Ca=(0,i.useMemo)(()=>{let s=fi?.trim().toUpperCase();return s?X?No.filter(S=>{let K=X[S];return!K||K.length===0||K.includes(s)}):(0,y.filterStripeMethodsByCountry)(No,fi):No},[No,fi,X]),gi=(0,i.useMemo)(()=>({mode:"payment",amount:Oo,currency:so,paymentMethodCreation:"manual",appearance:gs}),[Oo,so,gs]),[ks,Is]=(0,i.useState)("loading"),[Rs,_s]=(0,i.useState)("loading"),[Es,Ts]=(0,i.useState)("loading"),[wc,hi]=(0,i.useState)(!1),[As,bi]=(0,i.useState)("loading"),[Pi,kc]=(0,i.useState)();(0,i.useEffect)(()=>{kc(ea())},[]);let Sa=Pi?.inAppBrowser,wa=Pi?Da(Pi,ut?.approvalPresentation,Ge??(Et?"subscription":"order")):"popup",xs=T&&(kr||(Lo?Ss:Sa===!1)),Ms=Y&&Sc,zo=(!Ct||!!Ke.waitForDataAttachment)&&xs&&kr,Bs=As==="retrying"||As==="exhausted",Uo=null;Y&&(bt?Uo=fs:uo==="redirect"&&(Uo=Un));let Fs=(0,i.useMemo)(()=>({...qe,presentationMode:uo}),[qe,uo]),qo=!Ct&&xs&&!!Uo&&(!kr||Bs),mo=!Ct&&Ms&&!!Un,$o=!Ct&&Y&&ba&&Ca.length>0&&!!Un,Ic=zo&&!Bs?wc:qo&&Hl(ks),Rc=mo&&Hl(Rs),_c=$o&&Es!=="load_error",Ds=s=>s==="loading"||s==="ready",Os=zo||qo&&Ds(ks)||mo&&Ds(Rs)||$o&&Es!=="load_error",ka=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(!ka.current){if(!Y&&!T){ka.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){ka.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(Sa!==void 0&&!Ct&&!ht&&!Os){ka.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,Sa,Ct,ht,Os,d,we]);let Ls=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(Ls.current||!ba)return;let s=[];he!==!0&&s.push("showApplePay"),Fe!==!0&&s.push("showGooglePay"),s.length!==0&&(Ls.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.`))},[ba,he,Fe]);let Ns=(0,i.useCallback)((s,S)=>Ke.applyInlineSessionPatch?Ke.applyInlineSessionPatch(s).then(K=>({error:null,sessionId:K.sessionId||e,nonce:K.session?.clientSecret||t})).catch(K=>{let Ee=Wl(S,K);return we(Ee.message),d?.(Ee),{error:Ee,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ke.applyInlineSessionPatch,t,d,e,we]),cr=(0,i.useCallback)(async s=>{if(s!=="card"&&Ct&&await Ke.waitForDataAttachment?.(),!Ie)return{proceed:!0};try{let S=await Ie({method:s,sessionId:e||void 0,createSession:Ke.inlineSessionDraft});if(S===!1)return{proceed:!1};if(S&&typeof S=="object"){S.account&&mn(Ee=>({...Ee??{},...S.account}));let K=await Ns(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=Wl(s,S);return we(K.message),d?.(K),{proceed:!1}}},[Ns,Ke.inlineSessionDraft,Ke.waitForDataAttachment,Ct,Ie,d,e,we]),zs=(0,i.useCallback)(async(s,S)=>{if(le.current)return;le.current=!0,ze(!0),A("processing"),we(null);let K=S?.sessionId??e,Ee=S?.nonce??t,ne=xi(_,S?.accountPatch),Se=S?.completionPaymentMethodId??Jo(s),Xt=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,dr=tu(s),tt=S?.presentationMode?Xa(dn(xe),{...qe,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(ae).processPayment(ne.userId??"",{sessionId:K,nonce:Ee,paymentMethodCategory:S?.paymentMethodCategory??ru(s),tokenizedData:Xt,accountData:{...S?.accountPatch,userId:ne.userId??"",email:ne.email??"",firstName:ne.firstName||void 0,lastName:ne.lastName||void 0,...te?(()=>{let Ot=Zt.current,Ir=(0,y.isAVSFieldVisible)(te.state,Ot),qn=(0,y.isAVSFieldVisible)(te.address_line_1,Ot),Rr=(0,y.isAVSFieldVisible)(te.postal_code,Ot),eo=qn&&!Ir&&Rr?(0,y.getStateFromPostalCode)(Ot,(wt.current??"").trim()):null,Go=Ir?Ht.current:eo;return{country:Ot,...Rr&&wt.current?{zip:wt.current}:{},...(0,y.isAVSFieldVisible)(te.city,Ot)&&Qt.current?{city:Qt.current}:{},...Go?{state:Go}:{},...qn&&yn.current?{addressLine1:yn.current}:{},...(0,y.isAVSFieldVisible)(te.address_line_2,Ot)&&Dt.current?{addressLine2:Dt.current}:{}}})():{}},chv:B,avsCheck:Le??!1,checkoutType:ct,checkoutLayout:at,avsConfig:te?{country:(0,y.isAVSFieldVisible)(te.country,Zt.current),postal_code:(0,y.isAVSFieldVisible)(te.postal_code,Zt.current),address_line_1:(0,y.isAVSFieldVisible)(te.address_line_1,Zt.current),address_line_2:(0,y.isAVSFieldVisible)(te.address_line_2,Zt.current),city:(0,y.isAVSFieldVisible)(te.city,Zt.current),state:(0,y.isAVSFieldVisible)(te.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";To(K),tt?.terminal({outcome:"payment_succeeded",...yr}),A("success"),g(null),await new Promise(eo=>setTimeout(eo,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(!xe||!Ot){A("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:eo}=await qn.confirmPayment({clientSecret:Ot,confirmParams:Rr,redirect:"if_required"});if(eo){A("error");let Go=eo.message??"PayPal payment failed.";we(Go),wr("paypal",Go,{code:eo.code})}}catch(qn){A("error"),we(qn instanceof Error?qn.message:"PayPal authorization failed.")}return}if(ln?.type==="paypal_direct_required"){let Ot=ln.orderId;if(!Ot){A("error"),we("PayPal retry required but no order id provided.");return}let Ir=D.current?.attempts??0;if(Ir>=2){A("error"),we("PayPal payment could not be completed after multiple attempts."),wr("paypal","paypal_direct_required retry limit exceeded");return}hi(!1),bi("loading"),g({orderId:Ot,attempts:Ir+1}),A(null);return}(0,y.classifyPaymentRejection)(Ut.status,ln)?tt?.terminal({outcome:"payment_declined",...yr,terminalReason:"provider_declined"}):mt(),A("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){Ql(kt)||mt(),A("error"),we(kt instanceof Error?kt.message:"An unexpected error occurred"),await new Promise(Ut=>setTimeout(Ut,400))}finally{ze(!1),A(null),le.current=!1}},[ae,e,t,_,te,Le,ct,at,B,xe,bt,q,l,we,wr,$,qe]),xn=(0,i.useCallback)((s,S)=>{p?p(s):zs(s,S)},[p,zs]),jo=`${Xl}:${e}`;(0,i.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem(jo);if(!s)return;let S;try{S=JSON.parse(s)}catch{$t(jo);return}if(!S||typeof S.createdAt!="number"||Date.now()-S.createdAt<0||Date.now()-S.createdAt>Jl||typeof S.paymentMethodId!="string"||typeof S.providerIntentId!="string"||typeof S.paymentMethodType!="string"||S.sessionId!==e||!t||S.nonce!==t||!po.includes(S.paymentMethodType)){$t(jo);return}$t(jo),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,jo,po]);let Us=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(typeof window>"u"||Us.current)return;let[s,S,K]=os();if(!s||!S||Pa.current||!xe)return;let Ee=xe.getRawProvider();if(!Ee)return;let ne=mt=>{let kt=localStorage.getItem(mt);if(!kt)return null;try{return JSON.parse(kt)}catch{return $t(mt),null}},Se=ne(Tr)??ne(Nl),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;Us.current=!0,$t(Tr),$t(Nl),window.history.replaceState({},"",as());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 Ee.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=Xo(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 Xs=typeof mt.payment_method=="string"?mt.payment_method:mt.payment_method?.id;xn({id:Xs??Se?.paymentMethodId??Se?.tokenId??mt.id,type:"card",threeDSecureActionResultTokenId:mt.id,gateway:Se?.gateway??"stripe",paymentMethodType:dr},Xt)})()},[e,xn,xe,we,wr]);let vi=(0,i.useCallback)(s=>{s.preventDefault()},[]);if(!(ie||xe!==null))return(0,c.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Vo=oe==="buttons",Mn=Pe?.variables,Ec=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ci=Mn?.colorBackground,Tc=Ci&&!Ec.has(Ci)?Ci:void 0,Wo=E.cardInputBorder??(Vo?"#e5e7eb":"#A4A4FF"),qs=Mn?.colorDanger??"#dc2626",zt=s=>Br[s]&&(Pr[s]||En),Ia=io&&(Fr||En),Jn=s=>s?qs:Wo,Ra=(hn.malformed||hn.empty)&&(br||En),Ac=Jn(Ra),Si=E.cardFormContainer?.backgroundColor??Tc??(Vo?"white":"#EDEDFF"),yo=E.cardInputBackground??Mn?.colorBackground??"white",wi=ho(ke),$s=ho(Oe),fo=E.nameInput,js=E.cardInputFontSize??lu(fo?.fontSize)??Mn?.fontSizeBase??"16px",Vs=typeof fo?.fontFamily=="string"?fo.fontFamily:Mn?.fontFamily??"Poppins, sans-serif",Ws=Gi(fo?.fontWeight)??400,xc=E.cardInputColor??(typeof fo?.color=="string"?fo.color:void 0)??Mn?.colorText??"#262833",Mc=E.cardInputPlaceholderColor??"#9ca3af",Yt=Mn?.borderRadius??"8px",Zr=Mn?.borderRadius??E.cardButton?.borderRadius??Yt,Qr=Mn?.colorPrimary??"#4A49FF",Bc=Mn?.colorPrimaryHover??Fo(Qr,.12),ki=Mn?.colorText??"#262833",Ii={fontSize:js,fontFamily:Vs,fontWeight:Ws,color:xc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ho={marginTop:"0.375rem",...Ii,fontSize:"0.75rem",lineHeight:1.4,color:qs},Fc={"--flopay-input-placeholder-color":Mc,"--flopay-input-font-size":js,"--flopay-input-font-family":Vs,"--flopay-input-font-weight":String(Ws)},Ko=E.cardFormContainer??{},Ri=Ko.padding??(Vo?"0":"1rem"),_i=Ko.borderRadius??Yt,Dc=Gt&&Xn?(0,c.jsx)(Bo,{capture:Gt,html:Xn.html,messageToken:Xn.messageToken,expectedOrigin:Xn.expectedOrigin,theme:At,submitLabel:w,onReady:()=>{if(!Sn&&!te||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"&&(Me.current&&(clearTimeout(Me.current),Me.current=null),pt.current="idle",A(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"}),Hs=(0,c.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&ar()},style:{backgroundColor:Si,borderRadius:_i,...Ko,padding:Ri,...Fc,display:"flex",flexDirection:"column"},children:[(0,c.jsx)("style",{children:`
30
+ `,Ia=44,Ra=180,rc=`flopay-card-enter ${Ra}ms cubic-bezier(0, 0, 0.2, 1) both`,oc=`flopay-card-exit ${Ra}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Tu=`flopay-buttons-enter ${Ra}ms cubic-bezier(0, 0, 0.2, 1) both`,Au=`flopay-buttons-exit ${Ra}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function xu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ws(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var Mu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Fu(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var gs={width:"100%",minHeight:Ia,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Bu(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ac(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function hs(e){return e==="paypal"?"PayPal":(0,y.getStripeMethodDisplayName)(e)}function Du(e){let t=(0,y.getPostalCodeExample)(e);return`Enter a valid ${(0,y.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Ou(e,t,n){let r=(0,y.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,s=a&&!o,c=a&&!!o&&!(0,y.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:s,malformed:c}}function Lu(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,y.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function ic(e,t){return t instanceof y.FloPayError?t:new y.FloPayError(t instanceof Error?t.message:`${Bu(e)} before-click hook failed.`,"validation_error")}function fs(){return(0,d.jsx)("style",{children:Eu})}function Nu(e){return typeof e=="number"?`${e}px`:e}function hc(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Pc({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,d.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,d.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,d.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function sc(e){return e!=="unavailable"&&e!=="load_error"}function gi(e){return(0,d.jsx)(Uu,{...e})}function lc({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:s=!1,onButtonClick:c,onDecline:u,onTechnicalFailure:p,runBeforeButtonClick:h,billingName:b,onBuyerIdentityReady:I,onLoadStateChange:k,placeholderBorderRadius:C,popupCapabilityOwner:f,externalTelemetryContext:S,presentationMode:G}){let _=Hr(),{emitInstrument:q}=(0,i.useContext)(rr),E=(0,Zt.useStripe)(),ne=(0,Zt.useElements)(),$=(0,i.useMemo)(()=>li(pn(_),S),[S,_]),[W,ie]=(0,i.useState)("loading");(0,i.useEffect)(()=>{k?.(W)},[W,k]);let[V,Be]=(0,i.useState)(!1),Ue=(0,i.useRef)(!1),X=!(0,y.isValidEmail)(n?.trim())||!b?.trim(),{request:Ae,collect:it,finish:Re}=Oo(),xe=(0,i.useRef)(!1),ve=(0,i.useRef)(null),se=(0,i.useRef)(null),[me,He]=(0,i.useState)(0),[st,T]=(0,i.useState)(!1),ye=(0,i.useRef)(!1),le=(0,i.useRef)(new Map),{startAttempt:F,finishAttempt:Se,invalidateAttempt:ce,isAttemptInvalidated:De,isAttemptCurrent:re,generationRef:$e}=ya((U,we,lt)=>{p?.(U,we,{...lt,popupBlocked:lt?.popupBlocked??oo(we),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:G,terminalReason:"overlay_timeout"}),T(!0),He(Z=>Z+1)},{onHandoffObserved:()=>{f.markAvailable(),$?.log({name:"provider.popup.opened",stage:"overlay_open",...vr,attempt:$e.current})}});(0,i.useEffect)(()=>{st&&se.current?.focus()},[st,me]);let dt=(0,i.useCallback)(()=>{He(U=>U+1)},[]),Me=(0,i.useCallback)((U,we,lt)=>{ce(lt),p?.("paypal",U,{code:we,popupBlocked:oo(U),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:G}),T(!0),dt()},[ce,p,G,dt]),Oe=(0,i.useCallback)(()=>{window.setTimeout(()=>{(ve.current?.querySelector("iframe")??ve.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{ye.current&&(ye.current=!1,Oe())},[Oe,me]);let ut=(0,i.useCallback)(()=>{T(!1),a?.(null),Oe()},[Oe,a]);(0,i.useEffect)(()=>{if(!E||xe.current)return;let[U,we,lt]=vs();if(!U||!we)return;let Z=fc(we);if(!Z)return;xe.current=!0;let qe=!0,St=wa.get(we);St||(St=lt==="failed"?Promise.resolve(null):Promise.resolve().then(()=>E.retrievePaymentIntent(we)),wa.set(we,St));let Ze={accountPatch:Z.accountPatch,sessionId:Z.sessionId,nonce:Z.nonce},H=()=>{$?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...vr,requestCategory:"provider_sdk"})};return $?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...vr}),(async()=>{try{Be(!0);let g=await St;if(!qe)return;if(g?.error){wa.delete(we),H(),a?.(g.error.message??"Failed to retrieve PayPal payment status.");return}if(wu(),wa.delete(we),lt==="failed"){let ee="PayPal payment was declined. Please try again.";$?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}),a?.(ee),u?.(un("paypal",ee));return}let v=g?.paymentIntent;if(v&&v.id!==U){H(),a?.("Failed to match the returned PayPal payment.");return}if(v&&(v.status==="requires_capture"||v.status==="succeeded")){let ee=typeof v.payment_method=="string"?v.payment_method:v.payment_method?.id;o({id:ee??v.id,type:"card",threeDSecureActionResultTokenId:v.id,isPaypal:!0},{...Ze,presentationMode:"redirect"})}else{let ee="PayPal payment was not completed. Please try again.";$?.terminal({outcome:v?.status==="canceled"?"payment_cancelled":"payment_declined",...vr,terminalReason:v?.status==="canceled"?"cancelled":"provider_declined"}),a?.(ee),u?.(un("paypal",ee))}}catch(g){if(!qe)return;wa.delete(we),H(),a?.(g instanceof Error?g.message:"Failed to complete PayPal payment.")}finally{qe&&Be(!1)}})(),()=>{qe=!1,xe.current=!1}},[E,o,a,u,$]);let Y=(0,i.useCallback)(async(U=!1)=>{let we=h?await h("paypal"):{proceed:!0};if(!we.proceed)return le.current.delete(me),!1;let lt=F("paypal");return le.current.set(me,{generation:lt,accountPatch:we.accountPatch,sessionId:we.sessionId,nonce:we.nonce}),T(!1),$?.log({name:`provider.${U?"redirect.started":"handoff.requested"}`,stage:U?"redirect":"overlay_open",...vr,attempt:lt}),c?.("paypal"),!0},[c,$,h,F,me]),J=(0,i.useCallback)(async U=>{if(s||V||!await Y()){U.reject();return}U.resolve()},[s,Y,V]),mt=(0,i.useCallback)(async U=>{if(!E||!ne)return;let we=le.current.get(me);if(we&&!re(we.generation)){le.current.delete(me);return}if(!we&&De()||we&&!Se(we.generation))return;we||Se();let lt=we??null;if(le.current.delete(me),!lt&&h){let nt=await h("paypal");if(!nt.proceed){U.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}lt={accountPatch:nt.accountPatch,sessionId:nt.sessionId,nonce:nt.nonce}}let Z=lt?.sessionId??e,qe=lt?.nonce??t,St=await _u({event:U,prepared:lt,email:n,billingName:b,methodLabel:"PayPal",collect:it});if(!St){U.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ze=St.email,H={...lt?.accountPatch,...On(St,!0)};try{if(Be(!0),a?.(null),!Z||!(0,y.isValidEmail)(Ze))throw new Error("Missing sessionId or email for PayPal payment");await I?.(St);let nt=E.createPaymentMethod,{error:g,paymentMethod:v}=await nt({type:"paypal"});if(g){Me(g,"stripe_paypal_create_payment_method_failed",we?.generation),U.paymentFailed({reason:"fail"});return}let ee=await yi(r,q,Z,qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:v?.id??null,intentKind:"payment"});if(ee.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let de=ee.clientSecret,Xe={return_url:Cs()};if(v?.id&&(Xe.payment_method=v.id),!Wt(ka,{clientSecret:de,sessionId:Z,nonce:qe,accountPatch:H})&&G==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:Qe,paymentIntent:ae}=await E.confirmPayment({clientSecret:de,confirmParams:Xe,redirect:"if_required"});if(Qe){if(Wt(ka),fo(Qe)){let It=Qe.message??"Your payment was declined.";$?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}),a?.(It),u?.(un("paypal",It,{code:Mr(Qe),declineCode:No(Qe)})),await fi({billingApiUrl:r,sessionId:Z,nonce:qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mr(Qe)??"provider_declined"}})}else Me(Qe,"stripe_paypal_confirm_failed",we?.generation);return}Wt(ka);let yt=typeof ae?.payment_method=="string"?ae.payment_method:ae?.payment_method?.id;o({id:yt??ae?.id,type:"card",threeDSecureActionResultTokenId:ae?.id,isPaypal:!0},{accountPatch:H,paymentMethodCategory:"paypal",presentationMode:G,sessionId:Z,nonce:qe});return}catch(nt){Me(nt,"stripe_paypal_failed",we?.generation)}finally{Be(!1)}},[E,ne,e,t,n,b,it,I,r,q,o,a,u,h,Me,Se,re,De,$,G,me]),gt=(0,i.useCallback)(async()=>{if(!(Ue.current||s||V||!E||!ne)){Ue.current=!0,Be(!0);try{if(!await Y(!0))return;await mt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Ue.current=!1,Be(!1)}}},[ne,mt,s,Y,E,V]),Ie=G==="redirect"?(0,d.jsx)("button",{type:"button",disabled:s||V,onClick:()=>{gt()},style:{width:"100%",minHeight:Ia,border:"1px solid #d1d5db",borderRadius:C??8,background:"#ffc439",color:"#111827",cursor:s||V?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,d.jsx)(Zt.ExpressCheckoutElement,{onReady:U=>ie(hc(U,["paypal"])),onLoadError:()=>{ie("load_error"),Ss($,"paypal","paypal","provider_error")},onClick:J,onConfirm:mt,onCancel:()=>{let U=le.current.get(me);le.current.delete(me),$?.terminal({outcome:"payment_cancelled",...vr,terminalReason:"cancelled",...U?{attempt:U.generation}:{}}),ce(U?.generation),T(!1),ye.current=!0,dt()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:X,emailRequired:X,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},me),ft=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{ref:ve,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[st&&(0,d.jsx)("button",{ref:se,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ut,style:gs,children:"Try PayPal again"}),Ae&&(0,d.jsx)(Lo,{identity:Ae.identity,methodLabel:Ae.methodLabel,onComplete:Re,onCancel:()=>Re(null)},Ae.id),(0,d.jsx)("div",{style:{display:Ae?"none":void 0},children:Ie})]}),V&&!Ae&&(0,d.jsx)(Ln,{status:"processing"})]});return G==="redirect"?ft:(0,d.jsx)(Pc,{state:W,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:ft})}function cc({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:s,onErrorChange:c,onButtonClick:u,onDecline:p,onTechnicalFailure:h,runBeforeButtonClick:b,billingName:I,onBuyerIdentityReady:k,onLoadStateChange:C,placeholderBorderRadius:f,popupCapabilityOwner:S,externalTelemetryContext:G}){let _=Hr(),{emitInstrument:q}=(0,i.useContext)(rr),E=(0,Zt.useStripe)(),ne=(0,Zt.useElements)(),$=(0,i.useMemo)(()=>li(pn(_),G),[G,_]),[W,ie]=(0,i.useState)("loading");(0,i.useEffect)(()=>{C?.(W)},[W,C]);let[V,Be]=(0,i.useState)(!1),Ue=(0,i.useRef)(!(0,y.isValidEmail)(n?.trim())||!I?.trim()).current,{request:X,collect:Ae,finish:it}=Oo(),Re=(0,i.useRef)(null),xe=(0,i.useRef)(null),[ve,se]=(0,i.useState)(0),[me,He]=(0,i.useState)(!1),[st,T]=(0,i.useState)(()=>mi(e,t)?"blocked":"idle"),[ye,le]=(0,i.useState)("google_pay"),F=(0,i.useRef)(null),Se=(0,i.useRef)(!0),ce=(0,i.useRef)(!1),De=(0,i.useRef)("google_pay"),re=(0,i.useRef)("google_pay"),$e=(0,i.useRef)(null),dt=(0,i.useRef)(null),Me=(0,i.useRef)(new Set);(0,i.useEffect)(()=>(Se.current=!0,()=>{Se.current=!1;for(let H of Me.current)window.clearTimeout(H);Me.current.clear()}),[]);let Oe=(0,i.useRef)(new Map),{startAttempt:ut,finishAttempt:Y,invalidateAttempt:J,isAttemptInvalidated:mt,isAttemptCurrent:gt,generationRef:Ie}=ya((H,nt,g)=>{h?.(H,nt,{...g,popupBlocked:g?.popupBlocked??oo(nt),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),le(H),He(!0),se(v=>v+1)},{onHandoffObserved:H=>{S.markAvailable(),$?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Ie.current,...H==="apple_pay"||H==="google_pay"?{walletType:H}:{}})}});(0,i.useEffect)(()=>{me&&xe.current?.focus()},[me,ve]);let ft=(0,i.useCallback)(()=>{se(H=>H+1)},[]),U=(0,i.useCallback)((H,nt,g,v,ee=!1)=>{J(v),h?.(H,nt,{code:g,popupBlocked:oo(nt),telemetryReported:ee,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),le(H),He(!0),ft()},[J,h,ft]),we=(0,i.useCallback)(()=>{window.setTimeout(()=>{(Re.current?.querySelector("iframe")??Re.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{ce.current&&(ce.current=!1,we())},[we,ve]);let lt=(0,i.useCallback)(()=>{He(!1),c?.(null),we()},[we,c]),Z=(0,i.useCallback)(()=>{F.current?.()},[]);(0,i.useEffect)(()=>{let H=mi(e,t);if(!H)return;let nt=!1,g=!1,v=async()=>{if(!g){g=!0,nt||T("checking");try{let ee=await tc(E,H.clientSecret,Me.current);if(nt)return;let de=ms(ee,H.providerObjectId,(0,y.isSetupIntentClientSecret)(H.clientSecret));if(de.kind==="confirmed"){if(!ec(e,t,H.clientSecret))return;F.current=null,T("idle"),s({id:de.paymentMethodId,type:"card",threeDSecureActionResultTokenId:de.intentId},{...H.accountPatch?{accountPatch:H.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(de.kind==="terminal"){ps(e,t,H.clientSecret),F.current=null,T("idle"),le(H.paymentMethodType),He(!0),ft();return}T("blocked")}catch{nt||T("blocked")}finally{g=!1}}};return F.current=v,T("blocked"),()=>{nt=!0,F.current===v&&(F.current=null)}},[t,s,ft,e,E]);let qe=(0,i.useCallback)(async H=>{let nt=!1,g=Ee=>{nt||(nt=!0,H.paymentFailed({reason:"fail",...Ee?{message:Ee}:{}}))};if(!E||!ne){g();return}let v=Oe.current.get(ve);if(v&&!gt(v.generation)){Oe.current.delete(ve),g();return}if(!v&&mt()){g();return}if(v&&!Y(v.generation)){g();return}v||Y();let ee=H.expressPaymentType??v?.method??De.current,de=v??null,Xe=ac(ee),kt;ee==="apple_pay"?kt="apple_pay":ee==="google_pay"&&(kt="google_pay");let Qe=v?.generation??Ie.current,ae=$,yt=ae?.now()??globalThis.performance?.now()??Date.now(),It=new AbortController,qt=!1,Ke=!1,Lt=null,Ge=e,zn="processing",Tn="other",Dt="provider_runtime",Rn,Un=new Promise((Ee,Rt)=>{Rn=Rt}),qn=window.setTimeout(()=>{qt=!0,It.abort(),Rn(ui)},gu),on=async(Ee,Rt,Mt)=>{zn=Ee,Tn=Rt,Dt=Rt==="intent_create"||Rt==="session_claim"?"transport_error":"provider_runtime";let wn=ae?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Mt,Un])}finally{let Ot=ae?.now()??globalThis.performance?.now()??Date.now();ae?.performance({stage:Ee,durationMs:Math.max(0,Ot-wn),durationMode:"machine",requestCategory:Rt,paymentMethodCategory:"wallet",provider:"stripe",...qt?{statusClass:"timeout"}:{}})}};try{if(Be(!0),c?.(null),!de&&b){let Le=await on("processing","other",b(Xe));if(!Le.proceed){g();return}de={accountPatch:Le.accountPatch,sessionId:Le.sessionId,nonce:Le.nonce}}let Ee=de?.sessionId??e;Ge=Ee;let Rt=de?.nonce??t,Mt=$e.current??de?.accountPatch,wn=gc({event:H,fallbackEmail:Mt?.email??n,fallbackName:[Mt?.firstName,Mt?.lastName].join(" ").trim()||I});if(!(0,y.isValidEmail)(wn.email)){g("Buyer details are required."),Ae(hs(ee),wn).then(Le=>{Le&&($e.current=Le)});return}$e.current=null;let Ot={...de?.accountPatch,...On(wn,!0)};await on("processing","session_claim",Promise.resolve(k?.(wn)));let{error:Yn}=await on("tokenization","provider_sdk",ne.submit());if(Yn){g(),U(ee,Yn,"stripe_wallet_submit_failed",v?.generation);return}if(!Ee)throw new Error("Missing sessionId or email for payment.");let yn={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ee,paymentMethodId:null,intentKind:o},Ht=JSON.stringify({sessionId:Ee,nonce:Rt??"",request:yn}),ln=dt.current,Xn=ln?.retryIdentity===Ht?ln.authorizationAttemptId:(0,y.randomUuidV4)();dt.current={authorizationAttemptId:Xn,retryIdentity:Ht};let fn=await on("processing","intent_create",yi(r,q,Ee,Rt??"",{...yn,authorizationAttemptId:Xn},{signal:It.signal}));if(fn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let _t=fn.clientSecret,Qt=bu({createdAt:Date.now(),sessionId:Ee,...Rt?{nonce:Rt}:{},clientSecret:_t,providerObjectId:fn.providerObjectId,paymentMethodType:ee,accountPatch:Ot});window.clearTimeout(qn),Ke=!0,ae?.performance({stage:"callback",durationMs:Math.max(0,(ae?.now()??globalThis.performance?.now()??Date.now())-yt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let gn=ae?.now()??globalThis.performance?.now()??Date.now(),Nt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...kt?{walletType:kt}:{},attempt:Qe},en=!1,Kt=null;ae?.log({name:"payment.provider_confirmation.started",...Nt}),Lt=window.setTimeout(()=>{Lt!==null&&Me.current.delete(Lt),en=!0;let Le=ae?.now()??globalThis.performance?.now()??Date.now();ae?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Nt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Le-gn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),ae?.flush?.().catch(()=>{}),Kt?.()},hu),Me.current.add(Lt);let hn=(Le,Ct)=>{Lt!==null&&(window.clearTimeout(Lt),Me.current.delete(Lt),Lt=null);let ge=ae?.now()??globalThis.performance?.now()??Date.now(),L=Math.max(0,ge-gn),rt=Le;en&&(Le==="resolved"?rt="resolved_late":Le==="returned_error"?rt="returned_error_late":rt="rejected_late");let he=Ct??(Le==="resolved"?"approved":"provider_error");return ae?.log({name:"payment.provider_confirmation.returned",...Nt,operationOutcome:rt,terminalReason:he}),ae?.performance({...Nt,durationMs:L,durationMode:"buyer",operationOutcome:rt,terminalReason:he}),{durationMs:L,operationOutcome:rt,terminalReason:he}},vt=!1,ue=!1,Vn=Le=>{if(!Le||typeof Le!="object")return null;let Ct=Le;if(Ct.error)return null;let ge=Ct.setupIntent??Ct.paymentIntent,L=ms(ge??null,void 0,!!Ct.setupIntent);return L.kind==="confirmed"?L:null},jn=Le=>{if(vt||v&&Ie.current!==v.generation)return;let Ct=Vn(Le);if(!Ct)return;if(Qt&&!ec(Ee,Rt,_t)){vt=!0;return}let{intentId:ge,paymentMethodId:L}=Ct;vt=!0,ue=!0,dt.current=null,F.current=null,Se.current&&(T("idle"),Be(!1));let rt=`${uc}:${Ee}`;Wt(rt,{createdAt:Date.now(),sessionId:Ee,nonce:Rt,accountPatch:Ot,paymentMethodId:L,providerIntentId:ge,paymentMethodType:ee});try{s({id:L,type:"card",threeDSecureActionResultTokenId:ge},{accountPatch:Ot,paymentMethodCategory:"wallet",sessionId:Ee,nonce:Rt})}finally{Wt(rt)}},Sr=!1;Kt=async()=>{if(!(Sr||vt||ue)){Sr=!0,Se.current&&T("checking");try{let Le=await tc(E,_t,Me.current);if(vt||ue)return;let Ct=(0,y.isSetupIntentClientSecret)(_t),ge=ms(Le,fn.providerObjectId,Ct);if(ge.kind==="confirmed"){jn(Ct?{setupIntent:Le}:{paymentIntent:Le});return}if(ge.kind==="terminal"){if(ue=!0,ps(Ee,Rt,_t),dt.current=null,F.current=null,!Se.current)return;T("idle"),g(),U(ee,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",v?.generation,!0);return}Se.current&&!ue&&(T("blocked"),Be(!1))}catch{Se.current&&!ue&&(T("blocked"),Be(!1))}finally{Sr=!1}}},F.current=Kt;let kn,cn;try{let Le=await((0,y.isSetupIntentClientSecret)(_t)?E.confirmSetup({elements:ne,clientSecret:_t,redirect:"if_required"}):E.confirmPayment({elements:ne,clientSecret:_t,redirect:"if_required"}));if(!Le||typeof Le!="object"||(kn=Le,!kn.error&&!Vn(kn)))throw us;cn=hn(kn.error?"returned_error":"resolved",kn.error&&fo(kn.error)?"provider_declined":void 0)}catch(Le){let Ct=Le===us,ge=hn(Ct?"returned_error":"rejected");if(ae?.error({...Ct?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:Gi(Le),...Nt,operationOutcome:ge.operationOutcome,durationMs:ge.durationMs,statusClass:"unknown",terminalReason:ge.terminalReason}),!Se.current||vt)return;await Kt?.();return}let An=kn.error;if(An){if(!Se.current||vt)return;if(fo(An)){ue=!0,ps(Ee,Rt,_t),dt.current=null,F.current=null,T("idle");let Le=An.message??"Your payment was declined.";g(Le),c?.(Le),p?.(un(Xe,Le,{code:Mr(An),declineCode:No(An)})),fi({billingApiUrl:r,sessionId:Ee,nonce:Rt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ee,providerDeclineReason:Mr(An)??"provider_declined",...fn.intentKind==="payment"&&fn.providerObjectId.startsWith("pi_")?{providerIntentId:fn.providerObjectId}:{}}})}else ae?.error({...Gi(An),...Nt,operationOutcome:cn.operationOutcome,durationMs:cn.durationMs,statusClass:"unknown",terminalReason:cn.terminalReason}),await Kt?.();return}if(jn(kn),!vt)throw new Error("Invalid provider returned for APM intent")}catch(Ee){if(Ee===ui){let Rt=ae?.now()??globalThis.performance?.now()??Date.now();ae?.error({errorCode:Cu(Tn),stage:zn,requestCategory:Tn,paymentMethodCategory:"wallet",provider:"stripe",...kt?{walletType:kt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ge,durationMs:Math.max(0,Rt-yt),statusClass:"timeout",failureCategory:Dt,attempt:Qe,terminalReason:"provider_error"}),ae?.flush?.().catch(()=>{})}g(),U(ee,Ee,Ee===ui?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",v?.generation,Ee===ui)}finally{if(window.clearTimeout(qn),Lt!==null&&(window.clearTimeout(Lt),Me.current.delete(Lt)),!Ke){let Ee=ae?.now()??globalThis.performance?.now()??Date.now();ae?.performance({stage:"callback",durationMs:Math.max(0,Ee-yt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...qt?{statusClass:"timeout"}:{}})}Se.current&&Be(!1)}},[E,ne,e,t,n,I,Ae,k,r,q,o,s,c,p,b,U,Y,gt,mt,Ie,$,ve]),St=(0,i.useMemo)(()=>{let H=["applePay","googlePay","paypal","link","amazonPay","klarna"],nt=new Set(["applePay","googlePay"]),g=new Set(a.map(y.stripeExpressMethodToOptionKey)),v={};for(let ee of H)g.has(ee)?v[ee]=nt.has(ee)?"always":"auto":v[ee]="never";return v},[a]),Ze=(0,i.useMemo)(()=>a.map(y.stripeExpressMethodToOptionKey),[a]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Pc,{state:W,placeholderTestId:"flopay-wallet-placeholder",borderRadius:f,children:(0,d.jsxs)("div",{ref:Re,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[me&&(0,d.jsxs)("button",{ref:xe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:lt,style:gs,children:["Try ",hs(ye)," again"]}),st!=="idle"&&(0,d.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,d.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,d.jsx)("button",{type:"button",onClick:Z,disabled:st==="checking",style:gs,children:st==="checking"?"Checking payment status\u2026":"Check payment status"})]}),X&&(0,d.jsx)(Lo,{identity:X.identity,methodLabel:X.methodLabel,onComplete:it,onCancel:()=>it(null)},X.id),st==="idle"&&(0,d.jsx)("div",{style:{display:X?"none":void 0},children:(0,d.jsx)(Zt.ExpressCheckoutElement,{onReady:H=>{ie(hc(H,Ze))},onLoadError:H=>{ie("load_error"),Ss($,"stripe","wallet","provider_error")},onClick:async H=>{De.current=H.expressPaymentType,re.current=ac(H.expressPaymentType);let nt=!0,g=window.setTimeout(()=>{nt=!1,H.reject()},fu),v=b?await b(re.current):{proceed:!0};if(window.clearTimeout(g),!nt)return;if(!v.proceed){Oe.current.delete(ve),H.reject();return}let ee=ut(H.expressPaymentType);Oe.current.set(ve,{generation:ee,method:H.expressPaymentType,accountPatch:v.accountPatch,sessionId:v.sessionId,nonce:v.nonce}),He(!1),$?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ee,...H.expressPaymentType==="apple_pay"||H.expressPaymentType==="google_pay"?{walletType:H.expressPaymentType}:{}}),u?.(re.current),H.resolve()},onConfirm:qe,onCancel:()=>{let H=Oe.current.get(ve);Oe.current.delete(ve),$?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...H?{attempt:H.generation}:{}}),J(H?.generation),dt.current=null,He(!1),ce.current=!0,ft()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:St,emailRequired:Ue,billingAddressRequired:Ue,layout:{maxColumns:1,overflow:"never"}}},ve)})]})}),V&&(0,d.jsx)(Ln,{status:"processing"})]})}function bc(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function zu({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:s,backgroundColor:c,borderColor:u,textColor:p,borderRadius:h,fontFamily:b}){let I=(0,y.resolveStripeMethodBrandVariant)(e,t),k=jl[e],[C,f]=(0,i.useState)(!1),S=!!k&&!C,G=I?.backgroundColor??c??"#ffffff",_=I?.borderColor??u??"#d1d5db",q=I?.textColor??p??"#262833";return(0,d.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&s()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Ia,padding:"0 1rem",backgroundColor:G,color:q,border:`1px solid ${_}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,d.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,y.getStripeMethodDisplayName)(e)}\u2026`}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,y.hasVendoredStripeMethodLogo)(e)?8:0},children:[S?(0,d.jsx)("img",{src:k,alt:"","aria-hidden":"true",onError:()=>f(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!S&&I?.logoSvg?(0,d.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:I.logoSvg}}):null,(0,d.jsx)("span",{children:(0,y.getStripeMethodDisplayName)(e)})]}),a&&(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:q,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,d.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Ps({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:c,onErrorChange:u,onDecline:p,onCancel:h,runBeforeButtonClick:b,onButtonClick:I,isProcessing:k,submitButtonColor:C,submitButtonBorderRadius:f,submitButtonStyle:S,errorText:G}){let _=Hr(),{emitInstrument:q}=(0,i.useContext)(rr),E=(0,Zt.useStripe)(),ne=(0,Zt.useElements)(),[$,W]=(0,i.useState)(!1),ie=(0,i.useRef)(!1),[V,Be]=(0,i.useState)(!1),[Ue,X]=(0,i.useState)("loading"),[Ae,it]=(0,i.useState)(""),Re=!(0,y.isValidEmail)(r?.trim()),xe=!Re||(0,y.isValidEmail)(Ae.trim()),ve=(0,i.useCallback)(async()=>{if(!E||!ne||k||ie.current||!V)return;ie.current=!0,W(!0);let se=b?await b("card"):{proceed:!0};if(!se.proceed){ie.current=!1,W(!1);return}I?.("card");let me=se.sessionId??t,He=se.nonce??n,st=mo(o?.trim()),T=On({email:se.accountPatch?.email?.trim()||r?.trim()||Ae.trim(),firstName:se.accountPatch?.firstName?.trim()||st.firstName,lastName:se.accountPatch?.lastName?.trim()||st.lastName}),ye=T.email,le=On({...se.accountPatch,...T});try{if(u?.(null),!(0,y.isValidEmail)(ye))throw new Error("A valid email address is required for payment.");await a?.(T);let F=await ne.submit();if(F.error){u?.(F.error.message??"Payment failed.");return}let Se=[T.firstName,T.lastName].filter(Boolean).join(" "),ce=await E.createPaymentMethod({elements:ne,params:{billing_details:{email:ye,...Se?{name:Se}:{}}}});if(ce.error||!ce.paymentMethod){u?.(ce.error?.message??"Failed to create payment method.");return}let De=ce.paymentMethod;if(!me||!ye)throw new Error("Missing sessionId or email for payment.");let re=De.type||e,$e=await yi(s,q,me,He??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,paymentMethodId:null,intentKind:"payment"});if($e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let dt=$e.clientSecret;Wt(Br,{clientSecret:dt,sessionId:me,nonce:He,accountPatch:le,paymentMethodId:De.id,paymentMethodType:De.type??e,gateway:"stripe"});let{error:Me,paymentIntent:Oe}=await E.confirmPayment({clientSecret:dt,confirmParams:{return_url:window.location.href,payment_method:De.id},redirect:"if_required"});if(Me){Wt(Br);let J=Me.message??"Payment failed.";u?.(J),p?.(un("card",J,{code:Me.code})),await fi({billingApiUrl:s,sessionId:me,nonce:He,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Me.code??"provider_declined"}});return}let ut=Oe?.status;if(!da(ut)){Wt(Br);let J=ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";u?.(J),p?.(un("card",J,{code:ut??"missing_payment_intent"}));return}Wt(Br);let Y=typeof Oe?.payment_method=="string"?Oe.payment_method:Oe?.payment_method?.id;c({id:Y??De.id,type:"card",threeDSecureActionResultTokenId:Oe?.id,gateway:"stripe",paymentMethodType:De.type??e},{accountPatch:le,paymentMethodCategory:"apm",sessionId:me,nonce:He})}catch(F){u?.(F instanceof Error?F.message:"Payment failed. Please try again.")}finally{ie.current=!1,W(!1)}},[E,ne,k,V,b,I,t,n,r,o,Ae,a,s,q,e,c,u,p]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Re&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Re&&(0,d.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,d.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Ae,onChange:se=>it(se.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(Zt.PaymentElement,{onReady:()=>X("ready"),onLoadError:()=>{X("load_error"),Ss(pn(_),"stripe","apm")},onChange:se=>{Be(!!se.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,y.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,d.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{ve()},disabled:!V||!xe||$||k||Ue!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:C,color:"white",border:"none",borderRadius:f,fontSize:"1rem",fontWeight:600,cursor:!V||!xe||$||k||Ue!=="ready"?"not-allowed":"pointer",opacity:!V||!xe||$||k||Ue!=="ready"?.5:1,transition:"opacity 120ms ease-out",...S??{}},children:$?"Processing\u2026":`Pay with ${(0,y.getStripeMethodDisplayName)(e)}`}),G&&(0,d.jsx)(Uo,{margin:"0.75rem 0 0",children:G})]})}function dc({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:s,stripeInstance:c,paymentElementBaseOptions:u,onTokenizedBody:p,onErrorChange:h,onButtonClick:b,onDecline:I,runBeforeButtonClick:k,onLoadStateChange:C,isProcessing:f=!1,submitButtonColor:S="#4A49FF",submitButtonBorderRadius:G=8,submitButtonStyle:_,buttonAppearance:q,themeId:E,onExpandApm:ne,expandedApmMethod:$}){let{emitInstrument:W}=(0,i.useContext)(rr),[ie,V]=(0,i.useState)(null),[Be,Ue]=(0,i.useState)(null),X=(0,i.useRef)(!1),{request:Ae,collect:it,finish:Re}=Oo();(0,i.useEffect)(()=>{s.length>0&&c?C?.("ready"):c||C?.("loading")},[s.length,c,C]);let xe=(0,i.useCallback)(async T=>{if(!c||X.current||f)return;X.current=!0,Ue(T);let ye=k?await k("card"):{proceed:!0};if(!ye.proceed){X.current=!1,Ue(null);return}b?.("card");let le=ye.sessionId??e,F=ye.nonce??t,Se=mo([ye.accountPatch?.firstName,ye.accountPatch?.lastName].filter(Boolean).join(" ")||r),ce=On({email:ye.accountPatch?.email?.trim()||n?.trim(),firstName:ye.accountPatch?.firstName?.trim()||Se.firstName,lastName:ye.accountPatch?.lastName?.trim()||Se.lastName});if(!(0,y.isValidEmail)(ce.email)){Ue(null);let $e=await it((0,y.getStripeMethodDisplayName)(T),ce);if(!$e){X.current=!1;return}ce=$e,Ue(T)}let De=ce.email,re=On({...ye.accountPatch,...ce});try{if(h?.(null),!le||!(0,y.isValidEmail)(De))throw new Error("Missing sessionId or email for payment.");await o?.(ce);let $e=await yi(a,W,le,F??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,paymentMethodId:null,intentKind:"payment"});if($e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let dt=$e.clientSecret;Wt(Br,{clientSecret:dt,sessionId:le,nonce:F,accountPatch:re,paymentMethodType:T,gateway:"stripe"});let{error:Me,paymentIntent:Oe}=await c.confirmPayment({clientSecret:dt,confirmParams:{return_url:window.location.href,payment_method_data:{type:T,billing_details:{name:[ce.firstName,ce.lastName].filter(Boolean).join(" "),...De?{email:De}:{}}}},redirect:"if_required"});if(Me){Wt(Br);let J=Me.message??"Payment failed.";h?.(J),I?.(un("card",J,{code:Me.code})),await fi({billingApiUrl:a,sessionId:le,nonce:F,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,providerDeclineReason:Me.code??"provider_declined"}});return}let ut=Oe?.status;if(!da(ut)){Wt(Br);let J=ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(J),I?.(un("card",J,{code:ut??"missing_payment_intent"}));return}Wt(Br);let Y=typeof Oe?.payment_method=="string"?Oe.payment_method:Oe?.payment_method?.id;p({id:Y??Oe?.id,type:"card",threeDSecureActionResultTokenId:Oe?.id,gateway:"stripe",paymentMethodType:T},{accountPatch:re,paymentMethodCategory:"apm",sessionId:le,nonce:F})}catch($e){h?.($e instanceof Error?$e.message:"Payment failed. Please try again.")}finally{X.current=!1,Ue(null)}},[c,f,k,b,e,t,n,it,a,W,r,o,p,h,I]),[ve,se]=(0,i.useState)(null),me=ne?$??null:ve,He=(0,i.useCallback)(T=>{X.current||f||me&&me!==T||((0,y.needsStripeMethodExplicitConfirm)(T)?ne?ne(T):se(T):xe(T))},[me,f,xe,ne]),st=(0,i.useMemo)(()=>ve?bc(u,ve):null,[ve,u]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ae?(0,d.jsx)(Lo,{identity:Ae.identity,methodLabel:Ae.methodLabel,onComplete:Re,onCancel:()=>Re(null)},Ae.id):s.map(T=>{let ye=$===T,le=Be===T,F=Be!==null&&Be!==T||$!=null&&$!==T;return(0,d.jsxs)(i.default.Fragment,{children:[(0,d.jsx)(zu,{method:T,themeId:E,submitting:le,disabled:F,highlighted:ye,hasNextStep:(0,y.needsStripeMethodExplicitConfirm)(T),onClick:()=>He(T),backgroundColor:q?.backgroundColor,borderColor:q?.borderColor,textColor:q?.textColor,borderRadius:q?.borderRadius,fontFamily:q?.fontFamily}),!ne&&ve===T&&st&&c&&(0,d.jsx)(Zt.Elements,{stripe:c,options:st,children:(0,d.jsx)(Ps,{method:T,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:p,onErrorChange:h,onDecline:I,onCancel:()=>se(null),runBeforeButtonClick:k,onButtonClick:b,isProcessing:f,submitButtonColor:S,submitButtonBorderRadius:G,submitButtonStyle:_})},T)]},T)})})}function Uu({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:s,onError:c,onDecline:u,onTokenizedBody:p,firstName:h,lastName:b,chv:I,className:k,submitLabel:C,isProcessing:f,error:S,onErrorChange:G,showPayPal:_=!0,showStripe:q=!0,walletPresentation:E="auto",enabledPaymentMethods:ne,enabledPaymentMethodCountries:$,showApplePay:W=!0,showGooglePay:ie=!0,layout:V="default",theme:Be,buttonsTheme:Ue,buttonsStyles:X,appearance:Ae,cardButtonContent:it,cardBackButtonContent:Re,cardTitleContent:xe,showSecurityFooter:ve,onButtonClick:se,onBeforeButtonClick:me,onBuyerIdentityReady:He,enableAVS:st,cardFieldOrder:T,cardPreFormSlot:ye,avsLayout:le="row",country:F,zip:Se,addressLine1:ce,addressLine2:De,city:re,state:$e,onCountryChange:dt,onZipChange:Me,avsCheck:Oe,checkoutType:ut,checkoutLayout:Y,totalAmount:J=0,currency:mt="usd",initialCardOpen:gt=!1,directPaypal:Ie,isSubscription:ft=!1,session:U,dataAttachmentPending:we=!1,dataAttachmentRequiresIdentity:lt=!1,debug:Z=!1}){let qe=Hr(),St=Wa(),Ze=(0,i.useContext)(Pr),{emitInstrument:H}=(0,i.useContext)(rr),nt=(0,i.useRef)(null);nt.current||(nt.current=Ya());let g=nt.current,[,v]=(0,i.useState)(0),ee=(0,i.useRef)(null);ee.current||(ee.current=Kr());let de=ee.current,Xe=(0,i.useMemo)(()=>({browser:de,capability:g,presentationMode:"popup"}),[de,g]),kt=U??Ze.session,Qe=kt?.gateways?.paypal?.providerObjectType??Ie?.providerObjectType,ae=we||Ze.claimPending===!0,yt=lt||Ze.claimRequiresIdentity===!0,It=ae&&!yt,qt=Tl(),Ke=n||qt,[Lt,Ge]=(0,i.useState)(!1),[zn,Tn]=(0,i.useState)(null),[Dt,Rn]=(0,i.useState)(F??""),[Un,qn]=(0,i.useState)(Se??""),[on,Ee]=(0,i.useState)(ce??""),[Rt,Mt]=(0,i.useState)(De??""),[wn,Ot]=(0,i.useState)(re??""),[Yn,yn]=(0,i.useState)($e??""),[Ht,ln]=(0,i.useState)(""),[Xn,fn]=(0,i.useState)({}),_t=(0,i.useRef)(Se??""),Qt=(0,i.useRef)(F??""),gn=(0,i.useRef)(ce??""),Nt=(0,i.useRef)(De??""),en=(0,i.useRef)(re??""),Kt=(0,i.useRef)($e??""),hn=(0,i.useRef)(""),vt=(0,i.useRef)({});(0,i.useEffect)(()=>{let l=(R,te,ze,pe,Te)=>{if(vt.current[R])return;let Jt=te?.trim();!Jt||Jt===ze.current||(ze.current=Jt,pe(Jt),Te?.(Jt))};l("country",F,Qt,Rn,dt),l("zip",Se,_t,qn,Me),l("addressLine1",ce,gn,Ee),l("addressLine2",De,Nt,Mt),l("city",re,en,Ot),l("state",$e,Kt,yn)},[F,Se,ce,De,re,$e,dt,Me]);let ue=(0,i.useMemo)(()=>(0,y.resolveAVSConfig)(st),[st]),Vn=ue!==null,jn=(0,i.useMemo)(()=>(0,y.isAuthorizationOnlySession)(U),[U]),Sr=!!U?.vault?.html,kn=!!U?.gateways?.pcivault,cn=Wi(U),Le=!!(U?.gateways?.stripe?.enabledPaymentMethods??ne)?.includes("card")||Zr(U),Ct=Sr||Le||kn,ge=!!(q&&Ct&&e),[L,rt]=(0,i.useState)(()=>V!=="buttons"||gt?e??null:null),[he,Jn]=(0,i.useState)(0),Pn=V!=="buttons"||gt||!!e&&L===e,Gt=U?.captureMethod,Zn=(0,i.useRef)(qe);(0,i.useEffect)(()=>{Zn.current=qe},[qe]);let[pt,Xr]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!ge||!e||!Pn){Xr(null);return}let l=Zn.current?Zn.current.cardCapture({sessionId:e,captureMethod:Gt}):new Cr.PciVaultCardCapture({sessionId:e,captureMethod:Gt,billingApiUrl:Ke,telemetry:r});return Xr({sessionId:e,captureMethod:Gt,billingApiUrl:Ke,telemetry:r,capture:l}),()=>{l.unmount()}},[ge,e,Pn,Gt,Ke,r]);let Yt=ge&&e&&Pn&&pt?.sessionId===e&&pt.captureMethod===Gt&&pt.billingApiUrl===Ke&&pt.telemetry===r?pt.capture:null,bn=(0,i.useMemo)(()=>{let l=Dt,R=ue?(0,y.isAVSFieldVisible)(ue.postal_code,l):!1;return Ou(l,Un,R)},[ue,Dt,Un]),{avsInvalid:Nr,invalidAvsFields:zr}=(0,i.useMemo)(()=>{let l={line1:!1,city:!1,state:!1,zip:!1};if(!ge||!ue)return{avsInvalid:!1,invalidAvsFields:l};let R=Dt,te=(Te,Jt)=>(0,y.isAVSFieldVisible)(Te,R)&&!Jt.trim(),ze={line1:te(ue.address_line_1,on),city:te(ue.city,wn),state:te(ue.state,Yn),zip:bn.empty||bn.malformed};return{avsInvalid:ze.line1||ze.city||ze.state||ze.zip,invalidAvsFields:ze}},[ge,ue,Dt,on,wn,Yn,bn]),[xn,tn]=(0,i.useState)(!1),[wr,Mn]=(0,i.useState)(!1),[Ur,Fn]=(0,i.useState)(!1),[kr,Ir]=(0,i.useState)({line1:!1,city:!1,state:!1}),cr=(0,i.useRef)(!1),Qn=(0,i.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),er=(0,i.useRef)(!1),Bt=(0,i.useCallback)(l=>{Qn.current[l]=!0,er.current=!0},[]),dr=(0,i.useCallback)(l=>!cr.current&&Qn.current[l],[]),_n=(0,i.useCallback)(l=>{dr(l)&&Ir(R=>R[l]?R:{...R,[l]:!0})},[dr]),[tr,Rr]=(0,i.useState)(()=>ys(U?.vault)),[ht,an]=(0,i.useState)(gt&&Ct?"card":"buttons"),[nn,qr]=(0,i.useState)(null),$n=ht==="expanding"||ht==="card",Jr=U?.gateways?.stripe&&!cn?"stripe":void 0,ur=(0,i.useCallback)(()=>{H?.({class:"card_surface",provider:Jr})},[Jr,H]),pr=(0,i.useRef)(null),vn=(0,i.useCallback)(l=>{pr.current&&clearTimeout(pr.current),pr.current=setTimeout(()=>{pr.current=null,l()},Ra)},[]);(0,i.useEffect)(()=>()=>{pr.current&&clearTimeout(pr.current)},[]);let mr=(0,i.useCallback)(()=>{ur(),rt(e??null),Jn(l=>l+1),an("expanding"),vn(()=>an("card"))},[vn,ur,e]),Vr=(0,i.useCallback)(()=>{an("collapsing"),vn(()=>an("buttons"))},[vn]),En=(0,i.useCallback)(l=>{qr(l),an("apm-expanding"),vn(()=>an("apm-form"))},[vn]),D=(0,i.useCallback)(()=>{an("apm-collapsing"),vn(()=>{an("buttons"),qr(null)})},[vn]);(0,i.useEffect)(()=>{V==="buttons"&&gt&&Ct&&(rt(e??null),an("card"))},[V,gt,Ct,e]);let[z,B]=(0,i.useState)(null),Pe=(0,i.useRef)(!1),Ve=(0,i.useRef)(null),Pt=(0,i.useRef)("idle"),[Ce,je]=(0,i.useState)(!1),Q=(0,i.useRef)(Ce);Q.current=Ce;let[m,P]=(0,i.useState)(()=>Ie?.existingOrderId?{orderId:Ie.existingOrderId,attempts:1}:null),N=(0,i.useRef)(m);(0,i.useEffect)(()=>{N.current=m},[m]);let j=(0,i.useRef)(null),be=(0,i.useMemo)(()=>{if(He||Ze.claimBuyerIdentity||U?.buyerIdentified!==!1||!e||!t)return;let l=`${Ke}|${e}|${t}`;j.current?.key!==l&&(j.current={key:l,claim:Bo(new Cr.PaymentAPI(Ke,{telemetry:!1}),e,t,{...a?{userId:a}:{},...h?{firstName:h}:{},...b?{lastName:b}:{}})});let R=j.current.claim;return async te=>{await R(te)}},[He,Ze.claimBuyerIdentity,U?.buyerIdentified,e,t,Ke,a,h,b]),oe=He??Ze.claimBuyerIdentity??be,et=S??zn,Tt=(0,i.useMemo)(()=>(0,y.resolveTheme)(Be),[Be]),M=(0,i.useMemo)(()=>{let l=Tt?.buttonsLayout??(0,y.resolveButtonsLayoutTheme)(Ue);return X?{...l,...X,cardButton:{...l.cardButton,...X.cardButton},cardFormContainer:{...l.cardFormContainer,...X.cardFormContainer},backButton:{...l.backButton,...X.backButton},backButtonIcon:{...l.backButtonIcon,...X.backButtonIcon},submitButton:{...l.submitButton,...X.submitButton},title:{...l.title,...X.title}}:l},[Tt,Ue,X]),_e=Ae??Tt?.appearance,Ft=(0,i.useMemo)(()=>Go({appearance:_e,buttonsStyles:M,layout:V}),[_e,M,V]),ke=Ze.inlineSessionPatchProcessing??!1,K=(f??Lt)||ke,fe=Ke.replace(/\/+$/,""),x=(0,i.useMemo)(()=>Ki({userId:a,email:o,firstName:h,lastName:b,country:F,zip:Se},Xn),[a,o,h,b,F,Se,Xn]),Ye=[x.firstName,x.lastName].filter(l=>!!l?.trim()).join(" "),At=!(0,y.isValidEmail)(x.email?.trim()),Ne=(0,i.useRef)(null);ge&&Ne.current===null&&(Ne.current=At);let In=ge&&(Ne.current??At),_r=(0,i.useMemo)(()=>Lu(Ht,In),[Ht,In]),Co=_r.empty||_r.malformed,Wn=(0,i.useMemo)(()=>qe?qe.getRawProvider():null,[qe]),Fs=(0,i.useMemo)(()=>St?St.getRawProvider():null,[St]),Xo=J||100,So=mt.toLowerCase(),Ri=(0,i.useMemo)(()=>_e?(0,Cr.toStripeAppearance)(_e):null,[_e]),wo=Ri,Bs=(0,i.useMemo)(()=>{let l=Ri??{},R=l.rules??{};return{...l,rules:{...R,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...R[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...R[".AccordionItemContents"]??{}}}}},[Ri]),Ds=(0,i.useMemo)(()=>({...kl(J,U?.captureMethod),currency:So,...wo?{appearance:wo}:null}),[J,So,U?.captureMethod,wo]),Os=(0,i.useMemo)(()=>({mode:"payment",amount:Xo,currency:So,captureMethod:"manual",setupFutureUsage:"off_session",...wo?{appearance:wo}:null}),[Xo,So,wo]),Fe=(0,i.useCallback)(l=>{Tn(l),G?.(l)},[G]),_i=(0,i.useRef)(""),[Ls,Yc]=(0,i.useState)(!1),Ei=(0,i.useCallback)(()=>{Yc(!0)},[]);(0,i.useEffect)(()=>{if(!ge||!In||!oe||!Ls||Co||_i.current)return;let l=On({email:(0,y.isValidEmail)(x.email?.trim())?x.email?.trim():hn.current.trim(),firstName:x.firstName?.trim(),lastName:x.lastName?.trim()});_i.current=JSON.stringify(l),fn(R=>({...R,...l})),Promise.resolve(oe(l)).catch(R=>{_i.current="",Fe(R instanceof Error?R.message:"Failed to attach buyer details.")})},[ge,In,oe,Ls,Co,x.email,x.firstName,x.lastName,Fe]),(0,i.useEffect)(()=>{!ge||!Yt||Yt.setCardFieldOrder?.(T??null,ue==null&&!In)},[ge,Yt,T,ue,In]),(0,i.useEffect)(()=>{(ht==="expanding"||ht==="collapsing"||ht==="apm-expanding"||ht==="apm-collapsing")&&Fe(null)},[ht,Fe]);let Er=(0,i.useCallback)((l,R,te)=>{u?.(un(l,R,te))},[u]),ko=(0,i.useCallback)((l,R,te)=>{let ze=te?.popupBlocked??oo(R);ze&&g.markBlocked()&&v(ct=>ct+1);let pe=no(hs(l),ze,de.inAppBrowser),Te=Mr(R),Jt=(Te?.toLowerCase()==="error"?void 0:Te)??yo(te?.code)??"external_payment_method_failed",gr=new y.FloPayError(pe,"api_error",{code:"external_payment_method_failed",param:l,details:{providerCode:Jt,popupBlocked:ze,inAppBrowser:de.inAppBrowser,appFamily:de.appFamily,popupCapability:g.current(),presentationMode:te?.presentationMode??"popup"}});te?.telemetryReported||pn(qe)?.error(Ho({...Xe,presentationMode:te?.presentationMode??"popup"},{errorCode:ze?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:te?.provider??(l==="paypal"?"paypal":"stripe"),paymentMethodCategory:te?.paymentMethodCategory??(l==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:te?.terminalReason??(ze?"popup_blocked":"provider_error")})),B(null),V==="buttons"&&(an("buttons"),qr(null)),Fe(pe),c?.(gr),console.error("[FloPay] External payment method failed:",{method:l,code:Jt,popupBlocked:ze})},[de,Xe,qe,V,c,g,Fe]);(0,i.useEffect)(()=>{if(!ge||!e){Rr(null);return}let l=ys(U?.vault);if(l){Rr(l);return}if(!Pn){Rr(null);return}Rr(null);let R=!0;return new Cr.PaymentAPI(fe).getVaultCapture(e,t).then(te=>{if(!R)return;let ze=ys(te);ze?Rr(ze):Fe("Failed to load the secure card form.")}).catch(te=>{R&&Fe(te instanceof Error?te.message:"Failed to load the secure card form.")}),()=>{R=!1}},[ge,Pn,he,e,U?.vault,fe,t,Fe]);let yr=(0,i.useRef)({onComplete:s,onError:c,updateError:Fe,emitDecline:Er,resolvedAccount:x,avsConfig:ue,avsCheckProp:Oe,sessionId:e,nonce:t,baseUrl:fe,captureMethod:U?.captureMethod,paymentId:U?.paymentId,authorizationExpiresAt:U?.authorizationExpiresAt,serverSideCardGateway:cn});yr.current={onComplete:s,onError:c,updateError:Fe,emitDecline:Er,resolvedAccount:x,avsConfig:ue,avsCheckProp:Oe,sessionId:e,nonce:t,baseUrl:fe,captureMethod:U?.captureMethod,paymentId:U?.paymentId,authorizationExpiresAt:U?.authorizationExpiresAt,serverSideCardGateway:cn};let Ti=(0,i.useRef)(!1),Ns=(0,i.useCallback)(()=>{let l=yr.current,R=l.resolvedAccount.email?.trim(),te=(0,y.isValidEmail)(R)?R:hn.current.trim();if(!(0,y.isValidEmail)(te))return null;let ze=l.resolvedAccount.firstName?.trim(),pe=l.resolvedAccount.lastName?.trim(),Te=Qt.current.trim()||l.resolvedAccount.country?.trim()||"",Jt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.state,Te):!1,gr=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_1,Te):!1,ct=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.postal_code,Te):!1,bt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.city,Te):!1,Et=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_2,Te):!1,jt=gr&&!Jt&&ct?(0,y.getStateFromPostalCode)(Te,(_t.current??"").trim()):null,dn=Jt?Kt.current:jt;return{accountData:{userId:l.resolvedAccount.userId??"",email:te,...ze?{firstName:ze}:{},...pe?{lastName:pe}:{},...ct&&_t.current?{zip:_t.current}:{},...bt&&en.current?{city:en.current}:{},...dn?{state:dn}:{},...gr&&gn.current?{addressLine1:gn.current}:{},...Et&&Nt.current?{addressLine2:Nt.current}:{},...Te?{country:Te}:{}},...l.avsCheckProp===void 0?{}:{avsCheck:l.avsCheckProp},...l.avsConfig?{avsConfig:{country:(0,y.isAVSFieldVisible)(l.avsConfig.country,Te),postal_code:ct,address_line_1:gr,address_line_2:Et,city:bt,state:Jt}}:{}}},[]),zs=(0,i.useRef)(ae);zs.current=ae,(0,i.useEffect)(()=>{ae||et!==nc||yr.current.updateError(null)},[ae,et]),(0,i.useEffect)(()=>{!ge||!Yt||Yt.setSubmitGate?.(Nr||ae||Co||Ce)},[ge,Yt,Nr,ae,Co,Ce]),(0,i.useEffect)(()=>{if(!ge||!Yt)return;Ti.current=!1;let l=null,R=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null,Pt.current="idle",B(null)},400)},te=Yt.on("submitting",()=>{tn(!0),Ve.current&&clearTimeout(Ve.current),Pt.current="validation-window",Ve.current=setTimeout(()=>{Ve.current=null,Pt.current==="validation-window"&&(Pt.current="processing")},ku),B("processing");let ct=yr.current;if(!ct.sessionId||!ct.nonce)return;let bt=Ns();if(!bt){ct.updateError("Enter a valid email address."),Pt.current="idle",B(null);return}new Cr.PaymentAPI(ct.baseUrl).patchAccountSnapshot(ct.sessionId,ct.nonce,bt,{telemetryMode:"best_effort"}).catch(Et=>{if(!Ru(Et))return;let jt=Et instanceof Error?Et.message:"Please check your billing address and try again.";ct.updateError(jt),Pt.current="idle",B(null),ct.onError?.(Et instanceof y.FloPayError?Et:new y.FloPayError(jt,"api_error"))})}),ze=Yt.on("complete",async ct=>{if(jo(ct.sessionId??yr.current.sessionId),Pt.current="terminal",je(!1),B("success"),await new Promise(dn=>setTimeout(dn,600)),Ti.current)return;Ti.current=!0;let bt=yr.current,Et=(0,y.isAuthorizationOnlySession)(bt)||ct.outcome==="authorized",jt=bt.serverSideCardGateway?{}:{paymentIntentId:ct.intentId};yr.current.onComplete?.(Et?{status:"authorized",...jt,paymentId:ct.paymentId??bt.paymentId,sessionId:ct.sessionId??bt.sessionId,authorizationExpiresAt:ct.authorizationExpiresAt??bt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...jt,checkoutMethod:"card"})}),pe=Yt.on("decline",ct=>{let bt=yr.current,Et=ct.message??"Your payment was declined. Please try another card or contact your bank.";Pt.current="terminal",je(!1),bt.updateError(Et),B("error");let jt=ct.failureOutcome??(0,y.normalizeCheckoutFailureOutcome)(ct.declineReason)??"authorization_declined";bt.emitDecline("card",Et,{code:jt,declineCode:jt}),R()}),Te=Yt.on("error",ct=>{let bt=yr.current,Et=ct.message??"There was a problem processing your payment. Please try again.";Pt.current="terminal",je(!1),bt.updateError(Et),B("error"),bt.onError?.(new y.FloPayError(Et,"api_error",{code:ct.failureOutcome??"capture_failed"})),R()}),Jt=Yt.on("challenge_dismissed",()=>{Ve.current&&(clearTimeout(Ve.current),Ve.current=null),Pt.current="processing",je(!0),B(null)}),gr=Yt.on("blocked",()=>{if(Q.current){yr.current.updateError(Iu);return}if(!zs.current){tn(!0);return}Ei(),yr.current.updateError(nc)});return()=>{l&&(clearTimeout(l),l=null),Ve.current&&(clearTimeout(Ve.current),Ve.current=null),Pt.current="idle",je(!1),B(null),te(),ze(),pe(),Te(),Jt(),gr()}},[ge,Yt,Ei,Ns]);let Tr=!!Ie?.clientId,Jo=Array.isArray(ne),xa=Jo&&ne.length>0,Us=Jo&&ne.includes("paypal"),Ma=(0,i.useRef)(null);Ma.current===null&&(Ma.current=Su());let Io=Ma.current?"redirect":Ha(de,E,g.current()),{expressMethods:Fa,paymentElementMethods:Zo}=(0,i.useMemo)(()=>(0,y.partitionStripeMethods)(ne,{excludePaypal:Tr}),[ne,Tr]),qs=Tr||!!St||Us&&Io==="redirect",Xc=(0,i.useMemo)(()=>qs?Fa.filter(l=>l!=="paypal"):Fa,[Fa,qs]),Jc=(0,i.useMemo)(()=>{let l=[];return W&&l.push("apple_pay"),ie&&l.push("google_pay"),l},[W,ie]),Ro=Jo?Xc:Jc,Zc=q&&Ro.length>0,Ai=Vn?Dt:F,Ba=(0,i.useMemo)(()=>{let l=Ai?.trim().toUpperCase();return l?$?Zo.filter(R=>{let te=$[R];return!te||te.length===0||te.includes(l)}):(0,y.filterStripeMethodsByCountry)(Zo,Ai):Zo},[Zo,Ai,$]),xi=(0,i.useMemo)(()=>({mode:"payment",amount:Xo,currency:So,paymentMethodCreation:"manual",appearance:Bs}),[Xo,So,Bs]),[Vs,js]=(0,i.useState)("loading"),[$s,Ws]=(0,i.useState)("loading"),[Hs,Ks]=(0,i.useState)("loading"),[Qc,Mi]=(0,i.useState)(!1),[Gs,Fi]=(0,i.useState)("loading"),[Bi,ed]=(0,i.useState)();(0,i.useEffect)(()=>{ed(Kr())},[]);let Da=Bi?.inAppBrowser,Oa=Bi?Ka(Bi,Ie?.approvalPresentation,Qe??(ft?"subscription":"order")):"popup",Ys=_&&(Tr||(Jo?Us:Da===!1)),Xs=q&&Zc,Qo=(!It||!!Ze.waitForDataAttachment)&&Ys&&Tr,Js=Gs==="retrying"||Gs==="exhausted",ea=null;q&&(St?ea=Fs:Io==="redirect"&&(ea=Wn));let Zs=(0,i.useMemo)(()=>({...Xe,presentationMode:Io}),[Xe,Io]),ta=!It&&Ys&&!!ea&&(!Tr||Js),_o=!It&&Xs&&!!Wn,na=!It&&q&&xa&&Ba.length>0&&!!Wn,td=Qo&&!Js?Qc:ta&&sc(Vs),nd=_o&&sc($s),rd=na&&Hs!=="load_error",Qs=l=>l==="loading"||l==="ready",el=Qo||ta&&Qs(Vs)||_o&&Qs($s)||na&&Hs!=="load_error",La=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(!La.current){if(!q&&!_){La.current=!0;let l=new y.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(l),Fe(l.message)}else if(!q&&_&&!Tr){La.current=!0;let l=new y.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(l),Fe(l.message)}else if(Da!==void 0&&!It&&!Ct&&!el){La.current=!0;let l=new y.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});c?.(l),Fe(l.message)}}},[q,_,Tr,Da,It,Ct,el,c,Fe]);let tl=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(tl.current||!xa)return;let l=[];W!==!0&&l.push("showApplePay"),ie!==!0&&l.push("showGooglePay"),l.length!==0&&(tl.current=!0,console.warn(`[FloPay] ${l.join(" / ")} ${l.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[xa,W,ie]);let nl=(0,i.useCallback)((l,R)=>Ze.applyInlineSessionPatch?Ze.applyInlineSessionPatch(l).then(te=>({error:null,sessionId:te.sessionId||e,nonce:te.session?.clientSecret||t})).catch(te=>{let ze=ic(R,te);return Fe(ze.message),c?.(ze),{error:ze,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ze.applyInlineSessionPatch,t,c,e,Fe]),fr=(0,i.useCallback)(async l=>{if(l!=="card"&&It&&await Ze.waitForDataAttachment?.(),!me)return{proceed:!0};try{let R=await me({method:l,sessionId:e||void 0,createSession:Ze.inlineSessionDraft});if(R===!1)return{proceed:!1};if(R&&typeof R=="object"){R.account&&fn(ze=>({...ze??{},...R.account}));let te=await nl(R,l);return te.error?{proceed:!1,accountPatch:R.account}:{proceed:!0,accountPatch:R.account,sessionId:te.sessionId,nonce:te.nonce}}return{proceed:!0}}catch(R){let te=ic(l,R);return Fe(te.message),c?.(te),{proceed:!1}}},[nl,Ze.inlineSessionDraft,Ze.waitForDataAttachment,It,me,c,e,Fe]),rl=(0,i.useCallback)(async(l,R)=>{if(Pe.current)return;Pe.current=!0,Ge(!0),B("processing"),Fe(null);let te=R?.sessionId??e,ze=R?.nonce??t,pe=Ki(x,R?.accountPatch),Te=R?.completionPaymentMethodId??ua(l),Jt=l.originalPaymentMethodId?{...l,originalPaymentMethodId:void 0}:l,gr=xu(l),ct=R?.presentationMode?li(pn(qe),{...Xe,presentationMode:R.presentationMode}):void 0,bt=()=>{H?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:gr}),ct?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...vr,requestCategory:"process_payment"})};try{let jt=await new Cr.PaymentAPI(fe).processPayment(pe.userId??"",{sessionId:te,nonce:ze,paymentMethodCategory:R?.paymentMethodCategory??Fu(l),tokenizedData:Jt,accountData:{...R?.accountPatch,userId:pe.userId??"",email:pe.email??"",firstName:pe.firstName||void 0,lastName:pe.lastName||void 0,...ue?(()=>{let zt=Qt.current,Ar=(0,y.isAVSFieldVisible)(ue.state,zt),Hn=(0,y.isAVSFieldVisible)(ue.address_line_1,zt),xr=(0,y.isAVSFieldVisible)(ue.postal_code,zt),po=Hn&&!Ar&&xr?(0,y.getStateFromPostalCode)(zt,(_t.current??"").trim()):null,la=Ar?Kt.current:po;return{country:zt,...xr&&_t.current?{zip:_t.current}:{},...(0,y.isAVSFieldVisible)(ue.city,zt)&&en.current?{city:en.current}:{},...la?{state:la}:{},...Hn&&gn.current?{addressLine1:gn.current}:{},...(0,y.isAVSFieldVisible)(ue.address_line_2,zt)&&Nt.current?{addressLine2:Nt.current}:{}}})():{}},chv:I,avsCheck:Oe??!1,checkoutType:ut,checkoutLayout:Y,avsConfig:ue?{country:(0,y.isAVSFieldVisible)(ue.country,Qt.current),postal_code:(0,y.isAVSFieldVisible)(ue.postal_code,Qt.current),address_line_1:(0,y.isAVSFieldVisible)(ue.address_line_1,Qt.current),address_line_2:(0,y.isAVSFieldVisible)(ue.address_line_2,Qt.current),city:(0,y.isAVSFieldVisible)(ue.city,Qt.current),state:(0,y.isAVSFieldVisible)(ue.state,Qt.current)}:void 0});if(jt.ok){let zt=jt.status===204?null:await jt.json().catch(()=>null),Ar=(0,y.isAuthorizationOnlySession)(U)||zt?.status==="authorized";jo(te),ct?.terminal({outcome:"payment_succeeded",...vr}),B("success"),P(null),await new Promise(po=>setTimeout(po,600));let Hn;typeof zt?.paymentId=="string"?Hn=zt.paymentId:U?.paymentId&&(Hn=U.paymentId);let xr;typeof zt?.authorizationExpiresAt=="string"?xr=zt.authorizationExpiresAt:U?.authorizationExpiresAt&&(xr=U.authorizationExpiresAt),s?.(Ar?{status:"authorized",...Hn===void 0?{}:{paymentId:Hn},sessionId:typeof zt?.sessionId=="string"?zt.sessionId:te,...xr===void 0?{}:{authorizationExpiresAt:xr},paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Te,checkoutMethod:l.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Te,checkoutMethod:l.isPaypal?"paypal":"card"});return}let dn=await jt.json().catch(()=>null);if(dn?.type==="paypal_redirect_required"){let zt=dn.threeDSecureToken,Ar=dn.paymentMethodId||l.id||"";if(!qe||!zt){B("error"),Fe("PayPal authorization required but no token provided.");return}try{let Hn=St?.getRawProvider();if(!Hn){Fe("PayPal is not available.");return}let xr={return_url:window.location.href};Ar&&(xr.payment_method=Ar);let{error:po}=await Hn.confirmPayment({clientSecret:zt,confirmParams:xr,redirect:"if_required"});if(po){B("error");let la=po.message??"PayPal payment failed.";Fe(la),Er("paypal",la,{code:po.code})}}catch(Hn){B("error"),Fe(Hn instanceof Error?Hn.message:"PayPal authorization failed.")}return}if(dn?.type==="paypal_direct_required"){let zt=dn.orderId;if(!zt){B("error"),Fe("PayPal retry required but no order id provided.");return}let Ar=N.current?.attempts??0;if(Ar>=2){B("error"),Fe("PayPal payment could not be completed after multiple attempts."),Er("paypal","paypal_direct_required retry limit exceeded");return}Mi(!1),Fi("loading"),P({orderId:zt,attempts:Ar+1}),B(null);return}(0,y.classifyPaymentRejection)(jt.status,dn)?ct?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}):bt(),B("error");let hr=dn?.message??"Payment failed. Please try again.";Fe(hr),Er(l.isPaypal?"paypal":"card",hr,{code:dn?.code??dn?.gatewayErrorCode,declineCode:dn?.declineCode??dn?.gatewayDeclineReason}),await new Promise(zt=>setTimeout(zt,400))}catch(Et){yc(Et)||bt(),B("error"),Fe(Et instanceof Error?Et.message:"An unexpected error occurred"),await new Promise(jt=>setTimeout(jt,400))}finally{Ge(!1),B(null),Pe.current=!1}},[fe,e,t,x,ue,Oe,ut,Y,I,qe,St,U,s,Fe,Er,H,Xe]),Bn=(0,i.useCallback)((l,R)=>{p?p(l):rl(l,R)},[p,rl]),ra=`${uc}:${e}`;(0,i.useEffect)(()=>{if(typeof window>"u")return;let l=localStorage.getItem(ra);if(!l)return;let R;try{R=JSON.parse(l)}catch{Wt(ra);return}if(!R||typeof R.createdAt!="number"||Date.now()-R.createdAt<0||Date.now()-R.createdAt>pc||typeof R.paymentMethodId!="string"||typeof R.providerIntentId!="string"||typeof R.paymentMethodType!="string"||R.sessionId!==e||!t||R.nonce!==t||!Ro.includes(R.paymentMethodType)){Wt(ra);return}Wt(ra),Bn({id:R.paymentMethodId,type:"card",threeDSecureActionResultTokenId:R.providerIntentId,gateway:"stripe",paymentMethodType:R.paymentMethodType},{...R.accountPatch?{accountPatch:R.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Bn,t,e,ra,Ro]);let ol=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(typeof window>"u"||ol.current)return;let[l,R,te]=vs();if(!l||!R||Ma.current||!qe)return;let ze=qe.getRawProvider();if(!ze)return;let pe=bt=>{let Et=localStorage.getItem(bt);if(!Et)return null;try{return JSON.parse(Et)}catch{return Wt(bt),null}},Te=pe(Br)??pe(Ql),Jt;if(Te?.clientSecret){if(Te.clientSecret!==R)return;Jt={...Te.accountPatch?{accountPatch:Te.accountPatch}:{},...Te.sessionId?{sessionId:Te.sessionId}:{},...Te.nonce?{nonce:Te.nonce}:{}}}else if(Te?.sessionId&&Te.sessionId!==e)return;ol.current=!0,Wt(Br),Wt(Ql),window.history.replaceState({},"",Cs());let gr=Te?.paymentMethodType??Te?.tokenType??"card",ct="card";(async()=>{if(te==="failed"){let hr="Payment was declined. Please try again.";Fe(hr),Er(ct,hr);return}let{paymentIntent:bt,error:Et}=await ze.retrievePaymentIntent(R);if(Et){let hr=Et.message??"Failed to retrieve payment status.";Fe(hr),Er(ct,hr,{code:Et.code});return}let jt=bt?.status,dn=da(jt);if(!bt||!dn){let hr=jt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Fe(hr),Er(ct,hr,{code:jt??"missing_payment_intent"});return}let yl=typeof bt.payment_method=="string"?bt.payment_method:bt.payment_method?.id;Bn({id:yl??Te?.paymentMethodId??Te?.tokenId??bt.id,type:"card",threeDSecureActionResultTokenId:bt.id,gateway:Te?.gateway??"stripe",paymentMethodType:gr},Jt)})()},[e,Bn,qe,Fe,Er]);let Di=(0,i.useCallback)(l=>{l.preventDefault()},[]);if(!(ge||qe!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let oa=V==="buttons",Dn=_e?.variables,od=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Oi=Dn?.colorBackground,ad=Oi&&!od.has(Oi)?Oi:void 0,aa=M.cardInputBorder??(oa?"#e5e7eb":"#A4A4FF"),al=Dn?.colorDanger??"#dc2626",Vt=l=>zr[l]&&(kr[l]||xn),Na=Co&&(Ur||xn),nr=l=>l?al:aa,za=(bn.malformed||bn.empty)&&(wr||xn),id=nr(za),Li=M.cardFormContainer?.backgroundColor??ad??(oa?"white":"#EDEDFF"),Eo=M.cardInputBackground??Dn?.colorBackground??"white",Ni=xo(Re),il=xo(xe),To=M.nameInput,sl=M.cardInputFontSize??Nu(To?.fontSize)??Dn?.fontSizeBase??"16px",ll=typeof To?.fontFamily=="string"?To.fontFamily:Dn?.fontFamily??"Poppins, sans-serif",cl=ds(To?.fontWeight)??400,sd=M.cardInputColor??(typeof To?.color=="string"?To.color:void 0)??Dn?.colorText??"#262833",ld=M.cardInputPlaceholderColor??"#9ca3af",Xt=Dn?.borderRadius??"8px",co=Dn?.borderRadius??M.cardButton?.borderRadius??Xt,uo=Dn?.colorPrimary??"#4A49FF",cd=Dn?.colorPrimaryHover??Ko(uo,.12),zi=Dn?.colorText??"#262833",Ui={fontSize:sl,fontFamily:ll,fontWeight:cl,color:sd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ia={marginTop:"0.375rem",...Ui,fontSize:"0.75rem",lineHeight:1.4,color:al},dd={"--flopay-input-placeholder-color":ld,"--flopay-input-font-size":sl,"--flopay-input-font-family":ll,"--flopay-input-font-weight":String(cl)},sa=M.cardFormContainer??{},qi=sa.padding??(oa?"0":"1rem"),Vi=sa.borderRadius??Xt,ud=Yt&&tr?(0,d.jsx)(so,{capture:Yt,html:tr.html,messageToken:tr.messageToken,expectedOrigin:tr.expectedOrigin,theme:Ft,submitLabel:C,onReady:()=>{if(!In&&!ue||typeof document>"u")return;let l=()=>{let te=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(te){cr.current=!0;try{te.focus()}finally{cr.current=!1}}};er.current||l()},onError:l=>Fe(l),onValidation:l=>{let R=Pt.current;(R==="idle"||R==="validation-window")&&(Fe(l),l&&Pt.current==="validation-window"&&(Ve.current&&(clearTimeout(Ve.current),Ve.current=null),Pt.current="idle",B(null)))}}):(0,d.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),dl=(0,d.jsxs)("div",{onFocusCapture:l=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(l.target.tagName)&&ur()},style:{backgroundColor:Li,borderRadius:Vi,...sa,padding:qi,...dd,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${Ne.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),Vo&&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:wi?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)(Po,{content:ke})]}),$s?(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)(Yo,{content:Oe})})]}),!Vo&&!$s&&(0,c.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ki,order:ie?-3:0,...E.title},children:(0,c.jsx)(Yo,{content:Oe})}),ie&&We&&(0,c.jsx)("div",{style:{order:-2,width:"100%"},children:We}),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:yo,border:`1px solid ${Jn(Ia)}`,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),io||mi()},disabled:j,required:!0,"aria-invalid":Ia||void 0,"aria-describedby":Ia?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ii}})}),Ia&&(0,c.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Ho,children:Sr.empty?"Email address is required":"Enter a valid email address"})]}),te&&(0,c.jsx)("div",{style:{order:ie?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Mt,S=(ne=!1)=>({backgroundColor:yo,border:`1px solid ${Jn(ne)}`,borderRadius:Yt,marginTop:"0.5rem",padding:"10px"}),K=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ii}),Ee=(0,y.getStateOptions)(s);return(0,c.jsxs)(c.Fragment,{children:[(0,y.isAVSFieldVisible)(te.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:ne=>{xt("line1"),gt.current.addressLine1=!0,yn.current=ne.target.value,Ce(ne.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:Ho,children:"Street address is required"})]}),(0,y.isAVSFieldVisible)(te.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:ne=>{gt.current.addressLine2=!0,Dt.current=ne.target.value,Tt(ne.target.value)},disabled:j,"data-testid":"flopay-address-line2",style:K()})}),((0,y.isAVSFieldVisible)(te.city,s)||(0,y.isAVSFieldVisible)(te.state,s))&&(0,c.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(te.city,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:yo,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)(te.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:ne=>{xt("city"),gt.current.city=!0,Qt.current=ne.target.value,Bt(ne.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)(te.state,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:yo,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)(te.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Jn(zt("state")||zt("city"))}`}:{borderRadius:Yt}},children:Ee?(0,c.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Vn,onChange:ne=>{xt("state"),gt.current.state=!0,Ht.current=ne.target.value,pn(ne.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)}),Ee.map(ne=>(0,c.jsx)("option",{value:ne.code,children:ne.name},ne.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:ne=>{xt("state"),gt.current.state=!0,Ht.current=ne.target.value,pn(ne.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:Ho,children:"City is required"}),zt("state")&&(0,c.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Ho,children:[(0,y.getStateLabel)(s)," is required"]}),((0,y.isAVSFieldVisible)(te.country,s)||(0,y.isAVSFieldVisible)(te.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)(te.country,s)&&(0,c.jsx)("div",{style:{flex:ye==="row"?1:void 0,backgroundColor:yo,borderTop:`1px solid ${Wo}`,borderRight:`1px solid ${Wo}`,borderBottom:`1px solid ${Wo}`,borderLeft:`1px solid ${Wo}`,padding:"10px",...ye==="row"&&(0,y.isAVSFieldVisible)(te.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:ne=>{gt.current.country=!0,Zt.current=ne.target.value,wn(ne.target.value),lt?.(ne.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(ne=>(0,c.jsxs)("option",{value:ne.code,children:[ne.flag," ",ne.name]},ne.code))]})}),(0,y.isAVSFieldVisible)(te.postal_code,s)&&(0,c.jsx)("div",{style:{flex:ye==="row"?1:void 0,backgroundColor:yo,border:`1px solid ${Ac}`,padding:"10px",...ye==="row"&&(0,y.isAVSFieldVisible)(te.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:ne=>{xt("zip"),gt.current.zip=!0,wt.current=ne.target.value,On(ne.target.value),Te?.(ne.target.value)},onPointerDown:()=>xt("zip"),onKeyDown:()=>xt("zip"),onBlur:()=>{or("zip")&&Tn(!0)},disabled:j,required:hn.required,"aria-invalid":Ra||void 0,"aria-describedby":Ra?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:K()})})]}),Ra&&(0,c.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Ho,children:hn.empty?`${(0,y.getPostalCodeLabel)(s)} is required`:au(s)})]})})()}),ie&&Dc,Ye&&(0,c.jsx)(Ro,{margin:"0.75rem 0",styleOverride:E.errorBanner,children:Ye})]}),_a={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"},Ks=s=>V?!T||!kr?(0,c.jsx)("pre",{"data-testid":s,style:_a,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":s,style:_a,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${T}`,` directPaypalConfigured=${kr}`,` inAppBrowserDetected=${String(Sa)}`,` shouldRenderDirectPayPal=${zo}`,` shouldRenderStripePayPal=${qo}`,` hasPaypalStripeInstance=${!!fs}`].join(`
39
- `)}):null,Gs=s=>V?!Y||!Un?(0,c.jsx)("pre",{"data-testid":s,style:_a,children:"FloPay/Stripe-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":s,style:_a,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${Y}`,` currency=${jt}`,` amountInCents=${Oo}`,` enabledPaymentMethods: ${JSON.stringify(de??[])}`,` enabledPaymentMethodsProvided=${Lo}`,` hasEnabledMethods=${ba}`,` expressMethods: ${JSON.stringify(va)}`,` walletExpressMethods: ${JSON.stringify(po)}`,` paymentElementMethods: ${JSON.stringify(No)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ca)}`,` hasStripeInstance=${!!Un}`,` shouldRenderWallets=${mo}`,` shouldRenderPaymentElement=${$o}`].join(`
40
- `)}):null,Ys=dt==="apm-expanding"||dt==="apm-form"||dt==="apm-collapsing",go;dt==="apm-expanding"?go=$l:dt==="apm-collapsing"&&(go=jl);let Ea=tn?oc(gi,tn):null;if(oe==="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:ma,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ee;dt==="expanding"||dt==="apm-expanding"?Ee=eu:(dt==="collapsing"||dt==="apm-collapsing")&&(Ee=Qd);let ne;return dt==="expanding"?ne=$l:dt==="collapsing"&&(ne=jl),(0,c.jsxs)("form",{onSubmit:vi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Qi,{}),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&&!Ee?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!Ee?nu:{},...Ee?{animation:Ee,pointerEvents:"none"}:{}},children:[Ks("flopay-direct-paypal-gate-debug"),Gs("flopay-stripe-gate-debug"),zo&&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)(ta.Provider,{value:f,children:(0,c.jsx)(ra,{sessionId:e,nonce:t,billingApiUrl:Ne,email:_.email,billingName:Ue||void 0,onBuyerIdentityReady:J,clientId:ut.clientId,environment:ut.environment,currency:jt.toUpperCase(),isSubscription:Et,providerObjectType:Ge,approvalPresentation:wa==="popup"?void 0:wa,onTokenizedBody:xn,onComplete:l,onErrorChange:we,onDecline:u,onTechnicalFailure:co,onButtonClick:me,runBeforeButtonClick:cr,isProcessing:j,onLoadStateChange:hi,onInitializationStateChange:bi,session:vt,existingOrderId:m?.orderId,debug:V},m?.orderId??"fresh")})]}),qo&&(0,c.jsx)(Jt.Elements,{stripe:Uo,options:bs,children:(0,c.jsx)(Kl,{sessionId:e,nonce:t,email:_.email,billingName:Ue||void 0,onBuyerIdentityReady:J,billingApiUrl:Ne,onTokenizedBody:xn,onErrorChange:we,isProcessing:j,onButtonClick:me,onDecline:u,onTechnicalFailure:co,runBeforeButtonClick:cr,onLoadStateChange:Is,placeholderBorderRadius:Zr,popupCapabilityOwner:f,externalTelemetryContext:Fs,presentationMode:uo})}),mo?(0,c.jsx)(Jt.Elements,{stripe:Un,options:hs,children:(0,c.jsx)(Gl,{sessionId:e,nonce:t,email:_.email,billingName:Ue||void 0,onBuyerIdentityReady:J,billingApiUrl:Ne,intentKind:Ae>0?"payment":"setup",expressMethods:po,onTokenizedBody:xn,onErrorChange:we,onButtonClick:me,onDecline:u,onTechnicalFailure:co,runBeforeButtonClick:cr,onLoadStateChange:_s,placeholderBorderRadius:Zr,popupCapabilityOwner:f,externalTelemetryContext:qe})}):null,!mo&&Ms?(0,c.jsx)("div",{style:{height:ma,borderRadius:Zr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,$o&&(0,c.jsx)(Yl,{sessionId:e,nonce:t,email:_.email,billingName:[_.firstName,_.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:Ne,paymentElementMethods:Ca,stripeInstance:Un,paymentElementBaseOptions:gi,onTokenizedBody:xn,onErrorChange:we,onButtonClick:me,onDecline:u,runBeforeButtonClick:cr,onLoadStateChange:Ts,isProcessing:j,submitButtonColor:Qr,submitButtonBorderRadius:Yt,submitButtonStyle:E.submitButton,onExpandApm:In,expandedApmMethod:tn,themeId:je,buttonAppearance:{backgroundColor:E.cardButton?.backgroundColor,borderColor:E.cardInputBorder,textColor:E.cardButton?.color,borderRadius:Zr}}),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,...ss({themeBundle:It,resolvedPrimaryColor:Qr,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=Bc)},onMouseLeave:Se=>{(It||Mn?.colorPrimary)&&(Se.currentTarget.style.backgroundColor=Qr)},onMouseDown:Se=>{Se.currentTarget.style.transform="scale(0.985)"},onMouseUp:Se=>{Se.currentTarget.style.transform="scale(1)"},children:(0,c.jsx)(bo,{content:ft})}),Ye&&dt==="buttons"&&(0,c.jsx)(Ro,{margin:"0.25rem 0",styleOverride:E.errorBanner,children:Ye})]}),ie&&S&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...ne?{animation:ne}:{},...dt==="collapsing"?{pointerEvents:"none"}:{}},children:Hs}),Y&&Ys&&tn&&Ea&&Un&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...go?{animation:go}:{},...dt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Si,borderRadius:_i,...Ko,padding:Ri},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:wi?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)(Po,{content:ke})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:E.titleFontSize??"1.05rem",color:ki,paddingRight:80,...E.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(tn)}`})]}),(0,c.jsx)(Jt.Elements,{stripe:Un,options:Ea,children:(0,c.jsx)(ns,{method:tn,sessionId:e,nonce:t,email:_.email,billingName:[_.firstName,_.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:Ne,onTokenizedBody:xn,onErrorChange:we,onDecline:u,onCancel:x,runBeforeButtonClick:cr,onButtonClick:me,isProcessing:j,submitButtonColor:Qr,submitButtonBorderRadius:Yt,submitButtonStyle:E.submitButton,errorText:Ye})},tn)]})})]})]})}return Ys&&tn&&Ea&&Un&&Y?(0,c.jsxs)("form",{onSubmit:vi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Qi,{}),L&&(0,c.jsx)(er,{status:L,errorMessage:Ye,authorized:Nn}),(0,c.jsx)("div",{style:{...go?{animation:go}:{},...dt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Si,borderRadius:_i,...Ko,padding:Ri},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:wi?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)(Po,{content:ke})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:E.titleFontSize??"1.05rem",color:ki,paddingRight:80,...E.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(tn)}`})]}),(0,c.jsx)(Jt.Elements,{stripe:Un,options:Ea,children:(0,c.jsx)(ns,{method:tn,sessionId:e,nonce:t,email:_.email,billingName:[_.firstName,_.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:Ne,onTokenizedBody:xn,onErrorChange:we,onDecline:u,onCancel:x,runBeforeButtonClick:cr,onButtonClick:me,isProcessing:j,submitButtonColor:Qr,submitButtonBorderRadius:Yt,submitButtonStyle:E.submitButton,errorText:Ye})},tn)]})})]}):(0,c.jsxs)("form",{onSubmit:vi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Qi,{}),L&&(0,c.jsx)(er,{status:L,errorMessage:Ye,authorized:Nn}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ks("flopay-direct-paypal-gate-debug-default"),Gs("flopay-stripe-gate-debug-default"),zo&&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)(ta.Provider,{value:f,children:(0,c.jsx)(ra,{sessionId:e,nonce:t,billingApiUrl:Ne,email:_.email,billingName:Ue||void 0,onBuyerIdentityReady:J,clientId:ut.clientId,environment:ut.environment,currency:jt.toUpperCase(),isSubscription:Et,providerObjectType:Ge,approvalPresentation:wa==="popup"?void 0:wa,onTokenizedBody:xn,onComplete:l,onErrorChange:we,onDecline:u,onTechnicalFailure:co,onButtonClick:me,runBeforeButtonClick:cr,isProcessing:j,onLoadStateChange:hi,onInitializationStateChange:bi,session:vt,existingOrderId:m?.orderId,debug:V},m?.orderId??"fresh")})]}),qo&&(0,c.jsx)(Jt.Elements,{stripe:Uo,options:bs,children:(0,c.jsx)(Kl,{sessionId:e,nonce:t,email:_.email,billingName:Ue||void 0,onBuyerIdentityReady:J,billingApiUrl:Ne,onTokenizedBody:xn,onErrorChange:we,isProcessing:j,onButtonClick:me,onDecline:u,onTechnicalFailure:co,runBeforeButtonClick:cr,onLoadStateChange:Is,placeholderBorderRadius:Zr,popupCapabilityOwner:f,externalTelemetryContext:Fs,presentationMode:uo})}),mo&&(0,c.jsx)(Jt.Elements,{stripe:Un,options:hs,children:(0,c.jsx)(Gl,{sessionId:e,nonce:t,email:_.email,billingName:Ue||void 0,onBuyerIdentityReady:J,billingApiUrl:Ne,intentKind:Ae>0?"payment":"setup",expressMethods:po,onTokenizedBody:xn,onErrorChange:we,onButtonClick:me,onDecline:u,onTechnicalFailure:co,runBeforeButtonClick:cr,onLoadStateChange:_s,placeholderBorderRadius:Zr,popupCapabilityOwner:f,externalTelemetryContext:qe})}),$o&&(0,c.jsx)(Yl,{sessionId:e,nonce:t,email:_.email,billingName:[_.firstName,_.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Ne,paymentElementMethods:Ca,stripeInstance:Un,paymentElementBaseOptions:gi,onTokenizedBody:xn,onErrorChange:we,onButtonClick:me,onDecline:u,runBeforeButtonClick:cr,onLoadStateChange:Ts,isProcessing:j,submitButtonColor:Qr,submitButtonBorderRadius:Yt,submitButtonStyle:E.submitButton,themeId:je,onExpandApm:In,expandedApmMethod:tn,buttonAppearance:{backgroundColor:E.cardButton?.backgroundColor,borderColor:E.cardInputBorder,textColor:E.cardButton?.color,borderRadius:Zr}})]}),ie&&(Rc||Ic||_c)&&(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&&Hs]})}var M=require("react/jsx-runtime"),Do=44,ms="flopay_checkout_saved_payment_resume",si=new Map,ai=new Map;function ac(e,t){t.settled&&t.consumers===0&&si.get(e)===t&&si.delete(e)}function uu(e,t,n){let r=ai.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};ai.set(e,a);let l=()=>{ai.get(e)===a&&ai.delete(e)};return o.then(l,l),o}function fa(e){return new Promise(t=>setTimeout(t,e))}function ii(e,t,n){let r=Na({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Xe.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function ga(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ls(e,t,n,r,o,a){let l=ii(e,t,n);l.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),ga(l)}function ic(e,t,n,r){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function sc(e,t,n,r,o){let a=(0,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 uc(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 cs(e){return!e||e.data.stripe?.publishableKey?!1:!!uc(e)?.clientId}var pu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function mu(e){return new $r.FloPay(pu,{publishableKey:"provider_unavailable",...e})}async function ds(e,t){let{publishableKey:n,paypalPublishableKey:r}=Wi(e);return{...await Hi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function ys(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function yu(){if(!ys())return null;try{let e=window.sessionStorage.getItem(ms);return e?JSON.parse(e):null}catch{return null}}function lc(e){if(ys())try{window.sessionStorage.setItem(ms,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function us(){if(ys())try{window.sessionStorage.removeItem(ms)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function fu(){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 cc(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 ps(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function gu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function dc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function hu(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 li({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:B,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:Fe,buttonsStyles:oe,cardButtonContent:je,cardBackButtonContent:yt,cardTitleContent:re,showSecurityFooter:De,onButtonClick:ft,onBeforeButtonClick:ke,enableAVS:Oe,cardFieldOrder:be,cardPreFormSlot:me,avsLayout:Ie,submitLabel:Ve,className:rt,initialErrorMessage:R=null,initialPayPalOrderId:We,children:ye,checkoutMode:N,confirmLabel:ve,renderConfirmButton:ue,onSessionCompleted:He}){let Q=(0,Xe.resolveBillingApiUrl)(r),ot=(0,C.useMemo)(()=>(0,Xe.resolveTheme)(he),[he]),lt=a??ot?.appearance,Te=n?"embedded_checkout":"standard_checkout",Le=ps(ye,X),[ct,at]=(0,C.useState)(null),[Ae,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,xe]=(0,C.useState)(null),bt=(0,C.useMemo)(()=>n?Eo(n):"",[n]),Ke=n?`create:${bt}`:`session:${e??""}`,$=dc(V),Je=(0,C.useRef)(new Set),f=(0,C.useRef)(Ke),P=(0,C.useRef)(Ke);ro(()=>{P.current=Ke,f.current!==Ke&&(f.current=Ke,Je.current.clear())},[Ke]);let H=(0,C.useCallback)(x=>{if(P.current===Ke){if(Di.has(x.name)){if(Je.current.has(x.name))return;Je.current.add(x.name)}st(()=>v?.(x))}},[Ke,v]),ee=Io(H,Ke),qe=(0,C.useRef)(!1),vt=(0,C.useCallback)(x=>{if(qe.current)return;let L=x.gateway||!$?x:{...x,gateway:$};H(L)},[H,$]);(0,C.useEffect)(()=>{ee({class:"lifecycle",name:"checkout.mount"})},[ee]);let[Ge,Z]=(0,C.useState)(e??""),it=e??Ge,Ct=n?"":it,[Nt,Ne]=(0,C.useState)(!0),[Ft,ze]=(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),te=(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),Re=(0,C.useRef)(!1),ht=(0,C.useRef)(null),ie=(0,C.useRef)(null),F=(0,C.useMemo)(()=>({checkoutMode:N??Mt,layout:gu(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)(B);Hn.current=B;let gn=(0,C.useCallback)(x=>Ka(ht,async L=>{try{return await x(L)}catch(A){throw L.aborted?Jr(A):A}}),[]);(0,C.useEffect)(()=>()=>{ht.current?.abort(),ht.current=null},[]);let Kt=(0,C.useCallback)((x,L)=>{Vt.current=x,jt(x),et.current=L,fe(L)},[]),Kn=(0,C.useCallback)(()=>{let x=ut.current;x&&(ut.current=null,x.destroy())},[]);(0,C.useEffect)(()=>{dn(Ae)?.setCheckoutContext(F),q&&q!==Ae&&dn(q)?.setCheckoutContext(F)},[Ae,q,F]);let nt=(0,C.useRef)(He);nt.current=He;let jr=(0,C.useCallback)(x=>{Nn(x),!(x!=="exhausted"||Re.current)&&(Re.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(x=>x+1)},[]);(0,C.useEffect)(()=>{Nn("loading"),Cn(0),Re.current=!1},[it]),(0,C.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Xe.SDK_VERSION,checkout_type:Te,checkout_layout:Le,billing_api_url:Q})},[Le,Te,Q]);let hn=(0,C.useMemo)(()=>n?Eo(n,!0):"",[n]),Mr=(0,C.useMemo)(()=>Wn===hn?Wt:void 0,[Wt,Wn,hn]),Br=(0,C.useMemo)(()=>n?Ai(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),te.current=void 0,fn.current=null,Ht(!1)},[hn]),(0,C.useEffect)(()=>{Ce(R)},[R]);let br=(0,C.useCallback)((x,L,A)=>{st(()=>{Hn.current?.(cn(x,L,A))})},[]),Tn=(0,C.useCallback)(async(x,L)=>{Ce(null),Bt(null),pn(!1),Tt("processing");let A=L?.sessionId??x.id,le=x.clientSecret||t,Me=dc(x),pt=Vt.current??et.current,pe=dn(pt),Be=pt?null:ii(Q,o,F),W={log:E=>{pe?pe.log(E):Be?.log(E)},error:E=>{pe?pe.error(E):Be?.error(E)},terminal:E=>{pe?pe.terminal(E):Be?.terminal(E)},performance:E=>{pe?pe.performance(E):Be?.performance(E)},now:()=>pe?.now()??Be?.now()??0,elapsed:E=>pe?.elapsed(E)??Math.max(0,(Be?.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"}),qe.current=!0;try{W.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{qe.current=!1}ee({class:"lifecycle",name:"payment.processing.started",provider:Me}),g&&ce();let It;try{let E=Il(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(ae=>Ao(j,{billingApiUrl:Q,sessionId:A,nonce:le,session:x,signal:ae})));if(Pe)At=await ge(Pe);else if(E)ce(),E.type==="paypal_redirect_required"&&ie.current?.publishableKey&&lc({sessionId:A,publishableKey:ie.current.publishableKey,paypalPublishableKey:ie.current.paypalPublishableKey}),At=await gn(j=>Ya(E,{flopay:Vt.current,paypalFlopay:et.current,attempt3DS:L?.attempt3DS,billingApiUrl:Q,sessionId:A,session:x,telemetry:!1,signal:j})),E.type==="paypal_redirect_required"&&us();else if(L?.initialAutoProcessingPending){let j=L.initialAutoProcessingPending,ae=new $r.PaymentAPI(Q,{telemetry:!1}),_=await gn(_e=>ae.waitForCheckoutSessionCompletion(j.sessionId,{initialDelayMs:j.retryAfterMs,nonce:le,statusUrl:j.statusUrl,signal:_e})),Ue=Gr(_,x),Rt=_.autoProcessingError?.type==="3ds_required"&&_.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:_.autoProcessingError.nextActionRedirectUrl}:null;if(Rt)At=await ge(Rt);else{if(!Nr(Ue))throw Co(Ue);At=Lr(Ue,A)}}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"),cc("full")),!1;{let j=await xo({billingApiUrl:Q,sessionId:A,session:x,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&&lc({sessionId:A,publishableKey:ie.current.publishableKey,paypalPublishableKey:ie.current.paypalPublishableKey}),At=await gn(ae=>Ya(j,{flopay:Vt.current,paypalFlopay:et.current,attempt3DS:L?.attempt3DS,billingApiUrl:Q,sessionId:A,session:x,telemetry:!1,signal:ae})),j.type==="paypal_redirect_required"&&us())}}A&&To(A),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 fa(600),It=()=>Ze.current?.(At)}catch(E){let Pe=Hr(la(E),A);if(Pe.code==="three_ds_aborted")return!1;let At=Pe.checkoutMethod??sa;Ce(Pe.message),Bt(Pe.message),pn(!1),L?.fallbackToFull&&(W.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),wn("full"),cc("full")),Ye();let ge=Pe.statusCode===void 0?void 0:(0,Xe.telemetryStatusClass)(Pe.statusCode,"unknown"),j=ge==="4xx"?{requestCategory:"process_payment",statusClass:ge}:{},ae=ge===void 0||ge==="4xx";if(ae&&(Pe.telemetryOutcome==="payment_declined"||!!(Pe.declineCode||Pe.code?.toLowerCase().includes("declin"))))W.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...j});else if(ae&&(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"),_e=Pe.telemetryRequestCategory??"process_payment";qe.current=!0;try{W.error({...Rt,...Pe.telemetryFailureCategory?{failureCategory:Pe.telemetryFailureCategory}:{},stage:g?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:_e})}finally{qe.current=!1}ee({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:_e,provider:Me})}return st(()=>se.current?.(Pe)),br(At,Pe,{code:Pe.code,declineCode:Pe.declineCode}),Tt("error"),await Promise.allSettled([fa(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(),Be&&ga(Be),Tt(null),Bt(null)}return st(It),!0},[br,ee,t,Q,gn,o,F]);(0,C.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 A=yu();A&&(_n.current=!0,(async()=>{let le,Me=0;Ce(null),Bt(null),Tt("processing"),On(!0);try{if(x.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 Hi({publishableKey:A.publishableKey,paypalPublishableKey:A.paypalPublishableKey,billingApiUrl:Q,locale:l,telemetry:o});le=dn(pe??pt),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=(pe??pt)?.getRawProvider();if(!Be)throw Object.assign(new Xe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:W,error:m}=await Be.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=al(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(A.sessionId){let Ye=(await new $r.PaymentAPI(Q,{telemetry:!1}).getUnifiedCheckoutSession(A.sessionId)).data.session;if(Ye&&Ye.status!=="complete"){let It=await xo({billingApiUrl:Q,sessionId:A.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}}A.sessionId&&To(A.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"}),Tt("success"),await fa(600),st(()=>Ze.current?.({status:z,paymentIntentId:W.id,paymentMethodId:D,checkoutMethod:"paypal"}))}catch(pt){let pe=Hr(la(pt),A.sessionId),Be=pe.checkoutMethod??"paypal",W=!!(pe.declineCode||pe.code?.toLowerCase().includes("declin"));if(le)le.performance({stage:"redirect_resume",durationMs:le.elapsed(Me),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=ii(Q,o,F);m.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ga(m)}else ls(Q,o,F,"REDIRECT_RESUME_FAILED","redirect_resume");Ce(pe.message),Bt(pe.message),st(()=>se.current?.(pe)),br(Be,pe,{code:pe.code,declineCode:pe.declineCode}),Tt("error"),await fa(400)}finally{us(),fu(),Tt(null),Bt(null),On(!1)}})())},[br,l,Q,o,F]);let Fr=(0,C.useRef)(null),An=(0,C.useMemo)(()=>en?Eo(en):"",[en]),Pr=(0,C.useRef)(en);Pr.current=en,(0,C.useEffect)(()=>{Z(e??"")},[e]),(0,C.useEffect)(()=>{sn.current=!1,Ce(R),Bt(null),pn(!1),Tt(null)},[An,R,e]);async function vr(x,L,A){let le=ii(Q,o,F),Me=new $r.PaymentAPI(Q,{telemetry:!1}),pt=!1;try{let pe=x.idempotencyKey===void 0?void 0:(0,Xe.resolveIdempotencyKey)(x.idempotencyKey),Be=Ni(L,A),W=zi(L,A);Be?.canonicalIdentity===A&&W&&W.canonicalIdentity===void 0&&(Wa(L,A,W.idempotencyKey),W={...W,canonicalIdentity:A});let m=pe??(W?.canonicalIdentity===A?W.idempotencyKey:void 0),g,D=!1;le.log({name:Be?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let z=Be?.sid??null,ce=null,J,Ye,It=!1;if(z)try{ce=await Me.getUnifiedCheckoutSession(z,Be?.nonce),Be&&Be.canonicalIdentity===void 0&&(Cl(ce.data.session,x)?(Va(L,A,z,Be.nonce??ce.data.session?.clientSecret),W&&W.canonicalIdentity===void 0&&(Wa(L,A,W.idempotencyKey),m??(m=W.idempotencyKey))):(ja(L,A),W=null,m=pe,z=null,ce=null));let Pe=ce?.data.session?.status,At=ce?.data.session,ge=At?.clientSecret||Be?.nonce;if(z&&At?.buyerIdentified===!1&&ge&&(Ye=vo(Me,z,ge,x.account)),z&&ce&&Pe==="complete"){if(Ui(z))return{sid:z,result:ce};ja(L,A),z=null,ce=null,D=!0}}catch{le.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Be?.canonicalIdentity===void 0?(ja(L,A),m=pe):$a(L,A),z=null}if(!z){!pe&&(D||!m)&&(m=(0,Xe.resolveIdempotencyKey)(),g=m),m&&Wa(L,A,m);let Pe=le.now(),At=0;le.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ge={...x,idempotencyKey:m,avsCheck:!!Oe,avsConfig:typeof Oe=="object"?Oe:void 0,checkoutType:"embedded_checkout",checkoutLayout:ps(ye,X)};Object.defineProperty(ge,$r.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:_=>{At=Math.max(At,_)}}});let j=()=>{ic(le,"session_create",Pe,At)},ae=_=>{sc(le,_,"session_create",Pe,At)&&ee({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,Xe.isDetachedSessionEligible)(ge)){let _=await Me.createDetachedSession(ge);_.claimed.catch(()=>{}),ce=_.shell,z=_.sessionId,Ye=_.claim;let Ue=le.now();le.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),J=_.claimed.then(Rt=>{let _e=Rt.data.session?.id??_.sessionId;return _e&&Va(L,A,_e,Rt.data.session?.clientSecret??_.nonce),ic(le,"session_claim",Ue),j(),Rt},Rt=>{throw $a(L,A),sc(le,Rt,"session_claim",Ue,0)&&ee({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Rt}).finally(()=>ga(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 Me.createAndFetchSession(ge),j()}catch(_){throw ae(_),_}z=ce.data.session?.id??z??"",z&&!J&&Va(L,A,z,ce.data.session?.clientSecret)}let E=ce?.data.session;return!Ye&&z&&E?.buyerIdentified===!1&&E.clientSecret&&(Ye=vo(Me,z,E.clientSecret,x.account)),{sid:z??"",result:ce,sdkGeneratedIdempotencyKey:g,...J?{claimed:J}:{},...Ye?{claim:Ye}:{},...It?{claimRequiresIdentity:!0}:{}}}finally{pt||ga(le)}}let rr=(0,C.useRef)(vr);ro(()=>{rr.current=vr},[vr]);let Gn=(0,C.useCallback)(async(x,L)=>{let A=Pr.current;if(!A)throw new Xe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let le=Ai(A,x),Me=Eo(le),pt=vl(le),pe=si.get(Me);if(!pe){let m={canonicalIdentity:Me,promise:rr.current(le,pt,Me),consumers:0,settled:!1};pe=m,si.set(Me,m);let g=()=>{m.settled=!0,ac(Me,m)};m.promise.then(g,g)}pe.consumers+=1;let Be=!1,W=()=>{Be||(Be=!0,pe.consumers-=1,ac(Me,pe))};L?.(W);try{let m=await pe.promise;Fr.current=Me,x&&(mn(hn),an(E=>nl(E,x)));let{sid:g,result:D,claimed:z,claim:ce,claimRequiresIdentity:J}=m;if(te.current=ce,Ht(J===!0),at(D),D.data.session&&xe(D.data.session),g&&Z(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&&xe(Pe.data.session),Dt(!1),Ht(!1))},Pe=>{gt.current===E&&(fn.current===z&&(fn.current=null),Dt(!1),Ht(!1),ze(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 ds(D,{billingApiUrl:Q,locale:l,telemetry:o});return Kt(Ye,It),Ne(!1),m}catch(m){throw Fr.current===Me&&(Fr.current=null),m}finally{L||W()}},[hn,Kt,l,Q,o]),Yn=(0,C.useRef)(Tn);Yn.current=Tn;let xt=(0,C.useRef)(Gn);xt.current=Gn;let or=(0,C.useCallback)(async x=>{if(!hu(x)||wt)return{sessionId:Ge,session:V};Zt(!0);try{let L=await Gn(x);return{sessionId:L.sid,session:L.result.data.session??null}}finally{Zt(!1)}},[Gn,wt,Ge,V]),kn=(0,C.useCallback)(async x=>{let L=te.current;if(!L)return;let A=gt.current,le=await L(x);gt.current===A&&(at(le),le.data.session&&xe(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 x=!1,L,A=++Et.current;Kn(),ze(null),Rn(0);let le=()=>{x=!0,Et.current===A&&(Et.current+=1,Kn())},Me=Pr.current;if(An&&Me)return wn(En),Ne(!1),Fr.current===An?le:(xe(rl(Me,N)),(async()=>{let Be=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),W=En==="auto"&&!sn.current&&!Be;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=Wi(m.result);let D=cs(m.result),z=Ui(m.sid||g?.id);if(!x&&W&&g&&!D&&!z){sn.current=!0,await uu(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&&W&&((D||z)&&(sn.current=!0),Tt(null),Bt(null))}catch(m){if(x)return;let g=xa(m);if(W&&g==="session_auto_completed"){sn.current=!0,Tt("success"),await fa(600),x||(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");ze(D)}finally{L?.(),L=void 0}})(),()=>{le(),L?.()});Ne(!0);async function pt(){let Be=!1,W=null;try{let m=new $r.PaymentAPI(Q,{telemetry:!1}),g=await m.getUnifiedCheckoutSession(it,t);if(W=g,x)return;at(g);let D=g.data.session??null;if(xe(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"){Ne(!1),st(()=>{Ze.current?.(Lr(D,it)),nt.current?.(D.successUrl??"")});return}if(D.status==="complete"){Ne(!1),st(()=>{nt.current?.(D.successUrl??"")});return}if(D.status==="expired")throw Aa(D);Be=!0;let ce=N??z??"full";wn(ce),gt.current+=1;let J=D.clientSecret||t;te.current=D.buyerIdentified===!1&&J?vo(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=cs(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}),x)return;await E,x||Ne(!1);return}catch{if(x)return;await E,x||Ne(!1);return}}await pe(g),x||Ne(!1)}catch(m){if(x)return;let g=tl(m,Be);if(Be&&ee({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),g){let{errorCode:z,stage:ce,...J}=g;ls(Q,o,F,z,ce,J)}if(g?.stage==="provider_load"&&(N??W?.data.session?.checkoutMode??"full")==="full"&&el(W,h,O)){let z=mu({billingApiUrl:Q,locale:l,telemetry:o});ut.current=z,Kt(z,null),Rn(1),Ne(!1);return}let D=m instanceof Xe.FloPayError&&g?.stage!=="provider_load"?m:Qs();D!==m&&st(()=>se.current?.(D)),ze(D),Ne(!1)}}async function pe(Be){let{flopay:W,paypalFlopay:m,...g}=await ds(Be,{billingApiUrl:Q,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 x=Et.current;Rn(2);try{let{flopay:L,paypalFlopay:A}=await ds(ct,{billingApiUrl:Q,locale:l,telemetry:o});if(Et.current!==x)return;Kn(),Kt(L,A),Rn(0)}catch(L){if(Et.current!==x)return;let{errorCode:A,stage:le,...Me}=Ei(L);ls(Q,o,F,A,le,Me)}},[Kn,Kt,l,Fn,Q,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=uc(ct,We),Vr=cs(ct),ar=(0,C.useMemo)(()=>{if(!(!ct||!V||!ct.data.stripe?.publishableKey))return{billingApiUrl:Q}},[ct,V,Q]),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&&(!Ae||!ar),In=St?(0,M.jsx)(er,{status:St,errorMessage:vn,authorized:Vn}):null;if(Nt&&!bn){if(d)return(0,M.jsxs)(M.Fragment,{children:[d,In]});if(X==="buttons"){let x=ot?.buttonsLayout?.cardButton?.borderRadius??ot?.appearance.variables?.borderRadius??8,L=A=>(0,M.jsx)("div",{style:{height:A,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:[h&&L(Do),O&&(Y||U)&&L(Do),O&&L(Do),(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 Ft?u?(0,M.jsx)(pr.Provider,{value:sr,children:u(Ft)}):(0,M.jsx)(pr.Provider,{value:sr,children:(0,M.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ft.message})}):Or?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(pr.Provider,{value:sr,children:(0,M.jsx)(Pu,{onButtonClick:ft,showPayPal:h,showStripe:O,showApplePay:Y,showGooglePay:U,theme:he,buttonsTheme:Fe,buttonsStyles:oe,cardButtonContent:je,cardBackButtonContent:yt,cardTitleContent:re})}),In]}):Vr&&V&&zn?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(pr.Provider,{value:sr,children:(0,M.jsxs)("div",{className:rt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[rn&&(0,M.jsx)(Ro,{icon:!1,children:rn}),Ln==="retrying"&&(0,M.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ln==="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:Gt,children:"Retry PayPal"})]}),Ln!=="exhausted"&&(0,M.jsx)("div",{"aria-hidden":Ln==="retrying"?!0:void 0,style:Ln==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,M.jsx)(Pl,{sessionId:it,nonce:V.clientSecret||void 0,billingApiUrl:Q,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:B,onButtonClick:ft,runBeforeButtonClick:Cr,onInitializationStateChange:jr,allowAutomaticRetry:hr===0,session:V,telemetry:o,telemetryContext:F,onInstrument:vt,debug:de},`${Ke}:paypal-init-${hr}`)})]})}),In]}):Mt==="confirm"?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(pr.Provider,{value:sr,children:(0,M.jsx)(aa,{flopay:Ae,paypalFlopay:q,options:ar??{billingApiUrl:Q},onInstrument:vt,children:(0,M.jsxs)("div",{className:rt,children:[rn&&(0,M.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:rn}),ue?ue({onConfirm:Dr,isProcessing:tn}):(0,M.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"})]})},Ke)}),In]}):(!Ae||!ar)&&!(bn&&Mt==="full")?(0,M.jsx)(M.Fragment,{children:In}):(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(pr.Provider,{value:sr,children:(0,M.jsxs)(aa,{flopay:Ae,paypalFlopay:q,options:ar??{billingApiUrl:Q},onInstrument:vt,children:[Fn===1&&(0,M.jsx)("button",{type:"button",onClick:dt,children:"Retry payment methods"}),ye?(0,M.jsxs)(M.Fragment,{children:[rn&&(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:rn}),(0,M.jsx)(bu,{sessionId:it,nonce:V?.clientSecret||void 0,billingApiUrl:Q,session:V,submitLabel:Ve,walletPresentation:G,children:ye})]}):(0,M.jsx)(oi,{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:B,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:Fe,buttonsStyles:oe,appearance:lt,cardButtonContent:je,cardBackButtonContent:yt,cardTitleContent:re,onButtonClick:ft,onBeforeButtonClick:ke,onBuyerIdentityReady:kn,enableAVS:Oe,...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:!!Oe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ps(ye,X),className:rt,submitLabel:Ve,directPaypal:zn,isSubscription:V?.mode==="subscription",session:V,dataAttachmentPending:yn,dataAttachmentRequiresIdentity:Qt,debug:de})]},Ke)}),In]})}function bu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:a,children:l}){return(0,M.jsx)(M.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 Pu({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,B]=(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,M.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:Do,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(v){let T=w.cardInputBorder??"#e5e7eb",Y=w.cardInputBackground??"white",U=ho(p),de=ho(b);return(0,M.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,M.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,M.jsxs)("button",{type:"button",onClick:()=>B(!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,M.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...w.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)(Po,{content:p})]}),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,...w.title},children:(0,M.jsx)(Yo,{content:b})})]}),(0,M.jsx)("div",{style:{backgroundColor:Y,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:Y,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:Y,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:Y,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",...w.submitButton,opacity:.5}}),(0,M.jsx)("style",{children:`
38
+ `}),oa&&$n&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ge?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:Vr,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:M.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...M.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...M.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Fo,{content:Re})]}),il?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:M.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...M.title},children:(0,d.jsx)(ca,{content:xe})})]}),!oa&&!il&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:zi,order:ge?-3:0,...M.title},children:(0,d.jsx)(ca,{content:xe})}),ge&&ye&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:ye}),ge&&In&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:Eo,border:`1px solid ${nr(Na)}`,borderRadius:Xt,padding:"10px"},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Ht,onChange:l=>{Bt("email"),hn.current=l.target.value,ln(l.target.value)},onPointerDown:()=>Bt("email"),onKeyDown:()=>Bt("email"),onBlur:()=>{dr("email")&&Fn(!0),Co||Ei()},disabled:K,required:!0,"aria-invalid":Na||void 0,"aria-describedby":Na?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ui}})}),Na&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ia,children:_r.empty?"Email address is required":"Enter a valid email address"})]}),ue&&(0,d.jsx)("div",{style:{order:ge?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let l=Dt,R=(pe=!1)=>({backgroundColor:Eo,border:`1px solid ${nr(pe)}`,borderRadius:Xt,marginTop:"0.5rem",padding:"10px"}),te=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ui}),ze=(0,y.getStateOptions)(l);return(0,d.jsxs)(d.Fragment,{children:[(0,y.isAVSFieldVisible)(ue.address_line_1,l)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:R(Vt("line1")),children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:on,onChange:pe=>{Bt("line1"),vt.current.addressLine1=!0,gn.current=pe.target.value,Ee(pe.target.value)},onPointerDown:()=>Bt("line1"),onKeyDown:()=>Bt("line1"),onBlur:()=>_n("line1"),disabled:K,required:!0,"aria-invalid":Vt("line1")||void 0,"aria-describedby":Vt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:te()})}),Vt("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ia,children:"Street address is required"})]}),(0,y.isAVSFieldVisible)(ue.address_line_2,l)&&(0,d.jsx)("div",{style:R(),children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Rt,onChange:pe=>{vt.current.addressLine2=!0,Nt.current=pe.target.value,Mt(pe.target.value)},disabled:K,"data-testid":"flopay-address-line2",style:te()})}),((0,y.isAVSFieldVisible)(ue.city,l)||(0,y.isAVSFieldVisible)(ue.state,l))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(ue.city,l)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Eo,borderTop:`1px solid ${nr(Vt("city"))}`,borderRight:`1px solid ${nr(Vt("city"))}`,borderBottom:`1px solid ${nr(Vt("city"))}`,borderLeft:`1px solid ${nr(Vt("city"))}`,padding:"10px",borderTopLeftRadius:Xt,borderBottomLeftRadius:Xt,...(0,y.isAVSFieldVisible)(ue.state,l)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Xt}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:wn,onChange:pe=>{Bt("city"),vt.current.city=!0,en.current=pe.target.value,Ot(pe.target.value)},onPointerDown:()=>Bt("city"),onKeyDown:()=>Bt("city"),onBlur:()=>_n("city"),disabled:K,required:!0,"aria-invalid":Vt("city")||void 0,"aria-describedby":Vt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:te()})}),(0,y.isAVSFieldVisible)(ue.state,l)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Eo,borderTop:`1px solid ${nr(Vt("state"))}`,borderRight:`1px solid ${nr(Vt("state"))}`,borderBottom:`1px solid ${nr(Vt("state"))}`,borderLeft:`1px solid ${nr(Vt("state"))}`,padding:"10px",borderTopRightRadius:Xt,borderBottomRightRadius:Xt,...(0,y.isAVSFieldVisible)(ue.city,l)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${nr(Vt("state")||Vt("city"))}`}:{borderRadius:Xt}},children:ze?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Yn,onChange:pe=>{Bt("state"),vt.current.state=!0,Kt.current=pe.target.value,yn(pe.target.value)},onPointerDown:()=>Bt("state"),onKeyDown:()=>Bt("state"),onBlur:()=>_n("state"),disabled:K,autoComplete:"billing address-level1",required:!0,"aria-invalid":Vt("state")||void 0,"aria-describedby":Vt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...te(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,y.getStateLabel)(l)}),ze.map(pe=>(0,d.jsx)("option",{value:pe.code,children:pe.name},pe.code))]}):(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,y.getStateLabel)(l),autoComplete:"billing address-level1",value:Yn,onChange:pe=>{Bt("state"),vt.current.state=!0,Kt.current=pe.target.value,yn(pe.target.value)},onPointerDown:()=>Bt("state"),onKeyDown:()=>Bt("state"),onBlur:()=>_n("state"),disabled:K,required:!0,"aria-invalid":Vt("state")||void 0,"aria-describedby":Vt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:te()})})]}),Vt("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ia,children:"City is required"}),Vt("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ia,children:[(0,y.getStateLabel)(l)," is required"]}),((0,y.isAVSFieldVisible)(ue.country,l)||(0,y.isAVSFieldVisible)(ue.postal_code,l))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:le==="column"?"column":"row",gap:le==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(ue.country,l)&&(0,d.jsx)("div",{style:{flex:le==="row"?1:void 0,backgroundColor:Eo,borderTop:`1px solid ${aa}`,borderRight:`1px solid ${aa}`,borderBottom:`1px solid ${aa}`,borderLeft:`1px solid ${aa}`,padding:"10px",...le==="row"&&(0,y.isAVSFieldVisible)(ue.postal_code,l)?{borderRadius:"0",borderTopLeftRadius:Xt,borderBottomLeftRadius:Xt,borderRight:"none"}:{borderRadius:Xt}},children:(0,d.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Dt,onChange:pe=>{vt.current.country=!0,Qt.current=pe.target.value,Rn(pe.target.value),dt?.(pe.target.value),Kt.current="",yn("")},disabled:K,autoComplete:"billing country","data-testid":"flopay-country",style:{...te(),cursor:"pointer"},children:[Dt===""?(0,d.jsx)("option",{value:"",children:"Select country"}):null,y.COUNTRY_OPTIONS.map(pe=>(0,d.jsxs)("option",{value:pe.code,children:[pe.flag," ",pe.name]},pe.code))]})}),(0,y.isAVSFieldVisible)(ue.postal_code,l)&&(0,d.jsx)("div",{style:{flex:le==="row"?1:void 0,backgroundColor:Eo,border:`1px solid ${id}`,padding:"10px",...le==="row"&&(0,y.isAVSFieldVisible)(ue.country,l)?{borderRadius:"0",borderTopRightRadius:Xt,borderBottomRightRadius:Xt}:{borderRadius:Xt}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,y.getPostalCodeLabel)(Dt),autoComplete:"billing postal-code",value:Un,onChange:pe=>{Bt("zip"),vt.current.zip=!0,_t.current=pe.target.value,qn(pe.target.value),Me?.(pe.target.value)},onPointerDown:()=>Bt("zip"),onKeyDown:()=>Bt("zip"),onBlur:()=>{dr("zip")&&Mn(!0)},disabled:K,required:bn.required,"aria-invalid":za||void 0,"aria-describedby":za?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:te()})})]}),za&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ia,children:bn.empty?`${(0,y.getPostalCodeLabel)(l)} is required`:Du(l)})]})})()}),ge&&ud,et&&(0,d.jsx)(Uo,{margin:"0.75rem 0",styleOverride:M.errorBanner,children:et})]}),Ua={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},ul=l=>Z?!_||!Tr?(0,d.jsx)("pre",{"data-testid":l,style:Ua,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":l,style:Ua,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${_}`,` directPaypalConfigured=${Tr}`,` inAppBrowserDetected=${String(Da)}`,` shouldRenderDirectPayPal=${Qo}`,` shouldRenderStripePayPal=${ta}`,` hasPaypalStripeInstance=${!!Fs}`].join(`
39
+ `)}):null,pl=l=>Z?!q||!Wn?(0,d.jsx)("pre",{"data-testid":l,style:Ua,children:"FloPay/Stripe-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":l,style:Ua,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${q}`,` currency=${mt}`,` amountInCents=${Xo}`,` enabledPaymentMethods: ${JSON.stringify(ne??[])}`,` enabledPaymentMethodsProvided=${Jo}`,` hasEnabledMethods=${xa}`,` expressMethods: ${JSON.stringify(Fa)}`,` walletExpressMethods: ${JSON.stringify(Ro)}`,` paymentElementMethods: ${JSON.stringify(Zo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ba)}`,` hasStripeInstance=${!!Wn}`,` shouldRenderWallets=${_o}`,` shouldRenderPaymentElement=${na}`].join(`
40
+ `)}):null,ml=ht==="apm-expanding"||ht==="apm-form"||ht==="apm-collapsing",Ao;ht==="apm-expanding"?Ao=rc:ht==="apm-collapsing"&&(Ao=oc);let qa=nn?bc(xi,nn):null;if(V==="buttons"){let l=ht==="buttons"||ht==="expanding"||ht==="apm-expanding",R=ht==="expanding"||ht==="card"||ht==="collapsing",te=it===void 0?{boxSizing:"border-box",height:Ia,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ze;ht==="expanding"||ht==="apm-expanding"?ze=Au:(ht==="collapsing"||ht==="apm-collapsing")&&(ze=Tu);let pe;return ht==="expanding"?pe=rc:ht==="collapsing"&&(pe=oc),(0,d.jsxs)("form",{onSubmit:Di,className:k,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(fs,{}),z&&(0,d.jsx)(Ln,{status:z,errorMessage:et,authorized:jn}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!l&&!ze?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!l&&!ze?Mu:{},...ze?{animation:ze,pointerEvents:"none"}:{}},children:[ul("flopay-direct-paypal-gate-debug"),pl("flopay-stripe-gate-debug"),Qo&&Ie&&(0,d.jsxs)(d.Fragment,{children:[m&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(ma.Provider,{value:g,children:(0,d.jsx)(fa,{sessionId:e,nonce:t,billingApiUrl:Ke,email:x.email,billingName:Ye||void 0,onBuyerIdentityReady:oe,clientId:Ie.clientId,environment:Ie.environment,currency:mt.toUpperCase(),isSubscription:ft,providerObjectType:Qe,approvalPresentation:Oa==="popup"?void 0:Oa,onTokenizedBody:Bn,onComplete:s,onErrorChange:Fe,onDecline:u,onTechnicalFailure:ko,onButtonClick:se,runBeforeButtonClick:fr,isProcessing:K,onLoadStateChange:Mi,onInitializationStateChange:Fi,session:kt,existingOrderId:m?.orderId,debug:Z},m?.orderId??"fresh")})]}),ta&&(0,d.jsx)(Zt.Elements,{stripe:ea,options:Os,children:(0,d.jsx)(lc,{sessionId:e,nonce:t,email:x.email,billingName:Ye||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,onTokenizedBody:Bn,onErrorChange:Fe,isProcessing:K,onButtonClick:se,onDecline:u,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:js,placeholderBorderRadius:co,popupCapabilityOwner:g,externalTelemetryContext:Zs,presentationMode:Io})}),_o?(0,d.jsx)(Zt.Elements,{stripe:Wn,options:Ds,children:(0,d.jsx)(cc,{sessionId:e,nonce:t,email:x.email,billingName:Ye||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,intentKind:J>0?"payment":"setup",expressMethods:Ro,onTokenizedBody:Bn,onErrorChange:Fe,onButtonClick:se,onDecline:u,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:Ws,placeholderBorderRadius:co,popupCapabilityOwner:g,externalTelemetryContext:Xe})}):null,!_o&&Xs?(0,d.jsx)("div",{style:{height:Ia,borderRadius:co,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,na&&(0,d.jsx)(dc,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,paymentElementMethods:Ba,stripeInstance:Wn,paymentElementBaseOptions:xi,onTokenizedBody:Bn,onErrorChange:Fe,onButtonClick:se,onDecline:u,runBeforeButtonClick:fr,onLoadStateChange:Ks,isProcessing:K,submitButtonColor:uo,submitButtonBorderRadius:Xt,submitButtonStyle:M.submitButton,onExpandApm:En,expandedApmMethod:nn,themeId:Be,buttonAppearance:{backgroundColor:M.cardButton?.backgroundColor,borderColor:M.cardInputBorder,textColor:M.cardButton?.color,borderRadius:co}}),ge&&(0,d.jsx)("button",{type:"button",onClick:async()=>{K||!(await fr("card")).proceed||(se?.("card"),mr())},disabled:K,style:{width:"100%",...te,...M.cardButton,...ws({themeBundle:Tt,resolvedPrimaryColor:uo,resolvedBorderRadius:Xt,submitButtonStyle:M.submitButton,explicitPrimaryColor:Dn?.colorPrimary}),fontSize:M.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:K?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:K?.6:1},onMouseEnter:Te=>{!K&&(Tt||Dn?.colorPrimary)&&(Te.currentTarget.style.backgroundColor=cd)},onMouseLeave:Te=>{(Tt||Dn?.colorPrimary)&&(Te.currentTarget.style.backgroundColor=uo)},onMouseDown:Te=>{Te.currentTarget.style.transform="scale(0.985)"},onMouseUp:Te=>{Te.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(Mo,{content:it})}),et&&ht==="buttons"&&(0,d.jsx)(Uo,{margin:"0.25rem 0",styleOverride:M.errorBanner,children:et})]}),ge&&R&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...pe?{animation:pe}:{},...ht==="collapsing"?{pointerEvents:"none"}:{}},children:dl}),q&&ml&&nn&&qa&&Wn&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Ao?{animation:Ao}:{},...ht==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Li,borderRadius:Vi,...sa,padding:qi},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:D,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:M.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...M.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...M.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Fo,{content:Re})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:M.titleFontSize??"1.05rem",color:zi,paddingRight:80,...M.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(nn)}`})]}),(0,d.jsx)(Zt.Elements,{stripe:Wn,options:qa,children:(0,d.jsx)(Ps,{method:nn,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,onTokenizedBody:Bn,onErrorChange:Fe,onDecline:u,onCancel:D,runBeforeButtonClick:fr,onButtonClick:se,isProcessing:K,submitButtonColor:uo,submitButtonBorderRadius:Xt,submitButtonStyle:M.submitButton,errorText:et})},nn)]})})]})]})}return ml&&nn&&qa&&Wn&&q?(0,d.jsxs)("form",{onSubmit:Di,className:k,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(fs,{}),z&&(0,d.jsx)(Ln,{status:z,errorMessage:et,authorized:jn}),(0,d.jsx)("div",{style:{...Ao?{animation:Ao}:{},...ht==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Li,borderRadius:Vi,...sa,padding:qi},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:D,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:M.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...M.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...M.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Fo,{content:Re})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:M.titleFontSize??"1.05rem",color:zi,paddingRight:80,...M.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(nn)}`})]}),(0,d.jsx)(Zt.Elements,{stripe:Wn,options:qa,children:(0,d.jsx)(Ps,{method:nn,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,onTokenizedBody:Bn,onErrorChange:Fe,onDecline:u,onCancel:D,runBeforeButtonClick:fr,onButtonClick:se,isProcessing:K,submitButtonColor:uo,submitButtonBorderRadius:Xt,submitButtonStyle:M.submitButton,errorText:et})},nn)]})})]}):(0,d.jsxs)("form",{onSubmit:Di,className:k,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(fs,{}),z&&(0,d.jsx)(Ln,{status:z,errorMessage:et,authorized:jn}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ul("flopay-direct-paypal-gate-debug-default"),pl("flopay-stripe-gate-debug-default"),Qo&&Ie&&(0,d.jsxs)(d.Fragment,{children:[m&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(ma.Provider,{value:g,children:(0,d.jsx)(fa,{sessionId:e,nonce:t,billingApiUrl:Ke,email:x.email,billingName:Ye||void 0,onBuyerIdentityReady:oe,clientId:Ie.clientId,environment:Ie.environment,currency:mt.toUpperCase(),isSubscription:ft,providerObjectType:Qe,approvalPresentation:Oa==="popup"?void 0:Oa,onTokenizedBody:Bn,onComplete:s,onErrorChange:Fe,onDecline:u,onTechnicalFailure:ko,onButtonClick:se,runBeforeButtonClick:fr,isProcessing:K,onLoadStateChange:Mi,onInitializationStateChange:Fi,session:kt,existingOrderId:m?.orderId,debug:Z},m?.orderId??"fresh")})]}),ta&&(0,d.jsx)(Zt.Elements,{stripe:ea,options:Os,children:(0,d.jsx)(lc,{sessionId:e,nonce:t,email:x.email,billingName:Ye||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,onTokenizedBody:Bn,onErrorChange:Fe,isProcessing:K,onButtonClick:se,onDecline:u,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:js,placeholderBorderRadius:co,popupCapabilityOwner:g,externalTelemetryContext:Zs,presentationMode:Io})}),_o&&(0,d.jsx)(Zt.Elements,{stripe:Wn,options:Ds,children:(0,d.jsx)(cc,{sessionId:e,nonce:t,email:x.email,billingName:Ye||void 0,onBuyerIdentityReady:oe,billingApiUrl:Ke,intentKind:J>0?"payment":"setup",expressMethods:Ro,onTokenizedBody:Bn,onErrorChange:Fe,onButtonClick:se,onDecline:u,onTechnicalFailure:ko,runBeforeButtonClick:fr,onLoadStateChange:Ws,placeholderBorderRadius:co,popupCapabilityOwner:g,externalTelemetryContext:Xe})}),na&&(0,d.jsx)(dc,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Ke,paymentElementMethods:Ba,stripeInstance:Wn,paymentElementBaseOptions:xi,onTokenizedBody:Bn,onErrorChange:Fe,onButtonClick:se,onDecline:u,runBeforeButtonClick:fr,onLoadStateChange:Ks,isProcessing:K,submitButtonColor:uo,submitButtonBorderRadius:Xt,submitButtonStyle:M.submitButton,themeId:Be,onExpandApm:En,expandedApmMethod:nn,buttonAppearance:{backgroundColor:M.cardButton?.backgroundColor,borderColor:M.cardInputBorder,textColor:M.cardButton?.color,borderRadius:co}})]}),ge&&(nd||td||rd)&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,d.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,d.jsx)("span",{children:"or pay with card"}),(0,d.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),ge&&dl]})}var O=require("react/jsx-runtime"),Yo=44,Ts="flopay_checkout_saved_payment_resume",bi=new Map,hi=new Map;function vc(e,t){t.settled&&t.consumers===0&&bi.get(e)===t&&bi.delete(e)}function qu(e,t,n){let r=hi.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};hi.set(e,a);let s=()=>{hi.get(e)===a&&hi.delete(e)};return o.then(s,s),o}function _a(e){return new Promise(t=>setTimeout(t,e))}function Pi(e,t,n){let r=Xa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:tt.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Ea(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ks(e,t,n,r,o,a){let s=Pi(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),Ea(s)}function Cc(e,t,n,r){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function Sc(e,t,n,r,o){let a=(0,tt.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:n,attempt:o,statusClass:a.statusClass}),t instanceof tt.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof tt.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):a.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...a,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function Rc(e,t){let n=e?.data.paypal?.publishableKey;if(n)return{clientId:n,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation,...t?{existingOrderId:t}:{}}}function Is(e){return!e||e.data.stripe?.publishableKey?!1:!!Rc(e)?.clientId}var Vu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function ju(e){return new Yr.FloPay(Vu,{publishableKey:"provider_unavailable",...e})}async function Rs(e,t){let{publishableKey:n,paypalPublishableKey:r}=ss(e);return{...await ls({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function As(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function $u(){if(!As())return null;try{let e=window.sessionStorage.getItem(Ts);return e?JSON.parse(e):null}catch{return null}}function wc(e){if(As())try{window.sessionStorage.setItem(Ts,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function _s(){if(As())try{window.sessionStorage.removeItem(Ts)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Wu(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function kc(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function Es(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Hu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Ic(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Ku(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function vi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:s,loading:c,error:u,onComplete:p,onError:h,onInstrument:b,onDecline:I,onCountryChange:k,onZipChange:C,showPayPal:f=!0,showStripe:S=!0,walletPresentation:G="auto",enabledPaymentMethods:_,showApplePay:q=!0,showGooglePay:E=!0,debug:ne=!1,layout:$,theme:W,buttonsTheme:ie,buttonsStyles:V,cardButtonContent:Be,cardBackButtonContent:Ue,cardTitleContent:X,showSecurityFooter:Ae,onButtonClick:it,onBeforeButtonClick:Re,enableAVS:xe,cardFieldOrder:ve,cardPreFormSlot:se,avsLayout:me,submitLabel:He,className:st,initialErrorMessage:T=null,initialPayPalOrderId:ye,children:le,checkoutMode:F,confirmLabel:Se,renderConfirmButton:ce,onSessionCompleted:De}){let re=(0,tt.resolveBillingApiUrl)(r),$e=(0,w.useMemo)(()=>(0,tt.resolveTheme)(W),[W]),dt=a??$e?.appearance,Me=n?"embedded_checkout":"standard_checkout",Oe=Es(le,$),[ut,Y]=(0,w.useState)(null),[J,mt]=(0,w.useState)(null),gt=(0,w.useRef)(null),Ie=(0,w.useRef)(null),ft=(0,w.useRef)(0),[U,we]=(0,w.useState)(null),lt=(0,w.useRef)(null),[Z,qe]=(0,w.useState)(null),St=(0,w.useMemo)(()=>n?Vo(n):"",[n]),Ze=n?`create:${St}`:`session:${e??""}`,H=Ic(Z),nt=(0,w.useRef)(new Set),g=(0,w.useRef)(Ze),v=(0,w.useRef)(Ze);go(()=>{v.current=Ze,g.current!==Ze&&(g.current=Ze,nt.current.clear())},[Ze]);let ee=(0,w.useCallback)(D=>{if(v.current===Ze){if(Ji.has(D.name)){if(nt.current.has(D.name))return;nt.current.add(D.name)}We(()=>b?.(D))}},[Ze,b]),de=zo(ee,Ze),Xe=(0,w.useRef)(!1),kt=(0,w.useCallback)(D=>{if(Xe.current)return;let z=D.gateway||!H?D:{...D,gateway:H};ee(z)},[ee,H]);(0,w.useEffect)(()=>{de({class:"lifecycle",name:"checkout.mount"})},[de]);let[Qe,ae]=(0,w.useState)(e??""),yt=e??Qe,It=n?"":yt,[qt,Ke]=(0,w.useState)(!0),[Lt,Ge]=(0,w.useState)(null),[zn,Tn]=(0,w.useState)(0),[Dt,Rn]=(0,w.useState)("full"),[Un,qn]=(0,w.useState)(!1),[on,Ee]=(0,w.useState)(T),[Rt,Mt]=(0,w.useState)(null),[wn,Ot]=(0,w.useState)(null),[Yn,yn]=(0,w.useState)(!1),[Ht,ln]=(0,w.useState)(void 0),[Xn,fn]=(0,w.useState)(""),[_t,Qt]=(0,w.useState)(!1),[gn,Nt]=(0,w.useState)(!1),[en,Kt]=(0,w.useState)(!1),hn=(0,w.useRef)(null),vt=(0,w.useRef)(0),ue=(0,w.useRef)(void 0),[Vn,jn]=(0,w.useState)("loading"),[Sr,kn]=(0,w.useState)(0),cn=(0,w.useRef)(!1),An=(0,w.useRef)(!1),Le=(0,w.useRef)(!1),Ct=(0,w.useRef)(null),ge=(0,w.useRef)(null),L=(0,w.useMemo)(()=>({checkoutMode:F??Dt,layout:Hu(le,$)}),[F,le,Dt,$]),rt=(0,w.useRef)(p);rt.current=p;let he=(0,w.useRef)(h);he.current=h;let Jn=(0,w.useRef)(I);Jn.current=I;let Pn=(0,w.useCallback)(D=>ai(Ct,async z=>{try{return await D(z)}catch(B){throw z.aborted?io(B):B}}),[]);(0,w.useEffect)(()=>()=>{Ct.current?.abort(),Ct.current=null},[]);let Gt=(0,w.useCallback)((D,z)=>{gt.current=D,mt(D),lt.current=z,we(z)},[]),Zn=(0,w.useCallback)(()=>{let D=Ie.current;D&&(Ie.current=null,D.destroy())},[]);(0,w.useEffect)(()=>{pn(J)?.setCheckoutContext(L),U&&U!==J&&pn(U)?.setCheckoutContext(L)},[J,U,L]);let pt=(0,w.useRef)(De);pt.current=De;let Xr=(0,w.useCallback)(D=>{jn(D),!(D!=="exhausted"||Le.current)&&(Le.current=!0,he.current?.(new tt.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Yt=(0,w.useCallback)(()=>{jn("retrying"),kn(D=>D+1)},[]);(0,w.useEffect)(()=>{jn("loading"),kn(0),Le.current=!1},[yt]),(0,w.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:tt.SDK_VERSION,checkout_type:Me,checkout_layout:Oe,billing_api_url:re})},[Oe,Me,re]);let bn=(0,w.useMemo)(()=>n?Vo(n,!0):"",[n]),Nr=(0,w.useMemo)(()=>Xn===bn?Ht:void 0,[Ht,Xn,bn]),zr=(0,w.useMemo)(()=>n?Hi(n,Nr):void 0,[n,Nr]),xn=F??zr?.checkoutMode??"full",tn=(0,w.useMemo)(()=>zr?{...zr,checkoutMode:xn}:void 0,[zr,xn]);(0,w.useEffect)(()=>{ln(void 0),fn(bn),ue.current=void 0,hn.current=null,Kt(!1)},[bn]),(0,w.useEffect)(()=>{Ee(T)},[T]);let wr=(0,w.useCallback)((D,z,B)=>{We(()=>{Jn.current?.(un(D,z,B))})},[]),Mn=(0,w.useCallback)(async(D,z)=>{Ee(null),Ot(null),yn(!1),Mt("processing");let B=z?.sessionId??D.id,Pe=D.clientSecret||t,Ve=Ic(D),Pt=gt.current??lt.current,Ce=pn(Pt),je=Pt?null:Pi(re,o,L),Q={log:M=>{Ce?Ce.log(M):je?.log(M)},error:M=>{Ce?Ce.error(M):je?.error(M)},terminal:M=>{Ce?Ce.terminal(M):je?.terminal(M)},performance:M=>{Ce?Ce.performance(M):je?.performance(M)},now:()=>Ce?.now()??je?.now()??0,elapsed:M=>Ce?.elapsed(M)??Math.max(0,(je?.now()??M)-M)},m=Q.now(),P=!!(z?.initialAutoProcessingError||z?.initialAutoProcessingPending),N=!1,j,be=()=>{N||(N=!0,P=!0,j=Q.now(),Q.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},oe=!1,et=()=>{oe||(oe=!0,Q.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),Q.performance({stage:"processing",durationMs:Q.elapsed(m),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),j!==void 0&&Q.performance({stage:"recovery",durationMs:Q.elapsed(j),durationMode:"machine",paymentMethodCategory:"saved"}))};Q.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Xe.current=!0;try{Q.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Xe.current=!1}de({class:"lifecycle",name:"payment.processing.started",provider:Ve}),P&&be();let Tt;try{let M=ql(z?.initialAutoProcessingError),_e=z?.initialAutoProcessingError?.type==="3ds_required"&&!z.initialAutoProcessingError.threeDSecureToken&&z.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:z.initialAutoProcessingError.nextActionRedirectUrl}:null,Ft,ke=K=>(be(),Pn(fe=>$o(K,{billingApiUrl:re,sessionId:B,nonce:Pe,session:D,signal:fe})));if(_e)Ft=await ke(_e);else if(M)be(),M.type==="paypal_redirect_required"&&ge.current?.publishableKey&&wc({sessionId:B,publishableKey:ge.current.publishableKey,paypalPublishableKey:ge.current.paypalPublishableKey}),Ft=await Pn(K=>si(M,{flopay:gt.current,paypalFlopay:lt.current,attempt3DS:z?.attempt3DS,billingApiUrl:re,sessionId:B,session:D,telemetry:!1,signal:K})),M.type==="paypal_redirect_required"&&_s();else if(z?.initialAutoProcessingPending){let K=z.initialAutoProcessingPending,fe=new Yr.PaymentAPI(re,{telemetry:!1}),x=await Pn(Ne=>fe.waitForCheckoutSessionCompletion(K.sessionId,{initialDelayMs:K.retryAfterMs,nonce:Pe,statusUrl:K.statusUrl,signal:Ne})),Ye=to(x,D),At=x.autoProcessingError?.type==="3ds_required"&&x.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:x.autoProcessingError.nextActionRedirectUrl}:null;if(At)Ft=await ke(At);else{if(!$r(Ye))throw Do(Ye);Ft=jr(Ye,B)}}else{if(z?.initialAutoProcessingError)throw Fr(z.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:z.initialAutoProcessingError.checkoutMethod});if(z?.fromCreateSession)return z?.fallbackToFull&&(Rn("full"),kc("full")),!1;{let K=await Wo({billingApiUrl:re,sessionId:B,session:D,nonce:Pe,telemetry:!1});K.type==="success"?Ft=K.result:K.type==="next_action_required"?Ft=await ke(K):(be(),K.type==="paypal_redirect_required"&&ge.current?.publishableKey&&wc({sessionId:B,publishableKey:ge.current.publishableKey,paypalPublishableKey:ge.current.paypalPublishableKey}),Ft=await Pn(fe=>si(K,{flopay:gt.current,paypalFlopay:lt.current,attempt3DS:z?.attempt3DS,billingApiUrl:re,sessionId:B,session:D,telemetry:!1,signal:fe})),K.type==="paypal_redirect_required"&&_s())}}B&&jo(B),et(),P&&(Q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),Q.terminal({outcome:Ft.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),yn(Ft.status==="authorized"),Mt("success"),await _a(600),Tt=()=>rt.current?.(Ft)}catch(M){let _e=Qr(va(M),B);if(_e.code==="three_ds_aborted")return!1;let Ft=_e.checkoutMethod??ba;Ee(_e.message),Ot(_e.message),yn(!1),z?.fallbackToFull&&(Q.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Rn("full"),kc("full")),et();let ke=_e.statusCode===void 0?void 0:(0,tt.telemetryStatusClass)(_e.statusCode,"unknown"),K=ke==="4xx"?{requestCategory:"process_payment",statusClass:ke}:{},fe=ke===void 0||ke==="4xx";if(fe&&(_e.telemetryOutcome==="payment_declined"||!!(_e.declineCode||_e.code?.toLowerCase().includes("declin"))))Q.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...K});else if(fe&&(_e.telemetryOutcome==="validation_rejected"||_e.type==="validation_error"))Q.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...K});else{let At=(0,tt.classifyTelemetryFailure)(M,P?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Ne=_e.telemetryRequestCategory??"process_payment";Xe.current=!0;try{Q.error({...At,..._e.telemetryFailureCategory?{failureCategory:_e.telemetryFailureCategory}:{},stage:P?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Ne})}finally{Xe.current=!1}de({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Ne,provider:Ve})}return We(()=>he.current?.(_e)),wr(Ft,_e,{code:_e.code,declineCode:_e.declineCode}),Mt("error"),await Promise.allSettled([_a(400),z?.ensureProvidersReady?z.ensureProvidersReady():Promise.resolve()]),P&&(Q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{et(),je&&Ea(je),Mt(null),Ot(null)}return We(Tt),!0},[wr,de,t,re,Pn,o,L]);(0,w.useEffect)(()=>{if(typeof window>"u"||An.current)return;let D=new URLSearchParams(window.location.search),z=D.get("payment_intent_client_secret");if(!z)return;let B=$u();B&&(An.current=!0,(async()=>{let Pe,Ve=0;Ee(null),Ot(null),Mt("processing"),qn(!0);try{if(D.get("redirect_status")==="failed")throw Object.assign(new tt.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Pt,paypalFlopay:Ce}=await ls({publishableKey:B.publishableKey,paypalPublishableKey:B.paypalPublishableKey,billingApiUrl:re,locale:s,telemetry:o});Pe=pn(Ce??Pt),Pe?.setCheckoutContext(L),Ve=Pe?.now()??0,Pe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let je=(Ce??Pt)?.getRawProvider();if(!je)throw Object.assign(new tt.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:Q,error:m}=await je.retrievePaymentIntent(z);if(m)throw Object.assign(new tt.FloPayError(m.message??"Failed to retrieve PayPal payment status.","api_error",{code:m.code}),{checkoutMethod:"paypal"});let P=Sl(Q?.status);if(!Q||P==="failed")throw Object.assign(new tt.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let N=typeof Q.payment_method=="string"?Q.payment_method:Q.payment_method?.id,j=P;if(B.sessionId){let et=(await new Yr.PaymentAPI(re,{telemetry:!1}).getUnifiedCheckoutSession(B.sessionId)).data.session;if(et&&et.status!=="complete"){let Tt=await Wo({billingApiUrl:re,sessionId:B.sessionId,session:et,telemetry:!1,tokenizedData:{id:N??Q.id,type:"card",threeDSecureActionResultTokenId:Q.id,isPaypal:!0}});if(Tt.type!=="success")throw Object.assign(new tt.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});j=Tt.result.status}}B.sessionId&&jo(B.sessionId),Pe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.performance({stage:"redirect_resume",durationMs:Pe.elapsed(Ve),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Mt("success"),await _a(600),We(()=>rt.current?.({status:j,paymentIntentId:Q.id,paymentMethodId:N,checkoutMethod:"paypal"}))}catch(Pt){let Ce=Qr(va(Pt),B.sessionId),je=Ce.checkoutMethod??"paypal",Q=!!(Ce.declineCode||Ce.code?.toLowerCase().includes("declin"));if(Pe)Pe.performance({stage:"redirect_resume",durationMs:Pe.elapsed(Ve),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Q?Pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Pe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(Q){let m=Pi(re,o,L);m.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ea(m)}else ks(re,o,L,"REDIRECT_RESUME_FAILED","redirect_resume");Ee(Ce.message),Ot(Ce.message),We(()=>he.current?.(Ce)),wr(je,Ce,{code:Ce.code,declineCode:Ce.declineCode}),Mt("error"),await _a(400)}finally{_s(),Wu(),Mt(null),Ot(null),qn(!1)}})())},[wr,s,re,o,L]);let Ur=(0,w.useRef)(null),Fn=(0,w.useMemo)(()=>tn?Vo(tn):"",[tn]),kr=(0,w.useRef)(tn);kr.current=tn,(0,w.useEffect)(()=>{ae(e??"")},[e]),(0,w.useEffect)(()=>{cn.current=!1,Ee(T),Ot(null),yn(!1),Mt(null)},[Fn,T,e]);async function Ir(D,z,B){let Pe=Pi(re,o,L),Ve=new Yr.PaymentAPI(re,{telemetry:!1}),Pt=!1;try{let Ce=D.idempotencyKey===void 0?void 0:(0,tt.resolveIdempotencyKey)(D.idempotencyKey),je=es(z,B),Q=ts(z,B);je?.canonicalIdentity===B&&Q&&Q.canonicalIdentity===void 0&&(ri(z,B,Q.idempotencyKey),Q={...Q,canonicalIdentity:B});let m=Ce??(Q?.canonicalIdentity===B?Q.idempotencyKey:void 0),P,N=!1;Pe.log({name:je?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let j=je?.sid??null,be=null,oe,et,Tt=!1;if(j)try{be=await Ve.getUnifiedCheckoutSession(j,je?.nonce),je&&je.canonicalIdentity===void 0&&(Ll(be.data.session,D)?(ni(z,B,j,je.nonce??be.data.session?.clientSecret),Q&&Q.canonicalIdentity===void 0&&(ri(z,B,Q.idempotencyKey),m??(m=Q.idempotencyKey))):(ti(z,B),Q=null,m=Ce,j=null,be=null));let _e=be?.data.session?.status,Ft=be?.data.session,ke=Ft?.clientSecret||je?.nonce;if(j&&Ft?.buyerIdentified===!1&&ke&&(et=Bo(Ve,j,ke,D.account)),j&&be&&_e==="complete"){if(ns(j))return{sid:j,result:be};ti(z,B),j=null,be=null,N=!0}}catch{Pe.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),je?.canonicalIdentity===void 0?(ti(z,B),m=Ce):ei(z,B),j=null}if(!j){!Ce&&(N||!m)&&(m=(0,tt.resolveIdempotencyKey)(),P=m),m&&ri(z,B,m);let _e=Pe.now(),Ft=0;Pe.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ke={...D,idempotencyKey:m,avsCheck:!!xe,avsConfig:typeof xe=="object"?xe:void 0,checkoutType:"embedded_checkout",checkoutLayout:Es(le,$)};Object.defineProperty(ke,Yr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:x=>{Ft=Math.max(Ft,x)}}});let K=()=>{Cc(Pe,"session_create",_e,Ft)},fe=x=>{Sc(Pe,x,"session_create",_e,Ft)&&de({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,tt.isDetachedSessionEligible)(ke)){let x=await Ve.createDetachedSession(ke);x.claimed.catch(()=>{}),be=x.shell,j=x.sessionId,et=x.claim;let Ye=Pe.now();Pe.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),oe=x.claimed.then(At=>{let Ne=At.data.session?.id??x.sessionId;return Ne&&ni(z,B,Ne,At.data.session?.clientSecret??x.nonce),Cc(Pe,"session_claim",Ye),K(),At},At=>{throw ei(z,B),Sc(Pe,At,"session_claim",Ye,0)&&de({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),At}).finally(()=>Ea(Pe)),oe.catch(()=>{}),Pt=!0,Pe.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Pe.performance({stage:"session_shell",durationMs:Pe.now()-_e,durationMode:"machine",requestCategory:"session_create",attempt:Ft,statusClass:"2xx",paymentMethodCategory:"card"})}else be=await Ve.createAndFetchSession(ke),K()}catch(x){throw fe(x),x}j=be.data.session?.id??j??"",j&&!oe&&ni(z,B,j,be.data.session?.clientSecret)}let M=be?.data.session;return!et&&j&&M?.buyerIdentified===!1&&M.clientSecret&&(et=Bo(Ve,j,M.clientSecret,D.account)),{sid:j??"",result:be,sdkGeneratedIdempotencyKey:P,...oe?{claimed:oe}:{},...et?{claim:et}:{},...Tt?{claimRequiresIdentity:!0}:{}}}finally{Pt||Ea(Pe)}}let cr=(0,w.useRef)(Ir);go(()=>{cr.current=Ir},[Ir]);let Qn=(0,w.useCallback)(async(D,z)=>{let B=kr.current;if(!B)throw new tt.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Pe=Hi(B,D),Ve=Vo(Pe),Pt=Ol(Pe),Ce=bi.get(Ve);if(!Ce){let m={canonicalIdentity:Ve,promise:cr.current(Pe,Pt,Ve),consumers:0,settled:!1};Ce=m,bi.set(Ve,m);let P=()=>{m.settled=!0,vc(Ve,m)};m.promise.then(P,P)}Ce.consumers+=1;let je=!1,Q=()=>{je||(je=!0,Ce.consumers-=1,vc(Ve,Ce))};z?.(Q);try{let m=await Ce.promise;Ur.current=Ve,D&&(fn(bn),ln(M=>bl(M,D)));let{sid:P,result:N,claimed:j,claim:be,claimRequiresIdentity:oe}=m;if(ue.current=be,Kt(oe===!0),Y(N),N.data.session&&qe(N.data.session),P&&ae(P),j){vt.current+=1;let M=vt.current;hn.current=j,Nt(!0),j.then(_e=>{vt.current===M&&(hn.current===j&&(hn.current=null),Y(_e),_e.data.session&&qe(_e.data.session),Nt(!1),Kt(!1))},_e=>{vt.current===M&&(hn.current===j&&(hn.current=null),Nt(!1),Kt(!1),Ge(_e instanceof tt.FloPayError?_e:new tt.FloPayError(_e instanceof Error?_e.message:"Failed to create session","api_error")))})}else vt.current+=1,hn.current=null,Nt(!1),Kt(!1);let{flopay:et,paypalFlopay:Tt}=await Rs(N,{billingApiUrl:re,locale:s,telemetry:o});return Gt(et,Tt),Ke(!1),m}catch(m){throw Ur.current===Ve&&(Ur.current=null),m}finally{z||Q()}},[bn,Gt,s,re,o]),er=(0,w.useRef)(Mn);er.current=Mn;let Bt=(0,w.useRef)(Qn);Bt.current=Qn;let dr=(0,w.useCallback)(async D=>{if(!Ku(D)||_t)return{sessionId:Qe,session:Z};Qt(!0);try{let z=await Qn(D);return{sessionId:z.sid,session:z.result.data.session??null}}finally{Qt(!1)}},[Qn,_t,Qe,Z]),_n=(0,w.useCallback)(async D=>{let z=ue.current;if(!z)return;let B=vt.current,Pe=await z(D);vt.current===B&&(Y(Pe),Pe.data.session&&qe(Pe.data.session))},[]),tr=(0,w.useCallback)(async()=>{await hn.current},[]),Rr=(0,w.useCallback)(async()=>(await tr(),{proceed:!0}),[tr]);(0,w.useEffect)(()=>{let D=!1,z,B=++ft.current;Zn(),Ge(null),Tn(0);let Pe=()=>{D=!0,ft.current===B&&(ft.current+=1,Zn())},Ve=kr.current;if(Fn&&Ve)return Rn(xn),Ke(!1),Ur.current===Fn?Pe:(qe(vl(Ve,F)),(async()=>{let je=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Q=xn==="auto"&&!cn.current&&!je;Q&&(Ee(null),Ot(null),Mt("processing"));try{let m=await Bt.current(void 0,be=>{z=be}),P=m.result.data.session??null;ge.current=ss(m.result);let N=Is(m.result),j=ns(m.sid||P?.id);if(!D&&Q&&P&&!N&&!j){cn.current=!0,await qu(Fn,m.sdkGeneratedIdempotencyKey,()=>er.current(P,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:m.result.autoProcessingError,initialAutoProcessingPending:m.result.autoProcessingPending,autoProcessingAttempted:m.result.autoProcessingAttempted,sessionId:m.sid||P.id}));return}!D&&Q&&((N||j)&&(cn.current=!0),Mt(null),Ot(null))}catch(m){if(D)return;let P=$a(m);if(Q&&P==="session_auto_completed"){cn.current=!0,Mt("success"),await _a(600),D||(We(()=>{rt.current?.({status:"succeeded"})}),Mt(null),Ot(null));return}Q&&(Mt(null),Ot(null));let N=m instanceof tt.FloPayError?m:new tt.FloPayError(m instanceof Error?m.message:"Failed to create session","api_error");Ge(N)}finally{z?.(),z=void 0}})(),()=>{Pe(),z?.()});Ke(!0);async function Pt(){let je=!1,Q=null;try{let m=new Yr.PaymentAPI(re,{telemetry:!1}),P=await m.getUnifiedCheckoutSession(yt,t);if(Q=P,D)return;Y(P);let N=P.data.session??null;if(qe(N),!N)throw new tt.FloPayError("No session data returned","api_error");let j=N.checkoutMode;if(j==="setup")throw new tt.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(N.status==="authorized"){Ke(!1),We(()=>{rt.current?.(jr(N,yt)),pt.current?.(N.successUrl??"")});return}if(N.status==="complete"){Ke(!1),We(()=>{pt.current?.(N.successUrl??"")});return}if(N.status==="expired")throw ja(N);je=!0;let be=F??j??"full";Rn(be),vt.current+=1;let oe=N.clientSecret||t;ue.current=N.buyerIdentified===!1&&oe?Bo(m,yt,oe,{...N.customer?.id?{userId:N.customer.id}:{}}):void 0,Nt(!1),Kt(!1);let et=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Tt=Is(P);if(be==="auto"&&!cn.current&&!et&&!Tt){cn.current=!0;let M=Ce(P);try{if(await er.current(N,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>M,sessionId:yt||N.id}),D)return;await M,D||Ke(!1);return}catch{if(D)return;await M,D||Ke(!1);return}}await Ce(P),D||Ke(!1)}catch(m){if(D)return;let P=Pl(m,je);if(je&&de({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),P){let{errorCode:j,stage:be,...oe}=P;ks(re,o,L,j,be,oe)}if(P?.stage==="provider_load"&&(F??Q?.data.session?.checkoutMode??"full")==="full"&&hl(Q,f,S)){let j=ju({billingApiUrl:re,locale:s,telemetry:o});Ie.current=j,Gt(j,null),Tn(1),Ke(!1);return}let N=m instanceof tt.FloPayError&&P?.stage!=="provider_load"?m:gl();N!==m&&We(()=>he.current?.(N)),Ge(N),Ke(!1)}}async function Ce(je){let{flopay:Q,paypalFlopay:m,...P}=await Rs(je,{billingApiUrl:re,locale:s,telemetry:o});ge.current={publishableKey:P.publishableKey,paypalPublishableKey:P.paypalPublishableKey},Gt(Q,m),Tn(0)}return Pt(),Pe},[F,Fn,xn,It,t,f,S]);let ht=(0,w.useCallback)(async()=>{if(!ut||zn!==1)return;let D=ft.current;Tn(2);try{let{flopay:z,paypalFlopay:B}=await Rs(ut,{billingApiUrl:re,locale:s,telemetry:o});if(ft.current!==D)return;Zn(),Gt(z,B),Tn(0)}catch(z){if(ft.current!==D)return;let{errorCode:B,stage:Pe,...Ve}=$i(z);ks(re,o,L,B,Pe,Ve)}},[Zn,Gt,s,zn,re,o,L,ut]),an=!!(yt&&(Z?.clientSecret||t)),nn=Un||!an,qr=(0,w.useCallback)(async()=>{if(!(Un||!an||!Z)){qn(!0),Ee(null);try{await Mn(Z,{attempt3DS:!0,fallbackToFull:!0,sessionId:yt||Z.id})}finally{qn(!1)}}},[yt,Un,an,Mn,Z]),$n=Rc(ut,ye),Jr=Is(ut),ur=(0,w.useMemo)(()=>{if(!(!ut||!Z||!ut.data.stripe?.publishableKey))return{billingApiUrl:re}},[ut,Z,re]),pr=!!(n&&!le&&$==="buttons"&&Re&&xn==="full"),vn=!!(yt&&(Z?.vault?.html||Zr(Z))),mr=(0,w.useMemo)(()=>({session:Z,loading:qt,error:Lt,checkoutMode:Dt,inlineSessionDraft:tn,applyInlineSessionPatch:pr?dr:void 0,inlineSessionPatchProcessing:_t,claimPending:gn,claimRequiresIdentity:en,claimBuyerIdentity:_n,waitForDataAttachment:tr}),[Z,qt,Lt,Dt,tn,pr,dr,_t,gn,en,_n,tr]),Vr=!!n&&$==="buttons"&&!Jr&&!vn&&(!J||!ur),En=Rt?(0,O.jsx)(Ln,{status:Rt,errorMessage:wn,authorized:Yn}):null;if(qt&&!vn){if(c)return(0,O.jsxs)(O.Fragment,{children:[c,En]});if($==="buttons"){let D=$e?.buttonsLayout?.cardButton?.borderRadius??$e?.appearance.variables?.borderRadius??8,z=B=>(0,O.jsx)("div",{style:{height:B,borderRadius:D,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[f&&z(Yo),S&&(q||E)&&z(Yo),S&&z(Yo),(0,O.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),En]})}return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,O.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,O.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),En]})}return Lt?u?(0,O.jsx)(Pr.Provider,{value:mr,children:u(Lt)}):(0,O.jsx)(Pr.Provider,{value:mr,children:(0,O.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Lt.message})}):Vr?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:mr,children:(0,O.jsx)(Yu,{onButtonClick:it,showPayPal:f,showStripe:S,showApplePay:q,showGooglePay:E,theme:W,buttonsTheme:ie,buttonsStyles:V,cardButtonContent:Be,cardBackButtonContent:Ue,cardTitleContent:X})}),En]}):Jr&&Z&&$n?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:mr,children:(0,O.jsxs)("div",{className:st,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[on&&(0,O.jsx)(Uo,{icon:!1,children:on}),Vn==="retrying"&&(0,O.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Vn==="exhausted"&&(0,O.jsxs)("div",{role:"alert",children:[(0,O.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,O.jsx)("button",{type:"button",onClick:Yt,children:"Retry PayPal"})]}),Vn!=="exhausted"&&(0,O.jsx)("div",{"aria-hidden":Vn==="retrying"?!0:void 0,style:Vn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,O.jsx)(Dl,{sessionId:yt,nonce:Z.clientSecret||void 0,billingApiUrl:re,email:Z.customer?.email||tn?.account?.email,billingName:[Z.customer?.firstName,Z.customer?.lastName].filter(Boolean).join(" ")||[tn?.account?.firstName,tn?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:_n,clientId:$n.clientId,environment:$n.environment,currency:(Z.currency??"usd").toUpperCase(),isSubscription:Z.mode==="subscription",providerObjectType:$n.providerObjectType,approvalPresentation:$n.approvalPresentation,existingOrderId:$n.existingOrderId,onComplete:p,onErrorChange:Ee,onDecline:I,onButtonClick:it,runBeforeButtonClick:Rr,onInitializationStateChange:Xr,allowAutomaticRetry:Sr===0,session:Z,telemetry:o,telemetryContext:L,onInstrument:kt,debug:ne},`${Ze}:paypal-init-${Sr}`)})]})}),En]}):Dt==="confirm"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:mr,children:(0,O.jsx)(ha,{flopay:J,paypalFlopay:U,options:ur??{billingApiUrl:re},onInstrument:kt,children:(0,O.jsxs)("div",{className:st,children:[on&&(0,O.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:on}),ce?ce({onConfirm:qr,isProcessing:nn}):(0,O.jsx)("button",{type:"button",onClick:qr,disabled:nn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:nn?"not-allowed":"pointer",opacity:nn?.6:1},children:Un?"Processing...":Se??"Confirm Purchase"})]})},Ze)}),En]}):(!J||!ur)&&!(vn&&Dt==="full")?(0,O.jsx)(O.Fragment,{children:En}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:mr,children:(0,O.jsxs)(ha,{flopay:J,paypalFlopay:U,options:ur??{billingApiUrl:re},onInstrument:kt,children:[zn===1&&(0,O.jsx)("button",{type:"button",onClick:ht,children:"Retry payment methods"}),le?(0,O.jsxs)(O.Fragment,{children:[on&&(0,O.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:on}),(0,O.jsx)(Gu,{sessionId:yt,nonce:Z?.clientSecret||void 0,billingApiUrl:re,session:Z,submitLabel:He,walletPresentation:G,children:le})]}):(0,O.jsx)(gi,{sessionId:yt,nonce:Z?.clientSecret||void 0,telemetry:o,email:Z?.customer?.email||tn?.account?.email,userId:Z?.customer?.id||tn?.account?.userId,firstName:Z?.customer?.firstName||tn?.account?.firstName,lastName:Z?.customer?.lastName||tn?.account?.lastName,totalAmount:Z?Math.round((0,tt.buildCheckoutDisplayData)(Z).total*100):0,currency:Z?.currency?.toLowerCase()??"usd",onComplete:p,onError:h,onDecline:I,error:on,onErrorChange:Ee,showPayPal:f,showStripe:S,walletPresentation:G,enabledPaymentMethods:zn?[]:_??ut?.data.stripe?.enabledPaymentMethods??Z?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ut?.data.stripe?.enabledPaymentMethodCountries,showApplePay:q,showGooglePay:E,layout:$,theme:W,buttonsTheme:ie,buttonsStyles:V,appearance:dt,cardButtonContent:Be,cardBackButtonContent:Ue,cardTitleContent:X,onButtonClick:it,onBeforeButtonClick:Re,onBuyerIdentityReady:_n,enableAVS:xe,...ve?{cardFieldOrder:ve}:{},...se?{cardPreFormSlot:se}:{},avsLayout:me,country:Z?.customer?.country,city:Z?.customer?.city,state:Z?.customer?.state,onCountryChange:k,onZipChange:C,avsCheck:!!xe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Es(le,$),className:st,submitLabel:He,directPaypal:$n,isSubscription:Z?.mode==="subscription",session:Z,dataAttachmentPending:gn,dataAttachmentRequiresIdentity:en,debug:ne})]},Ze)}),En]})}function Gu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:a,children:s}){return(0,O.jsx)(O.Fragment,{children:w.default.Children.map(s,c=>{if(!w.default.isValidElement(c))return c;let u=c.props,p={};return u.sessionId||(p.sessionId=e),!u.nonce&&t&&(p.nonce=t),u.billingApiUrl||(p.billingApiUrl=n),u.submitLabel===void 0&&o!==void 0&&(p.submitLabel=o),u.walletPresentation===void 0&&(p.walletPresentation=a),r?.customer&&(u.email||(p.email=r.customer.email),u.userId||(p.userId=r.customer.id),u.firstName||(p.firstName=r.customer.firstName),u.lastName||(p.lastName=r.customer.lastName)),Object.keys(p).length===0?c:w.default.cloneElement(c,p)})})}function Yu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:s,buttonsStyles:c,cardButtonContent:u,cardBackButtonContent:p,cardTitleContent:h}){let[b,I]=(0,w.useState)(!1),k=(0,w.useMemo)(()=>(0,tt.resolveTheme)(a),[a]),C=(0,w.useMemo)(()=>{let _=k?.buttonsLayout??(0,tt.resolveButtonsLayoutTheme)(s);return c?{..._,...c,cardButton:{..._.cardButton,...c.cardButton},cardFormContainer:{..._.cardFormContainer,...c.cardFormContainer},backButton:{..._.backButton,...c.backButton},backButtonIcon:{..._.backButtonIcon,...c.backButtonIcon},submitButton:{..._.submitButton,...c.submitButton},title:{..._.title,...c.title}}:_},[k,s,c]),f=k?.buttonsLayout?.cardButton?.borderRadius??k?.appearance.variables?.borderRadius??8,S=_=>(0,O.jsx)("div",{style:{height:_,borderRadius:f,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),G=u===void 0?{boxSizing:"border-box",height:Yo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let _=C.cardInputBorder??"#e5e7eb",q=C.cardInputBackground??"white",E=xo(p),ne=xo(h);return(0,O.jsxs)("div",{style:{backgroundColor:C.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...C.cardFormContainer},children:[(0,O.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,O.jsxs)("button",{type:"button",onClick:()=>I(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:E?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...C.backButton},children:[(0,O.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...C.backButtonIcon},children:(0,O.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,O.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,O.jsx)(Fo,{content:p})]}),ne?(0,O.jsx)("div",{style:{flex:1}}):(0,O.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...C.title},children:(0,O.jsx)(ca,{content:h})})]}),(0,O.jsx)("div",{style:{backgroundColor:q,border:`1px solid ${_}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsxs)("div",{style:{display:"flex"},children:[(0,O.jsx)("div",{style:{flex:1,backgroundColor:q,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${_}`,borderLeft:`1px solid ${_}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsx)("div",{style:{flex:1,backgroundColor:q,borderTop:"none",borderRight:`1px solid ${_}`,borderBottom:`1px solid ${_}`,borderLeft:`1px solid ${_}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,O.jsx)("div",{style:{backgroundColor:q,border:`1px solid ${_}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...C.submitButton,opacity:.5}}),(0,O.jsx)("style",{children:`
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&&O(Do),n&&(r||o)&&O(Do),n&&(0,M.jsx)("button",{type:"button",onClick:()=>{e?.("card"),B(!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,M.jsx)(bo,{content:u})}),(0,M.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var tr=require("react/jsx-runtime"),vu=44;function pc(e){return new Promise(t=>setTimeout(t,e))}function Cu(e,t){return e instanceof nr.FloPayError?e:new nr.FloPayError(e instanceof Error?e.message:t,"api_error")}function Su(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function wu(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function mc({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:d,subscriptions:u,account:p,successUrl:b,cancelUrl:v,couponCodes:B,tagsData:I,utmMetadata:w,billingApiUrl:h,locale:O,theme:G,appearance:T,buttonsTheme:Y,buttonsStyles:U,onSuccess:de,onError:X,onDecline:he,children:Fe,disabled:oe=!1,type:je="button",style:yt,...re}){let De=(0,Qe.useMemo)(()=>(0,nr.resolveBillingApiUrl)(h),[h]),ft=(0,Qe.useMemo)(()=>wu({createSession:n,clientId:a,products:l,items:d,subscriptions:u,account:p,successUrl:b,cancelUrl:v,couponCodes:B,tagsData:I,utmMetadata:w}),[p,v,a,B,n,l,d,u,b,I,w]),[ke,Oe]=(0,Qe.useState)(!1),[be,me]=(0,Qe.useState)(null),[Ie,Ve]=(0,Qe.useState)(null),[rt,R]=(0,Qe.useState)(!1),[We,ye]=(0,Qe.useState)(null),[N,ve]=(0,Qe.useState)(null),ue=(0,Qe.useRef)(!0),He=(0,Qe.useRef)(null),Q=(0,Qe.useRef)(N),ot=(0,Qe.useRef)(de),lt=(0,Qe.useRef)(X),Te=(0,Qe.useRef)(he),Le=(0,Qe.useCallback)(f=>Ka(He,async P=>{try{return await f(P)}catch(H){throw P.aborted?Jr(H):H}}),[]);(0,Qe.useEffect)(()=>{Q.current=N},[N]),(0,Qe.useEffect)(()=>{ot.current=de},[de]),(0,Qe.useEffect)(()=>{lt.current=X},[X]),(0,Qe.useEffect)(()=>{Te.current=he},[he]),(0,Qe.useEffect)(()=>(ue.current=!0,()=>{ue.current=!1,He.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=sa)=>{Te.current?.(cn(P,f,{code:f.code,declineCode:f.declineCode}))},[]),at=(0,Qe.useCallback)(async f=>{ue.current&&(Ve(null),R(f.result.status==="authorized"),me("success"),await pc(600),ue.current&&st(()=>ot.current?.(f)))},[]),Ae=(0,Qe.useCallback)(async(f,P)=>{ue.current&&(lt.current?.(f),P?.emitDecline&&ct(f,P.method),Ve(f.message),R(!1),me("error"),await pc(400))},[ct]),jt=(0,Qe.useCallback)(async(f,P,H)=>{let ee=f.data.session??null;if(!ee)throw Hr(new nr.FloPayError("No session data returned","api_error"),P);let qe=ee.clientSecret||t;if(Nr(ee)){await at({result:Lr(ee,P),session:ee,sessionId:ee.id||P,autoCompleted:!1});return}if(ee.status==="expired")throw Hr(Aa(ee),ee.id||P);try{if(f.autoProcessingPending){let Ge=f.autoProcessingPending,Z=new ci.PaymentAPI(De),it=await Le(Ne=>Z.waitForCheckoutSessionCompletion(Ge.sessionId,{initialDelayMs:Ge.retryAfterMs,nonce:qe,statusUrl:Ge.statusUrl,signal:Ne})),Ct=Gr(it,ee),Nt=it.autoProcessingError?.type==="3ds_required"&&it.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:it.autoProcessingError.nextActionRedirectUrl}:null;if(Nt&&P&&qe){let Ne=await Le(Ft=>Ao(Nt,{billingApiUrl:De,sessionId:P,nonce:qe,session:ee,signal:Ft,telemetry:!0}));await at({result:Ne,session:ee,sessionId:ee.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 Co(Ct);await at({result:Lr(Ct,P),session:Ct,sessionId:Ct.id||P,autoCompleted:!1});return}if(f.autoProcessingError){let Ge=f.autoProcessingError.nextActionRedirectUrl;if(f.autoProcessingError.type==="3ds_required"&&Ge&&P&&qe){let Z=await Le(Ne=>Vi({billingApiUrl:De,sessionId:P,nonce:qe,nextActionRedirectUrl:Ge,signal:Ne}));if(Z.status==="declined")throw Er({type:Z.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Z.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:f.autoProcessingError.checkoutMethod});let Ct=await new ci.PaymentAPI(De).waitForCheckoutSessionCompletion(P,{initialDelayMs:0,nonce:qe}),Nt=Gr(Ct,ee);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 xo({billingApiUrl:De,sessionId:P??ee.id,session:ee,nonce:qe});if(vt.type==="next_action_required"&&qe){let Ge=P??ee.id,Z=await Le(it=>Ao(vt,{billingApiUrl:De,sessionId:Ge,nonce:qe,session:ee,signal:it,telemetry:!0}));await at({result:Z,session:ee,sessionId:ee.id||Ge,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:ee,sessionId:ee.id||P,autoCompleted:!1})}catch(vt){let Ge=ee.id||P,Z=Hr(la(vt),Ge);if(Z.code==="three_ds_aborted")return;if(Z.code==="checkout_processing_timeout"){if(!ue.current)return;ye(Z.message),st(()=>lt.current?.(Z));return}await Ae(Z,{emitDecline:!0,method:Z.checkoutMethod??sa}),Su(Z,Ge)&&Ge&&ue.current&&ve({sessionId:Ge,errorMessage:Z.message,nonce:qe||void 0,payPalOrderId:Z.orderId})}},[t,De,Le,Ae,at]),Vt=(0,Qe.useCallback)(async f=>{if(re.onClick?.(f),!(f.defaultPrevented||oe||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 Ae(P),ue.current&&(me(null),Ve(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 Ae(P),ue.current&&(me(null),Ve(null));return}Oe(!0),Ve(null),R(!1),me("processing");try{let P=new ci.PaymentAPI(De);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(xa(H)==="session_auto_completed"){await at({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw H}}catch(P){await Ae(Hr(Cu(P,"Automatic payment failed. Please try again."),e))}finally{ue.current&&(me(null),Ve(null),Oe(!1))}}},[re.onClick,ft,oe,ke,t,jt,De,e,Ae,at]),ut=(0,Qe.useCallback)(f=>{let P=Q.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=>{Te.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]),xe=V?.variables,bt=xe?.colorPrimary??"#4A49FF",Ke=xe?.colorPrimaryHover??Fo(bt,.12),$=xe?.borderRadius??"8px";return(0,tr.jsxs)(tr.Fragment,{children:[(0,tr.jsx)("button",{...re,type:je,onClick:Vt,disabled:oe||ke,"aria-busy":ke,style:{width:"100%",...Fe===void 0?{boxSizing:"border-box",height:vu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...et.cardButton,...ss({themeBundle:fe,resolvedPrimaryColor:bt,resolvedBorderRadius:$,submitButtonStyle:et.submitButton,explicitPrimaryColor:xe?.colorPrimary}),fontSize:et.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:oe||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:oe||ke?.6:1,...yt},onMouseEnter:f=>{re.onMouseEnter?.(f),!f.defaultPrevented&&!oe&&!ke&&(fe||xe?.colorPrimary)&&(f.currentTarget.style.backgroundColor=Ke)},onMouseLeave:f=>{re.onMouseLeave?.(f),!f.defaultPrevented&&(fe||xe?.colorPrimary)&&(f.currentTarget.style.backgroundColor=bt)},onMouseDown:f=>{re.onMouseDown?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(0.985)")},onMouseUp:f=>{re.onMouseUp?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(1)")},children:(0,tr.jsx)(bo,{content:Fe})}),We&&(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:We}),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)(li,{sessionId:N.sessionId,nonce:N.nonce,checkoutMode:"full",billingApiUrl:De,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 di=require("@flopay/js/card-setup"),jn=require("@flopay/shared"),_t=require("react");var yc={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function fc(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?yc.dark:yc.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"),ha=class extends jn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function gc(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 ha(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 hc({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:B}){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),Fe=(0,_t.useRef)(!1),oe=(0,_t.useMemo)(()=>typeof o=="object"?void 0:(0,jn.resolveTheme)(o),[o]),je=(0,_t.useMemo)(()=>typeof o=="object"?o:oe?Za({appearance:oe.appearance,buttonsStyles:oe.buttonsLayout,layout:"default"}):null,[oe,o]),yt=(0,_t.useMemo)(()=>El(oe?.buttonsLayout.cardFormContainer,a),[oe,a]),re=(0,_t.useMemo)(()=>oe?fc(oe):void 0,[oe]),De=(0,_t.useRef)(d),ft=(0,_t.useRef)(B),ke=(0,_t.useRef)(u),Oe=(0,_t.useRef)(p),be=(0,_t.useRef)(b),me=(0,_t.useRef)(v),Ie=(0,_t.useRef)(!1),Ve=(0,_t.useRef)(!1),rt=(0,_t.useRef)(0);return De.current=d,ft.current=B,ke.current=u,Oe.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||Ve.current||(Ve.current=!0,st(()=>{be.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,_t.useEffect)(()=>{let R=!0,We=new di.PaymentAPI((0,jn.resolveBillingApiUrl)(n),{telemetry:r});return w(null),O(null),T(null),Ie.current=!1,Ve.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 We.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 We.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 di.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(ye){if(!R)return;let N=gc(ye);Ie.current=!0,T(N),st(()=>ft.current?.(N))}})(),()=>{R=!1,We.destroy()}},[n,t,e,r]),(0,_t.useEffect)(()=>{if(!I)return;let R=!1;Fe.current=!1,he.current=!1;let We=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(He=>setTimeout(He,600)),!Fe.current&&(Fe.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(()=>{Oe.current?.({status:"declined",sessionId:e,...ue.declineReason?{reason:ue.declineReason}:{},...ue.message?{message:ue.message}:{}})}),(async()=>(await new Promise(He=>setTimeout(He,400)),R||U(null)))()}),ve=I.on("challenge_dismissed",()=>{U(null)});return()=>{R=!0,We(),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,...re?{theme:re}:{}}),(0,xr.jsx)(Bo,{capture:I,html:h.html,messageToken:h.messageToken,expectedOrigin:h.expectedOrigin,theme:je,containerStyle:yt,onReady:()=>{st(()=>De.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 We=gc(new Error(R),{code:"card_setup_widget_failed",retryable:!0});st(()=>ft.current?.(We))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&S(Yo),n&&(r||o)&&S(Yo),n&&(0,O.jsx)("button",{type:"button",onClick:()=>{e?.("card"),I(!0)},style:{width:"100%",...G,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:C.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...C.cardButton},onMouseDown:_=>{_.currentTarget.style.transform="scale(0.985)"},onMouseUp:_=>{_.currentTarget.style.transform="scale(1)"},children:(0,O.jsx)(Mo,{content:u})}),(0,O.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var ir=require("react/jsx-runtime"),Xu=44;function _c(e){return new Promise(t=>setTimeout(t,e))}function Ju(e,t){return e instanceof sr.FloPayError?e:new sr.FloPayError(e instanceof Error?e.message:t,"api_error")}function Zu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Qu(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function Ec({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:s,items:c,subscriptions:u,account:p,successUrl:h,cancelUrl:b,couponCodes:I,tagsData:k,utmMetadata:C,billingApiUrl:f,locale:S,theme:G,appearance:_,buttonsTheme:q,buttonsStyles:E,onSuccess:ne,onError:$,onDecline:W,children:ie,disabled:V=!1,type:Be="button",style:Ue,...X}){let Ae=(0,ot.useMemo)(()=>(0,sr.resolveBillingApiUrl)(f),[f]),it=(0,ot.useMemo)(()=>Qu({createSession:n,clientId:a,products:s,items:c,subscriptions:u,account:p,successUrl:h,cancelUrl:b,couponCodes:I,tagsData:k,utmMetadata:C}),[p,b,a,I,n,s,c,u,h,k,C]),[Re,xe]=(0,ot.useState)(!1),[ve,se]=(0,ot.useState)(null),[me,He]=(0,ot.useState)(null),[st,T]=(0,ot.useState)(!1),[ye,le]=(0,ot.useState)(null),[F,Se]=(0,ot.useState)(null),ce=(0,ot.useRef)(!0),De=(0,ot.useRef)(null),re=(0,ot.useRef)(F),$e=(0,ot.useRef)(ne),dt=(0,ot.useRef)($),Me=(0,ot.useRef)(W),Oe=(0,ot.useCallback)(g=>ai(De,async v=>{try{return await g(v)}catch(ee){throw v.aborted?io(ee):ee}}),[]);(0,ot.useEffect)(()=>{re.current=F},[F]),(0,ot.useEffect)(()=>{$e.current=ne},[ne]),(0,ot.useEffect)(()=>{dt.current=$},[$]),(0,ot.useEffect)(()=>{Me.current=W},[W]),(0,ot.useEffect)(()=>(ce.current=!0,()=>{ce.current=!1,De.current?.abort()}),[]),(0,ot.useEffect)(()=>{if(typeof window>"u")return;let g=v=>{v.key==="Escape"&&Se(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let ut=(0,ot.useCallback)((g,v=ba)=>{Me.current?.(un(v,g,{code:g.code,declineCode:g.declineCode}))},[]),Y=(0,ot.useCallback)(async g=>{ce.current&&(He(null),T(g.result.status==="authorized"),se("success"),await _c(600),ce.current&&We(()=>$e.current?.(g)))},[]),J=(0,ot.useCallback)(async(g,v)=>{ce.current&&(dt.current?.(g),v?.emitDecline&&ut(g,v.method),He(g.message),T(!1),se("error"),await _c(400))},[ut]),mt=(0,ot.useCallback)(async(g,v,ee)=>{let de=g.data.session??null;if(!de)throw Qr(new sr.FloPayError("No session data returned","api_error"),v);let Xe=de.clientSecret||t;if($r(de)){await Y({result:jr(de,v),session:de,sessionId:de.id||v,autoCompleted:!1});return}if(de.status==="expired")throw Qr(ja(de),de.id||v);try{if(g.autoProcessingPending){let Qe=g.autoProcessingPending,ae=new Ci.PaymentAPI(Ae),yt=await Oe(Ke=>ae.waitForCheckoutSessionCompletion(Qe.sessionId,{initialDelayMs:Qe.retryAfterMs,nonce:Xe,statusUrl:Qe.statusUrl,signal:Ke})),It=to(yt,de),qt=yt.autoProcessingError?.type==="3ds_required"&&yt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:yt.autoProcessingError.nextActionRedirectUrl}:null;if(qt&&v&&Xe){let Ke=await Oe(Lt=>$o(qt,{billingApiUrl:Ae,sessionId:v,nonce:Xe,session:de,signal:Lt,telemetry:!0}));await Y({result:Ke,session:de,sessionId:de.id||v,autoCompleted:!1});return}if(yt.autoProcessingError)throw Fr(yt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:yt.autoProcessingError.checkoutMethod});if(!$r(It))throw Do(It);await Y({result:jr(It,v),session:It,sessionId:It.id||v,autoCompleted:!1});return}if(g.autoProcessingError){let Qe=g.autoProcessingError.nextActionRedirectUrl;if(g.autoProcessingError.type==="3ds_required"&&Qe&&v&&Xe){let ae=await Oe(Ke=>is({billingApiUrl:Ae,sessionId:v,nonce:Xe,nextActionRedirectUrl:Qe,signal:Ke}));if(ae.status==="declined")throw Fr({type:ae.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:ae.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let It=await new Ci.PaymentAPI(Ae).waitForCheckoutSessionCompletion(v,{initialDelayMs:0,nonce:Xe}),qt=to(It,de);if(!$r(qt))throw Fr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await Y({result:jr(qt,v),session:qt,sessionId:qt.id||v,autoCompleted:!1});return}throw Fr(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(ee?.fromCreateSession&&g.autoProcessingAttempted===!0)throw Fr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let kt=await Wo({billingApiUrl:Ae,sessionId:v??de.id,session:de,nonce:Xe});if(kt.type==="next_action_required"&&Xe){let Qe=v??de.id,ae=await Oe(yt=>$o(kt,{billingApiUrl:Ae,sessionId:Qe,nonce:Xe,session:de,signal:yt,telemetry:!0}));await Y({result:ae,session:de,sessionId:de.id||Qe,autoCompleted:!1});return}if(kt.type!=="success")throw Fr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Y({result:kt.result,session:de,sessionId:de.id||v,autoCompleted:!1})}catch(kt){let Qe=de.id||v,ae=Qr(va(kt),Qe);if(ae.code==="three_ds_aborted")return;if(ae.code==="checkout_processing_timeout"){if(!ce.current)return;le(ae.message),We(()=>dt.current?.(ae));return}await J(ae,{emitDecline:!0,method:ae.checkoutMethod??ba}),Zu(ae,Qe)&&Qe&&ce.current&&Se({sessionId:Qe,errorMessage:ae.message,nonce:Xe||void 0,payPalOrderId:ae.orderId})}},[t,Ae,Oe,J,Y]),gt=(0,ot.useCallback)(async g=>{if(X.onClick?.(g),!(g.defaultPrevented||V||Re)){if(Se(null),le(null),e&&it){let v=new sr.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await J(v),ce.current&&(se(null),He(null));return}if(!e&&!it){let v=new sr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await J(v),ce.current&&(se(null),He(null));return}xe(!0),He(null),T(!1),se("processing");try{let v=new Ci.PaymentAPI(Ae);if(e){let ee=await v.getUnifiedCheckoutSession(e,t);await mt(ee,e);return}try{let ee=await v.createAndFetchSession({...it});await mt(ee,ee.data.session?.id??null,{fromCreateSession:!0})}catch(ee){if($a(ee)==="session_auto_completed"){await Y({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw ee}}catch(v){await J(Qr(Ju(v,"Automatic payment failed. Please try again."),e))}finally{ce.current&&(se(null),He(null),xe(!1))}}},[X.onClick,it,V,Re,t,mt,Ae,e,J,Y]),Ie=(0,ot.useCallback)(g=>{let v=re.current;Se(null),$e.current?.({result:g,session:null,sessionId:v?.sessionId??null,autoCompleted:!1})},[]),ft=(0,ot.useCallback)(g=>{dt.current?.(g)},[]),U=(0,ot.useCallback)(g=>{Me.current?.(g)},[]),we=(0,ot.useMemo)(()=>(0,sr.resolveTheme)(G),[G]),lt=(0,ot.useMemo)(()=>{let g=we?.buttonsLayout??(0,sr.resolveButtonsLayoutTheme)(q);return E?{...g,...E,cardButton:{...g.cardButton,...E.cardButton}}:g},[we,q,E]),Z=(0,ot.useMemo)(()=>{let g=we?.appearance;return _?g?{...g,..._,variables:{...g.variables,..._.variables}}:_:g},[_,we]),qe=Z?.variables,St=qe?.colorPrimary??"#4A49FF",Ze=qe?.colorPrimaryHover??Ko(St,.12),H=qe?.borderRadius??"8px";return(0,ir.jsxs)(ir.Fragment,{children:[(0,ir.jsx)("button",{...X,type:Be,onClick:gt,disabled:V||Re,"aria-busy":Re,style:{width:"100%",...ie===void 0?{boxSizing:"border-box",height:Xu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...lt.cardButton,...ws({themeBundle:we,resolvedPrimaryColor:St,resolvedBorderRadius:H,submitButtonStyle:lt.submitButton,explicitPrimaryColor:qe?.colorPrimary}),fontSize:lt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:V||Re?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:V||Re?.6:1,...Ue},onMouseEnter:g=>{X.onMouseEnter?.(g),!g.defaultPrevented&&!V&&!Re&&(we||qe?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Ze)},onMouseLeave:g=>{X.onMouseLeave?.(g),!g.defaultPrevented&&(we||qe?.colorPrimary)&&(g.currentTarget.style.backgroundColor=St)},onMouseDown:g=>{X.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{X.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:(0,ir.jsx)(Mo,{content:ie})}),ye&&(0,ir.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ye}),ve&&(0,ir.jsx)(Ln,{status:ve,errorMessage:me,authorized:st}),F&&(0,ir.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&Se(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,ir.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,ir.jsx)(vi,{sessionId:F.sessionId,nonce:F.nonce,checkoutMode:"full",billingApiUrl:Ae,locale:S,theme:G,...Z?{appearance:Z}:{},buttonsTheme:q,buttonsStyles:E,initialErrorMessage:F.errorMessage,initialPayPalOrderId:F.payPalOrderId,cardTitleContent:null,onComplete:Ie,onError:ft,onDecline:U})})})]})}var wi=require("@flopay/js/card-setup"),Gn=require("@flopay/shared"),xt=require("react");var Tc={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function Si(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?Tc.dark:Tc.light,a=t.colorText??(r?"#F1F5F9":"#262833"),s=e.appearance.rules?.[".Label"];return{panel:{...n.background===void 0?{}:{background:n.background},...n.backgroundColor===void 0?{}:{backgroundColor:n.backgroundColor},...n.border===void 0?{}:{border:n.border},...n.borderRadius===void 0?{}:{borderRadius:n.borderRadius},...n.boxShadow===void 0?{}:{boxShadow:n.boxShadow},color:a,...t.fontFamily?{fontFamily:t.fontFamily}:{}},spinnerTrackColor:e.buttonsLayout.cardInputBorder??(r?"#374151":"#e5e7eb"),spinnerAccentColor:t.colorPrimary??"#4A49FF",labelColors:{processing:a,success:o.success,error:o.error},noteColor:s?.color??a}}var Dr=require("react/jsx-runtime"),Ta=class extends Gn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function bo(e,t={}){let n=e instanceof Gn.FloPayError?e:void 0,r=n?.statusCode,o=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof r=="number"&&r>=500||n?.code==="vault_capture_timeout"||!n);return new Ta(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:o,...n?.param?{param:n.param}:{},...r===void 0?{}:{statusCode:r}})}function Ac({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:s=null,onReady:c,onComplete:u,onDecline:p,onCancel:h,onValidation:b,onError:I}){let[k,C]=(0,xt.useState)(null),[f,S]=(0,xt.useState)(null),[G,_]=(0,xt.useState)(null),[q,E]=(0,xt.useState)(null),[ne,$]=(0,xt.useState)(null),W=(0,xt.useRef)(!1),ie=(0,xt.useRef)(!1),V=(0,xt.useMemo)(()=>typeof o=="object"?void 0:(0,Gn.resolveTheme)(o),[o]),Be=(0,xt.useMemo)(()=>typeof o=="object"?o:V?Go({appearance:V.appearance,buttonsStyles:V.buttonsLayout,layout:"default"}):null,[V,o]),Ue=(0,xt.useMemo)(()=>ci(V?.buttonsLayout.cardFormContainer,a),[V,a]),X=(0,xt.useMemo)(()=>V?Si(V):void 0,[V]),Ae=(0,xt.useRef)(c),it=(0,xt.useRef)(I),Re=(0,xt.useRef)(u),xe=(0,xt.useRef)(p),ve=(0,xt.useRef)(h),se=(0,xt.useRef)(b),me=(0,xt.useRef)(!1),He=(0,xt.useRef)(!1),st=(0,xt.useRef)(0);return Ae.current=c,it.current=I,Re.current=u,xe.current=p,ve.current=h,se.current=b,(0,xt.useEffect)(()=>{let T=st.current+1;return st.current=T,()=>{queueMicrotask(()=>{st.current===T&&(me.current||He.current||(He.current=!0,We(()=>{ve.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,xt.useEffect)(()=>{let T=!0,ye=new wi.PaymentAPI((0,Gn.resolveBillingApiUrl)(n),{telemetry:r});return C(null),S(null),_(null),me.current=!1,He.current=!1,(async()=>{try{if(!e.trim())throw new Gn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Gn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let le=await ye.getUnifiedCheckoutSession(e,t);if(!T)return;let F=le.data.session;if(!F||!(0,Gn.isCardSetupCheckoutSession)(F))throw new Gn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Se=F.vault;if(Se?.html?.trim()||(Se=await ye.getVaultCapture(e,t)),!Se.html?.trim())throw new Gn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!T)return;S(Se),C(new wi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(le){if(!T)return;let F=bo(le);me.current=!0,_(F),We(()=>it.current?.(F))}})(),()=>{T=!1,ye.destroy()}},[n,t,e,r]),(0,xt.useEffect)(()=>{if(!k)return;let T=!1;ie.current=!1,W.current=!1;let ye=k.on("submitting",()=>{W.current=!0,$(null),E("processing")}),le=k.on("complete",ce=>{me.current=!0,W.current=!1,E("success"),(async()=>(await new Promise(De=>setTimeout(De,600)),!ie.current&&(ie.current=!0,We(()=>{Re.current?.({status:"succeeded",sessionId:e,...ce.paymentMethod?{paymentMethod:ce.paymentMethod}:{}})}),T||E(null))))()}),F=k.on("decline",ce=>{me.current=!0,W.current=!1,$(ce.message??null),E("error"),We(()=>{xe.current?.({status:"declined",sessionId:e,...ce.declineReason?{reason:ce.declineReason}:{},...ce.message?{message:ce.message}:{}})}),(async()=>(await new Promise(De=>setTimeout(De,400)),T||E(null)))()}),Se=k.on("challenge_dismissed",()=>{E(null)});return()=>{T=!0,ye(),le(),F(),Se()}},[k,e]),G?(0,Dr.jsx)("div",{role:"alert",children:G.message}):!k||!f?.html?(0,Dr.jsx)(Dr.Fragment,{children:s}):(0,Dr.jsxs)(Dr.Fragment,{children:[q&&(0,Dr.jsx)(Ln,{status:q,errorMessage:ne,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...X?{theme:X}:{}}),(0,Dr.jsx)(so,{capture:k,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,theme:Be,containerStyle:Ue,onReady:()=>{We(()=>Ae.current?.())},onValidation:T=>{We(()=>se.current?.(T))},onError:T=>{if(!T)return;W.current&&(W.current=!1,$(T),E("error"),setTimeout(()=>E(null),400));let ye=bo(new Error(T),{code:"card_setup_widget_failed",retryable:!0});We(()=>it.current?.(ye))}})]})}var xc=require("@flopay/js/card-setup"),lo=require("@flopay/shared"),Mc=require("@paypal/paypal-js"),vo=require("react");var Bc=require("react/jsx-runtime");function Fc({clientId:e,environment:t,currency:n,sessionId:r,nonce:o,billingApiUrl:a,telemetry:s,customer:{userId:c,email:u},onSubmitting:p,onConfirmed:h,onFailed:b,onAbandoned:I}){let k=(0,vo.useRef)(null),C=(0,vo.useRef)({onSubmitting:p,onConfirmed:h,onFailed:b,onAbandoned:I});C.current={onSubmitting:p,onConfirmed:h,onFailed:b,onAbandoned:I};let[f]=(0,vo.useState)(()=>Kr().inAppBrowser);return(0,vo.useEffect)(()=>{let S=!0,G,_=new xc.PaymentAPI(a,{telemetry:s}),q={userId:c,email:u};return(async()=>{try{let E=await(0,Mc.loadScript)({clientId:e,currency:n.toUpperCase(),components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),ne=k.current;if(!S||!ne)return;if(!E?.Buttons)throw new lo.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let $=E.Buttons({createVaultSetupToken:async()=>{C.current.onSubmitting();let W=await _.createSessionIntent(r,o,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:lo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(W.provider!=="paypal"||W.providerObjectType!=="setup_token")throw new lo.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return W.providerObjectId},onApprove:async W=>{let ie=W.vaultSetupToken;if(!ie)throw new lo.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let V=await _.processPayment(q.userId,{sessionId:r,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:ie,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:lo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:q});if(!V.ok)throw new lo.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:V.status});S&&C.current.onConfirmed()},onCancel:()=>{S&&C.current.onAbandoned()},onError:W=>{if(!S)return;let{popupBlocked:ie}=ro(W,{inAppBrowser:f,handoffObserved:!1});C.current.onFailed(ie?new Error(no("PayPal",!0,f)):W,{code:ie?"popup_blocked":"paypal_setup_failed",retryable:!0})}});G=()=>$.close(),await $.render(ne)}catch(E){if(!S)return;C.current.onFailed(E,{code:"paypal_unavailable",retryable:!0})}})(),()=>{S=!1,G?.().catch(()=>{}),_.destroy()}},[a,e,n,u,t,f,o,r,s,c]),(0,Bc.jsx)("div",{ref:k,"data-flopay-paypal-setup":""})}var Dc=require("@flopay/js/card-setup"),ki=require("@flopay/shared"),Lr=require("@stripe/react-stripe-js"),Oc=require("@stripe/stripe-js"),lr=require("react");var Or=require("react/jsx-runtime"),Lc={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},xs=new Map;function ep(e){let t=xs.get(e);if(t)return t;let n=(0,Oc.loadStripe)(e).catch(r=>{throw xs.delete(e),r});return xs.set(e,n),n}var tp={night:"night",flat:"flat"};function np(e){return e?{theme:tp[e.theme??"default"]??"stripe",...e.variables?{variables:e.variables}:{},...e.rules?{rules:e.rules}:{}}:void 0}function rp(e){return fo(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function op(e){return e==="paypal"?"PayPal":(0,ki.getStripeMethodDisplayName)(e)}function ap(){return typeof window>"u"?"":window.location.href}function Nc(e){let{publishableKey:t,method:n,currency:r,appearance:o}=e,[a]=(0,lr.useState)(()=>ep(t)),s=(0,lr.useMemo)(()=>{let c=np(o);return{mode:"setup",currency:r.toLowerCase(),paymentMethodTypes:Lc[n]?.types??[n],...c?{appearance:c}:{}}},[o,r,n]);return(0,Or.jsx)(Lr.Elements,{stripe:a,options:s,children:(0,Or.jsx)(ip,{...e})})}function ip({method:e,category:t,sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onSubmitting:s,onConfirmed:c,onDeclined:u,onFailed:p,onValidation:h}){let b=(0,Lr.useStripe)(),I=(0,Lr.useElements)(),[k,C]=(0,lr.useState)(!1),f=(0,lr.useRef)(!1),[S]=(0,lr.useState)(()=>Kr()),[G,_]=(0,lr.useState)(!1),q=(0,lr.useCallback)((W,ie)=>{if(ro(W,{inAppBrowser:S.inAppBrowser,handoffObserved:!1}).popupBlocked){_(!0),p(new Error(no(op(e),!0,S.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}p(ie.message===void 0?W:new Error(ie.message),{code:ie.code,retryable:!0})},[S.inAppBrowser,e,p]),E=(0,lr.useCallback)(async()=>{if(!(!b||!I||f.current)){f.current=!0,C(!0);try{let W=await I.submit();if(W.error){h(W.error.message??null);return}s();let ie=await new Dc.PaymentAPI(o,{telemetry:a}).createSessionIntent(n,r,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(ie.provider!=="stripe"||ie.intentKind!=="setup")throw new ki.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let V=await b.confirmSetup({elements:I,clientSecret:ie.clientSecret,confirmParams:{return_url:ap()},redirect:"if_required"});if(V.error){rp(V.error)?u({...V.error.decline_code||V.error.code?{reason:V.error.decline_code??V.error.code}:{},...V.error.message?{message:V.error.message}:{}}):q(V.error,{code:"payment_method_setup_provider_failed",message:V.error.message??"The payment method could not be saved."});return}c()}catch(W){q(W,{code:"payment_method_setup_failed"})}finally{f.current=!1,C(!1)}}},[o,t,I,e,r,c,u,s,h,q,n,b,a]),ne=Lc[e]?.wallet,$=ne==="paypal"&&Ha(S,"auto",G?"blocked":S.popupCapability)==="redirect";if(t==="wallet"&&ne&&!$){let W={applePay:"never",googlePay:"never",link:"never",paypal:"never",amazonPay:"never"};return W[ne]="auto",(0,Or.jsx)(Lr.ExpressCheckoutElement,{options:{paymentMethods:W},onConfirm:()=>{E()}})}return(0,Or.jsxs)(Or.Fragment,{children:[(0,Or.jsx)(Lr.PaymentElement,{onChange:W=>{W.complete&&h(null)}}),(0,Or.jsx)("button",{type:"button","data-flopay-payment-method-save":e,disabled:!b||!I||k,onClick:()=>{E()},children:"Save payment method"})]})}var Aa=require("@flopay/js/card-setup"),Sn=require("@flopay/shared"),at=ji(require("react"),1);var sp=new Set(["apple_pay","google_pay","link","paypal","amazon_pay"]);function zc(e){let t=e.data.stripe,n=Array.from(new Set(t?.enabledPaymentMethods??[])),r=e.data.paypal,o=r?.publishableKey?{clientId:r.publishableKey,...r.environment?{environment:String(r.environment)}:{}}:null,a=n.filter(s=>s!=="card"&&!(o&&s==="paypal"));return{card:n.includes("card"),stripe:t?.publishableKey&&a.length>0?{publishableKey:t.publishableKey,methods:a}:null,paypal:o}}function Uc(e){return e.card||e.stripe!==null||e.paypal!==null}function qc(e){return sp.has(e)?"wallet":"apm"}var lp=["setup_intent","setup_intent_client_secret","redirect_status"];function Vc(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function jc(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let n of lp)e.searchParams.has(n)&&(e.searchParams.delete(n),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}function $c(e){return e==="card"?{processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED"}:{processingLabel:"SAVING PAYMENT METHOD...",successLabel:"PAYMENT METHOD SAVED",errorLabel:"PAYMENT METHOD NOT SAVED"}}var sn=require("react/jsx-runtime"),cp=15,dp=2e3;function up(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Ms(e){return new Promise(t=>setTimeout(t,e))}async function pp(e,t,n){if(!t.trim())throw new Sn.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!n.trim())throw new Sn.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let r=await e.getUnifiedCheckoutSession(t,n),o=r.data.session;if(!o||!(0,Sn.isCardSetupCheckoutSession)(o))throw new Sn.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let a=zc(r);if(!Uc(a))throw new Sn.FloPayError("FloPay: this setup session advertises no payment method.","validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"});return{session:o,advertisement:a}}async function mp(e,t,n,r){let o=t.vault??null;if(o?.html?.trim()||(o=await e.getVaultCapture(n,r)),!o.html?.trim())throw new Sn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return o}var Ii=class extends at.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(n){this.props.onFailed(n,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function Wc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,theme:s="modern-light",containerStyle:c,loading:u=null,onReady:p,onComplete:h,onDecline:b,onCancel:I,onValidation:k,onError:C}){let[f]=(0,at.useState)(Vc),[S,G]=(0,at.useState)(null),[_,q]=(0,at.useState)(!1),[E,ne]=(0,at.useState)(null),[$,W]=(0,at.useState)(null),[ie,V]=(0,at.useState)(null),[Be,Ue]=(0,at.useState)(null),X=(0,at.useRef)(!1),Ae=(0,at.useRef)(!1),it=(0,at.useRef)(!1),Re=(0,at.useRef)(!1),xe=(0,at.useRef)(0),ve=(0,at.useRef)(0),se=(0,at.useRef)(!1),me=(0,at.useMemo)(()=>typeof s=="object"?void 0:(0,Sn.resolveTheme)(s),[s]),He=(0,at.useMemo)(()=>typeof s=="object"?s:me?Go({appearance:me.appearance,buttonsStyles:me.buttonsLayout,layout:"default"}):null,[me,s]),st=(0,at.useMemo)(()=>ci(me?.buttonsLayout.cardFormContainer,c),[me,c]),T=(0,at.useMemo)(()=>me?Si(me):void 0,[me]),ye=(0,at.useRef)({sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:p,onComplete:h,onDecline:b,onCancel:I,onValidation:k,onError:C});ye.current={sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:p,onComplete:h,onDecline:b,onCancel:I,onValidation:k,onError:C},(0,at.useEffect)(()=>{se.current=!0;let Y=xe.current+1;return xe.current=Y,()=>{se.current=!1,ve.current+=1,queueMicrotask(()=>{xe.current===Y&&(it.current||Re.current||(Re.current=!0,We(()=>{ye.current.onCancel?.({status:"cancelled",sessionId:n})})))})}},[n]);let le=(0,at.useCallback)((Y,J)=>{it.current=!0,X.current=!1,Ue({status:"success",wording:Y,message:null}),(async()=>(await Ms(600),!Ae.current&&(Ae.current=!0,We(()=>{ye.current.onComplete?.({status:"succeeded",sessionId:ye.current.sessionId,...J?{paymentMethod:J}:{}})}),se.current&&Ue(null))))()},[]),F=(0,at.useCallback)((Y,J)=>{it.current=!0,X.current=!1,Ue({status:"error",wording:Y,message:J.message??null}),We(()=>{ye.current.onDecline?.({status:"declined",sessionId:ye.current.sessionId,...J.reason?{reason:J.reason}:{},...J.message?{message:J.message}:{}})}),(async()=>(await Ms(400),se.current&&Ue(null)))()},[]),Se=(0,at.useCallback)((Y,J)=>{X.current?(X.current=!1,Ue({status:"error",wording:Y,message:J.message}),setTimeout(()=>{se.current&&Ue(null)},400)):Ue(null),We(()=>ye.current.onError?.(J))},[]),ce=(0,at.useCallback)(async Y=>{let J=ve.current+1;ve.current=J;let mt=()=>!se.current||J!==ve.current;X.current=!0,Ue({status:"processing",wording:"payment_method",message:null});let gt=new Aa.PaymentAPI((0,Sn.resolveBillingApiUrl)(ye.current.billingApiUrl),{telemetry:ye.current.telemetry});try{for(let Ie=0;Ie<cp;Ie+=1){if((Ie>0||Y.waitFirst)&&await Ms(dp),mt())return;let ft=await gt.getUnifiedCheckoutSession(ye.current.sessionId,ye.current.nonce);if(mt())return;let U=ft.data.session?.status;if(U==="complete"){q(!0),le("payment_method");return}if(U==="expired")throw new Sn.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Sn.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(Ie){if(mt())return;let ft=Ie instanceof Sn.FloPayError&&Ie.code==="payment_method_setup_unverified";Se("payment_method",bo(Ie,ft?{retryable:!0}:{}))}finally{gt.destroy()}},[Se,le]);(0,at.useEffect)(()=>{let Y=!0,J=new Aa.PaymentAPI((0,Sn.resolveBillingApiUrl)(o),{telemetry:a});return G(null),q(!1),ne(null),W(null),V(null),it.current=!1,Re.current=!1,Ae.current=!1,(async()=>{try{let{session:mt,advertisement:gt}=await pp(J,n,r);if(!Y)return;let Ie={advertisement:gt,currency:mt.currency,customer:up(mt)};if(f){if(jc(),mt.status==="complete"){q(!0),G(Ie),le("payment_method");return}f.failed?F("payment_method",{reason:"redirect_failed"}):ce({waitFirst:!0})}let ft=gt.card?await mp(J,mt,n,r):null;if(!Y)return;G(Ie),ft&&(W(ft),ne(new Aa.PciVaultCardCapture({sessionId:n,operation:"card_setup",telemetry:a})))}catch(mt){if(!Y)return;let gt=bo(mt);it.current=!0,V(gt),We(()=>ye.current.onError?.(gt))}})(),()=>{Y=!1,J.destroy()}},[o,r,f,F,le,n,a,ce]),(0,at.useEffect)(()=>{if(!E)return;X.current=!1;let Y=E.on("submitting",()=>{X.current=!0,Ue({status:"processing",wording:"card",message:null})}),J=E.on("complete",Ie=>{le("card",Ie.paymentMethod)}),mt=E.on("decline",Ie=>{F("card",{...Ie.declineReason?{reason:Ie.declineReason}:{},...Ie.message?{message:Ie.message}:{}})}),gt=E.on("challenge_dismissed",()=>{Ue(null)});return()=>{Y(),J(),mt(),gt()}},[E,F,le]);let De=(0,at.useMemo)(()=>({onSubmitting:()=>{X.current=!0,Ue({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{ce({waitFirst:!1})},onDeclined:Y=>F("payment_method",Y),onFailed:(Y,J)=>{Se("payment_method",bo(Y,J))},onValidation:Y=>{We(()=>ye.current.onValidation?.(Y))},onAbandoned:()=>{X.current=!1,Ue(null)}}),[F,Se,ce]),re=Be?(0,sn.jsx)(Ln,{status:Be.status,errorMessage:Be.message,...$c(Be.wording),successNote:null,...T?{theme:T}:{}}):null;if(ie)return(0,sn.jsx)("div",{role:"alert",children:ie.message});if(!S||_)return(0,sn.jsxs)(sn.Fragment,{children:[re,S?null:u]});let{advertisement:$e,currency:dt,customer:Me}=S,Oe=(0,Sn.resolveBillingApiUrl)(o),ut=a===void 0?{}:{telemetry:a};return(0,sn.jsxs)(sn.Fragment,{children:[re,$e.card&&E&&$?.html?(0,sn.jsx)("div",{"data-flopay-payment-method":"card",children:(0,sn.jsx)(so,{capture:E,html:$.html,messageToken:$.messageToken,expectedOrigin:$.expectedOrigin,theme:He,containerStyle:st,onReady:()=>{We(()=>ye.current.onReady?.())},onValidation:Y=>{We(()=>ye.current.onValidation?.(Y))},onError:Y=>{Y&&Se("card",bo(new Error(Y),{code:"card_setup_widget_failed",retryable:!0}))}})}):null,$e.stripe?.methods.map(Y=>(0,sn.jsx)("div",{"data-flopay-payment-method":Y,children:(0,sn.jsx)(Ii,{onFailed:De.onFailed,children:(0,sn.jsx)(at.Suspense,{fallback:null,children:(0,sn.jsx)(e,{method:Y,category:qc(Y),publishableKey:$e.stripe?.publishableKey??"",currency:dt,sessionId:n,nonce:r,billingApiUrl:Oe,...ut,...me?{appearance:me.appearance}:{},...De})})})},Y)),$e.paypal?(0,sn.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,sn.jsx)(Ii,{onFailed:De.onFailed,children:(0,sn.jsx)(at.Suspense,{fallback:null,children:(0,sn.jsx)(t,{clientId:$e.paypal.clientId,...$e.paypal.environment?{environment:$e.paypal.environment}:{},currency:dt,sessionId:n,nonce:r,billingApiUrl:Oe,customer:Me,...ut,...De})})})}):null]})}var Kc=require("react/jsx-runtime"),yp={StripeSetupMethod:Nc,PayPalSetupMethod:Fc};function Hc(e){return(0,Kc.jsx)(Wc,{...e,branches:yp})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});