@flopay/react 1.7.0 → 1.8.2
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/README.md +13 -78
- package/dist/card-setup-entry.cjs +2 -2
- package/dist/card-setup-entry.mjs +1 -1
- package/dist/chunk-W24FSJC5.mjs +6 -0
- package/dist/index.cjs +9 -9
- package/dist/index.d.cts +7 -134
- package/dist/index.d.ts +7 -134
- package/dist/index.mjs +8 -8
- package/package.json +3 -3
- package/dist/chunk-VWT2TDA6.mjs +0 -6
- package/dist/payment-logos/alipay.svg +0 -1
- package/dist/payment-logos/bancontact.svg +0 -1
- package/dist/payment-logos/blik.svg +0 -1
- package/dist/payment-logos/eps.svg +0 -1
- package/dist/payment-logos/giropay.svg +0 -1
- package/dist/payment-logos/ideal.svg +0 -1
- package/dist/payment-logos/klarna.svg +0 -1
- package/dist/payment-logos/p24.svg +0 -1
- package/dist/payment-logos/sepa_debit.svg +0 -1
- package/dist/payment-logos/wechat_pay.svg +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var ys=Object.create;var mo=Object.defineProperty;var fs=Object.getOwnPropertyDescriptor;var gs=Object.getOwnPropertyNames;var hs=Object.getPrototypeOf,Ps=Object.prototype.hasOwnProperty;var vs=(e,t)=>{for(var n in t)mo(e,n,{get:t[n],enumerable:!0})},Xa=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of gs(t))!Ps.call(e,o)&&o!==n&&mo(e,o,{get:()=>t[o],enumerable:!(r=fs(t,o))||r.enumerable});return e};var Za=(e,t,n)=>(n=e!=null?ys(hs(e)):{},Xa(t||!e||!e.__esModule?mo(n,"default",{value:e,enumerable:!0}):n,e)),bs=e=>Xa(mo({},"__esModule",{value:!0}),e);var fl={};vs(fl,{AddressElement:()=>ji,DirectPayPalButton:()=>Kr,FloPayAutomaticPaymentButton:()=>Ui,FloPayCardSetup:()=>Hi,FloPayCardSetupError:()=>eo,FloPayCheckout:()=>No,FloPayProvider:()=>Yr,PayPalButton:()=>Gi,PaymentElement:()=>qi,SplitCardForm:()=>Bo,VaultCardFields:()=>Rr,dropThirdPartyOnlyError:()=>Ji.dropThirdPartyOnlyError,useCheckout:()=>ai,useElements:()=>Po,useFloPay:()=>In,usePayPalFloPay:()=>ho});module.exports=bs(fl);var Cs=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,Ae=Cs();var Ji=require("@flopay/shared");var zo=require("@flopay/js"),an=require("@flopay/shared"),De=require("react");var ct=require("react/jsx-runtime");function Ss(){return(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.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,ct.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,ct.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,ct.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,ct.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function ws(){return(0,ct.jsx)(ct.Fragment,{children:"Go back"})}function ks(){return(0,ct.jsx)(ct.Fragment,{children:"Secure card checkout"})}function fr(e){return e!==void 0&&(e===""||e===null||e===!1)}function gr({content:e}){return(0,ct.jsx)(ct.Fragment,{children:e===void 0?(0,ct.jsx)(Ss,{}):e})}function hr({content:e}){return(0,ct.jsx)(ct.Fragment,{children:e===void 0?(0,ct.jsx)(ws,{}):e})}function qr({content:e}){return(0,ct.jsx)(ct.Fragment,{children:e===void 0?(0,ct.jsx)(ks,{}):e})}var Pr=require("@flopay/shared");function Qa(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Qo(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ei(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,p)=>a+(p.overrideAmount??p.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,p)=>({uuid:`synthetic-${a.type??"item"}-${p}`,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 ea(e,t){return t?{...e,...t}:e}function Mt(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var Is=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Xn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Is)if(n.test(t))return r;return e}function sr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function vr(e){return e?.status==="authorized"||e?.status==="complete"}function ti(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function yo(e){let t=ti(e);return new Pr.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function fo(e){let t=ti(e);return new Pr.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function go(e,t){return e==="processing"||(0,Pr.isMoneySettledOutcome)(e,t)}function ni(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function ri(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function jr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var ur=require("@flopay/js"),ge=require("@flopay/shared"),_=Za(require("react"),1);var ta=require("react"),Wt=(0,ta.createContext)({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),kn=(0,ta.createContext)({session:null,loading:!1,error:null});var wo=require("@flopay/js"),Gt=require("@flopay/shared"),ci=require("@paypal/paypal-js"),z=require("react");function Es(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 lr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function jn(e){if(typeof e!="object"||e===null)return;let t=e;return lr(t.code)??lr(t.type)??lr(t.name)}function br(e){if(!(typeof e!="object"||e===null))return lr(e.decline_code)}function Vr(e){return typeof e!="object"||e===null?!1:lr(e.type)?.toLowerCase()==="card_error"||br(e)!==void 0}function Zn(e){let t=Es(e)?.toLowerCase()??"",r=`${jn(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var oi=require("@flopay/shared"),Cr=require("react");function In(){return(0,Cr.useContext)(Wt).flopay}function ho(){return(0,Cr.useContext)(Wt).paypalFlopay??null}function Po(){return(0,Cr.useContext)(Wt).elements}function ai(){return(0,Cr.useContext)(kn)}function vo(){return(0,Cr.useContext)(Wt).billingApiUrl||(0,oi.resolveBillingApiUrl)()}var ii=require("@flopay/shared"),cr=require("react");function Ne(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 bo=require("react"),Co=typeof window>"u"?bo.useEffect:bo.useLayoutEffect;var Rs={"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 _s(e){return e==="stripe"||e==="paypal"?e:void 0}function xs(e){let t=_s(e.provider),n={schemaVersion:ii.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Rs[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 na=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Sr(e,t){let n=(0,cr.useRef)(e);n.current=e;let r=(0,cr.useRef)(new Set),o=(0,cr.useRef)(t),a=(0,cr.useRef)(t);return Co(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,cr.useCallback)(p=>{if(a.current!==t)return;let d=xs(p);if(d){if(na.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}Ne(()=>n.current?.(d))}},[t])}var Ts=Symbol.for("@flopay/js.telemetry.bridge.v1"),As=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ms(){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 Fs(e){let t=Ms(),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 So(e){let t=globalThis[As];return Fs(t?.(e)??{})}function Tt(e){if(e)return e[Ts]}var En=require("react/jsx-runtime"),ko=45,Bs=1e3,Ds=11e3,Ls=["https://www.paypal.com","https://www.sandbox.paypal.com"],si="We couldn't open PayPal. Try again or choose another payment method.",Os={width:"100%",minHeight:ko,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 li(e){return e.includes("No ack for postMessage init()")&&Ls.some(t=>e.includes(t))&&e.includes("10000ms")}function Ns(e){return e?`${si} Allow pop-ups for this site, then try again.`:si}function di({sessionId:e,nonce:t,billingApiUrl:n,email:r,clientId:o,environment:a,currency:p,isSubscription:d,providerObjectType:I,onTokenizedBody:g,onComplete:h,onErrorChange:k,onDecline:w,onTechnicalFailure:x,isProcessing:y=!1,onLoadStateChange:v,onInitializationStateChange:H,allowAutomaticRetry:M=!0,onButtonClick:f,runBeforeButtonClick:ie,session:O,existingOrderId:Z,telemetry:Q,telemetryContext:ve,onInstrument:B,debug:se=!1}){let xe=In(),Se=Sr(B,e),he=(0,z.useMemo)(()=>{if(xe)return null;let F=So({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Gt.SDK_VERSION,enabled:Q!==!1});return F.setCheckoutContext(ve??{}),F.beginCheckout(ve??{}),F},[n,xe,Q,ve?.checkoutMode,ve?.layout]),$=(0,z.useMemo)(()=>Tt(xe),[xe]);(0,z.useEffect)(()=>()=>{he&&he.flush().catch(()=>{}).finally(()=>he.destroy())},[he]);let N=(0,z.useMemo)(()=>({error:F=>{$?$.error(F):he?.error(F),Se({class:"technical_error",errorCode:F.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":F.errorCode,requestCategory:F.requestCategory,provider:F.provider})},log:F=>{$?$.log(F):he?.log(F),Se({class:"lifecycle",name:F.name,provider:F.provider})},performance:F=>{$?$.performance(F):he?.performance(F)},terminal:F=>{$?$.terminal(F):he?.terminal(F)},startTiming:()=>$?.now()??he?.now()??0,elapsed:F=>$?.elapsed(F)??Math.max(0,(he?.now()??F)-F)}),[Se,$,he]),oe=(0,z.useRef)(null),Me=(0,z.useRef)(0),Te=(0,z.useRef)(null),te=(0,z.useRef)(!1),[K,re]=(0,z.useState)(!1),[ye,be]=(0,z.useState)(!1),[ne,_e]=(0,z.useState)(0),G=(0,z.useRef)(0),[T,fe]=(0,z.useState)(!1),$e=(0,z.useRef)(!1),qe=(0,z.useRef)(!1),[ue,L]=(0,z.useState)(!1),[le,ee]=(0,z.useState)(!1),ze=(0,z.useMemo)(()=>n.replace(/\/+$/,""),[n]),Le=I??(d?"subscription":"order"),Qe=I==="order"||I==="setup_token",ce=(0,z.useMemo)(()=>JSON.stringify([ze,o,p,a??"",Le,Qe,e,Z??""]),[ze,o,p,a,Z,Le,Qe,e]),ft=(0,z.useRef)(ce),V=ft.current!==ce,[je,bt]=(0,z.useState)([]),J=F=>{se&&bt(tt=>[...tt,`${new Date().toISOString().slice(11,23)} ${F}`])},Ct=(0,z.useRef)(g),He=(0,z.useRef)(h),en=(0,z.useRef)(k),Rt=(0,z.useRef)(w),A=(0,z.useRef)(x),Ce=(0,z.useRef)(f),gt=(0,z.useRef)(v),Ue=(0,z.useRef)(H),qt=(0,z.useRef)(ie),Jt=(0,z.useRef)(O),Ze=(0,z.useRef)(r),St=(0,z.useRef)(t),et=(0,z.useRef)(null),Ft=(0,z.useRef)(0),Ge=(0,z.useRef)(null),jt=(0,z.useRef)(null),_t=(0,z.useRef)(new Map),tn=(0,z.useRef)(new Map),Dt=(0,z.useRef)(!1);(0,z.useEffect)(()=>(Dt.current=!0,()=>{Dt.current=!1}),[]),(0,z.useEffect)(()=>{Ct.current=g},[g]),(0,z.useEffect)(()=>{He.current=h},[h]),(0,z.useEffect)(()=>{en.current=k},[k]),(0,z.useEffect)(()=>{Rt.current=w},[w]),(0,z.useEffect)(()=>{A.current=x},[x]),(0,z.useEffect)(()=>{Ce.current=f},[f]),(0,z.useEffect)(()=>{gt.current=v},[v]),(0,z.useEffect)(()=>{Ue.current=H},[H]),(0,z.useEffect)(()=>{qt.current=ie},[ie]),(0,z.useEffect)(()=>{Jt.current=O},[O]),(0,z.useEffect)(()=>{Ze.current=r},[r]),(0,z.useEffect)(()=>{St.current=t},[t]),(0,z.useEffect)(()=>{G.current=ne},[ne]),(0,z.useEffect)(()=>{T&&Te.current?.focus()},[T,ne]);let Tn=(0,z.useCallback)(()=>{window.setTimeout(()=>{Te.current?.focus()},0)},[]),ln=(0,z.useCallback)(()=>{re(!1),_e(F=>F+1)},[]),at=(0,z.useCallback)(()=>{fe(!1),(oe.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??oe.current)?.focus?.()},[]);(0,z.useEffect)(()=>{!K||!te.current||(te.current=!1,at())},[at,K,ne]);let Lt=(0,z.useCallback)((F,tt)=>{let Ie=A.current;if(Ie){Ie("paypal",F,tt);return}en.current?.(Ns(tt?.popupBlocked??Zn(F)))},[]),Je=()=>{Ge.current?.timer&&(clearTimeout(Ge.current.timer),Ge.current.timer=null)},An=()=>{Je();let F=Ft.current+1;return Ft.current=F,jt.current=null,Ge.current={generation:F,timer:null,yieldedControl:!1},fe(!1),F},dt=F=>F!==void 0&&Ge.current?.generation!==F?!1:(Je(),Ge.current=null,jt.current=null,!0),bn=F=>{let tt=F?.generation??Ge.current?.generation??Ft.current;(!F?.generation||Ge.current?.generation===tt)&&(Je(),Ge.current=null),jt.current=tt,F?.showRetry&&fe(!0),F?.remount&&ln(),F?.focus!==!1&&Tn()},Ot=F=>Ge.current?.generation===F&&jt.current!==F,me=F=>{typeof document<"u"&&document.visibilityState!=="visible"||(Je(),F.timer=setTimeout(()=>{Ge.current?.generation===F.generation&&(Ge.current=null,jt.current=F.generation,Lt(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),fe(!0),ln(),Tn())},600))},Yn=()=>{let F=Ge.current;F?.yieldedControl&&me(F)},Mn=()=>{let F=Ge.current;F&&(F.yieldedControl=!0,Je())},Fn=F=>{let tt=et.current;return tt&&tn.current.set(F,tt),F};(0,z.useEffect)(()=>{let F=()=>{document.visibilityState==="visible"?Yn():Mn()};return document.addEventListener("visibilitychange",F),window.addEventListener("focus",Yn),window.addEventListener("blur",Mn),()=>{document.removeEventListener("visibilitychange",F),window.removeEventListener("focus",Yn),window.removeEventListener("blur",Mn),Je()}},[]),(0,z.useEffect)(()=>{ft.current!==ce&&(ft.current=ce,$e.current=!1,qe.current=!1,re(!1),be(!1),L(!1),Ue.current?.("loading"))},[ce]),(0,z.useEffect)(()=>{Ne(()=>gt.current?.(K&&!ue))},[K,ue]);let Bn=(0,Gt.normalizeGatewayEnvironment)(a);(0,z.useEffect)(()=>{let F=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",tt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(J(`mount clientId=${F} env=${a??"(unset)"}\u2192${Bn??"live"} ccy=${p} sub=${d}`),J(`ua=${tt.slice(0,80)}${tt.length>80?"\u2026":""}`),!o){J("FAIL: clientId empty \u2014 gateway misconfigured"),L(!0),N.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(!oe.current){J("FAIL: containerRef not attached");return}Me.current=N.startTiming(),N.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ie=!1,Cn=!1,Ve=()=>Ie||Cn,Wn,tr=!1,Vt=()=>{Wn=(0,Gt.generateIdempotencyKey)(),Wn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),tr=!0},ut=null,Xt=!1,Kt=null,it=!1,cn=()=>{!Kt||it||(it=!0,Kt.close().catch(()=>{}))},dn=null,Gn=()=>{dn!==null&&(N.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"overlay_return",durationMs:N.elapsed(dn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),dn=null)},Sn=!1,nn=oe.current,un=null,we=null,wt=[],st=u=>{if(!u||typeof u.getBoundingClientRect!="function")return"(no rect)";let c=u.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},rn=u=>{if(!u)return"(empty)";try{let c=new URL(u,typeof window<"u"?window.location.href:"https://localhost"),m=c.pathname.toLowerCase();return m.includes("checkcaptcha")||m.includes("captcha")?`CAPTCHA(${c.host}${m})`:m.includes("risk")||m.includes("challenge")?`RISK(${c.host}${m})`:m.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${m}`.slice(0,100)}catch{return u.slice(0,80)}},pn=u=>{let c=u.getAttribute("src"),m=u.getAttribute("srcdoc"),q=u.getAttribute("name"),ae=u.getAttribute("sandbox"),Y=[];return c&&Y.push(`src=${rn(c)}`),m&&Y.push(`srcdoc[${m.length}ch]`),!c&&!m&&Y.push("src=(empty) srcdoc=(empty)"),q&&Y.push(`name=${q.slice(0,40)}`),ae!==null&&Y.push(`sandbox="${ae.slice(0,40)}"`),Y.join(" ")},zn=u=>{if(!(u instanceof HTMLIFrameElement))return"";try{let c=u.contentDocument;if(!c)return"cd=null";let m=c.body?.children.length??0,q=c.body?.innerHTML.length??0,ae=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${m}children,${q}ch] head[${ae}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},mn=[],Nt=u=>{if(Ve())return;let c=u.message??String(u.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(J(`window:error ${c.slice(0,140)}`),mn.push(c))},Ht=u=>{if(Ve())return;let c=u.reason instanceof Error?u.reason.message:String(u.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(J(`window:rejection ${c.slice(0,140)}`),mn.push(c))};se&&typeof window<"u"&&(window.addEventListener("error",Nt),window.addEventListener("unhandledrejection",Ht));let Yt={value:0};if(se&&typeof PerformanceObserver<"u")try{we=new PerformanceObserver(u=>{if(!Ve())for(let c of u.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;Yt.value+=1;let m=Math.round(c.duration);J(`net ${m}ms ${c.name.slice(0,90)}`)}}),we.observe({type:"resource",buffered:!0})}catch{}let Jn=()=>{for(un?.disconnect(),un=null,we?.disconnect(),we=null;wt.length;)clearTimeout(wt.pop());se&&typeof window<"u"&&(window.removeEventListener("error",Nt),window.removeEventListener("unhandledrejection",Ht))},Un=u=>{if(!u)return!1;let c=u.toLowerCase();return c.includes("zoid destroyed")||c.includes("destroyed all components")||c.includes("window closed")||c.includes("detected container element removed")},Dn=u=>{if(Ve()||Un(u))return;let c=Xn(u)??u;Ne(()=>en.current?.(c))},$n=u=>{Ie||(L(!0),u.includes("paypal_ineligible")||N.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",u))},zt=(u,c=!1)=>{if(Ie)return;let m=$e.current||!M;if(Xt)return;Xt=!0,Cn=!0,Jn(),cn();let q=c||li(u);if(q&&M&&!$e.current){$e.current=!0,re(!1),ee(!1),be(!0),Ue.current?.("retrying"),ut=setTimeout(()=>{Ie||_e(ae=>ae+1)},Bs);return}if(q||m){if(re(!1),ee(!1),be(!1),L(!0),Ue.current?.("exhausted"),!qe.current){qe.current=!0;let ae=li(u)?"paypal_init_timeout":c?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",ae)}return}$n(u)};L(!1);let nt=async(u,c=et.current)=>{if(Ve())return;let m=c?.sessionId??e;if(Ct.current){await Ct.current(u,{sessionId:m,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let q=N.startTiming();N.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ae=()=>{N.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"processing",durationMs:N.elapsed(q),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Y=Jt.current,E=c?.accountPatch?.email??Ze.current,C=c?.accountPatch?.userId??Y?.customer?.id??Y?.accountData?.userId??"",S=await new wo.PaymentAPI(ze,{telemetry:!1}).processPayment(C,{sessionId:m,nonce:c?.nonce??St.current,tokenizedData:u,accountData:{userId:C,email:E??Y?.customer?.email??"",firstName:c?.accountPatch?.firstName??Y?.customer?.firstName??Y?.accountData?.firstName??"",lastName:c?.accountPatch?.lastName??Y?.customer?.lastName??Y?.accountData?.lastName??"",country:c?.accountPatch?.country??Y?.customer?.country??Y?.accountData?.country??void 0,zip:c?.accountPatch?.zip??Y?.customer?.zip??Y?.accountData?.zip??void 0}});if(S.ok){if(Cn||Ie&&Dt.current)return;ae(),N.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ne(()=>He.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ve())return;let D=await S.json().catch(()=>null),de=D?.message??"PayPal payment failed.",Pe=Xn(de)??de;ae(),S.status===400&&(typeof D?.declineCode=="string"||!Array.isArray(D?.fields))?N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):S.status===400||S.status===422?N.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):N.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:S.status>=500?"5xx":S.status>=400?"4xx":S.status>=300?"3xx":"unknown",failureCategory:S.status>=500?"server_error":void 0}),Dn(Pe),Ne(()=>Rt.current?.(Mt("paypal",Pe,{code:D?.code,declineCode:D?.declineCode})));return}catch(Y){if(Ve())return;ae(),N.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let E=Y instanceof Error?Y.message:"PayPal payment failed.",C=Xn(E)??E;Dn(C),Ne(()=>Rt.current?.(Mt("paypal",C)));return}},yn=()=>new Gt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ut=u=>Ve()?Promise.reject(yn()):Promise.resolve(u),pt=async u=>{if(Ve())throw yn();tr||Vt();let c=et.current,m=c?.sessionId??e,q=c?.nonce??St.current;N.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ae;try{ae=await new wo.PaymentAPI(ze,{telemetry:!1}).createSessionIntent(m,q??"",Qe?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Gt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:Le==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Wn})}catch(Y){throw N.error({...(0,Gt.classifyTelemetryFailure)(Y,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Y}if(Ve())throw yn();if(ae.provider!=="paypal"||ae.providerObjectType!==Le)throw new Error(u);return N.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ae.providerObjectId},Zt=(u,c)=>{let m=c?.nonce??St.current;if(!m)return;let q=c?.sessionId??e,ae=br(u)??jn(u)??"provider_declined";new wo.PaymentAPI(ze,{telemetry:!1}).reportSessionIntentDecline(q,m,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ae}).catch(()=>{})},xt=ne;J("loadScript:scheduled (deferred 1 tick)");let nr=null,mt=setTimeout(()=>{if(Ie){J("loadScript:skipped (cancelled before defer ran)");return}J("loadScript:start");let u=Bn==="live"?"production":Bn;nr=(0,ci.loadScript)({clientId:o,currency:p,...Le==="subscription"?{intent:"subscription",vault:!0}:Le==="order"?{intent:"capture"}:{},...u?{environment:u}:{},...u==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),nr.then(c=>{if(J(`loadScript:resolved inactive=${Ve()} ns=${!!c} buttons=${!!c?.Buttons}`),Ve())return;if(!c?.Buttons){J("FAIL: namespace missing Buttons factory"),zt("PayPal SDK did not expose the Buttons factory.");return}N.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"provider_ready",durationMs:N.elapsed(Me.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let m=async b=>{if(Ve()||G.current!==xt)return;let S=b.vaultSetupToken??b.subscriptionID??b.orderID??"",D=S?tn.current.get(S):_t.current.get(xt);if(!(!D||!Ot(D.generation))&&dt(D.generation)){tn.current.delete(S),_t.current.delete(D.surfaceKey),Gn();try{if(ee(!0),Ne(()=>en.current?.(null)),!S)throw new Gt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await nt(Le==="setup_token"?{id:S,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Gt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Qe?{id:S,isPaypal:!0,gateway:"paypal",paymentMethodType:Gt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:{id:S,isPaypal:!0},D)}catch(de){Dn(de instanceof Error?de.message:"PayPal capture failed.")}finally{Ve()||ee(!1)}}},q=c.Buttons({style:{layout:"horizontal",height:ko,tagline:!1},onClick:async(b,S)=>{if(Ve()){await S.reject();return}Vt();let D=qt.current,de={};if(D)try{let Ye=await D("paypal");if(Ve()){await S.reject();return}if(!Ye.proceed){et.current=null,_t.current.delete(xt),await S.reject();return}de={sessionId:Ye.sessionId,accountPatch:Ye.accountPatch,nonce:Ye.nonce}}catch(Ye){J(`onClick:runBeforeButtonClick rejected msg=${(Ye instanceof Error?Ye.message:String(Ye)).slice(0,120)}`),et.current=null,_t.current.delete(xt),await S.reject();return}Ne(()=>Ce.current?.("paypal"));let Oe={generation:An(),surfaceKey:xt,...de};et.current=Oe,_t.current.set(xt,Oe),await S.resolve(),N.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),dn=N.startTiming()},createOrder:Le==="order"?Z?()=>Ut(Z).then(Fn):()=>pt("Failed to create PayPal order.").then(Fn):void 0,createSubscription:Le==="subscription"?Z?()=>Ut(Z).then(Fn):()=>pt("Failed to create PayPal subscription.").then(Fn):void 0,createVaultSetupToken:Le==="setup_token"?()=>pt("Failed to create PayPal setup token.").then(Fn):void 0,onApprove:m,onCancel:()=>{if(Ve())return;let b=_t.current.get(xt)??et.current;b&&_t.current.delete(b.surfaceKey),et.current=null,Gn(),N.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),te.current=!0,bn({generation:b?.generation,remount:!0,focus:!1})},onError:b=>{if(Ve()||G.current!==xt)return;let S=b instanceof Error?b.message:"PayPal failed to render.";if(J(`onError rendered=${Sn} msg=${S.slice(0,120)}`),Sn){let D=_t.current.get(xt)??et.current;if(D&&!Ot(D.generation)||!D&&jt.current===Ft.current)return;if(Un(S)){dt(D?.generation);return}if(Gn(),Vr(b)){N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Zt(b,D),Ne(()=>Rt.current?.(Mt("paypal",S))),D&&_t.current.delete(D.surfaceKey),et.current=null,dt(D?.generation);return}let de=S.toLowerCase();N.error({errorCode:de.includes("popup")&&de.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),D&&_t.current.delete(D.surfaceKey),et.current=null,bn({generation:D?.generation,remount:!0,showRetry:!0,focus:!0}),Lt(b,{code:"paypal_runtime_failed"});return}zt(S)}}),ae=q.isEligible();if(J(`isEligible=${ae}`),N.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ae){re(!1),zt("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Kt=q,se&&J(`container:dims ${st(nn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),se&&typeof MutationObserver<"u"&&(un=new MutationObserver(b=>{if(!Ve()){for(let S of b)if(S.type==="childList")S.addedNodes.forEach(D=>{if(!(D instanceof Element))return;let de=D.tagName.toLowerCase(),Pe=(D.getAttribute("title")??"").slice(0,40),Oe=de==="iframe"?` ${pn(D)}`:"";J(`child+ ${de}${Pe?` title="${Pe}"`:""}${Oe} dims=${st(D)}`)});else if(S.type==="attributes"&&S.target instanceof Element){let D=S.target;if(D.tagName.toLowerCase()!=="iframe")continue;let de=S.attributeName;(de==="src"||de==="srcdoc")&&J(`attr~ iframe ${de}=${de==="srcdoc"?`[${(D.getAttribute("srcdoc")??"").length}ch]`:rn(D.getAttribute("src"))} dims=${st(D)}`)}}}),un.observe(nn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let E=b=>{if(Ve()||Sn)return;let S=nn.querySelectorAll("iframe"),D=typeof document<"u"&&"hasStorageAccess"in document;J(`watchdog:${b} container=${st(nn)} children=${nn.childElementCount} iframes=${S.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${D} paypalNetRequests=${Yt.value}`),S.forEach((de,Pe)=>{let Oe=(de.getAttribute("title")??"").slice(0,40);J(` iframe[${Pe}] ${st(de)}${Oe?` title="${Oe}"`:""} ${pn(de)}`);let Ye=zn(de);Ye&&J(` ${Ye}`)}),mn.length===0&&J(" (no PayPal/zoid window errors captured)")};se&&(wt.push(setTimeout(()=>E("3s"),3e3)),wt.push(setTimeout(()=>E("8s"),8e3)),wt.push(setTimeout(()=>E("15s"),15e3))),J("render:start");let C=N.startTiming();wt.push(setTimeout(()=>{Ve()||Sn||(J("watchdog:11s retryable render timeout"),zt("PayPal Buttons render did not settle within 11000ms.",!0))},Ds)),q.render(nn).then(()=>{if(J(`render:resolved inactive=${Ve()}`),Jn(),Ve()){cn();return}Sn=!0,re(!0),be(!1),Ue.current?.("ready"),N.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"checkout_render",durationMs:N.elapsed(C),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(b=>{let S=b instanceof Error?b.message:"PayPal failed to render.";J(`render:rejected msg=${S.slice(0,120)}`),Jn(),zt(S)})}).catch(c=>{let m=c instanceof Error?c.message:"PayPal SDK failed to load.";J(`loadScript:rejected msg=${m.slice(0,120)}`),zt(m)})},0);return()=>{Ie=!0,clearTimeout(mt),ut&&clearTimeout(ut),Jn(),cn()}},[M,ze,o,p,a,Le,Qe,e,Z,ne,N]);let mr=se?(0,En.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ue?"#fef2f2":"#f3f4f6",border:`1px solid ${ue?"#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=${K} failed=${ue})`,je.length===0?`
|
|
1
|
+
"use strict";var ns=Object.create;var lo=Object.defineProperty;var rs=Object.getOwnPropertyDescriptor;var os=Object.getOwnPropertyNames;var as=Object.getPrototypeOf,is=Object.prototype.hasOwnProperty;var ss=(e,t)=>{for(var n in t)lo(e,n,{get:t[n],enumerable:!0})},Ka=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of os(t))!is.call(e,r)&&r!==n&&lo(e,r,{get:()=>t[r],enumerable:!(o=rs(t,r))||o.enumerable});return e};var Ha=(e,t,n)=>(n=e!=null?ns(as(e)):{},Ka(t||!e||!e.__esModule?lo(n,"default",{value:e,enumerable:!0}):n,e)),ls=e=>Ka(lo({},"__esModule",{value:!0}),e);var nl={};ss(nl,{DirectPayPalButton:()=>$r,FloPayAutomaticPaymentButton:()=>Di,FloPayCardSetup:()=>Oi,FloPayCardSetupError:()=>Jr,FloPayCheckout:()=>Mo,FloPayProvider:()=>jr,SplitCardForm:()=>_o,VaultCardFields:()=>Sr,dropThirdPartyOnlyError:()=>Ni.dropThirdPartyOnlyError,useCheckout:()=>Qa,useFloPay:()=>Un,usePayPalFloPay:()=>mo});module.exports=ls(nl);var Ni=require("@flopay/shared");var Fo=require("@flopay/js"),rn=require("@flopay/shared"),Me=require("react");var lt=require("react/jsx-runtime");function cs(){return(0,lt.jsxs)(lt.Fragment,{children:[(0,lt.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,lt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,lt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,lt.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,lt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function ds(){return(0,lt.jsx)(lt.Fragment,{children:"Go back"})}function us(){return(0,lt.jsx)(lt.Fragment,{children:"Secure card checkout"})}function ur(e){return e!==void 0&&(e===""||e===null||e===!1)}function pr({content:e}){return(0,lt.jsx)(lt.Fragment,{children:e===void 0?(0,lt.jsx)(cs,{}):e})}function mr({content:e}){return(0,lt.jsx)(lt.Fragment,{children:e===void 0?(0,lt.jsx)(ds,{}):e})}function Or({content:e}){return(0,lt.jsx)(lt.Fragment,{children:e===void 0?(0,lt.jsx)(us,{}):e})}var yr=require("@flopay/shared");function Ya(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Yo(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Wa(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],o=n.reduce((i,m)=>i+(m.overrideAmount??m.totalAmount??0),0),r=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(o*100),currency:r,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((i,m)=>({uuid:`synthetic-${i.type??"item"}-${m}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??r,metadata:i.metadata??null}))}}function Wo(e,t){return t?{...e,...t}:e}function Tt(e,t,n){let o=typeof t=="string"?t:t.message,r=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:o,...r?{code:r}:{},...i?{declineCode:i}:{}}}var ps=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Wn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:o}of ps)if(n.test(t))return o;return e}function or(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function fr(e){return e?.status==="authorized"||e?.status==="complete"}function Ga(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function co(e){let t=Ga(e);return new yr.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function uo(e){let t=Ga(e);return new yr.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function po(e,t){return e==="processing"||(0,yr.isMoneySettledOutcome)(e,t)}function Ja(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Xa(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Nr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var lr=require("@flopay/js"),fe=require("@flopay/shared"),E=Ha(require("react"),1);var Go=require("react"),gn=(0,Go.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),wn=(0,Go.createContext)({session:null,loading:!1,error:null});var ho=require("@flopay/js"),Yt=require("@flopay/shared"),oi=require("@paypal/paypal-js"),B=require("react");function ms(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 ar(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function zn(e){if(typeof e!="object"||e===null)return;let t=e;return ar(t.code)??ar(t.type)??ar(t.name)}function gr(e){if(!(typeof e!="object"||e===null))return ar(e.decline_code)}function zr(e){return typeof e!="object"||e===null?!1:ar(e.type)?.toLowerCase()==="card_error"||gr(e)!==void 0}function Gn(e){let t=ms(e)?.toLowerCase()??"",o=`${zn(e)?.toLowerCase()??""} ${t}`;return o.includes("popup")&&o.includes("block")}var Za=require("@flopay/shared"),Ur=require("react");function Un(){return(0,Ur.useContext)(gn).flopay}function mo(){return(0,Ur.useContext)(gn).paypalFlopay??null}function Qa(){return(0,Ur.useContext)(wn)}function ei(){return(0,Ur.useContext)(gn).billingApiUrl||(0,Za.resolveBillingApiUrl)()}var ti=require("@flopay/shared"),ir=require("react");function De(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 yo=require("react"),fo=typeof window>"u"?yo.useEffect:yo.useLayoutEffect;var ys={"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 fs(e){return e==="stripe"||e==="paypal"?e:void 0}function gs(e){let t=fs(e.provider),n={schemaVersion:ti.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let o=ys[e.name];return o?{...n,name:o}: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 Jo=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function hr(e,t){let n=(0,ir.useRef)(e);n.current=e;let o=(0,ir.useRef)(new Set),r=(0,ir.useRef)(t),i=(0,ir.useRef)(t);return fo(()=>{i.current=t,r.current!==t&&(r.current=t,o.current.clear())},[t]),(0,ir.useCallback)(m=>{if(i.current!==t)return;let d=gs(m);if(d){if(Jo.has(d.name)){if(o.current.has(d.name))return;o.current.add(d.name)}De(()=>n.current?.(d))}},[t])}var hs=Symbol.for("@flopay/js.telemetry.bridge.v1"),vs=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ps(){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 bs(e){let t=Ps(),n=(r,i)=>r?r.bind(e):i,o=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:o,elapsed:e.elapsed?e.elapsed.bind(e):r=>Math.max(0,o()-r),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 go(e){let t=globalThis[vs];return bs(t?.(e)??{})}function xt(e){if(e)return e[hs]}var kn=require("react/jsx-runtime"),vo=45,Cs=1e3,Ss=11e3,ws=["https://www.paypal.com","https://www.sandbox.paypal.com"],ni="We couldn't open PayPal. Try again or choose another payment method.",ks={width:"100%",minHeight:vo,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 ri(e){return e.includes("No ack for postMessage init()")&&ws.some(t=>e.includes(t))&&e.includes("10000ms")}function Is(e){return e?`${ni} Allow pop-ups for this site, then try again.`:ni}function ai({sessionId:e,nonce:t,billingApiUrl:n,email:o,clientId:r,environment:i,currency:m,isSubscription:d,providerObjectType:R,onTokenizedBody:g,onComplete:v,onErrorChange:b,onDecline:A,onTechnicalFailure:D,isProcessing:y=!1,onLoadStateChange:C,onInitializationStateChange:te,allowAutomaticRetry:G=!0,onButtonClick:S,runBeforeButtonClick:ge,session:U,existingOrderId:Q,telemetry:re,telemetryContext:be,onInstrument:oe,debug:he=!1}){let Ne=Un(),_e=hr(oe,e),Se=(0,B.useMemo)(()=>{if(Ne)return null;let x=go({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Yt.SDK_VERSION,enabled:re!==!1});return x.setCheckoutContext(be??{}),x.beginCheckout(be??{}),x},[n,Ne,re,be?.checkoutMode,be?.layout]),K=(0,B.useMemo)(()=>xt(Ne),[Ne]);(0,B.useEffect)(()=>()=>{Se&&Se.flush().catch(()=>{}).finally(()=>Se.destroy())},[Se]);let O=(0,B.useMemo)(()=>({error:x=>{K?K.error(x):Se?.error(x),_e({class:"technical_error",errorCode:x.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":x.errorCode,requestCategory:x.requestCategory,provider:x.provider})},log:x=>{K?K.log(x):Se?.log(x),_e({class:"lifecycle",name:x.name,provider:x.provider})},performance:x=>{K?K.performance(x):Se?.performance(x)},terminal:x=>{K?K.terminal(x):Se?.terminal(x)},startTiming:()=>K?.now()??Se?.now()??0,elapsed:x=>K?.elapsed(x)??Math.max(0,(Se?.now()??x)-x)}),[_e,K,Se]),ae=(0,B.useRef)(null),ze=(0,B.useRef)(0),Te=(0,B.useRef)(null),X=(0,B.useRef)(!1),[$,ee]=(0,B.useState)(!1),[pe,ve]=(0,B.useState)(!1),[Z,Re]=(0,B.useState)(0),H=(0,B.useRef)(0),[_,me]=(0,B.useState)(!1),Ye=(0,B.useRef)(!1),Ue=(0,B.useRef)(!1),[ce,F]=(0,B.useState)(!1),[ie,J]=(0,B.useState)(!1),Le=(0,B.useMemo)(()=>n.replace(/\/+$/,""),[n]),Fe=R??(d?"subscription":"order"),Ze=R==="order"||R==="setup_token",se=(0,B.useMemo)(()=>JSON.stringify([Le,r,m,i??"",Fe,Ze,e,Q??""]),[Le,r,m,i,Q,Fe,Ze,e]),mt=(0,B.useRef)(se),j=mt.current!==se,[$e,vt]=(0,B.useState)([]),Y=x=>{he&&vt(et=>[...et,`${new Date().toISOString().slice(11,23)} ${x}`])},Pt=(0,B.useRef)(g),Ve=(0,B.useRef)(v),Zt=(0,B.useRef)(b),It=(0,B.useRef)(A),T=(0,B.useRef)(D),Pe=(0,B.useRef)(S),yt=(0,B.useRef)(C),Oe=(0,B.useRef)(te),$t=(0,B.useRef)(ge),Wt=(0,B.useRef)(U),Xe=(0,B.useRef)(o),bt=(0,B.useRef)(t),Qe=(0,B.useRef)(null),At=(0,B.useRef)(0),We=(0,B.useRef)(null),qt=(0,B.useRef)(null),Et=(0,B.useRef)(new Map),Qt=(0,B.useRef)(new Map),Bt=(0,B.useRef)(!1);(0,B.useEffect)(()=>(Bt.current=!0,()=>{Bt.current=!1}),[]),(0,B.useEffect)(()=>{Pt.current=g},[g]),(0,B.useEffect)(()=>{Ve.current=v},[v]),(0,B.useEffect)(()=>{Zt.current=b},[b]),(0,B.useEffect)(()=>{It.current=A},[A]),(0,B.useEffect)(()=>{T.current=D},[D]),(0,B.useEffect)(()=>{Pe.current=S},[S]),(0,B.useEffect)(()=>{yt.current=C},[C]),(0,B.useEffect)(()=>{Oe.current=te},[te]),(0,B.useEffect)(()=>{$t.current=ge},[ge]),(0,B.useEffect)(()=>{Wt.current=U},[U]),(0,B.useEffect)(()=>{Xe.current=o},[o]),(0,B.useEffect)(()=>{bt.current=t},[t]),(0,B.useEffect)(()=>{H.current=Z},[Z]),(0,B.useEffect)(()=>{_&&Te.current?.focus()},[_,Z]);let En=(0,B.useCallback)(()=>{window.setTimeout(()=>{Te.current?.focus()},0)},[]),an=(0,B.useCallback)(()=>{ee(!1),Re(x=>x+1)},[]),ot=(0,B.useCallback)(()=>{me(!1),(ae.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ae.current)?.focus?.()},[]);(0,B.useEffect)(()=>{!$||!X.current||(X.current=!1,ot())},[ot,$,Z]);let Dt=(0,B.useCallback)((x,et)=>{let ke=T.current;if(ke){ke("paypal",x,et);return}Zt.current?.(Is(et?.popupBlocked??Gn(x)))},[]),Ge=()=>{We.current?.timer&&(clearTimeout(We.current.timer),We.current.timer=null)},Rn=()=>{Ge();let x=At.current+1;return At.current=x,qt.current=null,We.current={generation:x,timer:null,yieldedControl:!1},me(!1),x},ct=x=>x!==void 0&&We.current?.generation!==x?!1:(Ge(),We.current=null,qt.current=null,!0),Pn=x=>{let et=x?.generation??We.current?.generation??At.current;(!x?.generation||We.current?.generation===et)&&(Ge(),We.current=null),qt.current=et,x?.showRetry&&me(!0),x?.remount&&an(),x?.focus!==!1&&En()},Lt=x=>We.current?.generation===x&&qt.current!==x,ue=x=>{typeof document<"u"&&document.visibilityState!=="visible"||(Ge(),x.timer=setTimeout(()=>{We.current?.generation===x.generation&&(We.current=null,qt.current=x.generation,Dt(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),me(!0),an(),En())},600))},Vn=()=>{let x=We.current;x?.yieldedControl&&ue(x)},_n=()=>{let x=We.current;x&&(x.yieldedControl=!0,Ge())},Tn=x=>{let et=Qe.current;return et&&Qt.current.set(x,et),x};(0,B.useEffect)(()=>{let x=()=>{document.visibilityState==="visible"?Vn():_n()};return document.addEventListener("visibilitychange",x),window.addEventListener("focus",Vn),window.addEventListener("blur",_n),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("focus",Vn),window.removeEventListener("blur",_n),Ge()}},[]),(0,B.useEffect)(()=>{mt.current!==se&&(mt.current=se,Ye.current=!1,Ue.current=!1,ee(!1),ve(!1),F(!1),Oe.current?.("loading"))},[se]),(0,B.useEffect)(()=>{De(()=>yt.current?.($&&!ce))},[$,ce]);let xn=(0,Yt.normalizeGatewayEnvironment)(i);(0,B.useEffect)(()=>{let x=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",et=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(Y(`mount clientId=${x} env=${i??"(unset)"}\u2192${xn??"live"} ccy=${m} sub=${d}`),Y(`ua=${et.slice(0,80)}${et.length>80?"\u2026":""}`),!r){Y("FAIL: clientId empty \u2014 gateway misconfigured"),F(!0),O.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(!ae.current){Y("FAIL: containerRef not attached");return}ze.current=O.startTiming(),O.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ke=!1,bn=!1,qe=()=>ke||bn,Kn,Zn=!1,jt=()=>{Kn=(0,Yt.generateIdempotencyKey)(),Kn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Zn=!0},dt=null,Gt=!1,Vt=null,at=!1,sn=()=>{!Vt||at||(at=!0,Vt.close().catch(()=>{}))},ln=null,Hn=()=>{ln!==null&&(O.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"overlay_return",durationMs:O.elapsed(ln),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),ln=null)},Cn=!1,en=ae.current,cn=null,Ce=null,Ct=[],it=u=>{if(!u||typeof u.getBoundingClientRect!="function")return"(no rect)";let c=u.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},tn=u=>{if(!u)return"(empty)";try{let c=new URL(u,typeof window<"u"?window.location.href:"https://localhost"),p=c.pathname.toLowerCase();return p.includes("checkcaptcha")||p.includes("captcha")?`CAPTCHA(${c.host}${p})`:p.includes("risk")||p.includes("challenge")?`RISK(${c.host}${p})`:p.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${p}`.slice(0,100)}catch{return u.slice(0,80)}},dn=u=>{let c=u.getAttribute("src"),p=u.getAttribute("srcdoc"),N=u.getAttribute("name"),ne=u.getAttribute("sandbox"),q=[];return c&&q.push(`src=${tn(c)}`),p&&q.push(`srcdoc[${p.length}ch]`),!c&&!p&&q.push("src=(empty) srcdoc=(empty)"),N&&q.push(`name=${N.slice(0,40)}`),ne!==null&&q.push(`sandbox="${ne.slice(0,40)}"`),q.join(" ")},Dn=u=>{if(!(u instanceof HTMLIFrameElement))return"";try{let c=u.contentDocument;if(!c)return"cd=null";let p=c.body?.children.length??0,N=c.body?.innerHTML.length??0,ne=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${p}children,${N}ch] head[${ne}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},un=[],Ot=u=>{if(qe())return;let c=u.message??String(u.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(Y(`window:error ${c.slice(0,140)}`),un.push(c))},Kt=u=>{if(qe())return;let c=u.reason instanceof Error?u.reason.message:String(u.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(Y(`window:rejection ${c.slice(0,140)}`),un.push(c))};he&&typeof window<"u"&&(window.addEventListener("error",Ot),window.addEventListener("unhandledrejection",Kt));let Ht={value:0};if(he&&typeof PerformanceObserver<"u")try{Ce=new PerformanceObserver(u=>{if(!qe())for(let c of u.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;Ht.value+=1;let p=Math.round(c.duration);Y(`net ${p}ms ${c.name.slice(0,90)}`)}}),Ce.observe({type:"resource",buffered:!0})}catch{}let Yn=()=>{for(cn?.disconnect(),cn=null,Ce?.disconnect(),Ce=null;Ct.length;)clearTimeout(Ct.pop());he&&typeof window<"u"&&(window.removeEventListener("error",Ot),window.removeEventListener("unhandledrejection",Kt))},Ln=u=>{if(!u)return!1;let c=u.toLowerCase();return c.includes("zoid destroyed")||c.includes("destroyed all components")||c.includes("window closed")||c.includes("detected container element removed")},An=u=>{if(qe()||Ln(u))return;let c=Wn(u)??u;De(()=>Zt.current?.(c))},On=u=>{ke||(F(!0),u.includes("paypal_ineligible")||O.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",u))},Nt=(u,c=!1)=>{if(ke)return;let p=Ye.current||!G;if(Gt)return;Gt=!0,bn=!0,Yn(),sn();let N=c||ri(u);if(N&&G&&!Ye.current){Ye.current=!0,ee(!1),J(!1),ve(!0),Oe.current?.("retrying"),dt=setTimeout(()=>{ke||Re(ne=>ne+1)},Cs);return}if(N||p){if(ee(!1),J(!1),ve(!1),F(!0),Oe.current?.("exhausted"),!Ue.current){Ue.current=!0;let ne=ri(u)?"paypal_init_timeout":c?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",ne)}return}On(u)};F(!1);let tt=async(u,c=Qe.current)=>{if(qe())return;let p=c?.sessionId??e;if(Pt.current){await Pt.current(u,{sessionId:p,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let N=O.startTiming();O.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ne=()=>{O.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"processing",durationMs:O.elapsed(N),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let q=Wt.current,k=c?.accountPatch?.email??Xe.current,P=c?.accountPatch?.userId??q?.customer?.id??q?.accountData?.userId??"",w=await new ho.PaymentAPI(Le,{telemetry:!1}).processPayment(P,{sessionId:p,nonce:c?.nonce??bt.current,tokenizedData:u,accountData:{userId:P,email:k??q?.customer?.email??"",firstName:c?.accountPatch?.firstName??q?.customer?.firstName??q?.accountData?.firstName??"",lastName:c?.accountPatch?.lastName??q?.customer?.lastName??q?.accountData?.lastName??"",country:c?.accountPatch?.country??q?.customer?.country??q?.accountData?.country??void 0,zip:c?.accountPatch?.zip??q?.customer?.zip??q?.accountData?.zip??void 0}});if(w.ok){if(bn||ke&&Bt.current)return;ne(),O.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),De(()=>Ve.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(qe())return;let M=await w.json().catch(()=>null),le=M?.message??"PayPal payment failed.",ye=Wn(le)??le;ne(),w.status===400&&(typeof M?.declineCode=="string"||!Array.isArray(M?.fields))?O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):w.status===400||w.status===422?O.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):O.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:w.status>=500?"5xx":w.status>=400?"4xx":w.status>=300?"3xx":"unknown",failureCategory:w.status>=500?"server_error":void 0}),An(ye),De(()=>It.current?.(Tt("paypal",ye,{code:M?.code,declineCode:M?.declineCode})));return}catch(q){if(qe())return;ne(),O.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let k=q instanceof Error?q.message:"PayPal payment failed.",P=Wn(k)??k;An(P),De(()=>It.current?.(Tt("paypal",P)));return}},pn=()=>new Yt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),zt=u=>qe()?Promise.reject(pn()):Promise.resolve(u),ut=async u=>{if(qe())throw pn();Zn||jt();let c=Qe.current,p=c?.sessionId??e,N=c?.nonce??bt.current;O.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ne;try{ne=await new ho.PaymentAPI(Le,{telemetry:!1}).createSessionIntent(p,N??"",Ze?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Yt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:Fe==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Kn})}catch(q){throw O.error({...(0,Yt.classifyTelemetryFailure)(q,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),q}if(qe())throw pn();if(ne.provider!=="paypal"||ne.providerObjectType!==Fe)throw new Error(u);return O.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ne.providerObjectId},Jt=(u,c)=>{let p=c?.nonce??bt.current;if(!p)return;let N=c?.sessionId??e,ne=gr(u)??zn(u)??"provider_declined";new ho.PaymentAPI(Le,{telemetry:!1}).reportSessionIntentDecline(N,p,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ne}).catch(()=>{})},Rt=Z;Y("loadScript:scheduled (deferred 1 tick)");let Qn=null,pt=setTimeout(()=>{if(ke){Y("loadScript:skipped (cancelled before defer ran)");return}Y("loadScript:start");let u=xn==="live"?"production":xn;Qn=(0,oi.loadScript)({clientId:r,currency:m,...Fe==="subscription"?{intent:"subscription",vault:!0}:Fe==="order"?{intent:"capture"}:{},...u?{environment:u}:{},...u==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Qn.then(c=>{if(Y(`loadScript:resolved inactive=${qe()} ns=${!!c} buttons=${!!c?.Buttons}`),qe())return;if(!c?.Buttons){Y("FAIL: namespace missing Buttons factory"),Nt("PayPal SDK did not expose the Buttons factory.");return}O.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"provider_ready",durationMs:O.elapsed(ze.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let p=async h=>{if(qe()||H.current!==Rt)return;let w=h.vaultSetupToken??h.subscriptionID??h.orderID??"",M=w?Qt.current.get(w):Et.current.get(Rt);if(!(!M||!Lt(M.generation))&&ct(M.generation)){Qt.current.delete(w),Et.current.delete(M.surfaceKey),Hn();try{if(J(!0),De(()=>Zt.current?.(null)),!w)throw new Yt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await tt(Fe==="setup_token"?{id:w,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Yt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Ze?{id:w,isPaypal:!0,gateway:"paypal",paymentMethodType:Yt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:{id:w,isPaypal:!0},M)}catch(le){An(le instanceof Error?le.message:"PayPal capture failed.")}finally{qe()||J(!1)}}},N=c.Buttons({style:{layout:"horizontal",height:vo,tagline:!1},onClick:async(h,w)=>{if(qe()){await w.reject();return}jt();let M=$t.current,le={};if(M)try{let Ke=await M("paypal");if(qe()){await w.reject();return}if(!Ke.proceed){Qe.current=null,Et.current.delete(Rt),await w.reject();return}le={sessionId:Ke.sessionId,accountPatch:Ke.accountPatch,nonce:Ke.nonce}}catch(Ke){Y(`onClick:runBeforeButtonClick rejected msg=${(Ke instanceof Error?Ke.message:String(Ke)).slice(0,120)}`),Qe.current=null,Et.current.delete(Rt),await w.reject();return}De(()=>Pe.current?.("paypal"));let Be={generation:Rn(),surfaceKey:Rt,...le};Qe.current=Be,Et.current.set(Rt,Be),await w.resolve(),O.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),ln=O.startTiming()},createOrder:Fe==="order"?Q?()=>zt(Q).then(Tn):()=>ut("Failed to create PayPal order.").then(Tn):void 0,createSubscription:Fe==="subscription"?Q?()=>zt(Q).then(Tn):()=>ut("Failed to create PayPal subscription.").then(Tn):void 0,createVaultSetupToken:Fe==="setup_token"?()=>ut("Failed to create PayPal setup token.").then(Tn):void 0,onApprove:p,onCancel:()=>{if(qe())return;let h=Et.current.get(Rt)??Qe.current;h&&Et.current.delete(h.surfaceKey),Qe.current=null,Hn(),O.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),X.current=!0,Pn({generation:h?.generation,remount:!0,focus:!1})},onError:h=>{if(qe()||H.current!==Rt)return;let w=h instanceof Error?h.message:"PayPal failed to render.";if(Y(`onError rendered=${Cn} msg=${w.slice(0,120)}`),Cn){let M=Et.current.get(Rt)??Qe.current;if(M&&!Lt(M.generation)||!M&&qt.current===At.current)return;if(Ln(w)){ct(M?.generation);return}if(Hn(),zr(h)){O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Jt(h,M),De(()=>It.current?.(Tt("paypal",w))),M&&Et.current.delete(M.surfaceKey),Qe.current=null,ct(M?.generation);return}let le=w.toLowerCase();O.error({errorCode:le.includes("popup")&&le.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),M&&Et.current.delete(M.surfaceKey),Qe.current=null,Pn({generation:M?.generation,remount:!0,showRetry:!0,focus:!0}),Dt(h,{code:"paypal_runtime_failed"});return}Nt(w)}}),ne=N.isEligible();if(Y(`isEligible=${ne}`),O.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ne){ee(!1),Nt("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Vt=N,he&&Y(`container:dims ${it(en)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),he&&typeof MutationObserver<"u"&&(cn=new MutationObserver(h=>{if(!qe()){for(let w of h)if(w.type==="childList")w.addedNodes.forEach(M=>{if(!(M instanceof Element))return;let le=M.tagName.toLowerCase(),ye=(M.getAttribute("title")??"").slice(0,40),Be=le==="iframe"?` ${dn(M)}`:"";Y(`child+ ${le}${ye?` title="${ye}"`:""}${Be} dims=${it(M)}`)});else if(w.type==="attributes"&&w.target instanceof Element){let M=w.target;if(M.tagName.toLowerCase()!=="iframe")continue;let le=w.attributeName;(le==="src"||le==="srcdoc")&&Y(`attr~ iframe ${le}=${le==="srcdoc"?`[${(M.getAttribute("srcdoc")??"").length}ch]`:tn(M.getAttribute("src"))} dims=${it(M)}`)}}}),cn.observe(en,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let k=h=>{if(qe()||Cn)return;let w=en.querySelectorAll("iframe"),M=typeof document<"u"&&"hasStorageAccess"in document;Y(`watchdog:${h} container=${it(en)} children=${en.childElementCount} iframes=${w.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${M} paypalNetRequests=${Ht.value}`),w.forEach((le,ye)=>{let Be=(le.getAttribute("title")??"").slice(0,40);Y(` iframe[${ye}] ${it(le)}${Be?` title="${Be}"`:""} ${dn(le)}`);let Ke=Dn(le);Ke&&Y(` ${Ke}`)}),un.length===0&&Y(" (no PayPal/zoid window errors captured)")};he&&(Ct.push(setTimeout(()=>k("3s"),3e3)),Ct.push(setTimeout(()=>k("8s"),8e3)),Ct.push(setTimeout(()=>k("15s"),15e3))),Y("render:start");let P=O.startTiming();Ct.push(setTimeout(()=>{qe()||Cn||(Y("watchdog:11s retryable render timeout"),Nt("PayPal Buttons render did not settle within 11000ms.",!0))},Ss)),N.render(en).then(()=>{if(Y(`render:resolved inactive=${qe()}`),Yn(),qe()){sn();return}Cn=!0,ee(!0),ve(!1),Oe.current?.("ready"),O.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"checkout_render",durationMs:O.elapsed(P),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(h=>{let w=h instanceof Error?h.message:"PayPal failed to render.";Y(`render:rejected msg=${w.slice(0,120)}`),Yn(),Nt(w)})}).catch(c=>{let p=c instanceof Error?c.message:"PayPal SDK failed to load.";Y(`loadScript:rejected msg=${p.slice(0,120)}`),Nt(p)})},0);return()=>{ke=!0,clearTimeout(pt),dt&&clearTimeout(dt),Yn(),sn()}},[G,Le,r,m,i,Fe,Ze,e,Q,Z,O]);let cr=he?(0,kn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ce?"#fef2f2":"#f3f4f6",border:`1px solid ${ce?"#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=${$} failed=${ce})`,$e.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return
|
|
3
|
+
${$e.join(`
|
|
4
|
+
`)}`]}):null;return ce&&!j?he?(0,kn.jsx)("div",{children:cr}):null:(0,kn.jsxs)("div",{children:[cr,(0,kn.jsxs)("div",{"aria-hidden":pe?!0:void 0,style:pe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:vo},children:[!$&&!pe&&(0,kn.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,kn.jsx)("div",{ref:ae,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:vo,display:"flex",opacity:$?1:0},"aria-busy":ie||y},Z)]},Z),_&&(0,kn.jsx)("button",{ref:Te,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:ot,style:ks,children:"Try PayPal again"})]})}function $r(e){return(0,kn.jsx)(ai,{...e})}function ii(e){return(0,kn.jsx)(ai,{...e})}var qr=require("react/jsx-runtime");function vr({children:e,margin:t,icon:n=!0,styleOverride:o}){return(0,qr.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"}:{},...o??{}},children:[n&&(0,qr.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,qr.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 kt=require("react/jsx-runtime");function hn({status:e,errorMessage:t,authorized:n=!1,processingLabel:o="PROCESSING...",successLabel:r,errorLabel:i="PAYMENT FAILED",successNote:m="You will be automatically redirected, do not close or navigate away from this window."}){return(0,kt.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,kt.jsxs)("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,kt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,kt.jsxs)("svg",{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,kt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,kt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,kt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,kt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,kt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,kt.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,kt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,kt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,kt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,kt.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,kt.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&o,e==="success"&&(r??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&m!==null&&(0,kt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:m}),e==="error"&&t&&(0,kt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,kt.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 pi=require("@flopay/shared"),yt=require("react");var mi=require("react/jsx-runtime");function Yr({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,p]=(0,yt.useState)(e instanceof Promise?null:e),[d,I]=(0,yt.useState)(t instanceof Promise||!t?null:t),[g,h]=(0,yt.useState)(null),k=(0,yt.useRef)(null),w=(0,yt.useRef)(null),x=(0,yt.useRef)(null),y=Sr(r);(0,yt.useEffect)(()=>{y({class:"lifecycle",name:"checkout.mount"})},[y]),(0,yt.useEffect)(()=>{a&&y({class:"lifecycle",name:"sdk.initialize.ready"})},[y,a]),(0,yt.useEffect)(()=>{if(a)return Tt(a)?.subscribe?.(y)},[y,a]),(0,yt.useEffect)(()=>{if(!(!d||d===a))return Tt(d)?.subscribe?.(y)},[y,a,d]),(0,yt.useEffect)(()=>{if(!a)return;let f=Tt(a);return k.current=f?.beginCheckout()??f?.now()??0,f?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{f?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,yt.useEffect)(()=>{let f=!1;return e instanceof Promise?e.then(ie=>{f||p(ie)},()=>{f||y({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):p(e),()=>{f=!0}},[y,e]),(0,yt.useEffect)(()=>{let f=!1;if(!t){I(null);return}return t instanceof Promise?t.then(ie=>{f||I(ie)},()=>{f||y({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):I(t),()=>{f=!0}},[y,t]),(0,yt.useEffect)(()=>{if(!a){h(null);return}let f=a.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return h(f),()=>{f.destroy()}},[a,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),(0,yt.useEffect)(()=>{if(!a||!g||w.current===g)return;w.current=g;let f=Tt(a);f?.log({name:"checkout.rendered",stage:"checkout_render"}),y({class:"lifecycle",name:"checkout.rendered"}),f?.performance({stage:"checkout_render",durationMs:f.elapsed(k.current??0),durationMode:"machine"})},[g,y,a]);let v=(0,yt.useCallback)(()=>{if(!a||!g||x.current===g)return;x.current=g;let f=Tt(a);f?.log({name:"checkout.interactive",stage:"checkout_interactive"}),f?.performance({stage:"checkout_interactive",durationMs:f.elapsed(k.current??0),durationMode:"machine"})},[g,a]),H=(0,pi.resolveBillingApiUrl)(n?.billingApiUrl),M=(0,yt.useMemo)(()=>({flopay:a,paypalFlopay:d,elements:g,billingApiUrl:H,reportInteractive:v,emitInstrument:y}),[a,d,g,H,v,y]);return(0,mi.jsx)(Wt.Provider,{value:M,children:o})}var Io="flopay_recent_completion_";function kr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Io+e,JSON.stringify(t))}catch{}}function oa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Io+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Io+e),!1):!0}catch{return!1}}var Ir=require("@flopay/js"),Be=require("@flopay/shared");var Gr="card";async function zs(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:p}=await e.retrieveSetupIntent(t);return{error:p,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 Us(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:p,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:p??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function ia(e,t){return Object.assign(e,{checkoutMethod:t})}function Vn(e,t){let n=e instanceof Be.FloPayError?e:new Be.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 Wr(e,t){try{return await e()}catch(n){throw Vn(n,t)}}function yi(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 $s(e){return e.status==="succeeded"||e.status==="declined"}async function fi(e){if(typeof document>"u"||typeof window>"u")throw new Be.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Be.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let h=new AbortController,k=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",k);let w=window.setTimeout(()=>h.abort(),r);try{let x=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!x.ok)return{status:"unknown"};let y=await x.json().catch(()=>null);return qs(y)}catch{return{status:"unknown"}}finally{window.clearTimeout(w),e.signal?.removeEventListener("abort",k)}},p=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.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 I=document.createElement("iframe");I.setAttribute("title","Card authentication"),I.setAttribute("allow","payment"),I.tabIndex=0,I.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(";"),I.src=e.nextActionRedirectUrl,d.appendChild(I),document.body.appendChild(d),I.focus();let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let h=await new Promise((k,w)=>{let x=!1,y=0,v=0,H=0,M=!1,f=()=>{window.clearTimeout(y),window.clearInterval(v),window.clearTimeout(H),window.removeEventListener("message",Q),I.removeEventListener("load",O),e.signal?.removeEventListener("abort",Z)},ie=async()=>{if(!(x||M)){M=!0;try{let ve=await a();if(x||!$s(ve))return;x=!0,f(),k(ve)}finally{M=!1}}},O=()=>{window.clearTimeout(H),H=window.setTimeout(()=>{ie()},250)},Z=()=>{x||(x=!0,f(),w(new Be.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Q=ve=>{if(ve.source!==I.contentWindow||g&&ve.origin!==g)return;let B=ve.data;!B||typeof B!="object"||B.source!=="flopay-vault-3ds-return"||x||(x=!0,f(),k(null))};y=window.setTimeout(()=>{x||(x=!0,f(),w(new Be.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),v=window.setInterval(()=>{ie()},n),I.addEventListener("load",O),window.addEventListener("message",Q),e.signal?.addEventListener("abort",Z),e.signal?.aborted&&Z()});return h||await a()}finally{d.parentNode?.removeChild(d),p?.isConnected&&p.focus()}}function qs(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Qn(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=Xn(o)??o;return ia(new Be.FloPayError(a,"api_error",{code:(0,Be.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Be.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function aa(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Eo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function js(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function gi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Eo(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let d of a)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||Eo(d)))return d;let p=o.gateways;if(p&&typeof p=="object"){let d=p.stripe;if(d&&typeof d=="object"){let I=d,g=[I.stripeClientSecret,I.clientSecret];for(let h of g)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||Eo(h)))return h}}}}async function Vs({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=gi(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new Ir.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Eo(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function Er({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:p}){let d=e.replace(/\/+$/,""),I=t??n.id,g=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",k=n.customer?.email??n.accountData?.email??"",w=n.customer?.firstName??n.accountData?.firstName??"",x=n.customer?.lastName??n.accountData?.lastName??"",y=n.customer?.country??n.accountData?.country??void 0,v=n.customer?.zip??n.accountData?.zip??void 0,H=new Ir.PaymentAPI(d,p===!1?{telemetry:!1}:void 0),M=await js(()=>H.processPayment(h,{sessionId:I,nonce:g,tokenizedData:o,accountData:{userId:h,email:k,firstName:w,lastName:x,country:y,zip:v},returnUrl:a??aa(n)}));if(M.ok){let O=typeof M.json=="function"?await M.json().catch(()=>null):null;return(0,Be.isAuthorizationOnlySession)(n)||O?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof O?.paymentId=="string"?O.paymentId:n.paymentId,sessionId:typeof O?.sessionId=="string"?O.sessionId:I,authorizationExpiresAt:typeof O?.authorizationExpiresAt=="string"?O.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:jr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:jr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let f;try{f=await M.json()}catch{throw new Be.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:M.status})}if(f?.type==="paypal_redirect_required"||f?.type==="3ds_required"){let O=gi(f);if(!O)throw new Be.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:M.status});return{type:f.type,threeDSecureToken:O,paymentMethodId:f.paymentMethodId}}if(f?.gatewayErrorCode==="authentication_required"){let O=await Vs({billingApiUrl:d,sessionId:I,nonce:g,responseJson:f});if(O)return O;throw ia(new Be.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ie=new Be.FloPayError(f?.message??"Payment failed. Please try again.","api_error",{code:f?.code??f?.gatewayErrorCode,declineCode:f?.declineCode??f?.gatewayDeclineReason,statusCode:M.status});throw Object.assign(ie,{telemetryOutcome:(0,Be.classifyPaymentRejection)(M.status,f)})}async function Ro(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:p,returnUrl:d,telemetry:I}){let g=t?.getRawProvider();if(!g)throw Vn(new Be.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw ia(new Be.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=(0,Be.isSetupIntentClientSecret)(e.threeDSecureToken),k=null,w=e.paymentMethodId,x=await Wr(()=>zs(g,e.threeDSecureToken,h),"card");if(x){if(x.error)throw Vn(new Be.FloPayError(x.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:x.error.code}),"card");let v=x.intent;!w&&v?.payment_method&&(typeof v.payment_method=="string"?w=v.payment_method:"id"in v.payment_method&&(w=v.payment_method.id??void 0))}let y=w?await Wr(()=>Us(g,e.threeDSecureToken,{payment_method:w,return_url:d??aa(p)??window.location.href},h),"card"):null;if(y){if(y.error)throw Vn(new Be.FloPayError(y.error.message??"3DS authentication failed.","api_error",{code:y.error.code}),"card");k=y.intent}else{let v=await Wr(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(v.error)throw Vn(new Be.FloPayError(v.error.message??"3DS authentication failed.","api_error",{code:v.error.code}),"card");k=(h?v.setupIntent:v.paymentIntent)??null}if(k&&(k.status==="requires_capture"||k.status==="succeeded"||k.status==="processing")){let v=await Er({billingApiUrl:o,sessionId:a,session:p,telemetry:I,tokenizedData:{id:k.id,type:"card",threeDSecureActionResultTokenId:k.id},returnUrl:d});return v.type==="success"?{...v.result,paymentIntentId:v.result.paymentIntentId??k.id,paymentMethodId:v.result.paymentMethodId??w}:Ro(v,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:p,returnUrl:d,telemetry:I})}throw Vn(new Be.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw Vn(new Be.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:w}=await Wr(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(w)throw Vn(new Be.FloPayError(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:k}=await Wr(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??aa(p)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(k)throw Vn(new Be.FloPayError(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Be.FloPayError("Unsupported payment redirect state.","api_error")}function dr(e){if(e instanceof Be.FloPayError){let r=Xn(e.message);return r&&r!==e.message?Object.assign(new Be.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Xn(t)??t;return new Be.FloPayError(n,"api_error")}function _o(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Be.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function xo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[p,d]=await Promise.all([(0,Ir.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,Ir.loadFloPay)(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(I=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",I),null)):Promise.resolve(null)]);return{flopay:p,paypalFlopay:t?a?d:p:null}}var er=require("@flopay/js"),P=require("@flopay/shared"),vt=require("@stripe/react-stripe-js"),i=Za(require("react"),1);function hi(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var Pi={alipay:new URL("./payment-logos/alipay.svg",Ae).href,bancontact:new URL("./payment-logos/bancontact.svg",Ae).href,blik:new URL("./payment-logos/blik.svg",Ae).href,eps:new URL("./payment-logos/eps.svg",Ae).href,giropay:new URL("./payment-logos/giropay.svg",Ae).href,ideal:new URL("./payment-logos/ideal.svg",Ae).href,klarna:new URL("./payment-logos/klarna.svg",Ae).href,p24:new URL("./payment-logos/p24.svg",Ae).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",Ae).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",Ae).href};var Kn=require("react"),vi=require("react/jsx-runtime");function Rr({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:a,onReady:p,onError:d,onValidation:I}){let g=(0,Kn.useRef)(null),h=(0,Kn.useRef)(p),k=(0,Kn.useRef)(d),w=(0,Kn.useRef)(I);h.current=p,k.current=d,w.current=I;let x=(0,Kn.useRef)(o);return x.current=o,(0,Kn.useEffect)(()=>{let y=g.current;if(!y)return;let v=!0,H=!1,M=()=>{!v||H||(H=!0,h.current?.())},f=e.on("ready",()=>{M()}),ie=e.on("error",Q=>{k.current?.(Q.message??"There was a problem loading the secure card form.")}),O=e.on("validation",Q=>{w.current?.(Q.message??null)}),Z={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...x.current?{theme:x.current}:{}};return e.mount(y,Z).then(()=>{M()}).catch(Q=>{v&&k.current?.(Q instanceof Error?Q.message:"Failed to load the secure card form.")}),()=>{v=!1,f(),ie(),O(),e.unmount()}},[e,t,n,r]),(0,Kn.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,vi.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields",style:a})}function _r(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let r=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),a=Math.round((r>>16&255)*o),p=Math.round((r>>8&255)*o),d=Math.round((r&255)*o);return`#${(1<<24|a<<16|p<<8|d).toString(16).slice(1)}`}function sa(e){if(typeof e=="number"||typeof e=="string")return e}function To({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=g=>typeof g=="string"&&g?g:void 0,a=t.submitButton,p=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",d=n==="buttons",I=t.nameInput;return{primaryColor:p,primaryHoverColor:o(r?.colorPrimaryHover)??_r(p,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(I?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(d?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:o(I?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(sa(I?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px"}}var l=require("react/jsx-runtime"),Ln="flopay_stripe_resume",bi="flopay_wallet_resume";function _i(e){return e instanceof P.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Mo(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new er.PaymentAPI(e).createSessionIntent(...n)}catch(o){throw _i(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Jr="flopay_paypal_resume",Ks=250,Ci="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ua(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Fo({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new er.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Hs(e){return e instanceof P.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function la(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var Ys=`
|
|
9
|
+
`})]})})}var si=require("@flopay/shared"),Ft=require("react");var li=require("react/jsx-runtime");function jr({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:r}){let[i,m]=(0,Ft.useState)(e instanceof Promise?null:e),[d,R]=(0,Ft.useState)(t instanceof Promise||!t?null:t),g=(0,Ft.useRef)(null),v=(0,Ft.useRef)(null),b=hr(o);(0,Ft.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,Ft.useEffect)(()=>{i&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,i]),(0,Ft.useEffect)(()=>{if(i)return xt(i)?.subscribe?.(b)},[b,i]),(0,Ft.useEffect)(()=>{if(!(!d||d===i))return xt(d)?.subscribe?.(b)},[b,i,d]),(0,Ft.useEffect)(()=>{if(!i)return;let y=xt(i);return g.current=y?.beginCheckout()??y?.now()??0,y?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{y?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,Ft.useEffect)(()=>{let y=!1;return e instanceof Promise?e.then(C=>{y||m(C)},()=>{y||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):m(e),()=>{y=!0}},[b,e]),(0,Ft.useEffect)(()=>{let y=!1;if(!t){R(null);return}return t instanceof Promise?t.then(C=>{y||R(C)},()=>{y||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):R(t),()=>{y=!0}},[b,t]),(0,Ft.useEffect)(()=>{if(!i||v.current===i)return;v.current=i;let y=xt(i);y?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),y?.performance({stage:"checkout_render",durationMs:y.elapsed(g.current??0),durationMode:"machine"})},[b,i]);let A=(0,si.resolveBillingApiUrl)(n?.billingApiUrl),D=(0,Ft.useMemo)(()=>({flopay:i,paypalFlopay:d,billingApiUrl:A,emitInstrument:b}),[i,d,A,b]);return(0,li.jsx)(gn.Provider,{value:D,children:r})}var Po="flopay_recent_completion_";function Pr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Po+e,JSON.stringify(t))}catch{}}function Zo(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Po+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Po+e),!1):!0}catch{return!1}}var br=require("@flopay/js"),Ae=require("@flopay/shared");var Kr="card";async function Es(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:m}=await e.retrieveSetupIntent(t);return{error:m,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:o,error:r}=await e.retrievePaymentIntent(t);return{error:r,intent:o??null}}async function Rs(e,t,n,o){if(o){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:m,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:m??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:r,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:r??null}}function ea(e,t){return Object.assign(e,{checkoutMethod:t})}function $n(e,t){let n=e instanceof Ae.FloPayError?e:new Ae.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 Vr(e,t){try{return await e()}catch(n){throw $n(n,t)}}function ci(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 _s(e){return e.status==="succeeded"||e.status==="declined"}async function di(e){if(typeof document>"u"||typeof window>"u")throw new Ae.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ae.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,o=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let v=new AbortController,b=()=>v.abort();e.signal?.aborted?v.abort():e.signal?.addEventListener("abort",b);let A=window.setTimeout(()=>v.abort(),o);try{let D=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:v.signal});if(!D.ok)return{status:"unknown"};let y=await D.json().catch(()=>null);return Ts(y)}catch{return{status:"unknown"}}finally{window.clearTimeout(A),e.signal?.removeEventListener("abort",b)}},m=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.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 R=document.createElement("iframe");R.setAttribute("title","Card authentication"),R.setAttribute("allow","payment"),R.tabIndex=0,R.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(";"),R.src=e.nextActionRedirectUrl,d.appendChild(R),document.body.appendChild(d),R.focus();let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let v=await new Promise((b,A)=>{let D=!1,y=0,C=0,te=0,G=!1,S=()=>{window.clearTimeout(y),window.clearInterval(C),window.clearTimeout(te),window.removeEventListener("message",re),R.removeEventListener("load",U),e.signal?.removeEventListener("abort",Q)},ge=async()=>{if(!(D||G)){G=!0;try{let be=await i();if(D||!_s(be))return;D=!0,S(),b(be)}finally{G=!1}}},U=()=>{window.clearTimeout(te),te=window.setTimeout(()=>{ge()},250)},Q=()=>{D||(D=!0,S(),A(new Ae.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},re=be=>{if(be.source!==R.contentWindow||g&&be.origin!==g)return;let oe=be.data;!oe||typeof oe!="object"||oe.source!=="flopay-vault-3ds-return"||D||(D=!0,S(),b(null))};y=window.setTimeout(()=>{D||(D=!0,S(),A(new Ae.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),C=window.setInterval(()=>{ge()},n),R.addEventListener("load",U),window.addEventListener("message",re),e.signal?.addEventListener("abort",Q),e.signal?.aborted&&Q()});return v||await i()}finally{d.parentNode?.removeChild(d),m?.isConnected&&m.focus()}}function Ts(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Jn(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),r=e?.message??t,i=Wn(r)??r;return ea(new Ae.FloPayError(i,"api_error",{code:(0,Ae.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ae.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),o)}function Qo(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function bo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function xs(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function ui(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||bo(r)))return r;let o=e?.data;if(o&&typeof o=="object"){let r=o,i=[r.threeDSecureToken,r.clientSecret,r.stripeClientSecret,r.id];for(let d of i)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||bo(d)))return d;let m=r.gateways;if(m&&typeof m=="object"){let d=m.stripe;if(d&&typeof d=="object"){let R=d,g=[R.stripeClientSecret,R.clientSecret];for(let v of g)if(typeof v=="string"&&v.length>0&&(!t?.requirePaymentIntentClientSecret||bo(v)))return v}}}}async function As({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let r=ui(o,{requirePaymentIntentClientSecret:!0});if(typeof r=="string"&&r.length>0)return{type:"3ds_required",threeDSecureToken:r};if(!t)return null;try{let d=(await new br.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(bo(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function Cr({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:r,returnUrl:i,telemetry:m}){let d=e.replace(/\/+$/,""),R=t??n.id,g=o??n.clientSecret,v=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",A=n.customer?.firstName??n.accountData?.firstName??"",D=n.customer?.lastName??n.accountData?.lastName??"",y=n.customer?.country??n.accountData?.country??void 0,C=n.customer?.zip??n.accountData?.zip??void 0,te=new br.PaymentAPI(d,m===!1?{telemetry:!1}:void 0),G=await xs(()=>te.processPayment(v,{sessionId:R,nonce:g,tokenizedData:r,accountData:{userId:v,email:b,firstName:A,lastName:D,country:y,zip:C},returnUrl:i??Qo(n)}));if(G.ok){let U=typeof G.json=="function"?await G.json().catch(()=>null):null;return(0,Ae.isAuthorizationOnlySession)(n)||U?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof U?.paymentId=="string"?U.paymentId:n.paymentId,sessionId:typeof U?.sessionId=="string"?U.sessionId:R,authorizationExpiresAt:typeof U?.authorizationExpiresAt=="string"?U.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Nr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:Nr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}}let S;try{S=await G.json()}catch{throw new Ae.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:G.status})}if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let U=ui(S);if(!U)throw new Ae.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:G.status});return{type:S.type,threeDSecureToken:U,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let U=await As({billingApiUrl:d,sessionId:R,nonce:g,responseJson:S});if(U)return U;throw ea(new Ae.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ge=new Ae.FloPayError(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:G.status});throw Object.assign(ge,{telemetryOutcome:(0,Ae.classifyPaymentRejection)(G.status,S)})}async function Co(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:r,sessionId:i,session:m,returnUrl:d,telemetry:R}){let g=t?.getRawProvider();if(!g)throw $n(new Ae.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw ea(new Ae.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let v=(0,Ae.isSetupIntentClientSecret)(e.threeDSecureToken),b=null,A=e.paymentMethodId,D=await Vr(()=>Es(g,e.threeDSecureToken,v),"card");if(D){if(D.error)throw $n(new Ae.FloPayError(D.error.message??`Failed to retrieve 3DS ${v?"setup":"payment"} status.`,"api_error",{code:D.error.code}),"card");let C=D.intent;!A&&C?.payment_method&&(typeof C.payment_method=="string"?A=C.payment_method:"id"in C.payment_method&&(A=C.payment_method.id??void 0))}let y=A?await Vr(()=>Rs(g,e.threeDSecureToken,{payment_method:A,return_url:d??Qo(m)??window.location.href},v),"card"):null;if(y){if(y.error)throw $n(new Ae.FloPayError(y.error.message??"3DS authentication failed.","api_error",{code:y.error.code}),"card");b=y.intent}else{let C=await Vr(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(C.error)throw $n(new Ae.FloPayError(C.error.message??"3DS authentication failed.","api_error",{code:C.error.code}),"card");b=(v?C.setupIntent:C.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let C=await Cr({billingApiUrl:r,sessionId:i,session:m,telemetry:R,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:d});return C.type==="success"?{...C.result,paymentIntentId:C.result.paymentIntentId??b.id,paymentMethodId:C.result.paymentMethodId??A}:Co(C,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:r,sessionId:i,session:m,returnUrl:d,telemetry:R})}throw $n(new Ae.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let v=(n??t)?.getRawProvider();if(!v)throw $n(new Ae.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:A}=await Vr(()=>v.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(A)throw $n(new Ae.FloPayError(A.message??"PayPal authorization failed.","api_error",{code:A.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await Vr(()=>v.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Qo(m)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw $n(new Ae.FloPayError(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ae.FloPayError("Unsupported payment redirect state.","api_error")}function sr(e){if(e instanceof Ae.FloPayError){let o=Wn(e.message);return o&&o!==e.message?Object.assign(new Ae.FloPayError(o,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Wn(t)??t;return new Ae.FloPayError(n,"api_error")}function So(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ae.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function wo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:o,telemetry:r}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[m,d]=await Promise.all([(0,br.loadFloPay)(e,{billingApiUrl:n,locale:o,telemetry:r}),i?(0,br.loadFloPay)(t,{billingApiUrl:n,locale:o,telemetry:r}).catch(R=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",R),null)):Promise.resolve(null)]);return{flopay:m,paypalFlopay:t?i?d:m:null}}var Xn=require("@flopay/js"),f=require("@flopay/shared"),ht=require("@stripe/react-stripe-js"),a=Ha(require("react"),1);function pi(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var mi={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 qn=require("react"),yi=require("react/jsx-runtime");function Sr({capture:e,html:t,messageToken:n,expectedOrigin:o,theme:r,containerStyle:i,onReady:m,onError:d,onValidation:R}){let g=(0,qn.useRef)(null),v=(0,qn.useRef)(m),b=(0,qn.useRef)(d),A=(0,qn.useRef)(R);v.current=m,b.current=d,A.current=R;let D=(0,qn.useRef)(r);return D.current=r,(0,qn.useEffect)(()=>{let y=g.current;if(!y)return;let C=!0,te=!1,G=()=>{!C||te||(te=!0,v.current?.())},S=e.on("ready",()=>{G()}),ge=e.on("error",re=>{b.current?.(re.message??"There was a problem loading the secure card form.")}),U=e.on("validation",re=>{A.current?.(re.message??null)}),Q={html:t,...n?{messageToken:n}:{},...o?{expectedOrigin:o}:{},...D.current?{theme:D.current}:{}};return e.mount(y,Q).then(()=>{G()}).catch(re=>{C&&b.current?.(re instanceof Error?re.message:"Failed to load the secure card form.")}),()=>{C=!1,S(),ge(),U(),e.unmount()}},[e,t,n,o]),(0,qn.useEffect)(()=>{r&&e.applyTheme?.(r)},[e,r]),(0,yi.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields",style:i})}function wr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let o=parseInt(n[1],16),r=Math.max(0,Math.min(1,1-t)),i=Math.round((o>>16&255)*r),m=Math.round((o>>8&255)*r),d=Math.round((o&255)*r);return`#${(1<<24|i<<16|m<<8|d).toString(16).slice(1)}`}function ta(e){if(typeof e=="number"||typeof e=="string")return e}function ko({appearance:e,buttonsStyles:t,layout:n="default"}){let o=e?.variables,r=g=>typeof g=="string"&&g?g:void 0,i=t.submitButton,m=r(o?.colorPrimary)??r(i?.backgroundColor)??"#4A49FF",d=n==="buttons",R=t.nameInput;return{primaryColor:m,primaryHoverColor:r(o?.colorPrimaryHover)??wr(m,.12),inputBackgroundColor:r(t.cardInputBackground)??r(o?.colorBackground)??"#ffffff",textColor:r(t.cardInputColor)??r(R?.color)??r(o?.colorText)??"#262833",borderColor:r(t.cardInputBorder)??(d?"#e5e7eb":"#A4A4FF"),placeholderColor:r(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:r(o?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:r(R?.fontFamily)??r(o?.fontFamily)??"Poppins, sans-serif",fontSize:r(t.cardInputFontSize)??r(o?.fontSizeBase)??"16px",fontWeight:String(ta(R?.fontWeight)??400),borderRadius:r(o?.borderRadius)??"8px"}}var l=require("react/jsx-runtime"),Mn="flopay_stripe_resume",fi="flopay_wallet_resume";function wi(e){return e instanceof f.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Eo(e,t,...n){let o=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:o});try{return await new Xn.PaymentAPI(e).createSessionIntent(...n)}catch(r){throw wi(r)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),r}}var Hr="flopay_paypal_resume",Ms=250,gi="Just a moment \u2014 we are finalizing your order. Please press pay again.";function aa(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Ro({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new Xn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function Fs(e){return e instanceof f.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function na(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var Bs=`
|
|
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 @@ ${je.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
|
-
`,Ao=44;function pa(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 Ws={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},xi={width:"100%",minHeight:Ao,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 Gs(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Si(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ti(e){return e==="paypal"?"PayPal":(0,P.getStripeMethodDisplayName)(e)}function Js(e,t){let n=`We couldn't open ${Ti(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ai(e){let t=(0,i.useRef)(0),n=(0,i.useRef)(null),r=(0,i.useRef)(null),o=(0,i.useCallback)((y=r.current)=>{let v=y;v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),a=(0,i.useCallback)((y,v)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(y),y.timer=setTimeout(()=>{y.timer=null,r.current?.generation===y.generation&&(r.current=null,n.current=y.generation,e(y.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},v))},[o,e]),p=(0,i.useCallback)(y=>{y.yieldedControl&&a(y,600)},[a]),d=(0,i.useCallback)(y=>{o();let v=t.current+1;t.current=v,n.current=null;let H={generation:v,method:y,timer:null,yieldedControl:!1};return r.current=H,v},[o]),I=(0,i.useCallback)(y=>{let v=r.current;return typeof y=="number"&&v?.generation!==y?!1:(o(v),r.current=null,(typeof y!="number"||n.current===y)&&(n.current=null),!0)},[o]),g=(0,i.useCallback)(y=>{let v=r.current,H=y??v?.generation??t.current;(!y||v?.generation===y)&&(o(v),r.current=null),n.current=H},[o]),h=(0,i.useCallback)(y=>n.current===(y??t.current),[]),k=(0,i.useCallback)(y=>r.current?.generation===y&&n.current!==y,[]),w=(0,i.useCallback)(()=>{let y=r.current;y&&p(y)},[p]),x=(0,i.useCallback)(()=>{let y=r.current;y&&(y.yieldedControl=!0,o(y))},[o]);return(0,i.useEffect)(()=>{let y=()=>{document.visibilityState==="visible"?w():x()},v=()=>{x()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",v),window.addEventListener("focus",w),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",v),window.removeEventListener("focus",w),o()}},[o,x,w]),{startAttempt:d,finishAttempt:I,invalidateAttempt:g,isAttemptInvalidated:h,isAttemptCurrent:k}}function Xs(e){let t=(0,P.getPostalCodeExample)(e);return`Enter a valid ${(0,P.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Zs(e,t,n){let r=(0,P.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,p=a&&!o,d=a&&!!o&&!(0,P.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:p,malformed:d}}function wi(e,t){return t instanceof P.FloPayError?t:new P.FloPayError(t instanceof Error?t.message:`${Gs(e)} before-click hook failed.`,"validation_error")}function ca(){return(0,l.jsx)("style",{children:Ys})}function Qs(e){return typeof e=="number"?`${e}px`:e}function Mi(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Fi({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,l.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,l.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,l.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 ki(e){return e!=="unavailable"&&e!=="load_error"}function Bo(e){return(0,l.jsx)(tl,{...e})}function Ii({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:p=!1,onButtonClick:d,onDecline:I,onTechnicalFailure:g,runBeforeButtonClick:h,onLoadStateChange:k,placeholderBorderRadius:w}){let x=In(),{emitInstrument:y}=(0,i.useContext)(Wt),v=(0,vt.useStripe)(),H=(0,vt.useElements)(),[M,f]=(0,i.useState)("loading");(0,i.useEffect)(()=>{k?.(M)},[M,k]);let[ie,O]=(0,i.useState)(!1),Z=(0,i.useRef)(!1),Q=(0,i.useRef)(null),ve=(0,i.useRef)(null),[B,se]=(0,i.useState)(0),[xe,Se]=(0,i.useState)(!1),he=(0,i.useRef)(!1),$=(0,i.useRef)(new Map),{startAttempt:N,finishAttempt:oe,invalidateAttempt:Me,isAttemptInvalidated:Te,isAttemptCurrent:te}=Ai((G,T,fe)=>{g?.(G,T,{...fe,popupBlocked:fe?.popupBlocked??Zn(T)}),Se(!0),se($e=>$e+1)});(0,i.useEffect)(()=>{xe&&ve.current?.focus()},[xe,B]);let K=(0,i.useCallback)(()=>{se(G=>G+1)},[]),re=(0,i.useCallback)((G,T,fe)=>{Me(fe),g?.("paypal",G,{code:T,popupBlocked:Zn(G)}),Se(!0),K()},[Me,g,K]),ye=(0,i.useCallback)(()=>{window.setTimeout(()=>{(Q.current?.querySelector("iframe")??Q.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{he.current&&(he.current=!1,ye())},[ye,B]);let be=(0,i.useCallback)(()=>{Se(!1),a?.(null),ye()},[ye,a]);(0,i.useEffect)(()=>{if(!v||Z.current)return;let G=new URLSearchParams(window.location.search),T=G.get("payment_intent"),fe=G.get("payment_intent_client_secret"),$e=G.get("redirect_status");if(!T||!fe)return;Z.current=!0;let qe;try{let L=localStorage.getItem(Jr);if(L){let le=JSON.parse(L);le.clientSecret===fe&&(qe={...le.accountPatch?{accountPatch:le.accountPatch}:{},...le.sessionId?{sessionId:le.sessionId}:{},...le.nonce?{nonce:le.nonce}:{}})}}catch{}try{localStorage.removeItem(Jr)}catch{}let ue=new URL(window.location.href);ue.searchParams.delete("payment_intent"),ue.searchParams.delete("payment_intent_client_secret"),ue.searchParams.delete("redirect_status"),window.history.replaceState({},"",ue.toString()),(async()=>{try{if(O(!0),$e==="failed"){let ee="PayPal payment was declined. Please try again.";a?.(ee),I?.(Mt("paypal",ee));return}let{paymentIntent:L,error:le}=await v.retrievePaymentIntent(fe);if(le){a?.(le.message??"Failed to retrieve PayPal payment status.");return}if(L&&(L.status==="requires_capture"||L.status==="succeeded")){let ee=typeof L.payment_method=="string"?L.payment_method:L.payment_method?.id;o({id:ee??L.id,type:"card",threeDSecureActionResultTokenId:L.id,isPaypal:!0},qe)}else{let ee="PayPal payment was not completed. Please try again.";a?.(ee),I?.(Mt("paypal",ee))}}catch(L){a?.(L instanceof Error?L.message:"Failed to complete PayPal payment.")}finally{O(!1)}})()},[v,o,a,I]);let ne=(0,i.useCallback)(async G=>{if(p||ie){G.reject();return}let T=h?await h("paypal"):{proceed:!0};if(!T.proceed){$.current.delete(B),G.reject();return}let fe=N("paypal");$.current.set(B,{generation:fe,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),Se(!1),d?.("paypal"),G.resolve()},[$,p,d,h,N,ie,B]),_e=(0,i.useCallback)(async G=>{if(!v||!H)return;let T=$.current.get(B);if(T&&!te(T.generation)){$.current.delete(B);return}if(!T&&Te()||T&&!oe(T.generation))return;T||oe();let fe=T??null;if($.current.delete(B),!fe&&h){let L=await h("paypal");if(!L.proceed){G.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}fe={accountPatch:L.accountPatch,sessionId:L.sessionId,nonce:L.nonce}}let $e=fe?.sessionId??e,qe=fe?.nonce??t,ue=fe?.accountPatch?.email??n;try{if(O(!0),a?.(null),!$e||!ue)throw new Error("Missing sessionId or email for PayPal payment");let L=v.createPaymentMethod,{error:le,paymentMethod:ee}=await L({type:"paypal"});if(le){re(le,"stripe_paypal_create_payment_method_failed",T?.generation),G.paymentFailed({reason:"fail"});return}let ze=await Mo(r,y,$e,qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ee?.id??null,intentKind:"payment"});if(ze.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Le=ze.clientSecret,Qe={return_url:window.location.href};if(ee?.id&&(Qe.payment_method=ee.id),typeof window<"u")try{localStorage.setItem(Jr,JSON.stringify({clientSecret:Le,sessionId:$e,nonce:qe,accountPatch:fe?.accountPatch}))}catch{}let{error:ce,paymentIntent:ft}=await v.confirmPayment({clientSecret:Le,confirmParams:Qe,redirect:"if_required"});if(ce){if(typeof window<"u")try{localStorage.removeItem(Jr)}catch{}if(Vr(ce)){let je=ce.message??"Your payment was declined.";a?.(je),I?.(Mt("paypal",je,{code:jn(ce),declineCode:br(ce)})),await Fo({billingApiUrl:r,sessionId:$e,nonce:qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:jn(ce)??"provider_declined"}})}else re(ce,"stripe_paypal_confirm_failed",T?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Jr)}catch{}let V=typeof ft?.payment_method=="string"?ft.payment_method:ft?.payment_method?.id;o({id:V??ft?.id,type:"card",threeDSecureActionResultTokenId:ft?.id,isPaypal:!0},{accountPatch:fe?.accountPatch,sessionId:$e,nonce:qe});return}catch(L){re(L,"stripe_paypal_failed",T?.generation)}finally{O(!1)}},[v,H,e,t,n,r,y,o,a,I,h,re,oe,te,Te,B]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Fi,{state:M,placeholderTestId:"flopay-paypal-placeholder",borderRadius:w,children:(0,l.jsxs)("div",{ref:Q,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[xe&&(0,l.jsx)("button",{ref:ve,type:"button","data-testid":"flopay-paypal-retry-button",onClick:be,style:xi,children:"Try PayPal again"}),(0,l.jsx)(vt.ExpressCheckoutElement,{onReady:G=>f(Mi(G,["paypal"])),onLoadError:()=>{f("load_error"),ua(Tt(x),"paypal","paypal")},onClick:ne,onConfirm:_e,onCancel:()=>{let G=$.current.get(B);$.current.delete(B),Tt(x)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Me(G?.generation),Se(!1),he.current=!0,K()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},B)]})}),ie&&(0,l.jsx)(Pn,{status:"processing"})]})}function Ei({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:p,onErrorChange:d,onButtonClick:I,onDecline:g,onTechnicalFailure:h,runBeforeButtonClick:k,onLoadStateChange:w,placeholderBorderRadius:x}){let y=In(),{emitInstrument:v}=(0,i.useContext)(Wt),H=(0,vt.useStripe)(),M=(0,vt.useElements)(),[f,ie]=(0,i.useState)("loading");(0,i.useEffect)(()=>{w?.(f)},[f,w]);let[O,Z]=(0,i.useState)(!1),Q=(0,i.useRef)(null),ve=(0,i.useRef)(null),[B,se]=(0,i.useState)(0),[xe,Se]=(0,i.useState)(!1),[he,$]=(0,i.useState)("google_pay"),N=(0,i.useRef)(!1),oe=(0,i.useRef)("google_pay"),Me=(0,i.useRef)("google_pay"),Te=(0,i.useRef)(new Map),{startAttempt:te,finishAttempt:K,invalidateAttempt:re,isAttemptInvalidated:ye,isAttemptCurrent:be}=Ai((ue,L,le)=>{h?.(ue,L,{...le,popupBlocked:le?.popupBlocked??Zn(L)}),$(ue),Se(!0),se(ee=>ee+1)});(0,i.useEffect)(()=>{xe&&ve.current?.focus()},[xe,B]);let ne=(0,i.useCallback)(()=>{se(ue=>ue+1)},[]),_e=(0,i.useCallback)((ue,L,le,ee)=>{re(ee),h?.(ue,L,{code:le,popupBlocked:Zn(L)}),$(ue),Se(!0),ne()},[re,h,ne]),G=(0,i.useCallback)(()=>{window.setTimeout(()=>{(Q.current?.querySelector("iframe")??Q.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{N.current&&(N.current=!1,G())},[G,B]);let T=(0,i.useCallback)(()=>{Se(!1),d?.(null),G()},[G,d]),fe=(0,i.useCallback)(async ue=>{if(!H||!M)return;let L=Te.current.get(B);if(L&&!be(L.generation)){Te.current.delete(B);return}if(!L&&ye()||L&&!K(L.generation))return;L||K();let le=ue.expressPaymentType??L?.method??oe.current,ee=L??null;Te.current.delete(B);let ze=Si(le);if(!ee&&k){let V=await k(ze);if(!V.proceed){ue.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}ee={accountPatch:V.accountPatch,sessionId:V.sessionId,nonce:V.nonce}}let Le=ze,Qe=ee?.sessionId??e,ce=ee?.nonce??t,ft=ee?.accountPatch?.email??n;try{Z(!0),d?.(null);let{error:V}=await M.submit();if(V){_e(le,V,"stripe_wallet_submit_failed",L?.generation);return}let{error:je,paymentMethod:bt}=await H.createPaymentMethod({elements:M});if(je||!bt){_e(le,je??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",L?.generation);return}if(!Qe||!ft)throw new Error("Missing sessionId or email for wallet payment");let J=await Mo(r,v,Qe,ce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:le??ze,paymentMethodId:bt.id,intentKind:o});if(J.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Ct=J.clientSecret,{error:He,intentId:en}=(0,P.isSetupIntentClientSecret)(Ct)?await H.confirmCardSetup(Ct,{payment_method:bt.id}).then(Rt=>({error:Rt.error,intentId:Rt.setupIntent?.id})):await H.confirmCardPayment(Ct,{payment_method:bt.id}).then(Rt=>({error:Rt.error,intentId:Rt.paymentIntent?.id}));if(He){if(Vr(He)){let Rt=He.message??"Your payment was declined.";d?.(Rt),g?.(Mt(Le,Rt,{code:jn(He),declineCode:br(He)})),await Fo({billingApiUrl:r,sessionId:Qe,nonce:ce,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:le??ze,providerDeclineReason:jn(He)??"provider_declined"}})}else _e(le,He,"stripe_wallet_confirm_failed",L?.generation);return}p({id:bt.id,type:"card",threeDSecureActionResultTokenId:en},{accountPatch:ee?.accountPatch,sessionId:Qe,nonce:ce})}catch(V){_e(le,V,"stripe_wallet_failed",L?.generation)}finally{Z(!1)}},[H,M,e,t,n,r,v,o,p,d,g,k,_e,K,be,ye,B]),$e=(0,i.useMemo)(()=>{let ue=["applePay","googlePay","paypal","link","amazonPay","klarna"],L=new Set(["applePay","googlePay"]),le=new Set(a.map(P.stripeExpressMethodToOptionKey)),ee={};for(let ze of ue)le.has(ze)?ee[ze]=L.has(ze)?"always":"auto":ee[ze]="never";return ee},[a]),qe=(0,i.useMemo)(()=>a.map(P.stripeExpressMethodToOptionKey),[a]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Fi,{state:f,placeholderTestId:"flopay-wallet-placeholder",borderRadius:x,children:(0,l.jsxs)("div",{ref:Q,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[xe&&(0,l.jsxs)("button",{ref:ve,type:"button","data-testid":"flopay-wallet-retry-button",onClick:T,style:xi,children:["Try ",Ti(he)," again"]}),(0,l.jsx)(vt.ExpressCheckoutElement,{onReady:ue=>{ie(Mi(ue,qe))},onLoadError:ue=>{ie("load_error"),ua(Tt(y),"stripe","wallet")},onClick:async ue=>{oe.current=ue.expressPaymentType,Me.current=Si(ue.expressPaymentType);let L=k?await k(Me.current):{proceed:!0};if(!L.proceed){Te.current.delete(B),ue.reject();return}let le=te(ue.expressPaymentType);Te.current.set(B,{generation:le,method:ue.expressPaymentType,accountPatch:L.accountPatch,sessionId:L.sessionId,nonce:L.nonce}),Se(!1),I?.(Me.current),ue.resolve()},onConfirm:fe,onCancel:()=>{let ue=Te.current.get(B);Te.current.delete(B),Tt(y)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),re(ue?.generation),Se(!1),N.current=!0,ne()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:$e,layout:{maxColumns:1,overflow:"never"}}},B)]})}),O&&(0,l.jsx)(Pn,{status:"processing"})]})}function el({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:p,backgroundColor:d,borderColor:I,textColor:g,borderRadius:h,fontFamily:k}){let w=(0,P.resolveStripeMethodBrandVariant)(e,t),x=Pi[e],y=w?.backgroundColor??d??"#ffffff",v=w?.borderColor??I??"#d1d5db",H=w?.textColor??g??"#262833";return(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&p()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Ao,padding:"0 1rem",backgroundColor:y,color:H,border:`1px solid ${v}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:k,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,l.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,P.getStripeMethodDisplayName)(e)}\u2026`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,P.hasVendoredStripeMethodLogo)(e)?8:0},children:[x?(0,l.jsx)("img",{src:x,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):w?.logoSvg?(0,l.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:w.logoSvg}}):null,(0,l.jsx)("span",{children:(0,P.getStripeMethodDisplayName)(e)})]}),a&&(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:H,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,l.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function da({method:e,sessionId:t,nonce:n,email:r,billingName:o,billingApiUrl:a,onTokenizedBody:p,onErrorChange:d,onDecline:I,onCancel:g,runBeforeButtonClick:h,onButtonClick:k,isProcessing:w,submitButtonColor:x,submitButtonBorderRadius:y,submitButtonStyle:v,errorText:H}){let M=In(),{emitInstrument:f}=(0,i.useContext)(Wt),ie=(0,vt.useStripe)(),O=(0,vt.useElements)(),[Z,Q]=(0,i.useState)(!1),ve=(0,i.useRef)(!1),[B,se]=(0,i.useState)(!1),[xe,Se]=(0,i.useState)("loading"),he=(0,i.useCallback)(async()=>{if(!ie||!O||w||ve.current||!B)return;ve.current=!0,Q(!0);let $=h?await h("card"):{proceed:!0};if(!$.proceed){ve.current=!1,Q(!1);return}k?.("card");let N=$.sessionId??t,oe=$.nonce??n,Me=$.accountPatch?.email??r;try{d?.(null);let Te=await O.submit();if(Te.error){d?.(Te.error.message??"Payment failed.");return}let te=await ie.createPaymentMethod({elements:O});if(te.error||!te.paymentMethod){d?.(te.error?.message??"Failed to create payment method.");return}let K=te.paymentMethod;if(!N||!Me)throw new Error("Missing sessionId or email for payment.");let re=K.type||e,ye=await Mo(a,f,N,oe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,paymentMethodId:null,intentKind:"payment"});if(ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let be=ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(Ln,JSON.stringify({clientSecret:be,sessionId:N,nonce:oe,accountPatch:$.accountPatch,paymentMethodId:K.id,paymentMethodType:K.type??e,gateway:"stripe"}))}catch{}let{error:ne,paymentIntent:_e}=await ie.confirmPayment({clientSecret:be,confirmParams:{return_url:window.location.href,payment_method:K.id},redirect:"if_required"});if(ne){if(typeof window<"u")try{localStorage.removeItem(Ln)}catch{}let fe=ne.message??"Payment failed.";d?.(fe),I?.(Mt("card",fe,{code:ne.code})),await Fo({billingApiUrl:a,sessionId:N,nonce:oe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ne.code??"provider_declined"}});return}let G=_e?.status;if(!go(G)){if(typeof window<"u")try{localStorage.removeItem(Ln)}catch{}let fe=G==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(fe),I?.(Mt("card",fe,{code:G??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Ln)}catch{}let T=typeof _e?.payment_method=="string"?_e.payment_method:_e?.payment_method?.id;p({id:T??K.id,type:"card",threeDSecureActionResultTokenId:_e?.id,gateway:"stripe",paymentMethodType:K.type??e},{accountPatch:$.accountPatch,sessionId:N,nonce:oe})}catch(Te){d?.(Te instanceof Error?Te.message:"Payment failed. Please try again.")}finally{ve.current=!1,Q(!1)}},[ie,O,w,B,h,k,t,n,r,a,f,e,p,d,I]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,l.jsx)(vt.PaymentElement,{onReady:()=>Se("ready"),onLoadError:()=>{Se("load_error"),ua(Tt(M),"stripe","apm")},onChange:$=>{se(!!$.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...r?{email:r}:{}}}}}),(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{he()},disabled:!B||Z||w||xe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:x,color:"white",border:"none",borderRadius:y,fontSize:"1rem",fontWeight:600,cursor:!B||Z||w||xe!=="ready"?"not-allowed":"pointer",opacity:!B||Z||w||xe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...v??{}},children:Z?"Processing\u2026":`Pay with ${(0,P.getStripeMethodDisplayName)(e)}`}),H&&(0,l.jsx)(wr,{margin:"0.75rem 0 0",children:H})]})}function Ri({sessionId:e,nonce:t,email:n,billingName:r,billingApiUrl:o,paymentElementMethods:a,stripeInstance:p,paymentElementBaseOptions:d,onTokenizedBody:I,onErrorChange:g,onButtonClick:h,onDecline:k,runBeforeButtonClick:w,onLoadStateChange:x,isProcessing:y=!1,submitButtonColor:v="#4A49FF",submitButtonBorderRadius:H=8,submitButtonStyle:M,buttonAppearance:f,themeId:ie,onExpandApm:O,expandedApmMethod:Z}){let{emitInstrument:Q}=(0,i.useContext)(Wt),[ve,B]=(0,i.useState)(null),[se,xe]=(0,i.useState)(null),Se=(0,i.useRef)(!1);(0,i.useEffect)(()=>{a.length>0&&p?x?.("ready"):p||x?.("loading")},[a.length,p,x]);let he=(0,i.useCallback)(async te=>{if(!p||Se.current||y)return;Se.current=!0,xe(te);let K=w?await w("card"):{proceed:!0};if(!K.proceed){Se.current=!1,xe(null);return}h?.("card");let re=K.sessionId??e,ye=K.nonce??t,be=K.accountPatch?.email??n;try{if(g?.(null),!re||!be)throw new Error("Missing sessionId or email for payment.");let ne=await Mo(o,Q,re,ye??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,paymentMethodId:null,intentKind:"payment"});if(ne.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let _e=ne.clientSecret;if(typeof window<"u")try{localStorage.setItem(Ln,JSON.stringify({clientSecret:_e,sessionId:re,nonce:ye,accountPatch:K.accountPatch,paymentMethodType:te,gateway:"stripe"}))}catch{}let{error:G,paymentIntent:T}=await p.confirmPayment({clientSecret:_e,confirmParams:{return_url:window.location.href,payment_method_data:{type:te,billing_details:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...be?{email:be}:{}}}},redirect:"if_required"});if(G){if(typeof window<"u")try{localStorage.removeItem(Ln)}catch{}let qe=G.message??"Payment failed.";g?.(qe),k?.(Mt("card",qe,{code:G.code})),await Fo({billingApiUrl:o,sessionId:re,nonce:ye,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,providerDeclineReason:G.code??"provider_declined"}});return}let fe=T?.status;if(!go(fe)){if(typeof window<"u")try{localStorage.removeItem(Ln)}catch{}let qe=fe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(qe),k?.(Mt("card",qe,{code:fe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Ln)}catch{}let $e=typeof T?.payment_method=="string"?T.payment_method:T?.payment_method?.id;I({id:$e??T?.id,type:"card",threeDSecureActionResultTokenId:T?.id,gateway:"stripe",paymentMethodType:te},{accountPatch:K.accountPatch,sessionId:re,nonce:ye})}catch(ne){g?.(ne instanceof Error?ne.message:"Payment failed. Please try again.")}finally{Se.current=!1,xe(null)}},[p,y,w,h,e,t,n,o,Q,r,I,g,k]),[$,N]=(0,i.useState)(null),oe=O?Z??null:$,Me=(0,i.useCallback)(te=>{Se.current||y||oe&&oe!==te||((0,P.needsStripeMethodExplicitConfirm)(te)?O?O(te):N(te):he(te))},[oe,y,he,O]),Te=(0,i.useMemo)(()=>$?{...d,paymentMethodTypes:[$]}:null,[$,d]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(te=>{let K=Z===te,re=se===te,ye=se!==null&&se!==te||Z!=null&&Z!==te;return(0,l.jsxs)(i.default.Fragment,{children:[(0,l.jsx)(el,{method:te,themeId:ie,submitting:re,disabled:ye,highlighted:K,hasNextStep:(0,P.needsStripeMethodExplicitConfirm)(te),onClick:()=>Me(te),backgroundColor:f?.backgroundColor,borderColor:f?.borderColor,textColor:f?.textColor,borderRadius:f?.borderRadius,fontFamily:f?.fontFamily}),!O&&$===te&&Te&&p&&(0,l.jsx)(vt.Elements,{stripe:p,options:Te,children:(0,l.jsx)(da,{method:te,sessionId:e,email:n,billingName:r,billingApiUrl:o,onTokenizedBody:I,onErrorChange:g,onDecline:k,onCancel:()=>N(null),runBeforeButtonClick:w,onButtonClick:h,isProcessing:y,submitButtonColor:v,submitButtonBorderRadius:H,submitButtonStyle:M})},te)]},te)})})}function tl({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:p,onDecline:d,onTokenizedBody:I,firstName:g,lastName:h,chv:k,className:w,isProcessing:x,error:y,onErrorChange:v,showPayPal:H=!0,showStripe:M=!0,enabledPaymentMethods:f,enabledPaymentMethodCountries:ie,showApplePay:O=!0,showGooglePay:Z=!0,layout:Q="default",theme:ve,buttonsTheme:B,buttonsStyles:se,appearance:xe,cardButtonContent:Se,cardBackButtonContent:he,cardTitleContent:$,showSecurityFooter:N,onButtonClick:oe,onBeforeButtonClick:Me,enableAVS:Te,cardFieldOrder:te,cardPreFormSlot:K,avsLayout:re="row",country:ye,zip:be,addressLine1:ne,addressLine2:_e,city:G,state:T,onCountryChange:fe,onZipChange:$e,avsCheck:qe,checkoutType:ue,checkoutLayout:L,totalAmount:le=0,currency:ee="usd",initialCardOpen:ze=!1,directPaypal:Le,isSubscription:Qe=!1,session:ce,dataAttachmentPending:ft=!1,debug:V=!1}){let je=In(),bt=ho(),J=(0,i.useContext)(kn),{emitInstrument:Ct}=(0,i.useContext)(Wt),He=ft||J.claimPending===!0,en=vo(),[Rt,A]=(0,i.useState)(!1),[Ce,gt]=(0,i.useState)(null),[Ue,qt]=(0,i.useState)(ye??"US"),[Jt,Ze]=(0,i.useState)(be??""),[St,et]=(0,i.useState)(ne??""),[Ft,Ge]=(0,i.useState)(_e??""),[jt,_t]=(0,i.useState)(G??""),[tn,Dt]=(0,i.useState)(T??""),[Tn,ln]=(0,i.useState)({}),at=(0,i.useRef)(be??""),Lt=(0,i.useRef)(ye??"US"),Je=(0,i.useRef)(ne??""),An=(0,i.useRef)(_e??""),dt=(0,i.useRef)(G??""),bn=(0,i.useRef)(T??""),Ot=(0,i.useRef)({});(0,i.useEffect)(()=>{let s=(U,X,pe,W,ke)=>{if(Ot.current[U])return;let Fe=X?.trim();!Fe||Fe===pe.current||(pe.current=Fe,W(Fe),ke?.(Fe))};s("country",ye,Lt,qt,fe),s("zip",be,at,Ze,$e),s("addressLine1",ne,Je,et),s("addressLine2",_e,An,Ge),s("city",G,dt,_t),s("state",T,bn,Dt)},[ye,be,ne,_e,G,T,fe,$e]);let me=(0,i.useMemo)(()=>(0,P.resolveAVSConfig)(Te),[Te]),Yn=me!==null,Mn=(0,i.useMemo)(()=>(0,P.isAuthorizationOnlySession)(ce),[ce]),Fn=!!ce?.vault?.html,Bn=!!ce?.gateways?.pcivault,F=!!(ce?.gateways?.stripe?.enabledPaymentMethods??f)?.includes("card"),tt=Fn||F||Bn,Ie=!!(M&&tt&&je&&e),[Cn,Ve]=(0,i.useState)(()=>Q!=="buttons"||ze?e??null:null),[Wn,tr]=(0,i.useState)(0),Vt=Q!=="buttons"||ze||!!e&&Cn===e,ut=(0,i.useMemo)(()=>!je||!Ie||!e||!Vt?null:je.cardCapture({sessionId:e,captureMethod:ce?.captureMethod}),[je,Ie,e,Vt,ce?.captureMethod]),Xt=(0,i.useMemo)(()=>{let s=Ue,U=me?(0,P.isAVSFieldVisible)(me.postal_code,s):!1;return Zs(s,Jt,U)},[me,Ue,Jt]),{avsInvalid:Kt,invalidAvsFields:it}=(0,i.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!Ie||!me)return{avsInvalid:!1,invalidAvsFields:s};let U=Ue,X=(ke,Fe)=>(0,P.isAVSFieldVisible)(ke,U)&&!Fe.trim(),pe={line1:X(me.address_line_1,St),city:X(me.city,jt),state:X(me.state,tn),zip:Xt.empty||Xt.malformed};return{avsInvalid:pe.line1||pe.city||pe.state||pe.zip,invalidAvsFields:pe}},[Ie,me,Ue,St,jt,tn,Xt]),[cn,dn]=(0,i.useState)(!1),[Gn,Sn]=(0,i.useState)(!1),[nn,un]=(0,i.useState)(()=>la(ce?.vault)),[we,wt]=(0,i.useState)(ze&&tt?"card":"buttons"),[st,rn]=(0,i.useState)(null),pn=we==="expanding"||we==="card",zn=ce?.gateways?.stripe?"stripe":void 0,mn=(0,i.useCallback)(()=>{Ct?.({class:"card_surface",provider:zn})},[zn,Ct]),Nt=280,Ht=(0,i.useRef)(null),Yt=(0,i.useCallback)(s=>{Ht.current&&clearTimeout(Ht.current),Ht.current=setTimeout(()=>{Ht.current=null,s()},Nt)},[Nt]);(0,i.useEffect)(()=>()=>{Ht.current&&clearTimeout(Ht.current)},[]);let Jn=(0,i.useCallback)(()=>{mn(),Ve(e??null),tr(s=>s+1),wt("expanding"),Yt(()=>wt("card"))},[Yt,mn,e]),Un=(0,i.useCallback)(()=>{wt("collapsing"),Yt(()=>wt("buttons"))},[Yt]),Dn=(0,i.useCallback)(s=>{rn(s),wt("apm-expanding"),Yt(()=>wt("apm-form"))},[Yt]),$n=(0,i.useCallback)(()=>{wt("apm-collapsing"),Yt(()=>{wt("buttons"),rn(null)})},[Yt]);(0,i.useEffect)(()=>{Q==="buttons"&&ze&&tt&&(Ve(e??null),wt("card"))},[Q,ze,tt,e]);let[zt,nt]=(0,i.useState)(null),yn=(0,i.useRef)(!1),Ut=(0,i.useRef)(null),pt=(0,i.useRef)("idle"),[Zt,xt]=(0,i.useState)(null),nr=(0,i.useRef)(Zt);(0,i.useEffect)(()=>{nr.current=Zt},[Zt]);let mt=n||en,u=y??Ce,c=(0,i.useMemo)(()=>(0,P.resolveTheme)(ve),[ve]),m=(0,i.useMemo)(()=>{let s=c?.buttonsLayout??(0,P.resolveButtonsLayoutTheme)(B);return se?{...s,...se,cardButton:{...s.cardButton,...se.cardButton},cardFormContainer:{...s.cardFormContainer,...se.cardFormContainer},backButton:{...s.backButton,...se.backButton},backButtonIcon:{...s.backButtonIcon,...se.backButtonIcon},submitButton:{...s.submitButton,...se.submitButton},title:{...s.title,...se.title}}:s},[c,B,se]),q=xe??c?.appearance,ae=(0,i.useMemo)(()=>To({appearance:q,buttonsStyles:m,layout:Q}),[q,m,Q]),Y=J.inlineSessionPatchProcessing??!1,E=(x??Rt)||Y,C=mt.replace(/\/+$/,""),b=(0,i.useMemo)(()=>ea({userId:o,email:r,firstName:g,lastName:h,country:ye,zip:be},Tn),[o,r,g,h,ye,be,Tn]),S=[b.firstName,b.lastName].filter(s=>!!s?.trim()).join(" "),D=(0,i.useMemo)(()=>je?je.getRawProvider():null,[je]),de=(0,i.useMemo)(()=>bt?bt.getRawProvider():null,[bt]),Pe=le||100,Oe=(0,i.useMemo)(()=>q?(0,er.toStripeAppearance)(q):null,[q]),Ye=Oe?{appearance:Oe}:null,At=(0,i.useMemo)(()=>{let s=Oe??{},U=s.rules??{};return{...s,rules:{...U,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...U[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...U[".AccordionItemContents"]??{}}}}},[Oe]),Ee=(0,i.useMemo)(()=>{let s=ri(le);return{...s,currency:ee.toLowerCase(),paymentMethodCreation:"manual",...s.mode==="payment"?{captureMethod:"manual"}:{},...Ye}},[le,ee,Ye]),Re=(0,i.useMemo)(()=>({mode:"payment",amount:Pe,currency:ee.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Ye}),[Pe,ee,Ye]),j=(0,i.useCallback)(s=>{gt(s),v?.(s)},[v]);(0,i.useEffect)(()=>{!Ie||!ut||ut.setCardFieldOrder?.(te??null,me==null)},[Ie,ut,te,me]),(0,i.useEffect)(()=>{(we==="expanding"||we==="collapsing"||we==="apm-expanding"||we==="apm-collapsing")&&j(null)},[we,j]);let kt=(0,i.useCallback)((s,U,X)=>{d?.(Mt(s,U,X))},[d]),We=(0,i.useCallback)((s,U,X)=>{let pe=X?.popupBlocked??Zn(U),W=Js(s,pe),ke=lr(X?.code)??jn(U)??"external_payment_method_failed",Fe=new P.FloPayError(W,"api_error",{code:"external_payment_method_failed",param:s});nt(null),Q==="buttons"&&(wt("buttons"),rn(null)),j(W),p?.(Fe),console.error("[FloPay] External payment method failed:",{method:s,code:ke,popupBlocked:pe})},[Q,p,j]);(0,i.useEffect)(()=>{if(!Ie||!e){un(null);return}let s=la(ce?.vault);if(s){un(s);return}if(!Vt){un(null);return}un(null);let U=!0;return new er.PaymentAPI(C).getVaultCapture(e,t).then(X=>{if(!U)return;let pe=la(X);pe?un(pe):j("Failed to load the secure card form.")}).catch(X=>{U&&j(X instanceof Error?X.message:"Failed to load the secure card form.")}),()=>{U=!1}},[Ie,Vt,Wn,e,ce?.vault?.html,ce?.vault?.messageToken,ce?.vault?.expectedOrigin,C,t,j]);let rt=(0,i.useRef)({onComplete:a,onError:p,updateError:j,emitDecline:kt,resolvedAccount:b,avsConfig:me,avsCheckProp:qe,sessionId:e,nonce:t,baseUrl:C,captureMethod:ce?.captureMethod,paymentId:ce?.paymentId,authorizationExpiresAt:ce?.authorizationExpiresAt});rt.current={onComplete:a,onError:p,updateError:j,emitDecline:kt,resolvedAccount:b,avsConfig:me,avsCheckProp:qe,sessionId:e,nonce:t,baseUrl:C,captureMethod:ce?.captureMethod,paymentId:ce?.paymentId,authorizationExpiresAt:ce?.authorizationExpiresAt};let rr=(0,i.useRef)(!1),ka=(0,i.useCallback)(()=>{let{resolvedAccount:s,avsConfig:U,avsCheckProp:X}=rt.current,pe=Lt.current||s.country||"US",W=U?(0,P.isAVSFieldVisible)(U.state,pe):!1,ke=U?(0,P.isAVSFieldVisible)(U.address_line_1,pe):!1,Fe=U?(0,P.isAVSFieldVisible)(U.postal_code,pe):!1,ht=U?(0,P.isAVSFieldVisible)(U.city,pe):!1,$t=U?(0,P.isAVSFieldVisible)(U.address_line_2,pe):!1,Pt=ke&&!W&&Fe?(0,P.getStateFromPostalCode)(pe,(at.current??"").trim()):null,lt=W?bn.current:Pt;return{accountData:{userId:s.userId??"",email:s.email??"",firstName:s.firstName??"",lastName:s.lastName??"",...Fe&&at.current?{zip:at.current}:{},...ht&&dt.current?{city:dt.current}:{},...lt?{state:lt}:{},...ke&&Je.current?{addressLine1:Je.current}:{},...$t&&An.current?{addressLine2:An.current}:{},country:pe},...X!==void 0?{avsCheck:X}:{},...U?{avsConfig:{country:(0,P.isAVSFieldVisible)(U.country,pe),postal_code:Fe,address_line_1:ke,address_line_2:$t,city:ht,state:W}}:{}}},[]),to=(0,i.useRef)(He);to.current=He,(0,i.useEffect)(()=>{He||u!==Ci||rt.current.updateError(null)},[He,u]),(0,i.useEffect)(()=>{!Ie||!ut||ut.setSubmitGate?.(Kt||He)},[Ie,ut,Kt,He]),(0,i.useEffect)(()=>{if(!Ie||!ut)return;rr.current=!1;let s=!1,U=ut.on("submitting",()=>{dn(!0),Ut.current&&clearTimeout(Ut.current),pt.current="validation-window",Ut.current=setTimeout(()=>{Ut.current=null,pt.current==="validation-window"&&(pt.current="processing")},Ks),nt("processing");let{baseUrl:Fe,sessionId:ht,nonce:$t,updateError:Pt,onError:lt}=rt.current;!ht||!$t||new er.PaymentAPI(Fe).patchAccountSnapshot(ht,$t,ka(),{telemetryMode:"best_effort"}).catch(Ke=>{if(!Hs(Ke))return;let qn=Ke instanceof Error?Ke.message:"Please check your billing address and try again.";Pt(qn),pt.current="idle",nt(null),lt?.(Ke instanceof P.FloPayError?Ke:new P.FloPayError(qn,"api_error"))})}),X=ut.on("complete",async Fe=>{if(kr(Fe.sessionId??rt.current.sessionId),pt.current="terminal",nt("success"),await new Promise(Pt=>setTimeout(Pt,1200)),rr.current)return;rr.current=!0;let ht=rt.current,$t=(0,P.isAuthorizationOnlySession)(ht)||Fe.outcome==="authorized";rt.current.onComplete?.($t?{status:"authorized",paymentIntentId:Fe.intentId,paymentId:Fe.paymentId??ht.paymentId,sessionId:Fe.sessionId??ht.sessionId,authorizationExpiresAt:Fe.authorizationExpiresAt??ht.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Fe.intentId,checkoutMethod:"card"})}),pe=ut.on("decline",async Fe=>{let{updateError:ht,emitDecline:$t}=rt.current,Pt=Fe.message??"Your payment was declined. Please try another card or contact your bank.";pt.current="terminal",ht(Pt),nt("error");let lt=Fe.failureOutcome??(0,P.normalizeCheckoutFailureOutcome)(Fe.declineReason)??"authorization_declined";$t("card",Pt,{code:lt,declineCode:lt}),await new Promise(Ke=>setTimeout(Ke,1500)),!s&&(pt.current="idle",nt(null))}),W=ut.on("error",async Fe=>{let{updateError:ht,onError:$t}=rt.current,Pt=Fe.message??"There was a problem processing your payment. Please try again.";pt.current="terminal",ht(Pt),nt("error"),$t?.(new P.FloPayError(Pt,"api_error",{code:Fe.failureOutcome??"capture_failed"})),await new Promise(lt=>setTimeout(lt,1500)),!s&&(pt.current="idle",nt(null))}),ke=ut.on("blocked",()=>{if(!to.current){dn(!0);return}rt.current.updateError(Ci)});return()=>{s=!0,Ut.current&&(clearTimeout(Ut.current),Ut.current=null),pt.current="idle",U(),X(),pe(),W(),ke()}},[Ie,ut]);let on=!!Le?.clientId,Tr=Array.isArray(f),no=Tr&&f.length>0,Xi=Tr&&f.includes("paypal"),{expressMethods:ro,paymentElementMethods:Ar}=(0,i.useMemo)(()=>(0,P.partitionStripeMethods)(f,{excludePaypal:on}),[f,on]),Ia=on||!!bt,Zi=(0,i.useMemo)(()=>Ia?ro.filter(s=>s!=="paypal"):ro,[ro,Ia]),Qi=(0,i.useMemo)(()=>{let s=[];return O&&s.push("apple_pay"),Z&&s.push("google_pay"),s},[O,Z]),oo=Tr?Zi:Qi,es=M&&oo.length>0,$o=Yn?Ue:ye,ao=(0,i.useMemo)(()=>{let s=$o?.trim().toUpperCase();return s?ie?Ar.filter(U=>{let X=ie[U];return!X||X.length===0||X.includes(s)}):(0,P.filterStripeMethodsByCountry)(Ar,$o):Ar},[Ar,$o,ie]),qo=(0,i.useMemo)(()=>({mode:"payment",amount:Pe,currency:ee.toLowerCase(),paymentMethodCreation:"manual",appearance:At}),[Pe,ee,At]),[Ea,Ra]=(0,i.useState)("loading"),[_a,xa]=(0,i.useState)("loading"),[Ta,Aa]=(0,i.useState)("loading"),[ts,jo]=(0,i.useState)(!1),[Ma,Vo]=(0,i.useState)("loading"),[io,ns]=(0,i.useState)();(0,i.useEffect)(()=>{ns(hi())},[]);let Fa=H&&(on||(Tr?Xi:io===!1)),Ba=M&&es,Mr=!He&&Fa&&on,Da=Ma==="retrying"||Ma==="exhausted",Fr=!He&&Fa&&!!de&&(!on||Da),Br=!He&&Ba&&!!D,Dr=!He&&M&&no&&ao.length>0&&!!D,rs=Mr&&!Da?ts:Fr&&ki(Ea),os=Br&&ki(_a),as=Dr&&Ta!=="load_error",La=s=>s==="loading"||s==="ready",Oa=Mr||Fr&&La(Ea)||Br&&La(_a)||Dr&&Ta!=="load_error",so=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(!so.current){if(!M&&!H){so.current=!0;let s=new P.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(s),j(s.message)}else if(!M&&H&&!on&&!de){so.current=!0;let s=new P.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(s),j(s.message)}else if(io!==void 0&&!He&&!tt&&!Oa){so.current=!0;let s=new P.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"});p?.(s),j(s.message)}}},[M,H,on,de,io,He,tt,Oa,p,j]);let Na=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(Na.current||!no)return;let s=[];O!==!0&&s.push("showApplePay"),Z!==!0&&s.push("showGooglePay"),s.length!==0&&(Na.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[no,O,Z]);let za=(0,i.useCallback)((s,U)=>J.applyInlineSessionPatch?J.applyInlineSessionPatch(s).then(X=>({error:null,sessionId:X.sessionId||e,nonce:X.session?.clientSecret||t})).catch(X=>{let pe=wi(U,X);return j(pe.message),p?.(pe),{error:pe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[J.applyInlineSessionPatch,t,p,e,j]),wn=(0,i.useCallback)(async s=>{if(!Me)return{proceed:!0};try{let U=await Me({method:s,sessionId:e||void 0,createSession:J.inlineSessionDraft});if(U===!1)return{proceed:!1};if(U&&typeof U=="object"){U.account&&ln(pe=>({...pe??{},...U.account}));let X=await za(U,s);return X.error?{proceed:!1,accountPatch:U.account}:{proceed:!0,accountPatch:U.account,sessionId:X.sessionId,nonce:X.nonce}}return{proceed:!0}}catch(U){let X=wi(s,U);return j(X.message),p?.(X),{proceed:!1}}},[za,J.inlineSessionDraft,Me,p,e,j]),Ua=(0,i.useCallback)(async(s,U)=>{if(yn.current)return;yn.current=!0,A(!0),nt("processing"),j(null);let X=U?.sessionId??e,pe=U?.nonce??t,W=ea(b,U?.accountPatch),ke=U?.completionPaymentMethodId??jr(s),Fe=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,ht=s.gateway==="stripe"?"stripe":s.gateway==="paypal"||s.isPaypal?"paypal":void 0,$t=()=>{Ct?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:ht})};try{let lt=await new er.PaymentAPI(C).processPayment(W.userId??"",{sessionId:X,nonce:pe,tokenizedData:Fe,accountData:{userId:W.userId??"",email:W.email??"",firstName:W.firstName??"",lastName:W.lastName??"",...me?(()=>{let Xe=Lt.current,gn=(0,P.isAVSFieldVisible)(me.state,Xe),hn=(0,P.isAVSFieldVisible)(me.address_line_1,Xe),Bt=(0,P.isAVSFieldVisible)(me.postal_code,Xe),Ur=hn&&!gn&&Bt?(0,P.getStateFromPostalCode)(Xe,(at.current??"").trim()):null,$r=gn?bn.current:Ur;return{country:Xe,...Bt&&at.current?{zip:at.current}:{},...(0,P.isAVSFieldVisible)(me.city,Xe)&&dt.current?{city:dt.current}:{},...$r?{state:$r}:{},...hn&&Je.current?{addressLine1:Je.current}:{},...(0,P.isAVSFieldVisible)(me.address_line_2,Xe)&&An.current?{addressLine2:An.current}:{}}})():{}},chv:k,avsCheck:qe??!1,checkoutType:ue,checkoutLayout:L,avsConfig:me?{country:(0,P.isAVSFieldVisible)(me.country,Lt.current),postal_code:(0,P.isAVSFieldVisible)(me.postal_code,Lt.current),address_line_1:(0,P.isAVSFieldVisible)(me.address_line_1,Lt.current),address_line_2:(0,P.isAVSFieldVisible)(me.address_line_2,Lt.current),city:(0,P.isAVSFieldVisible)(me.city,Lt.current),state:(0,P.isAVSFieldVisible)(me.state,Lt.current)}:void 0});if(lt.ok){let Xe=lt.status===204?null:await lt.json().catch(()=>null),gn=(0,P.isAuthorizationOnlySession)(ce)||Xe?.status==="authorized";kr(X),nt("success"),xt(null),await new Promise(hn=>setTimeout(hn,1200)),a?.(gn?{status:"authorized",...typeof Xe?.paymentId=="string"?{paymentId:Xe.paymentId}:ce?.paymentId?{paymentId:ce.paymentId}:{},sessionId:typeof Xe?.sessionId=="string"?Xe.sessionId:X,...typeof Xe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Xe.authorizationExpiresAt}:ce?.authorizationExpiresAt?{authorizationExpiresAt:ce.authorizationExpiresAt}:{},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:ke,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:ke,checkoutMethod:s.isPaypal?"paypal":"card"});return}let Ke=await lt.json().catch(()=>null);if(Ke?.type==="paypal_redirect_required"){let Xe=Ke.threeDSecureToken,gn=Ke.paymentMethodId||s.id||"";if(!je||!Xe){nt("error"),j("PayPal authorization required but no token provided.");return}try{let hn=bt?.getRawProvider();if(!hn){j("PayPal is not available.");return}let Bt={return_url:window.location.href};gn&&(Bt.payment_method=gn);let{error:Ur}=await hn.confirmPayment({clientSecret:Xe,confirmParams:Bt,redirect:"if_required"});if(Ur){nt("error");let $r=Ur.message??"PayPal payment failed.";j($r),kt("paypal",$r,{code:Ur.code})}}catch(hn){nt("error"),j(hn instanceof Error?hn.message:"PayPal authorization failed.")}return}if(Ke?.type==="paypal_direct_required"){let Xe=Ke.orderId;if(!Xe){nt("error"),j("PayPal retry required but no order id provided.");return}let gn=nr.current?.attempts??0;if(gn>=2){nt("error"),j("PayPal payment could not be completed after multiple attempts."),kt("paypal","paypal_direct_required retry limit exceeded");return}jo(!1),Vo("loading"),xt({orderId:Xe,attempts:gn+1}),nt(null);return}(0,P.classifyPaymentRejection)(lt.status,Ke)||$t(),nt("error");let qn=Ke?.message??"Payment failed. Please try again.";j(qn),kt(s.isPaypal?"paypal":"card",qn,{code:Ke?.code??Ke?.gatewayErrorCode,declineCode:Ke?.declineCode??Ke?.gatewayDeclineReason}),await new Promise(Xe=>setTimeout(Xe,1500))}catch(Pt){_i(Pt)||$t(),nt("error"),j(Pt instanceof Error?Pt.message:"An unexpected error occurred"),await new Promise(lt=>setTimeout(lt,1500))}finally{A(!1),nt(null),yn.current=!1}},[C,e,t,b,S,k,je,bt,ce,a,p,j,kt,Ct]),fn=(0,i.useCallback)((s,U)=>{I?I(s):Ua(s,U)},[I,Ua]),$a=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(typeof window>"u"||$a.current)return;let s=new URLSearchParams(window.location.search),U=s.get("payment_intent"),X=s.get("payment_intent_client_secret"),pe=s.get("redirect_status");if(!U||!X)return;let W=lt=>{let Ke=localStorage.getItem(lt);if(!Ke)return null;try{return JSON.parse(Ke)}catch{return localStorage.removeItem(lt),null}},ke=W(Ln)??W(bi),Fe;if(ke?.clientSecret){if(ke.clientSecret!==X)return;Fe={...ke.accountPatch?{accountPatch:ke.accountPatch}:{},...ke.sessionId?{sessionId:ke.sessionId}:{},...ke.nonce?{nonce:ke.nonce}:{}}}else if(ke?.sessionId&&ke.sessionId!==e)return;$a.current=!0,localStorage.removeItem(Ln),localStorage.removeItem(bi);let ht=new URL(window.location.href);ht.searchParams.delete("payment_intent"),ht.searchParams.delete("payment_intent_client_secret"),ht.searchParams.delete("redirect_status"),window.history.replaceState({},"",ht.toString());let $t=ke?.paymentMethodType??ke?.tokenType??"card",Pt="card";(async()=>{let lt=je?.getRawProvider();if(!lt){let Bt="Payment is not available \u2014 please refresh and try again.";j(Bt),kt(Pt,Bt);return}if(pe==="failed"){let Bt="Payment was declined. Please try again.";j(Bt),kt(Pt,Bt);return}let{paymentIntent:Ke,error:qn}=await lt.retrievePaymentIntent(X);if(qn){let Bt=qn.message??"Failed to retrieve payment status.";j(Bt),kt(Pt,Bt,{code:qn.code});return}let Xe=Ke?.status,gn=go(Xe);if(!Ke||!gn){let Bt=Xe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";j(Bt),kt(Pt,Bt,{code:Xe??"missing_payment_intent"});return}let hn=typeof Ke.payment_method=="string"?Ke.payment_method:Ke.payment_method?.id;fn({id:hn??ke?.paymentMethodId??ke?.tokenId??Ke.id,type:"card",threeDSecureActionResultTokenId:Ke.id,gateway:ke?.gateway??"stripe",paymentMethodType:$t},Fe)})()},[e,fn,je,j,kt]);let Ko=(0,i.useCallback)(s=>{s.preventDefault()},[]);if(!(je!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Lr=Q==="buttons",Qt=q?.variables,is=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ho=Qt?.colorBackground,ss=Ho&&!is.has(Ho)?Ho:void 0,Or=m.cardInputBorder??(Lr?"#e5e7eb":"#A4A4FF"),Yo=Qt?.colorDanger??"#dc2626",or=s=>cn&&s?Yo:Or,lo=(Xt.malformed||Xt.empty)&&(Gn||cn),ls=lo?Yo:or(it.zip),Wo=m.cardFormContainer?.backgroundColor??ss??(Lr?"white":"#EDEDFF"),Nr=m.cardInputBackground??Qt?.colorBackground??"white",Go=fr(he),qa=fr($),yr=m.nameInput,ja=m.cardInputFontSize??Qs(yr?.fontSize)??Qt?.fontSizeBase??"16px",Va=typeof yr?.fontFamily=="string"?yr.fontFamily:Qt?.fontFamily??"Poppins, sans-serif",Ka=sa(yr?.fontWeight)??400,cs=m.cardInputColor??(typeof yr?.color=="string"?yr.color:void 0)??Qt?.colorText??"#262833",ds=m.cardInputPlaceholderColor??"#9ca3af",It=Qt?.borderRadius??"8px",ar=Qt?.borderRadius??m.cardButton?.borderRadius??It,ir=Qt?.colorPrimary??"#4A49FF",us=Qt?.colorPrimaryHover??_r(ir,.12),Jo=Qt?.colorText??"#262833",Ha={fontSize:ja,fontFamily:Va,fontWeight:Ka,color:cs,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ps={"--flopay-input-placeholder-color":ds,"--flopay-input-font-size":ja,"--flopay-input-font-family":Va,"--flopay-input-font-weight":String(Ka)},zr=m.cardFormContainer??{},Xo=zr.padding??(Lr?"0":"1rem"),Zo=zr.borderRadius??It,ms=ut&&nn?(0,l.jsx)(Rr,{capture:ut,html:nn.html,messageToken:nn.messageToken,expectedOrigin:nn.expectedOrigin,theme:ae,onReady:()=>{if(!me||typeof document>"u")return;let s=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};s();let U=0,X=window.setInterval(()=>{U+=1;let pe=document.activeElement;!!pe&&pe.tagName==="IFRAME"&&pe.id==="flopay_vault_form_iframe"?(s(),window.clearInterval(X)):U>=50&&window.clearInterval(X)},100)},onError:s=>j(s),onValidation:s=>{let U=pt.current;(U==="idle"||U==="validation-window")&&(j(s),s&&pt.current==="validation-window"&&(Ut.current&&(clearTimeout(Ut.current),Ut.current=null),pt.current="idle",nt(null)))}}):(0,l.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"}),Ya=(0,l.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&mn()},style:{backgroundColor:Wo,borderRadius:Zo,...zr,padding:Xo,...ps,display:"flex",flexDirection:"column"},children:[(0,l.jsx)("style",{children:`
|
|
30
|
+
`,Io=44;function ia(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 Ds={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ki={width:"100%",minHeight:Io,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 Ls(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function hi(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ii(e){return e==="paypal"?"PayPal":(0,f.getStripeMethodDisplayName)(e)}function Os(e,t){let n=`We couldn't open ${Ii(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ei(e){let t=(0,a.useRef)(0),n=(0,a.useRef)(null),o=(0,a.useRef)(null),r=(0,a.useCallback)((y=o.current)=>{let C=y;C?.timer&&(clearTimeout(C.timer),C.timer=null)},[]),i=(0,a.useCallback)((y,C)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(y),y.timer=setTimeout(()=>{y.timer=null,o.current?.generation===y.generation&&(o.current=null,n.current=y.generation,e(y.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},C))},[r,e]),m=(0,a.useCallback)(y=>{y.yieldedControl&&i(y,600)},[i]),d=(0,a.useCallback)(y=>{r();let C=t.current+1;t.current=C,n.current=null;let te={generation:C,method:y,timer:null,yieldedControl:!1};return o.current=te,C},[r]),R=(0,a.useCallback)(y=>{let C=o.current;return typeof y=="number"&&C?.generation!==y?!1:(r(C),o.current=null,(typeof y!="number"||n.current===y)&&(n.current=null),!0)},[r]),g=(0,a.useCallback)(y=>{let C=o.current,te=y??C?.generation??t.current;(!y||C?.generation===y)&&(r(C),o.current=null),n.current=te},[r]),v=(0,a.useCallback)(y=>n.current===(y??t.current),[]),b=(0,a.useCallback)(y=>o.current?.generation===y&&n.current!==y,[]),A=(0,a.useCallback)(()=>{let y=o.current;y&&m(y)},[m]),D=(0,a.useCallback)(()=>{let y=o.current;y&&(y.yieldedControl=!0,r(y))},[r]);return(0,a.useEffect)(()=>{let y=()=>{document.visibilityState==="visible"?A():D()},C=()=>{D()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",C),window.addEventListener("focus",A),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",C),window.removeEventListener("focus",A),r()}},[r,D,A]),{startAttempt:d,finishAttempt:R,invalidateAttempt:g,isAttemptInvalidated:v,isAttemptCurrent:b}}function Ns(e){let t=(0,f.getPostalCodeExample)(e);return`Enter a valid ${(0,f.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function zs(e,t,n){let o=(0,f.isPostalCodeSupported)(e),r=t.trim(),i=n&&o,m=i&&!r,d=i&&!!r&&!(0,f.isValidPostalCode)(e,r);return{visible:n,supported:o,required:i,empty:m,malformed:d}}function vi(e,t){return t instanceof f.FloPayError?t:new f.FloPayError(t instanceof Error?t.message:`${Ls(e)} before-click hook failed.`,"validation_error")}function ra(){return(0,l.jsx)("style",{children:Bs})}function Us(e){return typeof e=="number"?`${e}px`:e}function Ri(e,t){let n=e.availablePaymentMethods;return n&&t.some(o=>n[o])?"ready":"unavailable"}function _i({state:e,placeholderTestId:t,borderRadius:n=8,children:o}){return e==="unavailable"||e==="load_error"?null:(0,l.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,l.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,l.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:o})]})}function Pi(e){return e!=="unavailable"&&e!=="load_error"}function _o(e){return(0,l.jsx)(qs,{...e})}function bi({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:r,onErrorChange:i,isProcessing:m=!1,onButtonClick:d,onDecline:R,onTechnicalFailure:g,runBeforeButtonClick:v,onLoadStateChange:b,placeholderBorderRadius:A}){let D=Un(),{emitInstrument:y}=(0,a.useContext)(gn),C=(0,ht.useStripe)(),te=(0,ht.useElements)(),[G,S]=(0,a.useState)("loading");(0,a.useEffect)(()=>{b?.(G)},[G,b]);let[ge,U]=(0,a.useState)(!1),Q=(0,a.useRef)(!1),re=(0,a.useRef)(null),be=(0,a.useRef)(null),[oe,he]=(0,a.useState)(0),[Ne,_e]=(0,a.useState)(!1),Se=(0,a.useRef)(!1),K=(0,a.useRef)(new Map),{startAttempt:O,finishAttempt:ae,invalidateAttempt:ze,isAttemptInvalidated:Te,isAttemptCurrent:X}=Ei((H,_,me)=>{g?.(H,_,{...me,popupBlocked:me?.popupBlocked??Gn(_)}),_e(!0),he(Ye=>Ye+1)});(0,a.useEffect)(()=>{Ne&&be.current?.focus()},[Ne,oe]);let $=(0,a.useCallback)(()=>{he(H=>H+1)},[]),ee=(0,a.useCallback)((H,_,me)=>{ze(me),g?.("paypal",H,{code:_,popupBlocked:Gn(H)}),_e(!0),$()},[ze,g,$]),pe=(0,a.useCallback)(()=>{window.setTimeout(()=>{(re.current?.querySelector("iframe")??re.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{Se.current&&(Se.current=!1,pe())},[pe,oe]);let ve=(0,a.useCallback)(()=>{_e(!1),i?.(null),pe()},[pe,i]);(0,a.useEffect)(()=>{if(!C||Q.current)return;let H=new URLSearchParams(window.location.search),_=H.get("payment_intent"),me=H.get("payment_intent_client_secret"),Ye=H.get("redirect_status");if(!_||!me)return;Q.current=!0;let Ue;try{let F=localStorage.getItem(Hr);if(F){let ie=JSON.parse(F);ie.clientSecret===me&&(Ue={...ie.accountPatch?{accountPatch:ie.accountPatch}:{},...ie.sessionId?{sessionId:ie.sessionId}:{},...ie.nonce?{nonce:ie.nonce}:{}})}}catch{}try{localStorage.removeItem(Hr)}catch{}let ce=new URL(window.location.href);ce.searchParams.delete("payment_intent"),ce.searchParams.delete("payment_intent_client_secret"),ce.searchParams.delete("redirect_status"),window.history.replaceState({},"",ce.toString()),(async()=>{try{if(U(!0),Ye==="failed"){let J="PayPal payment was declined. Please try again.";i?.(J),R?.(Tt("paypal",J));return}let{paymentIntent:F,error:ie}=await C.retrievePaymentIntent(me);if(ie){i?.(ie.message??"Failed to retrieve PayPal payment status.");return}if(F&&(F.status==="requires_capture"||F.status==="succeeded")){let J=typeof F.payment_method=="string"?F.payment_method:F.payment_method?.id;r({id:J??F.id,type:"card",threeDSecureActionResultTokenId:F.id,isPaypal:!0},Ue)}else{let J="PayPal payment was not completed. Please try again.";i?.(J),R?.(Tt("paypal",J))}}catch(F){i?.(F instanceof Error?F.message:"Failed to complete PayPal payment.")}finally{U(!1)}})()},[C,r,i,R]);let Z=(0,a.useCallback)(async H=>{if(m||ge){H.reject();return}let _=v?await v("paypal"):{proceed:!0};if(!_.proceed){K.current.delete(oe),H.reject();return}let me=O("paypal");K.current.set(oe,{generation:me,accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}),_e(!1),d?.("paypal"),H.resolve()},[K,m,d,v,O,ge,oe]),Re=(0,a.useCallback)(async H=>{if(!C||!te)return;let _=K.current.get(oe);if(_&&!X(_.generation)){K.current.delete(oe);return}if(!_&&Te()||_&&!ae(_.generation))return;_||ae();let me=_??null;if(K.current.delete(oe),!me&&v){let F=await v("paypal");if(!F.proceed){H.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}me={accountPatch:F.accountPatch,sessionId:F.sessionId,nonce:F.nonce}}let Ye=me?.sessionId??e,Ue=me?.nonce??t,ce=me?.accountPatch?.email??n;try{if(U(!0),i?.(null),!Ye||!ce)throw new Error("Missing sessionId or email for PayPal payment");let F=C.createPaymentMethod,{error:ie,paymentMethod:J}=await F({type:"paypal"});if(ie){ee(ie,"stripe_paypal_create_payment_method_failed",_?.generation),H.paymentFailed({reason:"fail"});return}let Le=await Eo(o,y,Ye,Ue??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:J?.id??null,intentKind:"payment"});if(Le.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Fe=Le.clientSecret,Ze={return_url:window.location.href};if(J?.id&&(Ze.payment_method=J.id),typeof window<"u")try{localStorage.setItem(Hr,JSON.stringify({clientSecret:Fe,sessionId:Ye,nonce:Ue,accountPatch:me?.accountPatch}))}catch{}let{error:se,paymentIntent:mt}=await C.confirmPayment({clientSecret:Fe,confirmParams:Ze,redirect:"if_required"});if(se){if(typeof window<"u")try{localStorage.removeItem(Hr)}catch{}if(zr(se)){let $e=se.message??"Your payment was declined.";i?.($e),R?.(Tt("paypal",$e,{code:zn(se),declineCode:gr(se)})),await Ro({billingApiUrl:o,sessionId:Ye,nonce:Ue,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:zn(se)??"provider_declined"}})}else ee(se,"stripe_paypal_confirm_failed",_?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Hr)}catch{}let j=typeof mt?.payment_method=="string"?mt.payment_method:mt?.payment_method?.id;r({id:j??mt?.id,type:"card",threeDSecureActionResultTokenId:mt?.id,isPaypal:!0},{accountPatch:me?.accountPatch,sessionId:Ye,nonce:Ue});return}catch(F){ee(F,"stripe_paypal_failed",_?.generation)}finally{U(!1)}},[C,te,e,t,n,o,y,r,i,R,v,ee,ae,X,Te,oe]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(_i,{state:G,placeholderTestId:"flopay-paypal-placeholder",borderRadius:A,children:(0,l.jsxs)("div",{ref:re,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ne&&(0,l.jsx)("button",{ref:be,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ve,style:ki,children:"Try PayPal again"}),(0,l.jsx)(ht.ExpressCheckoutElement,{onReady:H=>S(Ri(H,["paypal"])),onLoadError:()=>{S("load_error"),aa(xt(D),"paypal","paypal")},onClick:Z,onConfirm:Re,onCancel:()=>{let H=K.current.get(oe);K.current.delete(oe),xt(D)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ze(H?.generation),_e(!1),Se.current=!0,$()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},oe)]})}),ge&&(0,l.jsx)(hn,{status:"processing"})]})}function Ci({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:r,expressMethods:i,onTokenizedBody:m,onErrorChange:d,onButtonClick:R,onDecline:g,onTechnicalFailure:v,runBeforeButtonClick:b,onLoadStateChange:A,placeholderBorderRadius:D}){let y=Un(),{emitInstrument:C}=(0,a.useContext)(gn),te=(0,ht.useStripe)(),G=(0,ht.useElements)(),[S,ge]=(0,a.useState)("loading");(0,a.useEffect)(()=>{A?.(S)},[S,A]);let[U,Q]=(0,a.useState)(!1),re=(0,a.useRef)(null),be=(0,a.useRef)(null),[oe,he]=(0,a.useState)(0),[Ne,_e]=(0,a.useState)(!1),[Se,K]=(0,a.useState)("google_pay"),O=(0,a.useRef)(!1),ae=(0,a.useRef)("google_pay"),ze=(0,a.useRef)("google_pay"),Te=(0,a.useRef)(new Map),{startAttempt:X,finishAttempt:$,invalidateAttempt:ee,isAttemptInvalidated:pe,isAttemptCurrent:ve}=Ei((ce,F,ie)=>{v?.(ce,F,{...ie,popupBlocked:ie?.popupBlocked??Gn(F)}),K(ce),_e(!0),he(J=>J+1)});(0,a.useEffect)(()=>{Ne&&be.current?.focus()},[Ne,oe]);let Z=(0,a.useCallback)(()=>{he(ce=>ce+1)},[]),Re=(0,a.useCallback)((ce,F,ie,J)=>{ee(J),v?.(ce,F,{code:ie,popupBlocked:Gn(F)}),K(ce),_e(!0),Z()},[ee,v,Z]),H=(0,a.useCallback)(()=>{window.setTimeout(()=>{(re.current?.querySelector("iframe")??re.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{O.current&&(O.current=!1,H())},[H,oe]);let _=(0,a.useCallback)(()=>{_e(!1),d?.(null),H()},[H,d]),me=(0,a.useCallback)(async ce=>{if(!te||!G)return;let F=Te.current.get(oe);if(F&&!ve(F.generation)){Te.current.delete(oe);return}if(!F&&pe()||F&&!$(F.generation))return;F||$();let ie=ce.expressPaymentType??F?.method??ae.current,J=F??null;Te.current.delete(oe);let Le=hi(ie);if(!J&&b){let j=await b(Le);if(!j.proceed){ce.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}J={accountPatch:j.accountPatch,sessionId:j.sessionId,nonce:j.nonce}}let Fe=Le,Ze=J?.sessionId??e,se=J?.nonce??t,mt=J?.accountPatch?.email??n;try{Q(!0),d?.(null);let{error:j}=await G.submit();if(j){Re(ie,j,"stripe_wallet_submit_failed",F?.generation);return}let{error:$e,paymentMethod:vt}=await te.createPaymentMethod({elements:G});if($e||!vt){Re(ie,$e??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",F?.generation);return}if(!Ze||!mt)throw new Error("Missing sessionId or email for wallet payment");let Y=await Eo(o,C,Ze,se??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ie??Le,paymentMethodId:vt.id,intentKind:r});if(Y.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Pt=Y.clientSecret,{error:Ve,intentId:Zt}=(0,f.isSetupIntentClientSecret)(Pt)?await te.confirmCardSetup(Pt,{payment_method:vt.id}).then(It=>({error:It.error,intentId:It.setupIntent?.id})):await te.confirmCardPayment(Pt,{payment_method:vt.id}).then(It=>({error:It.error,intentId:It.paymentIntent?.id}));if(Ve){if(zr(Ve)){let It=Ve.message??"Your payment was declined.";d?.(It),g?.(Tt(Fe,It,{code:zn(Ve),declineCode:gr(Ve)})),await Ro({billingApiUrl:o,sessionId:Ze,nonce:se,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ie??Le,providerDeclineReason:zn(Ve)??"provider_declined"}})}else Re(ie,Ve,"stripe_wallet_confirm_failed",F?.generation);return}m({id:vt.id,type:"card",threeDSecureActionResultTokenId:Zt},{accountPatch:J?.accountPatch,sessionId:Ze,nonce:se})}catch(j){Re(ie,j,"stripe_wallet_failed",F?.generation)}finally{Q(!1)}},[te,G,e,t,n,o,C,r,m,d,g,b,Re,$,ve,pe,oe]),Ye=(0,a.useMemo)(()=>{let ce=["applePay","googlePay","paypal","link","amazonPay","klarna"],F=new Set(["applePay","googlePay"]),ie=new Set(i.map(f.stripeExpressMethodToOptionKey)),J={};for(let Le of ce)ie.has(Le)?J[Le]=F.has(Le)?"always":"auto":J[Le]="never";return J},[i]),Ue=(0,a.useMemo)(()=>i.map(f.stripeExpressMethodToOptionKey),[i]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(_i,{state:S,placeholderTestId:"flopay-wallet-placeholder",borderRadius:D,children:(0,l.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:[Ne&&(0,l.jsxs)("button",{ref:be,type:"button","data-testid":"flopay-wallet-retry-button",onClick:_,style:ki,children:["Try ",Ii(Se)," again"]}),(0,l.jsx)(ht.ExpressCheckoutElement,{onReady:ce=>{ge(Ri(ce,Ue))},onLoadError:ce=>{ge("load_error"),aa(xt(y),"stripe","wallet")},onClick:async ce=>{ae.current=ce.expressPaymentType,ze.current=hi(ce.expressPaymentType);let F=b?await b(ze.current):{proceed:!0};if(!F.proceed){Te.current.delete(oe),ce.reject();return}let ie=X(ce.expressPaymentType);Te.current.set(oe,{generation:ie,method:ce.expressPaymentType,accountPatch:F.accountPatch,sessionId:F.sessionId,nonce:F.nonce}),_e(!1),R?.(ze.current),ce.resolve()},onConfirm:me,onCancel:()=>{let ce=Te.current.get(oe);Te.current.delete(oe),xt(y)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),ee(ce?.generation),_e(!1),O.current=!0,Z()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ye,layout:{maxColumns:1,overflow:"never"}}},oe)]})}),U&&(0,l.jsx)(hn,{status:"processing"})]})}function $s({method:e,themeId:t,submitting:n=!1,disabled:o=!1,highlighted:r=!1,hasNextStep:i=!1,onClick:m,backgroundColor:d,borderColor:R,textColor:g,borderRadius:v,fontFamily:b}){let A=(0,f.resolveStripeMethodBrandVariant)(e,t),D=mi[e],[y,C]=(0,a.useState)(!1),te=A?.backgroundColor??d??"#ffffff",G=A?.borderColor??R??"#d1d5db",S=A?.textColor??g??"#262833";return(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!o&&m()},disabled:n||o,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Io,padding:"0 1rem",backgroundColor:te,color:S,border:`1px solid ${G}`,borderRadius:v??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||o?"not-allowed":"pointer",opacity:o&&!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:r?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,l.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,f.getStripeMethodDisplayName)(e)}\u2026`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,f.hasVendoredStripeMethodLogo)(e)?8:0},children:[D&&!y?(0,l.jsx)("img",{src:D,alt:"","aria-hidden":"true",onError:()=>C(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):A?.logoSvg?(0,l.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:A.logoSvg}}):null,(0,l.jsx)("span",{children:(0,f.getStripeMethodDisplayName)(e)})]}),i&&(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:S,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,l.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function oa({method:e,sessionId:t,nonce:n,email:o,billingName:r,billingApiUrl:i,onTokenizedBody:m,onErrorChange:d,onDecline:R,onCancel:g,runBeforeButtonClick:v,onButtonClick:b,isProcessing:A,submitButtonColor:D,submitButtonBorderRadius:y,submitButtonStyle:C,errorText:te}){let G=Un(),{emitInstrument:S}=(0,a.useContext)(gn),ge=(0,ht.useStripe)(),U=(0,ht.useElements)(),[Q,re]=(0,a.useState)(!1),be=(0,a.useRef)(!1),[oe,he]=(0,a.useState)(!1),[Ne,_e]=(0,a.useState)("loading"),Se=(0,a.useCallback)(async()=>{if(!ge||!U||A||be.current||!oe)return;be.current=!0,re(!0);let K=v?await v("card"):{proceed:!0};if(!K.proceed){be.current=!1,re(!1);return}b?.("card");let O=K.sessionId??t,ae=K.nonce??n,ze=K.accountPatch?.email??o;try{d?.(null);let Te=await U.submit();if(Te.error){d?.(Te.error.message??"Payment failed.");return}let X=await ge.createPaymentMethod({elements:U});if(X.error||!X.paymentMethod){d?.(X.error?.message??"Failed to create payment method.");return}let $=X.paymentMethod;if(!O||!ze)throw new Error("Missing sessionId or email for payment.");let ee=$.type||e,pe=await Eo(i,S,O,ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,paymentMethodId:null,intentKind:"payment"});if(pe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ve=pe.clientSecret;if(typeof window<"u")try{localStorage.setItem(Mn,JSON.stringify({clientSecret:ve,sessionId:O,nonce:ae,accountPatch:K.accountPatch,paymentMethodId:$.id,paymentMethodType:$.type??e,gateway:"stripe"}))}catch{}let{error:Z,paymentIntent:Re}=await ge.confirmPayment({clientSecret:ve,confirmParams:{return_url:window.location.href,payment_method:$.id},redirect:"if_required"});if(Z){if(typeof window<"u")try{localStorage.removeItem(Mn)}catch{}let me=Z.message??"Payment failed.";d?.(me),R?.(Tt("card",me,{code:Z.code})),await Ro({billingApiUrl:i,sessionId:O,nonce:ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Z.code??"provider_declined"}});return}let H=Re?.status;if(!po(H)){if(typeof window<"u")try{localStorage.removeItem(Mn)}catch{}let me=H==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(me),R?.(Tt("card",me,{code:H??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Mn)}catch{}let _=typeof Re?.payment_method=="string"?Re.payment_method:Re?.payment_method?.id;m({id:_??$.id,type:"card",threeDSecureActionResultTokenId:Re?.id,gateway:"stripe",paymentMethodType:$.type??e},{accountPatch:K.accountPatch,sessionId:O,nonce:ae})}catch(Te){d?.(Te instanceof Error?Te.message:"Payment failed. Please try again.")}finally{be.current=!1,re(!1)}},[ge,U,A,oe,v,b,t,n,o,i,S,e,m,d,R]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(0,l.jsx)(ht.PaymentElement,{onReady:()=>_e("ready"),onLoadError:()=>{_e("load_error"),aa(xt(G),"stripe","apm")},onChange:K=>{he(!!K.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...o?{email:o}:{}}}}}),(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Se()},disabled:!oe||Q||A||Ne!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:D,color:"white",border:"none",borderRadius:y,fontSize:"1rem",fontWeight:600,cursor:!oe||Q||A||Ne!=="ready"?"not-allowed":"pointer",opacity:!oe||Q||A||Ne!=="ready"?.5:1,transition:"opacity 120ms ease-out",...C??{}},children:Q?"Processing\u2026":`Pay with ${(0,f.getStripeMethodDisplayName)(e)}`}),te&&(0,l.jsx)(vr,{margin:"0.75rem 0 0",children:te})]})}function Si({sessionId:e,nonce:t,email:n,billingName:o,billingApiUrl:r,paymentElementMethods:i,stripeInstance:m,paymentElementBaseOptions:d,onTokenizedBody:R,onErrorChange:g,onButtonClick:v,onDecline:b,runBeforeButtonClick:A,onLoadStateChange:D,isProcessing:y=!1,submitButtonColor:C="#4A49FF",submitButtonBorderRadius:te=8,submitButtonStyle:G,buttonAppearance:S,themeId:ge,onExpandApm:U,expandedApmMethod:Q}){let{emitInstrument:re}=(0,a.useContext)(gn),[be,oe]=(0,a.useState)(null),[he,Ne]=(0,a.useState)(null),_e=(0,a.useRef)(!1);(0,a.useEffect)(()=>{i.length>0&&m?D?.("ready"):m||D?.("loading")},[i.length,m,D]);let Se=(0,a.useCallback)(async X=>{if(!m||_e.current||y)return;_e.current=!0,Ne(X);let $=A?await A("card"):{proceed:!0};if(!$.proceed){_e.current=!1,Ne(null);return}v?.("card");let ee=$.sessionId??e,pe=$.nonce??t,ve=$.accountPatch?.email??n;try{if(g?.(null),!ee||!ve)throw new Error("Missing sessionId or email for payment.");let Z=await Eo(r,re,ee,pe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,paymentMethodId:null,intentKind:"payment"});if(Z.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Re=Z.clientSecret;if(typeof window<"u")try{localStorage.setItem(Mn,JSON.stringify({clientSecret:Re,sessionId:ee,nonce:pe,accountPatch:$.accountPatch,paymentMethodType:X,gateway:"stripe"}))}catch{}let{error:H,paymentIntent:_}=await m.confirmPayment({clientSecret:Re,confirmParams:{return_url:window.location.href,payment_method_data:{type:X,billing_details:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...ve?{email:ve}:{}}}},redirect:"if_required"});if(H){if(typeof window<"u")try{localStorage.removeItem(Mn)}catch{}let Ue=H.message??"Payment failed.";g?.(Ue),b?.(Tt("card",Ue,{code:H.code})),await Ro({billingApiUrl:r,sessionId:ee,nonce:pe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,providerDeclineReason:H.code??"provider_declined"}});return}let me=_?.status;if(!po(me)){if(typeof window<"u")try{localStorage.removeItem(Mn)}catch{}let Ue=me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(Ue),b?.(Tt("card",Ue,{code:me??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Mn)}catch{}let Ye=typeof _?.payment_method=="string"?_.payment_method:_?.payment_method?.id;R({id:Ye??_?.id,type:"card",threeDSecureActionResultTokenId:_?.id,gateway:"stripe",paymentMethodType:X},{accountPatch:$.accountPatch,sessionId:ee,nonce:pe})}catch(Z){g?.(Z instanceof Error?Z.message:"Payment failed. Please try again.")}finally{_e.current=!1,Ne(null)}},[m,y,A,v,e,t,n,r,re,o,R,g,b]),[K,O]=(0,a.useState)(null),ae=U?Q??null:K,ze=(0,a.useCallback)(X=>{_e.current||y||ae&&ae!==X||((0,f.needsStripeMethodExplicitConfirm)(X)?U?U(X):O(X):Se(X))},[ae,y,Se,U]),Te=(0,a.useMemo)(()=>K?{...d,paymentMethodTypes:[K]}:null,[K,d]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:i.map(X=>{let $=Q===X,ee=he===X,pe=he!==null&&he!==X||Q!=null&&Q!==X;return(0,l.jsxs)(a.default.Fragment,{children:[(0,l.jsx)($s,{method:X,themeId:ge,submitting:ee,disabled:pe,highlighted:$,hasNextStep:(0,f.needsStripeMethodExplicitConfirm)(X),onClick:()=>ze(X),backgroundColor:S?.backgroundColor,borderColor:S?.borderColor,textColor:S?.textColor,borderRadius:S?.borderRadius,fontFamily:S?.fontFamily}),!U&&K===X&&Te&&m&&(0,l.jsx)(ht.Elements,{stripe:m,options:Te,children:(0,l.jsx)(oa,{method:X,sessionId:e,email:n,billingName:o,billingApiUrl:r,onTokenizedBody:R,onErrorChange:g,onDecline:b,onCancel:()=>O(null),runBeforeButtonClick:A,onButtonClick:v,isProcessing:y,submitButtonColor:C,submitButtonBorderRadius:te,submitButtonStyle:G})},X)]},X)})})}function qs({sessionId:e,nonce:t,billingApiUrl:n,email:o,userId:r,onComplete:i,onError:m,onDecline:d,onTokenizedBody:R,firstName:g,lastName:v,chv:b,className:A,isProcessing:D,error:y,onErrorChange:C,showPayPal:te=!0,showStripe:G=!0,enabledPaymentMethods:S,enabledPaymentMethodCountries:ge,showApplePay:U=!0,showGooglePay:Q=!0,layout:re="default",theme:be,buttonsTheme:oe,buttonsStyles:he,appearance:Ne,cardButtonContent:_e,cardBackButtonContent:Se,cardTitleContent:K,showSecurityFooter:O,onButtonClick:ae,onBeforeButtonClick:ze,enableAVS:Te,cardFieldOrder:X,cardPreFormSlot:$,avsLayout:ee="row",country:pe,zip:ve,addressLine1:Z,addressLine2:Re,city:H,state:_,onCountryChange:me,onZipChange:Ye,avsCheck:Ue,checkoutType:ce,checkoutLayout:F,totalAmount:ie=0,currency:J="usd",initialCardOpen:Le=!1,directPaypal:Fe,isSubscription:Ze=!1,session:se,dataAttachmentPending:mt=!1,debug:j=!1}){let $e=Un(),vt=mo(),Y=(0,a.useContext)(wn),{emitInstrument:Pt}=(0,a.useContext)(gn),Ve=mt||Y.claimPending===!0,Zt=ei(),[It,T]=(0,a.useState)(!1),[Pe,yt]=(0,a.useState)(null),[Oe,$t]=(0,a.useState)(pe??"US"),[Wt,Xe]=(0,a.useState)(ve??""),[bt,Qe]=(0,a.useState)(Z??""),[At,We]=(0,a.useState)(Re??""),[qt,Et]=(0,a.useState)(H??""),[Qt,Bt]=(0,a.useState)(_??""),[En,an]=(0,a.useState)({}),ot=(0,a.useRef)(ve??""),Dt=(0,a.useRef)(pe??"US"),Ge=(0,a.useRef)(Z??""),Rn=(0,a.useRef)(Re??""),ct=(0,a.useRef)(H??""),Pn=(0,a.useRef)(_??""),Lt=(0,a.useRef)({});(0,a.useEffect)(()=>{let s=(L,W,de,V,we)=>{if(Lt.current[L])return;let xe=W?.trim();!xe||xe===de.current||(de.current=xe,V(xe),we?.(xe))};s("country",pe,Dt,$t,me),s("zip",ve,ot,Xe,Ye),s("addressLine1",Z,Ge,Qe),s("addressLine2",Re,Rn,We),s("city",H,ct,Et),s("state",_,Pn,Bt)},[pe,ve,Z,Re,H,_,me,Ye]);let ue=(0,a.useMemo)(()=>(0,f.resolveAVSConfig)(Te),[Te]),Vn=ue!==null,_n=(0,a.useMemo)(()=>(0,f.isAuthorizationOnlySession)(se),[se]),Tn=!!se?.vault?.html,xn=!!se?.gateways?.pcivault,x=!!(se?.gateways?.stripe?.enabledPaymentMethods??S)?.includes("card"),et=Tn||x||xn,ke=!!(G&&et&&$e&&e),[bn,qe]=(0,a.useState)(()=>re!=="buttons"||Le?e??null:null),[Kn,Zn]=(0,a.useState)(0),jt=re!=="buttons"||Le||!!e&&bn===e,dt=(0,a.useMemo)(()=>!$e||!ke||!e||!jt?null:$e.cardCapture({sessionId:e,captureMethod:se?.captureMethod}),[$e,ke,e,jt,se?.captureMethod]),Gt=(0,a.useMemo)(()=>{let s=Oe,L=ue?(0,f.isAVSFieldVisible)(ue.postal_code,s):!1;return zs(s,Wt,L)},[ue,Oe,Wt]),{avsInvalid:Vt,invalidAvsFields:at}=(0,a.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!ke||!ue)return{avsInvalid:!1,invalidAvsFields:s};let L=Oe,W=(we,xe)=>(0,f.isAVSFieldVisible)(we,L)&&!xe.trim(),de={line1:W(ue.address_line_1,bt),city:W(ue.city,qt),state:W(ue.state,Qt),zip:Gt.empty||Gt.malformed};return{avsInvalid:de.line1||de.city||de.state||de.zip,invalidAvsFields:de}},[ke,ue,Oe,bt,qt,Qt,Gt]),[sn,ln]=(0,a.useState)(!1),[Hn,Cn]=(0,a.useState)(!1),[en,cn]=(0,a.useState)(()=>na(se?.vault)),[Ce,Ct]=(0,a.useState)(Le&&et?"card":"buttons"),[it,tn]=(0,a.useState)(null),dn=Ce==="expanding"||Ce==="card",Dn=se?.gateways?.stripe?"stripe":void 0,un=(0,a.useCallback)(()=>{Pt?.({class:"card_surface",provider:Dn})},[Dn,Pt]),Ot=280,Kt=(0,a.useRef)(null),Ht=(0,a.useCallback)(s=>{Kt.current&&clearTimeout(Kt.current),Kt.current=setTimeout(()=>{Kt.current=null,s()},Ot)},[Ot]);(0,a.useEffect)(()=>()=>{Kt.current&&clearTimeout(Kt.current)},[]);let Yn=(0,a.useCallback)(()=>{un(),qe(e??null),Zn(s=>s+1),Ct("expanding"),Ht(()=>Ct("card"))},[Ht,un,e]),Ln=(0,a.useCallback)(()=>{Ct("collapsing"),Ht(()=>Ct("buttons"))},[Ht]),An=(0,a.useCallback)(s=>{tn(s),Ct("apm-expanding"),Ht(()=>Ct("apm-form"))},[Ht]),On=(0,a.useCallback)(()=>{Ct("apm-collapsing"),Ht(()=>{Ct("buttons"),tn(null)})},[Ht]);(0,a.useEffect)(()=>{re==="buttons"&&Le&&et&&(qe(e??null),Ct("card"))},[re,Le,et,e]);let[Nt,tt]=(0,a.useState)(null),pn=(0,a.useRef)(!1),zt=(0,a.useRef)(null),ut=(0,a.useRef)("idle"),[Jt,Rt]=(0,a.useState)(null),Qn=(0,a.useRef)(Jt);(0,a.useEffect)(()=>{Qn.current=Jt},[Jt]);let pt=n||Zt,u=y??Pe,c=(0,a.useMemo)(()=>(0,f.resolveTheme)(be),[be]),p=(0,a.useMemo)(()=>{let s=c?.buttonsLayout??(0,f.resolveButtonsLayoutTheme)(oe);return he?{...s,...he,cardButton:{...s.cardButton,...he.cardButton},cardFormContainer:{...s.cardFormContainer,...he.cardFormContainer},backButton:{...s.backButton,...he.backButton},backButtonIcon:{...s.backButtonIcon,...he.backButtonIcon},submitButton:{...s.submitButton,...he.submitButton},title:{...s.title,...he.title}}:s},[c,oe,he]),N=Ne??c?.appearance,ne=(0,a.useMemo)(()=>ko({appearance:N,buttonsStyles:p,layout:re}),[N,p,re]),q=Y.inlineSessionPatchProcessing??!1,k=(D??It)||q,P=pt.replace(/\/+$/,""),h=(0,a.useMemo)(()=>Wo({userId:r,email:o,firstName:g,lastName:v,country:pe,zip:ve},En),[r,o,g,v,pe,ve,En]),w=[h.firstName,h.lastName].filter(s=>!!s?.trim()).join(" "),M=(0,a.useMemo)(()=>$e?$e.getRawProvider():null,[$e]),le=(0,a.useMemo)(()=>vt?vt.getRawProvider():null,[vt]),ye=ie||100,Be=(0,a.useMemo)(()=>N?(0,Xn.toStripeAppearance)(N):null,[N]),Ke=Be?{appearance:Be}:null,_t=(0,a.useMemo)(()=>{let s=Be??{},L=s.rules??{};return{...s,rules:{...L,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...L[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...L[".AccordionItemContents"]??{}}}}},[Be]),Ie=(0,a.useMemo)(()=>{let s=Xa(ie);return{...s,currency:J.toLowerCase(),paymentMethodCreation:"manual",...s.mode==="payment"?{captureMethod:"manual"}:{},...Ke}},[ie,J,Ke]),Ee=(0,a.useMemo)(()=>({mode:"payment",amount:ye,currency:J.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Ke}),[ye,J,Ke]),z=(0,a.useCallback)(s=>{yt(s),C?.(s)},[C]);(0,a.useEffect)(()=>{!ke||!dt||dt.setCardFieldOrder?.(X??null,ue==null)},[ke,dt,X,ue]),(0,a.useEffect)(()=>{(Ce==="expanding"||Ce==="collapsing"||Ce==="apm-expanding"||Ce==="apm-collapsing")&&z(null)},[Ce,z]);let St=(0,a.useCallback)((s,L,W)=>{d?.(Tt(s,L,W))},[d]),He=(0,a.useCallback)((s,L,W)=>{let de=W?.popupBlocked??Gn(L),V=Os(s,de),we=ar(W?.code)??zn(L)??"external_payment_method_failed",xe=new f.FloPayError(V,"api_error",{code:"external_payment_method_failed",param:s});tt(null),re==="buttons"&&(Ct("buttons"),tn(null)),z(V),m?.(xe),console.error("[FloPay] External payment method failed:",{method:s,code:we,popupBlocked:de})},[re,m,z]);(0,a.useEffect)(()=>{if(!ke||!e){cn(null);return}let s=na(se?.vault);if(s){cn(s);return}if(!jt){cn(null);return}cn(null);let L=!0;return new Xn.PaymentAPI(P).getVaultCapture(e,t).then(W=>{if(!L)return;let de=na(W);de?cn(de):z("Failed to load the secure card form.")}).catch(W=>{L&&z(W instanceof Error?W.message:"Failed to load the secure card form.")}),()=>{L=!1}},[ke,jt,Kn,e,se?.vault?.html,se?.vault?.messageToken,se?.vault?.expectedOrigin,P,t,z]);let nt=(0,a.useRef)({onComplete:i,onError:m,updateError:z,emitDecline:St,resolvedAccount:h,avsConfig:ue,avsCheckProp:Ue,sessionId:e,nonce:t,baseUrl:P,captureMethod:se?.captureMethod,paymentId:se?.paymentId,authorizationExpiresAt:se?.authorizationExpiresAt});nt.current={onComplete:i,onError:m,updateError:z,emitDecline:St,resolvedAccount:h,avsConfig:ue,avsCheckProp:Ue,sessionId:e,nonce:t,baseUrl:P,captureMethod:se?.captureMethod,paymentId:se?.paymentId,authorizationExpiresAt:se?.authorizationExpiresAt};let er=(0,a.useRef)(!1),va=(0,a.useCallback)(()=>{let{resolvedAccount:s,avsConfig:L,avsCheckProp:W}=nt.current,de=Dt.current||s.country||"US",V=L?(0,f.isAVSFieldVisible)(L.state,de):!1,we=L?(0,f.isAVSFieldVisible)(L.address_line_1,de):!1,xe=L?(0,f.isAVSFieldVisible)(L.postal_code,de):!1,ft=L?(0,f.isAVSFieldVisible)(L.city,de):!1,Ut=L?(0,f.isAVSFieldVisible)(L.address_line_2,de):!1,gt=we&&!V&&xe?(0,f.getStateFromPostalCode)(de,(ot.current??"").trim()):null,st=V?Pn.current:gt;return{accountData:{userId:s.userId??"",email:s.email??"",firstName:s.firstName??"",lastName:s.lastName??"",...xe&&ot.current?{zip:ot.current}:{},...ft&&ct.current?{city:ct.current}:{},...st?{state:st}:{},...we&&Ge.current?{addressLine1:Ge.current}:{},...Ut&&Rn.current?{addressLine2:Rn.current}:{},country:de},...W!==void 0?{avsCheck:W}:{},...L?{avsConfig:{country:(0,f.isAVSFieldVisible)(L.country,de),postal_code:xe,address_line_1:we,address_line_2:Ut,city:ft,state:V}}:{}}},[]),Xr=(0,a.useRef)(Ve);Xr.current=Ve,(0,a.useEffect)(()=>{Ve||u!==gi||nt.current.updateError(null)},[Ve,u]),(0,a.useEffect)(()=>{!ke||!dt||dt.setSubmitGate?.(Vt||Ve)},[ke,dt,Vt,Ve]),(0,a.useEffect)(()=>{if(!ke||!dt)return;er.current=!1;let s=!1,L=dt.on("submitting",()=>{ln(!0),zt.current&&clearTimeout(zt.current),ut.current="validation-window",zt.current=setTimeout(()=>{zt.current=null,ut.current==="validation-window"&&(ut.current="processing")},Ms),tt("processing");let{baseUrl:xe,sessionId:ft,nonce:Ut,updateError:gt,onError:st}=nt.current;!ft||!Ut||new Xn.PaymentAPI(xe).patchAccountSnapshot(ft,Ut,va(),{telemetryMode:"best_effort"}).catch(je=>{if(!Fs(je))return;let Nn=je instanceof Error?je.message:"Please check your billing address and try again.";gt(Nn),ut.current="idle",tt(null),st?.(je instanceof f.FloPayError?je:new f.FloPayError(Nn,"api_error"))})}),W=dt.on("complete",async xe=>{if(Pr(xe.sessionId??nt.current.sessionId),ut.current="terminal",tt("success"),await new Promise(gt=>setTimeout(gt,1200)),er.current)return;er.current=!0;let ft=nt.current,Ut=(0,f.isAuthorizationOnlySession)(ft)||xe.outcome==="authorized";nt.current.onComplete?.(Ut?{status:"authorized",paymentIntentId:xe.intentId,paymentId:xe.paymentId??ft.paymentId,sessionId:xe.sessionId??ft.sessionId,authorizationExpiresAt:xe.authorizationExpiresAt??ft.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:xe.intentId,checkoutMethod:"card"})}),de=dt.on("decline",async xe=>{let{updateError:ft,emitDecline:Ut}=nt.current,gt=xe.message??"Your payment was declined. Please try another card or contact your bank.";ut.current="terminal",ft(gt),tt("error");let st=xe.failureOutcome??(0,f.normalizeCheckoutFailureOutcome)(xe.declineReason)??"authorization_declined";Ut("card",gt,{code:st,declineCode:st}),await new Promise(je=>setTimeout(je,1500)),!s&&(ut.current="idle",tt(null))}),V=dt.on("error",async xe=>{let{updateError:ft,onError:Ut}=nt.current,gt=xe.message??"There was a problem processing your payment. Please try again.";ut.current="terminal",ft(gt),tt("error"),Ut?.(new f.FloPayError(gt,"api_error",{code:xe.failureOutcome??"capture_failed"})),await new Promise(st=>setTimeout(st,1500)),!s&&(ut.current="idle",tt(null))}),we=dt.on("blocked",()=>{if(!Xr.current){ln(!0);return}nt.current.updateError(gi)});return()=>{s=!0,zt.current&&(clearTimeout(zt.current),zt.current=null),ut.current="idle",L(),W(),de(),V(),we()}},[ke,dt]);let nn=!!Fe?.clientId,Ir=Array.isArray(S),Zr=Ir&&S.length>0,zi=Ir&&S.includes("paypal"),{expressMethods:Qr,paymentElementMethods:Er}=(0,a.useMemo)(()=>(0,f.partitionStripeMethods)(S,{excludePaypal:nn}),[S,nn]),Pa=nn||!!vt,Ui=(0,a.useMemo)(()=>Pa?Qr.filter(s=>s!=="paypal"):Qr,[Qr,Pa]),$i=(0,a.useMemo)(()=>{let s=[];return U&&s.push("apple_pay"),Q&&s.push("google_pay"),s},[U,Q]),eo=Ir?Ui:$i,qi=G&&eo.length>0,Do=Vn?Oe:pe,to=(0,a.useMemo)(()=>{let s=Do?.trim().toUpperCase();return s?ge?Er.filter(L=>{let W=ge[L];return!W||W.length===0||W.includes(s)}):(0,f.filterStripeMethodsByCountry)(Er,Do):Er},[Er,Do,ge]),Lo=(0,a.useMemo)(()=>({mode:"payment",amount:ye,currency:J.toLowerCase(),paymentMethodCreation:"manual",appearance:_t}),[ye,J,_t]),[ba,Ca]=(0,a.useState)("loading"),[Sa,wa]=(0,a.useState)("loading"),[ka,Ia]=(0,a.useState)("loading"),[ji,Oo]=(0,a.useState)(!1),[Ea,No]=(0,a.useState)("loading"),[no,Vi]=(0,a.useState)();(0,a.useEffect)(()=>{Vi(pi())},[]);let Ra=te&&(nn||(Ir?zi:no===!1)),_a=G&&qi,Rr=!Ve&&Ra&&nn,Ta=Ea==="retrying"||Ea==="exhausted",_r=!Ve&&Ra&&!!le&&(!nn||Ta),Tr=!Ve&&_a&&!!M,xr=!Ve&&G&&Zr&&to.length>0&&!!M,Ki=Rr&&!Ta?ji:_r&&Pi(ba),Hi=Tr&&Pi(Sa),Yi=xr&&ka!=="load_error",xa=s=>s==="loading"||s==="ready",Aa=Rr||_r&&xa(ba)||Tr&&xa(Sa)||xr&&ka!=="load_error",ro=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(!ro.current){if(!G&&!te){ro.current=!0;let s=new f.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");m?.(s),z(s.message)}else if(!G&&te&&!nn&&!le){ro.current=!0;let s=new f.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");m?.(s),z(s.message)}else if(no!==void 0&&!Ve&&!et&&!Aa){ro.current=!0;let s=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"});m?.(s),z(s.message)}}},[G,te,nn,le,no,Ve,et,Aa,m,z]);let Ma=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(Ma.current||!Zr)return;let s=[];U!==!0&&s.push("showApplePay"),Q!==!0&&s.push("showGooglePay"),s.length!==0&&(Ma.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Zr,U,Q]);let Fa=(0,a.useCallback)((s,L)=>Y.applyInlineSessionPatch?Y.applyInlineSessionPatch(s).then(W=>({error:null,sessionId:W.sessionId||e,nonce:W.session?.clientSecret||t})).catch(W=>{let de=vi(L,W);return z(de.message),m?.(de),{error:de,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Y.applyInlineSessionPatch,t,m,e,z]),Sn=(0,a.useCallback)(async s=>{if(!ze)return{proceed:!0};try{let L=await ze({method:s,sessionId:e||void 0,createSession:Y.inlineSessionDraft});if(L===!1)return{proceed:!1};if(L&&typeof L=="object"){L.account&&an(de=>({...de??{},...L.account}));let W=await Fa(L,s);return W.error?{proceed:!1,accountPatch:L.account}:{proceed:!0,accountPatch:L.account,sessionId:W.sessionId,nonce:W.nonce}}return{proceed:!0}}catch(L){let W=vi(s,L);return z(W.message),m?.(W),{proceed:!1}}},[Fa,Y.inlineSessionDraft,ze,m,e,z]),Ba=(0,a.useCallback)(async(s,L)=>{if(pn.current)return;pn.current=!0,T(!0),tt("processing"),z(null);let W=L?.sessionId??e,de=L?.nonce??t,V=Wo(h,L?.accountPatch),we=L?.completionPaymentMethodId??Nr(s),xe=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,ft=s.gateway==="stripe"?"stripe":s.gateway==="paypal"||s.isPaypal?"paypal":void 0,Ut=()=>{Pt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:ft})};try{let st=await new Xn.PaymentAPI(P).processPayment(V.userId??"",{sessionId:W,nonce:de,tokenizedData:xe,accountData:{userId:V.userId??"",email:V.email??"",firstName:V.firstName??"",lastName:V.lastName??"",...ue?(()=>{let Je=Dt.current,yn=(0,f.isAVSFieldVisible)(ue.state,Je),fn=(0,f.isAVSFieldVisible)(ue.address_line_1,Je),Mt=(0,f.isAVSFieldVisible)(ue.postal_code,Je),Dr=fn&&!yn&&Mt?(0,f.getStateFromPostalCode)(Je,(ot.current??"").trim()):null,Lr=yn?Pn.current:Dr;return{country:Je,...Mt&&ot.current?{zip:ot.current}:{},...(0,f.isAVSFieldVisible)(ue.city,Je)&&ct.current?{city:ct.current}:{},...Lr?{state:Lr}:{},...fn&&Ge.current?{addressLine1:Ge.current}:{},...(0,f.isAVSFieldVisible)(ue.address_line_2,Je)&&Rn.current?{addressLine2:Rn.current}:{}}})():{}},chv:b,avsCheck:Ue??!1,checkoutType:ce,checkoutLayout:F,avsConfig:ue?{country:(0,f.isAVSFieldVisible)(ue.country,Dt.current),postal_code:(0,f.isAVSFieldVisible)(ue.postal_code,Dt.current),address_line_1:(0,f.isAVSFieldVisible)(ue.address_line_1,Dt.current),address_line_2:(0,f.isAVSFieldVisible)(ue.address_line_2,Dt.current),city:(0,f.isAVSFieldVisible)(ue.city,Dt.current),state:(0,f.isAVSFieldVisible)(ue.state,Dt.current)}:void 0});if(st.ok){let Je=st.status===204?null:await st.json().catch(()=>null),yn=(0,f.isAuthorizationOnlySession)(se)||Je?.status==="authorized";Pr(W),tt("success"),Rt(null),await new Promise(fn=>setTimeout(fn,1200)),i?.(yn?{status:"authorized",...typeof Je?.paymentId=="string"?{paymentId:Je.paymentId}:se?.paymentId?{paymentId:se.paymentId}:{},sessionId:typeof Je?.sessionId=="string"?Je.sessionId:W,...typeof Je?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Je.authorizationExpiresAt}:se?.authorizationExpiresAt?{authorizationExpiresAt:se.authorizationExpiresAt}:{},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:we,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:we,checkoutMethod:s.isPaypal?"paypal":"card"});return}let je=await st.json().catch(()=>null);if(je?.type==="paypal_redirect_required"){let Je=je.threeDSecureToken,yn=je.paymentMethodId||s.id||"";if(!$e||!Je){tt("error"),z("PayPal authorization required but no token provided.");return}try{let fn=vt?.getRawProvider();if(!fn){z("PayPal is not available.");return}let Mt={return_url:window.location.href};yn&&(Mt.payment_method=yn);let{error:Dr}=await fn.confirmPayment({clientSecret:Je,confirmParams:Mt,redirect:"if_required"});if(Dr){tt("error");let Lr=Dr.message??"PayPal payment failed.";z(Lr),St("paypal",Lr,{code:Dr.code})}}catch(fn){tt("error"),z(fn instanceof Error?fn.message:"PayPal authorization failed.")}return}if(je?.type==="paypal_direct_required"){let Je=je.orderId;if(!Je){tt("error"),z("PayPal retry required but no order id provided.");return}let yn=Qn.current?.attempts??0;if(yn>=2){tt("error"),z("PayPal payment could not be completed after multiple attempts."),St("paypal","paypal_direct_required retry limit exceeded");return}Oo(!1),No("loading"),Rt({orderId:Je,attempts:yn+1}),tt(null);return}(0,f.classifyPaymentRejection)(st.status,je)||Ut(),tt("error");let Nn=je?.message??"Payment failed. Please try again.";z(Nn),St(s.isPaypal?"paypal":"card",Nn,{code:je?.code??je?.gatewayErrorCode,declineCode:je?.declineCode??je?.gatewayDeclineReason}),await new Promise(Je=>setTimeout(Je,1500))}catch(gt){wi(gt)||Ut(),tt("error"),z(gt instanceof Error?gt.message:"An unexpected error occurred"),await new Promise(st=>setTimeout(st,1500))}finally{T(!1),tt(null),pn.current=!1}},[P,e,t,h,w,b,$e,vt,se,i,m,z,St,Pt]),mn=(0,a.useCallback)((s,L)=>{R?R(s):Ba(s,L)},[R,Ba]),Da=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||Da.current)return;let s=new URLSearchParams(window.location.search),L=s.get("payment_intent"),W=s.get("payment_intent_client_secret"),de=s.get("redirect_status");if(!L||!W)return;let V=st=>{let je=localStorage.getItem(st);if(!je)return null;try{return JSON.parse(je)}catch{return localStorage.removeItem(st),null}},we=V(Mn)??V(fi),xe;if(we?.clientSecret){if(we.clientSecret!==W)return;xe={...we.accountPatch?{accountPatch:we.accountPatch}:{},...we.sessionId?{sessionId:we.sessionId}:{},...we.nonce?{nonce:we.nonce}:{}}}else if(we?.sessionId&&we.sessionId!==e)return;Da.current=!0,localStorage.removeItem(Mn),localStorage.removeItem(fi);let ft=new URL(window.location.href);ft.searchParams.delete("payment_intent"),ft.searchParams.delete("payment_intent_client_secret"),ft.searchParams.delete("redirect_status"),window.history.replaceState({},"",ft.toString());let Ut=we?.paymentMethodType??we?.tokenType??"card",gt="card";(async()=>{let st=$e?.getRawProvider();if(!st){let Mt="Payment is not available \u2014 please refresh and try again.";z(Mt),St(gt,Mt);return}if(de==="failed"){let Mt="Payment was declined. Please try again.";z(Mt),St(gt,Mt);return}let{paymentIntent:je,error:Nn}=await st.retrievePaymentIntent(W);if(Nn){let Mt=Nn.message??"Failed to retrieve payment status.";z(Mt),St(gt,Mt,{code:Nn.code});return}let Je=je?.status,yn=po(Je);if(!je||!yn){let Mt=Je==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";z(Mt),St(gt,Mt,{code:Je??"missing_payment_intent"});return}let fn=typeof je.payment_method=="string"?je.payment_method:je.payment_method?.id;mn({id:fn??we?.paymentMethodId??we?.tokenId??je.id,type:"card",threeDSecureActionResultTokenId:je.id,gateway:we?.gateway??"stripe",paymentMethodType:Ut},xe)})()},[e,mn,$e,z,St]);let zo=(0,a.useCallback)(s=>{s.preventDefault()},[]);if(!($e!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Ar=re==="buttons",Xt=N?.variables,Wi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Uo=Xt?.colorBackground,Gi=Uo&&!Wi.has(Uo)?Uo:void 0,Mr=p.cardInputBorder??(Ar?"#e5e7eb":"#A4A4FF"),$o=Xt?.colorDanger??"#dc2626",tr=s=>sn&&s?$o:Mr,oo=(Gt.malformed||Gt.empty)&&(Hn||sn),Ji=oo?$o:tr(at.zip),qo=p.cardFormContainer?.backgroundColor??Gi??(Ar?"white":"#EDEDFF"),Fr=p.cardInputBackground??Xt?.colorBackground??"white",jo=ur(Se),La=ur(K),dr=p.nameInput,Oa=p.cardInputFontSize??Us(dr?.fontSize)??Xt?.fontSizeBase??"16px",Na=typeof dr?.fontFamily=="string"?dr.fontFamily:Xt?.fontFamily??"Poppins, sans-serif",za=ta(dr?.fontWeight)??400,Xi=p.cardInputColor??(typeof dr?.color=="string"?dr.color:void 0)??Xt?.colorText??"#262833",Zi=p.cardInputPlaceholderColor??"#9ca3af",wt=Xt?.borderRadius??"8px",nr=Xt?.borderRadius??p.cardButton?.borderRadius??wt,rr=Xt?.colorPrimary??"#4A49FF",Qi=Xt?.colorPrimaryHover??wr(rr,.12),Vo=Xt?.colorText??"#262833",Ua={fontSize:Oa,fontFamily:Na,fontWeight:za,color:Xi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},es={"--flopay-input-placeholder-color":Zi,"--flopay-input-font-size":Oa,"--flopay-input-font-family":Na,"--flopay-input-font-weight":String(za)},Br=p.cardFormContainer??{},Ko=Br.padding??(Ar?"0":"1rem"),Ho=Br.borderRadius??wt,ts=dt&&en?(0,l.jsx)(Sr,{capture:dt,html:en.html,messageToken:en.messageToken,expectedOrigin:en.expectedOrigin,theme:ne,onReady:()=>{if(!ue||typeof document>"u")return;let s=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};s();let L=0,W=window.setInterval(()=>{L+=1;let de=document.activeElement;!!de&&de.tagName==="IFRAME"&&de.id==="flopay_vault_form_iframe"?(s(),window.clearInterval(W)):L>=50&&window.clearInterval(W)},100)},onError:s=>z(s),onValidation:s=>{let L=ut.current;(L==="idle"||L==="validation-window")&&(z(s),s&&ut.current==="validation-window"&&(zt.current&&(clearTimeout(zt.current),zt.current=null),ut.current="idle",tt(null)))}}):(0,l.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"}),$a=(0,l.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&un()},style:{backgroundColor:qo,borderRadius:Ho,...Br,padding:Ko,...es,display:"flex",flexDirection:"column"},children:[(0,l.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 @@ ${je.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),
|
|
39
|
-
`)}):null,
|
|
40
|
-
`)}):null,Ja=we==="apm-expanding"||we==="apm-form"||we==="apm-collapsing",uo=we==="apm-expanding"?`flopay-card-enter ${Nt}ms cubic-bezier(0, 0, 0.2, 1) both`:we==="apm-collapsing"?`flopay-card-exit ${Nt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,po=st?{...qo,paymentMethodTypes:[st]}:null;if(Q==="buttons"){let s=we==="buttons"||we==="expanding"||we==="apm-expanding",U=we==="expanding"||we==="card"||we==="collapsing",X=Se===void 0?{boxSizing:"border-box",height:Ao,padding:"0 1rem"}:{padding:"0.9rem 1rem"},pe=we==="expanding"||we==="apm-expanding"?`flopay-buttons-exit ${Nt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:we==="collapsing"||we==="apm-collapsing"?`flopay-buttons-enter ${Nt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,W=we==="expanding"?`flopay-card-enter ${Nt}ms cubic-bezier(0, 0, 0.2, 1) both`:we==="collapsing"?`flopay-card-exit ${Nt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,l.jsxs)("form",{onSubmit:Ko,className:w,style:{position:"relative"},children:[(0,l.jsx)(ca,{}),zt&&(0,l.jsx)(Pn,{status:zt,errorMessage:u,authorized:Mn}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!pe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!pe?Ws:{},...pe?{animation:pe,pointerEvents:"none"}:{}},children:[Wa("flopay-direct-paypal-gate-debug"),Ga("flopay-stripe-gate-debug"),Mr&&Le&&(0,l.jsxs)(l.Fragment,{children:[Zt&&(0,l.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,l.jsx)(Kr,{sessionId:e,nonce:t,billingApiUrl:mt,email:b.email,clientId:Le.clientId,environment:Le.environment,currency:ee.toUpperCase(),isSubscription:Qe,providerObjectType:Le.providerObjectType,onTokenizedBody:fn,onComplete:a,onErrorChange:j,onDecline:d,onTechnicalFailure:We,onButtonClick:oe,runBeforeButtonClick:wn,isProcessing:E,onLoadStateChange:jo,onInitializationStateChange:Vo,session:ce??null,existingOrderId:Zt?.orderId,debug:V},Zt?.orderId??"fresh")]}),Fr&&(0,l.jsx)(vt.Elements,{stripe:de,options:Re,children:(0,l.jsx)(Ii,{sessionId:e,nonce:t,email:b.email,billingApiUrl:mt,onTokenizedBody:fn,onErrorChange:j,isProcessing:E,onButtonClick:oe,onDecline:d,onTechnicalFailure:We,runBeforeButtonClick:wn,onLoadStateChange:Ra,placeholderBorderRadius:ar})}),Br?(0,l.jsx)(vt.Elements,{stripe:D,options:Ee,children:(0,l.jsx)(Ei,{sessionId:e,nonce:t,email:b.email,billingApiUrl:mt,intentKind:le>0?"payment":"setup",expressMethods:oo,onTokenizedBody:fn,onErrorChange:j,onButtonClick:oe,onDecline:d,onTechnicalFailure:We,runBeforeButtonClick:wn,onLoadStateChange:xa,placeholderBorderRadius:ar})}):Ba?(0,l.jsx)("div",{style:{height:Ao,borderRadius:ar,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Dr&&(0,l.jsx)(Ri,{sessionId:e,nonce:t,email:b.email,billingName:[b.firstName,b.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:mt,paymentElementMethods:ao,stripeInstance:D,paymentElementBaseOptions:qo,onTokenizedBody:fn,onErrorChange:j,onButtonClick:oe,onDecline:d,runBeforeButtonClick:wn,onLoadStateChange:Aa,isProcessing:E,submitButtonColor:ir,submitButtonBorderRadius:It,submitButtonStyle:m.submitButton,onExpandApm:Dn,expandedApmMethod:st,themeId:ve,buttonAppearance:{backgroundColor:m.cardButton?.backgroundColor,borderColor:m.cardInputBorder,textColor:m.cardButton?.color,borderRadius:ar}}),Ie&&(0,l.jsx)("button",{type:"button",onClick:async()=>{E||!(await wn("card")).proceed||(oe?.("card"),Jn())},disabled:E,style:{width:"100%",...X,...m.cardButton,...pa({themeBundle:c,resolvedPrimaryColor:ir,resolvedBorderRadius:It,submitButtonStyle:m.submitButton,explicitPrimaryColor:Qt?.colorPrimary}),fontSize:m.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:E?"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:E?.6:1},onMouseEnter:ke=>{!E&&(c||Qt?.colorPrimary)&&(ke.currentTarget.style.backgroundColor=us)},onMouseLeave:ke=>{(c||Qt?.colorPrimary)&&(ke.currentTarget.style.backgroundColor=ir)},onMouseDown:ke=>{ke.currentTarget.style.transform="scale(0.985)"},onMouseUp:ke=>{ke.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(gr,{content:Se})}),u&&we==="buttons"&&(0,l.jsx)(wr,{margin:"0.25rem 0",styleOverride:m.errorBanner,children:u})]}),Ie&&U&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...W?{animation:W}:{},...we==="collapsing"?{pointerEvents:"none"}:{}},children:Ya}),M&&Ja&&st&&po&&D&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...uo?{animation:uo}:{},...we==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Wo,borderRadius:Zo,...zr,padding:Xo},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:$n,style:{display:"inline-flex",alignItems:"center",gap:Go?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...m.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(hr,{content:he})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:m.titleFontSize??"1.05rem",color:Jo,paddingRight:80,...m.title},children:`Pay with ${(0,P.getStripeMethodDisplayName)(st)}`})]}),(0,l.jsx)(vt.Elements,{stripe:D,options:po,children:(0,l.jsx)(da,{method:st,sessionId:e,nonce:t,email:b.email,billingName:[b.firstName,b.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:mt,onTokenizedBody:fn,onErrorChange:j,onDecline:d,onCancel:$n,runBeforeButtonClick:wn,onButtonClick:oe,isProcessing:E,submitButtonColor:ir,submitButtonBorderRadius:It,submitButtonStyle:m.submitButton,errorText:u})},st)]})})]})]})}return Ja&&st&&po&&D&&M?(0,l.jsxs)("form",{onSubmit:Ko,className:w,style:{position:"relative"},children:[(0,l.jsx)(ca,{}),zt&&(0,l.jsx)(Pn,{status:zt,errorMessage:u,authorized:Mn}),(0,l.jsx)("div",{style:{...uo?{animation:uo}:{},...we==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Wo,borderRadius:Zo,...zr,padding:Xo},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:$n,style:{display:"inline-flex",alignItems:"center",gap:Go?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...m.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(hr,{content:he})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:m.titleFontSize??"1.05rem",color:Jo,paddingRight:80,...m.title},children:`Pay with ${(0,P.getStripeMethodDisplayName)(st)}`})]}),(0,l.jsx)(vt.Elements,{stripe:D,options:po,children:(0,l.jsx)(da,{method:st,sessionId:e,nonce:t,email:b.email,billingName:[b.firstName,b.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:mt,onTokenizedBody:fn,onErrorChange:j,onDecline:d,onCancel:$n,runBeforeButtonClick:wn,onButtonClick:oe,isProcessing:E,submitButtonColor:ir,submitButtonBorderRadius:It,submitButtonStyle:m.submitButton,errorText:u})},st)]})})]}):(0,l.jsxs)("form",{onSubmit:Ko,className:w,style:{position:"relative"},children:[(0,l.jsx)(ca,{}),zt&&(0,l.jsx)(Pn,{status:zt,errorMessage:u,authorized:Mn}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Wa("flopay-direct-paypal-gate-debug-default"),Ga("flopay-stripe-gate-debug-default"),Mr&&Le&&(0,l.jsxs)(l.Fragment,{children:[Zt&&(0,l.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,l.jsx)(Kr,{sessionId:e,nonce:t,billingApiUrl:mt,email:b.email,clientId:Le.clientId,environment:Le.environment,currency:ee.toUpperCase(),isSubscription:Qe,providerObjectType:Le.providerObjectType,onTokenizedBody:fn,onComplete:a,onErrorChange:j,onDecline:d,onTechnicalFailure:We,onButtonClick:oe,runBeforeButtonClick:wn,isProcessing:E,onLoadStateChange:jo,onInitializationStateChange:Vo,session:ce??null,existingOrderId:Zt?.orderId,debug:V},Zt?.orderId??"fresh")]}),Fr&&(0,l.jsx)(vt.Elements,{stripe:de,options:Re,children:(0,l.jsx)(Ii,{sessionId:e,nonce:t,email:b.email,billingApiUrl:mt,onTokenizedBody:fn,onErrorChange:j,isProcessing:E,onButtonClick:oe,onDecline:d,onTechnicalFailure:We,runBeforeButtonClick:wn,onLoadStateChange:Ra,placeholderBorderRadius:ar})}),Br&&(0,l.jsx)(vt.Elements,{stripe:D,options:Ee,children:(0,l.jsx)(Ei,{sessionId:e,nonce:t,email:b.email,billingApiUrl:mt,intentKind:le>0?"payment":"setup",expressMethods:oo,onTokenizedBody:fn,onErrorChange:j,onButtonClick:oe,onDecline:d,onTechnicalFailure:We,runBeforeButtonClick:wn,onLoadStateChange:xa,placeholderBorderRadius:ar})}),Dr&&(0,l.jsx)(Ri,{sessionId:e,nonce:t,email:b.email,billingName:[b.firstName,b.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:mt,paymentElementMethods:ao,stripeInstance:D,paymentElementBaseOptions:qo,onTokenizedBody:fn,onErrorChange:j,onButtonClick:oe,onDecline:d,runBeforeButtonClick:wn,onLoadStateChange:Aa,isProcessing:E,submitButtonColor:ir,submitButtonBorderRadius:It,submitButtonStyle:m.submitButton,themeId:ve,onExpandApm:Dn,expandedApmMethod:st,buttonAppearance:{backgroundColor:m.cardButton?.backgroundColor,borderColor:m.cardInputBorder,textColor:m.cardButton?.color,borderRadius:ar}})]}),Ie&&(os||rs||as)&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,l.jsx)("span",{children:"or pay with card"}),(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ie&&Ya]})}var R=require("react/jsx-runtime"),xr=44,Sa="flopay_checkout_saved_payment_resume",Oo=new Map,Do=new Map;function Bi(e,t){t.settled&&t.consumers===0&&Oo.get(e)===t&&Oo.delete(e)}function nl(e,t,n){let r=Do.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Do.set(e,a);let p=()=>{Do.get(e)===a&&Do.delete(e)};return o.then(p,p),o}function Xr(e){return new Promise(t=>setTimeout(t,e))}function Lo(e,t,n){let r=So({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:ge.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Zr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ma(e,t,n,r,o){let a=Lo(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Zr(a)}function rl(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 ba(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function ya(e){return!e||e.data.stripe?.publishableKey?!1:!!ba(e)?.clientId}function Hn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ol(){if(!Hn())return null;try{let e=window.sessionStorage.getItem(Sa);return e?JSON.parse(e):null}catch{return null}}function Di(e){if(Hn())try{window.sessionStorage.setItem(Sa,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function fa(){if(Hn())try{window.sessionStorage.removeItem(Sa)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var wa=":idempotency-key";function Oi(e,t){if(!Hn())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 ga(e,t,n,r){if(Hn())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 Ca(e,t){if(Hn())try{Oi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Ni(e,t){if(!Hn())return null;try{let n=window.sessionStorage.getItem(e+wa);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 ha(e,t,n){if(Hn())try{window.sessionStorage.setItem(e+wa,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Pa(e,t){if(Ca(e,t),!!Hn())try{Ni(e,t)&&window.sessionStorage.removeItem(e+wa)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function al(){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 Li(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 il(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function va(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Qr(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=>va(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>va(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>va(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function sl(e,t=!1){let n=Qr(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function ll(e,t){if(!e?.customer||!e.products)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,ge.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,ge.foldIntoProducts)(t.items,t.subscriptions)).map(g=>({type:g.type,code:g.code??g.providerItemId??g.providerPlanId??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??o).toUpperCase()})).sort((g,h)=>`${g.code}:${g.type??""}`.localeCompare(`${h.code}:${h.type??""}`)),p=e.products.map(g=>({type:g.type,code:g.code??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??e.currency).toUpperCase()})).sort((g,h)=>`${g.code}:${g.type??""}`.localeCompare(`${h.code}:${h.type??""}`));if(a.length!==p.length)return!1;for(let g=0;g<a.length;g+=1){let h=a[g],k=p[g];if(h.code!==k.code||h.type!==void 0&&h.type!==k.type||h.quantity!==k.quantity||h.totalAmount!==k.totalAmount||h.overrideAmount!==k.overrideAmount||h.currency!==k.currency)return!1}let d=[...t.couponCodes??[]].sort(),I=[...e.coupons??[]].sort();return d.length===I.length&&d.every((g,h)=>g===I[h])}function No({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:p,loading:d,error:I,onComplete:g,onError:h,onInstrument:k,onDecline:w,onCountryChange:x,onZipChange:y,showPayPal:v=!0,showStripe:H=!0,enabledPaymentMethods:M,showApplePay:f=!0,showGooglePay:ie=!0,debug:O=!1,layout:Z,theme:Q,buttonsTheme:ve,buttonsStyles:B,cardButtonContent:se,cardBackButtonContent:xe,cardTitleContent:Se,showSecurityFooter:he,onButtonClick:$,onBeforeButtonClick:N,enableAVS:oe,cardFieldOrder:Me,cardPreFormSlot:Te,avsLayout:te,className:K,initialErrorMessage:re=null,children:ye,checkoutMode:be,confirmLabel:ne,renderConfirmButton:_e,onSessionCompleted:G}){let T=(0,ge.resolveBillingApiUrl)(r),fe=(0,_.useMemo)(()=>(0,ge.resolveTheme)(Q),[Q]),$e=a??fe?.appearance,qe=n?"embedded_checkout":"standard_checkout",ue=ye?"custom_layout":Z==="buttons"?"buttons_layout":"default_layout",[L,le]=(0,_.useState)(null),[ee,ze]=(0,_.useState)(null),Le=(0,_.useRef)(null),[Qe,ce]=(0,_.useState)(null),ft=(0,_.useRef)(null),[V,je]=(0,_.useState)(null),bt=(0,_.useMemo)(()=>n?Qr(n):"",[n]),J=n?`create:${bt}`:`session:${e??""}`,Ct=V?.gateways?.stripe?"stripe":V?.gateways?.paypal?"paypal":void 0,He=(0,_.useRef)(new Set),en=(0,_.useRef)(J),Rt=(0,_.useRef)(J);Co(()=>{Rt.current=J,en.current!==J&&(en.current=J,He.current.clear())},[J]);let A=(0,_.useCallback)(u=>{if(Rt.current===J){if(na.has(u.name)){if(He.current.has(u.name))return;He.current.add(u.name)}Ne(()=>k?.(u))}},[J,k]),Ce=Sr(A,J),gt=(0,_.useRef)(!1),Ue=(0,_.useCallback)(u=>{if(gt.current)return;let c=u.gateway||!Ct?u:{...u,gateway:Ct};A(c)},[A,Ct]);(0,_.useEffect)(()=>{Ce({class:"lifecycle",name:"checkout.mount"})},[Ce]);let[qt,Jt]=(0,_.useState)(e??""),Ze=e??qt,St=n?"":Ze,[et,Ft]=(0,_.useState)(!0),[Ge,jt]=(0,_.useState)(null),[_t,tn]=(0,_.useState)("full"),[Dt,Tn]=(0,_.useState)(!1),[ln,at]=(0,_.useState)(re),[Lt,Je]=(0,_.useState)(null),[An,dt]=(0,_.useState)(null),[bn,Ot]=(0,_.useState)(!1),[me,Yn]=(0,_.useState)(void 0),[Mn,Fn]=(0,_.useState)(""),[Bn,mr]=(0,_.useState)(!1),[F,tt]=(0,_.useState)(!1),Ie=(0,_.useRef)(0),[Cn,Ve]=(0,_.useState)("loading"),[Wn,tr]=(0,_.useState)(0),Vt=(0,_.useRef)(!1),ut=(0,_.useRef)(!1),Xt=(0,_.useRef)(!1),Kt=(0,_.useRef)(null),it=(0,_.useMemo)(()=>({checkoutMode:be??_t,layout:ye?"unknown":Z==="buttons"?"buttons":"embedded"}),[be,ye,_t,Z]),cn=(0,_.useRef)(g);cn.current=g;let dn=(0,_.useRef)(h);dn.current=h;let Gn=(0,_.useRef)(w);Gn.current=w,(0,_.useEffect)(()=>{Tt(ee)?.setCheckoutContext(it),Qe&&Qe!==ee&&Tt(Qe)?.setCheckoutContext(it)},[ee,Qe,it]);let Sn=(0,_.useRef)(G);Sn.current=G;let nn=(0,_.useCallback)(u=>{Ve(u),!(u!=="exhausted"||Xt.current)&&(Xt.current=!0,dn.current?.(new ge.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),un=(0,_.useCallback)(()=>{Ve("retrying"),tr(u=>u+1)},[]);(0,_.useEffect)(()=>{Ve("loading"),tr(0),Xt.current=!1},[Ze]),(0,_.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:ge.SDK_VERSION,checkout_type:qe,checkout_layout:ue,billing_api_url:T})},[ue,qe,T]);let we=(0,_.useMemo)(()=>n?Qr(n,!0):"",[n]),wt=(0,_.useMemo)(()=>Mn===we?me:void 0,[me,Mn,we]),st=(0,_.useMemo)(()=>n?Qo(n,wt):void 0,[n,wt]),rn=be??st?.checkoutMode??"full",pn=(0,_.useMemo)(()=>st?{...st,checkoutMode:rn}:void 0,[st,rn]);(0,_.useEffect)(()=>{Yn(void 0),Fn(we)},[we]),(0,_.useEffect)(()=>{at(re)},[re]);let zn=(0,_.useCallback)((u,c,m)=>{Ne(()=>{Gn.current?.(Mt(u,c,m))})},[Ne]),mn=(0,_.useCallback)(async(u,c)=>{at(null),dt(null),Ot(!1),Je("processing");let m=c?.sessionId??u.id,q=u.gateways?.stripe?"stripe":u.gateways?.paypal?"paypal":void 0,ae=Le.current??ft.current,Y=Tt(ae),E=ae?null:Lo(T,o,it),C={log:Ee=>{Y?Y.log(Ee):E?.log(Ee)},error:Ee=>{Y?Y.error(Ee):E?.error(Ee)},terminal:Ee=>{Y?Y.terminal(Ee):E?.terminal(Ee)},performance:Ee=>{Y?Y.performance(Ee):E?.performance(Ee)},now:()=>Y?.now()??E?.now()??0,elapsed:Ee=>Y?.elapsed(Ee)??Math.max(0,(E?.now()??Ee)-Ee)},b=C.now(),S=!!(c?.initialAutoProcessingError||c?.initialAutoProcessingPending),D=!1,de,Pe=()=>{D||(D=!0,S=!0,de=C.now(),C.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),C.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Oe=!1,Ye=()=>{Oe||(Oe=!0,C.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),C.performance({stage:"processing",durationMs:C.elapsed(b),durationMode:"machine",paymentMethodCategory:"saved"}),de!==void 0&&C.performance({stage:"recovery",durationMs:C.elapsed(de),durationMode:"machine",paymentMethodCategory:"saved"}))};C.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),gt.current=!0;try{C.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{gt.current=!1}Ce({class:"lifecycle",name:"payment.processing.started",provider:q}),S&&Pe();let At;try{let Ee=yi(c?.initialAutoProcessingError),Re;if(Ee)Pe(),Ee.type==="paypal_redirect_required"&&Kt.current?.publishableKey&&Di({sessionId:m,publishableKey:Kt.current.publishableKey,paypalPublishableKey:Kt.current.paypalPublishableKey}),Re=await Ro(Ee,{flopay:Le.current,paypalFlopay:ft.current,attempt3DS:c?.attempt3DS,billingApiUrl:T,sessionId:m,session:u,telemetry:!1}),Ee.type==="paypal_redirect_required"&&fa();else if(c?.initialAutoProcessingPending){let We=(await new ur.PaymentAPI(T,{telemetry:!1}).waitForCheckoutSessionCompletion(c.initialAutoProcessingPending.sessionId,{initialDelayMs:c.initialAutoProcessingPending.retryAfterMs})).data.session;if(!vr(We))throw fo(We);Re=sr(We,m)}else{if(c?.initialAutoProcessingError)throw Qn(c.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:c.initialAutoProcessingError.checkoutMethod});if(c?.fromCreateSession)return c?.fallbackToFull&&(tn("full"),Li("full")),!1;{let j=await Er({billingApiUrl:T,sessionId:m,session:u,telemetry:!1});j.type==="success"?Re=j.result:(Pe(),j.type==="paypal_redirect_required"&&Kt.current?.publishableKey&&Di({sessionId:m,publishableKey:Kt.current.publishableKey,paypalPublishableKey:Kt.current.paypalPublishableKey}),Re=await Ro(j,{flopay:Le.current,paypalFlopay:ft.current,attempt3DS:c?.attempt3DS,billingApiUrl:T,sessionId:m,session:u,telemetry:!1}),j.type==="paypal_redirect_required"&&fa())}}m&&kr(m),Ye(),S&&(C.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),C.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),C.terminal({outcome:Re.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Ot(Re.status==="authorized"),Je("success"),await Xr(1200),At=()=>cn.current?.(Re)}catch(Ee){let Re=dr(Ee),j=Re.checkoutMethod??Gr;at(Re.message),dt(Re.message),Ot(!1),c?.fallbackToFull&&(C.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),tn("full"),Li("full")),Ye();let kt=Re.statusCode!==void 0?(0,ge.telemetryStatusClass)(Re.statusCode,"unknown"):void 0,We=kt==="4xx"?{requestCategory:"process_payment",statusClass:kt}:{},rt=kt===void 0||kt==="4xx";if(rt&&(Re.telemetryOutcome==="payment_declined"||!!(Re.declineCode||Re.code?.toLowerCase().includes("declin"))))C.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...We});else if(rt&&(Re.telemetryOutcome==="validation_rejected"||Re.type==="validation_error"))C.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...We});else{let to=(0,ge.classifyTelemetryFailure)(Ee,S?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),on=Re.telemetryRequestCategory??"process_payment";gt.current=!0;try{C.error({...to,...Re.telemetryFailureCategory?{failureCategory:Re.telemetryFailureCategory}:{},stage:S?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:on})}finally{gt.current=!1}Ce({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:on,provider:q})}return Ne(()=>dn.current?.(Re)),zn(j,Re,{code:Re.code,declineCode:Re.declineCode}),Je("error"),await Promise.allSettled([Xr(1500),c?.ensureProvidersReady?c.ensureProvidersReady():Promise.resolve()]),S&&(C.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),C.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ye(),E&&Zr(E),Je(null),dt(null)}return Ne(At),!0},[zn,Ce,Ne,dr,T,o,it]);(0,_.useEffect)(()=>{if(typeof window>"u"||ut.current)return;let u=new URLSearchParams(window.location.search),c=u.get("payment_intent_client_secret");if(!c)return;let m=ol();m&&(ut.current=!0,(async()=>{let q,ae=0;at(null),dt(null),Je("processing"),Tn(!0);try{if(u.get("redirect_status")==="failed")throw Object.assign(new ge.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Y,paypalFlopay:E}=await xo({publishableKey:m.publishableKey,paypalPublishableKey:m.paypalPublishableKey,billingApiUrl:T,locale:p,telemetry:o});q=Tt(E??Y),ae=q?.now()??0,q?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),q?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let C=(E??Y)?.getRawProvider();if(!C)throw Object.assign(new ge.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:b,error:S}=await C.retrievePaymentIntent(c);if(S)throw Object.assign(new ge.FloPayError(S.message??"Failed to retrieve PayPal payment status.","api_error",{code:S.code}),{checkoutMethod:"paypal"});let D=ni(b?.status);if(!b||D==="failed")throw Object.assign(new ge.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let de=typeof b.payment_method=="string"?b.payment_method:b.payment_method?.id,Pe=D;if(m.sessionId){let At=(await new ur.PaymentAPI(T,{telemetry:!1}).getUnifiedCheckoutSession(m.sessionId)).data.session;if(At&&At.status!=="complete"){let Ee=await Er({billingApiUrl:T,sessionId:m.sessionId,session:At,telemetry:!1,tokenizedData:{id:de??b.id,type:"card",threeDSecureActionResultTokenId:b.id,isPaypal:!0}});if(Ee.type!=="success")throw Object.assign(new ge.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Pe=Ee.result.status}}m.sessionId&&kr(m.sessionId),q?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),q?.performance({stage:"redirect_resume",durationMs:q.elapsed(ae),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),q?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Je("success"),await Xr(1200),Ne(()=>cn.current?.({status:Pe,paymentIntentId:b.id,paymentMethodId:de,checkoutMethod:"paypal"}))}catch(Y){let E=dr(Y),C=E.checkoutMethod??"paypal",b=!!(E.declineCode||E.code?.toLowerCase().includes("declin"));if(q)q.performance({stage:"redirect_resume",durationMs:q.elapsed(ae),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),b?q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):q.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(b){let S=Lo(T,o,it);S.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Zr(S)}else ma(T,o,it,"REDIRECT_RESUME_FAILED","redirect_resume");at(E.message),dt(E.message),Ne(()=>dn.current?.(E)),zn(C,E,{code:E.code,declineCode:E.declineCode}),Je("error"),await Xr(1500)}finally{fa(),al(),Je(null),dt(null),Tn(!1)}})())},[zn,Ne,p,dr,T,o]);let Nt=(0,_.useRef)(null),Ht=(0,_.useMemo)(()=>pn?Qr(pn):"",[pn]),Yt=(0,_.useRef)(pn);Yt.current=pn,(0,_.useEffect)(()=>{Jt(e??"")},[e]),(0,_.useEffect)(()=>{Vt.current=!1,at(re),dt(null),Ot(!1),Je(null)},[Ht,re,e]);async function Jn(u,c,m){let q=Lo(T,o,it),ae=new ur.PaymentAPI(T,{telemetry:!1}),Y=!1;try{let E=u.idempotencyKey!==void 0?(0,ge.resolveIdempotencyKey)(u.idempotencyKey):void 0,C=Oi(c,m),b=Ni(c,m);C?.canonicalIdentity===m&&b&&b.canonicalIdentity===void 0&&(ha(c,m,b.idempotencyKey),b={...b,canonicalIdentity:m});let S=E??(b?.canonicalIdentity===m?b.idempotencyKey:void 0),D,de=!1;q.log({name:C?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let Pe=C?.sid??null,Oe=null,Ye;if(Pe)try{Oe=await ae.getUnifiedCheckoutSession(Pe,C?.nonce),C&&C.canonicalIdentity===void 0&&(ll(Oe.data.session,u)?(ga(c,m,Pe,C.nonce??Oe.data.session?.clientSecret),b&&b.canonicalIdentity===void 0&&(ha(c,m,b.idempotencyKey),S??(S=b.idempotencyKey))):(Pa(c,m),b=null,S=E,Pe=null,Oe=null));let At=Oe?.data.session?.status;if(Pe&&Oe&&At==="complete"){if(oa(Pe))return{sid:Pe,result:Oe};Pa(c,m),Pe=null,Oe=null,de=!0}}catch{q.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),C?.canonicalIdentity===void 0?(Pa(c,m),S=E):Ca(c,m),Pe=null}if(!Pe){!E&&(de||!S)&&(S=(0,ge.resolveIdempotencyKey)(),D=S),S&&ha(c,m,S);let At=q.now(),Ee=0;q.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Re={...u,idempotencyKey:S,avsCheck:!!oe,avsConfig:typeof oe=="object"?oe:void 0,checkoutType:"embedded_checkout",checkoutLayout:ye?"custom_layout":Z==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(Re,ur.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:We=>{Ee=Math.max(Ee,We)}}});let j=()=>{q.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),q.performance({stage:"session_create",durationMs:q.now()-At,durationMode:"machine",requestCategory:"session_create",attempt:Ee,statusClass:"2xx"})},kt=We=>{let rt=(0,ge.classifyTelemetryFailure)(We,"CHECKOUT_SESSION_CREATE_FAILED","unknown");q.performance({stage:"session_create",durationMs:q.now()-At,durationMode:"machine",requestCategory:"session_create",attempt:Ee,statusClass:rt.statusClass}),We instanceof ge.FloPayError&&We.type==="validation_error"?q.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):rt.statusClass==="4xx"?q.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(q.error({...rt,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Ce({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if((0,ge.isDetachedSessionEligible)(Re)){let We=await ae.createDetachedSession(Re);We.claimed.catch(()=>{}),Oe=We.shell,Pe=We.sessionId,Ye=We.claimed.then(rt=>{let rr=rt.data.session?.id??We.sessionId;return rr&&ga(c,m,rr,rt.data.session?.clientSecret??We.nonce),j(),rt},rt=>{throw Ca(c,m),kt(rt),rt}).finally(()=>Zr(q)),Ye.catch(()=>{}),Y=!0,q.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),q.performance({stage:"session_shell",durationMs:q.now()-At,durationMode:"machine",requestCategory:"session_create",attempt:Ee,statusClass:"2xx",paymentMethodCategory:"card"})}else Oe=await ae.createAndFetchSession(Re),j()}catch(We){throw kt(We),We}Pe=Oe.data.session?.id??Pe??"",Pe&&!Ye&&ga(c,m,Pe,Oe.data.session?.clientSecret)}return{sid:Pe??"",result:Oe,sdkGeneratedIdempotencyKey:D,...Ye?{claimed:Ye}:{}}}finally{Y||Zr(q)}}let Un=(0,_.useCallback)(async(u,c)=>{let m=Yt.current;if(!m)throw new ge.FloPayError("createSession is required to bootstrap checkout.","validation_error");let q=Qo(m,u),ae=Qr(q),Y=sl(q),E=Oo.get(ae);if(!E){let S={canonicalIdentity:ae,promise:Jn(q,Y,ae),consumers:0,settled:!1};E=S,Oo.set(ae,S);let D=()=>{S.settled=!0,Bi(ae,S)};S.promise.then(D,D)}E.consumers+=1;let C=!1,b=()=>{C||(C=!0,E.consumers-=1,Bi(ae,E))};c?.(b);try{let S=await E.promise;Nt.current=ae,u&&(Fn(we),Yn(Re=>Qa(Re,u)));let{sid:D,result:de,claimed:Pe}=S;if(le(de),de.data.session&&je(de.data.session),D&&Jt(D),Pe){Ie.current+=1;let Re=Ie.current;tt(!0),Pe.then(j=>{Ie.current===Re&&(le(j),j.data.session&&je(j.data.session),tt(!1))},j=>{Ie.current===Re&&(tt(!1),jt(j instanceof ge.FloPayError?j:new ge.FloPayError(j instanceof Error?j.message:"Failed to create session","api_error")))})}else Ie.current+=1,tt(!1);let{publishableKey:Oe,paypalPublishableKey:Ye}=_o(de),{flopay:At,paypalFlopay:Ee}=await xo({publishableKey:Oe,paypalPublishableKey:Ye,billingApiUrl:T,locale:p,telemetry:o});return Le.current=At,ze(At),ft.current=Ee,ce(Ee),Ft(!1),S}catch(S){throw Nt.current===ae&&(Nt.current=null),S}finally{c||b()}},[we,p,T,o,it]),Dn=(0,_.useRef)(mn);Dn.current=mn;let $n=(0,_.useRef)(Un);$n.current=Un;let zt=(0,_.useCallback)(async u=>{if(!il(u)||Bn)return{sessionId:qt,session:V};mr(!0);try{let c=await Un(u);return{sessionId:c.sid,session:c.result.data.session??null}}finally{mr(!1)}},[Un,Bn,qt,V]);(0,_.useEffect)(()=>{let u=!1,c;if(jt(null),Ht){let ae=Yt.current;return tn(rn),Ft(!1),Nt.current===Ht?()=>{u=!0}:(je(ei(ae,be)),(async()=>{let Y=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),E=rn==="auto"&&!Vt.current&&!Y;E&&(at(null),dt(null),Je("processing"));try{let C=await $n.current(void 0,de=>{c=de}),b=C.result.data.session??null;Kt.current=_o(C.result);let S=ya(C.result),D=oa(C.sid||b?.id);if(!u&&E&&b&&!S&&!D){Vt.current=!0,await nl(Ht,C.sdkGeneratedIdempotencyKey,()=>Dn.current(b,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:C.result.autoProcessingError,initialAutoProcessingPending:C.result.autoProcessingPending,autoProcessingAttempted:C.result.autoProcessingAttempted,sessionId:C.sid||b.id}));return}!u&&E&&((S||D)&&(Vt.current=!0),Je(null),dt(null))}catch(C){if(u)return;let b=C instanceof ge.FloPayError||typeof C=="object"&&C!==null&&"code"in C?C.code:void 0;if(E&&b==="session_auto_completed"){Vt.current=!0,Je("success"),await Xr(1200),u||(Ne(()=>{cn.current?.({status:"succeeded"})}),Je(null),dt(null));return}E&&(Je(null),dt(null));let S=C instanceof ge.FloPayError?C:new ge.FloPayError(C instanceof Error?C.message:"Failed to create session","api_error");jt(S)}finally{c?.(),c=void 0}})(),()=>{u=!0,c?.()})}Ft(!0);async function m(){let ae=!1;try{let E=await new ur.PaymentAPI(T,{telemetry:!1}).getUnifiedCheckoutSession(Ze,t);if(u)return;le(E);let C=E.data.session??null;if(je(C),!C)throw new ge.FloPayError("No session data returned","api_error");let b=C.checkoutMode;if(b==="setup")throw new ge.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(C.status==="authorized"){Ft(!1),Ne(()=>{cn.current?.(sr(C,Ze)),Sn.current?.(C.successUrl??"")});return}if(C.status==="complete"){Ft(!1),Ne(()=>{Sn.current?.(C.successUrl??"")});return}if(C.status==="expired")throw yo(C);ae=!0;let S=be??b??"full";tn(S);let D=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),de=ya(E);if(S==="auto"&&!Vt.current&&!D&&!de){Vt.current=!0;let Pe=q(E);try{if(await Dn.current(C,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Pe,sessionId:Ze||C.id}),u)return;await Pe,u||Ft(!1);return}catch{if(u)return;await Pe,u||Ft(!1);return}}await q(E),u||Ft(!1)}catch(Y){if(u)return;ae&&Ce({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),Y instanceof ge.FloPayError?!ae&&!rl(Y)&&ma(T,o,it,"NETWORK_REQUEST_FAILED","session_read"):ma(T,o,it,"INTERNAL_SDK_ERROR","checkout_mount");let E=Y instanceof ge.FloPayError?Y:new ge.FloPayError(Y instanceof Error?Y.message:"Failed to initialize checkout","api_error");jt(E),Ft(!1)}}async function q(ae){let{publishableKey:Y,paypalPublishableKey:E}=_o(ae);Kt.current={publishableKey:Y,paypalPublishableKey:E};let{flopay:C,paypalFlopay:b}=await xo({publishableKey:Y,paypalPublishableKey:E,billingApiUrl:T,locale:p,telemetry:o});Le.current=C,ze(C),ft.current=b,ce(b)}return m(),()=>{u=!0}},[be,Ht,rn,St,Ne,t]);let nt=(0,_.useCallback)(async()=>{if(!(Dt||!V)){Tn(!0),at(null);try{await mn(V,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ze||V.id})}finally{Tn(!1)}}},[Ze,Dt,mn,V]),yn=ba(L),Ut=ya(L),pt=(0,_.useMemo)(()=>{if(!L||!V||!L.data.stripe?.publishableKey)return;let u={appearance:$e,paymentMethodCreation:"manual",billingApiUrl:T};if(L.data.stripe?.clientSecret)u.clientSecret=L.data.stripe.clientSecret;else{let c=(0,ge.buildCheckoutDisplayData)(V).total;u.amount=Math.round(c*100)||V.amount,u.currency=V.currency?.toLowerCase()}return u},[L,V,$e,T]),Zt=!!(n&&!ye&&Z==="buttons"&&N&&rn==="full"),xt=(0,_.useMemo)(()=>({session:V,loading:et,error:Ge,checkoutMode:_t,inlineSessionDraft:pn,applyInlineSessionPatch:Zt?zt:void 0,inlineSessionPatchProcessing:Bn,claimPending:F}),[V,et,Ge,_t,pn,Zt,zt,Bn,F]),nr=!!n&&Z==="buttons"&&!Ut&&(!ee||!pt),mt=Lt?(0,R.jsx)(Pn,{status:Lt,errorMessage:An,authorized:bn}):null;if(et){if(d)return(0,R.jsxs)(R.Fragment,{children:[d,mt]});if(Z==="buttons"){let u=fe?.buttonsLayout?.cardButton?.borderRadius??fe?.appearance.variables?.borderRadius??8,c=m=>(0,R.jsx)("div",{style:{height:m,borderRadius:u,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[v&&c(xr),H&&(f||ie)&&c(xr),H&&c(xr),(0,R.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),mt]})}return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,R.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,R.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),mt]})}return Ge?I?(0,R.jsx)(kn.Provider,{value:xt,children:I(Ge)}):(0,R.jsx)(kn.Provider,{value:xt,children:(0,R.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ge.message})}):nr?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(kn.Provider,{value:xt,children:(0,R.jsx)(dl,{onButtonClick:$,showPayPal:v,showStripe:H,showApplePay:f,showGooglePay:ie,theme:Q,buttonsTheme:ve,buttonsStyles:B,cardButtonContent:se,cardBackButtonContent:xe,cardTitleContent:Se})}),mt]}):Ut&&V&&yn?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(kn.Provider,{value:xt,children:(0,R.jsxs)("div",{className:K,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ln&&(0,R.jsx)(wr,{icon:!1,children:ln}),Cn==="retrying"&&(0,R.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Cn==="exhausted"&&(0,R.jsxs)("div",{role:"alert",children:[(0,R.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,R.jsx)("button",{type:"button",onClick:un,children:"Retry PayPal"})]}),Cn!=="exhausted"&&(0,R.jsx)("div",{"aria-hidden":Cn==="retrying"?!0:void 0,style:Cn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,R.jsx)(ui,{sessionId:Ze,nonce:V.clientSecret||void 0,billingApiUrl:T,email:V.customer?.email,clientId:yn.clientId,environment:yn.environment,currency:(V.currency??"usd").toUpperCase(),isSubscription:V.mode==="subscription",providerObjectType:yn.providerObjectType,onComplete:g,onErrorChange:at,onDecline:w,onButtonClick:$,onInitializationStateChange:nn,allowAutomaticRetry:Wn===0,session:V,telemetry:o,telemetryContext:it,onInstrument:Ue,debug:O},`${J}:paypal-init-${Wn}`)})]})}),mt]}):!ee||!pt?(0,R.jsx)(R.Fragment,{children:mt}):_t==="confirm"?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(kn.Provider,{value:xt,children:(0,R.jsx)(Yr,{flopay:ee,paypalFlopay:Qe,options:pt,onInstrument:Ue,children:(0,R.jsxs)("div",{className:K,children:[ln&&(0,R.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:ln}),_e?_e({onConfirm:nt,isProcessing:Dt}):(0,R.jsx)("button",{type:"button",onClick:nt,disabled:Dt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Dt?"not-allowed":"pointer",opacity:Dt?.6:1},children:Dt?"Processing...":ne??"Confirm Purchase"})]})},J)}),mt]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(kn.Provider,{value:xt,children:(0,R.jsx)(Yr,{flopay:ee,paypalFlopay:Qe,options:pt,onInstrument:Ue,children:ye?(0,R.jsxs)(R.Fragment,{children:[ln&&(0,R.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:ln}),(0,R.jsx)(cl,{sessionId:Ze,nonce:V?.clientSecret||void 0,billingApiUrl:T,session:V,children:ye})]}):(0,R.jsx)(Bo,{sessionId:Ze,nonce:V?.clientSecret||void 0,email:V?.customer?.email,userId:V?.customer?.id,firstName:V?.customer?.firstName,lastName:V?.customer?.lastName,totalAmount:V?Math.round((0,ge.buildCheckoutDisplayData)(V).total*100):0,currency:V?.currency?.toLowerCase()??"usd",onComplete:g,onError:h,onDecline:w,error:ln,onErrorChange:at,showPayPal:v,showStripe:H,enabledPaymentMethods:M??L?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:L?.data.stripe?.enabledPaymentMethodCountries,showApplePay:f,showGooglePay:ie,layout:Z,theme:Q,buttonsTheme:ve,buttonsStyles:B,appearance:$e,cardButtonContent:se,cardBackButtonContent:xe,cardTitleContent:Se,onButtonClick:$,onBeforeButtonClick:N,enableAVS:oe,...Me?{cardFieldOrder:Me}:{},...Te?{cardPreFormSlot:Te}:{},avsLayout:te,country:V?.customer?.country,city:V?.customer?.city,state:V?.customer?.state,onCountryChange:x,onZipChange:y,avsCheck:!!oe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ye?"custom_layout":Z==="buttons"?"buttons_layout":"default_layout",className:K,directPaypal:ba(L),isSubscription:V?.mode==="subscription",session:V,dataAttachmentPending:F,debug:O})},J)}),mt]})}function cl({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,R.jsx)(R.Fragment,{children:_.default.Children.map(o,a=>{if(!_.default.isValidElement(a))return a;let p=a.props,d={};return p.sessionId||(d.sessionId=e),!p.nonce&&t&&(d.nonce=t),p.billingApiUrl||(d.billingApiUrl=n),r?.customer&&(p.email||(d.email=r.customer.email),p.userId||(d.userId=r.customer.id),p.firstName||(d.firstName=r.customer.firstName),p.lastName||(d.lastName=r.customer.lastName)),Object.keys(d).length===0?a:_.default.cloneElement(a,d)})})}function dl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:p,buttonsStyles:d,cardButtonContent:I,cardBackButtonContent:g,cardTitleContent:h}){let[k,w]=(0,_.useState)(!1),x=(0,_.useMemo)(()=>(0,ge.resolveTheme)(a),[a]),y=(0,_.useMemo)(()=>{let f=x?.buttonsLayout??(0,ge.resolveButtonsLayoutTheme)(p);return d?{...f,...d,cardButton:{...f.cardButton,...d.cardButton},cardFormContainer:{...f.cardFormContainer,...d.cardFormContainer},backButton:{...f.backButton,...d.backButton},backButtonIcon:{...f.backButtonIcon,...d.backButtonIcon},submitButton:{...f.submitButton,...d.submitButton},title:{...f.title,...d.title}}:f},[x,p,d]),v=x?.buttonsLayout?.cardButton?.borderRadius??x?.appearance.variables?.borderRadius??8,H=f=>(0,R.jsx)("div",{style:{height:f,borderRadius:v,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),M=I===void 0?{boxSizing:"border-box",height:xr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(k){let f=y.cardInputBorder??"#e5e7eb",ie=y.cardInputBackground??"white",O=fr(g),Z=fr(h);return(0,R.jsxs)("div",{style:{backgroundColor:y.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...y.cardFormContainer},children:[(0,R.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,R.jsxs)("button",{type:"button",onClick:()=>w(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:O?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...y.backButton},children:[(0,R.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...y.backButtonIcon},children:(0,R.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,R.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,R.jsx)(hr,{content:g})]}),Z?(0,R.jsx)("div",{style:{flex:1}}):(0,R.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...y.title},children:(0,R.jsx)(qr,{content:h})})]}),(0,R.jsx)("div",{style:{backgroundColor:ie,border:`1px solid ${f}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsxs)("div",{style:{display:"flex"},children:[(0,R.jsx)("div",{style:{flex:1,backgroundColor:ie,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsx)("div",{style:{flex:1,backgroundColor:ie,borderTop:"none",borderRight:`1px solid ${f}`,borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,R.jsx)("div",{style:{backgroundColor:ie,border:`1px solid ${f}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...y.submitButton,opacity:.5}}),(0,R.jsx)("style",{children:`
|
|
38
|
+
`}),Ar&&dn&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ke?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:Ln,style:{display:"inline-flex",alignItems:"center",gap:jo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(mr,{content:Se})]}),La?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...p.title},children:(0,l.jsx)(Or,{content:K})})]}),!Ar&&!La&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Vo,order:ke?-3:0,...p.title},children:(0,l.jsx)(Or,{content:K})}),ue&&(0,l.jsx)("div",{style:{order:ke?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Oe,L=(V=!1)=>({backgroundColor:Fr,border:`1px solid ${tr(V)}`,borderRadius:wt,marginTop:"0.5rem",padding:"10px"}),W=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ua}),de=(0,f.getStateOptions)(s);return(0,l.jsxs)(l.Fragment,{children:[(0,f.isAVSFieldVisible)(ue.address_line_1,s)&&(0,l.jsx)("div",{style:L(at.line1),children:(0,l.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:bt,onChange:V=>{Lt.current.addressLine1=!0,Ge.current=V.target.value,Qe(V.target.value)},disabled:k,required:!0,"data-testid":"flopay-address-line1",style:W()})}),(0,f.isAVSFieldVisible)(ue.address_line_2,s)&&(0,l.jsx)("div",{style:L(),children:(0,l.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:At,onChange:V=>{Lt.current.addressLine2=!0,Rn.current=V.target.value,We(V.target.value)},disabled:k,"data-testid":"flopay-address-line2",style:W()})}),((0,f.isAVSFieldVisible)(ue.city,s)||(0,f.isAVSFieldVisible)(ue.state,s))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,f.isAVSFieldVisible)(ue.city,s)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Fr,borderTop:`1px solid ${tr(at.city)}`,borderRight:`1px solid ${tr(at.city)}`,borderBottom:`1px solid ${tr(at.city)}`,borderLeft:`1px solid ${tr(at.city)}`,padding:"10px",borderTopLeftRadius:wt,borderBottomLeftRadius:wt,...(0,f.isAVSFieldVisible)(ue.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:wt}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:qt,onChange:V=>{Lt.current.city=!0,ct.current=V.target.value,Et(V.target.value)},disabled:k,required:!0,"data-testid":"flopay-city",style:W()})}),(0,f.isAVSFieldVisible)(ue.state,s)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Fr,border:`1px solid ${tr(at.state)}`,padding:"10px",borderTopRightRadius:wt,borderBottomRightRadius:wt,...(0,f.isAVSFieldVisible)(ue.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:wt}},children:de?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Qt,onChange:V=>{Lt.current.state=!0,Pn.current=V.target.value,Bt(V.target.value)},disabled:k,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...W(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,f.getStateLabel)(s)}),de.map(V=>(0,l.jsx)("option",{value:V.code,children:V.name},V.code))]}):(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,f.getStateLabel)(s),autoComplete:"billing address-level1",value:Qt,onChange:V=>{Lt.current.state=!0,Pn.current=V.target.value,Bt(V.target.value)},disabled:k,required:!0,"data-testid":"flopay-state",style:W()})})]}),((0,f.isAVSFieldVisible)(ue.country,s)||(0,f.isAVSFieldVisible)(ue.postal_code,s))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:ee==="column"?"column":"row",gap:ee==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,f.isAVSFieldVisible)(ue.country,s)&&(0,l.jsx)("div",{style:{flex:ee==="row"?1:void 0,backgroundColor:Fr,borderTop:`1px solid ${Mr}`,borderRight:`1px solid ${Mr}`,borderBottom:`1px solid ${Mr}`,borderLeft:`1px solid ${Mr}`,padding:"10px",...ee==="row"&&(0,f.isAVSFieldVisible)(ue.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:wt,borderBottomLeftRadius:wt,borderRight:"none"}:{borderRadius:wt}},children:(0,l.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Oe,onChange:V=>{Lt.current.country=!0,Dt.current=V.target.value,$t(V.target.value),me?.(V.target.value),Pn.current="",Bt("")},disabled:k,autoComplete:"billing country","data-testid":"flopay-country",style:{...W(),cursor:"pointer"},children:f.COUNTRY_OPTIONS.map(V=>(0,l.jsxs)("option",{value:V.code,children:[V.flag," ",V.name]},V.code))})}),(0,f.isAVSFieldVisible)(ue.postal_code,s)&&(0,l.jsx)("div",{style:{flex:ee==="row"?1:void 0,backgroundColor:Fr,border:`1px solid ${Ji}`,padding:"10px",...ee==="row"&&(0,f.isAVSFieldVisible)(ue.country,s)?{borderRadius:"0",borderTopRightRadius:wt,borderBottomRightRadius:wt}:{borderRadius:wt}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,f.getPostalCodeLabel)(Oe),autoComplete:"billing postal-code",value:Wt,onChange:V=>{Lt.current.zip=!0,ot.current=V.target.value,Xe(V.target.value),Ye?.(V.target.value)},onBlur:()=>Cn(!0),disabled:k,required:Gt.required,"aria-invalid":oo||void 0,"aria-describedby":oo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:W()})})]}),oo&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:$o,...Ua,fontSize:"0.75rem"},children:Gt.empty?`${(0,f.getPostalCodeLabel)(s)} is required`:Ns(s)})]})})()}),ke&&$&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:$}),ke&&ts,u&&(0,l.jsx)(vr,{margin:"0.75rem 0",styleOverride:p.errorBanner,children:u})]}),ao={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"},qa=s=>j?!te||!nn?(0,l.jsx)("pre",{"data-testid":s,style:ao,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":s,style:ao,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${te}`,` directPaypalConfigured=${nn}`,` inAppBrowserDetected=${String(no)}`,` shouldRenderDirectPayPal=${Rr}`,` shouldRenderStripePayPal=${_r}`,` hasPaypalStripeInstance=${!!le}`].join(`
|
|
39
|
+
`)}):null,ja=s=>j?!G||!M?(0,l.jsx)("pre",{"data-testid":s,style:ao,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":s,style:ao,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${G}`,` currency=${J}`,` amountInCents=${ye}`,` enabledPaymentMethods: ${JSON.stringify(S??[])}`,` enabledPaymentMethodsProvided=${Ir}`,` hasEnabledMethods=${Zr}`,` expressMethods: ${JSON.stringify(Qr)}`,` walletExpressMethods: ${JSON.stringify(eo)}`,` paymentElementMethods: ${JSON.stringify(Er)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(to)}`,` hasStripeInstance=${!!M}`,` shouldRenderWallets=${Tr}`,` shouldRenderPaymentElement=${xr}`].join(`
|
|
40
|
+
`)}):null,Va=Ce==="apm-expanding"||Ce==="apm-form"||Ce==="apm-collapsing",io=Ce==="apm-expanding"?`flopay-card-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:Ce==="apm-collapsing"?`flopay-card-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,so=it?{...Lo,paymentMethodTypes:[it]}:null;if(re==="buttons"){let s=Ce==="buttons"||Ce==="expanding"||Ce==="apm-expanding",L=Ce==="expanding"||Ce==="card"||Ce==="collapsing",W=_e===void 0?{boxSizing:"border-box",height:Io,padding:"0 1rem"}:{padding:"0.9rem 1rem"},de=Ce==="expanding"||Ce==="apm-expanding"?`flopay-buttons-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ce==="collapsing"||Ce==="apm-collapsing"?`flopay-buttons-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,V=Ce==="expanding"?`flopay-card-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:Ce==="collapsing"?`flopay-card-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,l.jsxs)("form",{onSubmit:zo,className:A,style:{position:"relative"},children:[(0,l.jsx)(ra,{}),Nt&&(0,l.jsx)(hn,{status:Nt,errorMessage:u,authorized:_n}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!de?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!de?Ds:{},...de?{animation:de,pointerEvents:"none"}:{}},children:[qa("flopay-direct-paypal-gate-debug"),ja("flopay-stripe-gate-debug"),Rr&&Fe&&(0,l.jsxs)(l.Fragment,{children:[Jt&&(0,l.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,l.jsx)($r,{sessionId:e,nonce:t,billingApiUrl:pt,email:h.email,clientId:Fe.clientId,environment:Fe.environment,currency:J.toUpperCase(),isSubscription:Ze,providerObjectType:Fe.providerObjectType,onTokenizedBody:mn,onComplete:i,onErrorChange:z,onDecline:d,onTechnicalFailure:He,onButtonClick:ae,runBeforeButtonClick:Sn,isProcessing:k,onLoadStateChange:Oo,onInitializationStateChange:No,session:se??null,existingOrderId:Jt?.orderId,debug:j},Jt?.orderId??"fresh")]}),_r&&(0,l.jsx)(ht.Elements,{stripe:le,options:Ee,children:(0,l.jsx)(bi,{sessionId:e,nonce:t,email:h.email,billingApiUrl:pt,onTokenizedBody:mn,onErrorChange:z,isProcessing:k,onButtonClick:ae,onDecline:d,onTechnicalFailure:He,runBeforeButtonClick:Sn,onLoadStateChange:Ca,placeholderBorderRadius:nr})}),Tr?(0,l.jsx)(ht.Elements,{stripe:M,options:Ie,children:(0,l.jsx)(Ci,{sessionId:e,nonce:t,email:h.email,billingApiUrl:pt,intentKind:ie>0?"payment":"setup",expressMethods:eo,onTokenizedBody:mn,onErrorChange:z,onButtonClick:ae,onDecline:d,onTechnicalFailure:He,runBeforeButtonClick:Sn,onLoadStateChange:wa,placeholderBorderRadius:nr})}):_a?(0,l.jsx)("div",{style:{height:Io,borderRadius:nr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,xr&&(0,l.jsx)(Si,{sessionId:e,nonce:t,email:h.email,billingName:[h.firstName,h.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,paymentElementMethods:to,stripeInstance:M,paymentElementBaseOptions:Lo,onTokenizedBody:mn,onErrorChange:z,onButtonClick:ae,onDecline:d,runBeforeButtonClick:Sn,onLoadStateChange:Ia,isProcessing:k,submitButtonColor:rr,submitButtonBorderRadius:wt,submitButtonStyle:p.submitButton,onExpandApm:An,expandedApmMethod:it,themeId:be,buttonAppearance:{backgroundColor:p.cardButton?.backgroundColor,borderColor:p.cardInputBorder,textColor:p.cardButton?.color,borderRadius:nr}}),ke&&(0,l.jsx)("button",{type:"button",onClick:async()=>{k||!(await Sn("card")).proceed||(ae?.("card"),Yn())},disabled:k,style:{width:"100%",...W,...p.cardButton,...ia({themeBundle:c,resolvedPrimaryColor:rr,resolvedBorderRadius:wt,submitButtonStyle:p.submitButton,explicitPrimaryColor:Xt?.colorPrimary}),fontSize:p.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:k?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:k?.6:1},onMouseEnter:we=>{!k&&(c||Xt?.colorPrimary)&&(we.currentTarget.style.backgroundColor=Qi)},onMouseLeave:we=>{(c||Xt?.colorPrimary)&&(we.currentTarget.style.backgroundColor=rr)},onMouseDown:we=>{we.currentTarget.style.transform="scale(0.985)"},onMouseUp:we=>{we.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(pr,{content:_e})}),u&&Ce==="buttons"&&(0,l.jsx)(vr,{margin:"0.25rem 0",styleOverride:p.errorBanner,children:u})]}),ke&&L&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...V?{animation:V}:{},...Ce==="collapsing"?{pointerEvents:"none"}:{}},children:$a}),G&&Va&&it&&so&&M&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...io?{animation:io}:{},...Ce==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:qo,borderRadius:Ho,...Br,padding:Ko},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:On,style:{display:"inline-flex",alignItems:"center",gap:jo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(mr,{content:Se})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:Vo,paddingRight:80,...p.title},children:`Pay with ${(0,f.getStripeMethodDisplayName)(it)}`})]}),(0,l.jsx)(ht.Elements,{stripe:M,options:so,children:(0,l.jsx)(oa,{method:it,sessionId:e,nonce:t,email:h.email,billingName:[h.firstName,h.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,onTokenizedBody:mn,onErrorChange:z,onDecline:d,onCancel:On,runBeforeButtonClick:Sn,onButtonClick:ae,isProcessing:k,submitButtonColor:rr,submitButtonBorderRadius:wt,submitButtonStyle:p.submitButton,errorText:u})},it)]})})]})]})}return Va&&it&&so&&M&&G?(0,l.jsxs)("form",{onSubmit:zo,className:A,style:{position:"relative"},children:[(0,l.jsx)(ra,{}),Nt&&(0,l.jsx)(hn,{status:Nt,errorMessage:u,authorized:_n}),(0,l.jsx)("div",{style:{...io?{animation:io}:{},...Ce==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:qo,borderRadius:Ho,...Br,padding:Ko},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:On,style:{display:"inline-flex",alignItems:"center",gap:jo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(mr,{content:Se})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:Vo,paddingRight:80,...p.title},children:`Pay with ${(0,f.getStripeMethodDisplayName)(it)}`})]}),(0,l.jsx)(ht.Elements,{stripe:M,options:so,children:(0,l.jsx)(oa,{method:it,sessionId:e,nonce:t,email:h.email,billingName:[h.firstName,h.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,onTokenizedBody:mn,onErrorChange:z,onDecline:d,onCancel:On,runBeforeButtonClick:Sn,onButtonClick:ae,isProcessing:k,submitButtonColor:rr,submitButtonBorderRadius:wt,submitButtonStyle:p.submitButton,errorText:u})},it)]})})]}):(0,l.jsxs)("form",{onSubmit:zo,className:A,style:{position:"relative"},children:[(0,l.jsx)(ra,{}),Nt&&(0,l.jsx)(hn,{status:Nt,errorMessage:u,authorized:_n}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[qa("flopay-direct-paypal-gate-debug-default"),ja("flopay-stripe-gate-debug-default"),Rr&&Fe&&(0,l.jsxs)(l.Fragment,{children:[Jt&&(0,l.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,l.jsx)($r,{sessionId:e,nonce:t,billingApiUrl:pt,email:h.email,clientId:Fe.clientId,environment:Fe.environment,currency:J.toUpperCase(),isSubscription:Ze,providerObjectType:Fe.providerObjectType,onTokenizedBody:mn,onComplete:i,onErrorChange:z,onDecline:d,onTechnicalFailure:He,onButtonClick:ae,runBeforeButtonClick:Sn,isProcessing:k,onLoadStateChange:Oo,onInitializationStateChange:No,session:se??null,existingOrderId:Jt?.orderId,debug:j},Jt?.orderId??"fresh")]}),_r&&(0,l.jsx)(ht.Elements,{stripe:le,options:Ee,children:(0,l.jsx)(bi,{sessionId:e,nonce:t,email:h.email,billingApiUrl:pt,onTokenizedBody:mn,onErrorChange:z,isProcessing:k,onButtonClick:ae,onDecline:d,onTechnicalFailure:He,runBeforeButtonClick:Sn,onLoadStateChange:Ca,placeholderBorderRadius:nr})}),Tr&&(0,l.jsx)(ht.Elements,{stripe:M,options:Ie,children:(0,l.jsx)(Ci,{sessionId:e,nonce:t,email:h.email,billingApiUrl:pt,intentKind:ie>0?"payment":"setup",expressMethods:eo,onTokenizedBody:mn,onErrorChange:z,onButtonClick:ae,onDecline:d,onTechnicalFailure:He,runBeforeButtonClick:Sn,onLoadStateChange:wa,placeholderBorderRadius:nr})}),xr&&(0,l.jsx)(Si,{sessionId:e,nonce:t,email:h.email,billingName:[h.firstName,h.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,paymentElementMethods:to,stripeInstance:M,paymentElementBaseOptions:Lo,onTokenizedBody:mn,onErrorChange:z,onButtonClick:ae,onDecline:d,runBeforeButtonClick:Sn,onLoadStateChange:Ia,isProcessing:k,submitButtonColor:rr,submitButtonBorderRadius:wt,submitButtonStyle:p.submitButton,themeId:be,onExpandApm:An,expandedApmMethod:it,buttonAppearance:{backgroundColor:p.cardButton?.backgroundColor,borderColor:p.cardInputBorder,textColor:p.cardButton?.color,borderRadius:nr}})]}),ke&&(Hi||Ki||Yi)&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,l.jsx)("span",{children:"or pay with card"}),(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),ke&&$a]})}var I=require("react/jsx-runtime"),kr=44,ga="flopay_checkout_saved_payment_resume",Ao=new Map,To=new Map;function Ti(e,t){t.settled&&t.consumers===0&&Ao.get(e)===t&&Ao.delete(e)}function js(e,t,n){let o=To.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let r=n(),i={attempt:r,sdkGeneratedIdempotencyKey:t};To.set(e,i);let m=()=>{To.get(e)===i&&To.delete(e)};return r.then(m,m),r}function Yr(e){return new Promise(t=>setTimeout(t,e))}function xo(e,t,n){let o=go({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:fe.SDK_VERSION,enabled:t!==!1});return o.beginCheckout(n),o}function Wr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function sa(e,t,n,o,r){let i=xo(e,t,n);i.error({errorCode:o,stage:r,paymentMethodCategory:"unknown",...r==="session_read"?{requestCategory:"session_read"}:{}}),Wr(i)}function Vs(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 ya(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function la(e){return!e||e.data.stripe?.publishableKey?!1:!!ya(e)?.clientId}function jn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Ks(){if(!jn())return null;try{let e=window.sessionStorage.getItem(ga);return e?JSON.parse(e):null}catch{return null}}function xi(e){if(jn())try{window.sessionStorage.setItem(ga,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ca(){if(jn())try{window.sessionStorage.removeItem(ga)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ha=":idempotency-key";function Mi(e,t){if(!jn())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let o=JSON.parse(n);return!o||typeof o.sid!="string"||!o.sid||"canonicalIdentity"in o&&o.canonicalIdentity!==t?null:{..."canonicalIdentity"in o?{canonicalIdentity:t}:{},sid:o.sid,nonce:typeof o.nonce=="string"?o.nonce:void 0}}catch{return{sid:n}}}function da(e,t,n,o){if(jn())try{window.sessionStorage.setItem(e,JSON.stringify(o?{canonicalIdentity:t,sid:n,nonce:o}:{canonicalIdentity:t,sid:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",r)}}function fa(e,t){if(jn())try{Mi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Fi(e,t){if(!jn())return null;try{let n=window.sessionStorage.getItem(e+ha);if(!n)return null;try{let o=JSON.parse(n);return typeof o=="string"?o?{idempotencyKey:o}:null:!o||typeof o.idempotencyKey!="string"||!o.idempotencyKey||"canonicalIdentity"in o&&o.canonicalIdentity!==t?null:{..."canonicalIdentity"in o?{canonicalIdentity:t}:{},idempotencyKey:o.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function ua(e,t,n){if(jn())try{window.sessionStorage.setItem(e+ha,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",o)}}function pa(e,t){if(fa(e,t),!!jn())try{Fi(e,t)&&window.sessionStorage.removeItem(e+ha)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Hs(){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 o of t)e.searchParams.has(o)&&(e.searchParams.delete(o),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Ai(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 Ys(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function ma(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Gr(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",o={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(r=>ma(`${r.type??""}:${r.code??r.providerItemId??r.providerPlanId??""}`,r)).sort(),i:e?.items?.map(r=>ma(r.code??r.providerItemId??"",r)).sort(),s:e?.subscriptions?.map(r=>ma(r.code??r.providerPlanId??"",r)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(o)}function Ws(e,t=!1){let n=Gr(e,t),o=0;for(let r=0;r<n.length;r++)o=(o<<5)-o+n.charCodeAt(r)|0;return`flopay_session_${Math.abs(o).toString(36)}`}function Gs(e,t){if(!e?.customer||!e.products)return!1;let n=t.account.email?.trim().toLowerCase()??"",o=e.customer.email?.trim().toLowerCase()??"";if((n?o!==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 r=(0,fe.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!r||e.currency.toUpperCase()!==r.toUpperCase())return!1;let i=(t.products??(0,fe.foldIntoProducts)(t.items,t.subscriptions)).map(g=>({type:g.type,code:g.code??g.providerItemId??g.providerPlanId??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??r).toUpperCase()})).sort((g,v)=>`${g.code}:${g.type??""}`.localeCompare(`${v.code}:${v.type??""}`)),m=e.products.map(g=>({type:g.type,code:g.code??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??e.currency).toUpperCase()})).sort((g,v)=>`${g.code}:${g.type??""}`.localeCompare(`${v.code}:${v.type??""}`));if(i.length!==m.length)return!1;for(let g=0;g<i.length;g+=1){let v=i[g],b=m[g];if(v.code!==b.code||v.type!==void 0&&v.type!==b.type||v.quantity!==b.quantity||v.totalAmount!==b.totalAmount||v.overrideAmount!==b.overrideAmount||v.currency!==b.currency)return!1}let d=[...t.couponCodes??[]].sort(),R=[...e.coupons??[]].sort();return d.length===R.length&&d.every((g,v)=>g===R[v])}function Mo({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:r,appearance:i,locale:m,loading:d,error:R,onComplete:g,onError:v,onInstrument:b,onDecline:A,onCountryChange:D,onZipChange:y,showPayPal:C=!0,showStripe:te=!0,enabledPaymentMethods:G,showApplePay:S=!0,showGooglePay:ge=!0,debug:U=!1,layout:Q,theme:re,buttonsTheme:be,buttonsStyles:oe,cardButtonContent:he,cardBackButtonContent:Ne,cardTitleContent:_e,showSecurityFooter:Se,onButtonClick:K,onBeforeButtonClick:O,enableAVS:ae,cardFieldOrder:ze,cardPreFormSlot:Te,avsLayout:X,className:$,initialErrorMessage:ee=null,children:pe,checkoutMode:ve,confirmLabel:Z,renderConfirmButton:Re,onSessionCompleted:H}){let _=(0,fe.resolveBillingApiUrl)(o),me=(0,E.useMemo)(()=>(0,fe.resolveTheme)(re),[re]),Ye=i??me?.appearance,Ue=n?"embedded_checkout":"standard_checkout",ce=pe?"custom_layout":Q==="buttons"?"buttons_layout":"default_layout",[F,ie]=(0,E.useState)(null),[J,Le]=(0,E.useState)(null),Fe=(0,E.useRef)(null),[Ze,se]=(0,E.useState)(null),mt=(0,E.useRef)(null),[j,$e]=(0,E.useState)(null),vt=(0,E.useMemo)(()=>n?Gr(n):"",[n]),Y=n?`create:${vt}`:`session:${e??""}`,Pt=j?.gateways?.stripe?"stripe":j?.gateways?.paypal?"paypal":void 0,Ve=(0,E.useRef)(new Set),Zt=(0,E.useRef)(Y),It=(0,E.useRef)(Y);fo(()=>{It.current=Y,Zt.current!==Y&&(Zt.current=Y,Ve.current.clear())},[Y]);let T=(0,E.useCallback)(u=>{if(It.current===Y){if(Jo.has(u.name)){if(Ve.current.has(u.name))return;Ve.current.add(u.name)}De(()=>b?.(u))}},[Y,b]),Pe=hr(T,Y),yt=(0,E.useRef)(!1),Oe=(0,E.useCallback)(u=>{if(yt.current)return;let c=u.gateway||!Pt?u:{...u,gateway:Pt};T(c)},[T,Pt]);(0,E.useEffect)(()=>{Pe({class:"lifecycle",name:"checkout.mount"})},[Pe]);let[$t,Wt]=(0,E.useState)(e??""),Xe=e??$t,bt=n?"":Xe,[Qe,At]=(0,E.useState)(!0),[We,qt]=(0,E.useState)(null),[Et,Qt]=(0,E.useState)("full"),[Bt,En]=(0,E.useState)(!1),[an,ot]=(0,E.useState)(ee),[Dt,Ge]=(0,E.useState)(null),[Rn,ct]=(0,E.useState)(null),[Pn,Lt]=(0,E.useState)(!1),[ue,Vn]=(0,E.useState)(void 0),[_n,Tn]=(0,E.useState)(""),[xn,cr]=(0,E.useState)(!1),[x,et]=(0,E.useState)(!1),ke=(0,E.useRef)(0),[bn,qe]=(0,E.useState)("loading"),[Kn,Zn]=(0,E.useState)(0),jt=(0,E.useRef)(!1),dt=(0,E.useRef)(!1),Gt=(0,E.useRef)(!1),Vt=(0,E.useRef)(null),at=(0,E.useMemo)(()=>({checkoutMode:ve??Et,layout:pe?"unknown":Q==="buttons"?"buttons":"embedded"}),[ve,pe,Et,Q]),sn=(0,E.useRef)(g);sn.current=g;let ln=(0,E.useRef)(v);ln.current=v;let Hn=(0,E.useRef)(A);Hn.current=A,(0,E.useEffect)(()=>{xt(J)?.setCheckoutContext(at),Ze&&Ze!==J&&xt(Ze)?.setCheckoutContext(at)},[J,Ze,at]);let Cn=(0,E.useRef)(H);Cn.current=H;let en=(0,E.useCallback)(u=>{qe(u),!(u!=="exhausted"||Gt.current)&&(Gt.current=!0,ln.current?.(new fe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),cn=(0,E.useCallback)(()=>{qe("retrying"),Zn(u=>u+1)},[]);(0,E.useEffect)(()=>{qe("loading"),Zn(0),Gt.current=!1},[Xe]),(0,E.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:fe.SDK_VERSION,checkout_type:Ue,checkout_layout:ce,billing_api_url:_})},[ce,Ue,_]);let Ce=(0,E.useMemo)(()=>n?Gr(n,!0):"",[n]),Ct=(0,E.useMemo)(()=>_n===Ce?ue:void 0,[ue,_n,Ce]),it=(0,E.useMemo)(()=>n?Yo(n,Ct):void 0,[n,Ct]),tn=ve??it?.checkoutMode??"full",dn=(0,E.useMemo)(()=>it?{...it,checkoutMode:tn}:void 0,[it,tn]);(0,E.useEffect)(()=>{Vn(void 0),Tn(Ce)},[Ce]),(0,E.useEffect)(()=>{ot(ee)},[ee]);let Dn=(0,E.useCallback)((u,c,p)=>{De(()=>{Hn.current?.(Tt(u,c,p))})},[De]),un=(0,E.useCallback)(async(u,c)=>{ot(null),ct(null),Lt(!1),Ge("processing");let p=c?.sessionId??u.id,N=u.gateways?.stripe?"stripe":u.gateways?.paypal?"paypal":void 0,ne=Fe.current??mt.current,q=xt(ne),k=ne?null:xo(_,r,at),P={log:Ie=>{q?q.log(Ie):k?.log(Ie)},error:Ie=>{q?q.error(Ie):k?.error(Ie)},terminal:Ie=>{q?q.terminal(Ie):k?.terminal(Ie)},performance:Ie=>{q?q.performance(Ie):k?.performance(Ie)},now:()=>q?.now()??k?.now()??0,elapsed:Ie=>q?.elapsed(Ie)??Math.max(0,(k?.now()??Ie)-Ie)},h=P.now(),w=!!(c?.initialAutoProcessingError||c?.initialAutoProcessingPending),M=!1,le,ye=()=>{M||(M=!0,w=!0,le=P.now(),P.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Be=!1,Ke=()=>{Be||(Be=!0,P.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),P.performance({stage:"processing",durationMs:P.elapsed(h),durationMode:"machine",paymentMethodCategory:"saved"}),le!==void 0&&P.performance({stage:"recovery",durationMs:P.elapsed(le),durationMode:"machine",paymentMethodCategory:"saved"}))};P.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),yt.current=!0;try{P.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{yt.current=!1}Pe({class:"lifecycle",name:"payment.processing.started",provider:N}),w&&ye();let _t;try{let Ie=ci(c?.initialAutoProcessingError),Ee;if(Ie)ye(),Ie.type==="paypal_redirect_required"&&Vt.current?.publishableKey&&xi({sessionId:p,publishableKey:Vt.current.publishableKey,paypalPublishableKey:Vt.current.paypalPublishableKey}),Ee=await Co(Ie,{flopay:Fe.current,paypalFlopay:mt.current,attempt3DS:c?.attempt3DS,billingApiUrl:_,sessionId:p,session:u,telemetry:!1}),Ie.type==="paypal_redirect_required"&&ca();else if(c?.initialAutoProcessingPending){let He=(await new lr.PaymentAPI(_,{telemetry:!1}).waitForCheckoutSessionCompletion(c.initialAutoProcessingPending.sessionId,{initialDelayMs:c.initialAutoProcessingPending.retryAfterMs})).data.session;if(!fr(He))throw uo(He);Ee=or(He,p)}else{if(c?.initialAutoProcessingError)throw Jn(c.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:c.initialAutoProcessingError.checkoutMethod});if(c?.fromCreateSession)return c?.fallbackToFull&&(Qt("full"),Ai("full")),!1;{let z=await Cr({billingApiUrl:_,sessionId:p,session:u,telemetry:!1});z.type==="success"?Ee=z.result:(ye(),z.type==="paypal_redirect_required"&&Vt.current?.publishableKey&&xi({sessionId:p,publishableKey:Vt.current.publishableKey,paypalPublishableKey:Vt.current.paypalPublishableKey}),Ee=await Co(z,{flopay:Fe.current,paypalFlopay:mt.current,attempt3DS:c?.attempt3DS,billingApiUrl:_,sessionId:p,session:u,telemetry:!1}),z.type==="paypal_redirect_required"&&ca())}}p&&Pr(p),Ke(),w&&(P.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),P.terminal({outcome:Ee.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Lt(Ee.status==="authorized"),Ge("success"),await Yr(1200),_t=()=>sn.current?.(Ee)}catch(Ie){let Ee=sr(Ie),z=Ee.checkoutMethod??Kr;ot(Ee.message),ct(Ee.message),Lt(!1),c?.fallbackToFull&&(P.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Qt("full"),Ai("full")),Ke();let St=Ee.statusCode!==void 0?(0,fe.telemetryStatusClass)(Ee.statusCode,"unknown"):void 0,He=St==="4xx"?{requestCategory:"process_payment",statusClass:St}:{},nt=St===void 0||St==="4xx";if(nt&&(Ee.telemetryOutcome==="payment_declined"||!!(Ee.declineCode||Ee.code?.toLowerCase().includes("declin"))))P.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...He});else if(nt&&(Ee.telemetryOutcome==="validation_rejected"||Ee.type==="validation_error"))P.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...He});else{let Xr=(0,fe.classifyTelemetryFailure)(Ie,w?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),nn=Ee.telemetryRequestCategory??"process_payment";yt.current=!0;try{P.error({...Xr,...Ee.telemetryFailureCategory?{failureCategory:Ee.telemetryFailureCategory}:{},stage:w?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:nn})}finally{yt.current=!1}Pe({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:nn,provider:N})}return De(()=>ln.current?.(Ee)),Dn(z,Ee,{code:Ee.code,declineCode:Ee.declineCode}),Ge("error"),await Promise.allSettled([Yr(1500),c?.ensureProvidersReady?c.ensureProvidersReady():Promise.resolve()]),w&&(P.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ke(),k&&Wr(k),Ge(null),ct(null)}return De(_t),!0},[Dn,Pe,De,sr,_,r,at]);(0,E.useEffect)(()=>{if(typeof window>"u"||dt.current)return;let u=new URLSearchParams(window.location.search),c=u.get("payment_intent_client_secret");if(!c)return;let p=Ks();p&&(dt.current=!0,(async()=>{let N,ne=0;ot(null),ct(null),Ge("processing"),En(!0);try{if(u.get("redirect_status")==="failed")throw Object.assign(new fe.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:q,paypalFlopay:k}=await wo({publishableKey:p.publishableKey,paypalPublishableKey:p.paypalPublishableKey,billingApiUrl:_,locale:m,telemetry:r});N=xt(k??q),ne=N?.now()??0,N?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),N?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let P=(k??q)?.getRawProvider();if(!P)throw Object.assign(new fe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:h,error:w}=await P.retrievePaymentIntent(c);if(w)throw Object.assign(new fe.FloPayError(w.message??"Failed to retrieve PayPal payment status.","api_error",{code:w.code}),{checkoutMethod:"paypal"});let M=Ja(h?.status);if(!h||M==="failed")throw Object.assign(new fe.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let le=typeof h.payment_method=="string"?h.payment_method:h.payment_method?.id,ye=M;if(p.sessionId){let _t=(await new lr.PaymentAPI(_,{telemetry:!1}).getUnifiedCheckoutSession(p.sessionId)).data.session;if(_t&&_t.status!=="complete"){let Ie=await Cr({billingApiUrl:_,sessionId:p.sessionId,session:_t,telemetry:!1,tokenizedData:{id:le??h.id,type:"card",threeDSecureActionResultTokenId:h.id,isPaypal:!0}});if(Ie.type!=="success")throw Object.assign(new fe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});ye=Ie.result.status}}p.sessionId&&Pr(p.sessionId),N?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),N?.performance({stage:"redirect_resume",durationMs:N.elapsed(ne),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),N?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ge("success"),await Yr(1200),De(()=>sn.current?.({status:ye,paymentIntentId:h.id,paymentMethodId:le,checkoutMethod:"paypal"}))}catch(q){let k=sr(q),P=k.checkoutMethod??"paypal",h=!!(k.declineCode||k.code?.toLowerCase().includes("declin"));if(N)N.performance({stage:"redirect_resume",durationMs:N.elapsed(ne),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),h?N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):N.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(h){let w=xo(_,r,at);w.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Wr(w)}else sa(_,r,at,"REDIRECT_RESUME_FAILED","redirect_resume");ot(k.message),ct(k.message),De(()=>ln.current?.(k)),Dn(P,k,{code:k.code,declineCode:k.declineCode}),Ge("error"),await Yr(1500)}finally{ca(),Hs(),Ge(null),ct(null),En(!1)}})())},[Dn,De,m,sr,_,r]);let Ot=(0,E.useRef)(null),Kt=(0,E.useMemo)(()=>dn?Gr(dn):"",[dn]),Ht=(0,E.useRef)(dn);Ht.current=dn,(0,E.useEffect)(()=>{Wt(e??"")},[e]),(0,E.useEffect)(()=>{jt.current=!1,ot(ee),ct(null),Lt(!1),Ge(null)},[Kt,ee,e]);async function Yn(u,c,p){let N=xo(_,r,at),ne=new lr.PaymentAPI(_,{telemetry:!1}),q=!1;try{let k=u.idempotencyKey!==void 0?(0,fe.resolveIdempotencyKey)(u.idempotencyKey):void 0,P=Mi(c,p),h=Fi(c,p);P?.canonicalIdentity===p&&h&&h.canonicalIdentity===void 0&&(ua(c,p,h.idempotencyKey),h={...h,canonicalIdentity:p});let w=k??(h?.canonicalIdentity===p?h.idempotencyKey:void 0),M,le=!1;N.log({name:P?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let ye=P?.sid??null,Be=null,Ke;if(ye)try{Be=await ne.getUnifiedCheckoutSession(ye,P?.nonce),P&&P.canonicalIdentity===void 0&&(Gs(Be.data.session,u)?(da(c,p,ye,P.nonce??Be.data.session?.clientSecret),h&&h.canonicalIdentity===void 0&&(ua(c,p,h.idempotencyKey),w??(w=h.idempotencyKey))):(pa(c,p),h=null,w=k,ye=null,Be=null));let _t=Be?.data.session?.status;if(ye&&Be&&_t==="complete"){if(Zo(ye))return{sid:ye,result:Be};pa(c,p),ye=null,Be=null,le=!0}}catch{N.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),P?.canonicalIdentity===void 0?(pa(c,p),w=k):fa(c,p),ye=null}if(!ye){!k&&(le||!w)&&(w=(0,fe.resolveIdempotencyKey)(),M=w),w&&ua(c,p,w);let _t=N.now(),Ie=0;N.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ee={...u,idempotencyKey:w,avsCheck:!!ae,avsConfig:typeof ae=="object"?ae:void 0,checkoutType:"embedded_checkout",checkoutLayout:pe?"custom_layout":Q==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(Ee,lr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:He=>{Ie=Math.max(Ie,He)}}});let z=()=>{N.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),N.performance({stage:"session_create",durationMs:N.now()-_t,durationMode:"machine",requestCategory:"session_create",attempt:Ie,statusClass:"2xx"})},St=He=>{let nt=(0,fe.classifyTelemetryFailure)(He,"CHECKOUT_SESSION_CREATE_FAILED","unknown");N.performance({stage:"session_create",durationMs:N.now()-_t,durationMode:"machine",requestCategory:"session_create",attempt:Ie,statusClass:nt.statusClass}),He instanceof fe.FloPayError&&He.type==="validation_error"?N.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):nt.statusClass==="4xx"?N.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(N.error({...nt,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Pe({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if((0,fe.isDetachedSessionEligible)(Ee)){let He=await ne.createDetachedSession(Ee);He.claimed.catch(()=>{}),Be=He.shell,ye=He.sessionId,Ke=He.claimed.then(nt=>{let er=nt.data.session?.id??He.sessionId;return er&&da(c,p,er,nt.data.session?.clientSecret??He.nonce),z(),nt},nt=>{throw fa(c,p),St(nt),nt}).finally(()=>Wr(N)),Ke.catch(()=>{}),q=!0,N.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),N.performance({stage:"session_shell",durationMs:N.now()-_t,durationMode:"machine",requestCategory:"session_create",attempt:Ie,statusClass:"2xx",paymentMethodCategory:"card"})}else Be=await ne.createAndFetchSession(Ee),z()}catch(He){throw St(He),He}ye=Be.data.session?.id??ye??"",ye&&!Ke&&da(c,p,ye,Be.data.session?.clientSecret)}return{sid:ye??"",result:Be,sdkGeneratedIdempotencyKey:M,...Ke?{claimed:Ke}:{}}}finally{q||Wr(N)}}let Ln=(0,E.useCallback)(async(u,c)=>{let p=Ht.current;if(!p)throw new fe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let N=Yo(p,u),ne=Gr(N),q=Ws(N),k=Ao.get(ne);if(!k){let w={canonicalIdentity:ne,promise:Yn(N,q,ne),consumers:0,settled:!1};k=w,Ao.set(ne,w);let M=()=>{w.settled=!0,Ti(ne,w)};w.promise.then(M,M)}k.consumers+=1;let P=!1,h=()=>{P||(P=!0,k.consumers-=1,Ti(ne,k))};c?.(h);try{let w=await k.promise;Ot.current=ne,u&&(Tn(Ce),Vn(Ee=>Ya(Ee,u)));let{sid:M,result:le,claimed:ye}=w;if(ie(le),le.data.session&&$e(le.data.session),M&&Wt(M),ye){ke.current+=1;let Ee=ke.current;et(!0),ye.then(z=>{ke.current===Ee&&(ie(z),z.data.session&&$e(z.data.session),et(!1))},z=>{ke.current===Ee&&(et(!1),qt(z instanceof fe.FloPayError?z:new fe.FloPayError(z instanceof Error?z.message:"Failed to create session","api_error")))})}else ke.current+=1,et(!1);let{publishableKey:Be,paypalPublishableKey:Ke}=So(le),{flopay:_t,paypalFlopay:Ie}=await wo({publishableKey:Be,paypalPublishableKey:Ke,billingApiUrl:_,locale:m,telemetry:r});return Fe.current=_t,Le(_t),mt.current=Ie,se(Ie),At(!1),w}catch(w){throw Ot.current===ne&&(Ot.current=null),w}finally{c||h()}},[Ce,m,_,r,at]),An=(0,E.useRef)(un);An.current=un;let On=(0,E.useRef)(Ln);On.current=Ln;let Nt=(0,E.useCallback)(async u=>{if(!Ys(u)||xn)return{sessionId:$t,session:j};cr(!0);try{let c=await Ln(u);return{sessionId:c.sid,session:c.result.data.session??null}}finally{cr(!1)}},[Ln,xn,$t,j]);(0,E.useEffect)(()=>{let u=!1,c;if(qt(null),Kt){let ne=Ht.current;return Qt(tn),At(!1),Ot.current===Kt?()=>{u=!0}:($e(Wa(ne,ve)),(async()=>{let q=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),k=tn==="auto"&&!jt.current&&!q;k&&(ot(null),ct(null),Ge("processing"));try{let P=await On.current(void 0,le=>{c=le}),h=P.result.data.session??null;Vt.current=So(P.result);let w=la(P.result),M=Zo(P.sid||h?.id);if(!u&&k&&h&&!w&&!M){jt.current=!0,await js(Kt,P.sdkGeneratedIdempotencyKey,()=>An.current(h,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:P.result.autoProcessingError,initialAutoProcessingPending:P.result.autoProcessingPending,autoProcessingAttempted:P.result.autoProcessingAttempted,sessionId:P.sid||h.id}));return}!u&&k&&((w||M)&&(jt.current=!0),Ge(null),ct(null))}catch(P){if(u)return;let h=P instanceof fe.FloPayError||typeof P=="object"&&P!==null&&"code"in P?P.code:void 0;if(k&&h==="session_auto_completed"){jt.current=!0,Ge("success"),await Yr(1200),u||(De(()=>{sn.current?.({status:"succeeded"})}),Ge(null),ct(null));return}k&&(Ge(null),ct(null));let w=P instanceof fe.FloPayError?P:new fe.FloPayError(P instanceof Error?P.message:"Failed to create session","api_error");qt(w)}finally{c?.(),c=void 0}})(),()=>{u=!0,c?.()})}At(!0);async function p(){let ne=!1;try{let k=await new lr.PaymentAPI(_,{telemetry:!1}).getUnifiedCheckoutSession(Xe,t);if(u)return;ie(k);let P=k.data.session??null;if($e(P),!P)throw new fe.FloPayError("No session data returned","api_error");let h=P.checkoutMode;if(h==="setup")throw new fe.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(P.status==="authorized"){At(!1),De(()=>{sn.current?.(or(P,Xe)),Cn.current?.(P.successUrl??"")});return}if(P.status==="complete"){At(!1),De(()=>{Cn.current?.(P.successUrl??"")});return}if(P.status==="expired")throw co(P);ne=!0;let w=ve??h??"full";Qt(w);let M=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),le=la(k);if(w==="auto"&&!jt.current&&!M&&!le){jt.current=!0;let ye=N(k);try{if(await An.current(P,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ye,sessionId:Xe||P.id}),u)return;await ye,u||At(!1);return}catch{if(u)return;await ye,u||At(!1);return}}await N(k),u||At(!1)}catch(q){if(u)return;ne&&Pe({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),q instanceof fe.FloPayError?!ne&&!Vs(q)&&sa(_,r,at,"NETWORK_REQUEST_FAILED","session_read"):sa(_,r,at,"INTERNAL_SDK_ERROR","checkout_mount");let k=q instanceof fe.FloPayError?q:new fe.FloPayError(q instanceof Error?q.message:"Failed to initialize checkout","api_error");qt(k),At(!1)}}async function N(ne){let{publishableKey:q,paypalPublishableKey:k}=So(ne);Vt.current={publishableKey:q,paypalPublishableKey:k};let{flopay:P,paypalFlopay:h}=await wo({publishableKey:q,paypalPublishableKey:k,billingApiUrl:_,locale:m,telemetry:r});Fe.current=P,Le(P),mt.current=h,se(h)}return p(),()=>{u=!0}},[ve,Kt,tn,bt,De,t]);let tt=(0,E.useCallback)(async()=>{if(!(Bt||!j)){En(!0),ot(null);try{await un(j,{attempt3DS:!0,fallbackToFull:!0,sessionId:Xe||j.id})}finally{En(!1)}}},[Xe,Bt,un,j]),pn=ya(F),zt=la(F),ut=(0,E.useMemo)(()=>{if(!(!F||!j||!F.data.stripe?.publishableKey))return{billingApiUrl:_}},[F,j,_]),Jt=!!(n&&!pe&&Q==="buttons"&&O&&tn==="full"),Rt=(0,E.useMemo)(()=>({session:j,loading:Qe,error:We,checkoutMode:Et,inlineSessionDraft:dn,applyInlineSessionPatch:Jt?Nt:void 0,inlineSessionPatchProcessing:xn,claimPending:x}),[j,Qe,We,Et,dn,Jt,Nt,xn,x]),Qn=!!n&&Q==="buttons"&&!zt&&(!J||!ut),pt=Dt?(0,I.jsx)(hn,{status:Dt,errorMessage:Rn,authorized:Pn}):null;if(Qe){if(d)return(0,I.jsxs)(I.Fragment,{children:[d,pt]});if(Q==="buttons"){let u=me?.buttonsLayout?.cardButton?.borderRadius??me?.appearance.variables?.borderRadius??8,c=p=>(0,I.jsx)("div",{style:{height:p,borderRadius:u,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[C&&c(kr),te&&(S||ge)&&c(kr),te&&c(kr),(0,I.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),pt]})}return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,I.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,I.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),pt]})}return We?R?(0,I.jsx)(wn.Provider,{value:Rt,children:R(We)}):(0,I.jsx)(wn.Provider,{value:Rt,children:(0,I.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:We.message})}):Qn?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(wn.Provider,{value:Rt,children:(0,I.jsx)(Xs,{onButtonClick:K,showPayPal:C,showStripe:te,showApplePay:S,showGooglePay:ge,theme:re,buttonsTheme:be,buttonsStyles:oe,cardButtonContent:he,cardBackButtonContent:Ne,cardTitleContent:_e})}),pt]}):zt&&j&&pn?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(wn.Provider,{value:Rt,children:(0,I.jsxs)("div",{className:$,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[an&&(0,I.jsx)(vr,{icon:!1,children:an}),bn==="retrying"&&(0,I.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),bn==="exhausted"&&(0,I.jsxs)("div",{role:"alert",children:[(0,I.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,I.jsx)("button",{type:"button",onClick:cn,children:"Retry PayPal"})]}),bn!=="exhausted"&&(0,I.jsx)("div",{"aria-hidden":bn==="retrying"?!0:void 0,style:bn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,I.jsx)(ii,{sessionId:Xe,nonce:j.clientSecret||void 0,billingApiUrl:_,email:j.customer?.email,clientId:pn.clientId,environment:pn.environment,currency:(j.currency??"usd").toUpperCase(),isSubscription:j.mode==="subscription",providerObjectType:pn.providerObjectType,onComplete:g,onErrorChange:ot,onDecline:A,onButtonClick:K,onInitializationStateChange:en,allowAutomaticRetry:Kn===0,session:j,telemetry:r,telemetryContext:at,onInstrument:Oe,debug:U},`${Y}:paypal-init-${Kn}`)})]})}),pt]}):!J||!ut?(0,I.jsx)(I.Fragment,{children:pt}):Et==="confirm"?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(wn.Provider,{value:Rt,children:(0,I.jsx)(jr,{flopay:J,paypalFlopay:Ze,options:ut,onInstrument:Oe,children:(0,I.jsxs)("div",{className:$,children:[an&&(0,I.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:an}),Re?Re({onConfirm:tt,isProcessing:Bt}):(0,I.jsx)("button",{type:"button",onClick:tt,disabled:Bt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Bt?"not-allowed":"pointer",opacity:Bt?.6:1},children:Bt?"Processing...":Z??"Confirm Purchase"})]})},Y)}),pt]}):(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(wn.Provider,{value:Rt,children:(0,I.jsx)(jr,{flopay:J,paypalFlopay:Ze,options:ut,onInstrument:Oe,children:pe?(0,I.jsxs)(I.Fragment,{children:[an&&(0,I.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:an}),(0,I.jsx)(Js,{sessionId:Xe,nonce:j?.clientSecret||void 0,billingApiUrl:_,session:j,children:pe})]}):(0,I.jsx)(_o,{sessionId:Xe,nonce:j?.clientSecret||void 0,email:j?.customer?.email,userId:j?.customer?.id,firstName:j?.customer?.firstName,lastName:j?.customer?.lastName,totalAmount:j?Math.round((0,fe.buildCheckoutDisplayData)(j).total*100):0,currency:j?.currency?.toLowerCase()??"usd",onComplete:g,onError:v,onDecline:A,error:an,onErrorChange:ot,showPayPal:C,showStripe:te,enabledPaymentMethods:G??F?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:F?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:ge,layout:Q,theme:re,buttonsTheme:be,buttonsStyles:oe,appearance:Ye,cardButtonContent:he,cardBackButtonContent:Ne,cardTitleContent:_e,onButtonClick:K,onBeforeButtonClick:O,enableAVS:ae,...ze?{cardFieldOrder:ze}:{},...Te?{cardPreFormSlot:Te}:{},avsLayout:X,country:j?.customer?.country,city:j?.customer?.city,state:j?.customer?.state,onCountryChange:D,onZipChange:y,avsCheck:!!ae,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:pe?"custom_layout":Q==="buttons"?"buttons_layout":"default_layout",className:$,directPaypal:ya(F),isSubscription:j?.mode==="subscription",session:j,dataAttachmentPending:x,debug:U})},Y)}),pt]})}function Js({sessionId:e,nonce:t,billingApiUrl:n,session:o,children:r}){return(0,I.jsx)(I.Fragment,{children:E.default.Children.map(r,i=>{if(!E.default.isValidElement(i))return i;let m=i.props,d={};return m.sessionId||(d.sessionId=e),!m.nonce&&t&&(d.nonce=t),m.billingApiUrl||(d.billingApiUrl=n),o?.customer&&(m.email||(d.email=o.customer.email),m.userId||(d.userId=o.customer.id),m.firstName||(d.firstName=o.customer.firstName),m.lastName||(d.lastName=o.customer.lastName)),Object.keys(d).length===0?i:E.default.cloneElement(i,d)})})}function Xs({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:o,showGooglePay:r,theme:i,buttonsTheme:m,buttonsStyles:d,cardButtonContent:R,cardBackButtonContent:g,cardTitleContent:v}){let[b,A]=(0,E.useState)(!1),D=(0,E.useMemo)(()=>(0,fe.resolveTheme)(i),[i]),y=(0,E.useMemo)(()=>{let S=D?.buttonsLayout??(0,fe.resolveButtonsLayoutTheme)(m);return d?{...S,...d,cardButton:{...S.cardButton,...d.cardButton},cardFormContainer:{...S.cardFormContainer,...d.cardFormContainer},backButton:{...S.backButton,...d.backButton},backButtonIcon:{...S.backButtonIcon,...d.backButtonIcon},submitButton:{...S.submitButton,...d.submitButton},title:{...S.title,...d.title}}:S},[D,m,d]),C=D?.buttonsLayout?.cardButton?.borderRadius??D?.appearance.variables?.borderRadius??8,te=S=>(0,I.jsx)("div",{style:{height:S,borderRadius:C,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),G=R===void 0?{boxSizing:"border-box",height:kr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let S=y.cardInputBorder??"#e5e7eb",ge=y.cardInputBackground??"white",U=ur(g),Q=ur(v);return(0,I.jsxs)("div",{style:{backgroundColor:y.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...y.cardFormContainer},children:[(0,I.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,I.jsxs)("button",{type:"button",onClick:()=>A(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:U?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...y.backButton},children:[(0,I.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...y.backButtonIcon},children:(0,I.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,I.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,I.jsx)(mr,{content:g})]}),Q?(0,I.jsx)("div",{style:{flex:1}}):(0,I.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...y.title},children:(0,I.jsx)(Or,{content:v})})]}),(0,I.jsx)("div",{style:{backgroundColor:ge,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsxs)("div",{style:{display:"flex"},children:[(0,I.jsx)("div",{style:{flex:1,backgroundColor:ge,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsx)("div",{style:{flex:1,backgroundColor:ge,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,I.jsx)("div",{style:{backgroundColor:ge,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...y.submitButton,opacity:.5}}),(0,I.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,R.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&H(xr),n&&(r||o)&&H(xr),n&&(0,R.jsx)("button",{type:"button",onClick:()=>{e?.("card"),w(!0)},style:{width:"100%",...M,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:y.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,...y.cardButton},onMouseDown:f=>{f.currentTarget.style.transform="scale(0.985)"},onMouseUp:f=>{f.currentTarget.style.transform="scale(1)"},children:(0,R.jsx)(gr,{content:I})}),(0,R.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Rn=require("react/jsx-runtime"),ul=44;function zi(e){return new Promise(t=>setTimeout(t,e))}function pl(e,t){return e instanceof an.FloPayError?e:new an.FloPayError(e instanceof Error?e.message:t,"api_error")}function ml(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function yl(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 Ui({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:p,items:d,subscriptions:I,account:g,successUrl:h,cancelUrl:k,couponCodes:w,tagsData:x,utmMetadata:y,billingApiUrl:v,locale:H,theme:M,appearance:f,buttonsTheme:ie,buttonsStyles:O,onSuccess:Z,onError:Q,onDecline:ve,children:B,disabled:se=!1,type:xe="button",style:Se,...he}){let $=(0,De.useMemo)(()=>(0,an.resolveBillingApiUrl)(v),[v]),N=(0,De.useMemo)(()=>yl({createSession:n,clientId:a,products:p,items:d,subscriptions:I,account:g,successUrl:h,cancelUrl:k,couponCodes:w,tagsData:x,utmMetadata:y}),[g,k,a,w,n,p,d,I,h,x,y]),[oe,Me]=(0,De.useState)(!1),[Te,te]=(0,De.useState)(null),[K,re]=(0,De.useState)(null),[ye,be]=(0,De.useState)(!1),[ne,_e]=(0,De.useState)(null),G=(0,De.useRef)(!0),T=(0,De.useRef)(null),fe=(0,De.useRef)(ne),$e=(0,De.useRef)(Z),qe=(0,De.useRef)(Q),ue=(0,De.useRef)(ve);(0,De.useEffect)(()=>{fe.current=ne},[ne]),(0,De.useEffect)(()=>{$e.current=Z},[Z]),(0,De.useEffect)(()=>{qe.current=Q},[Q]),(0,De.useEffect)(()=>{ue.current=ve},[ve]),(0,De.useEffect)(()=>(G.current=!0,()=>{G.current=!1,T.current?.abort()}),[]),(0,De.useEffect)(()=>{if(typeof window>"u")return;let A=Ce=>{Ce.key==="Escape"&&_e(null)};return window.addEventListener("keydown",A),()=>{window.removeEventListener("keydown",A)}},[]);let L=(0,De.useCallback)((A,Ce=Gr)=>{ue.current?.(Mt(Ce,A,{code:A.code,declineCode:A.declineCode}))},[]),le=(0,De.useCallback)(async A=>{G.current&&(re(null),be(A.result.status==="authorized"),te("success"),await zi(1200),G.current&&$e.current?.(A))},[]),ee=(0,De.useCallback)(async(A,Ce)=>{G.current&&(qe.current?.(A),Ce?.emitDecline&&L(A,Ce.method),re(A.message),be(!1),te("error"),await zi(1500))},[L]),ze=(0,De.useCallback)(async(A,Ce,gt)=>{let Ue=A.data.session??null;if(!Ue)throw new an.FloPayError("No session data returned","api_error");let qt=Ue.clientSecret||t;if(vr(Ue)){await le({result:sr(Ue,Ce),session:Ue,sessionId:Ue.id||Ce,autoCompleted:!1});return}if(Ue.status==="expired")throw yo(Ue);try{if(A.autoProcessingPending){let et=(await new zo.PaymentAPI($).waitForCheckoutSessionCompletion(A.autoProcessingPending.sessionId,{initialDelayMs:A.autoProcessingPending.retryAfterMs})).data.session;if(!vr(et))throw fo(et);await le({result:sr(et,Ce),session:et,sessionId:et.id||Ce,autoCompleted:!1});return}if(A.autoProcessingError){if(A.autoProcessingError.type==="3ds_required"&&A.autoProcessingError.nextActionRedirectUrl&&Ce&&qt){let Ze=new AbortController;T.current=Ze;let St;try{St=await fi({billingApiUrl:$,sessionId:Ce,nonce:qt,nextActionRedirectUrl:A.autoProcessingError.nextActionRedirectUrl,signal:Ze.signal})}finally{T.current===Ze&&(T.current=null)}if(St.status==="declined")throw Qn({type:St.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:St.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:A.autoProcessingError.checkoutMethod});let Ge=(await new zo.PaymentAPI($).waitForCheckoutSessionCompletion(Ce,{initialDelayMs:0,nonce:qt})).data.session;if(!vr(Ge))throw Qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:A.autoProcessingError.checkoutMethod});await le({result:sr(Ge,Ce),session:Ge,sessionId:Ge.id||Ce,autoCompleted:!1});return}throw Qn(A.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:A.autoProcessingError.checkoutMethod})}if(gt?.fromCreateSession&&A.autoProcessingAttempted===!0)throw Qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Jt=await Er({billingApiUrl:$,sessionId:Ce??Ue.id,session:Ue,nonce:qt});if(Jt.type!=="success")throw Qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await le({result:Jt.result,session:Ue,sessionId:Ue.id||Ce,autoCompleted:!1})}catch(Jt){let Ze=dr(Jt),St=Ue.id||Ce;await ee(Ze,{emitDecline:!0,method:Ze.checkoutMethod??Gr}),ml(Ze,St)&&St&&G.current&&_e({sessionId:St,errorMessage:Ze.message,nonce:qt||void 0})}},[t,$,ee,le]),Le=(0,De.useCallback)(async A=>{if(he.onClick?.(A),!(A.defaultPrevented||se||oe)){if(_e(null),e&&N){let Ce=new an.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await ee(Ce),G.current&&(te(null),re(null));return}if(!e&&!N){let Ce=new an.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await ee(Ce),G.current&&(te(null),re(null));return}Me(!0),re(null),be(!1),te("processing");try{let Ce=new zo.PaymentAPI($);if(e){let gt=await Ce.getUnifiedCheckoutSession(e,t);await ze(gt,e);return}try{let gt=await Ce.createAndFetchSession({...N});await ze(gt,gt.data.session?.id??null,{fromCreateSession:!0})}catch(gt){if(gt instanceof an.FloPayError&>.code==="session_auto_completed"){await le({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw gt}}catch(Ce){await ee(pl(Ce,"Automatic payment failed. Please try again."))}finally{G.current&&(te(null),re(null),Me(!1))}}},[he,N,se,oe,t,ze,$,e,ee,le]),Qe=(0,De.useCallback)(A=>{let Ce=fe.current;_e(null),$e.current?.({result:A,session:null,sessionId:Ce?.sessionId??null,autoCompleted:!1})},[]),ce=(0,De.useCallback)(A=>{qe.current?.(A)},[]),ft=(0,De.useCallback)(A=>{ue.current?.(A)},[]),V=(0,De.useMemo)(()=>(0,an.resolveTheme)(M),[M]),je=(0,De.useMemo)(()=>{let A=V?.buttonsLayout??(0,an.resolveButtonsLayoutTheme)(ie);return O?{...A,...O,cardButton:{...A.cardButton,...O.cardButton}}:A},[V,ie,O]),bt=(0,De.useMemo)(()=>{let A=V?.appearance;return f?A?{...A,...f,variables:{...A.variables,...f.variables}}:f:A},[f,V]),J=bt?.variables,Ct=J?.colorPrimary??"#4A49FF",He=J?.colorPrimaryHover??_r(Ct,.12),en=J?.borderRadius??"8px";return(0,Rn.jsxs)(Rn.Fragment,{children:[(0,Rn.jsx)("button",{...he,type:xe,onClick:Le,disabled:se||oe,"aria-busy":oe,style:{width:"100%",...B===void 0?{boxSizing:"border-box",height:ul,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...je.cardButton,...pa({themeBundle:V,resolvedPrimaryColor:Ct,resolvedBorderRadius:en,submitButtonStyle:je.submitButton,explicitPrimaryColor:J?.colorPrimary}),fontSize:je.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:se||oe?"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:se||oe?.6:1,...Se},onMouseEnter:A=>{he.onMouseEnter?.(A),!A.defaultPrevented&&!se&&!oe&&(V||J?.colorPrimary)&&(A.currentTarget.style.backgroundColor=He)},onMouseLeave:A=>{he.onMouseLeave?.(A),!A.defaultPrevented&&(V||J?.colorPrimary)&&(A.currentTarget.style.backgroundColor=Ct)},onMouseDown:A=>{he.onMouseDown?.(A),A.defaultPrevented||(A.currentTarget.style.transform="scale(0.985)")},onMouseUp:A=>{he.onMouseUp?.(A),A.defaultPrevented||(A.currentTarget.style.transform="scale(1)")},children:(0,Rn.jsx)(gr,{content:B})}),Te&&(0,Rn.jsx)(Pn,{status:Te,errorMessage:K,authorized:ye}),ne&&(0,Rn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:A=>{A.target===A.currentTarget&&_e(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,Rn.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,Rn.jsx)(No,{sessionId:ne.sessionId,nonce:ne.nonce,checkoutMode:"full",billingApiUrl:$,locale:H,theme:M,...bt?{appearance:bt}:{},buttonsTheme:ie,buttonsStyles:O,initialErrorMessage:ne.errorMessage,cardTitleContent:null,onComplete:Qe,onError:ce,onDecline:ft})})})]})}var pr=require("react");var Vi=require("react/jsx-runtime");function $i(e,t){function n({className:r,id:o,style:a,options:p,onChange:d,onReady:I,onFocus:g,onBlur:h,onEscape:k}){let w=(0,pr.useRef)(null),x=(0,pr.useRef)(null),{elements:y,reportInteractive:v}=(0,pr.useContext)(Wt);return(0,pr.useEffect)(()=>{if(!y||!w.current)return;let H=!0;return(async()=>{let M=y.getElement(e);M||(M=await y.create(e,p)),!(!H||!w.current)&&(M.mount(w.current),x.current=M,d&&M.on("change",d),M.on("ready",()=>{v?.(),I?.()}),g&&M.on("focus",g),h&&M.on("blur",h),k&&M.on("escape",k))})(),()=>{if(H=!1,x.current){try{x.current.unmount()}catch{}x.current=null}}},[y,v]),(0,Vi.jsx)("div",{ref:w,className:r,id:o,style:a})}return n.displayName=t,n}var qi=$i("payment","PaymentElement"),ji=$i("address","AddressElement");var Uo=require("@flopay/js/card-setup"),sn=require("@flopay/shared"),ot=require("react");var Nn=require("react/jsx-runtime"),eo=class extends sn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Ki(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 eo(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 Hi({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:p=null,onReady:d,onComplete:I,onDecline:g,onCancel:h,onValidation:k,onError:w}){let[x,y]=(0,ot.useState)(null),[v,H]=(0,ot.useState)(null),[M,f]=(0,ot.useState)(null),[ie,O]=(0,ot.useState)(null),[Z,Q]=(0,ot.useState)(null),ve=(0,ot.useRef)(!1),B=(0,ot.useRef)(!1),se=(0,ot.useMemo)(()=>{if(typeof o=="object")return o;let K=(0,sn.resolveTheme)(o);if(K)return To({appearance:K.appearance,buttonsStyles:K.buttonsLayout,layout:"default"})},[o]),xe=(0,ot.useRef)(d),Se=(0,ot.useRef)(w),he=(0,ot.useRef)(I),$=(0,ot.useRef)(g),N=(0,ot.useRef)(h),oe=(0,ot.useRef)(k),Me=(0,ot.useRef)(!1),Te=(0,ot.useRef)(!1),te=(0,ot.useRef)(0);return xe.current=d,Se.current=w,he.current=I,$.current=g,N.current=h,oe.current=k,(0,ot.useEffect)(()=>{let K=te.current+1;return te.current=K,()=>{queueMicrotask(()=>{te.current===K&&(Me.current||Te.current||(Te.current=!0,Ne(()=>{N.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,ot.useEffect)(()=>{let K=!0,re=new Uo.PaymentAPI((0,sn.resolveBillingApiUrl)(n),{telemetry:r});return y(null),H(null),f(null),Me.current=!1,Te.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 ye=await re.getUnifiedCheckoutSession(e,t);if(!K)return;let be=ye.data.session;if(!be||!(0,sn.isCardSetupCheckoutSession)(be))throw new sn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let ne=be.vault;if(ne?.html?.trim()||(ne=await re.getVaultCapture(e,t)),!ne.html?.trim())throw new sn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!K)return;H(ne),y(new Uo.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(ye){if(!K)return;let be=Ki(ye);Me.current=!0,f(be),Ne(()=>Se.current?.(be))}})(),()=>{K=!1,re.destroy()}},[n,t,e,r]),(0,ot.useEffect)(()=>{if(!x)return;let K=!1;B.current=!1,ve.current=!1;let re=x.on("submitting",()=>{ve.current=!0,Q(null),O("processing")}),ye=x.on("complete",ne=>{Me.current=!0,ve.current=!1,O("success"),(async()=>(await new Promise(_e=>setTimeout(_e,1200)),!B.current&&(B.current=!0,Ne(()=>{he.current?.({status:"succeeded",sessionId:e,...ne.paymentMethod?{paymentMethod:ne.paymentMethod}:{}})}),K||O(null))))()}),be=x.on("decline",ne=>{Me.current=!0,ve.current=!1,Q(ne.message??null),O("error"),Ne(()=>{$.current?.({status:"declined",sessionId:e,...ne.declineReason?{reason:ne.declineReason}:{},...ne.message?{message:ne.message}:{}})}),(async()=>(await new Promise(_e=>setTimeout(_e,1500)),K||O(null)))()});return()=>{K=!0,re(),ye(),be()}},[x,e]),M?(0,Nn.jsx)("div",{role:"alert",children:M.message}):!x||!v?.html?(0,Nn.jsx)(Nn.Fragment,{children:p}):(0,Nn.jsxs)(Nn.Fragment,{children:[ie&&(0,Nn.jsx)(Pn,{status:ie,errorMessage:Z,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,Nn.jsx)(Rr,{capture:x,html:v.html,messageToken:v.messageToken,expectedOrigin:v.expectedOrigin,theme:se,containerStyle:a,onReady:()=>{Ne(()=>xe.current?.())},onValidation:K=>{Ne(()=>oe.current?.(K))},onError:K=>{if(!K)return;ve.current&&(ve.current=!1,Q(K),O("error"),setTimeout(()=>O(null),1500));let re=Ki(new Error(K),{code:"card_setup_widget_failed",retryable:!0});Ne(()=>Se.current?.(re))}})]})}var Yi=require("@flopay/js"),Wi=require("@flopay/shared"),xn=require("react");var _n=require("react/jsx-runtime");function Gi({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,firstName:a,lastName:p,chv:d,onTokenizedBody:I,onComplete:g,onErrorChange:h,isProcessing:k=!1}){let w=In(),x=Po(),y=vo(),[v,H]=(0,xn.useState)(!1),[M,f]=(0,xn.useState)(!1),ie=(0,xn.useRef)(!1),O=(n||y).replace(/\/+$/,""),Z=(0,xn.useCallback)(async B=>{try{let xe=await new Yi.PaymentAPI(O).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:B,accountData:{userId:o??"",email:r??"",firstName:a??"",lastName:p??""},chv:d});if(xe.ok){g?.();return}let Se=await xe.json().catch(()=>null);h?.(Se?.message??"Payment failed. Please try again.")}catch(se){h?.(se instanceof Error?se.message:"An unexpected error occurred")}},[O,e,t,o,r,a,p,d,g,h]),Q=(0,xn.useCallback)(B=>{I?I(B):Z(B)},[I,Z]);(0,xn.useEffect)(()=>{if(!w||ie.current)return;let B=new URLSearchParams(window.location.search),se=B.get("payment_intent"),xe=B.get("payment_intent_client_secret"),Se=B.get("redirect_status");!se||!xe||(ie.current=!0,(async()=>{try{if(f(!0),Se==="failed"){h?.("PayPal payment was declined. Please try again.");return}let he=w.getRawProvider();if(!he?.retrievePaymentIntent){h?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:$,error:N}=await he.retrievePaymentIntent(xe);if(N){h?.(N.message??"Failed to retrieve PayPal payment status.");return}if($&&($.status==="requires_capture"||$.status==="succeeded")){let oe=typeof $.payment_method=="string"?$.payment_method:$.payment_method?.id;Q({id:oe??$.id,type:"card",threeDSecureActionResultTokenId:$.id,isPaypal:!0});let Me=new URL(window.location.href);Me.searchParams.delete("payment_intent"),Me.searchParams.delete("payment_intent_client_secret"),Me.searchParams.delete("redirect_status"),window.history.replaceState({},"",Me.toString())}else h?.("PayPal payment was not completed. Please try again.")}catch(he){h?.(he instanceof Error?he.message:"Failed to complete PayPal payment.")}finally{f(!1)}})())},[w,Q,h]);let ve=(0,xn.useCallback)(async()=>{if(!(!w||!x))try{if(f(!0),h?.(null),!e||!r)throw new Wi.FloPayError("Missing sessionId or email for PayPal payment","validation_error");let B=await w.confirmPayPalPayment({billingApiUrl:O,sessionId:e,nonce:t,email:r,returnUrl:window.location.href});if(B.error){h?.(B.error.message);return}B.paymentIntentId&&(B.status==="succeeded"||B.status==="processing"||B.status==="requires_capture")&&Q({id:B.paymentMethodId??B.paymentIntentId,type:"card",threeDSecureActionResultTokenId:B.paymentIntentId,isPaypal:!0})}catch(B){h?.(B instanceof Error?B.message:"PayPal payment failed. Please try again.")}finally{f(!1)}},[w,x,e,t,r,O,Q,h]);return!w||!x?(0,_n.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):(0,_n.jsxs)(_n.Fragment,{children:[!v&&(0,_n.jsx)("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),(0,_n.jsx)("div",{style:v?{}:{display:"none"},children:(0,_n.jsx)("button",{type:"button",onClick:ve,disabled:M||k,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:M||k?"not-allowed":"pointer",opacity:M||k?.6:1},ref:()=>H(!0),children:M?"Processing...":"PayPal"})}),(M||k)&&(0,_n.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:(0,_n.jsx)("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}0&&(module.exports={AddressElement,DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,PayPalButton,PaymentElement,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useElements,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}return(0,I.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&te(kr),n&&(o||r)&&te(kr),n&&(0,I.jsx)("button",{type:"button",onClick:()=>{e?.("card"),A(!0)},style:{width:"100%",...G,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:y.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,...y.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:(0,I.jsx)(pr,{content:R})}),(0,I.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var In=require("react/jsx-runtime"),Zs=44;function Bi(e){return new Promise(t=>setTimeout(t,e))}function Qs(e,t){return e instanceof rn.FloPayError?e:new rn.FloPayError(e instanceof Error?e.message:t,"api_error")}function el(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function tl(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 Di({sessionId:e,nonce:t,createSession:n,paymentMethodId:o,checkoutMethod:r,clientId:i,products:m,items:d,subscriptions:R,account:g,successUrl:v,cancelUrl:b,couponCodes:A,tagsData:D,utmMetadata:y,billingApiUrl:C,locale:te,theme:G,appearance:S,buttonsTheme:ge,buttonsStyles:U,onSuccess:Q,onError:re,onDecline:be,children:oe,disabled:he=!1,type:Ne="button",style:_e,...Se}){let K=(0,Me.useMemo)(()=>(0,rn.resolveBillingApiUrl)(C),[C]),O=(0,Me.useMemo)(()=>tl({createSession:n,clientId:i,products:m,items:d,subscriptions:R,account:g,successUrl:v,cancelUrl:b,couponCodes:A,tagsData:D,utmMetadata:y}),[g,b,i,A,n,m,d,R,v,D,y]),[ae,ze]=(0,Me.useState)(!1),[Te,X]=(0,Me.useState)(null),[$,ee]=(0,Me.useState)(null),[pe,ve]=(0,Me.useState)(!1),[Z,Re]=(0,Me.useState)(null),H=(0,Me.useRef)(!0),_=(0,Me.useRef)(null),me=(0,Me.useRef)(Z),Ye=(0,Me.useRef)(Q),Ue=(0,Me.useRef)(re),ce=(0,Me.useRef)(be);(0,Me.useEffect)(()=>{me.current=Z},[Z]),(0,Me.useEffect)(()=>{Ye.current=Q},[Q]),(0,Me.useEffect)(()=>{Ue.current=re},[re]),(0,Me.useEffect)(()=>{ce.current=be},[be]),(0,Me.useEffect)(()=>(H.current=!0,()=>{H.current=!1,_.current?.abort()}),[]),(0,Me.useEffect)(()=>{if(typeof window>"u")return;let T=Pe=>{Pe.key==="Escape"&&Re(null)};return window.addEventListener("keydown",T),()=>{window.removeEventListener("keydown",T)}},[]);let F=(0,Me.useCallback)((T,Pe=Kr)=>{ce.current?.(Tt(Pe,T,{code:T.code,declineCode:T.declineCode}))},[]),ie=(0,Me.useCallback)(async T=>{H.current&&(ee(null),ve(T.result.status==="authorized"),X("success"),await Bi(1200),H.current&&Ye.current?.(T))},[]),J=(0,Me.useCallback)(async(T,Pe)=>{H.current&&(Ue.current?.(T),Pe?.emitDecline&&F(T,Pe.method),ee(T.message),ve(!1),X("error"),await Bi(1500))},[F]),Le=(0,Me.useCallback)(async(T,Pe,yt)=>{let Oe=T.data.session??null;if(!Oe)throw new rn.FloPayError("No session data returned","api_error");let $t=Oe.clientSecret||t;if(fr(Oe)){await ie({result:or(Oe,Pe),session:Oe,sessionId:Oe.id||Pe,autoCompleted:!1});return}if(Oe.status==="expired")throw co(Oe);try{if(T.autoProcessingPending){let Qe=(await new Fo.PaymentAPI(K).waitForCheckoutSessionCompletion(T.autoProcessingPending.sessionId,{initialDelayMs:T.autoProcessingPending.retryAfterMs})).data.session;if(!fr(Qe))throw uo(Qe);await ie({result:or(Qe,Pe),session:Qe,sessionId:Qe.id||Pe,autoCompleted:!1});return}if(T.autoProcessingError){if(T.autoProcessingError.type==="3ds_required"&&T.autoProcessingError.nextActionRedirectUrl&&Pe&&$t){let Xe=new AbortController;_.current=Xe;let bt;try{bt=await di({billingApiUrl:K,sessionId:Pe,nonce:$t,nextActionRedirectUrl:T.autoProcessingError.nextActionRedirectUrl,signal:Xe.signal})}finally{_.current===Xe&&(_.current=null)}if(bt.status==="declined")throw Jn({type:bt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:bt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:T.autoProcessingError.checkoutMethod});let We=(await new Fo.PaymentAPI(K).waitForCheckoutSessionCompletion(Pe,{initialDelayMs:0,nonce:$t})).data.session;if(!fr(We))throw Jn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:T.autoProcessingError.checkoutMethod});await ie({result:or(We,Pe),session:We,sessionId:We.id||Pe,autoCompleted:!1});return}throw Jn(T.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:T.autoProcessingError.checkoutMethod})}if(yt?.fromCreateSession&&T.autoProcessingAttempted===!0)throw Jn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Wt=await Cr({billingApiUrl:K,sessionId:Pe??Oe.id,session:Oe,nonce:$t});if(Wt.type!=="success")throw Jn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await ie({result:Wt.result,session:Oe,sessionId:Oe.id||Pe,autoCompleted:!1})}catch(Wt){let Xe=sr(Wt),bt=Oe.id||Pe;await J(Xe,{emitDecline:!0,method:Xe.checkoutMethod??Kr}),el(Xe,bt)&&bt&&H.current&&Re({sessionId:bt,errorMessage:Xe.message,nonce:$t||void 0})}},[t,K,J,ie]),Fe=(0,Me.useCallback)(async T=>{if(Se.onClick?.(T),!(T.defaultPrevented||he||ae)){if(Re(null),e&&O){let Pe=new rn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await J(Pe),H.current&&(X(null),ee(null));return}if(!e&&!O){let Pe=new rn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await J(Pe),H.current&&(X(null),ee(null));return}ze(!0),ee(null),ve(!1),X("processing");try{let Pe=new Fo.PaymentAPI(K);if(e){let yt=await Pe.getUnifiedCheckoutSession(e,t);await Le(yt,e);return}try{let yt=await Pe.createAndFetchSession({...O});await Le(yt,yt.data.session?.id??null,{fromCreateSession:!0})}catch(yt){if(yt instanceof rn.FloPayError&&yt.code==="session_auto_completed"){await ie({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw yt}}catch(Pe){await J(Qs(Pe,"Automatic payment failed. Please try again."))}finally{H.current&&(X(null),ee(null),ze(!1))}}},[Se,O,he,ae,t,Le,K,e,J,ie]),Ze=(0,Me.useCallback)(T=>{let Pe=me.current;Re(null),Ye.current?.({result:T,session:null,sessionId:Pe?.sessionId??null,autoCompleted:!1})},[]),se=(0,Me.useCallback)(T=>{Ue.current?.(T)},[]),mt=(0,Me.useCallback)(T=>{ce.current?.(T)},[]),j=(0,Me.useMemo)(()=>(0,rn.resolveTheme)(G),[G]),$e=(0,Me.useMemo)(()=>{let T=j?.buttonsLayout??(0,rn.resolveButtonsLayoutTheme)(ge);return U?{...T,...U,cardButton:{...T.cardButton,...U.cardButton}}:T},[j,ge,U]),vt=(0,Me.useMemo)(()=>{let T=j?.appearance;return S?T?{...T,...S,variables:{...T.variables,...S.variables}}:S:T},[S,j]),Y=vt?.variables,Pt=Y?.colorPrimary??"#4A49FF",Ve=Y?.colorPrimaryHover??wr(Pt,.12),Zt=Y?.borderRadius??"8px";return(0,In.jsxs)(In.Fragment,{children:[(0,In.jsx)("button",{...Se,type:Ne,onClick:Fe,disabled:he||ae,"aria-busy":ae,style:{width:"100%",...oe===void 0?{boxSizing:"border-box",height:Zs,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...$e.cardButton,...ia({themeBundle:j,resolvedPrimaryColor:Pt,resolvedBorderRadius:Zt,submitButtonStyle:$e.submitButton,explicitPrimaryColor:Y?.colorPrimary}),fontSize:$e.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:he||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:he||ae?.6:1,..._e},onMouseEnter:T=>{Se.onMouseEnter?.(T),!T.defaultPrevented&&!he&&!ae&&(j||Y?.colorPrimary)&&(T.currentTarget.style.backgroundColor=Ve)},onMouseLeave:T=>{Se.onMouseLeave?.(T),!T.defaultPrevented&&(j||Y?.colorPrimary)&&(T.currentTarget.style.backgroundColor=Pt)},onMouseDown:T=>{Se.onMouseDown?.(T),T.defaultPrevented||(T.currentTarget.style.transform="scale(0.985)")},onMouseUp:T=>{Se.onMouseUp?.(T),T.defaultPrevented||(T.currentTarget.style.transform="scale(1)")},children:(0,In.jsx)(pr,{content:oe})}),Te&&(0,In.jsx)(hn,{status:Te,errorMessage:$,authorized:pe}),Z&&(0,In.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:T=>{T.target===T.currentTarget&&Re(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,In.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,In.jsx)(Mo,{sessionId:Z.sessionId,nonce:Z.nonce,checkoutMode:"full",billingApiUrl:K,locale:te,theme:G,...vt?{appearance:vt}:{},buttonsTheme:ge,buttonsStyles:U,initialErrorMessage:Z.errorMessage,cardTitleContent:null,onComplete:Ze,onError:se,onDecline:mt})})})]})}var Bo=require("@flopay/js/card-setup"),on=require("@flopay/shared"),rt=require("react");var Bn=require("react/jsx-runtime"),Jr=class extends on.FloPayError{constructor(t,n,o){super(t,n,o),this.name="FloPayCardSetupError",this.retryable=o.retryable}};function Li(e,t={}){let n=e instanceof on.FloPayError?e:void 0,o=n?.statusCode,r=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof o=="number"&&o>=500||n?.code==="vault_capture_timeout"||!n);return new Jr(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:r,...n?.param?{param:n.param}:{},...o!==void 0?{statusCode:o}:{}})}function Oi({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,theme:r="modern-light",containerStyle:i,loading:m=null,onReady:d,onComplete:R,onDecline:g,onCancel:v,onValidation:b,onError:A}){let[D,y]=(0,rt.useState)(null),[C,te]=(0,rt.useState)(null),[G,S]=(0,rt.useState)(null),[ge,U]=(0,rt.useState)(null),[Q,re]=(0,rt.useState)(null),be=(0,rt.useRef)(!1),oe=(0,rt.useRef)(!1),he=(0,rt.useMemo)(()=>{if(typeof r=="object")return r;let $=(0,on.resolveTheme)(r);if($)return ko({appearance:$.appearance,buttonsStyles:$.buttonsLayout,layout:"default"})},[r]),Ne=(0,rt.useRef)(d),_e=(0,rt.useRef)(A),Se=(0,rt.useRef)(R),K=(0,rt.useRef)(g),O=(0,rt.useRef)(v),ae=(0,rt.useRef)(b),ze=(0,rt.useRef)(!1),Te=(0,rt.useRef)(!1),X=(0,rt.useRef)(0);return Ne.current=d,_e.current=A,Se.current=R,K.current=g,O.current=v,ae.current=b,(0,rt.useEffect)(()=>{let $=X.current+1;return X.current=$,()=>{queueMicrotask(()=>{X.current===$&&(ze.current||Te.current||(Te.current=!0,De(()=>{O.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,rt.useEffect)(()=>{let $=!0,ee=new Bo.PaymentAPI((0,on.resolveBillingApiUrl)(n),{telemetry:o});return y(null),te(null),S(null),ze.current=!1,Te.current=!1,(async()=>{try{if(!e.trim())throw new on.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new on.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let pe=await ee.getUnifiedCheckoutSession(e,t);if(!$)return;let ve=pe.data.session;if(!ve||!(0,on.isCardSetupCheckoutSession)(ve))throw new on.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Z=ve.vault;if(Z?.html?.trim()||(Z=await ee.getVaultCapture(e,t)),!Z.html?.trim())throw new on.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!$)return;te(Z),y(new Bo.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:o}))}catch(pe){if(!$)return;let ve=Li(pe);ze.current=!0,S(ve),De(()=>_e.current?.(ve))}})(),()=>{$=!1,ee.destroy()}},[n,t,e,o]),(0,rt.useEffect)(()=>{if(!D)return;let $=!1;oe.current=!1,be.current=!1;let ee=D.on("submitting",()=>{be.current=!0,re(null),U("processing")}),pe=D.on("complete",Z=>{ze.current=!0,be.current=!1,U("success"),(async()=>(await new Promise(Re=>setTimeout(Re,1200)),!oe.current&&(oe.current=!0,De(()=>{Se.current?.({status:"succeeded",sessionId:e,...Z.paymentMethod?{paymentMethod:Z.paymentMethod}:{}})}),$||U(null))))()}),ve=D.on("decline",Z=>{ze.current=!0,be.current=!1,re(Z.message??null),U("error"),De(()=>{K.current?.({status:"declined",sessionId:e,...Z.declineReason?{reason:Z.declineReason}:{},...Z.message?{message:Z.message}:{}})}),(async()=>(await new Promise(Re=>setTimeout(Re,1500)),$||U(null)))()});return()=>{$=!0,ee(),pe(),ve()}},[D,e]),G?(0,Bn.jsx)("div",{role:"alert",children:G.message}):!D||!C?.html?(0,Bn.jsx)(Bn.Fragment,{children:m}):(0,Bn.jsxs)(Bn.Fragment,{children:[ge&&(0,Bn.jsx)(hn,{status:ge,errorMessage:Q,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,Bn.jsx)(Sr,{capture:D,html:C.html,messageToken:C.messageToken,expectedOrigin:C.expectedOrigin,theme:he,containerStyle:i,onReady:()=>{De(()=>Ne.current?.())},onValidation:$=>{De(()=>ae.current?.($))},onError:$=>{if(!$)return;be.current&&(be.current=!1,re($),U("error"),setTimeout(()=>U(null),1500));let ee=Li(new Error($),{code:"card_setup_widget_failed",retryable:!0});De(()=>_e.current?.(ee))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|