@flopay/react 1.11.4 → 1.11.5
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/card-setup-entry.cjs +2 -2
- package/dist/card-setup-entry.mjs +1 -1
- package/dist/chunk-52RFSQJ7.mjs +1 -0
- package/dist/chunk-AW5LOT2K.mjs +6 -0
- package/dist/index.cjs +9 -9
- package/dist/index.d.cts +8 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.mjs +6 -6
- package/dist/payment-method-setup-entry.cjs +3 -3
- package/dist/payment-method-setup-entry.mjs +1 -1
- package/package.json +3 -3
- package/dist/chunk-AZRGKPW7.mjs +0 -6
- package/dist/chunk-LIYRDFMO.mjs +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var Tu=Object.create;var Za=Object.defineProperty;var Au=Object.getOwnPropertyDescriptor;var Mu=Object.getOwnPropertyNames;var xu=Object.getPrototypeOf,Fu=Object.prototype.hasOwnProperty;var Bu=(e,t)=>{for(var n in t)Za(e,n,{get:t[n],enumerable:!0})},Fl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Mu(t))!Fu.call(e,o)&&o!==n&&Za(e,o,{get:()=>t[o],enumerable:!(r=Au(t,o))||r.enumerable});return e};var ls=(e,t,n)=>(n=e!=null?Tu(xu(e)):{},Fl(t||!e||!e.__esModule?Za(n,"default",{value:e,enumerable:!0}):n,e)),Du=e=>Fl(Za({},"__esModule",{value:!0}),e);var zp={};Bu(zp,{DirectPayPalButton:()=>wa,FloPayAutomaticPaymentButton:()=>$c,FloPayCardSetup:()=>Hc,FloPayCardSetupError:()=>Ua,FloPayCheckout:()=>Oi,FloPayPaymentMethodSetup:()=>cu,FloPayProvider:()=>Ra,SplitCardForm:()=>xi,VaultCardFields:()=>lo,dropThirdPartyOnlyError:()=>du.dropThirdPartyOnlyError,useCheckout:()=>Hl,useFloPay:()=>Hr,usePayPalFloPay:()=>ti});module.exports=Du(zp);var du=require("@flopay/shared");var Li=require("@flopay/js"),lr=require("@flopay/shared"),ut=require("react");var Vt=require("react/jsx-runtime");function Ou(){return(0,Vt.jsxs)(Vt.Fragment,{children:[(0,Vt.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,Vt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Vt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Vt.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,Vt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Lu(){return(0,Vt.jsx)(Vt.Fragment,{children:"Go back"})}function Nu(){return(0,Vt.jsx)(Vt.Fragment,{children:"Secure card checkout"})}function Do(e){return e!==void 0&&(e===""||e===null||e===!1)}function Oo({content:e}){return(0,Vt.jsx)(Vt.Fragment,{children:e===void 0?(0,Vt.jsx)(Ou,{}):e})}function Lo({content:e}){return(0,Vt.jsx)(Vt.Fragment,{children:e===void 0?(0,Vt.jsx)(Lu,{}):e})}function ha({content:e}){return(0,Vt.jsx)(Vt.Fragment,{children:e===void 0?(0,Vt.jsx)(Nu,{}):e})}var Rt=require("@flopay/shared"),Uu="Checkout is temporarily unavailable. Please try again later.";function cs(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Rt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function zu(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 Bl(){return new Rt.FloPayError(Uu,"api_error",{code:"CheckoutInitializationFailed"})}function us(e){return!!e?.gateways?.worldpayCorporateGateway}function Qr(e){return e?.status==="open"&&us(e)}function Dl(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")||Qr(r))||t&&e?.data.paypal?.publishableKey)}function Ol(e,t){if(t&&(!(e instanceof Rt.FloPayError)||e.type==="authentication_error"))return cs(e);if(!(e instanceof Rt.FloPayError&&zu(e))){if(!t&&!(e instanceof Rt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,Rt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Rt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Rt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function No(e,t,n,r={}){let o;return(a={})=>{if(o!==void 0)return o;let i={...r,...a,email:a.email?.trim()||r.email?.trim()},c=(0,Rt.isCardHolderNamePlaceholder)(i.firstName,i.lastName);if(!(0,Rt.isValidEmail)(i.email))return Promise.reject(new Rt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[u,g]of Object.entries(i)){if(c&&u.endsWith("Name")||typeof g!="string")continue;let b=g.trim();b&&(p[u]=b)}return o=e.claimCheckoutSession(t,n,{accountData:p}),o.catch(()=>{}),o}}function Ll(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 ds(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Nl(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,i)=>a+(i.overrideAmount??i.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,i)=>({uuid:`synthetic-${a.type??"item"}-${i}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function ho(e){if((0,Rt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function ps(e,t){return t?{...e,...t}:e}function mn(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,i=typeof t=="string"?void 0:t.sessionId;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{},...i?{sessionId:i}:{}}}function eo(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var qu=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function to(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of qu)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 no(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 Ul(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Qa(e){let t=Ul(e);return new Rt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ei(e){return e instanceof Rt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Uo(e){return Ul(e)?new Rt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Rt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Rt.FloPayError(Rt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function ba(e,t){return e==="processing"||(0,Rt.isMoneySettledOutcome)(e,t)}function zl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function ql(e,t){let n=e;if((0,Rt.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:i}=await n.retrieveSetupIntent(t);if(i)throw new Rt.FloPayError(i.message??"Failed to retrieve setup intent.","api_error",{...i.code?{code:i.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new Rt.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}var Vu=["apple_pay","google_pay"];function Vl(e,t="automatic",n){let r=(0,Rt.resolveSetupFutureUsage)(n,Vu,"wallet");return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],...r?{setupFutureUsage:r}:{}}}var ju=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function ms(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:ju.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Pa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Xr=require("@flopay/js"),ot=require("@flopay/shared"),R=ls(require("react"),1);var ys=require("react"),or=(0,ys.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Pr=(0,ys.createContext)({session:null,loading:!1,error:null});var si=require("@flopay/js"),Ht=require("@flopay/shared"),Jl=require("@paypal/paypal-js"),M=require("react");var jl=require("@flopay/shared"),vr=require("react"),Wr=require("react/jsx-runtime");function Un(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),i=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...i||t?{lastName:i??""}:{}}}function zo(){let[e,t]=(0,vr.useState)(null),n=(0,vr.useRef)(null),r=(0,vr.useRef)(0),o=(0,vr.useCallback)((i,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:i,identity:c}),new Promise(p=>{n.current=p})),[]),a=(0,vr.useCallback)(i=>{let c=n.current;n.current=null,t(null),c?.(i)},[]);return(0,vr.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function qo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[i,c]=(0,vr.useState)(e.email?.trim()??""),p=(0,jl.isValidEmail)(i.trim());return(0,Wr.jsxs)("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,Wr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Wr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Wr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:i,onChange:u=>c(u.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Wr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Wr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Wr.jsxs)("button",{type:"button",disabled:!p||o,onClick:()=>{n(Un({...e,email:i.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var $u=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),Wu=["https://www.paypal.com","https://www.sandbox.paypal.com"];function ro(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 $l(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 bo(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 bo(t.code)??bo(t.type)??bo(t.name)}function Vo(e){if(!(typeof e!="object"||e===null))return bo(e.decline_code)}function Po(e){return typeof e!="object"||e===null?!1:bo(e.type)?.toLowerCase()==="card_error"||Vo(e)!==void 0}function Hu(e){let t=$l(e)?.toLowerCase()??"",n=Mr(e)?.toLowerCase()??"";return $u.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 fs(e){if(Mr(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=$l(e)??"";return n.includes("No ack for postMessage init()")&&Wu.some(r=>n.includes(r))&&n.includes("10000ms")}function oo(e,t){if(Po(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=Hu(e)||t.inAppBrowser&&!t.handoffObserved&&fs(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function ao(e){return oo(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}var Wl=require("@flopay/shared"),va=require("react");function Hr(){return(0,va.useContext)(or).flopay}function ti(){return(0,va.useContext)(or).paypalFlopay??null}function Hl(){return(0,va.useContext)(Pr)}function Kl(){return(0,va.useContext)(or).billingApiUrl||(0,Wl.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 ni(e,t,n=e.popupCapability){return e.inAppBrowser||n==="blocked"||t==="prefer_redirect"?"redirect":"popup"}function ri(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var Gl=require("@flopay/shared"),Co=require("react");function Je(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}var oi=require("react"),vo=typeof window>"u"?oi.useEffect:oi.useLayoutEffect;var Ku={"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 Gu(e){return e==="stripe"||e==="paypal"?e:void 0}function Yu(e){let t=Gu(e.provider),n={schemaVersion:Gl.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Ku[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 gs=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function jo(e,t){let n=(0,Co.useRef)(e);n.current=e;let r=(0,Co.useRef)(new Set),o=(0,Co.useRef)(t),a=(0,Co.useRef)(t);return vo(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,Co.useCallback)(i=>{if(a.current!==t)return;let c=Yu(i);if(c){if(gs.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}Je(()=>n.current?.(c))}},[t])}var Yl=require("react"),Ca=(0,Yl.createContext)(null);function ai(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Xu=Symbol.for("@flopay/js.telemetry.bridge.v1"),Ju=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Zu(){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 Qu(e){let t=Zu(),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 ii(e){let t=globalThis[Ju];return Qu(t?.(e)??{})}function yn(e){if(e)return e[Xu]}var on=require("react");function Sa(e,t){let n=(0,on.useRef)(0),r=(0,on.useRef)(null),o=(0,on.useRef)(null),a=(0,on.useRef)(e),i=(0,on.useRef)(t?.onHandoffObserved),c=(0,on.useRef)(t?.defersMissingTerminal),p=(0,on.useRef)(t?.onMissingTerminalDeferred);(0,on.useEffect)(()=>{a.current=e,i.current=t?.onHandoffObserved,c.current=t?.defersMissingTerminal,p.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let u=(0,on.useCallback)((P=o.current)=>{P?.timer&&(clearTimeout(P.timer),P.timer=null)},[]),g=(0,on.useCallback)(P=>{u();let w=n.current+1;return n.current=w,r.current=null,o.current={generation:w,method:P,timer:null,yieldedControl:!1},w},[u]),b=(0,on.useCallback)(P=>{let w=o.current;return P!==void 0&&w?.generation!==P?!1:(u(w),o.current=null,(P===void 0||r.current===P)&&(r.current=null),!0)},[u]),T=(0,on.useCallback)(P=>{let w=o.current,K=P??w?.generation??n.current;(P===void 0||w?.generation===P)&&(u(w),o.current=null),r.current=K},[u]),I=(0,on.useCallback)(P=>r.current===(P??n.current),[]),S=(0,on.useCallback)(P=>o.current?.generation===P&&r.current!==P,[]),A=(0,on.useCallback)(()=>{let P=o.current;P&&(u(P),!P.yieldedControl&&(P.yieldedControl=!0,i.current?.(P.method)))},[u]),_=(0,on.useCallback)(()=>{let P=o.current;!P?.yieldedControl||document.visibilityState!=="visible"||(u(P),P.timer=setTimeout(()=>{if(P.timer=null,o.current?.generation===P.generation){if(c.current?.(P.method)){p.current?.(P.method,P.generation);return}o.current=null,r.current=P.generation,a.current(P.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},600))},[u]);return(0,on.useEffect)(()=>{let P=()=>{document.visibilityState==="visible"?_():A()};return document.addEventListener("visibilitychange",P),window.addEventListener("blur",A),window.addEventListener("focus",_),()=>{document.removeEventListener("visibilitychange",P),window.removeEventListener("blur",A),window.removeEventListener("focus",_),u()}},[u,A,_]),{startAttempt:g,finishAttempt:b,invalidateAttempt:T,isAttemptInvalidated:I,isAttemptCurrent:S,generationRef:n}}var ar=require("react/jsx-runtime"),li=45,ed=1e3,td=11e3,nd={width:"100%",minHeight:li,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"},rd={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 od(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:rd[e.kind]??null}}function Xl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":fs(t)?"paypal_init_timeout":"paypal_init_failure"}function ad(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 id(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Zl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:i,environment:c,currency:p,isSubscription:u,providerObjectType:g,approvalPresentation:b,onTokenizedBody:T,onComplete:I,onErrorChange:S,onDecline:A,onTechnicalFailure:_,isProcessing:P=!1,onLoadStateChange:w,onInitializationStateChange:K,allowAutomaticRetry:k=!0,onButtonClick:ge,runBeforeButtonClick:z,session:X,existingOrderId:Se,telemetry:ae,telemetryContext:De,onInstrument:Ze,debug:le=!1}){let Ee=Hr(),We=jo(Ze,e),Re=(0,M.useMemo)(()=>{if(Ee)return null;let v=ii({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ht.SDK_VERSION,enabled:ae!==!1});return v.setCheckoutContext(De??{}),v.beginCheckout(De??{}),v},[n,Ee,ae,De?.checkoutMode,De?.layout]),Ie=(0,M.useMemo)(()=>yn(Ee),[Ee]);(0,M.useEffect)(()=>()=>{Re&&Re.flush().catch(()=>{}).finally(()=>Re.destroy())},[Re]);let _e=(0,M.useMemo)(()=>({error:v=>{Ie?Ie.error(v):Re?.error(v),We({class:"technical_error",errorCode:v.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":v.errorCode,requestCategory:v.requestCategory,provider:v.provider})},log:v=>{Ie?Ie.log(v):Re?.log(v),We({class:"lifecycle",name:v.name,provider:v.provider})},performance:v=>{Ie?Ie.performance(v):Re?.performance(v)},terminal:v=>{Ie?Ie.terminal(v):Re?.terminal(v)},startTiming:()=>Ie?.now()??Re?.now()??0,elapsed:v=>Ie?.elapsed(v)??Math.max(0,(Re?.now()??v)-v)}),[We,Ie,Re]),ce=(0,M.useRef)(null),ue=(0,M.useRef)(0),Pe=(0,M.useRef)(null),Ae=(0,M.useRef)(null),J=(0,M.useRef)(null),ee=(0,M.useContext)(Ca),he=(0,M.useRef)(null);he.current||(he.current=ai());let U=ee??he.current,we=(0,M.useRef)(null),ie=(0,M.useRef)(!1),[Te,te]=(0,M.useState)(!1),[it,He]=(0,M.useState)(!1),[je,at]=(0,M.useState)(0),Ke=(0,M.useRef)(0),[st,$e]=(0,M.useState)(!1),vt=(0,M.useRef)(!1),Lt=(0,M.useRef)(!1),[ht,Tt]=(0,M.useState)(!1),[V,be]=(0,M.useState)(!1),{request:Qe,collect:Z,finish:Ne}=zo(),bt=(0,M.useRef)({sessionId:e,required:!(0,Ht.isValidEmail)(r?.trim()||X?.customer?.email?.trim())});bt.current.sessionId!==e&&(bt.current={sessionId:e,required:!(0,Ht.isValidEmail)(r?.trim()||X?.customer?.email?.trim())});let Ye=bt.current.required,_t=(0,M.useMemo)(()=>n.replace(/\/+$/,""),[n]),h=X?.gateways?.paypal?.providerObjectType??g,C=h??(u?"subscription":"order"),[Y]=(0,M.useState)(Kr),H=X?.gateways?.paypal?.approvalPresentation??b,ve=ri(Y,H==="app_switch"?"app_switch":void 0,C),x=h==="order"||h==="setup_token",B=(0,M.useMemo)(()=>JSON.stringify([_t,i,p,c??"",C,x,ve,e,Se??""]),[_t,i,p,c,Se,C,x,ve,e]),de=(0,M.useRef)(B),D=de.current!==B,Me=(0,M.useRef)(le),lt=(0,M.useRef)(null),[yt,Ct]=(0,M.useState)([]),Be=(0,M.useCallback)(v=>{Me.current&&Ct(et=>[...et,`${new Date().toISOString().slice(11,23)} ${v}`])},[]);(0,M.useEffect)(()=>{Me.current=le,le&&Be("debug:enabled"),lt.current?.setEnabled(le)},[Be,le]);let Tn=(0,M.useRef)(T),Vn=(0,M.useRef)(I),gn=(0,M.useRef)(S),jt=(0,M.useRef)(A),jn=(0,M.useRef)(_),$n=(0,M.useRef)(ge),vn=(0,M.useRef)(w),Dt=(0,M.useRef)(K),dt=(0,M.useRef)(a),rt=(0,M.useRef)(z),An=(0,M.useRef)(X),Mt=(0,M.useRef)(r),Wn=(0,M.useRef)(o),hn=(0,M.useRef)(t),$t=(0,M.useRef)(null),en=(0,M.useRef)(new Map),cr=(0,M.useRef)(new Map),Qn=(0,M.useRef)(!1);(0,M.useEffect)(()=>(Qn.current=!0,()=>{Qn.current=!1}),[]),(0,M.useEffect)(()=>{Tn.current=T},[T]),(0,M.useEffect)(()=>{dt.current=a},[a]),(0,M.useEffect)(()=>{Vn.current=I},[I]),(0,M.useEffect)(()=>{gn.current=S},[S]),(0,M.useEffect)(()=>{jt.current=A},[A]),(0,M.useEffect)(()=>{jn.current=_},[_]),(0,M.useEffect)(()=>{$n.current=ge},[ge]),(0,M.useEffect)(()=>{vn.current=w},[w]),(0,M.useEffect)(()=>{Dt.current=K},[K]),(0,M.useEffect)(()=>{rt.current=z},[z]),(0,M.useEffect)(()=>{An.current=X},[X]),(0,M.useEffect)(()=>{Mt.current=r},[r]),(0,M.useEffect)(()=>{Wn.current=o},[o]),(0,M.useEffect)(()=>{hn.current=t},[t]),(0,M.useEffect)(()=>{Ke.current=je},[je]),(0,M.useEffect)(()=>{st&&we.current?.focus()},[st,je]);let tn=(0,M.useCallback)(()=>{window.setTimeout(()=>{we.current?.focus()},0)},[]),xt=(0,M.useCallback)(()=>{te(!1),at(v=>v+1)},[]),nn=(0,M.useCallback)(()=>{$e(!1),(ce.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ce.current)?.focus?.()},[]);(0,M.useEffect)(()=>{!Te||!ie.current||(ie.current=!1,nn())},[nn,Te,je]);let sn=(0,M.useCallback)((v,et)=>{let pe=et?.popupBlocked??ao(v);pe&&U.markBlocked();let Cn=ro("PayPal",pe,Y.inAppBrowser),Hn=jn.current;if(Hn){let Gt=pe&&Y.inAppBrowser?new Ht.FloPayError(Cn,"api_error",{code:et?.code??"paypal_popup_blocked"}):v;Hn("paypal",Gt,et);return}gn.current?.(Cn)},[U,Y.inAppBrowser]),Nt=(0,M.useCallback)(v=>{let et=Pe.current,pe=Ae.current;et===null||!pe||(_e.log({...pe,popupCapability:U.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:v}),_e.performance({...pe,popupCapability:U.current(),stage:"overlay_return",durationMs:_e.elapsed(et),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:v}),Pe.current=null)},[U,_e]),cn=(0,M.useCallback)((v,et,pe)=>{let Cn=Ae.current;Nt("overlay_timeout"),Cn&&_e.error({...Cn,popupCapability:U.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),sn(et,{...pe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ve,terminalReason:"overlay_timeout"}),$e(!0),xt(),tn()},[Nt,tn,sn,U,ve,xt,_e]),zt=(0,M.useCallback)(()=>{U.markAvailable();let v=Ae.current;v&&(J.current=v.attempt,_e.log({...v,popupCapability:U.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[U,_e]),{finishAttempt:ln,generationRef:Ut,invalidateAttempt:me,isAttemptCurrent:ur,isAttemptInvalidated:dr,startAttempt:pr}=Sa(cn,{onHandoffObserved:zt}),rn=(0,M.useCallback)(()=>($e(!1),pr("paypal")),[pr]),Mn=(0,M.useCallback)(v=>{me(v?.generation),v?.showRetry&&$e(!0),v?.remount&&xt(),v?.focus!==!1&&tn()},[tn,me,xt]),wn=v=>{let et=$t.current;return et&&cr.current.set(v,et),v};(0,M.useEffect)(()=>{de.current!==B&&(de.current=B,vt.current=!1,Lt.current=!1,te(!1),He(!1),Tt(!1),Dt.current?.("loading"))},[B]),(0,M.useEffect)(()=>{Je(()=>vn.current?.(Te&&!ht))},[Te,ht]);let Oe=(0,Ht.normalizeGatewayEnvironment)(c);(0,M.useEffect)(()=>{let v={attempt:Ut.current+1,inAppBrowser:Y.inAppBrowser,appFamily:Y.appFamily,popupCapability:U.current(),presentationMode:ve},et=()=>({...Ae.current??v,popupCapability:U.current()}),pe={error:f=>_e.error({...f,...et()}),log:f=>_e.log({...f,...et()}),performance:f=>_e.performance({...f,...et()}),terminal:f=>_e.terminal({...f,...et()}),startTiming:_e.startTiming,elapsed:_e.elapsed},Cn=i?`${i.slice(0,6)}\u2026(len ${i.length})`:"(empty)",Hn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Be(`mount clientId=${Cn} env=${c??"(unset)"}\u2192${Oe??"live"} ccy=${p} sub=${u}`),Be(`ua=${Hn.slice(0,80)}${Hn.length>80?"\u2026":""}`),!i){Be("FAIL: clientId empty \u2014 gateway misconfigured"),Tt(!0),pe.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!ce.current){Be("FAIL: containerRef not attached");return}ue.current=pe.startTiming(),pe.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Gt=!1,xn=!1,ft=()=>Gt||xn,mr,uo=!1,Ft=()=>{mr=(0,Ht.generateIdempotencyKey)(),mr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),uo=!0},Fn=null,wr=!1,er=null,Yt=!1,yr=()=>{!er||Yt||(Yt=!0,er.close().catch(()=>{}))},Bn=!1,Or=!1,Dn=ce.current,kr=null,Rr=null,Lr=[],Kn=null,tr=!1,Nr=!1,Ot=null,kn=f=>{if(!f||typeof f.getBoundingClientRect!="function")return"(no rect)";let m=f.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},nr=f=>{if(!f)return"(empty)";try{let m=new URL(f,typeof window>"u"?"https://localhost":window.location.href),N=m.pathname.toLowerCase();return N.includes("checkcaptcha")||N.includes("captcha")?`CAPTCHA(${m.host}${N})`:N.includes("risk")||N.includes("challenge")?`RISK(${m.host}${N})`:N.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${N}`.slice(0,100)}catch{return f.slice(0,80)}},Ur=f=>{let m=f.getAttribute("src"),N=f.getAttribute("srcdoc"),W=f.getAttribute("name"),Ce=f.getAttribute("sandbox"),xe=[];return m&&xe.push(`src=${nr(m)}`),N&&xe.push(`srcdoc[${N.length}ch]`),!m&&!N&&xe.push("src=(empty) srcdoc=(empty)"),W&&xe.push(`name=${W.slice(0,40)}`),Ce!==null&&xe.push(`sandbox="${Ce.slice(0,40)}"`),xe.join(" ")},zr=f=>{if(!(f instanceof HTMLIFrameElement))return"";try{let m=f.contentDocument;if(!m)return"cd=null";let N=m.body?.children.length??0,W=m.body?.innerHTML.length??0,Ce=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${N}children,${W}ch] head[${Ce}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},ct=[],un=f=>{if(ft())return;let m=f.message??String(f.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(Be(`window:error ${m.slice(0,140)}`),ct.push(m))},dn=f=>{if(ft())return;let m=f.reason instanceof Error?f.reason.message:String(f.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(Be(`window:rejection ${m.slice(0,140)}`),ct.push(m))},Rn={value:0},po=()=>{kr?.disconnect(),kr=null,Rr?.disconnect(),Rr=null;for(let f of Lr.splice(0))clearTimeout(f);Nr=!1,tr&&typeof window<"u"&&(window.removeEventListener("error",un),window.removeEventListener("unhandledrejection",dn)),tr=!1},_r=()=>{if(!(tr||ft()||Bn)){if(tr=!0,ct.length=0,Rn.value=0,typeof window<"u"&&(window.addEventListener("error",un),window.addEventListener("unhandledrejection",dn)),typeof PerformanceObserver<"u")try{Rr=new PerformanceObserver(f=>{if(!ft())for(let m of f.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;Rn.value+=1;let N=Math.round(m.duration);Be(`net ${N}ms ${m.name.slice(0,90)}`)}}),Rr.observe({type:"resource",buffered:!0})}catch{}Ot?.()}},Zr=()=>{Kn&&(clearTimeout(Kn),Kn=null)},_n=()=>{po(),Zr()},pn={setEnabled:f=>{f?_r():po()}};lt.current=pn,Me.current&&_r();let qr=f=>{if(!f)return!1;let m=f.toLowerCase();return m.includes("zoid destroyed")||m.includes("destroyed all components")||m.includes("window closed")||m.includes("detected container element removed")},On=f=>{if(ft()||qr(f))return;let m=to(f)??f;Je(()=>gn.current?.(m))},L=(f,m)=>{if(Gt||wr)return;wr=!0,xn=!0,_n(),yr();let N=od({kind:f,generationActive:!0,automaticRetryAllowed:k,automaticRetryUsed:vt.current});if(N.action==="retry"){vt.current=!0,te(!1),be(!1),He(!0),Dt.current?.("retrying"),Fn=setTimeout(()=>{Gt||at(W=>W+1)},ed);return}if(te(!1),be(!1),He(!1),Tt(!0),N.action!=="ignore"){if(Dt.current?.("exhausted"),N.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",m);return}if(N.report){let W=oo({code:Xl(f,m),message:m},{inAppBrowser:Y.inAppBrowser,handoffObserved:!1});W.popupBlocked&&U.markBlocked(),pe.error({errorCode:W.popupBlocked?W.errorCode:N.report.errorCode,stage:N.report.stage,operationOutcome:N.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:W.terminalReason})}Lt.current||(Lt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Xl(f,m)))}};Tt(!1);let q=async(f,m=$t.current)=>{if(ft())return;let N=m?.sessionId??e;if(Tn.current){await Tn.current(f,{sessionId:N,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let W=pe.startTiming();pe.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Ce=()=>{pe.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"processing",durationMs:pe.elapsed(W),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let xe=An.current,tt=m?.accountPatch?.email??Mt.current,Pt=m?.accountPatch?.userId??xe?.customer?.id??xe?.accountData?.userId??"",Le=m?.accountPatch?.firstName??xe?.customer?.firstName??xe?.accountData?.firstName,F=m?.accountPatch?.lastName??xe?.customer?.lastName??xe?.accountData?.lastName,Fe=await new si.PaymentAPI(_t,{telemetry:!1}).processPayment(Pt,{sessionId:N,nonce:m?.nonce??hn.current,paymentMethodCategory:"paypal",tokenizedData:f,accountData:{userId:Pt,email:tt??xe?.customer?.email??"",...Le?{firstName:Le}:{},...F?{lastName:F}:{},country:m?.accountPatch?.country??xe?.customer?.country??xe?.accountData?.country??void 0,zip:m?.accountPatch?.zip??xe?.customer?.zip??xe?.accountData?.zip??void 0}});if(Fe.ok){if(xn||Gt&&Qn.current)return;Ce(),pe.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Je(()=>Vn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ft())return;let ke=await Fe.json().catch(()=>null),G=ke?.message??"PayPal payment failed.",ye=to(G)??G;Ce(),Fe.status===400&&(typeof ke?.declineCode=="string"||!Array.isArray(ke?.fields))?pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Fe.status===400||Fe.status===422?pe.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):pe.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:id(Fe.status),failureCategory:Fe.status>=500?"server_error":void 0}),On(ye),Je(()=>jt.current?.(mn("paypal",ye,{code:ke?.code,declineCode:ke?.declineCode})));return}catch(xe){if(ft())return;Ce(),pe.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let tt=xe instanceof Error?xe.message:"PayPal payment failed.",Pt=to(tt)??tt;On(Pt),Je(()=>jt.current?.(mn("paypal",Pt)));return}},re=()=>new Ht.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),$=f=>ft()?Promise.reject(re()):Promise.resolve(f),gt=async f=>{if(ft())throw re();uo||Ft();let m=$t.current,N=m?.sessionId??e,W=m?.nonce??hn.current;pe.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Ce;try{Ce=await new si.PaymentAPI(_t,{telemetry:!1}).createSessionIntent(N,W??"",x?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Ht.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:C==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:mr})}catch(xe){throw pe.error({...(0,Ht.classifyTelemetryFailure)(xe,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),xe}if(ft())throw re();if(Ce.provider!=="paypal"||Ce.providerObjectType!==C)throw new Error(f);return pe.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Ce.providerObjectId},Et=(f,m)=>{let N=m?.nonce??hn.current;if(!N)return;let W=m?.sessionId??e,Ce=Vo(f)??Mr(f)??"provider_declined";new si.PaymentAPI(_t,{telemetry:!1}).reportSessionIntentDecline(W,N,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ce}).catch(()=>{})},se=je;Be("loadScript:scheduled (deferred 1 tick)");let Xe=null,Q=setTimeout(()=>{if(Gt){Be("loadScript:skipped (cancelled before defer ran)");return}Be("loadScript:start");let f=Oe==="live"?"production":Oe,m={};C==="subscription"?m={intent:"subscription",vault:!0}:C==="order"&&(m={intent:"capture"}),Xe=(0,Jl.loadScript)({clientId:i,currency:p,...m,...f?{environment:f}:{},...f==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let N=!1;Xe.then(W=>{if(N=!0,Be(`loadScript:resolved inactive=${ft()} ns=${!!W} buttons=${!!W?.Buttons}`),ft())return;if(!W?.Buttons){Be("FAIL: namespace missing Buttons factory"),L("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}pe.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"provider_ready",durationMs:pe.elapsed(ue.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),pe.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Ce=async(Fe,ke)=>{if(ft()||Ke.current!==se)return;let G=Fe.vaultSetupToken??Fe.subscriptionID??Fe.orderID??"",ye=G?cr.current.get(G):en.current.get(se);if(!(!ye||!ur(ye.generation))&&ln(ye.generation)){cr.current.delete(G),en.current.delete(ye.surfaceKey),Nt("approved");try{if(be(!0),Je(()=>gn.current?.(null)),!G)throw new Ht.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ne=An.current,wt=ho(Wn.current??[ne?.customer?.firstName,ne?.customer?.lastName].filter(Boolean).join(" ")),Ge=Un({email:ye.accountPatch?.email?.trim()||Mt.current?.trim()||ne?.customer?.email?.trim(),firstName:ye.accountPatch?.firstName?.trim()||wt.firstName,lastName:ye.accountPatch?.lastName?.trim()||wt.lastName});if(!(0,Ht.isValidEmail)(Ge.email)||!(Ge.firstName||Ge.lastName))try{let En=ad(await ke?.order?.get?.());Ge=Un({email:En.email||Ge.email,firstName:En.firstName||Ge.firstName,lastName:En.lastName||Ge.lastName})}catch{}if((dt.current||Ye)&&!(0,Ht.isValidEmail)(Ge.email)){let En=await Z("PayPal",Ge);if(!En)return;Ge=En}(0,Ht.isValidEmail)(Ge.email)&&(ye.accountPatch=Un({...ye.accountPatch,...Ge}),await dt.current?.(Ge));let fr;C==="setup_token"?fr={id:G,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Ht.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:x?fr={id:G,isPaypal:!0,gateway:"paypal",paymentMethodType:Ht.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:fr={id:G,isPaypal:!0},await q(fr,ye)}catch(ne){On(ne instanceof Error?ne.message:"PayPal capture failed.")}finally{ft()||be(!1)}}},xe=Fe=>{let ke=Se?()=>$(Se):()=>gt(Fe);return async()=>wn(await ke())},tt=W.Buttons({style:{layout:"horizontal",height:li,tagline:!1},...ve==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Fe,ke)=>{if(ft()){await ke.reject();return}Ft();let G=rt.current,ye={};if(G)try{let Ge=await G("paypal");if(ft()){await ke.reject();return}if(!Ge.proceed){$t.current=null,en.current.delete(se),await ke.reject();return}ye={sessionId:Ge.sessionId,accountPatch:Ge.accountPatch,nonce:Ge.nonce}}catch(Ge){Be(`onClick:runBeforeButtonClick rejected msg=${(Ge instanceof Error?Ge.message:String(Ge)).slice(0,120)}`),$t.current=null,en.current.delete(se),await ke.reject();return}Je(()=>$n.current?.("paypal"));let ne=rn(),wt={generation:ne,surfaceKey:se,...ye};$t.current=wt,en.current.set(se,wt),Ae.current={...v,attempt:ne},await ke.resolve(),pe.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),pe.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Pe.current=pe.startTiming()},createOrder:C==="order"?xe("Failed to create PayPal order."):void 0,createSubscription:C==="subscription"?xe("Failed to create PayPal subscription."):void 0,createVaultSetupToken:C==="setup_token"?async()=>wn(await gt("Failed to create PayPal setup token.")):void 0,onApprove:Ce,onCancel:()=>{if(ft())return;let Fe=en.current.get(se)??$t.current;Fe&&en.current.delete(Fe.surfaceKey),$t.current=null,Nt("cancelled"),pe.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ie.current=!0,Mn({generation:Fe?.generation,remount:!0,focus:!1})},onError:Fe=>{if(ft()||Ke.current!==se)return;let ke=Fe instanceof Error?Fe.message:"PayPal failed to render.";if(Be(`onError rendered=${Bn} msg=${ke.slice(0,120)}`),Bn){let G=en.current.get(se)??$t.current;if(G&&!ur(G.generation)||!G&&dr())return;if(qr(ke)){ln(G?.generation);return}let{errorCode:ye,popupBlocked:ne,providerDeclined:wt,terminalReason:Ge}=oo(Fe,{inAppBrowser:Y.inAppBrowser,handoffObserved:G!=null&&J.current===G.generation});if(ne&&U.markBlocked(),Nt(Ge),wt){pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ge}),Et(Fe,G),Je(()=>jt.current?.(mn("paypal",ke))),G&&en.current.delete(G.surfaceKey),$t.current=null,ln(G?.generation);return}pe.error({errorCode:ye,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ge}),G&&en.current.delete(G.surfaceKey),$t.current=null,Mn({generation:G?.generation,remount:!0,showRetry:!0,focus:!0}),sn(Fe,{code:"paypal_runtime_failed",popupBlocked:ne,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ve,terminalReason:Ge});return}L(qr(ke)?"teardown":"pre_ready_callback",ke)}}),Pt=tt.isEligible();if(Be(`isEligible=${Pt}`),pe.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Pt){te(!1),L("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Or=!0,er=tt,Ot=()=>{if(!tr||Nr||ft()||Bn)return;Nr=!0,Be(`container:dims ${kn(Dn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(kr=new MutationObserver(ke=>{if(!ft()){for(let G of ke)if(G.type==="childList")G.addedNodes.forEach(ye=>{if(!(ye instanceof Element))return;let ne=ye.tagName.toLowerCase(),wt=(ye.getAttribute("title")??"").slice(0,40),Ge=ne==="iframe"?` ${Ur(ye)}`:"";Be(`child+ ${ne}${wt?` title="${wt}"`:""}${Ge} dims=${kn(ye)}`)});else if(G.type==="attributes"&&G.target instanceof Element){let ye=G.target;if(ye.tagName.toLowerCase()!=="iframe")continue;let ne=G.attributeName;(ne==="src"||ne==="srcdoc")&&Be(`attr~ iframe ${ne}=${ne==="srcdoc"?`[${(ye.getAttribute("srcdoc")??"").length}ch]`:nr(ye.getAttribute("src"))} dims=${kn(ye)}`)}}}),kr.observe(Dn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Fe=ke=>{if(ft()||Bn)return;let G=Dn.querySelectorAll("iframe"),ye=typeof document<"u"&&"hasStorageAccess"in document;Be(`watchdog:${ke} container=${kn(Dn)} children=${Dn.childElementCount} iframes=${G.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${ye} paypalNetRequests=${Rn.value}`),G.forEach((ne,wt)=>{let Ge=(ne.getAttribute("title")??"").slice(0,40);Be(` iframe[${wt}] ${kn(ne)}${Ge?` title="${Ge}"`:""} ${Ur(ne)}`);let fr=zr(ne);fr&&Be(` ${fr}`)}),ct.length===0&&Be(" (no PayPal/zoid window errors captured)")};Lr.push(setTimeout(()=>Fe("3s"),3e3)),Lr.push(setTimeout(()=>Fe("8s"),8e3)),Lr.push(setTimeout(()=>Fe("15s"),15e3))},Ot(),Be("render:start");let F=pe.startTiming();Kn=setTimeout(()=>{ft()||Bn||(Be("watchdog:11s retryable render timeout"),L("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},td);let St=tt.render(Dn);(async()=>{try{if(await St,Be(`render:resolved inactive=${ft()}`),_n(),ft()){yr();return}Bn=!0,te(!0),He(!1),Dt.current?.("ready"),pe.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"checkout_render",durationMs:pe.elapsed(F),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Fe){let ke=Fe instanceof Error?Fe.message:"PayPal failed to render.";Be(`render:rejected msg=${ke.slice(0,120)}`),_n(),L(qr(ke)?"teardown":"render_rejected",ke)}})()}).catch(W=>{let Ce=W instanceof Error?W.message:"PayPal operation failed.";Be(`provider:failed msg=${Ce.slice(0,120)}`);let xe="script_rejected";N&&qr(Ce)?xe="teardown":N&&Or&&(xe="render_rejected"),L(xe,Ce)})},0);return()=>{Gt=!0,clearTimeout(Q),Fn&&clearTimeout(Fn),_n(),lt.current===pn&&(lt.current=null),yr(),Pe.current=null,Ae.current=null}},[k,_t,i,p,c,C,ve,x,e,Se,je,_e,Z,Ye,Be,Nt]);let mt=le?(0,ar.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ht?"#fef2f2":"#f3f4f6",border:`1px solid ${ht?"#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=${Te} failed=${ht})`,yt.length===0?`
|
|
1
|
+
"use strict";var Fu=Object.create;var ei=Object.defineProperty;var Bu=Object.getOwnPropertyDescriptor;var Du=Object.getOwnPropertyNames;var Ou=Object.getPrototypeOf,Lu=Object.prototype.hasOwnProperty;var Nu=(e,t)=>{for(var n in t)ei(e,n,{get:t[n],enumerable:!0})},Ll=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Du(t))!Lu.call(e,o)&&o!==n&&ei(e,o,{get:()=>t[o],enumerable:!(r=Bu(t,o))||r.enumerable});return e};var ds=(e,t,n)=>(n=e!=null?Fu(Ou(e)):{},Ll(t||!e||!e.__esModule?ei(n,"default",{value:e,enumerable:!0}):n,e)),Uu=e=>Ll(ei({},"__esModule",{value:!0}),e);var $p={};Nu($p,{DirectPayPalButton:()=>Ra,FloPayAutomaticPaymentButton:()=>Gc,FloPayCardSetup:()=>Xc,FloPayCardSetupError:()=>qa,FloPayCheckout:()=>Ni,FloPayPaymentMethodSetup:()=>mu,FloPayProvider:()=>Ea,SplitCardForm:()=>Bi,VaultCardFields:()=>co,dropThirdPartyOnlyError:()=>fu.dropThirdPartyOnlyError,useCheckout:()=>Xl,useFloPay:()=>Hr,usePayPalFloPay:()=>ri});module.exports=Uu($p);var fu=require("@flopay/shared");var Ui=require("@flopay/js"),cr=require("@flopay/shared"),ut=require("react");var jt=require("react/jsx-runtime");function zu(){return(0,jt.jsxs)(jt.Fragment,{children:[(0,jt.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,jt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,jt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,jt.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,jt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function qu(){return(0,jt.jsx)(jt.Fragment,{children:"Go back"})}function Vu(){return(0,jt.jsx)(jt.Fragment,{children:"Secure card checkout"})}function Lo(e){return e!==void 0&&(e===""||e===null||e===!1)}function No({content:e}){return(0,jt.jsx)(jt.Fragment,{children:e===void 0?(0,jt.jsx)(zu,{}):e})}function Uo({content:e}){return(0,jt.jsx)(jt.Fragment,{children:e===void 0?(0,jt.jsx)(qu,{}):e})}function Pa({content:e}){return(0,jt.jsx)(jt.Fragment,{children:e===void 0?(0,jt.jsx)(Vu,{}):e})}var bt=require("@flopay/shared"),ju="Checkout is temporarily unavailable. Please try again later.";function ps(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof bt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function $u(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 Nl(){return new bt.FloPayError(ju,"api_error",{code:"CheckoutInitializationFailed"})}function ms(e){return!!e?.gateways?.worldpayCorporateGateway}function eo(e){return e?.status==="open"&&ms(e)}function Ul(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&((0,bt.isMountableVaultBlock)(r?.vault)||r?.gateways?.pcivault||o?.includes("card")||eo(r))||t&&e?.data.paypal?.publishableKey)}function zl(e,t){if(t&&(!(e instanceof bt.FloPayError)||e.type==="authentication_error"))return ps(e);if(!(e instanceof bt.FloPayError&&$u(e))){if(!t&&!(e instanceof bt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,bt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof bt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof bt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function zo(e,t,n,r={}){let o;return(a={})=>{if(o!==void 0)return o;let i={...r,...a,email:a.email?.trim()||r.email?.trim()},c=(0,bt.isCardHolderNamePlaceholder)(i.firstName,i.lastName);if(!(0,bt.isValidEmail)(i.email))return Promise.reject(new bt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[u,h]of Object.entries(i)){if(c&&u.endsWith("Name")||typeof h!="string")continue;let P=h.trim();P&&(p[u]=P)}return o=e.claimCheckoutSession(t,n,{accountData:p}),o.catch(()=>{}),o}}function ql(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 ys(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,i)=>a+(i.overrideAmount??i.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,i)=>({uuid:`synthetic-${a.type??"item"}-${i}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function bo(e){if((0,bt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function fs(e,t){return t?{...e,...t}:e}function fn(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,i=typeof t=="string"?void 0:t.sessionId;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{},...i?{sessionId:i}:{}}}function to(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var Wu=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function no(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Wu)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 ro(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 jl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ti(e){let t=jl(e);return new bt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ni(e){return e instanceof bt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function qo(e){return jl(e)?new bt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new bt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new bt.FloPayError(bt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function va(e,t){return e==="processing"||(0,bt.isMoneySettledOutcome)(e,t)}function $l(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Wl(e,t){let n=e;if((0,bt.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:i}=await n.retrieveSetupIntent(t);if(i)throw new bt.FloPayError(i.message??"Failed to retrieve setup intent.","api_error",{...i.code?{code:i.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new bt.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}var Hu=["apple_pay","google_pay"];function Hl(e,t="automatic",n){let r=(0,bt.resolveSetupFutureUsage)(n,Hu,"wallet");return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],...r?{setupFutureUsage:r}:{}}}var Ku=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function gs(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Ku.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Ca(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Xr=require("@flopay/js"),et=require("@flopay/shared"),R=ds(require("react"),1);var hs=require("react"),ar=(0,hs.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Cr=(0,hs.createContext)({session:null,loading:!1,error:null});var ci=require("@flopay/js"),Kt=require("@flopay/shared"),tc=require("@paypal/paypal-js"),x=require("react");var Kl=require("@flopay/shared"),Sr=require("react"),Wr=require("react/jsx-runtime");function qn(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),i=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...i||t?{lastName:i??""}:{}}}function Vo(){let[e,t]=(0,Sr.useState)(null),n=(0,Sr.useRef)(null),r=(0,Sr.useRef)(0),o=(0,Sr.useCallback)((i,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:i,identity:c}),new Promise(p=>{n.current=p})),[]),a=(0,Sr.useCallback)(i=>{let c=n.current;n.current=null,t(null),c?.(i)},[]);return(0,Sr.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function jo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[i,c]=(0,Sr.useState)(e.email?.trim()??""),p=(0,Kl.isValidEmail)(i.trim());return(0,Wr.jsxs)("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,Wr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Wr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Wr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:i,onChange:u=>c(u.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Wr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Wr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Wr.jsxs)("button",{type:"button",disabled:!p||o,onClick:()=>{n(qn({...e,email:i.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Gu=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),Yu=["https://www.paypal.com","https://www.sandbox.paypal.com"];function oo(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 Gl(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 Po(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Br(e){if(typeof e!="object"||e===null)return;let t=e;return Po(t.code)??Po(t.type)??Po(t.name)}function $o(e){if(!(typeof e!="object"||e===null))return Po(e.decline_code)}function vo(e){return typeof e!="object"||e===null?!1:Po(e.type)?.toLowerCase()==="card_error"||$o(e)!==void 0}function Xu(e){let t=Gl(e)?.toLowerCase()??"",n=Br(e)?.toLowerCase()??"";return Gu.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 bs(e){if(Br(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=Gl(e)??"";return n.includes("No ack for postMessage init()")&&Yu.some(r=>n.includes(r))&&n.includes("10000ms")}function ao(e,t){if(vo(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=Xu(e)||t.inAppBrowser&&!t.handoffObserved&&bs(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function io(e){return ao(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}var Yl=require("@flopay/shared"),Sa=require("react");function Hr(){return(0,Sa.useContext)(ar).flopay}function ri(){return(0,Sa.useContext)(ar).paypalFlopay??null}function Xl(){return(0,Sa.useContext)(Cr)}function Jl(){return(0,Sa.useContext)(ar).billingApiUrl||(0,Yl.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 oi(e,t,n=e.popupCapability){return e.inAppBrowser||n==="blocked"||t==="prefer_redirect"?"redirect":"popup"}function ai(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var Zl=require("@flopay/shared"),So=require("react");function Je(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}var ii=require("react"),Co=typeof window>"u"?ii.useEffect:ii.useLayoutEffect;var Ju={"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 Zu(e){return e==="stripe"||e==="paypal"?e:void 0}function Qu(e){let t=Zu(e.provider),n={schemaVersion:Zl.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Ju[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var Ps=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Wo(e,t){let n=(0,So.useRef)(e);n.current=e;let r=(0,So.useRef)(new Set),o=(0,So.useRef)(t),a=(0,So.useRef)(t);return Co(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,So.useCallback)(i=>{if(a.current!==t)return;let c=Qu(i);if(c){if(Ps.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}Je(()=>n.current?.(c))}},[t])}var Ql=require("react"),wa=(0,Ql.createContext)(null);function si(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var ed=Symbol.for("@flopay/js.telemetry.bridge.v1"),td=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function nd(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function rd(e){let t=nd(),n=(o,a)=>o?o.bind(e):a,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function li(e){let t=globalThis[td];return rd(t?.(e)??{})}function gn(e){if(e)return e[ed]}var sn=require("react");function ka(e,t){let n=(0,sn.useRef)(0),r=(0,sn.useRef)(null),o=(0,sn.useRef)(null),a=(0,sn.useRef)(e),i=(0,sn.useRef)(t?.onHandoffObserved),c=(0,sn.useRef)(t?.defersMissingTerminal),p=(0,sn.useRef)(t?.onMissingTerminalDeferred);(0,sn.useEffect)(()=>{a.current=e,i.current=t?.onHandoffObserved,c.current=t?.defersMissingTerminal,p.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let u=(0,sn.useCallback)((b=o.current)=>{b?.timer&&(clearTimeout(b.timer),b.timer=null)},[]),h=(0,sn.useCallback)(b=>{u();let C=n.current+1;return n.current=C,r.current=null,o.current={generation:C,method:b,timer:null,yieldedControl:!1},C},[u]),P=(0,sn.useCallback)(b=>{let C=o.current;return b!==void 0&&C?.generation!==b?!1:(u(C),o.current=null,(b===void 0||r.current===b)&&(r.current=null),!0)},[u]),M=(0,sn.useCallback)(b=>{let C=o.current,G=b??C?.generation??n.current;(b===void 0||C?.generation===b)&&(u(C),o.current=null),r.current=G},[u]),_=(0,sn.useCallback)(b=>r.current===(b??n.current),[]),w=(0,sn.useCallback)(b=>o.current?.generation===b&&r.current!==b,[]),A=(0,sn.useCallback)(()=>{let b=o.current;b&&(u(b),!b.yieldedControl&&(b.yieldedControl=!0,i.current?.(b.method)))},[u]),I=(0,sn.useCallback)(()=>{let b=o.current;!b?.yieldedControl||document.visibilityState!=="visible"||(u(b),b.timer=setTimeout(()=>{if(b.timer=null,o.current?.generation===b.generation){if(c.current?.(b.method)){p.current?.(b.method,b.generation);return}o.current=null,r.current=b.generation,a.current(b.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},600))},[u]);return(0,sn.useEffect)(()=>{let b=()=>{document.visibilityState==="visible"?I():A()};return document.addEventListener("visibilitychange",b),window.addEventListener("blur",A),window.addEventListener("focus",I),()=>{document.removeEventListener("visibilitychange",b),window.removeEventListener("blur",A),window.removeEventListener("focus",I),u()}},[u,A,I]),{startAttempt:h,finishAttempt:P,invalidateAttempt:M,isAttemptInvalidated:_,isAttemptCurrent:w,generationRef:n}}var ir=require("react/jsx-runtime"),ui=45,od=1e3,ad=11e3,id={width:"100%",minHeight:ui,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},sd={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function ld(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:sd[e.kind]??null}}function ec(e,t){return e==="watchdog_expired"?"paypal_render_timeout":bs(t)?"paypal_init_timeout":"paypal_init_failure"}function cd(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function ud(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function nc({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:i,environment:c,currency:p,isSubscription:u,providerObjectType:h,approvalPresentation:P,onTokenizedBody:M,onComplete:_,onErrorChange:w,onDecline:A,onTechnicalFailure:I,isProcessing:b=!1,onLoadStateChange:C,onInitializationStateChange:G,allowAutomaticRetry:k=!0,onButtonClick:ye,runBeforeButtonClick:N,session:H,existingOrderId:_e,telemetry:te,telemetryContext:Ne,onInstrument:Ye,debug:be=!1}){let fe=Hr(),We=Wo(Ye,e),Te=(0,x.useMemo)(()=>{if(fe)return null;let v=li({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Kt.SDK_VERSION,enabled:te!==!1});return v.setCheckoutContext(Ne??{}),v.beginCheckout(Ne??{}),v},[n,fe,te,Ne?.checkoutMode,Ne?.layout]),Fe=(0,x.useMemo)(()=>gn(fe),[fe]);(0,x.useEffect)(()=>()=>{Te&&Te.flush().catch(()=>{}).finally(()=>Te.destroy())},[Te]);let Ae=(0,x.useMemo)(()=>({error:v=>{Fe?Fe.error(v):Te?.error(v),We({class:"technical_error",errorCode:v.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":v.errorCode,requestCategory:v.requestCategory,provider:v.provider})},log:v=>{Fe?Fe.log(v):Te?.log(v),We({class:"lifecycle",name:v.name,provider:v.provider})},performance:v=>{Fe?Fe.performance(v):Te?.performance(v)},terminal:v=>{Fe?Fe.terminal(v):Te?.terminal(v)},startTiming:()=>Fe?.now()??Te?.now()??0,elapsed:v=>Fe?.elapsed(v)??Math.max(0,(Te?.now()??v)-v)}),[We,Fe,Te]),re=(0,x.useRef)(null),se=(0,x.useRef)(0),Ce=(0,x.useRef)(null),Be=(0,x.useRef)(null),Y=(0,x.useRef)(null),Q=(0,x.useContext)(wa),Pe=(0,x.useRef)(null);Pe.current||(Pe.current=si());let z=Q??Pe.current,we=(0,x.useRef)(null),J=(0,x.useRef)(!1),[Ee,Z]=(0,x.useState)(!1),[it,He]=(0,x.useState)(!1),[Ve,at]=(0,x.useState)(0),Ke=(0,x.useRef)(0),[st,je]=(0,x.useState)(!1),St=(0,x.useRef)(!1),Lt=(0,x.useRef)(!1),[Pt,Et]=(0,x.useState)(!1),[q,ve]=(0,x.useState)(!1),{request:Qe,collect:X,finish:Ue}=Vo(),vt=(0,x.useRef)({sessionId:e,required:!(0,Kt.isValidEmail)(r?.trim()||H?.customer?.email?.trim())});vt.current.sessionId!==e&&(vt.current={sessionId:e,required:!(0,Kt.isValidEmail)(r?.trim()||H?.customer?.email?.trim())});let Xe=vt.current.required,kt=(0,x.useMemo)(()=>n.replace(/\/+$/,""),[n]),g=H?.gateways?.paypal?.providerObjectType??h,S=g??(u?"subscription":"order"),[K]=(0,x.useState)(Kr),W=H?.gateways?.paypal?.approvalPresentation??P,Se=ai(K,W==="app_switch"?"app_switch":void 0,S),F=g==="order"||g==="setup_token",B=(0,x.useMemo)(()=>JSON.stringify([kt,i,p,c??"",S,F,Se,e,_e??""]),[kt,i,p,c,_e,S,F,Se,e]),oe=(0,x.useRef)(B),j=oe.current!==B,Ie=(0,x.useRef)(be),tt=(0,x.useRef)(null),[gt,yt]=(0,x.useState)([]),De=(0,x.useCallback)(v=>{Ie.current&&yt(nt=>[...nt,`${new Date().toISOString().slice(11,23)} ${v}`])},[]);(0,x.useEffect)(()=>{Ie.current=be,be&&De("debug:enabled"),tt.current?.setEnabled(be)},[De,be]);let xn=(0,x.useRef)(M),$n=(0,x.useRef)(_),bn=(0,x.useRef)(w),$t=(0,x.useRef)(A),Wn=(0,x.useRef)(I),Hn=(0,x.useRef)(ye),wn=(0,x.useRef)(C),Dt=(0,x.useRef)(G),dt=(0,x.useRef)(a),rt=(0,x.useRef)(N),Fn=(0,x.useRef)(H),Tt=(0,x.useRef)(r),Kn=(0,x.useRef)(o),Pn=(0,x.useRef)(t),Wt=(0,x.useRef)(null),nn=(0,x.useRef)(new Map),ur=(0,x.useRef)(new Map),er=(0,x.useRef)(!1);(0,x.useEffect)(()=>(er.current=!0,()=>{er.current=!1}),[]),(0,x.useEffect)(()=>{xn.current=M},[M]),(0,x.useEffect)(()=>{dt.current=a},[a]),(0,x.useEffect)(()=>{$n.current=_},[_]),(0,x.useEffect)(()=>{bn.current=w},[w]),(0,x.useEffect)(()=>{$t.current=A},[A]),(0,x.useEffect)(()=>{Wn.current=I},[I]),(0,x.useEffect)(()=>{Hn.current=ye},[ye]),(0,x.useEffect)(()=>{wn.current=C},[C]),(0,x.useEffect)(()=>{Dt.current=G},[G]),(0,x.useEffect)(()=>{rt.current=N},[N]),(0,x.useEffect)(()=>{Fn.current=H},[H]),(0,x.useEffect)(()=>{Tt.current=r},[r]),(0,x.useEffect)(()=>{Kn.current=o},[o]),(0,x.useEffect)(()=>{Pn.current=t},[t]),(0,x.useEffect)(()=>{Ke.current=Ve},[Ve]),(0,x.useEffect)(()=>{st&&we.current?.focus()},[st,Ve]);let rn=(0,x.useCallback)(()=>{window.setTimeout(()=>{we.current?.focus()},0)},[]),At=(0,x.useCallback)(()=>{Z(!1),at(v=>v+1)},[]),on=(0,x.useCallback)(()=>{je(!1),(re.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??re.current)?.focus?.()},[]);(0,x.useEffect)(()=>{!Ee||!J.current||(J.current=!1,on())},[on,Ee,Ve]);let cn=(0,x.useCallback)((v,nt)=>{let le=nt?.popupBlocked??io(v);le&&z.markBlocked();let kn=oo("PayPal",le,K.inAppBrowser),Gn=Wn.current;if(Gn){let Yt=le&&K.inAppBrowser?new Kt.FloPayError(kn,"api_error",{code:nt?.code??"paypal_popup_blocked"}):v;Gn("paypal",Yt,nt);return}bn.current?.(kn)},[z,K.inAppBrowser]),Nt=(0,x.useCallback)(v=>{let nt=Ce.current,le=Be.current;nt===null||!le||(Ae.log({...le,popupCapability:z.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:v}),Ae.performance({...le,popupCapability:z.current(),stage:"overlay_return",durationMs:Ae.elapsed(nt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:v}),Ce.current=null)},[z,Ae]),dn=(0,x.useCallback)((v,nt,le)=>{let kn=Be.current;Nt("overlay_timeout"),kn&&Ae.error({...kn,popupCapability:z.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),cn(nt,{...le,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Se,terminalReason:"overlay_timeout"}),je(!0),At(),rn()},[Nt,rn,cn,z,Se,At,Ae]),zt=(0,x.useCallback)(()=>{z.markAvailable();let v=Be.current;v&&(Y.current=v.attempt,Ae.log({...v,popupCapability:z.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[z,Ae]),{finishAttempt:un,generationRef:Ut,invalidateAttempt:ue,isAttemptCurrent:dr,isAttemptInvalidated:pr,startAttempt:mr}=ka(dn,{onHandoffObserved:zt}),an=(0,x.useCallback)(()=>(je(!1),mr("paypal")),[mr]),Bn=(0,x.useCallback)(v=>{ue(v?.generation),v?.showRetry&&je(!0),v?.remount&&At(),v?.focus!==!1&&rn()},[rn,ue,At]),En=v=>{let nt=Wt.current;return nt&&ur.current.set(v,nt),v};(0,x.useEffect)(()=>{oe.current!==B&&(oe.current=B,St.current=!1,Lt.current=!1,Z(!1),He(!1),Et(!1),Dt.current?.("loading"))},[B]),(0,x.useEffect)(()=>{Je(()=>wn.current?.(Ee&&!Pt))},[Ee,Pt]);let Oe=(0,Kt.normalizeGatewayEnvironment)(c);(0,x.useEffect)(()=>{let v={attempt:Ut.current+1,inAppBrowser:K.inAppBrowser,appFamily:K.appFamily,popupCapability:z.current(),presentationMode:Se},nt=()=>({...Be.current??v,popupCapability:z.current()}),le={error:m=>Ae.error({...m,...nt()}),log:m=>Ae.log({...m,...nt()}),performance:m=>Ae.performance({...m,...nt()}),terminal:m=>Ae.terminal({...m,...nt()}),startTiming:Ae.startTiming,elapsed:Ae.elapsed},kn=i?`${i.slice(0,6)}\u2026(len ${i.length})`:"(empty)",Gn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(De(`mount clientId=${kn} env=${c??"(unset)"}\u2192${Oe??"live"} ccy=${p} sub=${u}`),De(`ua=${Gn.slice(0,80)}${Gn.length>80?"\u2026":""}`),!i){De("FAIL: clientId empty \u2014 gateway misconfigured"),Et(!0),le.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(!re.current){De("FAIL: containerRef not attached");return}se.current=le.startTiming(),le.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Yt=!1,Dn=!1,ht=()=>Yt||Dn,yr,po=!1,Mt=()=>{yr=(0,Kt.generateIdempotencyKey)(),yr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),po=!0},On=null,Rr=!1,tr=null,Xt=!1,fr=()=>{!tr||Xt||(Xt=!0,tr.close().catch(()=>{}))},Ln=!1,Ur=!1,Nn=re.current,_r=null,Er=null,zr=[],Yn=null,nr=!1,qr=!1,Ot=null,In=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let y=m.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},rr=m=>{if(!m)return"(empty)";try{let y=new URL(m,typeof window>"u"?"https://localhost":window.location.href),D=y.pathname.toLowerCase();return D.includes("checkcaptcha")||D.includes("captcha")?`CAPTCHA(${y.host}${D})`:D.includes("risk")||D.includes("challenge")?`RISK(${y.host}${D})`:D.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${D}`.slice(0,100)}catch{return m.slice(0,80)}},gr=m=>{let y=m.getAttribute("src"),D=m.getAttribute("srcdoc"),U=m.getAttribute("name"),Re=m.getAttribute("sandbox"),ge=[];return y&&ge.push(`src=${rr(y)}`),D&&ge.push(`srcdoc[${D.length}ch]`),!y&&!D&&ge.push("src=(empty) srcdoc=(empty)"),U&&ge.push(`name=${U.slice(0,40)}`),Re!==null&&ge.push(`sandbox="${Re.slice(0,40)}"`),ge.join(" ")},Ir=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let y=m.contentDocument;if(!y)return"cd=null";let D=y.body?.children.length??0,U=y.body?.innerHTML.length??0,Re=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${D}children,${U}ch] head[${Re}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},lt=[],pn=m=>{if(ht())return;let y=m.message??String(m.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(De(`window:error ${y.slice(0,140)}`),lt.push(y))},mn=m=>{if(ht())return;let y=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(De(`window:rejection ${y.slice(0,140)}`),lt.push(y))},Tn={value:0},mo=()=>{_r?.disconnect(),_r=null,Er?.disconnect(),Er=null;for(let m of zr.splice(0))clearTimeout(m);qr=!1,nr&&typeof window<"u"&&(window.removeEventListener("error",pn),window.removeEventListener("unhandledrejection",mn)),nr=!1},Tr=()=>{if(!(nr||ht()||Ln)){if(nr=!0,lt.length=0,Tn.value=0,typeof window<"u"&&(window.addEventListener("error",pn),window.addEventListener("unhandledrejection",mn)),typeof PerformanceObserver<"u")try{Er=new PerformanceObserver(m=>{if(!ht())for(let y of m.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;Tn.value+=1;let D=Math.round(y.duration);De(`net ${D}ms ${y.name.slice(0,90)}`)}}),Er.observe({type:"resource",buffered:!0})}catch{}Ot?.()}},Zr=()=>{Yn&&(clearTimeout(Yn),Yn=null)},An=()=>{mo(),Zr()},yn={setEnabled:m=>{m?Tr():mo()}};tt.current=yn,Ie.current&&Tr();let hr=m=>{if(!m)return!1;let y=m.toLowerCase();return y.includes("zoid destroyed")||y.includes("destroyed all components")||y.includes("window closed")||y.includes("detected container element removed")},vn=m=>{if(ht()||hr(m))return;let y=no(m)??m;Je(()=>bn.current?.(y))},L=(m,y)=>{if(Yt||Rr)return;Rr=!0,Dn=!0,An(),fr();let D=ld({kind:m,generationActive:!0,automaticRetryAllowed:k,automaticRetryUsed:St.current});if(D.action==="retry"){St.current=!0,Z(!1),ve(!1),He(!0),Dt.current?.("retrying"),On=setTimeout(()=>{Yt||at(U=>U+1)},od);return}if(Z(!1),ve(!1),He(!1),Et(!0),D.action!=="ignore"){if(Dt.current?.("exhausted"),D.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",y);return}if(D.report){let U=ao({code:ec(m,y),message:y},{inAppBrowser:K.inAppBrowser,handoffObserved:!1});U.popupBlocked&&z.markBlocked(),le.error({errorCode:U.popupBlocked?U.errorCode:D.report.errorCode,stage:D.report.stage,operationOutcome:D.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:U.terminalReason})}Lt.current||(Lt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",ec(m,y)))}};Et(!1);let $=async(m,y=Wt.current)=>{if(ht())return;let D=y?.sessionId??e;if(xn.current){await xn.current(m,{sessionId:D,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let U=le.startTiming();le.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Re=()=>{le.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),le.performance({stage:"processing",durationMs:le.elapsed(U),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ge=Fn.current,Rt=y?.accountPatch?.email??Tt.current,qt=y?.accountPatch?.userId??ge?.customer?.id??ge?.accountData?.userId??"",$e=y?.accountPatch?.firstName??ge?.customer?.firstName??ge?.accountData?.firstName,Ge=y?.accountPatch?.lastName??ge?.customer?.lastName??ge?.accountData?.lastName,pe=await new ci.PaymentAPI(kt,{telemetry:!1}).processPayment(qt,{sessionId:D,nonce:y?.nonce??Pn.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:qt,email:Rt??ge?.customer?.email??"",...$e?{firstName:$e}:{},...Ge?{lastName:Ge}:{},country:y?.accountPatch?.country??ge?.customer?.country??ge?.accountData?.country??void 0,zip:y?.accountPatch?.zip??ge?.customer?.zip??ge?.accountData?.zip??void 0}});if(pe.ok){if(Dn||Yt&&er.current)return;Re(),le.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Je(()=>$n.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ht())return;let he=await pe.json().catch(()=>null),E=he?.message??"PayPal payment failed.",me=no(E)??E;Re(),pe.status===400&&(typeof he?.declineCode=="string"||!Array.isArray(he?.fields))?le.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):pe.status===400||pe.status===422?le.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):le.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ud(pe.status),failureCategory:pe.status>=500?"server_error":void 0}),vn(me),Je(()=>$t.current?.(fn("paypal",me,{code:he?.code,declineCode:he?.declineCode})));return}catch(ge){if(ht())return;Re(),le.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Rt=ge instanceof Error?ge.message:"PayPal payment failed.",qt=no(Rt)??Rt;vn(qt),Je(()=>$t.current?.(fn("paypal",qt)));return}},ce=()=>new Kt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Me=m=>ht()?Promise.reject(ce()):Promise.resolve(m),Ct=async m=>{if(ht())throw ce();po||Mt();let y=Wt.current,D=y?.sessionId??e,U=y?.nonce??Pn.current;le.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Re;try{Re=await new ci.PaymentAPI(kt,{telemetry:!1}).createSessionIntent(D,U??"",F?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Kt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:S==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:yr})}catch(ge){throw le.error({...(0,Kt.classifyTelemetryFailure)(ge,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ge}if(ht())throw ce();if(Re.provider!=="paypal"||Re.providerObjectType!==S)throw new Error(m);return le.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Re.providerObjectId},Jt=(m,y)=>{let D=y?.nonce??Pn.current;if(!D)return;let U=y?.sessionId??e,Re=$o(m)??Br(m)??"provider_declined";new ci.PaymentAPI(kt,{telemetry:!1}).reportSessionIntentDecline(U,D,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Re}).catch(()=>{})},ke=Ve;De("loadScript:scheduled (deferred 1 tick)");let de=null,ee=setTimeout(()=>{if(Yt){De("loadScript:skipped (cancelled before defer ran)");return}De("loadScript:start");let m=Oe==="live"?"production":Oe,y={};S==="subscription"?y={intent:"subscription",vault:!0}:S==="order"&&(y={intent:"capture"}),de=(0,tc.loadScript)({clientId:i,currency:p,...y,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let D=!1;de.then(U=>{if(D=!0,De(`loadScript:resolved inactive=${ht()} ns=${!!U} buttons=${!!U?.Buttons}`),ht())return;if(!U?.Buttons){De("FAIL: namespace missing Buttons factory"),L("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}le.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),le.performance({stage:"provider_ready",durationMs:le.elapsed(se.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),le.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Re=async(pe,he)=>{if(ht()||Ke.current!==ke)return;let E=pe.vaultSetupToken??pe.subscriptionID??pe.orderID??"",me=E?ur.current.get(E):nn.current.get(ke);if(!(!me||!dr(me.generation))&&un(me.generation)){ur.current.delete(E),nn.current.delete(me.surfaceKey),Nt("approved");try{if(ve(!0),Je(()=>bn.current?.(null)),!E)throw new Kt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let pt=Fn.current,xt=bo(Kn.current??[pt?.customer?.firstName,pt?.customer?.lastName].filter(Boolean).join(" ")),ae=qn({email:me.accountPatch?.email?.trim()||Tt.current?.trim()||pt?.customer?.email?.trim(),firstName:me.accountPatch?.firstName?.trim()||xt.firstName,lastName:me.accountPatch?.lastName?.trim()||xt.lastName});if(!(0,Kt.isValidEmail)(ae.email)||!(ae.firstName||ae.lastName))try{let ot=cd(await he?.order?.get?.());ae=qn({email:ot.email||ae.email,firstName:ot.firstName||ae.firstName,lastName:ot.lastName||ae.lastName})}catch{}if((dt.current||Xe)&&!(0,Kt.isValidEmail)(ae.email)){let ot=await X("PayPal",ae);if(!ot)return;ae=ot}(0,Kt.isValidEmail)(ae.email)&&(me.accountPatch=qn({...me.accountPatch,...ae}),await dt.current?.(ae));let Rn;S==="setup_token"?Rn={id:E,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Kt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:F?Rn={id:E,isPaypal:!0,gateway:"paypal",paymentMethodType:Kt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Rn={id:E,isPaypal:!0},await $(Rn,me)}catch(pt){vn(pt instanceof Error?pt.message:"PayPal capture failed.")}finally{ht()||ve(!1)}}},ge=pe=>{let he=_e?()=>Me(_e):()=>Ct(pe);return async()=>En(await he())},Rt=U.Buttons({style:{layout:"horizontal",height:ui,tagline:!1},...Se==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(pe,he)=>{if(ht()){await he.reject();return}Mt();let E=rt.current,me={};if(E)try{let ae=await E("paypal");if(ht()){await he.reject();return}if(!ae.proceed){Wt.current=null,nn.current.delete(ke),await he.reject();return}me={sessionId:ae.sessionId,accountPatch:ae.accountPatch,nonce:ae.nonce}}catch(ae){De(`onClick:runBeforeButtonClick rejected msg=${(ae instanceof Error?ae.message:String(ae)).slice(0,120)}`),Wt.current=null,nn.current.delete(ke),await he.reject();return}Je(()=>Hn.current?.("paypal"));let pt=an(),xt={generation:pt,surfaceKey:ke,...me};Wt.current=xt,nn.current.set(ke,xt),Be.current={...v,attempt:pt},await he.resolve(),le.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),le.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Ce.current=le.startTiming()},createOrder:S==="order"?ge("Failed to create PayPal order."):void 0,createSubscription:S==="subscription"?ge("Failed to create PayPal subscription."):void 0,createVaultSetupToken:S==="setup_token"?async()=>En(await Ct("Failed to create PayPal setup token.")):void 0,onApprove:Re,onCancel:()=>{if(ht())return;let pe=nn.current.get(ke)??Wt.current;pe&&nn.current.delete(pe.surfaceKey),Wt.current=null,Nt("cancelled"),le.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),J.current=!0,Bn({generation:pe?.generation,remount:!0,focus:!1})},onError:pe=>{if(ht()||Ke.current!==ke)return;let he=pe instanceof Error?pe.message:"PayPal failed to render.";if(De(`onError rendered=${Ln} msg=${he.slice(0,120)}`),Ln){let E=nn.current.get(ke)??Wt.current;if(E&&!dr(E.generation)||!E&&pr())return;if(hr(he)){un(E?.generation);return}let{errorCode:me,popupBlocked:pt,providerDeclined:xt,terminalReason:ae}=ao(pe,{inAppBrowser:K.inAppBrowser,handoffObserved:E!=null&&Y.current===E.generation});if(pt&&z.markBlocked(),Nt(ae),xt){le.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:ae}),Jt(pe,E),Je(()=>$t.current?.(fn("paypal",he))),E&&nn.current.delete(E.surfaceKey),Wt.current=null,un(E?.generation);return}le.error({errorCode:me,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:ae}),E&&nn.current.delete(E.surfaceKey),Wt.current=null,Bn({generation:E?.generation,remount:!0,showRetry:!0,focus:!0}),cn(pe,{code:"paypal_runtime_failed",popupBlocked:pt,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Se,terminalReason:ae});return}L(hr(he)?"teardown":"pre_ready_callback",he)}}),qt=Rt.isEligible();if(De(`isEligible=${qt}`),le.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!qt){Z(!1),L("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ur=!0,tr=Rt,Ot=()=>{if(!nr||qr||ht()||Ln)return;qr=!0,De(`container:dims ${In(Nn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(_r=new MutationObserver(he=>{if(!ht()){for(let E of he)if(E.type==="childList")E.addedNodes.forEach(me=>{if(!(me instanceof Element))return;let pt=me.tagName.toLowerCase(),xt=(me.getAttribute("title")??"").slice(0,40),ae=pt==="iframe"?` ${gr(me)}`:"";De(`child+ ${pt}${xt?` title="${xt}"`:""}${ae} dims=${In(me)}`)});else if(E.type==="attributes"&&E.target instanceof Element){let me=E.target;if(me.tagName.toLowerCase()!=="iframe")continue;let pt=E.attributeName;(pt==="src"||pt==="srcdoc")&&De(`attr~ iframe ${pt}=${pt==="srcdoc"?`[${(me.getAttribute("srcdoc")??"").length}ch]`:rr(me.getAttribute("src"))} dims=${In(me)}`)}}}),_r.observe(Nn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let pe=he=>{if(ht()||Ln)return;let E=Nn.querySelectorAll("iframe"),me=typeof document<"u"&&"hasStorageAccess"in document;De(`watchdog:${he} container=${In(Nn)} children=${Nn.childElementCount} iframes=${E.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${me} paypalNetRequests=${Tn.value}`),E.forEach((pt,xt)=>{let ae=(pt.getAttribute("title")??"").slice(0,40);De(` iframe[${xt}] ${In(pt)}${ae?` title="${ae}"`:""} ${gr(pt)}`);let Rn=Ir(pt);Rn&&De(` ${Rn}`)}),lt.length===0&&De(" (no PayPal/zoid window errors captured)")};zr.push(setTimeout(()=>pe("3s"),3e3)),zr.push(setTimeout(()=>pe("8s"),8e3)),zr.push(setTimeout(()=>pe("15s"),15e3))},Ot(),De("render:start");let Ge=le.startTiming();Yn=setTimeout(()=>{ht()||Ln||(De("watchdog:11s retryable render timeout"),L("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},ad);let ct=Rt.render(Nn);(async()=>{try{if(await ct,De(`render:resolved inactive=${ht()}`),An(),ht()){fr();return}Ln=!0,Z(!0),He(!1),Dt.current?.("ready"),le.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),le.performance({stage:"checkout_render",durationMs:le.elapsed(Ge),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(pe){let he=pe instanceof Error?pe.message:"PayPal failed to render.";De(`render:rejected msg=${he.slice(0,120)}`),An(),L(hr(he)?"teardown":"render_rejected",he)}})()}).catch(U=>{let Re=U instanceof Error?U.message:"PayPal operation failed.";De(`provider:failed msg=${Re.slice(0,120)}`);let ge="script_rejected";D&&hr(Re)?ge="teardown":D&&Ur&&(ge="render_rejected"),L(ge,Re)})},0);return()=>{Yt=!0,clearTimeout(ee),On&&clearTimeout(On),An(),tt.current===yn&&(tt.current=null),fr(),Ce.current=null,Be.current=null}},[k,kt,i,p,c,S,Se,F,e,_e,Ve,Ae,X,Xe,De,Nt]);let ft=be?(0,ir.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Pt?"#fef2f2":"#f3f4f6",border:`1px solid ${Pt?"#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=${Ee} failed=${Pt})`,gt.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return
|
|
3
|
+
${gt.join(`
|
|
4
|
+
`)}`]}):null;return Pt&&!j?be?(0,ir.jsx)("div",{children:ft}):null:(0,ir.jsxs)("div",{children:[ft,Qe&&(0,ir.jsx)(jo,{identity:Qe.identity,methodLabel:Qe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Ue,onCancel:()=>Ue(null)}),(0,ir.jsxs)("div",{"aria-hidden":it||Qe?!0:void 0,style:it||Qe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ui},children:[!Ee&&!it&&(0,ir.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,ir.jsx)("div",{ref:re,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ui,display:"flex",opacity:Ee?1:0},"aria-busy":q||b},Ve)]},Ve),st&&(0,ir.jsx)("button",{ref:we,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:on,style:id,children:"Try PayPal again"})]})}function Ra(e){return(0,ir.jsx)(nc,{...e})}function rc(e){return(0,ir.jsx)(nc,{...e})}var _a=require("react/jsx-runtime");function Ho({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,_a.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,_a.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,_a.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 di=require("@flopay/shared");function Ko(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Cs=":idempotency-key";function Ss(e,t){if(!Ko())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 ws(e,t){if(!Ko())return null;try{let n=window.sessionStorage.getItem(e+Cs);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 pi(e,t){if(Ko())try{Ss(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function mi(e,t){if(pi(e,t),!!Ko())try{ws(e,t)&&window.sessionStorage.removeItem(e+Cs)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function yi(e,t,n,r){if(Ko())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 fi(e,t,n){if(Ko())try{window.sessionStorage.setItem(e+Cs,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function vs(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function dd(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([i],[c])=>i<c?-1:i>c?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let i=0;i<t.length;i++){let c=t.charCodeAt(i);n=r^Math.imul(n^c,597399067),r=o^Math.imul(r^c,2869860233),o=a^Math.imul(o^c,951274213),a=n^Math.imul(a^c,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(a^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),a=Math.imul(r^a>>>19,2716044179),n^=r^o^a,r^=n,o^=n,a^=n,[n,r,o,a].map(i=>(i>>>0).toString(16).padStart(8,"0")).join("")}function Go(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=>vs(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>vs(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>vs(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:dd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function oc(e,t=!1){let n=Go(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 ac(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,di.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,di.foldIntoProducts)(t.items,t.subscriptions)).map(u=>({type:u.type,code:u.code??u.providerItemId??u.providerPlanId??"",quantity:u.quantity??1,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount??null,currency:(u.currency??o).toUpperCase()})).sort((u,h)=>`${u.code}:${u.type??""}`.localeCompare(`${h.code}:${h.type??""}`)),i=e.products.map(u=>({type:u.type,code:u.code??"",quantity:u.quantity??1,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount??null,currency:(u.currency??e.currency).toUpperCase()})).sort((u,h)=>`${u.code}:${u.type??""}`.localeCompare(`${h.code}:${h.type??""}`));if(a.length!==i.length)return!1;for(let[u,h]of a.entries()){let P=i[u];if(P===void 0||h.code!==P.code||h.type!==void 0&&h.type!==P.type||h.quantity!==P.quantity||h.totalAmount!==P.totalAmount||h.overrideAmount!==P.overrideAmount||h.currency!==P.currency)return!1}let c=[...t.couponCodes??[]].sort(),p=[...e.coupons??[]].sort();return c.length===p.length&&c.every((u,h)=>u===p[h])}var ln=require("react/jsx-runtime");var pd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function Vn({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:i="You will be automatically redirected, do not close or navigate away from this window.",theme:c=pd}){let p={fontSize:13,color:c.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,ln.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,ln.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,ln.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,ln.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,ln.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:c.spinnerTrackColor,strokeWidth:"3"}),(0,ln.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:c.spinnerAccentColor})]}),e==="success"&&(0,ln.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,ln.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,ln.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,ln.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,ln.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,ln.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,ln.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,ln.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,ln.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:c.labelColors[e]},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&a]}),e==="success"&&i!==null&&(0,ln.jsx)("p",{style:p,children:i}),e==="error"&&t&&(0,ln.jsx)("p",{style:p,children:t}),(0,ln.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 nc=require("@flopay/shared"),bn=require("react");var rc=require("react/jsx-runtime");function Ra({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,i]=(0,bn.useState)(e instanceof Promise?null:e),[c,p]=(0,bn.useState)(t instanceof Promise||!t?null:t),u=(0,bn.useRef)(null),g=(0,bn.useRef)(null),b=jo(r);(0,bn.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,bn.useEffect)(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),(0,bn.useEffect)(()=>{if(a)return yn(a)?.subscribe?.(b)},[b,a]),(0,bn.useEffect)(()=>{if(!(!c||c===a))return yn(c)?.subscribe?.(b)},[b,a,c]),(0,bn.useEffect)(()=>{if(!a)return;let S=yn(a);return u.current=S?.beginCheckout()??S?.now()??0,S?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{S?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,bn.useEffect)(()=>{let S=!1;return e instanceof Promise?e.then(A=>{S||i(A)},()=>{S||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):i(e),()=>{S=!0}},[b,e]),(0,bn.useEffect)(()=>{let S=!1;if(!t){p(null);return}return t instanceof Promise?t.then(A=>{S||p(A)},()=>{S||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{S=!0}},[b,t]),(0,bn.useEffect)(()=>{if(!a||g.current===a)return;g.current=a;let S=yn(a);S?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),S?.performance({stage:"checkout_render",durationMs:S.elapsed(u.current??0),durationMode:"machine"})},[b,a]);let T=(0,nc.resolveBillingApiUrl)(n?.billingApiUrl),I=(0,bn.useMemo)(()=>({flopay:a,paypalFlopay:c,billingApiUrl:T,emitInstrument:b}),[a,c,T,b]);return(0,rc.jsx)(or.Provider,{value:I,children:o})}var yi="flopay_recent_completion_";function Ko(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(yi+e,JSON.stringify(t))}catch{}}function Cs(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(yi+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(yi+e),!1):!0}catch{return!1}}async function fi(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 io=require("@flopay/js"),nt=require("@flopay/shared");var Ea="card",cd=1e3;async function ud(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:i}=await e.retrieveSetupIntent(t);return{error:i,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function dd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:i,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:i??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function so(e){return new nt.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Ss(){return new nt.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function ks(e,t){return Object.assign(e,{checkoutMethod:t})}function Gr(e,t){let n=e instanceof nt.FloPayError?e:new nt.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 _a(e,t){try{return await e()}catch(n){throw Gr(n,t)}}function ac(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 pd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function Rs(e){if(typeof document>"u"||typeof window>"u")throw new nt.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw so();let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let b=new AbortController,T=()=>b.abort();e.signal?.aborted?b.abort():e.signal?.addEventListener("abort",T);let I=window.setTimeout(()=>b.abort(),n);try{let S=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:b.signal});if(!S.ok)return{status:"unknown"};let A=await S.json().catch(()=>null);return md(A)}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",T)}},a,i=()=>e.pollCompletionEndpoint!==!1?o():(a??(a=o()),a),c=document.activeElement instanceof HTMLElement?document.activeElement:null,p=document.createElement("div");p.setAttribute("data-flopay-auto-3ds-overlay","1"),p.setAttribute("role","dialog"),p.setAttribute("aria-modal","true"),p.setAttribute("aria-label","Card authentication"),p.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let u=document.createElement("iframe");u.setAttribute("title","Card authentication"),u.setAttribute("allow","payment"),u.tabIndex=0,u.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let b=await new Promise((T,I)=>{let S=!1,A=0,_=0,P=0,w=!1,K=()=>{window.clearTimeout(A),window.clearInterval(_),window.clearTimeout(P),window.removeEventListener("message",X),u.removeEventListener("load",ge),e.signal?.removeEventListener("abort",z)},k=async()=>{if(!(S||w)){w=!0;try{let Se=await i();if(S||!pd(Se))return;S=!0,K(),T(Se)}finally{w=!1}}},ge=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(P),P=window.setTimeout(()=>{k()},250))},z=()=>{S||(S=!0,K(),I(so()))},X=Se=>{if(Se.source!==u.contentWindow||g&&Se.origin!==g)return;let ae=Se.data;!ae||typeof ae!="object"||ae.source!=="flopay-vault-3ds-return"||S||(S=!0,K(),T(null))};A=window.setTimeout(()=>{S||(S=!0,K(),I(Ss()))},nt.THREE_DS_CHALLENGE_WINDOW_MS),e.pollCompletionEndpoint!==!1&&(_=window.setInterval(()=>{k()},t)),u.addEventListener("load",ge),window.addEventListener("message",X),e.signal?.addEventListener("abort",z),u.src=e.nextActionRedirectUrl,p.appendChild(u),document.body.appendChild(p),u.focus(),e.signal?.aborted&&z()});return b||await i()}finally{p.parentNode?.removeChild(p),c?.isConnected&&c.focus()}}async function Go(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,a=t.nonce??t.session.clientSecret,i=new io.PaymentAPI(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,p=new AbortController,u=new AbortController,g=()=>{p.abort(o.reason),u.abort(o.reason)};o.aborted?g():o.addEventListener("abort",g,{once:!0});let b=Rs({billingApiUrl:n,sessionId:r,nonce:a,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:p.signal,pollCompletionEndpoint:!1}),T=i.waitForCheckoutSessionCompletion(r,{initialDelayMs:cd,nonce:a,statusUrl:c,continueAfterActionRequired:!0,timeoutMs:nt.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:u.signal}),I;try{let A=await Promise.race([b,T]);if("data"in A)I=A;else{if(A.status==="declined")throw xr({type:A.declineReason??"authorization_declined",gatewayErrorCode:A.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(A.status==="timeout")throw Ss();I=await T}}catch(A){if(o.aborted||A instanceof Error&&A.name==="AbortError")throw so(A);if(!(A instanceof nt.FloPayError)||A.code!=="three_ds_timeout"&&A.code!=="checkout_processing_timeout")throw A;try{I=await i.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:a,statusUrl:c,timeoutMs:5e3,signal:o})}catch(P){if(o.aborted)throw so(P);if(!(P instanceof nt.FloPayError)||P.code!=="checkout_processing_timeout")throw P}let _=I&&no(I,t.session);if(!$r(_)&&_?.status!=="expired"){if(t.telemetry){let P=new io.PaymentAPI(n);try{P.reportThreeDsAbandoned(r)}finally{P.destroy()}}throw Ss()}}finally{o.removeEventListener("abort",g),p.abort(),u.abort()}let S=I&&no(I,t.session);if(!$r(S))throw Uo(S);return{...jr(S,r),checkoutMethod:"card"}}function md(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function xr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=to(o)??o,i=ks(new nt.FloPayError(a,"api_error",{code:e?.code??(0,nt.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,nt.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(i.orderId=e.orderId),i}function ws(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function gi(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ic(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||gi(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||gi(c)))return c;let i=o.gateways;if(i&&typeof i=="object"){let c=i.stripe;if(c&&typeof c=="object"){let p=c,u=[p.stripeClientSecret,p.clientSecret];for(let g of u)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||gi(g)))return g}}}}async function yd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ic(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 io.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(gi(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function Yo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:i}){let c=e.replace(/\/+$/,""),p=t??n.id,u=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",T=n.customer?.firstName??n.accountData?.firstName??"",I=n.customer?.lastName??n.accountData?.lastName??"",S=n.customer?.country??n.accountData?.country??void 0,A=n.customer?.zip??n.accountData?.zip??void 0,P=await new io.PaymentAPI(c,i===!1?{telemetry:!1}:void 0).processPayment(g,{sessionId:p,nonce:u,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:g,email:b,firstName:T,lastName:I,country:S,zip:A},returnUrl:a??ws(n)});if(P.ok){let k=typeof P.json=="function"?await P.json().catch(()=>null):null;if((0,nt.isAuthorizationOnlySession)(n)||k?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof k?.paymentId=="string"?k.paymentId:n.paymentId,sessionId:typeof k?.sessionId=="string"?k.sessionId:p,authorizationExpiresAt:typeof k?.authorizationExpiresAt=="string"?k.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Pa(o),checkoutMethod:oc(o,n)}};let ge=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ge?{paymentIntentId:ge}:{},paymentMethodId:Pa(o),checkoutMethod:oc(o,n)}}}let w;try{w=await P.json()}catch(k){throw new nt.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:P.status,cause:k})}if(w?.type==="3ds_required"&&typeof w.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:w.nextActionRedirectUrl};if(w?.type==="paypal_redirect_required"||w?.type==="3ds_required"){let k=ic(w);if(!k)throw new nt.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:P.status});return{type:w.type,threeDSecureToken:k,paymentMethodId:w.paymentMethodId}}if(w?.gatewayErrorCode==="authentication_required"){let k=await yd({billingApiUrl:c,sessionId:p,nonce:u,responseJson:w});if(k)return k;throw ks(new nt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let K=new nt.FloPayError(w?.message??"Payment failed. Please try again.","api_error",{code:w?.code??w?.gatewayErrorCode,declineCode:w?.declineCode??w?.gatewayDeclineReason,statusCode:P.status});throw Object.assign(K,{telemetryOutcome:(0,nt.classifyPaymentRejection)(P.status,w)})}async function hi(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:i,returnUrl:c,telemetry:p,signal:u}){let g=t?.getRawProvider();if(!g)throw Gr(new nt.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw ks(new nt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let b=(0,nt.isSetupIntentClientSecret)(e.threeDSecureToken),T=null,I=e.paymentMethodId,S=await _a(()=>ud(g,e.threeDSecureToken,b),"card");if(S){if(S.error)throw Gr(new nt.FloPayError(S.error.message??`Failed to retrieve 3DS ${b?"setup":"payment"} status.`,"api_error",{code:S.error.code}),"card");let _=S.intent;!I&&_?.payment_method&&(typeof _.payment_method=="string"?I=_.payment_method:"id"in _.payment_method&&(I=_.payment_method.id??void 0))}let A=I?await _a(()=>dd(g,e.threeDSecureToken,{payment_method:I,return_url:c??ws(i)??window.location.href},b),"card"):null;if(A){if(A.error)throw Gr(new nt.FloPayError(A.error.message??"3DS authentication failed.","api_error",{code:A.error.code}),"card");T=A.intent}else{let _=await _a(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(_.error)throw Gr(new nt.FloPayError(_.error.message??"3DS authentication failed.","api_error",{code:_.error.code}),"card");T=(b?_.setupIntent:_.paymentIntent)??null}if(T&&(T.status==="requires_capture"||T.status==="succeeded"||T.status==="processing")){let _=await Yo({billingApiUrl:o,sessionId:a,session:i,telemetry:p,tokenizedData:{id:T.id,type:"card",threeDSecureActionResultTokenId:T.id},returnUrl:c});return _.type==="success"?{..._.result,paymentIntentId:_.result.paymentIntentId??T.id,paymentMethodId:_.result.paymentMethodId??I}:_.type==="next_action_required"?Go(_,{billingApiUrl:o,sessionId:a??i.id,session:i,signal:u}):hi(_,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:i,returnUrl:c,telemetry:p,signal:u})}throw Gr(new nt.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 nt.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:I}=await _a(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(I)throw Gr(new nt.FloPayError(I.message??"PayPal authorization failed.","api_error",{code:I.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:T}=await _a(()=>b.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??ws(i)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(T)throw Gr(new nt.FloPayError(T.message??"PayPal authorization failed.","api_error",{code:T.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new nt.FloPayError("Unsupported payment redirect state.","api_error")}function Ia(e){if(e instanceof nt.FloPayError){let r=to(e.message);return r&&r!==e.message?Object.assign(new nt.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=to(t)??t;return new nt.FloPayError(n,"api_error")}function _s(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Qr(e.data.session);if(!t&&!n&&!r)throw new nt.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 oc(e,t){return e?e.isPaypal?"paypal":"card":t&&Qr(t)?"card":void 0}async function Es({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=t&&t!==e?t:void 0,[i,c]=await Promise.all([(0,io.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,io.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(u=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",u),null)):Promise.resolve(null)]);if(!i)throw new nt.FloPayError("The payment provider did not initialize.","authentication_error");let p=null;return a?p=c:t&&(p=i),{flopay:i,paypalFlopay:p}}var Sr=require("@flopay/js"),y=require("@flopay/shared"),Zt=require("@stripe/react-stripe-js"),s=ls(require("react"),1);function Xo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function bi(e,t){if(e)return{error:n=>e.error(Xo(t,n)),log:n=>e.log(Xo(t,n)),performance:n=>e.performance(Xo(t,n)),terminal:n=>e.terminal(Xo(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}var Yr=require("@flopay/shared"),lc=require("react");var sc={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 fn=require("react/jsx-runtime"),fd=`
|
|
9
|
+
`})]})})}var ic=require("@flopay/shared"),Cn=require("react");var sc=require("react/jsx-runtime");function Ea({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,i]=(0,Cn.useState)(e instanceof Promise?null:e),[c,p]=(0,Cn.useState)(t instanceof Promise||!t?null:t),u=(0,Cn.useRef)(null),h=(0,Cn.useRef)(null),P=Wo(r);(0,Cn.useEffect)(()=>{P({class:"lifecycle",name:"checkout.mount"})},[P]),(0,Cn.useEffect)(()=>{a&&P({class:"lifecycle",name:"sdk.initialize.ready"})},[P,a]),(0,Cn.useEffect)(()=>{if(a)return gn(a)?.subscribe?.(P)},[P,a]),(0,Cn.useEffect)(()=>{if(!(!c||c===a))return gn(c)?.subscribe?.(P)},[P,a,c]),(0,Cn.useEffect)(()=>{if(!a)return;let w=gn(a);return u.current=w?.beginCheckout()??w?.now()??0,w?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{w?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,Cn.useEffect)(()=>{let w=!1;return e instanceof Promise?e.then(A=>{w||i(A)},()=>{w||P({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):i(e),()=>{w=!0}},[P,e]),(0,Cn.useEffect)(()=>{let w=!1;if(!t){p(null);return}return t instanceof Promise?t.then(A=>{w||p(A)},()=>{w||P({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{w=!0}},[P,t]),(0,Cn.useEffect)(()=>{if(!a||h.current===a)return;h.current=a;let w=gn(a);w?.log({name:"checkout.rendered",stage:"checkout_render"}),P({class:"lifecycle",name:"checkout.rendered"}),w?.performance({stage:"checkout_render",durationMs:w.elapsed(u.current??0),durationMode:"machine"})},[P,a]);let M=(0,ic.resolveBillingApiUrl)(n?.billingApiUrl),_=(0,Cn.useMemo)(()=>({flopay:a,paypalFlopay:c,billingApiUrl:M,emitInstrument:P}),[a,c,M,P]);return(0,sc.jsx)(ar.Provider,{value:_,children:o})}var gi="flopay_recent_completion_";function Yo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(gi+e,JSON.stringify(t))}catch{}}function ks(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(gi+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(gi+e),!1):!0}catch{return!1}}async function hi(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 so=require("@flopay/js"),Ze=require("@flopay/shared");var Ta="card",md=1e3;async function yd(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:i}=await e.retrieveSetupIntent(t);return{error:i,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function fd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:i,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:i??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function lo(e){return new Ze.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Rs(){return new Ze.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Es(e,t){return Object.assign(e,{checkoutMethod:t})}function Gr(e,t){let n=e instanceof Ze.FloPayError?e:new Ze.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 Gr(n,t)}}function cc(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function gd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function Is(e){if(typeof document>"u"||typeof window>"u")throw new Ze.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw lo();let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let P=new AbortController,M=()=>P.abort();e.signal?.aborted?P.abort():e.signal?.addEventListener("abort",M);let _=window.setTimeout(()=>P.abort(),n);try{let w=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:P.signal});if(!w.ok)return{status:"unknown"};let A=await w.json().catch(()=>null);return hd(A)}catch{return{status:"unknown"}}finally{window.clearTimeout(_),e.signal?.removeEventListener("abort",M)}},a,i=()=>e.pollCompletionEndpoint!==!1?o():(a??(a=o()),a),c=document.activeElement instanceof HTMLElement?document.activeElement:null,p=document.createElement("div");p.setAttribute("data-flopay-auto-3ds-overlay","1"),p.setAttribute("role","dialog"),p.setAttribute("aria-modal","true"),p.setAttribute("aria-label","Card authentication"),p.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let u=document.createElement("iframe");u.setAttribute("title","Card authentication"),u.setAttribute("allow","payment"),u.tabIndex=0,u.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}try{let P=await new Promise((M,_)=>{let w=!1,A=0,I=0,b=0,C=!1,G=()=>{window.clearTimeout(A),window.clearInterval(I),window.clearTimeout(b),window.removeEventListener("message",H),u.removeEventListener("load",ye),e.signal?.removeEventListener("abort",N)},k=async()=>{if(!(w||C)){C=!0;try{let _e=await i();if(w||!gd(_e))return;w=!0,G(),M(_e)}finally{C=!1}}},ye=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(b),b=window.setTimeout(()=>{k()},250))},N=()=>{w||(w=!0,G(),_(lo()))},H=_e=>{if(_e.source!==u.contentWindow||h&&_e.origin!==h)return;let te=_e.data;!te||typeof te!="object"||te.source!=="flopay-vault-3ds-return"||w||(w=!0,G(),M(null))};A=window.setTimeout(()=>{w||(w=!0,G(),_(Rs()))},Ze.THREE_DS_CHALLENGE_WINDOW_MS),e.pollCompletionEndpoint!==!1&&(I=window.setInterval(()=>{k()},t)),u.addEventListener("load",ye),window.addEventListener("message",H),e.signal?.addEventListener("abort",N),u.src=e.nextActionRedirectUrl,p.appendChild(u),document.body.appendChild(p),u.focus(),e.signal?.aborted&&N()});return P||await i()}finally{p.parentNode?.removeChild(p),c?.isConnected&&c.focus()}}async function Xo(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,a=t.nonce??t.session.clientSecret,i=new so.PaymentAPI(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,p=new AbortController,u=new AbortController,h=()=>{p.abort(o.reason),u.abort(o.reason)};o.aborted?h():o.addEventListener("abort",h,{once:!0});let P=Is({billingApiUrl:n,sessionId:r,nonce:a,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:p.signal,pollCompletionEndpoint:!1}),M=i.waitForCheckoutSessionCompletion(r,{initialDelayMs:md,nonce:a,statusUrl:c,continueAfterActionRequired:!0,timeoutMs:Ze.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:u.signal}),_;try{let A=await Promise.race([P,M]);if("data"in A)_=A;else{if(A.status==="declined")throw Dr({type:A.declineReason??"authorization_declined",gatewayErrorCode:A.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(A.status==="timeout")throw Rs();_=await M}}catch(A){if(o.aborted||A instanceof Error&&A.name==="AbortError")throw lo(A);if(!(A instanceof Ze.FloPayError)||A.code!=="three_ds_timeout"&&A.code!=="checkout_processing_timeout")throw A;try{_=await i.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:a,statusUrl:c,timeoutMs:5e3,signal:o})}catch(b){if(o.aborted)throw lo(b);if(!(b instanceof Ze.FloPayError)||b.code!=="checkout_processing_timeout")throw b}let I=_&&ro(_,t.session);if(!$r(I)&&I?.status!=="expired"){if(t.telemetry){let b=new so.PaymentAPI(n);try{b.reportThreeDsAbandoned(r)}finally{b.destroy()}}throw Rs()}}finally{o.removeEventListener("abort",h),p.abort(),u.abort()}let w=_&&ro(_,t.session);if(!$r(w))throw qo(w);return{...jr(w,r),checkoutMethod:"card"}}function hd(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Dr(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=no(o)??o,i=Es(new Ze.FloPayError(a,"api_error",{code:e?.code??(0,Ze.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ze.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(i.orderId=e.orderId),i}function _s(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function bi(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function uc(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||bi(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||bi(c)))return c;let i=o.gateways;if(i&&typeof i=="object"){let c=i.stripe;if(c&&typeof c=="object"){let p=c,u=[p.stripeClientSecret,p.clientSecret];for(let h of u)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||bi(h)))return h}}}}async function bd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=uc(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 so.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(bi(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function Jo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:i}){let c=e.replace(/\/+$/,""),p=t??n.id,u=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",P=n.customer?.email??n.accountData?.email??"",M=n.customer?.firstName??n.accountData?.firstName??"",_=n.customer?.lastName??n.accountData?.lastName??"",w=n.customer?.country??n.accountData?.country??void 0,A=n.customer?.zip??n.accountData?.zip??void 0,b=await new so.PaymentAPI(c,i===!1?{telemetry:!1}:void 0).processPayment(h,{sessionId:p,nonce:u,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:h,email:P,firstName:M,lastName:_,country:w,zip:A},returnUrl:a??_s(n)});if(b.ok){let k=typeof b.json=="function"?await b.json().catch(()=>null):null;if((0,Ze.isAuthorizationOnlySession)(n)||k?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof k?.paymentId=="string"?k.paymentId:n.paymentId,sessionId:typeof k?.sessionId=="string"?k.sessionId:p,authorizationExpiresAt:typeof k?.authorizationExpiresAt=="string"?k.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Ca(o),checkoutMethod:lc(o,n)}};let ye=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ye?{paymentIntentId:ye}:{},paymentMethodId:Ca(o),checkoutMethod:lc(o,n)}}}let C;try{C=await b.json()}catch(k){throw new Ze.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:b.status,cause:k})}if(C?.type==="3ds_required"&&typeof C.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:C.nextActionRedirectUrl};if(C?.type==="paypal_redirect_required"||C?.type==="3ds_required"){let k=uc(C);if(!k)throw new Ze.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:b.status});return{type:C.type,threeDSecureToken:k,paymentMethodId:C.paymentMethodId}}if(C?.gatewayErrorCode==="authentication_required"){let k=await bd({billingApiUrl:c,sessionId:p,nonce:u,responseJson:C});if(k)return k;throw Es(new Ze.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let G=new Ze.FloPayError(C?.message??"Payment failed. Please try again.","api_error",{code:C?.code??C?.gatewayErrorCode,declineCode:C?.declineCode??C?.gatewayDeclineReason,statusCode:b.status});throw Object.assign(G,{telemetryOutcome:(0,Ze.classifyPaymentRejection)(b.status,C)})}async function Pi(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:i,returnUrl:c,telemetry:p,signal:u}){let h=t?.getRawProvider();if(!h)throw Gr(new Ze.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Es(new Ze.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let P=(0,Ze.isSetupIntentClientSecret)(e.threeDSecureToken),M=null,_=e.paymentMethodId,w=await Ia(()=>yd(h,e.threeDSecureToken,P),"card");if(w){if(w.error)throw Gr(new Ze.FloPayError(w.error.message??`Failed to retrieve 3DS ${P?"setup":"payment"} status.`,"api_error",{code:w.error.code}),"card");let I=w.intent;!_&&I?.payment_method&&(typeof I.payment_method=="string"?_=I.payment_method:"id"in I.payment_method&&(_=I.payment_method.id??void 0))}let A=_?await Ia(()=>fd(h,e.threeDSecureToken,{payment_method:_,return_url:c??_s(i)??window.location.href},P),"card"):null;if(A){if(A.error)throw Gr(new Ze.FloPayError(A.error.message??"3DS authentication failed.","api_error",{code:A.error.code}),"card");M=A.intent}else{let I=await Ia(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(I.error)throw Gr(new Ze.FloPayError(I.error.message??"3DS authentication failed.","api_error",{code:I.error.code}),"card");M=(P?I.setupIntent:I.paymentIntent)??null}if(M&&(M.status==="requires_capture"||M.status==="succeeded"||M.status==="processing")){let I=await Jo({billingApiUrl:o,sessionId:a,session:i,telemetry:p,tokenizedData:{id:M.id,type:"card",threeDSecureActionResultTokenId:M.id},returnUrl:c});return I.type==="success"?{...I.result,paymentIntentId:I.result.paymentIntentId??M.id,paymentMethodId:I.result.paymentMethodId??_}:I.type==="next_action_required"?Xo(I,{billingApiUrl:o,sessionId:a??i.id,session:i,signal:u}):Pi(I,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:i,returnUrl:c,telemetry:p,signal:u})}throw Gr(new Ze.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let P=(n??t)?.getRawProvider();if(!P)throw Gr(new Ze.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:_}=await Ia(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(_)throw Gr(new Ze.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:M}=await Ia(()=>P.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??_s(i)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(M)throw Gr(new Ze.FloPayError(M.message??"PayPal authorization failed.","api_error",{code:M.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ze.FloPayError("Unsupported payment redirect state.","api_error")}function Aa(e){if(e instanceof Ze.FloPayError){let r=no(e.message);return r&&r!==e.message?Object.assign(new Ze.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=no(t)??t;return new Ze.FloPayError(n,"api_error")}function Ts(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=(0,Ze.isMountableVaultBlock)(e.data.session?.vault)||eo(e.data.session);if(!t&&!n&&!r)throw new Ze.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 lc(e,t){return e?e.isPaypal?"paypal":"card":t&&eo(t)?"card":void 0}async function As({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=t&&t!==e?t:void 0,[i,c]=await Promise.all([(0,so.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,so.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(u=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",u),null)):Promise.resolve(null)]);if(!i)throw new Ze.FloPayError("The payment provider did not initialize.","authentication_error");let p=null;return a?p=c:t&&(p=i),{flopay:i,paypalFlopay:p}}var kr=require("@flopay/js"),f=require("@flopay/shared"),Qt=require("@stripe/react-stripe-js"),s=ds(require("react"),1);function Zo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function vi(e,t){if(e)return{error:n=>e.error(Zo(t,n)),log:n=>e.log(Zo(t,n)),performance:n=>e.performance(Zo(t,n)),terminal:n=>e.terminal(Zo(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 Yr=require("@flopay/shared"),pc=require("react");var dc={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 hn=require("react/jsx-runtime"),Pd=`
|
|
10
10
|
.paypal-buttons { margin: 0 !important; vertical-align: top !important; }
|
|
11
11
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
12
12
|
@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
@@ -27,7 +27,7 @@ ${yt.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
|
-
`,Jo=44;function Zo(){return(0,fn.jsx)("style",{children:fd})}function Ta(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Aa({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,fn.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,fn.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,fn.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 Is(e){return e!=="unavailable"&&e!=="load_error"}function Pi({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:i,backgroundColor:c,borderColor:p,textColor:u,borderRadius:g,fontFamily:b}){let T=(0,Yr.resolveStripeMethodBrandVariant)(e,t),I=sc[e],[S,A]=(0,lc.useState)(!1),_=!!I&&!S,P=T?.backgroundColor??c??"#ffffff",w=T?.borderColor??p??"#d1d5db",K=T?.textColor??u??"#262833";return(0,fn.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&i()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Jo,padding:"0 1rem",backgroundColor:P,color:K,border:`1px solid ${w}`,borderRadius:g??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,fn.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,Yr.getStripeMethodDisplayName)(e)}\u2026`}):(0,fn.jsxs)(fn.Fragment,{children:[(0,fn.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,Yr.hasVendoredStripeMethodLogo)(e)?8:0},children:[_?(0,fn.jsx)("img",{src:I,alt:"","aria-hidden":"true",onError:()=>A(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!_&&T?.logoSvg?(0,fn.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:T.logoSvg}}):null,(0,fn.jsx)("span",{children:(0,Yr.getStripeMethodDisplayName)(e)})]}),a&&(0,fn.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:K,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,fn.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function vi(e){let t=new Set(e.map(Yr.stripeExpressMethodToOptionKey)),n=r=>r==="applePay"||r==="googlePay"?"always":"auto";return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?n(r):"never"]))}var Ci={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},Si={type:"accordion",defaultCollapsed:!1,radios:"never"};function wi({testId:e,attributes:t,disabled:n,onClick:r,color:o,borderRadius:a,style:i,children:c}){return(0,fn.jsx)("button",{type:"button","data-testid":e,...t,onClick:r,disabled:n,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:o,color:"white",border:"none",borderRadius:a,fontSize:"1rem",fontWeight:600,cursor:n?"not-allowed":"pointer",opacity:n?.5:1,transition:"opacity 120ms ease-out",...i??{}},children:c})}var Jn=require("react");function ki(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(i=>i.startsWith("background")),a={};for(let[i,c]of Object.entries(e))i in n||o&&i.startsWith("background")||(a[i]=c);for(let i of r)a[i]=n[i];return a}var gd=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 hd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return gd.has(t.charAt(0).toLowerCase()+t.slice(1))}function bd(e,t){return typeof t=="number"&&t!==0&&!hd(e)?`${t}px`:String(t).trim()}function cc(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]=bd(n,r)}}}var So=require("react/jsx-runtime"),Ts=new WeakSet;function lo({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:i,onReady:c,onError:p,onValidation:u}){let g=(0,Jn.useRef)(null),b=(0,Jn.useRef)(c),T=(0,Jn.useRef)(p),I=(0,Jn.useRef)(u);b.current=c,T.current=p,I.current=u;let S=(0,Jn.useRef)(o);S.current=o;let A=(0,Jn.useRef)(null),_=a??void 0,P=(0,Jn.useRef)(_);P.current=_;let w=(0,Jn.useRef)(void 0);return(0,Jn.useEffect)(()=>{let K=g.current;if(!K)return;let k=!0,ge=!1,z=()=>{!k||ge||(ge=!0,b.current?.())},X=e.on("ready",()=>{z()}),Se=e.on("error",le=>{T.current?.(le.message??"There was a problem loading the secure card form.")}),ae=e.on("validation",le=>{I.current?.(le.message??null)}),De=P.current??(Ts.has(e)?null:void 0),Ze={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...S.current?{theme:S.current}:{},...De===void 0?{}:{submitLabel:De}};return A.current=S.current??null,w.current=P.current,P.current!==void 0&&Ts.add(e),e.mount(K,Ze).then(()=>{z()}).catch(le=>{k&&T.current?.(le instanceof Error?le.message:"Failed to load the secure card form.")}),()=>{k=!1,X(),Se(),ae(),e.unmount()}},[e,t,n,r]),vo(()=>{let K=g.current;K&&cc(K,i)},[i]),(0,Jn.useEffect)(()=>{o!==void 0&&(o===null&&A.current===null||(A.current=o,e.applyTheme?.(o)))},[e,o]),(0,Jn.useEffect)(()=>{_!==w.current&&(w.current=_,_!==void 0&&Ts.add(e),e.setSubmitLabel?.(_??null))},[e,_]),(0,So.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields"})}function Ri({label:e}){return(0,So.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,So.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,So.jsx)("span",{children:e}),(0,So.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var dc=/^#([0-9a-f]{6})$/i,Pd=/^#([0-9a-f]{3})$/i,pc=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,mc=/^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,vd=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,Cd=/^(-?\d+(?:\.\d+)?)(?:px)?$/,Sd=/^(-?\d+(?:\.\d+)?)em$/,wd=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,kd=/^[a-z][a-z0-9 -]{0,31}$/i,Rd=new Set(["none","uppercase","lowercase","capitalize"]);function yc(e){if(typeof e!="string")return null;let t=e.trim(),n=dc.exec(t);if(n){let g=Number.parseInt(n[1],16);return{r:g>>16&255,g:g>>8&255,b:g&255,a:null}}let r=Pd.exec(t);if(r){let[g,b,T]=r[1].split("").map(I=>Number.parseInt(I+I,16));return{r:g,g:b,b:T,a:null}}let o=pc.exec(t),a=o?null:mc.exec(t),i=o??a;if(!i)return null;let c=Number(i[1]),p=Number(i[2]),u=Number(i[3]);return c>255||p>255||u>255?null:{r:c,g:p,b:u,a:a?Number(a[4]):null}}function fc({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 Ma(e){if(typeof e!="string")return;let t=e.trim();if(dc.test(t)||pc.test(t))return t;let n=mc.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=yc(t);return r?fc(r):void 0}function _i(e,t=.12){let n=yc(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return fc({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function xa(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 wo(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=Cd.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function _d(e,t,n){if(typeof e!="string")return;let r=Sd.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Ed(e){let t=xa(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=xa(o," "),i=Ma(a[0]);if(!i)return;let c=r/(t.length-1)*100,p=a[1]===void 0?c:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),u=n[n.length-1]?.position??-1;if(!Number.isFinite(p)||p<0||p>100||p<u)return;n.push({color:i,position:p})}return{type:"linearGradient",angle:0,stops:n}}function Id(e){if(typeof e!="string")return;let t=e.trim(),n=Ma(t);if(n)return{type:"solid",color:n};let r=vd.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=Ed(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function Td(e){return e.type==="solid"?{type:"solid",color:_i(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:_i(t.color)}))}}function Ad(e){let t=!1,n,r=[];for(let p of xa(e," ")){if(p.toLowerCase()==="inset"){t=!0;continue}let u=Ma(p);if(u){n=u;continue}let g=wo(p,-128,128);if(g===void 0)return;r.push(g)}if(!n||r.length<2||r.length>4)return;let[o,a,i=0,c=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||i>128||Math.abs(c)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:i,spread:c}}function Md(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=xa(t,",").map(Ad);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function uc(e){if(typeof e!="string")return;let t=xa(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>kd.test(n)).slice(0,4);return t.length>0?t:void 0}function xd(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=wo(t[0],0,64),r=wo(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function Fd(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 gc({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=Id(r.background??r.backgroundColor),i=Ma(o?.colorPrimaryHover),c=i?{type:"solid",color:i}:a&&Td(a),p={fontFamilies:uc(r.fontFamily)??uc(n),fontSize:wo(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:Fd(r.fontWeight)??600,letterSpacing:_d(r.letterSpacing,-.1,.5)??.01,lineHeight:wo(r.lineHeight,.8,2)??1,textTransform:Rd.has(String(r.textTransform))?r.textTransform:"uppercase"},u=xd(r.padding),g=Md(r.boxShadow),b=wo(r.borderRadius,0,9999),T=typeof r.backdropFilter=="string"?wo(wd.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Ma(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...c?{hoverBackground:c}:{},typography:p,...u?{spacing:u}:{},...g?{shadow:g}:{},...b===void 0?{}:{borderRadius:b},disabledOpacity:e?.theme==="night"?.8:.6,...T===void 0?{}:{backdropBlur:T}}}function Qo(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)?_i(r,t):e}function As(e){if(typeof e=="number"||typeof e=="string")return e}function ea({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=b=>typeof b=="string"&&b?b:void 0,a=t.submitButton,i=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",c=n==="buttons",p=t.nameInput,u=o(p?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",g=gc({appearance:e,buttonsStyles:t,fontFamily:u});return{primaryColor:i,primaryHoverColor:o(r?.colorPrimaryHover)??Qo(i,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(p?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(c?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:u,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(As(p?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...g?{submitButton:g}:{}}}var d=require("react/jsx-runtime"),Fr="flopay_stripe_resume",hc="flopay_wallet_resume",Tc="fw1",Bd="fw2",Ac=300*1e3,Dd=900,Od=25e3,Ld=25e3,Nd=1e4,Mc=["payment_intent","payment_intent_client_secret","redirect_status"],Cr={provider:"paypal",paymentMethodCategory:"paypal"},Ud="x-flopay-process-result-source",zd="status";async function qd(e,t,n){try{let r=(await e.getUnifiedCheckoutSession(t,n)).data.session;if(r?.status==="complete")return null;if(r?.status==="authorized")return{status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}}catch{}}var Ei={},Ba=class{constructor(t){this.reason=t}};function Vd(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function Kt(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 Ls(e){return`${Bd}:${e}`}function Ii(e){return Kt(Ls(e))}function Ti(e,t){if(typeof window>"u")return null;let n=Ls(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>Ac||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Ii(e),null):o}catch{return Ii(e),null}}function jd(e){return Kt(Ls(e.sessionId),e)}function bc(e,t,n){let r=Ti(e,t);return!r||r.clientSecret!==n?!1:Ii(e)}function Ms(e,t,n){if(typeof window>"u")return;Ti(e,t)?.clientSecret===n&&Ii(e)}function $d(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function xs(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":ba(e.status),o=$d(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function Pc(e,t,n){let r=null;try{return await Promise.race([ql(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},Nd),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Wd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function xc(e){return e instanceof y.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Ai(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Sr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw xc(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Da="flopay_paypal_resume",Fa=new Map;function Fc(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(Da);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]=Ns();return e?Fc(t)!==null:!1}function Ns(){let e=new URLSearchParams(window.location.search);return Mc.map(t=>e.get(t))}function Us(){let e=new URL(window.location.href);for(let t of Mc)e.searchParams.delete(t);return e.toString()}function Kd(){Kt(Da),window.history.replaceState({},"",Us())}var Gd=250,vc="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 zs(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 Mi({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Sr.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 Fs(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Bc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=ho(n),i=a.firstName?a:ho(r?.name);return Un({email:(0,y.isValidEmail)(o)?o:r?.email?.trim(),firstName:i.firstName,lastName:i.lastName})}async function Jd({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let i=Bc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,y.isValidEmail)(i.email)?i:a(o,i)}var Oa=180,Cc=`flopay-card-enter ${Oa}ms cubic-bezier(0, 0, 0.2, 1) both`,Sc=`flopay-card-exit ${Oa}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Zd=`flopay-buttons-enter ${Oa}ms cubic-bezier(0, 0, 0.2, 1) both`,Qd=`flopay-buttons-exit ${Oa}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function ep(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function qs(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 tp={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function np(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 Bs={width:"100%",minHeight:Jo,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 rp(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function wc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ds(e){return e==="paypal"?"PayPal":(0,y.getStripeMethodDisplayName)(e)}function op(e){let t=(0,y.getPostalCodeExample)(e);return`Enter a valid ${(0,y.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function ap(e,t,n){let r=(0,y.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,i=a&&!o,c=a&&!!o&&!(0,y.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:i,malformed:c}}function ip(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 kc(e,t){return t instanceof y.FloPayError?t:new y.FloPayError(t instanceof Error?t.message:`${rp(e)} before-click hook failed.`,"validation_error")}function sp(e){return typeof e=="number"?`${e}px`:e}function xi(e){return(0,d.jsx)(lp,{...e})}function Rc({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:i=!1,onButtonClick:c,onDecline:p,onTechnicalFailure:u,runBeforeButtonClick:g,billingName:b,onBuyerIdentityReady:T,onLoadStateChange:I,placeholderBorderRadius:S,popupCapabilityOwner:A,externalTelemetryContext:_,presentationMode:P}){let w=Hr(),{emitInstrument:K}=(0,s.useContext)(or),k=(0,Zt.useStripe)(),ge=(0,Zt.useElements)(),z=(0,s.useMemo)(()=>bi(yn(w),_),[_,w]),[X,Se]=(0,s.useState)("loading");(0,s.useEffect)(()=>{I?.(X)},[X,I]);let[ae,De]=(0,s.useState)(!1),Ze=(0,s.useRef)(!1),le=!(0,y.isValidEmail)(n?.trim())||!b?.trim(),{request:Ee,collect:We,finish:Re}=zo(),Ie=(0,s.useRef)(!1),_e=(0,s.useRef)(null),ce=(0,s.useRef)(null),[ue,Pe]=(0,s.useState)(0),[Ae,J]=(0,s.useState)(!1),ee=(0,s.useRef)(!1),he=(0,s.useRef)(new Map),{startAttempt:U,finishAttempt:we,invalidateAttempt:ie,isAttemptInvalidated:Te,isAttemptCurrent:te,generationRef:it}=Sa((V,be,Qe)=>{u?.(V,be,{...Qe,popupBlocked:Qe?.popupBlocked??ao(be),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:P,terminalReason:"overlay_timeout"}),J(!0),Pe(Z=>Z+1)},{onHandoffObserved:()=>{A.markAvailable(),z?.log({name:"provider.popup.opened",stage:"overlay_open",...Cr,attempt:it.current})}});(0,s.useEffect)(()=>{Ae&&ce.current?.focus()},[Ae,ue]);let He=(0,s.useCallback)(()=>{Pe(V=>V+1)},[]),je=(0,s.useCallback)((V,be,Qe)=>{ie(Qe),u?.("paypal",V,{code:be,popupBlocked:ao(V),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:P}),J(!0),He()},[ie,u,P,He]),at=(0,s.useCallback)(()=>{window.setTimeout(()=>{(_e.current?.querySelector("iframe")??_e.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{ee.current&&(ee.current=!1,at())},[at,ue]);let Ke=(0,s.useCallback)(()=>{J(!1),a?.(null),at()},[at,a]);(0,s.useEffect)(()=>{if(!k||Ie.current)return;let[V,be,Qe]=Ns();if(!V||!be)return;let Z=Fc(be);if(!Z)return;Ie.current=!0;let Ne=!0,bt=Fa.get(be);bt||(bt=Qe==="failed"?Promise.resolve(null):Promise.resolve().then(()=>k.retrievePaymentIntent(be)),Fa.set(be,bt));let Ye={accountPatch:Z.accountPatch,sessionId:Z.sessionId,nonce:Z.nonce},_t=()=>{z?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Cr,requestCategory:"provider_sdk"})};return z?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Cr}),(async()=>{try{De(!0);let h=await bt;if(!Ne)return;if(h?.error){Fa.delete(be),_t(),a?.(h.error.message??"Failed to retrieve PayPal payment status.");return}if(Kd(),Fa.delete(be),Qe==="failed"){let Y="PayPal payment was declined. Please try again.";z?.terminal({outcome:"payment_declined",...Cr,terminalReason:"provider_declined"}),a?.(Y),p?.(mn("paypal",Y));return}let C=h?.paymentIntent;if(C&&C.id!==V){_t(),a?.("Failed to match the returned PayPal payment.");return}if(C&&(C.status==="requires_capture"||C.status==="succeeded")){let Y=typeof C.payment_method=="string"?C.payment_method:C.payment_method?.id;o({id:Y??C.id,type:"card",threeDSecureActionResultTokenId:C.id,isPaypal:!0},{...Ye,presentationMode:"redirect"})}else{let Y="PayPal payment was not completed. Please try again.";z?.terminal({outcome:C?.status==="canceled"?"payment_cancelled":"payment_declined",...Cr,terminalReason:C?.status==="canceled"?"cancelled":"provider_declined"}),a?.(Y),p?.(mn("paypal",Y))}}catch(h){if(!Ne)return;Fa.delete(be),_t(),a?.(h instanceof Error?h.message:"Failed to complete PayPal payment.")}finally{Ne&&De(!1)}})(),()=>{Ne=!1,Ie.current=!1}},[k,o,a,p,z]);let st=(0,s.useCallback)(async(V=!1)=>{let be=g?await g("paypal"):{proceed:!0};if(!be.proceed)return he.current.delete(ue),!1;let Qe=U("paypal");return he.current.set(ue,{generation:Qe,accountPatch:be.accountPatch,sessionId:be.sessionId,nonce:be.nonce}),J(!1),z?.log({name:`provider.${V?"redirect.started":"handoff.requested"}`,stage:V?"redirect":"overlay_open",...Cr,attempt:Qe}),c?.("paypal"),!0},[c,z,g,U,ue]),$e=(0,s.useCallback)(async V=>{if(i||ae||!await st()){V.reject();return}V.resolve()},[i,st,ae]),vt=(0,s.useCallback)(async V=>{if(!k||!ge)return;let be=he.current.get(ue);if(be&&!te(be.generation)){he.current.delete(ue);return}if(!be&&Te()||be&&!we(be.generation))return;be||we();let Qe=be??null;if(he.current.delete(ue),!Qe&&g){let j=await g("paypal");if(!j.proceed){V.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Qe={accountPatch:j.accountPatch,sessionId:j.sessionId,nonce:j.nonce}}let Z=Qe?.sessionId??e,Ne=Qe?.nonce??t,bt=await Jd({event:V,prepared:Qe,email:n,billingName:b,methodLabel:"PayPal",collect:We});if(!bt){V.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ye=bt.email,_t={...Qe?.accountPatch,...Un(bt,!0)};try{if(De(!0),a?.(null),!Z||!(0,y.isValidEmail)(Ye))throw new Error("Missing sessionId or email for PayPal payment");await T?.(bt);let j=k.createPaymentMethod,{error:h,paymentMethod:C}=await j({type:"paypal"});if(h){je(h,"stripe_paypal_create_payment_method_failed",be?.generation),V.paymentFailed({reason:"fail"});return}let Y=await Ai(r,K,Z,Ne??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:C?.id??null,intentKind:"payment"});if(Y.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let H=Y.clientSecret,ve={return_url:Us()};if(C?.id&&(ve.payment_method=C.id),!Kt(Da,{clientSecret:H,sessionId:Z,nonce:Ne,accountPatch:_t})&&P==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:B,paymentIntent:de}=await k.confirmPayment({clientSecret:H,confirmParams:ve,redirect:"if_required"});if(B){if(Kt(Da),Po(B)){let Me=B.message??"Your payment was declined.";z?.terminal({outcome:"payment_declined",...Cr,terminalReason:"provider_declined"}),a?.(Me),p?.(mn("paypal",Me,{code:Mr(B),declineCode:Vo(B)})),await Mi({billingApiUrl:r,sessionId:Z,nonce:Ne,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mr(B)??"provider_declined"}})}else je(B,"stripe_paypal_confirm_failed",be?.generation);return}Kt(Da);let D=typeof de?.payment_method=="string"?de.payment_method:de?.payment_method?.id;o({id:D??de?.id,type:"card",threeDSecureActionResultTokenId:de?.id,isPaypal:!0},{accountPatch:_t,paymentMethodCategory:"paypal",presentationMode:P,sessionId:Z,nonce:Ne});return}catch(j){je(j,"stripe_paypal_failed",be?.generation)}finally{De(!1)}},[k,ge,e,t,n,b,We,T,r,K,o,a,p,g,je,we,te,Te,z,P,ue]),Lt=(0,s.useCallback)(async()=>{if(!(Ze.current||i||ae||!k||!ge)){Ze.current=!0,De(!0);try{if(!await st(!0))return;await vt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Ze.current=!1,De(!1)}}},[ge,vt,i,st,k,ae]),ht=P==="redirect"?(0,d.jsx)("button",{type:"button",disabled:i||ae,onClick:()=>{Lt()},style:{width:"100%",minHeight:Jo,border:"1px solid #d1d5db",borderRadius:S??8,background:"#ffc439",color:"#111827",cursor:i||ae?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,d.jsx)(Zt.ExpressCheckoutElement,{onReady:V=>Se(Ta(V,["paypal"])),onLoadError:()=>{Se("load_error"),zs(z,"paypal","paypal","provider_error")},onClick:$e,onConfirm:vt,onCancel:()=>{let V=he.current.get(ue);he.current.delete(ue),z?.terminal({outcome:"payment_cancelled",...Cr,terminalReason:"cancelled",...V?{attempt:V.generation}:{}}),ie(V?.generation),J(!1),ee.current=!0,He()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:le,emailRequired:le,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ue),Tt=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{ref:_e,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ae&&(0,d.jsx)("button",{ref:ce,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ke,style:Bs,children:"Try PayPal again"}),Ee&&(0,d.jsx)(qo,{identity:Ee.identity,methodLabel:Ee.methodLabel,onComplete:Re,onCancel:()=>Re(null)},Ee.id),(0,d.jsx)("div",{style:{display:Ee?"none":void 0},children:ht})]}),ae&&!Ee&&(0,d.jsx)(zn,{status:"processing"})]});return P==="redirect"?Tt:(0,d.jsx)(Aa,{state:X,placeholderTestId:"flopay-paypal-placeholder",borderRadius:S,children:Tt})}function _c(e){return e==="apple_pay"||e==="google_pay"}function Ec({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:i,onErrorChange:c,onButtonClick:p,onDecline:u,onTechnicalFailure:g,runBeforeButtonClick:b,billingName:T,onBuyerIdentityReady:I,onLoadStateChange:S,placeholderBorderRadius:A,popupCapabilityOwner:_,externalTelemetryContext:P}){let w=Hr(),{emitInstrument:K}=(0,s.useContext)(or),k=(0,Zt.useStripe)(),ge=(0,Zt.useElements)(),z=(0,s.useMemo)(()=>bi(yn(w),P),[P,w]),[X,Se]=(0,s.useState)("loading");(0,s.useEffect)(()=>{S?.(X)},[X,S]);let[ae,De]=(0,s.useState)(!1),Ze=(0,s.useRef)(!(0,y.isValidEmail)(n?.trim())||!T?.trim()).current,{request:le,collect:Ee,finish:We}=zo(),Re=(0,s.useRef)(null),Ie=(0,s.useRef)(null),[_e,ce]=(0,s.useState)(0),[ue,Pe]=(0,s.useState)(!1),[Ae,J]=(0,s.useState)(()=>Ti(e,t)?"blocked":"idle"),[ee,he]=(0,s.useState)("google_pay"),U=(0,s.useRef)(null),we=(0,s.useRef)(!0),ie=(0,s.useRef)(!1),Te=(0,s.useRef)("google_pay"),te=(0,s.useRef)("google_pay"),it=(0,s.useRef)(null),He=(0,s.useRef)(null),je=(0,s.useRef)(new Set),at=(0,s.useRef)(null);(0,s.useEffect)(()=>(we.current=!0,()=>{we.current=!1;for(let j of je.current)window.clearTimeout(j);je.current.clear()}),[]);let Ke=(0,s.useRef)(new Map),{startAttempt:st,finishAttempt:$e,invalidateAttempt:vt,isAttemptInvalidated:Lt,isAttemptCurrent:ht,generationRef:Tt}=Sa((j,h,C)=>{g?.(j,h,{...C,popupBlocked:C?.popupBlocked??ao(h),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),he(j),Pe(!0),ce(Y=>Y+1)},{onHandoffObserved:j=>{_.markAvailable(),z?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Tt.current,...j==="apple_pay"||j==="google_pay"?{walletType:j}:{}})},defersMissingTerminal:_c,onMissingTerminalDeferred:(j,h)=>{let C=z?.now()??globalThis.performance?.now()??Date.now(),Y=at.current,H=Y?.generation===h?Y.startedAt:C;z?.performance({stage:"overlay_return",durationMs:Math.max(0,C-H),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:h,..._c(j)?{walletType:j}:{}}),z?.flush?.().catch(()=>{})}});(0,s.useEffect)(()=>{ue&&Ie.current?.focus()},[ue,_e]);let V=(0,s.useCallback)(()=>{ce(j=>j+1)},[]),be=(0,s.useCallback)((j,h,C,Y,H=!1)=>{vt(Y),g?.(j,h,{code:C,popupBlocked:ao(h),telemetryReported:H,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),he(j),Pe(!0),V()},[vt,g,V]),Qe=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Re.current?.querySelector("iframe")??Re.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{ie.current&&(ie.current=!1,Qe())},[Qe,_e]);let Z=(0,s.useCallback)(()=>{Pe(!1),c?.(null),Qe()},[Qe,c]),Ne=(0,s.useCallback)(()=>{U.current?.()},[]);(0,s.useEffect)(()=>{let j=Ti(e,t);if(!j)return;let h=!1,C=!1,Y=async()=>{if(!C){C=!0,h||J("checking");try{let H=await Pc(k,j.clientSecret,je.current);if(h)return;let ve=xs(H,j.providerObjectId,(0,y.isSetupIntentClientSecret)(j.clientSecret));if(ve.kind==="confirmed"){if(!bc(e,t,j.clientSecret))return;U.current=null,J("idle"),i({id:ve.paymentMethodId,type:"card",threeDSecureActionResultTokenId:ve.intentId},{...j.accountPatch?{accountPatch:j.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(ve.kind==="terminal"){Ms(e,t,j.clientSecret),U.current=null,J("idle"),he(j.paymentMethodType),Pe(!0),V();return}J("blocked")}catch{h||J("blocked")}finally{C=!1}}};return U.current=Y,J("blocked"),()=>{h=!0,U.current===Y&&(U.current=null)}},[t,i,V,e,k]);let bt=(0,s.useCallback)(async j=>{let h=!1,C=dt=>{h||(h=!0,j.paymentFailed({reason:"fail",...dt?{message:dt}:{}}))};if(!k||!ge){C();return}let Y=Ke.current.get(_e);if(Y&&!ht(Y.generation)){Ke.current.delete(_e),C();return}if(!Y&&Lt()){C();return}if(Y&&!$e(Y.generation)){C();return}Y||$e();let H=j.expressPaymentType??Y?.method??Te.current,ve=Y??null,x=wc(H),B;H==="apple_pay"?B="apple_pay":H==="google_pay"&&(B="google_pay");let de=Y?.generation??Tt.current,D=z,Me=D?.now()??globalThis.performance?.now()??Date.now(),lt=new AbortController,yt=!1,Ct=!1,Be=null,Tn=e,Vn="processing",gn="other",jt="provider_runtime",jn,$n=new Promise((dt,rt)=>{jn=rt}),vn=window.setTimeout(()=>{yt=!0,lt.abort(),jn(Ei)},Od),Dt=async(dt,rt,An)=>{Vn=dt,gn=rt,jt=rt==="intent_create"||rt==="session_claim"?"transport_error":"provider_runtime";let Mt=D?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([An,$n])}finally{let Wn=D?.now()??globalThis.performance?.now()??Date.now();D?.performance({stage:dt,durationMs:Math.max(0,Wn-Mt),durationMode:"machine",requestCategory:rt,paymentMethodCategory:"wallet",provider:"stripe",...yt?{statusClass:"timeout"}:{}})}};try{if(De(!0),c?.(null),!ve&&b){let Oe=await Dt("processing","other",b(x));if(!Oe.proceed){C();return}ve={accountPatch:Oe.accountPatch,sessionId:Oe.sessionId,nonce:Oe.nonce}}let dt=ve?.sessionId??e;Tn=dt;let rt=ve?.nonce??t,An=it.current??ve?.accountPatch,Mt=Bc({event:j,fallbackEmail:An?.email??n,fallbackName:[An?.firstName,An?.lastName].join(" ").trim()||T});if(!(0,y.isValidEmail)(Mt.email)){C("Buyer details are required."),Ee(Ds(H),Mt).then(Oe=>{Oe&&(it.current=Oe)});return}it.current=null;let Wn={...ve?.accountPatch,...Un(Mt,!0)};await Dt("processing","session_claim",Promise.resolve(I?.(Mt)));let{error:hn}=await Dt("tokenization","provider_sdk",ge.submit());if(hn){C(),be(H,hn,"stripe_wallet_submit_failed",Y?.generation);return}if(!dt)throw new Error("Missing sessionId or email for payment.");let $t={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H,paymentMethodId:null,intentKind:o},en=JSON.stringify({sessionId:dt,nonce:rt??"",request:$t}),cr=He.current,Qn=cr?.retryIdentity===en?cr.authorizationAttemptId:(0,y.randomUuidV4)();He.current={authorizationAttemptId:Qn,retryIdentity:en};let tn=await Dt("processing","intent_create",Ai(r,K,dt,rt??"",{...$t,authorizationAttemptId:Qn},{signal:lt.signal}));if(tn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let xt=tn.clientSecret,nn=jd({createdAt:Date.now(),sessionId:dt,...rt?{nonce:rt}:{},clientSecret:xt,providerObjectId:tn.providerObjectId,paymentMethodType:H,accountPatch:Wn});window.clearTimeout(vn),Ct=!0,D?.performance({stage:"callback",durationMs:Math.max(0,(D?.now()??globalThis.performance?.now()??Date.now())-Me),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let sn=D?.now()??globalThis.performance?.now()??Date.now(),Nt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...B?{walletType:B}:{},attempt:de},cn=!1,zt=null;D?.log({name:"payment.provider_confirmation.started",...Nt}),Be=window.setTimeout(()=>{Be!==null&&je.current.delete(Be),cn=!0;let Oe=D?.now()??globalThis.performance?.now()??Date.now();D?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Nt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Oe-sn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),D?.flush?.().catch(()=>{}),zt?.()},Ld),je.current.add(Be);let ln=(Oe,mt)=>{Be!==null&&(window.clearTimeout(Be),je.current.delete(Be),Be=null);let v=D?.now()??globalThis.performance?.now()??Date.now(),et=Math.max(0,v-sn),pe=Oe;cn&&(Oe==="resolved"?pe="resolved_late":Oe==="returned_error"?pe="returned_error_late":pe="rejected_late");let Cn=mt??(Oe==="resolved"?"approved":"provider_error");return D?.log({name:"payment.provider_confirmation.returned",...Nt,operationOutcome:pe,terminalReason:Cn}),D?.performance({...Nt,durationMs:et,durationMode:"buyer",operationOutcome:pe,terminalReason:Cn}),{durationMs:et,operationOutcome:pe,terminalReason:Cn}},Ut=!1,me=!1,ur=Oe=>{if(!Oe||typeof Oe!="object")return null;let mt=Oe;if(mt.error)return null;let v=mt.setupIntent??mt.paymentIntent,et=xs(v??null,void 0,!!mt.setupIntent);return et.kind==="confirmed"?et:null},dr=Oe=>{if(Ut||Y&&Tt.current!==Y.generation)return;let mt=ur(Oe);if(!mt)return;if(nn&&!bc(dt,rt,xt)){Ut=!0;return}let{intentId:v,paymentMethodId:et}=mt;Ut=!0,me=!0,He.current=null,U.current=null,we.current&&(J("idle"),De(!1));let pe=`${Tc}:${dt}`;Kt(pe,{createdAt:Date.now(),sessionId:dt,nonce:rt,accountPatch:Wn,paymentMethodId:et,providerIntentId:v,paymentMethodType:H});try{i({id:et,type:"card",threeDSecureActionResultTokenId:v},{accountPatch:Wn,paymentMethodCategory:"wallet",sessionId:dt,nonce:rt})}finally{Kt(pe)}},pr=!1;zt=async()=>{if(!(pr||Ut||me)){pr=!0,we.current&&J("checking");try{let Oe=await Pc(k,xt,je.current);if(Ut||me)return;let mt=(0,y.isSetupIntentClientSecret)(xt),v=xs(Oe,tn.providerObjectId,mt);if(v.kind==="confirmed"){dr(mt?{setupIntent:Oe}:{paymentIntent:Oe});return}if(v.kind==="terminal"){if(me=!0,Ms(dt,rt,xt),He.current=null,U.current=null,!we.current)return;J("idle"),C(),be(H,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",Y?.generation,!0);return}we.current&&!me&&(J("blocked"),De(!1))}catch{we.current&&!me&&(J("blocked"),De(!1))}finally{pr=!1}}},U.current=zt;let rn,Mn;try{let Oe=await((0,y.isSetupIntentClientSecret)(xt)?k.confirmSetup({elements:ge,clientSecret:xt,redirect:"if_required"}):k.confirmPayment({elements:ge,clientSecret:xt,redirect:"if_required"}));if(!Oe||typeof Oe!="object")throw new Ba(Vd(Oe));if(rn=Oe,!rn.error&&!ur(rn))throw new Ba("confirmation_result_unconfirmed");Mn=ln(rn.error?"returned_error":"resolved",rn.error&&Po(rn.error)?"provider_declined":void 0)}catch(Oe){let mt=Oe instanceof Ba?Oe.reason:void 0,v=mt!==void 0,et=ln(v?"returned_error":"rejected");if(D?.error({...v?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:mt}:ms(Oe),...Nt,operationOutcome:et.operationOutcome,durationMs:et.durationMs,statusClass:"unknown",terminalReason:et.terminalReason}),!we.current||Ut)return;await zt?.();return}let wn=rn.error;if(wn){if(!we.current||Ut)return;if(Po(wn)){me=!0,Ms(dt,rt,xt),He.current=null,U.current=null,J("idle");let Oe=wn.message??"Your payment was declined.";C(Oe),c?.(Oe),u?.(mn(x,Oe,{code:Mr(wn),declineCode:Vo(wn)})),Mi({billingApiUrl:r,sessionId:dt,nonce:rt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H,providerDeclineReason:Mr(wn)??"provider_declined",...tn.intentKind==="payment"&&tn.providerObjectId.startsWith("pi_")?{providerIntentId:tn.providerObjectId}:{}}})}else D?.error({...ms(wn),...Nt,operationOutcome:Mn.operationOutcome,durationMs:Mn.durationMs,statusClass:"unknown",terminalReason:Mn.terminalReason}),await zt?.();return}if(dr(rn),!Ut)throw new Error("Invalid provider returned for APM intent")}catch(dt){if(dt===Ei){let rt=D?.now()??globalThis.performance?.now()??Date.now();D?.error({errorCode:Wd(gn),stage:Vn,requestCategory:gn,paymentMethodCategory:"wallet",provider:"stripe",...B?{walletType:B}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Tn,durationMs:Math.max(0,rt-Me),statusClass:"timeout",failureCategory:jt,attempt:de,terminalReason:"provider_error"}),D?.flush?.().catch(()=>{})}C(),be(H,dt,dt===Ei?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",Y?.generation,dt===Ei)}finally{if(window.clearTimeout(vn),Be!==null&&(window.clearTimeout(Be),je.current.delete(Be)),!Ct){let dt=D?.now()??globalThis.performance?.now()??Date.now();D?.performance({stage:"callback",durationMs:Math.max(0,dt-Me),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...yt?{statusClass:"timeout"}:{}})}we.current&&De(!1)}},[k,ge,e,t,n,T,Ee,I,r,K,o,i,c,u,b,be,$e,ht,Lt,Tt,z,_e]),Ye=(0,s.useMemo)(()=>vi(a),[a]),_t=(0,s.useMemo)(()=>a.map(y.stripeExpressMethodToOptionKey),[a]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Aa,{state:X,placeholderTestId:"flopay-wallet-placeholder",borderRadius:A,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:[ue&&(0,d.jsxs)("button",{ref:Ie,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Z,style:Bs,children:["Try ",Ds(ee)," again"]}),Ae!=="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:Ne,disabled:Ae==="checking",style:Bs,children:Ae==="checking"?"Checking payment status\u2026":"Check payment status"})]}),le&&(0,d.jsx)(qo,{identity:le.identity,methodLabel:le.methodLabel,onComplete:We,onCancel:()=>We(null)},le.id),Ae==="idle"&&(0,d.jsx)("div",{style:{display:le?"none":void 0},children:(0,d.jsx)(Zt.ExpressCheckoutElement,{onReady:j=>{Se(Ta(j,_t))},onLoadError:j=>{Se("load_error"),zs(z,"stripe","wallet","provider_error")},onClick:async j=>{let h=z?.now()??globalThis.performance?.now()??Date.now();Te.current=j.expressPaymentType,te.current=wc(j.expressPaymentType);let C=!0,Y=window.setTimeout(()=>{C=!1,j.reject()},Dd),H=b?await b(te.current):{proceed:!0};if(window.clearTimeout(Y),!C)return;if(!H.proceed){Ke.current.delete(_e),j.reject();return}let ve=st(j.expressPaymentType);at.current={generation:ve,startedAt:h},Ke.current.set(_e,{generation:ve,method:j.expressPaymentType,accountPatch:H.accountPatch,sessionId:H.sessionId,nonce:H.nonce}),Pe(!1),z?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ve,...j.expressPaymentType==="apple_pay"||j.expressPaymentType==="google_pay"?{walletType:j.expressPaymentType}:{}}),p?.(te.current),j.resolve()},onConfirm:bt,onCancel:()=>{let j=Ke.current.get(_e);Ke.current.delete(_e),z?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...j?{attempt:j.generation}:{}}),vt(j?.generation),He.current=null,Pe(!1),ie.current=!0,V()},options:{...Ci,paymentMethods:Ye,emailRequired:Ze,billingAddressRequired:Ze}},_e)})]})}),ae&&(0,d.jsx)(zn,{status:"processing"})]})}function Dc(e,t,n){let r=(0,y.resolveSetupFutureUsage)(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...r?{setupFutureUsage:r}:null}}function Os({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:c,onErrorChange:p,onDecline:u,onCancel:g,runBeforeButtonClick:b,onButtonClick:T,isProcessing:I,submitButtonColor:S,submitButtonBorderRadius:A,submitButtonStyle:_,errorText:P}){let w=Hr(),{emitInstrument:K}=(0,s.useContext)(or),k=(0,Zt.useStripe)(),ge=(0,Zt.useElements)(),[z,X]=(0,s.useState)(!1),Se=(0,s.useRef)(!1),[ae,De]=(0,s.useState)(!1),[Ze,le]=(0,s.useState)("loading"),[Ee,We]=(0,s.useState)(""),Re=!(0,y.isValidEmail)(r?.trim()),Ie=!Re||(0,y.isValidEmail)(Ee.trim()),_e=(0,s.useCallback)(async()=>{if(!k||!ge||I||Se.current||!ae)return;Se.current=!0,X(!0);let ce=b?await b("card"):{proceed:!0};if(!ce.proceed){Se.current=!1,X(!1);return}T?.("card");let ue=ce.sessionId??t,Pe=ce.nonce??n,Ae=ho(o?.trim()),J=Un({email:ce.accountPatch?.email?.trim()||r?.trim()||Ee.trim(),firstName:ce.accountPatch?.firstName?.trim()||Ae.firstName,lastName:ce.accountPatch?.lastName?.trim()||Ae.lastName}),ee=J.email,he=Un({...ce.accountPatch,...J});try{if(p?.(null),!(0,y.isValidEmail)(ee))throw new Error("A valid email address is required for payment.");await a?.(J);let U=await ge.submit();if(U.error){p?.(U.error.message??"Payment failed.");return}let we=[J.firstName,J.lastName].filter(Boolean).join(" "),ie=await k.createPaymentMethod({elements:ge,params:{billing_details:{email:ee,...we?{name:we}:{}}}});if(ie.error||!ie.paymentMethod){p?.(ie.error?.message??"Failed to create payment method.");return}let Te=ie.paymentMethod;if(!ue||!ee)throw new Error("Missing sessionId or email for payment.");let te=Te.type||e,it=await Ai(i,K,ue,Pe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,paymentMethodId:null,intentKind:"payment"});if(it.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let He=it.clientSecret;Kt(Fr,{clientSecret:He,sessionId:ue,nonce:Pe,accountPatch:he,paymentMethodId:Te.id,paymentMethodType:Te.type??e,gateway:"stripe"});let{error:je,paymentIntent:at}=await k.confirmPayment({clientSecret:He,confirmParams:{return_url:window.location.href,payment_method:Te.id},redirect:"if_required"});if(je){Kt(Fr);let $e=je.message??"Payment failed.";p?.($e),u?.(mn("card",$e,{code:je.code})),await Mi({billingApiUrl:i,sessionId:ue,nonce:Pe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:je.code??"provider_declined"}});return}let Ke=at?.status;if(!ba(Ke)){Kt(Fr);let $e=Ke==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.($e),u?.(mn("card",$e,{code:Ke??"missing_payment_intent"}));return}Kt(Fr);let st=typeof at?.payment_method=="string"?at.payment_method:at?.payment_method?.id;c({id:st??Te.id,type:"card",threeDSecureActionResultTokenId:at?.id,gateway:"stripe",paymentMethodType:Te.type??e},{accountPatch:he,paymentMethodCategory:"apm",sessionId:ue,nonce:Pe})}catch(U){p?.(U instanceof Error?U.message:"Payment failed. Please try again.")}finally{Se.current=!1,X(!1)}},[k,ge,I,ae,b,T,t,n,r,o,Ee,a,i,K,e,c,p,u]);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:Ee,onChange:ce=>We(ce.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(Zt.PaymentElement,{onReady:()=>le("ready"),onLoadError:()=>{le("load_error"),zs(yn(w),"stripe","apm")},onChange:ce=>{De(!!ce.complete)},options:{layout:Si,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,y.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,d.jsx)(wi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{_e()},disabled:!ae||!Ie||z||I||Ze!=="ready",color:S,borderRadius:A,style:_,children:z?"Processing\u2026":`Pay with ${(0,y.getStripeMethodDisplayName)(e)}`}),P&&(0,d.jsx)($o,{margin:"0.75rem 0 0",children:P})]})}function Ic({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:i,stripeInstance:c,paymentElementBaseOptions:p,futureUseSession:u,onTokenizedBody:g,onErrorChange:b,onButtonClick:T,onDecline:I,runBeforeButtonClick:S,onLoadStateChange:A,isProcessing:_=!1,submitButtonColor:P="#4A49FF",submitButtonBorderRadius:w=8,submitButtonStyle:K,buttonAppearance:k,themeId:ge,onExpandApm:z,expandedApmMethod:X}){let{emitInstrument:Se}=(0,s.useContext)(or),[ae,De]=(0,s.useState)(null),[Ze,le]=(0,s.useState)(null),Ee=(0,s.useRef)(!1),{request:We,collect:Re,finish:Ie}=zo();(0,s.useEffect)(()=>{i.length>0&&c?A?.("ready"):c||A?.("loading")},[i.length,c,A]);let _e=(0,s.useCallback)(async ee=>{if(!c||Ee.current||_)return;Ee.current=!0,le(ee);let he=S?await S("card"):{proceed:!0};if(!he.proceed){Ee.current=!1,le(null);return}T?.("card");let U=he.sessionId??e,we=he.nonce??t,ie=ho([he.accountPatch?.firstName,he.accountPatch?.lastName].filter(Boolean).join(" ")||r),Te=Un({email:he.accountPatch?.email?.trim()||n?.trim(),firstName:he.accountPatch?.firstName?.trim()||ie.firstName,lastName:he.accountPatch?.lastName?.trim()||ie.lastName});if(!(0,y.isValidEmail)(Te.email)){le(null);let He=await Re((0,y.getStripeMethodDisplayName)(ee),Te);if(!He){Ee.current=!1;return}Te=He,le(ee)}let te=Te.email,it=Un({...he.accountPatch,...Te});try{if(b?.(null),!U||!(0,y.isValidEmail)(te))throw new Error("Missing sessionId or email for payment.");await o?.(Te);let He=await Ai(a,Se,U,we??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,paymentMethodId:null,intentKind:"payment"});if(He.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let je=He.clientSecret;Kt(Fr,{clientSecret:je,sessionId:U,nonce:we,accountPatch:it,paymentMethodType:ee,gateway:"stripe"});let{error:at,paymentIntent:Ke}=await c.confirmPayment({clientSecret:je,confirmParams:{return_url:window.location.href,payment_method_data:{type:ee,billing_details:{name:[Te.firstName,Te.lastName].filter(Boolean).join(" "),...te?{email:te}:{}}}},redirect:"if_required"});if(at){Kt(Fr);let vt=at.message??"Payment failed.";b?.(vt),I?.(mn("card",vt,{code:at.code})),await Mi({billingApiUrl:a,sessionId:U,nonce:we,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,providerDeclineReason:at.code??"provider_declined"}});return}let st=Ke?.status;if(!ba(st)){Kt(Fr);let vt=st==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";b?.(vt),I?.(mn("card",vt,{code:st??"missing_payment_intent"}));return}Kt(Fr);let $e=typeof Ke?.payment_method=="string"?Ke.payment_method:Ke?.payment_method?.id;g({id:$e??Ke?.id,type:"card",threeDSecureActionResultTokenId:Ke?.id,gateway:"stripe",paymentMethodType:ee},{accountPatch:it,paymentMethodCategory:"apm",sessionId:U,nonce:we})}catch(He){b?.(He instanceof Error?He.message:"Payment failed. Please try again.")}finally{Ee.current=!1,le(null)}},[c,_,S,T,e,t,n,Re,a,Se,r,o,g,b,I]),[ce,ue]=(0,s.useState)(null),Pe=z?X??null:ce,Ae=(0,s.useCallback)(ee=>{Ee.current||_||Pe&&Pe!==ee||((0,y.needsStripeMethodExplicitConfirm)(ee)?z?z(ee):ue(ee):_e(ee))},[Pe,_,_e,z]),J=(0,s.useMemo)(()=>ce?Dc(p,ce,u):null,[ce,p,u]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:We?(0,d.jsx)(qo,{identity:We.identity,methodLabel:We.methodLabel,onComplete:Ie,onCancel:()=>Ie(null)},We.id):i.map(ee=>{let he=X===ee,U=Ze===ee,we=Ze!==null&&Ze!==ee||X!=null&&X!==ee;return(0,d.jsxs)(s.default.Fragment,{children:[(0,d.jsx)(Pi,{method:ee,themeId:ge,submitting:U,disabled:we,highlighted:he,hasNextStep:(0,y.needsStripeMethodExplicitConfirm)(ee),onClick:()=>Ae(ee),backgroundColor:k?.backgroundColor,borderColor:k?.borderColor,textColor:k?.textColor,borderRadius:k?.borderRadius,fontFamily:k?.fontFamily}),!z&&ce===ee&&J&&c&&(0,d.jsx)(Zt.Elements,{stripe:c,options:J,children:(0,d.jsx)(Os,{method:ee,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:g,onErrorChange:b,onDecline:I,onCancel:()=>ue(null),runBeforeButtonClick:S,onButtonClick:T,isProcessing:_,submitButtonColor:P,submitButtonBorderRadius:w,submitButtonStyle:K})},ee)]},ee)})})}function lp({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:i,onError:c,onDecline:p,onTokenizedBody:u,firstName:g,lastName:b,chv:T,className:I,submitLabel:S,isProcessing:A,error:_,onErrorChange:P,showPayPal:w=!0,showStripe:K=!0,walletPresentation:k="auto",enabledPaymentMethods:ge,enabledPaymentMethodCountries:z,showApplePay:X=!0,showGooglePay:Se=!0,layout:ae="default",theme:De,buttonsTheme:Ze,buttonsStyles:le,appearance:Ee,cardButtonContent:We,cardBackButtonContent:Re,cardTitleContent:Ie,showSecurityFooter:_e,onButtonClick:ce,onBeforeButtonClick:ue,onBuyerIdentityReady:Pe,enableAVS:Ae,cardFieldOrder:J,cardPreFormSlot:ee,avsLayout:he="row",country:U,zip:we,addressLine1:ie,addressLine2:Te,city:te,state:it,onCountryChange:He,onZipChange:je,avsCheck:at,checkoutType:Ke,checkoutLayout:st,totalAmount:$e=0,currency:vt="usd",initialCardOpen:Lt=!1,directPaypal:ht,isSubscription:Tt=!1,session:V,dataAttachmentPending:be=!1,dataAttachmentRequiresIdentity:Qe=!1,debug:Z=!1}){let Ne=Hr(),bt=ti(),Ye=(0,s.useContext)(Pr),{emitInstrument:_t}=(0,s.useContext)(or),j=(0,s.useRef)(null);j.current||(j.current=ai());let h=j.current,[,C]=(0,s.useState)(0),Y=(0,s.useRef)(null);Y.current||(Y.current=Kr());let H=Y.current,ve=(0,s.useMemo)(()=>({browser:H,capability:h,presentationMode:"popup"}),[H,h]),x=V??Ye.session,B=(0,s.useMemo)(()=>({futureUse:x?.futureUse,futureUseUnsupported:x?.futureUseUnsupported}),[x?.futureUse,x?.futureUseUnsupported]),de=x?.gateways?.paypal?.providerObjectType??ht?.providerObjectType,D=be||Ye.claimPending===!0,Me=Qe||Ye.claimRequiresIdentity===!0,lt=D&&!Me,yt=Kl(),Ct=n||yt,[Be,Tn]=(0,s.useState)(!1),[Vn,gn]=(0,s.useState)(null),[jt,jn]=(0,s.useState)(U??""),[$n,vn]=(0,s.useState)(we??""),[Dt,dt]=(0,s.useState)(ie??""),[rt,An]=(0,s.useState)(Te??""),[Mt,Wn]=(0,s.useState)(te??""),[hn,$t]=(0,s.useState)(it??""),[en,cr]=(0,s.useState)(""),[Qn,tn]=(0,s.useState)({}),xt=(0,s.useRef)(we??""),nn=(0,s.useRef)(U??""),sn=(0,s.useRef)(ie??""),Nt=(0,s.useRef)(Te??""),cn=(0,s.useRef)(te??""),zt=(0,s.useRef)(it??""),ln=(0,s.useRef)(""),Ut=(0,s.useRef)({});(0,s.useEffect)(()=>{let l=(E,oe,Ve,fe,Ue)=>{if(Ut.current[E])return;let Jt=oe?.trim();!Jt||Jt===Ve.current||(Ve.current=Jt,fe(Jt),Ue?.(Jt))};l("country",U,nn,jn,He),l("zip",we,xt,vn,je),l("addressLine1",ie,sn,dt),l("addressLine2",Te,Nt,An),l("city",te,cn,Wn),l("state",it,zt,$t)},[U,we,ie,Te,te,it,He,je]);let me=(0,s.useMemo)(()=>(0,y.resolveAVSConfig)(Ae),[Ae]),ur=me!==null,dr=(0,s.useMemo)(()=>(0,y.isAuthorizationOnlySession)(V),[V]),pr=!!V?.vault?.html,rn=!!V?.gateways?.pcivault,Mn=us(V),Oe=!!(V?.gateways?.stripe?.enabledPaymentMethods??ge)?.includes("card")||Qr(V),mt=pr||Oe||rn,v=!!(K&&mt&&e),[et,pe]=(0,s.useState)(()=>ae!=="buttons"||Lt?e??null:null),[Cn,Hn]=(0,s.useState)(0),Gt=ae!=="buttons"||Lt||!!e&&et===e,xn=V?.captureMethod,ft=(0,s.useRef)(Ne);(0,s.useEffect)(()=>{ft.current=Ne},[Ne]);let[mr,uo]=(0,s.useState)(null);(0,s.useEffect)(()=>{if(!v||!e||!Gt){uo(null);return}let l=ft.current?ft.current.cardCapture({sessionId:e,captureMethod:xn}):new Sr.PciVaultCardCapture({sessionId:e,captureMethod:xn,billingApiUrl:Ct,telemetry:r});return uo({sessionId:e,captureMethod:xn,billingApiUrl:Ct,telemetry:r,capture:l}),()=>{l.unmount()}},[v,e,Gt,xn,Ct,r]);let Ft=v&&e&&Gt&&mr?.sessionId===e&&mr.captureMethod===xn&&mr.billingApiUrl===Ct&&mr.telemetry===r?mr.capture:null,Fn=(0,s.useMemo)(()=>{let l=jt,E=me?(0,y.isAVSFieldVisible)(me.postal_code,l):!1;return ap(l,$n,E)},[me,jt,$n]),{avsInvalid:wr,invalidAvsFields:er}=(0,s.useMemo)(()=>{let l={line1:!1,city:!1,state:!1,zip:!1};if(!v||!me)return{avsInvalid:!1,invalidAvsFields:l};let E=jt,oe=(Ue,Jt)=>(0,y.isAVSFieldVisible)(Ue,E)&&!Jt.trim(),Ve={line1:oe(me.address_line_1,Dt),city:oe(me.city,Mt),state:oe(me.state,hn),zip:Fn.empty||Fn.malformed};return{avsInvalid:Ve.line1||Ve.city||Ve.state||Ve.zip,invalidAvsFields:Ve}},[v,me,jt,Dt,Mt,hn,Fn]),[Yt,yr]=(0,s.useState)(!1),[Bn,Or]=(0,s.useState)(!1),[Dn,kr]=(0,s.useState)(!1),[Rr,Lr]=(0,s.useState)({line1:!1,city:!1,state:!1}),Kn=(0,s.useRef)(!1),tr=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Nr=(0,s.useRef)(!1),Ot=(0,s.useCallback)(l=>{tr.current[l]=!0,Nr.current=!0},[]),kn=(0,s.useCallback)(l=>!Kn.current&&tr.current[l],[]),nr=(0,s.useCallback)(l=>{kn(l)&&Lr(E=>E[l]?E:{...E,[l]:!0})},[kn]),[Ur,zr]=(0,s.useState)(()=>Fs(V?.vault)),[ct,un]=(0,s.useState)(Lt&&mt?"card":"buttons"),[dn,Rn]=(0,s.useState)(null),po=ct==="expanding"||ct==="card",_r=V?.gateways?.stripe&&!Mn?"stripe":void 0,Zr=(0,s.useCallback)(()=>{_t?.({class:"card_surface",provider:_r})},[_r,_t]),_n=(0,s.useRef)(null),pn=(0,s.useCallback)(l=>{_n.current&&clearTimeout(_n.current),_n.current=setTimeout(()=>{_n.current=null,l()},Oa)},[]);(0,s.useEffect)(()=>()=>{_n.current&&clearTimeout(_n.current)},[]);let qr=(0,s.useCallback)(()=>{Zr(),pe(e??null),Hn(l=>l+1),un("expanding"),pn(()=>un("card"))},[pn,Zr,e]),On=(0,s.useCallback)(()=>{un("collapsing"),pn(()=>un("buttons"))},[pn]),L=(0,s.useCallback)(l=>{Rn(l),un("apm-expanding"),pn(()=>un("apm-form"))},[pn]),q=(0,s.useCallback)(()=>{un("apm-collapsing"),pn(()=>{un("buttons"),Rn(null)})},[pn]);(0,s.useEffect)(()=>{ae==="buttons"&&Lt&&mt&&(pe(e??null),un("card"))},[ae,Lt,mt,e]);let[re,$]=(0,s.useState)(null),gt=(0,s.useRef)(!1),Et=(0,s.useRef)(null),se=(0,s.useRef)("idle"),[Xe,Q]=(0,s.useState)(!1),f=(0,s.useRef)(Xe);f.current=Xe;let[m,N]=(0,s.useState)(()=>ht?.existingOrderId?{orderId:ht.existingOrderId,attempts:1}:null),W=(0,s.useRef)(m);(0,s.useEffect)(()=>{W.current=m},[m]);let Ce=(0,s.useRef)(null),xe=(0,s.useMemo)(()=>{if(Pe||Ye.claimBuyerIdentity||V?.buyerIdentified!==!1||!e||!t)return;let l=`${Ct}|${e}|${t}`;Ce.current?.key!==l&&(Ce.current={key:l,claim:No(new Sr.PaymentAPI(Ct,{telemetry:!1}),e,t,{...a?{userId:a}:{},...g?{firstName:g}:{},...b?{lastName:b}:{}})});let E=Ce.current.claim;return async oe=>{await E(oe)}},[Pe,Ye.claimBuyerIdentity,V?.buyerIdentified,e,t,Ct,a,g,b]),tt=Pe??Ye.claimBuyerIdentity??xe,Pt=_??Vn,Le=(0,s.useMemo)(()=>(0,y.resolveTheme)(De),[De]),F=(0,s.useMemo)(()=>{let l=Le?.buttonsLayout??(0,y.resolveButtonsLayoutTheme)(Ze);return le?{...l,...le,cardButton:{...l.cardButton,...le.cardButton},cardFormContainer:{...l.cardFormContainer,...le.cardFormContainer},backButton:{...l.backButton,...le.backButton},backButtonIcon:{...l.backButtonIcon,...le.backButtonIcon},submitButton:{...l.submitButton,...le.submitButton},title:{...l.title,...le.title}}:l},[Le,Ze,le]),St=Ee??Le?.appearance,Fe=(0,s.useMemo)(()=>ea({appearance:St,buttonsStyles:F,layout:ae}),[St,F,ae]),ke=Ye.inlineSessionPatchProcessing??!1,G=(A??Be)||ke,ye=Ct.replace(/\/+$/,""),ne=(0,s.useMemo)(()=>ps({userId:a,email:o,firstName:g,lastName:b,country:U,zip:we},Qn),[a,o,g,b,U,we,Qn]),wt=[ne.firstName,ne.lastName].filter(l=>!!l?.trim()).join(" "),Ge=!(0,y.isValidEmail)(ne.email?.trim()),fr=(0,s.useRef)(null);v&&fr.current===null&&(fr.current=Ge);let En=v&&(fr.current??Ge),ji=(0,s.useMemo)(()=>ip(en,En),[en,En]),Ro=ji.empty||ji.malformed,Gn=(0,s.useMemo)(()=>Ne?Ne.getRawProvider():null,[Ne]),Js=(0,s.useMemo)(()=>bt?bt.getRawProvider():null,[bt]),oa=$e||100,_o=vt.toLowerCase(),$i=(0,s.useMemo)(()=>St?(0,Sr.toStripeAppearance)(St):null,[St]),Eo=$i,Zs=(0,s.useMemo)(()=>{let l=$i??{},E=l.rules??{};return{...l,rules:{...E,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...E[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...E[".AccordionItemContents"]??{}}}}},[$i]),Qs=(0,s.useMemo)(()=>({...Vl($e,x?.captureMethod,B),currency:_o,...Eo?{appearance:Eo}:null}),[$e,_o,x?.captureMethod,B,Eo]),Wi=(0,y.resolveSetupFutureUsage)(B,"paypal","paypal"),el=(0,s.useMemo)(()=>({mode:"payment",amount:oa,currency:_o,captureMethod:"manual",...Wi?{setupFutureUsage:Wi}:null,...Eo?{appearance:Eo}:null}),[oa,_o,Wi,Eo]),qe=(0,s.useCallback)(l=>{gn(l),P?.(l)},[P]),Hi=(0,s.useRef)(""),[tl,pu]=(0,s.useState)(!1),Ki=(0,s.useCallback)(()=>{pu(!0)},[]);(0,s.useEffect)(()=>{if(!v||!En||!tt||!tl||Ro||Hi.current)return;let l=Un({email:(0,y.isValidEmail)(ne.email?.trim())?ne.email?.trim():ln.current.trim(),firstName:ne.firstName?.trim(),lastName:ne.lastName?.trim()});Hi.current=JSON.stringify(l),tn(E=>({...E,...l})),Promise.resolve(tt(l)).catch(E=>{Hi.current="",qe(E instanceof Error?E.message:"Failed to attach buyer details.")})},[v,En,tt,tl,Ro,ne.email,ne.firstName,ne.lastName,qe]),(0,s.useEffect)(()=>{!v||!Ft||Ft.setCardFieldOrder?.(J??null,me==null&&!En)},[v,Ft,J,me,En]),(0,s.useEffect)(()=>{(ct==="expanding"||ct==="collapsing"||ct==="apm-expanding"||ct==="apm-collapsing")&&qe(null)},[ct,qe]);let Er=(0,s.useCallback)((l,E,oe)=>{p?.(mn(l,E,oe))},[p]),Io=(0,s.useCallback)((l,E,oe)=>{let Ve=oe?.popupBlocked??ao(E);Ve&&h.markBlocked()&&C(pt=>pt+1);let fe=ro(Ds(l),Ve,H.inAppBrowser),Ue=Mr(E),Jt=(Ue?.toLowerCase()==="error"?void 0:Ue)??bo(oe?.code)??"external_payment_method_failed",br=new y.FloPayError(fe,"api_error",{code:"external_payment_method_failed",param:l,details:{providerCode:Jt,popupBlocked:Ve,inAppBrowser:H.inAppBrowser,appFamily:H.appFamily,popupCapability:h.current(),presentationMode:oe?.presentationMode??"popup"}});oe?.telemetryReported||yn(Ne)?.error(Xo({...ve,presentationMode:oe?.presentationMode??"popup"},{errorCode:Ve?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:oe?.provider??(l==="paypal"?"paypal":"stripe"),paymentMethodCategory:oe?.paymentMethodCategory??(l==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:oe?.terminalReason??(Ve?"popup_blocked":"provider_error")})),$(null),ae==="buttons"&&(un("buttons"),Rn(null)),qe(fe),c?.(br),console.error("[FloPay] External payment method failed:",{method:l,code:Jt,popupBlocked:Ve})},[H,ve,Ne,ae,c,h,qe]);(0,s.useEffect)(()=>{if(!v||!e){zr(null);return}let l=Fs(V?.vault);if(l){zr(l);return}if(!Gt){zr(null);return}zr(null);let E=!0;return new Sr.PaymentAPI(ye).getVaultCapture(e,t).then(oe=>{if(!E)return;let Ve=Fs(oe);Ve?zr(Ve):qe("Failed to load the secure card form.")}).catch(oe=>{E&&qe(oe instanceof Error?oe.message:"Failed to load the secure card form.")}),()=>{E=!1}},[v,Gt,Cn,e,V?.vault,ye,t,qe]);let gr=(0,s.useRef)({onComplete:i,onError:c,updateError:qe,emitDecline:Er,resolvedAccount:ne,avsConfig:me,avsCheckProp:at,sessionId:e,nonce:t,baseUrl:ye,captureMethod:V?.captureMethod,paymentId:V?.paymentId,authorizationExpiresAt:V?.authorizationExpiresAt,serverSideCardGateway:Mn});gr.current={onComplete:i,onError:c,updateError:qe,emitDecline:Er,resolvedAccount:ne,avsConfig:me,avsCheckProp:at,sessionId:e,nonce:t,baseUrl:ye,captureMethod:V?.captureMethod,paymentId:V?.paymentId,authorizationExpiresAt:V?.authorizationExpiresAt,serverSideCardGateway:Mn};let Gi=(0,s.useRef)(!1),nl=(0,s.useCallback)(()=>{let l=gr.current,E=l.resolvedAccount.email?.trim(),oe=(0,y.isValidEmail)(E)?E:ln.current.trim();if(!(0,y.isValidEmail)(oe))return null;let Ve=l.resolvedAccount.firstName?.trim(),fe=l.resolvedAccount.lastName?.trim(),Ue=nn.current.trim()||l.resolvedAccount.country?.trim()||"",Jt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.state,Ue):!1,br=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_1,Ue):!1,pt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.postal_code,Ue):!1,kt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.city,Ue):!1,It=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_2,Ue):!1,qt=br&&!Jt&&pt?(0,y.getStateFromPostalCode)(Ue,(xt.current??"").trim()):null,fo=Jt?zt.current:qt;return{accountData:{userId:l.resolvedAccount.userId??"",email:oe,...Ve?{firstName:Ve}:{},...fe?{lastName:fe}:{},...pt&&xt.current?{zip:xt.current}:{},...kt&&cn.current?{city:cn.current}:{},...fo?{state:fo}:{},...br&&sn.current?{addressLine1:sn.current}:{},...It&&Nt.current?{addressLine2:Nt.current}:{},...Ue?{country:Ue}:{}},...l.avsCheckProp===void 0?{}:{avsCheck:l.avsCheckProp},...l.avsConfig?{avsConfig:{country:(0,y.isAVSFieldVisible)(l.avsConfig.country,Ue),postal_code:pt,address_line_1:br,address_line_2:It,city:kt,state:Jt}}:{}}},[]),rl=(0,s.useRef)(D);rl.current=D,(0,s.useEffect)(()=>{D||Pt!==vc||gr.current.updateError(null)},[D,Pt]),(0,s.useEffect)(()=>{!v||!Ft||Ft.setSubmitGate?.(wr||D||Ro||Xe)},[v,Ft,wr,D,Ro,Xe]),(0,s.useEffect)(()=>{if(!v||!Ft)return;Gi.current=!1;let l=null,E=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null,se.current="idle",$(null)},400)},oe=Ft.on("submitting",()=>{yr(!0),Et.current&&clearTimeout(Et.current),se.current="validation-window",Et.current=setTimeout(()=>{Et.current=null,se.current==="validation-window"&&(se.current="processing")},Gd),$("processing");let pt=gr.current;if(!pt.sessionId||!pt.nonce)return;let kt=nl();if(!kt){pt.updateError("Enter a valid email address."),se.current="idle",$(null);return}new Sr.PaymentAPI(pt.baseUrl).patchAccountSnapshot(pt.sessionId,pt.nonce,kt,{telemetryMode:"best_effort"}).catch(It=>{if(!Xd(It))return;let qt=It instanceof Error?It.message:"Please check your billing address and try again.";pt.updateError(qt),se.current="idle",$(null),pt.onError?.(It instanceof y.FloPayError?It:new y.FloPayError(qt,"api_error"))})}),Ve=Ft.on("complete",pt=>{Ko(pt.sessionId??gr.current.sessionId),se.current="terminal",Q(!1),$("success"),setTimeout(()=>{if(Gi.current)return;Gi.current=!0;let kt=gr.current,It=(0,y.isAuthorizationOnlySession)(kt)||pt.outcome==="authorized",qt=kt.serverSideCardGateway?{}:{paymentIntentId:pt.intentId};gr.current.onComplete?.(It?{status:"authorized",...qt,paymentId:pt.paymentId??kt.paymentId,sessionId:pt.sessionId??kt.sessionId,authorizationExpiresAt:pt.authorizationExpiresAt??kt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...qt,checkoutMethod:"card"})},600)}),fe=Ft.on("decline",pt=>{let kt=gr.current,It=pt.message??"Your payment was declined. Please try another card or contact your bank.";se.current="terminal",Q(!1),kt.updateError(It),$("error");let qt=pt.failureOutcome??(0,y.normalizeCheckoutFailureOutcome)(pt.declineReason)??"authorization_declined";kt.emitDecline("card",It,{code:qt,declineCode:qt}),E()}),Ue=Ft.on("error",pt=>{let kt=gr.current,It=pt.message??"There was a problem processing your payment. Please try again.";se.current="terminal",Q(!1),kt.updateError(It),$("error"),kt.onError?.(new y.FloPayError(It,"api_error",{code:pt.failureOutcome??"capture_failed"})),E()}),Jt=Ft.on("challenge_dismissed",()=>{Et.current&&(clearTimeout(Et.current),Et.current=null),se.current="processing",Q(!0),$(null)}),br=Ft.on("blocked",()=>{if(f.current){gr.current.updateError(Yd);return}if(!rl.current){yr(!0);return}Ki(),gr.current.updateError(vc)});return()=>{l&&(clearTimeout(l),l=null),Et.current&&(clearTimeout(Et.current),Et.current=null),se.current="idle",Q(!1),$(null),oe(),Ve(),fe(),Ue(),Jt(),br()}},[v,Ft,Ki,nl]);let Ir=!!ht?.clientId,aa=Array.isArray(ge),qa=aa&&ge.length>0,ol=aa&&ge.includes("paypal"),Va=(0,s.useRef)(null);Va.current===null&&(Va.current=Hd());let To=Va.current?"redirect":ni(H,k,h.current()),{expressMethods:ja,paymentElementMethods:ia}=(0,s.useMemo)(()=>(0,y.partitionStripeMethods)(ge,{excludePaypal:Ir}),[ge,Ir]),al=Ir||!!bt||ol&&To==="redirect",mu=(0,s.useMemo)(()=>al?ja.filter(l=>l!=="paypal"):ja,[ja,al]),yu=(0,s.useMemo)(()=>{let l=[];return X&&l.push("apple_pay"),Se&&l.push("google_pay"),l},[X,Se]),Ao=aa?mu:yu,fu=K&&Ao.length>0,Yi=ur?jt:U,$a=(0,s.useMemo)(()=>{let l=Yi?.trim().toUpperCase();return l?z?ia.filter(E=>{let oe=z[E];return!oe||oe.length===0||oe.includes(l)}):(0,y.filterStripeMethodsByCountry)(ia,Yi):ia},[ia,Yi,z]),Xi=(0,s.useMemo)(()=>({mode:"payment",amount:oa,currency:_o,paymentMethodCreation:"manual",appearance:Zs}),[oa,_o,Zs]),[il,sl]=(0,s.useState)("loading"),[ll,cl]=(0,s.useState)("loading"),[ul,dl]=(0,s.useState)("loading"),[gu,Ji]=(0,s.useState)(!1),[pl,Zi]=(0,s.useState)("loading"),[Qi,hu]=(0,s.useState)();(0,s.useEffect)(()=>{hu(Kr())},[]);let Wa=Qi?.inAppBrowser,Ha=Qi?ri(Qi,ht?.approvalPresentation,de??(Tt?"subscription":"order")):"popup",ml=w&&(Ir||(aa?ol:Wa===!1)),yl=K&&fu,sa=(!lt||!!Ye.waitForDataAttachment)&&ml&&Ir,fl=pl==="retrying"||pl==="exhausted",la=null;K&&(bt?la=Js:To==="redirect"&&(la=Gn));let gl=(0,s.useMemo)(()=>({...ve,presentationMode:To}),[ve,To]),ca=!lt&&ml&&!!la&&(!Ir||fl),Mo=!lt&&yl&&!!Gn,ua=!lt&&K&&qa&&$a.length>0&&!!Gn,bu=sa&&!fl?gu:ca&&Is(il),Pu=Mo&&Is(ll),vu=ua&&ul!=="load_error",hl=l=>l==="loading"||l==="ready",bl=sa||ca&&hl(il)||Mo&&hl(ll)||ua&&ul!=="load_error",Ka=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!Ka.current){if(!K&&!w){Ka.current=!0;let l=new y.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(l),qe(l.message)}else if(!K&&w&&!Ir){Ka.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),qe(l.message)}else if(Wa!==void 0&&!lt&&!mt&&!bl){Ka.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),qe(l.message)}}},[K,w,Ir,Wa,lt,mt,bl,c,qe]);let Pl=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(Pl.current||!qa)return;let l=[];X!==!0&&l.push("showApplePay"),Se!==!0&&l.push("showGooglePay"),l.length!==0&&(Pl.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.`))},[qa,X,Se]);let vl=(0,s.useCallback)((l,E)=>Ye.applyInlineSessionPatch?Ye.applyInlineSessionPatch(l).then(oe=>({error:null,sessionId:oe.sessionId||e,nonce:oe.session?.clientSecret||t})).catch(oe=>{let Ve=kc(E,oe);return qe(Ve.message),c?.(Ve),{error:Ve,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ye.applyInlineSessionPatch,t,c,e,qe]),hr=(0,s.useCallback)(async l=>{if(l!=="card"&<&&await Ye.waitForDataAttachment?.(),!ue)return{proceed:!0};try{let E=await ue({method:l,sessionId:e||void 0,createSession:Ye.inlineSessionDraft});if(E===!1)return{proceed:!1};if(E&&typeof E=="object"){E.account&&tn(Ve=>({...Ve??{},...E.account}));let oe=await vl(E,l);return oe.error?{proceed:!1,accountPatch:E.account}:{proceed:!0,accountPatch:E.account,sessionId:oe.sessionId,nonce:oe.nonce}}return{proceed:!0}}catch(E){let oe=kc(l,E);return qe(oe.message),c?.(oe),{proceed:!1}}},[vl,Ye.inlineSessionDraft,Ye.waitForDataAttachment,lt,ue,c,e,qe]),Cl=(0,s.useCallback)(async(l,E)=>{if(gt.current)return;gt.current=!0,Tn(!0),$("processing"),qe(null);let oe=E?.sessionId??e,Ve=E?.nonce??t,fe=ps(ne,E?.accountPatch),Ue=E?.completionPaymentMethodId??Pa(l),Jt=l.originalPaymentMethodId?{...l,originalPaymentMethodId:void 0}:l,br=ep(l),pt=E?.presentationMode?bi(yn(Ne),{...ve,presentationMode:E.presentationMode}):void 0,kt=()=>{_t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:br}),pt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Cr,requestCategory:"process_payment"})};try{let It=new Sr.PaymentAPI(ye),qt=await It.processPayment(fe.userId??"",{sessionId:oe,nonce:Ve,paymentMethodCategory:E?.paymentMethodCategory??np(l),tokenizedData:Jt,accountData:{...E?.accountPatch,userId:fe.userId??"",email:fe.email??"",firstName:fe.firstName||void 0,lastName:fe.lastName||void 0,...me?(()=>{let Bt=nn.current,Tr=(0,y.isAVSFieldVisible)(me.state,Bt),Xn=(0,y.isAVSFieldVisible)(me.address_line_1,Bt),Ar=(0,y.isAVSFieldVisible)(me.postal_code,Bt),go=Xn&&!Tr&&Ar?(0,y.getStateFromPostalCode)(Bt,(xt.current??"").trim()):null,ga=Tr?zt.current:go;return{country:Bt,...Ar&&xt.current?{zip:xt.current}:{},...(0,y.isAVSFieldVisible)(me.city,Bt)&&cn.current?{city:cn.current}:{},...ga?{state:ga}:{},...Xn&&sn.current?{addressLine1:sn.current}:{},...(0,y.isAVSFieldVisible)(me.address_line_2,Bt)&&Nt.current?{addressLine2:Nt.current}:{}}})():{}},chv:T,avsCheck:at??!1,checkoutType:Ke,checkoutLayout:st,avsConfig:me?{country:(0,y.isAVSFieldVisible)(me.country,nn.current),postal_code:(0,y.isAVSFieldVisible)(me.postal_code,nn.current),address_line_1:(0,y.isAVSFieldVisible)(me.address_line_1,nn.current),address_line_2:(0,y.isAVSFieldVisible)(me.address_line_2,nn.current),city:(0,y.isAVSFieldVisible)(me.city,nn.current),state:(0,y.isAVSFieldVisible)(me.state,nn.current)}:void 0}),fo=async Bt=>{let Tr=(0,y.isAuthorizationOnlySession)(V)||Bt?.status==="authorized";Ko(oe),pt?.terminal({outcome:"payment_succeeded",...Cr}),$("success"),N(null),await new Promise(go=>setTimeout(go,600));let Xn;typeof Bt?.paymentId=="string"?Xn=Bt.paymentId:V?.paymentId&&(Xn=V.paymentId);let Ar;typeof Bt?.authorizationExpiresAt=="string"?Ar=Bt.authorizationExpiresAt:V?.authorizationExpiresAt&&(Ar=V.authorizationExpiresAt),i?.(Tr?{status:"authorized",...Xn===void 0?{}:{paymentId:Xn},sessionId:typeof Bt?.sessionId=="string"?Bt.sessionId:oe,...Ar===void 0?{}:{authorizationExpiresAt:Ar},paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Ue,checkoutMethod:l.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Ue,checkoutMethod:l.isPaypal?"paypal":"card"})};if(qt.ok){await fo(qt.status===204?null:await qt.json().catch(()=>null));return}let Yn=await qt.json().catch(()=>null);if(Yn?.type==="paypal_redirect_required"){let Bt=Yn.threeDSecureToken,Tr=Yn.paymentMethodId||l.id||"";if(!Ne||!Bt){$("error"),qe("PayPal authorization required but no token provided.");return}try{let Xn=bt?.getRawProvider();if(!Xn){qe("PayPal is not available.");return}let Ar={return_url:window.location.href};Tr&&(Ar.payment_method=Tr);let{error:go}=await Xn.confirmPayment({clientSecret:Bt,confirmParams:Ar,redirect:"if_required"});if(go){$("error");let ga=go.message??"PayPal payment failed.";qe(ga),Er("paypal",ga,{code:go.code})}}catch(Xn){$("error"),qe(Xn instanceof Error?Xn.message:"PayPal authorization failed.")}return}if(Yn?.type==="paypal_direct_required"){let Bt=Yn.orderId;if(!Bt){$("error"),qe("PayPal retry required but no order id provided.");return}let Tr=W.current?.attempts??0;if(Tr>=2){$("error"),qe("PayPal payment could not be completed after multiple attempts."),Er("paypal","paypal_direct_required retry limit exceeded");return}Ji(!1),Zi("loading"),N({orderId:Bt,attempts:Tr+1}),$(null);return}if(qt.headers.get(Ud)===zd){let Bt=await qd(It,oe,Ve);if(Bt!==void 0){await fo(Bt);return}}(0,y.classifyPaymentRejection)(qt.status,Yn)?pt?.terminal({outcome:"payment_declined",...Cr,terminalReason:"provider_declined"}):kt(),$("error");let xl=Yn?.message??"Payment failed. Please try again.";qe(xl),Er(l.isPaypal?"paypal":"card",xl,{code:Yn?.code??Yn?.gatewayErrorCode,declineCode:Yn?.declineCode??Yn?.gatewayDeclineReason}),await new Promise(Bt=>setTimeout(Bt,400))}catch(It){xc(It)||kt(),$("error"),qe(It instanceof Error?It.message:"An unexpected error occurred"),await new Promise(qt=>setTimeout(qt,400))}finally{Tn(!1),$(null),gt.current=!1}},[ye,e,t,ne,me,at,Ke,st,T,Ne,bt,V,i,qe,Er,_t,ve]),Ln=(0,s.useCallback)((l,E)=>{u?u(l):Cl(l,E)},[u,Cl]),da=`${Tc}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let l=localStorage.getItem(da);if(!l)return;let E;try{E=JSON.parse(l)}catch{Kt(da);return}if(!E||typeof E.createdAt!="number"||Date.now()-E.createdAt<0||Date.now()-E.createdAt>Ac||typeof E.paymentMethodId!="string"||typeof E.providerIntentId!="string"||typeof E.paymentMethodType!="string"||E.sessionId!==e||!t||E.nonce!==t||!Ao.includes(E.paymentMethodType)){Kt(da);return}Kt(da),Ln({id:E.paymentMethodId,type:"card",threeDSecureActionResultTokenId:E.providerIntentId,gateway:"stripe",paymentMethodType:E.paymentMethodType},{...E.accountPatch?{accountPatch:E.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Ln,t,e,da,Ao]);let Sl=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||Sl.current)return;let[l,E,oe]=Ns();if(!l||!E||Va.current||!Ne)return;let Ve=Ne.getRawProvider();if(!Ve)return;let fe=kt=>{let It=localStorage.getItem(kt);if(!It)return null;try{return JSON.parse(It)}catch{return Kt(kt),null}},Ue=fe(Fr)??fe(hc),Jt;if(Ue?.clientSecret){if(Ue.clientSecret!==E)return;Jt={...Ue.accountPatch?{accountPatch:Ue.accountPatch}:{},...Ue.sessionId?{sessionId:Ue.sessionId}:{},...Ue.nonce?{nonce:Ue.nonce}:{}}}else if(Ue?.sessionId&&Ue.sessionId!==e)return;Sl.current=!0,Kt(Fr),Kt(hc),window.history.replaceState({},"",Us());let br=Ue?.paymentMethodType??Ue?.tokenType??"card",pt="card";(async()=>{if(oe==="failed"){let Vr="Payment was declined. Please try again.";qe(Vr),Er(pt,Vr);return}let{paymentIntent:kt,error:It}=await Ve.retrievePaymentIntent(E);if(It){let Vr=It.message??"Failed to retrieve payment status.";qe(Vr),Er(pt,Vr,{code:It.code});return}let qt=kt?.status,fo=ba(qt);if(!kt||!fo){let Vr=qt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";qe(Vr),Er(pt,Vr,{code:qt??"missing_payment_intent"});return}let Yn=typeof kt.payment_method=="string"?kt.payment_method:kt.payment_method?.id;Ln({id:Yn??Ue?.paymentMethodId??Ue?.tokenId??kt.id,type:"card",threeDSecureActionResultTokenId:kt.id,gateway:Ue?.gateway??"stripe",paymentMethodType:br},Jt)})()},[e,Ln,Ne,qe,Er]);let es=(0,s.useCallback)(l=>{l.preventDefault()},[]);if(!(v||Ne!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let pa=ae==="buttons",Nn=St?.variables,Cu=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ts=Nn?.colorBackground,Su=ts&&!Cu.has(ts)?ts:void 0,ma=F.cardInputBorder??(pa?"#e5e7eb":"#A4A4FF"),wl=Nn?.colorDanger??"#dc2626",Wt=l=>er[l]&&(Rr[l]||Yt),Ga=Ro&&(Dn||Yt),rr=l=>l?wl:ma,Ya=(Fn.malformed||Fn.empty)&&(Bn||Yt),wu=rr(Ya),ns=F.cardFormContainer?.backgroundColor??Su??(pa?"white":"#EDEDFF"),xo=F.cardInputBackground??Nn?.colorBackground??"white",rs=Do(Re),kl=Do(Ie),Fo=F.nameInput,Rl=F.cardInputFontSize??sp(Fo?.fontSize)??Nn?.fontSizeBase??"16px",_l=typeof Fo?.fontFamily=="string"?Fo.fontFamily:Nn?.fontFamily??"Poppins, sans-serif",El=As(Fo?.fontWeight)??400,ku=F.cardInputColor??(typeof Fo?.color=="string"?Fo.color:void 0)??Nn?.colorText??"#262833",Ru=F.cardInputPlaceholderColor??"#9ca3af",Xt=Nn?.borderRadius??"8px",mo=Nn?.borderRadius??F.cardButton?.borderRadius??Xt,yo=Nn?.colorPrimary??"#4A49FF",_u=Nn?.colorPrimaryHover??Qo(yo,.12),os=Nn?.colorText??"#262833",as={fontSize:Rl,fontFamily:_l,fontWeight:El,color:ku,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ya={marginTop:"0.375rem",...as,fontSize:"0.75rem",lineHeight:1.4,color:wl},Eu={"--flopay-input-placeholder-color":Ru,"--flopay-input-font-size":Rl,"--flopay-input-font-family":_l,"--flopay-input-font-weight":String(El)},fa=F.cardFormContainer??{},is=fa.padding??(pa?"0":"1rem"),ss=fa.borderRadius??Xt,Iu=Ft&&Ur?(0,d.jsx)(lo,{capture:Ft,html:Ur.html,messageToken:Ur.messageToken,expectedOrigin:Ur.expectedOrigin,theme:Fe,submitLabel:S,onReady:()=>{if(!En&&!me||typeof document>"u")return;let l=()=>{let oe=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(oe){Kn.current=!0;try{oe.focus()}finally{Kn.current=!1}}};Nr.current||l()},onError:l=>qe(l),onValidation:l=>{let E=se.current;(E==="idle"||E==="validation-window")&&(qe(l),l&&se.current==="validation-window"&&(Et.current&&(clearTimeout(Et.current),Et.current=null),se.current="idle",$(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"}),Il=(0,d.jsxs)("div",{onFocusCapture:l=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(l.target.tagName)&&Zr()},style:{backgroundColor:ns,borderRadius:ss,...fa,padding:is,...Eu,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
|
|
30
|
+
`,Qo=44;function ea(){return(0,hn.jsx)("style",{children:Pd})}function Ma(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function xa({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,hn.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,hn.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,hn.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 Ms(e){return e!=="unavailable"&&e!=="load_error"}function Ci({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:i,backgroundColor:c,borderColor:p,textColor:u,borderRadius:h,fontFamily:P}){let M=(0,Yr.resolveStripeMethodBrandVariant)(e,t),_=dc[e],[w,A]=(0,pc.useState)(!1),I=!!_&&!w,b=M?.backgroundColor??c??"#ffffff",C=M?.borderColor??p??"#d1d5db",G=M?.textColor??u??"#262833";return(0,hn.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&i()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Qo,padding:"0 1rem",backgroundColor:b,color:G,border:`1px solid ${C}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:P,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,hn.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,Yr.getStripeMethodDisplayName)(e)}\u2026`}):(0,hn.jsxs)(hn.Fragment,{children:[(0,hn.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,Yr.hasVendoredStripeMethodLogo)(e)?8:0},children:[I?(0,hn.jsx)("img",{src:_,alt:"","aria-hidden":"true",onError:()=>A(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!I&&M?.logoSvg?(0,hn.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:M.logoSvg}}):null,(0,hn.jsx)("span",{children:(0,Yr.getStripeMethodDisplayName)(e)})]}),a&&(0,hn.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:G,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,hn.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Si(e){let t=new Set(e.map(Yr.stripeExpressMethodToOptionKey)),n=r=>r==="applePay"||r==="googlePay"?"always":"auto";return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?n(r):"never"]))}var wi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},ki={type:"accordion",defaultCollapsed:!1,radios:"never"};function Ri({testId:e,attributes:t,disabled:n,onClick:r,color:o,borderRadius:a,style:i,children:c}){return(0,hn.jsx)("button",{type:"button","data-testid":e,...t,onClick:r,disabled:n,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:o,color:"white",border:"none",borderRadius:a,fontSize:"1rem",fontWeight:600,cursor:n?"not-allowed":"pointer",opacity:n?.5:1,transition:"opacity 120ms ease-out",...i??{}},children:c})}var Qn=require("react");function _i(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(i=>i.startsWith("background")),a={};for(let[i,c]of Object.entries(e))i in n||o&&i.startsWith("background")||(a[i]=c);for(let i of r)a[i]=n[i];return a}var 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 mc(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 wo=require("react/jsx-runtime"),xs=new WeakSet;function co({capture:e,html:t,messageToken:n,expectedOrigin:r,verificationRequired:o,theme:a,submitLabel:i,containerStyle:c,onReady:p,onError:u,onValidation:h}){let P=(0,Qn.useRef)(null),M=(0,Qn.useRef)(p),_=(0,Qn.useRef)(u),w=(0,Qn.useRef)(h);M.current=p,_.current=u,w.current=h;let A=(0,Qn.useRef)(a);A.current=a;let I=(0,Qn.useRef)(null),b=i??void 0,C=(0,Qn.useRef)(b);C.current=b;let G=(0,Qn.useRef)(void 0);return(0,Qn.useEffect)(()=>{let k=P.current;if(!k)return;let ye=!0,N=!1,H=()=>{!ye||N||(N=!0,M.current?.())},_e=e.on("ready",()=>{H()}),te=e.on("error",fe=>{_.current?.(fe.message??"There was a problem loading the secure card form.")}),Ne=e.on("validation",fe=>{w.current?.(fe.message??null)}),Ye=C.current??(xs.has(e)?null:void 0),be={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...o?{verificationRequired:!0}:{},...A.current?{theme:A.current}:{},...Ye===void 0?{}:{submitLabel:Ye}};return I.current=A.current??null,G.current=C.current,C.current!==void 0&&xs.add(e),e.mount(k,be).then(()=>{H()}).catch(fe=>{ye&&_.current?.(fe instanceof Error?fe.message:"Failed to load the secure card form.")}),()=>{ye=!1,_e(),te(),Ne(),e.unmount()}},[e,t,n,r,o]),Co(()=>{let k=P.current;k&&mc(k,c)},[c]),(0,Qn.useEffect)(()=>{a!==void 0&&(a===null&&I.current===null||(I.current=a,e.applyTheme?.(a)))},[e,a]),(0,Qn.useEffect)(()=>{b!==G.current&&(G.current=b,b!==void 0&&xs.add(e),e.setSubmitLabel?.(b??null))},[e,b]),(0,wo.jsx)("div",{ref:P,"data-testid":"flopay-vault-card-fields"})}function Ei({label:e}){return(0,wo.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,wo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,wo.jsx)("span",{children:e}),(0,wo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var fc=/^#([0-9a-f]{6})$/i,wd=/^#([0-9a-f]{3})$/i,gc=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,hc=/^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,Rd=/^(-?\d+(?:\.\d+)?)(?:px)?$/,_d=/^(-?\d+(?:\.\d+)?)em$/,Ed=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,Id=/^[a-z][a-z0-9 -]{0,31}$/i,Td=new Set(["none","uppercase","lowercase","capitalize"]);function bc(e){if(typeof e!="string")return null;let t=e.trim(),n=fc.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=wd.exec(t);if(r){let[h,P,M]=r[1].split("").map(_=>Number.parseInt(_+_,16));return{r:h,g:P,b:M,a:null}}let o=gc.exec(t),a=o?null:hc.exec(t),i=o??a;if(!i)return null;let c=Number(i[1]),p=Number(i[2]),u=Number(i[3]);return c>255||p>255||u>255?null:{r:c,g:p,b:u,a:a?Number(a[4]):null}}function Pc({r:e,g:t,b:n,a:r}){return r===null?`#${(1<<24|e<<16|t<<8|n).toString(16).slice(1)}`:`rgba(${e},${t},${n},${r})`}function Fa(e){if(typeof e!="string")return;let t=e.trim();if(fc.test(t)||gc.test(t))return t;let n=hc.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=bc(t);return r?Pc(r):void 0}function Ii(e,t=.12){let n=bc(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Pc({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function Ba(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 ko(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=Rd.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=_d.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Md(e){let t=Ba(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=Ba(o," "),i=Fa(a[0]);if(!i)return;let c=r/(t.length-1)*100,p=a[1]===void 0?c:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),u=n[n.length-1]?.position??-1;if(!Number.isFinite(p)||p<0||p>100||p<u)return;n.push({color:i,position:p})}return{type:"linearGradient",angle:0,stops:n}}function xd(e){if(typeof e!="string")return;let t=e.trim(),n=Fa(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=Md(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function Fd(e){return e.type==="solid"?{type:"solid",color:Ii(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:Ii(t.color)}))}}function Bd(e){let t=!1,n,r=[];for(let p of Ba(e," ")){if(p.toLowerCase()==="inset"){t=!0;continue}let u=Fa(p);if(u){n=u;continue}let h=ko(p,-128,128);if(h===void 0)return;r.push(h)}if(!n||r.length<2||r.length>4)return;let[o,a,i=0,c=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||i>128||Math.abs(c)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:i,spread:c}}function Dd(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=Ba(t,",").map(Bd);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function yc(e){if(typeof e!="string")return;let t=Ba(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>Id.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=ko(t[0],0,64),r=ko(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 vc({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=xd(r.background??r.backgroundColor),i=Fa(o?.colorPrimaryHover),c=i?{type:"solid",color:i}:a&&Fd(a),p={fontFamilies:yc(r.fontFamily)??yc(n),fontSize:ko(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:Ld(r.fontWeight)??600,letterSpacing:Ad(r.letterSpacing,-.1,.5)??.01,lineHeight:ko(r.lineHeight,.8,2)??1,textTransform:Td.has(String(r.textTransform))?r.textTransform:"uppercase"},u=Od(r.padding),h=Dd(r.boxShadow),P=ko(r.borderRadius,0,9999),M=typeof r.backdropFilter=="string"?ko(Ed.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Fa(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...c?{hoverBackground:c}:{},typography:p,...u?{spacing:u}:{},...h?{shadow:h}:{},...P===void 0?{}:{borderRadius:P},disabledOpacity:e?.theme==="night"?.8:.6,...M===void 0?{}:{backdropBlur:M}}}function ta(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)?Ii(r,t):e}function Fs(e){if(typeof e=="number"||typeof e=="string")return e}function na({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=P=>typeof P=="string"&&P?P:void 0,a=t.submitButton,i=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",c=n==="buttons",p=t.nameInput,u=o(p?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",h=vc({appearance:e,buttonsStyles:t,fontFamily:u});return{primaryColor:i,primaryHoverColor:o(r?.colorPrimaryHover)??ta(i,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(p?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(c?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:u,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(Fs(p?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...h?{submitButton:h}:{}}}var d=require("react/jsx-runtime"),Or="flopay_stripe_resume",Cc="flopay_wallet_resume",Fc="fw1",Nd="fw2",Bc=300*1e3,Ud=900,zd=25e3,qd=25e3,Vd=1e4,Dc=["payment_intent","payment_intent_client_secret","redirect_status"],wr={provider:"paypal",paymentMethodCategory:"paypal"},jd="x-flopay-process-result-source",$d="status";async function Wd(e,t,n){try{let r=(await e.getUnifiedCheckoutSession(t,n)).data.session;if(r?.status==="complete")return null;if(r?.status==="authorized")return{status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}}catch{}}var Ti={},Oa=class{constructor(t){this.reason=t}};function Hd(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function Gt(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 Us(e){return`${Nd}:${e}`}function Ai(e){return Gt(Us(e))}function Mi(e,t){if(typeof window>"u")return null;let n=Us(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>Bc||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Ai(e),null):o}catch{return Ai(e),null}}function Kd(e){return Gt(Us(e.sessionId),e)}function Sc(e,t,n){let r=Mi(e,t);return!r||r.clientSecret!==n?!1:Ai(e)}function Bs(e,t,n){if(typeof window>"u")return;Mi(e,t)?.clientSecret===n&&Ai(e)}function Gd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Ds(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":va(e.status),o=Gd(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function wc(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)},Vd),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Yd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Oc(e){return e instanceof f.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function xi(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new kr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Oc(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var La="flopay_paypal_resume",Da=new Map;function Lc(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(La);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function Xd(){if(typeof window>"u")return!1;let[e,t]=zs();return e?Lc(t)!==null:!1}function zs(){let e=new URLSearchParams(window.location.search);return Dc.map(t=>e.get(t))}function qs(){let e=new URL(window.location.href);for(let t of Dc)e.searchParams.delete(t);return e.toString()}function Jd(){Gt(La),window.history.replaceState({},"",qs())}var Zd=250,kc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Qd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Vs(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 kr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function ep(e){return e instanceof f.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Nc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=bo(n),i=a.firstName?a:bo(r?.name);return qn({email:(0,f.isValidEmail)(o)?o:r?.email?.trim(),firstName:i.firstName,lastName:i.lastName})}async function tp({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let i=Nc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,f.isValidEmail)(i.email)?i:a(o,i)}var Na=180,Rc=`flopay-card-enter ${Na}ms cubic-bezier(0, 0, 0.2, 1) both`,_c=`flopay-card-exit ${Na}ms cubic-bezier(0.4, 0, 0.2, 1) both`,np=`flopay-buttons-enter ${Na}ms cubic-bezier(0, 0, 0.2, 1) both`,rp=`flopay-buttons-exit ${Na}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function op(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function js(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 ap={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function ip(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 Os={width:"100%",minHeight:Qo,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 sp(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ec(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ls(e){return e==="paypal"?"PayPal":(0,f.getStripeMethodDisplayName)(e)}function lp(e){let t=(0,f.getPostalCodeExample)(e);return`Enter a valid ${(0,f.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function cp(e,t,n){let r=(0,f.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,i=a&&!o,c=a&&!!o&&!(0,f.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:i,malformed:c}}function up(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,f.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function Ic(e,t){return t instanceof f.FloPayError?t:new f.FloPayError(t instanceof Error?t.message:`${sp(e)} before-click hook failed.`,"validation_error")}function dp(e){return typeof e=="number"?`${e}px`:e}function Bi(e){return(0,d.jsx)(pp,{...e})}function Tc({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:i=!1,onButtonClick:c,onDecline:p,onTechnicalFailure:u,runBeforeButtonClick:h,billingName:P,onBuyerIdentityReady:M,onLoadStateChange:_,placeholderBorderRadius:w,popupCapabilityOwner:A,externalTelemetryContext:I,presentationMode:b}){let C=Hr(),{emitInstrument:G}=(0,s.useContext)(ar),k=(0,Qt.useStripe)(),ye=(0,Qt.useElements)(),N=(0,s.useMemo)(()=>vi(gn(C),I),[I,C]),[H,_e]=(0,s.useState)("loading");(0,s.useEffect)(()=>{_?.(H)},[H,_]);let[te,Ne]=(0,s.useState)(!1),Ye=(0,s.useRef)(!1),be=!(0,f.isValidEmail)(n?.trim())||!P?.trim(),{request:fe,collect:We,finish:Te}=Vo(),Fe=(0,s.useRef)(!1),Ae=(0,s.useRef)(null),re=(0,s.useRef)(null),[se,Ce]=(0,s.useState)(0),[Be,Y]=(0,s.useState)(!1),Q=(0,s.useRef)(!1),Pe=(0,s.useRef)(new Map),{startAttempt:z,finishAttempt:we,invalidateAttempt:J,isAttemptInvalidated:Ee,isAttemptCurrent:Z,generationRef:it}=ka((q,ve,Qe)=>{u?.(q,ve,{...Qe,popupBlocked:Qe?.popupBlocked??io(ve),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:b,terminalReason:"overlay_timeout"}),Y(!0),Ce(X=>X+1)},{onHandoffObserved:()=>{A.markAvailable(),N?.log({name:"provider.popup.opened",stage:"overlay_open",...wr,attempt:it.current})}});(0,s.useEffect)(()=>{Be&&re.current?.focus()},[Be,se]);let He=(0,s.useCallback)(()=>{Ce(q=>q+1)},[]),Ve=(0,s.useCallback)((q,ve,Qe)=>{J(Qe),u?.("paypal",q,{code:ve,popupBlocked:io(q),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:b}),Y(!0),He()},[J,u,b,He]),at=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Ae.current?.querySelector("iframe")??Ae.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{Q.current&&(Q.current=!1,at())},[at,se]);let Ke=(0,s.useCallback)(()=>{Y(!1),a?.(null),at()},[at,a]);(0,s.useEffect)(()=>{if(!k||Fe.current)return;let[q,ve,Qe]=zs();if(!q||!ve)return;let X=Lc(ve);if(!X)return;Fe.current=!0;let Ue=!0,vt=Da.get(ve);vt||(vt=Qe==="failed"?Promise.resolve(null):Promise.resolve().then(()=>k.retrievePaymentIntent(ve)),Da.set(ve,vt));let Xe={accountPatch:X.accountPatch,sessionId:X.sessionId,nonce:X.nonce},kt=()=>{N?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...wr,requestCategory:"provider_sdk"})};return N?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...wr}),(async()=>{try{Ne(!0);let g=await vt;if(!Ue)return;if(g?.error){Da.delete(ve),kt(),a?.(g.error.message??"Failed to retrieve PayPal payment status.");return}if(Jd(),Da.delete(ve),Qe==="failed"){let K="PayPal payment was declined. Please try again.";N?.terminal({outcome:"payment_declined",...wr,terminalReason:"provider_declined"}),a?.(K),p?.(fn("paypal",K));return}let S=g?.paymentIntent;if(S&&S.id!==q){kt(),a?.("Failed to match the returned PayPal payment.");return}if(S&&(S.status==="requires_capture"||S.status==="succeeded")){let K=typeof S.payment_method=="string"?S.payment_method:S.payment_method?.id;o({id:K??S.id,type:"card",threeDSecureActionResultTokenId:S.id,isPaypal:!0},{...Xe,presentationMode:"redirect"})}else{let K="PayPal payment was not completed. Please try again.";N?.terminal({outcome:S?.status==="canceled"?"payment_cancelled":"payment_declined",...wr,terminalReason:S?.status==="canceled"?"cancelled":"provider_declined"}),a?.(K),p?.(fn("paypal",K))}}catch(g){if(!Ue)return;Da.delete(ve),kt(),a?.(g instanceof Error?g.message:"Failed to complete PayPal payment.")}finally{Ue&&Ne(!1)}})(),()=>{Ue=!1,Fe.current=!1}},[k,o,a,p,N]);let st=(0,s.useCallback)(async(q=!1)=>{let ve=h?await h("paypal"):{proceed:!0};if(!ve.proceed)return Pe.current.delete(se),!1;let Qe=z("paypal");return Pe.current.set(se,{generation:Qe,accountPatch:ve.accountPatch,sessionId:ve.sessionId,nonce:ve.nonce}),Y(!1),N?.log({name:`provider.${q?"redirect.started":"handoff.requested"}`,stage:q?"redirect":"overlay_open",...wr,attempt:Qe}),c?.("paypal"),!0},[c,N,h,z,se]),je=(0,s.useCallback)(async q=>{if(i||te||!await st()){q.reject();return}q.resolve()},[i,st,te]),St=(0,s.useCallback)(async q=>{if(!k||!ye)return;let ve=Pe.current.get(se);if(ve&&!Z(ve.generation)){Pe.current.delete(se);return}if(!ve&&Ee()||ve&&!we(ve.generation))return;ve||we();let Qe=ve??null;if(Pe.current.delete(se),!Qe&&h){let V=await h("paypal");if(!V.proceed){q.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Qe={accountPatch:V.accountPatch,sessionId:V.sessionId,nonce:V.nonce}}let X=Qe?.sessionId??e,Ue=Qe?.nonce??t,vt=await tp({event:q,prepared:Qe,email:n,billingName:P,methodLabel:"PayPal",collect:We});if(!vt){q.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Xe=vt.email,kt={...Qe?.accountPatch,...qn(vt,!0)};try{if(Ne(!0),a?.(null),!X||!(0,f.isValidEmail)(Xe))throw new Error("Missing sessionId or email for PayPal payment");await M?.(vt);let V=k.createPaymentMethod,{error:g,paymentMethod:S}=await V({type:"paypal"});if(g){Ve(g,"stripe_paypal_create_payment_method_failed",ve?.generation),q.paymentFailed({reason:"fail"});return}let K=await xi(r,G,X,Ue??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:S?.id??null,intentKind:"payment"});if(K.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let W=K.clientSecret,Se={return_url:qs()};if(S?.id&&(Se.payment_method=S.id),!Gt(La,{clientSecret:W,sessionId:X,nonce:Ue,accountPatch:kt})&&b==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:B,paymentIntent:oe}=await k.confirmPayment({clientSecret:W,confirmParams:Se,redirect:"if_required"});if(B){if(Gt(La),vo(B)){let Ie=B.message??"Your payment was declined.";N?.terminal({outcome:"payment_declined",...wr,terminalReason:"provider_declined"}),a?.(Ie),p?.(fn("paypal",Ie,{code:Br(B),declineCode:$o(B)})),await Fi({billingApiUrl:r,sessionId:X,nonce:Ue,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Br(B)??"provider_declined"}})}else Ve(B,"stripe_paypal_confirm_failed",ve?.generation);return}Gt(La);let j=typeof oe?.payment_method=="string"?oe.payment_method:oe?.payment_method?.id;o({id:j??oe?.id,type:"card",threeDSecureActionResultTokenId:oe?.id,isPaypal:!0},{accountPatch:kt,paymentMethodCategory:"paypal",presentationMode:b,sessionId:X,nonce:Ue});return}catch(V){Ve(V,"stripe_paypal_failed",ve?.generation)}finally{Ne(!1)}},[k,ye,e,t,n,P,We,M,r,G,o,a,p,h,Ve,we,Z,Ee,N,b,se]),Lt=(0,s.useCallback)(async()=>{if(!(Ye.current||i||te||!k||!ye)){Ye.current=!0,Ne(!0);try{if(!await st(!0))return;await St({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Ye.current=!1,Ne(!1)}}},[ye,St,i,st,k,te]),Pt=b==="redirect"?(0,d.jsx)("button",{type:"button",disabled:i||te,onClick:()=>{Lt()},style:{width:"100%",minHeight:Qo,border:"1px solid #d1d5db",borderRadius:w??8,background:"#ffc439",color:"#111827",cursor:i||te?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,d.jsx)(Qt.ExpressCheckoutElement,{onReady:q=>_e(Ma(q,["paypal"])),onLoadError:()=>{_e("load_error"),Vs(N,"paypal","paypal","provider_error")},onClick:je,onConfirm:St,onCancel:()=>{let q=Pe.current.get(se);Pe.current.delete(se),N?.terminal({outcome:"payment_cancelled",...wr,terminalReason:"cancelled",...q?{attempt:q.generation}:{}}),J(q?.generation),Y(!1),Q.current=!0,He()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:be,emailRequired:be,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},se),Et=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{ref:Ae,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Be&&(0,d.jsx)("button",{ref:re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ke,style:Os,children:"Try PayPal again"}),fe&&(0,d.jsx)(jo,{identity:fe.identity,methodLabel:fe.methodLabel,onComplete:Te,onCancel:()=>Te(null)},fe.id),(0,d.jsx)("div",{style:{display:fe?"none":void 0},children:Pt})]}),te&&!fe&&(0,d.jsx)(Vn,{status:"processing"})]});return b==="redirect"?Et:(0,d.jsx)(xa,{state:H,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:Et})}function Ac(e){return e==="apple_pay"||e==="google_pay"}function Mc({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:i,onErrorChange:c,onButtonClick:p,onDecline:u,onTechnicalFailure:h,runBeforeButtonClick:P,billingName:M,onBuyerIdentityReady:_,onLoadStateChange:w,placeholderBorderRadius:A,popupCapabilityOwner:I,externalTelemetryContext:b}){let C=Hr(),{emitInstrument:G}=(0,s.useContext)(ar),k=(0,Qt.useStripe)(),ye=(0,Qt.useElements)(),N=(0,s.useMemo)(()=>vi(gn(C),b),[b,C]),[H,_e]=(0,s.useState)("loading");(0,s.useEffect)(()=>{w?.(H)},[H,w]);let[te,Ne]=(0,s.useState)(!1),Ye=(0,s.useRef)(!(0,f.isValidEmail)(n?.trim())||!M?.trim()).current,{request:be,collect:fe,finish:We}=Vo(),Te=(0,s.useRef)(null),Fe=(0,s.useRef)(null),[Ae,re]=(0,s.useState)(0),[se,Ce]=(0,s.useState)(!1),[Be,Y]=(0,s.useState)(()=>Mi(e,t)?"blocked":"idle"),[Q,Pe]=(0,s.useState)("google_pay"),z=(0,s.useRef)(null),we=(0,s.useRef)(!0),J=(0,s.useRef)(!1),Ee=(0,s.useRef)("google_pay"),Z=(0,s.useRef)("google_pay"),it=(0,s.useRef)(null),He=(0,s.useRef)(null),Ve=(0,s.useRef)(new Set),at=(0,s.useRef)(null);(0,s.useEffect)(()=>(we.current=!0,()=>{we.current=!1;for(let V of Ve.current)window.clearTimeout(V);Ve.current.clear()}),[]);let Ke=(0,s.useRef)(new Map),{startAttempt:st,finishAttempt:je,invalidateAttempt:St,isAttemptInvalidated:Lt,isAttemptCurrent:Pt,generationRef:Et}=ka((V,g,S)=>{h?.(V,g,{...S,popupBlocked:S?.popupBlocked??io(g),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Pe(V),Ce(!0),re(K=>K+1)},{onHandoffObserved:V=>{I.markAvailable(),N?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Et.current,...V==="apple_pay"||V==="google_pay"?{walletType:V}:{}})},defersMissingTerminal:Ac,onMissingTerminalDeferred:(V,g)=>{let S=N?.now()??globalThis.performance?.now()??Date.now(),K=at.current,W=K?.generation===g?K.startedAt:S;N?.performance({stage:"overlay_return",durationMs:Math.max(0,S-W),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:g,...Ac(V)?{walletType:V}:{}}),N?.flush?.().catch(()=>{})}});(0,s.useEffect)(()=>{se&&Fe.current?.focus()},[se,Ae]);let q=(0,s.useCallback)(()=>{re(V=>V+1)},[]),ve=(0,s.useCallback)((V,g,S,K,W=!1)=>{St(K),h?.(V,g,{code:S,popupBlocked:io(g),telemetryReported:W,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Pe(V),Ce(!0),q()},[St,h,q]),Qe=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{J.current&&(J.current=!1,Qe())},[Qe,Ae]);let X=(0,s.useCallback)(()=>{Ce(!1),c?.(null),Qe()},[Qe,c]),Ue=(0,s.useCallback)(()=>{z.current?.()},[]);(0,s.useEffect)(()=>{let V=Mi(e,t);if(!V)return;let g=!1,S=!1,K=async()=>{if(!S){S=!0,g||Y("checking");try{let W=await wc(k,V.clientSecret,Ve.current);if(g)return;let Se=Ds(W,V.providerObjectId,(0,f.isSetupIntentClientSecret)(V.clientSecret));if(Se.kind==="confirmed"){if(!Sc(e,t,V.clientSecret))return;z.current=null,Y("idle"),i({id:Se.paymentMethodId,type:"card",threeDSecureActionResultTokenId:Se.intentId},{...V.accountPatch?{accountPatch:V.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(Se.kind==="terminal"){Bs(e,t,V.clientSecret),z.current=null,Y("idle"),Pe(V.paymentMethodType),Ce(!0),q();return}Y("blocked")}catch{g||Y("blocked")}finally{S=!1}}};return z.current=K,Y("blocked"),()=>{g=!0,z.current===K&&(z.current=null)}},[t,i,q,e,k]);let vt=(0,s.useCallback)(async V=>{let g=!1,S=dt=>{g||(g=!0,V.paymentFailed({reason:"fail",...dt?{message:dt}:{}}))};if(!k||!ye){S();return}let K=Ke.current.get(Ae);if(K&&!Pt(K.generation)){Ke.current.delete(Ae),S();return}if(!K&&Lt()){S();return}if(K&&!je(K.generation)){S();return}K||je();let W=V.expressPaymentType??K?.method??Ee.current,Se=K??null,F=Ec(W),B;W==="apple_pay"?B="apple_pay":W==="google_pay"&&(B="google_pay");let oe=K?.generation??Et.current,j=N,Ie=j?.now()??globalThis.performance?.now()??Date.now(),tt=new AbortController,gt=!1,yt=!1,De=null,xn=e,$n="processing",bn="other",$t="provider_runtime",Wn,Hn=new Promise((dt,rt)=>{Wn=rt}),wn=window.setTimeout(()=>{gt=!0,tt.abort(),Wn(Ti)},zd),Dt=async(dt,rt,Fn)=>{$n=dt,bn=rt,$t=rt==="intent_create"||rt==="session_claim"?"transport_error":"provider_runtime";let Tt=j?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Fn,Hn])}finally{let Kn=j?.now()??globalThis.performance?.now()??Date.now();j?.performance({stage:dt,durationMs:Math.max(0,Kn-Tt),durationMode:"machine",requestCategory:rt,paymentMethodCategory:"wallet",provider:"stripe",...gt?{statusClass:"timeout"}:{}})}};try{if(Ne(!0),c?.(null),!Se&&P){let Oe=await Dt("processing","other",P(F));if(!Oe.proceed){S();return}Se={accountPatch:Oe.accountPatch,sessionId:Oe.sessionId,nonce:Oe.nonce}}let dt=Se?.sessionId??e;xn=dt;let rt=Se?.nonce??t,Fn=it.current??Se?.accountPatch,Tt=Nc({event:V,fallbackEmail:Fn?.email??n,fallbackName:[Fn?.firstName,Fn?.lastName].join(" ").trim()||M});if(!(0,f.isValidEmail)(Tt.email)){S("Buyer details are required."),fe(Ls(W),Tt).then(Oe=>{Oe&&(it.current=Oe)});return}it.current=null;let Kn={...Se?.accountPatch,...qn(Tt,!0)};await Dt("processing","session_claim",Promise.resolve(_?.(Tt)));let{error:Pn}=await Dt("tokenization","provider_sdk",ye.submit());if(Pn){S(),ve(W,Pn,"stripe_wallet_submit_failed",K?.generation);return}if(!dt)throw new Error("Missing sessionId or email for payment.");let Wt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,paymentMethodId:null,intentKind:o},nn=JSON.stringify({sessionId:dt,nonce:rt??"",request:Wt}),ur=He.current,er=ur?.retryIdentity===nn?ur.authorizationAttemptId:(0,f.randomUuidV4)();He.current={authorizationAttemptId:er,retryIdentity:nn};let rn=await Dt("processing","intent_create",xi(r,G,dt,rt??"",{...Wt,authorizationAttemptId:er},{signal:tt.signal}));if(rn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let At=rn.clientSecret,on=Kd({createdAt:Date.now(),sessionId:dt,...rt?{nonce:rt}:{},clientSecret:At,providerObjectId:rn.providerObjectId,paymentMethodType:W,accountPatch:Kn});window.clearTimeout(wn),yt=!0,j?.performance({stage:"callback",durationMs:Math.max(0,(j?.now()??globalThis.performance?.now()??Date.now())-Ie),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let cn=j?.now()??globalThis.performance?.now()??Date.now(),Nt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...B?{walletType:B}:{},attempt:oe},dn=!1,zt=null;j?.log({name:"payment.provider_confirmation.started",...Nt}),De=window.setTimeout(()=>{De!==null&&Ve.current.delete(De),dn=!0;let Oe=j?.now()??globalThis.performance?.now()??Date.now();j?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Nt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Oe-cn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),j?.flush?.().catch(()=>{}),zt?.()},qd),Ve.current.add(De);let un=(Oe,ft)=>{De!==null&&(window.clearTimeout(De),Ve.current.delete(De),De=null);let v=j?.now()??globalThis.performance?.now()??Date.now(),nt=Math.max(0,v-cn),le=Oe;dn&&(Oe==="resolved"?le="resolved_late":Oe==="returned_error"?le="returned_error_late":le="rejected_late");let kn=ft??(Oe==="resolved"?"approved":"provider_error");return j?.log({name:"payment.provider_confirmation.returned",...Nt,operationOutcome:le,terminalReason:kn}),j?.performance({...Nt,durationMs:nt,durationMode:"buyer",operationOutcome:le,terminalReason:kn}),{durationMs:nt,operationOutcome:le,terminalReason:kn}},Ut=!1,ue=!1,dr=Oe=>{if(!Oe||typeof Oe!="object")return null;let ft=Oe;if(ft.error)return null;let v=ft.setupIntent??ft.paymentIntent,nt=Ds(v??null,void 0,!!ft.setupIntent);return nt.kind==="confirmed"?nt:null},pr=Oe=>{if(Ut||K&&Et.current!==K.generation)return;let ft=dr(Oe);if(!ft)return;if(on&&!Sc(dt,rt,At)){Ut=!0;return}let{intentId:v,paymentMethodId:nt}=ft;Ut=!0,ue=!0,He.current=null,z.current=null,we.current&&(Y("idle"),Ne(!1));let le=`${Fc}:${dt}`;Gt(le,{createdAt:Date.now(),sessionId:dt,nonce:rt,accountPatch:Kn,paymentMethodId:nt,providerIntentId:v,paymentMethodType:W});try{i({id:nt,type:"card",threeDSecureActionResultTokenId:v},{accountPatch:Kn,paymentMethodCategory:"wallet",sessionId:dt,nonce:rt})}finally{Gt(le)}},mr=!1;zt=async()=>{if(!(mr||Ut||ue)){mr=!0,we.current&&Y("checking");try{let Oe=await wc(k,At,Ve.current);if(Ut||ue)return;let ft=(0,f.isSetupIntentClientSecret)(At),v=Ds(Oe,rn.providerObjectId,ft);if(v.kind==="confirmed"){pr(ft?{setupIntent:Oe}:{paymentIntent:Oe});return}if(v.kind==="terminal"){if(ue=!0,Bs(dt,rt,At),He.current=null,z.current=null,!we.current)return;Y("idle"),S(),ve(W,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",K?.generation,!0);return}we.current&&!ue&&(Y("blocked"),Ne(!1))}catch{we.current&&!ue&&(Y("blocked"),Ne(!1))}finally{mr=!1}}},z.current=zt;let an,Bn;try{let Oe=await((0,f.isSetupIntentClientSecret)(At)?k.confirmSetup({elements:ye,clientSecret:At,redirect:"if_required"}):k.confirmPayment({elements:ye,clientSecret:At,redirect:"if_required"}));if(!Oe||typeof Oe!="object")throw new Oa(Hd(Oe));if(an=Oe,!an.error&&!dr(an))throw new Oa("confirmation_result_unconfirmed");Bn=un(an.error?"returned_error":"resolved",an.error&&vo(an.error)?"provider_declined":void 0)}catch(Oe){let ft=Oe instanceof Oa?Oe.reason:void 0,v=ft!==void 0,nt=un(v?"returned_error":"rejected");if(j?.error({...v?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:ft}:gs(Oe),...Nt,operationOutcome:nt.operationOutcome,durationMs:nt.durationMs,statusClass:"unknown",terminalReason:nt.terminalReason}),!we.current||Ut)return;await zt?.();return}let En=an.error;if(En){if(!we.current||Ut)return;if(vo(En)){ue=!0,Bs(dt,rt,At),He.current=null,z.current=null,Y("idle");let Oe=En.message??"Your payment was declined.";S(Oe),c?.(Oe),u?.(fn(F,Oe,{code:Br(En),declineCode:$o(En)})),Fi({billingApiUrl:r,sessionId:dt,nonce:rt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,providerDeclineReason:Br(En)??"provider_declined",...rn.intentKind==="payment"&&rn.providerObjectId.startsWith("pi_")?{providerIntentId:rn.providerObjectId}:{}}})}else j?.error({...gs(En),...Nt,operationOutcome:Bn.operationOutcome,durationMs:Bn.durationMs,statusClass:"unknown",terminalReason:Bn.terminalReason}),await zt?.();return}if(pr(an),!Ut)throw new Error("Invalid provider returned for APM intent")}catch(dt){if(dt===Ti){let rt=j?.now()??globalThis.performance?.now()??Date.now();j?.error({errorCode:Yd(bn),stage:$n,requestCategory:bn,paymentMethodCategory:"wallet",provider:"stripe",...B?{walletType:B}:{},operationOutcome:"watchdog_expired",checkoutSessionId:xn,durationMs:Math.max(0,rt-Ie),statusClass:"timeout",failureCategory:$t,attempt:oe,terminalReason:"provider_error"}),j?.flush?.().catch(()=>{})}S(),ve(W,dt,dt===Ti?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",K?.generation,dt===Ti)}finally{if(window.clearTimeout(wn),De!==null&&(window.clearTimeout(De),Ve.current.delete(De)),!yt){let dt=j?.now()??globalThis.performance?.now()??Date.now();j?.performance({stage:"callback",durationMs:Math.max(0,dt-Ie),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...gt?{statusClass:"timeout"}:{}})}we.current&&Ne(!1)}},[k,ye,e,t,n,M,fe,_,r,G,o,i,c,u,P,ve,je,Pt,Lt,Et,N,Ae]),Xe=(0,s.useMemo)(()=>Si(a),[a]),kt=(0,s.useMemo)(()=>a.map(f.stripeExpressMethodToOptionKey),[a]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(xa,{state:H,placeholderTestId:"flopay-wallet-placeholder",borderRadius:A,children:(0,d.jsxs)("div",{ref:Te,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[se&&(0,d.jsxs)("button",{ref:Fe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:X,style:Os,children:["Try ",Ls(Q)," again"]}),Be!=="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:Ue,disabled:Be==="checking",style:Os,children:Be==="checking"?"Checking payment status\u2026":"Check payment status"})]}),be&&(0,d.jsx)(jo,{identity:be.identity,methodLabel:be.methodLabel,onComplete:We,onCancel:()=>We(null)},be.id),Be==="idle"&&(0,d.jsx)("div",{style:{display:be?"none":void 0},children:(0,d.jsx)(Qt.ExpressCheckoutElement,{onReady:V=>{_e(Ma(V,kt))},onLoadError:V=>{_e("load_error"),Vs(N,"stripe","wallet","provider_error")},onClick:async V=>{let g=N?.now()??globalThis.performance?.now()??Date.now();Ee.current=V.expressPaymentType,Z.current=Ec(V.expressPaymentType);let S=!0,K=window.setTimeout(()=>{S=!1,V.reject()},Ud),W=P?await P(Z.current):{proceed:!0};if(window.clearTimeout(K),!S)return;if(!W.proceed){Ke.current.delete(Ae),V.reject();return}let Se=st(V.expressPaymentType);at.current={generation:Se,startedAt:g},Ke.current.set(Ae,{generation:Se,method:V.expressPaymentType,accountPatch:W.accountPatch,sessionId:W.sessionId,nonce:W.nonce}),Ce(!1),N?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Se,...V.expressPaymentType==="apple_pay"||V.expressPaymentType==="google_pay"?{walletType:V.expressPaymentType}:{}}),p?.(Z.current),V.resolve()},onConfirm:vt,onCancel:()=>{let V=Ke.current.get(Ae);Ke.current.delete(Ae),N?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...V?{attempt:V.generation}:{}}),St(V?.generation),He.current=null,Ce(!1),J.current=!0,q()},options:{...wi,paymentMethods:Xe,emailRequired:Ye,billingAddressRequired:Ye}},Ae)})]})}),te&&(0,d.jsx)(Vn,{status:"processing"})]})}function Uc(e,t,n){let r=(0,f.resolveSetupFutureUsage)(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...r?{setupFutureUsage:r}:null}}function Ns({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:c,onErrorChange:p,onDecline:u,onCancel:h,runBeforeButtonClick:P,onButtonClick:M,isProcessing:_,submitButtonColor:w,submitButtonBorderRadius:A,submitButtonStyle:I,errorText:b}){let C=Hr(),{emitInstrument:G}=(0,s.useContext)(ar),k=(0,Qt.useStripe)(),ye=(0,Qt.useElements)(),[N,H]=(0,s.useState)(!1),_e=(0,s.useRef)(!1),[te,Ne]=(0,s.useState)(!1),[Ye,be]=(0,s.useState)("loading"),[fe,We]=(0,s.useState)(""),Te=!(0,f.isValidEmail)(r?.trim()),Fe=!Te||(0,f.isValidEmail)(fe.trim()),Ae=(0,s.useCallback)(async()=>{if(!k||!ye||_||_e.current||!te)return;_e.current=!0,H(!0);let re=P?await P("card"):{proceed:!0};if(!re.proceed){_e.current=!1,H(!1);return}M?.("card");let se=re.sessionId??t,Ce=re.nonce??n,Be=bo(o?.trim()),Y=qn({email:re.accountPatch?.email?.trim()||r?.trim()||fe.trim(),firstName:re.accountPatch?.firstName?.trim()||Be.firstName,lastName:re.accountPatch?.lastName?.trim()||Be.lastName}),Q=Y.email,Pe=qn({...re.accountPatch,...Y});try{if(p?.(null),!(0,f.isValidEmail)(Q))throw new Error("A valid email address is required for payment.");await a?.(Y);let z=await ye.submit();if(z.error){p?.(z.error.message??"Payment failed.");return}let we=[Y.firstName,Y.lastName].filter(Boolean).join(" "),J=await k.createPaymentMethod({elements:ye,params:{billing_details:{email:Q,...we?{name:we}:{}}}});if(J.error||!J.paymentMethod){p?.(J.error?.message??"Failed to create payment method.");return}let Ee=J.paymentMethod;if(!se||!Q)throw new Error("Missing sessionId or email for payment.");let Z=Ee.type||e,it=await xi(i,G,se,Ce??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,paymentMethodId:null,intentKind:"payment"});if(it.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let He=it.clientSecret;Gt(Or,{clientSecret:He,sessionId:se,nonce:Ce,accountPatch:Pe,paymentMethodId:Ee.id,paymentMethodType:Ee.type??e,gateway:"stripe"});let{error:Ve,paymentIntent:at}=await k.confirmPayment({clientSecret:He,confirmParams:{return_url:window.location.href,payment_method:Ee.id},redirect:"if_required"});if(Ve){Gt(Or);let je=Ve.message??"Payment failed.";p?.(je),u?.(fn("card",je,{code:Ve.code})),await Fi({billingApiUrl:i,sessionId:se,nonce:Ce,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ve.code??"provider_declined"}});return}let Ke=at?.status;if(!va(Ke)){Gt(Or);let je=Ke==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(je),u?.(fn("card",je,{code:Ke??"missing_payment_intent"}));return}Gt(Or);let st=typeof at?.payment_method=="string"?at.payment_method:at?.payment_method?.id;c({id:st??Ee.id,type:"card",threeDSecureActionResultTokenId:at?.id,gateway:"stripe",paymentMethodType:Ee.type??e},{accountPatch:Pe,paymentMethodCategory:"apm",sessionId:se,nonce:Ce})}catch(z){p?.(z instanceof Error?z.message:"Payment failed. Please try again.")}finally{_e.current=!1,H(!1)}},[k,ye,_,te,P,M,t,n,r,o,fe,a,i,G,e,c,p,u]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Te&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Te&&(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:fe,onChange:re=>We(re.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(Qt.PaymentElement,{onReady:()=>be("ready"),onLoadError:()=>{be("load_error"),Vs(gn(C),"stripe","apm")},onChange:re=>{Ne(!!re.complete)},options:{layout:ki,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,f.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,d.jsx)(Ri,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{Ae()},disabled:!te||!Fe||N||_||Ye!=="ready",color:w,borderRadius:A,style:I,children:N?"Processing\u2026":`Pay with ${(0,f.getStripeMethodDisplayName)(e)}`}),b&&(0,d.jsx)(Ho,{margin:"0.75rem 0 0",children:b})]})}function xc({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:i,stripeInstance:c,paymentElementBaseOptions:p,futureUseSession:u,onTokenizedBody:h,onErrorChange:P,onButtonClick:M,onDecline:_,runBeforeButtonClick:w,onLoadStateChange:A,isProcessing:I=!1,submitButtonColor:b="#4A49FF",submitButtonBorderRadius:C=8,submitButtonStyle:G,buttonAppearance:k,themeId:ye,onExpandApm:N,expandedApmMethod:H}){let{emitInstrument:_e}=(0,s.useContext)(ar),[te,Ne]=(0,s.useState)(null),[Ye,be]=(0,s.useState)(null),fe=(0,s.useRef)(!1),{request:We,collect:Te,finish:Fe}=Vo();(0,s.useEffect)(()=>{i.length>0&&c?A?.("ready"):c||A?.("loading")},[i.length,c,A]);let Ae=(0,s.useCallback)(async Q=>{if(!c||fe.current||I)return;fe.current=!0,be(Q);let Pe=w?await w("card"):{proceed:!0};if(!Pe.proceed){fe.current=!1,be(null);return}M?.("card");let z=Pe.sessionId??e,we=Pe.nonce??t,J=bo([Pe.accountPatch?.firstName,Pe.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ee=qn({email:Pe.accountPatch?.email?.trim()||n?.trim(),firstName:Pe.accountPatch?.firstName?.trim()||J.firstName,lastName:Pe.accountPatch?.lastName?.trim()||J.lastName});if(!(0,f.isValidEmail)(Ee.email)){be(null);let He=await Te((0,f.getStripeMethodDisplayName)(Q),Ee);if(!He){fe.current=!1;return}Ee=He,be(Q)}let Z=Ee.email,it=qn({...Pe.accountPatch,...Ee});try{if(P?.(null),!z||!(0,f.isValidEmail)(Z))throw new Error("Missing sessionId or email for payment.");await o?.(Ee);let He=await xi(a,_e,z,we??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,paymentMethodId:null,intentKind:"payment"});if(He.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ve=He.clientSecret;Gt(Or,{clientSecret:Ve,sessionId:z,nonce:we,accountPatch:it,paymentMethodType:Q,gateway:"stripe"});let{error:at,paymentIntent:Ke}=await c.confirmPayment({clientSecret:Ve,confirmParams:{return_url:window.location.href,payment_method_data:{type:Q,billing_details:{name:[Ee.firstName,Ee.lastName].filter(Boolean).join(" "),...Z?{email:Z}:{}}}},redirect:"if_required"});if(at){Gt(Or);let St=at.message??"Payment failed.";P?.(St),_?.(fn("card",St,{code:at.code})),await Fi({billingApiUrl:a,sessionId:z,nonce:we,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,providerDeclineReason:at.code??"provider_declined"}});return}let st=Ke?.status;if(!va(st)){Gt(Or);let St=st==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";P?.(St),_?.(fn("card",St,{code:st??"missing_payment_intent"}));return}Gt(Or);let je=typeof Ke?.payment_method=="string"?Ke.payment_method:Ke?.payment_method?.id;h({id:je??Ke?.id,type:"card",threeDSecureActionResultTokenId:Ke?.id,gateway:"stripe",paymentMethodType:Q},{accountPatch:it,paymentMethodCategory:"apm",sessionId:z,nonce:we})}catch(He){P?.(He instanceof Error?He.message:"Payment failed. Please try again.")}finally{fe.current=!1,be(null)}},[c,I,w,M,e,t,n,Te,a,_e,r,o,h,P,_]),[re,se]=(0,s.useState)(null),Ce=N?H??null:re,Be=(0,s.useCallback)(Q=>{fe.current||I||Ce&&Ce!==Q||((0,f.needsStripeMethodExplicitConfirm)(Q)?N?N(Q):se(Q):Ae(Q))},[Ce,I,Ae,N]),Y=(0,s.useMemo)(()=>re?Uc(p,re,u):null,[re,p,u]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:We?(0,d.jsx)(jo,{identity:We.identity,methodLabel:We.methodLabel,onComplete:Fe,onCancel:()=>Fe(null)},We.id):i.map(Q=>{let Pe=H===Q,z=Ye===Q,we=Ye!==null&&Ye!==Q||H!=null&&H!==Q;return(0,d.jsxs)(s.default.Fragment,{children:[(0,d.jsx)(Ci,{method:Q,themeId:ye,submitting:z,disabled:we,highlighted:Pe,hasNextStep:(0,f.needsStripeMethodExplicitConfirm)(Q),onClick:()=>Be(Q),backgroundColor:k?.backgroundColor,borderColor:k?.borderColor,textColor:k?.textColor,borderRadius:k?.borderRadius,fontFamily:k?.fontFamily}),!N&&re===Q&&Y&&c&&(0,d.jsx)(Qt.Elements,{stripe:c,options:Y,children:(0,d.jsx)(Ns,{method:Q,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:h,onErrorChange:P,onDecline:_,onCancel:()=>se(null),runBeforeButtonClick:w,onButtonClick:M,isProcessing:I,submitButtonColor:b,submitButtonBorderRadius:C,submitButtonStyle:G})},Q)]},Q)})})}function pp({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:i,onError:c,onDecline:p,onTokenizedBody:u,firstName:h,lastName:P,chv:M,className:_,submitLabel:w,isProcessing:A,error:I,onErrorChange:b,showPayPal:C=!0,showStripe:G=!0,walletPresentation:k="auto",enabledPaymentMethods:ye,enabledPaymentMethodCountries:N,showApplePay:H=!0,showGooglePay:_e=!0,layout:te="default",theme:Ne,buttonsTheme:Ye,buttonsStyles:be,appearance:fe,cardButtonContent:We,cardBackButtonContent:Te,cardTitleContent:Fe,showSecurityFooter:Ae,onButtonClick:re,onBeforeButtonClick:se,onBuyerIdentityReady:Ce,enableAVS:Be,cardFieldOrder:Y,cardPreFormSlot:Q,avsLayout:Pe="row",country:z,zip:we,addressLine1:J,addressLine2:Ee,city:Z,state:it,onCountryChange:He,onZipChange:Ve,avsCheck:at,checkoutType:Ke,checkoutLayout:st,totalAmount:je=0,currency:St="usd",initialCardOpen:Lt=!1,directPaypal:Pt,isSubscription:Et=!1,session:q,dataAttachmentPending:ve=!1,dataAttachmentRequiresIdentity:Qe=!1,debug:X=!1}){let Ue=Hr(),vt=ri(),Xe=(0,s.useContext)(Cr),{emitInstrument:kt}=(0,s.useContext)(ar),V=(0,s.useRef)(null);V.current||(V.current=si());let g=V.current,[,S]=(0,s.useState)(0),K=(0,s.useRef)(null);K.current||(K.current=Kr());let W=K.current,Se=(0,s.useMemo)(()=>({browser:W,capability:g,presentationMode:"popup"}),[W,g]),F=q??Xe.session,B=(0,s.useMemo)(()=>({futureUse:F?.futureUse,futureUseUnsupported:F?.futureUseUnsupported}),[F?.futureUse,F?.futureUseUnsupported]),oe=F?.gateways?.paypal?.providerObjectType??Pt?.providerObjectType,j=ve||Xe.claimPending===!0,Ie=Qe||Xe.claimRequiresIdentity===!0,tt=j&&!Ie,gt=Jl(),yt=n||gt,[De,xn]=(0,s.useState)(!1),[$n,bn]=(0,s.useState)(null),[$t,Wn]=(0,s.useState)(z??""),[Hn,wn]=(0,s.useState)(we??""),[Dt,dt]=(0,s.useState)(J??""),[rt,Fn]=(0,s.useState)(Ee??""),[Tt,Kn]=(0,s.useState)(Z??""),[Pn,Wt]=(0,s.useState)(it??""),[nn,ur]=(0,s.useState)(""),[er,rn]=(0,s.useState)({}),At=(0,s.useRef)(we??""),on=(0,s.useRef)(z??""),cn=(0,s.useRef)(J??""),Nt=(0,s.useRef)(Ee??""),dn=(0,s.useRef)(Z??""),zt=(0,s.useRef)(it??""),un=(0,s.useRef)(""),Ut=(0,s.useRef)({});(0,s.useEffect)(()=>{let l=(T,ne,ze,ie,xe)=>{if(Ut.current[T])return;let Ft=ne?.trim();!Ft||Ft===ze.current||(ze.current=Ft,ie(Ft),xe?.(Ft))};l("country",z,on,Wn,He),l("zip",we,At,wn,Ve),l("addressLine1",J,cn,dt),l("addressLine2",Ee,Nt,Fn),l("city",Z,dn,Kn),l("state",it,zt,Wt)},[z,we,J,Ee,Z,it,He,Ve]);let ue=(0,s.useMemo)(()=>(0,f.resolveAVSConfig)(Be),[Be]),dr=ue!==null,pr=(0,s.useMemo)(()=>(0,f.isAuthorizationOnlySession)(q),[q]),mr=(0,f.isMountableVaultBlock)(q?.vault),an=!!q?.gateways?.pcivault,Bn=ms(q),Oe=!!(q?.gateways?.stripe?.enabledPaymentMethods??ye)?.includes("card")||eo(q),ft=mr||Oe||an,v=!!(G&&ft&&e),[nt,le]=(0,s.useState)(()=>te!=="buttons"||Lt?e??null:null),[kn,Gn]=(0,s.useState)(0),Yt=te!=="buttons"||Lt||!!e&&nt===e,Dn=q?.captureMethod,ht=(0,s.useRef)(Ue);(0,s.useEffect)(()=>{ht.current=Ue},[Ue]);let[yr,po]=(0,s.useState)(null);(0,s.useEffect)(()=>{if(!v||!e||!Yt){po(null);return}let l=ht.current?ht.current.cardCapture({sessionId:e,captureMethod:Dn}):new kr.PciVaultCardCapture({sessionId:e,captureMethod:Dn,billingApiUrl:yt,telemetry:r});return po({sessionId:e,captureMethod:Dn,billingApiUrl:yt,telemetry:r,capture:l}),()=>{l.unmount()}},[v,e,Yt,Dn,yt,r]);let Mt=v&&e&&Yt&&yr?.sessionId===e&&yr.captureMethod===Dn&&yr.billingApiUrl===yt&&yr.telemetry===r?yr.capture:null,On=(0,s.useMemo)(()=>{let l=$t,T=ue?(0,f.isAVSFieldVisible)(ue.postal_code,l):!1;return cp(l,Hn,T)},[ue,$t,Hn]),{avsInvalid:Rr,invalidAvsFields:tr}=(0,s.useMemo)(()=>{let l={line1:!1,city:!1,state:!1,zip:!1};if(!v||!ue)return{avsInvalid:!1,invalidAvsFields:l};let T=$t,ne=(xe,Ft)=>(0,f.isAVSFieldVisible)(xe,T)&&!Ft.trim(),ze={line1:ne(ue.address_line_1,Dt),city:ne(ue.city,Tt),state:ne(ue.state,Pn),zip:On.empty||On.malformed};return{avsInvalid:ze.line1||ze.city||ze.state||ze.zip,invalidAvsFields:ze}},[v,ue,$t,Dt,Tt,Pn,On]),[Xt,fr]=(0,s.useState)(!1),[Ln,Ur]=(0,s.useState)(!1),[Nn,_r]=(0,s.useState)(!1),[Er,zr]=(0,s.useState)({line1:!1,city:!1,state:!1}),Yn=(0,s.useRef)(!1),nr=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),qr=(0,s.useRef)(!1),Ot=(0,s.useCallback)(l=>{nr.current[l]=!0,qr.current=!0},[]),In=(0,s.useCallback)(l=>!Yn.current&&nr.current[l],[]),rr=(0,s.useCallback)(l=>{In(l)&&zr(T=>T[l]?T:{...T,[l]:!0})},[In]),[gr,Ir]=(0,s.useState)(()=>(0,f.resolveVaultMountOptions)(q?.vault,{billingApiUrl:yt,sessionId:e,nonce:t})),[lt,pn]=(0,s.useState)(Lt&&ft?"card":"buttons"),[mn,Tn]=(0,s.useState)(null),mo=lt==="expanding"||lt==="card",Tr=q?.gateways?.stripe&&!Bn?"stripe":void 0,Zr=(0,s.useCallback)(()=>{kt?.({class:"card_surface",provider:Tr})},[Tr,kt]),An=(0,s.useRef)(null),yn=(0,s.useCallback)(l=>{An.current&&clearTimeout(An.current),An.current=setTimeout(()=>{An.current=null,l()},Na)},[]);(0,s.useEffect)(()=>()=>{An.current&&clearTimeout(An.current)},[]);let hr=(0,s.useRef)(!1),[vn,L]=(0,s.useState)(0),$=(0,s.useRef)(null),ce=(0,s.useCallback)(()=>{Zr(),le(e??null),hr.current&&(hr.current=!1,L(l=>l+1)),Gn(l=>l+1),pn("expanding"),yn(()=>pn("card"))},[yn,Zr,e]),Me=(0,s.useCallback)(()=>{pn("collapsing"),yn(()=>pn("buttons"))},[yn]),Ct=(0,s.useCallback)(l=>{Tn(l),pn("apm-expanding"),yn(()=>pn("apm-form"))},[yn]),Jt=(0,s.useCallback)(()=>{pn("apm-collapsing"),yn(()=>{pn("buttons"),Tn(null)})},[yn]);(0,s.useEffect)(()=>{te==="buttons"&&Lt&&ft&&(le(e??null),pn("card"))},[te,Lt,ft,e]);let[ke,de]=(0,s.useState)(null),ee=(0,s.useRef)(!1),m=(0,s.useRef)(null),y=(0,s.useRef)("idle"),[D,U]=(0,s.useState)(!1),Re=(0,s.useRef)(D);Re.current=D;let[ge,Rt]=(0,s.useState)(()=>Pt?.existingOrderId?{orderId:Pt.existingOrderId,attempts:1}:null),qt=(0,s.useRef)(ge);(0,s.useEffect)(()=>{qt.current=ge},[ge]);let $e=(0,s.useRef)(null),Ge=(0,s.useMemo)(()=>{if(Ce||Xe.claimBuyerIdentity||q?.buyerIdentified!==!1||!e||!t)return;let l=`${yt}|${e}|${t}`;$e.current?.key!==l&&($e.current={key:l,claim:zo(new kr.PaymentAPI(yt,{telemetry:!1}),e,t,{...a?{userId:a}:{},...h?{firstName:h}:{},...P?{lastName:P}:{}})});let T=$e.current.claim;return async ne=>{await T(ne)}},[Ce,Xe.claimBuyerIdentity,q?.buyerIdentified,e,t,yt,a,h,P]),ct=Ce??Xe.claimBuyerIdentity??Ge,pe=I??$n,he=(0,s.useMemo)(()=>(0,f.resolveTheme)(Ne),[Ne]),E=(0,s.useMemo)(()=>{let l=he?.buttonsLayout??(0,f.resolveButtonsLayoutTheme)(Ye);return be?{...l,...be,cardButton:{...l.cardButton,...be.cardButton},cardFormContainer:{...l.cardFormContainer,...be.cardFormContainer},backButton:{...l.backButton,...be.backButton},backButtonIcon:{...l.backButtonIcon,...be.backButtonIcon},submitButton:{...l.submitButton,...be.submitButton},title:{...l.title,...be.title}}:l},[he,Ye,be]),me=fe??he?.appearance,pt=(0,s.useMemo)(()=>na({appearance:me,buttonsStyles:E,layout:te}),[me,E,te]),xt=Xe.inlineSessionPatchProcessing??!1,ae=(A??De)||xt,Rn=yt.replace(/\/+$/,""),ot=(0,s.useMemo)(()=>fs({userId:a,email:o,firstName:h,lastName:P,country:z,zip:we},er),[a,o,h,P,z,we,er]),_o=[ot.firstName,ot.lastName].filter(l=>!!l?.trim()).join(" "),Qs=!(0,f.isValidEmail)(ot.email?.trim()),Wi=(0,s.useRef)(null);v&&Wi.current===null&&(Wi.current=Qs);let Qr=v&&(Wi.current??Qs),Hi=(0,s.useMemo)(()=>up(nn,Qr),[nn,Qr]),Eo=Hi.empty||Hi.malformed,Xn=(0,s.useMemo)(()=>Ue?Ue.getRawProvider():null,[Ue]),el=(0,s.useMemo)(()=>vt?vt.getRawProvider():null,[vt]),ia=je||100,Io=St.toLowerCase(),Ki=(0,s.useMemo)(()=>me?(0,kr.toStripeAppearance)(me):null,[me]),To=Ki,tl=(0,s.useMemo)(()=>{let l=Ki??{},T=l.rules??{};return{...l,rules:{...T,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...T[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...T[".AccordionItemContents"]??{}}}}},[Ki]),nl=(0,s.useMemo)(()=>({...Hl(je,F?.captureMethod,B),currency:Io,...To?{appearance:To}:null}),[je,Io,F?.captureMethod,B,To]),Gi=(0,f.resolveSetupFutureUsage)(B,"paypal","paypal"),rl=(0,s.useMemo)(()=>({mode:"payment",amount:ia,currency:Io,captureMethod:"manual",...Gi?{setupFutureUsage:Gi}:null,...To?{appearance:To}:null}),[ia,Io,Gi,To]),Le=(0,s.useCallback)(l=>{bn(l),b?.(l)},[b]),ol=(0,s.useRef)(0);(0,s.useEffect)(()=>{vn!==ol.current&&(ol.current=vn,Le(null))},[vn,Le]);let Yi=(0,s.useRef)(""),[al,gu]=(0,s.useState)(!1),Xi=(0,s.useCallback)(()=>{gu(!0)},[]);(0,s.useEffect)(()=>{if(!v||!Qr||!ct||!al||Eo||Yi.current)return;let l=qn({email:(0,f.isValidEmail)(ot.email?.trim())?ot.email?.trim():un.current.trim(),firstName:ot.firstName?.trim(),lastName:ot.lastName?.trim()});Yi.current=JSON.stringify(l),rn(T=>({...T,...l})),Promise.resolve(ct(l)).catch(T=>{Yi.current="",Le(T instanceof Error?T.message:"Failed to attach buyer details.")})},[v,Qr,ct,al,Eo,ot.email,ot.firstName,ot.lastName,Le]),(0,s.useEffect)(()=>{!v||!Mt||Mt.setCardFieldOrder?.(Y??null,ue==null&&!Qr)},[v,Mt,Y,ue,Qr]),(0,s.useEffect)(()=>{(lt==="expanding"||lt==="collapsing"||lt==="apm-expanding"||lt==="apm-collapsing")&&Le(null)},[lt,Le]);let Ar=(0,s.useCallback)((l,T,ne)=>{p?.(fn(l,T,ne))},[p]),Ao=(0,s.useCallback)((l,T,ne)=>{let ze=ne?.popupBlocked??io(T);ze&&g.markBlocked()&&S(mt=>mt+1);let ie=oo(Ls(l),ze,W.inAppBrowser),xe=Br(T),Ft=(xe?.toLowerCase()==="error"?void 0:xe)??Po(ne?.code)??"external_payment_method_failed",vr=new f.FloPayError(ie,"api_error",{code:"external_payment_method_failed",param:l,details:{providerCode:Ft,popupBlocked:ze,inAppBrowser:W.inAppBrowser,appFamily:W.appFamily,popupCapability:g.current(),presentationMode:ne?.presentationMode??"popup"}});ne?.telemetryReported||gn(Ue)?.error(Zo({...Se,presentationMode:ne?.presentationMode??"popup"},{errorCode:ze?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:ne?.provider??(l==="paypal"?"paypal":"stripe"),paymentMethodCategory:ne?.paymentMethodCategory??(l==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:ne?.terminalReason??(ze?"popup_blocked":"provider_error")})),de(null),te==="buttons"&&(pn("buttons"),Tn(null)),Le(ie),c?.(vr),console.error("[FloPay] External payment method failed:",{method:l,code:Ft,popupBlocked:ze})},[W,Se,Ue,te,c,g,Le]);(0,s.useEffect)(()=>{if(!v||!e){Ir(null);return}let l={billingApiUrl:Rn,sessionId:e,nonce:t},T=(0,f.resolveVaultMountOptions)(q?.vault,l);if(T){Ir(T);return}if(!Yt){Ir(null);return}let ne=`${Rn}\0${e}\0${t??""}`,ze=$.current;if(ze&&ze.key===ne){Ir(ze.mount);return}Ir(null);let ie=!0;return new kr.PaymentAPI(Rn).getVaultCapture(e,t).then(xe=>{if(!ie)return;let Ft=(0,f.resolveVaultMountOptions)(xe,l);Ft?.verificationRequired&&!xe.html&&($.current={key:ne,mount:Ft}),Ft?Ir(Ft):Le("Failed to load the secure card form.")}).catch(xe=>{ie&&Le(xe instanceof Error?xe.message:"Failed to load the secure card form.")}),()=>{ie=!1}},[v,Yt,kn,e,q?.vault,Rn,t,Le]);let br=(0,s.useRef)({onComplete:i,onError:c,updateError:Le,emitDecline:Ar,resolvedAccount:ot,avsConfig:ue,avsCheckProp:at,sessionId:e,nonce:t,baseUrl:Rn,captureMethod:q?.captureMethod,paymentId:q?.paymentId,authorizationExpiresAt:q?.authorizationExpiresAt,serverSideCardGateway:Bn});br.current={onComplete:i,onError:c,updateError:Le,emitDecline:Ar,resolvedAccount:ot,avsConfig:ue,avsCheckProp:at,sessionId:e,nonce:t,baseUrl:Rn,captureMethod:q?.captureMethod,paymentId:q?.paymentId,authorizationExpiresAt:q?.authorizationExpiresAt,serverSideCardGateway:Bn};let Ji=(0,s.useRef)(!1),il=(0,s.useCallback)(()=>{let l=br.current,T=l.resolvedAccount.email?.trim(),ne=(0,f.isValidEmail)(T)?T:un.current.trim();if(!(0,f.isValidEmail)(ne))return null;let ze=l.resolvedAccount.firstName?.trim(),ie=l.resolvedAccount.lastName?.trim(),xe=on.current.trim()||l.resolvedAccount.country?.trim()||"",Ft=l.avsConfig?(0,f.isAVSFieldVisible)(l.avsConfig.state,xe):!1,vr=l.avsConfig?(0,f.isAVSFieldVisible)(l.avsConfig.address_line_1,xe):!1,mt=l.avsConfig?(0,f.isAVSFieldVisible)(l.avsConfig.postal_code,xe):!1,wt=l.avsConfig?(0,f.isAVSFieldVisible)(l.avsConfig.city,xe):!1,_t=l.avsConfig?(0,f.isAVSFieldVisible)(l.avsConfig.address_line_2,xe):!1,Vt=vr&&!Ft&&mt?(0,f.getStateFromPostalCode)(xe,(At.current??"").trim()):null,go=Ft?zt.current:Vt;return{accountData:{userId:l.resolvedAccount.userId??"",email:ne,...ze?{firstName:ze}:{},...ie?{lastName:ie}:{},...mt&&At.current?{zip:At.current}:{},...wt&&dn.current?{city:dn.current}:{},...go?{state:go}:{},...vr&&cn.current?{addressLine1:cn.current}:{},..._t&&Nt.current?{addressLine2:Nt.current}:{},...xe?{country:xe}:{}},...l.avsCheckProp===void 0?{}:{avsCheck:l.avsCheckProp},...l.avsConfig?{avsConfig:{country:(0,f.isAVSFieldVisible)(l.avsConfig.country,xe),postal_code:mt,address_line_1:vr,address_line_2:_t,city:wt,state:Ft}}:{}}},[]),sl=(0,s.useRef)(j);sl.current=j,(0,s.useEffect)(()=>{j||pe!==kc||br.current.updateError(null)},[j,pe]),(0,s.useEffect)(()=>{!v||!Mt||Mt.setSubmitGate?.(Rr||j||Eo||D)},[v,Mt,Rr,j,Eo,D]),(0,s.useEffect)(()=>{if(!v||!Mt)return;Ji.current=!1;let l=null,T=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null,y.current="idle",de(null)},400)},ne=Mt.on("submitting",()=>{fr(!0),m.current&&clearTimeout(m.current),y.current="validation-window",m.current=setTimeout(()=>{m.current=null,y.current==="validation-window"&&(y.current="processing")},Zd),de("processing");let mt=br.current;if(!mt.sessionId||!mt.nonce)return;let wt=il();if(!wt){mt.updateError("Enter a valid email address."),y.current="idle",de(null);return}new kr.PaymentAPI(mt.baseUrl).patchAccountSnapshot(mt.sessionId,mt.nonce,wt,{telemetryMode:"best_effort"}).catch(_t=>{if(!ep(_t))return;let Vt=_t instanceof Error?_t.message:"Please check your billing address and try again.";mt.updateError(Vt),y.current="idle",de(null),mt.onError?.(_t instanceof f.FloPayError?_t:new f.FloPayError(Vt,"api_error"))})}),ze=Mt.on("complete",mt=>{Yo(mt.sessionId??br.current.sessionId),y.current="terminal",U(!1),de("success"),setTimeout(()=>{if(Ji.current)return;Ji.current=!0;let wt=br.current,_t=(0,f.isAuthorizationOnlySession)(wt)||mt.outcome==="authorized",Vt=wt.serverSideCardGateway?{}:{paymentIntentId:mt.intentId};br.current.onComplete?.(_t?{status:"authorized",...Vt,paymentId:mt.paymentId??wt.paymentId,sessionId:mt.sessionId??wt.sessionId,authorizationExpiresAt:mt.authorizationExpiresAt??wt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Vt,checkoutMethod:"card"})},600)}),ie=Mt.on("decline",mt=>{let wt=br.current,_t=mt.message??"Your payment was declined. Please try another card or contact your bank.";y.current="terminal",U(!1),wt.updateError(_t),de("error");let Vt=mt.failureOutcome??(0,f.normalizeCheckoutFailureOutcome)(mt.declineReason)??"authorization_declined";wt.emitDecline("card",_t,{code:Vt,declineCode:Vt}),T()}),xe=Mt.on("error",mt=>{let wt=br.current,_t=mt.message??"There was a problem processing your payment. Please try again.";y.current="terminal",U(!1),wt.updateError(_t),de("error"),wt.onError?.(new f.FloPayError(_t,"api_error",{code:mt.failureOutcome??"capture_failed"})),T()}),Ft=Mt.on("challenge_dismissed",()=>{m.current&&(clearTimeout(m.current),m.current=null),y.current="processing",U(!0),de(null)}),vr=Mt.on("blocked",()=>{if(Re.current){br.current.updateError(Qd);return}if(!sl.current){fr(!0);return}Xi(),br.current.updateError(kc)});return()=>{l&&(clearTimeout(l),l=null),m.current&&(clearTimeout(m.current),m.current=null),y.current="idle",U(!1),de(null),ne(),ze(),ie(),xe(),Ft(),vr()}},[v,Mt,Xi,il]);let Mr=!!Pt?.clientId,sa=Array.isArray(ye),ja=sa&&ye.length>0,ll=sa&&ye.includes("paypal"),$a=(0,s.useRef)(null);$a.current===null&&($a.current=Xd());let Mo=$a.current?"redirect":oi(W,k,g.current()),{expressMethods:Wa,paymentElementMethods:la}=(0,s.useMemo)(()=>(0,f.partitionStripeMethods)(ye,{excludePaypal:Mr}),[ye,Mr]),cl=Mr||!!vt||ll&&Mo==="redirect",hu=(0,s.useMemo)(()=>cl?Wa.filter(l=>l!=="paypal"):Wa,[Wa,cl]),bu=(0,s.useMemo)(()=>{let l=[];return H&&l.push("apple_pay"),_e&&l.push("google_pay"),l},[H,_e]),xo=sa?hu:bu,Pu=G&&xo.length>0,Zi=dr?$t:z,Ha=(0,s.useMemo)(()=>{let l=Zi?.trim().toUpperCase();return l?N?la.filter(T=>{let ne=N[T];return!ne||ne.length===0||ne.includes(l)}):(0,f.filterStripeMethodsByCountry)(la,Zi):la},[la,Zi,N]),Qi=(0,s.useMemo)(()=>({mode:"payment",amount:ia,currency:Io,paymentMethodCreation:"manual",appearance:tl}),[ia,Io,tl]),[ul,dl]=(0,s.useState)("loading"),[pl,ml]=(0,s.useState)("loading"),[yl,fl]=(0,s.useState)("loading"),[vu,es]=(0,s.useState)(!1),[gl,ts]=(0,s.useState)("loading"),[ns,Cu]=(0,s.useState)();(0,s.useEffect)(()=>{Cu(Kr())},[]);let Ka=ns?.inAppBrowser,Ga=ns?ai(ns,Pt?.approvalPresentation,oe??(Et?"subscription":"order")):"popup",hl=C&&(Mr||(sa?ll:Ka===!1)),bl=G&&Pu,ca=(!tt||!!Xe.waitForDataAttachment)&&hl&&Mr,Pl=gl==="retrying"||gl==="exhausted",ua=null;G&&(vt?ua=el:Mo==="redirect"&&(ua=Xn));let vl=(0,s.useMemo)(()=>({...Se,presentationMode:Mo}),[Se,Mo]),da=!tt&&hl&&!!ua&&(!Mr||Pl),Fo=!tt&&bl&&!!Xn,pa=!tt&&G&&ja&&Ha.length>0&&!!Xn,Su=ca&&!Pl?vu:da&&Ms(ul),wu=Fo&&Ms(pl),ku=pa&&yl!=="load_error",Cl=l=>l==="loading"||l==="ready",Sl=ca||da&&Cl(ul)||Fo&&Cl(pl)||pa&&yl!=="load_error",Ya=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!Ya.current){if(!G&&!C){Ya.current=!0;let l=new f.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(l),Le(l.message)}else if(!G&&C&&!Mr){Ya.current=!0;let l=new f.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(l),Le(l.message)}else if(Ka!==void 0&&!tt&&!ft&&!Sl){Ya.current=!0;let l=new f.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});c?.(l),Le(l.message)}}},[G,C,Mr,Ka,tt,ft,Sl,c,Le]);let wl=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(wl.current||!ja)return;let l=[];H!==!0&&l.push("showApplePay"),_e!==!0&&l.push("showGooglePay"),l.length!==0&&(wl.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.`))},[ja,H,_e]);let kl=(0,s.useCallback)((l,T)=>Xe.applyInlineSessionPatch?Xe.applyInlineSessionPatch(l).then(ne=>({error:null,sessionId:ne.sessionId||e,nonce:ne.session?.clientSecret||t})).catch(ne=>{let ze=Ic(T,ne);return Le(ze.message),c?.(ze),{error:ze,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Xe.applyInlineSessionPatch,t,c,e,Le]),Pr=(0,s.useCallback)(async l=>{if(l!=="card"&&tt&&await Xe.waitForDataAttachment?.(),!se)return{proceed:!0};try{let T=await se({method:l,sessionId:e||void 0,createSession:Xe.inlineSessionDraft});if(T===!1)return{proceed:!1};if(T&&typeof T=="object"){T.account&&rn(ze=>({...ze??{},...T.account}));let ne=await kl(T,l);return ne.error?{proceed:!1,accountPatch:T.account}:{proceed:!0,accountPatch:T.account,sessionId:ne.sessionId,nonce:ne.nonce}}return{proceed:!0}}catch(T){let ne=Ic(l,T);return Le(ne.message),c?.(ne),{proceed:!1}}},[kl,Xe.inlineSessionDraft,Xe.waitForDataAttachment,tt,se,c,e,Le]),Rl=(0,s.useCallback)(async(l,T)=>{if(ee.current)return;ee.current=!0,xn(!0),de("processing"),Le(null);let ne=T?.sessionId??e,ze=T?.nonce??t,ie=fs(ot,T?.accountPatch),xe=T?.completionPaymentMethodId??Ca(l),Ft=l.originalPaymentMethodId?{...l,originalPaymentMethodId:void 0}:l,vr=op(l),mt=T?.presentationMode?vi(gn(Ue),{...Se,presentationMode:T.presentationMode}):void 0,wt=()=>{kt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:vr}),mt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...wr,requestCategory:"process_payment"})};try{let _t=new kr.PaymentAPI(Rn),Vt=await _t.processPayment(ie.userId??"",{sessionId:ne,nonce:ze,paymentMethodCategory:T?.paymentMethodCategory??ip(l),tokenizedData:Ft,accountData:{...T?.accountPatch,userId:ie.userId??"",email:ie.email??"",firstName:ie.firstName||void 0,lastName:ie.lastName||void 0,...ue?(()=>{let Bt=on.current,xr=(0,f.isAVSFieldVisible)(ue.state,Bt),Zn=(0,f.isAVSFieldVisible)(ue.address_line_1,Bt),Fr=(0,f.isAVSFieldVisible)(ue.postal_code,Bt),ho=Zn&&!xr&&Fr?(0,f.getStateFromPostalCode)(Bt,(At.current??"").trim()):null,ba=xr?zt.current:ho;return{country:Bt,...Fr&&At.current?{zip:At.current}:{},...(0,f.isAVSFieldVisible)(ue.city,Bt)&&dn.current?{city:dn.current}:{},...ba?{state:ba}:{},...Zn&&cn.current?{addressLine1:cn.current}:{},...(0,f.isAVSFieldVisible)(ue.address_line_2,Bt)&&Nt.current?{addressLine2:Nt.current}:{}}})():{}},chv:M,avsCheck:at??!1,checkoutType:Ke,checkoutLayout:st,avsConfig:ue?{country:(0,f.isAVSFieldVisible)(ue.country,on.current),postal_code:(0,f.isAVSFieldVisible)(ue.postal_code,on.current),address_line_1:(0,f.isAVSFieldVisible)(ue.address_line_1,on.current),address_line_2:(0,f.isAVSFieldVisible)(ue.address_line_2,on.current),city:(0,f.isAVSFieldVisible)(ue.city,on.current),state:(0,f.isAVSFieldVisible)(ue.state,on.current)}:void 0}),go=async Bt=>{let xr=(0,f.isAuthorizationOnlySession)(q)||Bt?.status==="authorized";Yo(ne),mt?.terminal({outcome:"payment_succeeded",...wr}),de("success"),Rt(null),await new Promise(ho=>setTimeout(ho,600));let Zn;typeof Bt?.paymentId=="string"?Zn=Bt.paymentId:q?.paymentId&&(Zn=q.paymentId);let Fr;typeof Bt?.authorizationExpiresAt=="string"?Fr=Bt.authorizationExpiresAt:q?.authorizationExpiresAt&&(Fr=q.authorizationExpiresAt),i?.(xr?{status:"authorized",...Zn===void 0?{}:{paymentId:Zn},sessionId:typeof Bt?.sessionId=="string"?Bt.sessionId:ne,...Fr===void 0?{}:{authorizationExpiresAt:Fr},paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:xe,checkoutMethod:l.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:xe,checkoutMethod:l.isPaypal?"paypal":"card"})};if(Vt.ok){await go(Vt.status===204?null:await Vt.json().catch(()=>null));return}let Jn=await Vt.json().catch(()=>null);if(Jn?.type==="paypal_redirect_required"){let Bt=Jn.threeDSecureToken,xr=Jn.paymentMethodId||l.id||"";if(!Ue||!Bt){de("error"),Le("PayPal authorization required but no token provided.");return}try{let Zn=vt?.getRawProvider();if(!Zn){Le("PayPal is not available.");return}let Fr={return_url:window.location.href};xr&&(Fr.payment_method=xr);let{error:ho}=await Zn.confirmPayment({clientSecret:Bt,confirmParams:Fr,redirect:"if_required"});if(ho){de("error");let ba=ho.message??"PayPal payment failed.";Le(ba),Ar("paypal",ba,{code:ho.code})}}catch(Zn){de("error"),Le(Zn instanceof Error?Zn.message:"PayPal authorization failed.")}return}if(Jn?.type==="paypal_direct_required"){let Bt=Jn.orderId;if(!Bt){de("error"),Le("PayPal retry required but no order id provided.");return}let xr=qt.current?.attempts??0;if(xr>=2){de("error"),Le("PayPal payment could not be completed after multiple attempts."),Ar("paypal","paypal_direct_required retry limit exceeded");return}es(!1),ts("loading"),Rt({orderId:Bt,attempts:xr+1}),de(null);return}if(Vt.headers.get(jd)===$d){let Bt=await Wd(_t,ne,ze);if(Bt!==void 0){await go(Bt);return}}(0,f.classifyPaymentRejection)(Vt.status,Jn)?mt?.terminal({outcome:"payment_declined",...wr,terminalReason:"provider_declined"}):wt(),de("error");let Ol=Jn?.message??"Payment failed. Please try again.";Le(Ol),Ar(l.isPaypal?"paypal":"card",Ol,{code:Jn?.code??Jn?.gatewayErrorCode,declineCode:Jn?.declineCode??Jn?.gatewayDeclineReason}),await new Promise(Bt=>setTimeout(Bt,400))}catch(_t){Oc(_t)||wt(),de("error"),Le(_t instanceof Error?_t.message:"An unexpected error occurred"),await new Promise(Vt=>setTimeout(Vt,400))}finally{xn(!1),de(null),ee.current=!1}},[Rn,e,t,ot,ue,at,Ke,st,M,Ue,vt,q,i,Le,Ar,kt,Se]),Un=(0,s.useCallback)((l,T)=>{u?u(l):Rl(l,T)},[u,Rl]),ma=`${Fc}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let l=localStorage.getItem(ma);if(!l)return;let T;try{T=JSON.parse(l)}catch{Gt(ma);return}if(!T||typeof T.createdAt!="number"||Date.now()-T.createdAt<0||Date.now()-T.createdAt>Bc||typeof T.paymentMethodId!="string"||typeof T.providerIntentId!="string"||typeof T.paymentMethodType!="string"||T.sessionId!==e||!t||T.nonce!==t||!xo.includes(T.paymentMethodType)){Gt(ma);return}Gt(ma),Un({id:T.paymentMethodId,type:"card",threeDSecureActionResultTokenId:T.providerIntentId,gateway:"stripe",paymentMethodType:T.paymentMethodType},{...T.accountPatch?{accountPatch:T.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Un,t,e,ma,xo]);let _l=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||_l.current)return;let[l,T,ne]=zs();if(!l||!T||$a.current||!Ue)return;let ze=Ue.getRawProvider();if(!ze)return;let ie=wt=>{let _t=localStorage.getItem(wt);if(!_t)return null;try{return JSON.parse(_t)}catch{return Gt(wt),null}},xe=ie(Or)??ie(Cc),Ft;if(xe?.clientSecret){if(xe.clientSecret!==T)return;Ft={...xe.accountPatch?{accountPatch:xe.accountPatch}:{},...xe.sessionId?{sessionId:xe.sessionId}:{},...xe.nonce?{nonce:xe.nonce}:{}}}else if(xe?.sessionId&&xe.sessionId!==e)return;_l.current=!0,Gt(Or),Gt(Cc),window.history.replaceState({},"",qs());let vr=xe?.paymentMethodType??xe?.tokenType??"card",mt="card";(async()=>{if(ne==="failed"){let Vr="Payment was declined. Please try again.";Le(Vr),Ar(mt,Vr);return}let{paymentIntent:wt,error:_t}=await ze.retrievePaymentIntent(T);if(_t){let Vr=_t.message??"Failed to retrieve payment status.";Le(Vr),Ar(mt,Vr,{code:_t.code});return}let Vt=wt?.status,go=va(Vt);if(!wt||!go){let Vr=Vt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Le(Vr),Ar(mt,Vr,{code:Vt??"missing_payment_intent"});return}let Jn=typeof wt.payment_method=="string"?wt.payment_method:wt.payment_method?.id;Un({id:Jn??xe?.paymentMethodId??xe?.tokenId??wt.id,type:"card",threeDSecureActionResultTokenId:wt.id,gateway:xe?.gateway??"stripe",paymentMethodType:vr},Ft)})()},[e,Un,Ue,Le,Ar]);let rs=(0,s.useCallback)(l=>{l.preventDefault()},[]);if(!(v||Ue!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ya=te==="buttons",zn=me?.variables,Ru=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),os=zn?.colorBackground,_u=os&&!Ru.has(os)?os:void 0,fa=E.cardInputBorder??(ya?"#e5e7eb":"#A4A4FF"),El=zn?.colorDanger??"#dc2626",Ht=l=>tr[l]&&(Er[l]||Xt),Xa=Eo&&(Nn||Xt),or=l=>l?El:fa,Ja=(On.malformed||On.empty)&&(Ln||Xt),Eu=or(Ja),as=E.cardFormContainer?.backgroundColor??_u??(ya?"white":"#EDEDFF"),Bo=E.cardInputBackground??zn?.colorBackground??"white",is=Lo(Te),Il=Lo(Fe),Do=E.nameInput,Tl=E.cardInputFontSize??dp(Do?.fontSize)??zn?.fontSizeBase??"16px",Al=typeof Do?.fontFamily=="string"?Do.fontFamily:zn?.fontFamily??"Poppins, sans-serif",Ml=Fs(Do?.fontWeight)??400,Iu=E.cardInputColor??(typeof Do?.color=="string"?Do.color:void 0)??zn?.colorText??"#262833",Tu=E.cardInputPlaceholderColor??"#9ca3af",Zt=zn?.borderRadius??"8px",yo=zn?.borderRadius??E.cardButton?.borderRadius??Zt,fo=zn?.colorPrimary??"#4A49FF",Au=zn?.colorPrimaryHover??ta(fo,.12),ss=zn?.colorText??"#262833",ls={fontSize:Tl,fontFamily:Al,fontWeight:Ml,color:Iu,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ga={marginTop:"0.375rem",...ls,fontSize:"0.75rem",lineHeight:1.4,color:El},Mu={"--flopay-input-placeholder-color":Tu,"--flopay-input-font-size":Tl,"--flopay-input-font-family":Al,"--flopay-input-font-weight":String(Ml)},ha=E.cardFormContainer??{},cs=ha.padding??(ya?"0":"1rem"),us=ha.borderRadius??Zt,xu=Mt&&gr?(0,d.jsx)(co,{capture:Mt,html:gr.html,messageToken:gr.messageToken,expectedOrigin:gr.expectedOrigin,verificationRequired:gr.verificationRequired,theme:pt,submitLabel:w,onReady:()=>{if(!Qr&&!ue||typeof document>"u")return;let l=()=>{let ne=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(ne){Yn.current=!0;try{ne.focus()}finally{Yn.current=!1}}};qr.current||l()},onError:l=>{l&&gr.verificationRequired&&y.current==="idle"&&(hr.current=!0),Le(l)},onValidation:l=>{let T=y.current;(T==="idle"||T==="validation-window")&&(Le(l),l&&y.current==="validation-window"&&(m.current&&(clearTimeout(m.current),m.current=null),y.current="idle",de(null)))}},vn):(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"}),xl=(0,d.jsxs)("div",{onFocusCapture:l=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(l.target.tagName)&&Zr()},style:{backgroundColor:as,borderRadius:us,...ha,padding:cs,...Mu,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 @@ ${yt.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),pa&&po&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:v?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:On,style:{display:"inline-flex",alignItems:"center",gap:rs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:F.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...F.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",...F.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)(Lo,{content:Re})]}),kl?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:F.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...F.title},children:(0,d.jsx)(ha,{content:Ie})})]}),!pa&&!kl&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:os,order:v?-3:0,...F.title},children:(0,d.jsx)(ha,{content:Ie})}),v&&ee&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:ee}),v&&En&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:xo,border:`1px solid ${rr(Ga)}`,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:en,onChange:l=>{Ot("email"),ln.current=l.target.value,cr(l.target.value)},onPointerDown:()=>Ot("email"),onKeyDown:()=>Ot("email"),onBlur:()=>{kn("email")&&kr(!0),Ro||Ki()},disabled:G,required:!0,"aria-invalid":Ga||void 0,"aria-describedby":Ga?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...as}})}),Ga&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ya,children:ji.empty?"Email address is required":"Enter a valid email address"})]}),me&&(0,d.jsx)("div",{style:{order:v?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let l=jt,E=(fe=!1)=>({backgroundColor:xo,border:`1px solid ${rr(fe)}`,borderRadius:Xt,marginTop:"0.5rem",padding:"10px"}),oe=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...as}),Ve=(0,y.getStateOptions)(l);return(0,d.jsxs)(d.Fragment,{children:[(0,y.isAVSFieldVisible)(me.address_line_1,l)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:E(Wt("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:Dt,onChange:fe=>{Ot("line1"),Ut.current.addressLine1=!0,sn.current=fe.target.value,dt(fe.target.value)},onPointerDown:()=>Ot("line1"),onKeyDown:()=>Ot("line1"),onBlur:()=>nr("line1"),disabled:G,required:!0,"aria-invalid":Wt("line1")||void 0,"aria-describedby":Wt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:oe()})}),Wt("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ya,children:"Street address is required"})]}),(0,y.isAVSFieldVisible)(me.address_line_2,l)&&(0,d.jsx)("div",{style:E(),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:fe=>{Ut.current.addressLine2=!0,Nt.current=fe.target.value,An(fe.target.value)},disabled:G,"data-testid":"flopay-address-line2",style:oe()})}),((0,y.isAVSFieldVisible)(me.city,l)||(0,y.isAVSFieldVisible)(me.state,l))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(me.city,l)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${rr(Wt("city"))}`,borderRight:`1px solid ${rr(Wt("city"))}`,borderBottom:`1px solid ${rr(Wt("city"))}`,borderLeft:`1px solid ${rr(Wt("city"))}`,padding:"10px",borderTopLeftRadius:Xt,borderBottomLeftRadius:Xt,...(0,y.isAVSFieldVisible)(me.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:Mt,onChange:fe=>{Ot("city"),Ut.current.city=!0,cn.current=fe.target.value,Wn(fe.target.value)},onPointerDown:()=>Ot("city"),onKeyDown:()=>Ot("city"),onBlur:()=>nr("city"),disabled:G,required:!0,"aria-invalid":Wt("city")||void 0,"aria-describedby":Wt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:oe()})}),(0,y.isAVSFieldVisible)(me.state,l)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${rr(Wt("state"))}`,borderRight:`1px solid ${rr(Wt("state"))}`,borderBottom:`1px solid ${rr(Wt("state"))}`,borderLeft:`1px solid ${rr(Wt("state"))}`,padding:"10px",borderTopRightRadius:Xt,borderBottomRightRadius:Xt,...(0,y.isAVSFieldVisible)(me.city,l)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${rr(Wt("state")||Wt("city"))}`}:{borderRadius:Xt}},children:Ve?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:hn,onChange:fe=>{Ot("state"),Ut.current.state=!0,zt.current=fe.target.value,$t(fe.target.value)},onPointerDown:()=>Ot("state"),onKeyDown:()=>Ot("state"),onBlur:()=>nr("state"),disabled:G,autoComplete:"billing address-level1",required:!0,"aria-invalid":Wt("state")||void 0,"aria-describedby":Wt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...oe(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,y.getStateLabel)(l)}),Ve.map(fe=>(0,d.jsx)("option",{value:fe.code,children:fe.name},fe.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:hn,onChange:fe=>{Ot("state"),Ut.current.state=!0,zt.current=fe.target.value,$t(fe.target.value)},onPointerDown:()=>Ot("state"),onKeyDown:()=>Ot("state"),onBlur:()=>nr("state"),disabled:G,required:!0,"aria-invalid":Wt("state")||void 0,"aria-describedby":Wt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:oe()})})]}),Wt("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ya,children:"City is required"}),Wt("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ya,children:[(0,y.getStateLabel)(l)," is required"]}),((0,y.isAVSFieldVisible)(me.country,l)||(0,y.isAVSFieldVisible)(me.postal_code,l))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:he==="column"?"column":"row",gap:he==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(me.country,l)&&(0,d.jsx)("div",{style:{flex:he==="row"?1:void 0,backgroundColor:xo,borderTop:`1px solid ${ma}`,borderRight:`1px solid ${ma}`,borderBottom:`1px solid ${ma}`,borderLeft:`1px solid ${ma}`,padding:"10px",...he==="row"&&(0,y.isAVSFieldVisible)(me.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:jt,onChange:fe=>{Ut.current.country=!0,nn.current=fe.target.value,jn(fe.target.value),He?.(fe.target.value),zt.current="",$t("")},disabled:G,autoComplete:"billing country","data-testid":"flopay-country",style:{...oe(),cursor:"pointer"},children:[jt===""?(0,d.jsx)("option",{value:"",children:"Select country"}):null,y.COUNTRY_OPTIONS.map(fe=>(0,d.jsxs)("option",{value:fe.code,children:[fe.flag," ",fe.name]},fe.code))]})}),(0,y.isAVSFieldVisible)(me.postal_code,l)&&(0,d.jsx)("div",{style:{flex:he==="row"?1:void 0,backgroundColor:xo,border:`1px solid ${wu}`,padding:"10px",...he==="row"&&(0,y.isAVSFieldVisible)(me.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)(jt),autoComplete:"billing postal-code",value:$n,onChange:fe=>{Ot("zip"),Ut.current.zip=!0,xt.current=fe.target.value,vn(fe.target.value),je?.(fe.target.value)},onPointerDown:()=>Ot("zip"),onKeyDown:()=>Ot("zip"),onBlur:()=>{kn("zip")&&Or(!0)},disabled:G,required:Fn.required,"aria-invalid":Ya||void 0,"aria-describedby":Ya?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:oe()})})]}),Ya&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ya,children:Fn.empty?`${(0,y.getPostalCodeLabel)(l)} is required`:op(l)})]})})()}),v&&Iu,Pt&&(0,d.jsx)($o,{margin:"0.75rem 0",styleOverride:F.errorBanner,children:Pt})]}),Xa={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"},Tl=l=>Z?!w||!Ir?(0,d.jsx)("pre",{"data-testid":l,style:Xa,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":l,style:Xa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${w}`,` directPaypalConfigured=${Ir}`,` inAppBrowserDetected=${String(Wa)}`,` shouldRenderDirectPayPal=${sa}`,` shouldRenderStripePayPal=${ca}`,` hasPaypalStripeInstance=${!!Js}`].join(`
|
|
39
|
-
`)}):null,
|
|
40
|
-
`)}):null,Ml=ct==="apm-expanding"||ct==="apm-form"||ct==="apm-collapsing",Bo;ct==="apm-expanding"?Bo=Cc:ct==="apm-collapsing"&&(Bo=Sc);let Ja=dn?Dc(Xi,dn,B):null;if(ae==="buttons"){let l=ct==="buttons"||ct==="expanding"||ct==="apm-expanding",E=ct==="expanding"||ct==="card"||ct==="collapsing",oe=We===void 0?{boxSizing:"border-box",height:Jo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ve;ct==="expanding"||ct==="apm-expanding"?Ve=Qd:(ct==="collapsing"||ct==="apm-collapsing")&&(Ve=Zd);let fe;return ct==="expanding"?fe=Cc:ct==="collapsing"&&(fe=Sc),(0,d.jsxs)("form",{onSubmit:es,className:I,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Zo,{}),re&&(0,d.jsx)(zn,{status:re,errorMessage:Pt,authorized:dr}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!l&&!Ve?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!l&&!Ve?tp:{},...Ve?{animation:Ve,pointerEvents:"none"}:{}},children:[Tl("flopay-direct-paypal-gate-debug"),Al("flopay-stripe-gate-debug"),sa&&ht&&(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)(Ca.Provider,{value:h,children:(0,d.jsx)(wa,{sessionId:e,nonce:t,billingApiUrl:Ct,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:tt,clientId:ht.clientId,environment:ht.environment,currency:vt.toUpperCase(),isSubscription:Tt,providerObjectType:de,approvalPresentation:Ha==="popup"?void 0:Ha,onTokenizedBody:Ln,onComplete:i,onErrorChange:qe,onDecline:p,onTechnicalFailure:Io,onButtonClick:ce,runBeforeButtonClick:hr,isProcessing:G,onLoadStateChange:Ji,onInitializationStateChange:Zi,session:x,existingOrderId:m?.orderId,debug:Z},m?.orderId??"fresh")})]}),ca&&(0,d.jsx)(Zt.Elements,{stripe:la,options:el,children:(0,d.jsx)(Rc,{sessionId:e,nonce:t,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:tt,billingApiUrl:Ct,onTokenizedBody:Ln,onErrorChange:qe,isProcessing:G,onButtonClick:ce,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:hr,onLoadStateChange:sl,placeholderBorderRadius:mo,popupCapabilityOwner:h,externalTelemetryContext:gl,presentationMode:To})}),Mo?(0,d.jsx)(Zt.Elements,{stripe:Gn,options:Qs,children:(0,d.jsx)(Ec,{sessionId:e,nonce:t,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:tt,billingApiUrl:Ct,intentKind:$e>0?"payment":"setup",expressMethods:Ao,onTokenizedBody:Ln,onErrorChange:qe,onButtonClick:ce,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:hr,onLoadStateChange:cl,placeholderBorderRadius:mo,popupCapabilityOwner:h,externalTelemetryContext:ve})}):null,!Mo&&yl?(0,d.jsx)("div",{style:{height:Jo,borderRadius:mo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ua&&(0,d.jsx)(Ic,{sessionId:e,nonce:t,email:ne.email,billingName:[ne.firstName,ne.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:tt,billingApiUrl:Ct,paymentElementMethods:$a,stripeInstance:Gn,paymentElementBaseOptions:Xi,futureUseSession:B,onTokenizedBody:Ln,onErrorChange:qe,onButtonClick:ce,onDecline:p,runBeforeButtonClick:hr,onLoadStateChange:dl,isProcessing:G,submitButtonColor:yo,submitButtonBorderRadius:Xt,submitButtonStyle:F.submitButton,onExpandApm:L,expandedApmMethod:dn,themeId:De,buttonAppearance:{backgroundColor:F.cardButton?.backgroundColor,borderColor:F.cardInputBorder,textColor:F.cardButton?.color,borderRadius:mo}}),v&&(0,d.jsx)("button",{type:"button",onClick:async()=>{G||!(await hr("card")).proceed||(ce?.("card"),qr())},disabled:G,style:{width:"100%",...oe,...F.cardButton,...qs({themeBundle:Le,resolvedPrimaryColor:yo,resolvedBorderRadius:Xt,submitButtonStyle:F.submitButton,explicitPrimaryColor:Nn?.colorPrimary}),fontSize:F.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:G?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:G?.6:1},onMouseEnter:Ue=>{!G&&(Le||Nn?.colorPrimary)&&(Ue.currentTarget.style.backgroundColor=_u)},onMouseLeave:Ue=>{(Le||Nn?.colorPrimary)&&(Ue.currentTarget.style.backgroundColor=yo)},onMouseDown:Ue=>{Ue.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ue=>{Ue.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(Oo,{content:We})}),Pt&&ct==="buttons"&&(0,d.jsx)($o,{margin:"0.25rem 0",styleOverride:F.errorBanner,children:Pt})]}),v&&E&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...fe?{animation:fe}:{},...ct==="collapsing"?{pointerEvents:"none"}:{}},children:Il}),K&&Ml&&dn&&Ja&&Gn&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Bo?{animation:Bo}:{},...ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:ns,borderRadius:ss,...fa,padding:is},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:q,style:{display:"inline-flex",alignItems:"center",gap:rs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:F.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...F.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",...F.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)(Lo,{content:Re})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:F.titleFontSize??"1.05rem",color:os,paddingRight:80,...F.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(dn)}`})]}),(0,d.jsx)(Zt.Elements,{stripe:Gn,options:Ja,children:(0,d.jsx)(Os,{method:dn,sessionId:e,nonce:t,email:ne.email,billingName:[ne.firstName,ne.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:tt,billingApiUrl:Ct,onTokenizedBody:Ln,onErrorChange:qe,onDecline:p,onCancel:q,runBeforeButtonClick:hr,onButtonClick:ce,isProcessing:G,submitButtonColor:yo,submitButtonBorderRadius:Xt,submitButtonStyle:F.submitButton,errorText:Pt})},dn)]})})]})]})}return Ml&&dn&&Ja&&Gn&&K?(0,d.jsxs)("form",{onSubmit:es,className:I,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Zo,{}),re&&(0,d.jsx)(zn,{status:re,errorMessage:Pt,authorized:dr}),(0,d.jsx)("div",{style:{...Bo?{animation:Bo}:{},...ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:ns,borderRadius:ss,...fa,padding:is},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:q,style:{display:"inline-flex",alignItems:"center",gap:rs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:F.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...F.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",...F.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)(Lo,{content:Re})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:F.titleFontSize??"1.05rem",color:os,paddingRight:80,...F.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(dn)}`})]}),(0,d.jsx)(Zt.Elements,{stripe:Gn,options:Ja,children:(0,d.jsx)(Os,{method:dn,sessionId:e,nonce:t,email:ne.email,billingName:[ne.firstName,ne.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:tt,billingApiUrl:Ct,onTokenizedBody:Ln,onErrorChange:qe,onDecline:p,onCancel:q,runBeforeButtonClick:hr,onButtonClick:ce,isProcessing:G,submitButtonColor:yo,submitButtonBorderRadius:Xt,submitButtonStyle:F.submitButton,errorText:Pt})},dn)]})})]}):(0,d.jsxs)("form",{onSubmit:es,className:I,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Zo,{}),re&&(0,d.jsx)(zn,{status:re,errorMessage:Pt,authorized:dr}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Tl("flopay-direct-paypal-gate-debug-default"),Al("flopay-stripe-gate-debug-default"),sa&&ht&&(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)(Ca.Provider,{value:h,children:(0,d.jsx)(wa,{sessionId:e,nonce:t,billingApiUrl:Ct,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:tt,clientId:ht.clientId,environment:ht.environment,currency:vt.toUpperCase(),isSubscription:Tt,providerObjectType:de,approvalPresentation:Ha==="popup"?void 0:Ha,onTokenizedBody:Ln,onComplete:i,onErrorChange:qe,onDecline:p,onTechnicalFailure:Io,onButtonClick:ce,runBeforeButtonClick:hr,isProcessing:G,onLoadStateChange:Ji,onInitializationStateChange:Zi,session:x,existingOrderId:m?.orderId,debug:Z},m?.orderId??"fresh")})]}),ca&&(0,d.jsx)(Zt.Elements,{stripe:la,options:el,children:(0,d.jsx)(Rc,{sessionId:e,nonce:t,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:tt,billingApiUrl:Ct,onTokenizedBody:Ln,onErrorChange:qe,isProcessing:G,onButtonClick:ce,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:hr,onLoadStateChange:sl,placeholderBorderRadius:mo,popupCapabilityOwner:h,externalTelemetryContext:gl,presentationMode:To})}),Mo&&(0,d.jsx)(Zt.Elements,{stripe:Gn,options:Qs,children:(0,d.jsx)(Ec,{sessionId:e,nonce:t,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:tt,billingApiUrl:Ct,intentKind:$e>0?"payment":"setup",expressMethods:Ao,onTokenizedBody:Ln,onErrorChange:qe,onButtonClick:ce,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:hr,onLoadStateChange:cl,placeholderBorderRadius:mo,popupCapabilityOwner:h,externalTelemetryContext:ve})}),ua&&(0,d.jsx)(Ic,{sessionId:e,nonce:t,email:ne.email,billingName:[ne.firstName,ne.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Ct,paymentElementMethods:$a,stripeInstance:Gn,paymentElementBaseOptions:Xi,futureUseSession:B,onTokenizedBody:Ln,onErrorChange:qe,onButtonClick:ce,onDecline:p,runBeforeButtonClick:hr,onLoadStateChange:dl,isProcessing:G,submitButtonColor:yo,submitButtonBorderRadius:Xt,submitButtonStyle:F.submitButton,themeId:De,onExpandApm:L,expandedApmMethod:dn,buttonAppearance:{backgroundColor:F.cardButton?.backgroundColor,borderColor:F.cardInputBorder,textColor:F.cardButton?.color,borderRadius:mo}})]}),v&&(Pu||bu||vu)&&(0,d.jsx)(Ri,{label:"or pay with card"}),v&&Il]})}var O=require("react/jsx-runtime"),ta=44,Ks="flopay_checkout_saved_payment_resume",Di=new Map,Fi=new Map;function Oc(e,t){t.settled&&t.consumers===0&&Di.get(e)===t&&Di.delete(e)}function cp(e,t,n){let r=Fi.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Fi.set(e,a);let i=()=>{Fi.get(e)===a&&Fi.delete(e)};return o.then(i,i),o}function La(e){return new Promise(t=>setTimeout(t,e))}function Bi(e,t,n){let r=ii({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:ot.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Na(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Vs(e,t,n,r,o,a){let i=Bi(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),Na(i)}function Lc(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 Nc(e,t,n,r,o){let a=(0,ot.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:n,attempt:o,statusClass:a.statusClass}),t instanceof ot.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof ot.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):a.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...a,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function Vc(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 js(e){return!e||e.data.stripe?.publishableKey?!1:!!Vc(e)?.clientId}var up={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function dp(e){return new Xr.FloPay(up,{publishableKey:"provider_unavailable",...e})}async function $s(e,t){let{publishableKey:n,paypalPublishableKey:r}=_s(e);return{...await Es({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Gs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function pp(){if(!Gs())return null;try{let e=window.sessionStorage.getItem(Ks);return e?JSON.parse(e):null}catch{return null}}function Uc(e){if(Gs())try{window.sessionStorage.setItem(Ks,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ws(){if(Gs())try{window.sessionStorage.removeItem(Ks)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function mp(){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 zc(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 Hs(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function yp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function qc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function fp(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 Oi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:i,loading:c,error:p,onComplete:u,onError:g,onInstrument:b,onDecline:T,onCountryChange:I,onZipChange:S,showPayPal:A=!0,showStripe:_=!0,walletPresentation:P="auto",enabledPaymentMethods:w,showApplePay:K=!0,showGooglePay:k=!0,debug:ge=!1,layout:z,theme:X,buttonsTheme:Se,buttonsStyles:ae,cardButtonContent:De,cardBackButtonContent:Ze,cardTitleContent:le,showSecurityFooter:Ee,onButtonClick:We,onBeforeButtonClick:Re,enableAVS:Ie,cardFieldOrder:_e,cardPreFormSlot:ce,avsLayout:ue,submitLabel:Pe,className:Ae,initialErrorMessage:J=null,initialPayPalOrderId:ee,children:he,checkoutMode:U,confirmLabel:we,renderConfirmButton:ie,onSessionCompleted:Te}){let te=(0,ot.resolveBillingApiUrl)(r),it=(0,R.useMemo)(()=>(0,ot.resolveTheme)(X),[X]),He=a??it?.appearance,je=n?"embedded_checkout":"standard_checkout",at=Hs(he,z),[Ke,st]=(0,R.useState)(null),[$e,vt]=(0,R.useState)(null),Lt=(0,R.useRef)(null),ht=(0,R.useRef)(null),Tt=(0,R.useRef)(0),[V,be]=(0,R.useState)(null),Qe=(0,R.useRef)(null),[Z,Ne]=(0,R.useState)(null),bt=(0,R.useMemo)(()=>n?Ho(n):"",[n]),Ye=n?`create:${bt}`:`session:${e??""}`,_t=qc(Z),j=(0,R.useRef)(new Set),h=(0,R.useRef)(Ye),C=(0,R.useRef)(Ye);vo(()=>{C.current=Ye,h.current!==Ye&&(h.current=Ye,j.current.clear())},[Ye]);let Y=(0,R.useCallback)(L=>{if(C.current===Ye){if(gs.has(L.name)){if(j.current.has(L.name))return;j.current.add(L.name)}Je(()=>b?.(L))}},[Ye,b]),H=jo(Y,Ye),ve=(0,R.useRef)(!1),x=(0,R.useCallback)(L=>{if(ve.current)return;let q=L.gateway||!_t?L:{...L,gateway:_t};Y(q)},[Y,_t]);(0,R.useEffect)(()=>{H({class:"lifecycle",name:"checkout.mount"})},[H]);let[B,de]=(0,R.useState)(e??""),D=e??B,Me=n?"":D,[lt,yt]=(0,R.useState)(!0),[Ct,Be]=(0,R.useState)(null),[Tn,Vn]=(0,R.useState)(0),[gn,jt]=(0,R.useState)("full"),[jn,$n]=(0,R.useState)(!1),[vn,Dt]=(0,R.useState)(J),[dt,rt]=(0,R.useState)(null),[An,Mt]=(0,R.useState)(null),[Wn,hn]=(0,R.useState)(!1),[$t,en]=(0,R.useState)(void 0),[cr,Qn]=(0,R.useState)(""),[tn,xt]=(0,R.useState)(!1),[nn,sn]=(0,R.useState)(!1),[Nt,cn]=(0,R.useState)(!1),zt=(0,R.useRef)(null),ln=(0,R.useRef)(0),Ut=(0,R.useRef)(void 0),[me,ur]=(0,R.useState)("loading"),[dr,pr]=(0,R.useState)(0),rn=(0,R.useRef)(!1),Mn=(0,R.useRef)(!1),wn=(0,R.useRef)(!1),Oe=(0,R.useRef)(null),mt=(0,R.useRef)(null),v=(0,R.useMemo)(()=>({checkoutMode:U??gn,layout:yp(he,z)}),[U,he,gn,z]),et=(0,R.useRef)(u);et.current=u;let pe=(0,R.useRef)(g);pe.current=g;let Cn=(0,R.useRef)(T);Cn.current=T;let Hn=(0,R.useCallback)(L=>fi(Oe,async q=>{try{return await L(q)}catch(re){throw q.aborted?so(re):re}}),[]);(0,R.useEffect)(()=>()=>{Oe.current?.abort(),Oe.current=null},[]);let Gt=(0,R.useCallback)((L,q)=>{Lt.current=L,vt(L),Qe.current=q,be(q)},[]),xn=(0,R.useCallback)(()=>{let L=ht.current;L&&(ht.current=null,L.destroy())},[]);(0,R.useEffect)(()=>{yn($e)?.setCheckoutContext(v),V&&V!==$e&&yn(V)?.setCheckoutContext(v)},[$e,V,v]);let ft=(0,R.useRef)(Te);ft.current=Te;let mr=(0,R.useCallback)(L=>{ur(L),!(L!=="exhausted"||wn.current)&&(wn.current=!0,pe.current?.(new ot.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),uo=(0,R.useCallback)(()=>{ur("retrying"),pr(L=>L+1)},[]);(0,R.useEffect)(()=>{ur("loading"),pr(0),wn.current=!1},[D]),(0,R.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:ot.SDK_VERSION,checkout_type:je,checkout_layout:at,billing_api_url:te})},[at,je,te]);let Ft=(0,R.useMemo)(()=>n?Ho(n,!0):"",[n]),Fn=(0,R.useMemo)(()=>cr===Ft?$t:void 0,[$t,cr,Ft]),wr=(0,R.useMemo)(()=>n?ds(n,Fn):void 0,[n,Fn]),er=U??wr?.checkoutMode??"full",Yt=(0,R.useMemo)(()=>wr?{...wr,checkoutMode:er}:void 0,[wr,er]);(0,R.useEffect)(()=>{en(void 0),Qn(Ft),Ut.current=void 0,zt.current=null,cn(!1)},[Ft]),(0,R.useEffect)(()=>{Dt(J)},[J]);let yr=(0,R.useCallback)((L,q,re)=>{Je(()=>{Cn.current?.(mn(L,q,re))})},[]),Bn=(0,R.useCallback)(async(L,q)=>{Dt(null),Mt(null),hn(!1),rt("processing");let re=q?.sessionId??L.id,$=L.clientSecret||t,gt=qc(L),Et=Lt.current??Qe.current,se=yn(Et),Xe=Et?null:Bi(te,o,v),Q={log:Le=>{se?se.log(Le):Xe?.log(Le)},error:Le=>{se?se.error(Le):Xe?.error(Le)},terminal:Le=>{se?se.terminal(Le):Xe?.terminal(Le)},performance:Le=>{se?se.performance(Le):Xe?.performance(Le)},now:()=>se?.now()??Xe?.now()??0,elapsed:Le=>se?.elapsed(Le)??Math.max(0,(Xe?.now()??Le)-Le)},f=Q.now(),m=!!(q?.initialAutoProcessingError||q?.initialAutoProcessingPending),N=!1,W,Ce=()=>{N||(N=!0,m=!0,W=Q.now(),Q.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},xe=!1,tt=()=>{xe||(xe=!0,Q.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),Q.performance({stage:"processing",durationMs:Q.elapsed(f),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),W!==void 0&&Q.performance({stage:"recovery",durationMs:Q.elapsed(W),durationMode:"machine",paymentMethodCategory:"saved"}))};Q.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ve.current=!0;try{Q.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ve.current=!1}H({class:"lifecycle",name:"payment.processing.started",provider:gt}),m&&Ce();let Pt;try{let Le=ac(q?.initialAutoProcessingError),F=q?.initialAutoProcessingError?.type==="3ds_required"&&!q.initialAutoProcessingError.threeDSecureToken&&q.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:q.initialAutoProcessingError.nextActionRedirectUrl}:null,St,Fe=ke=>(Ce(),Hn(G=>Go(ke,{billingApiUrl:te,sessionId:re,nonce:$,session:L,signal:G})));if(F)St=await Fe(F);else if(Le)Ce(),Le.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Uc({sessionId:re,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey}),St=await Hn(ke=>hi(Le,{flopay:Lt.current,paypalFlopay:Qe.current,attempt3DS:q?.attempt3DS,billingApiUrl:te,sessionId:re,session:L,telemetry:!1,signal:ke})),Le.type==="paypal_redirect_required"&&Ws();else if(q?.initialAutoProcessingPending){let ke=q.initialAutoProcessingPending,G=new Xr.PaymentAPI(te,{telemetry:!1}),ye=await Hn(Ge=>G.waitForCheckoutSessionCompletion(ke.sessionId,{initialDelayMs:ke.retryAfterMs,nonce:$,statusUrl:ke.statusUrl,signal:Ge})),ne=no(ye,L),wt=ye.autoProcessingError?.type==="3ds_required"&&ye.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ye.autoProcessingError.nextActionRedirectUrl}:null;if(wt)St=await Fe(wt);else{if(!$r(ne))throw Uo(ne);St=jr(ne,re)}}else{if(q?.initialAutoProcessingError)throw xr(q.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:q.initialAutoProcessingError.checkoutMethod});if(q?.fromCreateSession)return q?.fallbackToFull&&(jt("full"),zc("full")),!1;{let ke=await Yo({billingApiUrl:te,sessionId:re,session:L,nonce:$,telemetry:!1});ke.type==="success"?St=ke.result:ke.type==="next_action_required"?St=await Fe(ke):(Ce(),ke.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Uc({sessionId:re,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey}),St=await Hn(G=>hi(ke,{flopay:Lt.current,paypalFlopay:Qe.current,attempt3DS:q?.attempt3DS,billingApiUrl:te,sessionId:re,session:L,telemetry:!1,signal:G})),ke.type==="paypal_redirect_required"&&Ws())}}re&&Ko(re),tt(),m&&(Q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),Q.terminal({outcome:St.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),hn(St.status==="authorized"),rt("success"),await La(600),Pt=()=>et.current?.(St)}catch(Le){let F=eo(Ia(Le),re);if(F.code==="three_ds_aborted")return!1;let St=F.checkoutMethod??Ea;Dt(F.message),Mt(F.message),hn(!1),q?.fallbackToFull&&(Q.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),jt("full"),zc("full")),tt();let Fe=F.statusCode===void 0?void 0:(0,ot.telemetryStatusClass)(F.statusCode,"unknown"),ke=Fe==="4xx"?{requestCategory:"process_payment",statusClass:Fe}:{},G=Fe===void 0||Fe==="4xx";if(G&&(F.telemetryOutcome==="payment_declined"||!!(F.declineCode||F.code?.toLowerCase().includes("declin"))))Q.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...ke});else if(G&&(F.telemetryOutcome==="validation_rejected"||F.type==="validation_error"))Q.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...ke});else{let wt=(0,ot.classifyTelemetryFailure)(Le,m?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Ge=F.telemetryRequestCategory??"process_payment";ve.current=!0;try{Q.error({...wt,...F.telemetryFailureCategory?{failureCategory:F.telemetryFailureCategory}:{},stage:m?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Ge})}finally{ve.current=!1}H({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Ge,provider:gt})}return Je(()=>pe.current?.(F)),yr(St,F,{code:F.code,declineCode:F.declineCode}),rt("error"),await Promise.allSettled([La(400),q?.ensureProvidersReady?q.ensureProvidersReady():Promise.resolve()]),m&&(Q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{tt(),Xe&&Na(Xe),rt(null),Mt(null)}return Je(Pt),!0},[yr,H,t,te,Hn,o,v]);(0,R.useEffect)(()=>{if(typeof window>"u"||Mn.current)return;let L=new URLSearchParams(window.location.search),q=L.get("payment_intent_client_secret");if(!q)return;let re=pp();re&&(Mn.current=!0,(async()=>{let $,gt=0;Dt(null),Mt(null),rt("processing"),$n(!0);try{if(L.get("redirect_status")==="failed")throw Object.assign(new ot.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Et,paypalFlopay:se}=await Es({publishableKey:re.publishableKey,paypalPublishableKey:re.paypalPublishableKey,billingApiUrl:te,locale:i,telemetry:o});$=yn(se??Et),$?.setCheckoutContext(v),gt=$?.now()??0,$?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),$?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Xe=(se??Et)?.getRawProvider();if(!Xe)throw Object.assign(new ot.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:Q,error:f}=await Xe.retrievePaymentIntent(q);if(f)throw Object.assign(new ot.FloPayError(f.message??"Failed to retrieve PayPal payment status.","api_error",{code:f.code}),{checkoutMethod:"paypal"});let m=zl(Q?.status);if(!Q||m==="failed")throw Object.assign(new ot.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,W=m;if(re.sessionId){let tt=(await new Xr.PaymentAPI(te,{telemetry:!1}).getUnifiedCheckoutSession(re.sessionId)).data.session;if(tt&&tt.status!=="complete"){let Pt=await Yo({billingApiUrl:te,sessionId:re.sessionId,session:tt,telemetry:!1,tokenizedData:{id:N??Q.id,type:"card",threeDSecureActionResultTokenId:Q.id,isPaypal:!0}});if(Pt.type!=="success")throw Object.assign(new ot.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});W=Pt.result.status}}re.sessionId&&Ko(re.sessionId),$?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),$?.performance({stage:"redirect_resume",durationMs:$.elapsed(gt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),$?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),rt("success"),await La(600),Je(()=>et.current?.({status:W,paymentIntentId:Q.id,paymentMethodId:N,checkoutMethod:"paypal"}))}catch(Et){let se=eo(Ia(Et),re.sessionId),Xe=se.checkoutMethod??"paypal",Q=!!(se.declineCode||se.code?.toLowerCase().includes("declin"));if($)$.performance({stage:"redirect_resume",durationMs:$.elapsed(gt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Q?$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):$.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(Q){let f=Bi(te,o,v);f.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Na(f)}else Vs(te,o,v,"REDIRECT_RESUME_FAILED","redirect_resume");Dt(se.message),Mt(se.message),Je(()=>pe.current?.(se)),yr(Xe,se,{code:se.code,declineCode:se.declineCode}),rt("error"),await La(400)}finally{Ws(),mp(),rt(null),Mt(null),$n(!1)}})())},[yr,i,te,o,v]);let Or=(0,R.useRef)(null),Dn=(0,R.useMemo)(()=>Yt?Ho(Yt):"",[Yt]),kr=(0,R.useRef)(Yt);kr.current=Yt,(0,R.useEffect)(()=>{de(e??"")},[e]),(0,R.useEffect)(()=>{rn.current=!1,Dt(J),Mt(null),hn(!1),rt(null)},[Dn,J,e]);async function Rr(L,q,re){let $=Bi(te,o,v),gt=new Xr.PaymentAPI(te,{telemetry:!1}),Et=!1;try{let se=L.idempotencyKey===void 0?void 0:(0,ot.resolveIdempotencyKey)(L.idempotencyKey),Xe=Ps(q,re),Q=vs(q,re);Xe?.canonicalIdentity===re&&Q&&Q.canonicalIdentity===void 0&&(mi(q,re,Q.idempotencyKey),Q={...Q,canonicalIdentity:re});let f=se??(Q?.canonicalIdentity===re?Q.idempotencyKey:void 0),m,N=!1;$.log({name:Xe?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let W=Xe?.sid??null,Ce=null,xe,tt,Pt=!1;if(W)try{Ce=await gt.getUnifiedCheckoutSession(W,Xe?.nonce),Xe&&Xe.canonicalIdentity===void 0&&(tc(Ce.data.session,L)?(pi(q,re,W,Xe.nonce??Ce.data.session?.clientSecret),Q&&Q.canonicalIdentity===void 0&&(mi(q,re,Q.idempotencyKey),f??(f=Q.idempotencyKey))):(di(q,re),Q=null,f=se,W=null,Ce=null));let F=Ce?.data.session?.status,St=Ce?.data.session,Fe=St?.clientSecret||Xe?.nonce;if(W&&St?.buyerIdentified===!1&&Fe&&(tt=No(gt,W,Fe,L.account)),W&&Ce&&F==="complete"){if(Cs(W))return{sid:W,result:Ce};di(q,re),W=null,Ce=null,N=!0}}catch{$.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Xe?.canonicalIdentity===void 0?(di(q,re),f=se):ui(q,re),W=null}if(!W){!se&&(N||!f)&&(f=(0,ot.resolveIdempotencyKey)(),m=f),f&&mi(q,re,f);let F=$.now(),St=0;$.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Fe={...L,idempotencyKey:f,avsCheck:!!Ie,avsConfig:typeof Ie=="object"?Ie:void 0,checkoutType:"embedded_checkout",checkoutLayout:Hs(he,z)};Object.defineProperty(Fe,Xr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ye=>{St=Math.max(St,ye)}}});let ke=()=>{Lc($,"session_create",F,St)},G=ye=>{Nc($,ye,"session_create",F,St)&&H({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,ot.isDetachedSessionEligible)(Fe)){let ye=await gt.createDetachedSession(Fe);ye.claimed.catch(()=>{}),Ce=ye.shell,W=ye.sessionId,tt=ye.claim;let ne=$.now();$.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),xe=ye.claimed.then(wt=>{let Ge=wt.data.session?.id??ye.sessionId;return Ge&&pi(q,re,Ge,wt.data.session?.clientSecret??ye.nonce),Lc($,"session_claim",ne),ke(),wt},wt=>{throw ui(q,re),Nc($,wt,"session_claim",ne,0)&&H({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),wt}).finally(()=>Na($)),xe.catch(()=>{}),Et=!0,$.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),$.performance({stage:"session_shell",durationMs:$.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:St,statusClass:"2xx",paymentMethodCategory:"card"})}else Ce=await gt.createAndFetchSession(Fe),ke()}catch(ye){throw G(ye),ye}W=Ce.data.session?.id??W??"",W&&!xe&&pi(q,re,W,Ce.data.session?.clientSecret)}let Le=Ce?.data.session;return!tt&&W&&Le?.buyerIdentified===!1&&Le.clientSecret&&(tt=No(gt,W,Le.clientSecret,L.account)),{sid:W??"",result:Ce,sdkGeneratedIdempotencyKey:m,...xe?{claimed:xe}:{},...tt?{claim:tt}:{},...Pt?{claimRequiresIdentity:!0}:{}}}finally{Et||Na($)}}let Lr=(0,R.useRef)(Rr);vo(()=>{Lr.current=Rr},[Rr]);let Kn=(0,R.useCallback)(async(L,q)=>{let re=kr.current;if(!re)throw new ot.FloPayError("createSession is required to bootstrap checkout.","validation_error");let $=ds(re,L),gt=Ho($),Et=ec($),se=Di.get(gt);if(!se){let f={canonicalIdentity:gt,promise:Lr.current($,Et,gt),consumers:0,settled:!1};se=f,Di.set(gt,f);let m=()=>{f.settled=!0,Oc(gt,f)};f.promise.then(m,m)}se.consumers+=1;let Xe=!1,Q=()=>{Xe||(Xe=!0,se.consumers-=1,Oc(gt,se))};q?.(Q);try{let f=await se.promise;Or.current=gt,L&&(Qn(Ft),en(Le=>Ll(Le,L)));let{sid:m,result:N,claimed:W,claim:Ce,claimRequiresIdentity:xe}=f;if(Ut.current=Ce,cn(xe===!0),st(N),N.data.session&&Ne(N.data.session),m&&de(m),W){ln.current+=1;let Le=ln.current;zt.current=W,sn(!0),W.then(F=>{ln.current===Le&&(zt.current===W&&(zt.current=null),st(F),F.data.session&&Ne(F.data.session),sn(!1),cn(!1))},F=>{ln.current===Le&&(zt.current===W&&(zt.current=null),sn(!1),cn(!1),Be(F instanceof ot.FloPayError?F:new ot.FloPayError(F instanceof Error?F.message:"Failed to create session","api_error")))})}else ln.current+=1,zt.current=null,sn(!1),cn(!1);let{flopay:tt,paypalFlopay:Pt}=await $s(N,{billingApiUrl:te,locale:i,telemetry:o});return Gt(tt,Pt),yt(!1),f}catch(f){throw Or.current===gt&&(Or.current=null),f}finally{q||Q()}},[Ft,Gt,i,te,o]),tr=(0,R.useRef)(Bn);tr.current=Bn;let Nr=(0,R.useRef)(Kn);Nr.current=Kn;let Ot=(0,R.useCallback)(async L=>{if(!fp(L)||tn)return{sessionId:B,session:Z};xt(!0);try{let q=await Kn(L);return{sessionId:q.sid,session:q.result.data.session??null}}finally{xt(!1)}},[Kn,tn,B,Z]),kn=(0,R.useCallback)(async L=>{let q=Ut.current;if(!q)return;let re=ln.current,$=await q(L);ln.current===re&&(st($),$.data.session&&Ne($.data.session))},[]),nr=(0,R.useCallback)(async()=>{await zt.current},[]),Ur=(0,R.useCallback)(async()=>(await nr(),{proceed:!0}),[nr]);(0,R.useEffect)(()=>{let L=!1,q,re=++Tt.current;xn(),Be(null),Vn(0);let $=()=>{L=!0,Tt.current===re&&(Tt.current+=1,xn())},gt=kr.current;if(Dn&>)return jt(er),yt(!1),Or.current===Dn?$:(Ne(Nl(gt,U)),(async()=>{let Xe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Q=er==="auto"&&!rn.current&&!Xe;Q&&(Dt(null),Mt(null),rt("processing"));try{let f=await Nr.current(void 0,Ce=>{q=Ce}),m=f.result.data.session??null;mt.current=_s(f.result);let N=js(f.result),W=Cs(f.sid||m?.id);if(!L&&Q&&m&&!N&&!W){rn.current=!0,await cp(Dn,f.sdkGeneratedIdempotencyKey,()=>tr.current(m,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:f.result.autoProcessingError,initialAutoProcessingPending:f.result.autoProcessingPending,autoProcessingAttempted:f.result.autoProcessingAttempted,sessionId:f.sid||m.id}));return}!L&&Q&&((N||W)&&(rn.current=!0),rt(null),Mt(null))}catch(f){if(L)return;let m=ei(f);if(Q&&m==="session_auto_completed"){rn.current=!0,rt("success"),await La(600),L||(Je(()=>{et.current?.({status:"succeeded"})}),rt(null),Mt(null));return}Q&&(rt(null),Mt(null));let N=f instanceof ot.FloPayError?f:new ot.FloPayError(f instanceof Error?f.message:"Failed to create session","api_error");Be(N)}finally{q?.(),q=void 0}})(),()=>{$(),q?.()});yt(!0);async function Et(){let Xe=!1,Q=null;try{let f=new Xr.PaymentAPI(te,{telemetry:!1}),m=await f.getUnifiedCheckoutSession(D,t);if(Q=m,L)return;st(m);let N=m.data.session??null;if(Ne(N),!N)throw new ot.FloPayError("No session data returned","api_error");let W=N.checkoutMode;if(W==="setup")throw new ot.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(N.status==="authorized"){yt(!1),Je(()=>{et.current?.(jr(N,D)),ft.current?.(N.successUrl??"")});return}if(N.status==="complete"){yt(!1),Je(()=>{ft.current?.(N.successUrl??"")});return}if(N.status==="expired")throw Qa(N);Xe=!0;let Ce=U??W??"full";jt(Ce),ln.current+=1;let xe=N.clientSecret||t;Ut.current=N.buyerIdentified===!1&&xe?No(f,D,xe,{...N.customer?.id?{userId:N.customer.id}:{}}):void 0,sn(!1),cn(!1);let tt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Pt=js(m);if(Ce==="auto"&&!rn.current&&!tt&&!Pt){rn.current=!0;let Le=se(m);try{if(await tr.current(N,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Le,sessionId:D||N.id}),L)return;await Le,L||yt(!1);return}catch{if(L)return;await Le,L||yt(!1);return}}await se(m),L||yt(!1)}catch(f){if(L)return;let m=Ol(f,Xe);if(Xe&&H({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),m){let{errorCode:W,stage:Ce,...xe}=m;Vs(te,o,v,W,Ce,xe)}if(m?.stage==="provider_load"&&(U??Q?.data.session?.checkoutMode??"full")==="full"&&Dl(Q,A,_)){let W=dp({billingApiUrl:te,locale:i,telemetry:o});ht.current=W,Gt(W,null),Vn(1),yt(!1);return}let N=f instanceof ot.FloPayError&&m?.stage!=="provider_load"?f:Bl();N!==f&&Je(()=>pe.current?.(N)),Be(N),yt(!1)}}async function se(Xe){let{flopay:Q,paypalFlopay:f,...m}=await $s(Xe,{billingApiUrl:te,locale:i,telemetry:o});mt.current={publishableKey:m.publishableKey,paypalPublishableKey:m.paypalPublishableKey},Gt(Q,f),Vn(0)}return Et(),$},[U,Dn,er,Me,t,A,_]);let zr=(0,R.useCallback)(async()=>{if(!Ke||Tn!==1)return;let L=Tt.current;Vn(2);try{let{flopay:q,paypalFlopay:re}=await $s(Ke,{billingApiUrl:te,locale:i,telemetry:o});if(Tt.current!==L)return;xn(),Gt(q,re),Vn(0)}catch(q){if(Tt.current!==L)return;let{errorCode:re,stage:$,...gt}=cs(q);Vs(te,o,v,re,$,gt)}},[xn,Gt,i,Tn,te,o,v,Ke]),ct=!!(D&&(Z?.clientSecret||t)),un=jn||!ct,dn=(0,R.useCallback)(async()=>{if(!(jn||!ct||!Z)){$n(!0),Dt(null);try{await Bn(Z,{attempt3DS:!0,fallbackToFull:!0,sessionId:D||Z.id})}finally{$n(!1)}}},[D,jn,ct,Bn,Z]),Rn=Vc(Ke,ee),po=js(Ke),_r=(0,R.useMemo)(()=>{if(!(!Ke||!Z||!Ke.data.stripe?.publishableKey))return{billingApiUrl:te}},[Ke,Z,te]),Zr=!!(n&&!he&&z==="buttons"&&Re&&er==="full"),_n=!!(D&&(Z?.vault?.html||Qr(Z))),pn=(0,R.useMemo)(()=>({session:Z,loading:lt,error:Ct,checkoutMode:gn,inlineSessionDraft:Yt,applyInlineSessionPatch:Zr?Ot:void 0,inlineSessionPatchProcessing:tn,claimPending:nn,claimRequiresIdentity:Nt,claimBuyerIdentity:kn,waitForDataAttachment:nr}),[Z,lt,Ct,gn,Yt,Zr,Ot,tn,nn,Nt,kn,nr]),qr=!!n&&z==="buttons"&&!po&&!_n&&(!$e||!_r),On=dt?(0,O.jsx)(zn,{status:dt,errorMessage:An,authorized:Wn}):null;if(lt&&!_n){if(c)return(0,O.jsxs)(O.Fragment,{children:[c,On]});if(z==="buttons"){let L=it?.buttonsLayout?.cardButton?.borderRadius??it?.appearance.variables?.borderRadius??8,q=re=>(0,O.jsx)("div",{style:{height:re,borderRadius:L,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:[A&&q(ta),_&&(K||k)&&q(ta),_&&q(ta),(0,O.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),On]})}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); } }"})]}),On]})}return Ct?p?(0,O.jsx)(Pr.Provider,{value:pn,children:p(Ct)}):(0,O.jsx)(Pr.Provider,{value:pn,children:(0,O.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ct.message})}):qr?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:pn,children:(0,O.jsx)(hp,{onButtonClick:We,showPayPal:A,showStripe:_,showApplePay:K,showGooglePay:k,theme:X,buttonsTheme:Se,buttonsStyles:ae,cardButtonContent:De,cardBackButtonContent:Ze,cardTitleContent:le})}),On]}):po&&Z&&Rn?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:pn,children:(0,O.jsxs)("div",{className:Ae,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[vn&&(0,O.jsx)($o,{icon:!1,children:vn}),me==="retrying"&&(0,O.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),me==="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:uo,children:"Retry PayPal"})]}),me!=="exhausted"&&(0,O.jsx)("div",{"aria-hidden":me==="retrying"?!0:void 0,style:me==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,O.jsx)(Ql,{sessionId:D,nonce:Z.clientSecret||void 0,billingApiUrl:te,email:Z.customer?.email||Yt?.account?.email,billingName:[Z.customer?.firstName,Z.customer?.lastName].filter(Boolean).join(" ")||[Yt?.account?.firstName,Yt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:kn,clientId:Rn.clientId,environment:Rn.environment,currency:(Z.currency??"usd").toUpperCase(),isSubscription:Z.mode==="subscription",providerObjectType:Rn.providerObjectType,approvalPresentation:Rn.approvalPresentation,existingOrderId:Rn.existingOrderId,onComplete:u,onErrorChange:Dt,onDecline:T,onButtonClick:We,runBeforeButtonClick:Ur,onInitializationStateChange:mr,allowAutomaticRetry:dr===0,session:Z,telemetry:o,telemetryContext:v,onInstrument:x,debug:ge},`${Ye}:paypal-init-${dr}`)})]})}),On]}):gn==="confirm"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:pn,children:(0,O.jsx)(Ra,{flopay:$e,paypalFlopay:V,options:_r??{billingApiUrl:te},onInstrument:x,children:(0,O.jsxs)("div",{className:Ae,children:[vn&&(0,O.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:vn}),ie?ie({onConfirm:dn,isProcessing:un}):(0,O.jsx)("button",{type:"button",onClick:dn,disabled:un,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:un?"not-allowed":"pointer",opacity:un?.6:1},children:jn?"Processing...":we??"Confirm Purchase"})]})},Ye)}),On]}):(!$e||!_r)&&!(_n&&gn==="full")?(0,O.jsx)(O.Fragment,{children:On}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:pn,children:(0,O.jsxs)(Ra,{flopay:$e,paypalFlopay:V,options:_r??{billingApiUrl:te},onInstrument:x,children:[Tn===1&&(0,O.jsx)("button",{type:"button",onClick:zr,children:"Retry payment methods"}),he?(0,O.jsxs)(O.Fragment,{children:[vn&&(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:vn}),(0,O.jsx)(gp,{sessionId:D,nonce:Z?.clientSecret||void 0,billingApiUrl:te,session:Z,submitLabel:Pe,walletPresentation:P,children:he})]}):(0,O.jsx)(xi,{sessionId:D,nonce:Z?.clientSecret||void 0,telemetry:o,email:Z?.customer?.email||Yt?.account?.email,userId:Z?.customer?.id||Yt?.account?.userId,firstName:Z?.customer?.firstName||Yt?.account?.firstName,lastName:Z?.customer?.lastName||Yt?.account?.lastName,totalAmount:Z?Math.round((0,ot.buildCheckoutDisplayData)(Z).total*100):0,currency:Z?.currency?.toLowerCase()??"usd",onComplete:u,onError:g,onDecline:T,error:vn,onErrorChange:Dt,showPayPal:A,showStripe:_,walletPresentation:P,enabledPaymentMethods:Tn?[]:w??Ke?.data.stripe?.enabledPaymentMethods??Z?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ke?.data.stripe?.enabledPaymentMethodCountries,showApplePay:K,showGooglePay:k,layout:z,theme:X,buttonsTheme:Se,buttonsStyles:ae,appearance:He,cardButtonContent:De,cardBackButtonContent:Ze,cardTitleContent:le,onButtonClick:We,onBeforeButtonClick:Re,onBuyerIdentityReady:kn,enableAVS:Ie,..._e?{cardFieldOrder:_e}:{},...ce?{cardPreFormSlot:ce}:{},avsLayout:ue,country:Z?.customer?.country,city:Z?.customer?.city,state:Z?.customer?.state,onCountryChange:I,onZipChange:S,avsCheck:!!Ie,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Hs(he,z),className:Ae,submitLabel:Pe,directPaypal:Rn,isSubscription:Z?.mode==="subscription",session:Z,dataAttachmentPending:nn,dataAttachmentRequiresIdentity:Nt,debug:ge})]},Ye)}),On]})}function gp({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:a,children:i}){return(0,O.jsx)(O.Fragment,{children:R.default.Children.map(i,c=>{if(!R.default.isValidElement(c))return c;let p=c.props,u={};return p.sessionId||(u.sessionId=e),!p.nonce&&t&&(u.nonce=t),p.billingApiUrl||(u.billingApiUrl=n),p.submitLabel===void 0&&o!==void 0&&(u.submitLabel=o),p.walletPresentation===void 0&&(u.walletPresentation=a),r?.customer&&(p.email||(u.email=r.customer.email),p.userId||(u.userId=r.customer.id),p.firstName||(u.firstName=r.customer.firstName),p.lastName||(u.lastName=r.customer.lastName)),Object.keys(u).length===0?c:R.default.cloneElement(c,u)})})}function hp({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:i,buttonsStyles:c,cardButtonContent:p,cardBackButtonContent:u,cardTitleContent:g}){let[b,T]=(0,R.useState)(!1),I=(0,R.useMemo)(()=>(0,ot.resolveTheme)(a),[a]),S=(0,R.useMemo)(()=>{let w=I?.buttonsLayout??(0,ot.resolveButtonsLayoutTheme)(i);return c?{...w,...c,cardButton:{...w.cardButton,...c.cardButton},cardFormContainer:{...w.cardFormContainer,...c.cardFormContainer},backButton:{...w.backButton,...c.backButton},backButtonIcon:{...w.backButtonIcon,...c.backButtonIcon},submitButton:{...w.submitButton,...c.submitButton},title:{...w.title,...c.title}}:w},[I,i,c]),A=I?.buttonsLayout?.cardButton?.borderRadius??I?.appearance.variables?.borderRadius??8,_=w=>(0,O.jsx)("div",{style:{height:w,borderRadius:A,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),P=p===void 0?{boxSizing:"border-box",height:ta,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let w=S.cardInputBorder??"#e5e7eb",K=S.cardInputBackground??"white",k=Do(u),ge=Do(g);return(0,O.jsxs)("div",{style:{backgroundColor:S.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...S.cardFormContainer},children:[(0,O.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,O.jsxs)("button",{type:"button",onClick:()=>T(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:k?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...S.backButton},children:[(0,O.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...S.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)(Lo,{content:u})]}),ge?(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,...S.title},children:(0,O.jsx)(ha,{content:g})})]}),(0,O.jsx)("div",{style:{backgroundColor:K,border:`1px solid ${w}`,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:K,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,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:K,borderTop:"none",borderRight:`1px solid ${w}`,borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,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:K,border:`1px solid ${w}`,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",...S.submitButton,opacity:.5}}),(0,O.jsx)("style",{children:`
|
|
38
|
+
`}),ya&&mo&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:v?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:Me,style:{display:"inline-flex",alignItems:"center",gap:is?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,d.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,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)(Uo,{content:Te})]}),Il?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:E.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...E.title},children:(0,d.jsx)(Pa,{content:Fe})})]}),!ya&&!Il&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ss,order:v?-3:0,...E.title},children:(0,d.jsx)(Pa,{content:Fe})}),v&&Q&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:Q}),v&&Qr&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:Bo,border:`1px solid ${or(Xa)}`,borderRadius:Zt,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:nn,onChange:l=>{Ot("email"),un.current=l.target.value,ur(l.target.value)},onPointerDown:()=>Ot("email"),onKeyDown:()=>Ot("email"),onBlur:()=>{In("email")&&_r(!0),Eo||Xi()},disabled:ae,required:!0,"aria-invalid":Xa||void 0,"aria-describedby":Xa?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...ls}})}),Xa&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ga,children:Hi.empty?"Email address is required":"Enter a valid email address"})]}),ue&&(0,d.jsx)("div",{style:{order:v?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let l=$t,T=(ie=!1)=>({backgroundColor:Bo,border:`1px solid ${or(ie)}`,borderRadius:Zt,marginTop:"0.5rem",padding:"10px"}),ne=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ls}),ze=(0,f.getStateOptions)(l);return(0,d.jsxs)(d.Fragment,{children:[(0,f.isAVSFieldVisible)(ue.address_line_1,l)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:T(Ht("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:Dt,onChange:ie=>{Ot("line1"),Ut.current.addressLine1=!0,cn.current=ie.target.value,dt(ie.target.value)},onPointerDown:()=>Ot("line1"),onKeyDown:()=>Ot("line1"),onBlur:()=>rr("line1"),disabled:ae,required:!0,"aria-invalid":Ht("line1")||void 0,"aria-describedby":Ht("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:ne()})}),Ht("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ga,children:"Street address is required"})]}),(0,f.isAVSFieldVisible)(ue.address_line_2,l)&&(0,d.jsx)("div",{style:T(),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:ie=>{Ut.current.addressLine2=!0,Nt.current=ie.target.value,Fn(ie.target.value)},disabled:ae,"data-testid":"flopay-address-line2",style:ne()})}),((0,f.isAVSFieldVisible)(ue.city,l)||(0,f.isAVSFieldVisible)(ue.state,l))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,f.isAVSFieldVisible)(ue.city,l)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Bo,borderTop:`1px solid ${or(Ht("city"))}`,borderRight:`1px solid ${or(Ht("city"))}`,borderBottom:`1px solid ${or(Ht("city"))}`,borderLeft:`1px solid ${or(Ht("city"))}`,padding:"10px",borderTopLeftRadius:Zt,borderBottomLeftRadius:Zt,...(0,f.isAVSFieldVisible)(ue.state,l)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Zt}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Tt,onChange:ie=>{Ot("city"),Ut.current.city=!0,dn.current=ie.target.value,Kn(ie.target.value)},onPointerDown:()=>Ot("city"),onKeyDown:()=>Ot("city"),onBlur:()=>rr("city"),disabled:ae,required:!0,"aria-invalid":Ht("city")||void 0,"aria-describedby":Ht("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:ne()})}),(0,f.isAVSFieldVisible)(ue.state,l)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Bo,borderTop:`1px solid ${or(Ht("state"))}`,borderRight:`1px solid ${or(Ht("state"))}`,borderBottom:`1px solid ${or(Ht("state"))}`,borderLeft:`1px solid ${or(Ht("state"))}`,padding:"10px",borderTopRightRadius:Zt,borderBottomRightRadius:Zt,...(0,f.isAVSFieldVisible)(ue.city,l)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${or(Ht("state")||Ht("city"))}`}:{borderRadius:Zt}},children:ze?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Pn,onChange:ie=>{Ot("state"),Ut.current.state=!0,zt.current=ie.target.value,Wt(ie.target.value)},onPointerDown:()=>Ot("state"),onKeyDown:()=>Ot("state"),onBlur:()=>rr("state"),disabled:ae,autoComplete:"billing address-level1",required:!0,"aria-invalid":Ht("state")||void 0,"aria-describedby":Ht("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...ne(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,f.getStateLabel)(l)}),ze.map(ie=>(0,d.jsx)("option",{value:ie.code,children:ie.name},ie.code))]}):(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,f.getStateLabel)(l),autoComplete:"billing address-level1",value:Pn,onChange:ie=>{Ot("state"),Ut.current.state=!0,zt.current=ie.target.value,Wt(ie.target.value)},onPointerDown:()=>Ot("state"),onKeyDown:()=>Ot("state"),onBlur:()=>rr("state"),disabled:ae,required:!0,"aria-invalid":Ht("state")||void 0,"aria-describedby":Ht("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:ne()})})]}),Ht("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ga,children:"City is required"}),Ht("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ga,children:[(0,f.getStateLabel)(l)," is required"]}),((0,f.isAVSFieldVisible)(ue.country,l)||(0,f.isAVSFieldVisible)(ue.postal_code,l))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:Pe==="column"?"column":"row",gap:Pe==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,f.isAVSFieldVisible)(ue.country,l)&&(0,d.jsx)("div",{style:{flex:Pe==="row"?1:void 0,backgroundColor:Bo,borderTop:`1px solid ${fa}`,borderRight:`1px solid ${fa}`,borderBottom:`1px solid ${fa}`,borderLeft:`1px solid ${fa}`,padding:"10px",...Pe==="row"&&(0,f.isAVSFieldVisible)(ue.postal_code,l)?{borderRadius:"0",borderTopLeftRadius:Zt,borderBottomLeftRadius:Zt,borderRight:"none"}:{borderRadius:Zt}},children:(0,d.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:$t,onChange:ie=>{Ut.current.country=!0,on.current=ie.target.value,Wn(ie.target.value),He?.(ie.target.value),zt.current="",Wt("")},disabled:ae,autoComplete:"billing country","data-testid":"flopay-country",style:{...ne(),cursor:"pointer"},children:[$t===""?(0,d.jsx)("option",{value:"",children:"Select country"}):null,f.COUNTRY_OPTIONS.map(ie=>(0,d.jsxs)("option",{value:ie.code,children:[ie.flag," ",ie.name]},ie.code))]})}),(0,f.isAVSFieldVisible)(ue.postal_code,l)&&(0,d.jsx)("div",{style:{flex:Pe==="row"?1:void 0,backgroundColor:Bo,border:`1px solid ${Eu}`,padding:"10px",...Pe==="row"&&(0,f.isAVSFieldVisible)(ue.country,l)?{borderRadius:"0",borderTopRightRadius:Zt,borderBottomRightRadius:Zt}:{borderRadius:Zt}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,f.getPostalCodeLabel)($t),autoComplete:"billing postal-code",value:Hn,onChange:ie=>{Ot("zip"),Ut.current.zip=!0,At.current=ie.target.value,wn(ie.target.value),Ve?.(ie.target.value)},onPointerDown:()=>Ot("zip"),onKeyDown:()=>Ot("zip"),onBlur:()=>{In("zip")&&Ur(!0)},disabled:ae,required:On.required,"aria-invalid":Ja||void 0,"aria-describedby":Ja?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:ne()})})]}),Ja&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ga,children:On.empty?`${(0,f.getPostalCodeLabel)(l)} is required`:lp(l)})]})})()}),v&&xu,pe&&(0,d.jsx)(Ho,{margin:"0.75rem 0",styleOverride:E.errorBanner,children:pe})]}),Za={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"},Fl=l=>X?!C||!Mr?(0,d.jsx)("pre",{"data-testid":l,style:Za,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":l,style:Za,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${C}`,` directPaypalConfigured=${Mr}`,` inAppBrowserDetected=${String(Ka)}`,` shouldRenderDirectPayPal=${ca}`,` shouldRenderStripePayPal=${da}`,` hasPaypalStripeInstance=${!!el}`].join(`
|
|
39
|
+
`)}):null,Bl=l=>X?!G||!Xn?(0,d.jsx)("pre",{"data-testid":l,style:Za,children:"FloPay/Stripe-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":l,style:Za,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${G}`,` currency=${St}`,` amountInCents=${ia}`,` enabledPaymentMethods: ${JSON.stringify(ye??[])}`,` enabledPaymentMethodsProvided=${sa}`,` hasEnabledMethods=${ja}`,` expressMethods: ${JSON.stringify(Wa)}`,` walletExpressMethods: ${JSON.stringify(xo)}`,` paymentElementMethods: ${JSON.stringify(la)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ha)}`,` hasStripeInstance=${!!Xn}`,` shouldRenderWallets=${Fo}`,` shouldRenderPaymentElement=${pa}`].join(`
|
|
40
|
+
`)}):null,Dl=lt==="apm-expanding"||lt==="apm-form"||lt==="apm-collapsing",Oo;lt==="apm-expanding"?Oo=Rc:lt==="apm-collapsing"&&(Oo=_c);let Qa=mn?Uc(Qi,mn,B):null;if(te==="buttons"){let l=lt==="buttons"||lt==="expanding"||lt==="apm-expanding",T=lt==="expanding"||lt==="card"||lt==="collapsing",ne=We===void 0?{boxSizing:"border-box",height:Qo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ze;lt==="expanding"||lt==="apm-expanding"?ze=rp:(lt==="collapsing"||lt==="apm-collapsing")&&(ze=np);let ie;return lt==="expanding"?ie=Rc:lt==="collapsing"&&(ie=_c),(0,d.jsxs)("form",{onSubmit:rs,className:_,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ea,{}),ke&&(0,d.jsx)(Vn,{status:ke,errorMessage:pe,authorized:pr}),(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?ap:{},...ze?{animation:ze,pointerEvents:"none"}:{}},children:[Fl("flopay-direct-paypal-gate-debug"),Bl("flopay-stripe-gate-debug"),ca&&Pt&&(0,d.jsxs)(d.Fragment,{children:[ge&&(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)(wa.Provider,{value:g,children:(0,d.jsx)(Ra,{sessionId:e,nonce:t,billingApiUrl:yt,email:ot.email,billingName:_o||void 0,onBuyerIdentityReady:ct,clientId:Pt.clientId,environment:Pt.environment,currency:St.toUpperCase(),isSubscription:Et,providerObjectType:oe,approvalPresentation:Ga==="popup"?void 0:Ga,onTokenizedBody:Un,onComplete:i,onErrorChange:Le,onDecline:p,onTechnicalFailure:Ao,onButtonClick:re,runBeforeButtonClick:Pr,isProcessing:ae,onLoadStateChange:es,onInitializationStateChange:ts,session:F,existingOrderId:ge?.orderId,debug:X},ge?.orderId??"fresh")})]}),da&&(0,d.jsx)(Qt.Elements,{stripe:ua,options:rl,children:(0,d.jsx)(Tc,{sessionId:e,nonce:t,email:ot.email,billingName:_o||void 0,onBuyerIdentityReady:ct,billingApiUrl:yt,onTokenizedBody:Un,onErrorChange:Le,isProcessing:ae,onButtonClick:re,onDecline:p,onTechnicalFailure:Ao,runBeforeButtonClick:Pr,onLoadStateChange:dl,placeholderBorderRadius:yo,popupCapabilityOwner:g,externalTelemetryContext:vl,presentationMode:Mo})}),Fo?(0,d.jsx)(Qt.Elements,{stripe:Xn,options:nl,children:(0,d.jsx)(Mc,{sessionId:e,nonce:t,email:ot.email,billingName:_o||void 0,onBuyerIdentityReady:ct,billingApiUrl:yt,intentKind:je>0?"payment":"setup",expressMethods:xo,onTokenizedBody:Un,onErrorChange:Le,onButtonClick:re,onDecline:p,onTechnicalFailure:Ao,runBeforeButtonClick:Pr,onLoadStateChange:ml,placeholderBorderRadius:yo,popupCapabilityOwner:g,externalTelemetryContext:Se})}):null,!Fo&&bl?(0,d.jsx)("div",{style:{height:Qo,borderRadius:yo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,pa&&(0,d.jsx)(xc,{sessionId:e,nonce:t,email:ot.email,billingName:[ot.firstName,ot.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ct,billingApiUrl:yt,paymentElementMethods:Ha,stripeInstance:Xn,paymentElementBaseOptions:Qi,futureUseSession:B,onTokenizedBody:Un,onErrorChange:Le,onButtonClick:re,onDecline:p,runBeforeButtonClick:Pr,onLoadStateChange:fl,isProcessing:ae,submitButtonColor:fo,submitButtonBorderRadius:Zt,submitButtonStyle:E.submitButton,onExpandApm:Ct,expandedApmMethod:mn,themeId:Ne,buttonAppearance:{backgroundColor:E.cardButton?.backgroundColor,borderColor:E.cardInputBorder,textColor:E.cardButton?.color,borderRadius:yo}}),v&&(0,d.jsx)("button",{type:"button",onClick:async()=>{ae||!(await Pr("card")).proceed||(re?.("card"),ce())},disabled:ae,style:{width:"100%",...ne,...E.cardButton,...js({themeBundle:he,resolvedPrimaryColor:fo,resolvedBorderRadius:Zt,submitButtonStyle:E.submitButton,explicitPrimaryColor:zn?.colorPrimary}),fontSize:E.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ae?"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:ae?.6:1},onMouseEnter:xe=>{!ae&&(he||zn?.colorPrimary)&&(xe.currentTarget.style.backgroundColor=Au)},onMouseLeave:xe=>{(he||zn?.colorPrimary)&&(xe.currentTarget.style.backgroundColor=fo)},onMouseDown:xe=>{xe.currentTarget.style.transform="scale(0.985)"},onMouseUp:xe=>{xe.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(No,{content:We})}),pe&<==="buttons"&&(0,d.jsx)(Ho,{margin:"0.25rem 0",styleOverride:E.errorBanner,children:pe})]}),v&&T&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...ie?{animation:ie}:{},...lt==="collapsing"?{pointerEvents:"none"}:{}},children:xl}),G&&Dl&&mn&&Qa&&Xn&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Oo?{animation:Oo}:{},...lt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:as,borderRadius:us,...ha,padding:cs},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:Jt,style:{display:"inline-flex",alignItems:"center",gap:is?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,d.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,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)(Uo,{content:Te})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:E.titleFontSize??"1.05rem",color:ss,paddingRight:80,...E.title},children:`Pay with ${(0,f.getStripeMethodDisplayName)(mn)}`})]}),(0,d.jsx)(Qt.Elements,{stripe:Xn,options:Qa,children:(0,d.jsx)(Ns,{method:mn,sessionId:e,nonce:t,email:ot.email,billingName:[ot.firstName,ot.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ct,billingApiUrl:yt,onTokenizedBody:Un,onErrorChange:Le,onDecline:p,onCancel:Jt,runBeforeButtonClick:Pr,onButtonClick:re,isProcessing:ae,submitButtonColor:fo,submitButtonBorderRadius:Zt,submitButtonStyle:E.submitButton,errorText:pe})},mn)]})})]})]})}return Dl&&mn&&Qa&&Xn&&G?(0,d.jsxs)("form",{onSubmit:rs,className:_,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ea,{}),ke&&(0,d.jsx)(Vn,{status:ke,errorMessage:pe,authorized:pr}),(0,d.jsx)("div",{style:{...Oo?{animation:Oo}:{},...lt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:as,borderRadius:us,...ha,padding:cs},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:Jt,style:{display:"inline-flex",alignItems:"center",gap:is?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,d.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,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)(Uo,{content:Te})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:E.titleFontSize??"1.05rem",color:ss,paddingRight:80,...E.title},children:`Pay with ${(0,f.getStripeMethodDisplayName)(mn)}`})]}),(0,d.jsx)(Qt.Elements,{stripe:Xn,options:Qa,children:(0,d.jsx)(Ns,{method:mn,sessionId:e,nonce:t,email:ot.email,billingName:[ot.firstName,ot.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ct,billingApiUrl:yt,onTokenizedBody:Un,onErrorChange:Le,onDecline:p,onCancel:Jt,runBeforeButtonClick:Pr,onButtonClick:re,isProcessing:ae,submitButtonColor:fo,submitButtonBorderRadius:Zt,submitButtonStyle:E.submitButton,errorText:pe})},mn)]})})]}):(0,d.jsxs)("form",{onSubmit:rs,className:_,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ea,{}),ke&&(0,d.jsx)(Vn,{status:ke,errorMessage:pe,authorized:pr}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Fl("flopay-direct-paypal-gate-debug-default"),Bl("flopay-stripe-gate-debug-default"),ca&&Pt&&(0,d.jsxs)(d.Fragment,{children:[ge&&(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)(wa.Provider,{value:g,children:(0,d.jsx)(Ra,{sessionId:e,nonce:t,billingApiUrl:yt,email:ot.email,billingName:_o||void 0,onBuyerIdentityReady:ct,clientId:Pt.clientId,environment:Pt.environment,currency:St.toUpperCase(),isSubscription:Et,providerObjectType:oe,approvalPresentation:Ga==="popup"?void 0:Ga,onTokenizedBody:Un,onComplete:i,onErrorChange:Le,onDecline:p,onTechnicalFailure:Ao,onButtonClick:re,runBeforeButtonClick:Pr,isProcessing:ae,onLoadStateChange:es,onInitializationStateChange:ts,session:F,existingOrderId:ge?.orderId,debug:X},ge?.orderId??"fresh")})]}),da&&(0,d.jsx)(Qt.Elements,{stripe:ua,options:rl,children:(0,d.jsx)(Tc,{sessionId:e,nonce:t,email:ot.email,billingName:_o||void 0,onBuyerIdentityReady:ct,billingApiUrl:yt,onTokenizedBody:Un,onErrorChange:Le,isProcessing:ae,onButtonClick:re,onDecline:p,onTechnicalFailure:Ao,runBeforeButtonClick:Pr,onLoadStateChange:dl,placeholderBorderRadius:yo,popupCapabilityOwner:g,externalTelemetryContext:vl,presentationMode:Mo})}),Fo&&(0,d.jsx)(Qt.Elements,{stripe:Xn,options:nl,children:(0,d.jsx)(Mc,{sessionId:e,nonce:t,email:ot.email,billingName:_o||void 0,onBuyerIdentityReady:ct,billingApiUrl:yt,intentKind:je>0?"payment":"setup",expressMethods:xo,onTokenizedBody:Un,onErrorChange:Le,onButtonClick:re,onDecline:p,onTechnicalFailure:Ao,runBeforeButtonClick:Pr,onLoadStateChange:ml,placeholderBorderRadius:yo,popupCapabilityOwner:g,externalTelemetryContext:Se})}),pa&&(0,d.jsx)(xc,{sessionId:e,nonce:t,email:ot.email,billingName:[ot.firstName,ot.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:yt,paymentElementMethods:Ha,stripeInstance:Xn,paymentElementBaseOptions:Qi,futureUseSession:B,onTokenizedBody:Un,onErrorChange:Le,onButtonClick:re,onDecline:p,runBeforeButtonClick:Pr,onLoadStateChange:fl,isProcessing:ae,submitButtonColor:fo,submitButtonBorderRadius:Zt,submitButtonStyle:E.submitButton,themeId:Ne,onExpandApm:Ct,expandedApmMethod:mn,buttonAppearance:{backgroundColor:E.cardButton?.backgroundColor,borderColor:E.cardInputBorder,textColor:E.cardButton?.color,borderRadius:yo}})]}),v&&(wu||Su||ku)&&(0,d.jsx)(Ei,{label:"or pay with card"}),v&&xl]})}var O=require("react/jsx-runtime"),ra=44,Ys="flopay_checkout_saved_payment_resume",Li=new Map,Di=new Map;function zc(e,t){t.settled&&t.consumers===0&&Li.get(e)===t&&Li.delete(e)}function mp(e,t,n){let r=Di.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Di.set(e,a);let i=()=>{Di.get(e)===a&&Di.delete(e)};return o.then(i,i),o}function Ua(e){return new Promise(t=>setTimeout(t,e))}function Oi(e,t,n){let r=li({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:et.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function za(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function $s(e,t,n,r,o,a){let i=Oi(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),za(i)}function qc(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 Vc(e,t,n,r,o){let a=(0,et.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 et.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof et.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 Hc(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 Ws(e){return!e||e.data.stripe?.publishableKey?!1:!!Hc(e)?.clientId}var yp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function fp(e){return new Xr.FloPay(yp,{publishableKey:"provider_unavailable",...e})}async function Hs(e,t){let{publishableKey:n,paypalPublishableKey:r}=Ts(e);return{...await As({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Xs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function gp(){if(!Xs())return null;try{let e=window.sessionStorage.getItem(Ys);return e?JSON.parse(e):null}catch{return null}}function jc(e){if(Xs())try{window.sessionStorage.setItem(Ys,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ks(){if(Xs())try{window.sessionStorage.removeItem(Ys)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function hp(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function $c(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function Gs(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function bp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Wc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Pp(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 Ni({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:i,loading:c,error:p,onComplete:u,onError:h,onInstrument:P,onDecline:M,onCountryChange:_,onZipChange:w,showPayPal:A=!0,showStripe:I=!0,walletPresentation:b="auto",enabledPaymentMethods:C,showApplePay:G=!0,showGooglePay:k=!0,debug:ye=!1,layout:N,theme:H,buttonsTheme:_e,buttonsStyles:te,cardButtonContent:Ne,cardBackButtonContent:Ye,cardTitleContent:be,showSecurityFooter:fe,onButtonClick:We,onBeforeButtonClick:Te,enableAVS:Fe,cardFieldOrder:Ae,cardPreFormSlot:re,avsLayout:se,submitLabel:Ce,className:Be,initialErrorMessage:Y=null,initialPayPalOrderId:Q,children:Pe,checkoutMode:z,confirmLabel:we,renderConfirmButton:J,onSessionCompleted:Ee}){let Z=(0,et.resolveBillingApiUrl)(r),it=(0,R.useMemo)(()=>(0,et.resolveTheme)(H),[H]),He=a??it?.appearance,Ve=n?"embedded_checkout":"standard_checkout",at=Gs(Pe,N),[Ke,st]=(0,R.useState)(null),[je,St]=(0,R.useState)(null),Lt=(0,R.useRef)(null),Pt=(0,R.useRef)(null),Et=(0,R.useRef)(0),[q,ve]=(0,R.useState)(null),Qe=(0,R.useRef)(null),[X,Ue]=(0,R.useState)(null),vt=(0,R.useMemo)(()=>n?Go(n):"",[n]),Xe=n?`create:${vt}`:`session:${e??""}`,kt=Wc(X),V=(0,R.useRef)(new Set),g=(0,R.useRef)(Xe),S=(0,R.useRef)(Xe);Co(()=>{S.current=Xe,g.current!==Xe&&(g.current=Xe,V.current.clear())},[Xe]);let K=(0,R.useCallback)(L=>{if(S.current===Xe){if(Ps.has(L.name)){if(V.current.has(L.name))return;V.current.add(L.name)}Je(()=>P?.(L))}},[Xe,P]),W=Wo(K,Xe),Se=(0,R.useRef)(!1),F=(0,R.useCallback)(L=>{if(Se.current)return;let $=L.gateway||!kt?L:{...L,gateway:kt};K($)},[K,kt]);(0,R.useEffect)(()=>{W({class:"lifecycle",name:"checkout.mount"})},[W]);let[B,oe]=(0,R.useState)(e??""),j=e??B,Ie=n?"":j,[tt,gt]=(0,R.useState)(!0),[yt,De]=(0,R.useState)(null),[xn,$n]=(0,R.useState)(0),[bn,$t]=(0,R.useState)("full"),[Wn,Hn]=(0,R.useState)(!1),[wn,Dt]=(0,R.useState)(Y),[dt,rt]=(0,R.useState)(null),[Fn,Tt]=(0,R.useState)(null),[Kn,Pn]=(0,R.useState)(!1),[Wt,nn]=(0,R.useState)(void 0),[ur,er]=(0,R.useState)(""),[rn,At]=(0,R.useState)(!1),[on,cn]=(0,R.useState)(!1),[Nt,dn]=(0,R.useState)(!1),zt=(0,R.useRef)(null),un=(0,R.useRef)(0),Ut=(0,R.useRef)(void 0),[ue,dr]=(0,R.useState)("loading"),[pr,mr]=(0,R.useState)(0),an=(0,R.useRef)(!1),Bn=(0,R.useRef)(!1),En=(0,R.useRef)(!1),Oe=(0,R.useRef)(null),ft=(0,R.useRef)(null),v=(0,R.useMemo)(()=>({checkoutMode:z??bn,layout:bp(Pe,N)}),[z,Pe,bn,N]),nt=(0,R.useRef)(u);nt.current=u;let le=(0,R.useRef)(h);le.current=h;let kn=(0,R.useRef)(M);kn.current=M;let Gn=(0,R.useCallback)(L=>hi(Oe,async $=>{try{return await L($)}catch(ce){throw $.aborted?lo(ce):ce}}),[]);(0,R.useEffect)(()=>()=>{Oe.current?.abort(),Oe.current=null},[]);let Yt=(0,R.useCallback)((L,$)=>{Lt.current=L,St(L),Qe.current=$,ve($)},[]),Dn=(0,R.useCallback)(()=>{let L=Pt.current;L&&(Pt.current=null,L.destroy())},[]);(0,R.useEffect)(()=>{gn(je)?.setCheckoutContext(v),q&&q!==je&&gn(q)?.setCheckoutContext(v)},[je,q,v]);let ht=(0,R.useRef)(Ee);ht.current=Ee;let yr=(0,R.useCallback)(L=>{dr(L),!(L!=="exhausted"||En.current)&&(En.current=!0,le.current?.(new et.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),po=(0,R.useCallback)(()=>{dr("retrying"),mr(L=>L+1)},[]);(0,R.useEffect)(()=>{dr("loading"),mr(0),En.current=!1},[j]),(0,R.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:et.SDK_VERSION,checkout_type:Ve,checkout_layout:at,billing_api_url:Z})},[at,Ve,Z]);let Mt=(0,R.useMemo)(()=>n?Go(n,!0):"",[n]),On=(0,R.useMemo)(()=>ur===Mt?Wt:void 0,[Wt,ur,Mt]),Rr=(0,R.useMemo)(()=>n?ys(n,On):void 0,[n,On]),tr=z??Rr?.checkoutMode??"full",Xt=(0,R.useMemo)(()=>Rr?{...Rr,checkoutMode:tr}:void 0,[Rr,tr]);(0,R.useEffect)(()=>{nn(void 0),er(Mt),Ut.current=void 0,zt.current=null,dn(!1)},[Mt]),(0,R.useEffect)(()=>{Dt(Y)},[Y]);let fr=(0,R.useCallback)((L,$,ce)=>{Je(()=>{kn.current?.(fn(L,$,ce))})},[]),Ln=(0,R.useCallback)(async(L,$)=>{Dt(null),Tt(null),Pn(!1),rt("processing");let ce=$?.sessionId??L.id,Me=L.clientSecret||t,Ct=Wc(L),Jt=Lt.current??Qe.current,ke=gn(Jt),de=Jt?null:Oi(Z,o,v),ee={log:$e=>{ke?ke.log($e):de?.log($e)},error:$e=>{ke?ke.error($e):de?.error($e)},terminal:$e=>{ke?ke.terminal($e):de?.terminal($e)},performance:$e=>{ke?ke.performance($e):de?.performance($e)},now:()=>ke?.now()??de?.now()??0,elapsed:$e=>ke?.elapsed($e)??Math.max(0,(de?.now()??$e)-$e)},m=ee.now(),y=!!($?.initialAutoProcessingError||$?.initialAutoProcessingPending),D=!1,U,Re=()=>{D||(D=!0,y=!0,U=ee.now(),ee.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),ee.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ge=!1,Rt=()=>{ge||(ge=!0,ee.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),ee.performance({stage:"processing",durationMs:ee.elapsed(m),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),U!==void 0&&ee.performance({stage:"recovery",durationMs:ee.elapsed(U),durationMode:"machine",paymentMethodCategory:"saved"}))};ee.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Se.current=!0;try{ee.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Se.current=!1}W({class:"lifecycle",name:"payment.processing.started",provider:Ct}),y&&Re();let qt;try{let $e=cc($?.initialAutoProcessingError),Ge=$?.initialAutoProcessingError?.type==="3ds_required"&&!$.initialAutoProcessingError.threeDSecureToken&&$.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:$.initialAutoProcessingError.nextActionRedirectUrl}:null,ct,pe=he=>(Re(),Gn(E=>Xo(he,{billingApiUrl:Z,sessionId:ce,nonce:Me,session:L,signal:E})));if(Ge)ct=await pe(Ge);else if($e)Re(),$e.type==="paypal_redirect_required"&&ft.current?.publishableKey&&jc({sessionId:ce,publishableKey:ft.current.publishableKey,paypalPublishableKey:ft.current.paypalPublishableKey}),ct=await Gn(he=>Pi($e,{flopay:Lt.current,paypalFlopay:Qe.current,attempt3DS:$?.attempt3DS,billingApiUrl:Z,sessionId:ce,session:L,telemetry:!1,signal:he})),$e.type==="paypal_redirect_required"&&Ks();else if($?.initialAutoProcessingPending){let he=$.initialAutoProcessingPending,E=new Xr.PaymentAPI(Z,{telemetry:!1}),me=await Gn(ae=>E.waitForCheckoutSessionCompletion(he.sessionId,{initialDelayMs:he.retryAfterMs,nonce:Me,statusUrl:he.statusUrl,signal:ae})),pt=ro(me,L),xt=me.autoProcessingError?.type==="3ds_required"&&me.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:me.autoProcessingError.nextActionRedirectUrl}:null;if(xt)ct=await pe(xt);else{if(!$r(pt))throw qo(pt);ct=jr(pt,ce)}}else{if($?.initialAutoProcessingError)throw Dr($.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:$.initialAutoProcessingError.checkoutMethod});if($?.fromCreateSession)return $?.fallbackToFull&&($t("full"),$c("full")),!1;{let he=await Jo({billingApiUrl:Z,sessionId:ce,session:L,nonce:Me,telemetry:!1});he.type==="success"?ct=he.result:he.type==="next_action_required"?ct=await pe(he):(Re(),he.type==="paypal_redirect_required"&&ft.current?.publishableKey&&jc({sessionId:ce,publishableKey:ft.current.publishableKey,paypalPublishableKey:ft.current.paypalPublishableKey}),ct=await Gn(E=>Pi(he,{flopay:Lt.current,paypalFlopay:Qe.current,attempt3DS:$?.attempt3DS,billingApiUrl:Z,sessionId:ce,session:L,telemetry:!1,signal:E})),he.type==="paypal_redirect_required"&&Ks())}}ce&&Yo(ce),Rt(),y&&(ee.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),ee.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),ee.terminal({outcome:ct.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Pn(ct.status==="authorized"),rt("success"),await Ua(600),qt=()=>nt.current?.(ct)}catch($e){let Ge=to(Aa($e),ce);if(Ge.code==="three_ds_aborted")return!1;let ct=Ge.checkoutMethod??Ta;Dt(Ge.message),Tt(Ge.message),Pn(!1),$?.fallbackToFull&&(ee.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),$t("full"),$c("full")),Rt();let pe=Ge.statusCode===void 0?void 0:(0,et.telemetryStatusClass)(Ge.statusCode,"unknown"),he=pe==="4xx"?{requestCategory:"process_payment",statusClass:pe}:{},E=pe===void 0||pe==="4xx";if(E&&(Ge.telemetryOutcome==="payment_declined"||!!(Ge.declineCode||Ge.code?.toLowerCase().includes("declin"))))ee.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...he});else if(E&&(Ge.telemetryOutcome==="validation_rejected"||Ge.type==="validation_error"))ee.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...he});else{let xt=(0,et.classifyTelemetryFailure)($e,y?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),ae=Ge.telemetryRequestCategory??"process_payment";Se.current=!0;try{ee.error({...xt,...Ge.telemetryFailureCategory?{failureCategory:Ge.telemetryFailureCategory}:{},stage:y?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:ae})}finally{Se.current=!1}W({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:ae,provider:Ct})}return Je(()=>le.current?.(Ge)),fr(ct,Ge,{code:Ge.code,declineCode:Ge.declineCode}),rt("error"),await Promise.allSettled([Ua(400),$?.ensureProvidersReady?$.ensureProvidersReady():Promise.resolve()]),y&&(ee.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),ee.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Rt(),de&&za(de),rt(null),Tt(null)}return Je(qt),!0},[fr,W,t,Z,Gn,o,v]);(0,R.useEffect)(()=>{if(typeof window>"u"||Bn.current)return;let L=new URLSearchParams(window.location.search),$=L.get("payment_intent_client_secret");if(!$)return;let ce=gp();ce&&(Bn.current=!0,(async()=>{let Me,Ct=0;Dt(null),Tt(null),rt("processing"),Hn(!0);try{if(L.get("redirect_status")==="failed")throw Object.assign(new et.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Jt,paypalFlopay:ke}=await As({publishableKey:ce.publishableKey,paypalPublishableKey:ce.paypalPublishableKey,billingApiUrl:Z,locale:i,telemetry:o});Me=gn(ke??Jt),Me?.setCheckoutContext(v),Ct=Me?.now()??0,Me?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Me?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let de=(ke??Jt)?.getRawProvider();if(!de)throw Object.assign(new et.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:ee,error:m}=await de.retrievePaymentIntent($);if(m)throw Object.assign(new et.FloPayError(m.message??"Failed to retrieve PayPal payment status.","api_error",{code:m.code}),{checkoutMethod:"paypal"});let y=$l(ee?.status);if(!ee||y==="failed")throw Object.assign(new et.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let D=typeof ee.payment_method=="string"?ee.payment_method:ee.payment_method?.id,U=y;if(ce.sessionId){let Rt=(await new Xr.PaymentAPI(Z,{telemetry:!1}).getUnifiedCheckoutSession(ce.sessionId)).data.session;if(Rt&&Rt.status!=="complete"){let qt=await Jo({billingApiUrl:Z,sessionId:ce.sessionId,session:Rt,telemetry:!1,tokenizedData:{id:D??ee.id,type:"card",threeDSecureActionResultTokenId:ee.id,isPaypal:!0}});if(qt.type!=="success")throw Object.assign(new et.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});U=qt.result.status}}ce.sessionId&&Yo(ce.sessionId),Me?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Me?.performance({stage:"redirect_resume",durationMs:Me.elapsed(Ct),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Me?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),rt("success"),await Ua(600),Je(()=>nt.current?.({status:U,paymentIntentId:ee.id,paymentMethodId:D,checkoutMethod:"paypal"}))}catch(Jt){let ke=to(Aa(Jt),ce.sessionId),de=ke.checkoutMethod??"paypal",ee=!!(ke.declineCode||ke.code?.toLowerCase().includes("declin"));if(Me)Me.performance({stage:"redirect_resume",durationMs:Me.elapsed(Ct),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ee?Me.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Me.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(ee){let m=Oi(Z,o,v);m.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),za(m)}else $s(Z,o,v,"REDIRECT_RESUME_FAILED","redirect_resume");Dt(ke.message),Tt(ke.message),Je(()=>le.current?.(ke)),fr(de,ke,{code:ke.code,declineCode:ke.declineCode}),rt("error"),await Ua(400)}finally{Ks(),hp(),rt(null),Tt(null),Hn(!1)}})())},[fr,i,Z,o,v]);let Ur=(0,R.useRef)(null),Nn=(0,R.useMemo)(()=>Xt?Go(Xt):"",[Xt]),_r=(0,R.useRef)(Xt);_r.current=Xt,(0,R.useEffect)(()=>{oe(e??"")},[e]),(0,R.useEffect)(()=>{an.current=!1,Dt(Y),Tt(null),Pn(!1),rt(null)},[Nn,Y,e]);async function Er(L,$,ce){let Me=Oi(Z,o,v),Ct=new Xr.PaymentAPI(Z,{telemetry:!1}),Jt=!1;try{let ke=L.idempotencyKey===void 0?void 0:(0,et.resolveIdempotencyKey)(L.idempotencyKey),de=Ss($,ce),ee=ws($,ce);de?.canonicalIdentity===ce&&ee&&ee.canonicalIdentity===void 0&&(fi($,ce,ee.idempotencyKey),ee={...ee,canonicalIdentity:ce});let m=ke??(ee?.canonicalIdentity===ce?ee.idempotencyKey:void 0),y,D=!1;Me.log({name:de?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let U=de?.sid??null,Re=null,ge,Rt,qt=!1;if(U)try{Re=await Ct.getUnifiedCheckoutSession(U,de?.nonce),de&&de.canonicalIdentity===void 0&&(ac(Re.data.session,L)?(yi($,ce,U,de.nonce??Re.data.session?.clientSecret),ee&&ee.canonicalIdentity===void 0&&(fi($,ce,ee.idempotencyKey),m??(m=ee.idempotencyKey))):(mi($,ce),ee=null,m=ke,U=null,Re=null));let Ge=Re?.data.session?.status,ct=Re?.data.session,pe=ct?.clientSecret||de?.nonce;if(U&&ct?.buyerIdentified===!1&&pe&&(Rt=zo(Ct,U,pe,L.account)),U&&Re&&Ge==="complete"){if(ks(U))return{sid:U,result:Re};mi($,ce),U=null,Re=null,D=!0}}catch{Me.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),de?.canonicalIdentity===void 0?(mi($,ce),m=ke):pi($,ce),U=null}if(!U){!ke&&(D||!m)&&(m=(0,et.resolveIdempotencyKey)(),y=m),m&&fi($,ce,m);let Ge=Me.now(),ct=0;Me.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let pe={...L,idempotencyKey:m,avsCheck:!!Fe,avsConfig:typeof Fe=="object"?Fe:void 0,checkoutType:"embedded_checkout",checkoutLayout:Gs(Pe,N)};Object.defineProperty(pe,Xr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:me=>{ct=Math.max(ct,me)}}});let he=()=>{qc(Me,"session_create",Ge,ct)},E=me=>{Vc(Me,me,"session_create",Ge,ct)&&W({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,et.isDetachedSessionEligible)(pe)){let me=await Ct.createDetachedSession(pe);me.claimed.catch(()=>{}),Re=me.shell,U=me.sessionId,Rt=me.claim;let pt=Me.now();Me.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ge=me.claimed.then(xt=>{let ae=xt.data.session?.id??me.sessionId;return ae&&yi($,ce,ae,xt.data.session?.clientSecret??me.nonce),qc(Me,"session_claim",pt),he(),xt},xt=>{throw pi($,ce),Vc(Me,xt,"session_claim",pt,0)&&W({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),xt}).finally(()=>za(Me)),ge.catch(()=>{}),Jt=!0,Me.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Me.performance({stage:"session_shell",durationMs:Me.now()-Ge,durationMode:"machine",requestCategory:"session_create",attempt:ct,statusClass:"2xx",paymentMethodCategory:"card"})}else Re=await Ct.createAndFetchSession(pe),he()}catch(me){throw E(me),me}U=Re.data.session?.id??U??"",U&&!ge&&yi($,ce,U,Re.data.session?.clientSecret)}let $e=Re?.data.session;return!Rt&&U&&$e?.buyerIdentified===!1&&$e.clientSecret&&(Rt=zo(Ct,U,$e.clientSecret,L.account)),{sid:U??"",result:Re,sdkGeneratedIdempotencyKey:y,...ge?{claimed:ge}:{},...Rt?{claim:Rt}:{},...qt?{claimRequiresIdentity:!0}:{}}}finally{Jt||za(Me)}}let zr=(0,R.useRef)(Er);Co(()=>{zr.current=Er},[Er]);let Yn=(0,R.useCallback)(async(L,$)=>{let ce=_r.current;if(!ce)throw new et.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Me=ys(ce,L),Ct=Go(Me),Jt=oc(Me),ke=Li.get(Ct);if(!ke){let m={canonicalIdentity:Ct,promise:zr.current(Me,Jt,Ct),consumers:0,settled:!1};ke=m,Li.set(Ct,m);let y=()=>{m.settled=!0,zc(Ct,m)};m.promise.then(y,y)}ke.consumers+=1;let de=!1,ee=()=>{de||(de=!0,ke.consumers-=1,zc(Ct,ke))};$?.(ee);try{let m=await ke.promise;Ur.current=Ct,L&&(er(Mt),nn($e=>ql($e,L)));let{sid:y,result:D,claimed:U,claim:Re,claimRequiresIdentity:ge}=m;if(Ut.current=Re,dn(ge===!0),st(D),D.data.session&&Ue(D.data.session),y&&oe(y),U){un.current+=1;let $e=un.current;zt.current=U,cn(!0),U.then(Ge=>{un.current===$e&&(zt.current===U&&(zt.current=null),st(Ge),Ge.data.session&&Ue(Ge.data.session),cn(!1),dn(!1))},Ge=>{un.current===$e&&(zt.current===U&&(zt.current=null),cn(!1),dn(!1),De(Ge instanceof et.FloPayError?Ge:new et.FloPayError(Ge instanceof Error?Ge.message:"Failed to create session","api_error")))})}else un.current+=1,zt.current=null,cn(!1),dn(!1);let{flopay:Rt,paypalFlopay:qt}=await Hs(D,{billingApiUrl:Z,locale:i,telemetry:o});return Yt(Rt,qt),gt(!1),m}catch(m){throw Ur.current===Ct&&(Ur.current=null),m}finally{$||ee()}},[Mt,Yt,i,Z,o]),nr=(0,R.useRef)(Ln);nr.current=Ln;let qr=(0,R.useRef)(Yn);qr.current=Yn;let Ot=(0,R.useCallback)(async L=>{if(!Pp(L)||rn)return{sessionId:B,session:X};At(!0);try{let $=await Yn(L);return{sessionId:$.sid,session:$.result.data.session??null}}finally{At(!1)}},[Yn,rn,B,X]),In=(0,R.useCallback)(async L=>{let $=Ut.current;if(!$)return;let ce=un.current,Me=await $(L);un.current===ce&&(st(Me),Me.data.session&&Ue(Me.data.session))},[]),rr=(0,R.useCallback)(async()=>{await zt.current},[]),gr=(0,R.useCallback)(async()=>(await rr(),{proceed:!0}),[rr]);(0,R.useEffect)(()=>{let L=!1,$,ce=++Et.current;Dn(),De(null),$n(0);let Me=()=>{L=!0,Et.current===ce&&(Et.current+=1,Dn())},Ct=_r.current;if(Nn&&Ct)return $t(tr),gt(!1),Ur.current===Nn?Me:(Ue(Vl(Ct,z)),(async()=>{let de=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ee=tr==="auto"&&!an.current&&!de;ee&&(Dt(null),Tt(null),rt("processing"));try{let m=await qr.current(void 0,Re=>{$=Re}),y=m.result.data.session??null;ft.current=Ts(m.result);let D=Ws(m.result),U=ks(m.sid||y?.id);if(!L&&ee&&y&&!D&&!U){an.current=!0,await mp(Nn,m.sdkGeneratedIdempotencyKey,()=>nr.current(y,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:m.result.autoProcessingError,initialAutoProcessingPending:m.result.autoProcessingPending,autoProcessingAttempted:m.result.autoProcessingAttempted,sessionId:m.sid||y.id}));return}!L&&ee&&((D||U)&&(an.current=!0),rt(null),Tt(null))}catch(m){if(L)return;let y=ni(m);if(ee&&y==="session_auto_completed"){an.current=!0,rt("success"),await Ua(600),L||(Je(()=>{nt.current?.({status:"succeeded"})}),rt(null),Tt(null));return}ee&&(rt(null),Tt(null));let D=m instanceof et.FloPayError?m:new et.FloPayError(m instanceof Error?m.message:"Failed to create session","api_error");De(D)}finally{$?.(),$=void 0}})(),()=>{Me(),$?.()});gt(!0);async function Jt(){let de=!1,ee=null;try{let m=new Xr.PaymentAPI(Z,{telemetry:!1}),y=await m.getUnifiedCheckoutSession(j,t);if(ee=y,L)return;st(y);let D=y.data.session??null;if(Ue(D),!D)throw new et.FloPayError("No session data returned","api_error");let U=D.checkoutMode;if(U==="setup")throw new et.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(D.status==="authorized"){gt(!1),Je(()=>{nt.current?.(jr(D,j)),ht.current?.(D.successUrl??"")});return}if(D.status==="complete"){gt(!1),Je(()=>{ht.current?.(D.successUrl??"")});return}if(D.status==="expired")throw ti(D);de=!0;let Re=z??U??"full";$t(Re),un.current+=1;let ge=D.clientSecret||t;Ut.current=D.buyerIdentified===!1&&ge?zo(m,j,ge,{...D.customer?.id?{userId:D.customer.id}:{}}):void 0,cn(!1),dn(!1);let Rt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),qt=Ws(y);if(Re==="auto"&&!an.current&&!Rt&&!qt){an.current=!0;let $e=ke(y);try{if(await nr.current(D,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>$e,sessionId:j||D.id}),L)return;await $e,L||gt(!1);return}catch{if(L)return;await $e,L||gt(!1);return}}await ke(y),L||gt(!1)}catch(m){if(L)return;let y=zl(m,de);if(de&&W({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),y){let{errorCode:U,stage:Re,...ge}=y;$s(Z,o,v,U,Re,ge)}if(y?.stage==="provider_load"&&(z??ee?.data.session?.checkoutMode??"full")==="full"&&Ul(ee,A,I)){let U=fp({billingApiUrl:Z,locale:i,telemetry:o});Pt.current=U,Yt(U,null),$n(1),gt(!1);return}let D=m instanceof et.FloPayError&&y?.stage!=="provider_load"?m:Nl();D!==m&&Je(()=>le.current?.(D)),De(D),gt(!1)}}async function ke(de){let{flopay:ee,paypalFlopay:m,...y}=await Hs(de,{billingApiUrl:Z,locale:i,telemetry:o});ft.current={publishableKey:y.publishableKey,paypalPublishableKey:y.paypalPublishableKey},Yt(ee,m),$n(0)}return Jt(),Me},[z,Nn,tr,Ie,t,A,I]);let Ir=(0,R.useCallback)(async()=>{if(!Ke||xn!==1)return;let L=Et.current;$n(2);try{let{flopay:$,paypalFlopay:ce}=await Hs(Ke,{billingApiUrl:Z,locale:i,telemetry:o});if(Et.current!==L)return;Dn(),Yt($,ce),$n(0)}catch($){if(Et.current!==L)return;let{errorCode:ce,stage:Me,...Ct}=ps($);$s(Z,o,v,ce,Me,Ct)}},[Dn,Yt,i,xn,Z,o,v,Ke]),lt=!!(j&&(X?.clientSecret||t)),pn=Wn||!lt,mn=(0,R.useCallback)(async()=>{if(!(Wn||!lt||!X)){Hn(!0),Dt(null);try{await Ln(X,{attempt3DS:!0,fallbackToFull:!0,sessionId:j||X.id})}finally{Hn(!1)}}},[j,Wn,lt,Ln,X]),Tn=Hc(Ke,Q),mo=Ws(Ke),Tr=(0,R.useMemo)(()=>{if(!(!Ke||!X||!Ke.data.stripe?.publishableKey))return{billingApiUrl:Z}},[Ke,X,Z]),Zr=!!(n&&!Pe&&N==="buttons"&&Te&&tr==="full"),An=!!(j&&((0,et.isMountableVaultBlock)(X?.vault)||eo(X))),yn=(0,R.useMemo)(()=>({session:X,loading:tt,error:yt,checkoutMode:bn,inlineSessionDraft:Xt,applyInlineSessionPatch:Zr?Ot:void 0,inlineSessionPatchProcessing:rn,claimPending:on,claimRequiresIdentity:Nt,claimBuyerIdentity:In,waitForDataAttachment:rr}),[X,tt,yt,bn,Xt,Zr,Ot,rn,on,Nt,In,rr]),hr=!!n&&N==="buttons"&&!mo&&!An&&(!je||!Tr),vn=dt?(0,O.jsx)(Vn,{status:dt,errorMessage:Fn,authorized:Kn}):null;if(tt&&!An){if(c)return(0,O.jsxs)(O.Fragment,{children:[c,vn]});if(N==="buttons"){let L=it?.buttonsLayout?.cardButton?.borderRadius??it?.appearance.variables?.borderRadius??8,$=ce=>(0,O.jsx)("div",{style:{height:ce,borderRadius:L,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:[A&&$(ra),I&&(G||k)&&$(ra),I&&$(ra),(0,O.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),vn]})}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); } }"})]}),vn]})}return yt?p?(0,O.jsx)(Cr.Provider,{value:yn,children:p(yt)}):(0,O.jsx)(Cr.Provider,{value:yn,children:(0,O.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:yt.message})}):hr?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Cr.Provider,{value:yn,children:(0,O.jsx)(Cp,{onButtonClick:We,showPayPal:A,showStripe:I,showApplePay:G,showGooglePay:k,theme:H,buttonsTheme:_e,buttonsStyles:te,cardButtonContent:Ne,cardBackButtonContent:Ye,cardTitleContent:be})}),vn]}):mo&&X&&Tn?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Cr.Provider,{value:yn,children:(0,O.jsxs)("div",{className:Be,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[wn&&(0,O.jsx)(Ho,{icon:!1,children:wn}),ue==="retrying"&&(0,O.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),ue==="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:po,children:"Retry PayPal"})]}),ue!=="exhausted"&&(0,O.jsx)("div",{"aria-hidden":ue==="retrying"?!0:void 0,style:ue==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,O.jsx)(rc,{sessionId:j,nonce:X.clientSecret||void 0,billingApiUrl:Z,email:X.customer?.email||Xt?.account?.email,billingName:[X.customer?.firstName,X.customer?.lastName].filter(Boolean).join(" ")||[Xt?.account?.firstName,Xt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:In,clientId:Tn.clientId,environment:Tn.environment,currency:(X.currency??"usd").toUpperCase(),isSubscription:X.mode==="subscription",providerObjectType:Tn.providerObjectType,approvalPresentation:Tn.approvalPresentation,existingOrderId:Tn.existingOrderId,onComplete:u,onErrorChange:Dt,onDecline:M,onButtonClick:We,runBeforeButtonClick:gr,onInitializationStateChange:yr,allowAutomaticRetry:pr===0,session:X,telemetry:o,telemetryContext:v,onInstrument:F,debug:ye},`${Xe}:paypal-init-${pr}`)})]})}),vn]}):bn==="confirm"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Cr.Provider,{value:yn,children:(0,O.jsx)(Ea,{flopay:je,paypalFlopay:q,options:Tr??{billingApiUrl:Z},onInstrument:F,children:(0,O.jsxs)("div",{className:Be,children:[wn&&(0,O.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:wn}),J?J({onConfirm:mn,isProcessing:pn}):(0,O.jsx)("button",{type:"button",onClick:mn,disabled:pn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:pn?"not-allowed":"pointer",opacity:pn?.6:1},children:Wn?"Processing...":we??"Confirm Purchase"})]})},Xe)}),vn]}):(!je||!Tr)&&!(An&&bn==="full")?(0,O.jsx)(O.Fragment,{children:vn}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Cr.Provider,{value:yn,children:(0,O.jsxs)(Ea,{flopay:je,paypalFlopay:q,options:Tr??{billingApiUrl:Z},onInstrument:F,children:[xn===1&&(0,O.jsx)("button",{type:"button",onClick:Ir,children:"Retry payment methods"}),Pe?(0,O.jsxs)(O.Fragment,{children:[wn&&(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:wn}),(0,O.jsx)(vp,{sessionId:j,nonce:X?.clientSecret||void 0,billingApiUrl:Z,session:X,submitLabel:Ce,walletPresentation:b,children:Pe})]}):(0,O.jsx)(Bi,{sessionId:j,nonce:X?.clientSecret||void 0,telemetry:o,email:X?.customer?.email||Xt?.account?.email,userId:X?.customer?.id||Xt?.account?.userId,firstName:X?.customer?.firstName||Xt?.account?.firstName,lastName:X?.customer?.lastName||Xt?.account?.lastName,totalAmount:X?Math.round((0,et.buildCheckoutDisplayData)(X).total*100):0,currency:X?.currency?.toLowerCase()??"usd",onComplete:u,onError:h,onDecline:M,error:wn,onErrorChange:Dt,showPayPal:A,showStripe:I,walletPresentation:b,enabledPaymentMethods:xn?[]:C??Ke?.data.stripe?.enabledPaymentMethods??X?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ke?.data.stripe?.enabledPaymentMethodCountries,showApplePay:G,showGooglePay:k,layout:N,theme:H,buttonsTheme:_e,buttonsStyles:te,appearance:He,cardButtonContent:Ne,cardBackButtonContent:Ye,cardTitleContent:be,onButtonClick:We,onBeforeButtonClick:Te,onBuyerIdentityReady:In,enableAVS:Fe,...Ae?{cardFieldOrder:Ae}:{},...re?{cardPreFormSlot:re}:{},avsLayout:se,country:X?.customer?.country,city:X?.customer?.city,state:X?.customer?.state,onCountryChange:_,onZipChange:w,avsCheck:!!Fe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Gs(Pe,N),className:Be,submitLabel:Ce,directPaypal:Tn,isSubscription:X?.mode==="subscription",session:X,dataAttachmentPending:on,dataAttachmentRequiresIdentity:Nt,debug:ye})]},Xe)}),vn]})}function vp({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:a,children:i}){return(0,O.jsx)(O.Fragment,{children:R.default.Children.map(i,c=>{if(!R.default.isValidElement(c))return c;let p=c.props,u={};return p.sessionId||(u.sessionId=e),!p.nonce&&t&&(u.nonce=t),p.billingApiUrl||(u.billingApiUrl=n),p.submitLabel===void 0&&o!==void 0&&(u.submitLabel=o),p.walletPresentation===void 0&&(u.walletPresentation=a),r?.customer&&(p.email||(u.email=r.customer.email),p.userId||(u.userId=r.customer.id),p.firstName||(u.firstName=r.customer.firstName),p.lastName||(u.lastName=r.customer.lastName)),Object.keys(u).length===0?c:R.default.cloneElement(c,u)})})}function Cp({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:i,buttonsStyles:c,cardButtonContent:p,cardBackButtonContent:u,cardTitleContent:h}){let[P,M]=(0,R.useState)(!1),_=(0,R.useMemo)(()=>(0,et.resolveTheme)(a),[a]),w=(0,R.useMemo)(()=>{let C=_?.buttonsLayout??(0,et.resolveButtonsLayoutTheme)(i);return c?{...C,...c,cardButton:{...C.cardButton,...c.cardButton},cardFormContainer:{...C.cardFormContainer,...c.cardFormContainer},backButton:{...C.backButton,...c.backButton},backButtonIcon:{...C.backButtonIcon,...c.backButtonIcon},submitButton:{...C.submitButton,...c.submitButton},title:{...C.title,...c.title}}:C},[_,i,c]),A=_?.buttonsLayout?.cardButton?.borderRadius??_?.appearance.variables?.borderRadius??8,I=C=>(0,O.jsx)("div",{style:{height:C,borderRadius:A,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),b=p===void 0?{boxSizing:"border-box",height:ra,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(P){let C=w.cardInputBorder??"#e5e7eb",G=w.cardInputBackground??"white",k=Lo(u),ye=Lo(h);return(0,O.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,O.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,O.jsxs)("button",{type:"button",onClick:()=>M(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:k?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,O.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...w.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)(Uo,{content:u})]}),ye?(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,...w.title},children:(0,O.jsx)(Pa,{content:h})})]}),(0,O.jsx)("div",{style:{backgroundColor:G,border:`1px solid ${C}`,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:G,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,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:G,borderTop:"none",borderRight:`1px solid ${C}`,borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,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:G,border:`1px solid ${C}`,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",...w.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,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&_(ta),n&&(r||o)&&_(ta),n&&(0,O.jsx)("button",{type:"button",onClick:()=>{e?.("card"),T(!0)},style:{width:"100%",...P,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:S.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...S.cardButton},onMouseDown:w=>{w.currentTarget.style.transform="scale(0.985)"},onMouseUp:w=>{w.currentTarget.style.transform="scale(1)"},children:(0,O.jsx)(Oo,{content:p})}),(0,O.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var sr=require("react/jsx-runtime"),bp=44;function jc(e){return new Promise(t=>setTimeout(t,e))}function Pp(e,t){return e instanceof lr.FloPayError?e:new lr.FloPayError(e instanceof Error?e.message:t,"api_error")}function vp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Cp(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 $c({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:i,items:c,subscriptions:p,account:u,successUrl:g,cancelUrl:b,couponCodes:T,tagsData:I,utmMetadata:S,billingApiUrl:A,locale:_,theme:P,appearance:w,buttonsTheme:K,buttonsStyles:k,onSuccess:ge,onError:z,onDecline:X,children:Se,disabled:ae=!1,type:De="button",style:Ze,...le}){let Ee=(0,ut.useMemo)(()=>(0,lr.resolveBillingApiUrl)(A),[A]),We=(0,ut.useMemo)(()=>Cp({createSession:n,clientId:a,products:i,items:c,subscriptions:p,account:u,successUrl:g,cancelUrl:b,couponCodes:T,tagsData:I,utmMetadata:S}),[u,b,a,T,n,i,c,p,g,I,S]),[Re,Ie]=(0,ut.useState)(!1),[_e,ce]=(0,ut.useState)(null),[ue,Pe]=(0,ut.useState)(null),[Ae,J]=(0,ut.useState)(!1),[ee,he]=(0,ut.useState)(null),[U,we]=(0,ut.useState)(null),ie=(0,ut.useRef)(!0),Te=(0,ut.useRef)(null),te=(0,ut.useRef)(U),it=(0,ut.useRef)(ge),He=(0,ut.useRef)(z),je=(0,ut.useRef)(X),at=(0,ut.useCallback)(h=>fi(Te,async C=>{try{return await h(C)}catch(Y){throw C.aborted?so(Y):Y}}),[]);(0,ut.useEffect)(()=>{te.current=U},[U]),(0,ut.useEffect)(()=>{it.current=ge},[ge]),(0,ut.useEffect)(()=>{He.current=z},[z]),(0,ut.useEffect)(()=>{je.current=X},[X]),(0,ut.useEffect)(()=>(ie.current=!0,()=>{ie.current=!1,Te.current?.abort()}),[]),(0,ut.useEffect)(()=>{if(typeof window>"u")return;let h=C=>{C.key==="Escape"&&we(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let Ke=(0,ut.useCallback)((h,C=Ea)=>{je.current?.(mn(C,h,{code:h.code,declineCode:h.declineCode}))},[]),st=(0,ut.useCallback)(async h=>{ie.current&&(Pe(null),J(h.result.status==="authorized"),ce("success"),await jc(600),ie.current&&Je(()=>it.current?.(h)))},[]),$e=(0,ut.useCallback)(async(h,C)=>{ie.current&&(He.current?.(h),C?.emitDecline&&Ke(h,C.method),Pe(h.message),J(!1),ce("error"),await jc(400))},[Ke]),vt=(0,ut.useCallback)(async(h,C,Y)=>{let H=h.data.session??null;if(!H)throw eo(new lr.FloPayError("No session data returned","api_error"),C);let ve=H.clientSecret||t;if($r(H)){await st({result:jr(H,C),session:H,sessionId:H.id||C,autoCompleted:!1});return}if(H.status==="expired")throw eo(Qa(H),H.id||C);try{if(h.autoProcessingPending){let B=h.autoProcessingPending,de=new Li.PaymentAPI(Ee),D=await at(yt=>de.waitForCheckoutSessionCompletion(B.sessionId,{initialDelayMs:B.retryAfterMs,nonce:ve,statusUrl:B.statusUrl,signal:yt})),Me=no(D,H),lt=D.autoProcessingError?.type==="3ds_required"&&D.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:D.autoProcessingError.nextActionRedirectUrl}:null;if(lt&&C&&ve){let yt=await at(Ct=>Go(lt,{billingApiUrl:Ee,sessionId:C,nonce:ve,session:H,signal:Ct,telemetry:!0}));await st({result:yt,session:H,sessionId:H.id||C,autoCompleted:!1});return}if(D.autoProcessingError)throw xr(D.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:D.autoProcessingError.checkoutMethod});if(!$r(Me))throw Uo(Me);await st({result:jr(Me,C),session:Me,sessionId:Me.id||C,autoCompleted:!1});return}if(h.autoProcessingError){let B=h.autoProcessingError.nextActionRedirectUrl;if(h.autoProcessingError.type==="3ds_required"&&B&&C&&ve){let de=await at(yt=>Rs({billingApiUrl:Ee,sessionId:C,nonce:ve,nextActionRedirectUrl:B,signal:yt}));if(de.status==="declined")throw xr({type:de.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:de.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let Me=await new Li.PaymentAPI(Ee).waitForCheckoutSessionCompletion(C,{initialDelayMs:0,nonce:ve}),lt=no(Me,H);if(!$r(lt))throw xr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await st({result:jr(lt,C),session:lt,sessionId:lt.id||C,autoCompleted:!1});return}throw xr(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(Y?.fromCreateSession&&h.autoProcessingAttempted===!0)throw xr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let x=await Yo({billingApiUrl:Ee,sessionId:C??H.id,session:H,nonce:ve});if(x.type==="next_action_required"&&ve){let B=C??H.id,de=await at(D=>Go(x,{billingApiUrl:Ee,sessionId:B,nonce:ve,session:H,signal:D,telemetry:!0}));await st({result:de,session:H,sessionId:H.id||B,autoCompleted:!1});return}if(x.type!=="success")throw xr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await st({result:x.result,session:H,sessionId:H.id||C,autoCompleted:!1})}catch(x){let B=H.id||C,de=eo(Ia(x),B);if(de.code==="three_ds_aborted")return;if(de.code==="checkout_processing_timeout"){if(!ie.current)return;he(de.message),Je(()=>He.current?.(de));return}await $e(de,{emitDecline:!0,method:de.checkoutMethod??Ea}),vp(de,B)&&B&&ie.current&&we({sessionId:B,errorMessage:de.message,nonce:ve||void 0,payPalOrderId:de.orderId})}},[t,Ee,at,$e,st]),Lt=(0,ut.useCallback)(async h=>{if(le.onClick?.(h),!(h.defaultPrevented||ae||Re)){if(we(null),he(null),e&&We){let C=new lr.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await $e(C),ie.current&&(ce(null),Pe(null));return}if(!e&&!We){let C=new lr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $e(C),ie.current&&(ce(null),Pe(null));return}Ie(!0),Pe(null),J(!1),ce("processing");try{let C=new Li.PaymentAPI(Ee);if(e){let Y=await C.getUnifiedCheckoutSession(e,t);await vt(Y,e);return}try{let Y=await C.createAndFetchSession({...We});await vt(Y,Y.data.session?.id??null,{fromCreateSession:!0})}catch(Y){if(ei(Y)==="session_auto_completed"){await st({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Y}}catch(C){await $e(eo(Pp(C,"Automatic payment failed. Please try again."),e))}finally{ie.current&&(ce(null),Pe(null),Ie(!1))}}},[le.onClick,We,ae,Re,t,vt,Ee,e,$e,st]),ht=(0,ut.useCallback)(h=>{let C=te.current;we(null),it.current?.({result:h,session:null,sessionId:C?.sessionId??null,autoCompleted:!1})},[]),Tt=(0,ut.useCallback)(h=>{He.current?.(h)},[]),V=(0,ut.useCallback)(h=>{je.current?.(h)},[]),be=(0,ut.useMemo)(()=>(0,lr.resolveTheme)(P),[P]),Qe=(0,ut.useMemo)(()=>{let h=be?.buttonsLayout??(0,lr.resolveButtonsLayoutTheme)(K);return k?{...h,...k,cardButton:{...h.cardButton,...k.cardButton}}:h},[be,K,k]),Z=(0,ut.useMemo)(()=>{let h=be?.appearance;return w?h?{...h,...w,variables:{...h.variables,...w.variables}}:w:h},[w,be]),Ne=Z?.variables,bt=Ne?.colorPrimary??"#4A49FF",Ye=Ne?.colorPrimaryHover??Qo(bt,.12),_t=Ne?.borderRadius??"8px";return(0,sr.jsxs)(sr.Fragment,{children:[(0,sr.jsx)("button",{...le,type:De,onClick:Lt,disabled:ae||Re,"aria-busy":Re,style:{width:"100%",...Se===void 0?{boxSizing:"border-box",height:bp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Qe.cardButton,...qs({themeBundle:be,resolvedPrimaryColor:bt,resolvedBorderRadius:_t,submitButtonStyle:Qe.submitButton,explicitPrimaryColor:Ne?.colorPrimary}),fontSize:Qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ae||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:ae||Re?.6:1,...Ze},onMouseEnter:h=>{le.onMouseEnter?.(h),!h.defaultPrevented&&!ae&&!Re&&(be||Ne?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Ye)},onMouseLeave:h=>{le.onMouseLeave?.(h),!h.defaultPrevented&&(be||Ne?.colorPrimary)&&(h.currentTarget.style.backgroundColor=bt)},onMouseDown:h=>{le.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{le.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,sr.jsx)(Oo,{content:Se})}),ee&&(0,sr.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ee}),_e&&(0,sr.jsx)(zn,{status:_e,errorMessage:ue,authorized:Ae}),U&&(0,sr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&we(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,sr.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,sr.jsx)(Oi,{sessionId:U.sessionId,nonce:U.nonce,checkoutMode:"full",billingApiUrl:Ee,locale:_,theme:P,...Z?{appearance:Z}:{},buttonsTheme:K,buttonsStyles:k,initialErrorMessage:U.errorMessage,initialPayPalOrderId:U.payPalOrderId,cardTitleContent:null,onComplete:ht,onError:Tt,onDecline:V})})})]})}var Ui=require("@flopay/js/card-setup"),Zn=require("@flopay/shared"),At=require("react");var Wc={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function Ni(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?Wc.dark:Wc.light,a=t.colorText??(r?"#F1F5F9":"#262833"),i=e.appearance.rules?.[".Label"];return{panel:{...n.background===void 0?{}:{background:n.background},...n.backgroundColor===void 0?{}:{backgroundColor:n.backgroundColor},...n.border===void 0?{}:{border:n.border},...n.borderRadius===void 0?{}:{borderRadius:n.borderRadius},...n.boxShadow===void 0?{}:{boxShadow:n.boxShadow},color:a,...t.fontFamily?{fontFamily:t.fontFamily}:{}},spinnerTrackColor:e.buttonsLayout.cardInputBorder??(r?"#374151":"#e5e7eb"),spinnerAccentColor:t.colorPrimary??"#4A49FF",labelColors:{processing:a,success:o.success,error:o.error},noteColor:i?.color??a}}var Br=require("react/jsx-runtime"),Ua=class extends Zn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Jr(e,t={}){let n=e instanceof Zn.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 Ua(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:i=null,onReady:c,onComplete:p,onDecline:u,onCancel:g,onValidation:b,onError:T}){let[I,S]=(0,At.useState)(null),[A,_]=(0,At.useState)(null),[P,w]=(0,At.useState)(null),[K,k]=(0,At.useState)(null),[ge,z]=(0,At.useState)(null),X=(0,At.useRef)(!1),Se=(0,At.useRef)(!1),ae=(0,At.useMemo)(()=>typeof o=="object"?void 0:(0,Zn.resolveTheme)(o),[o]),De=(0,At.useMemo)(()=>typeof o=="object"?o:ae?ea({appearance:ae.appearance,buttonsStyles:ae.buttonsLayout,layout:"default"}):null,[ae,o]),Ze=(0,At.useMemo)(()=>ki(ae?.buttonsLayout.cardFormContainer,a),[ae,a]),le=(0,At.useMemo)(()=>ae?Ni(ae):void 0,[ae]),Ee=(0,At.useRef)(c),We=(0,At.useRef)(T),Re=(0,At.useRef)(p),Ie=(0,At.useRef)(u),_e=(0,At.useRef)(g),ce=(0,At.useRef)(b),ue=(0,At.useRef)(!1),Pe=(0,At.useRef)(!1),Ae=(0,At.useRef)(0);return Ee.current=c,We.current=T,Re.current=p,Ie.current=u,_e.current=g,ce.current=b,(0,At.useEffect)(()=>{let J=Ae.current+1;return Ae.current=J,()=>{queueMicrotask(()=>{Ae.current===J&&(ue.current||Pe.current||(Pe.current=!0,Je(()=>{_e.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,At.useEffect)(()=>{let J=!0,ee=new Ui.PaymentAPI((0,Zn.resolveBillingApiUrl)(n),{telemetry:r});return S(null),_(null),w(null),ue.current=!1,Pe.current=!1,(async()=>{try{if(!e.trim())throw new Zn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Zn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let he=await ee.getUnifiedCheckoutSession(e,t);if(!J)return;let U=he.data.session;if(!U||!(0,Zn.isCardSetupCheckoutSession)(U))throw new Zn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let we=U.vault;if(we?.html?.trim()||(we=await ee.getVaultCapture(e,t)),!we.html?.trim())throw new Zn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!J)return;_(we),S(new Ui.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(he){if(!J)return;let U=Jr(he);ue.current=!0,w(U),Je(()=>We.current?.(U))}})(),()=>{J=!1,ee.destroy()}},[n,t,e,r]),(0,At.useEffect)(()=>{if(!I)return;let J=!1;Se.current=!1,X.current=!1;let ee=I.on("submitting",()=>{X.current=!0,z(null),k("processing")}),he=I.on("complete",ie=>{ue.current=!0,X.current=!1,k("success"),(async()=>(await new Promise(Te=>setTimeout(Te,600)),!Se.current&&(Se.current=!0,Je(()=>{Re.current?.({status:"succeeded",sessionId:e,...ie.paymentMethod?{paymentMethod:ie.paymentMethod}:{}})}),J||k(null))))()}),U=I.on("decline",ie=>{ue.current=!0,X.current=!1,z(ie.message??null),k("error"),Je(()=>{Ie.current?.({status:"declined",sessionId:e,...ie.declineReason?{reason:ie.declineReason}:{},...ie.message?{message:ie.message}:{}})}),(async()=>(await new Promise(Te=>setTimeout(Te,400)),J||k(null)))()}),we=I.on("challenge_dismissed",()=>{k(null)});return()=>{J=!0,ee(),he(),U(),we()}},[I,e]),P?(0,Br.jsx)("div",{role:"alert",children:P.message}):!I||!A?.html?(0,Br.jsx)(Br.Fragment,{children:i}):(0,Br.jsxs)(Br.Fragment,{children:[K&&(0,Br.jsx)(zn,{status:K,errorMessage:ge,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...le?{theme:le}:{}}),(0,Br.jsx)(lo,{capture:I,html:A.html,messageToken:A.messageToken,expectedOrigin:A.expectedOrigin,theme:De,containerStyle:Ze,onReady:()=>{Je(()=>Ee.current?.())},onValidation:J=>{Je(()=>ce.current?.(J))},onError:J=>{if(!J)return;X.current&&(X.current=!1,z(J),k("error"),setTimeout(()=>k(null),400));let ee=Jr(new Error(J),{code:"card_setup_widget_failed",retryable:!0});Je(()=>We.current?.(ee))}})]})}var Kc=require("@flopay/js/card-setup"),co=require("@flopay/shared"),Gc=require("@paypal/paypal-js"),ko=require("react");var Xc=require("react/jsx-runtime");function Yc({clientId:e,environment:t,currency:n,sessionId:r,nonce:o,billingApiUrl:a,telemetry:i,customer:{userId:c,email:p},onSubmitting:u,onConfirmed:g,onFailed:b,onAbandoned:T}){let I=(0,ko.useRef)(null),S=(0,ko.useRef)({onSubmitting:u,onConfirmed:g,onFailed:b,onAbandoned:T});S.current={onSubmitting:u,onConfirmed:g,onFailed:b,onAbandoned:T};let[A]=(0,ko.useState)(()=>Kr().inAppBrowser);return(0,ko.useEffect)(()=>{let _=!0,P,w=new Kc.PaymentAPI(a,{telemetry:i}),K={userId:c,email:p};return(async()=>{try{let k=await(0,Gc.loadScript)({clientId:e,...n?{currency:n.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),ge=I.current;if(!_||!ge)return;if(!k?.Buttons)throw new co.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let z=k.Buttons({createVaultSetupToken:async()=>{S.current.onSubmitting();let X=await w.createSessionIntent(r,o,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:co.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(X.provider!=="paypal"||X.providerObjectType!=="setup_token")throw new co.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return X.providerObjectId},onApprove:async X=>{let Se=X.vaultSetupToken;if(!Se)throw new co.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let ae=await w.processPayment(K.userId,{sessionId:r,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:Se,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:co.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:K});if(!ae.ok)throw new co.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:ae.status});_&&S.current.onConfirmed()},onCancel:()=>{_&&S.current.onAbandoned()},onError:X=>{if(!_)return;let{popupBlocked:Se}=oo(X,{inAppBrowser:A,handoffObserved:!1});S.current.onFailed(Se?new Error(ro("PayPal",!0,A)):X,{code:Se?"popup_blocked":"paypal_setup_failed",retryable:!0})}});P=()=>z.close(),await z.render(ge)}catch(k){if(!_)return;S.current.onFailed(k,{code:"paypal_unavailable",retryable:!0})}})(),()=>{_=!1,P?.().catch(()=>{}),w.destroy()}},[a,e,n,p,t,A,o,r,i,c]),(0,Xc.jsx)("div",{ref:I,"data-flopay-paypal-setup":""})}var Zc=require("@flopay/js/card-setup"),na=require("@flopay/shared"),Dr=require("@stripe/react-stripe-js"),Qc=require("@stripe/stripe-js"),In=require("react");var Sn=require("react/jsx-runtime"),eu={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"}},Ys=new Map;function Sp(e){let t=Ys.get(e);if(t)return t;let n=(0,Qc.loadStripe)(e).catch(r=>{throw Ys.delete(e),r});return Ys.set(e,n),n}var wp={night:"night",flat:"flat"};function kp(e){return e?{theme:wp[e.theme??"default"]??"stripe",...e.variables?{variables:e.variables}:{},...e.rules?{rules:e.rules}:{}}:void 0}function Rp(e){return Po(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function Jc(e){return e==="paypal"?"PayPal":(0,na.getStripeMethodDisplayName)(e)}function _p(){return typeof window>"u"?"":window.location.href}var Ep={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function tu(e){let{publishableKey:t,method:n,currency:r,futureUse:o,futureUseUnsupported:a,appearance:i}=e,[c]=(0,In.useState)(()=>Sp(t)),p=(0,In.useMemo)(()=>{let u=kp(i),g=(0,na.resolveSetupFutureUsage)({futureUse:o,futureUseUnsupported:a},n,"setup");return{mode:"setup",currency:r.toLowerCase(),paymentMethodTypes:eu[n]?.types??[n],...g?{setupFutureUsage:g}:{},...u?{appearance:u}:{}}},[i,r,o,a,n]);return(0,Sn.jsx)(Dr.Elements,{stripe:c,options:p,children:(0,Sn.jsx)(Ip,{...e})})}function Ip({method:e,category:t,sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,appearance:i,themeId:c,buttonsLayout:p,onSubmitting:u,onConfirmed:g,onDeclined:b,onFailed:T,onValidation:I,onUnavailable:S}){let A=(0,Dr.useStripe)(),_=(0,Dr.useElements)(),[P,w]=(0,In.useState)(!1),[K,k]=(0,In.useState)("loading"),[ge,z]=(0,In.useState)(!1),[X,Se]=(0,In.useState)(!1),ae=(0,In.useRef)(!1),[De]=(0,In.useState)(()=>Kr()),[Ze,le]=(0,In.useState)(!1),Ee=(0,In.useCallback)((ue,Pe)=>{if(oo(ue,{inAppBrowser:De.inAppBrowser,handoffObserved:!1}).popupBlocked){le(!0),T(new Error(ro(Jc(e),!0,De.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}T(Pe.message===void 0?ue:new Error(Pe.message),{code:Pe.code,retryable:!0})},[De.inAppBrowser,e,T]),We=(0,In.useCallback)(async()=>{if(!(!A||!_||ae.current)){ae.current=!0,w(!0);try{let ue=await _.submit();if(ue.error){I(ue.error.message??null);return}u();let Pe=await new Zc.PaymentAPI(o,{telemetry:a}).createSessionIntent(n,r,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(Pe.provider!=="stripe"||Pe.intentKind!=="setup")throw new na.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let Ae=await A.confirmSetup({elements:_,clientSecret:Pe.clientSecret,confirmParams:{return_url:_p()},redirect:"if_required"});if(Ae.error){Rp(Ae.error)?b({...Ae.error.decline_code||Ae.error.code?{reason:Ae.error.decline_code??Ae.error.code}:{},...Ae.error.message?{message:Ae.error.message}:{}}):Ee(Ae.error,{code:"payment_method_setup_provider_failed",message:Ae.error.message??"The payment method could not be saved."});return}g()}catch(ue){Ee(ue,{code:"payment_method_setup_failed"})}finally{ae.current=!1,w(!1)}}},[o,t,_,e,r,g,b,u,I,Ee,n,A,a]),Re=eu[e]?.wallet,Ie=Re==="paypal"&&ni(De,"auto",Ze?"blocked":De.popupCapability)==="redirect",_e=i?.variables?.borderRadius??p?.cardButton?.borderRadius??8;if(t==="wallet"&&Re&&!Ie)return(0,Sn.jsxs)(Sn.Fragment,{children:[(0,Sn.jsx)(Zo,{}),(0,Sn.jsx)(Aa,{state:K,borderRadius:_e,children:(0,Sn.jsx)(Dr.ExpressCheckoutElement,{options:{...Ci,paymentMethods:vi([e])},onReady:ue=>{let Pe=Ta(ue,[Re]);k(Pe),Pe==="unavailable"&&S()},onLoadError:()=>{k("load_error"),S()},onConfirm:()=>{We()}})})]});let ce=Jc(e);return(0,Sn.jsxs)(Sn.Fragment,{children:[ge?(0,Sn.jsx)(Pi,{method:e,themeId:c,hasNextStep:!0,highlighted:X,disabled:P,onClick:()=>Se(ue=>!ue),backgroundColor:p?.cardButton?.backgroundColor,borderColor:p?.cardInputBorder,textColor:p?.cardButton?.color,borderRadius:_e}):null,(0,Sn.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!X,style:X?{display:"flex",flexDirection:"column"}:Ep,children:[(0,Sn.jsx)(Dr.PaymentElement,{options:{layout:Si},onReady:()=>z(!0),onLoadError:()=>S(),onChange:ue=>{ue.complete&&I(null)}}),(0,Sn.jsx)(wi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!A||!_||P||!X,onClick:()=>{We()},color:i?.variables?.colorPrimary??"#4A49FF",borderRadius:i?.variables?.borderRadius??"8px",style:p?.submitButton,children:P?"Saving\u2026":`Save ${ce}`})]})]})}var za=require("@flopay/js/card-setup"),Pn=require("@flopay/shared"),ze=ls(require("react"),1);var nu=require("@flopay/shared"),Tp=new Set(["apple_pay","google_pay","link","paypal","amazon_pay"]),Ap=new Set(["wallet","apm"]);function ra(e){return typeof e=="string"&&e.trim().length>0}function Mp(e){if(typeof e!="object"||e===null)return!1;let t=e;return ra(t.family)&&ra(t.paymentMethodType)}function xp(e){let n=e.raw?.data?.currency;return ra(n)?n.trim().toUpperCase():null}function ru(e){let t=xp(e),n=e.data.session?.advertisedPaymentMethods;if(!Array.isArray(n))return{card:!0,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]};let r={card:!1,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]},o=new Set;for(let a of n){if(!Mp(a)||o.has(a.paymentMethodType))continue;let{family:i,paymentMethodType:c,providerType:p,publishableKey:u}=a;if(i==="card"){if(c!=="card")continue;r.card=!0}else if(Ap.has(i)){if(p!=="stripe"||c==="card"||!ra(u))continue;if(t===null){r.skippedForMissingCurrency.includes(c)||r.skippedForMissingCurrency.push(c);continue}r.stripe.push({method:c,publishableKey:u,currency:t})}else if(i==="paypal"){if(c!==nu.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE||p!=="paypal"||!ra(u))continue;r.paypal={clientId:u,...ra(a.environment)?{environment:a.environment}:{}}}else continue;o.add(c)}return r.paypal&&(r.stripe=r.stripe.filter(a=>a.method!=="paypal")),r}function zi(e){return[...e.card?["card"]:[],...e.stripe.map(t=>t.method),...e.paypal?["paypal"]:[]]}function ou(e){return zi(e).length>0}function qi(e){return Tp.has(e)?"wallet":"apm"}var Fp=["setup_intent","setup_intent_client_secret","redirect_status"];function au(){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 iu(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let n of Fp)e.searchParams.has(n)&&(e.searchParams.delete(n),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}function su(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 Qt=require("react/jsx-runtime"),Bp=15,Dp=2e3;function Op(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Xs(e){return new Promise(t=>setTimeout(t,e))}async function Lp(e,t,n){if(!t.trim())throw new Pn.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!n.trim())throw new Pn.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,Pn.isCardSetupCheckoutSession)(o))throw new Pn.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let a=ru(r);if(!ou(a)){let{skippedForMissingCurrency:i}=a,c=i.length>0?`FloPay: this setup session advertises only Stripe methods (${i.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new Pn.FloPayError(c,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:o,advertisement:a}}async function Np(e,t,n,r){let o=t.vault??null;if(o?.html?.trim()||(o=await e.getVaultCapture(n,r)),!o.html?.trim())throw new Pn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return o}var Vi=class extends ze.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 lu({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,theme:i="modern-light",containerStyle:c,loading:p=null,onReady:u,onComplete:g,onDecline:b,onCancel:T,onValidation:I,onError:S}){let[A]=(0,ze.useState)(au),[_,P]=(0,ze.useState)(null),[w,K]=(0,ze.useState)(!1),[k,ge]=(0,ze.useState)(null),[z,X]=(0,ze.useState)(null),[Se,ae]=(0,ze.useState)(null),[De,Ze]=(0,ze.useState)(null),[le,Ee]=(0,ze.useState)(()=>new Set),We=(0,ze.useRef)(le),Re=(0,ze.useRef)(null);Re.current=_;let Ie=(0,ze.useRef)(!1),_e=(0,ze.useRef)(!1),ce=(0,ze.useRef)(!1),ue=(0,ze.useRef)(!1),Pe=(0,ze.useRef)(0),Ae=(0,ze.useRef)(0),J=(0,ze.useRef)(!1),ee=(0,ze.useMemo)(()=>typeof i=="object"?void 0:(0,Pn.resolveTheme)(i),[i]),he=(0,ze.useMemo)(()=>typeof i=="object"?i:ee?ea({appearance:ee.appearance,buttonsStyles:ee.buttonsLayout,layout:"default"}):null,[ee,i]),U=(0,ze.useMemo)(()=>ki(ee?.buttonsLayout.cardFormContainer,c),[ee,c]),we=(0,ze.useMemo)(()=>ee?Ni(ee):void 0,[ee]),ie=(0,ze.useRef)({sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:u,onComplete:g,onDecline:b,onCancel:T,onValidation:I,onError:S});ie.current={sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:u,onComplete:g,onDecline:b,onCancel:T,onValidation:I,onError:S},(0,ze.useEffect)(()=>{J.current=!0;let x=Pe.current+1;return Pe.current=x,()=>{J.current=!1,Ae.current+=1,queueMicrotask(()=>{Pe.current===x&&(ce.current||ue.current||(ue.current=!0,Je(()=>{ie.current.onCancel?.({status:"cancelled",sessionId:n})})))})}},[n]);let Te=(0,ze.useCallback)((x,B)=>{ce.current=!0,Ie.current=!1,Ze({status:"success",wording:x,message:null}),(async()=>(await Xs(600),!_e.current&&(_e.current=!0,Je(()=>{ie.current.onComplete?.({status:"succeeded",sessionId:ie.current.sessionId,...B?{paymentMethod:B}:{}})}),J.current&&Ze(null))))()},[]),te=(0,ze.useCallback)((x,B)=>{ce.current=!0,Ie.current=!1,Ze({status:"error",wording:x,message:B.message??null}),Je(()=>{ie.current.onDecline?.({status:"declined",sessionId:ie.current.sessionId,...B.reason?{reason:B.reason}:{},...B.message?{message:B.message}:{}})}),(async()=>(await Xs(400),J.current&&Ze(null)))()},[]),it=(0,ze.useCallback)((x,B)=>{Ie.current?(Ie.current=!1,Ze({status:"error",wording:x,message:B.message}),setTimeout(()=>{J.current&&Ze(null)},400)):Ze(null),Je(()=>ie.current.onError?.(B))},[]),He=(0,ze.useCallback)(async x=>{let B=Ae.current+1;Ae.current=B;let de=()=>!J.current||B!==Ae.current;Ie.current=!0,Ze({status:"processing",wording:"payment_method",message:null});let D=new za.PaymentAPI((0,Pn.resolveBillingApiUrl)(ie.current.billingApiUrl),{telemetry:ie.current.telemetry});try{for(let Me=0;Me<Bp;Me+=1){if((Me>0||x.waitFirst)&&await Xs(Dp),de())return;let lt=await D.getUnifiedCheckoutSession(ie.current.sessionId,ie.current.nonce);if(de())return;let yt=lt.data.session?.status;if(yt==="complete"){K(!0),Te("payment_method");return}if(yt==="expired")throw new Pn.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Pn.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(Me){if(de())return;let lt=Me instanceof Pn.FloPayError&&Me.code==="payment_method_setup_unverified";it("payment_method",Jr(Me,lt?{retryable:!0}:{}))}finally{D.destroy()}},[it,Te]);(0,ze.useEffect)(()=>{let x=!0,B=new za.PaymentAPI((0,Pn.resolveBillingApiUrl)(o),{telemetry:a});P(null),K(!1),ge(null),X(null),ae(null);let de=new Set;return We.current=de,Ee(de),ce.current=!1,ue.current=!1,_e.current=!1,(async()=>{try{let{session:D,advertisement:Me}=await Lp(B,n,r);if(!x)return;let lt={advertisement:Me,customer:Op(D),...D.futureUse?{futureUse:D.futureUse}:{},...D.futureUseUnsupported?{futureUseUnsupported:D.futureUseUnsupported}:{}};if(A){if(iu(),D.status==="complete"){K(!0),P(lt),Te("payment_method");return}A.failed?te("payment_method",{reason:"redirect_failed"}):He({waitFirst:!0})}let yt=Me.card?await Np(B,D,n,r):null;if(!x)return;P(lt),yt&&(X(yt),ge(new za.PciVaultCardCapture({sessionId:n,operation:"card_setup",telemetry:a})))}catch(D){if(!x)return;let Me=Jr(D);ce.current=!0,ae(Me),Je(()=>ie.current.onError?.(Me))}})(),()=>{x=!1,B.destroy()}},[o,r,A,te,Te,n,a,He]),(0,ze.useEffect)(()=>{if(!k)return;Ie.current=!1;let x=k.on("submitting",()=>{Ie.current=!0,Ze({status:"processing",wording:"card",message:null})}),B=k.on("complete",Me=>{Te("card",Me.paymentMethod)}),de=k.on("decline",Me=>{te("card",{...Me.declineReason?{reason:Me.declineReason}:{},...Me.message?{message:Me.message}:{}})}),D=k.on("challenge_dismissed",()=>{Ze(null)});return()=>{x(),B(),de(),D()}},[k,te,Te]);let je=(0,ze.useCallback)((x,B,de)=>{if(de.retryable){it("payment_method",Jr(B,de));return}if(We.current.has(x))return;let D=new Set(We.current);D.add(x),We.current=D,Ee(D);let Me=Re.current?.advertisement,lt=Me?zi(Me).some(yt=>!D.has(yt)):!1;it("payment_method",Jr(B,{code:de.code,retryable:lt}))},[it]),at=(0,ze.useMemo)(()=>({onSubmitting:()=>{Ie.current=!0,Ze({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{He({waitFirst:!1})},onDeclined:x=>te("payment_method",x),onValidation:x=>{Je(()=>ie.current.onValidation?.(x))},onAbandoned:()=>{Ie.current=!1,Ze(null)}}),[te,He]),Ke=(0,ze.useRef)(je);Ke.current=je;let st=(0,ze.useRef)(new Map),$e=x=>{let B=st.current.get(x);if(B)return B;let de=(D,Me)=>Ke.current(x,D,Me);return st.current.set(x,de),de},vt=(0,ze.useCallback)(x=>{if(We.current.has(x))return;let B=new Set(We.current);B.add(x),We.current=B,Ee(B);let de=Re.current?.advertisement;de&&zi(de).some(Me=>!B.has(Me))||it("payment_method",Jr(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[it]),Lt=(0,ze.useRef)(vt);Lt.current=vt;let ht=(0,ze.useRef)(new Map),Tt=x=>{let B=ht.current.get(x);if(B)return B;let de=()=>Lt.current(x);return ht.current.set(x,de),de},V=De?(0,Qt.jsx)(zn,{status:De.status,errorMessage:De.message,...su(De.wording),successNote:null,...we?{theme:we}:{}}):null;if(Se)return(0,Qt.jsx)("div",{role:"alert",children:Se.message});if(!_||w)return(0,Qt.jsxs)(Qt.Fragment,{children:[V,_?null:p]});let{advertisement:be,customer:Qe,futureUse:Z,futureUseUnsupported:Ne}=_,bt=(0,Pn.resolveBillingApiUrl)(o),Ye=a===void 0?{}:{telemetry:a},_t=be.stripe.filter(({method:x})=>!le.has(x)),j=le.has("paypal")?null:be.paypal,h=!!(be.card&&k&&z?.html),C=({method:x,publishableKey:B,currency:de})=>(0,Qt.jsx)("div",{"data-flopay-payment-method":x,style:{display:"contents"},children:(0,Qt.jsx)(Vi,{onFailed:$e(x),children:(0,Qt.jsx)(ze.Suspense,{fallback:null,children:(0,Qt.jsx)(e,{method:x,category:qi(x),publishableKey:B,currency:de,...Z?{futureUse:Z}:{},...Ne?{futureUseUnsupported:Ne}:{},sessionId:n,nonce:r,billingApiUrl:bt,...Ye,...ee?{appearance:ee.appearance,buttonsLayout:ee.buttonsLayout}:{},...typeof i=="string"?{themeId:i}:{},...at,onFailed:$e(x),onUnavailable:Tt(x)})})})},x),Y=_t.filter(({method:x})=>qi(x)==="wallet"),H=_t.filter(({method:x})=>qi(x)!=="wallet"),ve=_t.length>0||j!==null;return(0,Qt.jsxs)(Qt.Fragment,{children:[V,ve?(0,Qt.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Y.map(C),j?(0,Qt.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,Qt.jsx)(Vi,{onFailed:$e("paypal"),children:(0,Qt.jsx)(ze.Suspense,{fallback:null,children:(0,Qt.jsx)(t,{clientId:j.clientId,...j.environment?{environment:j.environment}:{},...be.currency?{currency:be.currency}:{},sessionId:n,nonce:r,billingApiUrl:bt,customer:Qe,...Ye,...at,onFailed:$e("paypal"),onUnavailable:Tt("paypal")})})})}):null,H.map(C)]}):null,h&&ve?(0,Qt.jsx)(Ri,{label:"or add a card"}):null,h&&k&&z?.html?(0,Qt.jsx)("div",{"data-flopay-payment-method":"card",children:(0,Qt.jsx)(lo,{capture:k,html:z.html,messageToken:z.messageToken,expectedOrigin:z.expectedOrigin,theme:he,containerStyle:U,onReady:()=>{Je(()=>ie.current.onReady?.())},onValidation:x=>{Je(()=>ie.current.onValidation?.(x))},onError:x=>{x&&it("card",Jr(new Error(x),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var uu=require("react/jsx-runtime"),Up={StripeSetupMethod:tu,PayPalSetupMethod:Yc};function cu(e){return(0,uu.jsx)(lu,{...e,branches:Up})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}return(0,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&I(ra),n&&(r||o)&&I(ra),n&&(0,O.jsx)("button",{type:"button",onClick:()=>{e?.("card"),M(!0)},style:{width:"100%",...b,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:w.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...w.cardButton},onMouseDown:C=>{C.currentTarget.style.transform="scale(0.985)"},onMouseUp:C=>{C.currentTarget.style.transform="scale(1)"},children:(0,O.jsx)(No,{content:p})}),(0,O.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var lr=require("react/jsx-runtime"),Sp=44;function Kc(e){return new Promise(t=>setTimeout(t,e))}function wp(e,t){return e instanceof cr.FloPayError?e:new cr.FloPayError(e instanceof Error?e.message:t,"api_error")}function kp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Rp(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function Gc({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:i,items:c,subscriptions:p,account:u,successUrl:h,cancelUrl:P,couponCodes:M,tagsData:_,utmMetadata:w,billingApiUrl:A,locale:I,theme:b,appearance:C,buttonsTheme:G,buttonsStyles:k,onSuccess:ye,onError:N,onDecline:H,children:_e,disabled:te=!1,type:Ne="button",style:Ye,...be}){let fe=(0,ut.useMemo)(()=>(0,cr.resolveBillingApiUrl)(A),[A]),We=(0,ut.useMemo)(()=>Rp({createSession:n,clientId:a,products:i,items:c,subscriptions:p,account:u,successUrl:h,cancelUrl:P,couponCodes:M,tagsData:_,utmMetadata:w}),[u,P,a,M,n,i,c,p,h,_,w]),[Te,Fe]=(0,ut.useState)(!1),[Ae,re]=(0,ut.useState)(null),[se,Ce]=(0,ut.useState)(null),[Be,Y]=(0,ut.useState)(!1),[Q,Pe]=(0,ut.useState)(null),[z,we]=(0,ut.useState)(null),J=(0,ut.useRef)(!0),Ee=(0,ut.useRef)(null),Z=(0,ut.useRef)(z),it=(0,ut.useRef)(ye),He=(0,ut.useRef)(N),Ve=(0,ut.useRef)(H),at=(0,ut.useCallback)(g=>hi(Ee,async S=>{try{return await g(S)}catch(K){throw S.aborted?lo(K):K}}),[]);(0,ut.useEffect)(()=>{Z.current=z},[z]),(0,ut.useEffect)(()=>{it.current=ye},[ye]),(0,ut.useEffect)(()=>{He.current=N},[N]),(0,ut.useEffect)(()=>{Ve.current=H},[H]),(0,ut.useEffect)(()=>(J.current=!0,()=>{J.current=!1,Ee.current?.abort()}),[]),(0,ut.useEffect)(()=>{if(typeof window>"u")return;let g=S=>{S.key==="Escape"&&we(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let Ke=(0,ut.useCallback)((g,S=Ta)=>{Ve.current?.(fn(S,g,{code:g.code,declineCode:g.declineCode}))},[]),st=(0,ut.useCallback)(async g=>{J.current&&(Ce(null),Y(g.result.status==="authorized"),re("success"),await Kc(600),J.current&&Je(()=>it.current?.(g)))},[]),je=(0,ut.useCallback)(async(g,S)=>{J.current&&(He.current?.(g),S?.emitDecline&&Ke(g,S.method),Ce(g.message),Y(!1),re("error"),await Kc(400))},[Ke]),St=(0,ut.useCallback)(async(g,S,K)=>{let W=g.data.session??null;if(!W)throw to(new cr.FloPayError("No session data returned","api_error"),S);let Se=W.clientSecret||t;if($r(W)){await st({result:jr(W,S),session:W,sessionId:W.id||S,autoCompleted:!1});return}if(W.status==="expired")throw to(ti(W),W.id||S);try{if(g.autoProcessingPending){let B=g.autoProcessingPending,oe=new Ui.PaymentAPI(fe),j=await at(gt=>oe.waitForCheckoutSessionCompletion(B.sessionId,{initialDelayMs:B.retryAfterMs,nonce:Se,statusUrl:B.statusUrl,signal:gt})),Ie=ro(j,W),tt=j.autoProcessingError?.type==="3ds_required"&&j.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:j.autoProcessingError.nextActionRedirectUrl}:null;if(tt&&S&&Se){let gt=await at(yt=>Xo(tt,{billingApiUrl:fe,sessionId:S,nonce:Se,session:W,signal:yt,telemetry:!0}));await st({result:gt,session:W,sessionId:W.id||S,autoCompleted:!1});return}if(j.autoProcessingError)throw Dr(j.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:j.autoProcessingError.checkoutMethod});if(!$r(Ie))throw qo(Ie);await st({result:jr(Ie,S),session:Ie,sessionId:Ie.id||S,autoCompleted:!1});return}if(g.autoProcessingError){let B=g.autoProcessingError.nextActionRedirectUrl;if(g.autoProcessingError.type==="3ds_required"&&B&&S&&Se){let oe=await at(gt=>Is({billingApiUrl:fe,sessionId:S,nonce:Se,nextActionRedirectUrl:B,signal:gt}));if(oe.status==="declined")throw Dr({type:oe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:oe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let Ie=await new Ui.PaymentAPI(fe).waitForCheckoutSessionCompletion(S,{initialDelayMs:0,nonce:Se}),tt=ro(Ie,W);if(!$r(tt))throw Dr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await st({result:jr(tt,S),session:tt,sessionId:tt.id||S,autoCompleted:!1});return}throw Dr(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(K?.fromCreateSession&&g.autoProcessingAttempted===!0)throw Dr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let F=await Jo({billingApiUrl:fe,sessionId:S??W.id,session:W,nonce:Se});if(F.type==="next_action_required"&&Se){let B=S??W.id,oe=await at(j=>Xo(F,{billingApiUrl:fe,sessionId:B,nonce:Se,session:W,signal:j,telemetry:!0}));await st({result:oe,session:W,sessionId:W.id||B,autoCompleted:!1});return}if(F.type!=="success")throw Dr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await st({result:F.result,session:W,sessionId:W.id||S,autoCompleted:!1})}catch(F){let B=W.id||S,oe=to(Aa(F),B);if(oe.code==="three_ds_aborted")return;if(oe.code==="checkout_processing_timeout"){if(!J.current)return;Pe(oe.message),Je(()=>He.current?.(oe));return}await je(oe,{emitDecline:!0,method:oe.checkoutMethod??Ta}),kp(oe,B)&&B&&J.current&&we({sessionId:B,errorMessage:oe.message,nonce:Se||void 0,payPalOrderId:oe.orderId})}},[t,fe,at,je,st]),Lt=(0,ut.useCallback)(async g=>{if(be.onClick?.(g),!(g.defaultPrevented||te||Te)){if(we(null),Pe(null),e&&We){let S=new cr.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await je(S),J.current&&(re(null),Ce(null));return}if(!e&&!We){let S=new cr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await je(S),J.current&&(re(null),Ce(null));return}Fe(!0),Ce(null),Y(!1),re("processing");try{let S=new Ui.PaymentAPI(fe);if(e){let K=await S.getUnifiedCheckoutSession(e,t);await St(K,e);return}try{let K=await S.createAndFetchSession({...We});await St(K,K.data.session?.id??null,{fromCreateSession:!0})}catch(K){if(ni(K)==="session_auto_completed"){await st({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw K}}catch(S){await je(to(wp(S,"Automatic payment failed. Please try again."),e))}finally{J.current&&(re(null),Ce(null),Fe(!1))}}},[be.onClick,We,te,Te,t,St,fe,e,je,st]),Pt=(0,ut.useCallback)(g=>{let S=Z.current;we(null),it.current?.({result:g,session:null,sessionId:S?.sessionId??null,autoCompleted:!1})},[]),Et=(0,ut.useCallback)(g=>{He.current?.(g)},[]),q=(0,ut.useCallback)(g=>{Ve.current?.(g)},[]),ve=(0,ut.useMemo)(()=>(0,cr.resolveTheme)(b),[b]),Qe=(0,ut.useMemo)(()=>{let g=ve?.buttonsLayout??(0,cr.resolveButtonsLayoutTheme)(G);return k?{...g,...k,cardButton:{...g.cardButton,...k.cardButton}}:g},[ve,G,k]),X=(0,ut.useMemo)(()=>{let g=ve?.appearance;return C?g?{...g,...C,variables:{...g.variables,...C.variables}}:C:g},[C,ve]),Ue=X?.variables,vt=Ue?.colorPrimary??"#4A49FF",Xe=Ue?.colorPrimaryHover??ta(vt,.12),kt=Ue?.borderRadius??"8px";return(0,lr.jsxs)(lr.Fragment,{children:[(0,lr.jsx)("button",{...be,type:Ne,onClick:Lt,disabled:te||Te,"aria-busy":Te,style:{width:"100%",..._e===void 0?{boxSizing:"border-box",height:Sp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Qe.cardButton,...js({themeBundle:ve,resolvedPrimaryColor:vt,resolvedBorderRadius:kt,submitButtonStyle:Qe.submitButton,explicitPrimaryColor:Ue?.colorPrimary}),fontSize:Qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:te||Te?"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:te||Te?.6:1,...Ye},onMouseEnter:g=>{be.onMouseEnter?.(g),!g.defaultPrevented&&!te&&!Te&&(ve||Ue?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Xe)},onMouseLeave:g=>{be.onMouseLeave?.(g),!g.defaultPrevented&&(ve||Ue?.colorPrimary)&&(g.currentTarget.style.backgroundColor=vt)},onMouseDown:g=>{be.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{be.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:(0,lr.jsx)(No,{content:_e})}),Q&&(0,lr.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Q}),Ae&&(0,lr.jsx)(Vn,{status:Ae,errorMessage:se,authorized:Be}),z&&(0,lr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&we(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,lr.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,lr.jsx)(Ni,{sessionId:z.sessionId,nonce:z.nonce,checkoutMode:"full",billingApiUrl:fe,locale:I,theme:b,...X?{appearance:X}:{},buttonsTheme:G,buttonsStyles:k,initialErrorMessage:z.errorMessage,initialPayPalOrderId:z.payPalOrderId,cardTitleContent:null,onComplete:Pt,onError:Et,onDecline:q})})})]})}var qi=require("@flopay/js/card-setup"),Sn=require("@flopay/shared"),It=require("react");var Yc={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function zi(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"),i=e.appearance.rules?.[".Label"];return{panel:{...n.background===void 0?{}:{background:n.background},...n.backgroundColor===void 0?{}:{backgroundColor:n.backgroundColor},...n.border===void 0?{}:{border:n.border},...n.borderRadius===void 0?{}:{borderRadius:n.borderRadius},...n.boxShadow===void 0?{}:{boxShadow:n.boxShadow},color:a,...t.fontFamily?{fontFamily:t.fontFamily}:{}},spinnerTrackColor:e.buttonsLayout.cardInputBorder??(r?"#374151":"#e5e7eb"),spinnerAccentColor:t.colorPrimary??"#4A49FF",labelColors:{processing:a,success:o.success,error:o.error},noteColor:i?.color??a}}var Lr=require("react/jsx-runtime"),qa=class extends Sn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Jr(e,t={}){let n=e instanceof Sn.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 qa(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 Xc({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:i=null,onReady:c,onComplete:p,onDecline:u,onCancel:h,onValidation:P,onError:M}){let[_,w]=(0,It.useState)(null),[A,I]=(0,It.useState)(null),[b,C]=(0,It.useState)(null),[G,k]=(0,It.useState)(null),[ye,N]=(0,It.useState)(null),H=(0,It.useRef)(!1),_e=(0,It.useRef)(!1),te=(0,It.useMemo)(()=>typeof o=="object"?void 0:(0,Sn.resolveTheme)(o),[o]),Ne=(0,It.useMemo)(()=>typeof o=="object"?o:te?na({appearance:te.appearance,buttonsStyles:te.buttonsLayout,layout:"default"}):null,[te,o]),Ye=(0,It.useMemo)(()=>_i(te?.buttonsLayout.cardFormContainer,a),[te,a]),be=(0,It.useMemo)(()=>te?zi(te):void 0,[te]),fe=(0,It.useRef)(c),We=(0,It.useRef)(M),Te=(0,It.useRef)(p),Fe=(0,It.useRef)(u),Ae=(0,It.useRef)(h),re=(0,It.useRef)(P),se=(0,It.useRef)(!1),Ce=(0,It.useRef)(!1),Be=(0,It.useRef)(0);return fe.current=c,We.current=M,Te.current=p,Fe.current=u,Ae.current=h,re.current=P,(0,It.useEffect)(()=>{let Y=Be.current+1;return Be.current=Y,()=>{queueMicrotask(()=>{Be.current===Y&&(se.current||Ce.current||(Ce.current=!0,Je(()=>{Ae.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,It.useEffect)(()=>{let Y=!0,Q=(0,Sn.resolveBillingApiUrl)(n),Pe=new qi.PaymentAPI(Q,{telemetry:r});return w(null),I(null),C(null),se.current=!1,Ce.current=!1,(async()=>{try{if(!e.trim())throw new Sn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Sn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let z=await Pe.getUnifiedCheckoutSession(e,t);if(!Y)return;let we=z.data.session;if(!we||!(0,Sn.isCardSetupCheckoutSession)(we))throw new Sn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let J=we.vault;(0,Sn.isMountableVaultBlock)(J)||(J=await Pe.getVaultCapture(e,t));let Ee=(0,Sn.resolveVaultMountOptions)(J,{billingApiUrl:Q,sessionId:e,nonce:t});if(!Ee)throw new Sn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!Y)return;I(Ee),w(new qi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(z){if(!Y)return;let we=Jr(z);se.current=!0,C(we),Je(()=>We.current?.(we))}})(),()=>{Y=!1,Pe.destroy()}},[n,t,e,r]),(0,It.useEffect)(()=>{if(!_)return;let Y=!1;_e.current=!1,H.current=!1;let Q=_.on("submitting",()=>{H.current=!0,N(null),k("processing")}),Pe=_.on("complete",J=>{se.current=!0,H.current=!1,k("success"),(async()=>(await new Promise(Ee=>setTimeout(Ee,600)),!_e.current&&(_e.current=!0,Je(()=>{Te.current?.({status:"succeeded",sessionId:e,...J.paymentMethod?{paymentMethod:J.paymentMethod}:{}})}),Y||k(null))))()}),z=_.on("decline",J=>{se.current=!0,H.current=!1,N(J.message??null),k("error"),Je(()=>{Fe.current?.({status:"declined",sessionId:e,...J.declineReason?{reason:J.declineReason}:{},...J.message?{message:J.message}:{}})}),(async()=>(await new Promise(Ee=>setTimeout(Ee,400)),Y||k(null)))()}),we=_.on("challenge_dismissed",()=>{k(null)});return()=>{Y=!0,Q(),Pe(),z(),we()}},[_,e]),b?(0,Lr.jsx)("div",{role:"alert",children:b.message}):!_||!A?.html?(0,Lr.jsx)(Lr.Fragment,{children:i}):(0,Lr.jsxs)(Lr.Fragment,{children:[G&&(0,Lr.jsx)(Vn,{status:G,errorMessage:ye,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...be?{theme:be}:{}}),(0,Lr.jsx)(co,{capture:_,html:A.html,messageToken:A.messageToken,expectedOrigin:A.expectedOrigin,verificationRequired:A.verificationRequired,theme:Ne,containerStyle:Ye,onReady:()=>{Je(()=>fe.current?.())},onValidation:Y=>{Je(()=>re.current?.(Y))},onError:Y=>{if(!Y)return;H.current&&(H.current=!1,N(Y),k("error"),setTimeout(()=>k(null),400));let Q=Jr(new Error(Y),{code:"card_setup_widget_failed",retryable:!0});Je(()=>We.current?.(Q))}})]})}var Jc=require("@flopay/js/card-setup"),uo=require("@flopay/shared"),Zc=require("@paypal/paypal-js"),Ro=require("react");var eu=require("react/jsx-runtime");function Qc({clientId:e,environment:t,currency:n,sessionId:r,nonce:o,billingApiUrl:a,telemetry:i,customer:{userId:c,email:p},onSubmitting:u,onConfirmed:h,onFailed:P,onAbandoned:M}){let _=(0,Ro.useRef)(null),w=(0,Ro.useRef)({onSubmitting:u,onConfirmed:h,onFailed:P,onAbandoned:M});w.current={onSubmitting:u,onConfirmed:h,onFailed:P,onAbandoned:M};let[A]=(0,Ro.useState)(()=>Kr().inAppBrowser);return(0,Ro.useEffect)(()=>{let I=!0,b,C=new Jc.PaymentAPI(a,{telemetry:i}),G={userId:c,email:p};return(async()=>{try{let k=await(0,Zc.loadScript)({clientId:e,...n?{currency:n.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),ye=_.current;if(!I||!ye)return;if(!k?.Buttons)throw new uo.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let N=k.Buttons({createVaultSetupToken:async()=>{w.current.onSubmitting();let H=await C.createSessionIntent(r,o,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:uo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(H.provider!=="paypal"||H.providerObjectType!=="setup_token")throw new uo.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return H.providerObjectId},onApprove:async H=>{let _e=H.vaultSetupToken;if(!_e)throw new uo.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let te=await C.processPayment(G.userId,{sessionId:r,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:_e,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:uo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:G});if(!te.ok)throw new uo.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:te.status});I&&w.current.onConfirmed()},onCancel:()=>{I&&w.current.onAbandoned()},onError:H=>{if(!I)return;let{popupBlocked:_e}=ao(H,{inAppBrowser:A,handoffObserved:!1});w.current.onFailed(_e?new Error(oo("PayPal",!0,A)):H,{code:_e?"popup_blocked":"paypal_setup_failed",retryable:!0})}});b=()=>N.close(),await N.render(ye)}catch(k){if(!I)return;w.current.onFailed(k,{code:"paypal_unavailable",retryable:!0})}})(),()=>{I=!1,b?.().catch(()=>{}),C.destroy()}},[a,e,n,p,t,A,o,r,i,c]),(0,eu.jsx)("div",{ref:_,"data-flopay-paypal-setup":""})}var nu=require("@flopay/js/card-setup"),oa=require("@flopay/shared"),Nr=require("@stripe/react-stripe-js"),ru=require("@stripe/stripe-js"),Mn=require("react");var _n=require("react/jsx-runtime"),ou={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"}},Js=new Map;function _p(e){let t=Js.get(e);if(t)return t;let n=(0,ru.loadStripe)(e).catch(r=>{throw Js.delete(e),r});return Js.set(e,n),n}var Ep={night:"night",flat:"flat"};function Ip(e){return e?{theme:Ep[e.theme??"default"]??"stripe",...e.variables?{variables:e.variables}:{},...e.rules?{rules:e.rules}:{}}:void 0}function Tp(e){return vo(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function tu(e){return e==="paypal"?"PayPal":(0,oa.getStripeMethodDisplayName)(e)}function Ap(){return typeof window>"u"?"":window.location.href}var Mp={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function au(e){let{publishableKey:t,method:n,currency:r,futureUse:o,futureUseUnsupported:a,appearance:i}=e,[c]=(0,Mn.useState)(()=>_p(t)),p=(0,Mn.useMemo)(()=>{let u=Ip(i),h=(0,oa.resolveSetupFutureUsage)({futureUse:o,futureUseUnsupported:a},n,"setup");return{mode:"setup",currency:r.toLowerCase(),paymentMethodTypes:ou[n]?.types??[n],...h?{setupFutureUsage:h}:{},...u?{appearance:u}:{}}},[i,r,o,a,n]);return(0,_n.jsx)(Nr.Elements,{stripe:c,options:p,children:(0,_n.jsx)(xp,{...e})})}function xp({method:e,category:t,sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,appearance:i,themeId:c,buttonsLayout:p,onSubmitting:u,onConfirmed:h,onDeclined:P,onFailed:M,onValidation:_,onUnavailable:w}){let A=(0,Nr.useStripe)(),I=(0,Nr.useElements)(),[b,C]=(0,Mn.useState)(!1),[G,k]=(0,Mn.useState)("loading"),[ye,N]=(0,Mn.useState)(!1),[H,_e]=(0,Mn.useState)(!1),te=(0,Mn.useRef)(!1),[Ne]=(0,Mn.useState)(()=>Kr()),[Ye,be]=(0,Mn.useState)(!1),fe=(0,Mn.useCallback)((se,Ce)=>{if(ao(se,{inAppBrowser:Ne.inAppBrowser,handoffObserved:!1}).popupBlocked){be(!0),M(new Error(oo(tu(e),!0,Ne.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}M(Ce.message===void 0?se:new Error(Ce.message),{code:Ce.code,retryable:!0})},[Ne.inAppBrowser,e,M]),We=(0,Mn.useCallback)(async()=>{if(!(!A||!I||te.current)){te.current=!0,C(!0);try{let se=await I.submit();if(se.error){_(se.error.message??null);return}u();let Ce=await new nu.PaymentAPI(o,{telemetry:a}).createSessionIntent(n,r,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(Ce.provider!=="stripe"||Ce.intentKind!=="setup")throw new oa.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let Be=await A.confirmSetup({elements:I,clientSecret:Ce.clientSecret,confirmParams:{return_url:Ap()},redirect:"if_required"});if(Be.error){Tp(Be.error)?P({...Be.error.decline_code||Be.error.code?{reason:Be.error.decline_code??Be.error.code}:{},...Be.error.message?{message:Be.error.message}:{}}):fe(Be.error,{code:"payment_method_setup_provider_failed",message:Be.error.message??"The payment method could not be saved."});return}h()}catch(se){fe(se,{code:"payment_method_setup_failed"})}finally{te.current=!1,C(!1)}}},[o,t,I,e,r,h,P,u,_,fe,n,A,a]),Te=ou[e]?.wallet,Fe=Te==="paypal"&&oi(Ne,"auto",Ye?"blocked":Ne.popupCapability)==="redirect",Ae=i?.variables?.borderRadius??p?.cardButton?.borderRadius??8;if(t==="wallet"&&Te&&!Fe)return(0,_n.jsxs)(_n.Fragment,{children:[(0,_n.jsx)(ea,{}),(0,_n.jsx)(xa,{state:G,borderRadius:Ae,children:(0,_n.jsx)(Nr.ExpressCheckoutElement,{options:{...wi,paymentMethods:Si([e])},onReady:se=>{let Ce=Ma(se,[Te]);k(Ce),Ce==="unavailable"&&w()},onLoadError:()=>{k("load_error"),w()},onConfirm:()=>{We()}})})]});let re=tu(e);return(0,_n.jsxs)(_n.Fragment,{children:[ye?(0,_n.jsx)(Ci,{method:e,themeId:c,hasNextStep:!0,highlighted:H,disabled:b,onClick:()=>_e(se=>!se),backgroundColor:p?.cardButton?.backgroundColor,borderColor:p?.cardInputBorder,textColor:p?.cardButton?.color,borderRadius:Ae}):null,(0,_n.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!H,style:H?{display:"flex",flexDirection:"column"}:Mp,children:[(0,_n.jsx)(Nr.PaymentElement,{options:{layout:ki},onReady:()=>N(!0),onLoadError:()=>w(),onChange:se=>{se.complete&&_(null)}}),(0,_n.jsx)(Ri,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!A||!I||b||!H,onClick:()=>{We()},color:i?.variables?.colorPrimary??"#4A49FF",borderRadius:i?.variables?.borderRadius??"8px",style:p?.submitButton,children:b?"Saving\u2026":`Save ${re}`})]})]})}var Va=require("@flopay/js/card-setup"),tn=require("@flopay/shared"),qe=ds(require("react"),1);var iu=require("@flopay/shared"),Fp=new Set(["apple_pay","google_pay","link","paypal","amazon_pay"]),Bp=new Set(["wallet","apm"]);function aa(e){return typeof e=="string"&&e.trim().length>0}function Dp(e){if(typeof e!="object"||e===null)return!1;let t=e;return aa(t.family)&&aa(t.paymentMethodType)}function Op(e){let n=e.raw?.data?.currency;return aa(n)?n.trim().toUpperCase():null}function su(e){let t=Op(e),n=e.data.session?.advertisedPaymentMethods;if(!Array.isArray(n))return{card:!0,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]};let r={card:!1,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]},o=new Set;for(let a of n){if(!Dp(a)||o.has(a.paymentMethodType))continue;let{family:i,paymentMethodType:c,providerType:p,publishableKey:u}=a;if(i==="card"){if(c!=="card")continue;r.card=!0}else if(Bp.has(i)){if(p!=="stripe"||c==="card"||!aa(u))continue;if(t===null){r.skippedForMissingCurrency.includes(c)||r.skippedForMissingCurrency.push(c);continue}r.stripe.push({method:c,publishableKey:u,currency:t})}else if(i==="paypal"){if(c!==iu.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE||p!=="paypal"||!aa(u))continue;r.paypal={clientId:u,...aa(a.environment)?{environment:a.environment}:{}}}else continue;o.add(c)}return r.paypal&&(r.stripe=r.stripe.filter(a=>a.method!=="paypal")),r}function Vi(e){return[...e.card?["card"]:[],...e.stripe.map(t=>t.method),...e.paypal?["paypal"]:[]]}function lu(e){return Vi(e).length>0}function ji(e){return Fp.has(e)?"wallet":"apm"}var Lp=["setup_intent","setup_intent_client_secret","redirect_status"];function cu(){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 uu(){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 du(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 en=require("react/jsx-runtime"),Np=15,Up=2e3;function zp(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Zs(e){return new Promise(t=>setTimeout(t,e))}async function qp(e,t,n){if(!t.trim())throw new tn.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!n.trim())throw new tn.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,tn.isCardSetupCheckoutSession)(o))throw new tn.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let a=su(r);if(!lu(a)){let{skippedForMissingCurrency:i}=a,c=i.length>0?`FloPay: this setup session advertises only Stripe methods (${i.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new tn.FloPayError(c,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:o,advertisement:a}}async function Vp(e,t,n,r,o){let a=t.vault??null;(0,tn.isMountableVaultBlock)(a)||(a=await e.getVaultCapture(n,r));let i=(0,tn.resolveVaultMountOptions)(a,{billingApiUrl:o,sessionId:n,nonce:r});if(!i)throw new tn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return i}var $i=class extends qe.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(n){this.props.onFailed(n,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function pu({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,theme:i="modern-light",containerStyle:c,loading:p=null,onReady:u,onComplete:h,onDecline:P,onCancel:M,onValidation:_,onError:w}){let[A]=(0,qe.useState)(cu),[I,b]=(0,qe.useState)(null),[C,G]=(0,qe.useState)(!1),[k,ye]=(0,qe.useState)(null),[N,H]=(0,qe.useState)(null),[_e,te]=(0,qe.useState)(null),[Ne,Ye]=(0,qe.useState)(null),[be,fe]=(0,qe.useState)(()=>new Set),We=(0,qe.useRef)(be),Te=(0,qe.useRef)(null);Te.current=I;let Fe=(0,qe.useRef)(!1),Ae=(0,qe.useRef)(!1),re=(0,qe.useRef)(!1),se=(0,qe.useRef)(!1),Ce=(0,qe.useRef)(0),Be=(0,qe.useRef)(0),Y=(0,qe.useRef)(!1),Q=(0,qe.useMemo)(()=>typeof i=="object"?void 0:(0,tn.resolveTheme)(i),[i]),Pe=(0,qe.useMemo)(()=>typeof i=="object"?i:Q?na({appearance:Q.appearance,buttonsStyles:Q.buttonsLayout,layout:"default"}):null,[Q,i]),z=(0,qe.useMemo)(()=>_i(Q?.buttonsLayout.cardFormContainer,c),[Q,c]),we=(0,qe.useMemo)(()=>Q?zi(Q):void 0,[Q]),J=(0,qe.useRef)({sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:u,onComplete:h,onDecline:P,onCancel:M,onValidation:_,onError:w});J.current={sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:u,onComplete:h,onDecline:P,onCancel:M,onValidation:_,onError:w},(0,qe.useEffect)(()=>{Y.current=!0;let F=Ce.current+1;return Ce.current=F,()=>{Y.current=!1,Be.current+=1,queueMicrotask(()=>{Ce.current===F&&(re.current||se.current||(se.current=!0,Je(()=>{J.current.onCancel?.({status:"cancelled",sessionId:n})})))})}},[n]);let Ee=(0,qe.useCallback)((F,B)=>{re.current=!0,Fe.current=!1,Ye({status:"success",wording:F,message:null}),(async()=>(await Zs(600),!Ae.current&&(Ae.current=!0,Je(()=>{J.current.onComplete?.({status:"succeeded",sessionId:J.current.sessionId,...B?{paymentMethod:B}:{}})}),Y.current&&Ye(null))))()},[]),Z=(0,qe.useCallback)((F,B)=>{re.current=!0,Fe.current=!1,Ye({status:"error",wording:F,message:B.message??null}),Je(()=>{J.current.onDecline?.({status:"declined",sessionId:J.current.sessionId,...B.reason?{reason:B.reason}:{},...B.message?{message:B.message}:{}})}),(async()=>(await Zs(400),Y.current&&Ye(null)))()},[]),it=(0,qe.useCallback)((F,B)=>{Fe.current?(Fe.current=!1,Ye({status:"error",wording:F,message:B.message}),setTimeout(()=>{Y.current&&Ye(null)},400)):Ye(null),Je(()=>J.current.onError?.(B))},[]),He=(0,qe.useCallback)(async F=>{let B=Be.current+1;Be.current=B;let oe=()=>!Y.current||B!==Be.current;Fe.current=!0,Ye({status:"processing",wording:"payment_method",message:null});let j=new Va.PaymentAPI((0,tn.resolveBillingApiUrl)(J.current.billingApiUrl),{telemetry:J.current.telemetry});try{for(let Ie=0;Ie<Np;Ie+=1){if((Ie>0||F.waitFirst)&&await Zs(Up),oe())return;let tt=await j.getUnifiedCheckoutSession(J.current.sessionId,J.current.nonce);if(oe())return;let gt=tt.data.session?.status;if(gt==="complete"){G(!0),Ee("payment_method");return}if(gt==="expired")throw new tn.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new tn.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(Ie){if(oe())return;let tt=Ie instanceof tn.FloPayError&&Ie.code==="payment_method_setup_unverified";it("payment_method",Jr(Ie,tt?{retryable:!0}:{}))}finally{j.destroy()}},[it,Ee]);(0,qe.useEffect)(()=>{let F=!0,B=(0,tn.resolveBillingApiUrl)(o),oe=new Va.PaymentAPI(B,{telemetry:a});b(null),G(!1),ye(null),H(null),te(null);let j=new Set;return We.current=j,fe(j),re.current=!1,se.current=!1,Ae.current=!1,(async()=>{try{let{session:Ie,advertisement:tt}=await qp(oe,n,r);if(!F)return;let gt={advertisement:tt,customer:zp(Ie),...Ie.futureUse?{futureUse:Ie.futureUse}:{},...Ie.futureUseUnsupported?{futureUseUnsupported:Ie.futureUseUnsupported}:{}};if(A){if(uu(),Ie.status==="complete"){G(!0),b(gt),Ee("payment_method");return}A.failed?Z("payment_method",{reason:"redirect_failed"}):He({waitFirst:!0})}let yt=tt.card?await Vp(oe,Ie,n,r,B):null;if(!F)return;b(gt),yt&&(H(yt),ye(new Va.PciVaultCardCapture({sessionId:n,operation:"card_setup",telemetry:a})))}catch(Ie){if(!F)return;let tt=Jr(Ie);re.current=!0,te(tt),Je(()=>J.current.onError?.(tt))}})(),()=>{F=!1,oe.destroy()}},[o,r,A,Z,Ee,n,a,He]),(0,qe.useEffect)(()=>{if(!k)return;Fe.current=!1;let F=k.on("submitting",()=>{Fe.current=!0,Ye({status:"processing",wording:"card",message:null})}),B=k.on("complete",Ie=>{Ee("card",Ie.paymentMethod)}),oe=k.on("decline",Ie=>{Z("card",{...Ie.declineReason?{reason:Ie.declineReason}:{},...Ie.message?{message:Ie.message}:{}})}),j=k.on("challenge_dismissed",()=>{Ye(null)});return()=>{F(),B(),oe(),j()}},[k,Z,Ee]);let Ve=(0,qe.useCallback)((F,B,oe)=>{if(oe.retryable){it("payment_method",Jr(B,oe));return}if(We.current.has(F))return;let j=new Set(We.current);j.add(F),We.current=j,fe(j);let Ie=Te.current?.advertisement,tt=Ie?Vi(Ie).some(gt=>!j.has(gt)):!1;it("payment_method",Jr(B,{code:oe.code,retryable:tt}))},[it]),at=(0,qe.useMemo)(()=>({onSubmitting:()=>{Fe.current=!0,Ye({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{He({waitFirst:!1})},onDeclined:F=>Z("payment_method",F),onValidation:F=>{Je(()=>J.current.onValidation?.(F))},onAbandoned:()=>{Fe.current=!1,Ye(null)}}),[Z,He]),Ke=(0,qe.useRef)(Ve);Ke.current=Ve;let st=(0,qe.useRef)(new Map),je=F=>{let B=st.current.get(F);if(B)return B;let oe=(j,Ie)=>Ke.current(F,j,Ie);return st.current.set(F,oe),oe},St=(0,qe.useCallback)(F=>{if(We.current.has(F))return;let B=new Set(We.current);B.add(F),We.current=B,fe(B);let oe=Te.current?.advertisement;oe&&Vi(oe).some(Ie=>!B.has(Ie))||it("payment_method",Jr(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[it]),Lt=(0,qe.useRef)(St);Lt.current=St;let Pt=(0,qe.useRef)(new Map),Et=F=>{let B=Pt.current.get(F);if(B)return B;let oe=()=>Lt.current(F);return Pt.current.set(F,oe),oe},q=Ne?(0,en.jsx)(Vn,{status:Ne.status,errorMessage:Ne.message,...du(Ne.wording),successNote:null,...we?{theme:we}:{}}):null;if(_e)return(0,en.jsx)("div",{role:"alert",children:_e.message});if(!I||C)return(0,en.jsxs)(en.Fragment,{children:[q,I?null:p]});let{advertisement:ve,customer:Qe,futureUse:X,futureUseUnsupported:Ue}=I,vt=(0,tn.resolveBillingApiUrl)(o),Xe=a===void 0?{}:{telemetry:a},kt=ve.stripe.filter(({method:F})=>!be.has(F)),V=be.has("paypal")?null:ve.paypal,g=!!(ve.card&&k&&N?.html),S=({method:F,publishableKey:B,currency:oe})=>(0,en.jsx)("div",{"data-flopay-payment-method":F,style:{display:"contents"},children:(0,en.jsx)($i,{onFailed:je(F),children:(0,en.jsx)(qe.Suspense,{fallback:null,children:(0,en.jsx)(e,{method:F,category:ji(F),publishableKey:B,currency:oe,...X?{futureUse:X}:{},...Ue?{futureUseUnsupported:Ue}:{},sessionId:n,nonce:r,billingApiUrl:vt,...Xe,...Q?{appearance:Q.appearance,buttonsLayout:Q.buttonsLayout}:{},...typeof i=="string"?{themeId:i}:{},...at,onFailed:je(F),onUnavailable:Et(F)})})})},F),K=kt.filter(({method:F})=>ji(F)==="wallet"),W=kt.filter(({method:F})=>ji(F)!=="wallet"),Se=kt.length>0||V!==null;return(0,en.jsxs)(en.Fragment,{children:[q,Se?(0,en.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[K.map(S),V?(0,en.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,en.jsx)($i,{onFailed:je("paypal"),children:(0,en.jsx)(qe.Suspense,{fallback:null,children:(0,en.jsx)(t,{clientId:V.clientId,...V.environment?{environment:V.environment}:{},...ve.currency?{currency:ve.currency}:{},sessionId:n,nonce:r,billingApiUrl:vt,customer:Qe,...Xe,...at,onFailed:je("paypal"),onUnavailable:Et("paypal")})})})}):null,W.map(S)]}):null,g&&Se?(0,en.jsx)(Ei,{label:"or add a card"}):null,g&&k&&N?.html?(0,en.jsx)("div",{"data-flopay-payment-method":"card",children:(0,en.jsx)(co,{capture:k,html:N.html,messageToken:N.messageToken,expectedOrigin:N.expectedOrigin,verificationRequired:N.verificationRequired,theme:Pe,containerStyle:z,onReady:()=>{Je(()=>J.current.onReady?.())},onValidation:F=>{Je(()=>J.current.onValidation?.(F))},onError:F=>{F&&it("card",Jr(new Error(F),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var yu=require("react/jsx-runtime"),jp={StripeSetupMethod:au,PayPalSetupMethod:Qc};function mu(e){return(0,yu.jsx)(pu,{...e,branches:jp})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|